Skip to content

Database API ​

controlfreak-api is the controller's REST API and the owner of its database. It is FastAPI over SQLite, built from rpi-controller/database-api/, and it listens on port 8000.

Every other service on the Pi reads and writes state through it, and clients reach it directly on the LAN or through api-bridge when remote. See Architecture for how the remote path works.

Reaching it ​

FromAddress
The LANhttp://controlfreak.local:8000
Services on the PiAPI_URL from .env
A local dev stackhttp://localhost:8000

Interactive docs are served at /docs. rpi-controller/docs/openapi.json is a checked in copy of the schema, and can fall behind the code.

There is no authentication on the API. Anything on the LAN can call it.

Layout ​

PathWhat it holds
app/main.pyApp setup, router registration, seeding and startup tasks
app/endpoints/One router per area
app/models/SQLAlchemy models
app/schemas/Pydantic request and response schemas
app/alembic/Migrations
app/database.pyEngine and session, from DATABASE_PATH

Endpoints ​

Controller ​

MethodPathWhat it does
GET/controller-configName, status, version, timezone, thing name and AWS state
POST/controller-configUpdate controller settings
POST/controller-config/wifiJoin a WiFi network
POST/controller-config/install-awsRun the aws-installer to web enable the controller
POST/controller-config/aws-statusCalled by the installer to report progress and the thing name

Health and updates ​

MethodPathWhat it does
GET/health{ name, version, status }
POST/prepare-updatePull and start controlfreak-docker-updater. 503 when the controller has no internet.
GET/restore-updateWhether snapshots are available to restore
POST/restore-updateStart the updater in restore mode. 409 when there is nothing to restore.
POST/clean-updateSet status back to healthy, remove the updater, clear the retained update status
POST/diagnosticsBuild a zip of logs and state

Devices ​

MethodPathWhat it does
GET/device-settingsEvery device
GET/device-settings/by-type/{type_name}Devices of one type
GET/device-settings/{uuid}One device
POST/device-settingsAdd a device
PUT/device-settings/{uuid}Update a device
PUT/device-settings/{uuid}/telemetryRecord the latest state reported by hardware
PUT/device-settings/orderReorder devices
DELETE/device-settings/{uuid}Remove a device

Reference data ​

Seeded on startup and read only through the API.

PathWhat it holds
/device-types, /device-types/{name}Pump, relay, valve, thermistor and the other device types
/capabilities, /capabilities/{uuid}What each device type can do
/connection-types, /connection-types/{uuid}How a device is wired, and the RS485 driver it uses
/drivers, /drivers/{slug}RS485 drivers
/pump-models, /pump-models/{uuid}, /pump-models/commands/{uuid}Pump models and the commands each accepts
/ports, /ports/{uuid}, /ports/by-name/{name}Physical ports on the boards
/topics, /topics/{uuid}The MQTT topic for each port
/physical-buttons, /physical-buttons/{uuid}What the buttons on the controller do. PUT changes a button.

Features ​

Tethering, themes and freeze protection each have a parent, the rule, and children, the devices it drives. Every one of these has GET, POST, PUT and DELETE, on the collection and on /{uuid}.

AreaPathsExtras
Schedules/schedulesGET /schedules/{device_setting_uuid}
Tethering/tethering/parents, /tethering/childrenGET .../by-device/{uuid} on both
Themes/themes/parents, /themes/childrenPUT /themes/parents/{uuid}/started
Freeze protection/freeze-protection/parents, /freeze-protection/childrenGET /freeze-protection/parents/by-device/{uuid}

Logs ​

MethodPathWhat it does
GET/logsEvery controller container and its status
GET/logs/{name}?tail=&grep=One container's recent log lines

tail defaults to 300 lines and is capped at 2000. grep filters lines case insensitively. Responses are trimmed to about 90 KB so they fit through the remote path.

Controller status ​

controller_settings.status is the controller's state, returned by GET /health. It is healthy normally and moves through update# states during an update.

success:  healthy -> update#preparing -> update#ready -> update#completed -> healthy
failure:  healthy -> update#preparing -> update#ready -> update#failed
restore:  update#failed -> update#restoring -> update#restored -> healthy

The version in GET /health is written by the updater at the end of a successful update.

The database ​

On a Pi/home/pi/sqlite-data/controller.db, mounted at /app/data
In local devrpi-controller/database-api/data/controller.db
Configured byDATABASE_PATH, a SQLAlchemy URL
TableWhat it holds
controller_settingsThe single controller row, name, status, version, timezone, WiFi, thing name, AWS state
device_settingsEvery device and its settings, plus its last known state
device_telemetryReadings reported by hardware
device_associationsLinks between devices, such as a heater and the pump it needs
device_types, device_type_capabilitiesDevice types and what they can do
ports, topicsBoard ports and their MQTT topics
connection_types, connection_type_propertiesWiring and RS485 driver choice
pump_models, pump_model_commandsSupported pumps
physical_button_settingsButton behaviour
scheduleSchedules
tethering_parents, tethering_childrenTethering rules
theme_parents, theme_childrenThemes
freeze_protection_parents, freeze_protection_childrenFreeze protection rules

Startup ​

On every start the API:

  1. Creates any table that does not exist yet.
  2. Seeds reference data and the default devices, ports and topics, but only into an empty database. On an existing database it instead resets the status to healthy, unless an update is running.
  3. Starts api-bridge when the controller is web enabled and it is not running.
  4. Clears the retained update status on the broker, unless an update is running.

On a Pi the production image first runs alembic upgrade heads, then starts uvicorn. The local dev image skips alembic and runs uvicorn with --reload.

Migrations ​

Migrations live in database-api/app/alembic/versions/ and run from database-api/app. env.py reads the database from DATABASE_PATH.

Create one against a copy of a real database, so autogenerate compares against the current schema:

bash
cd rpi-controller/database-api/app
DATABASE_PATH="sqlite:///$PWD/../data/controller.db" alembic upgrade heads
DATABASE_PATH="sqlite:///$PWD/../data/controller.db" alembic revision --autogenerate -m "add pump priming"

Read the generated file before keeping it. SQLite cannot alter columns in place, so migrations use batch mode, which rebuilds the table.

There must be exactly one head. tests/api/test_migrations.py fails otherwise. If two branches each add a migration off the same parent, add a merge migration whose down_revision is a tuple of both heads:

bash
alembic merge -m "merge heads" <head_a> <head_b>

Never re-parent one of them instead, or a database already at that head skips the other migration.

Table creation on startup does not add columns to an existing table. A new column only reaches an existing controller through a migration.

Adding an endpoint ​

  1. Add the route to the router in app/endpoints/ for that area, or add a new router and register it in app/main.py.
  2. Add request and response schemas in app/schemas/.
  3. Add a test in tests/api/.
  4. Keep responses under 120 KB, or they cannot be returned over the remote path.