Skip to content

Hardware Sensor Event Contract

This is the pre-hardware contract for ESP32 and other sensor devices. It is local documentation only; no device connection or actuator control is enabled by this contract.

Transport

MQTT topic:

pomona/{farm_id}/{zone_id}/sensor/{device_id}/state

The MQTT payload must be one JSON object matching schemas/sensor-event.schema.json. The same object can be submitted to POST /v1/sensors/events for HTTP testing.

Canonical payload

{
  "device_id": "esp32-greenhouse-01",
  "farm_id": "demo-farm",
  "zone_id": "greenhouse-a",
  "crop": "tomato",
  "growth_stage": "flowering",
  "system_type": "greenhouse_substrate",
  "air_temperature_c": 31.2,
  "humidity_pct": 88.0,
  "ec_ms_cm": 3.4,
  "ph": 7.5,
  "soil_moisture_pct": 42.0,
  "timestamp": "2026-07-21T10:00:00Z",
  "source": "esp32",
  "schema_version": "1.0"
}

Required: device_id, farm_id, zone_id, timestamp and at least one reading. crop, growth_stage and system_type are optional (Core fills tomato, flowering, greenhouse_substrate). The schema also lists the optional weather, zone_area_m2, crop_kc, npk_target (context for the model-router's calculations), sequence and boot_id (duplicate and stale-packet detection), source (at most 64 characters), and received_at / mqtt_retained, which Core sets itself and ignores from a sender. Properties the schema does not list are ignored, not rejected. services/core/tests/test_sensor_event_schema.py checks that the schema and Core accept and reject the same packets; a sample time too old or too far ahead is rejected by Core only (see below).

schema_version is the payload contract version, "MAJOR.MINOR" as a string. A packet without it is treated as "1.0", so older senders keep working. Core accepts any 1.x (minor versions only add optional fields) and rejects another major version, for example "2.0", with a validation error instead of storing it as if it were 1.x. The stored payload keeps the version, so old records stay readable after the contract changes. The same field applies to modular observations (POST /v1/sensors/observations).

A probe that did not report

A full packet may leave out any reading. When a probe fails, send the packet without its field or with null; Core stores it as null, never fills a default, and the model-router says "can't confirm" for that reading (missing_ec, ...) instead of showing a calm zone: the dashboard's sensor-trust line reads EC not reported in the latest reading, and the sensor_check alert is raised after 3 such readings in a row.

  • Reading fields are air_temperature_c, humidity_pct, ec_ms_cm, ph, soil_moisture_pct, substrate_temperature_c and substrate_moisture_pct. A packet needs at least one that is a number; {"ec_ms_cm": null} alone is refused (422). weather, npk_target, zone_area_m2 and crop_kc do not count.
  • NaN and Infinity stay refused (422). A probe library that returns NaN on a failed read must send null.
  • The schema version stays 1.0: every 1.x sender may send a partial packet. Behaviour change worth knowing: a firmware bug that drops a field used to get a 422 only the device log saw; now the grower sees the missing reading and a sensor_check alert.
  • One device per zone sending the full set of probes is the simplest case and behaves as always. Two or more devices in one zone (for example a climate node with air temperature and humidity, and a substrate node with pH, EC and moisture) are judged per device from the first live full packet of the second device on (docs/design/multi-device-zones.md, slice 1):
  • Each device's sensor checks run on its own history, so an offset between two probes of one field is not noise and a frozen probe is still "stuck".
  • Each device is expected to report only the fields it has reported in the last 7 days (retention_days), so no device gets missing_* for a probe it never had. Only finite numbers count, not null.
  • A probe that stops reporting stays expected for 7 days: missing_* and the sensor_check alert stay up that long, then the field is forgotten. In a multi-device zone a probe silent for 7 days is forgotten; remove it from the zone or fix it. A single-device zone keeps today's rule (missing until it reports).
  • A zone returns to single-device when the other device has sent no live full packet for 7 days. The remaining device must then carry everything the system type expects, or it gets missing_*. That is the first signal a node dead for a week gives: there is no whole-node silence alert.
  • A device that carries none of the expected fields gets today's behaviour; give such a device its own zone.
  • Only live full packets count: modular observations, retained MQTT messages and packets with a bad clock do not.
  • MULTI_DEVICE_ZONES=0 turns this off (every zone is judged as single-device).
  • A fast device in a shared zone shortens how far back a slow device's stored history reaches (retention is per zone).
  • Drift detection needs a second device. A slow drift of one probe (air temperature, humidity or substrate moisture) is caught while it lasts when another device in the same zone reports the same field and the probe itself reports at least every 5 minutes; Core then judges each probe against the others (the pair check, see SENSOR_QUALITY_REASONER.md). A probe is judged only when it reports at least every 5 minutes, and a partner's reading counts when it is earlier and recent enough for the judged probe (2.5 of that probe's intervals, 60 to 750 seconds), so give both probes the same cadence, 5 minutes or faster. A zone with one probe, or a probe that reports less often, keeps the old behaviour: a drift is noticed only when it ends. Substrate temperature drift is not covered. PAIR_CHECK=0 turns the pair check off.
    • One zone per shared air space. The check assumes the probes of a zone see the same weather. Probes in different rooms or different compartments must not share a zone_id, or their normal differences will be read as drift.
    • Retention is per zone, so two devices that share a zone each keep about half of MAX_EVENTS' history (three keep about a third); a 30-second probe and a 5-minute probe in one zone leave the slow one little.
    • Calibrate only the probe that was wrong. A calibration of the field on any device of the zone restarts the pair reference. If the good probe is calibrated while the other is still drifted, today's difference becomes the new normal. The check text says: check both with a meter, calibrate only the one that was wrong.
    • In a zone with only two probes it is close to a coin flip which one is flagged first, so the card may name the good probe. While the probes disagree, the zone view treats that field as "can't confirm": the air or humidity tile shows both values with "probes disagree: check both with a meter", and no advice uses either value.
  • The zone view (slice 2, docs/design/multi-device-zones-slice2.md): the dashboard builds one view of the zone from every device instead of showing the newest packet.
    • Each reading field comes from one device. Core's GET /v1/sensors/zone-snapshot uses only each device's latest packet, never an older one, so a probe that stopped reporting looks missing instead of showing an old value. Send every probe in each packet, because a packet that carries one probe leaves the device's others missing until they come round again.
    • Pair tiles: when two devices carry the same field (for example two air temperature probes), the tile shows one stable device (the one that first sent the field, skipping one whose own sensor check failed) and an also <device>: <value> line for the other, with (not used) when that probe failed its check.
    • Staleness is per device. A device leaves the zone view after the larger of ZONE_STALE_AFTER_S (default 10 min) and 3 times its own reporting interval (the median gap of its last 6 live packets), so a substrate node that reports every 15 min stays in until 45 min. A device that left is named in the trust line ("no reading from climate-1 for 15 min"). "No reading from this zone" appears only when every device is quiet. The dashboard's ZONE_STALE_AFTER_S=0 (demos, replays) turns the filter off.
    • Each device's own sensor check is carried in. Core keeps the data-quality labels and safe next checks behind each verdict, so a probe that is stuck on climate-1's own history shows as stuck_value and "not used" in the zone view. A device Core has not judged yet is judged by the dashboard (the trust line says "checked by the dashboard"; that check has no persistent stuck check).
    • Context (crop, growth_stage, system_type, weather, ...): the newest live device wins, schema defaults are dropped when another device sets a real value, and a disagreement is shown ("Devices disagree on growth_stage"). Send system_type and crop from every device that is not meant to use the defaults.
    • Alerts stay per device and gain a Device column and, for sensor-check alerts, the router's check text. A risk that needs fields from two devices (heat on the climate node together with low moisture on the substrate node) now reaches "Evaluate current risk" and the risk panels, but is still not raised as an alert: Core's feed evaluates each device alone.
  • Core's /v1/sensors/events, /v1/sensors/events/latest, /v1/sensors/export.csv and /v1/sensors/observations take an optional device_id filter; /v1/sensors/events also returns zone_multi_device and latest_device_fields.
  • A probe not fitted for the zone's system type (for example substrate moisture on a hydroponic zone) is not expected, so leaving it out raises nothing.

