Skip to content

Build Your First Service

This tutorial builds a minimal sensor service. By the end you will have a service called dummy that publishes a random value on events.data every second and answers a command.

This tutorial does not cover metric types, configuration or BLE sensors; a fuller version lives in examples/temperature/.

Prerequisites

  • Python ≥ 3.11
  • uv installed
  • A working instance of the ToloMEO Edge agent
  • Py ToloMEO installed: uv add tolomeo
  • The NATS CLI, configured for the device's NATS server

Step 1 — Create the plugin

A plugin wraps your hardware or data source. SensorPlugin registers the metrics and tracks the sensor state. It has no polling loop: the plugin pushes each reading with await self.push_reading({...}).

Create my_service/plugin.py:

import asyncio
import time
from random import random
from typing import Dict

from tolomeo.commands.plugin import PluginCmd, PluginCmdContext
from tolomeo.metrics import Metric
from tolomeo.plugins import SensorPlugin


class PingCmd(PluginCmd):
    """A simple command that returns the plugin ID."""

    @classmethod
    async def execute(cls, context: PluginCmdContext) -> Dict:
        return {"message": f"pong from {context.plugin.id}"}


class DummyPlugin(SensorPlugin):
    class Meta:
        commands = [PingCmd]
        out_metrics = [Metric("dummy_metric", "")]

    async def connect(self) -> bool:
        self.id = "DummyPlugin"         # must be set inside connect()
        self._logger.info("Connected")
        return True

    async def disconnect(self) -> bool:
        self._logger.info("Disconnected")
        return True

    async def after_setup(self) -> None:
        # Start a background task that generates data
        await self.task_manager.add_task("simulate", self._simulate)

    async def _simulate(self) -> None:
        while True:
            await asyncio.sleep(1)
            await self.push_reading({
                "timestamp": round(time.time()),
                f"{self.id}:dummy_metric": random(),
            })

Step 2 — Create the service

A service hosts the plugin and talks NATS. SingleSensorService hosts exactly one sensor plugin.

Create my_service/service.py:

from tolomeo.services import SingleSensorService
from .plugin import DummyPlugin


class DummyService(SingleSensorService):
    class Meta:
        plugin_class = DummyPlugin

That is the whole service: SingleSensorService creates the plugin, attaches it and wires its callbacks. To host several plugin instances, or discover them, subclass SensorService and override acquire_plugins; see Implement a Sensor Plugin.

Step 3 — Wire the entry point

Create my_service/main.py:

import asyncio
import logging
from .service import DummyService

logging.basicConfig(level=logging.INFO)


async def main() -> None:
    service = DummyService("dummy")
    try:
        await service.run()
    except asyncio.CancelledError:
        pass


if __name__ == "__main__":
    asyncio.run(main())

Step 4 — Run the service

Start the service:

DEVICE_SERIAL_NUMBER=test001 python -m my_service.main

In a separate terminal, subscribe to NATS to observe the output:

nats sub "events.data"

You should see SenML records arriving every second:

[{"bn": "urn:cpt:device:sn:test001:", "n": "DummyPlugin:dummy_metric", "t": 1700000010, "u": "", "v": 0.723}]

Step 5 — Send a command

nats pub commands.dummy.req \
  '[{"n":"PingCmd","vs":"{\"id\":\"DummyPlugin\"}"}]'

The reply appears on events.params. The service adds the plugin id to every plugin command's reply:

[{"bn": "urn:cpt:device:sn:test001:", "n": "PingCmd", "vs": "{\"id\": \"DummyPlugin\", \"message\": \"pong from DummyPlugin\"}"}]

Step 6 — Declare a command payload

A command receives the message body as context.payload, a plain dict. To validate it before the command runs, and announce its shape to clients, declare a model: subclass CommandPayload and set it as Meta.payload_model.

from tolomeo.commands import CommandPayload, PluginCmd, PluginCmdContext


class SetIntervalPayload(CommandPayload):
    seconds: int = 1


class SetIntervalCmd(PluginCmd):
    class Meta:
        payload_model = SetIntervalPayload

    @classmethod
    async def execute(cls, context: PluginCmdContext) -> dict:
        params = cls.params_of(context)
        return {"seconds": params.seconds}

Add it to the plugin's Meta.commands. Before execute runs, the payload is validated into context.params, which cls.params_of(context) returns. context.payload stays the raw dict.

  • Unknown fields are ignored. Fields without a default are required.
  • A plugin command's model never declares id: the framework removes it to find the plugin and adds it to the announced schema.
  • A command without a Meta.payload_model is not validated.
  • A subclass inherits its parent's model unless its own Meta sets another.
  • Use CommandStr for string fields that should also accept JSON numbers and booleans: they are stringified, so 123 becomes "123".

An invalid payload is answered with an error record naming each offending field, for example Invalid payload for 'SetIntervalCmd': seconds: Input should be a valid integer, unable to parse string as an integer. To reply in the command's own format instead, override on_invalid_payload:

from tolomeo.exceptions import InvalidPayloadError


class SetIntervalCmd(PluginCmd):
    class Meta:
        payload_model = SetIntervalPayload

    @classmethod
    async def on_invalid_payload(cls, context: PluginCmdContext, error: InvalidPayloadError) -> dict:
        return {"result": "error", "error": str(error)}

    ...

The service announces every command's schema, so a frontend can build a form for it; see SenML Format.

Next Steps