ratbag package

Subpackages

Submodules

ratbag.driver module

ratbag.emulator module

ratbag.hid module

ratbag.parser module

A Parser helper function to convert a byte array to a Python object and the other way around. The conversion is specified in a list of Spec instances, for example:

>>> data = bytes(range(16))
>>> spec = [
...     Spec("B", "zero"),
...     Spec("B", "first"),
...     Spec("H", "second", endian="BE"),
...     Spec("H", "third", endian="le"),
...     Spec("BB", "tuples", repeat=5)
... ]
...
>>> result = Parser.to_object(data, spec)
>>> assert result.size == len(data)
>>> assert result.object.zero == 0
>>> assert result.object.first == 0x1
>>> assert result.object.second == 0x0203
>>> assert result.object.third == 0x0504 # little endian
>>> assert result.object.tuples == [(6, 7), (8, 9), (10, 11), (12, 13), (14, 15)]

And likewise, an object can be turned into a bytearray:

>>> new_data = Parser.from_object(result.object, spec)
>>> assert new_data == data

See the Spec documentation for details on the format.

class ratbag.parser.Spec(format, name, endian='BE', repeat=1, greedy=False, convert_from_data=None, convert_to_data=None)

Bases: object

The format specification for a single logical in a data set. This is used in Parser.to_object() or Parser.from_object() to convert from or to a byte stream. For example:

  • Spec("B", "myattr") is a single byte from/to an object’s myattr property

  • Spec("BB", "point") is a tuple of two bytes from/to an object’s myattr property

See Parser.to_object() and Parser.from_object() for details.

class ConverterArg(bytes, value, index)

Bases: object

The argument passed to convert_to_data

bytes: _CountingAttr(counter=74, _default=NOTHING, repr=True, eq=True, order=True, hash=None, init=True, metadata={})
value: Any
index: int
format: str

The format, must be compatible to Python’s struct format specifiers, excluding the endian prefixes. If the format contains more than one element, the respective object attribute is a tuple.

With the exception of fixed-length strings (4s for a 4-byte string) this format must not contain any repeat specifiers. Use the repeat attribute instead. IOW:

>>> Spec("3s", "string")  # One 3-byte string
>>> Spec("s", "string", repeat=3)  # Three 1-byte strings
>>> Spec("3H", "foo")  # Not permitted
name: str

The name to assign to the resulting object attribute.

endian: str

Endianess of the field, one of "BE" or "le".

repeat: int

The number of times this field repeats in struct. Where repeat is greater than 1, the resulting attribute is a list with repeat elements (each element may be tuple, see format).

greedy: bool

If true, repeat is ignored and the current field repeats until the remainder of the available data. This takes the current format spec into account. For example, a HH tuple has 4 bytes and will repeat 5 times in a data size 20.

If the data size is not a multiple of the current format size, the remainder is silently skipped:

>>> spec = Spec("H", "foo", greedy=True)
>>> data = Parser.to_object(bytes(5), spec)
>>> assert data.object.size == 4
convert_from_data: Optional[Callable[[Any], Any]]

Conversion function for the data. An example for converting a sequence of bytes to a string:

>>> spec = Spec("B", "foo", repeat=3, convert_from_data=lambda s: bytes(s).decode("utf-8"))
# Or alternatively use the string length format:
>>> spec = Spec("3s", "foo", convert_from_data=lambda s: s.decode("utf-8"))
>>> data = Parser.to_object("bar".encode("utf-8"), spec)
>>> assert data.object.foo == "bar"

Note that the conversion happens once all repeat have been completed, i.e. the input value for repeat > 1 is a list.

convert_to_data: Optional[Callable[[ConverterArg], Any]]

Conversion function of this attribute to data. This function takes the data bytes produced so far by Parser.from_object() and the current value and index (if applicable). It must return a value compatible to the format specifier. Specifically:

  • if format specifies more than one type, the return value must be a tuple

  • if repeat is greater than 1, the return value must be a list of repeat elements. Note that this function is called once per element the list, with the data argument updated accordingly.

