Skip to content

Add OTA Support

This tutorial adds firmware updates to a Py ToloMEO service. By the end you will have a service that accepts OTA commands, downloads a package and walks through the OTA state machine.

This tutorial simulates the installation instead of flashing a real image; the complete example is in examples/ota_mock/.

Prerequisites

  • A working service (see Build Your First Service) or a fresh project
  • Py ToloMEO installed: uv add tolomeo
  • A NATS broker the service can reach, and the NATS CLI configured for it
  • A firmware package that the device can download from a URL; to serve a local file, run python -m http.server 8000 in its directory
  • /usr/lib/os-release defining FIRMWARE_NAME and BUILD_VERSION (a SemVer version): the plugin reads the installed firmware from there and fails to start without them

Step 1 — Subclass OTAPlugin

OTAPlugin handles the download and the state machine. A concrete plugin implements four methods:

Method Description
connect Assign self.id; reach whatever performs the flash
disconnect Release that connection
install_update Perform the actual firmware flash
monitor_update Track progress and report success or failure

A missing method raises TypeError when the plugin is created.

Create my_service/ota_plugin.py:

import asyncio

from tolomeo.plugins.ota import OTAPlugin


class MyOTAPlugin(OTAPlugin):

    async def connect(self) -> bool:
        self.id = "swupdate"
        self._logger.info("OTA plugin connected")
        return True

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

    async def install_update(self) -> None:
        """Trigger the actual firmware install and start monitoring."""
        self._logger.info("Starting installation from %s", self.fsm.pending_update.download_path)
        self.fsm.install()

        # Start a task to monitor progress
        await self.task_manager.add_task("monitor_update", self.monitor_update, auto_restart=False)

    async def monitor_update(self) -> None:
        """Simulate or perform the installation and report success/failure."""
        self._logger.info("Monitoring update in state: %s", self.state)

        # Replace the sleep + fsm.update_success() with real install logic
        await asyncio.sleep(5)
        self.fsm.update_success()
        self._logger.info("Installation succeeded")

Step 2 — Wire the plugin into a service

Create my_service/ota_service.py:

from tolomeo.services.ota import OTAService
from .ota_plugin import MyOTAPlugin


class MyOTAService(OTAService):
    class Meta:
        plugin_class = MyOTAPlugin

Step 3 — Choose where files land

Your plugin inherits the OTAOptions configuration keys. Set them in tolomeo.toml, in the working directory or at the path in TOLOMEO_CONFIG, under the plugin id set in connect:

[plugins.swupdate]
download_dir = "/data/firmware"
download_filename = "image.swu"
checkpoint_file = "/data/firmware/ota-state.yml"

Every key is optional. For all keys and defaults, see Configuration File.

To add options of your own, extend the inherited model and declare it in MyOTAPlugin's Meta:

from pathlib import Path

from tolomeo.plugins.ota import OTAPlugin
from tolomeo.plugins.ota.models import OTAOptions


class MyOTAOptions(OTAOptions):
    socket_path: Path = Path("/run/swupdate.sock")


class MyOTAPlugin(OTAPlugin):
    class Meta:
        config_model = MyOTAOptions

    # connect, disconnect, install_update and monitor_update as in Step 1

A model that does not extend OTAOptions raises TypeError at import time, because OTAPlugin reads its fields.

Step 4 — Wire the entry point

Create my_service/ota_main.py:

import asyncio
import logging
from .ota_service import MyOTAService

logging.basicConfig(level=logging.INFO)


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


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

Step 5 — Run the service

DEVICE_SERIAL_NUMBER=test001 python -m my_service.ota_main

The log ends with the service starting, in the updated state:

INFO:tolomeo.services.base:State machine bootstrapped
INFO:tolomeo.services.base:Service swupdate started

Step 6 — Walk through the update flow

Open a NATS subscriber to watch status events:

nats sub events.infos

Then send the commands from Trigger OTA via NATS, with the URL of your package as url, and watch the status:

  1. NotifyOTAUpdate, with a fw_version newer than the device's BUILD_VERSION → update_available
  2. StartOTADownload → downloading → update_ready
  3. InstallOTAUpdate → updating → update_successful

Each transition publishes one event. With a BUILD_VERSION of 1.0.0 and a package at 1.2.3, the subscriber shows:

{"otaStatus": "update_available", "fwName": "firmware", "fwVersion": "1.0.0", "timestamp": 1794213309, "pendingFwName": "firmware", "pendingFwVersion": "1.2.3"}
{"otaStatus": "downloading", "fwName": "firmware", "fwVersion": "1.0.0", "timestamp": 1794213311, "pendingFwName": "firmware", "pendingFwVersion": "1.2.3"}
{"otaStatus": "update_ready", "fwName": "firmware", "fwVersion": "1.0.0", "timestamp": 1794213311, "pendingFwName": "firmware", "pendingFwVersion": "1.2.3"}
{"otaStatus": "updating", "fwName": "firmware", "fwVersion": "1.0.0", "timestamp": 1794213314, "pendingFwName": "firmware", "pendingFwVersion": "1.2.3"}
{"otaStatus": "update_successful", "fwName": "firmware", "fwVersion": "1.0.0", "timestamp": 1794213319, "pendingFwName": "firmware", "pendingFwVersion": "1.2.3"}

Every command also replies on events.params, for example after NotifyOTAUpdate:

[{"bn": "urn:cpt:device:sn:test001:", "n": "NotifyOTAUpdate", "vs": "{\"id\": \"swupdate\", \"result\": \"success\", \"status\": \"update_available\"}"}]

Step 7 — Handle a download failure

A failed download, for example from a bad URL, moves the state to download_failed. Send StartOTADownload to retry, or AbortOTAUpdate to return to update_available. See Recover from a Failure.

Next Steps