runtime.service

runtime.service.broker

Broker service handler.

class runtime.service.broker.Broker(ctx, update_publisher, client, buffers, uids=<factory>, logger=<factory>)[source]

Bases: runtime.remote.Handler

The coordinator between Runtime’s clients and Runtime’s other processes.

Parameters
async get_option(option=None)[source]

Get a command-line option.

Parameters

option (Optional[str]) – The option name. If not provided, all options are returned.

Returns

If the option name was requested, a single option value. Otherwise, a mapping from all option names to their respective values.

async lint()[source]

Lint student code to identify errors and suggest best practices.

Returns

A list of warnings. See the Pylint Output documentation for details.

Note

The numerical score Pylint produces is not reported because Runtime’s API built-ins (runtime.api) are always flagged as undefined. There is no way to selectively exclude certain errors within a category from the score calculation. Perfectly written student code will always have a meaningless penalty.

async send_update()[source]

Broadcast a Smart Device update.

async set_option(options)[source]

Set a command-line option to be used when Runtime is next restarted.

Note

Command-line switches are not supported at this time.

update_gamepads(update)[source]

Update gamepad parameters.

Parameters

update (dict[str, dict[str, typing.Any]]) – A map of gamepad indices to their values.

async update_uids()[source]

Update the set of valid Smart Device UIDs.

property button_params: list[runtime.buffer.Parameter]

Gamepad button parameters.

async runtime.service.broker.main(ctx, **options)[source]

Async entry point.

Parameters

options (Any) – Processed command-line options.

runtime.service.device

Smart device management.

exception runtime.service.device.DeviceError(message, /, **context)[source]

Bases: runtime.exception.RuntimeBaseException

General device error.

class runtime.service.device.EventObserver(devices=<factory>, context=<factory>)[source]

Bases: runtime.service.device.SmartDeviceObserver

Detect Smart Devices using Linux’s udev.

Parameters

devices (asyncio.queues.Queue) – A queue of batches of detected devices. The devices are batched to reduce expensive calls to list_ports.comports().

handle_devices(devices)[source]

Callback for handling newly connected devices.

classmethod is_sensor(device)[source]

Determine whether a udev device is a Smart Sensor.

async start()[source]

Begin monitoring udev events and register initially connected devices.

class runtime.service.device.PollingObserver(patterns=frozenset({'/dev/ttyACM*'}), interval=1, ports=<factory>)[source]

Bases: runtime.service.device.SmartDeviceObserver

Detect Smart Devices by polling the filesystem.

This observer exists for portability on systems without udev.

class runtime.service.device.SmartDeviceClient(reader, writer, buffer=<factory>, requests=<factory>, read_queue=<factory>, write_queue=<factory>, logger=<factory>)[source]

Bases: runtime.service.device.SmartDevice

A Smart Device implementation from the upstream end.

async disable()[source]

Disable the sensor.

async discover(buffers, /, *, interval=1)[source]

Identify information about a newly connected device.

This method periodically pings the device to get a subscription response, which contains the current subscription and the UID. Once the UID is known, the device allocates a buffer.

Parameters
async ping()[source]

Ping the sensor to receive a subscription response.

async read(params=None)[source]

Read some parameters from the device.

Parameters

params (Optional[Collection[str]]) – The names of a collection of parameters to read. If not provided, this client reads all parameters.

async subscribe(params=None, interval=None)[source]

Receive periodic updates for zero or more parameters.

Parameters
  • params (Optional[Collection[str]]) – A list of parameter names.

  • interval (Optional[float]) – The duration between subscription updates in seconds.

Raises

OverflowError – If interval cannot fit in an unsigned 16-bit integer.

async unsubscribe()[source]

Stop receiving subscription updates.

class runtime.service.device.SmartDeviceManager(buffers, observer=<factory>, devices=<factory>, poll_interval=0.04, discovery_timeout=10, logger=<factory>)[source]

Bases: runtime.remote.Handler

Manage the lifecycle and operations of Smart Devices.

Parameters

Note

Although integer UIDs are used internally, UIDs are transported over the network as strings because the serialization protocol may not support 96-bit integers.

async disable(uids=None)[source]

Disable one or more devices.

Parameters

uids (Optional[Union[str, list[str]]]) – The UIDs of devices to disable. See SmartDeviceManager.ping() for an explanation of this argument’s type.

async heartbeat(uid, heartbeat_id=None, timeout=1, block=True)[source]

Send heartbeat requests to a device.

Parameters

uid (str) – The UID of the device to send the request to.

The remaining arguments are passed to SmartDevice.heartbeat().

async list_uids()[source]

List the UIDs of Smart Devices connected currently.

async open_serial_devices(**options)[source]

Open serial ports and schedule their execution concurrently.

Parameters

**options – Keyword arguments passed to serial_asyncio.open_serial_connection().

async open_virtual_devices(vsd_addr)[source]

Establish connections to Virtual Smart Devices forever.

Parameters

vsd_addr (str) – The address to listen on.

async ping(uids=None)[source]

Ping one or more devices.

Parameters

uids (Optional[Union[str, list[str]]]) – The UIDs of devices to ping. If None is provided, this handler will ping all devices. A single UID or a list of UIDs may also be provided.

async read(uid, params=None)[source]

Read some parameters.

The parameter values are not returned from this method, since the Smart Device protocol is asynchronous. Instead, the updated parameters will be copied into the corresponding buffer.

Parameters

uid (str) – The UID of the device to read parameters from.

The remaining arguments are passed to SmartDevice.read().

async run_device(reader, writer, port=None)[source]