An example for producing a checksum with some_crc():

>>> specs = []  # other fields
>>> checksum_spec("H", "checksum", convert_to_data=lambda bs, v, idx: some_crc(bs))
>>> data = Parser.from_object(myobj, specs + checksum_spec)
>>> assert data[-2:] == some_crc(data[:-2])
class ratbag.parser.Result(object, size)

Bases: object

The return value from Parser.to_object()

object: Any

The object passed to Parser.to_object() or otherwise an unspecified instance with all attribute names as requested by the parser spec.

size: int

The number of bytes used to create this object

class ratbag.parser.Parser

Bases: object

classmethod to_object(data, specs, obj=None, result_class='Result')

Convert the given data into an object according to the specs. If obj is not None, the attributes are set on that object (resetting any attributes of the same name already set on the object). Otherwise, a new generic object is created with all attributes as specified in the parser specs.

The result_class specifies either the type of class to instantiate, or the name of the created class for this object.

>>> specs = [Spec("B", "field")]
>>> r = Parser.to_object(bytes(16), specs, result_class = "Foo")
>>> print(type(r.object).__name__)
Foo
>>> class Bar:
...     def __init__(self, field):
...         pass
>>> r = Parser.to_object(bytes(16), specs, result_class = Bar)
>>> assert isinstance(r.object, Bar)

Where an existing type is used, that type must take all Spec fields as keyword arguments in the constructor, except:

  • Spec names with a single leading underscore are expected to drop that underscore in the constructor.

  • Spec names with a double leading underscore are ignored

Return type

Any

classmethod from_object(obj, specs, pad_to=0)

Convert the attributes on the given objects to a byte array, given the specifications (in-order). This is the inverse of Parser.to_object().

Note that each attribute must exist on the object and have the format compatible by its respective spec. For example, a Spec with

  • a format "BB" must be a tuple of 2 bytes

  • a format "H" with a repeat of 5 must be a list of five 16-bit integers,

  • a format "HB" with a repeat of 3 must be a list of three tuples with a 16-bit integer and byte each

Return type

bytes

ratbag.recorder module

class ratbag.recorder.YamlDeviceRecorder(filename, info)

Bases: Recorder

A simple recorder that logs the data to/from the device as a series of YAML objects. All elements in config are logged as attributes.

The output of this logger can be consumed by ratbag.emulator.YamlDevice.

Example output:

logger: YAMLDeviceRecorder
attributes:
  - { name: name, type: str, value: the device name }
  - { name: path, type: str: value: /dev/hidraw0 }
  - { name: report_descriptor, type: bytes, value: [1, 2, 3] }
data:
  - tx: [ 16, 255,   0,  24,   0,   0,   0]        # 10 ff 00 18 00 00 00
  - rx: [ 17, 255,   0,  24,   4,   2,   0,   0,   # 11 ff 00 18 04 02 00 00
           0,   0,   0,   0,   0,   0,   0,   0,   # 00 00 00 00 00 00 00 00
           0,   0,   0,   0]                       # 00 00 00 00
Parameters

config – a dictionary with attributes to log

info: Dict
last_timestamp: datetime
last_ts_default()
classmethod create_in_blackbox(blackbox, filename, info={})
Return type

YamlDeviceRecorder

start()
Return type

None

log_rx(data)

Log data received from the device

Return type

None

log_tx(data)

Log data sent to the device

Return type

None

log_ioctl_tx(ioctl_name, data)
Return type

None

log_ioctl_rx(ioctl_name, data)
Return type

None

ratbag.util module

ratbag.util.as_hex(bs)

Convert the bytes bs to a "ab 12 cd 34" string.

>>> as_hex(bytes([1, 2, 3]))
'01 02 03'
Return type

str

ratbag.util.ffs(x)
Return type

int

ratbag.util.add_to_sparse_tuple(tpl, index, new_value)

