Skip to content

sensors — API Reference

Each sensor package registers itself via @register("type_key"). The classes below are the public plugin interface.

tf_mini

sensors.tf_mini.sensor.TFminiSensor(sensor_id, config)

Bases: SensorBase

Benewake TF Mini Plus LiDAR over UART.

Config connection fields

type: uart port: /dev/ttyAMA0 (or /dev/ttyUSB0, etc.) baud_rate: 115200

Source code in sensors/tf_mini/sensor.py
def __init__(self, sensor_id: str, config: SensorConfig) -> None:
    super().__init__(sensor_id, config)
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False

sensors.tf_mini.driver

TF Mini Plus LiDAR — serial frame parser.

9-byte frames at 115200 baud.

Byte 0–1: 0x59 0x59 (header) Byte 2–3: distance (cm, little-endian uint16) Byte 4–5: signal strength (little-endian uint16) Byte 6–7: chip temperature raw (little-endian uint16) Byte 8: checksum (sum of bytes 0–7, lowest byte)

parse_frame(frame)

Parse a 9-byte TF Mini Plus frame.

Returns (distance_cm, strength, temp_c) on success, None on bad frame.

Source code in sensors/tf_mini/driver.py
def parse_frame(frame: bytes) -> tuple[int, int, float] | None:
    """
    Parse a 9-byte TF Mini Plus frame.

    Returns (distance_cm, strength, temp_c) on success, None on bad frame.
    """
    if len(frame) < 9:
        return None
    if frame[0] != 0x59 or frame[1] != 0x59:
        return None
    if (sum(frame[:8]) & 0xFF) != frame[8]:
        return None

    distance_cm = frame[2] | (frame[3] << 8)
    strength    = frame[4] | (frame[5] << 8)
    temp_raw    = (frame[7] << 8) | frame[6]
    temp_c      = temp_raw / 8.0 - 256.0
    return distance_cm, strength, temp_c

lv_maxsonar

sensors.lv_maxsonar.sensor.LVMaxSonarSensor(sensor_id, config)

Bases: SensorBase

MaxBotix LV-MaxSonar-EZ ultrasonic distance sensor over UART (direct).

Config connection fields

type: uart port: /dev/ttyS0 baud_rate: 9600

The MB1010 TX is inverted (RS232-format, idles LOW); reading it directly on an SBC UART needs a hardware inverter (74HC14 / 2N3904) on the TX line. See README.

Source code in sensors/lv_maxsonar/sensor.py
def __init__(self, sensor_id: str, config: SensorConfig) -> None:
    super().__init__(sensor_id, config)
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False

sensors.lv_maxsonar.driver

LV-MaxSonar-EZ ultrasonic sensor — ASCII serial protocol parser.

ASCII frames at 9600 baud, CR-terminated.

Format: R where NNN is distance in inches (0–254) Example: R023 = 23 inches

parse_line(raw)

Parse one ASCII frame.

Returns distance in inches on success, None on malformed input.

Source code in sensors/lv_maxsonar/driver.py
def parse_line(raw: bytes) -> int | None:
    """
    Parse one ASCII frame.

    Returns distance in inches on success, None on malformed input.
    """
    line = raw.decode("ascii", errors="ignore").strip()
    if len(line) != 4 or line[0] != "R" or not line[1:].isdigit():
        return None
    return int(line[1:])

vl53l1x

sensors.vl53l1x.sensor.VL53L1XSensor(sensor_id, config)

Bases: SensorBase

ST VL53L1X time-of-flight distance sensor over I2C.

Config connection fields

type: i2c bus: 3 (I2C bus number, e.g. /dev/i2c-3) address: 0x29 (default VL53L1X address)

Ranging modes (1=short ~1.3 m, 2=medium ~2 m, 3=long ~4 m) trade maximum range for speed and ambient-light immunity. The sensor starts in long mode. Two runtime controls are exposed (via node/routers/vl53l1x.py):

set_mode(m) — pin a fixed mode (also turns auto off) set_auto(on) — let the sensor pick the tightest mode that covers the current distance, with hysteresis to prevent flapping

