// Copyright 2026 Beacon Contributors // SPDX-License-Identifier: AGPL-3.0-or-later package api import ( "math" "sort" "time" "github.com/google/uuid" ) // Packets a radio can't beat per second; a higher claimed rate is a garbage reading. const packetRate = 50.0 // Counters only arrive on status readings, which a poller may take up to 24h apart. A pair // two such intervals apart still places growth in a bucket; a longer one can't be placed, so it // is dropped. Independent of the bucket size, which can be much finer than the poll interval. const nodeCounterMaxGap = 48 * time.Hour // NodeReading is one stored reading of a polled node, ascending by SampledAt. type NodeReading struct { SampledAt time.Time // Method is how the reading was taken, "status" or "telemetry". Only consecutive status readings make counter // pairs, whatever their counters hold. Method string Trusted bool // Foreign is true when the reading came from an observer this server does not manage. Foreign bool BatteryMV *int32 TemperatureC *float32 NoiseFloorDB *int32 LastRSSIDB *int32 LastSNRDB *float32 UptimeSeconds *int64 QueueLength *int32 AirtimeTxSecs *int64 AirtimeRxSecs *int64 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 // bucket, covering counterSpanSecs of elapsed time, uptime is the bucket maximum, the rest are averages. A field is omitted when no // reading in the bucket carried it. type NodeTelemetryPoint struct { T int64 `json:"t"` // epoch ms, bucket start Readings int `json:"readings"` BatteryMV *int32 `json:"batteryMv,omitempty"` TemperatureC *float32 `json:"temperatureC,omitempty"` NoiseFloorDB *int32 `json:"noiseFloorDb,omitempty"` LastRSSIDB *int32 `json:"lastRssiDb,omitempty"` LastSNRDB *float32 `json:"lastSnrDb,omitempty"` UptimeSeconds *int64 `json:"uptimeSeconds,omitempty"` QueueLength *int32 `json:"queueLength,omitempty"` AirtimeTxSecs *float64 `json:"airtimeTxSecs,omitempty"` AirtimeRxSecs *float64 `json:"airtimeRxSecs,omitempty"` PacketsReceived *int64 `json:"packetsReceived,omitempty"` PacketsSent *int64 `json:"packetsSent,omitempty"` ReceiveErrors *int64 `json:"receiveErrors,omitempty"` // 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. type NodeTelemetry struct { Range string `json:"range"` Interval string `json:"interval"` Polled bool `json:"polled"` // any reading has ever been stored for the node UntrustedReadings int `json:"untrustedReadings"` // readings in range left out because include=untrusted was not set // Foreign says how many of the readings behind the points came from observers this server does not manage: // none, some or all. It is none when there are no points. Foreign string `json:"foreign" enums:"none,some,all"` Points []NodeTelemetryPoint `json:"points"` } // ForeignShare is NodeTelemetry.Foreign for the readings BucketNodeReadings turns into points: those sampled at or // after since. The earlier reading that only serves as a counter baseline is not one of them. func ForeignShare(readings []NodeReading, since time.Time) string { total, foreign := 0, 0 for i := range readings { if readings[i].SampledAt.Before(since) { continue } total++ if readings[i].Foreign { foreign++ } } switch { case foreign == 0: return "none" case foreign == total: return "all" } return "some" } // nodeCounters are the five since-boot counters on a status reading, each with the fastest // rate per second it can honestly climb. var nodeCounters = [5]struct { get func(*NodeReading) *int64 cap float64 }{ {func(r *NodeReading) *int64 { return r.AirtimeTxSecs }, airtimeRate}, {func(r *NodeReading) *int64 { return r.AirtimeRxSecs }, airtimeRate}, {func(r *NodeReading) *int64 { return r.PacketsReceived }, packetRate}, {func(r *NodeReading) *int64 { return r.PacketsSent }, packetRate}, {func(r *NodeReading) *int64 { return r.ReceiveErrors }, errorRate}, } const ( ctrTx = iota ctrRx ctrRecv ctrSent ctrErrs ) // isStatusReading goes by the reading's method, not its counters: a status reply too short to carry any is still the // status reading its neighbours pair with, which is also how the store picks the baseline before a range. func isStatusReading(r *NodeReading) bool { return r.Method == "status" } // counterPair is what one pair of consecutive status readings contributes. type counterPair struct { inc [5]int64 has [5]bool spanMS int64 } // pairIncrements reads only prev and cur, so a pair gives the same answer whatever range was // asked for. It reports false when the pair can't be trusted to say anything. func pairIncrements(prev, cur *NodeReading) (counterPair, bool) { var p counterPair elapsed := cur.SampledAt.Sub(prev.SampledAt).Milliseconds() if elapsed <= 0 || elapsed > nodeCounterMaxGap.Milliseconds() { return p, false } rebooted := prev.UptimeSeconds != nil && cur.UptimeSeconds != nil && (*cur.UptimeSeconds < *prev.UptimeSeconds || *cur.UptimeSeconds*1000 < elapsed) var drops, rises int var vals [5][2]int64 for i, c := range nodeCounters { pv, cv := c.get(prev), c.get(cur) if pv == nil || cv == nil { continue } if *pv < 0 || *cv < 0 { return p, false // a counter cannot be negative; whatever sent one is not to be believed } vals[i] = [2]int64{*pv, *cv} p.has[i] = true if *cv < *pv { drops++ } else { rises++ } } if drops+rises == 0 { return p, false } p.spanMS = elapsed switch { case rebooted && drops > 0 && rises == 0: // the counters restarted with the device if up := *cur.UptimeSeconds * 1000; up < elapsed { p.spanMS = up } for i := range p.inc { p.inc[i] = vals[i][1] } case drops == 0: // counting on, through a reboot or not for i := range p.inc { p.inc[i] = vals[i][1] - vals[i][0] } default: return p, false } if p.spanMS < 1000 { return p, false } secs := float64(p.spanMS) / 1000 for i, c := range nodeCounters { if p.has[i] && float64(p.inc[i])/secs > c.cap { return p, false } } return p, true } type nodeBucket struct { start time.Time readings int battery, temp, noise, rssi mean snr, qlen mean uptime *int64 pairs int 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) { b.pairs++ b.spanMS += p.spanMS for i := range p.inc { if p.has[i] { b.inc[i] += p.inc[i] b.carried[i]++ } } } // BucketNodeReadings folds readings (ascending, with any before since serving only as the first // pair's predecessor) into fixed UTC buckets of size. Buckets with no readings are not emitted. // Counter increments come from consecutive pairs of status readings, credited to the bucket of // the later one. func BucketNodeReadings(readings []NodeReading, since time.Time, size time.Duration) []NodeTelemetryPoint { var prevStatus *NodeReading var buckets []*nodeBucket for i := range readings { r := &readings[i] var pair counterPair var paired bool if isStatusReading(r) { if prevStatus != nil { pair, paired = pairIncrements(prevStatus, r) } prevStatus = r } if r.SampledAt.Before(since) { continue } start := r.SampledAt.UTC().Truncate(size) if len(buckets) == 0 || !buckets[len(buckets)-1].start.Equal(start) { buckets = append(buckets, &nodeBucket{start: start}) } cur := buckets[len(buckets)-1] cur.readings++ if paired { cur.addPair(pair) } cur.battery.add(i32f(r.BatteryMV)) cur.temp.add(f64(r.TemperatureC)) cur.noise.add(i32f(r.NoiseFloorDB)) 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 } } out := make([]NodeTelemetryPoint, 0, len(buckets)) for _, cur := range buckets { 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) p.QueueLength = roundedMean32(cur.qlen) p.TemperatureC = tenthsMean(cur.temp) p.LastSNRDB = tenthsMean(cur.snr) if cur.pairs > 0 { p.CounterSpanSecs = ptr(cur.spanMS / 1000) // A counter missing from any contributing pair would understate its rate, so it is left out. full := func(i int) bool { return cur.carried[i] == cur.pairs } if full(ctrTx) { p.AirtimeTxSecs = ptr(float64(cur.inc[ctrTx])) } if full(ctrRx) { p.AirtimeRxSecs = ptr(float64(cur.inc[ctrRx])) } if full(ctrRecv) { p.PacketsReceived = ptr(cur.inc[ctrRecv]) } if full(ctrSent) { p.PacketsSent = ptr(cur.inc[ctrSent]) } if full(ctrErrs) { p.ReceiveErrors = ptr(cur.inc[ctrErrs]) } } out = append(out, p) } return out } func roundedMean32(m mean) *int32 { if m.n == 0 { return nil } return ptr(int32(math.Round(m.sum / float64(m.n)))) } func tenthsMean(m mean) *float32 { if m.n == 0 { return nil } return ptr(float32(math.Round(m.sum/float64(m.n)*10) / 10)) } // NodePollingObserver is an observer assigned to poll a node. Rank is 0 for the poller (omitted) and 1+ for standbys. type NodePollingObserver struct { ObserverID uuid.UUID `json:"observerId"` Name string `json:"name"` Rank int `json:"rank,omitempty"` } // NodePollingForeign is an observer this server does not manage that checks a node: it follows another server, or // none. It is never the poller or a standby here. type NodePollingForeign struct { ObserverID uuid.UUID `json:"observerId"` Name string `json:"name"` // PollHost is the server the observer says it follows, null when it sends no claim or its firmware does not say. 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 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 } // NodePolling says who polls a node and when it last got a trusted reading. type NodePolling struct { Polled bool `json:"polled"` // any reading has ever been stored for the node LatestReadingAt *int64 `json:"latestReadingAt"` // newest trusted reading, epoch ms Poller *NodePollingObserver `json:"poller"` // null when nobody is assigned Standbys []NodePollingObserver `json:"standbys"` // Foreign lists the observers this server does not manage that check the node: a live claim names it, or // they delivered a reading of it in the last 24 hours. Empty unless polling.foreign_claims is check. Foreign []NodePollingForeign `json:"foreign"` } // NodePollerSlots is how a poller's target slots are used. Max is the limit the poller reports, 8 when it reports none. type NodePollerSlots struct { Max int `json:"max"` Used int `json:"used"` // targets the claim names Own int `json:"own"` // targets the poller chose itself Requested int `json:"requested"` // targets it polls for a request Free int `json:"free"` // seats a request can still take: 0 unless the claim is live and accepts requests, less those handed out but not yet claimed } // NodePollerClaim is the newest claim a poller sent. Live is false once it is older than the claim TTL. type NodePollerClaim struct { ReceivedAt int64 `json:"receivedAt"` // epoch ms Live bool `json:"live"` AcceptsRequests bool `json:"acceptsRequests"` // Signed is true when the claim carried a signature by the observer's own key and it checked out: the claim // came from this observer and was not changed on the way. Signed bool `json:"signed"` // Foreign is true when this server does not manage the observer: it follows another server, or none. It is // then never a poller or standby here and its targets all have the role unassigned. Foreign bool `json:"foreign"` // PollHost is the server the observer says it follows, null when its firmware does not say. PollHost *string `json:"pollHost"` // PollIntervalMinutes is how often the poller polls each target, null when its firmware does not report it. PollIntervalMinutes *int `json:"pollIntervalMinutes"` Slots NodePollerSlots `json:"slots"` } // NodePollerTarget is one repeater a poller's claim names, or one a claimless observer sent readings for. Role is poller (rank 0), standby (rank 1+) or // unassigned (rank null). State is the device's own word for the target, passed through as stored. type NodePollerTarget struct { NodeID *uuid.UUID `json:"nodeId"` // null when the target has no node row PublicKey string `json:"publicKey"` Name *string `json:"name"` Requested bool `json:"requested"` Role string `json:"role" enums:"poller,standby,unassigned"` Rank *int `json:"rank"` State string `json:"state"` Misses int `json:"misses"` LastAttempt *int64 `json:"lastAttempt"` // epoch ms, null when never LastOk *int64 `json:"lastOk"` // epoch ms, null when never ClaimedSnr *float32 `json:"claimedSnr"` EvidenceSnr *float32 `json:"evidenceSnr"` // as of the last election EvidenceCount int `json:"evidenceCount"` LatestReadingAt *int64 `json:"latestReadingAt"` // newest reading this poller delivered, epoch ms // LatestReadingRssi is how strongly the poller heard the repeater's reply for that reading, in dBm. Null when // there is no reading or its firmware does not report it. LatestReadingRssi *int `json:"latestReadingRssi"` // LatestReadingSigned is true when that reading carried the poller's signature and it checked out. LatestReadingSigned bool `json:"latestReadingSigned"` // LatestReadingRequested is what that reading, when signed, says of the repeater: polled on a request (true) or // as the poller's own (false). Null when it does not say: no reading, unsigned, or firmware older than the flag. LatestReadingRequested *bool `json:"latestReadingRequested"` } // NodePoller is what a node polls as an observer. Claim is null when the node has no polling claim; Targets then // holds the repeaters its claimless readings of the last 24 h were for, if any. type NodePoller struct { Claim *NodePollerClaim `json:"claim"` Readings24h int `json:"readings24h"` // readings it delivered in the last 24 h // ForeignReadings24h is how many of those were stored as foreign: delivered without a claim of this server's // own behind them. An observer in local mode sends readings and no claim, so it has these and a null claim. ForeignReadings24h int `json:"foreignReadings24h"` Targets []NodePollerTarget `json:"targets"` } // NodeLatestReading is the newest trusted battery and temperature of one polled node. SampledAt is the later of // the two readings' times. type NodeLatestReading struct { NodeID uuid.UUID `json:"nodeId"` SampledAt int64 `json:"sampledAt"` // epoch ms BatteryMV *int32 `json:"batteryMv,omitempty"` TemperatureC *float32 `json:"temperatureC,omitempty"` } // NodeLatestReadings is the response of the latest readings route. type NodeLatestReadings struct { GeneratedAt int64 `json:"generatedAt"` // epoch ms Items []NodeLatestReading `json:"items"` }