Skip to content

core — API Reference

The core package is the cortex runtime plus shared infrastructure. No hardware dependencies — importable on any machine (hardware libs load lazily).

sensor_base

core.sensor_base.SensorBase(sensor_id, config)

Bases: ABC

Abstract base class for all sensor plugins.

Subclasses implement the hardware-specific start/stop/read loop. Broadcasting to HTTP clients is handled here via Broadcaster — subclasses call self._broadcast(reading) after each successful reading.

Source code in core/sensor_base.py
def __init__(self, sensor_id: str, config: SensorConfig) -> None:
    self.id = sensor_id
    self.config = config
    self._broadcaster = Broadcaster()
    self._frames = FrameBroadcaster()
    self._latest: SensorReading | None = None

latest abstractmethod property

Most recent reading, or None if no reading has been taken yet.

is_healthy() abstractmethod

True if the sensor is connected and producing readings.

Source code in core/sensor_base.py
@abstractmethod
def is_healthy(self) -> bool:
    """True if the sensor is connected and producing readings."""

start() abstractmethod

Open hardware connection and start the background reading thread.

Source code in core/sensor_base.py
@abstractmethod
def start(self) -> None:
    """Open hardware connection and start the background reading thread."""

stop() abstractmethod

Signal the reading thread to stop and release hardware resources.

Source code in core/sensor_base.py
@abstractmethod
def stop(self) -> None:
    """Signal the reading thread to stop and release hardware resources."""

subscribe()

Register a new subscriber. Returns a queue that receives JSON payloads.

Source code in core/sensor_base.py
def subscribe(self) -> queue.Queue[str]:
    """Register a new subscriber. Returns a queue that receives JSON payloads."""
    return self._broadcaster.subscribe()

subscribe_frames()

Register a subscriber for the binary frame stream.

Source code in core/sensor_base.py
def subscribe_frames(self) -> queue.Queue[bytes]:
    """Register a subscriber for the binary frame stream."""
    return self._frames.subscribe()

analog_array

core.analog_array.AnalogArrayBase(sensor_id, config)

Bases: SensorBase

Base for device-fed analog array sensors. Subclasses set sensor_type and may override enrich().

Source code in core/analog_array.py
def __init__(self, sensor_id, config) -> None:
    super().__init__(sensor_id, config)
    self._devices: dict[str, "Device"] = {}
    self._samples: dict[str, tuple[int, ...]] = {}   # device id → latest samples
    self._lock = threading.Lock()

device_ids property

Device ids referenced by this sensor's channels.

enrich(data, raw)

Add calibrated/derived values to data. Default: raw only.

Source code in core/analog_array.py
def enrich(self, data: dict, raw: dict[str, int]) -> None:
    """Add calibrated/derived values to `data`. Default: raw only."""

ingest(device_id, frame)

Record a device's latest samples, compose + broadcast a reading.

Called from the device read thread (and directly in tests). Returns the composed reading.

Source code in core/analog_array.py
def ingest(self, device_id: str, frame: "Frame") -> SensorReading:
    """Record a device's latest samples, compose + broadcast a reading.

    Called from the device read thread (and directly in tests). Returns the
    composed reading.
    """
    with self._lock:
        self._samples[device_id] = frame.samples
    reading = self._compose(frame.seq)
    self._broadcast(reading)
    return reading

device

The base class, registry, and factory for devices. Concrete kinds (McuSerialDevice, Ads1115Device, SaraR5Device, Si5351Device) live in the devices/ plugin tree, auto-discovered like sensors.

core.device.Device(device_id, config)

Bases: ABC

Base class for shared peripherals.