Return a new tuple based on tpl with new_value added at the given index. The tuple is either expanded with None values to match the new size required or the value is replaced.

   >>> t = add_to_sparse_tuple(('a', 'b'), 5, 'f')
   >>> print(t)
   ('a', 'b', None, None, None, 'f')
   >>> t = add_to_sparse_tuple(t, 3, 'd')
   >>> print(t)
   ('a', 'b', None, 'd', None, 'f')

This function does not replace existing values in the tuple. ::

   >>> t = add_to_sparse_tuple(('a', 'b'), 0, 'A')
   Traceback (most recent call last):
       ...
   AssertionError
Return type

Tuple

ratbag.util.find_hidraw_devices()
Return type

List[str]

Returns

a list of local hidraw device paths ["/dev/hidraw0", "/dev/hidraw1"]

class ratbag.util.DataFile(name, matches, driver, driver_options=NOTHING)

Bases: object

name: str
matches: List[str]
driver: str
driver_options: Dict[str, str]
classmethod from_config_parser(parser)
ratbag.util.load_data_files()
Return type

List[DataFile]

Returns

a list of configparser.ConfigParser objects

ratbag.util.to_tuple(x)
Return type

Tuple

ratbag.util.to_sorted_tuple(x)
Return type

Tuple

Module contents

exception ratbag.ConfigError(message)

Bases: Exception

Error indicating that the caller has tried to set the device’s configuration to an unsupported value, format, or feature.

This error is recoverable by re-reading the device’s current state and attempting a different configuration.

message: str

The error message to display

class ratbag.Ratbag(blackbox=None)

Bases: Object

An instance managing one or more ratbag devices. This is the entry point for all ratbag clients. This context loads the data files and instantiates the drivers accordingly.

Example:

r = ratbag.Ratbag()
r.connect("device-added", lambda ratbag, device: print(f"New device: {device}"))
r.start()
GLib.MainLoop().run()

ratbag.Ratbag requires a GLib mainloop.

Parameters
  • config – a dictionary with configuration information

  • load_data_filesTrue if the data files should be loaded. There is rarely a need for setting this to False outside specific test cases.

GObject Signals:

classmethod create_empty(blackbox)

Create an “empty” instance of ratbag that does not load any drivers and thus will not detect devices. The caller is responsible for adding drivers.

This is used for testing only, use Ratbag.create() instead.

Return type

Ratbag

classmethod create(blackbox=None)

Create a new Ratbag instance.

Return type

Ratbag

device_added

GObject signal emitted when a new ratbag.Device was added

add_driver(drivername, supported_devices)

Add the given driver name. This API exists primarily to support testing and niche features, there is rarely a need for calling this function. Drivers are handled automatically for known devices.

Parameters
  • drivername – The string name of the driver to load

  • supported_devices – A list of ratbag.driver.DeviceConfig instances with the devices supported by this driver.

Raises

ratbag.driver.DriverUnavailable

start()

Start the context. Before invoking this function ensure the caller has connected to all the signals.

Return type

None

do_device_added(*args)

GObject signal emitted when a new ratbag.Device was added

do_start(*args)

GObject signal emitted in response to start(). This signal is for internal use.

class ratbag.Blackbox(directory=NOTHING)

Bases: object

The manager class for any recorders active in this session.

The default recordings directory is $XDG_STATE_HOME/ratbag/recordings/$timestamp.

directory: Path
add_recorder(recorder)
make_path(filename)

Return a path for filename that is within this blackbox’ recordings directory.

Return type

Path

classmethod create(directory)
Return type

Blackbox

static default_recordings_directory()
class ratbag.Recorder

Bases: Object

Recorder can be added to a ratbag.Driver to log data between the host and the device, see ratbag.Driver.add_recorder()

Parameters

config – A dictionary with logger-specific data to initialize

log_rx(data)

Log data received from the device

Return type

None

log_tx(data)

Log data sent to the device

Return type

None

class ratbag.CommitTransaction(device)

