iotile.core.hw.virtual

Base classes for creating and interacting with virtual IOTile devices.

Package Contents

class VirtualTile(address, name, device=None)

Bases:iotile.core.hw.virtual.base_runnable.BaseRunnable, iotile.core.hw.virtual.common_types.RPCDispatcher

A virtual tile.

Tiles have their own RPC based API and can run background threads to do periodic work.

Args:
address (int): The address of this tile in the VirtualIOTIleDevice
that contains it
name (str): The 6 character name that should be returned when this
tile is asked for its status to allow matching it with a proxy object.

device (TileBasedVirtualDevice) : optional, device on which this tile is running

classmethod _check_convert_name(cls, name)
start(self, channel=None)

Start any background workers on this tile.

stop(self)

Stop any background workers on this tile.

signal_stop(self)

Asynchronously signal that all workers should stop.

wait_stopped(self)

Wait for all workers to stop.

classmethod FindByName(cls, name)

Find an installed VirtualTile by name.

This function searches for installed virtual tiles using the pkg_resources entry_point iotile.virtual_tile.

If name is a path ending in .py, it is assumed to point to a module on disk and loaded directly rather than using pkg_resources.

Args:
name (str): The name of the tile to search
for.
Returns:
VirtualTile class: A virtual tile subclass that can be
instantiated to create a virtual tile.
classmethod LoadFromFile(cls, script_path)

Import a virtual tile from a file rather than an installed module

script_path must point to a python file ending in .py that contains exactly one VirtualTile class definition. That class is loaded and executed as if it were installed.

To facilitate development, if there is a proxy object defined in the same file, it is also added to the HardwareManager proxy registry so that it can be found and used with the device.

Args:
script_path (string): The path to the script to load
Returns:
VirtualTile: A subclass of VirtualTile that was loaded from script_path
tile_status(self)

Required status RPC that allows matching a proxy object with a tile.

class VirtualIOTileDevice(iotile_id, name)

Bases:iotile.core.hw.virtual.base_runnable.BaseRunnable

A Virtual IOTile device that can be interacted with as if it were a real one.

This is the base class of all other Virtual IOTile devices. It allows defining RPCs directly using decorators and the register_rpc function. Subclasses implement virtual tiles that modularize building complex virtual devices from reusable pieces.

This class also implements the required controller status RPC that allows matching it with a proxy object.

Args:
iotile_id (int): A 32-bit integer that specifies the globally unique ID
for this IOTile device.
name (string): The 6 byte name that should be returned when anyone asks
for the controller’s name of this IOTile device using an RPC
connected

Whether someone is connected to the virtual device.

stream_iface_open

Whether the streaming interface is opened.

Deprecated:
3.14.5: Use interface_open(‘stream’) instead
trace_iface_open

Whether the tracing interface is opened.

Deprecated:
3.14.5: Use interface_open(‘trace’) instead
pending_data

Whether there are streaming reports waiting to be sent.

start(self, channel)

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
stop(self)

Stop running this virtual device including any worker threads.

stream(self, report, callback=None)

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

this report is actually sent.
stream_realtime(self, stream, value)

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 value to send
trace(self, data, callback=None)

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 get notified when
this data is actually sent.
register_rpc(self, address, rpc_id, func)

Register a single RPC handler with the given info.

This function can be used to directly register individual RPCs, rather than delegating all RPCs at a given address to a virtual Tile.

If calls to this function are mixed with calls to add_tile for the same address, these RPCs will take precedence over what is defined in the tiles.

Args:

address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC func (callable): The function that should be called to handle the

RPC. func is called as func(payload) and must return a single string object of up to 20 bytes with its response
call_rpc(self, address, rpc_id, payload=b'')

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
add_tile(self, address, tile)

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
open_rpc_interface(self)

Called when someone opens an RPC interface to the device.

close_rpc_interface(self)

Called when someone closes an RPC interface to the device.

open_script_interface(self)

Called when someone opens a script interface on this device.

close_script_interface(self)

Called when someone closes a script interface on this device.

open_streaming_interface(self)

Called when someone opens a streaming interface to the device.

Returns:
list: A list of IOTileReport objects that should be sent out
the streaming interface.
close_streaming_interface(self)

Called when someone closes the streaming interface to the device.

open_tracing_interface(self)

Called when someone opens a tracing interface to the device.

Returns:
list: A list of bytearray objects that should be sent out
the tracing interface.
close_tracing_interface(self)

Called when someone closes the tracing interface to the device.

push_script_chunk(self, chunk)

Called when someone pushes a new bit of a TRUB script to this device

Args:
chunk (str): a buffer with the next bit of script to append
tile_rpc(rpc_id, arg_format, resp_format=None)

Decorator to denote that a function implements an RPC with the given ID on a tile.

The underlying function should be a member function that will take individual parameters after the RPC payload has been decoded according to arg_format.

Arguments to the function are decoded from the 20 byte RPC argument payload according to arg_format, which should be a format string that can be passed to struct.unpack.

Similarly, the function being decorated should return an iterable of results that will be encoded into a 20 byte response buffer by struct.pack using resp_format as the format string.

The RPC will respond as if it were implemented by a tile at address address and the 16-bit RPC id rpc_id.

