docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Open an interface on a connected device. Args: client (string): The client id who is requesting this operation uuid (int): The id of the device we're opening the interface on iface (string): The name of the interface that we're opening key (string): The key to au...
def _open_interface(self, client, uuid, iface, key): conn_id = self._validate_connection('open_interface', uuid, key) if conn_id is None: return conn_data = self._connections[uuid] conn_data['last_touch'] = monotonic() slug = self._build_device_slug(uuid) ...
520,430
Connect to a device given its uuid Args: uuid (int): The unique id of the device key (string): A 64 byte string used to secure this connection client (string): The client id for who is trying to connect to the device.
def _connect_to_device(self, uuid, key, client): slug = self._build_device_slug(uuid) message = {'client': client, 'type': 'response', 'operation': 'connect'} self._logger.info("Connection attempt for device %d", uuid) # If someone is already connected, fail the request ...
520,433
Process a request for scanning information Args: sequence (int:) The sequence number of the packet received topic (string): The topic this message was received on message_type (string): The type of the packet received message (dict): The message itself
def _on_scan_request(self, sequence, topic, message): if messages.ProbeCommand.matches(message): self._logger.debug("Received probe message on topic %s, message=%s", topic, message) self._loop.add_callback(self._publish_scan_response, message['client']) else: ...
520,437
Publish a scan response message The message contains all of the devices that are currently known to this agent. Connection strings for direct connections are translated to what is appropriate for this agent. Args: client (string): A unique id for the client that made this ...
def _publish_scan_response(self, client): devices = self._manager.scanned_devices converted_devs = [] for uuid, info in devices.items(): slug = self._build_device_slug(uuid) message = {} message['uuid'] = uuid if uuid in self._connectio...
520,438
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating ...
def verify(self, obj): if obj is not None: raise ValidationError("Object is not None", reason='%s is not None' % str(obj), object=obj) return obj
520,457
Actually send the trub script. Args: resources (dict): A dictionary containing the required resources that we needed access to in order to perform this step.
def run(self, resources): hwman = resources['connection'] updater = hwman.hwman.app(name='device_updater') updater.run_script(self._script, no_reboot=self._no_reboot)
520,608
Process a BGAPI event containing a GATT service description and add it to a dictionary Args: services (dict): A dictionary of discovered services that is updated with this event event (BGAPIPacket): An event containing a GATT service
def process_gatt_service(services, event): length = len(event.payload) - 5 handle, start, end, uuid = unpack('<BHH%ds' % length, event.payload) uuid = process_uuid(uuid) services[uuid] = {'uuid_raw': uuid, 'start_handle': start, 'end_handle': end}
520,610
Constructor. Args: level (int): The message importance message (string): The message contents message_id (int): A unique id for the message timestamp (float): An optional monotonic value in seconds for when the message was created now_reference (float...
def __init__(self, level, message, message_id, timestamp=None, now_reference=None): self.level = level self.message = message self.count = 1 self.id = message_id if timestamp is None: self.created = monotonic() elif now_reference is None: ...
520,617
Create from a dictionary with kv pairs. Args: msg_dict (dict): A dictionary with information as created by to_dict() Returns: ServiceMessage: the converted message
def FromDictionary(cls, msg_dict): level = msg_dict.get('level') msg = msg_dict.get('message') now = msg_dict.get('now_time') created = msg_dict.get('created_time') count = msg_dict.get('count', 1) msg_id = msg_dict.get('id', 0) new_msg = ServiceMessage...
520,618
Constructor. Args: short_name (string): A unique short name for the service long_name (string): A user friendly name for the service preregistered (bool): Whether this is an expected preregistered service int_id (int): An internal numeric id for t...
def __init__(self, short_name, long_name, preregistered, int_id=None, max_messages=5): self.short_name = short_name self.long_name = long_name self.preregistered = preregistered self.last_heartbeat = monotonic() self.num_heartbeats = 0 self.id = int_id s...
520,620
Get a message by its persistent id. Args: message_id (int): The id of the message that we're looking for
def get_message(self, message_id): for message in self.messages: if message.id == message_id: return message raise ArgumentError("Message ID not found", message_id=message_id)
520,622
Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An optional monotonic value in seconds for when the message was created now_referenc...
def set_headline(self, level, message, timestamp=None, now_reference=None): if self.headline is not None and self.headline.message == message: self.headline.created = monotonic() self.headline.count += 1 return msg_object = ServiceMessage(level, message, se...
520,624
Fill in our default doxygen template file with info from an IOTile This populates things like name, version, etc. Arguments: output_path (str): a string path for where the filled template should go iotile (IOTile): An IOTile object that can be queried for information
def generate_doxygen_file(output_path, iotile): mapping = {} mapping['short_name'] = iotile.short_name mapping['full_name'] = iotile.full_name mapping['authors'] = iotile.authors mapping['version'] = iotile.version render_template('doxygen.txt.tpl', mapping, out_path=output_path)
520,625
Add a callback when device events happen. Args: name (str): currently support 'on_scan' and 'on_disconnect' func (callable): the function that should be called
def add_callback(self, name, func): if name == 'on_scan': events = ['device_seen'] def callback(_conn_string, _conn_id, _name, event): func(self.id, event, event.get('validity_period', 60)) elif name == 'on_report': events = ['report', 'broad...
520,629
Set the key that will be used to ensure messages come from one party Args: key (string): The key used to validate future messages client (string): A string that will be returned to indicate who locked this device.
def lock(self, key, client): self.key = key self.client = client
520,642
Start running this virtual device including any necessary worker threads. Args: channel (IOTilePushChannel): the channel with a stream and trace routine for streaming and tracing data through a VirtualInterface
def start(self, channel): super(TileBasedVirtualDevice, self).start(channel) for tile in self._tiles.values(): tile.start(channel=channel)
520,650
Add Builders and construction variables for Intel C/C++ compiler to an Environment. args: version: (string) compiler version to use, like "80" abi: (string) 'win32' or whatever Itanium version wants topdir: (string) compiler top dir, like "c:\Program Files\Intel\C...
def generate(env, version=None, abi=None, topdir=None, verbose=0): if not (is_mac or is_linux or is_windows): # can't handle this platform return if is_windows: SCons.Tool.msvc.generate(env) elif is_linux: SCons.Tool.gcc.generate(env) elif is_mac: SCons.Tool...
520,717
Parse a string node descriptor. The function creates an SGNode object without connecting its inputs and outputs and returns a 3-tuple: SGNode, [(input X, trigger X)], <processing function name> Args: desc (str): A description of the node to be created. model (str): A device model for ...
def parse_node_descriptor(desc, model): try: data = graph_node.parseString(desc) except ParseException: raise # TODO: Fix this to properly encapsulate the parse error stream_desc = u' '.join(data['node']) stream = DataStream.FromString(stream_desc) node = SGNode(stream, mode...
520,719
Convert a string node descriptor into a 20-byte binary descriptor. This is the inverse operation of parse_binary_descriptor and composing the two operations is a noop. Args: descriptor (str): A string node descriptor Returns: bytes: A 20-byte binary node descriptor.
def create_binary_descriptor(descriptor): func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'} func_codes = {y: x for x, y in func_names.items()} ...
520,720
Create an IOTileEvent from the result of a previous call to asdict(). Args: obj (dict): A dictionary produced by a call to IOTileEvent.asdict() Returns: IOTileEvent: The converted IOTileEvent object.
def FromDict(cls, obj): timestamp = obj.get('timestamp') if timestamp is not None: import dateutil.parser timestamp = dateutil.parser.parse(timestamp) return IOTileEvent(obj.get('device_timestamp'), obj.get('stream'), obj.get('extra_data'), ...
520,731
Save a binary copy of this report Args: path (string): The path where we should save the binary copy of the report
def save(self, path): data = self.encode() with open(path, "wb") as out: out.write(data)
520,734
Attach this DataStreamer to an underlying SensorLog. Calling this method is required if you want to use this DataStreamer to generate reports from the underlying data in the SensorLog. You can call it multiple times and it will unlink itself from any previous SensorLog each time. ...
def link_to_storage(self, sensor_log): if self.walker is not None: self._sensor_log.destroy_walker(self.walker) self.walker = None self.walker = sensor_log.create_walker(self.selector) self._sensor_log = sensor_log
520,745
Create a slot identifier from a string description. The string needs to be either: controller OR slot <X> where X is an integer that can be converted with int(X, 0) Args: desc (str): The string description of the slot Returns: SlotIdentifier
def FromString(cls, desc): desc = str(desc) if desc == u'controller': return SlotIdentifier(controller=True) words = desc.split() if len(words) != 2 or words[0] != u'slot': raise ArgumentError(u"Illegal slot identifier", descriptor=desc) try: ...
520,753
Create a slot identifier from an encoded binary descriptor. These binary descriptors are used to communicate slot targeting to an embedded device. They are exactly 8 bytes in length. Args: bindata (bytes): The 8-byte binary descriptor. Returns: SlotIdentifier
def FromEncoded(cls, bindata): if len(bindata) != 8: raise ArgumentError("Invalid binary slot descriptor with invalid length", length=len(bindata), expected=8, data=bindata) slot, match_op = struct.unpack("<B6xB", bindata) match_name = cls.KNOWN_MATCH_CODES.get(match_op) ...
520,754
Restore the current state of this emulated object. Args: state (dict): A previously dumped state produced by dump_state.
def restore_state(self, state): super(ReferenceController, self).restore_state(state) state_name = state.get('state_name') state_version = state.get('state_version') if state_name != self.STATE_NAME or state_version != self.STATE_VERSION: raise ArgumentError("Inva...
520,811
Callback called when a new device is discovered on this CMDStream Args: info (dict): Information about the scanned device
def _on_scan(self, info): device_id = info['uuid'] expiration_time = info.get('validity_period', 60) infocopy = deepcopy(info) infocopy['expiration_time'] = monotonic() + expiration_time with self._scan_lock: self._scanned_devices[device_id] = infocopy
520,839
Callback when a device is disconnected unexpectedly. Args: adapter_id (int): An ID for the adapter that was connected to the device connection_id (int): An ID for the connection that has become disconnected
def _on_disconnect(self): self._logger.info("Connection to device %s was interrupted", self.connection_string) self.connection_interrupted = True
520,840
Indent a multiline string Args: text (string): The string to indent indent_level (int): The number of indent_size spaces to prepend to each line indent_size (int): The number of spaces to prepend for each indent level Returns: ...
def wrap_lines(self, text, indent_level, indent_size=4): indent = ' '*indent_size*indent_level lines = text.split('\n') wrapped_lines = [] for line in lines: if line == '': wrapped_lines.append(line) else: wrapped_lines....
520,884
Remove leading whitespace from each line of a multiline string Args: text (string): The text to be unindented Returns: string: The unindented block of text
def trim_whitespace(self, text): lines = text.split('\n') new_lines = [x.lstrip() for x in lines] return '\n'.join(new_lines)
520,886
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Returns: bytes or byterray: The decoded byte buffer Raises: ValidationError: If there is a problem verifying the object, a ValidationErro...
def verify(self, obj): if self.encoding == 'none' and not isinstance(obj, (bytes, bytearray)): raise ValidationError('Byte object was not either bytes or a bytearray', type=obj.__class__.__name__) elif self.encoding == 'base64': try: data = base64.b64dec...
520,919
Forward an event on behalf of a client. This method is called by StandardDeviceServer when it has an event that should be sent to a client. Args: client_id (str): The client that we should send this event to event_tuple (tuple): The conn_string, event_name and event ...
async def client_event_handler(self, client_id, event_tuple, user_data): #TODO: Support sending disconnection events conn_string, event_name, event = event_tuple if event_name == 'report': report = event.serialize() report['encoded_report'] = base64.b64encode(...
520,939
Parse a binary targeting information structure. This function only supports extracting the slot number or controller from the target and will raise an ArgumentError if more complicated targeting is desired. Args: target (bytes): The binary targeting data blob. Returns: dict: The p...
def _parse_target(target): if len(target) != 8: raise ArgumentError("Invalid targeting data length", expected=8, length=len(target)) slot, match_op = struct.unpack("<B6xB", target) if match_op == _MATCH_CONTROLLER: return {'controller': True, 'slot': 0} elif match_op == _MATCH_SLO...
520,984
Place a task onto the RPC queue. This temporary functionality will go away but it lets you run a task synchronously with RPC dispatch by placing it onto the RCP queue. Args: func (callable): The function to execute args (iterable): The function arguments ...
def put_task(self, func, args, response): self._rpc_queue.put_nowait((func, args, response))
520,991
Place an RPC onto the RPC queue. The rpc will be dispatched asynchronously by the background dispatch task. This method must be called from the event loop. This method does not block. Args: address (int): The address of the tile with the RPC rpc_id (int): The ...
def put_rpc(self, address, rpc_id, arg_payload, response): self._rpc_queue.put_nowait((address, rpc_id, arg_payload, response))
520,992
Add a contiguous segment of data to this memory map If the segment overlaps with a segment already added , an ArgumentError is raised unless the overwrite flag is True. Params: address (int): The starting address for this segment data (bytearray): The data to add ...
def add_segment(self, address, data, overwrite=False): seg_type = self._classify_segment(address, len(data)) if not isinstance(seg_type, DisjointSegment): raise ArgumentError("Unsupported segment type") segment = MemorySegment(address, address+len(data)-1, len(data), bytea...
520,997
Determine how a new data segment fits into our existing world Params: address (int): The address we wish to classify length (int): The length of the segment Returns: int: One of SparseMemoryMap.prepended
def _classify_segment(self, address, length): end_address = address + length - 1 _, start_seg = self._find_address(address) _, end_seg = self._find_address(end_address) if start_seg is not None or end_seg is not None: raise ArgumentError("Overlapping segments are ...
521,002
Add an already created connection. Used to register devices connected before starting the device adapter. Args: connection_id (int): The external connection id internal_id (string): An internal identifier for the connection context (dict): Additional information to a...
def add_connection(self, connection_id, internal_id, context): # Make sure we are not reusing an id that is currently connected to something if self._get_connection_state(connection_id) != self.Disconnected: return if self._get_connection_state(internal_id) != self.Disconnec...
521,019
Finish a connection attempt Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id successful (bool): Whether this connection attempt was successful failure_reason (string): If this connection attempt failed, an optio...
def finish_connection(self, conn_or_internal_id, successful, failure_reason=None): data = { 'id': conn_or_internal_id, 'success': successful, 'failure_reason': failure_reason } action = ConnectionAction('finish_connection', data, sync=False) ...
521,021
Begin a connection attempt Args: action (ConnectionAction): the action object describing what we are connecting to
def _begin_connection_action(self, action): connection_id = action.data['connection_id'] internal_id = action.data['internal_id'] callback = action.data['callback'] # Make sure we are not reusing an id that is currently connected to something if self._get_connection_st...
521,022
Forcibly disconnect a device. Args: action (ConnectionAction): the action object describing what we are forcibly disconnecting
def _force_disconnect_action(self, action): conn_key = action.data['id'] if self._get_connection_state(conn_key) == self.Disconnected: return data = self._get_connection(conn_key) # If there are any operations in progress, cancel them cleanly if data['stat...
521,023
Finish a disconnection attempt There are two possible outcomes: - if we were successful at disconnecting, we transition to disconnected - if we failed at disconnecting, we transition back to idle Args: action (ConnectionAction): the action object describing what we are ...
def _finish_disconnection_action(self, action): success = action.data['success'] conn_key = action.data['id'] if self._get_connection_state(conn_key) != self.Disconnecting: self._logger.error( "Invalid finish_disconnection action on a connection whose state...
521,024
Begin an attempted operation. Args: action (ConnectionAction): the action object describing what we are operating on
def _begin_operation_action(self, action): conn_key = action.data['id'] callback = action.data['callback'] if self._get_connection_state(conn_key) != self.Idle: callback(conn_key, self.id, False, 'Cannot start operation, connection is not idle') return ...
521,026
Connect to the websocket server. This method will spawn a background task in the designated event loop that will run until stop() is called. You can control the name of the background task for debugging purposes using the name parameter. The name is not used in anyway except for debug...
async def start(self, name="websocket_client"): self._con = await websockets.connect(self.url) self._connection_task = self._loop.add_task(self._manage_connection(), name=name)
521,029
Save the current state of this emulated object to a file. Args: out_path (str): The path to save the dumped state of this emulated object.
def save_state(self, out_path): state = self.dump_state() # Remove all IntEnums from state since they cannot be json-serialized on python 2.7 # See https://bitbucket.org/stoneleaf/enum34/issues/17/difference-between-enum34-and-enum-json state = _clean_intenum(state) w...
521,051
Load the current state of this emulated object from a file. The file should have been produced by a previous call to save_state. Args: in_path (str): The path to the saved state dump that you wish to load.
def load_state(self, in_path): with open(in_path, "r") as infile: state = json.load(infile) self.restore_state(state)
521,052
Topologically sort optimization passes. This ensures that the resulting passes are run in order respecting before/after constraints. Args: passes (iterable): An iterable of pass names that should be included in the optimization passes run.
def _order_pases(self, passes): passes = set(passes) pass_deps = {} for opt in passes: _, before, after = self._known_passes[opt] if opt not in pass_deps: pass_deps[opt] = set() for after_pass in after: pass_deps[o...
521,058
Optimize a sensor graph by running optimization passes. The passes are run one at a time and modify the sensor graph for future passes. Args: sensor_graph (SensorGraph): The graph to be optimized model (DeviceModel): The device that we are optimizing for...
def optimize(self, sensor_graph, model): passes = self._order_pases(self._known_passes.keys()) for opt_name in passes: rerun = True pass_instance = self._known_passes[opt_name][0]() while rerun: rerun = pass_instance.run(sensor_graph, model...
521,059
Run this optimization pass on the sensor graph If necessary, information on the device model being targeted can be found in the associated model argument. Args: sensor_graph (SensorGraph): The sensor graph to optimize model (DeviceModel): The device model we're using
def run(self, sensor_graph, model): # This check can be done if there is 1 input and it is count == 1 # and the stream type is input or unbuffered for node, inputs, outputs in sensor_graph.iterate_bfs(): if node.num_inputs != 1: continue input_...
521,133
Directly instantiate a dependency resolver by name with the given arguments Args: name (string): The name of the class that we want to instantiate args (dict): The arguments to pass to the resolver factory Returns: DependencyResolver
def instantiate_resolver(self, name, args): if name not in self._known_resolvers: raise ArgumentError("Attempting to instantiate unknown dependency resolver", name=name) return self._known_resolvers[name](args)
521,136
Link a subtask to this parent task. This will cause stop() to block until the subtask has also finished. Calling stop will not directly cancel the subtask. It is expected that your finalizer for this parent task will cancel or otherwise stop the subtask. Args: subt...
def add_subtask(self, subtask): if self.stopped: raise InternalError("Cannot add a subtask to a parent that is already stopped") if not isinstance(subtask, BackgroundTask): raise ArgumentError("Subtasks must inherit from BackgroundTask, task={}".format(subtask)) ...
521,148
Run a coroutine to completion and return its result. This method may only be called outside of the event loop. Attempting to call it from inside the event loop would deadlock and will raise InternalError instead. Args: cor (coroutine): The coroutine that we wish to run in t...
def run_coroutine(self, cor, *args, **kwargs): if self.stopping: raise LoopStoppingError("Could not launch coroutine because loop is shutting down: %s" % cor) self.start() cor = _instaniate_coroutine(cor, args, kwargs) if self.inside_loop(): raise Int...
521,158
Remove a key from the data store Args: key (string): The key to remove Raises: KeyError: if the key was not found
def remove(self, key): data = self._load_file() del data[key] self._save_file(data)
521,165
Set the value of a key Args: key (string): The key used to store this value value (string): The value to store
def set(self, key, value): data = self._load_file() data[key] = value self._save_file(data)
521,166
Process a mock RPC argument. Args: input_string (str): The input string that should be in the format <slot id>:<rpc id> = value
def process_mock_rpc(input_string): spec, equals, value = input_string.partition(u'=') if len(equals) == 0: print("Could not parse mock RPC argument: {}".format(input_string)) sys.exit(1) try: value = int(value.strip(), 0) except ValueError as exc: print("Could no...
521,172
Print a watched value. Args: watch (DataStream): The stream that was watched value (IOTileReading): The value to was seen
def watch_printer(watch, value): print("({: 8} s) {}: {}".format(value.raw_time, watch, value.value))
521,173
Main entry point for iotile sensorgraph simulator. This is the iotile-sgrun command line program. It takes an optional set of command line parameters to allow for testing. Args: argv (list of str): An optional set of command line parameters. If not passed, these are taken from ...
def main(argv=None): if argv is None: argv = sys.argv[1:] try: executor = None parser = build_args() args = parser.parse_args(args=argv) model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(args.sensor_graph) parser.com...
521,174
Set the current state of a service. If the state is unchanged from a previous attempt, this routine does nothing. Args: short_name (string): The short name of the service state (int): The new stae of the service
async def update_state(self, short_name, state): if short_name not in self.services: raise ArgumentError("Service name is unknown", short_name=short_name) if state not in states.KNOWN_STATES: raise ArgumentError("Invalid service state", state=state) serv = sel...
521,278
Get static information about a service. Args: short_name (string): The short name of the service to query Returns: dict: A dictionary with the long_name and preregistered info on this service.
def service_info(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) info = {} info['short_name'] = short_name info['long_name'] = self.services[short_name]['state'].long_name info['prere...
521,280
Get the messages stored for a service. Args: short_name (string): The short name of the service to get messages for Returns: list(ServiceMessage): A list of the ServiceMessages stored for this service
def service_messages(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) return list(self.services[short_name]['state'].messages)
521,281
Get the headline stored for a service. Args: short_name (string): The short name of the service to get messages for Returns: ServiceMessage: the headline or None if there is no headline
def service_headline(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) return self.services[short_name]['state'].headline
521,282
Get the current status of a service. Returns information about the service such as the length since the last heartbeat, any status messages that have been posted about the service and whether the heartbeat should be considered out of the ordinary. Args: short_name (string):...
def service_status(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) info = {} service = self.services[short_name]['state'] info['heartbeat_age'] = monotonic() - service.last_heartbeat ...
521,283
Post a message for a service. Args: name (string): The short name of the service to query level (int): The level of the message (info, warning, error) message (string): The message contents
async def send_message(self, name, level, message): if name not in self.services: raise ArgumentError("Unknown service name", short_name=name) msg = self.services[name]['state'].post_message(level, message) await self._notify_update(name, 'new_message', msg.to_dict())
521,284
Set the sticky headline for a service. Args: name (string): The short name of the service to query level (int): The level of the message (info, warning, error) message (string): The message contents
async def set_headline(self, name, level, message): if name not in self.services: raise ArgumentError("Unknown service name", short_name=name) self.services[name]['state'].set_headline(level, message) headline = self.services[name]['state'].headline.to_dict() awai...
521,285
Post a heartbeat for a service. Args: short_name (string): The short name of the service to query
async def send_heartbeat(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) self.services[short_name]['state'].heartbeat() await self._notify_update(short_name, 'heartbeat')
521,286
Register a client id that handlers commands for a service. Args: short_name (str): The name of the service to set an agent for. client_id (str): A globally unique id for the client that should receive commands for this service.
def set_agent(self, short_name, client_id): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) self.agents[short_name] = client_id
521,287
Remove a client id from being the command handler for a service. Args: short_name (str): The name of the service to set an agent for. client_id (str): A globally unique id for the client that should no longer receive commands for this service.
def clear_agent(self, short_name, client_id): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) if short_name not in self.agents: raise ArgumentError("No agent registered for service", short_name=short_name) ...
521,288
Send a response to an RPC. Args: rpc_tag (str): The exact string given in a previous call to send_rpc_command result (str): The result of the operation. The possible values of response are: service_not_found, rpc_not_found, timeout, success, invalid_response, ...
def send_rpc_response(self, rpc_tag, result, response): if rpc_tag not in self.in_flight_rpcs: raise ArgumentError("In flight RPC could not be found, it may have timed out", rpc_tag=rpc_tag) del self.in_flight_rpcs[rpc_tag] response_message = { 'response': res...
521,290
Check if the user has placed a registry_type.txt file to choose the registry type If a default registry type file is found, the DefaultBackingType and DefaultBackingFile class parameters in ComponentRegistry are updated accordingly. Args: folder (string): The folder that we should check for a defa...
def _check_registry_type(folder=None): folder = _registry_folder(folder) default_file = os.path.join(folder, 'registry_type.txt') try: with open(default_file, "r") as infile: data = infile.read() data = data.strip() ComponentRegistry.SetBackingStore(data)...
521,303
Register an extension. Args: group (str): The type of the extension name (str): A name for the extension extension (str or class): If this is a string, then it will be interpreted as a path to import and load. Otherwise it will be treated as ...
def register_extension(self, group, name, extension): if isinstance(extension, str): name, extension = self.load_extension(extension)[0] if group not in self._registered_extensions: self._registered_extensions[group] = [] self._registered_extensions[group].app...
521,311
Set a persistent config key to a value, stored in the registry Args: key (string): The key name value (string): The key value
def set_config(self, key, value): keyname = "config:" + key self.kvstore.set(keyname, value)
521,330
Get the value of a persistent config key from the registry If no default is specified and the key is not found ArgumentError is raised. Args: key (string): The key name to fetch default (string): an optional value to be returned if key cannot be found Returns: ...
def get_config(self, key, default=MISSING): keyname = "config:" + key try: return self.kvstore.get(keyname) except KeyError: if default is MISSING: raise ArgumentError("No config value found for key", key=key) return default
521,331
Register a known record type in KNOWN_CLASSES. Args: record_class (UpdateRecord): An update record subclass.
def RegisterRecordType(cls, record_class): record_type = record_class.MatchType() if record_type not in UpdateRecord.KNOWN_CLASSES: UpdateRecord.KNOWN_CLASSES[record_type] = [] UpdateRecord.KNOWN_CLASSES[record_type].append(record_class)
521,370
Attempt to find a proxy plugin provided by a specific component Args: component (string): The name of the component that provides the plugin plugin_name (string): The name of the plugin to load Returns: TileBuxProxyPlugin: The plugin, if found, otherwise raises DataError
def find_proxy_plugin(component, plugin_name): reg = ComponentRegistry() plugins = reg.load_extensions('iotile.proxy_plugin', comp_filter=component, class_filter=TileBusProxyPlugin, product_name='proxy_plugin') for _name, plugin in plugins: if plugin.__name_...
521,378
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating ...
def verify(self, obj): if not isinstance(obj, bool): raise ValidationError("Object is not a bool", reason='object is not a bool', object=obj) if self._require_value is not None and obj != self._require_value: raise ValidationError("Boolean is not equal to specified lit...
521,380
Execute statement before children are executed. Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying scope_stack (list(Scope)): A stack of nested scopes that may influence how this statement allocates clocks or other stream...
def execute_before(self, sensor_graph, scope_stack): parent = scope_stack[-1] alloc = parent.allocator stream_a, trigger_a = self._convert_trigger(self.trigger_a, parent) if self.trigger_b is None: new_scope = TriggerScope(sensor_graph, scope_stack, (stream_a, tri...
521,389
Store a mock return value for an RPC Args: slot (SlotIdentifier): The slot we are mocking rpc_id (int): The rpc we are mocking value (int): The value that should be returned when the RPC is called.
def mock(self, slot, rpc_id, value): address = slot.address if address not in self.mock_rpcs: self.mock_rpcs[address] = {} self.mock_rpcs[address][rpc_id] = value
521,401
Create a packed binary descriptor of a DataStreamer object. Args: streamer (DataStreamer): The streamer to create a packed descriptor for Returns: bytes: A packed 14-byte streamer descriptor.
def create_binary_descriptor(streamer): trigger = 0 if streamer.automatic: trigger = 1 elif streamer.with_other is not None: trigger = (1 << 7) | streamer.with_other return struct.pack("<8sHBBBx", streamer.dest.encode(), streamer.selector.encode(), trigger, streamer.KnownFormats[s...
521,411
Parse a string descriptor of a streamer into a DataStreamer object. Args: string_desc (str): The string descriptor that we wish to parse. Returns: DataStreamer: A DataStreamer object representing the streamer.
def parse_string_descriptor(string_desc): if not isinstance(string_desc, str): string_desc = str(string_desc) if not string_desc.endswith(';'): string_desc += ';' parsed = get_streamer_parser().parseString(string_desc)[0] realtime = 'realtime' in parsed broadcast = 'broadcas...
521,412
Verify that the object conforms to this verifier's schema. Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating ...
def verify(self, obj): if not isinstance(obj, float): raise ValidationError("Object is not a float", reason='object is not a float', object=obj) return obj
521,415
Execute statement before children are executed. Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying scope_stack (list(Scope)): A stack of nested scopes that may influence how this statement allocates clocks or other stream...
def execute_before(self, sensor_graph, scope_stack): parent = scope_stack[-1] alloc = parent.allocator # We want to create a gated clock that only fires when there is a connection # to a communication tile. So we create a latching constant stream that is used to gate the ...
521,417
Remove a message callback. This call will remove a callback previously registered using every_match. Args: waiter_handle (object): The opaque handle returned by the previous call to every_match().
def remove_waiter(self, waiter_handle): spec, waiter = waiter_handle self._remove_waiter(spec, waiter)
521,470
Asynchronously send an RPC to this IOTile device Args: conn_id (int): A unique identifier that will refer to this connection address (int): the address of the tile that we wish to send the RPC to rpc_id (int): the 16-bit id of the RPC we want to call payload (byt...
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout): try: return await super(EmulatedDeviceAdapter, self).send_rpc(conn_id, address, rpc_id, payload, timeout) finally: for dev in self.devices.values(): dev.wait_idle()
521,480
Asynchronously complete a named debug command. The command name and arguments are passed to the underlying device adapter and interpreted there. Args: conn_id (int): A unique identifer that will refer to this connection name (string): the name of the debug command we wa...
async def debug(self, conn_id, name, cmd_args): device = self._get_property(conn_id, 'device') retval = None try: if name == 'dump_state': retval = device.dump_state() elif name == 'restore_state': state = cmd_args['snapshot'] ...
521,481
Verify that the object conforms to this verifier's schema. Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the object, a ValidationError is thrown with at least the reason key set indicating ...
def verify(self, obj): if obj not in self.options: raise ValidationError("Object is not in list of enumerated options", reason='not in list of enumerated options', object=obj, options=self.options) return obj
521,483
Find a virtual interface by name and instantiate it Args: virtual_iface (string): The name of the pkg_resources entry point corresponding to the interface. It should be in group iotile.virtual_interface config (dict): A dictionary with a 'interface' key with the config info for configu...
def instantiate_interface(virtual_iface, config, loop): # Allow the null virtual interface for testing if virtual_iface == 'null': return StandardDeviceServer(None, {}, loop=loop) conf = {} if 'interface' in config: conf = config['interface'] try: reg = ComponentRegis...
521,487
Parse this stop condition from a string representation. The string needs to match: run_time number [seconds|minutes|hours|days|months|years] Args: desc (str): The description Returns: TimeBasedStopCondition
def FromString(cls, desc): parse_exp = Literal(u'run_time').suppress() + time_interval(u'interval') try: data = parse_exp.parseString(desc) return TimeBasedStopCondition(data[u'interval'][0]) except ParseException: raise ArgumentError(u"Could not pa...
521,517
Copy necessary files into build/output so that this component can be used by others Args: family (ArchitectureGroup): The architecture group that we are targeting. If not provided, it is assumed that we are building in the current directory and the module_settings.json file is read...
def autobuild_release(family=None): if family is None: family = utilities.get_family('module_settings.json') env = Environment(tools=[]) env['TILE'] = family.tile target = env.Command(['#build/output/module_settings.json'], ['#module_settings.json'], action=env.A...
521,543
Add a known identifier resolution. Args: name (str): The name of the identifier obj (object): The object that is should resolve to
def add_identifier(self, name, obj): name = str(name) self._known_identifiers[name] = obj
521,550
Add a device property with a given default value. Args: name (str): The name of the property to add default_value (int, bool): The value of the property
def _add_property(self, name, default_value): name = str(name) self._properties[name] = default_value
521,556
Set a device model property. Args: name (str): The name of the property to set value (int, bool): The value of the property to set
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
521,557
Get a device model property. Args: name (str): The name of the property to get
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]
521,558
Generate the RPCs needed to stream this config variable to a tile. Args: address (int): The address of the tile that we should stream to. Returns: list of tuples: A list of argument tuples for each RPC. These tuples can be passed to EmulatedDevice.rpc to actually m...
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) return rpc_list
521,565
Begin a new config database entry. If there is a current entry in progress, it is aborted but the data was already committed to persistent storage so that space is wasted. Args: target (SlotIdentifer): The target slot for this config variable. var_id (int): The ...
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 += struct.pack("<H", var_id) self.data_i...
521,569
Add data to the currently in progress entry. Args: data (bytes): The data that we want to add. Returns: int: An error code
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
521,570
Return the RPCs needed to stream matching config variables to the given tile. This function will return a list of tuples suitable for passing to EmulatedDevice.deferred_rpc. Args: address (int): The address of the tile that we wish to stream to name (str or bytes): The ...
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_list
521,572
Directly add a config variable. This method is meant to be called from emulation scenarios that want to directly set config database entries from python. Args: target (SlotIdentifer): The target slot for this config variable. var_id (int): The config variable ID ...
def add_direct(self, target, var_id, var_type, data): data = struct.pack("<H", var_id) + _convert_to_bytes(var_type, data) if self.data_size - self.data_index < len(data): raise DataError("Not enough space for data in new conig entry", needed_space=len(data), actual_space=(self.da...
521,573
Add data to our stream, emitting reports as each new one is seen Args: data (bytearray): A chunk of new data to add
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()
521,587
Deserialize a report that has been serialized by calling report.serialize() Args: serialized (dict): A serialized report object
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']) report = type_map[serialized['report_format']](ser...
521,591
Start a scan. Will call self._on_device_found for each device scanned. Args: active (bool): Indicate if it is an active scan (probing for scan response) or not.
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 the active scan param if self._ac...
521,611
Asynchronously disconnect from a device that has previously been connected Args: connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): A function called as callback(connection_id, adapter_id, success, failure_reaso...
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") return self.connections.begin_disc...
521,619