From 9820de539802a9bdece7ea75f0fffe21be37b22b Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 20:08:05 -0500 Subject: [PATCH 1/7] feat(api): say when an outside observer on a repeater has no claim at all claimed is false for a stale claim too, so it cannot tell a local mode observer from a foreign poller that went quiet. --- db/polling.go | 2 +- db/polling_foreign_integration_test.go | 6 ++++-- db/queries/polling.sql | 3 +++ db/sqlc/polling.sql.go | 5 +++++ docs/docs.go | 6 +++++- docs/swagger.json | 6 +++++- docs/swagger.yaml | 6 +++++- internal/api/node_telemetry.go | 6 ++++-- 8 files changed, 32 insertions(+), 8 deletions(-) diff --git a/db/polling.go b/db/polling.go index 684be4c5..0ae4f8b0 100644 --- a/db/polling.go +++ b/db/polling.go @@ -929,7 +929,7 @@ func (s *Store) GetNodePolling(ctx context.Context, nodeID uuid.UUID) (*api.Node } for _, f := range foreign { o := api.NodePollingForeign{ObserverID: f.ObserverID, Name: f.Name, Signed: f.Signed, - Claimed: f.Claimed, LatestReadingAt: epochMs(f.LatestReadingAt)} + Claimed: f.Claimed, Local: f.IsLocal, LatestReadingAt: epochMs(f.LatestReadingAt)} if f.PollHost != "" { h := f.PollHost o.PollHost = &h diff --git a/db/polling_foreign_integration_test.go b/db/polling_foreign_integration_test.go index 1385af42..6aaf3247 100644 --- a/db/polling_foreign_integration_test.go +++ b/db/polling_foreign_integration_test.go @@ -150,7 +150,8 @@ func TestPollingForeignClaimsPostgres(t *testing.T) { } for _, f := range view.Foreign { claimed := f.ObserverID == pollObserver(t, ctx, s, foreign.pub) - if f.Claimed != claimed || f.LatestReadingAt == nil || f.PollHost != nil || f.Signed { + // The one with no claim at all is local; a claim, even one naming other repeaters, is not. + if f.Claimed != claimed || f.Local == claimed || f.LatestReadingAt == nil || f.PollHost != nil || f.Signed { t.Errorf("foreign reporter: %+v", f) } } @@ -420,7 +421,8 @@ func TestPollingForeignClaimedIsPerTargetPostgres(t *testing.T) { w.claimVia(d, foreignOtherBroker, 2, reqNode(pollKey(0xA2), false, "ok")) for node, want := range map[uuid.UUID]bool{a: false, b: true} { v, err := s.GetNodePolling(ctx, node) - if err != nil || len(v.Foreign) != 1 || v.Foreign[0].Claimed != want { + // It has a claim, so it is never local, whichever repeaters the claim names. + if err != nil || len(v.Foreign) != 1 || v.Foreign[0].Claimed != want || v.Foreign[0].Local { t.Fatalf("claimed want %v: %+v %v", want, v.Foreign, err) } } diff --git a/db/queries/polling.sql b/db/queries/polling.sql index 68db3314..b400a019 100644 --- a/db/queries/polling.sql +++ b/db/queries/polling.sql @@ -99,6 +99,9 @@ SELECT o.id AS observer_id, (fc.observer_public_key IS NOT NULL AND EXISTS ( SELECT 1 FROM polling_foreign_targets ft WHERE ft.observer_public_key = k.observer_public_key AND ft.target_public_key = sqlc.arg(target_public_key)))::boolean AS claimed, + -- local is about the observer: no stored claim of either kind, live or not. + (NOT EXISTS (SELECT 1 FROM polling_foreign_claims a WHERE a.observer_public_key = k.observer_public_key) + AND NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = k.observer_public_key))::boolean AS is_local, (SELECT r.sampled_at FROM repeater_readings r WHERE r.target_public_key = sqlc.arg(target_public_key) AND r.observer_public_key = k.observer_public_key ORDER BY r.sampled_at DESC LIMIT 1)::timestamptz AS latest_reading_at diff --git a/db/sqlc/polling.sql.go b/db/sqlc/polling.sql.go index 7dcdc2f4..b8e8fbb8 100644 --- a/db/sqlc/polling.sql.go +++ b/db/sqlc/polling.sql.go @@ -716,6 +716,9 @@ SELECT o.id AS observer_id, (fc.observer_public_key IS NOT NULL AND EXISTS ( SELECT 1 FROM polling_foreign_targets ft WHERE ft.observer_public_key = k.observer_public_key AND ft.target_public_key = $1))::boolean AS claimed, + -- local is about the observer: no stored claim of either kind, live or not. + (NOT EXISTS (SELECT 1 FROM polling_foreign_claims a WHERE a.observer_public_key = k.observer_public_key) + AND NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = k.observer_public_key))::boolean AS is_local, (SELECT r.sampled_at FROM repeater_readings r WHERE r.target_public_key = $1 AND r.observer_public_key = k.observer_public_key ORDER BY r.sampled_at DESC LIMIT 1)::timestamptz AS latest_reading_at @@ -737,6 +740,7 @@ type ListForeignReportersRow struct { PollHost string `json:"poll_host"` Signed bool `json:"signed"` Claimed bool `json:"claimed"` + IsLocal bool `json:"is_local"` LatestReadingAt pgtype.Timestamptz `json:"latest_reading_at"` } @@ -757,6 +761,7 @@ func (q *Queries) ListForeignReporters(ctx context.Context, arg ListForeignRepor &i.PollHost, &i.Signed, &i.Claimed, + &i.IsLocal, &i.LatestReadingAt, ); err != nil { return nil, err diff --git a/docs/docs.go b/docs/docs.go index 81a74a18..0a90e368 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -9580,13 +9580,17 @@ const docTemplate = `{ "type": "object", "properties": { "claimed": { - "description": "Claimed is true when it has a live claim naming the node; false for one that only sends readings.", + "description": "Claimed is true when it has a live claim naming the node; false when its claim is stale or does not name it.", "type": "boolean" }, "latestReadingAt": { "description": "its newest reading of the node, epoch ms", "type": "integer" }, + "local": { + "description": "Local is true when it has no stored claim at all and only sends readings, as the firmware's local mode does.", + "type": "boolean" + }, "name": { "type": "string" }, diff --git a/docs/swagger.json b/docs/swagger.json index c80248a3..dafb4949 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -9578,13 +9578,17 @@ "type": "object", "properties": { "claimed": { - "description": "Claimed is true when it has a live claim naming the node; false for one that only sends readings.", + "description": "Claimed is true when it has a live claim naming the node; false when its claim is stale or does not name it.", "type": "boolean" }, "latestReadingAt": { "description": "its newest reading of the node, epoch ms", "type": "integer" }, + "local": { + "description": "Local is true when it has no stored claim at all and only sends readings, as the firmware's local mode does.", + "type": "boolean" + }, "name": { "type": "string" }, diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 56b22d93..39abcdd8 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1357,11 +1357,15 @@ definitions: properties: claimed: description: Claimed is true when it has a live claim naming the node; false - for one that only sends readings. + when its claim is stale or does not name it. type: boolean latestReadingAt: description: its newest reading of the node, epoch ms type: integer + local: + description: Local is true when it has no stored claim at all and only sends + readings, as the firmware's local mode does. + type: boolean name: type: string observerId: diff --git a/internal/api/node_telemetry.go b/internal/api/node_telemetry.go index 0ea6cad4..53cac006 100644 --- a/internal/api/node_telemetry.go +++ b/internal/api/node_telemetry.go @@ -317,8 +317,10 @@ type NodePollingForeign struct { PollHost *string `json:"pollHost"` // Signed is true when its claim carried a signature that checked out. Signed bool `json:"signed"` - // Claimed is true when it has a live claim naming the node; false for one that only sends readings. - Claimed bool `json:"claimed"` + // Claimed is true when it has a live claim naming the node; false when its claim is stale or does not name it. + Claimed bool `json:"claimed"` + // Local is true when it has no stored claim at all and only sends readings, as the firmware's local mode does. + Local bool `json:"local"` LatestReadingAt *int64 `json:"latestReadingAt"` // its newest reading of the node, epoch ms } From 1ddd1e862f3a1d7bef64be5cf602a996462ab3c2 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 20:42:14 -0500 Subject: [PATCH 2/7] feat(alerts): telemetry alerts for any repeater with fresh readings, and a telemetry stopped alert A repeater read by a poller this server does not assign now counts as polled while a trusted reading is under 36 hours old. gone_quiet takes 3 and 6 hours on every radio. --- db/alerts.go | 7 +- db/alerts_eval.go | 4 +- db/alerts_eval_integration_test.go | 4 +- db/alerts_final_integration_test.go | 86 +++++++++++++++++++ db/migrations/096_alert_telemetry_stopped.sql | 8 ++ db/queries/alerts.sql | 8 +- db/queries/alerts_eval.sql | 17 +++- db/sqlc/alerts.sql.go | 20 +++-- db/sqlc/alerts_eval.sql.go | 26 ++++-- db/sqlc/querier.go | 3 +- docs/docs.go | 3 +- docs/swagger.json | 3 +- docs/swagger.yaml | 7 +- internal/alerts/evaluate.go | 16 ++++ internal/alerts/evaluate_test.go | 29 +++++++ internal/alerts/kinds.go | 45 ++++++---- internal/alerts/kinds_test.go | 39 +++++++-- internal/alerts/outbox_test.go | 2 + internal/alerts/text.go | 2 + internal/api/alerts.go | 10 +-- 20 files changed, 282 insertions(+), 57 deletions(-) create mode 100644 db/migrations/096_alert_telemetry_stopped.sql diff --git a/db/alerts.go b/db/alerts.go index 1706b28a..597857f6 100644 --- a/db/alerts.go +++ b/db/alerts.go @@ -49,8 +49,9 @@ type radioCaps struct { func loadRadioCaps(ctx context.Context, q sqlc.Querier, keys [][]byte, now time.Time, pollingOn bool) (radioCaps, error) { since := ts(now.Add(-alerts.DataWindow * time.Second)) fresh := ts(now.Add(-alerts.ObserverFresh)) + nodeFresh := ts(now.Add(-alerts.NodeFresh)) rc := radioCaps{node: map[string]sqlc.AlertNodeCapsRow{}, observer: map[string]sqlc.AlertObserverCapsRow{}} - nodes, err := q.AlertNodeCaps(ctx, sqlc.AlertNodeCapsParams{Since: since, Keys: keys, PollingEnabled: pollingOn}) + nodes, err := q.AlertNodeCaps(ctx, sqlc.AlertNodeCapsParams{Since: since, FreshSince: nodeFresh, Keys: keys, PollingEnabled: pollingOn}) if err != nil { return rc, err } @@ -74,11 +75,11 @@ func (rc radioCaps) pick(key, want string) (id uuid.UUID, kind string, c alerts. n, isNode := rc.node[key] o, isObs := rc.observer[key] // What a radio reports only counts while it has a current source (the same test the evaluation applies). - nodeCaps := alerts.Caps{HasNode: true, NodeType: n.NodeType, Polled: n.Polled, Battery: n.Polled && n.HasBattery, + nodeCaps := alerts.Caps{HasNode: true, NodeType: n.NodeType, Polled: n.Polled, NodePolled: n.Polled, Battery: n.Polled && n.HasBattery, Temperature: n.Polled && n.HasTemperature, Noise: n.Polled && n.HasNoise, Uptime: n.Polled && n.HasUptime} obsCaps := alerts.Caps{Observer: true, Polled: o.Polled, Battery: o.Polled && o.HasBattery, Noise: o.Polled && o.HasNoise, Uptime: o.Polled && o.HasUptime} if isNode && isObs { - c = alerts.Caps{Observer: true, HasNode: true, NodeType: n.NodeType, Polled: n.Polled || o.Polled, + c = alerts.Caps{Observer: true, HasNode: true, NodeType: n.NodeType, Polled: n.Polled || o.Polled, NodePolled: n.Polled, Battery: nodeCaps.Battery || obsCaps.Battery, Temperature: nodeCaps.Temperature, Noise: nodeCaps.Noise || obsCaps.Noise, Uptime: nodeCaps.Uptime || obsCaps.Uptime, ObsBattery: obsCaps.Battery, ObsNoise: obsCaps.Noise, ObsUptime: obsCaps.Uptime} if want == alerts.TargetObserver { diff --git a/db/alerts_eval.go b/db/alerts_eval.go index 47f05872..216e37f8 100644 --- a/db/alerts_eval.go +++ b/db/alerts_eval.go @@ -150,13 +150,13 @@ func (a AlertEval) LoadTargets(ctx context.Context, rules []alerts.RuleRow, now since := ts(now.Add(-alerts.DataWindow * time.Second)) if len(nodeKeys) > 0 { - nodes, err := a.q.AlertNodesData(ctx, sqlc.AlertNodesDataParams{Keys: nodeKeys, PollingEnabled: !a.pollingOff.Load()}) + nodes, err := a.q.AlertNodesData(ctx, sqlc.AlertNodesDataParams{Keys: nodeKeys, PollingEnabled: !a.pollingOff.Load(), FreshSince: ts(now.Add(-alerts.NodeFresh))}) if err != nil { return nil, err } for _, n := range nodes { td := alerts.TargetData{Name: n.Name} - td.Exists, td.Polled, td.LastHeard = true, n.Polled, tsTime(n.LastSeen) + td.Exists, td.Polled, td.LastHeard, td.LastReading = true, n.Polled, tsTime(n.LastSeen), tsTime(n.LastReadingAt) out[alerts.TargetID(alerts.TargetNode, n.PublicKey)] = td } reads, err := a.q.AlertNodeReadings(ctx, sqlc.AlertNodeReadingsParams{Keys: nodeKeys, Since: since}) diff --git a/db/alerts_eval_integration_test.go b/db/alerts_eval_integration_test.go index 9dc6945b..698f0664 100644 --- a/db/alerts_eval_integration_test.go +++ b/db/alerts_eval_integration_test.go @@ -686,8 +686,8 @@ func ruleStateOf(t *testing.T, ctx context.Context, pool interface { return st } -// Readings from days ago do not make a radio polled: it needs a polling assignment (a repeater) or fresh status -// telemetry (an observer). The overview's flag and the evaluation use the same answer. +// Readings from days ago do not make a radio polled: it needs a polling assignment or a fresh reading (a repeater) +// or fresh status telemetry (an observer). The overview's flag and the evaluation use the same answer. func TestAlertPolledNeedsACurrentSourcePostgres(t *testing.T) { ctx, pool, s := userStore(t) svc := alertSvc(s) diff --git a/db/alerts_final_integration_test.go b/db/alerts_final_integration_test.go index dd797e94..01580eea 100644 --- a/db/alerts_final_integration_test.go +++ b/db/alerts_final_integration_test.go @@ -4,6 +4,7 @@ package db import ( + "slices" "strings" "testing" "time" @@ -83,6 +84,91 @@ func TestAlertClockBreachBetweenPassesPostgres(t *testing.T) { } } +// A repeater nobody is assigned to, read by a poller this server does not manage: its trusted readings offer the +// telemetry kinds and their rules are judged. When the readings stop, telemetry_stopped fires and keeps firing. +func TestAlertTelemetryWithoutAssignmentPostgres(t *testing.T) { + ctx, pool, s := userStore(t) + svc := alertSvc(s) + u := newUser(t, ctx, s, "alice") + rep, silent := atlasKey(1), atlasKey(2) + insertNode(t, ctx, s, rep, 2, "Hilltop") + insertNode(t, ctx, s, silent, 2, "Valley") + insertReading(t, ctx, s, rep, time.Now().Add(-4*time.Hour), 3000, nil) + insertReading(t, ctx, s, rep, time.Now().Add(-5*time.Hour), 3000, nil) + pinAtlas(t, ctx, s, u, 0, api.StoredPin{Kind: "node", Key: rep}, api.StoredPin{Kind: "node", Key: silent}) + ov, err := svc.Overview(ctx, u.ID) + if err != nil || len(ov.Targets) != 2 { + t.Fatalf("%+v %v", ov, err) + } + if got := ov.Targets[0]; !got.Caps.Polled || !slices.Contains(got.Available, "battery_low") || !slices.Contains(got.Available, "telemetry_stopped") { + t.Fatalf("a repeater with readings and no assignment: %+v", got) + } + if got := ov.Targets[1]; got.Caps.Polled || got.UnavailableCodes["battery_low"] != alerts.CodeNotPolled || got.UnavailableCodes["telemetry_stopped"] != alerts.CodeNotPolled { + t.Fatalf("a repeater with no readings: %+v", got) + } + // Any repeater takes the short gone_quiet windows. + if _, err := svc.PutRule(ctx, u.ID, alerts.RuleInput{TargetKind: "node", PublicKey: silent, Kind: "gone_quiet", Threshold: ipp(3), Enabled: true}); err != nil { + t.Fatalf("gone_quiet 3 on an unpolled repeater: %v", err) + } + for kind, th := range map[string]int{"battery_low": 3500, "telemetry_stopped": 6} { + if _, err := svc.PutRule(ctx, u.ID, alerts.RuleInput{TargetKind: "node", PublicKey: rep, Kind: kind, Threshold: ipp(th), Enabled: true}); err != nil { + t.Fatalf("%s: %v", kind, err) + } + } + task := alerts.NewTask(AlertEval{s}, time.Now) + run := func() { + t.Helper() + if err := task.Run(ctx); err != nil { + t.Fatal(err) + } + } + run() + if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "firing" { + t.Fatalf("battery_low without an assignment: %s", got) + } + if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" { + t.Fatalf("telemetry_stopped with a reading 4 hours old and a 6 hour limit: %s", got) + } + // The rule was set now, with the last reading 4 hours old: the clock starts at the rule, not in the past. + if _, err := pool.Exec(ctx, `UPDATE user_alert_rules SET cursor_at = now() - interval '3 hours' WHERE kind = 'telemetry_stopped'`); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET sampled_at = sampled_at - interval '3 hours' WHERE target_public_key = $1`, rep); err != nil { + t.Fatal(err) + } + run() + if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" { + t.Fatalf("telemetry_stopped 3 hours after it was set: %s", got) + } + // A month on there is no current source, so the battery rule is inactive, and the stopped rule fires. + if _, err := pool.Exec(ctx, `UPDATE user_alert_rules SET cursor_at = cursor_at - interval '30 days' WHERE kind = 'telemetry_stopped'`); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET sampled_at = sampled_at - interval '30 days', received_at = received_at - interval '30 days' WHERE target_public_key = $1`, rep); err != nil { + t.Fatal(err) + } + run() + if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "firing" { + t.Fatalf("telemetry_stopped a month after the last reading: %s", got) + } + if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "inactive" { + t.Fatalf("battery_low with no current source: %s", got) + } + // Retention deletes the readings; the rule remembers when the last one was and keeps firing. + if _, err := pool.Exec(ctx, `DELETE FROM repeater_readings WHERE target_public_key = $1`, rep); err != nil { + t.Fatal(err) + } + run() + if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "firing" { + t.Fatalf("telemetry_stopped after retention deleted the readings: %s", got) + } + insertReading(t, ctx, s, rep, time.Now().Add(-time.Minute), 4000, nil) + run() + if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" { + t.Fatalf("telemetry_stopped after a new reading: %s", got) + } +} + // With polling switched off the assignment rows that remain are no current source: repeater telemetry kinds are // unavailable (not_polled) and their rules read inactive. Observer status alerts do not depend on it. func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) { diff --git a/db/migrations/096_alert_telemetry_stopped.sql b/db/migrations/096_alert_telemetry_stopped.sql new file mode 100644 index 00000000..98e4a3a1 --- /dev/null +++ b/db/migrations/096_alert_telemetry_stopped.sql @@ -0,0 +1,8 @@ +-- Copyright 2026 Beacon Contributors +-- SPDX-License-Identifier: AGPL-3.0-or-later + +-- A rule kind for a repeater whose readings stopped arriving. +ALTER TABLE user_alert_rules DROP CONSTRAINT IF EXISTS user_alert_rules_kind_check; +ALTER TABLE user_alert_rules ADD CONSTRAINT user_alert_rules_kind_check + CHECK (kind IN ('gone_quiet', 'back_online', 'telemetry_stopped', 'battery_low', 'battery_falling', 'rebooted', + 'temperature', 'noise_high', 'clock', 'observer_offline')); diff --git a/db/queries/alerts.sql b/db/queries/alerts.sql index cd6ce74b..96f0feb7 100644 --- a/db/queries/alerts.sql +++ b/db/queries/alerts.sql @@ -84,8 +84,12 @@ SELECT n.id, n.public_key, n.node_type, COALESCE(n.name, '')::text AS name, COALESCE(c.readings, 0)::int AS readings, COALESCE(c.battery, false)::boolean AS has_battery, COALESCE(c.temperature, false)::boolean AS has_temperature, COALESCE(c.noise, false)::boolean AS has_noise, COALESCE(c.uptime, false)::boolean AS has_uptime, - -- Polled is a current source, not history: some observer holds the repeater as a polling assignment, and polling is on. - (sqlc.arg(polling_enabled)::boolean AND EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key))::boolean AS polled + -- Polled is a current source, not history, while polling is on: some observer holds the repeater as a polling + -- assignment, or a trusted reading of it was taken since fresh_since (a poller this server does not assign). + (sqlc.arg(polling_enabled)::boolean AND ( + EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key) + OR EXISTS (SELECT 1 FROM repeater_readings f WHERE f.target_public_key = n.public_key AND f.trusted + AND f.sampled_at >= sqlc.arg(fresh_since))))::boolean AS polled FROM nodes n LEFT JOIN LATERAL ( SELECT count(*) AS readings, bool_or(r.battery_mv IS NOT NULL) AS battery, bool_or(r.temperature_c IS NOT NULL) AS temperature, diff --git a/db/queries/alerts_eval.sql b/db/queries/alerts_eval.sql index 5f3632cb..78b30ba4 100644 --- a/db/queries/alerts_eval.sql +++ b/db/queries/alerts_eval.sql @@ -25,10 +25,19 @@ ORDER BY r.id LIMIT sqlc.arg(row_limit); -- name: AlertNodesData :many --- polled is the same test as the overview's (AlertNodeCaps): a current polling assignment while polling is on. -SELECT public_key, COALESCE(name, '')::text AS name, last_seen, last_advert_at, device_clock_drift_seconds, prev_clock_drift_seconds, - (sqlc.arg(polling_enabled)::boolean AND EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = nodes.public_key))::boolean AS polled -FROM nodes WHERE public_key = ANY(sqlc.arg(keys)::bytea[]); +-- polled is the same test as the overview's (AlertNodeCaps): while polling is on, a polling assignment or a trusted +-- reading since fresh_since. last_reading_at is the newest trusted reading of any age. +SELECT n.public_key, COALESCE(n.name, '')::text AS name, n.last_seen, n.last_advert_at, n.device_clock_drift_seconds, n.prev_clock_drift_seconds, + (sqlc.arg(polling_enabled)::boolean AND (COALESCE(l.sampled_at >= sqlc.arg(fresh_since)::timestamptz, false) + OR EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key)))::boolean AS polled, + l.sampled_at AS last_reading_at +FROM nodes n +LEFT JOIN LATERAL ( + SELECT r.sampled_at FROM repeater_readings r + WHERE r.target_public_key = n.public_key AND r.trusted + ORDER BY r.sampled_at DESC LIMIT 1 +) l ON true +WHERE n.public_key = ANY(sqlc.arg(keys)::bytea[]); -- name: AlertObserversData :many -- polled is the same test as the overview's (AlertObserverCaps): status telemetry within fresh_since. diff --git a/db/sqlc/alerts.sql.go b/db/sqlc/alerts.sql.go index 96fe1b08..29627870 100644 --- a/db/sqlc/alerts.sql.go +++ b/db/sqlc/alerts.sql.go @@ -17,20 +17,25 @@ SELECT n.id, n.public_key, n.node_type, COALESCE(n.name, '')::text AS name, COALESCE(c.readings, 0)::int AS readings, COALESCE(c.battery, false)::boolean AS has_battery, COALESCE(c.temperature, false)::boolean AS has_temperature, COALESCE(c.noise, false)::boolean AS has_noise, COALESCE(c.uptime, false)::boolean AS has_uptime, - -- Polled is a current source, not history: some observer holds the repeater as a polling assignment, and polling is on. - ($1::boolean AND EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key))::boolean AS polled + -- Polled is a current source, not history, while polling is on: some observer holds the repeater as a polling + -- assignment, or a trusted reading of it was taken since fresh_since (a poller this server does not assign). + ($1::boolean AND ( + EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key) + OR EXISTS (SELECT 1 FROM repeater_readings f WHERE f.target_public_key = n.public_key AND f.trusted + AND f.sampled_at >= $2)))::boolean AS polled FROM nodes n LEFT JOIN LATERAL ( SELECT count(*) AS readings, bool_or(r.battery_mv IS NOT NULL) AS battery, bool_or(r.temperature_c IS NOT NULL) AS temperature, bool_or(r.noise_floor IS NOT NULL) AS noise, bool_or(r.uptime_secs IS NOT NULL) AS uptime FROM repeater_readings r - WHERE r.target_public_key = n.public_key AND r.trusted AND r.sampled_at >= $2 + WHERE r.target_public_key = n.public_key AND r.trusted AND r.sampled_at >= $3 ) c ON true -WHERE n.public_key = ANY($3::bytea[]) +WHERE n.public_key = ANY($4::bytea[]) ` type AlertNodeCapsParams struct { PollingEnabled bool `json:"polling_enabled"` + FreshSince pgtype.Timestamptz `json:"fresh_since"` Since pgtype.Timestamptz `json:"since"` Keys [][]byte `json:"keys"` } @@ -50,7 +55,12 @@ type AlertNodeCapsRow struct { // What each of the nodes is and what a polled one reports, over the readings since the cutoff. func (q *Queries) AlertNodeCaps(ctx context.Context, arg AlertNodeCapsParams) ([]AlertNodeCapsRow, error) { - rows, err := q.db.Query(ctx, alertNodeCaps, arg.PollingEnabled, arg.Since, arg.Keys) + rows, err := q.db.Query(ctx, alertNodeCaps, + arg.PollingEnabled, + arg.FreshSince, + arg.Since, + arg.Keys, + ) if err != nil { return nil, err } diff --git a/db/sqlc/alerts_eval.sql.go b/db/sqlc/alerts_eval.sql.go index 4c15fa22..fa5e5122 100644 --- a/db/sqlc/alerts_eval.sql.go +++ b/db/sqlc/alerts_eval.sql.go @@ -210,14 +210,23 @@ func (q *Queries) AlertNodeUptimes(ctx context.Context, arg AlertNodeUptimesPara } const alertNodesData = `-- name: AlertNodesData :many -SELECT public_key, COALESCE(name, '')::text AS name, last_seen, last_advert_at, device_clock_drift_seconds, prev_clock_drift_seconds, - ($1::boolean AND EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = nodes.public_key))::boolean AS polled -FROM nodes WHERE public_key = ANY($2::bytea[]) +SELECT n.public_key, COALESCE(n.name, '')::text AS name, n.last_seen, n.last_advert_at, n.device_clock_drift_seconds, n.prev_clock_drift_seconds, + ($1::boolean AND (COALESCE(l.sampled_at >= $2::timestamptz, false) + OR EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key)))::boolean AS polled, + l.sampled_at AS last_reading_at +FROM nodes n +LEFT JOIN LATERAL ( + SELECT r.sampled_at FROM repeater_readings r + WHERE r.target_public_key = n.public_key AND r.trusted + ORDER BY r.sampled_at DESC LIMIT 1 +) l ON true +WHERE n.public_key = ANY($3::bytea[]) ` type AlertNodesDataParams struct { - PollingEnabled bool `json:"polling_enabled"` - Keys [][]byte `json:"keys"` + PollingEnabled bool `json:"polling_enabled"` + FreshSince pgtype.Timestamptz `json:"fresh_since"` + Keys [][]byte `json:"keys"` } type AlertNodesDataRow struct { @@ -228,11 +237,13 @@ type AlertNodesDataRow struct { DeviceClockDriftSeconds *int64 `json:"device_clock_drift_seconds"` PrevClockDriftSeconds *int64 `json:"prev_clock_drift_seconds"` Polled bool `json:"polled"` + LastReadingAt pgtype.Timestamptz `json:"last_reading_at"` } -// polled is the same test as the overview's (AlertNodeCaps): a current polling assignment while polling is on. +// polled is the same test as the overview's (AlertNodeCaps): while polling is on, a polling assignment or a trusted +// reading since fresh_since. last_reading_at is the newest trusted reading of any age. func (q *Queries) AlertNodesData(ctx context.Context, arg AlertNodesDataParams) ([]AlertNodesDataRow, error) { - rows, err := q.db.Query(ctx, alertNodesData, arg.PollingEnabled, arg.Keys) + rows, err := q.db.Query(ctx, alertNodesData, arg.PollingEnabled, arg.FreshSince, arg.Keys) if err != nil { return nil, err } @@ -248,6 +259,7 @@ func (q *Queries) AlertNodesData(ctx context.Context, arg AlertNodesDataParams) &i.DeviceClockDriftSeconds, &i.PrevClockDriftSeconds, &i.Polled, + &i.LastReadingAt, ); err != nil { return nil, err } diff --git a/db/sqlc/querier.go b/db/sqlc/querier.go index 96bb9387..45527369 100644 --- a/db/sqlc/querier.go +++ b/db/sqlc/querier.go @@ -39,7 +39,8 @@ type Querier interface { // For each repeater and the cursor of its reboot rule: the newest trusted uptime reading at or before the cursor (the // baseline), then the oldest page_size readings after it, so every reading since the cursor is reached page by page. AlertNodeUptimes(ctx context.Context, arg AlertNodeUptimesParams) ([]AlertNodeUptimesRow, error) - // polled is the same test as the overview's (AlertNodeCaps): a current polling assignment while polling is on. + // polled is the same test as the overview's (AlertNodeCaps): while polling is on, a polling assignment or a trusted + // reading since fresh_since. last_reading_at is the newest trusted reading of any age. AlertNodesData(ctx context.Context, arg AlertNodesDataParams) ([]AlertNodesDataRow, error) AlertObserverCaps(ctx context.Context, arg AlertObserverCapsParams) ([]AlertObserverCapsRow, error) AlertObserverDayAgo(ctx context.Context, arg AlertObserverDayAgoParams) ([]AlertObserverDayAgoRow, error) diff --git a/docs/docs.go b/docs/docs.go index 0a90e368..a7e1d30b 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -8022,6 +8022,7 @@ const docTemplate = `{ "enum": [ "gone_quiet", "back_online", + "telemetry_stopped", "clock", "battery_low", "battery_falling", @@ -8083,7 +8084,7 @@ const docTemplate = `{ "example": "Hilltop" }, "polled": { - "description": "Polled: the radio has a current source: a repeater is assigned to an observer that polls it, an observer has sent\nstatus telemetry in the last day. Old readings alone do not count. It is what offers the telemetry kinds and the 3 and 6 hour\ngone_quiet thresholds for a repeater (observers always have those).", + "description": "Polled: the radio has a current source: a repeater is assigned to an observer that polls it or has a trusted\nreading from the last 36 hours, an observer has sent status telemetry in the last day. Older readings alone do\nnot count. It is what offers the telemetry kinds.", "type": "boolean" }, "publicKey": { diff --git a/docs/swagger.json b/docs/swagger.json index dafb4949..7cd68f9d 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -8020,6 +8020,7 @@ "enum": [ "gone_quiet", "back_online", + "telemetry_stopped", "clock", "battery_low", "battery_falling", @@ -8081,7 +8082,7 @@ "example": "Hilltop" }, "polled": { - "description": "Polled: the radio has a current source: a repeater is assigned to an observer that polls it, an observer has sent\nstatus telemetry in the last day. Old readings alone do not count. It is what offers the telemetry kinds and the 3 and 6 hour\ngone_quiet thresholds for a repeater (observers always have those).", + "description": "Polled: the radio has a current source: a repeater is assigned to an observer that polls it or has a trusted\nreading from the last 36 hours, an observer has sent status telemetry in the last day. Older readings alone do\nnot count. It is what offers the telemetry kinds.", "type": "boolean" }, "publicKey": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 39abcdd8..d8788e6e 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -217,6 +217,7 @@ definitions: enum: - gone_quiet - back_online + - telemetry_stopped - clock - battery_low - battery_falling @@ -265,9 +266,9 @@ definitions: type: string polled: description: |- - Polled: the radio has a current source: a repeater is assigned to an observer that polls it, an observer has sent - status telemetry in the last day. Old readings alone do not count. It is what offers the telemetry kinds and the 3 and 6 hour - gone_quiet thresholds for a repeater (observers always have those). + Polled: the radio has a current source: a repeater is assigned to an observer that polls it or has a trusted + reading from the last 36 hours, an observer has sent status telemetry in the last day. Older readings alone do + not count. It is what offers the telemetry kinds. type: boolean publicKey: type: string diff --git a/internal/alerts/evaluate.go b/internal/alerts/evaluate.go index fdf3148c..197ed4c9 100644 --- a/internal/alerts/evaluate.go +++ b/internal/alerts/evaluate.go @@ -66,6 +66,8 @@ type Data struct { LastHeard time.Time // StatusAt is the observer's last status report. StatusAt time.Time + // LastReading is the repeater's newest trusted reading still stored, of any age; zero when there is none. + LastReading time.Time // Readings are the newest first. Readings []Reading // Uptimes are the uptime readings a reboot rule judges, newest first: the one before its cursor (the baseline) @@ -133,6 +135,20 @@ func Evaluate(r Rule, d Data) Outcome { } quiet := d.Now.Sub(d.StatusAt) out = set(r.Threshold != nil && quiet >= time.Duration(*r.Threshold)*time.Minute, int64(quiet/time.Minute)) + case KindTelemetryStop: + // The clock runs from the newest reading or from when the rule was set, whichever is later. The cursor keeps + // that time, so the rule still fires after retention has deleted the last reading. + if !d.Exists { + return inactive() + } + if d.LastReading.After(o.Cursor) { + o.Cursor = d.LastReading + } + if o.Cursor.IsZero() { + return inactive() + } + quiet := d.Now.Sub(o.Cursor) + out = set(r.Threshold != nil && quiet >= time.Duration(*r.Threshold)*time.Hour, int64(quiet/time.Hour)) case KindBatteryLow: if !d.Exists || !d.Polled { return inactive() diff --git a/internal/alerts/evaluate_test.go b/internal/alerts/evaluate_test.go index 21bee75d..5f0014e1 100644 --- a/internal/alerts/evaluate_test.go +++ b/internal/alerts/evaluate_test.go @@ -71,6 +71,35 @@ func TestEvaluateGoneQuiet(t *testing.T) { func (d Data) withNow() Data { d.Now = now; return d } +func TestEvaluateTelemetryStopped(t *testing.T) { + th := 6 + rule := func(st State, set time.Duration) Rule { + return Rule{Kind: KindTelemetryStop, Threshold: &th, State: st, Cursor: ago(set)} + } + read := func(d time.Duration) Data { return Data{Exists: true, LastReading: ago(d)} } + run(t, []step{ + {"readings arriving", rule(StateUnknown, 48*time.Hour), read(time.Hour), StateOK, false, 0}, + {"stopped at the threshold", rule(StateOK, 48*time.Hour), read(6 * time.Hour), StateFiring, true, 6}, + {"still stopped, said once", rule(StateFiring, 48*time.Hour), read(9 * time.Hour), StateFiring, false, 0}, + {"stopped for a month", rule(StateFiring, 60*24*time.Hour), read(30 * 24 * time.Hour), StateFiring, false, 0}, + {"a reading clears it", rule(StateFiring, 48*time.Hour), read(time.Minute), StateOK, false, 0}, + // Set an hour ago on a repeater silent for a day: no alert about the past, the clock starts at the rule. + {"set after the readings stopped", rule(StateUnknown, time.Hour), read(24 * time.Hour), StateOK, false, 0}, + {"and fires once the rule is that old", rule(StateOK, 7*time.Hour), read(24 * time.Hour), StateFiring, true, 7}, + // Retention deleted the last reading: the cursor still holds its time. + {"last reading deleted", rule(StateFiring, 9*time.Hour), Data{Exists: true}, StateFiring, false, 0}, + {"deleted before it fired", rule(StateOK, 9*time.Hour), Data{Exists: true}, StateFiring, true, 9}, + {"node gone", rule(StateOK, 9*time.Hour), Data{LastReading: ago(time.Hour)}, StateInactive, false, 0}, + }) + // The newest reading moves the cursor, and nothing moves it back. + if got := Evaluate(rule(StateOK, 48*time.Hour), Data{Now: now, Exists: true, LastReading: ago(time.Hour)}); !got.Cursor.Equal(ago(time.Hour)) { + t.Fatalf("cursor %v", got.Cursor) + } + if got := Evaluate(rule(StateOK, time.Hour), Data{Now: now, Exists: true, LastReading: ago(5 * time.Hour)}); !got.Cursor.Equal(ago(time.Hour)) { + t.Fatalf("cursor went back: %v", got.Cursor) + } +} + func TestEvaluateObserverOffline(t *testing.T) { r := func(st State) Rule { return Rule{Kind: KindObserverOff, Threshold: ip(60), State: st} } d := func(quiet time.Duration) Data { return Data{Exists: true, StatusAt: ago(quiet)} } diff --git a/internal/alerts/kinds.go b/internal/alerts/kinds.go index 354abe07..f771b9b2 100644 --- a/internal/alerts/kinds.go +++ b/internal/alerts/kinds.go @@ -15,6 +15,7 @@ import ( const ( KindGoneQuiet = "gone_quiet" KindBackOnline = "back_online" + KindTelemetryStop = "telemetry_stopped" KindClock = "clock" KindBatteryLow = "battery_low" KindBatteryFalling = "battery_falling" @@ -27,7 +28,7 @@ const ( ) // Kinds is every stored rule kind in display order. -var Kinds = []string{KindGoneQuiet, KindBackOnline, KindClock, KindBatteryLow, KindBatteryFalling, KindRebooted, +var Kinds = []string{KindGoneQuiet, KindBackOnline, KindTelemetryStop, KindClock, KindBatteryLow, KindBatteryFalling, KindRebooted, KindTemperature, KindNoiseHigh, KindObserverOff} // Target kinds. @@ -45,6 +46,10 @@ const ( // whether the radio is polled. const DataWindow = 14 * 24 * 3600 +// NodeFresh is how recent a repeater's newest trusted reading must be for it to count as a current source when no +// observer holds it as a polling assignment. Pollers may take a reading only once a day. +const NodeFresh = 36 * time.Hour + // ObserverFresh is how recent an observer's status telemetry must be for it to count as a current source. const ObserverFresh = 24 * time.Hour @@ -56,9 +61,12 @@ type Caps struct { Observer bool HasNode bool NodeType int16 // nodes only - // Polled: the radio has a current source: a polling assignment (nodes) or fresh status telemetry (observers). - // The data flags below only count while it does, so readings from before the source went do not offer a kind. - Polled bool + // Polled: the radio has a current source: a polling assignment or a trusted reading within NodeFresh (nodes), or fresh + // status telemetry (observers). The data flags below only count while it does, so readings from before the + // source went do not offer a kind. + Polled bool + // NodePolled: the node row is the one with the source (a radio that is also an observer can be Polled without). + NodePolled bool Battery, Temperature, Noise, Uptime bool ObsBattery, ObsNoise, ObsUptime bool } @@ -79,7 +87,7 @@ func (c Caps) Source(kind, requested string) string { switch kind { case KindObserverOff: return TargetObserver - case KindClock, KindTemperature: + case KindClock, KindTemperature, KindTelemetryStop: return TargetNode case KindBatteryLow, KindBatteryFalling: return pickSource(c.ObsBattery) @@ -102,7 +110,7 @@ func pickSource(observerHasIt bool) string { const ( CodeObserverNoData = "observer_no_data" // an observer does not report this value CodeRepeatersOnly = "repeaters_only" // only repeaters report this value - CodeNotPolled = "not_polled" // Beacon is not polling this repeater + CodeNotPolled = "not_polled" // no telemetry is arriving for this repeater CodeNoData = "no_data" // a polled repeater does not report this value CodeObserverNoClock = "observer_no_clock" // observers have no clock drift value CodeClockRepeatersOnly = "clock_repeaters_only" // only repeaters and room servers report a clock @@ -152,7 +160,7 @@ func kindStatus(c Caps, kind string) (ok bool, code, why string, relevant bool) case !c.repeaterLike(): return false, CodeRepeatersOnly, "Only repeaters report " + what + ".", true case !c.Polled: - return false, CodeNotPolled, "Beacon is not polling this repeater. Request telemetry for it first.", true + return false, CodeNotPolled, notPolledText, true default: return false, CodeNoData, "This repeater does not report " + what + ".", true } @@ -160,6 +168,16 @@ func kindStatus(c Caps, kind string) (ok bool, code, why string, relevant bool) switch kind { case KindGoneQuiet, KindBackOnline: return true, "", "", true + case KindTelemetryStop: + switch { + case !c.isNode(): + return false, "", "", false + case c.NodeType != nodeTypeRepeater && c.NodeType != nodeTypeRoomServer: + return false, CodeRepeatersOnly, "Only repeaters report telemetry.", true + case !c.NodePolled: + return false, CodeNotPolled, notPolledText, true + } + return true, "", "", true case KindObserverOff: return c.Observer, "", "", c.Observer case KindClock: @@ -182,9 +200,10 @@ func kindStatus(c Caps, kind string) (ok bool, code, why string, relevant bool) return false, "", "", false } +const notPolledText = "No telemetry is arriving for this repeater. Request telemetry for it first." + var ( - goneQuietHours = []int{12, 24, 48} - goneQuietFastHours = []int{3, 6, 12, 24, 48} + quietHours = []int{3, 6, 12, 24, 48} // gone_quiet and telemetry_stopped fallingPerDay = []int{100, 200, 300} clockSeconds = []int{300, 3600, 86400} observerOffMinutes = []int{30, 60, 180, 360} @@ -247,14 +266,10 @@ func ValidateRule(c Caps, kind string, th, high *int, enabled, hasGoneQuiet bool switch kind { case KindBackOnline, KindRebooted: err = none() - case KindGoneQuiet: + case KindGoneQuiet, KindTelemetryStop: var v int if v, err = single(); err == nil { - set := goneQuietHours - if !enabled || c.Observer || c.Polled { - set = goneQuietFastHours - } - err = oneOf(v, set, "Hours") + err = oneOf(v, quietHours, "Hours") } case KindBatteryLow: var v int diff --git a/internal/alerts/kinds_test.go b/internal/alerts/kinds_test.go index 7590a07f..62bc6a10 100644 --- a/internal/alerts/kinds_test.go +++ b/internal/alerts/kinds_test.go @@ -13,7 +13,7 @@ import ( func ip(v int) *int { return &v } var ( - polledRepeater = Caps{NodeType: 2, Polled: true, Battery: true, Noise: true, Uptime: true} + polledRepeater = Caps{NodeType: 2, Polled: true, NodePolled: true, Battery: true, Noise: true, Uptime: true} plainRepeater = Caps{NodeType: 2} companion = Caps{NodeType: 1} observerCaps = Caps{Observer: true, Polled: true, Battery: true, Noise: true, Uptime: true} @@ -21,7 +21,7 @@ var ( func TestAvailability(t *testing.T) { av, un, _ := Availability(polledRepeater) - if want := []string{"gone_quiet", "back_online", "clock", "battery_low", "battery_falling", "rebooted", "noise_high"}; !slices.Equal(av, want) { + if want := []string{"gone_quiet", "back_online", "telemetry_stopped", "clock", "battery_low", "battery_falling", "rebooted", "noise_high"}; !slices.Equal(av, want) { t.Fatalf("polled repeater: %v", av) } if un["temperature"] != "This repeater does not report a temperature." || len(un) != 1 { @@ -32,14 +32,14 @@ func TestAvailability(t *testing.T) { if want := []string{"gone_quiet", "back_online", "clock"}; !slices.Equal(av, want) { t.Fatalf("unpolled repeater: %v", av) } - for _, k := range []string{"battery_low", "battery_falling", "rebooted", "temperature", "noise_high"} { + for _, k := range []string{"telemetry_stopped", "battery_low", "battery_falling", "rebooted", "temperature", "noise_high"} { if un[k] == "" { t.Errorf("no reason for %s", k) } } av, un, _ = Availability(companion) - if want := []string{"gone_quiet", "back_online"}; !slices.Equal(av, want) || un["clock"] == "" || un["battery_low"] == "" { + if want := []string{"gone_quiet", "back_online"}; !slices.Equal(av, want) || un["clock"] == "" || un["battery_low"] == "" || un["telemetry_stopped"] != "Only repeaters report telemetry." { t.Fatalf("companion: %v %v", av, un) } @@ -50,6 +50,22 @@ func TestAvailability(t *testing.T) { if un["temperature"] == "" || un["clock"] == "" { t.Fatalf("%v", un) } + if av, _, _ := Availability(Caps{NodeType: 3, Polled: true, NodePolled: true}); !slices.Contains(av, "telemetry_stopped") { + t.Fatalf("room server: %v", av) + } + // telemetry_stopped is for repeaters only and not mentioned for an observer with no node row. + if _, ok := un["telemetry_stopped"]; ok { + t.Fatal("telemetry_stopped listed for an observer") + } + // An observer that also adverts as a repeater has it only when the node side has readings. + both := Caps{Observer: true, HasNode: true, NodeType: 2, Polled: true} + if _, un, codes := Availability(both); un["telemetry_stopped"] == "" || codes["telemetry_stopped"] != CodeNotPolled { + t.Fatalf("observer and node without node readings: %v", un) + } + both.NodePolled = true + if av, _, _ := Availability(both); !slices.Contains(av, "telemetry_stopped") { + t.Fatalf("observer and node with node readings: %v", av) + } // observer_offline is for observers only and not mentioned for nodes. if _, ok := un["observer_offline"]; ok || slices.Contains(av, "observer_offline") != true { t.Fatal("observer_offline") @@ -79,7 +95,7 @@ func TestAvailabilityCodes(t *testing.T) { } } check("polled", polledRepeater, map[string]string{"temperature": CodeNoData}) - check("plain", plainRepeater, map[string]string{"battery_low": CodeNotPolled, "noise_high": CodeNotPolled, "temperature": CodeNotPolled}) + check("plain", plainRepeater, map[string]string{"telemetry_stopped": CodeNotPolled, "battery_low": CodeNotPolled, "noise_high": CodeNotPolled, "temperature": CodeNotPolled}) check("companion", companion, map[string]string{"battery_low": CodeRepeatersOnly, "clock": CodeClockRepeatersOnly}) check("observer", observerCaps, map[string]string{"temperature": CodeObserverNoData, "clock": CodeObserverNoClock}) // Every code the server can emit is in the list clients are told about. @@ -126,7 +142,12 @@ func TestValidateRule(t *testing.T) { } cases := []tc{ on("gone quiet 24", plainRepeater, "gone_quiet", ip(24), nil), - {name: "gone quiet 6 not polled", caps: plainRepeater, kind: "gone_quiet", th: ip(6), enabled: true, wantInvalid: true}, + on("gone quiet 3 not polled", plainRepeater, "gone_quiet", ip(3), nil), + on("telemetry stopped 3", polledRepeater, "telemetry_stopped", ip(3), nil), + {name: "telemetry stopped 7", caps: polledRepeater, kind: "telemetry_stopped", th: ip(7), enabled: true, wantInvalid: true}, + {name: "telemetry stopped none", caps: polledRepeater, kind: "telemetry_stopped", enabled: true, wantInvalid: true}, + {name: "telemetry stopped not polled", caps: plainRepeater, kind: "telemetry_stopped", th: ip(12), enabled: true, wantNotAvail: true}, + {name: "telemetry stopped off, not polled", caps: plainRepeater, kind: "telemetry_stopped", th: ip(12)}, on("gone quiet 6 polled", polledRepeater, "gone_quiet", ip(6), nil), on("gone quiet 3 observer", observerCaps, "gone_quiet", ip(3), nil), {name: "gone quiet 7", caps: polledRepeater, kind: "gone_quiet", th: ip(7), enabled: true, wantInvalid: true}, @@ -203,7 +224,13 @@ func TestCapsOfAnObserverThatIsAlsoANode(t *testing.T) { for kind, want := range map[string]string{ KindObserverOff: TargetObserver, KindClock: TargetNode, KindTemperature: TargetNode, KindBatteryLow: TargetObserver, KindNoiseHigh: TargetObserver, KindRebooted: TargetObserver, KindGoneQuiet: TargetNode, + KindTelemetryStop: TargetNode, } { + if kind == KindTelemetryStop { // the node's own readings, even when the observer row was asked for + if got := c.Source(kind, TargetObserver); got != TargetNode { + t.Errorf("%s asked as an observer reads from %s", kind, got) + } + } if got := c.Source(kind, TargetNode); got != want { t.Errorf("%s reads from %s, want %s", kind, got, want) } diff --git a/internal/alerts/outbox_test.go b/internal/alerts/outbox_test.go index ca5cf9ca..d18803e3 100644 --- a/internal/alerts/outbox_test.go +++ b/internal/alerts/outbox_test.go @@ -309,6 +309,8 @@ func TestSentences(t *testing.T) { {KindGoneQuiet, "", 1, "N has not been heard for 1 hour."}, {KindGoneQuiet, "", 30, "N has not been heard for 30 hours."}, {KindBackOnline, "", 0, "N is back online."}, + {KindTelemetryStop, "", 1, "N has sent no telemetry for 1 hour."}, + {KindTelemetryStop, "", 12, "N has sent no telemetry for 12 hours."}, {KindBatteryFalling, "", 250, "N battery is falling by about 0.25 V a day."}, {KindTemperature, "", -25, "N temperature is -2.5 C, outside your limits."}, {KindNoiseHigh, "", -80, "N noise floor is high: -80 dBm."}, diff --git a/internal/alerts/text.go b/internal/alerts/text.go index 48e8733b..9cc5b4d1 100644 --- a/internal/alerts/text.go +++ b/internal/alerts/text.go @@ -19,6 +19,8 @@ func Sentence(kind, name string, value int64, detail, tempUnit string) string { return fmt.Sprintf("%s has not been heard for %s.", name, plural(value, "hour")) case KindBackOnline: return fmt.Sprintf("%s is back online.", name) + case KindTelemetryStop: + return fmt.Sprintf("%s has sent no telemetry for %s.", name, plural(value, "hour")) case KindBatteryLow: return fmt.Sprintf("%s battery is low: %.2f V.", name, float64(value)/1000) case KindBatteryFalling: diff --git a/internal/api/alerts.go b/internal/api/alerts.go index 99e78316..dd87c94f 100644 --- a/internal/api/alerts.go +++ b/internal/api/alerts.go @@ -3,12 +3,12 @@ package api -// AlertRule is one stored rule. Thresholds are in the kind's own unit: hours (gone_quiet), millivolts (battery_low), +// AlertRule is one stored rule. Thresholds are in the kind's own unit: hours (gone_quiet, telemetry_stopped), millivolts (battery_low), // millivolts per day (battery_falling), tenths of a degree C (temperature, low and high), dBm (noise_high), seconds // (clock), minutes (observer_offline); null for back_online and rebooted. Times are epoch milliseconds. type AlertRule struct { ID string `json:"id"` - Kind string `json:"kind" enums:"gone_quiet,back_online,clock,battery_low,battery_falling,rebooted,temperature,noise_high,observer_offline"` + Kind string `json:"kind" enums:"gone_quiet,back_online,telemetry_stopped,clock,battery_low,battery_falling,rebooted,temperature,noise_high,observer_offline"` Threshold *int `json:"threshold" example:"3500"` ThresholdHigh *int `json:"thresholdHigh"` Enabled bool `json:"enabled"` @@ -24,9 +24,9 @@ type AlertTarget struct { Kind string `json:"kind" enums:"node,observer"` PublicKey string `json:"publicKey"` Name string `json:"name" example:"Hilltop"` - // Polled: the radio has a current source: a repeater is assigned to an observer that polls it, an observer has sent - // status telemetry in the last day. Old readings alone do not count. It is what offers the telemetry kinds and the 3 and 6 hour - // gone_quiet thresholds for a repeater (observers always have those). + // Polled: the radio has a current source: a repeater is assigned to an observer that polls it or has a trusted + // reading from the last 36 hours, an observer has sent status telemetry in the last day. Older readings alone do + // not count. It is what offers the telemetry kinds. Polled bool `json:"polled"` Available []string `json:"available"` // Unavailable maps a kind to the English reason this radio cannot have it. From a7c36e8e76735969aae02a56b3d5a2a685760f01 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 21:00:59 -0500 Subject: [PATCH 3/7] feat(polling): decode sensor channels from LPP and serve them with node telemetry Humidity, pressure, gas and power monitor channels are decoded when a reading is stored. Positions and altitude are never decoded. Fixes the humidity size, which is one byte on the wire. --- .../097_repeater_readings_sensors.sql | 6 + db/polling.go | 13 ++ db/polling_integration_test.go | 36 ++++ db/queries/polling.sql | 8 +- db/sqlc/models.go | 1 + db/sqlc/polling.sql.go | 28 +-- docs/docs.go | 78 +++++++- docs/swagger.json | 78 +++++++- docs/swagger.yaml | 68 ++++++- internal/api/atlas.go | 8 +- internal/api/atlas_test.go | 2 + internal/api/handlers/info_test.go | 4 +- internal/api/info.go | 3 + internal/api/node_telemetry.go | 100 ++++++++++- internal/api/node_telemetry_test.go | 48 +++++ internal/api/router/router.go | 2 +- internal/api/router/router_test.go | 4 +- internal/polling/lpp.go | 170 +++++++++++++++++- internal/polling/lpp_sensors_test.go | 95 ++++++++++ internal/polling/wire.go | 9 +- internal/polling/wire_test.go | 2 +- 21 files changed, 726 insertions(+), 37 deletions(-) create mode 100644 db/migrations/097_repeater_readings_sensors.sql create mode 100644 internal/polling/lpp_sensors_test.go diff --git a/db/migrations/097_repeater_readings_sensors.sql b/db/migrations/097_repeater_readings_sensors.sql new file mode 100644 index 00000000..8d37e2f5 --- /dev/null +++ b/db/migrations/097_repeater_readings_sensors.sql @@ -0,0 +1,6 @@ +-- Copyright 2026 Beacon Contributors +-- SPDX-License-Identifier: AGPL-3.0-or-later + +-- What a reading's sensor channels carried (humidity, pressure, gas, power monitors), decoded when it is stored. +-- NULL when it carried none, and on every reading stored before this. +ALTER TABLE repeater_readings ADD COLUMN IF NOT EXISTS sensors jsonb; diff --git a/db/polling.go b/db/polling.go index 0ae4f8b0..419e8d32 100644 --- a/db/polling.go +++ b/db/polling.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/hex" + "encoding/json" "errors" "fmt" "sort" @@ -366,6 +367,13 @@ func storeReading(ctx context.Context, q *sqlc.Queries, r polling.Reading, obser if foreign != nil { params.ForeignSource, params.EvidenceSince, params.ApprovedOnly = true, ts(foreign.evidenceSince), foreign.approvedOnly } + if len(r.Sensors) > 0 { + b, err := json.Marshal(r.Sensors) + if err != nil { + return false, err + } + params.Sensors = b + } n, err := q.InsertRepeaterReading(ctx, params) return n > 0, err } @@ -855,7 +863,12 @@ func (l *PollingElectionLock) Close(ctx context.Context) { } func nodeReading(r sqlc.ListNodeReadingsRow) api.NodeReading { + var sensors []api.NodeSensor + if len(r.Sensors) > 0 { + _ = json.Unmarshal(r.Sensors, &sensors) // written by this server; a row it cannot read has no sensors + } return api.NodeReading{ + Sensors: sensors, SampledAt: r.SampledAt.Time, Method: r.Method, Trusted: r.Trusted, Foreign: r.ForeignSource, BatteryMV: r.BatteryMv, TemperatureC: r.TemperatureC, NoiseFloorDB: r.NoiseFloor, LastRSSIDB: r.LastRssi, LastSNRDB: r.LastSnr, UptimeSeconds: r.UptimeSecs, QueueLength: r.TxQueue, diff --git a/db/polling_integration_test.go b/db/polling_integration_test.go index 9a931868..e534c3fa 100644 --- a/db/polling_integration_test.go +++ b/db/polling_integration_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/hex" + "encoding/json" "errors" "fmt" "log/slog" @@ -1412,6 +1413,41 @@ func trustedIndexValid(t *testing.T, ctx context.Context, pool *pgxpool.Pool) bo return valid } +// A reading's sensor channels are decoded when it is stored and read back with it; the position in the same LPP is +// not among them. +func TestReadingSensorsPostgres(t *testing.T) { + ctx, pool, s := pollStore(t) + obs, target := pollKey(1), pollKey(0xA) + oid := pollObserver(t, ctx, s, obs) + nodeID := uuid.New() + if _, err := pool.Exec(ctx, `INSERT INTO nodes (id, public_key, node_type, name) VALUES ($1, $2, 2, 'rep')`, nodeID, target); err != nil { + t.Fatal(err) + } + now := time.Now().UTC().Truncate(time.Second) + // 3.94 V on channel 1, a position, then 45.5 % and 1013.2 hPa on channel 2 and 8.70 V at 0.122 A on channel 3. + lpp, _ := hex.DecodeString("0174018a" + "018806f7c8f4b2e0002710" + "02685b" + "02732794" + "03740366" + "0375007a") + mv := 3940 + plain := polling.Reading{Version: 2, Observer: obs, Target: target, Method: "status", SampledAt: now.Add(-2 * time.Hour), BatteryMV: &mv} + withLPP := polling.Reading{Version: 2, Observer: obs, Target: target, Method: "telemetry", SampledAt: now.Add(-time.Hour), BatteryMV: &mv, + LPP: lpp, Sensors: polling.DecodeSensors(lpp)} + for _, r := range []polling.Reading{plain, withLPP} { + if ok, err := s.InsertRepeaterReading(ctx, r, oid, r.SampledAt); err != nil || !ok { + t.Fatalf("insert: %v %v", ok, err) + } + } + got, _, _, err := s.GetNodeReadings(ctx, nodeID, now.Add(-24*time.Hour), time.Time{}, true) + if err != nil || len(got) != 2 { + t.Fatalf("%d readings, %v", len(got), err) + } + if got[0].Sensors != nil { + t.Fatalf("a reading without sensor channels: %+v", got[0].Sensors) + } + b, _ := json.Marshal(got[1].Sensors) + if want := `[{"channel":2,"humidityPct":45.5,"pressureHpa":1013.2},{"channel":3,"voltageV":8.7,"currentA":0.122,"powerW":1.061}]`; string(b) != want { + t.Fatalf("sensors %s", b) + } +} + func TestNodeReadingsPostgres(t *testing.T) { ctx, pool, s := pollStore(t) obs := pollKey(1) diff --git a/db/queries/polling.sql b/db/queries/polling.sql index b400a019..833b845f 100644 --- a/db/queries/polling.sql +++ b/db/queries/polling.sql @@ -175,7 +175,7 @@ INSERT INTO repeater_readings ( battery_mv, temperature_c, poll_snr, poll_rssi, signed, uptime_secs, packets_recv, packets_sent, recv_flood, recv_direct, sent_flood, sent_direct, tx_air_secs, rx_air_secs, recv_errors, noise_floor, last_rssi, tx_queue, flood_dups, direct_dups, err_events, last_snr, - lpp, packet_hash, client, foreign_source, trusted) + lpp, sensors, packet_hash, client, foreign_source, trusted) SELECT sqlc.arg(target_public_key), sqlc.arg(observer_public_key), sqlc.arg(observer_id), sqlc.arg(sampled_at), sqlc.arg(received_at), sqlc.arg(method), sqlc.arg(tag), @@ -184,7 +184,7 @@ SELECT sqlc.narg(sent_flood), sqlc.narg(sent_direct), sqlc.narg(tx_air_secs), sqlc.narg(rx_air_secs), sqlc.narg(recv_errors), sqlc.narg(noise_floor), sqlc.narg(last_rssi), sqlc.narg(tx_queue), sqlc.narg(flood_dups), sqlc.narg(direct_dups), sqlc.narg(err_events), sqlc.narg(last_snr), - sqlc.narg(lpp), sqlc.narg(packet_hash), sqlc.arg(client), + sqlc.narg(lpp), sqlc.narg(sensors)::jsonb, sqlc.narg(packet_hash), sqlc.arg(client), -- A reading with no claim behind it is foreign unless this server gave the observer the target: a requested -- target is assigned before the device's claim names it. (sqlc.arg(foreign_source)::boolean AND NOT EXISTS ( @@ -544,7 +544,7 @@ SELECT public_key FROM nodes WHERE id = $1; -- name: ListNodeReadings :many -- Readings of one target in [since, until) ascending; until is open when NULL. Untrusted ones only when asked for. SELECT sampled_at, method, trusted, foreign_source, battery_mv, temperature_c, noise_floor, last_rssi, last_snr, uptime_secs, tx_queue, - tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors + tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors, sensors FROM repeater_readings WHERE target_public_key = @target_public_key AND sampled_at >= @since::timestamptz @@ -562,7 +562,7 @@ WHERE target_public_key = @target_public_key -- name: LatestNodeStatusReadingBefore :many -- The newest status reading before since: the baseline for the first counter increments in range. SELECT sampled_at, method, trusted, foreign_source, battery_mv, temperature_c, noise_floor, last_rssi, last_snr, uptime_secs, tx_queue, - tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors + tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors, sensors FROM repeater_readings WHERE target_public_key = @target_public_key AND sampled_at < @since::timestamptz diff --git a/db/sqlc/models.go b/db/sqlc/models.go index 2ca0ee10..45146e93 100644 --- a/db/sqlc/models.go +++ b/db/sqlc/models.go @@ -702,6 +702,7 @@ type RepeaterReading struct { ForeignSource bool `json:"foreign_source"` PollRssi *int16 `json:"poll_rssi"` Signed bool `json:"signed"` + Sensors []byte `json:"sensors"` } type RollupOb struct { diff --git a/db/sqlc/polling.sql.go b/db/sqlc/polling.sql.go index b8e8fbb8..93c08aa6 100644 --- a/db/sqlc/polling.sql.go +++ b/db/sqlc/polling.sql.go @@ -409,7 +409,7 @@ INSERT INTO repeater_readings ( battery_mv, temperature_c, poll_snr, poll_rssi, signed, uptime_secs, packets_recv, packets_sent, recv_flood, recv_direct, sent_flood, sent_direct, tx_air_secs, rx_air_secs, recv_errors, noise_floor, last_rssi, tx_queue, flood_dups, direct_dups, err_events, last_snr, - lpp, packet_hash, client, foreign_source, trusted) + lpp, sensors, packet_hash, client, foreign_source, trusted) SELECT $1, $2, $3, $4, $5, $6, $7, @@ -418,20 +418,20 @@ SELECT $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, - $30, $31, $32, + $30, $31::jsonb, $32, $33, -- A reading with no claim behind it is foreign unless this server gave the observer the target: a requested -- target is assigned before the device's claim names it. - ($33::boolean AND NOT EXISTS ( + ($34::boolean AND NOT EXISTS ( SELECT 1 FROM polling_assignments t WHERE t.target_public_key = $1 AND t.observer_public_key = $2)), -- Same rule as latest_ts in PollingOwnerRows, frozen at insert time. A foreign observer holds no assignment, so -- its reading is trusted on the same evidence an election would have counted: zero-hop adverts of the target it -- heard since evidence_since, missing signal left out. -- With polling.authority approved only an approved observer's readings count, foreign or not. - CASE WHEN $33::boolean AND NOT EXISTS ( + CASE WHEN $34::boolean AND NOT EXISTS ( SELECT 1 FROM polling_assignments t WHERE t.target_public_key = $1 AND t.observer_public_key = $2 - ) THEN (NOT $34::boolean OR EXISTS ( + ) THEN (NOT $35::boolean OR EXISTS ( SELECT 1 FROM polling_observers po WHERE po.observer_public_key = $2 AND po.approved )) AND EXISTS ( @@ -439,7 +439,7 @@ SELECT JOIN packet_observations o ON o.packet_hash = p.packet_hash WHERE p.origin_pubkey = $1 AND p.payload_type = 4 AND o.observer_id = $3::uuid AND o.hop_count = 0 AND o.snr IS NOT NULL - AND p.first_heard_at >= $35::timestamptz AND NOT (o.snr = 0 AND o.rssi = 0) + AND p.first_heard_at >= $36::timestamptz AND NOT (o.snr = 0 AND o.rssi = 0) ) ELSE EXISTS ( SELECT 1 FROM polling_assignments t WHERE t.target_public_key = $1 AND t.observer_public_key = $2 @@ -448,11 +448,11 @@ SELECT WHERE NOT EXISTS ( SELECT 1 FROM repeater_readings x WHERE x.target_public_key = $1 AND x.observer_public_key = $2 - AND x.method = $6 AND x.received_at > $36 + AND x.method = $6 AND x.received_at > $37 ) AND ( SELECT count(*) FROM repeater_readings b - WHERE b.observer_public_key = $2 AND b.received_at > $37 -) < $38::bigint + WHERE b.observer_public_key = $2 AND b.received_at > $38 +) < $39::bigint ON CONFLICT (target_public_key, observer_public_key, tag, method) DO NOTHING ` @@ -487,6 +487,7 @@ type InsertRepeaterReadingParams struct { ErrEvents *int32 `json:"err_events"` LastSnr *float32 `json:"last_snr"` Lpp []byte `json:"lpp"` + Sensors []byte `json:"sensors"` PacketHash []byte `json:"packet_hash"` Client string `json:"client"` ForeignSource bool `json:"foreign_source"` @@ -531,6 +532,7 @@ func (q *Queries) InsertRepeaterReading(ctx context.Context, arg InsertRepeaterR arg.ErrEvents, arg.LastSnr, arg.Lpp, + arg.Sensors, arg.PacketHash, arg.Client, arg.ForeignSource, @@ -627,7 +629,7 @@ func (q *Queries) LatestNodeReadings(ctx context.Context, arg LatestNodeReadings const latestNodeStatusReadingBefore = `-- name: LatestNodeStatusReadingBefore :many SELECT sampled_at, method, trusted, foreign_source, battery_mv, temperature_c, noise_floor, last_rssi, last_snr, uptime_secs, tx_queue, - tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors + tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors, sensors FROM repeater_readings WHERE target_public_key = $1 AND sampled_at < $2::timestamptz @@ -660,6 +662,7 @@ type LatestNodeStatusReadingBeforeRow struct { PacketsRecv *int64 `json:"packets_recv"` PacketsSent *int64 `json:"packets_sent"` RecvErrors *int64 `json:"recv_errors"` + Sensors []byte `json:"sensors"` } // The newest status reading before since: the baseline for the first counter increments in range. @@ -689,6 +692,7 @@ func (q *Queries) LatestNodeStatusReadingBefore(ctx context.Context, arg LatestN &i.PacketsRecv, &i.PacketsSent, &i.RecvErrors, + &i.Sensors, ); err != nil { return nil, err } @@ -776,7 +780,7 @@ func (q *Queries) ListForeignReporters(ctx context.Context, arg ListForeignRepor const listNodeReadings = `-- name: ListNodeReadings :many SELECT sampled_at, method, trusted, foreign_source, battery_mv, temperature_c, noise_floor, last_rssi, last_snr, uptime_secs, tx_queue, - tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors + tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors, sensors FROM repeater_readings WHERE target_public_key = $1 AND sampled_at >= $2::timestamptz @@ -809,6 +813,7 @@ type ListNodeReadingsRow struct { PacketsRecv *int64 `json:"packets_recv"` PacketsSent *int64 `json:"packets_sent"` RecvErrors *int64 `json:"recv_errors"` + Sensors []byte `json:"sensors"` } // Readings of one target in [since, until) ascending; until is open when NULL. Untrusted ones only when asked for. @@ -843,6 +848,7 @@ func (q *Queries) ListNodeReadings(ctx context.Context, arg ListNodeReadingsPara &i.PacketsRecv, &i.PacketsSent, &i.RecvErrors, + &i.Sensors, ); err != nil { return nil, err } diff --git a/docs/docs.go b/docs/docs.go index a7e1d30b..d9a2978e 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -8290,7 +8290,13 @@ const docTemplate = `{ "temperature", "packets", "signal", - "errors" + "errors", + "humidity", + "pressure", + "gas", + "power", + "current", + "sensorVoltage" ] } }, @@ -8334,7 +8340,7 @@ const docTemplate = `{ "type": "string" }, "telemetryTiles": { - "description": "TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors.\nNode pins only.", + "description": "TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors,\nhumidity, pressure, gas, power, current, sensorVoltage. Node pins only.", "type": "array", "items": { "type": "string" @@ -8854,6 +8860,11 @@ const docTemplate = `{ "type": "boolean", "example": false }, + "sensors": { + "description": "Sensors is true when node telemetry points carry sensors and telemetryTiles takes the sensor tiles (humidity,\npressure, gas, power, current, sensorVoltage). Always true on this version.", + "type": "boolean", + "example": true + }, "telemetryRequests": { "type": "boolean", "example": false @@ -9622,6 +9633,62 @@ const docTemplate = `{ } } }, + "github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSensor": { + "type": "object", + "properties": { + "channel": { + "type": "integer", + "example": 2 + }, + "currentA": { + "type": "number", + "example": 0.122 + }, + "distanceM": { + "type": "number" + }, + "gasOhms": { + "description": "GasOhms is a gas sensor's raw resistance. IAQ is its air quality index (0 to 500) when the firmware computes\none instead, with IAQAccuracy 0 to 3 (3 is calibrated); in a bucket the accuracy is the lowest seen.", + "type": "number", + "example": 50000 + }, + "humidityPct": { + "type": "number", + "example": 45.5 + }, + "iaq": { + "type": "number", + "example": 50 + }, + "iaqAccuracy": { + "type": "integer", + "example": 3 + }, + "luminosityLux": { + "type": "number" + }, + "percent": { + "type": "number" + }, + "powerW": { + "description": "PowerW is voltage times current when the channel carried both, which keeps the decimals the firmware's whole\nwatts lose.", + "type": "number", + "example": 1.061 + }, + "pressureHpa": { + "type": "number", + "example": 1013.2 + }, + "temperatureC": { + "type": "number", + "example": 21.4 + }, + "voltageV": { + "type": "number", + "example": 8.7 + } + } + }, "github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSummary": { "type": "object", "properties": { @@ -9783,6 +9850,13 @@ const docTemplate = `{ "receiveErrors": { "type": "integer" }, + "sensors": { + "description": "Sensors are the averages of each sensor channel over the bucket, ascending by channel. Omitted when no\nreading in the bucket carried a sensor channel.", + "type": "array", + "items": { + "$ref": "#/definitions/github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSensor" + } + }, "t": { "description": "epoch ms, bucket start", "type": "integer" diff --git a/docs/swagger.json b/docs/swagger.json index 7cd68f9d..cbd81418 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -8288,7 +8288,13 @@ "temperature", "packets", "signal", - "errors" + "errors", + "humidity", + "pressure", + "gas", + "power", + "current", + "sensorVoltage" ] } }, @@ -8332,7 +8338,7 @@ "type": "string" }, "telemetryTiles": { - "description": "TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors.\nNode pins only.", + "description": "TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors,\nhumidity, pressure, gas, power, current, sensorVoltage. Node pins only.", "type": "array", "items": { "type": "string" @@ -8852,6 +8858,11 @@ "type": "boolean", "example": false }, + "sensors": { + "description": "Sensors is true when node telemetry points carry sensors and telemetryTiles takes the sensor tiles (humidity,\npressure, gas, power, current, sensorVoltage). Always true on this version.", + "type": "boolean", + "example": true + }, "telemetryRequests": { "type": "boolean", "example": false @@ -9620,6 +9631,62 @@ } } }, + "github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSensor": { + "type": "object", + "properties": { + "channel": { + "type": "integer", + "example": 2 + }, + "currentA": { + "type": "number", + "example": 0.122 + }, + "distanceM": { + "type": "number" + }, + "gasOhms": { + "description": "GasOhms is a gas sensor's raw resistance. IAQ is its air quality index (0 to 500) when the firmware computes\none instead, with IAQAccuracy 0 to 3 (3 is calibrated); in a bucket the accuracy is the lowest seen.", + "type": "number", + "example": 50000 + }, + "humidityPct": { + "type": "number", + "example": 45.5 + }, + "iaq": { + "type": "number", + "example": 50 + }, + "iaqAccuracy": { + "type": "integer", + "example": 3 + }, + "luminosityLux": { + "type": "number" + }, + "percent": { + "type": "number" + }, + "powerW": { + "description": "PowerW is voltage times current when the channel carried both, which keeps the decimals the firmware's whole\nwatts lose.", + "type": "number", + "example": 1.061 + }, + "pressureHpa": { + "type": "number", + "example": 1013.2 + }, + "temperatureC": { + "type": "number", + "example": 21.4 + }, + "voltageV": { + "type": "number", + "example": 8.7 + } + } + }, "github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSummary": { "type": "object", "properties": { @@ -9781,6 +9848,13 @@ "receiveErrors": { "type": "integer" }, + "sensors": { + "description": "Sensors are the averages of each sensor channel over the bucket, ascending by channel. Omitted when no\nreading in the bucket carried a sensor channel.", + "type": "array", + "items": { + "$ref": "#/definitions/github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSensor" + } + }, "t": { "description": "epoch ms, bucket start", "type": "integer" diff --git a/docs/swagger.yaml b/docs/swagger.yaml index d8788e6e..f99171a2 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -418,6 +418,12 @@ definitions: - packets - signal - errors + - humidity + - pressure + - gas + - power + - current + - sensorVoltage type: string type: array tiles: @@ -449,8 +455,8 @@ definitions: type: string telemetryTiles: description: |- - TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors. - Node pins only. + TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors, + humidity, pressure, gas, power, current, sensorVoltage. Node pins only. items: type: string type: array @@ -818,6 +824,12 @@ definitions: when accounts is "local". example: false type: boolean + sensors: + description: |- + Sensors is true when node telemetry points carry sensors and telemetryTiles takes the sensor tiles (humidity, + pressure, gas, power, current, sensorVoltage). Always true on this version. + example: true + type: boolean telemetryRequests: example: false type: boolean @@ -1389,6 +1401,51 @@ definitions: rank: type: integer type: object + github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSensor: + properties: + channel: + example: 2 + type: integer + currentA: + example: 0.122 + type: number + distanceM: + type: number + gasOhms: + description: |- + GasOhms is a gas sensor's raw resistance. IAQ is its air quality index (0 to 500) when the firmware computes + one instead, with IAQAccuracy 0 to 3 (3 is calibrated); in a bucket the accuracy is the lowest seen. + example: 50000 + type: number + humidityPct: + example: 45.5 + type: number + iaq: + example: 50 + type: number + iaqAccuracy: + example: 3 + type: integer + luminosityLux: + type: number + percent: + type: number + powerW: + description: |- + PowerW is voltage times current when the channel carried both, which keeps the decimals the firmware's whole + watts lose. + example: 1.061 + type: number + pressureHpa: + example: 1013.2 + type: number + temperatureC: + example: 21.4 + type: number + voltageV: + example: 8.7 + type: number + type: object github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSummary: properties: defaultScope: @@ -1517,6 +1574,13 @@ definitions: type: integer receiveErrors: type: integer + sensors: + description: |- + Sensors are the averages of each sensor channel over the bucket, ascending by channel. Omitted when no + reading in the bucket carried a sensor channel. + items: + $ref: '#/definitions/github_com_MeshCore-Beacon_beacon-server_internal_api.NodeSensor' + type: array t: description: epoch ms, bucket start type: integer diff --git a/internal/api/atlas.go b/internal/api/atlas.go index ca2f7e8b..51e1228d 100644 --- a/internal/api/atlas.go +++ b/internal/api/atlas.go @@ -25,9 +25,11 @@ var atlasTiles = map[string]bool{ "snr": true, "rssi": true, "noise": true, "queue": true, "errors": true, } +// The last six read the repeater's sensor channels (NodeTelemetryPoint.Sensors). var atlasTelemetryTiles = map[string]bool{ "battery": true, "noise": true, "uptime": true, "airtime": true, "temperature": true, "packets": true, "signal": true, "errors": true, + "humidity": true, "pressure": true, "gas": true, "power": true, "current": true, "sensorVoltage": true, } // AtlasPin is one pin as a client reads it. A node pin carries publicKey, id and observerId; an observer pin @@ -42,7 +44,7 @@ type AtlasPin struct { Tiles []string `json:"tiles,omitempty"` View string `json:"view,omitempty" enums:"heard,observer,telemetry,poller"` // TelemetryTiles are the four tiles of a node pin's Telemetry view; absent means the client's default. - TelemetryTiles []string `json:"telemetryTiles,omitempty" enums:"battery,noise,uptime,airtime,temperature,packets,signal,errors"` + TelemetryTiles []string `json:"telemetryTiles,omitempty" enums:"battery,noise,uptime,airtime,temperature,packets,signal,errors,humidity,pressure,gas,power,current,sensorVoltage"` } // MarshalJSON leaves out the fields that do not belong to the pin's kind. @@ -93,8 +95,8 @@ type AtlasPinInput struct { Name string `json:"name"` Tiles []string `json:"tiles"` View *string `json:"view" enums:"heard,observer,telemetry,poller"` - // TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors. - // Node pins only. + // TelemetryTiles is four distinct ids from battery, noise, uptime, airtime, temperature, packets, signal, errors, + // humidity, pressure, gas, power, current, sensorVoltage. Node pins only. TelemetryTiles []string `json:"telemetryTiles"` } diff --git a/internal/api/atlas_test.go b/internal/api/atlas_test.go index f59d4f94..fd068c50 100644 --- a/internal/api/atlas_test.go +++ b/internal/api/atlas_test.go @@ -42,6 +42,8 @@ func TestValidateAtlasPut(t *testing.T) { {"poller view", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), View: str("poller")}}}, ""}, {"telemetry tiles", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), TelemetryTiles: ttiles}}}, ""}, {"telemetry tiles with tiles", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), Tiles: tiles, TelemetryTiles: ttiles, View: str("telemetry")}}}, ""}, + {"sensor tiles", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), TelemetryTiles: []string{"humidity", "pressure", "gas", "power"}}}}, ""}, + {"more sensor tiles", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), TelemetryTiles: []string{"current", "sensorVoltage", "battery", "noise"}}}}, ""}, {"three telemetry tiles", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), TelemetryTiles: ttiles[:3]}}}, "telemetryTiles"}, {"empty telemetry tiles", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), TelemetryTiles: []string{}}}}, "telemetryTiles"}, {"repeated telemetry tile", PutAtlasRequest{Range: "24h", Pins: []AtlasPinInput{{Kind: "node", PublicKey: key(1), TelemetryTiles: []string{"battery", "battery", "noise", "uptime"}}}}, "telemetryTiles"}, diff --git a/internal/api/handlers/info_test.go b/internal/api/handlers/info_test.go index cabcd2e3..6b60d88e 100644 --- a/internal/api/handlers/info_test.go +++ b/internal/api/handlers/info_test.go @@ -19,8 +19,8 @@ func TestGetInfo(t *testing.T) { info api.Info want string }{ - {"unset", api.Info{ServerVersion: "2.0.2", Features: api.InfoFeatures{Accounts: "off"}}, `{"minAppVersion":null,"minWebVersion":null,"serverVersion":"2.0.2","features":{"polling":false,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":false,"atlasPoller":false,"atlas7d":false,"mapTelemetry":false,"appDeviceLabel":false},"display":{"temperatureUnit":"","distanceUnit":""},"limits":{"atlas":0}}`}, - {"set", api.Info{MinAppVersion: &version, MinWebVersion: &web, ServerVersion: "2.0.2", Features: api.InfoFeatures{Polling: true, Accounts: "off"}}, `{"minAppVersion":"0.1.1","minWebVersion":"2.0.3","serverVersion":"2.0.2","features":{"polling":true,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":false,"atlasPoller":false,"atlas7d":false,"mapTelemetry":false,"appDeviceLabel":false},"display":{"temperatureUnit":"","distanceUnit":""},"limits":{"atlas":0}}`}, + {"unset", api.Info{ServerVersion: "2.0.2", Features: api.InfoFeatures{Accounts: "off"}}, `{"minAppVersion":null,"minWebVersion":null,"serverVersion":"2.0.2","features":{"polling":false,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":false,"sensors":false,"atlasPoller":false,"atlas7d":false,"mapTelemetry":false,"appDeviceLabel":false},"display":{"temperatureUnit":"","distanceUnit":""},"limits":{"atlas":0}}`}, + {"set", api.Info{MinAppVersion: &version, MinWebVersion: &web, ServerVersion: "2.0.2", Features: api.InfoFeatures{Polling: true, Accounts: "off"}}, `{"minAppVersion":"0.1.1","minWebVersion":"2.0.3","serverVersion":"2.0.2","features":{"polling":true,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":false,"sensors":false,"atlasPoller":false,"atlas7d":false,"mapTelemetry":false,"appDeviceLabel":false},"display":{"temperatureUnit":"","distanceUnit":""},"limits":{"atlas":0}}`}, } { t.Run(tc.name, func(t *testing.T) { w := httptest.NewRecorder() diff --git a/internal/api/info.go b/internal/api/info.go index be46b8ef..cfc41732 100644 --- a/internal/api/info.go +++ b/internal/api/info.go @@ -72,6 +72,9 @@ type InfoFeatures struct { // AtlasTelemetry is true when the server accepts the telemetry view and telemetryTiles on Atlas pins and the 72h // node telemetry range. Always true on this version. AtlasTelemetry bool `json:"atlasTelemetry" example:"true"` + // Sensors is true when node telemetry points carry sensors and telemetryTiles takes the sensor tiles (humidity, + // pressure, gas, power, current, sensorVoltage). Always true on this version. + Sensors bool `json:"sensors" example:"true"` // AtlasPoller is true when the server accepts the poller view on Atlas pins. Always true on this version. AtlasPoller bool `json:"atlasPoller" example:"true"` // Atlas7d is true when the server accepts the 7d Atlas range. Always true on this version. diff --git a/internal/api/node_telemetry.go b/internal/api/node_telemetry.go index 53cac006..fc34ce22 100644 --- a/internal/api/node_telemetry.go +++ b/internal/api/node_telemetry.go @@ -5,6 +5,7 @@ package api import ( "math" + "sort" "time" "github.com/google/uuid" @@ -39,6 +40,32 @@ type NodeReading struct { PacketsReceived *int64 PacketsSent *int64 ReceiveErrors *int64 + // Sensors are the reading's sensor channels, ascending by channel. + Sensors []NodeSensor +} + +// NodeSensor is what one sensor channel of a repeater reported: one stored reading's values, or their averages over +// a bucket. Channel 1 is the repeater's own board; added sensors take 2 and up in the order the firmware found them. +// The firmware sends no sensor names, so a channel is told by what it carries. A field is omitted when the channel +// did not carry it. A position is never among them. +type NodeSensor struct { + Channel int `json:"channel" example:"2"` + TemperatureC *float64 `json:"temperatureC,omitempty" example:"21.4"` + HumidityPct *float64 `json:"humidityPct,omitempty" example:"45.5"` + PressureHpa *float64 `json:"pressureHpa,omitempty" example:"1013.2"` + // GasOhms is a gas sensor's raw resistance. IAQ is its air quality index (0 to 500) when the firmware computes + // one instead, with IAQAccuracy 0 to 3 (3 is calibrated); in a bucket the accuracy is the lowest seen. + GasOhms *float64 `json:"gasOhms,omitempty" example:"50000"` + IAQ *float64 `json:"iaq,omitempty" example:"50"` + IAQAccuracy *int `json:"iaqAccuracy,omitempty" example:"3"` + VoltageV *float64 `json:"voltageV,omitempty" example:"8.7"` + CurrentA *float64 `json:"currentA,omitempty" example:"0.122"` + // PowerW is voltage times current when the channel carried both, which keeps the decimals the firmware's whole + // watts lose. + PowerW *float64 `json:"powerW,omitempty" example:"1.061"` + DistanceM *float64 `json:"distanceM,omitempty"` + Percent *float64 `json:"percent,omitempty"` + LuminosityLux *float64 `json:"luminosityLux,omitempty"` } // NodeTelemetryPoint is one bucket of a node's readings. Counters are increments within the @@ -62,6 +89,9 @@ type NodeTelemetryPoint struct { // Seconds of elapsed time the counter increments cover; divide an increment by it for a rate. // Omitted, along with the counters, when no increment in the bucket could be placed in time. CounterSpanSecs *int64 `json:"counterSpanSecs,omitempty"` + // Sensors are the averages of each sensor channel over the bucket, ascending by channel. Omitted when no + // reading in the bucket carried a sensor channel. + Sensors []NodeSensor `json:"sensors,omitempty"` } // NodeTelemetry is the telemetry response for a polled node. @@ -199,6 +229,73 @@ type nodeBucket struct { inc [5]int64 carried [5]int // contributing pairs that had the counter spanMS int64 + sensors map[int]*sensorBucket +} + +// sensorFields are a sensor channel's averaged values, in the order of sensorBucket.m. +var sensorFields = [...]struct { + get func(*NodeSensor) **float64 + // decimals the average is rounded to + decimals int +}{ + {func(s *NodeSensor) **float64 { return &s.TemperatureC }, 1}, + {func(s *NodeSensor) **float64 { return &s.HumidityPct }, 1}, + {func(s *NodeSensor) **float64 { return &s.PressureHpa }, 1}, + {func(s *NodeSensor) **float64 { return &s.GasOhms }, 0}, + {func(s *NodeSensor) **float64 { return &s.IAQ }, 0}, + {func(s *NodeSensor) **float64 { return &s.VoltageV }, 2}, + {func(s *NodeSensor) **float64 { return &s.CurrentA }, 3}, + {func(s *NodeSensor) **float64 { return &s.PowerW }, 3}, + {func(s *NodeSensor) **float64 { return &s.DistanceM }, 3}, + {func(s *NodeSensor) **float64 { return &s.Percent }, 0}, + {func(s *NodeSensor) **float64 { return &s.LuminosityLux }, 0}, +} + +type sensorBucket struct { + m [len(sensorFields)]mean + accuracy *int +} + +func (b *nodeBucket) addSensors(sensors []NodeSensor) { + for i := range sensors { + s := &sensors[i] + if b.sensors == nil { + b.sensors = map[int]*sensorBucket{} + } + sb := b.sensors[s.Channel] + if sb == nil { + sb = &sensorBucket{} + b.sensors[s.Channel] = sb + } + for f, field := range sensorFields { + sb.m[f].add(*field.get(s)) + } + if a := s.IAQAccuracy; a != nil && (sb.accuracy == nil || *a < *sb.accuracy) { + sb.accuracy = a + } + } +} + +func (b *nodeBucket) sensorPoints() []NodeSensor { + if len(b.sensors) == 0 { + return nil + } + out := make([]NodeSensor, 0, len(b.sensors)) + for ch, sb := range b.sensors { + s := NodeSensor{Channel: ch} + for f, field := range sensorFields { + if m := sb.m[f]; m.n > 0 { + scale := math.Pow10(field.decimals) + *field.get(&s) = ptr(math.Round(m.sum/float64(m.n)*scale) / scale) + } + } + if s.IAQ != nil { + s.IAQAccuracy = sb.accuracy + } + out = append(out, s) + } + sort.Slice(out, func(i, j int) bool { return out[i].Channel < out[j].Channel }) + return out } func (b *nodeBucket) addPair(p counterPair) { @@ -248,6 +345,7 @@ func BucketNodeReadings(readings []NodeReading, since time.Time, size time.Durat cur.rssi.add(i32f(r.LastRSSIDB)) cur.snr.add(f64(r.LastSNRDB)) cur.qlen.add(i32f(r.QueueLength)) + cur.addSensors(r.Sensors) if r.UptimeSeconds != nil && (cur.uptime == nil || *r.UptimeSeconds > *cur.uptime) { cur.uptime = r.UptimeSeconds } @@ -255,7 +353,7 @@ func BucketNodeReadings(readings []NodeReading, since time.Time, size time.Durat out := make([]NodeTelemetryPoint, 0, len(buckets)) for _, cur := range buckets { - p := NodeTelemetryPoint{T: cur.start.UnixMilli(), Readings: cur.readings, UptimeSeconds: cur.uptime} + p := NodeTelemetryPoint{T: cur.start.UnixMilli(), Readings: cur.readings, UptimeSeconds: cur.uptime, Sensors: cur.sensorPoints()} p.BatteryMV = roundedMean32(cur.battery) p.NoiseFloorDB = roundedMean32(cur.noise) p.LastRSSIDB = roundedMean32(cur.rssi) diff --git a/internal/api/node_telemetry_test.go b/internal/api/node_telemetry_test.go index 468fc6d2..8d718eb5 100644 --- a/internal/api/node_telemetry_test.go +++ b/internal/api/node_telemetry_test.go @@ -461,3 +461,51 @@ func TestForeignShare(t *testing.T) { } } } + +func TestBucketNodeReadingsSensors(t *testing.T) { + f := func(v float64) *float64 { return &v } + n := func(v int) *int { return &v } + rs := []NodeReading{ + {SampledAt: at(1), Sensors: []NodeSensor{ + {Channel: 2, TemperatureC: f(20), HumidityPct: f(40), PressureHpa: f(1010), IAQ: f(50), IAQAccuracy: n(3)}, + {Channel: 3, VoltageV: f(8.70), CurrentA: f(0.122), PowerW: f(1.061)}, + }}, + {SampledAt: at(2), Sensors: []NodeSensor{ + {Channel: 3, VoltageV: f(8.60), CurrentA: f(0.100), PowerW: f(0.863)}, + {Channel: 2, TemperatureC: f(21), HumidityPct: f(45.5), PressureHpa: f(1012.5), IAQ: f(61), IAQAccuracy: n(1)}, + }}, + {SampledAt: at(3), BatteryMV: ptr(int32(4000))}, // a status reading with no sensor channels + {SampledAt: at(7), Sensors: []NodeSensor{{Channel: 2, GasOhms: f(50000.4)}}}, + {SampledAt: at(13), BatteryMV: ptr(int32(4000))}, + } + got := BucketNodeReadings(rs, nodeBase, 6*time.Hour) + if len(got) != 3 { + t.Fatalf("points = %d", len(got)) + } + b, _ := json.Marshal(got[0].Sensors) + want := `[{"channel":2,"temperatureC":20.5,"humidityPct":42.8,"pressureHpa":1011.3,"iaq":56,"iaqAccuracy":1},` + + `{"channel":3,"voltageV":8.65,"currentA":0.111,"powerW":0.962}]` + if string(b) != want { + t.Errorf("first bucket\n got %s\nwant %s", b, want) + } + if b, _ := json.Marshal(got[1].Sensors); string(b) != `[{"channel":2,"gasOhms":50000}]` { + t.Errorf("second bucket %s", b) + } + // A bucket with no sensor channels leaves the field out altogether. + if b, _ := json.Marshal(got[2]); strings.Contains(string(b), "sensors") { + t.Errorf("third bucket %s", b) + } +} + +// What a client reads of a reading never includes its raw LPP bytes, which can hold a position. +func TestNodeTelemetryPointHasNoRawLPP(t *testing.T) { + f := 1.0 + p := NodeTelemetryPoint{Sensors: []NodeSensor{{Channel: 2, TemperatureC: &f, HumidityPct: &f, PressureHpa: &f, GasOhms: &f, IAQ: &f, + VoltageV: &f, CurrentA: &f, PowerW: &f, DistanceM: &f, Percent: &f, LuminosityLux: &f}}} + b, _ := json.Marshal(p) + for _, word := range []string{"lpp", "lat", "lon", "lng", "alt", "gps"} { + if strings.Contains(strings.ToLower(string(b)), word) { + t.Fatalf("%q in %s", word, b) + } + } +} diff --git a/internal/api/router/router.go b/internal/api/router/router.go index e5e7bbdf..9074614c 100644 --- a/internal/api/router/router.go +++ b/internal/api/router/router.go @@ -81,7 +81,7 @@ func New(h *hub.Hub, reader api.Reader, workers []*ingest.Worker, opts Options) Mobile: api.AdminMobileConfig{MinAppVersion: opts.MinAppVersion}, Web: api.AdminWebConfig{MinWebVersion: opts.MinWebVersion}, } - features := api.InfoFeatures{Polling: opts.PollingEnabled, Accounts: "off", TelemetryRequests: opts.TelemetryRequests, AtlasTelemetry: true, AtlasPoller: true, Atlas7d: true, MapTelemetry: true, AppDeviceLabel: true} + features := api.InfoFeatures{Polling: opts.PollingEnabled, Accounts: "off", TelemetryRequests: opts.TelemetryRequests, AtlasTelemetry: true, Sensors: true, AtlasPoller: true, Atlas7d: true, MapTelemetry: true, AppDeviceLabel: true} switch opts.AccountsMode { case "local": features.Accounts, features.Registration = "local", opts.RegistrationOpen diff --git a/internal/api/router/router_test.go b/internal/api/router/router_test.go index ce28cebf..cf218173 100644 --- a/internal/api/router/router_test.go +++ b/internal/api/router/router_test.go @@ -123,8 +123,8 @@ func TestInfoAccountsFeatures(t *testing.T) { func TestInfoFeatures(t *testing.T) { for polling, want := range map[bool]string{ - true: `"features":{"polling":true,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":true,"atlasPoller":true,"atlas7d":true,"mapTelemetry":true,"appDeviceLabel":true}`, - false: `"features":{"polling":false,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":true,"atlasPoller":true,"atlas7d":true,"mapTelemetry":true,"appDeviceLabel":true}`, + true: `"features":{"polling":true,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":true,"sensors":true,"atlasPoller":true,"atlas7d":true,"mapTelemetry":true,"appDeviceLabel":true}`, + false: `"features":{"polling":false,"accounts":"off","registration":false,"telemetryRequests":false,"alerts":false,"alertChannels":{"email":false,"push":false},"atlasTelemetry":true,"sensors":true,"atlasPoller":true,"atlas7d":true,"mapTelemetry":true,"appDeviceLabel":true}`, } { handler := New(nil, nil, nil, Options{ServerVersion: "2.0.2", PollingEnabled: polling}) response := httptest.NewRecorder() diff --git a/internal/polling/lpp.go b/internal/polling/lpp.go index 7b1c721a..03739d1c 100644 --- a/internal/polling/lpp.go +++ b/internal/polling/lpp.go @@ -3,12 +3,18 @@ package polling -// lppValueSize mirrors the firmware's table. -1 means an unknown type. +import ( + "math" + "sort" +) + +// lppValueSize is the size the CayenneLPP library writes for each type. -1 means an unknown type. +// Humidity is one byte on the wire; the firmware's own skip table says two, which is wrong. func lppValueSize(t byte) int { switch t { - case 0, 1, 102, 120, 142: + case 0, 1, 102, 104, 120, 142: return 1 - case 2, 3, 101, 103, 104, 115, 116, 117, 121, 125, 128, 132: + case 2, 3, 101, 103, 115, 116, 117, 121, 125, 128, 132: return 2 case 135: return 3 @@ -64,3 +70,161 @@ func DecodeLPP(b []byte) (batteryMV *int, temperatureC *float64) { } return batteryMV, temperatureC } + +// LPP types the sensor decoder reads. GPS (136) and altitude (121) are skipped on purpose: neither a position nor +// anything derived from one is kept. +const ( + lppAnalogInput = 2 + lppGeneric = 100 + lppLuminosity = 101 + lppHumidity = 104 + lppPressure = 115 + lppCurrent = 117 + lppFrequency = 118 + lppPercentage = 120 + lppPower = 128 + lppDistance = 130 + + // MaxSensorChannels caps what one reading stores. + MaxSensorChannels = 16 + + // An added sensor can be an infrared thermometer, which reads far outside what the board itself survives. + sensorTempMin, sensorTempMax = -273.0, 1000.0 +) + +// Sensor is what one LPP channel carried, in the JSON shape it is stored and served in. Channel 1 is the device +// itself, whose voltage and temperature are the reading's own battery and temperature and are not repeated here. +type Sensor struct { + Channel int `json:"channel"` + TemperatureC *float64 `json:"temperatureC,omitempty"` + HumidityPct *float64 `json:"humidityPct,omitempty"` + PressureHpa *float64 `json:"pressureHpa,omitempty"` + GasOhms *float64 `json:"gasOhms,omitempty"` + IAQ *float64 `json:"iaq,omitempty"` + IAQAccuracy *int `json:"iaqAccuracy,omitempty"` + VoltageV *float64 `json:"voltageV,omitempty"` + CurrentA *float64 `json:"currentA,omitempty"` + PowerW *float64 `json:"powerW,omitempty"` + DistanceM *float64 `json:"distanceM,omitempty"` + Percent *float64 `json:"percent,omitempty"` + LuminosityLux *float64 `json:"luminosityLux,omitempty"` +} + +func (s Sensor) empty() bool { + return s.TemperatureC == nil && s.HumidityPct == nil && s.PressureHpa == nil && s.GasOhms == nil && s.IAQ == nil && + s.VoltageV == nil && s.CurrentA == nil && s.PowerW == nil && s.DistanceM == nil && s.Percent == nil && + s.LuminosityLux == nil +} + +// DecodeSensors reads the sensor channels of raw CayenneLPP, ascending by channel. It stops where DecodeLPP stops +// and keeps what it decoded. The first record of each type on a channel wins; a value out of range is left out. +// Voltage and current are signed on the wire (a power monitor reads a reverse current), whatever the library's +// comments say. +func DecodeSensors(b []byte) []Sensor { + type raw struct { + s Sensor + generic, analog *float64 + power *float64 + frequency bool + sawT, sawV bool + } + chans := map[int]*raw{} + cut := false // the walk stopped on a record it could not read + for i := 0; i+2 <= len(b); { + ch, typ := int(b[i]), b[i+1] + if ch == 0 { + break + } + sz := lppValueSize(typ) + if sz < 0 || i+2+sz > len(b) { + cut = true + break + } + v := b[i+2 : i+2+sz] + i += 2 + sz + c := chans[ch] + if c == nil { + if len(chans) >= MaxSensorChannels { + continue + } + c = &raw{s: Sensor{Channel: ch}} + chans[ch] = c + } + var u uint32 + for _, x := range v { + u = u<<8 | uint32(x) + } + set := func(dst **float64, val float64, lo, hi float64) { + if *dst == nil && val >= lo && val <= hi { + *dst = &val + } + } + switch typ { + case lppTemperature: + if ch != lppChannelSelf && !c.sawT { + c.sawT = true + set(&c.s.TemperatureC, float64(int16(u))/10, sensorTempMin, sensorTempMax) + } + case lppVoltage: + if ch != lppChannelSelf && !c.sawV { + c.sawV = true + set(&c.s.VoltageV, float64(int16(u))/100, -327.68, 327.67) + } + case lppHumidity: + set(&c.s.HumidityPct, float64(u)/2, 0, 100) + case lppPressure: + set(&c.s.PressureHpa, float64(u)/10, 300, 1100) + case lppCurrent: + set(&c.s.CurrentA, float64(int16(u))/1000, -32.768, 32.767) + case lppPower: + set(&c.power, float64(u), 0, 65535) + case lppDistance: + set(&c.s.DistanceM, float64(u)/1000, 0, 4294967.295) + case lppPercentage: + set(&c.s.Percent, float64(u), 0, 100) + case lppLuminosity: + set(&c.s.LuminosityLux, float64(u), 0, 65535) + case lppGeneric: + set(&c.generic, float64(u), 0, 4294967295) + case lppAnalogInput: + set(&c.analog, float64(int16(u))/100, -327.68, 327.67) + case lppFrequency: + c.frequency = true + } + } + out := make([]Sensor, 0, len(chans)) + for _, c := range chans { + s := c.s + // The firmware's soil sensor reuses temperature and power on a calibration channel for other figures. + if c.frequency { + continue + } + // The computed product keeps the decimals the wire's whole watts lose. + switch { + case s.VoltageV != nil && s.CurrentA != nil: + w := math.Round(*s.VoltageV**s.CurrentA*1000) / 1000 + s.PowerW = &w + case s.VoltageV != nil || s.CurrentA != nil: + s.PowerW = c.power + } + // A gas sensor has no LPP type of its own: beside humidity and pressure, the generic value is its reading. + // With an analog value next to it, it is an air quality index and the analog value is its accuracy (0 to 3). + if c.generic != nil && s.HumidityPct != nil && s.PressureHpa != nil { + if a := c.analog; a != nil && *a >= 0 && *a <= 3 && *a == math.Trunc(*a) && *c.generic <= 500 { + acc := int(*a) + s.IAQ, s.IAQAccuracy = c.generic, &acc + } else if a == nil && !cut { + // Cut short, the accuracy value may be what was lost, and the figure cannot be told apart. + s.GasOhms = c.generic + } + } + if !s.empty() { + out = append(out, s) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Channel < out[j].Channel }) + if len(out) == 0 { + return nil + } + return out +} diff --git a/internal/polling/lpp_sensors_test.go b/internal/polling/lpp_sensors_test.go new file mode 100644 index 00000000..118b3080 --- /dev/null +++ b/internal/polling/lpp_sensors_test.go @@ -0,0 +1,95 @@ +// Copyright 2026 Beacon Contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +package polling + +import ( + "encoding/hex" + "encoding/json" + "strings" + "testing" +) + +func sensorsOf(t *testing.T, h string) string { + t.Helper() + b, err := hex.DecodeString(strings.ReplaceAll(h, " ", "")) + if err != nil { + t.Fatal(err) + } + out, err := json.Marshal(DecodeSensors(b)) + if err != nil { + t.Fatal(err) + } + return string(out) +} + +const ( + lppSelf = "0174018a 016700a5" // 3.94 V, 16.5 C + lppGPS = "0188 06f7c8 f4b2e0 002710" // a position on channel 1 + lppBSEC = "026700d6 02685b 02732794 02790064 026400000032 0202012c" // 21.4 C, 45.5 %, 1013.2 hPa, altitude, IAQ 50, accuracy 3 + lppBME = "026700d6 02685b 02732794 02790064 02640000c350" // the same with a 50 kOhm gas resistance + lppINA = "03740366 0375007a 03800001" // 8.70 V, 0.122 A, 1 W +) + +func TestDecodeSensors(t *testing.T) { + cases := []struct{ name, hex, want string }{ + {"nothing but the device itself", lppSelf, "null"}, + {"air quality sensor and a power monitor", lppSelf + lppGPS + lppBSEC + lppINA, + `[{"channel":2,"temperatureC":21.4,"humidityPct":45.5,"pressureHpa":1013.2,"iaq":50,"iaqAccuracy":3},` + + `{"channel":3,"voltageV":8.7,"currentA":0.122,"powerW":1.061}]`}, + {"gas resistance without the accuracy value", lppBME, + `[{"channel":2,"temperatureC":21.4,"humidityPct":45.5,"pressureHpa":1013.2,"gasOhms":50000}]`}, + {"a generic value with no humidity and pressure beside it is not a gas reading", "026700d6 02640000c350", `[{"channel":2,"temperatureC":21.4}]`}, + {"an accuracy out of range names nothing", "02685b 02732794 026400000032 020201f4", `[{"channel":2,"humidityPct":45.5,"pressureHpa":1013.2}]`}, + {"the wire's whole watts when a side is missing", "03740366 03800002", `[{"channel":3,"voltageV":8.7,"powerW":2}]`}, + {"power alone means nothing", "03800002", "null"}, + {"built-in sensors on channel 1, without its voltage and temperature", lppSelf + "01685b 01732794 0165012c", + `[{"channel":1,"humidityPct":45.5,"pressureHpa":1013.2,"luminosityLux":300}]`}, + {"two temperatures on two channels", "026700d6 036700c8", `[{"channel":2,"temperatureC":21.4},{"channel":3,"temperatureC":20}]`}, + {"an infrared thermometer's object and ambient channels", "026705dc 036700fa", `[{"channel":2,"temperatureC":150},{"channel":3,"temperatureC":25}]`}, + {"an object colder than the board survives", "0267fd44", `[{"channel":2,"temperatureC":-70}]`}, + {"a reverse current is negative, and so is its power", "03740320 0375ff06 03800002", `[{"channel":3,"voltageV":8,"currentA":-0.25,"powerW":-2}]`}, + {"a negative voltage", "0374ff9c 03750064", `[{"channel":3,"voltageV":-1,"currentA":0.1,"powerW":-0.1}]`}, + {"zero current", "03740320 03750000", `[{"channel":3,"voltageV":8,"currentA":0,"powerW":0}]`}, + {"the signed limits", "03747fff 03758000", `[{"channel":3,"voltageV":327.67,"currentA":-32.768,"powerW":-10737.091}]`}, + {"an air quality reading cut off before its accuracy is not called a resistance", "02685b 02732794 026400000032 0202", `[{"channel":2,"humidityPct":45.5,"pressureHpa":1013.2}]`}, + {"distance and moisture", "0282000004d2 037837", `[{"channel":2,"distanceM":1.234},{"channel":3,"percent":55}]`}, + {"the soil sensor's calibration channel is dropped", "03760000012c 036700c8 03800190", "null"}, + {"out of range values are left out", "0268c9 02730001 026700d6", `[{"channel":2,"temperatureC":21.4}]`}, + {"first of a type wins", "02685b 026864", `[{"channel":2,"humidityPct":45.5}]`}, + {"stops at an unknown type and keeps the rest", "02685b 02fa00 02732794", `[{"channel":2,"humidityPct":45.5}]`}, + {"stops at a truncated record", "02685b 027327", `[{"channel":2,"humidityPct":45.5}]`}, + {"empty", "", "null"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := sensorsOf(t, tc.hex); got != tc.want { + t.Errorf("got %s\nwant %s", got, tc.want) + } + }) + } +} + +// Nothing a position could be read from is ever in the decoded sensors. +func TestDecodeSensorsKeepsNoPosition(t *testing.T) { + got := sensorsOf(t, lppSelf+lppGPS+"0288 06f7c8 f4b2e0 002710"+lppBSEC) + for _, word := range []string{"lat", "lon", "lng", "alt", "gps", "45.6", "-74"} { + if strings.Contains(strings.ToLower(got), word) { + t.Fatalf("%q in %s", word, got) + } + } + if !strings.Contains(got, `"humidityPct":45.5`) { + t.Fatalf("the sensor after the positions was lost: %s", got) + } +} + +func TestDecodeSensorsCapsChannels(t *testing.T) { + var h strings.Builder + for ch := 2; ch < 2+MaxSensorChannels+5; ch++ { + h.WriteString(hex.EncodeToString([]byte{byte(ch), 0x68, 0x5b})) + } + b, _ := hex.DecodeString(h.String()) + if got := len(DecodeSensors(b)); got != MaxSensorChannels { + t.Fatalf("%d channels", got) + } +} diff --git a/internal/polling/wire.go b/internal/polling/wire.go index eff5e96f..0b95af5d 100644 --- a/internal/polling/wire.go +++ b/internal/polling/wire.go @@ -75,9 +75,11 @@ type Reading struct { // PollRSSI is the signal strength of the repeater's reply, in dBm; nil when the firmware does not send it. PollRSSI *int // Signed is true when the message carried a signature by the observer's key and it checked out. - Signed bool - Stats Stats - LPP []byte + Signed bool + Stats Stats + LPP []byte + // Sensors is what the LPP's sensor channels carried; nil when it carried none. + Sensors []Sensor PacketHash []byte } @@ -411,6 +413,7 @@ func parseReading(rw readingWire, ver int, obs []byte, client string) (Reading, r.PollRSSI = &rssi } if len(r.LPP) > 0 { + r.Sensors = DecodeSensors(r.LPP) mv, c := DecodeLPP(r.LPP) if r.BatteryMV == nil && mv != nil && *mv > 0 { r.BatteryMV = mv diff --git a/internal/polling/wire_test.go b/internal/polling/wire_test.go index f110975b..64b23eb8 100644 --- a/internal/polling/wire_test.go +++ b/internal/polling/wire_test.go @@ -335,7 +335,7 @@ func TestDecodeLPP(t *testing.T) { {"empty", "", nil, nil}, {"stops at channel 0", "000001740" + "18a", nil, nil}, {"truncated voltage", "017401", nil, nil}, - {"skips other record then reads", "0268006401" + "74018a", ip(3940), nil}, + {"skips a one byte humidity then reads", "026864" + "0174018a", ip(3940), nil}, {"first temperature wins even if out of range", "0167fd00" + "016700a5", nil, nil}, {"unknown type stops walk", "01fa00" + "01" + "74018a", nil, nil}, } From 8a194e337e2f1bedaab9729c25dc9a9ed7381da0 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 22:50:43 -0500 Subject: [PATCH 4/7] chore: bump version to 2.3.4 --- cmd/beacon/main.go | 2 +- docs/docs.go | 2 +- docs/swagger.json | 2 +- docs/swagger.yaml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/beacon/main.go b/cmd/beacon/main.go index 8e088d46..dad69c81 100644 --- a/cmd/beacon/main.go +++ b/cmd/beacon/main.go @@ -56,7 +56,7 @@ import ( var version = "dev" // @title MeshCore Beacon API -// @version 2.3.3 +// @version 2.3.4 // @description MeshCore network observation backend. Ingests LoRa packets from MQTT brokers, stores in PostgreSQL, and streams live events via WebSocket. // @description REST requests share a configurable per-client rate limit (default 600/minute and a 600-request one-second burst cap). Exceeded limits return HTTP 429 with error.code=rate_limited and a Retry-After header in seconds. CORS preflights and WebSocket upgrades do not consume this API budget. // @description WebSocket upgrade attempts at /ws have a configurable per-client limit (default 10/minute, including failed handshakes). Rate exhaustion returns HTTP 429 with Retry-After before upgrade. An accepted socket exceeding the concurrent cap closes with code 1013 before hello; established connections remain open. diff --git a/docs/docs.go b/docs/docs.go index d9a2978e..062c1be3 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -12364,7 +12364,7 @@ const docTemplate = `{ // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = &swag.Spec{ - Version: "2.3.3", + Version: "2.3.4", Host: "localhost:8080", BasePath: "/api/v1", Schemes: []string{"http", "https"}, diff --git a/docs/swagger.json b/docs/swagger.json index cbd81418..5e4c0600 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -15,7 +15,7 @@ "license": { "name": "AGPL-3-or-later" }, - "version": "2.3.3" + "version": "2.3.4" }, "host": "localhost:8080", "basePath": "/api/v1", diff --git a/docs/swagger.yaml b/docs/swagger.yaml index f99171a2..8f1f0478 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -3303,7 +3303,7 @@ info: name: AGPL-3-or-later termsOfService: https://github.com/MeshCore-Beacon/beacon-server title: MeshCore Beacon API - version: 2.3.3 + version: 2.3.4 paths: /admin/accounts: get: From b661b7a8039f32146d46abf1dd81ffc5d6857d4f Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 23:00:23 -0500 Subject: [PATCH 5/7] feat(api): require Beacon Web and BEACON Mobile 2.3.4 --- internal/api/info.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/api/info.go b/internal/api/info.go index cfc41732..c943e491 100644 --- a/internal/api/info.go +++ b/internal/api/info.go @@ -11,8 +11,8 @@ import ( // Client floors this server code needs. Bump the matching one when a release breaks older // clients; config can raise them, never lower them. Empty means no requirement. const ( - MinAppVersion = "2.3.0" // BEACON Mobile: alert push through the push server - MinWebVersion = "2.3.0" // Beacon Web: alert channel switches + MinAppVersion = "2.3.4" // BEACON Mobile: sensor tiles and the telemetry_stopped alert + MinWebVersion = "2.3.4" // Beacon Web: sensor tiles and the telemetry_stopped alert // BEACON Mobile: the first release that sends a /ws ticket, required while websocket.require_origin is on TicketAppVersion = "2.1.1" ) From a6705a774ed6e441974e7f090f9c46a2f337e3bf Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 23:35:34 -0500 Subject: [PATCH 6/7] fix(alerts): telemetry stopped rules go inactive while polling is off --- db/alerts_eval.go | 1 + db/alerts_final_integration_test.go | 12 ++++++++++++ internal/alerts/evaluate.go | 7 +++++-- internal/alerts/evaluate_test.go | 3 +++ 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/db/alerts_eval.go b/db/alerts_eval.go index 216e37f8..cae0c2cf 100644 --- a/db/alerts_eval.go +++ b/db/alerts_eval.go @@ -157,6 +157,7 @@ func (a AlertEval) LoadTargets(ctx context.Context, rules []alerts.RuleRow, now for _, n := range nodes { td := alerts.TargetData{Name: n.Name} td.Exists, td.Polled, td.LastHeard, td.LastReading = true, n.Polled, tsTime(n.LastSeen), tsTime(n.LastReadingAt) + td.PollingOff = a.pollingOff.Load() out[alerts.TargetID(alerts.TargetNode, n.PublicKey)] = td } reads, err := a.q.AlertNodeReadings(ctx, sqlc.AlertNodeReadingsParams{Keys: nodeKeys, Since: since}) diff --git a/db/alerts_final_integration_test.go b/db/alerts_final_integration_test.go index 01580eea..d5ff2e0a 100644 --- a/db/alerts_final_integration_test.go +++ b/db/alerts_final_integration_test.go @@ -185,6 +185,11 @@ func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) { VALUES ($1, 'node', $2, 'battery_low', 3500, now() - interval '3 days')`, u.ID, rep); err != nil { t.Fatal(err) } + // Set two days ago with a 1 hour limit: firing while polling is on. + if _, err := pool.Exec(ctx, `INSERT INTO user_alert_rules (user_id, target_kind, target_public_key, kind, threshold, cursor_at) + VALUES ($1, 'node', $2, 'telemetry_stopped', 3, now() - interval '2 days')`, u.ID, rep); err != nil { + t.Fatal(err) + } task := alerts.NewTask(AlertEval{s}, time.Now) if err := task.Run(ctx); err != nil { t.Fatal(err) @@ -192,6 +197,9 @@ func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) { if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "firing" { t.Fatalf("with polling on: %s", got) } + if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "ok" { + t.Fatalf("telemetry_stopped with a reading 10 minutes old: %s", got) + } s.SetPollingEnabled(false) ov, err := svc.Overview(ctx, u.ID) if err != nil || len(ov.Targets) != 1 || ov.Targets[0].Caps.Polled { @@ -206,6 +214,10 @@ func TestAlertTelemetryStopsWhenPollingIsOffPostgres(t *testing.T) { if got := ruleStateOf(t, ctx, pool, "battery_low"); got != "inactive" { t.Fatalf("rule with polling off: %s", got) } + // The stopped rule would otherwise fire for every repeater once its hours passed. + if got := ruleStateOf(t, ctx, pool, "telemetry_stopped"); got != "inactive" { + t.Fatalf("telemetry_stopped with polling off: %s", got) + } } // The sender takes the notices of a finished pass only, so a pass that is still being evaluated is not split across diff --git a/internal/alerts/evaluate.go b/internal/alerts/evaluate.go index 197ed4c9..83bd4078 100644 --- a/internal/alerts/evaluate.go +++ b/internal/alerts/evaluate.go @@ -66,6 +66,8 @@ type Data struct { LastHeard time.Time // StatusAt is the observer's last status report. StatusAt time.Time + // PollingOff: this server has polling switched off, so no reading can arrive. + PollingOff bool // LastReading is the repeater's newest trusted reading still stored, of any age; zero when there is none. LastReading time.Time // Readings are the newest first. @@ -137,8 +139,9 @@ func Evaluate(r Rule, d Data) Outcome { out = set(r.Threshold != nil && quiet >= time.Duration(*r.Threshold)*time.Minute, int64(quiet/time.Minute)) case KindTelemetryStop: // The clock runs from the newest reading or from when the rule was set, whichever is later. The cursor keeps - // that time, so the rule still fires after retention has deleted the last reading. - if !d.Exists { + // that time, so the rule still fires after retention has deleted the last reading. With polling switched + // off nothing can arrive, and saying so about every repeater would only be noise. + if !d.Exists || d.PollingOff { return inactive() } if d.LastReading.After(o.Cursor) { diff --git a/internal/alerts/evaluate_test.go b/internal/alerts/evaluate_test.go index 5f0014e1..f92face3 100644 --- a/internal/alerts/evaluate_test.go +++ b/internal/alerts/evaluate_test.go @@ -90,6 +90,9 @@ func TestEvaluateTelemetryStopped(t *testing.T) { {"last reading deleted", rule(StateFiring, 9*time.Hour), Data{Exists: true}, StateFiring, false, 0}, {"deleted before it fired", rule(StateOK, 9*time.Hour), Data{Exists: true}, StateFiring, true, 9}, {"node gone", rule(StateOK, 9*time.Hour), Data{LastReading: ago(time.Hour)}, StateInactive, false, 0}, + // Polling switched off for the whole server: no reading can arrive, so nothing is said. + {"polling off", rule(StateOK, 9*time.Hour), Data{Exists: true, PollingOff: true, LastReading: ago(8 * time.Hour)}, StateInactive, false, 0}, + {"polling off while firing", rule(StateFiring, 9*time.Hour), Data{Exists: true, PollingOff: true}, StateInactive, false, 0}, }) // The newest reading moves the cursor, and nothing moves it back. if got := Evaluate(rule(StateOK, 48*time.Hour), Data{Now: now, Exists: true, LastReading: ago(time.Hour)}); !got.Cursor.Equal(ago(time.Hour)) { From b8f6acbe85645a7a226a94e4ea9b0c3ef865d71c Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 29 Nov 2026 23:35:56 -0500 Subject: [PATCH 7/7] docs(config): example floors are 2.3.4 --- config.yaml.example | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config.yaml.example b/config.yaml.example index 6ea879b4..461fde40 100644 --- a/config.yaml.example +++ b/config.yaml.example @@ -428,9 +428,9 @@ cache: # can raise it, never lower it. Strict X.Y.Z (no v, no suffix); anything else # prevents startup. Default: empty, the built-in floor only. #mobile: -# min_app_version: "2.3.0" # BEACON Mobile; built-in floor: 2.3.0 +# min_app_version: "2.3.4" # BEACON Mobile; built-in floor: 2.3.4 #web: -# min_web_version: "2.3.0" # Beacon Web; built-in floor: 2.3.0 +# min_web_version: "2.3.4" # Beacon Web; built-in floor: 2.3.4 # Repeater polling: observers ask nearby repeaters for battery, temperature and counters, and # Beacon picks which observer polls which repeater and stores the readings. Off by default.