Args:

rpc_id (int): The number of the RPC arg_format (string): a struct format code (without the <) for the

parameter format for this RPC
resp_format (string): an optional format code (without the <) for
the response format for this RPC
class RPCDispatcher(*args, **kwargs)

A simple dispatcher that can store and call RPCs.

add_rpc(self, rpc_id, func)

Add an RPC.

Args:

rpc_id (int): The ID of the RPC func (callable): The RPC implementation.

The signature of callable should be callable(args) taking a bytes object with the argument and returning a bytes object with the response.
has_rpc(self, rpc_id)

Check if an RPC is defined.

Args:
rpc_id (int): The RPC to check
Returns:
bool: Whether it exists
call_rpc(self, rpc_id, payload=bytes())

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
class RPCInvalidIDError

Bases:iotile.core.exceptions.IOTileException

Exception thrown when an RPC is created with an invalid RPC id.

class RPCNotFoundError

Bases:iotile.core.exceptions.IOTileException

Exception thrown when an RPC is not found.

class RPCInvalidArgumentsError

Bases:iotile.core.exceptions.IOTileException

Exception thrown when an RPC with a fixed parameter format has invalid arguments.

class RPCInvalidReturnValueError

Bases:iotile.core.exceptions.IOTileException

Exception thrown when the return value of an RPC does not conform to its known format.

class TileNotFoundError

Bases:iotile.core.exceptions.IOTileException

Exception thrown when an RPC is sent to a tile that does not exist.

class RPCErrorCode(status_code)

Bases:iotile.core.exceptions.IOTileException

Exception thrown from an RPC implementation to set the status code.

unpack_rpc_payload(resp_format, payload)

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): The binary payload that should be unpacked.

Returns:
list: A list of the unpacked payload items.
pack_rpc_payload(arg_format, args)

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 of arguments to pack according to arg_format.

Returns:
bytes: The packed argument buffer.
class VirtualIOTileInterface

A virtual interface that presents an IOTile device to the world

An example of a virtual interface is a bluetooth adapter configured with a GATT server that implements the TileBus over BLE protocol allowing any BLE client to connect to this virtual IOTile device as if it were a real one.

There are two portions of the VirtualIOTileInterface.

The first is to handle external control commands to the VirtualIOTileDevice that it is managing.

The second is to provide an API to that device for it to asynchronously stream or trace data back to any client that might be connected over the virtual interface.

start(self, device)

Begin allowing connections to a virtual IOTile device.

Args:
device (VirtualIOTileDevice): The python object that implements the IOTile
device functionality that we wish to allow interaction with.
process(self)

Process all pending actions, needs to be called periodically after start.

This function will block for up to 100 ms so that it may be simply called in a tight while loop without pegging the CPU to 100%.

stop(self)

Stop allowing connections to this virtual IOTile device.

_audit(self, event, **kwargs)

Log an audit event with the given message and parameters.

Args:

event (string): The event type that we are logging **kwargs: All required and any desired optional parameters associated

with the audit event
_defer(self, action, args=None)

Queue an action to be executed the next time process is called.

This is very useful for callbacks that should be called on the main thread but are queued from a different thread.

Args:
action (callable): A function to be called as action(*args) args (list): A list of arguments (possibly empty) to be passed to action
_clear_reports(self)

Clear all queued reports and any in progress reports.

This function should be called when a client disconnects so that future clients don’t get a partial report streamed to them.

_clear_traces(self)

Clear all queued traces and any in progress traces.

This function should be called when a client disconnects so that future clients don’t get old tracing data.

_queue_reports(self, *reports)

Queue reports for transmission over the streaming interface.

The primary reason for this function is to allow for a single implementation of encoding and chunking reports for streaming.

You can pass a series of either IOTileReport subclasses or tuples of a report and a callback. The callback will be called with a single bool argument when the report finishes streaming. It will be passed True if the report actually was streamed and False if it was cleared before streaming.

Args:
*reports (list): A list of IOTileReport objects that should be sent over

the streaming interface. If you want to get a callback when the report actually finishes being streamed out over the interface, you can put a tuple of (IOTileReport, callback) instead of an IOTileReport.

Your callback, if supplied will be called when the report finishes being streamed.

_queue_traces(self, *traces)

Queue tracing information for transmission over the tracing interface.

The primary reason for this function is to allow for a single implementation of encoding and chunking traces for tracing.

You can pass a series of either bytes/bytearrays or tuples of a byte/bytearray and a callback. The callback will be called with a single bool argument when the trace is actually sent. It will be passed True if the trace actually was sent and False if it was cleared before being sent (e.g. because the client disconnected).

Args:
*traces (list): A list of bytes or bytearray objects that should be sent over
the tracing interface.
_next_streaming_chunk(self, max_size)

Get the next chunk of data that should be streamed

Args:
max_size (int): The maximum size of the chunk to be returned
Returns:
bytearray: the chunk of raw data with size up to but not exceeding
max_size.
_next_tracing_chunk(self, max_size)

Get the next chunk of data that should be traced

Args:
max_size (int): The maximum size of the chunk to be returned
Returns:
bytearray: the chunk of raw data with size up to but not exceeding
max_size.