Skip to content

Commit 5413c98

Browse files
James Boultonclaude
andcommitted
SaF END and stored layouts, and device certificates (dash#49, #57, #29)
Store and forward: - set_saf_end_callback() and saf_end_timeout for the server's SAF END. - The server's CFG DASH request is answered with the C64 on the announce topic. - disconnect() publishes what the devices have already sent first. - The intermittent example waits for SAF END and the store sync. Device certificates (dash_docs ClientCertificates): - DeviceCertificates and Device(certificates=): states PASSWORD, PENDING and CERT, the first certificate from the server over the password, renewal in the last year, and the CRT messages with the app. - DashConnection logs in on cert_port (8885) as d-<device id>, checks a new certificate before using it, falls back to the password while PENDING, and erases the password on reaching CERT. - The DashIO Server CA is bundled. cryptography is a new dependency. Tested on dash.dashio.io: first issue, login without a password, revocation, recovery with a new Dash login, and renewal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cd12aa7 commit 5413c98

14 files changed

Lines changed: 1780 additions & 75 deletions

‎CLAUDE.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Notes for working on python-dashio, the Python library for the DashIO protocol a
99
- `dash_connection.py`: Dash server MQTT connection.
1010
- `dash_store.py`: `DashStore` (sqlite storage for TimeGraph, EventLog and Map data) and `SDUSession` (history upload to the Dash server).
1111
- `tcp_connection.py`, `zmq_connection.py`: the other connections.
12+
- `device_certificates.py`: `DeviceCertificates`, the device's key and certificate for logging in on port 8885, and `CertificateSession`.
1213
- `load_config.py`: `decode_cfg64`, `encode_cfg64`, `generate_cfg64`.
1314
- `iotcontrol/`: controls.
1415
- `utilities/`: the `c64_encode`, `c64_decode` and `dashio_data_exporter` commands.
@@ -78,6 +79,17 @@ Notes for working on python-dashio, the Python library for the DashIO protocol a
7879
- `SEC`: `\t<device_id>\tSEC\tKEY\t<key>`, stores a device key (BLE security).
7980
- `DATA`: `OTA` and `SDU` only.
8081
- **The Dash server is the source of truth for history.** For a control with `storage_enable()` (`Device._server_stored`), history requests are only answered when they come from a Dash server connection (`msg_from` starting `DASH:`), never over TCP, BLE or other local connections. Otherwise an app connected locally takes the device's history as complete and doesn't fetch the older history from the server. Live updates still go to every connection.
82+
- **Store and forward (SaF) on the Dash server** (dash_docs `StoreAndForward.md`, dash#49, dash#57), for devices with `store_and_forward` on:
83+
- After each WHO the server sends the held control messages, then `\t<device_id>\tSAF\tEND\n`, in one publish. `set_saf_end_callback()` is called with True on END, or False when it doesn't come within `saf_end_timeout` (5 s, as zephyr-dashio) of the WHO on a DashConnection. The wait is checked in `Device.run()`.
84+
- When the server doesn't keep the device's current layout, it asks with `\t<device_id>\tCFG\tDASH\t1\n`, before END. The device sends its usual C64 reply, always C64 and the 1 column layout, on the **announce** topic, not as a reply. `DASH` is never a dashboard ID.
85+
- `DashConnection.disconnect()` from another thread has the connection thread publish what's waiting in its zmq socket first, so a reply sent just before END isn't dropped by the planned disconnect.
86+
- **Device certificates** (dash_docs `ClientCertificates/DashIO_Client_Certificates.md`, dash#29), in `device_certificates.py`:
87+
- `DeviceCertificates(path)` is given to the Device (`certificates=`), which handles the CRT messages: REQUEST INFO/CSR and UPDATE from the app, over any connection, and SVR_CRT/ERR from the server. The device sends SVR_CSR and SVR_STATUS on announce (`CertificateSession`, polled in `Device.run()`, started by `connection_ready()` from the DashConnection's subscription).
88+
- States PASSWORD, PENDING and CERT, kept in `state.json` in the directory with `key.pem`, `cert.pem`, `ca.pem` (from the app's `caCert`), `new_key.pem` (an outstanding request's key) and `previous_*.pem` (a renewal not yet proven). Files are written 0600.
89+
- The DashConnection takes the certificate from its one device (a second device raises `ValueError`), and makes a new paho client when it changes login: client ID `d-<device_id>` and `tls_set_context` for port 8885, a random client ID for 8883, because the broker refuses `d-` client IDs on password logins.
90+
- A certificate not yet used to log in (PENDING, or a renewal) is checked first with a TLS handshake and a short read (`_check_certificate()`): with TLS 1.3 the broker refuses a client certificate with an alert after the handshake, which paho only reports as a lost connection. Refused: PENDING falls back to the password for an hour and reports 420; a renewal rolls back to the previous certificate. Unreachable: check again with backoff.
91+
- On the first certificate login the connection erases its password and `state_callback("CERT")` lets the program erase its copy. A new Dash login from the app (the DASHIO message, when the dashio callback accepts it) calls `reset()`: back to PASSWORD, keys deleted.
92+
- The DashIO Server CA is bundled as `dashio/certs/dashio-server-ca.crt` (package data). `cryptography` is a dependency.
8193
- **`DashStore` and history upload (SDU):** a port of the firmware's DashIO Storage Manager (`../zephyr-dashio-tally/port.md`, ESP-IDF port in `../dashesp/components/dashio_dsm`), using sqlite instead of a flash ring buffer.
8294
- `Device(..., store=DashStore(path))` gives every TimeGraph, EventLog and Map on the device the store (`control._store`). They record into it as well as their ring buffers, and answer the app's history requests from it.
8395
- The wire format follows `../dash_docs/DashIODataFormat/DashIO_Data_Updater.md` (the SDU section): the timestamp request (lines, then tracks, then logs), `%.6f` floats, `T`/`F` booleans, MAP values as strings without `time`, LOG `color` left out when empty, and the FNV-1a hash (`%016x`) over the JSON. The golden vectors are in `tests/test_dash_store.py`.

‎Examples/intermittent_connection.py‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
- Connect with DashConnection(auto_connect=False) and connect() on a schedule.
99
- Disconnect with disconnect() when the store has synced with the Dash server, using the store sync callback.
1010
The server is sent the data it missed, and the Dash app gets the history from the server.
11-
- Support store and forward (SAF), so the Dash app can turn it on for the device on the Dash server.
11+
- Support store and forward (SAF), so the Dash app can turn it on for the device on the Dash server. The server
12+
then keeps the app's messages for the device while it's disconnected, sends them when it connects, then SAF END.
13+
The logger also waits for SAF END, using the SAF END callback, before it disconnects.
1214
- Provision the device over an always on TCP connection on the local network, as an IoT device usually does
1315
over BLE: the Dash app gets the layout, sets the device name and the Dash server username and password, and
1416
sets the connection and record intervals in the device's provisioning menu.
@@ -87,6 +89,7 @@ def __init__(self, settings: Settings, store: dashio.DashStore, port: int):
8789
self.store = store
8890
self.lock = threading.Lock()
8991
self.disconnect_at = None # When connected, the time to disconnect.
92+
self.waiting_for = set() # What has to end before disconnecting: "store" and "saf".
9093
self.next_record = self.next_connect = time.monotonic()
9194

9295
self.device = dashio.Device("IntermittentLogger", settings.get("DEVICE", "device_id"), settings.get("DEVICE", "device_name"), store=store)
@@ -126,6 +129,7 @@ def __init__(self, settings: Settings, store: dashio.DashStore, port: int):
126129
self.dash = dashio.DashConnection(settings.get("DASH", "username"), settings.get("DASH", "password"), auto_connect=False)
127130
self.dash.add_device(self.device)
128131
self.device.set_store_sync_callback(self.synced)
132+
self.device.set_saf_end_callback(self.saf_ended)
129133
# The Dash server keeps the history, so the app gets it from the server. STE is sent when connected.
130134
self.device.storage_enable(dashio.ControlName.TGRPH, "graph")
131135
self.device.storage_enable(dashio.ControlName.LOG, "events")
@@ -183,8 +187,19 @@ def dashio_handler(self, msg) -> bool:
183187
def synced(self, completed: bool):
184188
"""Store sync callback, called on the device thread when the sync with the Dash server ends."""
185189
logging.info("Sync %s", "finished" if completed else "failed")
190+
self.finished("store")
191+
192+
def saf_ended(self, received: bool):
193+
"""SAF END callback, called on the device thread once the messages the server kept have arrived, or when
194+
SAF END doesn't come, e.g. store and forward isn't turned on for the device."""
195+
logging.info("Store and forward %s", "messages received" if received else "END didn't arrive")
196+
self.finished("saf")
197+
198+
def finished(self, part: str):
199+
"""Disconnect once the store has synced and the store and forward messages have arrived."""
186200
with self.lock:
187-
if self.disconnect_at is not None:
201+
self.waiting_for.discard(part)
202+
if self.disconnect_at is not None and not self.waiting_for:
188203
self.disconnect_at = time.monotonic()
189204

190205
def record(self):
@@ -199,6 +214,7 @@ def wake(self):
199214
self.events.add_event_data(dashio.EventData("Connecting", dashio.Color.GREEN))
200215
with self.lock:
201216
self.disconnect_at = time.monotonic() + SYNC_TIME_LIMIT
217+
self.waiting_for = {"store", "saf"}
202218
self.dash.connect()
203219

204220
def sleep(self):

‎dashio/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from .dash_connection import DashConnection
3737
from .dash_store import DashStore
3838
from .device import Device
39+
from .device_certificates import DeviceCertificates
3940
from .iotcontrol.alarm import Alarm
4041
from .iotcontrol.audio_visual_display import AudioVisualDisplay
4142
from .iotcontrol.button import Button
@@ -81,6 +82,7 @@
8182
'ZMQConnection',
8283
'DashConnection',
8384
'DashStore',
85+
'DeviceCertificates',
8486
'ConnectionState',
8587
'DashIOCommsModuleConnection',
8688
'Schedular',

‎dashio/certs/dashio-server-ca.crt‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIBnjCCAUOgAwIBAgIQbHBBOspCE/+BfHoq72pDVDAKBggqhkjOPQQDAjAsMQ8w
3+
DQYDVQQKDAZEYXNoSU8xGTAXBgNVBAMMEERhc2hJTyBTZXJ2ZXIgQ0EwIBcNMjYx
4+
MTA0MjA0MTE0WhgPMjA1MTExMDQyMDQxMTRaMCwxDzANBgNVBAoMBkRhc2hJTzEZ
5+
MBcGA1UEAwwQRGFzaElPIFNlcnZlciBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEH
6+
A0IABOOe2nAQyy70LliyaTwFeA3sZsRG7ovYPZnRmKpK6qgvO8Koz4yhikcrT6EC
7+
UAEMKz9BuH8L3Swoncz+RSe8vyOjRTBDMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYD
8+
VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBQVDGQQHqc4XzpzkZ9L5w0x7di+AzAKBggq
9+
hkjOPQQDAgNJADBGAiEAuC4HEjtz/GaVdfb6dgUEUP0tgG4p5qzARPE/wcZQfuYC
10+
IQDnuQ/28pC1EgmxGxRJA6yJzB56Ys7onrvwOCkEqiV+/w==
11+
-----END CERTIFICATE-----

0 commit comments

Comments
 (0)