Skip to content

Implement a Custom Plugin

This guide covers writing a plugin that answers commands but does not stream sensor data.

Prerequisites

  • Py ToloMEO installed: uv add tolomeo
  • A NATS broker and the NATS CLI, to send a command

Define the Commands

Each command is a class with a single async execute class method:

from typing import Dict
from tolomeo.commands.plugin import PluginCmd, PluginCmdContext


class RebootCmd(PluginCmd):
    @classmethod
    async def execute(cls, context: PluginCmdContext) -> Dict:
        # context.plugin is the plugin instance
        # context.payload is the decoded command dict
        plugin_id = context.plugin.id
        return {"status": "rebooting", "plugin": plugin_id}


class GetVersionCmd(PluginCmd):
    @classmethod
    async def execute(cls, context: PluginCmdContext) -> Dict:
        return {"version": "1.0.0"}

Define the Plugin Class

Declare your commands in Meta.commands, set self.id inside connect, and release resources in disconnect:

from tolomeo.plugins import PluginBase


class SystemPlugin(PluginBase):
    class Meta:
        commands = [RebootCmd, GetVersionCmd]

    async def connect(self) -> bool:
        self.id = "system"
        return True

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

Use Lifecycle Hooks (Optional)

Override a hook to run code at a point of the lifecycle:

import asyncio


class SystemPlugin(PluginBase):
    # … (Meta, connect and disconnect as above)

    async def before_connect(self) -> None:
        self._logger.info("Preparing system plugin resources")

    async def after_setup(self) -> None:
        # Start a background monitoring task after all commands are registered
        await self.task_manager.add_task("monitor", self._monitor)

    async def _monitor(self) -> None:
        while True:
            # periodic monitoring
            await asyncio.sleep(30)

Available hooks (called in order during attach):

  • before_connect → connect → after_connect
  • before_setup → setup → after_setup

And during detach:

  • before_disconnect → disconnect → after_disconnect

Read Configuration (Optional)

To take options from the deployment's configuration file, declare a Pydantic model in Meta.config_model and read self.options:

from pydantic import BaseModel, ConfigDict, PositiveInt


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

    monitor_interval_s: PositiveInt = 30


class SystemPlugin(PluginBase):
    # … (connect, disconnect, before_connect and after_setup as above)

    class Meta:
        commands = [RebootCmd, GetVersionCmd]  # as above
        config_model = SystemOptions

    async def _monitor(self) -> None:
        while True:
            await asyncio.sleep(self.options.monitor_interval_s)

This _monitor replaces the one in the hooks example: it sleeps for the configured monitor_interval_s. Set it in the configuration file:

[plugins.system]
monitor_interval_s = 60

Options are keyed by the plugin id, so they are readable only after connect sets it. With extra="forbid", a mistyped key fails the attach and names the key. See Configuration File.

Wire into a Service

Declare the plugin class and override acquire_plugins to attach it:

from tolomeo.services import NATSService
from .plugin import SystemPlugin


class SystemService(NATSService):
    class Meta:
        plugin_class = SystemPlugin

    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. Override wire_plugin to bind your own handlers.

Run the Service

Create my_service/main.py and start it with python -m my_service.main:

import asyncio
import logging

from .service import SystemService

logging.basicConfig(level=logging.INFO)

asyncio.run(SystemService("system").run())

Send a Command

Send commands to commands.{service}.req as a SenML record: n is the command class name, vs the payload as a JSON string:

nats pub commands.system.req \
  '[{"n":"GetVersionCmd","vs":"{\"id\":\"system\"}"}]'

See also