# Demeter IoT Device Protocols

How Demeter talks to sensors and actuators. The protocol layer lives in
[`@demeter/sensors`](../../../../libs/demeter/sensors/src/protocols.ts) and is
**protocol-agnostic**: every transport implements one `ProtocolAdapter`
interface, and every payload is normalised to a single `NormalizedReading` shape
before it reaches the rest of the platform.

## Supported protocols

`SUPPORTED_PROTOCOLS` catalogs each transport's characteristics (used by the UI
when guiding device setup):

| Protocol           | Range                           | Power      | Max devices | Data rate         |
| ------------------ | ------------------------------- | ---------- | ----------- | ----------------- |
| **MQTT**           | Unlimited (IP-based)            | Low–Medium | 1,000,000   | Network-dependent |
| **Zigbee**         | 10–100 m indoor / 300 m outdoor | Very low   | 65,000      | 250 kbps          |
| **Z-Wave**         | 30 m indoor / 100 m outdoor     | Very low   | 232         | 100 kbps          |
| **Matter**         | Varies (Thread/Wi-Fi/Ethernet)  | Low–Medium | 65,000      | Varies            |
| **Thread**         | 10–30 m/hop (mesh)              | Very low   | 250         | 250 kbps          |
| **Wi-Fi**          | 30–50 m indoor / 100 m outdoor  | High       | 253         | Up to 9.6 Gbps    |
| **BLE**            | 10–30 m indoor / 100 m outdoor  | Very low   | 20          | 2 Mbps            |
| **LoRa / LoRaWAN** | 2–15 km rural / 1–5 km urban    | Very low   | 10,000      | 0.3–50 kbps       |

For outdoor agricultural sensing LoRa is preferred (range + battery); for
in-home devices Zigbee/Thread/Matter; MQTT is the IP-level backbone everything
else bridges into.

## The adapter abstraction

Every transport implements `ProtocolAdapter` — `connect()`, `disconnect()`,
`subscribe(topic, cb)`, `publish(topic, payload)`, and a `protocol` name.
Factory functions build them: `createMQTTAdapter`, `createZigbeeAdapter`,
`createBLEAdapter`, `createLoRaAdapter`. `createProtocolBridge(a, b)` forwards
messages between two adapters (e.g. Zigbee → MQTT).

> **Dev vs production transport.** The bundled adapters provide **in-memory**
> pub/sub message routing — real and fully functional for local development,
> tests, and protocol-bridging logic, but not a network broker. In production,
> point the MQTT adapter at an external broker (e.g. Mosquitto/EMQX) and the
> Zigbee/BLE/LoRa adapters at their gateways; broker provisioning is part of the
> deployment infrastructure (§29.19).

## Topic convention (MQTT)

Topics follow a `garden / bed / sensor` hierarchy; `parseMQTTTopic` decodes it:

| Topic                          | Parsed as                                           |
| ------------------------------ | --------------------------------------------------- |
| `garden-1`                     | `{ garden: "garden-1" }`                            |
| `garden-1/bed-3`               | `{ garden, bed }`                                   |
| `garden-1/bed-3/soil-moisture` | `{ garden, bed, sensor }` (extra segments retained) |

## Payload format

The canonical reading shape is `NormalizedReading`:

```ts
{
  (sensorType, value, unit, timestamp /* Date */, metadata);
}
```

`formatMQTTPayload(reading)` serialises it to JSON (timestamp as ISO-8601,
metadata spread in). `parseSensorPayload(protocol, payload)` does the inverse,
handling each protocol's native conventions:

- **MQTT** — standard JSON with `sensorType` / `value` / `unit`.
- **Zigbee** — `zigbee2mqtt` JSON (`temperature`, `humidity`, `soil_moisture`,
  …) mapped onto sensor types.
- **BLE** — characteristic JSON.
- **LoRa** — compact JSON / decoded uplink.

Unknown or malformed payloads are rejected rather than silently coerced, so a
bad device can't poison the time-series.

## End-to-end flow

```
device → (protocol adapter, subscribe) → parseSensorPayload → NormalizedReading
       → @demeter/sensors readings/timeseries → POST /v1/sensors/:id/readings
       → demeter_sensor_readings (Postgres)
```

Calibration (`calibration.ts`) and alert thresholds
(`demeter_sensor_alert_configs`) are applied on top of the normalised stream.
For connecting **commercial** platforms (GARDENA, Rachio, Home Assistant, …) see
the [integration guide](../integrations/third-party-integrations.md).