Bases: Object

A helper object for Device.commit(). This object keeps track of a current commit transaction and emits the finished signal once the driver has completed the transaction.

>>> device = None  # should be a device though...
>>> t = CommitTransaction.create(device)
>>> def on_finished(transaction):
...     print(f"Device {transaction.device} is done")
>>> signal_number = t.connect("finished", on_finished)
>>> t.commit()  

A transaction object can only be used once.

class State(value)

Bases: IntEnum

An enumeration.

NEW = 1
IN_USE = 2
FAILED = 3
SUCCESS = 4
classmethod create(device)
Return type

CommitTransaction

finished

GObject signal sent when the transaction is complete.

property seqno: int

The unique sequence number for this transaction. This can be used to compare transactions.

Return type

int

property used: bool

True if the transaction has been used in Device.commit() (even if the transaction is not yet complete).

Return type

bool

property device: Device

The device assigned to this transaction.

Return type

Device

property success: bool

Returns True on success. This property is False until the transaction is complete.

Return type

bool

property is_finished: bool
Return type

bool

commit()
complete(success)

Complete this transaction with the given success status.

do_finished(*args)

GObject signal sent when the transaction is complete.

class ratbag.Device(driver, path, name, model='', firmware_version='')

Bases: Object

A device as exposed to Ratbag clients. A driver implementation must not expose a ratbag.Device until it is fully setup and ready to be accessed by the client. Usually this means not sending the ratbag.Driver::device-added signal until the device is finalized.

GObject Signals:

  • disconnected: this device has been disconnected

  • commit: commit the current state to the physical device. This signal is used by drivers.

  • resync: callers should re-sync the state of the device

driver: ratbag.driver.Driver
path: str
name: str

The device name as advertised by the kernel

model: str

The device model, a more precise identifier (where available)

firmware_version: str

A device-specific string with the firmware version, or the empty string. For devices with a major/minor or purely numeric firmware version, the conversion into a string is implementation-defined.

classmethod create(driver, path, name, **kwargs)
disconnected

GObject signal emitted when the device was disconnected

resync

GObject signal emitted when the device state has changed and the caller should update its internal state from the device.

This signal carries a single integer that is the CommitTransaction.seqno() for the corresponding transaction.

property profiles: Tuple[Profile, ...]

The tuple of device profiles, in-order sorted by profile index.

Return type

Tuple[Profile, ...]

commit(transaction)

Write the current changes to the driver. This is an asynchronous operation (maybe in a separate thread). Once complete, the given transaction object will emit the finished signal.

You should not call this function directly, use CommitTransaction.commit() instead:

>>> device = None  # should be a device though...
>>> t = CommitTransaction.create(device)
>>> def on_finished(transaction):
...     print(f"Device {transaction.device} is done")
>>> signal_number = t.connect("finished", on_finished)
>>> t.commit()  

The dirty status of the device’s features is reset to False immediately before the callback is invoked but not before the driver handles the state changes. In other words, a caller must not rely on the dirty status between commit() and the callback.

If an error occurs, the driver calls the callback with a False.

If any device state changes in response to commit(), the driver emits a resync signal to notify all other listeners. This signal includes the same sequence number as the transaction to allow for filtering signals.

Returns

a sequence number for this transaction

dirty

True if changes are uncommited. Connect to notify::dirty to receive changes.

as_dict()

Returns this device as a dictionary that can e.g. be printed as YAML or JSON.

Return type

Dict[str, Any]

do_commit(*args)

GObject signal emitted when the device was disconnected. This signal is for internal use only.

Name clash with commit()

do_disconnected(*args)

GObject signal emitted when the device was disconnected

do_get_property(pspec)
do_resync(*args)

GObject signal emitted when the device state has changed and the caller should update its internal state from the device.

This signal carries a single integer that is the CommitTransaction.seqno() for the corresponding transaction.

do_set_property(pspec, value)
class ratbag.Feature(device, index)

Bases: Object

