docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Enable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
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") return self.connections.begin_o...
521,622
Enable script streaming interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
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") return success = HighSpeedCh...
521,623
Enable streaming interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
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") return self._logger.info(...
521,624
Enable the tracing interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
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") return self._logger.info("A...
521,625
Disable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
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") return self.connections.begin_...
521,627
Callback function called when a report has been processed. Args: report (IOTileReport): The report object connection_id (int): The connection id related to this report Returns: - True to indicate that IOTileReportParser should also keep a copy of the report ...
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
521,629
Callback function called when a notification has been received. It is executed in the baBLE working thread: should not be blocking. Args: success (bool): A bool indicating that the operation is successful or not result (dict): The notification information - value (...
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['attribute_handle']) callback = None ...
521,634
Format this sensor graph as iotile command snippets. This includes commands to reset and clear previously stored sensor graphs. Args: sensor_graph (SensorGraph): the sensor graph that we want to format
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(node)) # Load in the streamer...
521,637
Asynchronously disconnect from a device that has previously been connected Args: conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): A function called as callback(conn_id, adapter_id, success, failure_r...
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 if found_handle is None: call...
521,645
Enable script streaming interface for this IOTile device Args: conn_id (int): the unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
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, 'Connection closed unexpectedly before we could op...
521,649
Enable the debug tracing interface for this IOTile device Args: conn_id (int): the unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
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, 'Connection closed unexpectedly before we could o...
521,650
Given a connected device, probe for its GATT services and characteristics Args: handle (int): a handle to the connection on the BLED112 dongle conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callab...
def probe_services(self, handle, conn_id, callback): self._command_task.async_command(['_probe_services', handle], callback, {'connection_id': conn_id, 'handle': handle})
521,658
Probe a device for all characteristics defined in its GATT table This routine must be called after probe_services and passed the services dictionary produced by that method. Args: handle (int): a handle to the connection on the BLED112 dongle conn_id (int): a unique ide...
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, ...
521,659
Callback called when disconnection command finishes Args: result (dict): result returned from diconnection command
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, "No reason given") self._remove_conn...
521,661
Callback when the connection attempt to a BLE device has finished This function if called when a new connection is successfully completed Args: event (BGAPIPacket): Connection event
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, 'Timeout opening connection') with...
521,665
Callback called after a BLE device has had its GATT table completely probed Args: result (dict): Parameters determined by the probe and context passed to the call to probe_device()
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(handle, 'preparing') if conndata is Non...
521,667
Callback when BLE adapter has finished probing services and characteristics for a device Args: result (dict): Result from the probe_characteristics command
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.info('Connection disconnected before probe_c...
521,668
Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string
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_type, conf_val = conf_def if co...
521,677
Set an exception as the result of this operation. Args: exc_class (object): The exception type
def set_exception(self, exc_class, exc_info, exc_stack): if self.is_finished(): raise InternalError("set_exception called on finished AsynchronousResponse", result=self._result, exception=self._exception) self._exception = (exc_class, exc_info, exc_...
521,687
Wait for this operation to finish. You can specify an optional timeout that defaults to no timeout if None is passed. The result of the operation is returned from this method. If the operation raised an exception, it is reraised from this method. Args: timeout (flo...
def wait(self, timeout=None): flag = self._finished.wait(timeout=timeout) if flag is False: raise TimeoutExpiredError("Timeout waiting for response to event loop operation") if self._exception is not None: self._raise_exception() return self._result
521,691
Wait for this operation to finish. You can specify an optional timeout that defaults to no timeout if None is passed. The result of the operation is returned from this method. If the operation raised an exception, it is reraised from this method. Args: timeout (flo...
async def wait(self, timeout=None): await asyncio.wait_for(self._future, timeout) if self._exception is not None: self._raise_exception() return self._result
521,693
Return a list of all python wheel objects created by dependencies of this tile Args: tile (IOTile): Tile that we should scan for dependencies Returns: list: A list of paths to dependency wheels
def find_dependency_wheels(tile): return [os.path.join(x.folder, 'python', x.support_wheel) for x in _iter_dependencies(tile) if x.has_wheel]
521,703
Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not
def check(self, version): for disjunct in self._disjuncts: if self._check_insersection(version, disjunct): return True return False
521,706
Filter all of the versions in an iterable that match this version range Args: versions (iterable): An iterable of SemanticVersion objects Returns: list: A list of the SemanticVersion objects that matched this range
def filter(self, versions, key=lambda x: x): return [x for x in versions if self.check(key(x))]
521,707
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, int): raise ValidationError("Object is not a int", reason='object is not a int', object=obj, type=type(obj), int_type=int) return obj
521,736
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): # We can only eliminate a node if the following checks are true # 1. It has no other nodes connected to it # 2. Its stream is not an output of the entire sensor graph # 3. Its stream is autogenerated by the compiler # 4. Its operation...
521,762
Start serving access to this VirtualIOTileDevice Args: device (VirtualIOTileDevice): The device we will be providing access to
def start(self, device): super(NativeBLEVirtualInterface, self).start(device) self.set_advertising(True)
521,792
Synchronously disconnect from whoever has connected to us Args: connection_handle (int): The handle of the connection we wish to disconnect.
def disconnect_sync(self, connection_handle): self.bable.disconnect(connection_handle=connection_handle, sync=True)
521,798
Callback function called when a connected event has been received. It is executed in the baBLE working thread: should not be blocking. Args: device (dict): Information about the newly connected device
def _on_connected(self, device): self._logger.debug("Device connected event: {}".format(device)) self.connected = True self._connection_handle = device['connection_handle'] self.device.connected = True self._audit('ClientConnected')
521,799
Callback function called when a disconnected event has been received. This resets any open interfaces on the virtual device and clears any in progress traces and streams. It is executed in the baBLE working thread: should not be blocking. Args: device (dict): Information abo...
def _on_disconnected(self, device): self._logger.debug("Device disconnected event: {}".format(device)) if self.streaming: self.device.close_streaming_interface() self.streaming = False if self.tracing: self.device.close_tracing_interface() ...
521,800
Callback function called when a write request has been received. It is executed in the baBLE working thread: should not be blocking. Args: request (dict): Information about the request - connection_handle (int): The connection handle that sent the request - attri...
def _on_write_request(self, request): if request['connection_handle'] != self._connection_handle: return False attribute_handle = request['attribute_handle'] # If write to configure notification config_handles = [ ReceiveHeaderChar.config_handle, ...
521,801
Call an RPC given a header and possibly a previously sent payload It is executed in the baBLE working thread: should not be blocking. Args: header (bytearray): The RPC header we should call
def _call_rpc(self, header): length, _, cmd, feature, address = struct.unpack("<BBBBB", bytes(header)) rpc_id = (feature << 8) | cmd payload = self.rpc_payload[:length] status = (1 << 6) try: response = self.device.call_rpc(address, rpc_id, bytes(payload))...
521,802
Send a notification over BLE It is executed in the baBLE working thread: should not be blocking. Args: handle (int): The handle to notify on payload (bytearray): The value to notify
def _send_notification(self, handle, payload): self.bable.notify( connection_handle=self._connection_handle, attribute_handle=handle, value=payload )
521,803
Stream reports to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports.
def _stream_data(self, chunk=None): # If we failed to transmit a chunk, we will be requeued with an argument self._stream_sm_running = True if chunk is None: chunk = self._next_streaming_chunk(20) if chunk is None or len(chunk) == 0: self._stream_sm_ru...
521,805
Stream tracing data to the ble client in 20 byte chunks Args: chunk (bytearray): A chunk that should be sent instead of requesting a new chunk from the pending reports.
def _send_trace(self, chunk=None): self._trace_sm_running = True # If we failed to transmit a chunk, we will be requeued with an argument if chunk is None: chunk = self._next_tracing_chunk(20) if chunk is None or len(chunk) == 0: self._trace_sm_running ...
521,806
Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: list(ServiceMessage): A list of the messages stored for this service
async def get_messages(self, name): resp = await self.send_command(OPERATIONS.CMD_QUERY_MESSAGES, {'name': name}, MESSAGES.QueryMessagesResponse, timeout=5.0) return [states.ServiceMessage.FromDictionary(x) for x in resp]
521,814
Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: ServiceMessage: the headline or None if no headline has been set
async def get_headline(self, name): resp = await self.send_command(OPERATIONS.CMD_QUERY_HEADLINE, {'name': name}, MESSAGES.QueryHeadlineResponse, timeout=5.0) if resp is not None: resp = states.ServiceMessage.FromDictionary(resp) ret...
521,815
Send a heartbeat for a service. Args: name (string): The name of the service to send a heartbeat for
async def send_heartbeat(self, name): await self.send_command(OPERATIONS.CMD_HEARTBEAT, {'name': name}, MESSAGES.HeartbeatResponse, timeout=5.0)
521,817
Update the state for a service. Args: name (string): The name of the service state (int): The new state of the service
async def update_state(self, name, state): await self.send_command(OPERATIONS.CMD_UPDATE_STATE, {'name': name, 'new_status': state}, MESSAGES.UpdateStateResponse, timeout=5.0)
521,818
Asynchronously update the sticky headline for a service. Args: name (string): The name of the service level (int): A message level in states.*_LEVEL message (string): The user facing error message that will be stored for the service and can be queried later.
def post_headline(self, name, level, message): self.post_command(OPERATIONS.CMD_SET_HEADLINE, {'name': name, 'level': level, 'message': message})
521,819
Asynchronously try to update the state for a service. If the update fails, nothing is reported because we don't wait for a response from the server. This function will return immmediately and not block. Args: name (string): The name of the service state (int): ...
def post_state(self, name, state): self.post_command(OPERATIONS.CMD_UPDATE_STATE, {'name': name, 'new_status': state})
521,820
Asynchronously post a user facing error message about a service. Args: name (string): The name of the service message (string): The user facing error message that will be stored for the service and can be queried later.
def post_error(self, name, message): self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.ERROR_LEVEL, message))
521,821
Asynchronously post a user facing warning message about a service. Args: name (string): The name of the service message (string): The user facing warning message that will be stored for the service and can be queried later.
def post_warning(self, name, message): self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.WARNING_LEVEL, message))
521,822
Asynchronously post a user facing info message about a service. Args: name (string): The name of the service message (string): The user facing info message that will be stored for the service and can be queried later.
def post_info(self, name, message): self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.INFO_LEVEL, message))
521,823
Register a new service with the service manager. Args: short_name (string): A unique short name for this service that functions as an id long_name (string): A user facing name for this service allow_duplicate (boolean): Don't throw an error if this service is...
async def register_service(self, short_name, long_name, allow_duplicate=True): try: await self.send_command(OPERATIONS.CMD_REGISTER_SERVICE, dict(name=short_name, long_name=long_name), MESSAGES.RegisterServiceResponse) except ArgumentError: ...
521,826
Register to act as the RPC agent for this service. After this call succeeds, all requests to send RPCs to this service will be routed through this agent. Args: short_name (str): A unique short name for this service that functions as an id
async def register_agent(self, short_name): await self.send_command(OPERATIONS.CMD_SET_AGENT, {'name': short_name}, MESSAGES.SetAgentResponse)
521,827
Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: list(ServiceMessage): A list of the messages stored for this service
def get_messages(self, name): return self._loop.run_coroutine(self._client.get_messages(name))
521,835
Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: ServiceMessage: the headline or None if no headline has been set
def get_headline(self, name): return self._loop.run_coroutine(self._client.get_headline(name))
521,836
Send a heartbeat for a service. Args: name (string): The name of the service to send a heartbeat for
def send_heartbeat(self, name): return self._loop.run_coroutine(self._client.send_heartbeat(name))
521,837
Update the state for a service. Args: name (string): The name of the service state (int): The new state of the service
def update_state(self, name, state): self._loop.run_coroutine(self._client.update_state(name, state))
521,839
Asynchronously update the sticky headline for a service. Args: name (string): The name of the service level (int): A message level in states.*_LEVEL message (string): The user facing error message that will be stored for the service and can be queried later.
def post_headline(self, name, level, message): self._client.post_headline(name, level, message)
521,840
Register a new service with the service manager. Args: short_name (string): A unique short name for this service that functions as an id long_name (string): A user facing name for this service allow_duplicate (boolean): Don't throw an error if this service is...
def register_service(self, short_name, long_name, allow_duplicate=True): self._loop.run_coroutine(self._client.register_service(short_name, long_name, allow_duplicate))
521,843
Register to act as the RPC agent for this service. After this cal succeeds, all requests to send RPCs to this service will be routed through this agent. Args: short_name (str): A unique short name for this service that functions as an id
def register_agent(self, short_name): self._loop.run_coroutine(self._client.register_agent(short_name))
521,844
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] new_scope = TriggerScope(sensor_graph, scope_stack, parent.clock(self.interval, basis=self.basis)) scope_stack.append(new_scope)
521,847
Dispatch a message to a callback based on its schema. Args: message (dict): The message to dispatch
def dispatch(self, message): for validator, callback in self.validators: if not validator.matches(message): continue callback(message) return raise ArgumentError("No handler was registered for message", message=message)
521,865
Run the iotile-emulate script. Args: raw_args (list): Optional list of commmand line arguments. If not passed these are pulled from sys.argv.
def main(raw_args=None): if raw_args is None: raw_args = sys.argv[1:] parser = build_parser() args = parser.parse_args(raw_args) if args.firmware_image is None and args.gdb is None: print("You must specify either a firmware image or attach a debugger with --gdb <PORT>") r...
521,868
Probe for all primary services and characteristics in those services Args: handle (int): the connection handle to probe
def _probe_services(self, handle): code = 0x2800 def event_filter_func(event): if (event.command_class == 4 and event.command == 2): event_handle, = unpack("B", event.payload[0:1]) return event_handle == handle return False def...
521,901
Probe gatt services for all associated characteristics in a BLE device Args: conn (int): the connection handle to probe services (dict): a dictionary of services produced by probe_services() timeout (float): the maximum number of seconds to spend in any single task
def _probe_characteristics(self, conn, services, timeout=5.0): for service in services.values(): success, result = self._enumerate_handles(conn, service['start_handle'], service['end_handle']) if not success: ...
521,902
Write to a BLE device characteristic by its handle Args: conn (int): The connection handle for the device we should read from handle (int): The characteristics handle we should read ack (bool): Should this be an acknowledges write or unacknowledged timeout (float...
def _write_handle(self, conn, handle, ack, value, timeout=1.0): conn_handle = conn char_handle = handle def write_handle_acked(event): if event.command_class == 4 and event.command == 1: conn, _, char = unpack("<BHH", event.payload) return ...
521,909
Set the advertising data for advertisements sent out by this bled112 Args: packet_type (int): 0 for advertisement, 1 for scan response data (bytearray): the data to set
def _set_advertising_data(self, packet_type, data): payload = struct.pack("<BB%ss" % (len(data)), packet_type, len(data), bytes(data)) response = self._send_command(6, 9, payload) result, = unpack("<H", response.payload) if result != 0: return False, {'reason': 'Er...
521,912
Set the mode of the BLED112, used to enable and disable advertising To enable advertising, use 4, 2. To disable advertising use 0, 0. Args: discover_mode (int): The discoverability mode, 0 for off, 4 for on (user data) connect_mode (int): The connectability mode, 0 for ...
def _set_mode(self, discover_mode, connect_mode): payload = struct.pack("<BB", discover_mode, connect_mode) response = self._send_command(6, 1, payload) result, = unpack("<H", response.payload) if result != 0: return False, {'reason': 'Error code from BLED112 setti...
521,913
Send a notification to all connected clients on a characteristic Args: handle (int): The handle we wish to notify on value (bytearray): The value we wish to send
def _send_notification(self, handle, value): value_len = len(value) value = bytes(value) payload = struct.pack("<BHB%ds" % value_len, 0xFF, handle, value_len, value) response = self._send_command(2, 5, payload) result, = unpack("<H", response.payload) if resul...
521,914
Enable/disable notifications on a GATT characteristic Args: conn (int): The connection handle for the device we should interact with char (dict): The characteristic we should modify enabled (bool): Should we enable or disable notifications timeout (float): How lo...
def _set_notification(self, conn, char, enabled, timeout=1.0): if 'client_configuration' not in char: return False, {'reason': 'Cannot enable notification without a client configuration attribute for characteristic'} props = char['properties'] if not props.notify: ...
521,915
Connect to AWS IOT with the given client_id Args: client_id (string): The client ID passed to the MQTT message broker
def connect(self, client_id): if self.client is not None: raise InternalError("Connect called on an alreaded connected MQTT client") client = AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient(client_id, useWebsocket=self.websockets) if self.websockets: client.configure...
521,927
Publish a json message to a topic with a type and a sequence number The actual message will be published as a JSON object: { "sequence": <incrementing id>, "message": message } Args: topic (string): The MQTT topic to publish in message (s...
def publish(self, topic, message): seq = self.sequencer.next_id(topic) packet = { 'sequence': seq, 'message': message } # Need to encode bytes types for json.dumps if 'key' in packet['message']: packet['message']['key'] = packet['mes...
521,929
Reset the expected sequence number for a topic If the topic is unknown, this does nothing. This behaviour is useful when you have wildcard topics that only create queues once they receive the first message matching the topic. Args: topic (string): The topic to reset the pa...
def reset_sequence(self, topic): if topic in self.queues: self.queues[topic].reset()
521,931
Unsubscribe from messages on a given topic Args: topic (string): The MQTT topic to unsubscribe from
def unsubscribe(self, topic): del self.queues[topic] try: self.client.unsubscribe(topic) except operationError as exc: raise InternalError("Could not unsubscribe from topic", topic=topic, message=exc.message)
521,932
Callback called whenever we receive a message on a subscribed topic Args: client (string): The client id of the client receiving the message userdata (string): Any user data set with the underlying MQTT client message (object): The mesage with a topic and payload.
def _on_receive(self, client, userdata, message): topic = message.topic encoded = message.payload try: packet = json.loads(encoded) except ValueError: self._logger.warn("Could not decode json packet: %s", encoded) return try: ...
521,933
Sets the RTC timestamp to UTC. 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'] con = hwman.hwman.controller() test_interface = con.test_interface() try: test_interface.synchronize_clock() print('Time currently set at %s' % test_interface.current_time_str()) except: ...
521,934
Add a command to this command file. Args: command (str): The command to add *args (str): The parameters to call the command with
def add(self, command, *args): cmd = Command(command, args) self.commands.append(cmd)
521,936
Load a CommandFile from a string. The string should be produced from a previous call to encode. Args: indata (str): The encoded input data. Returns: CommandFile: The decoded CommandFile object.
def FromString(cls, indata): lines = [x.strip() for x in indata.split("\n") if not x.startswith('#') and not x.strip() == ""] if len(lines) < 3: raise DataError("Invalid CommandFile string that did not contain 3 header lines", lines=lines) fmt_line, version_line, ascii_li...
521,939
Load a CommandFile from a path. Args: inpath (str): The path to the file to load Returns: CommandFile: The decoded CommandFile object.
def FromFile(cls, inpath): with open(inpath, "r") as infile: indata = infile.read() return cls.FromString(indata)
521,940
Encode a command as an unambiguous string. Args: command (Command): The command to encode. Returns: str: The encoded command
def encode(cls, command): args = [] for arg in command.args: if not isinstance(arg, str): arg = str(arg) if "," in arg or arg.startswith(" ") or arg.endswith(" ") or arg.startswith("hex:"): arg = "hex:{}".format(hexlify(arg.encode('utf-8...
521,941
Decode a string encoded command back into a Command object. Args: command_str (str): The encoded command string output from a previous call to encode. Returns: Command: The decoded Command object.
def decode(cls, command_str): name, _, arg = command_str.partition(" ") args = [] if len(arg) > 0: if arg[0] != '{' or arg[-1] != '}': raise DataError("Invalid command, argument is not contained in { and }", arg=arg, cmd=name) arg = arg[1:-1] ...
521,942
Receive one packet If the sequence number is one we've already seen before, it is dropped. If it is not the next expected sequence number, it is put into the _out_of_order queue to be processed once the holes in sequence number are filled in. Args: sequence (int): ...
def receive(self, sequence, args): # If we are told to ignore sequence numbers, just pass the packet on if not self._reorder: self._callback(*args) return # If this packet is in the past, drop it if self._next_expected is not None and sequence < self._n...
521,944
Runs the flash step Args: resources (dict): A dictionary containing the required resources that we needed access to in order to perform this step.
def run(self, resources): if not resources['connection']._port.startswith('jlink'): raise ArgumentError("FlashBoardStep is currently only possible through jlink", invalid_port=args['port']) hwman = resources['connection'] debug = hwman.hwman.debug(self._debug_string) ...
521,950
Run the iotile-tbcompile script. Args: raw_args (list): Optional list of command line arguments. If not passed these are pulled from sys.argv.
def main(raw_args=None): multifile_choices = frozenset(['c_files']) if raw_args is None: raw_args = sys.argv[1:] parser = build_parser() args = parser.parse_args(raw_args) if args.output is None and args.format in multifile_choices: print("You must specify an output file wit...
521,978
Count the number of readings matching selector. Args: selector (DataStreamSelector): The selector that we want to count matching readings for. offset (int): The starting offset that we should begin counting at. Returns: int: The number of matching re...
def count_matching(self, selector, offset=0): if selector.output: data = self.streaming_data elif selector.buffered: data = self.storage_data else: raise ArgumentError("You can only pass a buffered selector to count_matching", selector=selector) ...
522,005
Store a new value for the given stream. Args: value (IOTileReading): The value to store. The stream parameter must have the correct value
def push(self, value): stream = DataStream.FromEncoded(value.stream) if stream.stream_type == DataStream.OutputType: if len(self.streaming_data) == self.streaming_length: raise StorageFullError('Streaming buffer full') self.streaming_data.append(value)...
522,007
Remove and return the oldest count values from the named buffer Args: buffer_type (str): The buffer to pop from (either u"storage" or u"streaming") count (int): The number of readings to pop Returns: list(IOTileReading): The values popped from the buffer
def popn(self, buffer_type, count): buffer_type = str(buffer_type) if buffer_type == u'streaming': chosen_buffer = self.streaming_data else: chosen_buffer = self.storage_data if count > len(chosen_buffer): raise StreamEmptyError("Not enough...
522,009
Send a a script to this IOTile device Args: conn_id (int): A unique identifier that will refer to this connection data (bytes): the script to send to the device
async def send_script(self, conn_id, data): self._ensure_connection(conn_id, True) connection_string = self._get_property(conn_id, "connection_string") msg = dict(connection_string=connection_string, fragment_count=1, fragment_index=0, script=base64.b64encode(data))...
522,016
Callback function called when a report event is received. Args: event (dict): The report_event
async def _on_report_notification(self, event): conn_string = event.get('connection_string') report = self._report_parser.deserialize_report(event.get('serialized_report')) self.notify_event(conn_string, 'report', report)
522,017
Callback function called when a trace chunk is received. Args: trace_chunk (dict): The received trace chunk information
async def _on_trace_notification(self, trace_event): conn_string = trace_event.get('connection_string') payload = trace_event.get('payload') await self.notify_event(conn_string, 'trace', payload)
522,018
Callback function called when a progress notification is received. Args: progress (dict): The received notification containing the progress information
async def _on_progress_notification(self, progress): conn_string = progress.get('connection_string') done = progress.get('done_count') total = progress.get('total_count') operation = progress.get('operation') await self.notify_progress(conn_string, operation, done, tot...
522,019
Archive this recipe and all associated files into a .ship archive. Args: output_path (str): The path where the .ship file should be saved.
def archive(self, output_path): if self.path is None: raise ArgumentError("Cannot archive a recipe yet without a reference to its original yaml file in self.path") outfile = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) outfile.write(self.path, arcname="recipe_s...
522,026
Initialize all steps in this recipe using their parameters. Args: variables (dict): A dictionary of global variable definitions that may be used to replace or augment the parameters given to each step. Returns: list of RecipeActionObject like ins...
def prepare(self, variables): initializedsteps = [] if variables is None: variables = dict() for step, params, _resources, _files in self.steps: new_params = _complete_parameters(params, variables) initializedsteps.append(step(new_params)) ret...
522,035
Execute this statement on the sensor_graph given the current scope tree. This adds a single config variable assignment to the current sensor graph Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying scope_stack (list(Scope)): A s...
def execute(self, sensor_graph, scope_stack): parent = scope_stack[-1] try: slot = parent.resolve_identifier('current_slot', SlotIdentifier) except UnresolvedIdentifierError: raise SensorGraphSemanticError("set config statement used outside of config block") ...
522,056
Format an RPC call and response. Args: data (tuple): A tuple containing the address, rpc_id, argument and response payloads and any error code. Returns: str: The formated RPC string.
def format_rpc(data): address, rpc_id, args, resp, _status = data name = rpc_name(rpc_id) if isinstance(args, (bytes, bytearray)): arg_str = hexlify(args) else: arg_str = repr(args) if isinstance(resp, (bytes, bytearray)): resp_str = hexlify(resp) else: r...
522,057
Call an RPC given a header and possibly a previously sent payload Args: header (bytearray): The RPC header we should call
async def _call_rpc(self, header): length, _, cmd, feature, address = struct.unpack("<BBBBB", bytes(header)) rpc_id = (feature << 8) | cmd payload = self.rpc_payload[:length] self._logger.debug("Calling RPC %d:%04X with %s", address, rpc_id, binascii.hexlify(payload)) ...
522,073
Create a binary script containing this sensor graph. This function produces a repeatable script by applying a known sorting order to all constants and config variables when iterating over those dictionaries. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns...
def format_script(sensor_graph): records = [] records.append(SetGraphOnlineRecord(False, address=8)) records.append(ClearDataRecord(address=8)) records.append(ResetGraphRecord(address=8)) for node in sensor_graph.nodes: records.append(AddNodeRecord(str(node), address=8)) for str...
522,076
Call a function whenever a stream changes. Args: selector (DataStreamSelector): The selector to watch. If this is None, it is treated as a wildcard selector that matches every stream. callback (callable): The function to call when a new re...
def watch(self, selector, callback): if selector not in self._monitors: self._monitors[selector] = set() self._monitors[selector].add(callback)
522,082
Destroy a previously created stream walker. Args: walker (StreamWalker): The walker to remove from internal updating lists.
def destroy_walker(self, walker): if walker.buffered: self._queue_walkers.remove(walker) else: self._virtual_walkers.remove(walker)
522,084
Restore a stream walker that was previously serialized. Since stream walkers need to be tracked in an internal list for notification purposes, we need to be careful with how we restore them to make sure they remain part of the right list. Args: dumped_state (dict): The dump...
def restore_walker(self, dumped_state): selector_string = dumped_state.get(u'selector') if selector_string is None: raise ArgumentError("Invalid stream walker state in restore_walker, missing 'selector' key", state=dumped_state) selector = DataStreamSelector.FromString(sel...
522,085
Push a reading into a stream, updating any associated stream walkers. Args: stream (DataStream): the stream to push the reading into reading (IOTileReading): the reading to push
def push(self, stream, reading): # Make sure the stream is correct reading = copy.copy(reading) reading.stream = stream.encode() if stream.buffered: output_buffer = stream.output if self.id_assigner is not None: reading.reading_id = sel...
522,087
Execute this statement on the sensor_graph given the current scope tree. This adds a single DataStreamer to the current sensor graph Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying scope_stack (list(Scope)): A stack of nested...
def execute(self, sensor_graph, scope_stack): streamer = DataStreamer(self.selector, self.dest, self.report_format, self.auto, report_type=self.report_type, with_other=self.with_other) sensor_graph.add_streamer(streamer)
522,109
Start this emulated device. This triggers the controller to call start on all peripheral tiles in the device to make sure they start after the controller does and then it waits on each one to make sure they have finished initializing before returning. Args: channel ...
def start(self, channel=None): super(EmulatedDevice, self).start(channel) self.emulator.start()
522,125
Call an RPC by its address and ID. This will send the RPC to the background rpc dispatch thread and synchronously wait for the response. Args: address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC payload (bytes): A ...
def call_rpc(self, address, rpc_id, payload=b""): return self.emulator.call_rpc_external(address, rpc_id, payload)
522,128
Restore the current state of this emulated device. Args: state (dict): A previously dumped state produced by dump_state.
def restore_state(self, state): tile_states = state.get('tile_states', {}) for address, tile_state in tile_states.items(): address = int(address) tile = self._tiles.get(address) if tile is None: raise DataError("Invalid dumped state, tile do...
522,132
Call an RPC by its ID. Args: rpc_id (int): The number of the RPC payload (bytes): A byte string of payload parameters up to 20 bytes Returns: str: The response payload from the RPC
def call_rpc(self, rpc_id, payload=bytes()): # If we define the RPC locally, call that one. We use this for reporting # our status if super(ServiceDelegateTile, self).has_rpc(rpc_id): return super(ServiceDelegateTile, self).call_rpc(rpc_id, payload) async def _awa...
522,137
Create a DataStream from a string representation. The format for stream designators when encoded as strings is: [system] (buffered|unbuffered|constant|input|count|output) <integer> Args: string_rep (str): The string representation to turn into a DataStream
def FromString(cls, string_rep): rep = str(string_rep) parts = rep.split() if len(parts) > 3: raise ArgumentError("Too many whitespace separated parts of stream designator", input_string=string_rep) elif len(parts) == 3 and parts[0] != u'system': raise ...
522,142