Subclasses decorate with @register_device("kind") and implement the lifecycle. Push devices (e.g. an MCU link, a modem's NMEA stream) fan decoded data to subscribe*() callbacks; pull devices (e.g. an ADS1115) expose a read method. Either way the device owns the transport — sensors and effectors bind to it by id and never open the port themselves.

Source code in core/device.py
def __init__(self, device_id: str, config: "DeviceConfig") -> None:
    self.id = device_id
    self.config = config

core.device.create_device(config)

Instantiate a device from its config. Raises ValueError for unknown kinds.

The kind must be registered, which happens when its package under devices/ is imported. If a kind is missing, check that import devices ran and the package's hardware deps are installed (failed imports are skipped, not fatal).

Source code in core/device.py
def create_device(config: "DeviceConfig") -> "Device":
    """Instantiate a device from its config. Raises ValueError for unknown kinds.

    The kind must be registered, which happens when its package under `devices/`
    is imported. If a kind is missing, check that `import devices` ran and the
    package's hardware deps are installed (failed imports are skipped, not fatal).
    """
    cls = _registry.get(config.kind)
    if cls is None:
        raise ValueError(
            f"Unknown device kind '{config.kind}'. Known: {sorted(_registry)}. "
            f"Is the device package present on this board?"
        )
    return cls(config.id, config)

devices.mcu_serial

devices.mcu_serial.device.McuSerialDevice(device_id, config)

Bases: Device

An MCU on a serial link: streams sample frames in, takes command frames out.

Source code in devices/mcu_serial/device.py
def __init__(self, device_id: str, config: "DeviceConfig") -> None:
    super().__init__(device_id, config)
    self._subscribers: list[Callable[[Frame], None]] = []
    self._ser = None
    self._write_lock = threading.Lock()
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False

send_command(cmd_id, args=())

Send a command frame to the MCU. Returns False if the link is down.

Source code in devices/mcu_serial/device.py
def send_command(self, cmd_id: int, args=()) -> bool:
    """Send a command frame to the MCU. Returns False if the link is down."""
    ser = self._ser
    if ser is None:
        return False
    payload = encode_command(cmd_id, list(args))
    with self._write_lock:
        try:
            ser.write(payload)
            return True
        except OSError as exc:              # pyserial SerialException is an OSError
            log.warning("device %s: command write failed — %s", self.id, exc)
            return False

subscribe(callback)

Register a callback invoked (in the read thread) for every decoded frame.

Source code in devices/mcu_serial/device.py
def subscribe(self, callback: Callable[[Frame], None]) -> None:
    """Register a callback invoked (in the read thread) for every decoded frame."""
    self._subscribers.append(callback)

devices.ads1115

devices.ads1115.device.Ads1115Device(device_id, config)

Bases: Device

An ADS1115 ADC chip on the SBC's I2C bus (pull model).

Source code in devices/ads1115/device.py
def __init__(self, device_id: str, config: "DeviceConfig") -> None:
    super().__init__(device_id, config)
    self._bus_no = config.bus if config.bus is not None else 1
    self._addr = config.address if config.address is not None else 0x48
    rate = int((config.params or {}).get("data_rate", 128))
    if rate not in self.DATA_RATES:
        raise ValueError(
            f"ads1115 data_rate {rate} not supported (one of {sorted(self.DATA_RATES)})")
    self._rate = rate
    # config: OS=1 | MUX(AIN_n single-ended) | PGA(gain) | MODE single-shot |
    #         DR=data_rate | comparator disabled
    self._base = 0x8000 | 0x0100 | (self.DATA_RATES[rate] << 5) | 0b00011
    # conversion time + 15% margin (e.g. ~9 ms at 128 SPS, ~144 ms at 8 SPS)
    self._wait_s = 1.15 / rate
    self._bus = None
    self._lock = threading.Lock()

read_channel(channel, gain=1)

Single-shot read of single-ended AINx. Returns signed counts, or None.

Source code in devices/ads1115/device.py
def read_channel(self, channel: int, gain: int = 1) -> int | None:
    """Single-shot read of single-ended AINx. Returns signed counts, or None."""
    if self._bus is None or not 0 <= channel <= 3:
        return None
    config = self._base | ((0b100 | channel) << 12) | ((gain & 0b111) << 9)
    with self._lock:
        try:
            self._bus.write_i2c_block_data(
                self._addr, self._CONFIG, [(config >> 8) & 0xFF, config & 0xFF]
            )
            time.sleep(self._wait_s)       # one conversion at the configured rate
            hi, lo = self._bus.read_i2c_block_data(self._addr, self._CONV, 2)
        except OSError as exc:
            log.warning("device %s: ADS1115 read failed — %s", self.id, exc)
            return None
    raw = (hi << 8) | lo
    return raw - 0x10000 if raw & 0x8000 else raw

devices.sara_r5

devices.sara_r5.device.SaraR5Device(device_id, config)

Bases: Device

u-blox SARA-R5 modem over UART.

DeviceConfig fields

port — UART device path, e.g. /dev/ttyS5 baud — baud rate (default 115200) params: power_line — core.gpio spec for the LTE power-enable pin (optional) reset_line — core.gpio spec for the reset pin (optional) init — list of AT commands sent on connect (default enables GNSS) power_on_delay_s / reset_settle_s — timing overrides (optional)

Source code in devices/sara_r5/device.py
def __init__(self, device_id: str, config: "DeviceConfig") -> None:
    super().__init__(device_id, config)
    params = config.params or {}
    self._init_cmds: list[str] = list(params.get("init", _DEFAULT_INIT))
    self._power_on_delay = float(params.get("power_on_delay_s", 1.0))
    self._reset_settle = float(params.get("reset_settle_s", 3.0))

    # Pin control is backend-agnostic (libgpiod / mcu / null) — see core.gpio.
    self._power_line = make_output_line(params.get("power_line"))
    self._reset_line = make_output_line(params.get("reset_line"))

    self._gnss_subs: list[Callable[[str], None]] = []
    self._stop = threading.Event()
    self._thread: threading.Thread | None = None
    self._healthy = False

    # AT engine — one command outstanding at a time.
    self._at_lock = threading.Lock()
    self._at_buf: list[str] = []
    self._at_ready = threading.Event()
    self._ser = None
    self._write_lock = threading.Lock()

reset_modem()

Pulse the reset line low→high and wait for the modem to boot.

Source code in devices/sara_r5/device.py
def reset_modem(self) -> None:
    """Pulse the reset line low→high and wait for the modem to boot."""
    log.info("device %s: pulsing reset", self.id)
    self._reset_line.set(False)
    self._stop.wait(0.1)
    self._reset_line.set(True)
    self._stop.wait(self._reset_settle)

send_at(cmd, timeout=5.0)

Send an AT command; return the response lines (excluding the final OK/ERROR terminator). Thread-safe. Returns [] on timeout or a down link.

Source code in devices/sara_r5/device.py
def send_at(self, cmd: str, timeout: float = 5.0) -> list[str]:
    """Send an AT command; return the response lines (excluding the final
    OK/ERROR terminator). Thread-safe. Returns [] on timeout or a down link."""
    with self._at_lock:
        self._at_buf = []
        self._at_ready.clear()
        with self._write_lock:
            ser = self._ser
            if ser is None:
                return []
            try:
                ser.write(f"{cmd}\r\n".encode())
            except OSError as exc:
                log.warning("device %s: AT write failed — %s", self.id, exc)
                return []
        if not self._at_ready.wait(timeout):
            log.warning("device %s: AT timeout for %r", self.id, cmd)
            return []
        return [
            ln for ln in self._at_buf
            if ln not in _AT_TERMINATORS
            and not ln.startswith(_AT_ERROR_PREFIXES)
        ]

subscribe_gnss(callback)

Register a callback invoked (in the read thread) for each NMEA sentence.

Source code in devices/sara_r5/device.py
def subscribe_gnss(self, callback: Callable[[str], None]) -> None:
    """Register a callback invoked (in the read thread) for each NMEA sentence."""
    self._gnss_subs.append(callback)

devices.si5351

devices.si5351.device.Si5351Device(device_id, config)

Bases: Device

Si5351A on I2C: program CLK0–CLK2 from params.clk_hz, then health-check.

Source code in devices/si5351/device.py
def __init__(self, device_id: str, config: "DeviceConfig") -> None:
    super().__init__(device_id, config)
    self._bus_no = config.bus if config.bus is not None else 1
    self._addr = config.address if config.address is not None else 0x60
    params = config.params or {}
    self._outputs = {
        i: int(params[f"clk{i}_hz"])
        for i in _REG_MS if f"clk{i}_hz" in params
    }
    if not self._outputs:
        self._outputs = {0: 12_288_000}    # historical default: 256 × 48 kHz on CLK0
    self._bus = None
    self._configured = False

devices.si5351.device.plan_clock(target_hz, xtal_hz=_XTAL_HZ)

Choose (fb_int, fb_num, fb_denom, out_div) for one output frequency.

out_div is the smallest even integer divider that puts the PLL in range; the feedback fraction then hits the PLL exactly enough for audio use (error < 1 Hz at 12.288 MHz). Raises ValueError when out of range.

Source code in devices/si5351/device.py
def plan_clock(target_hz: int, xtal_hz: int = _XTAL_HZ) -> tuple[int, int, int, int]:
    """Choose (fb_int, fb_num, fb_denom, out_div) for one output frequency.

    out_div is the smallest even integer divider that puts the PLL in range;
    the feedback fraction then hits the PLL exactly enough for audio use
    (error < 1 Hz at 12.288 MHz). Raises ValueError when out of range.
    """
    if target_hz <= 0:
        raise ValueError("target_hz must be positive")
    out_div = max(4, -(-_PLL_MIN // target_hz))          # ceil, then round up to even
    if out_div % 2:
        out_div += 1
    pll_hz = target_hz * out_div
    if not _PLL_MIN <= pll_hz <= _PLL_MAX:
        raise ValueError(f"no even divider puts {target_hz} Hz in PLL range (got {pll_hz})")
    fb = pll_hz / xtal_hz
    fb_int = int(fb)
    fb_num = round((fb - fb_int) * _DENOM)
    if not 15 <= fb_int <= 90:
        raise ValueError(f"feedback ratio {fb:.3f} outside Si5351 range")
    return fb_int, fb_num, _DENOM, out_div

gpio

Portable digital output lines for devices that toggle SBC/MCU pins (libgpiod / mcu / null backends), so a device never hard-codes how a pin is driven.

core.gpio.make_output_line(spec, devices=None)

Build an OutputLine from a spec dict.

Returns a NullOutputLine (never raises) when no pin is configured or the backend can't be opened — failures are logged. backend defaults to libgpiod; none/null force a no-op; mcu drives a pin through a device's command sink and needs the devices registry passed in.

Source code in core/gpio.py
def make_output_line(spec: dict[str, Any] | None,
                     devices: dict[str, Any] | None = None) -> OutputLine:
    """Build an `OutputLine` from a spec dict.

    Returns a `NullOutputLine` (never raises) when no pin is configured or the
    backend can't be opened — failures are logged. `backend` defaults to
    `libgpiod`; `none`/`null` force a no-op; `mcu` drives a pin through a
    device's command sink and needs the `devices` registry passed in.
    """
    if not spec:
        return NullOutputLine("no spec")

    backend = spec.get("backend", "libgpiod")

    if backend in ("none", "null"):
        return NullOutputLine("backend=none")

    if backend == "libgpiod":
        try:
            return LibgpiodOutputLine(
                chip=str(spec["chip"]),
                line=int(spec["line"]),
                active_low=bool(spec.get("active_low", False)),
            )
        except KeyError as exc:
            log.warning("gpio: libgpiod spec missing %s — %s", exc, spec)
            return NullOutputLine(f"missing key {exc}")
        except Exception as exc:                            # no gpiod, bad chip/line, busy
            log.warning("gpio: libgpiod line unavailable (%s) — %s", exc, spec)
            return NullOutputLine(f"libgpiod error: {exc}")

    if backend == "mcu":
        dev_id = spec.get("device")
        device = (devices or {}).get(dev_id)
        if device is None:
            log.warning("gpio: mcu backend device %r not available — %s", dev_id, spec)
            return NullOutputLine(f"mcu device {dev_id!r} unavailable")
        return McuOutputLine(
            device=device,
            channel=int(spec.get("channel", 0)),
            active_low=bool(spec.get("active_low", False)),
        )

    log.warning("gpio: unknown backend %r — %s", backend, spec)
    return NullOutputLine(f"unknown backend {backend}")

core.gpio.OutputLine

Bases: ABC

A single digital output a device can drive high/low.

close()

Release the line. Default no-op; backends override as needed.

Source code in core/gpio.py
def close(self) -> None:
    """Release the line. Default no-op; backends override as needed."""

set(value) abstractmethod

Drive the line; True = active (respecting active_low).

Source code in core/gpio.py
@abstractmethod
def set(self, value: bool) -> None:
    """Drive the line; True = active (respecting active_low)."""

effector_base

The base class and registry for effectors. Full API — including concrete plugin types (PwmEffector, FanArray, StreamSink) — is on the effectors reference page.

core.effector_base.create_effector(config)

Source code in core/effector_base.py
def create_effector(config: "EffectorConfig") -> "EffectorBase":
    cls = _registry.get(config.type)
    if cls is None:
        raise ValueError(
            f"Unknown effector type '{config.type}'. Known: {sorted(_registry)}."
        )
    return cls(config.id, config)

policy

The base class, PolicyRuntime, and registry for policies. Full API — including concrete plugin types (CurvePolicy) — is on the policies reference page.

core.policy.create_policy(config)

Source code in core/policy.py
def create_policy(config: "PolicyConfig") -> "PolicyBase":
    cls = _registry.get(config.type)
    if cls is None:
        raise ValueError(
            f"Unknown policy type '{config.type}'. Known: {sorted(_registry)}."
        )
    return cls(config.id, config)

relay

core.relay.Relay(gate=None)

Latest-value pub/sub keyed by dotted signal name, with an optional gate.

Source code in core/relay.py
def __init__(self, gate: Callable[[str, Any], Any] | None = None) -> None:
    # gate(name, value) -> value to store, or None to drop (attention/gating).
    self._gate = gate
    self._values: dict[str, Any] = {}
    self._lock = threading.Lock()

publish_tree(prefix, data)

Flatten a nested reading dict into dotted signal names and publish each.

Source code in core/relay.py
def publish_tree(self, prefix: str, data: dict) -> None:
    """Flatten a nested reading dict into dotted signal names and publish each."""
    for key, value in data.items():
        name = f"{prefix}.{key}"
        if isinstance(value, dict):
            self.publish_tree(name, value)
        else:
            self.publish(name, value)

core.mcu_link.encode(samples, seq=0)

Serialize one frame of int16 samples. Raises ValueError on >255 channels.

Source code in core/mcu_link.py
def encode(samples: Sequence[int], seq: int = 0) -> bytes:
    """Serialize one frame of int16 samples. Raises ValueError on >255 channels."""
    count = len(samples)
    if count > MAX_CHANNELS:
        raise ValueError(f"too many channels: {count} (max {MAX_CHANNELS})")
    body = _HEADER.pack(MAGIC, VERSION, seq & 0xFF, count)
    body += struct.pack(f"<{count}h", *samples)
    return body + bytes([sum(body) & 0xFF])

core.mcu_link.decode(frame)

Decode one complete frame.

Returns None if the bytes are not exactly one well-formed frame (bad magic, unknown version, wrong length, or checksum mismatch).

Source code in core/mcu_link.py
def decode(frame: bytes) -> Frame | None:
    """Decode one complete frame.

    Returns None if the bytes are not exactly one well-formed frame (bad magic,
    unknown version, wrong length, or checksum mismatch).
    """
    if len(frame) < _MIN_FRAME:
        return None
    magic, version, seq, count = _HEADER.unpack_from(frame, 0)
    if magic != MAGIC or version != VERSION:
        return None
    if len(frame) != frame_size(count):
        return None
    if (sum(frame[:-1]) & 0xFF) != frame[-1]:
        return None
    samples = struct.unpack_from(f"<{count}h", frame, _HEADER.size)
    return Frame(seq=seq, samples=samples)

core.mcu_link.FrameStream(max_buffer=4096)

Stateful, resyncing decoder for a raw serial byte stream.

Feed it whatever bytes arrive; it returns complete, checksum-valid frames and keeps partial data buffered, resyncing on the magic marker after garbage or a corrupt frame. This is what the node-side read loop uses (the MCU emits a continuous stream with no external framing).

Source code in core/mcu_link.py
def __init__(self, max_buffer: int = 4096) -> None:
    self._buf = bytearray()
    self._max = max_buffer

feed(data)

Append bytes and return every complete frame now available.

Source code in core/mcu_link.py
def feed(self, data: bytes) -> list[Frame]:
    """Append bytes and return every complete frame now available."""
    self._buf.extend(data)
    out: list[Frame] = []
    while self._extract(out):
        pass
    # Bound the buffer if we never sync (e.g. wrong baud → endless garbage).
    if len(self._buf) > self._max:
        del self._buf[: len(self._buf) - self._max]
    return out

core.mcu_link.encode_command(cmd_id, args=())

Serialize a command frame (e.g. encode_command(CMD_SET_DUTY, [ch, duty])).

Source code in core/mcu_link.py
def encode_command(cmd_id: int, args: Sequence[int] = ()) -> bytes:
    """Serialize a command frame (e.g. encode_command(CMD_SET_DUTY, [ch, duty]))."""
    n = len(args)
    if n > MAX_CHANNELS:
        raise ValueError(f"too many args: {n} (max {MAX_CHANNELS})")
    body = _CMD_HEADER.pack(CMD_MAGIC, CMD_VERSION, cmd_id & 0xFF, n)
    body += struct.pack(f"<{n}h", *args)
    return body + bytes([sum(body) & 0xFF])

core.mcu_link.decode_command(frame)

Decode one complete command frame, or None if malformed.

Source code in core/mcu_link.py
def decode_command(frame: bytes) -> Command | None:
    """Decode one complete command frame, or None if malformed."""
    if len(frame) < _CMD_HEADER.size + 1:
        return None
    magic, version, cmd_id, n = _CMD_HEADER.unpack_from(frame, 0)
    if magic != CMD_MAGIC or version != CMD_VERSION:
        return None
    if len(frame) != _CMD_HEADER.size + 2 * n + 1:
        return None
    if (sum(frame[:-1]) & 0xFF) != frame[-1]:
        return None
    return Command(cmd_id, struct.unpack_from(f"<{n}h", frame, _CMD_HEADER.size))

broadcaster

core.broadcaster.Broadcaster(maxsize=10)

Queue-per-subscriber pub/sub utility.

Replaces the _clients / _clients_lock pattern duplicated across all sensor servers. SSE and WebSocket route handlers subscribe a queue when a client connects; the sensor's background thread calls broadcast() after each reading. Stale queues from disconnected clients are pruned automatically.

Source code in core/broadcaster.py
def __init__(self, maxsize: int = 10) -> None:
    self._clients: list[queue.Queue[str]] = []
    self._lock = threading.Lock()
    self._maxsize = maxsize

registry

core.registry.register(sensor_type)

Class decorator that registers a SensorBase subclass under a type key.

Usage

@register("tf_mini") class TFminiSensor(SensorBase): ...

The key must match the type field used in config.yaml sensor entries.

Source code in core/registry.py
def register(sensor_type: str):
    """
    Class decorator that registers a SensorBase subclass under a type key.

    Usage:
        @register("tf_mini")
        class TFminiSensor(SensorBase):
            ...

    The key must match the `type` field used in config.yaml sensor entries.
    """
    def decorator(cls: type["SensorBase"]) -> type["SensorBase"]:
        _registry[sensor_type] = cls
        return cls
    return decorator

core.registry.create(config)

Instantiate a sensor from its config. Raises ValueError for unknown types.

Source code in core/registry.py
def create(config: "SensorConfig") -> "SensorBase":
    """Instantiate a sensor from its config. Raises ValueError for unknown types."""
    cls = _registry.get(config.type)
    if cls is None:
        known = sorted(_registry)
        raise ValueError(
            f"Unknown sensor type '{config.type}'. "
            f"Known types: {known}. "
            f"Is the sensor package present on this board?"
        )
    return cls(config.id, config)

core.registry.registered_types()

Return all currently registered sensor type keys.

Source code in core/registry.py
def registered_types() -> list[str]:
    """Return all currently registered sensor type keys."""
    return sorted(_registry)

models

core.models.SensorReading

Bases: BaseModel

Standardized reading emitted by every sensor.

Standardized data keys per sensor type

tf_mini, lv_maxsonar, vl53l1x: distance_mm: int strength: int | None temp_c: float | None mlx90640: pixels: list[float] (768 values, row-major 32×24) min_temp: float max_temp: float width: int (32) height: int (24) ir_xcvr: protocol : str — "NEC" | "NECX" | "NEC32" | "RC5" | … | "PROTO_N" address : int — decoded device address command : int — decoded command byte scancode : int — raw kernel scancode (address << 8 | command for NEC) repeat : bool — True when this is a held-key repeat frame

to_sse()

Format as an SSE data frame.

Source code in core/models.py
def to_sse(self) -> str:
    """Format as an SSE data frame."""
    return f"data: {self.model_dump_json()}\n\n"

core.models.SensorConfig

Bases: BaseModel

Configuration for a single sensor instance on this node.

core.models.ConnectionConfig

Bases: BaseModel

Hardware connection parameters for a sensor.

core.models.SensorChannel

Bases: BaseModel

One channel of an array sensor — its source, meaning, and calibration.

Array sensors read a flat vector of raw values from one or more devices. device is the device id this channel comes from (a logical sensor may span several — e.g. cranial pressure across 4 MCUs); index is the position within that device's frame; signal is the node-side name; calibration is applied in Python. Authored consistently with the MCU's config/mcus/.yaml.

core.models.DeviceConfig

Bases: BaseModel

A shared peripheral on this node — an MCU link, an ADS1115 chip, etc.

A device owns its transport; sensors read through it and effectors write through it. Created at node startup and bound to sensors/effectors by id.

core.models.EffectorConfig

Bases: BaseModel

An output device on this node (fans, LEDs, motors, …).

backend selects where it writes: {device: } drives a device's command sink (e.g. an MCU's PWM); an SBC-direct backend (e.g. {type: sbc_pwm, pins}) is a later addition. Channels carry name+index.

core.models.PolicyConfig

Bases: BaseModel

A control loop on this node. The behavior is code (a registered PolicyBase subclass named by type); this only declares the wiring + params.

observation is a list of relay signal names (e.g. "gas_array.raw.mq135", "board_temp.cpu_c"); action targets an effector ({effector: }); always_on marks a reflex that should keep running when cortical policies are absent. Learned policies reference weights via params.

core.models.NodeConfig

Bases: BaseModel

Complete per-board configuration loaded from config.yaml.

core.models.CameraConfig

Bases: BaseModel

core.models.NetworkConfig

Bases: BaseModel

config

core.config.load_node_config(path='config/config.yaml')

Load and validate a per-board node configuration.

Used by the node agent at startup and by the fleet tool when reading staging copies from config/boards/.yaml.

Parameters:

Name Type Description Default
path str | Path

Path to a board config YAML file.

'config/config.yaml'

Returns:

Type Description
NodeConfig

Validated NodeConfig instance.

Raises:

Type Description
FileNotFoundError

if the config file does not exist.

ValidationError

if the config is malformed.

Source code in core/config.py
def load_node_config(path: str | Path = "config/config.yaml") -> NodeConfig:
    """Load and validate a per-board node configuration.

    Used by the node agent at startup and by the fleet tool when reading
    staging copies from config/boards/<id>.yaml.

    Args:
        path: Path to a board config YAML file.

    Returns:
        Validated NodeConfig instance.

    Raises:
        FileNotFoundError: if the config file does not exist.
        pydantic.ValidationError: if the config is malformed.
    """
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(
            f"Board config not found: {p}\n"
            f"Copy config/config.example.yaml to {p} and edit it for this board."
        )
    raw = yaml.safe_load(p.read_text(encoding="utf-8"))
    return NodeConfig.model_validate(raw)