Custom Device Schema Guide

If a piece of hardware can be controlled from Python on the server or host machine, you can add RemoteRF support for it by writing a small Python schema wrapper. The server converts your schema into a JSON Interface Description Language (IDL) document, and clients use that IDL to generate a local Python driver automatically without manual client-side code updates.

Overview

RemoteRF separates device support into two layers:

  • Server schema wrapper (~/.config/remoterf/drivers/*.py): Written by the administrator on the server or host machine that physically owns the hardware. It imports the vendor library, opens the physical device in make_device(**kwargs), and marks safe operations with @idl_expose.
  • Client remote driver (generated automatically): When a user reserves the device, the client queries the server’s IDL and generates a local Python class under remoterf.drivers.<device_type> that translates property accesses and method calls into RemoteRF RPCs.

For a new device type, the workflow is:

  1. Verify that the server or host machine can control the hardware locally from Python.
  2. Create a schema file in ~/.config/remoterf/drivers/ on the server or host.
  3. Add one or more matching entries to devices.yml with the same device_type.
  4. Restart serverrf or hostrf so the schema and device inventory are reloaded.
  5. Reserve the device from a client and import the generated driver.

devices.yml vs. Schema: devices.yml declares which physical device instances exist (and their serials/addresses), while the schema defines what that device type can do remotely.

Tip: Check the Approved Schema Registry First On a Global Deployment, custom schemas must match an approved interface specification in the RemoteRF Global schema registry. You can browse and download approved interface JSON specifications into ~/.config/remoterf/drivers/registry/ with:

serverrf schema browse
serverrf schema download <name|hash>

Then place the matching Python <device>_schema.py implementation in ~/.config/remoterf/drivers/ and restart or reload the server.

How the Pipeline Works

When serverrf or hostrf starts, it loads every .py file in the drivers/ directory, registers each @idl_register("<device_type>") class, and calls make_device(**init) for each matching entry in devices.yml. It also introspects the exposed methods to build an IDL JSON description with a schema_hash so clients know when to regenerate their cached wrapper.

Client Code Generated RPC Server Dispatch
sdr.rx_lo Pluto:rx_lo:GET dispatch("get_rx_lo", {})
sdr.rx_lo = 2_400_000_000 Pluto:rx_lo:SET dispatch("set_rx_lo", {"value": 2400000000})
samples = sdr.rx() Pluto:rx:CALL0 dispatch("call_rx", {})
sdr.tx(samples) Pluto:tx:CALL1 dispatch("call_tx", {"value": samples})
dev.capture(4096, channel=1, timeout=2.0) My_device:capture:CALLN dispatch("call_capture", {"count": 4096, "channel": 1, "timeout": 2.0})

The client generator strips get_, set_, and call_ prefixes from your exposed method names: get_rx_lo and set_rx_lo become the readable/writable property sdr.rx_lo, and call_rx becomes the method sdr.rx().

Authoring a Schema

A device is a good fit for a custom schema when it has a Python library or control interface on the host machine, can be opened from stable initialization identifiers (such as serial, device_index, ip, or uri), and uses request/response operations with serializable data.

1. Imports and Registration

Every schema imports DeviceSchema, idl_expose, and idl_register from remoteRF_server.common.idl and registers a lowercase, Python-identifier device_type string that matches devices.yml:

from remoteRF_server.common.idl import DeviceSchema, idl_expose, idl_register


@idl_register("dummy_sdr")
class DummySdrSchema(DeviceSchema):
    device_type = "dummy_sdr"
    client_class = "DummySdr"  # optional; defaults to PascalCase of device_type
    driver_version = "0.0.1"

Avoid opening hardware at import time, since the server imports all schema files on startup. Hardware connections belong inside make_device(**kwargs).

2. Opening the Hardware (make_device)

make_device(**kwargs) is a @staticmethod factory that receives the init dictionary from devices.yml as keyword arguments and returns the live device object (or None if the device cannot be opened, which marks the device offline):

@staticmethod
def make_device(**kwargs):
    return connect_dummy_sdr(
        serial=kwargs["serial"],
        sample_rate=kwargs.get("sample_rate", 1_000_000),
    )

When a device is opened successfully, RemoteRF binds the returned object to self.device on the schema instance.

3. Exposing Operations (@idl_expose)

Decorate client-facing methods with @idl_expose. Methods without @idl_expose remain private to the server.

  • Getters (kind="get"): Expose a readable property. Method name must start with get_.
  • Setters (kind="set"): Expose a writable property accepting one value argument. Method name must start with set_.
  • Calls (kind="call" or bare @idl_expose): Expose a method call accepting zero, one, or multiple named arguments. Method name must start with call_.
@idl_expose(kind="get", doc="Center frequency in Hz.")
def get_frequency(self):
    return self.device.frequency

@idl_expose(kind="set")
def set_frequency(self, value):
    self.device.frequency = int(value)

@idl_expose(kind="call", doc="Capture IQ samples.")
def call_capture(
    self,
    count: int = 4096,
    *,
    channel: int = 0,
    timeout: float = 1.0,
):
    return self.device.capture(
        count=int(count),
        channel=int(channel),
        timeout=float(timeout),
    )

@idl_expose
def call_reset(self):
    """Reset the device state."""
    self.device.reset()
    return 0

Calls & Data Shapes

RemoteRF inspects the Python signature of every exposed call_* method and publishes parameter names, required/optional flags, defaults, and keyword-only markers in the IDL.

@idl_expose(kind="call", doc="Configure one receive channel.")
def call_configure(
    self,
    frequency: float,
    gain: float = 0.0,
    options: dict = None,
    *,
    channel: int = 0,
):
    options = {} if options is None else dict(options)
    return self.device.configure(
        frequency=float(frequency),
        gain=float(gain),
        options=options,
        channel=int(channel),
    )

Clients can then call dev.configure(915e6), dev.configure(915e6, gain=12.5), or pass keyword-only arguments like channel=1.

Signature Rules

Feature Supported Notes
Required named arguments Yes Standard positional-or-keyword parameters (e.g., frequency).
Optional defaults Yes Defaults must be JSON-serializable (numbers, booleans, strings, None, lists, dicts).
Keyword-only arguments Yes Place * before keyword-only parameters in the method signature.
Positional-only (/), *args, **kwargs No Every exposed parameter must have an explicit name in the IDL.
Reserved parameter names Avoid Do not name parameters a, g, token, device_id, or device_name.

Supported Return & Argument Types

Exposed methods can accept and return:

  • Scalars (int, float, bool, str, complex, NumPy scalars) and None
  • Real or complex NumPy ndarray buffers (excluding object-dtype arrays)
  • Dictionaries, lists, and tuples (including nested combinations of scalars and NumPy arrays)
@idl_expose(kind="call")
def call_measure(self, count: int, *, include_spectrum: bool = False):
    samples = self.device.capture(int(count))
    result = {
        "samples": samples,
        "peak": float(abs(samples).max()),
        "metadata": {"count": int(samples.size), "channel": 0},
    }
    if include_spectrum:
        result["spectrum"] = np.fft.fft(samples)
    return result

Do not return live vendor objects, sockets, file handles, or iterators directly. Convert results into serializable structures or use Client Object Adapters for handle-backed proxies.

Wrapper Template

Save custom schema files in ~/.config/remoterf/drivers/ on the server or host using any .py filename that does not start with _:

# ~/.config/remoterf/drivers/my_device_schema.py
from remoteRF_server.common.idl import DeviceSchema, idl_expose, idl_register


def connect_my_device(*, serial=None, address=None):
    """Open the physical device and return the vendor device object."""
    try:
        # return vendor_device_api.open(serial=serial, address=address)
        raise NotImplementedError("replace with real connection code")
    except Exception as exc:
        print(f"Failed to open my_device: {exc}")
        return None


@idl_register("my_device")
class MyDeviceSchema(DeviceSchema):
    device_type = "my_device"
    client_class = "MyDevice"
    driver_version = "0.1.0"

    @staticmethod
    def make_device(**kwargs):
        return connect_my_device(
            serial=kwargs.get("serial"),
            address=kwargs.get("address"),
        )

    @idl_expose(kind="get", doc="Center frequency in Hz.")
    def get_frequency(self):
        return self.device.frequency

    @idl_expose(kind="set")
    def set_frequency(self, value):
        self.device.frequency = int(value)

    @idl_expose(kind="call", doc="Capture samples from one channel.")
    def call_capture(
        self,
        count: int = 4096,
        *,
        channel: int = 0,
        timeout: float = 1.0,
    ):
        return self.device.capture(
            count=int(count),
            channel=int(channel),
            timeout=float(timeout),
        )

    @idl_expose
    def call_reset(self):
        self.device.reset()
        return 0

Register the physical device instance in ~/.config/remoterf/devices.yml:

devices:
  - device_id: 42
    device_type: my_device
    name: Custom Device 1
    init:
      serial: "abc123"
      address: "192.168.1.80"

Testing & Validation

1. Validate IDL Generation Offline

Before restarting the server, verify that your schema registers cleanly and produces valid IDL JSON:

cd ~/.config/remoterf/drivers
python - <<'PY'
from my_device_schema import MyDeviceSchema

schema = MyDeviceSchema()
print(schema.list_exposed())
print(schema.get_idl_json(pretty=True))
PY

get_idl_json() immediately catches unsupported call signatures, non-serializable defaults, or invalid method prefixes.

2. Test Local Hardware Dispatch

Next, test opening and dispatching against the physical hardware directly on the server/host:

from my_device_schema import MyDeviceSchema

schema = MyDeviceSchema()
device = schema.make_device(serial="abc123", address="192.168.1.80")
if device is None:
    raise RuntimeError("device did not open")

schema.bind(device)
samples = schema.dispatch("call_capture", {"count": 16, "channel": 0, "timeout": 1.0})
print(type(samples), getattr(samples, "shape", None))

3. Use the Generated Client Driver

Restart serverrf or hostrf, reserve the device from a client, and use ensure_driver (or let the reservation flow generate the driver automatically):

from remoterf.drivers import ensure_driver

TOKEN = "My_Device_00@mylab"
ensure_driver(token=TOKEN)

from remoterf.drivers.my_device import MyDevice

dev = MyDevice(TOKEN)
dev.frequency = 915e6
samples = dev.capture(8192, channel=1, timeout=2.0)

Checklist

Before restarting serverrf or hostrf, verify:

  • File placement: The schema file is in ~/.config/remoterf/drivers/, ends in .py, and does not start with _.
  • Matching device_type: @idl_register("..."), device_type = "...", and device_type: in devices.yml all use the exact same lowercase identifier.
  • Factory method: make_device(**kwargs) is defined with that exact name and returns the device object or None.
  • Method prefixes: Exposed methods start with get_, set_, or call_, and setters take a single value argument.
  • Clean signatures: Exposed calls use explicit parameter names and JSON-serializable defaults (no *args, **kwargs, or / positional-only markers).

Client Object Adapters

Most custom devices only need getters, setters, and calls. For libraries whose local Python API relies on helper classes, enums, or stateful streamer proxies (such as UHD/USRP with uhd.types.TimeSpec, uhd.usrp.StreamArgs, and uhd.RXStreamer), schemas can declare client_objects metadata using idl_client:

from remoteRF_server.common.idl import (
    DeviceSchema,
    idl_client as c,
    idl_expose,
    idl_register,
)

client_objects does not send live Python objects or arbitrary code over the network. Instead, it instructs the client generator to emit compatibility classes from pre-validated templates that serialize to JSON-safe payloads or wrap server-side handles.

Declaration Purpose
c.module(members, exports=None, bind_client_class_to=None) Defines a root generated module namespace (e.g., uhd) and optionally binds the generated device class into a submodule (e.g., uhd.usrp.MultiUSRP).
c.namespace(members) Defines a nested namespace (e.g., uhd.types, uhd.usrp).
c.payload_class(payload_type, fields, init=None, methods=None, operators=None) Declares a client-side value class (such as TimeSpec or StreamArgs) that serializes to a dictionary via as_payload() when passed as an RPC argument.
c.strict_class(fields, defaults=None, init=None, methods=None) Declares a slotted client-side state object (such as RXMetadata or TXMetadata).
c.proxy_class(fields, init=None, methods=None) Declares a client-side proxy object (such as RXStreamer or TXStreamer) that holds a server-side handle and forwards calls back to the device.
c.enum(values) Declares symbolic enum values (such as StreamMode).
c.function(template, **options) / c.method(template, **options) Attaches a built-in generator template for helper functions and methods.
client_return=c.ctor(target, *args) Option on @idl_expose(...) that wraps a method's decoded RPC result in a generated client constructor (using "$result", "$self", or {"const": value}).

Example: Returning a Wrapped Value or Proxy

When an exposed method sets client_return=c.ctor(...), the server returns a JSON-safe payload or handle dictionary and the generated client constructs the helper object automatically:

@idl_expose(
    kind="call",
    client_return=c.ctor("uhd.types.TimeSpec", "$result"),
)
def call_get_time_now(self):
    return {
        "__uhd_type__": "TimeSpec",
        "secs": self.device.get_time_now().get_real_secs(),
    }


@idl_expose(
    kind="call",
    client_return=c.ctor("uhd.RXStreamer", "$self", "$result"),
)
def call_get_rx_stream(self, stream_args):
    real_stream_args = construct_uhd_object(stream_args)
    real_streamer = self.device.get_rx_stream(real_stream_args)
    return self.put_streamer("rx", real_streamer)

Note: Built-in init, method, function, and operator template names (timespec, stream_args, stream_cmd, rx_metadata, tx_metadata, streamer_handle, etc.) are validated against a fixed allowlist in the client generator and are primarily designed for UHD/USRP compatibility. For standard custom hardware, use @idl_expose getters, setters, and multi-argument calls with dictionaries and NumPy arrays.