Base class for all device features, including profiles. This is a convenience class only to avoid re-implementation of common properties.

index_validator(attribute, value)
property device: Device
Return type

Device

property index: int

The 0-based device index of this feature. Indices are counted from the parent feature up, i.e. the first resolution of a profile 1 is resolution 0, the first resolution of profile 2 also has an index of 0.

Return type

int

dirty

True if changes are uncommited. Connect to notify::dirty to receive changes.

do_get_property(pspec)
do_set_property(pspec, value)
class ratbag.Profile(device, index, name=NOTHING, report_rate=None, active=False, enabled=True, default=False, capabilities=NOTHING, buttons=NOTHING, resolutions=NOTHING, leds=NOTHING, report_rates=NOTHING)

Bases: Feature

A profile on the device. A device must have at least one profile, the number of available proviles is device-specific.

Only one profile may be active at any time. When the active profile changes, the active signal is emitted for the previously active profile with a boolean false value, then the active signal is emitted on the newly active profile.

class Capability(value)

Bases: IntEnum

Capabilities specific to profiles.

SET_DEFAULT = 101

This profile can be set as the default profile. The default profile is the one used immediately after the device has been plugged in. If this capability is missing, the device typically picks either the last-used profile or the first available profile.

DISABLE = 102

The profile can be disabled and enabled. Profiles are not immediately deleted after being disabled, it is not guaranteed that the device will remember any disabled profiles the next time ratbag runs. Furthermore, the order of profiles may get changed the next time ratbag runs if profiles are disabled.

Note that this capability only notes the general capability. A specific profile may still fail to be disabled, e.g. when it is the last enabled profile on the device.

WRITE_ONLY = 103

The profile information cannot be queried from the hardware. Where this capability is present, libratbag cannot query the device for its current configuration and the configured resolutions and button mappings are unknown. libratbag will still provide information about the structure of the device such as the number of buttons and resolutions. Clients that encounter a device without this resolution are encouraged to upload a configuration stored on-disk to the device to reset the device to a known state.

Any changes uploaded to the device will be cached in libratbag, once a client has sent a full configuration to the device libratbag can be used to query the device as normal.

INDIVIDUAL_REPORT_RATE = 104

The report rate applies per-profile. On devices without this capability changing the report rate on one profile also changes it on all other profiles.

name: str
classmethod create(device, index, **kwargs)
property buttons: Tuple[Button, ...]

The tuple of Button that are available in this profile

Return type

Tuple[Button, ...]

property resolutions: Tuple[Resolution, ...]

The tuple of Resolution that are available in this profile

Return type

Tuple[Resolution, ...]

property leds: Tuple[Led, ...]

The tuple of Led that are available in this profile

Return type

Tuple[Led, ...]

report_rate

The report rate in Hz. If the profile does not support configurable (or queryable) report rates, the report rate is always None

set_report_rate(rate)

Set the report rate for this profile.

Raises

ConfigError

Return type

None

property report_rates: Tuple[int, ...]

The tuple of supported report rates in Hz. If the device does not support configurable report rates, the tuple is the empty tuple

Return type

Tuple[int, ...]

property capabilities: Tuple[Capability, ...]

Return the tuple of supported Profile.Capability

Return type

Tuple[Capability, ...]

enabled

True if this profile is enabled.

set_enabled(enabled)
Return type

None

active

True if this profile is active, False otherwise. Note that only one profile at a time can be active. See set_active().

set_active()

Set this profile to be the active profile.

Return type

None

default

True if this profile is the default profile, False otherwise. Note that only one profile at a time can be the default. See set_default().

set_default()

Set this profile as the default profile.

Raises

ConfigError

Return type

None

as_dict()

Returns this profile as a dictionary that can e.g. be printed as YAML or JSON.

Return type

Dict[str, Any]

do_get_property(pspec)
do_set_property(pspec, value)
class ratbag.Resolution(device, index, profile, dpi, *, active=False, enabled=True, default=False, capabilities=NOTHING, dpi_list=NOTHING)

