viam.components.input.service

Attributes

LOGGER

Exceptions

NotSupportedError

Exception raised when specific component functionality is not supported

Classes

DoCommandRequest

DoCommandRequest represents a generic DoCommand input

DoCommandResponse

DoCommandResponse represents a generic DoCommand output

GetGeometriesRequest

Abstract base class for protocol messages.

GetGeometriesResponse

Abstract base class for protocol messages.

GetControlsRequest

Abstract base class for protocol messages.

GetControlsResponse

Abstract base class for protocol messages.

GetEventsRequest

Abstract base class for protocol messages.

GetEventsResponse

Abstract base class for protocol messages.

InputControllerServiceBase

Helper class that provides a standard way to create an ABC using

StreamEventsRequest

Abstract base class for protocol messages.

StreamEventsResponse

Abstract base class for protocol messages.

TriggerEventRequest

Abstract base class for protocol messages.

TriggerEventResponse

Abstract base class for protocol messages.

ResourceRPCServiceBase

Base RPC service for a resource.

Control

Control identifies the input (specific Axis or Button) of a controller.

Controller

Controller is a logical "container" more than an actual device

Event

EventType

Represents the type of input event.

InputControllerRPCService

gRPC Service for an input controller

Functions

dict_to_struct(→ google.protobuf.struct_pb2.Struct)

struct_to_dict(→ Dict[str, ValueTypes])

Module Contents

exception viam.components.input.service.NotSupportedError(message: str)[source]

Bases: ViamGRPCError

Exception raised when specific component functionality is not supported

class viam.components.input.service.DoCommandRequest(*, name: str = ..., command: google.protobuf.struct_pb2.Struct | None = ...)

Bases: google.protobuf.message.Message

DoCommandRequest represents a generic DoCommand input