Create and register a new Smart Device and block until the connection closes.

Parameters
  • reader (asyncio.streams.StreamReader) – Stream reader.

  • writer (asyncio.streams.StreamWriter) – Stream writer.

  • port (Optional[pathlib.Path]) – The COM port path, if this is a serial connection. If not provided, this method assumes this device is virtual.

async subscribe(uid, params=None, interval=None)[source]

Send subscription requests to a device.

Parameters

uid (str) – The UID of the device to send the request to.

The remaining arguments are passed to SmartDevice.subscribe().

async unsubscribe(uids=None)[source]

Unsubscribe from all parameters.

Parameters

uids (Optional[Union[str, list[str]]]) – The UIDs of devices to unsubscribe from. See SmartDeviceManager.ping() for an explanation of this argument’s type.

runtime.service.device.target(**options)[source]

Process entry point.

Parameters

**options – Command-line options.

runtime.service.executor

Student code execution.

exception runtime.service.executor.ExecutionError(message, /, **context)[source]

Bases: runtime.exception.RuntimeBaseException

General execution error.

class runtime.service.executor.AsyncExecutor(loop=None, requests=None, max_actions=128, requests_size=128, running_actions=<factory>, configure_loop=<function AsyncExecutor.<lambda>>, logger=<factory>)[source]

Bases: runtime.service.executor.Executor, runtime.api.Actions

An executor that executes coroutine functions.

Parameters
  • loop (Optional[asyncio.events.AbstractEventLoop]) – The event loop running the coroutine functions as tasks.

  • requests (Optional[asyncio.queues.Queue]) – An async queue of execution requests.

  • max_actions (int) – The maximum number of concurrently running tasks.

  • requests_size (int) – The size of the requests queue.

  • running_actions (dict[typing.Callable[..., typing.Awaitable[NoneType]], _asyncio.Task]) – Maps coroutine functions to their running task instances. For resource contention reasons, only one task instance may exist at a time per coroutine function. Once a task completes, its entry is removed from this mapping.

  • debugasyncio debug flag.

  • executorasyncio executor for dispatching synchronous tasks.

async dispatch(*, cooldown=1)[source]

Receive and handle requests from the queue.

class runtime.service.executor.Dispatcher(buffers, student_code_name='studentcode', timeouts=<factory>, names=<factory>, sync_exec=<factory>, async_exec=<factory>, client=None, logger=<factory>)[source]

Bases: runtime.remote.Handler

An RPC handler to forward execution requests to the executors.

Parameters
async auto()[source]

Enter autonomous mode.

estop()[source]

Raise an emergency stop exception.

async execute(requests, block=False, enable_gamepads=True)[source]

Request student code execution.

async idle()[source]

Suspend all execution (synchronous and asynchronous).

prepare_student_code_run(requests, enable_gamepads=True)[source]

Prepare to run student code.

Reload the student code module, then enqueue execution requests for the module’s functions.

Parameters

requests (list[dict[str, typing.Any]]) – A list of keyword arguments to ExecutionRequest. However, the func argument should be a string naming a function in the student code module. Also, if timeout is not present, this method matches each function name against patterns in timeouts to find the timeout.

reload(*, enable_gamepads=True)[source]

Load student code from disk and monkey-patch in the Runtime API.

Parameters

enable_gamepads (bool) – Whether to allow reading from gamepads.

async teleop()[source]

Enter teleop mode.

class runtime.service.executor.ExecutionRequest(func=<function ExecutionRequest.<lambda>>, args=(), timeout=1, periodic=False, loop=None, future=None)[source]

Bases: NamedTuple

A request for an Executor to execute a callable.

Parameters
  • func (Callable[[...], Optional[Awaitable[None]]]) – The callable. May or may be a coroutine function.

  • args (Sequence[Any]) – Positonal arguments to pass to func.

  • timeout (float) – If the request is not periodic, the timeout is the maximum number of seconds the callable should run for. If the request is periodic, the timeout is the interval between invocations.

  • periodic (bool) – Whether the callable should be invoked once or repeatedly at a fixed rate.

set_result(result, /)[source]

Resolve this request’s future.

class runtime.service.executor.Executor[source]

Bases: abc.ABC

Schedule and execute callables with timeouts.

cancel()[source]

Cancel all current execution.

abstract execute_forever()[source]

Execute callables indefinitely (blocking) until stop() is called.

abstract schedule(request)[source]

Schedule a callable for execution.

Parameters

request (runtime.service.executor.ExecutionRequest) – The execution request.

Raises

ExecutionError – If the callable was unable to be scheduled.

Note

This method should be thread-safe but is allowed to block. The order in which callables are registered may or may not be meaningful. They may be executed in the order in which they were registered, or they may execute concurrently.

stop()[source]

Cancel all execution, then unblock execute_forever().

class runtime.service.executor.SyncExecutor(requests=<factory>, logger=<factory>)[source]

Bases: runtime.service.executor.Executor

An executor that executes synchronous functions, using alarms for timeouts.

A synchronous executor may only run in the main thread because the main thread executes signal handlers. Synchronous handlers rely on the SIGALRM handler to raise an exception that will interrupt code that reaches a timeout.

Parameters

requests (queue.Queue[runtime.service.executor.ExecutionRequest]) – A synchronous queue of execution requests.

execute(request)[source]

Execute a regular execution request.

Parameters

request (runtime.service.executor.ExecutionRequest) – An execution request.

runtime.service.executor.target(name, **options)[source]

The process entry point.

Parameters
  • name (str) – This process’s application name.

  • options (Any) – Processed command-line options.