Bases: Feature

A resolution within a profile. A device must have at least one profile, the number of available proviles is device-specific.

Only one resolution may be active at any time. When the active resolution changes, the notify::active signal is emitted for the previously active resolution with a boolean false value, then the notify::active signal is emitted on the newly active resolution.

class Capability(value)

Bases: IntEnum

Capabilities specific to resolutions.

SEPARATE_XY_RESOLUTION = 1

The device can adjust x and y resolution independently. If this capability is not present, the arguments to set_dpi() must be a tuple of identical values.

classmethod create(profile, index, dpi, **kwargs)
property profile: Profile
Return type

Profile

property capabilities: Tuple[Capability, ...]

Return the tuple of supported Resolution.Capability

Return type

Tuple[Capability, ...]

enabled
set_enabled(enabled)
Return type

None

active

True if this resolution is active, False otherwise. This property should be treated as read-only, use set_active() instead of writing directly.

set_active()

Set this resolution to be the active resolution.

Return type

None

default

True if this resolution is the default resolution, False otherwise. Note that only one resolution at a time can be the default. See set_default().

set_default()

Set this resolution as the default resolution.

Raises

ConfigError

Return type

None

dpi

A tuple of (x, y) resolution values. If this device does not have Resolution.Capability.SEPARATE_XY_RESOLUTION(), the tuple always has two identical values.

set_dpi(new_dpi)

Change the dpi of this device.

Raises

ConfigError

Return type

None

property dpi_list: Tuple[int, ...]

Return a tuple of possible resolution values on this device

Return type

Tuple[int, ...]

as_dict()

Returns this resolution as a dictionary that can e.g. be printed as YAML or JSON.

Return type

Dict[str, Any]

do_get_property(pspec)
do_set_property(pspec, value)
class ratbag.Action(type)

Bases: Object

An “abstract” base class for all actions

class Type(value)

Bases: IntEnum

An enumeration.

NONE = 0
BUTTON = 1
SPECIAL = 2
MACRO = 4
UNKNOWN = 1000
property type: Type
Return type

Type

as_dict()
Return type

Dict[str, Any]

class ratbag.ActionUnknown(type)

Bases: Action

A “none” action to signal the button is disabled and does not send an event when physically presed down.

classmethod create()
Return type

ActionUnknown

class ratbag.ActionNone(type)

Bases: Action

A “none” action to signal the button is disabled and does not send an event when physically presed down.

classmethod create()
Return type

ActionNone

class ratbag.ActionButton(type, button)

Bases: Action

A button action triggered by a button. This is the simplest case of an action where a button triggers… a button event! Note that while Button uses indices starting at zero, button actions start at button 1 (left mouse button).

classmethod create(button)
Return type

ActionButton

property button: int

The 1-indexed mouse button

Return type

int

as_dict()
Return type

Dict[str, Any]

class ratbag.ActionSpecial(type, special)

Bases: Action

A special action triggered by a button. These actions are fixed events supported by devices, see ActionSpecial.Special for the list of known actions.

Note that not all devices support all special actions and buttons on a given device may not support all special events.

class Special(value)

Bases: IntEnum

An enumeration.

UNKNOWN = 1073741824
DOUBLECLICK = 1073741825
WHEEL_LEFT = 1073741826
WHEEL_RIGHT = 1073741827
WHEEL_UP = 1073741828
WHEEL_DOWN = 1073741829
RATCHET_MODE_SWITCH = 1073741830
RESOLUTION_CYCLE_UP = 1073741831
RESOLUTION_CYCLE_DOWN = 1073741832
RESOLUTION_UP = 1073741833
RESOLUTION_DOWN = 1073741834
RESOLUTION_ALTERNATE = 1073741835
RESOLUTION_DEFAULT = 1073741836
PROFILE_CYCLE_UP = 1073741837
PROFILE_CYCLE_DOWN = 1073741838
PROFILE_UP = 1073741839
PROFILE_DOWN = 1073741840
SECOND_MODE = 1073741841
BATTERY_LEVEL = 1073741842
classmethod create(special)
property special: Special
Return type