name: str
property command: google.protobuf.struct_pb2.Struct
HasField(field_name: Literal['command', b'command']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.DoCommandResponse(*, result: google.protobuf.struct_pb2.Struct | None = ...)

Bases: google.protobuf.message.Message

DoCommandResponse represents a generic DoCommand output

property result: google.protobuf.struct_pb2.Struct
HasField(field_name: Literal['result', b'result']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.GetGeometriesRequest(*, name: str = ..., extra: google.protobuf.struct_pb2.Struct | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

name: str

The component name

property extra: google.protobuf.struct_pb2.Struct

Additional arguments to the method

HasField(field_name: Literal['extra', b'extra']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.GetGeometriesResponse(*, geometries: collections.abc.Iterable[global___Geometry] | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

property geometries: google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Geometry]

All geometries associated with the component, in their current configuration, in the frame of that component.

class viam.components.input.service.GetControlsRequest(*, controller: str = ..., extra: google.protobuf.struct_pb2.Struct | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

controller: str

Name of an input controller

property extra: google.protobuf.struct_pb2.Struct

Additional arguments to the method

HasField(field_name: Literal['extra', b'extra']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.GetControlsResponse(*, controls: collections.abc.Iterable[str] | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

property controls: google.protobuf.internal.containers.RepeatedScalarFieldContainer[str]

Returns a list of all the controls (buttons and axes) that are available to a given Input Controller

class viam.components.input.service.GetEventsRequest(*, controller: str = ..., extra: google.protobuf.struct_pb2.Struct | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

controller: str

Name of an input controller

property extra: google.protobuf.struct_pb2.Struct

Additional arguments to the method

HasField(field_name: Literal['extra', b'extra']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.GetEventsResponse(*, events: collections.abc.Iterable[global___Event] | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

property events: google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Event]

Returns a list of the most recent event for each control on a given InputController. Effectively provides the current “state” of all buttons/axes on a given input controller

class viam.components.input.service.InputControllerServiceBase[source]

Bases: abc.ABC

Helper class that provides a standard way to create an ABC using inheritance.

abstract GetControls(stream: grpclib.server.Stream[component.inputcontroller.v1.input_controller_pb2.GetControlsRequest, component.inputcontroller.v1.input_controller_pb2.GetControlsResponse]) None[source]
Async:

abstract GetEvents(stream: grpclib.server.Stream[component.inputcontroller.v1.input_controller_pb2.GetEventsRequest, component.inputcontroller.v1.input_controller_pb2.GetEventsResponse]) None[source]
Async:

abstract StreamEvents(stream: grpclib.server.Stream[component.inputcontroller.v1.input_controller_pb2.StreamEventsRequest, component.inputcontroller.v1.input_controller_pb2.StreamEventsResponse]) None[source]
Async:

abstract TriggerEvent(stream: grpclib.server.Stream[component.inputcontroller.v1.input_controller_pb2.TriggerEventRequest, component.inputcontroller.v1.input_controller_pb2.TriggerEventResponse]) None[source]
Async:

abstract DoCommand(stream: grpclib.server.Stream[common.v1.common_pb2.DoCommandRequest, common.v1.common_pb2.DoCommandResponse]) None[source]
Async:

abstract GetGeometries(stream: grpclib.server.Stream[common.v1.common_pb2.GetGeometriesRequest, common.v1.common_pb2.GetGeometriesResponse]) None[source]
Async:

__mapping__() Dict[str, grpclib.const.Handler][source]
class viam.components.input.service.StreamEventsRequest(*, controller: str = ..., events: collections.abc.Iterable[global___StreamEventsRequest] | None = ..., extra: google.protobuf.struct_pb2.Struct | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

class Events(*, control: str = ..., events: collections.abc.Iterable[str] | None = ..., cancelled_events: collections.abc.Iterable[str] | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

control: str

Name of a control (button or axis)

property events: google.protobuf.internal.containers.RepeatedScalarFieldContainer[str]

Specify which event types to recieve events for

property cancelled_events: google.protobuf.internal.containers.RepeatedScalarFieldContainer[str]

Specify which event types to stop recieving events for This can be an empty list

controller: str

Name of an input controller

property events: google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___StreamEventsRequest]

A list of Events

property extra: google.protobuf.struct_pb2.Struct

Additional arguments to the method

HasField(field_name: Literal['extra', b'extra']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.StreamEventsResponse(*, event: global___Event | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

property event: global___Event

Event for a controller

HasField(field_name: Literal['event', b'event']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.TriggerEventRequest(*, controller: str = ..., event: global___Event | None = ..., extra: google.protobuf.struct_pb2.Struct | None = ...)

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

controller: str

Name of an input controller

property event: global___Event

Digitally assert a given event

property extra: google.protobuf.struct_pb2.Struct

Additional arguments to the method

HasField(field_name: Literal['event', b'event', 'extra', b'extra']) bool

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Parameters:

field_name (str) – The name of the field to check for presence.

Returns:

Whether a value has been set for the named field.

Return type:

bool

Raises:

ValueError – if the field_name is not a member of this message.

class viam.components.input.service.TriggerEventResponse

Bases: google.protobuf.message.Message

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

class viam.components.input.service.ResourceRPCServiceBase(manager: viam.resource.manager.ResourceManager)[source]

Bases: abc.ABC, viam.rpc.types.RPCServiceBase, Generic[viam.resource.manager.ResourceType]

Base RPC service for a resource. All resource RPC services must inherit from this class.

RESOURCE_TYPE
manager: viam.resource.manager.ResourceManager
get_resource(name: str) viam.resource.manager.ResourceType[source]

Return the resource with the given name if it exists in the registry. If the resource does not exist in the registry, this function will raise an error

Parameters:

name (str) – Name of the resource

Raises:

GRPCError with the status code Status.NOT_FOUND

Returns:

The resource

Return type:

ResourceType

viam.components.input.service.dict_to_struct(obj: Mapping[str, ValueTypes]) google.protobuf.struct_pb2.Struct[source]
viam.components.input.service.struct_to_dict(struct: google.protobuf.struct_pb2.Struct) Dict[str, ValueTypes][source]
class viam.components.input.service.Control[source]

Bases: str, enum.Enum

Control identifies the input (specific Axis or Button) of a controller.

ABSOLUTE_X = 'AbsoluteX'
ABSOLUTE_Y = 'AbsoluteY'
ABSOLUTE_Z = 'AbsoluteZ'
ABSOLUTE_RX = 'AbsoluteRX'
ABSOLUTE_RY = 'AbsoluteRY'
ABSOLUTE_RZ = 'AbsoluteRZ'
ABSOLUTE_HAT0_X = 'AbsoluteHat0X'
ABSOLUTE_HAT0_Y = 'AbsoluteHat0Y'
BUTTON_SOUTH = 'ButtonSouth'
BUTTON_EAST = 'ButtonEast'
BUTTON_WEST = 'ButtonWest'
BUTTON_NORTH = 'ButtonNorth'
BUTTON_LT = 'ButtonLT'
BUTTON_RT = 'ButtonRT'
BUTTON_LT2 = 'ButtonLT2'
BUTTON_RT2 = 'ButtonRT2'
BUTTON_L_THUMB = 'ButtonLThumb'
BUTTON_R_THUMB = 'ButtonRThumb'
BUTTON_SELECT = 'ButtonSelect'
BUTTON_START = 'ButtonStart'
BUTTON_MENU = 'ButtonMenu'
BUTTON_RECORD = 'ButtonRecord'
BUTTON_E_STOP = 'ButtonEStop'
ABSOLUTE_PEDAL_ACCELERATOR = 'AbsolutePedalAccelerator'
ABSOLUTE_PEDAL_BRAKE = 'AbsolutePedalBrake'
ABSOLUTE_PEDAL_CLUTCH = 'AbsolutePedalClutch'
class viam.components.input.service.Controller(name: str)[source]

Bases: viam.components.component_base.ComponentBase

Controller is a logical “container” more than an actual device Could be a single gamepad, or a collection of digitalInterrupts and analogReaders, a keyboard, etc.

from viam.components.input import Control, Controller, EventType

For more information, see Input Controller component.

SUBTYPE: Final
abstract get_controls(*, extra: Dict[str, Any] | None = None, timeout: float | None = None, **kwargs) List[Control][source]
Async:

Returns a list of Controls provided by the Controller

# Get the controller from the machine.
my_controller = Controller.from_robot(
    robot=myRobotWithController, name="my_controller")

# Get the list of Controls provided by the controller.
controls = await my_controller.get_controls()

# Print the list of Controls provided by the controller.
print(f"Controls: {controls}")
Returns:

List of controls provided by the Controller

Return type:

List[Control]

For more information, see Input Controller component.

abstract get_events(*, extra: Dict[str, Any] | None = None, timeout: float | None = None, **kwargs) Dict[Control, Event][source]
Async:

Returns the most recent Event for each input (which should be the current state)

# Get the controller from the machine.
my_controller = Controller.from_robot(
    robot=myRobotWithController, name="my_controller")

# Get the most recent Event for each Control.
recent_events = await my_controller.get_events()

# Print out the most recent Event for each Control.
print(f"Recent Events: {recent_events}")
Returns:

The most recent event for each input

Return type:

Dict[Control, Event]

For more information, see Input Controller component.

abstract register_control_callback(control: Control, triggers: List[EventType], function: ControlFunction | None, *, extra: Dict[str, Any] | None = None, **kwargs)[source]

Register a function that will fire on given EventTypes for a given Control

# Define a function to handle pressing the Start Menu Button "BUTTON_START" on
# your controller, printing out the start time.
def print_start_time(event):
    print(f"Start Menu Button was pressed at this time: {event.time}")


# Define a function that handles the controller.
async def handle_controller(controller):
    # Get the list of Controls on the controller.
    controls = await controller.get_controls()

    # If the "BUTTON_START" Control is found, register the function
    # print_start_time to fire when "BUTTON_START" has the event "ButtonPress"
    # occur.
    if Control.BUTTON_START in controls:
        controller.register_control_callback(
            Control.BUTTON_START, [EventType.BUTTON_PRESS], print_start_time)
    else:
        print("Oops! Couldn't find the start button control! Is your "
            "controller connected?")
        exit()

    while True:
        await asyncio.sleep(1.0)


async def main():
    # ... < INSERT CONNECTION CODE FROM MACHINE'S CODE SAMPLE TAB >

    # Get your controller from the machine.
    my_controller = Controller.from_robot(
        robot=myRobotWithController, name="my_controller")

    # Run the handleController function.
    await handleController(my_controller)

    # ... < INSERT ANY OTHER CODE FOR MAIN FUNCTION >
Parameters:
  • control (Control) – The control to register the function for

  • triggers (List[EventType]) – The events that will trigger the function

  • function (ControlFunction) – The function to run on specific triggers

For more information, see Input Controller component.

async trigger_event(event: Event, *, extra: Dict[str, Any] | None = None, timeout: float | None = None, **kwargs) None[source]

Directly send an Event (such as a button press) from external code

# Define a "Button is Pressed" event for the control BUTTON_START.
button_is_pressed_event = Event(
    time(), EventType.BUTTON_PRESS, Control.BUTTON_START, 1.0)

# Trigger the event on your controller. Set this trigger to timeout if it has
# not completed in 7 seconds.
await myController.trigger_event(event=my_event, timeout=7.0)
Parameters:

event (Event) – The event to trigger

For more information, see Input Controller component.

classmethod from_robot(robot: viam.robot.client.RobotClient, name: str) typing_extensions.Self

Get the component named name from the provided robot.

Parameters:
  • robot (RobotClient) – The robot

  • name (str) – The name of the component

Returns:

The component, if it exists on the robot

Return type:

Self

abstract do_command(command: Mapping[str, ValueTypes], *, timeout: float | None = None, **kwargs) Mapping[str, ValueTypes]
Async:

Send/Receive arbitrary commands to the Resource

command = {"cmd": "test", "data1": 500}
result = component.do(command)
Parameters:

command (Mapping[str, ValueTypes]) – The command to execute

Raises:

NotImplementedError – Raised if the Resource does not support arbitrary commands

Returns:

Result of the executed command

Return type:

Mapping[str, ValueTypes]

async get_geometries(*, extra: Dict[str, Any] | None = None, timeout: float | None = None) List[viam.proto.common.Geometry]

Get all geometries associated with the component, in their current configuration, in the frame of the component.

geometries = await component.get_geometries()

if geometries:
    # Get the center of the first geometry
    print(f"Pose of the first geometry's centerpoint: {geometries[0].center}")
Returns:

The geometries associated with the Component.

Return type:

List[Geometry]

classmethod get_resource_name(name: str) viam.proto.common.ResourceName

Get the ResourceName for this Resource with the given name

# Can be used with any resource, using an arm as an example
my_arm_name = my_arm.get_resource_name("my_arm")
Parameters:

name (str) – The name of the Resource

Returns:

The ResourceName of this Resource

Return type:

ResourceName

get_operation(kwargs: Mapping[str, Any]) viam.operations.Operation

Get the Operation associated with the currently running function.

When writing custom resources, you should get the Operation by calling this function and check to see if it’s cancelled. If the Operation is cancelled, then you can perform any necessary (terminating long running tasks, cleaning up connections, etc. ).

Parameters:

kwargs (Mapping[str, Any]) – The kwargs object containing the operation

Returns:

The operation associated with this function

Return type:

viam.operations.Operation

async close()

Safely shut down the resource and prevent further use.

Close must be idempotent. Later configuration may allow a resource to be “open” again. If a resource does not want or need a close function, it is assumed that the resource does not need to return errors when future non-Close methods are called.

await component.close()
class viam.components.input.service.Event[source]
time: float

seconds since epoch

event: EventType
control: Control
value: float

0 or 1 for buttons, -1.0 to +1.0 for axes

property proto
classmethod from_proto(proto: viam.proto.component.inputcontroller.Event) typing_extensions.Self[source]
class viam.components.input.service.EventType[source]

Bases: str, enum.Enum

Represents the type of input event.

ALL_EVENTS = 'AllEvents'

Callbacks registered for this event will be called in ADDITION to other registered event callbacks.

CONNECT = 'Connect'

Sent at controller initialization, and on reconnects.

DISCONNECT = 'Disconnect'

If unplugged, or wireless/network times out.

BUTTON_PRESS = 'ButtonPress'

Typical key press.

BUTTON_RELEASE = 'ButtonRelease'

Key release.

BUTTON_HOLD = 'ButtonHold'

Key is held down. This wil likely be a repeated event.

BUTTON_CHANGE = 'ButtonChange'

Both up and down for convenience during registration, not typically emitted.

POSITION_CHANGE_ABSOLUTE = 'PositionChangeAbs'

Absolute position is reported via Value, a la joysticks.

POSITION_CHANGE_RELATIVE = 'PositionChangeRel'

Relative position is reported via Value, a la mice, or simulating axes with up/down buttons.

viam.components.input.service.LOGGER
class viam.components.input.service.InputControllerRPCService(manager: viam.resource.manager.ResourceManager)[source]

Bases: viam.proto.component.inputcontroller.InputControllerServiceBase, viam.resource.rpc_service_base.ResourceRPCServiceBase[viam.components.input.input.Controller]

gRPC Service for an input controller

RESOURCE_TYPE
async GetControls(stream: grpclib.server.Stream[viam.proto.component.inputcontroller.GetControlsRequest, viam.proto.component.inputcontroller.GetControlsResponse]) None[source]
async GetEvents(stream: grpclib.server.Stream[viam.proto.component.inputcontroller.GetEventsRequest, viam.proto.component.inputcontroller.GetEventsResponse]) None[source]
async StreamEvents(stream: grpclib.server.Stream[viam.proto.component.inputcontroller.StreamEventsRequest, viam.proto.component.inputcontroller.StreamEventsResponse]) None[source]
async TriggerEvent(stream: grpclib.server.Stream[viam.proto.component.inputcontroller.TriggerEventRequest, viam.proto.component.inputcontroller.TriggerEventResponse]) None[source]
async DoCommand(stream: grpclib.server.Stream[viam.proto.common.DoCommandRequest, viam.proto.common.DoCommandResponse]) None[source]
async GetGeometries(stream: grpclib.server.Stream[viam.proto.common.GetGeometriesRequest, viam.proto.common.GetGeometriesResponse]) None[source]