Both are thread-safe: the caller only stages intent; the background read loop is the single thread that ever touches the I2C bus.

Source code in sensors/vl53l1x/sensor.py
def __init__(self, sensor_id: str, config: SensorConfig) -> None:
    super().__init__(sensor_id, config)
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False

    self._lock = threading.Lock()
    self._mode = 3                 # currently applied mode (loop writes only)
    self._auto = False
    self._pending_mode: int | None = None   # staged by set_mode()

mode_info()

Current control state — used by the state endpoint and named events.

Source code in sensors/vl53l1x/sensor.py
def mode_info(self) -> dict:
    """Current control state — used by the state endpoint and named events."""
    with self._lock:
        m = self._mode
        return {
            "mode":   m,
            "label":  _MODES[m]["label"],
            "max_mm": _MODES[m]["max_mm"],
            "auto":   self._auto,
        }

set_auto(enabled)

Enable or disable distance-driven auto mode selection.

Source code in sensors/vl53l1x/sensor.py
def set_auto(self, enabled: bool) -> None:
    """Enable or disable distance-driven auto mode selection."""
    with self._lock:
        self._auto = bool(enabled)
    # Reflect the toggle immediately; mode changes broadcast as they apply.
    self._broadcast_event("mode", self.mode_info())

set_mode(mode)

Pin a fixed ranging mode (1/2/3). Disables auto-ranging.

Source code in sensors/vl53l1x/sensor.py
def set_mode(self, mode: int) -> None:
    """Pin a fixed ranging mode (1/2/3). Disables auto-ranging."""
    if mode not in _MODES:
        raise ValueError(f"mode must be one of {sorted(_MODES)}, got {mode!r}")
    with self._lock:
        self._auto = False
        self._pending_mode = mode

sensors.vl53l1x.driver.VL53L1X(bus, addr=41)

Low-level smbus2 driver for the ST VL53L1X ToF sensor.

Usage

bus = smbus2.SMBus(3) sensor = VL53L1X(bus, addr=0x29) sensor.init() sensor.set_distance_mode(3) # long range sensor.start_continuous() while True: mm = sensor.read_mm() # returns int or None

Source code in sensors/vl53l1x/driver.py
def __init__(self, bus: smbus2.SMBus, addr: int = 0x29) -> None:
    self._bus  = bus
    self._addr = addr

init()

Load default config blob and wait for firmware boot.

Source code in sensors/vl53l1x/driver.py
def init(self) -> None:
    """Load default config blob and wait for firmware boot."""
    model_id = self._rd(_IDENTIFICATION__MODEL_ID)
    log.info("VL53L1X model ID: 0x%02X (expect 0xEA)", model_id)
    if model_id != 0xEA:
        raise RuntimeError(f"Unexpected model ID 0x{model_id:02X}")

    log.info("Waiting for firmware boot…")
    deadline = time.time() + 2.0
    while self._rd(_FIRMWARE__SYSTEM_STATUS) != 0x03:
        if time.time() > deadline:
            raise RuntimeError("Firmware boot timeout")
        time.sleep(0.01)

    self._wr_block(0x002D, _DEFAULT_CONFIG)
    self._wr(_VHV_CONFIG__TIMEOUT_MACROP_LOOP_BOUND, 0x09)
    self._wr(0x000B, 0x00)
    log.info("VL53L1X init complete")

read_mm(timeout=1.0)

Block until a measurement is ready and return distance in mm. Returns None on ranging error or timeout.

Source code in sensors/vl53l1x/driver.py
def read_mm(self, timeout: float = 1.0) -> int | None:
    """
    Block until a measurement is ready and return distance in mm.
    Returns None on ranging error or timeout.
    """
    deadline = time.time() + timeout
    while not (self._rd(_GPIO__TIO_HV_STATUS) & 0x01):
        if time.time() > deadline:
            return None
        time.sleep(0.001)

    status   = self._rd(_RESULT__RANGE_STATUS) & 0x1F
    distance = self._rd16(_RESULT__FINAL_CROSSTALK_CORRECTED_RANGE_MM_SD0)
    self._wr(_SYSTEM__INTERRUPT_CLEAR, 0x01)

    # Status 0 = valid, 9 = wraparound (still usable)
    return distance if status in (0, 9) else None

