Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def add_identifier(self, name, obj): name = str(name) self._known_identifiers[name] = obj
[ "Add a known identifier resolution.\n\n Args:\n name (str): The name of the identifier\n obj (object): The object that is should resolve to\n " ]
Please provide a description of the function:def resolve_identifier(self, name, expected_type=None): name = str(name) if name in self._known_identifiers: obj = self._known_identifiers[name] if expected_type is not None and not isinstance(obj, expected_type): ...
[ "Resolve an identifier to an object.\n\n There is a single namespace for identifiers so the user also should\n pass an expected type that will be checked against what the identifier\n actually resolves to so that there are no surprises.\n\n Args:\n name (str): The name that we...
Please provide a description of the function:def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0): lowest_id = IOTileReading.InvalidReadingID highest_id = IO...
[ "Generate an instance of the report format from a list of readings and a uuid.\n\n The signed list report is created using the passed readings and signed using the specified method\n and AuthProvider. If no auth provider is specified, the report is signed using the default authorization\n chai...
Please provide a description of the function:def decode(self): fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \ origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20]) assert fmt == 1 length = (len_high << 8) | len_low ...
[ "Decode this report into a list of readings\n " ]
Please provide a description of the function:def _add_property(self, name, default_value): name = str(name) self._properties[name] = default_value
[ "Add a device property with a given default value.\n\n Args:\n name (str): The name of the property to add\n default_value (int, bool): The value of the property\n " ]
Please provide a description of the function:def set(self, name, value): name = str(name) if name not in self._properties: raise ArgumentError("Unknown property in DeviceModel", name=name) self._properties[name] = value
[ "Set a device model property.\n\n Args:\n name (str): The name of the property to set\n value (int, bool): The value of the property to set\n " ]
Please provide a description of the function:def get(self, name): name = str(name) if name not in self._properties: raise ArgumentError("Unknown property in DeviceModel", name=name) return self._properties[name]
[ "Get a device model property.\n\n Args:\n name (str): The name of the property to get\n " ]
Please provide a description of the function:def _convert_to_bytes(type_name, value): int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'} type_name = type_name.lower() if type_name not in int_types and type_name not in ['string', 'binary']: ...
[ "Convert a typed value to a binary array" ]
Please provide a description of the function:def dump(self): return { 'target': str(self.target), 'data': base64.b64encode(self.data).decode('utf-8'), 'var_id': self.var_id, 'valid': self.valid }
[ "Serialize this object." ]
Please provide a description of the function:def generate_rpcs(self, address): rpc_list = [] for offset in range(2, len(self.data), 16): rpc = (address, rpcs.SET_CONFIG_VARIABLE, self.var_id, offset - 2, self.data[offset:offset + 16]) rpc_list.append(rpc) retu...
[ "Generate the RPCs needed to stream this config variable to a tile.\n\n Args:\n address (int): The address of the tile that we should stream to.\n\n Returns:\n list of tuples: A list of argument tuples for each RPC.\n\n These tuples can be passed to EmulatedDevice.rpc ...
Please provide a description of the function:def Restore(cls, state): target = SlotIdentifier.FromString(state.get('target')) data = base64.b64decode(state.get('data')) var_id = state.get('var_id') valid = state.get('valid') return ConfigEntry(target, var_id, data, val...
[ "Unserialize this object." ]
Please provide a description of the function:def compact(self): saved_length = 0 to_remove = [] for i, entry in enumerate(self.entries): if not entry.valid: to_remove.append(i) saved_length += entry.data_space() for i in reversed(to_...
[ "Remove all invalid config entries." ]
Please provide a description of the function:def start_entry(self, target, var_id): self.in_progress = ConfigEntry(target, var_id, b'') if self.data_size - self.data_index < self.in_progress.data_space(): return Error.DESTINATION_BUFFER_TOO_SMALL self.in_progress.data += ...
[ "Begin a new config database entry.\n\n If there is a current entry in progress, it is aborted but the\n data was already committed to persistent storage so that space\n is wasted.\n\n Args:\n target (SlotIdentifer): The target slot for this config variable.\n var_i...
Please provide a description of the function:def add_data(self, data): if self.data_size - self.data_index < len(data): return Error.DESTINATION_BUFFER_TOO_SMALL if self.in_progress is not None: self.in_progress.data += data return Error.NO_ERROR
[ "Add data to the currently in progress entry.\n\n Args:\n data (bytes): The data that we want to add.\n\n Returns:\n int: An error code\n " ]
Please provide a description of the function:def end_entry(self): # Matching current firmware behavior if self.in_progress is None: return Error.NO_ERROR # Make sure there was actually data stored if self.in_progress.data_space() == 2: return Error.INPU...
[ "Finish a previously started config database entry.\n\n This commits the currently in progress entry. The expected flow is\n that start_entry() is called followed by 1 or more calls to add_data()\n followed by a single call to end_entry().\n\n Returns:\n int: An error code\n ...
Please provide a description of the function:def stream_matching(self, address, name): matching = [x for x in self.entries if x.valid and x.target.matches(address, name)] rpc_list = [] for var in matching: rpc_list.extend(var.generate_rpcs(address)) return rpc_lis...
[ "Return the RPCs needed to stream matching config variables to the given tile.\n\n This function will return a list of tuples suitable for passing to\n EmulatedDevice.deferred_rpc.\n\n Args:\n address (int): The address of the tile that we wish to stream to\n name (str or ...
Please provide a description of the function:def start_config_var_entry(self, var_id, encoded_selector): selector = SlotIdentifier.FromEncoded(encoded_selector) err = self.config_database.start_entry(selector, var_id) return [err]
[ "Start a new config variable entry." ]
Please provide a description of the function:def get_config_var_entry(self, index): if index == 0 or index > len(self.config_database.entries): return [Error.INVALID_ARRAY_KEY, 0, 0, 0, b'\0'*8, 0, 0] entry = self.config_database.entries[index - 1] if not entry.valid: ...
[ "Get the metadata from the selected config variable entry." ]
Please provide a description of the function:def get_config_var_data(self, index, offset): if index == 0 or index > len(self.config_database.entries): return [Error.INVALID_ARRAY_KEY, b''] entry = self.config_database.entries[index - 1] if not entry.valid: retu...
[ "Get a chunk of data for a config variable." ]
Please provide a description of the function:def invalidate_config_var_entry(self, index): if index == 0 or index > len(self.config_database.entries): return [Error.INVALID_ARRAY_KEY, b''] entry = self.config_database.entries[index - 1] if not entry.valid: retu...
[ "Mark a config variable as invalid." ]
Please provide a description of the function:def get_config_database_info(self): max_size = self.config_database.data_size max_entries = self.config_database.max_entries() used_size = self.config_database.data_index used_entries = len(self.config_database.entries) inval...
[ "Get memory usage and space statistics on the config database." ]
Please provide a description of the function:def FindByName(cls, name): if name.endswith('.py'): return cls.LoadFromFile(name) reg = ComponentRegistry() for _name, tile in reg.load_extensions('iotile.virtual_tile', name_filter=name, class_filter=VirtualTile): r...
[ "Find an installed VirtualTile by name.\n\n This function searches for installed virtual tiles\n using the pkg_resources entry_point `iotile.virtual_tile`.\n\n If name is a path ending in .py, it is assumed to point to\n a module on disk and loaded directly rather than using\n pkg...
Please provide a description of the function:def LoadFromFile(cls, script_path): _name, dev = ComponentRegistry().load_extension(script_path, class_filter=VirtualTile, unique=True) return dev
[ "Import a virtual tile from a file rather than an installed module\n\n script_path must point to a python file ending in .py that contains exactly one\n VirtualTile class definition. That class is loaded and executed as if it\n were installed.\n\n To facilitate development, if there is ...
Please provide a description of the function:def stage(self): if 'PYPI_USER' not in os.environ or 'PYPI_PASS' not in os.environ: raise BuildError("You must set the PYPI_USER and PYPI_PASS environment variables") try: import twine except ImportError: ...
[ "Stage python packages for release, verifying everything we can about them." ]
Please provide a description of the function:def _upload_dists(self, repo, dists): from twine.commands.upload import upload if 'PYPI_USER' in os.environ and 'PYPI_PASS' in os.environ: pypi_user = os.environ['PYPI_USER'] pypi_pass = os.environ['PYPI_PASS'] else:...
[ "Upload a given component to pypi\n\n The pypi username and password must either be specified in a ~/.pypirc\n file or in environment variables PYPI_USER and PYPI_PASS\n " ]
Please provide a description of the function:def add_data(self, data): if self.state == self.ErrorState: return self.raw_data += bytearray(data) still_processing = True while still_processing: still_processing = self.process_data()
[ "Add data to our stream, emitting reports as each new one is seen\n\n Args:\n data (bytearray): A chunk of new data to add\n " ]
Please provide a description of the function:def process_data(self): further_processing = False if self.state == self.WaitingForReportType and len(self.raw_data) > 0: self.current_type = self.raw_data[0] try: self.current_header_size = self.calculate_h...
[ "Attempt to extract a report from the current data stream contents\n\n Returns:\n bool: True if further processing is required and process_data should be\n called again.\n " ]
Please provide a description of the function:def calculate_report_size(self, current_type, report_header): fmt = self.known_formats[current_type] return fmt.ReportLength(report_header)
[ "Determine the size of a report given its type and header" ]
Please provide a description of the function:def parse_report(self, current_type, report_data): fmt = self.known_formats[current_type] return fmt(report_data)
[ "Parse a report into an IOTileReport subclass" ]
Please provide a description of the function:def deserialize_report(self, serialized): type_map = self.known_formats if serialized['report_format'] not in type_map: raise ArgumentError("Unknown report format in DeserializeReport", format=serialized['report_format']) repor...
[ "Deserialize a report that has been serialized by calling report.serialize()\n\n Args:\n serialized (dict): A serialized report object\n " ]
Please provide a description of the function:def _handle_report(self, report): keep_report = True if self.report_callback is not None: keep_report = self.report_callback(report, self.context) if keep_report: self.reports.append(report)
[ "Try to emit a report and possibly keep a copy of it" ]
Please provide a description of the function:def _optional_no_translator_flag(env): import SCons.Util if 'POAUTOINIT' in env: autoinit = env['POAUTOINIT'] else: autoinit = False if autoinit: return [SCons.Util.CLVar('--no-translator')] else: return [SCons.Util.CLVar('')]
[ " Return '--no-translator' flag if we run *msginit(1)* in non-interactive\n mode." ]
Please provide a description of the function:def _POInitBuilder(env, **kw): import SCons.Action from SCons.Tool.GettextCommon import _init_po_files, _POFileBuilder action = SCons.Action.Action(_init_po_files, None) return _POFileBuilder(env, action=action, target_alias='$POCREATE_ALIAS')
[ " Create builder object for `POInit` builder. " ]
Please provide a description of the function:def _POInitBuilderWrapper(env, target=None, source=_null, **kw): if source is _null: if 'POTDOMAIN' in kw: domain = kw['POTDOMAIN'] elif 'POTDOMAIN' in env: domain = env['POTDOMAIN'] else: domain = 'messages' source = [ domain ] # NOTE:...
[ " Wrapper for _POFileBuilder. We use it to make user's life easier.\n \n This wrapper checks for `$POTDOMAIN` construction variable (or override in\n `**kw`) and treats it appropriatelly. \n " ]
Please provide a description of the function:def generate(env,**kw): import SCons.Util from SCons.Tool.GettextCommon import _detect_msginit try: env['MSGINIT'] = _detect_msginit(env) except: env['MSGINIT'] = 'msginit' msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \ ...
[ " Generate the `msginit` tool " ]
Please provide a description of the function:def generate(env): path, _cxx, version = get_xlc(env) if path and _cxx: _cxx = os.path.join(path, _cxx) if 'CXX' not in env: env['CXX'] = _cxx cplusplus.generate(env) if version: env['CXXVERSION'] = version
[ "Add Builders and construction variables for xlC / Visual Age\n suite to an Environment." ]
Please provide a description of the function:def generate(env): cc.generate(env) env['CC'] = 'icc' env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET' env['CXXCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /...
[ "Add Builders and construction variables for the OS/2 to an Environment." ]
Please provide a description of the function:def open_bled112(port, logger): if port is not None and port != '<auto>': logger.info("Using BLED112 adapter at %s", port) return serial.Serial(port, _BAUD_RATE, timeout=0.01, rtscts=True, exclusive=True) return _find_available_bled112(logger)
[ "Open a BLED112 adapter either by name or the first available." ]
Please provide a description of the function:def _find_ble_controllers(self): controllers = self.bable.list_controllers() return [ctrl for ctrl in controllers if ctrl.powered and ctrl.low_energy]
[ "Get a list of the available and powered BLE controllers" ]
Please provide a description of the function:def _initialize_system_sync(self): connected_devices = self.bable.list_connected_devices() for device in connected_devices: context = { 'connection_id': len(self.connections.get_connections()), 'connection_...
[ "Initialize the device adapter by removing all active connections and resetting scan and advertising to have\n a clean starting state." ]
Please provide a description of the function:def start_scan(self, active): try: self.bable.start_scan(self._on_device_found, active_scan=active, sync=True) except bable_interface.BaBLEException as err: # If we are already scanning, raise an error only we tried to change ...
[ "Start a scan. Will call self._on_device_found for each device scanned.\n Args:\n active (bool): Indicate if it is an active scan (probing for scan response) or not.\n " ]
Please provide a description of the function:def _on_device_found(self, success, device, failure_reason): if not success: self._logger.error("on_device_found() callback called with error: ", failure_reason) return # If it is an adverting report if device['type']...
[ "Callback function called when a device has been scanned.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n device (dict): The scanned device information\n - t...
Please provide a description of the function:def stop_scan(self): try: self.bable.stop_scan(sync=True) except bable_interface.BaBLEException: # If we errored our it is because we were not currently scanning pass self.scanning = False
[ "Stop to scan." ]
Please provide a description of the function:def connect_async(self, connection_id, connection_string, callback, retries=4, context=None): if context is None: # It is the first attempt to connect: begin a new connection context = { 'connection_id': connection_id,...
[ "Connect to a device by its connection_string\n\n This function asynchronously connects to a device by its BLE address + address type passed in the\n connection_string parameter and calls callback when finished. Callback is called on either success\n or failure with the signature:\n ...
Please provide a description of the function:def _on_connection_finished(self, success, result, failure_reason, context): connection_id = context['connection_id'] if not success: self._logger.error("Error while connecting to the device err=%s", failure_reason) # If con...
[ "Callback called when the connection attempt to a BLE device has finished.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): The connection information (if s...
Please provide a description of the function:def _on_services_probed(self, success, result, failure_reason, context): connection_id = context['connection_id'] if not success: self._logger.error("Error while probing services to the device, err=%s", failure_reason) contex...
[ "Callback called when the services has been probed.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information probed (if successful)\n - ser...
Please provide a description of the function:def _on_characteristics_probed(self, success, result, failure_reason, context): connection_id = context['connection_id'] if not success: self._logger.error("Error while probing characteristics to the device, err=%s", failure_reason) ...
[ "Callback called when the characteristics has been probed.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information probed (if successful)\n ...
Please provide a description of the function:def _on_connection_failed(self, connection_id, adapter_id, success, failure_reason): self._logger.info("_on_connection_failed connection_id=%d, reason=%s", connection_id, failure_reason) try: context = self.connections.get_context(connec...
[ "Callback function called when a connection has failed.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter.\n adapter_id (int): A unique identif...
Please provide a description of the function:def disconnect_async(self, connection_id, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find connection information") ...
[ "Asynchronously disconnect from a device that has previously been connected\n\n Args:\n connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter.\n callback (callable): A function called as callback(connection_id, adapter_id, success, fail...
Please provide a description of the function:def _on_unexpected_disconnection(self, success, result, failure_reason, context): connection_id = context['connection_id'] self._logger.warn('Unexpected disconnection event, handle=%d, reason=0x%X, state=%s', result['connec...
[ "Callback function called when an unexpected disconnection occured (meaning that we didn't previously send\n a `disconnect` request).\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful o...
Please provide a description of the function:def _on_disconnection_finished(self, success, result, failure_reason, context): if 'connection_handle' in context: # Remove all the notification callbacks registered for this connection with self.notification_callbacks_lock: ...
[ "Callback function called when a previously asked disconnection has been finished.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Disconnection informatio...
Please provide a description of the function:def _open_rpc_interface(self, connection_id, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find connection information") ...
[ "Enable RPC interface for this IOTile device\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n " ]
Please provide a description of the function:def _open_script_interface(self, connection_id, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find connection information") ...
[ "Enable script streaming interface for this IOTile device\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n " ...
Please provide a description of the function:def _open_streaming_interface(self, connection_id, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find connection information") ...
[ "Enable streaming interface for this IOTile device\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n ", "Cal...
Please provide a description of the function:def _open_tracing_interface(self, connection_id, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find connection information") ...
[ "Enable the tracing interface for this IOTile device\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n " ]
Please provide a description of the function:def _on_interface_opened(self, success, result, failure_reason, context, next_characteristic=None): if not success: self.connections.finish_operation(context['connection_id'], False, failure_reason) return if next_characteris...
[ "Callback function called when the notification related to an interface has been enabled.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information (if s...
Please provide a description of the function:def _close_rpc_interface(self, connection_id, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find connection information") ...
[ "Disable RPC interface for this IOTile device\n\n Args:\n connection_id (int): The unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n " ]
Please provide a description of the function:def _on_interface_closed(self, success, result, failure_reason, context, next_characteristic=None): if not success: self.connections.finish_operation(context['connection_id'], False, failure_reason) return if next_characteris...
[ "Callback function called when the notification related to an interface has been disabled.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): Information (if ...
Please provide a description of the function:def _on_report(self, report, connection_id): self._logger.info('Received report: %s', str(report)) self._trigger_callback('on_report', connection_id, report) return False
[ "Callback function called when a report has been processed.\n\n Args:\n report (IOTileReport): The report object\n connection_id (int): The connection id related to this report\n\n Returns:\n - True to indicate that IOTileReportParser should also keep a copy of the rep...
Please provide a description of the function:def _on_report_error(self, code, message, connection_id): self._logger.critical( "Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s", code, message )
[ "Callback function called if an error occured while parsing a report" ]
Please provide a description of the function:def send_rpc_async(self, connection_id, address, rpc_id, payload, timeout, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find con...
[ "Asynchronously send an RPC to this IOTile device\n\n Args:\n connection_id (int): A unique identifier that will refer to this connection\n address (int): The address of the tile that we wish to send the RPC to\n rpc_id (int): The 16-bit id of the RPC we want to call\n ...
Please provide a description of the function:def send_script_async(self, connection_id, data, progress_callback, callback): try: context = self.connections.get_context(connection_id) except ArgumentError: callback(connection_id, self.id, False, "Could not find connectio...
[ "Asynchronously send a a script to this IOTile device\n\n Args:\n connection_id (int): A unique identifier that will refer to this connection\n data (bytes): the script to send to the device\n progress_callback (callable): A function to be called with status on our progress, ...
Please provide a description of the function:def _register_notification_callback(self, connection_handle, attribute_handle, callback, once=False): notification_id = (connection_handle, attribute_handle) with self.notification_callbacks_lock: self.notification_callbacks[notification_...
[ "Register a callback as a notification callback. It will be called if a notification with the matching\n connection_handle and attribute_handle is received.\n\n Args:\n connection_handle (int): The connection handle to watch\n attribute_handle (int): The attribute handle to watch...
Please provide a description of the function:def _on_notification_received(self, success, result, failure_reason): if not success: self._logger.info("Notification received with failure failure_reason=%s", failure_reason) notification_id = (result['connection_handle'], result['attri...
[ "Callback function called when a notification has been received.\n It is executed in the baBLE working thread: should not be blocking.\n\n Args:\n success (bool): A bool indicating that the operation is successful or not\n result (dict): The notification information\n ...
Please provide a description of the function:def stop_sync(self): # Stop to scan if self.scanning: self.stop_scan() # Disconnect all connected devices for connection_id in list(self.connections.get_connections()): self.disconnect_sync(connection_id) ...
[ "Safely stop this BLED112 instance without leaving it in a weird state" ]
Please provide a description of the function:def periodic_callback(self): if self.stopped: return # Check if we should start scanning again if not self.scanning and len(self.connections.get_connections()) == 0: self._logger.info("Restarting scan for devices") ...
[ "Periodic cleanup tasks to maintain this adapter, should be called every second. " ]
Please provide a description of the function:def format_snippet(sensor_graph): output = [] # Clear any old sensor graph output.append("disable") output.append("clear") output.append("reset") # Load in the nodes for node in sensor_graph.dump_nodes(): output.append('add_node "{...
[ "Format this sensor graph as iotile command snippets.\n\n This includes commands to reset and clear previously stored\n sensor graphs.\n\n Args:\n sensor_graph (SensorGraph): the sensor graph that we want to format\n " ]
Please provide a description of the function:def find_bled112_devices(cls): found_devs = [] ports = serial.tools.list_ports.comports() for port in ports: if not hasattr(port, 'pid') or not hasattr(port, 'vid'): continue # Check if the device mat...
[ "Look for BLED112 dongles on this computer and start an instance on each one" ]
Please provide a description of the function:def get_scan_stats(self): time_spent = time.time() return self._scan_event_count, self._v1_scan_count, self._v1_scan_response_count, \ self._v2_scan_count, self._device_scan_counts.copy(), \ (time_spent - self._last_reset_time...
[ "Return the scan event statistics for this adapter\n\n Returns:\n int : total scan events\n int : total v1 scan count\n int : total v1 scan response count\n int : total v2 scan count\n dict : device-specific scan counts\n float : seconds since...
Please provide a description of the function:def reset_scan_stats(self): self._scan_event_count = 0 self._v1_scan_count = 0 self._v1_scan_response_count = 0 self._v2_scan_count = 0 self._device_scan_counts = {} self._last_reset_time = time.time()
[ "Clears the scan event statistics and updates the last reset time" ]
Please provide a description of the function:def stop_sync(self): if self.scanning: self.stop_scan() # Make a copy since this will change size as we disconnect con_copy = copy.copy(self._connections) for _, context in con_copy.items(): self.disconnect_...
[ "Safely stop this BLED112 instance without leaving it in a weird state" ]
Please provide a description of the function:def start_scan(self, active): self._command_task.sync_command(['_start_scan', active]) self.scanning = True
[ "Start the scanning task" ]
Please provide a description of the function:def connect_async(self, connection_id, connection_string, callback, retries=4): context = {} context['connection_id'] = connection_id context['callback'] = callback context['retries'] = retries context['connection_string'] = c...
[ "Connect to a device by its connection_string\n\n This function asynchronously connects to a device by its BLE address passed in the\n connection_string parameter and calls callback when finished. Callback is called\n on either success or failure with the signature:\n\n callback(conn_id...
Please provide a description of the function:def disconnect_async(self, conn_id, callback): found_handle = None # Find the handle by connection id for handle, conn in self._connections.items(): if conn['connection_id'] == conn_id: found_handle = handle ...
[ "Asynchronously disconnect from a device that has previously been connected\n\n Args:\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n callback (callable): A function called as callback(conn_id, adapter_id, success,...
Please provide a description of the function:def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback): found_handle = None # Find the handle by connection id for handle, conn in self._connections.items(): if conn['connection_id'] == conn_id: ...
[ "Asynchronously send an RPC to this IOTile device\n\n Args:\n conn_id (int): A unique identifer that will refer to this connection\n address (int): the addres of the tile that we wish to send the RPC to\n rpc_id (int): the 16-bit id of the RPC we want to call\n pay...
Please provide a description of the function:def send_script_async(self, conn_id, data, progress_callback, callback): found_handle = None # Find the handle by connection id for handle, conn in self._connections.items(): if conn['connection_id'] == conn_id: f...
[ "Asynchronously send a a script to this IOTile device\n\n Args:\n conn_id (int): A unique identifer that will refer to this connection\n data (bytes): the script to send to the device\n progress_callback (callable): A function to be called with status on our progress, called ...
Please provide a description of the function:def _open_script_interface(self, conn_id, callback): try: handle = self._find_handle(conn_id) services = self._connections[handle]['services'] except (ValueError, KeyError): callback(conn_id, self.id, False, 'Conn...
[ "Enable script streaming interface for this IOTile device\n\n Args:\n conn_id (int): the unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n " ]
Please provide a description of the function:def _open_tracing_interface(self, conn_id, callback): try: handle = self._find_handle(conn_id) services = self._connections[handle]['services'] except (ValueError, KeyError): callback(conn_id, self.id, False, 'Con...
[ "Enable the debug tracing interface for this IOTile device\n\n Args:\n conn_id (int): the unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n " ]
Please provide a description of the function:def _process_scan_event(self, response): payload = response.payload length = len(payload) - 10 if length < 0: return rssi, packet_type, sender, _addr_type, _bond, data = unpack("<bB6sBB%ds" % length, payload) st...
[ "Parse the BLE advertisement packet.\n\n If it's an IOTile device, parse and add to the scanned devices. Then,\n parse advertisement and determine if it matches V1 or V2. There are\n two supported type of advertisements:\n\n v1: There is both an advertisement and a scan response (if act...
Please provide a description of the function:def _parse_v2_advertisement(self, rssi, sender, data): if len(data) != 31: return # We have already verified that the device is an IOTile device # by checking its service data uuid in _process_scan_event so # here we jus...
[ " Parse the IOTile Specific advertisement packet" ]
Please provide a description of the function:def probe_services(self, handle, conn_id, callback): self._command_task.async_command(['_probe_services', handle], callback, {'connection_id': conn_id, 'handle': handle})
[ "Given a connected device, probe for its GATT services and characteristics\n\n Args:\n handle (int): a handle to the connection on the BLED112 dongle\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n callb...
Please provide a description of the function:def probe_characteristics(self, conn_id, handle, services): self._command_task.async_command(['_probe_characteristics', handle, services], self._probe_characteristics_finished, {'connection_id': conn_id, ...
[ "Probe a device for all characteristics defined in its GATT table\n\n This routine must be called after probe_services and passed the services dictionary\n produced by that method.\n\n Args:\n handle (int): a handle to the connection on the BLED112 dongle\n conn_id (int): ...
Please provide a description of the function:def initialize_system_sync(self): retval = self._command_task.sync_command(['_query_systemstate']) self.maximum_connections = retval['max_connections'] for conn in retval['active_connections']: self._connections[conn] = {'handl...
[ "Remove all active connections and query the maximum number of supported connections\n " ]
Please provide a description of the function:def _on_disconnect(self, result): success, _, context = self._parse_return(result) callback = context['callback'] connection_id = context['connection_id'] handle = context['handle'] callback(connection_id, self.id, success,...
[ "Callback called when disconnection command finishes\n\n Args:\n result (dict): result returned from diconnection command\n " ]
Please provide a description of the function:def _parse_return(cls, result): return_value = None success = result['result'] context = result['context'] if 'return_value' in result: return_value = result['return_value'] return success, return_value, context
[ "Extract the result, return value and context from a result object\n " ]
Please provide a description of the function:def _get_connection(self, handle, expect_state=None): conndata = self._connections.get(handle) if conndata and expect_state is not None and conndata['state'] != expect_state: self._logger.error("Connection in unexpected state, wanted=%s...
[ "Get a connection object, logging an error if its in an unexpected state\n " ]
Please provide a description of the function:def _on_connection_finished(self, result): success, retval, context = self._parse_return(result) conn_id = context['connection_id'] callback = context['callback'] if success is False: callback(conn_id, self.id, False, 'T...
[ "Callback when the connection attempt to a BLE device has finished\n\n This function if called when a new connection is successfully completed\n\n Args:\n event (BGAPIPacket): Connection event\n " ]
Please provide a description of the function:def _on_connection_failed(self, conn_id, handle, clean, reason): with self.count_lock: self.connecting_count -= 1 self._logger.info("_on_connection_failed conn_id=%d, reason=%s", conn_id, str(reason)) conndata = self._get_conne...
[ "Callback called from another thread when a connection attempt has failed.\n " ]
Please provide a description of the function:def _probe_services_finished(self, result): #If we were disconnected before this function is called, don't proceed handle = result['context']['handle'] conn_id = result['context']['connection_id'] conndata = self._get_connection(han...
[ "Callback called after a BLE device has had its GATT table completely probed\n\n Args:\n result (dict): Parameters determined by the probe and context passed to the call to\n probe_device()\n " ]
Please provide a description of the function:def _probe_characteristics_finished(self, result): handle = result['context']['handle'] conn_id = result['context']['connection_id'] conndata = self._get_connection(handle, 'preparing') if conndata is None: self._logger...
[ "Callback when BLE adapter has finished probing services and characteristics for a device\n\n Args:\n result (dict): Result from the probe_characteristics command\n " ]
Please provide a description of the function:def periodic_callback(self): if self.stopped: return # Check if we should start scanning again if not self.scanning and len(self._connections) == 0 and self.connecting_count == 0: self._logger.info("Restarting scan f...
[ "Periodic cleanup tasks to maintain this adapter, should be called every second\n " ]
Please provide a description of the function:def build_update_script(file_name, slot_assignments=None, os_info=None, sensor_graph=None, app_info=None, use_safeupdate=False): resolver = ProductResolver.Create() env = Environment(tools=[]) files = [] if slot_assignments is n...
[ "Build a trub script that loads given firmware into the given slots.\n\n slot_assignments should be a list of tuples in the following form:\n (\"slot X\" or \"controller\", firmware_image_name)\n\n The output of this autobuild action will be a trub script in\n build/output/<file_name> that assigns the g...
Please provide a description of the function:def _build_reflash_script_action(target, source, env): out_path = str(target[0]) source = [str(x) for x in source] records = [] if env['USE_SAFEUPDATE']: sgf_off = SendRPCRecord(8,0x2005,bytearray([0])) # Disable Sensorgraph records.app...
[ "Create a TRUB script containing tile and controller reflashes and/or sensorgraph\n\n If the app_info is provided, then the final source file will be a sensorgraph.\n All subsequent files in source must be in intel hex format. This is guaranteed\n by the ensure_image_is_hex call in build_update_script.\n ...
Please provide a description of the function:def convert_to_BuildError(status, exc_info=None): if not exc_info and isinstance(status, Exception): exc_info = (status.__class__, status, None) if isinstance(status, BuildError): buildError = status buildError.exitstatus = 2 # alway...
[ "\n Convert any return code a BuildError Exception.\n\n :Parameters:\n - `status`: can either be a return code or an Exception.\n\n The buildError.status we set here will normally be\n used as the exit status of the \"scons\" process.\n " ]
Please provide a description of the function:def format_config(sensor_graph): cmdfile = CommandFile("Config Variables", "1.0") for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()): for conf_var, conf_def in sorted(sensor_graph.config_database[slot].items()): conf...
[ "Extract the config variables from this sensor graph in ASCII format.\n\n Args:\n sensor_graph (SensorGraph): the sensor graph that we want to format\n\n Returns:\n str: The ascii output lines concatenated as a single string\n " ]
Please provide a description of the function:def generate(env): path, _f77, _shf77, version = get_xlf77(env) if path: _f77 = os.path.join(path, _f77) _shf77 = os.path.join(path, _shf77) f77.generate(env) env['F77'] = _f77 env['SHF77'] = _shf77
[ "\n Add Builders and construction variables for the Visual Age FORTRAN\n compiler to an Environment.\n " ]
Please provide a description of the function:def DirScanner(**kw): kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw)
[ "Return a prototype Scanner instance for scanning\n directories for on-disk files" ]
Please provide a description of the function:def DirEntryScanner(**kw): kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw)
[ "Return a prototype Scanner instance for \"scanning\"\n directory Nodes for their in-memory entries" ]
Please provide a description of the function:def scan_on_disk(node, env, path=()): try: flist = node.fs.listdir(node.get_abspath()) except (IOError, OSError): return [] e = node.Entry for f in filter(do_not_scan, flist): # Add ./ to the beginning of the file name so if it b...
[ "\n Scans a directory for on-disk files and directories therein.\n\n Looking up the entries will add these to the in-memory Node tree\n representation of the file system, so all we have to do is just\n that and then call the in-memory scanning function.\n " ]
Please provide a description of the function:def scan_in_memory(node, env, path=()): try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing # mixed Node ty...
[ "\n \"Scans\" a Node.FS.Dir for its in-memory entries.\n " ]