Skip to content

Implement a Sensor Plugin

This guide covers writing a plugin that reads a sensor and publishes its values.

Prerequisites

  • Py ToloMEO installed: uv add tolomeo
  • A sensor you can read from Python, such as a driver, a serial port or a BLE device
  • A NATS broker the service can reach
  • A Bluetooth adapter, for BLE sensors

Define the Plugin Class

Use SensorPlugin for a plugin that publishes metrics from a sensor; for one that only answers commands, see Implement a Custom Plugin. Declare your output metrics in Meta.out_metrics, implement connect (setting self.id) and disconnect:

import asyncio
import time
from tolomeo.metrics import Metric, MetricType, MetricDataType
from tolomeo.plugins import SensorPlugin


class Thermometer:
    """Stands in for your hardware driver."""

    async def read_celsius(self) -> float:
        return 23.5


class TemperaturePlugin(SensorPlugin):
    class Meta:
        out_metrics = [
            Metric(
                name="temperature",
                unit="°C",
                type=MetricType.TEMPORAL,
                data_type=MetricDataType.NUMBER,
            )
        ]

    async def connect(self) -> bool:
        self.id = "temperature_sensor"   # must be set here
        self._hw = Thermometer()         # your hardware driver: open the serial port, BLE connection, etc.
        return True

    async def disconnect(self) -> bool:
        # close connection
        return True

Push Data

SensorPlugin has no polling loop: push each reading with await self.push_reading(...) from a background task started in after_setup. The dict holds a timestamp plus one value per metric, keyed f"{self.id}:{metric.name}":

    async def after_setup(self) -> None:
        await self.task_manager.add_task("read_sensor", self._read_loop)

    async def _read_loop(self) -> None:
        while True:
            temperature = await self._hw.read_celsius()
            await self.push_reading({
                "timestamp": round(time.time()),
                f"{self.id}:temperature": temperature,
            })
            await asyncio.sleep(1)

Handle Reconnects (Optional)

SensorPlugin does not detect a lost connection itself. Your read loop detects it, sets the state and reconnects, using self.conn_context.reconnect_policy for the retry cadence:

    # in TemperaturePlugin; SensorState comes from tolomeo.plugins.sensor
    async def _read_loop(self) -> None:
        while True:
            try:
                temperature = await self._hw.read_celsius()
            except ConnectionError:
                self.state = SensorState.DISCONNECTED
                self._logger.warning("Sensor disconnected, reconnecting")
                await self.connect()
                continue
            # … push the reading as above

on_disconnect holds an optional callback for that moment; nothing calls it unless your code does. BLESensorPlugin is the exception: Bleak calls it when the device drops.

Make the Cadence Configurable (Optional)

Hardcoding the reading interval means a deployment cannot change it. Declare a model in Meta.config_model and read self.options instead:

from pydantic import BaseModel, ConfigDict, PositiveFloat


class TemperatureOptions(BaseModel):
    model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)

    interval_s: PositiveFloat = 1.0


class TemperaturePlugin(SensorPlugin):
    # … (connect, disconnect and after_setup as above)

    class Meta:
        out_metrics = [...]                # as above
        config_model = TemperatureOptions

    async def _read_loop(self) -> None:
        while True:
            temperature = await self._hw.read_celsius()
            await self.push_reading({
                "timestamp": round(time.time()),
                f"{self.id}:temperature": temperature,
            })
            await asyncio.sleep(self.options.interval_s)

This _read_loop replaces the loop above and sleeps for the configured interval_s. Set it in the file:

[plugins.temperature_sensor]
interval_s = 5.0

Keep the cadence in the plugin loop, not in the sensor object, so a deployment can change it. PositiveFloat rules out a zero that would spin. See Configuration File.

Wire into a Service

For one plugin, use SingleSensorService:

from tolomeo.services import SingleSensorService
from .plugin import TemperaturePlugin


class TemperatureService(SingleSensorService):
    class Meta:
        plugin_class = TemperaturePlugin

For several instances of the plugin, or discovery, subclass SensorService and override acquire_plugins:

from tolomeo.services import SensorService


class MultiSensorService(SensorService):
    class Meta:
        plugin_class = TemperaturePlugin

    async def acquire_plugins(self) -> None:
        await self.attach_plugin(self.new_plugin())

attach_plugin wires the plugin's callbacks, attaches it, and registers it only if the attach succeeded. It also announces the new plugin list; detach_plugin does the same on removal.

Every sensor service names its own plugin_class: SensorPlugin is abstract, so there is no default. A missing one raises RuntimeError when the service is created.

BLE Sensors

BLESensorPlugin adds Bleak connection management, GATT discovery and a state machine. Every BLE device speaks its own wire format, so each device needs its own plugin implementing parse_data.

import time
from typing import Dict

from tolomeo.metrics import Metric
from tolomeo.plugins.ble import BLESensorPlugin


class ThermoBeaconPlugin(BLESensorPlugin):
    class Meta:
        out_metrics = [Metric("temperature", "Cel")]

    def parse_data(self, data: bytearray) -> Dict:
        raw = int.from_bytes(data[0:2], "little", signed=True)
        return {
            "timestamp": round(time.time()),
            f"{self.id}:temperature": raw / 100.0,
        }

The service only names the plugin. BLESensorService handles discovery by address, registration, persistence and the ConnectDevice/DisconnectDevice commands:

from tolomeo.services import BLESensorService


class ThermoBeaconService(BLESensorService):
    class Meta:
        plugin_class = ThermoBeaconPlugin

A BLE plugin's id is the device address

connect sets self.id from the connected client's address, so a configuration table for a BLE plugin is keyed by the address and must be quoted in TOML:

[plugins."AA:BB:CC:DD:EE:FF"]
notify_interval_s = 2.0

All devices of a service share its one plugin_class, so one service cannot mix two sensor models.

Devices to discover at startup come from .devices.yml; the CONFIG_FILENAME environment variable renames it. Override new_config_manager to keep the list elsewhere. examples/ble_mock uses an in-memory list and a mock device, so it runs without a config file or a BLE adapter: start it with python -m examples.ble_mock.main against a NATS broker, then send StartAcquisition to get readings.

Published NATS Output

Metrics are published to events.data as SenML records:

[{"bn": "urn:cpt:device:sn:abc123:", "n": "temperature_sensor:temperature", "t": 1700000010, "u": "\u00b0C", "v": 23.5}]

See also