set_distance_mode(mode)

Set ranging mode (1=short, 2=medium, 3=long). Default config is mode 3.

Source code in sensors/vl53l1x/driver.py
def set_distance_mode(self, mode: int) -> None:
    """Set ranging mode (1=short, 2=medium, 3=long). Default config is mode 3."""
    cfg = _MODE_REGS[mode]
    self._wr(0x004B, cfg[0x004B])
    self._wr(0x0060, cfg[0x0060])
    self._wr(0x0063, cfg[0x0063])
    self._wr(0x0069, cfg[0x0069])
    self._wr16(0x0078, cfg[0x0078_16])
    self._wr16(0x007A, cfg[0x007A_16])

mlx90640

sensors.mlx90640.sensor.MLX90640Sensor(sensor_id, config)

Bases: SensorBase

Melexis MLX90640 32×24 IR thermal array over I2C.

Config connection fields

type: i2c bus: 3 (I2C bus number) address: 0x33 (default MLX90640 address)

Two output lanes

JSON reading (/sensors//stream, /ws) — lean per-frame summary: {min_temp, max_temp, width, height}. No pixel array, so serialising it 32×/s stays cheap and GET /sensors/ is a light snapshot. Binary frames (/sensors//frames) — the full 768-pixel array as a packed little-endian frame (see _FRAME_HEADER above). This is the lane the thermal viewer consumes; it skips json.dumps server-side and a big array parse + GC client-side.

Source code in sensors/mlx90640/sensor.py
def __init__(self, sensor_id: str, config: SensorConfig) -> None:
    super().__init__(sensor_id, config)
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False
    self._frame_id = 0

sensors.mlx90640.driver.MLX90640(bus, addr=51, refresh_hz=8)

Complete MLX90640 driver implementing datasheet §11 calibration compensation.

Reads EEPROM calibration data on construction; subsequent get_frame() calls fill a 768-element list with temperatures in °C.

Source code in sensors/mlx90640/driver.py
def __init__(self, bus: smbus2.SMBus, addr: int = 0x33,
             refresh_hz: float = 8) -> None:
    if refresh_hz not in self.REFRESH_CODES:
        raise ValueError(
            f"mlx90640 refresh_hz {refresh_hz} not supported "
            f"(one of {sorted(self.REFRESH_CODES)})")
    self.refresh_hz = refresh_hz
    self.bus  = bus
    self.addr = addr
    log.info("Reading MLX90640 EEPROM…")
    self._ee = read_words(bus, addr, self.REG_EEPROM, 832)
    log.info("Extracting calibration parameters…")
    self._p: dict = {}
    self._extract_params()
    self._set_refresh_rate(self.REFRESH_CODES[self.refresh_hz])
    log.info("MLX90640 ready (%s Hz, %s mode)", self.refresh_hz,
             "chess" if self._p["chess"] else "interleaved")

get_frame(out)

Fill out[768] with temperatures in °C (updates both subpages). out must be a pre-allocated list of 768 floats.

Source code in sensors/mlx90640/driver.py
def get_frame(self, out: list[float]) -> None:
    """
    Fill out[768] with temperatures in °C (updates both subpages).
    out must be a pre-allocated list of 768 floats.
    """
    for sp in range(2):
        if not self._wait_ready(sp):
            log.warning("Timeout waiting for subpage %d", sp)
            continue
        ram = read_words(self.bus, self.addr, self.REG_RAM, 832)
        self._compensate(ram, sp, out)

mq_array

sensors.mq_array.sensor.MqArray(sensor_id, config)

Bases: AnalogArrayBase

An array of MQ-series gas sensors, read as raw ADC over an MCU uplink.

Wiring (which gas is on which channel) and per-unit calibration live in the sensor's channels config — authored consistently with the MCU's forge contract (config/mcus/.yaml). Raw counts are always emitted; when a channel's calibration is {type: mq, rl, r0} we also emit its Rs/R0 ratio.

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()

sensors.mq_array.driver

MQ gas-sensor math — pure functions, no I/O, no hardware.

MQ-series sensors are resistive: a heated element's resistance Rs falls as target gas rises. The board reads the voltage across a load resistor RL, which the MCU digitizes to a raw ADC count. Datasheet ppm curves are all plotted against the ratio Rs/R0, where R0 is the sensor's resistance in clean air (per-unit, measured during calibration). These helpers convert raw counts → that ratio; turning the ratio into ppm needs per-gas curve constants and is deferred.

rs_over_r0(raw, rl_ohms, r0_ohms, adc_max=ADC_MAX)

Rs/R0 ratio — the x-axis of every MQ datasheet ppm curve.

Needs the load resistor RL and the clean-air baseline R0 (both ohms). Returns None when the inputs are unusable (raw <= 0 or r0 <= 0).

Source code in sensors/mq_array/driver.py
def rs_over_r0(raw: int, rl_ohms: float, r0_ohms: float,
               adc_max: int = ADC_MAX) -> float | None:
    """Rs/R0 ratio — the x-axis of every MQ datasheet ppm curve.

    Needs the load resistor RL and the clean-air baseline R0 (both ohms).
    Returns None when the inputs are unusable (raw <= 0 or r0 <= 0).
    """
    ratio = rs_over_rl(raw, adc_max)
    if ratio is None or r0_ohms <= 0:
        return None
    return ratio * rl_ohms / r0_ohms

rs_over_rl(raw, adc_max=ADC_MAX)

Rs/RL from a raw ADC count: (adc_max - raw) / raw.

Returns None for raw <= 0 (open input / no reading) to avoid divide-by-zero.

Source code in sensors/mq_array/driver.py
def rs_over_rl(raw: int, adc_max: int = ADC_MAX) -> float | None:
    """Rs/RL from a raw ADC count: (adc_max - raw) / raw.

    Returns None for raw <= 0 (open input / no reading) to avoid divide-by-zero.
    """
    if raw <= 0:
        return None
    return (adc_max - raw) / raw

pressure_array

sensors.pressure_array.sensor.PressureArray(sensor_id, config)

Bases: AnalogArrayBase

A logical pressure surface read across one or more MCU devices.

Two shapes, decided by config:

Flat array (no row_tag channels): every channel is a static tap; AnalogArrayBase composes the per-device frames into one reading and enrich adds kPa for linear-calibrated channels. The original cranial-pressure shape.

Scanned lattice (params.rows + one row_tag channel per device): the velostat lattice is energized one row at a time by a conductor MCU (see mcu/circuit_python/modules/matrix_scan), so each device frame is one row's worth of that device's columns, tagged with the row index in its row_tag channel (-1 = the follower saw no conductor). This class accumulates rows per device, freezes a device's sweep when its row counter wraps, and when every device has a frozen sweep composes the full rows x columns grid:

  • JSON lane: latest raw values + a sweep summary (n / complete / missing cells / follower timeouts) — light, for status + scalars.
  • Binary frame lane (/sensors/<id>/frames): the full grid as float32, header <IHHff = (sweep_n, rows, cols, min, max), row-major, NaN for cells a device never delivered. Columns are the non-row_tag channels in config order.

A device that laps the others (double wrap before composition) forces a partial emit so a dead follower degrades to complete: false, never to silence — mirroring the firmware's -1 sentinel philosophy.

Source code in sensors/pressure_array/sensor.py
def __init__(self, sensor_id, config) -> None:
    super().__init__(sensor_id, config)
    self._rows = int((config.params or {}).get("rows", 0))
    self._row_ch: dict[str, int] = {}                  # device → row-tag index
    self._dev_cols: dict[str, list[tuple[int, str]]] = {}   # device → [(index, signal)]
    self._cols: list[tuple[str, str]] = []             # grid columns: (device, signal)
    for ch in config.channels:
        if (ch.calibration or {}).get("type") == "row_tag":
            if ch.device:
                self._row_ch[ch.device] = ch.index
        elif ch.device:
            self._dev_cols.setdefault(ch.device, []).append((ch.index, ch.signal))
            self._cols.append((ch.device, ch.signal))
    # Sweep accumulation (guarded by the base's lock — ingest is per-device-thread)
    self._acc: dict[str, dict[int, dict[str, int]]] = {}      # device → row → signals
    self._frozen: dict[str, dict[int, dict[str, int]]] = {}
    self._last_row: dict[str, int] = {}
    self._timeouts = 0                                 # follower -1 frames this sweep
    self._sweep_n = 0
    self._sweep_meta: dict | None = None

sensors.pressure_array.driver

Pressure transfer math — pure functions, no I/O.

to_kpa(count, scale, offset=0.0)

Linear transfer from a raw ADC count to kPa: count * scale + offset.

scale/offset come from the transducer datasheet + the ADC reference, per channel. (Non-linear transducers can extend this with their own kind.)

Source code in sensors/pressure_array/driver.py
def to_kpa(count: int, scale: float, offset: float = 0.0) -> float:
    """Linear transfer from a raw ADC count to kPa: count * scale + offset.

    `scale`/`offset` come from the transducer datasheet + the ADC reference, per
    channel. (Non-linear transducers can extend this with their own kind.)
    """
    return count * scale + offset

ir_xcvr

sensors.ir_xcvr.sensor.IrXcvrSensor(sensor_id, config)

Bases: SensorBase

IR transceiver sensor wrapping TSOP38238 (RX) and TSAL6200 (TX).

Config example::

- id: ir_xcvr
  type: ir_xcvr
  enabled: true
  connection:
    type: ir
    rx_device: /dev/lirc0
    tx_device: /dev/lirc1
Source code in sensors/ir_xcvr/sensor.py
def __init__(self, sensor_id: str, config: SensorConfig) -> None:
    super().__init__(sensor_id, config)

    conn = config.connection
    self._rx_device: str | None = getattr(conn, "rx_device", None)
    self._tx_device: str | None = getattr(conn, "tx_device", None)

    self._thread:      threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy    = False

    self._tx_fd:            int | None = None
    self._tx_scancode_mode: bool       = False
    self._tx_lock = threading.Lock()

transmit(protocol, address, command)

Transmit one IR code.

Parameters

protocol : "NEC" or "NECX" address : 0-255 (NEC) / 0-65535 (NECX) command : 0-255

Returns

bool True on success; False if TX unavailable or the write failed.

Source code in sensors/ir_xcvr/sensor.py
def transmit(self, protocol: str, address: int, command: int) -> bool:
    """
    Transmit one IR code.

    Parameters
    ----------
    protocol : "NEC" or "NECX"
    address  : 0-255 (NEC) / 0-65535 (NECX)
    command  : 0-255

    Returns
    -------
    bool  True on success; False if TX unavailable or the write failed.
    """
    with self._tx_lock:
        if self._tx_fd is None:
            log.warning("%s: transmit called but TX device is not open", self.id)
            return False
        try:
            if self._tx_scancode_mode:
                return _drv.write_scancode(self._tx_fd, protocol, address, command)
            else:
                from sensors.ir_xcvr.codec import encode_nec
                pulses = encode_nec(address, command, extended=(protocol.upper() == "NECX"))
                return _drv.write_raw_pulses(self._tx_fd, pulses)
        except OSError as exc:
            log.error("%s: TX write failed — %s", self.id, exc)
            return False

analog_in

sensors.analog_in.sensor.AnalogIn(sensor_id, config)

Bases: SensorBase

Heterogeneous scalar analog inputs read through a pull device (an ADS1115).

Unlike an array sensor, each channel is its own signal with its own meaning and calibration (e.g. 4 different sources on one Pi02W ADS1115). Polls each configured channel via the device's read_channel(); emits raw counts always, plus a calibrated value per channel whose calibration is linear.

Source code in sensors/analog_in/sensor.py
def __init__(self, sensor_id, config) -> None:
    super().__init__(sensor_id, config)
    self._devices: dict[str, "Device"] = {}
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False

board_temp

sensors.board_temp.sensor.BoardTemp(sensor_id, config)

Bases: SensorBase

SBC board/CPU temperatures from Linux thermal zones (sysfs).

No external hardware and no device — reads /sys/class/thermal/thermal_zone*/temp. Emits one key per zone (zone0_c, zone1_c, …) plus cpu_c (the primary, zone0). A common input to a cooling-control policy.

Source code in sensors/board_temp/sensor.py
def __init__(self, sensor_id, config) -> None:
    super().__init__(sensor_id, config)
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False

fan_tach

sensors.fan_tach.sensor.FanTach(sensor_id, config)

Bases: AnalogArrayBase

Fan RPM streamed from an MCU's tach (FG) counters.

A thin AnalogArrayBase: the device already streams RPM (the firmware tach module counts FG edges and converts), so the raw frame value is the RPM — no calibration. enrich just mirrors raw under rpm for a friendly key.

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()

servo_feedback

sensors.servo_feedback.sensor.ServoFeedback(sensor_id, config)

Bases: AnalogArrayBase

Proprioception: servo pot-wiper taps read back as joint angles.

Device-fed (no connection): channels arrive over an MCU serial uplink (e.g. the cervical SAMD21's analog_in pins) or an SBC-side ADS1115 (the ear pots on the pizero). The taps are voltage-divided to the ADC rail — the divider ratio is part of the calibration end points, never firmware.

Calibration {type: servo_pot, counts_min, counts_max, deg_min, deg_max}: deg = deg_min + (count - counts_min) / (counts_max - counts_min) * (deg_max - deg_min), clamped to [deg_min, deg_max] Endpoints are measured at bench (command the servo to each soft limit and record the counts). Raw counts are always emitted alongside.

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()

current

sensors.current.sensor.CurrentSensor(sensor_id, config)

Bases: AnalogArrayBase

Rail current from hall-effect sensors (ACS712 et al.) — interoception.

Device-fed: the ACS712's analog output (Vcc/2 at zero current, ±mV/A) arrives as raw ADC counts over an ads1115 device or MCU uplink. The counts→amps meaning lives here, per channel:

Calibration {type: acs712, zero_counts, counts_per_amp}: amps = (count - zero_counts) / counts_per_amp (signed)

zero_counts is captured at bench with the load off (it drifts with the sensor's actual Vcc); counts_per_amp folds together the sensor's mV/A (66 for the 30 A part) and the ADC's counts/mV at the configured gain. The overcurrent guard observes the published amps signal — see policies/threshold.

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()

radar_motion

sensors.radar_motion.sensor.RadarMotion(sensor_id, config)

Bases: AnalogArrayBase

Microwave Doppler motion from analog-hacked RCWL-0516 modules.

The stock RCWL-0516 outputs a 2 s digital pulse; these units are hacked to expose the analog Doppler stage instead, so motion appears as deviation from a slowly-drifting resting level. Device-fed raw counts; meaning here:

Per channel, a slow EMA baseline tracks the resting level and the reading publishes the absolute deviation plus a boolean over params.threshold:

level  = |count - baseline|          (counts)
motion = level > threshold

Config keys (params): baseline_alpha — EMA coefficient for the resting level (default 0.02; smaller = slower drift tracking) threshold — counts of deviation that count as motion (default 500; tune at bench — VERIFY against the hack's gain)

The baseline only adapts while quiescent (level under threshold), so a person standing in the field doesn't get absorbed into "resting".

Source code in sensors/radar_motion/sensor.py
def __init__(self, sensor_id, config) -> None:
    super().__init__(sensor_id, config)
    self._baseline: dict[str, float] = {}

audio_in

sensors.audio_in.sensor.AudioIn(sensor_id, config)

Bases: SensorBase

Stereo audio capture (PCM1808 over the shared-clock I2S bus) — audition.

Two lanes, per the high-rate array convention: - binary frame lane (/sensors/<id>/frames): every captured block, header <IHHI> = (frame_id, channels, bits, rate) + raw interleaved S16_LE samples — the waveform/feature stream for viewers and the inference hub. ~2.3 Mbps at 48 kHz stereo: trivial for the network lane. - JSON lane: rate-limited per-channel level summaries (rms / peak / dBFS), throttled to ~params.json_hz (default 5) readings/s.

Connectionless (the I2S bus is OS plumbing, not a fleet-config wiring detail); params: alsa_device ("hw:0,0"), sample_rate (48000), channels (2), block_ms (50), json_hz (5).

Capture uses pyalsaaudio when present, else an arecord raw pipe — and on a machine with neither (Windows dev) the sensor stays cleanly unhealthy.

Source code in sensors/audio_in/sensor.py
def __init__(self, sensor_id: str, config: SensorConfig) -> None:
    super().__init__(sensor_id, config)
    p = config.params or {}
    self._device = str(p.get("alsa_device", "hw:0,0"))
    self._rate = int(p.get("sample_rate", 48000))
    self._channels = int(p.get("channels", 2))
    self._block_frames = max(1, self._rate * int(p.get("block_ms", 50)) // 1000)
    self._json_period = 1.0 / float(p.get("json_hz", 5))
    self._thread: threading.Thread | None = None
    self._stop_event = threading.Event()
    self._healthy = False
    self._frame_id = 0

sensors.audio_in.driver

ALSA capture + PCM block math for audio_in. Hardware I/O only — no threading, no HTTP. The DSP helpers are pure and unit-tested on any platform.

Capture backends, tried in order: 1. pyalsaaudio (alsaaudio) — in-process, lowest overhead. 2. arecord subprocess piping raw S16_LE — present on every ALSA board. Both deliver interleaved signed 16-bit little-endian blocks.

AlsaCapture(device, rate, channels, block_frames)

One opened capture stream delivering raw S16_LE blocks.

Source code in sensors/audio_in/driver.py
def __init__(self, device: str, rate: int, channels: int,
             block_frames: int) -> None:
    self.device = device
    self.rate = rate
    self.channels = channels
    self.block_frames = block_frames
    self._pcm = None          # pyalsaaudio handle
    self._proc = None         # arecord subprocess
    self._block_bytes = block_frames * channels * 2

read()

Block until one block is available; b'' on stream end.

Source code in sensors/audio_in/driver.py
def read(self) -> bytes:
    """Block until one block is available; b'' on stream end."""
    if self._pcm is not None:
        length, data = self._pcm.read()
        return data if length > 0 else b""
    if self._proc is not None and self._proc.stdout is not None:
        return self._proc.stdout.read(self._block_bytes) or b""
    return b""

block_stats(pcm, channels)

Per-channel RMS + peak of one interleaved S16_LE block, as 0..1 of FS.

Pure function (the unit-tested meaning layer). Returns one {"rms": …, "peak": …, "dbfs": …} per channel; silence → dbfs -120.

Source code in sensors/audio_in/driver.py
def block_stats(pcm: bytes, channels: int) -> list[dict[str, float]]:
    """Per-channel RMS + peak of one interleaved S16_LE block, as 0..1 of FS.

    Pure function (the unit-tested meaning layer). Returns one
    {"rms": …, "peak": …, "dbfs": …} per channel; silence → dbfs -120.
    """
    samples = array.array("h")
    samples.frombytes(pcm[: len(pcm) - (len(pcm) % (2 * channels))])
    if not _LITTLE_ENDIAN:
        samples.byteswap()
    n = len(samples) // channels
    out = []
    for ch in range(channels):
        acc = 0
        peak = 0
        for i in range(ch, len(samples), channels):
            v = samples[i]
            acc += v * v
            peak = max(peak, abs(v))
        rms = math.sqrt(acc / n) / FULL_SCALE if n else 0.0
        out.append({
            "rms": round(rms, 5),
            "peak": round(peak / FULL_SCALE, 5),
            "dbfs": round(20 * math.log10(rms) if rms > 0 else -120.0, 1),
        })
    return out