Boundary rules

Field Unit Accepted range
air_temperature_c Celsius -40 to 80
humidity_pct percent 0 to 100
ec_ms_cm mS/cm 0 to 20
ph pH scale 0 to 14
soil_moisture_pct percent 0 to 100

Supported deployment profiles are represented by system_type, for example soil, greenhouse_substrate, hydroponic, and aquaponic. The transport contract is shared, but each profile needs its own expected fields and rules.

timestamp (the sample time, with a timezone) is required: Core never stamps a packet with its own receipt time. Sample times before MIN_SAMPLE_TIME (default 2020-01-01T00:00:00Z) are rejected for full packets, observations and corrected observations, because an ESP32 without NTP reports 1970 and a dead RTC battery often 2000; check the device clock, NTP sync or RTC battery. Sample times more than MAX_FUTURE_SAMPLE_S (default 300 s, 0 disables) ahead of Core's clock are rejected too: a device or spreadsheet that writes local time but labels it Z lands hours ahead in UTC+ zones, so stamp local time with its UTC offset (+04:00) or convert to UTC. A sample time Core accepts counts as current (a clock a few minutes fast still shows); with the check off (0), only a sample time up to 60 s ahead does. Core stores and compares UTC only; FARM_TIMEZONE (shown on GET /health and the dashboard) is display only and converts no data. Stored rows are not re-checked.

