docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Get a recipe by name. Args: recipe_name (str): The name of the recipe to fetch. Can be either the yaml file name or the name of the recipe.
def get_recipe(self, recipe_name): if recipe_name.endswith('.yaml'): recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name) else: recipe = self._recipes.get(recipe_name) if recipe is None: rai...
519,457
Run an asynchronous command. Args: cmd_name (int): The unique code for the command to execute. callback (callable): The optional callback to run when the command finishes. The signature should be callback(cmd_name, result, exception) *args: Any arguments that...
def command(self, cmd_name, callback, *args): cmd = JLinkCommand(cmd_name, args, callback) self._commands.put(cmd)
519,463
Save an ascii representation of this simulation trace. Args: out_path (str): The output path to save this simulation trace.
def save(self, out_path): out = { 'selectors': [str(x) for x in self.selectors], 'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self] } with open(out_path, "wb") as outfile:...
519,473
Load a previously saved ascii representation of this simulation trace. Args: in_path (str): The path of the input file that we should load. Returns: SimulationTrace: The loaded trace object.
def FromFile(cls, in_path): with open(in_path, "rb") as infile: in_data = json.load(infile) if not ('trace', 'selectors') in in_data: raise ArgumentError("Invalid trace file format", keys=in_data.keys(), expected=('trace', 'selectors')) selectors = [DataStream...
519,474
Get a config value from this adapter by name Args: name (string): The name of the config variable default (object): The default value to return if config is not found Returns: object: the value associated with the name Raises: ArgumentError: if ...
def get_config(self, name, default=_MISSING): value = self._adapter.get_config(name, default) if value is _MISSING: raise ArgumentError("Config value did not exist", name=name) return value
519,483
Step the sensor graph through one since input. The internal tick count is not advanced so this function may be called as many times as desired to input specific conditions without simulation time passing. Args: input_stream (DataStream): The input stream to push the ...
def step(self, input_stream, value): reading = IOTileReading(input_stream.encode(), self.tick_count, value) self.sensor_graph.process_input(input_stream, reading, self.rpc_executor)
519,503
Check if any of our stop conditions are met. Args: sensor_graph (SensorGraph): The sensor graph we are currently simulating Returns: bool: True if we should stop the simulation
def _check_stop_conditions(self, sensor_graph): for stop in self.stop_conditions: if stop.should_stop(self.tick_count, self.tick_count - self._start_tick, sensor_graph): return True return False
519,506
Add a stop condition to this simulation. Stop conditions are specified as strings and parsed into the appropriate internal structures. Args: condition (str): a string description of the stop condition
def stop_condition(self, condition): # Try to parse this into a stop condition with each of our registered # condition types for cond_format in self._known_conditions: try: cond = cond_format.FromString(condition) self.stop_conditions.append(...
519,508
Restore the state of this subsystem from a prior call to dump(). Calling restore must be properly sequenced with calls to other subsystems that include stream walkers so that their walkers are properly restored. Args: state (dict): The results of a prior call to dump().
def restore(self, state): self.storage.restore(state.get('storage')) dump_walker = state.get('dump_walker') if dump_walker is not None: dump_walker = self.storage.restore_walker(dump_walker) self.dump_walker = dump_walker self.next_id = state.get('next_id'...
519,511
Clear all data from the RSL. This pushes a single reading once we clear everything so that we keep track of the highest ID that we have allocated to date. This needs the current timestamp to be able to properly timestamp the cleared storage reading that it pushes. Args: ...
def clear(self, timestamp): self.storage.clear() self.push(streams.DATA_CLEARED, timestamp, 1)
519,512
Push a value to a stream. Args: stream_id (int): The stream we want to push to. timestamp (int): The raw timestamp of the value we want to store. value (int): The 32-bit integer value we want to push. Returns: int: Packed 32-bit error code...
def push(self, stream_id, timestamp, value): stream = DataStream.FromEncoded(stream_id) reading = IOTileReading(stream_id, timestamp, value) try: self.storage.push(stream, reading) return Error.NO_ERROR except StorageFullError: return pack_...
519,514
Inspect the last value written into a virtual stream. Args: stream_id (int): The virtual stream was want to inspect. Returns: (int, int): An error code and the stream value.
def inspect_virtual(self, stream_id): stream = DataStream.FromEncoded(stream_id) if stream.buffered: return [pack_error(ControllerSubsystem.SENSOR_LOG, SensorLogError.VIRTUAL_STREAM_NOT_FOUND), 0] try: reading = self.storage.inspect_last(stream, only_allocated...
519,515
Start dumping a stream. Args: selector_id (int): The buffered stream we want to dump. Returns: (int, int, int): Error code, second error code, number of available readings
def dump_begin(self, selector_id): if self.dump_walker is not None: self.storage.destroy_walker(self.dump_walker) selector = DataStreamSelector.FromEncoded(selector_id) self.dump_walker = self.storage.create_walker(selector, skip_all=False) return Error.NO_ERROR, ...
519,516
Restore the current state of this emulated object. Args: state (dict): A previously dumped state produced by dump_state.
def restore_state(self, state): config_vars = state.get('config_variables', {}) for str_name, str_value in config_vars.items(): name = int(str_name) value = base64.b64decode(str_value) if name in self._config_variables: self._config_variabl...
519,539
Get a config value from this adapter by name Args: name (string): The name of the config variable default (object): The default value to return if config is not found Returns: object: the value associated with the name Raises: ArgumentError: if ...
def get_config(self, name, default=MISSING): res = self.config.get(name, default) if res is MISSING: raise ArgumentError("Could not find config value by name and no default supplied", name=name) return res
519,546
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 not in self.callbacks: raise ValueError("Unknown callback name: %s" % name) self.callbacks[name].add(func)
519,547
Asynchronously connect to a device Args: connection_id (int): A unique identifier that will refer to this connection connection_string (string): A DeviceAdapter specific string that can be used to connect to a device using this DeviceAdapter. callback (callab...
def connect_async(self, connection_id, connection_string, callback): if callback is not None: callback(connection_id, self.id, False, "connect command is not supported in device adapter")
519,549
Synchronously disconnect from a connected device Args: conn_id (int): A unique identifier that will refer to this connection Returns: dict: A dictionary with two elements 'success': a bool with the result of the connection attempt 'failure_reason...
def disconnect_sync(self, conn_id): done = threading.Event() result = {} def disconnect_done(conn_id, adapter_id, status, reason): result['success'] = status result['failure_reason'] = reason done.set() self.disconnect_async(conn_id, discon...
519,551
Declare that a key will be set in the future. This will create a future for the key that is used to hold its result and allow awaiting it. Args: name (str): The unique key that will be used.
def declare(self, name): if name in self._data: raise KeyError("Declared name {} that already existed".format(name)) self._data[name] = self._loop.create_future()
519,563
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 != self._literal: raise ValidationError("Object is not equal to literal", reason='%s is not equal to %s' % (str(obj), str(self._literal)), object=obj) return obj
519,568
Dump the AST for this parsed file. Args: statement (SensorGraphStatement): the statement to print if this function is called recursively. indent_level (int): The number of spaces to indent this statement. Used for recursively printing blocks of ...
def dump_tree(self, statement=None, indent_level=0): out = u"" indent = u" "*indent_level if statement is None: for root_statement in self.statements: out += self.dump_tree(root_statement, indent_level) else: out += indent + str(stateme...
519,570
Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimiza...
def compile(self, model): log = SensorLog(InMemoryStorageEngine(model), model) self.sensor_graph = SensorGraph(log, model) allocator = StreamAllocator(self.sensor_graph, model) self._scope_stack = [] # Create a root scope root = RootScope(self.sensor_graph, a...
519,572
Parse a statement, possibly called recursively. Args: statement (int, ParseResult): The pyparsing parse result that contains one statement prepended with the match location orig_contents (str): The original contents of the file that we're parsing in case ...
def parse_statement(self, statement, orig_contents): children = [] is_block = False name = statement.getName() # Recursively parse all children statements in a block # before parsing the block itself. # If this is a non-block statement, parse it using the state...
519,573
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): if self._started: raise InternalError("The method start() was called twice on VirtualIOTileDevice.") self._push_channel = channel self.start_workers()
519,576
Stream a report asynchronously. If no one is listening for the report, the report may be dropped, otherwise it will be queued for sending Args: report (IOTileReport): The report that should be streamed callback (callable): Optional callback to get notified when ...
def stream(self, report, callback=None): if self._push_channel is None: return self._push_channel.stream(report, callback=callback)
519,577
Stream a realtime value as an IndividualReadingReport. If the streaming interface of the VirtualInterface this VirtualDevice is attached to is not opened, the realtime reading may be dropped. Args: stream (int): The stream id to send value (int): The stream valu...
def stream_realtime(self, stream, value): if not self.stream_iface_open: return reading = IOTileReading(0, stream, value) report = IndividualReadingReport.FromReadings(self.iotile_id, [reading]) self.stream(report)
519,578
Trace data asynchronously. If no one is listening for traced data, it will be dropped otherwise it will be queued for sending. Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): Optional callback to g...
def trace(self, data, callback=None): if self._push_channel is None: return self._push_channel.trace(data, callback=callback)
519,579
Call an RPC by its address and ID. Args: address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC payload (bytes): A byte string of payload parameters up to 20 bytes Returns: bytes: The response payload from the RPC
def call_rpc(self, address, rpc_id, payload=b""): if rpc_id < 0 or rpc_id > 0xFFFF: raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id)) if address not in self._rpc_overlays and address not in self._tiles: raise TileNotFoundError("Unknown tile address, no regis...
519,581
Add a tile to handle all RPCs at a given address. Args: address (int): The address of the tile tile (RPCDispatcher): A tile object that inherits from RPCDispatcher
def add_tile(self, address, tile): if address in self._tiles: raise ArgumentError("Tried to add two tiles at the same address", address=address) self._tiles[address] = tile
519,582
Iterate over all tiles in this device in order. The ordering is by tile address which places the controller tile first in the list. Args: include_controller (bool): Include the controller tile in the results. Yields: int, EmulatedTile: A tuple w...
def iter_tiles(self, include_controller=True): for address, tile in sorted(self._tiles.items()): if address == 8 and not include_controller: continue yield address, tile
519,590
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(ReferenceDevice, self).start(channel) try: self.controller.start(channel) # Guarantee an initialization order so that our trace files are deterministic for address, tile in sorted(self._tiles.items()): i...
519,591
Restore the current state of this emulated device. Note that restore_state happens synchronously in the emulation thread to avoid any race conditions with accessing data members and ensure a consistent atomic restoration process. This method will block while the background restore happ...
def restore_state(self, 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("Invalid emulated device state name or version", found=(state_name, ...
519,595
Set up the global logging level. Args: verbosity (int): The logging verbosity
def configure_logging(verbosity): root = logging.getLogger() formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s', '%y-%m-%d %H:%M:%S') handler = logging.StreamHandler() handler.setFormatter(formatter) loglevels = [log...
519,597
Execute this statement on the sensor_graph given the current scope tree. This adds a single node to the sensor graph with the call_rpc function as is processing function. Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying ...
def execute(self, sensor_graph, scope_stack): parent = scope_stack[-1] alloc = parent.allocator trigger_stream, trigger_cond = parent.trigger_chain() rpc_const = alloc.allocate_stream(DataStream.ConstantType, attach=True) rpc_val = (self.slot_id.address << 16) | self.r...
519,701
A background thread to kill the process if it takes too long. Args: timeout (float): The number of seconds to wait before killing the process. stop_event (Event): An optional event to cleanly stop the background thread if required during testing.
def timeout_thread_handler(timeout, stop_event): stop_happened = stop_event.wait(timeout) if stop_happened is False: print("Killing program due to %f second timeout" % timeout) os._exit(2)
519,702
Parse all global iotile tool arguments. Any flag based argument at the start of the command line is considered as a global flag and parsed. The first non flag argument starts the commands that are passed to the underlying hierarchical shell. Args: argv (list): The command line for this comman...
def parse_global_args(argv): parser = create_parser() args = parser.parse_args(argv) should_log = args.include or args.exclude or (args.verbose > 0) verbosity = args.verbose root = logging.getLogger() if should_log: formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(leveln...
519,704
Return all of the architectures for this target. Args: as_list (bool): Return a list instead of the default set object. Returns: set or list: All of the architectures used in this TargetSettings object.
def archs(self, as_list=False): archs = self.arch_list().split('/') if as_list: return archs return set(archs)
519,719
Update the a tick's interval. Args: index (int): The index of the tick that you want to fetch. interval (int): The number of seconds between ticks. Setting this to 0 will disable the tick. Returns: int: An error code.
def set_tick(self, index, interval): name = self.tick_name(index) if name is None: return pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY) self.ticks[name] = interval return Error.NO_ERROR
519,740
Get a tick's interval. Args: index (int): The index of the tick that you want to fetch. Returns: int, int: Error code and The tick's interval in seconds. A value of 0 means that the tick is disabled.
def get_tick(self, index): name = self.tick_name(index) if name is None: return [pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY), 0] return [Error.NO_ERROR, self.ticks[name]]
519,741
Get the current UTC time or uptime. By default, this method will return UTC time if possible and fall back to uptime if not. If you specify, force_uptime=True, it will always return uptime even if utc time is available. Args: force_uptime (bool): Always return uptime, defa...
def get_time(self, force_uptime=False): if force_uptime: return self.uptime time = self.uptime + self.time_offset if self.is_utc: time |= (1 << 31) return time
519,742
Persistently synchronize the clock to UTC time. Args: offset (int): The number of seconds since 1/1/2000 00:00Z
def synchronize_clock(self, offset): self.time_offset = offset - self.uptime self.is_utc = True if self.has_rtc: self.stored_offset = self.time_offset
519,743
Convert a d-- device slug to an integer. Args: slug (str): A slug in the format d--XXXX-XXXX-XXXX-XXXX Returns: int: The device id as an integer Raises: ArgumentError: if there is a malformed slug
def device_slug_to_id(slug): if not isinstance(slug, str): raise ArgumentError("Invalid device slug that is not a string", slug=slug) try: device_slug = IOTileDeviceSlug(slug, allow_64bits=False) except ValueError: raise ArgumentError("Unable to recognize {} as a device id".fo...
519,748
Converts a device id into a correct device slug. Args: did (long) : A device id did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX Returns: str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format Raises: ArgumentError: if the ...
def device_id_to_slug(did): try: device_slug = IOTileDeviceSlug(did, allow_64bits=False) except ValueError: raise ArgumentError("Unable to recognize {} as a device id".format(did)) return str(device_slug)
519,749
Converts a fleet id into a correct fleet slug. Args: did (long) : A fleet id did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, g--XXXX, g--XXXX-XXXX-XXXX Returns: str: The device slug in the g--XXXX-XXXX-XXX format Raises: ArgumentError: if the ID is not in t...
def fleet_id_to_slug(did): try: fleet_slug = IOTileFleetSlug(did) except ValueError: raise ArgumentError("Unable to recognize {} as a fleet id".format(did)) return str(fleet_slug)
519,750
Get the next sequence number for a named channel or topic If channel has not been sent to next_id before, 0 is returned otherwise next_id returns the last id returned + 1. Args: channel (string): The name of the channel to get a sequential id for. Returns: ...
def next_id(self, channel): if channel not in self.topics: self.topics[channel] = 0 return 0 self.topics[channel] += 1 return self.topics[channel]
519,762
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, str): raise ValidationError("Object is not a string", reason='object is not a string', object=obj, type=type(obj), str_type=str) return obj
519,774
Start streaming a streamer. Args: streamer (DataStreamer): The streamer itself. callback (callable): An optional callable that will be called as: callable(index, success, highest_id_received_from_other_side)
def process_streamer(self, streamer, callback=None): index = streamer.index if index in self._in_progress_streamers: raise InternalError("You cannot add a streamer again until it has finished streaming.") queue_item = QueuedStreamer(streamer, callback) self._in_pr...
519,781
Pack an RPC payload according to arg_format. Args: arg_format (str): a struct format code (without the <) for the parameter format for this RPC. This format code may include the final character V, which means that it expects a variable length bytearray. args (list): A list ...
def pack_rpc_payload(arg_format, args): code = _create_respcode(arg_format, args) packed_result = struct.pack(code, *args) unpacked_validation = struct.unpack(code, packed_result) if tuple(args) != unpacked_validation: raise RPCInvalidArgumentsError("Passed values would be truncated, plea...
519,787
Unpack an RPC payload according to resp_format. Args: resp_format (str): a struct format code (without the <) for the parameter format for this RPC. This format code may include the final character V, which means that it expects a variable length bytearray. payload (bytes):...
def unpack_rpc_payload(resp_format, payload): code = _create_argcode(resp_format, payload) return struct.unpack(code, payload)
519,788
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: bytes: The response payload from the RPC
def call_rpc(self, rpc_id, payload=bytes()): if rpc_id < 0 or rpc_id > 0xFFFF: raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id)) if rpc_id not in self._rpcs: raise RPCNotFoundError("rpc_id: {}".format(rpc_id)) return self._rpcs[rpc_id](payload)
519,791
Wait for the thread to pass control to its routine. Args: timeout (float): The maximum amount of time to wait
def wait_running(self, timeout=None): flag = self._running.wait(timeout) if flag is False: raise TimeoutExpiredError("Timeout waiting for thread to start running")
519,959
Create a new work queue and optionally register it. This will make sure the queue is attached to the correct event loop. You can optionally choose to automatically register it so that wait_idle() will block until the queue is empty. Args: register (bool): Whether to call re...
def create_queue(self, register=False): queue = asyncio.Queue(loop=self._loop) if register: self._work_queues.add(queue) return queue
519,962
Inject a task into the emulation loop and wait for it to finish. The coroutine parameter is run as a Task inside the EmulationLoop until it completes and the return value (or any raised Exception) is pased back into the caller's thread. Args: coroutine (coroutine): The task...
def run_task_external(self, coroutine): self.verify_calling_thread(False, 'run_task_external must not be called from the emulation thread') future = asyncio.run_coroutine_threadsafe(coroutine, self._loop) return future.result()
519,967
Clear all tasks pertaining to a tile. This coroutine will synchronously cancel all running tasks that were attached to the given tile and wait for them to stop before returning. Args: address (int): The address of the tile we should stop.
async def stop_tasks(self, address): tasks = self._tasks.get(address, []) for task in tasks: task.cancel() asyncio.gather(*tasks, return_exceptions=True) self._tasks[address] = []
519,973
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): out_obj = {} if not isinstance(obj, dict): raise ValidationError("Invalid dictionary", reason="object is not a dictionary") if self._fixed_length is not None and len(obj) != self._fixed_length: raise ValidationError("Dictionary did not h...
519,978
Queue data for streaming Args: report (IOTileReport): A report object to stream to a client callback (callable): An optional callback that will be called with a bool value of True when this report actually gets streamed. If the client disconnects and the ...
def stream(self, report, callback=None): conn_id = self._find_connection(self.conn_string) if isinstance(report, BroadcastReport): self.adapter.notify_event_nowait(self.conn_string, 'broadcast', report) elif conn_id is not None: self.adapter.notify_event_nowait...
519,980
Queue data for tracing Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): An optional callback that will be called with a bool value of True when this data actually gets traced. If the ...
def trace(self, data, callback=None): conn_id = self._find_connection(self.conn_string) if conn_id is not None: self.adapter.notify_event_nowait(self.conn_string, 'trace', data) if callback is not None: callback(conn_id is not None)
519,981
Asynchronously connect to a device Args: conn_id (int): A unique identifer that will refer to this connection connection_string (string): A DeviceAdapter specific string that can be used to connect to a device using this DeviceAdapter. callback (callable): A ...
async def connect(self, conn_id, connection_string): id_number = int(connection_string) if id_number not in self.devices: raise DeviceAdapterError(conn_id, 'connect', 'device not found') if self._get_conn_id(connection_string) is not None: raise DeviceAdapterEr...
519,985
Asynchronously disconnect from a connected device Args: conn_id (int): A unique identifier that will refer to this connection callback (callback): A callback that will be called as callback(conn_id, adapter_id, success, failure_reason)
async def disconnect(self, conn_id): self._ensure_connection(conn_id, True) dev = self._get_property(conn_id, 'device') dev.connected = False self._teardown_connection(conn_id)
519,986
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): self._ensure_connection(conn_id, True) dev = self._get_property(conn_id, 'device') try: res = dev.call_rpc(address, rpc_id, bytes(payload)) if inspect.iscoroutine(res): return...
519,989
Asynchronously send a a script to this IOTile device Args: conn_id (int): A unique identifier that will refer to this connection data (bytes or bytearray): the script to send to the device
async def send_script(self, conn_id, data): self._ensure_connection(conn_id, True) dev = self._get_property(conn_id, 'device') conn_string = self._get_property(conn_id, 'connection_string') # Simulate some progress callbacks (0, 50%, 100%) await self.notify_progress(co...
519,990
Map an RPC id to a string name. This function looks the RPC up in a map of all globally declared RPCs, and returns a nice name string. if the RPC is not found in the global name map, returns a generic name string such as 'rpc 0x%04X'. Args: rpc_id (int): The id of the RPC that we wish to look...
def rpc_name(rpc_id): name = _RPC_NAME_MAP.get(rpc_id) if name is None: name = 'RPC 0x%04X' % rpc_id return name
519,993
Map a stream id to a human readable name. The mapping process is as follows: If the stream id is globally known, its global name is used as <name> otherwise a string representation of the stream is used as <name>. In both cases the hex representation of the stream id is appended as a number: ...
def stream_name(stream_id): name = _STREAM_NAME_MAP.get(stream_id) if name is None: name = str(DataStream.FromEncoded(stream_id)) return "{} (0x{:04X})".format(name, stream_id)
519,994
Notify that a reading in the given stream was overwritten. Args: stream (DataStream): The stream that had overwritten data.
def notify_rollover(self, stream): self.offset -= 1 if not self.matches(stream): return if self._count == 0: raise InternalError("BufferedStreamWalker out of sync with storage engine, count was wrong.") self._count -= 1
520,032
Restore the contents of this virtual stream walker. Args: state (dict): The previously serialized state. Raises: ArgumentError: If the serialized state does not have a matching selector.
def restore(self, state): reading = state.get(u'reading') if reading is not None: reading = IOTileReading.FromDict(reading) selector = DataStreamSelector.FromString(state.get(u'selector')) if self.selector != selector: raise ArgumentError("Attempted to ...
520,035
Restore the contents of this virtual stream walker. Args: state (dict): The previously serialized state. Raises: ArgumentError: If the serialized state does not have a matching selector.
def restore(self, state): selector = DataStreamSelector.FromString(state.get(u'selector')) if self.selector != selector: raise ArgumentError("Attempted to restore an InvalidStreamWalker with a different selector", selector=self.selector, serialized_...
520,041
Update this stream walker with a new responsive reading. Args: stream (DataStream): The stream that we're pushing value (IOTileReading): The reading tha we're pushing
def push(self, stream, value): raise ArgumentError("Attempting to push reading to an invalid stream walker that cannot hold data", selector=self.selector, stream=stream)
520,042
Compile and optionally optimize an SGF file. Args: in_path (str): The input path to the sgf file to compile. optimize (bool): Whether to optimize the compiled result, defaults to True if not passed. model (DeviceModel): Optional device model if we are compiling for a...
def compile_sgf(in_path, optimize=True, model=None): if model is None: model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(in_path) parser.compile(model) if optimize: opt = SensorGraphOptimizer() opt.optimize(parser.sensor_graph, model=model) ...
520,060
Execute this statement on the sensor_graph given the current scope tree. This adds a single node to the sensor graph with the trigger_streamer function as is processing function. Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying ...
def execute(self, sensor_graph, scope_stack): parent = scope_stack[-1] alloc = parent.allocator # The output is unused output = alloc.allocate_stream(DataStream.UnbufferedType, attach=True) trigger_stream, trigger_cond = parent.trigger_chain() streamer_const =...
520,064
Add a node to the sensor graph based on the description given. The node_descriptor must follow the sensor graph DSL and describe a node whose input nodes already exist. Args: node_descriptor (str): A description of the node to be added including its inputs, triggeri...
def add_node(self, node_descriptor): if self._max_nodes is not None and len(self.nodes) >= self._max_nodes: raise ResourceUsageError("Maximum number of nodes exceeded", max_nodes=self._max_nodes) node, inputs, processor = parse_node_descriptor(node_descriptor, self.model) ...
520,104
Add a config variable assignment to this sensor graph. Args: slot (SlotIdentifier): The slot identifier that this config variable is assigned to. config_id (int): The 16-bit id of this config_id config_type (str): The type of the config variable, currently ...
def add_config(self, slot, config_id, config_type, value): if slot not in self.config_database: self.config_database[slot] = {} self.config_database[slot][config_id] = (config_type, value)
520,105
Add a streamer to this sensor graph. Args: streamer (DataStreamer): The streamer we want to add
def add_streamer(self, streamer): if self._max_streamers is not None and len(self.streamers) >= self._max_streamers: raise ResourceUsageError("Maximum number of streamers exceeded", max_streamers=self._max_streamers) streamer.link_to_storage(self.sensor_log) streamer.index...
520,106
Store a constant value for use in this sensor graph. Constant assignments occur after all sensor graph nodes have been allocated since they must be propogated to all appropriate virtual stream walkers. Args: stream (DataStream): The constant stream to assign the value to ...
def add_constant(self, stream, value): if stream in self.constant_database: raise ArgumentError("Attempted to set the same constant twice", stream=stream, old_value=self.constant_database[stream], new_value=value) self.constant_database[stream] = value
520,107
Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. Args: stream (DataStream): The stream the input is part of value (IOTileReading): The value to process ...
def process_input(self, stream, value, rpc_executor): self.sensor_log.push(stream, value) # FIXME: This should be specified in our device model if stream.important: associated_output = stream.associated_stream() self.sensor_log.push(associated_output, value) ...
520,114
Manually mark a streamer that should trigger. The next time check_streamers is called, the given streamer will be manually marked that it should trigger, which will cause it to trigger unless it has no data. Args: index (int): The index of the streamer that we should mark a...
def mark_streamer(self, index): self._logger.debug("Marking streamer %d manually", index) if index >= len(self.streamers): raise ArgumentError("Invalid streamer index", index=index, num_streamers=len(self.streamers)) self._manually_triggered_streamers.add(index)
520,115
Create a user understandable string like count(stream) >= X. Args: stream (DataStream): The stream to use to format ourselves. Returns: str: The formatted string
def format_trigger(self, stream): src = u'value' if self.use_count: src = u'count' return u"{}({}) {} {}".format(src, stream, self.comp_string, self.reference)
520,121
Check if this input is triggered on the given stream walker. Args: walker (StreamWalker): The walker to check Returns: bool: Whether this trigger is triggered or not
def triggered(self, walker): if self.use_count: comp_value = walker.count() else: if walker.count() == 0: return False comp_value = walker.peek().value return self.comp_function(comp_value, self.reference)
520,122
Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None
def find_input(self, stream): for i, input_x in enumerate(self.inputs): if input_x[0].matches(stream): return i
520,127
Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output
def connect_output(self, node): if len(self.outputs) == self.max_outputs: raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream) self.outputs.append(node)
520,129
Main script entry point. Args: argv (list): The command line arguments, defaults to sys.argv if not passed. Returns: int: The return value of the script.
def main(argv=None): if argv is None: argv = sys.argv[1:] parser = build_args() args = parser.parse_args(args=argv) verbosity = args.verbose root = logging.getLogger() formatter = logging.Formatter('%(levelname).6s %(name)s %(message)s') handler = logging.StreamHandler() ...
520,134
Restore this state from the output of a previous call to dump(). Only those properties in this object and listed in state will be updated. Other properties will not be modified and state may contain keys that do not correspond with properties in this object. Args: state (d...
def restore(self, state): own_properties = set(self.get_properties()) state_properties = set(state) to_restore = own_properties.intersection(state_properties) for name in to_restore: value = state.get(name) if name in self._complex_properties: ...
520,146
Mark a property as complex with serializer and deserializer functions. Args: name (str): The name of the complex property. serializer (callable): The function to call to serialize the property's value to something that can be saved in a json. deserializer (ca...
def mark_complex(self, name, serializer, deserializer): self._complex_properties[name] = (serializer, deserializer)
520,147
Serialize a property of this class by name. Args: name (str): The name of the property to dump. Returns: object: The serialized value of the property.
def dump_property(self, name): if not hasattr(self, name): raise ArgumentError("Unknown property %s" % name) value = getattr(self, name) if name in self._complex_properties: value = self._complex_properties[name][0](value) return value
520,151
Change (or add) a json key/value pair. Args: data (dict): The original data. This will not be modified. key (list): A list of keys and subkeys specifing the key to change (list can be one) value (str): The value to change for the above key create_if_missing (bool): Set to true to cr...
def modify_dict(data, key, value, create_if_missing=False): data_copy = copy.deepcopy(data) key_copy = copy.deepcopy(key) delver = data_copy current_key = key_copy last_key = "Root" # Dig through the json, setting delver to the dict that contains the last key in "key" while len(curren...
520,227
Make sure the hardware version is what we expect. This convenience function is meant for ensuring that we are talking to a tile that has the correct hardware version. Args: expected (str): The expected hardware string that is compared against what is reported by the...
def check_hardware(self, expected): if len(expected) < 10: expected += '\0'*(10 - len(expected)) err, = self.rpc(0x00, 0x03, expected, result_format="L") if err == 0: return True return False
520,303
Release all resources held by a client. This method must be called and awaited whenever a client is disconnected. It ensures that all of the client's resources are properly released and any devices they have connected to are disconnected cleanly. Args: client_id (s...
async def teardown_client(self, client_id): client_info = self._client_info(client_id) self.adapter.remove_monitor(client_info['monitor']) conns = client_info['connections'] for conn_string, conn_id in conns.items(): try: self._logger.debug("Discon...
520,312
Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: ...
async def connect(self, client_id, conn_string): conn_id = self.adapter.unique_conn_id() self._client_info(client_id) await self.adapter.connect(conn_id, conn_string) self._hook_connect(conn_string, conn_id, client_id)
520,313
Add or replace an entry in the tile cache. Args: tile_info (TileInfo): The newly registered tile.
def insert_tile(self, tile_info): for i, tile in enumerate(self.registered_tiles): if tile.slot == tile_info.slot: self.registered_tiles[i] = tile_info return self.registered_tiles.append(tile_info)
520,335
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): sensor_graph.add_constant(self.stream, 0) new_scope = GatedClockScope(sensor_graph, scope_stack, (self.stream, self.trigger)) scope_stack.append(new_scope)
520,341
Return a NodeInput tuple for triggering an event every interval. We request each distinct type of clock at most once and combine it with our latch stream each time it is requested. Args: interval (int): The interval (in seconds) at which this input should trigger.
def clock(self, interval, basis): cache_name = self._classify_clock(interval, basis) cache_data = self.clock_cache.get(cache_name) if cache_data is None: parent_stream, trigger = self.parent.clock(interval, basis) if trigger.use_count is False: ...
520,354
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 = Scope("Configuration Scope", sensor_graph, parent.allocator, parent) new_scope.add_identifier('current_slot', self.slot) scope_stack.append(new_scope)
520,362
Send advertisements for all connected devices. Args: callback (callable): A callback for when the probe operation has completed. callback should have signature callback(adapter_id, success, failure_reason) where: success: bool failure_reason: ...
def probe_async(self, callback): def _on_finished(_name, control_info, exception): if exception is not None: callback(self.id, False, str(exception)) return self._control_info = control_info try: info = { ...
520,368
Enable debug 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_debug_interface(self, conn_id, callback, connection_string=None): self._try_connect(connection_string) callback(conn_id, self.id, True, None)
520,371
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(EmulatedPeripheralTile, self).restore_state(state) self.debug_mode = state.get('debug_mode', False) self.run_level = state.get('run_level', None) if state.get('app_started', False): self._hosted_app_running.set()
520,379
Load all variables from cmdline args and/or a config file. Args: defines (list of str): A list of name=value pairs that define free variables. config_file (str): An optional path to a yaml config file that defines a single dict with name=value variable definition...
def load_variables(defines, config_file): if config_file is not None: with open(config_file, "r") as conf_file: variables = yaml.load(conf_file) else: variables = {} for define in defines: name, equ, value = define.partition('=') if equ != '=': ...
520,386
Main entry point for iotile-ship recipe runner. This is the iotile-ship command line program. Args: argv (list of str): An optional set of command line parameters. If not passed, these are taken from sys.argv.
def main(argv=None): if argv is None: argv = sys.argv[1:] parser = build_args() args = parser.parse_args(args=argv) recipe_name, _ext = os.path.splitext(os.path.basename(args.recipe)) rm = RecipeManager() rm.add_recipe_folder(os.path.dirname(args.recipe), whitelist=[os.path.base...
520,387
Publish a status message for a device Args: slug (string): The device slug that we are publishing on behalf of data (dict): The status message data to be sent back to the caller
def _publish_status(self, slug, data): status_topic = self.topics.prefix + 'devices/{}/data/status'.format(slug) self._logger.debug("Publishing status message: (topic=%s) (message=%s)", status_topic, str(data)) self.client.publish(status_topic, data)
520,422
Publish a response message for a device Args: slug (string): The device slug that we are publishing on behalf of message (dict): A set of key value pairs that are used to create the message that is sent.
def _publish_response(self, slug, message): resp_topic = self.topics.gateway_topic(slug, 'data/response') self._logger.debug("Publishing response message: (topic=%s) (message=%s)", resp_topic, message) self.client.publish(resp_topic, message)
520,423
Process a command action that we received on behalf of a device. Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself
def _on_action(self, sequence, topic, message): try: slug = None parts = topic.split('/') slug = parts[-3] uuid = self._extract_device_uuid(slug) except Exception as exc: self._logger.warn("Error parsing slug in action handler (slug=%...
520,424
Notify progress reporting on the status of a script download. This function must be called synchronously inside of the event loop. Args: uuid (int): The id of the device that we are talking to client (string): The client identifier done_count (int): The number of it...
def _notify_progress_sync(self, uuid, client, done_count, total_count): # If the connection was closed, don't notify anything conn_data = self._connections.get(uuid, None) if conn_data is None: return last_progress = conn_data['last_progress'] should_drop ...
520,428