Special

as_dict()
Return type

Dict[str, Any]

class ratbag.ActionMacro(type, name='Unnamed macro', events=NOTHING)

Bases: Action

A macro assigned to a button. The macro may consist of key presses, releases and timeouts (see ActionMacro.Event), the length of the macro and limitations on what keys can be used are device-specific.

class Event(value)

Bases: IntEnum

An enumeration.

INVALID = -1
NONE = 0
KEY_PRESS = 1
KEY_RELEASE = 2
WAIT_MS = 3
classmethod create(events, name='Unamed macro')
property name: str
Return type

str

property events: List[Tuple[Event, int]]

A list of tuples that describe the sequence of this macro. Each tuple is of type (Macro.Event.KEY_PRESS, 34) or (Macro.Event.WAIT_MS, 500), i.e. the first entry is a Macro.Event enum and the remaining entries are the type-specific values.

The length of each tuple is type-specific, clients must be able to handle tuples with lengths other than 2.

This property is read-only. To change a macro, create a new one with the desired event sequence and assign it to the button.

Return type

List[Tuple[Event, int]]

as_dict()
Return type

Dict[str, Any]

class ratbag.Button(device, index, profile, types=(<Type.BUTTON: 1>, ), action=ActionNone(_type=<Type.NONE: 0>))

Bases: Feature

A physical button on the device as represented in a profile. A button has an Action assigned to it, be that to generate a button click, a special event or even a full sequence of key strokes (Macro).

Note that each Button represents one profile only so the same physical button will have multiple Button instances.

profile

The profile this button belongs to

classmethod create(profile, index, **kwargs)
property types: Tuple[Type, ...]

The list of supported Action.Type for this button

Return type

Tuple[Type, ...]

action

The currently assigned action. This action is guaranteed to be of type Action or one of its subclasses.

set_action(new_action)

Set the action rate for this button.

Raises

ConfigError

Return type

None

as_dict()

Returns this button as a dictionary that can e.g. be printed as YAML or JSON.

Return type

Dict[str, Any]

do_get_property(pspec)
do_set_property(pspec, value)
class ratbag.Led(device, index, profile, color=(0, 0, 0), brightness=0, colordepth=Colordepth.RGB_888, mode=Mode.OFF, modes=(<Mode.OFF: 0>, ), effect_duration=0)

Bases: Feature

class Colordepth(value)

Bases: IntEnum

An enumeration.

MONOCHROME = 0
RGB_888 = 1
RGB_111 = 2
class Mode(value)

Bases: IntEnum

An enumeration.

OFF = 0
ON = 1
CYCLE = 2
BREATHING = 3
classmethod create(profile, index, **kwargs)
do_get_property(pspec)
do_set_property(pspec, value)
color

Return a triplet of (r, g, b) of positive integers. If any color scaling applies because of the device’s ratbag.Led.Colordepth this is not reflected in this value. In other words, the color always matches the last successful call to set_color().

set_color(rgb)

Set the color for this LED. The color provided has to be within the allowed color range, see ratbag.Led.Colordepth. ratbag silently scales and/or clamps to the device’s color depth, it is the caller’s responsibility to set the colors in a non-ambiguous way.

Raises

ConfigError

Return type

None

property colordepth: Colordepth
Return type

Colordepth

brightness
set_brightness(brightness)
Return type

None

effect_duration
set_effect_duration(effect_duration)
Return type

None

mode
set_mode(mode)

Change the mode of this LED. The supplied mode must be one returned by modes().

Return type

None

property modes: Tuple[Mode, ...]

Return a tuple of the available Led.Mode for this LED

Return type

Tuple[Mode, ...]

as_dict()

Returns this resolution as a dictionary that can e.g. be printed as YAML or JSON.

Return type

Dict[str, Any]