Core rejects malformed packets and values outside these transport ranges. A value inside the transport range can still be agronomically suspicious; the Sensor Quality reasoner remains responsible for stale, conflicting, drift, or crop-specific checks.

Hardware safety boundary

Modular observation API (monitoring only)

Temperature-only nodes can use POST /v1/sensors/observations, or MQTT topic pomona/{farm_id}/{zone_id}/sensor/{device_id}/observation. The existing full-packet /state topic and /v1/sensors/events requirements are unchanged.

{
  "device_id": "temperature-node-01",
  "farm_id": "demo-farm",
  "zone_id": "greenhouse-a",
  "sensor_id": "air-temperature-01",
  "measurement": "air_temperature_c",
  "unit": "C",
  "value": 24.5,
  "quality": "valid",
  "timestamp": "2026-09-05T10:00:00Z",
  "sequence": 1,
  "boot_id": "boot-01",
  "firmware": "prototype-0.1"
}

Supported measurements are air/water temperature (C), humidity and soil moisture (%), pH (pH), EC (mS/cm), and low-level contact (boolean, 0/1). Contact polarity remains a device-specific convention, not an irrigation rule. Quality may be valid, missing, suspect, conflicting, or disconnected. Missing values must not be marked valid. Optional calibration_timestamp and sample timestamps require timezones. Quality/calibration are sender-reported, not evidence of validation; sequence/boot metadata are stored, not deduplicated. Core overwrites received_at with its own receipt time.

These records are not fused into reasoner inputs. No synthetic pH/EC values are filled in. A validated state-assembly policy is a later task.

Scoped history and device visibility

  • GET /v1/sensors/events and /events/latest accept farm_id and zone_id.
  • GET /v1/sensors/observations accepts the same filters, limit, and offset.
  • GET /v1/sensors/devices reports last receipt, sample age, and recent or silent (default threshold 120 seconds). This is inferred availability, not proof of connectivity. Old migrated records do not invent a last-seen time.
  • GET /v1/sensors/export.csv?kind=observations&farm_id=demo-farm&zone_id=greenhouse-a exports a bounded CSV; kind=events exports full packets. Maximum page size is 10,000; offset pages newest records first, chronological within a page. Pause ingestion for a consistent multi-page export: offsets can shift during writes or retention cleanup. Spreadsheet formula-like strings are escaped.

Retention defaults to seven days by server receipt time and at most 100,000 records per farm/zone per record type, whichever limit is reached first. Cleanup runs on ingest, not on a timer (the age limit at most once a minute). Configure RETENTION_DAYS, MAX_EVENTS, and DEVICE_TIMEOUT_SECONDS. Legacy rows without receipt times remain subject to the count limit; device last-seen metadata is retained separately. This is not a global disk quota: many zones/devices can increase storage usage. Back up SQLite before upgrading; the schema migration adds scope columns, observation/presence tables and a numeric sample-time column with indexes (the latest-reading queries read it), and the database file switches to write-ahead logging (-wal and -shm files beside it; copy it with scripts/backup.sh, not cp). No authentication change accompanies these APIs; keep the MVP on a trusted local network.

The dashboard accepts a farm/zone selection and displays device health plus 100-record history pages, with CSV download for the same selection and offset. Full-packet trend sparklines remain separate from the modular observation table; modular observations are not assembled into recommendations.

Command boundary

Sensor events are observation data only. They cannot authorize a pump, valve, fertigation, climate, pesticide, or diagnostic command. Proposed actions must go through the guarded pipeline and deterministic Safety Checker. Hardware integration must begin in dry-run mode with commands logged but not executed.