diff --git a/package-lock.json b/package-lock.json
index 1b109c05..ce1b0222 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "beacon-web",
- "version": "2.3.2",
+ "version": "2.3.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "beacon-web",
- "version": "2.3.2",
+ "version": "2.3.4",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@nazka/map-gl-js-spiderfy": "^2.0.0",
diff --git a/package.json b/package.json
index 50adbd0d..5f056e49 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "beacon-web",
"private": true,
- "version": "2.3.2",
+ "version": "2.3.4",
"license": "AGPL-3.0-or-later",
"type": "module",
"scripts": {
diff --git a/src/api/client.ts b/src/api/client.ts
index 451b7d14..6d671d1e 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -128,7 +128,7 @@ export interface ServerInfo {
minWebVersion: string | null;
serverVersion: string;
// absent on servers that predate the flags
- features?: { polling?: boolean; accounts?: string; registration?: boolean; telemetryRequests?: boolean; alerts?: boolean; atlasTelemetry?: boolean; atlas7d?: boolean; atlasPoller?: boolean; mapTelemetry?: boolean; alertChannels?: { email?: boolean; push?: boolean }; push?: { server?: string; pushId?: string }; portalUrl?: string };
+ features?: { polling?: boolean; accounts?: string; registration?: boolean; telemetryRequests?: boolean; alerts?: boolean; atlasTelemetry?: boolean; atlas7d?: boolean; atlasPoller?: boolean; sensors?: boolean; mapTelemetry?: boolean; alertChannels?: { email?: boolean; push?: boolean }; push?: { server?: string; pushId?: string }; portalUrl?: string };
display?: { temperatureUnit?: string; distanceUnit?: string };
limits?: { atlas?: number };
}
diff --git a/src/features/account/alertRules.ts b/src/features/account/alertRules.ts
index 2f0f28e3..2c7c7816 100644
--- a/src/features/account/alertRules.ts
+++ b/src/features/account/alertRules.ts
@@ -4,7 +4,7 @@ import { fromDisplayTemp, tempSymbol, toDisplayTemp, type TemperatureUnit } from
// The order of the plan's alert kinds table; rows follow it.
export const ALERT_KINDS: AlertKind[] = [
- "gone_quiet", "back_online", "battery_low", "battery_falling", "rebooted", "temperature", "noise_high", "clock", "observer_offline",
+ "gone_quiet", "back_online", "telemetry_stopped", "battery_low", "battery_falling", "rebooted", "temperature", "noise_high", "clock", "observer_offline",
];
// The rules that are switched on, and the ones alerting now. Profile's summary and the Atlas bell both read these.
@@ -19,9 +19,9 @@ export function channelReaches(channels: AlertChannels): boolean {
return (email.available && email.enabled) || (push.available && push.enabled && push.hasDevice);
}
-export function goneQuietHours(target: AlertTarget, current: number | null): number[] {
- const short = target.kind === "observer" || target.polled;
- const hours = short ? [3, 6, 12, 24, 48] : [12, 24, 48];
+// The hour choices of gone_quiet and telemetry_stopped, plus a stored value that is not one of them.
+export function quietHours(current: number | null): number[] {
+ const hours = [3, 6, 12, 24, 48];
if (current != null && !hours.includes(current)) hours.push(current);
return hours.sort((a, b) => a - b);
}
@@ -38,6 +38,7 @@ export function inputsFor(kind: AlertKind, rule: AlertRule | undefined, unit: Te
const th = rule?.threshold ?? null;
switch (kind) {
case "gone_quiet": return { a: String(th ?? 24), b: "" };
+ case "telemetry_stopped": return { a: String(th ?? 12), b: "" };
case "battery_falling": return { a: String(th ?? 100), b: "" };
case "clock": return { a: String(th ?? 3600), b: "" };
case "observer_offline": return { a: String(th ?? 60), b: "" };
@@ -71,7 +72,7 @@ function num(text: string): number | null {
// Turns the typed values into the units the server takes, or an inline error key.
export function parseInputs(kind: AlertKind, { a, b }: Inputs, unit: TemperatureUnit): Parsed {
switch (kind) {
- case "gone_quiet": case "battery_falling": case "clock": case "observer_offline":
+ case "gone_quiet": case "telemetry_stopped": case "battery_falling": case "clock": case "observer_offline":
return { ok: true, threshold: Number(a), thresholdHigh: null };
case "battery_low": {
const v = num(a);
diff --git a/src/features/account/sections/AlertRow.tsx b/src/features/account/sections/AlertRow.tsx
index 5133b143..ccdabb63 100644
--- a/src/features/account/sections/AlertRow.tsx
+++ b/src/features/account/sections/AlertRow.tsx
@@ -13,7 +13,7 @@ import { useDisplayUnits } from "../../../hooks/useFeatures";
import { tempSymbol } from "../../../lib/units";
import { alertErrorText } from "../errors";
import {
- BATTERY_FALLING_STEPS, CLOCK_SECONDS, OBSERVER_OFFLINE_MINUTES, durationText, goneQuietHours, inputsFor, parseInputs, parseTemperature, temperatureLimits, type Inputs, type Parsed,
+ BATTERY_FALLING_STEPS, CLOCK_SECONDS, OBSERVER_OFFLINE_MINUTES, durationText, quietHours, inputsFor, parseInputs, parseTemperature, temperatureLimits, type Inputs, type Parsed,
} from "../alertRules";
import type { AlertKind, AlertRule, AlertTarget } from "../types";
import { useSessionEnded } from "./useSessionEnded";
@@ -102,7 +102,7 @@ export function AlertRow({ target, kind, rule, goneQuietOn }: { target: AlertTar
let input = null;
switch (kind) {
- case "gone_quiet": input = select("hours", goneQuietHours(target, rule?.threshold ?? null), (h) => durationText(t, "hours", h)); break;
+ case "gone_quiet": case "telemetry_stopped": input = select("hours", quietHours(rule?.threshold ?? null), (h) => durationText(t, "hours", h)); break;
case "battery_falling": input = select("drop", BATTERY_FALLING_STEPS, (m) => t("account.alerts.voltsPerDay", { volts: (m / 1000).toFixed(1) })); break;
case "clock": input = select("drift", CLOCK_SECONDS, (s) => secondsText(t, s)); break;
case "observer_offline": input = select("offline", OBSERVER_OFFLINE_MINUTES, (m) => minutesText(t, m)); break;
@@ -127,6 +127,7 @@ export function AlertRow({ target, kind, rule, goneQuietOn }: { target: AlertTar
{input &&
{input}{unit && {unit}}
}
+ {kind === "gone_quiet" && {t("account.alerts.goneQuietHint")}
}
{blocked && {t("account.alerts.backOnlineHint", { name: t("account.alerts.kinds.gone_quiet.name") })}
}
{stateText && (
diff --git a/src/features/account/types.ts b/src/features/account/types.ts
index 037945ac..8889082c 100644
--- a/src/features/account/types.ts
+++ b/src/features/account/types.ts
@@ -55,7 +55,7 @@ export interface TelemetryRequestList {
export type TelemetryRequestPatch = { password?: string | null; enabled?: true; acknowledgeForeign?: true };
export type AlertKind =
- | "gone_quiet" | "back_online" | "battery_low" | "battery_falling" | "rebooted"
+ | "gone_quiet" | "back_online" | "telemetry_stopped" | "battery_low" | "battery_falling" | "rebooted"
| "temperature" | "noise_high" | "clock" | "observer_offline";
export type AlertState = "ok" | "firing" | "inactive" | "unknown";
diff --git a/src/features/account/unavailableReason.ts b/src/features/account/unavailableReason.ts
index d8203c1e..fec3cf9b 100644
--- a/src/features/account/unavailableReason.ts
+++ b/src/features/account/unavailableReason.ts
@@ -14,7 +14,7 @@ const KEYS: Record = {
};
const NEEDS_WHAT = new Set(["observer_no_data", "repeaters_only", "no_data"]);
const WHAT: Record = {
- battery_low: "battery", battery_falling: "battery", rebooted: "uptime", temperature: "temperature", noise_high: "noise",
+ telemetry_stopped: "telemetry", battery_low: "battery", battery_falling: "battery", rebooted: "uptime", temperature: "temperature", noise_high: "noise",
};
// A reason in the user's language, by its code. No code (an older server) or one this build does not know shows the
diff --git a/src/features/atlas/AtlasCard.tsx b/src/features/atlas/AtlasCard.tsx
index 43184a37..8710c465 100644
--- a/src/features/atlas/AtlasCard.tsx
+++ b/src/features/atlas/AtlasCard.tsx
@@ -1,4 +1,4 @@
-import { Fragment, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
+import { Fragment, useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { isNotFound } from "../../api/client";
@@ -21,7 +21,7 @@ import { usePacketDetail } from "../packets/usePacketDetail";
import { Card, StatCard } from "../stats/cards";
import { useChartColors } from "../stats/chartTheme";
import { average } from "../stats/signal";
-import { DEFAULT_TELEMETRY_TILES, DEFAULT_TILES, OBSERVER_TILES, TELEMETRY_TILES, resolveObserverNode, type AtlasPin, type AtlasSample, type AtlasRange, type AtlasView, type ObserverTile, type TelemetryTile } from "./atlas";
+import { DEFAULT_TELEMETRY_TILES, DEFAULT_TILES, OBSERVER_TILES, TELEMETRY_TILES, isSensorTile, resolveObserverNode, type AtlasPin, type AtlasSample, type AtlasRange, type AtlasView, type ObserverTile, type TelemetryTile } from "./atlas";
import { AtlasAlertBell } from "./AtlasAlerts";
import { TilePicker } from "./TilePicker";
import { PollerTiles } from "./PollerTiles";
@@ -29,11 +29,13 @@ import { ATLAS_REFRESH_MS, useAtlasNode, useAtlasReadings, useAtlasTelemetry, us
import { DOT_LIMIT, sparkValues } from "./telemetry-sample";
import type { ObserverSample, PayloadShare } from "./observer-sample";
import { TileGraph } from "./TileGraph";
-import { NODE_METRICS, OBSERVER_METRICS, percent, perHour, readingPoints, shortUptime, slotPoints, telemetryMetrics, type NodeTile } from "./tile-graph";
+import { AIR_QUALITY, NODE_METRICS, OBSERVER_METRICS, percent, perHour, readingPoints, shortUptime, slotPoints, telemetryMetrics, type NodeTile } from "./tile-graph";
+import { AccuracyChip } from "../nodes/AccuracyChip";
import { useAtlasObserver } from "./useAtlasObserver";
import type { CardHandleProps } from "./useCardDrag";
import { ViewTabs } from "./ViewTabs";
import { TelemetrySourceTag } from "../nodes/ForeignObserver";
+import { telemetrySourceInfo } from "../nodes/telemetrySourceInfo";
import { allLocal } from "../nodes/poller-seats";
import { PollerClaimTags } from "../nodes/NodePollerSection";
@@ -86,6 +88,12 @@ const TELEMETRY_LABEL: Record = {
packets: "atlas.telemetry.packets",
signal: "atlas.telemetry.signal",
errors: "atlas.telemetry.errors",
+ humidity: "atlas.telemetry.humidity",
+ pressure: "atlas.telemetry.pressure",
+ gas: "atlas.telemetry.gas",
+ power: "atlas.telemetry.power",
+ current: "atlas.telemetry.current",
+ sensorVoltage: "atlas.telemetry.sensorVoltage",
};
// Accents belong to the slot, so a card keeps its colours whatever its tiles show.
const SLOT_ACCENT = [0, 3, 2, 1];
@@ -410,24 +418,29 @@ export function AtlasCard({
const [graph, setGraph] = useState(null);
const sparkButton = (label: string, tile: GraphTile) => ({ onSparkClick: () => setGraph(tile), sparkLabel: t("atlas.graph.open", { name: label }) });
const observerSample = obs.sample;
+ const gasIsIndex = telSample.gasIsIndex;
+ const telemetryLabel = useCallback((id: TelemetryTile) => (id === "gas" && gasIsIndex ? "atlas.telemetry.airQuality" : TELEMETRY_LABEL[id]), [gasIsIndex]);
+ const telemetrySpec = useCallback((id: TelemetryTile) => (id === "gas" && gasIsIndex ? AIR_QUALITY : telMetrics[id]), [gasIsIndex, telMetrics]);
// Memoized so the open graph is redrawn when the data changes, not on every render of the card.
const graphed = useMemo(() => {
if (!graph) return null;
if (graph.kind === "node") return { metric: t(NODE_LABEL[graph.id]), spec: NODE_METRICS[graph.id], points: slotPoints(nodeHourly(sample)[graph.id], range, now) };
if (graph.kind === "observer") return { metric: t(TILE_LABEL[graph.id]), spec: OBSERVER_METRICS[graph.id], points: slotPoints(observerHourly(observerSample)[graph.id], range, now) };
- return { metric: t(TELEMETRY_LABEL[graph.id]), spec: telMetrics[graph.id], points: readingPoints(telSample[graph.id].points, telSample.bucketMs) };
- }, [graph, sample, observerSample, telSample, telMetrics, range, now, t]);
- const freeTelemetry = TELEMETRY_TILES.filter((id) => !telemetryTiles.includes(id) && (id !== "temperature" || telSample.temperature.values.length > 0))
- .map((id) => ({ value: id, label: t(TELEMETRY_LABEL[id]) }));
+ return { metric: t(telemetryLabel(graph.id)), spec: telemetrySpec(graph.id), points: readingPoints(telSample[graph.id].points, telSample.bucketMs) };
+ }, [graph, sample, observerSample, telSample, telemetryLabel, telemetrySpec, range, now, t]);
+ // A tile whose value this repeater never sends is not offered: temperature, and each sensor tile.
+ const offered = (id: TelemetryTile) => (id !== "temperature" && !isSensorTile(id)) || telSample[id].values.length > 0;
+ const freeTelemetry = TELEMETRY_TILES.filter((id) => !telemetryTiles.includes(id) && offered(id))
+ .map((id) => ({ value: id, label: t(telemetryLabel(id)) }));
const telemetryTile = (id: TelemetryTile, slot: number) => {
const accent = c.series[SLOT_ACCENT[slot]!]!;
const common = {
compact: true,
accent,
- ...sparkButton(t(TELEMETRY_LABEL[id]), { kind: "telemetry", id, color: accent }),
+ ...sparkButton(t(telemetryLabel(id)), { kind: "telemetry", id, color: accent }),
label: (
= 2}
onPick={(next) => onTelemetryTilesChange(telemetryTiles.map((old, i) => (i === slot ? (next as TelemetryTile) : old)))}
@@ -440,7 +453,7 @@ export function AtlasCard({
const tile = (
series: { latest: number | null; values: number[] },
format: (v: number) => string,
- options: { peak?: boolean; sublabel?: string | null; counter?: boolean; title?: (v: number) => string } = {},
+ options: { peak?: boolean; sublabel?: ReactNode; counter?: boolean; title?: (v: number) => string } = {},
) => (
: null });
}
};
// polled only says a reading was ever stored; an assigned poller is what means it is polled now.
@@ -475,6 +490,11 @@ export function AtlasCard({
const lastReading = tab.polling?.latestReadingAt ?? telSample.latestAt;
const pollerName = tab.polling?.poller?.name;
const pollState = !tab.polling ? null : polledNow ? (pollerName ? t("atlas.telemetry.polledBy", { name: pollerName }) : t("atlas.telemetry.polled")) : t("atlas.telemetry.notPolled");
+ // The footer always says when the last reading was. Readings from an observer this server does not manage are
+ // tagged there, and with nobody here polling the tag stands in for "Not polled": the repeater is polled, only
+ // not by this server.
+ const outsideSource = tel.foreign === "all" || tel.foreign === "some";
+ const localSource = allLocal(tab.polling?.foreign);
const windowLabel = obs.sample.partial ? t("atlas.observerPartialCoverage") : t(`atlas.ranges.${range}`);
const observerTile = (id: ObserverTile, slot: number) => {
const sample = obs.sample;
@@ -652,15 +672,19 @@ export function AtlasCard({
)}
{view === "telemetry" && node && (
- {(tel.foreign === "all" || tel.foreign === "some") &&
}
{telemetryTiles.map((id, slot) => {telemetryTile(id, slot)})}
{footer(
- tab.polling
- ? lead(polledNow, t(polledNow ? "atlas.telemetry.polledShort" : "atlas.telemetry.notPolledShort"), polledNow ? lastReading : null)
- : lastReading != null && lead(null, t("atlas.telemetry.lastReading"), lastReading),
- polledNow && pollerName ? t("atlas.telemetry.byPoller", { name: pollerName }) : "",
+ <>
+ {polledNow
+ ? lead(true, t("atlas.telemetry.polledShort"), lastReading)
+ : lastReading != null
+ ? lead(tab.polling && !outsideSource ? false : null, t("atlas.telemetry.lastReading"), lastReading)
+ : tab.polling && !outsideSource && lead(false, t("atlas.telemetry.notPolledShort"), null)}
+ {outsideSource &&
}
+ >,
+ polledNow ? (pollerName ? t("atlas.telemetry.byPoller", { name: pollerName }) : "") : tab.polling && !outsideSource && lastReading != null ? t("atlas.telemetry.notPolledShort") : "",
tel,
- [pollState, lastReading != null && `${t("atlas.telemetry.lastReading")} ${formatAbsolute(lastReading)}`, t("atlas.telemetry.help")],
+ [(polledNow || !outsideSource) && pollState, outsideSource && t(telemetrySourceInfo(localSource)), lastReading != null && `${t("atlas.telemetry.lastReading")} ${formatAbsolute(lastReading)}`, t("atlas.telemetry.help")],
)}
)}
diff --git a/src/features/atlas/AtlasPage.tsx b/src/features/atlas/AtlasPage.tsx
index 856705e7..ad2b825d 100644
--- a/src/features/atlas/AtlasPage.tsx
+++ b/src/features/atlas/AtlasPage.tsx
@@ -292,7 +292,7 @@ export function AtlasPage({ active = true, ...actions }: AtlasActions & { active
-
+
{pendingImport && (
@@ -391,7 +391,7 @@ export function AtlasPage({ active = true, ...actions }: AtlasActions & { active
{saved.pins.length === 0 ? (
) : (
-
+
{saved.pins.map((pin, index) => (
(SENSOR_TILES as readonly string[]).includes(id);
export const DEFAULT_TELEMETRY_TILES: readonly TelemetryTile[] = ["battery", "noise", "uptime", "airtime"];
export type AtlasView = "analytics" | "heard" | "observer" | "telemetry" | "poller";
// `view` is the tab the card opens on, stored only when it is not Analytics.
diff --git a/src/features/atlas/atlasSync.ts b/src/features/atlas/atlasSync.ts
index 3465ecc1..0f6ea3de 100644
--- a/src/features/atlas/atlasSync.ts
+++ b/src/features/atlas/atlasSync.ts
@@ -1,4 +1,4 @@
-import { NO_NODE_ID, effectiveRange, parseAtlas, pinKey, type AtlasPin, type NodePin, type AtlasRange, type AtlasView, type ObserverTile, type SavedAtlas, type TelemetryTile } from "./atlas";
+import { isSensorTile, NO_NODE_ID, effectiveRange, parseAtlas, pinKey, type AtlasPin, type NodePin, type AtlasRange, type AtlasView, type ObserverTile, type SavedAtlas, type TelemetryTile } from "./atlas";
// The account document, as /me/atlas answers it. Times and ids follow the API contract.
export interface ServerNodePin { kind: "node"; publicKey: string; id: string | null; name: string; observerId: string | null; tiles?: ObserverTile[]; telemetryTiles?: TelemetryTile[]; view?: AtlasView }
@@ -26,8 +26,9 @@ export const emptyAtlas = (): SavedAtlas => ({ version: 2, range: "24h", pins: [
// without Telemetry tab support never stores `view: "telemetry"` or `telemetryTiles`, so with
// `keepTelemetry` the previous local pin's two stay in this browser's copy. Likewise `keep7d`: a server
// without 7d was sent 3d for a local 7d, so its 3d does not replace it. `keepPoller` does for
-// `view: "poller"` what `keepTelemetry` does for the Telemetry view.
-export function fromServer(doc: ServerAtlas, previous: SavedAtlas | null, known: ObserverKeys, keepTelemetry = false, keep7d = false, keepPoller = false): { atlas: SavedAtlas; keys: ObserverKeys } {
+// `view: "poller"` what `keepTelemetry` does for the Telemetry view. `keepSensors`: a server without the
+// sensor tiles was not sent a layout that names one, so the local layout stays where it sends none.
+export function fromServer(doc: ServerAtlas, previous: SavedAtlas | null, known: ObserverKeys, keepTelemetry = false, keep7d = false, keepPoller = false, keepSensors = false): { atlas: SavedAtlas; keys: ObserverKeys } {
const nodeIds = new Map();
const before = new Map();
const observerIds = new Map();
@@ -45,7 +46,8 @@ export function fromServer(doc: ServerAtlas, previous: SavedAtlas | null, known:
const publicKey = pin.publicKey.toLowerCase();
if (pin.observerId) keys[pin.observerId] = publicKey;
const local = before.get(publicKey);
- const telemetryTiles = pin.telemetryTiles ?? (keepTelemetry ? local?.telemetryTiles : undefined);
+ const keepTiles = keepTelemetry || (keepSensors && local?.telemetryTiles?.some(isSensorTile));
+ const telemetryTiles = pin.telemetryTiles ?? (keepTiles ? local?.telemetryTiles : undefined);
const kept = (keepTelemetry && local?.view === "telemetry") || (keepPoller && local?.view === "poller");
const view = pin.view ?? (kept ? local!.view : undefined);
return { kind: "node", id: pin.id ?? nodeIds.get(publicKey) ?? NO_NODE_ID, publicKey, name: pin.name, observerId: pin.observerId ?? undefined, ...tiles, ...(telemetryTiles && { telemetryTiles }), view };
@@ -63,13 +65,14 @@ export function fromServer(doc: ServerAtlas, previous: SavedAtlas | null, known:
// `telemetry` is the server's `features.atlasTelemetry`. Without it the Telemetry tab's two fields stay
// out of the body, which an older server would reject; a pin on that tab is sent as having no view.
// `atlas7d` is `features.atlas7d`: without it a 7d range goes out as 3d. `poller` is
-// `features.atlasPoller`: without it a pin on the Poller tab is sent as having no view.
-export function toPut(saved: SavedAtlas, keys: ObserverKeys, baseRevision: number, telemetry = false, atlas7d = false, poller = false): PutAtlas {
+// `features.atlasPoller`: without it a pin on the Poller tab is sent as having no view. `sensors` is
+// `features.sensors`: without it tiles that name a sensor tile are left out, since the server knows none of them.
+export function toPut(saved: SavedAtlas, keys: ObserverKeys, baseRevision: number, telemetry = false, atlas7d = false, poller = false, sensors = false): PutAtlas {
const pins = saved.pins.map((pin): PutPin => {
const tiles = pin.tiles && { tiles: pin.tiles };
if (pin.kind === "node") {
const view = (telemetry || pin.view !== "telemetry") && (poller || pin.view !== "poller") ? pin.view : undefined;
- return { kind: "node", publicKey: pin.publicKey, name: pin.name, ...tiles, ...(telemetry && pin.telemetryTiles && { telemetryTiles: pin.telemetryTiles }), ...(view && { view }) };
+ return { kind: "node", publicKey: pin.publicKey, name: pin.name, ...tiles, ...(telemetry && pin.telemetryTiles && (sensors || !pin.telemetryTiles.some(isSensorTile)) && { telemetryTiles: pin.telemetryTiles }), ...(view && { view }) };
}
const key = keys[pin.observerId];
if (isPlaceholder(pin.observerId) && key) return { kind: "observer", observerPublicKey: key, name: pin.name, ...tiles };
diff --git a/src/features/atlas/telemetry-sample.ts b/src/features/atlas/telemetry-sample.ts
index 3dfdbebe..e06644e2 100644
--- a/src/features/atlas/telemetry-sample.ts
+++ b/src/features/atlas/telemetry-sample.ts
@@ -1,6 +1,7 @@
import type { NodeTelemetry, NodeTelemetryRange } from "../nodes/types";
import { airtimePct } from "../nodes/telemetry";
-import { HOUR, type AtlasRange } from "./atlas";
+import { airQualityAccuracy, sensorChannels, sensorValue, type SensorValue } from "../nodes/sensors";
+import { HOUR, SENSOR_TILES, type AtlasRange, type SensorTile } from "./atlas";
// The route to ask per card range. 3d is a 72h read where the server offers it (features.atlasTelemetry);
// older servers only know 168h, which is trimmed to the window here.
@@ -35,6 +36,16 @@ export interface TelemetrySample {
signal: TelemetrySeries; // SNR, dB
rssi: number | null;
errors: TelemetrySeries; // receive errors per hour
+ // Sensor tiles read the lowest channel that carries the value in the window.
+ humidity: TelemetrySeries; // percent
+ pressure: TelemetrySeries; // hPa
+ gas: TelemetrySeries; // kOhm, or an air quality index when gasIsIndex
+ gasIsIndex: boolean;
+ gasAccuracy: number | null; // the index's calibration status, 0 to 3; null for a resistance
+ power: TelemetrySeries; // W
+ current: TelemetrySeries; // A
+ sensorVoltage: TelemetrySeries; // V
+ sensorChannel: Partial>; // the channel each tile reads; the tiles do not show it
rebooted: boolean; // uptime fell somewhere in the window
readings: number; // points in the window, whatever they carry
latestAt: number | null; // newest reading in the window, epoch ms
@@ -64,6 +75,8 @@ function bucketOf(interval: string | undefined): number {
return (hours ? Number(hours[1]) : 1) * HOUR;
}
+const TILE_VALUE: Record = { humidity: "humidity", pressure: "pressure", gas: "gas", power: "power", current: "current", sensorVoltage: "sensorVoltage" };
+
export function summarizeTelemetry(data: NodeTelemetry | undefined, range: AtlasRange, now: number): TelemetrySample {
const from = now - WINDOW_HOURS[range] * HOUR;
const points = (data?.points ?? []).filter((p) => finite(p.t) && p.t >= from && p.t <= now + HOUR).sort((a, b) => a.t - b.t);
@@ -76,7 +89,24 @@ export function summarizeTelemetry(data: NodeTelemetry | undefined, range: Atlas
const lastPackets = [...points].reverse().find((p) => perHour(p.packetsReceived, p.counterSpanSecs) !== null);
const lastSignal = [...points].reverse().find((p) => finite(p.lastSnrDb));
const uptime = series(points, (p) => (finite(p.uptimeSeconds) && p.uptimeSeconds >= 0 ? p.uptimeSeconds : null));
+ const sensorChannel: Partial> = {};
+ const empty: TelemetrySeries = { latest: null, values: [], points: [] };
+ const sensor = (tile: SensorTile, value: SensorValue = TILE_VALUE[tile]): TelemetrySeries => {
+ const channel = sensorChannels(points, value)[0];
+ if (channel === undefined) return empty;
+ sensorChannel[tile] = channel;
+ return series(points, (p) => sensorValue(p, channel, value));
+ };
+ // The lowest gas channel decides: an air quality index when it sends one, its raw resistance otherwise.
+ const indexChannel = sensorChannels(points, "airQuality")[0];
+ const rawChannel = sensorChannels(points, "gas")[0];
+ const gasIsIndex = indexChannel !== undefined && (rawChannel === undefined || indexChannel <= rawChannel);
+ const sensors = Object.fromEntries(SENSOR_TILES.map((tile) => [tile, tile === "gas" && gasIsIndex ? sensor(tile, "airQuality") : sensor(tile)])) as Record;
return {
+ ...sensors,
+ gasIsIndex,
+ gasAccuracy: gasIsIndex ? airQualityAccuracy(points, indexChannel) : null,
+ sensorChannel,
// A battery never reads zero: a 0 mV reading is "no battery", as on the Observer tiles.
battery: series(points, (p) => (finite(p.batteryMv) && p.batteryMv > 0 ? p.batteryMv / 1000 : null)),
noise: series(points, (p) => p.noiseFloorDb),
diff --git a/src/features/atlas/tile-graph.ts b/src/features/atlas/tile-graph.ts
index f1758936..382eadb9 100644
--- a/src/features/atlas/tile-graph.ts
+++ b/src/features/atlas/tile-graph.ts
@@ -55,9 +55,19 @@ export function telemetryMetrics(tempUnit: TemperatureUnit): Record `${v.toFixed(1)} dB`, unit: "dB" },
errors: rate,
+ humidity: { format: (v) => `${v.toFixed(1)}%`, unit: "%" },
+ pressure: { format: (v) => `${v.toFixed(1)} hPa`, unit: "hPa" },
+ gas: { format: (v) => `${v.toFixed(1)} kΩ`, unit: "kΩ" },
+ // A power monitor reads a reverse current as negative, so neither axis is pinned to zero.
+ power: { format: (v) => `${v.toFixed(3)} W`, unit: "W" },
+ current: { format: (v) => `${v.toFixed(3)} A`, unit: "A" },
+ sensorVoltage: { format: (v) => `${v.toFixed(2)} V`, unit: "V" },
};
}
+// The gas tile of a sensor that sends an air quality index instead of a resistance.
+export const AIR_QUALITY: TileMetric = { format: (v) => `IAQ ${Math.round(v)}`, unit: "IAQ", zero: true };
+
export type GraphPoint = [number, number | null];
// An hourly series as timed points: each slot at the clock hour it holds.
diff --git a/src/features/atlas/useSyncedAtlas.ts b/src/features/atlas/useSyncedAtlas.ts
index 0d042f29..f8842801 100644
--- a/src/features/atlas/useSyncedAtlas.ts
+++ b/src/features/atlas/useSyncedAtlas.ts
@@ -34,10 +34,11 @@ export function useSyncedAtlas() {
const { t } = useTranslation();
const base = useSavedAtlas();
// Read at send time like the rest: until /info answers, and on an older server, the Telemetry fields and a Poller view stay local.
- const { atlasTelemetry, atlas7d, atlasPoller } = useFeatures();
+ const { atlasTelemetry, atlas7d, atlasPoller, sensors } = useFeatures();
const telemetry = useRef(atlasTelemetry);
const sevenDay = useRef(atlas7d);
const pollerView = useRef(atlasPoller);
+ const sensorTiles = useRef(sensors);
// Until /info answers nobody knows what the server stores, so the load holds its adoption and writes wait.
const infoPending = useFeaturesLoading();
const infoLoading = useRef(infoPending);
@@ -77,12 +78,13 @@ export function useSyncedAtlas() {
telemetry.current = atlasTelemetry;
sevenDay.current = atlas7d;
pollerView.current = atlasPoller;
+ sensorTiles.current = sensors;
infoLoading.current = infoPending;
});
const markWhenSent = useRef(null);
const adopt = useCallback((doc: ServerAtlas) => {
- const { atlas, keys: next } = fromServer(doc, baseRef.current.latest(), keys.current, !telemetry.current, !sevenDay.current, !pollerView.current);
+ const { atlas, keys: next } = fromServer(doc, baseRef.current.latest(), keys.current, !telemetry.current, !sevenDay.current, !pollerView.current, !sensorTiles.current);
keys.current = next;
setObserverKeys(next);
revision.current = doc.revision;
@@ -107,7 +109,7 @@ export function useSyncedAtlas() {
const rev = revision.current;
// A conflict without a document cleared it: go back through the load before writing.
if (rev === null) { queued.current = true; return; }
- const doc = await me.putAtlas(toPut(baseRef.current.latest(), keys.current, rev, telemetry.current, sevenDay.current, pollerView.current));
+ const doc = await me.putAtlas(toPut(baseRef.current.latest(), keys.current, rev, telemetry.current, sevenDay.current, pollerView.current, sensorTiles.current));
if (generation.current !== mine) return;
// A save commits exactly rev + 1. Whatever the answer says, the next save builds on that, so a
// newer copy from another device meets a conflict instead of being overwritten.
@@ -159,7 +161,7 @@ export function useSyncedAtlas() {
try { previous = localStorage.getItem(OWNER_KEY); } catch { /* storage blocked */ }
// A copy last synced to someone else is theirs: never merge it into this account, nor lend it anything.
const foreign = previous !== null && previous !== id;
- const server = fromServer(doc, foreign ? null : local, {}, !telemetry.current, !sevenDay.current, !pollerView.current);
+ const server = fromServer(doc, foreign ? null : local, {}, !telemetry.current, !sevenDay.current, !pollerView.current, !sensorTiles.current);
keys.current = server.keys;
setObserverKeys(server.keys);
revision.current = doc.revision;
diff --git a/src/features/nodes/AccuracyChip.tsx b/src/features/nodes/AccuracyChip.tsx
new file mode 100644
index 00000000..d0eb32c2
--- /dev/null
+++ b/src/features/nodes/AccuracyChip.tsx
@@ -0,0 +1,20 @@
+import { useTranslation } from "react-i18next";
+import { VARIANT_CLASSES } from "../../components/badge-utils";
+import { Tooltip } from "../../components/Tooltip";
+import { accuracyText } from "./accuracyText";
+
+// A gas sensor's calibration status, 0 to 3, with what it means on hover or tap. `compact` is the
+// figure alone, for a tile's corner; its tip then says the status in words first.
+export function AccuracyChip({ accuracy, compact = false }: { accuracy: number; compact?: boolean }) {
+ const { t } = useTranslation();
+ const size = compact ? "px-1 py-px text-[9px]" : "px-1.5 py-0.5 text-[10px]";
+ const status = accuracyText(t, accuracy);
+ const help = t("nodeDetail.telemetry.accuracyHelp");
+ return (
+ {status}{help}> : help}>
+ = 3 ? "live" : "stale"]}`}>
+ {compact ? `${Math.min(accuracy, 3)}/3` : status}
+
+
+ );
+}
diff --git a/src/features/nodes/ForeignObserver.tsx b/src/features/nodes/ForeignObserver.tsx
index aeea6429..06e7fbd3 100644
--- a/src/features/nodes/ForeignObserver.tsx
+++ b/src/features/nodes/ForeignObserver.tsx
@@ -10,12 +10,14 @@ import type { NodePollingForeign, TelemetryForeign } from "./types";
const TAG = "inline-flex shrink-0 items-center rounded-sm border px-1.5 py-px font-mono text-[10px] font-semibold tracking-wider uppercase";
const OUTSIDE = `${TAG} border-dashed border-text-muted/60 text-text-normal`;
-// info overrides the foreign note, for a local-mode observer.
-function OutsideTag({ label, info, chip = "foreign-observer" }: { label: string; info?: string; chip?: "foreign-observer" | "local-observer" }) {
+// info overrides the foreign note, for a local-mode observer. bare leaves the note to a tip the row already has.
+function OutsideTag({ label, info, chip = "foreign-observer", bare = false }: { label: string; info?: string; chip?: "foreign-observer" | "local-observer"; bare?: boolean }) {
const { t } = useTranslation();
+ const tag = {label};
+ if (bare) return tag;
return (
- {label}
+ {tag}
);
@@ -33,11 +35,11 @@ export function LocalObserverTag({ source = false }: { source?: boolean }) {
}
// One tag for a telemetry panel, from the server's count of foreign readings behind it.
-export function TelemetrySourceTag({ foreign, local = false }: { foreign: TelemetryForeign | undefined; local?: boolean }) {
+export function TelemetrySourceTag({ foreign, local = false, bare = false }: { foreign: TelemetryForeign | undefined; local?: boolean; bare?: boolean }) {
const { t } = useTranslation();
if (foreign !== "all" && foreign !== "some") return null;
- if (local) return ;
- return ;
+ if (local) return ;
+ return ;
}
export function AlsoCheckedTag() {
@@ -56,12 +58,13 @@ export function SignedChip() {
}
// The node panel's "Also reported by" group. Each entry opens that observer on its Poller view.
-export function AlsoReportedBy({ foreign, onView }: { foreign: NodePollingForeign[]; onView?: (observerId: string) => void }) {
+// `also` is false when no poller of this server checks the node, so these are its only sources.
+export function AlsoReportedBy({ foreign, onView, also = true }: { foreign: NodePollingForeign[]; onView?: (observerId: string) => void; also?: boolean }) {
const { t } = useTranslation();
if (foreign.length === 0) return null;
return (
-
{t("nodeDetail.foreignObserver.alsoReportedBy")}
+
{t(also ? "nodeDetail.foreignObserver.alsoReportedBy" : "nodeDetail.foreignObserver.reportedBy")}
{foreign.map((f) => (
-
@@ -70,10 +73,10 @@ export function AlsoReportedBy({ foreign, onView }: { foreign: NodePollingForeig
) : (
)}
- {f.claimed === false ? : }
+ {f.local === true ? : }
{f.signed && }
{f.pollHost && {t("nodeDetail.foreignObserver.follows", { host: f.pollHost })}}
- {!f.claimed && {t("nodeDetail.foreignObserver.readingsOnly")}}
+ {!f.claimed && {t(f.local === false ? "nodeDetail.foreignObserver.claimStale" : "nodeDetail.foreignObserver.readingsOnly")}}
{f.latestReadingAt != null && }
))}
diff --git a/src/features/nodes/NodePollerSection.tsx b/src/features/nodes/NodePollerSection.tsx
index f3758207..ae93d569 100644
--- a/src/features/nodes/NodePollerSection.tsx
+++ b/src/features/nodes/NodePollerSection.tsx
@@ -48,15 +48,22 @@ export function PollerClaimTags({ data, className = "" }: { data: NodePoller; cl
);
}
-// A local-mode observer has no seats. An older server lists no repeaters for it either.
-export function LocalPollerSummary({ data }: { data: NodePoller }) {
+// A local-mode observer has no seats, so its reading count leads where a claim's slot count does.
+// An older server lists no repeaters for it either. `tags` sit at the right of the count.
+export function LocalPollerSummary({ data, tags }: { data: NodePoller; tags?: ReactNode }) {
const { t } = useTranslation();
return (
-
- {t("nodeDetail.pollerView.readings24h")} {formatCount(data.foreignReadings24h ?? 0)}
- {t("nodeDetail.pollerView.localNote")}
- {data.targets.length === 0 && {t("nodeDetail.foreignObserver.noClaim")}}
-
+ <>
+
+ {formatCount(data.foreignReadings24h ?? 0)}
+ {t("nodeDetail.pollerView.readingsUnit")}
+ {tags && {tags}}
+
+
+ {t("nodeDetail.pollerView.localNote")}
+ {data.targets.length === 0 && {t("nodeDetail.foreignObserver.noClaim")}}
+
+ >
);
}
@@ -239,8 +246,7 @@ export function NodePollerSection({ nodeId, onViewNode }: { nodeId: string; onVi
return <>
{stale}
{data.targets.length > 0 && (
diff --git a/src/features/nodes/NodeTelemetrySection.tsx b/src/features/nodes/NodeTelemetrySection.tsx
index db79c37e..1f9e31c5 100644
--- a/src/features/nodes/NodeTelemetrySection.tsx
+++ b/src/features/nodes/NodeTelemetrySection.tsx
@@ -7,7 +7,9 @@ import { Timestamp } from "../../components/Timestamp";
import { ChartCard } from "../stats/cards";
import { useChartColors } from "../stats/chartTheme";
import { Segmented } from "../stats/Segmented";
-import { buildNodeCharts } from "./nodeTelemetryOptions";
+import { SENSOR_CHARTS, buildNodeCharts } from "./nodeTelemetryOptions";
+import { accuracyText } from "./accuracyText";
+import { AccuracyChip } from "./AccuracyChip";
import { hasNodeTelemetry } from "./telemetry";
import { useNodePolling, useNodeTelemetry, type NodeTelemetryRange } from "./useNodeTelemetry";
import type { Node, NodeTelemetry } from "./types";
@@ -45,11 +47,18 @@ export default function NodeTelemetrySection({ node, onViewObserver, extra, info
battery: t("nodeDetail.telemetry.battery"),
temperature: t("nodeDetail.telemetry.temperature", { unit: tempSymbol(tempUnit) }),
noise: t("nodeDetail.telemetry.noise"),
+ channel: (n) => t("nodeDetail.telemetry.channel", { n }),
+ accuracy: (n) => accuracyText(t, n),
}, tempUnit)
: {}),
[source, colors, t, tempUnit],
);
- const drawn = Object.values(charts).some(Boolean);
+ const sensorCards = SENSOR_CHARTS.flatMap((id) => {
+ const option = charts.sensors?.[id];
+ const chip = id === "airQuality" && charts.airQualityAccuracy !== undefined ? : undefined;
+ return option ? [{ id, title: t(`nodeDetail.telemetry.sensors.${id}`), option, chip }] : [];
+ });
+ const drawn = sensorCards.length > 0 || [charts.battery, charts.temperature, charts.noise, charts.airtime].some(Boolean);
if (hasData && drawn && data !== shown) setShown(data!);
const seenData = shown !== null;
@@ -73,7 +82,7 @@ export default function NodeTelemetrySection({ node, onViewObserver, extra, info
const poller = polling.data?.poller ?? null;
const foreign = polling.data?.foreign ?? [];
- const foreignBlock = onViewObserver(id, "poller"))} />;
+ const foreignBlock = onViewObserver(id, "poller"))} />;
if (!hasData && !poller && foreign.length === 0 && !seenData) return bare;
const polled = !!(data?.polled || polling.data?.polled || seenData);
@@ -89,7 +98,7 @@ export default function NodeTelemetrySection({ node, onViewObserver, extra, info
const standbys = polling.data?.standbys.length ?? 0;
const latest = polling.data?.latestReadingAt;
- const cards: [string, keyof typeof charts, string][] = [
+ const cards: [string, "battery" | "temperature" | "noise" | "airtime", string][] = [
["battery", "battery", t("nodeDetail.telemetry.battery")],
["temperature", "temperature", t("nodeDetail.telemetry.temperature", { unit: tempSymbol(tempUnit) })],
["noise", "noise", t("nodeDetail.telemetry.noise")],
@@ -113,6 +122,7 @@ export default function NodeTelemetrySection({ node, onViewObserver, extra, info
const option = charts[key];
return option ? : null;
})}
+ {sensorCards.map(({ id, title, option, chip }) => )}
) : (
diff --git a/src/features/nodes/accuracyText.ts b/src/features/nodes/accuracyText.ts
new file mode 100644
index 00000000..7ba06ca3
--- /dev/null
+++ b/src/features/nodes/accuracyText.ts
@@ -0,0 +1,5 @@
+import type { TFunction } from "i18next";
+
+// A gas sensor's calibration status in words: it reports 0 to 3, and only 3 is calibrated.
+export const accuracyText = (t: TFunction, accuracy: number): string =>
+ accuracy >= 3 ? t("nodeDetail.telemetry.calibrated") : t("nodeDetail.telemetry.calibrating", { n: accuracy });
diff --git a/src/features/nodes/nodeTelemetryOptions.ts b/src/features/nodes/nodeTelemetryOptions.ts
index 68629d46..dd795162 100644
--- a/src/features/nodes/nodeTelemetryOptions.ts
+++ b/src/features/nodes/nodeTelemetryOptions.ts
@@ -1,9 +1,10 @@
import type { EChartsOption } from "../stats/echarts-setup";
import type { ChartColors } from "../stats/chartTheme";
-import { airtimeOption, metricLineOption, mvToVolts } from "../stats/chartOptions";
+import { MONO, airtimeOption, metricLineOption, mvToVolts } from "../stats/chartOptions";
import { intervalToMs } from "../stats/transforms";
import { airtimePct } from "./telemetry";
import { toDisplayTemp, type TemperatureUnit } from "../../lib/units";
+import { airQualityAccuracy, sensorChannels, sensorValue, type SensorValue } from "./sensors";
import type { NodeTelemetry, NodeTelemetryPoint } from "./types";
// The server skips empty buckets. Put an empty point in each one so the line breaks there
@@ -19,17 +20,27 @@ export function fillGaps(points: NodeTelemetryPoint[], intervalMs: number | null
return out;
}
+// The sensor charts, in the order they are shown. Sensor temperatures join the temperature chart instead.
+export const SENSOR_CHARTS = ["humidity", "pressure", "gas", "airQuality", "sensorVoltage", "current", "power", "distance", "moisture", "light"] as const satisfies readonly SensorValue[];
+export type SensorChart = (typeof SENSOR_CHARTS)[number];
+
export interface NodeCharts {
battery?: EChartsOption;
temperature?: EChartsOption;
noise?: EChartsOption;
airtime?: EChartsOption;
+ sensors?: Partial
>;
+ // The calibration status (0 to 3) of the one channel on the air quality chart, for its heading. With
+ // several channels each line carries its own.
+ airQualityAccuracy?: number;
}
export interface NodeChartLabels {
battery: string;
temperature: string;
noise: string;
+ channel: (n: number) => string; // names a sensor channel's line
+ accuracy: (n: number) => string; // a gas sensor's calibration status, 0 to 3
}
const has = (points: NodeTelemetryPoint[], pick: (p: NodeTelemetryPoint) => number | undefined) =>
@@ -51,9 +62,40 @@ export function buildNodeCharts(data: NodeTelemetry, c: ChartColors, labels: Nod
const points = fillGaps(data.points, bucketMs);
const line = (name: string, color: string, accessor: (p: NodeTelemetryPoint) => number | null) =>
withMarkers(metricLineOption(points, c, { name, color, accessor, connectNulls: false }));
+ type Line = { name: string; color: string; accessor: (p: NodeTelemetryPoint) => number | null };
+ // One chart with a line per entry, and a legend once there is more than one to tell apart.
+ const lines = (all: Line[]): EChartsOption => {
+ const option = metricLineOption(points, c, { ...all[0]!, connectNulls: false });
+ const series = option.series as unknown[];
+ for (const extra of all.slice(1)) series.push(...(metricLineOption(points, c, { ...extra, connectNulls: false }).series as unknown[]));
+ if (all.length > 1) {
+ option.legend = { right: 6, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { color: c.textNormal, fontFamily: MONO, fontSize: 10 } };
+ option.grid = { left: 50, right: 14, top: 24, bottom: 22 };
+ }
+ return withMarkers(option);
+ };
+ const channelLines = (value: SensorValue, from: number, convert: (v: number) => number = (v) => v): Line[] =>
+ sensorChannels(data.points, value).map((channel, i) => ({
+ name: labels.channel(channel),
+ color: c.series[(from + i) % c.series.length]!,
+ accessor: (p) => { const v = sensorValue(p, channel, value); return v == null ? null : convert(v); },
+ }));
const out: NodeCharts = {};
if (has(data.points, (p) => p.batteryMv)) out.battery = line(labels.battery, c.primary, (p) => mvToVolts(p.batteryMv));
- if (has(data.points, (p) => p.temperatureC)) out.temperature = line(labels.temperature, c.green, (p) => (p.temperatureC == null ? null : toDisplayTemp(p.temperatureC, tempUnit)));
+ const temperatures: Line[] = has(data.points, (p) => p.temperatureC)
+ ? [{ name: labels.temperature, color: c.green, accessor: (p) => (p.temperatureC == null ? null : toDisplayTemp(p.temperatureC, tempUnit)) }]
+ : [];
+ temperatures.push(...channelLines("temperature", 0, (v) => toDisplayTemp(v, tempUnit)));
+ if (temperatures.length > 0) out.temperature = lines(temperatures);
+ for (const id of SENSOR_CHARTS) {
+ const sensorLines = channelLines(id, 0);
+ if (id === "airQuality") {
+ const accuracies = sensorChannels(data.points, id).map((channel) => airQualityAccuracy(data.points, channel));
+ if (accuracies.length === 1) out.airQualityAccuracy = accuracies[0] ?? undefined;
+ else sensorLines.forEach((l, i) => { const a = accuracies[i]; if (a != null) l.name = `${l.name} · ${labels.accuracy(a)}`; });
+ }
+ if (sensorLines.length > 0) (out.sensors ??= {})[id] = lines(sensorLines);
+ }
if (has(data.points, (p) => p.noiseFloorDb)) out.noise = line(labels.noise, c.warn, (p) => p.noiseFloorDb ?? null);
if (bucketMs != null && (has(data.points, (p) => p.airtimeTxSecs) || has(data.points, (p) => p.airtimeRxSecs))) {
out.airtime = airtimeOption([], c, bucketMs, false);
diff --git a/src/features/nodes/poller-seats.ts b/src/features/nodes/poller-seats.ts
index d43da7a9..e09b2bc8 100644
--- a/src/features/nodes/poller-seats.ts
+++ b/src/features/nodes/poller-seats.ts
@@ -30,7 +30,7 @@ export function isLocalPoller(data: NodePoller): boolean {
return !data.claim && (data.foreignReadings24h ?? 0) > 0;
}
-// The readings carry no source, so a panel reads as local only when every outside reporter listed sends no claim.
+// The readings carry no source, so a panel reads as local only when every outside reporter listed has no claim at all.
export function allLocal(foreign: NodePollingForeign[] | undefined): boolean {
- return !!foreign && foreign.length > 0 && foreign.every((f) => f.claimed === false);
+ return !!foreign && foreign.length > 0 && foreign.every((f) => f.local === true);
}
diff --git a/src/features/nodes/sensors.ts b/src/features/nodes/sensors.ts
new file mode 100644
index 00000000..09212278
--- /dev/null
+++ b/src/features/nodes/sensors.ts
@@ -0,0 +1,50 @@
+import type { NodeSensor, NodeTelemetryPoint } from "./types";
+
+// What can be read from a repeater's sensor channels. Gas resistance is shown in kOhm.
+export const SENSOR_VALUES = {
+ temperature: (s: NodeSensor) => s.temperatureC,
+ humidity: (s: NodeSensor) => s.humidityPct,
+ pressure: (s: NodeSensor) => s.pressureHpa,
+ gas: (s: NodeSensor) => (s.gasOhms == null ? undefined : s.gasOhms / 1000),
+ airQuality: (s: NodeSensor) => s.iaq,
+ sensorVoltage: (s: NodeSensor) => s.voltageV,
+ current: (s: NodeSensor) => s.currentA,
+ power: (s: NodeSensor) => s.powerW,
+ distance: (s: NodeSensor) => s.distanceM,
+ moisture: (s: NodeSensor) => s.percent,
+ light: (s: NodeSensor) => s.luminosityLux,
+} as const;
+export type SensorValue = keyof typeof SENSOR_VALUES;
+
+const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
+
+// A point's sensor channels, without anything that is not one: the response is not checked on the way in.
+function sensorsOf(point: NodeTelemetryPoint): NodeSensor[] {
+ const raw: unknown = point.sensors;
+ return Array.isArray(raw) ? raw.filter((s): s is NodeSensor => typeof s === "object" && s !== null && finite((s as NodeSensor).channel)) : [];
+}
+
+// The channels that carry the value somewhere in the points, lowest first.
+export function sensorChannels(points: NodeTelemetryPoint[], value: SensorValue): number[] {
+ const seen = new Set();
+ for (const p of points) for (const s of sensorsOf(p)) if (finite(SENSOR_VALUES[value](s))) seen.add(s.channel);
+ return [...seen].sort((a, b) => a - b);
+}
+
+export function sensorValue(point: NodeTelemetryPoint, channel: number, value: SensorValue): number | null {
+ const sensor = sensorsOf(point).find((s) => s.channel === channel);
+ const v = sensor && SENSOR_VALUES[value](sensor);
+ return finite(v) ? v : null;
+}
+
+// How far a gas sensor's own calibration has got, 0 to 3, at the newest point where the channel sent an air
+// quality index. Below 3 the index is still a guess.
+export function airQualityAccuracy(points: NodeTelemetryPoint[], channel: number): number | null {
+ for (let i = points.length - 1; i >= 0; i--) {
+ const sensor = sensorsOf(points[i]!).find((s) => s.channel === channel && finite(s.iaq));
+ if (!sensor) continue;
+ const a: unknown = sensor.iaqAccuracy;
+ return typeof a === "number" && Number.isInteger(a) && a >= 0 && a <= 3 ? a : null;
+ }
+ return null;
+}
diff --git a/src/features/nodes/telemetrySourceInfo.ts b/src/features/nodes/telemetrySourceInfo.ts
new file mode 100644
index 00000000..8b295d07
--- /dev/null
+++ b/src/features/nodes/telemetrySourceInfo.ts
@@ -0,0 +1,2 @@
+// The catalog key of what a bare source tag's row says about it in its own tip.
+export const telemetrySourceInfo = (local: boolean): string => (local ? "nodeDetail.foreignObserver.localSourceInfo" : "nodeDetail.foreignObserver.info");
diff --git a/src/features/nodes/types.ts b/src/features/nodes/types.ts
index f46f5e30..5acff144 100644
--- a/src/features/nodes/types.ts
+++ b/src/features/nodes/types.ts
@@ -172,6 +172,25 @@ export interface NodeTelemetryPoint {
packetsSent?: number;
receiveErrors?: number;
counterSpanSecs?: number; // seconds the counter increments cover; divide by this, not the bucket length
+ sensors?: NodeSensor[]; // per-channel averages, lowest channel first; absent when the bucket had none
+}
+
+// One sensor channel of a repeater. Channel 1 is its own board, added sensors take 2 and up; the firmware
+// names none of them, so a channel is known by what it carries.
+export interface NodeSensor {
+ channel: number;
+ temperatureC?: number;
+ humidityPct?: number;
+ pressureHpa?: number;
+ gasOhms?: number; // raw gas resistance, or
+ iaq?: number; // an air quality index (0 to 500) with its accuracy, 0 to 3
+ iaqAccuracy?: number;
+ voltageV?: number;
+ currentA?: number;
+ powerW?: number; // voltage times current
+ distanceM?: number;
+ percent?: number;
+ luminosityLux?: number;
}
export type NodeTelemetryRange = "24h" | "72h" | "168h" | "720h";
@@ -188,13 +207,15 @@ export interface NodeTelemetry {
// How many of the charted readings came from observers this server does not manage.
export type TelemetryForeign = "none" | "some" | "all";
-// An observer this server does not manage that checks the node. claimed is false for one in local mode, which only sends readings.
+// An observer this server does not manage that checks the node. claimed is false when its claim is stale or names
+// other repeaters. local, from server 2.3.4, is true when it has no claim at all and only sends readings.
export interface NodePollingForeign {
observerId: string;
name: string;
pollHost: string | null;
signed: boolean;
claimed: boolean;
+ local?: boolean;
latestReadingAt: number | null; // epoch ms
}
diff --git a/src/features/observers/ObserverPoller.tsx b/src/features/observers/ObserverPoller.tsx
index 4a7b95f6..4e6c3b21 100644
--- a/src/features/observers/ObserverPoller.tsx
+++ b/src/features/observers/ObserverPoller.tsx
@@ -30,9 +30,9 @@ export function ObserverPoller({ nodeId, onViewNode }: { nodeId: string; onViewN
{heading}
{query.refreshFailed && }
0 ? "xl:grid-cols-[280px_minmax(0,1fr)]" : ""}`}>
-
- {tags}
-
+
+
{t("nodeDetail.pollerView.readings24h")}
+
{data.targets.length > 0 && (
diff --git a/src/features/stats/chartOptions.ts b/src/features/stats/chartOptions.ts
index f0f24a81..b1954654 100644
--- a/src/features/stats/chartOptions.ts
+++ b/src/features/stats/chartOptions.ts
@@ -4,7 +4,7 @@ import { formatCount } from "../../lib/formatters";
import { airtimePctSeries, busyPct } from "./transforms";
import type { ActivityPoint, TelemetryPoint } from "./types";
-const MONO = "JetBrains Mono, monospace";
+export const MONO = "JetBrains Mono, monospace";
export function timeAxis(c: ChartColors) {
return {
diff --git a/src/hooks/useFeatures.ts b/src/hooks/useFeatures.ts
index 6992f984..07d8befc 100644
--- a/src/hooks/useFeatures.ts
+++ b/src/hooks/useFeatures.ts
@@ -12,6 +12,7 @@ export interface Features {
atlasTelemetry: boolean;
atlas7d: boolean;
atlasPoller: boolean;
+ sensors: boolean;
mapTelemetry: boolean;
alertChannels: { email: boolean; push: boolean };
// Servers from before the channel switches send no alertChannels and no overview channels.
@@ -19,7 +20,7 @@ export interface Features {
portalUrl?: string;
}
-const OFF: Features = { polling: false, accounts: "off", registration: false, telemetryRequests: false, alerts: false, atlasTelemetry: false, atlas7d: false, atlasPoller: false, mapTelemetry: false, alertChannels: { email: false, push: false }, alertChannelsSent: false };
+const OFF: Features = { polling: false, accounts: "off", registration: false, telemetryRequests: false, alerts: false, atlasTelemetry: false, atlas7d: false, atlasPoller: false, sensors: false, mapTelemetry: false, alertChannels: { email: false, push: false }, alertChannelsSent: false };
// Shares VersionGate's /info query. Until it loads, on an older server, or on a failure, every feature reads as off.
function useInfo() {
@@ -49,6 +50,7 @@ export function useFeatures(): Features {
atlasTelemetry: f.atlasTelemetry === true,
atlas7d: f.atlas7d === true,
atlasPoller: f.atlasPoller === true,
+ sensors: f.sensors === true,
mapTelemetry: f.mapTelemetry === true,
alertChannels: { email: f.alertChannels?.email === true, push: f.alertChannels?.push === true },
alertChannelsSent: typeof f.alertChannels === "object" && f.alertChannels !== null,
diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json
index 34326c01..da6a6a01 100644
--- a/src/i18n/locales/en.json
+++ b/src/i18n/locales/en.json
@@ -321,6 +321,7 @@
"noEvidence": "No adverts heard from it",
"noClaim": "This radio has no polling claim.",
"noTargets": "It polls no repeaters yet.",
+ "readingsUnit": "readings",
"localNote": "Local mode. This observer reports no claim, so slots and login state are not known.",
"loadFailed": "Could not load the poller."
},
@@ -328,6 +329,8 @@
"tag": "Foreign",
"info": "These readings come from an observer this site doesn't manage. Its owner may have set it to check this repeater themselves, or it may be managed by other software. The readings reached us over a shared network, so we show them, but this site doesn't control when that observer checks the repeater.",
"alsoReportedBy": "Also reported by",
+ "reportedBy": "Reported by",
+ "claimStale": "no current claim",
"alsoChecked": "Also checked by an outside observer",
"follows": "follows {{host}}",
"readingsOnly": "sends readings only",
@@ -416,6 +419,22 @@
"carpeater": "CARpeater",
"carpeaterHint": "Mobile repeater in a vehicle: its position moves.",
"telemetry": {
+ "calibrating": "Calibrating ({{n}}/3)",
+ "calibrated": "Calibrated (3/3)",
+ "accuracyHelp": "The sensor calibrates itself over hours to days and reports how far it has got, from 0 to 3. Below 3 the air quality index is an estimate and can still change a lot.",
+ "channel": "Channel {{n}}",
+ "sensors": {
+ "humidity": "Humidity (%)",
+ "pressure": "Pressure (hPa)",
+ "gas": "Gas (kΩ)",
+ "airQuality": "Air quality (IAQ)",
+ "sensorVoltage": "Sensor voltage (V)",
+ "current": "Current (A)",
+ "power": "Power (W)",
+ "distance": "Distance (m)",
+ "moisture": "Moisture (%)",
+ "light": "Light (lux)"
+ },
"title": "Telemetry",
"range": "Telemetry range",
"battery": "Battery (V)",
@@ -1237,6 +1256,13 @@
"pinViewHelp": "Make this the tab the card opens on",
"viewPinned": "The card opens on this tab",
"telemetry": {
+ "humidity": "Humidity",
+ "pressure": "Pressure",
+ "gas": "Gas",
+ "airQuality": "Air quality",
+ "power": "Power",
+ "current": "Current",
+ "sensorVoltage": "Sensor voltage",
"temperature": "Temperature",
"packets": "Packets",
"signal": "Signal",
@@ -1461,6 +1487,7 @@
"firing_other": "Alerting: {{count}} alerts",
"turnOn": "Alert: {{name}}",
"backOnlineHint": "Turn on {{name}} first.",
+ "goneQuietHint": "Short windows can false-alarm on radios that are only heard through their adverts.",
"voltsPerDay": "{{volts}} V per day",
"hours_one": "{{count}} hour",
"hours_other": "{{count}} hours",
@@ -1487,6 +1514,7 @@
"kinds": {
"gone_quiet": { "name": "Gone quiet", "when": "When the radio has not been heard for this long." },
"back_online": { "name": "Back online", "when": "When the radio is heard again after it went quiet." },
+ "telemetry_stopped": { "name": "Telemetry stopped", "when": "When no telemetry has arrived for this long." },
"battery_low": { "name": "Battery low", "when": "When the battery stays below this voltage." },
"battery_falling": { "name": "Battery falling", "when": "When the battery drops faster than this in a day." },
"rebooted": { "name": "Rebooted", "when": "When the radio restarts." },
@@ -1498,7 +1526,7 @@
"reason": {
"observerNoData": "This observer does not report {{what}}.",
"repeatersOnly": "Only repeaters report {{what}}.",
- "notPolled": "Beacon is not polling this repeater. Request telemetry for it first.",
+ "notPolled": "No telemetry is arriving for this repeater. Request telemetry for it first.",
"noData": "This repeater does not report {{what}}.",
"observerNoClock": "Observers have no clock drift value.",
"clockRepeatersOnly": "Only repeaters and room servers report their clock.",
@@ -1509,7 +1537,8 @@
"battery": "a battery level",
"uptime": "its uptime",
"temperature": "a temperature",
- "noise": "a noise floor"
+ "noise": "a noise floor",
+ "telemetry": "telemetry"
},
"errors": {
"battery_low": "Enter a voltage between 2.50 and 5.00.",
diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json
index 82724592..d585f06d 100644
--- a/src/i18n/locales/fr.json
+++ b/src/i18n/locales/fr.json
@@ -327,6 +327,7 @@
"noEvidence": "Aucune annonce reçue de ce répéteur",
"noClaim": "Cette radio n’a aucune déclaration d’interrogation.",
"noTargets": "Elle n’interroge encore aucun répéteur.",
+ "readingsUnit": "mesures",
"localNote": "Mode local. Cet observateur n’envoie aucune déclaration, donc les places et l’état de connexion ne sont pas connus.",
"loadFailed": "Impossible de charger l’interrogateur."
},
@@ -334,6 +335,8 @@
"tag": "Externe",
"info": "Ces mesures viennent d’un observateur que ce site ne gère pas. Son propriétaire l’a peut-être réglé pour vérifier ce répéteur lui-même, ou il est peut-être géré par un autre logiciel. Les mesures nous sont parvenues par un réseau partagé, alors nous les affichons, mais ce site ne décide pas quand cet observateur vérifie le répéteur.",
"alsoReportedBy": "Aussi signalé par",
+ "reportedBy": "Signalé par",
+ "claimStale": "aucune déclaration en cours",
"alsoChecked": "Aussi vérifié par un observateur externe",
"follows": "suit {{host}}",
"readingsOnly": "envoie seulement des mesures",
@@ -387,6 +390,22 @@
"observations_many": "{{formatted}} obs.",
"hops": "Sauts",
"telemetry": {
+ "calibrating": "Calibrage en cours ({{n}}/3)",
+ "calibrated": "Calibré (3/3)",
+ "accuracyHelp": "Le capteur se calibre tout seul en quelques heures à quelques jours et indique où il en est, de 0 à 3. En dessous de 3, l'indice de qualité de l'air est une estimation et peut encore beaucoup changer.",
+ "channel": "Canal {{n}}",
+ "sensors": {
+ "humidity": "Humidité (%)",
+ "pressure": "Pression (hPa)",
+ "gas": "Gaz (kΩ)",
+ "airQuality": "Qualité de l'air (IAQ)",
+ "sensorVoltage": "Tension du capteur (V)",
+ "current": "Courant (A)",
+ "power": "Puissance (W)",
+ "distance": "Distance (m)",
+ "moisture": "Humidité du sol (%)",
+ "light": "Luminosité (lux)"
+ },
"title": "Télémétrie",
"range": "Période de télémétrie",
"battery": "Batterie (V)",
@@ -1247,6 +1266,13 @@
"pinViewHelp": "Faire de cet onglet celui sur lequel la fiche s’ouvre",
"viewPinned": "La fiche s’ouvre sur cet onglet",
"telemetry": {
+ "humidity": "Humidité",
+ "pressure": "Pression",
+ "gas": "Gaz",
+ "airQuality": "Qualité de l'air",
+ "power": "Puissance",
+ "current": "Courant",
+ "sensorVoltage": "Tension du capteur",
"temperature": "Température",
"packets": "Paquets",
"signal": "Signal",
@@ -1475,6 +1501,7 @@
"firing_other": "En alerte : {{count}} alertes",
"turnOn": "Alerte : {{name}}",
"backOnlineHint": "Activez d'abord « {{name}} ».",
+ "goneQuietHint": "Un délai court peut donner de fausses alertes sur les radios entendues seulement par leurs annonces.",
"voltsPerDay": "{{volts}} V par jour",
"hours_one": "{{count}} heure",
"hours_many": "{{count}} heures",
@@ -1504,6 +1531,7 @@
"kinds": {
"gone_quiet": { "name": "Silence", "when": "Quand la radio n'a pas été entendue depuis ce délai." },
"back_online": { "name": "De retour", "when": "Quand la radio est de nouveau entendue après un silence." },
+ "telemetry_stopped": { "name": "Télémétrie arrêtée", "when": "Quand aucune télémétrie n'est arrivée depuis ce délai." },
"battery_low": { "name": "Batterie faible", "when": "Quand la batterie reste sous cette tension." },
"battery_falling": { "name": "Batterie en baisse", "when": "Quand la batterie baisse plus vite que cela en une journée." },
"rebooted": { "name": "Redémarrage", "when": "Quand la radio redémarre." },
@@ -1515,7 +1543,7 @@
"reason": {
"observerNoData": "Cet observateur ne remonte pas {{what}}.",
"repeatersOnly": "Seuls les répéteurs remontent {{what}}.",
- "notPolled": "Beacon ne sonde pas ce répéteur. Demandez d'abord sa télémétrie.",
+ "notPolled": "Aucune télémétrie n'arrive pour ce répéteur. Demandez d'abord sa télémétrie.",
"noData": "Ce répéteur ne remonte pas {{what}}.",
"observerNoClock": "Les observateurs n'ont pas de dérive d'horloge.",
"clockRepeatersOnly": "Seuls les répéteurs et les serveurs de salle remontent leur horloge.",
@@ -1526,7 +1554,8 @@
"battery": "le niveau de batterie",
"uptime": "la durée de fonctionnement",
"temperature": "la température",
- "noise": "le niveau de bruit"
+ "noise": "le niveau de bruit",
+ "telemetry": "la télémétrie"
},
"errors": {
"battery_low": "Entrez une tension entre 2,50 et 5,00.",
diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json
index b135705c..99981ac3 100644
--- a/src/i18n/locales/sv.json
+++ b/src/i18n/locales/sv.json
@@ -321,6 +321,7 @@
"noEvidence": "Inga annonser mottagna från den",
"noClaim": "Den här radion har inget avläsningsanspråk.",
"noTargets": "Den avläser inga repeatrar ännu.",
+ "readingsUnit": "mätvärden",
"localNote": "Lokalt läge. Observatören skickar inget anspråk, så platser och inloggningsstatus är inte kända.",
"loadFailed": "Kunde inte läsa in pollaren."
},
@@ -328,6 +329,8 @@
"tag": "Extern",
"info": "Mätvärdena kommer från en observatör som den här webbplatsen inte hanterar. Dess ägare kan ha ställt in den att kontrollera repeatern själv, eller så hanteras den av annan programvara. Mätvärdena nådde oss över ett delat nätverk, så vi visar dem, men den här webbplatsen styr inte när observatören kontrollerar repeatern.",
"alsoReportedBy": "Rapporteras även av",
+ "reportedBy": "Rapporteras av",
+ "claimStale": "inget aktuellt anspråk",
"alsoChecked": "Kontrolleras även av en extern observatör",
"follows": "följer {{host}}",
"readingsOnly": "skickar bara mätvärden",
@@ -380,6 +383,22 @@
"observations_other": "{{formatted}} obs",
"hops": "Hopp",
"telemetry": {
+ "calibrating": "Kalibrerar ({{n}}/3)",
+ "calibrated": "Kalibrerad (3/3)",
+ "accuracyHelp": "Sensorn kalibrerar sig själv under timmar till dagar och anger hur långt den har kommit, från 0 till 3. Under 3 är luftkvalitetsindexet en uppskattning som fortfarande kan ändras mycket.",
+ "channel": "Kanal {{n}}",
+ "sensors": {
+ "humidity": "Luftfuktighet (%)",
+ "pressure": "Lufttryck (hPa)",
+ "gas": "Gas (kΩ)",
+ "airQuality": "Luftkvalitet (IAQ)",
+ "sensorVoltage": "Sensorspänning (V)",
+ "current": "Ström (A)",
+ "power": "Effekt (W)",
+ "distance": "Avstånd (m)",
+ "moisture": "Markfuktighet (%)",
+ "light": "Ljus (lux)"
+ },
"title": "Telemetri",
"range": "Telemetriperiod",
"battery": "Batteri (V)",
@@ -1137,6 +1156,13 @@
"viewTelemetry": "Telemetri",
"viewPoller": "Pollare",
"telemetry": {
+ "humidity": "Luftfuktighet",
+ "pressure": "Lufttryck",
+ "gas": "Gas",
+ "airQuality": "Luftkvalitet",
+ "power": "Effekt",
+ "current": "Ström",
+ "sensorVoltage": "Sensorspänning",
"temperature": "Temperatur",
"packets": "Paket",
"signal": "Signal",
@@ -1361,6 +1387,7 @@
"firing_other": "Larmar: {{count}} larm",
"turnOn": "Avisering: {{name}}",
"backOnlineHint": "Slå först på {{name}}.",
+ "goneQuietHint": "Korta tider kan ge falsklarm för radior som bara hörs genom sina annonser.",
"voltsPerDay": "{{volts}} V per dygn",
"hours_one": "{{count}} timme",
"hours_other": "{{count}} timmar",
@@ -1387,6 +1414,7 @@
"kinds": {
"gone_quiet": { "name": "Tystnat", "when": "När radion inte har hörts på så här länge." },
"back_online": { "name": "Tillbaka online", "when": "När radion hörs igen efter att ha tystnat." },
+ "telemetry_stopped": { "name": "Telemetri upphört", "when": "När ingen telemetri har kommit in på så här länge." },
"battery_low": { "name": "Lågt batteri", "when": "När batteriet stannar under den här spänningen." },
"battery_falling": { "name": "Fallande batteri", "when": "När batteriet sjunker snabbare än så här på ett dygn." },
"rebooted": { "name": "Startade om", "when": "När radion startar om." },
@@ -1398,7 +1426,7 @@
"reason": {
"observerNoData": "Den här observatören rapporterar inte {{what}}.",
"repeatersOnly": "Bara repeatrar rapporterar {{what}}.",
- "notPolled": "Beacon hämtar inte data från den här repeatern. Begär telemetri för den först.",
+ "notPolled": "Ingen telemetri kommer in för den här repeatern. Begär telemetri för den först.",
"noData": "Den här repeatern rapporterar inte {{what}}.",
"observerNoClock": "Observatörer har inget klockavvikelsevärde.",
"clockRepeatersOnly": "Bara repeatrar och rumsservrar rapporterar sin klocka.",
@@ -1409,7 +1437,8 @@
"battery": "batterinivå",
"uptime": "drifttid",
"temperature": "temperatur",
- "noise": "brusnivå"
+ "noise": "brusnivå",
+ "telemetry": "telemetri"
},
"errors": {
"battery_low": "Ange en spänning mellan 2,50 och 5,00.",
diff --git a/tests/features/account/alerts.test.tsx b/tests/features/account/alerts.test.tsx
index ae0f8a06..9fa3c5e1 100644
--- a/tests/features/account/alerts.test.tsx
+++ b/tests/features/account/alerts.test.tsx
@@ -211,7 +211,7 @@ describe("alerts section", () => {
await open(response({ targets: [plain(), odd] }));
expect(block("Ridge").getByText("This repeater does not report a temperature.")).toBeInTheDocument();
expect(block("Odd").getByText("Server sentence one.")).toBeInTheDocument();
- expect(block("Odd").getByText("Beacon is not polling this repeater. Request telemetry for it first.")).toBeInTheDocument();
+ expect(block("Odd").getByText("No telemetry is arriving for this repeater. Request telemetry for it first.")).toBeInTheDocument();
expect(block("Odd").getByText("Server sentence three.")).toBeInTheDocument();
});
@@ -255,17 +255,29 @@ describe("alerts section", () => {
await open(response({ targets: [repeater({ polled: true, available: ["gone_quiet", "clock"] })] }));
expect(options(row("Hilltop", "gone_quiet"))).toEqual(hours(3, 6, 12, 24, 48));
});
- it("offers only 12, 24, 48 for a repeater that is not polled, whatever it lists", async () => {
+ it("offers 3 and 6 for a repeater that is not polled", async () => {
await open(response({ targets: [repeater({ polled: false })] }));
- expect(options(row("Hilltop", "gone_quiet"))).toEqual(hours(12, 24, 48));
+ expect(options(row("Hilltop", "gone_quiet"))).toEqual(hours(3, 6, 12, 24, 48));
});
it("offers 3 and 6 for an observer", async () => {
await open(response({ targets: [repeater({ kind: "observer", available: ["gone_quiet"] })] }));
expect(options(row("Hilltop", "gone_quiet"))).toEqual(hours(3, 6, 12, 24, 48));
});
- it("offers only 12, 24, 48 otherwise", async () => {
+ it("offers the same hours on a radio with no telemetry, with a note about short windows", async () => {
await open(response({ targets: [plain()] }));
- expect(options(row("Ridge", "gone_quiet"))).toEqual(hours(12, 24, 48));
+ expect(options(row("Ridge", "gone_quiet"))).toEqual(hours(3, 6, 12, 24, 48));
+ expect(row("Ridge", "gone_quiet").getByText(/Short windows can false-alarm/)).toBeInTheDocument();
+ expect(row("Ridge", "back_online").queryByText(/Short windows/)).toBeNull();
+ });
+ it("lists telemetry stopped after back online, with the same hours and 12 to start", async () => {
+ await open(response({ targets: [repeater({ available: ["gone_quiet", "back_online", "telemetry_stopped", "battery_low"] })] }));
+ const kinds = within(block("Hilltop").getByRole("list")).getAllByRole("listitem").map((li) => li.getAttribute("data-testid"));
+ expect(kinds).toEqual(["alert-gone_quiet", "alert-back_online", "alert-telemetry_stopped", "alert-battery_low"]);
+ const stopped = row("Hilltop", "telemetry_stopped");
+ expect(stopped.getByText("Telemetry stopped")).toBeInTheDocument();
+ expect(options(stopped)).toEqual(hours(3, 6, 12, 24, 48));
+ fireEvent.click(stopped.getByRole("switch"));
+ await waitFor(() => expect(put()).toHaveBeenCalledWith(expect.objectContaining({ kind: "telemetry_stopped", threshold: 12, enabled: true })));
});
});
diff --git a/tests/features/account/serverContract.test.ts b/tests/features/account/serverContract.test.ts
index 8b370b54..85f52099 100644
--- a/tests/features/account/serverContract.test.ts
+++ b/tests/features/account/serverContract.test.ts
@@ -27,7 +27,8 @@ const reasonOf = (code: string, statusReason: string, days?: number) => ({
const UNAVAILABLE_CODES: Array<[string, string, string]> = [
["observer_no_data", "This observer does not report a battery level.", "battery_low"],
["repeaters_only", "Only repeaters report its uptime.", "rebooted"],
- ["not_polled", "Beacon is not polling this repeater. Request telemetry for it first.", "temperature"],
+ ["not_polled", "No telemetry is arriving for this repeater. Request telemetry for it first.", "temperature"],
+ ["repeaters_only", "Only repeaters report telemetry.", "telemetry_stopped"],
["no_data", "This repeater does not report a noise floor.", "noise_high"],
["observer_no_clock", "Observers have no clock drift value.", "clock"],
["clock_repeaters_only", "Only repeaters and room servers report their clock.", "clock"],
diff --git a/tests/features/atlas/AtlasCard.test.tsx b/tests/features/atlas/AtlasCard.test.tsx
index ea60cd70..a5fc63a7 100644
--- a/tests/features/atlas/AtlasCard.test.tsx
+++ b/tests/features/atlas/AtlasCard.test.tsx
@@ -717,8 +717,36 @@ describe("AtlasCard", () => {
client.clear();
vi.mocked(api.getNodeTelemetry).mockResolvedValue({ ...week, foreign: "all" } as never);
mount({ view: "telemetry" });
- expect(await screen.findByText("Foreign source")).toBeInTheDocument();
+ const tag = await screen.findByText("Foreign source");
expect(screen.getByText("4.23V")).toBeInTheDocument();
+ // It sits in the bottom row with the polling line, under the tiles, and that row has one info tip.
+ const row = tag.closest("[data-card-footer]") as HTMLElement;
+ expect(row).not.toBeNull();
+ expect(within(row).getAllByRole("button")).toHaveLength(1);
+ expect(within(row).getByRole("button")).toHaveTextContent(/observer this site doesn't manage/);
+ // Nobody here polls it, and the tag says who does: the row does not also call it not polled.
+ expect(within(row).queryByText("Not polled")).toBeNull();
+ expect(within(row).getByRole("button")).not.toHaveTextContent(/Not being polled/);
+ });
+
+ it("lets the source tag stand in for Not polled when nobody here polls the repeater", async () => {
+ vi.mocked(api.getNodePolling).mockResolvedValue(polling({ poller: null }));
+ const { unmount } = mount({ view: "telemetry" });
+ await screen.findByText("4.23V");
+ const plain = screen.getByText("Not polled").closest("[data-card-footer]") as HTMLElement;
+ // Polled or not, the row says when the last reading was.
+ expect(within(plain).getByText("Last reading")).toBeInTheDocument();
+ expect(plain.textContent).toMatch(/Last reading · .*ago/);
+ unmount();
+ client.clear();
+ vi.mocked(api.getNodeTelemetry).mockResolvedValue({ ...week, foreign: "all" } as never);
+ mount({ view: "telemetry" });
+ const row = (await screen.findByText("Foreign source")).closest("[data-card-footer]") as HTMLElement;
+ expect(within(row).queryByText("Not polled")).toBeNull();
+ expect(within(row).getByRole("button")).not.toHaveTextContent(/Not being polled/);
+ expect(within(row).getByRole("button")).toHaveTextContent(/observer this site doesn't manage/);
+ expect(within(row).getByText("Last reading")).toBeInTheDocument();
+ expect(row.textContent).toMatch(/Last reading · .*ago/);
});
it("draws two readings as dots, not a line", async () => {
@@ -773,6 +801,30 @@ describe("AtlasCard", () => {
expect(handlers.onTelemetryTilesChange).toHaveBeenCalledWith(["temperature", "noise", "uptime", "airtime"]);
});
+ it("names the gas tile for the air quality index it shows, with a calibration chip that explains itself and no channel caption", async () => {
+ const bme = (iaqAccuracy: number) => ({ ...week, points: week.points.map((p) => ({ ...p, sensors: [{ channel: 2, humidityPct: 21.5, pressureHpa: 984.3, iaq: 138, iaqAccuracy }] })) });
+ vi.mocked(api.getNodeTelemetry).mockResolvedValue(bme(1) as never);
+ const tiles = { pin: { ...pin, telemetryTiles: ["gas", "humidity", "pressure", "battery"] }, view: "telemetry" as const };
+ const { unmount } = mount(tiles);
+ expect(await screen.findByText("IAQ 138")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Change tile: Air quality" })).toBeInTheDocument();
+ const chip = screen.getByText("1/3");
+ expect(chip).toHaveAttribute("data-accuracy", "1");
+ expect(chip.closest(".flex-wrap")!.firstElementChild).toHaveTextContent("Air quality");
+ expect(chip.className).toContain("text-warn");
+ expect(screen.queryByText(/Channel 2/)).toBeNull();
+ fireEvent.mouseEnter(chip.parentElement!);
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(/Calibrating \(1\/3\).*calibrates itself over hours to days/);
+ fireEvent.mouseLeave(chip.parentElement!);
+ expect(screen.getByText("21.5%")).toBeInTheDocument();
+ expect(screen.getByText("984.3 hPa")).toBeInTheDocument();
+ unmount();
+ client.clear();
+ vi.mocked(api.getNodeTelemetry).mockResolvedValue(bme(3) as never);
+ mount(tiles);
+ expect((await screen.findByText("3/3")).className).toContain("text-green");
+ });
+
it("shows packets, signal and errors per the readings", async () => {
mount({ pin: { ...pin, telemetryTiles: ["packets", "signal", "errors", "battery"] }, view: "telemetry" });
expect(await screen.findByText("200/h")).toBeInTheDocument();
diff --git a/tests/features/atlas/AtlasPage.test.tsx b/tests/features/atlas/AtlasPage.test.tsx
index 1601a002..3685c0e0 100644
--- a/tests/features/atlas/AtlasPage.test.tsx
+++ b/tests/features/atlas/AtlasPage.test.tsx
@@ -79,6 +79,15 @@ describe("Atlas page", () => {
await waitFor(() => expect(api.getNodeActivity).toHaveBeenCalledWith(pin.id, "24h", expect.any(AbortSignal)));
});
+ it("lays the cards out in as many columns as fit, with no fixed column count or page width", async () => {
+ save();
+ mount();
+ const grid = (await card("Renamed repeater")).parentElement!;
+ expect(grid).toHaveClass("grid", "grid-cols-[repeat(auto-fill,minmax(min(380px,100%),1fr))]");
+ expect(grid.className).not.toMatch(/grid-cols-[23]\b/);
+ expect(grid.parentElement!.className).not.toMatch(/max-w-/);
+ });
+
it("keeps the search in a toolbar with the saved count chip beside the range picker, and lists matches only while typing", async () => {
save();
mount();
diff --git a/tests/features/atlas/atlasSync.test.ts b/tests/features/atlas/atlasSync.test.ts
index 027f81a6..80a54063 100644
--- a/tests/features/atlas/atlasSync.test.ts
+++ b/tests/features/atlas/atlasSync.test.ts
@@ -81,6 +81,17 @@ describe("toPut", () => {
it("sends 7d only to a server that has it, and 3d otherwise", () => {
expect(toPut(local([node(1)], "7d"), {}, 1, false, true).range).toBe("7d");
+ // What such a server answers has no tiles for that pin: the local layout stays, and only that one.
+ const answer = doc([{ kind: "node", publicKey: key(1), id: uuid(1), name: "A", observerId: null }, { kind: "node", publicKey: key(2), id: uuid(2), name: "B", observerId: null }]);
+ const local2 = local([node(1, { telemetryTiles: ["humidity", "battery", "noise", "uptime"] }), node(2, { telemetryTiles: ["noise", "battery", "uptime", "airtime"] })]);
+ const kept = fromServer(answer, local2, {}, false, false, false, true).atlas.pins as { telemetryTiles?: string[] }[];
+ expect(kept.map((p) => p.telemetryTiles)).toEqual([["humidity", "battery", "noise", "uptime"], undefined]);
+ const reset = fromServer(answer, local2, {}, false, false, false, false).atlas.pins as { telemetryTiles?: string[] }[];
+ expect(reset.map((p) => p.telemetryTiles)).toEqual([undefined, undefined]);
+ // Sensor tiles go out only to a server that knows them; the other tiles are not held back.
+ const sensorPin = local([node(1, { telemetryTiles: ["humidity", "battery", "noise", "uptime"] }), node(2, { telemetryTiles: ["noise", "battery", "uptime", "airtime"] })]);
+ expect(toPut(sensorPin, {}, 1, true, true, true, true).pins.map((p) => (p as { telemetryTiles?: string[] }).telemetryTiles)).toEqual([["humidity", "battery", "noise", "uptime"], ["noise", "battery", "uptime", "airtime"]]);
+ expect(toPut(sensorPin, {}, 1, true, true, true, false).pins.map((p) => (p as { telemetryTiles?: string[] }).telemetryTiles)).toEqual([undefined, ["noise", "battery", "uptime", "airtime"]]);
expect(toPut(local([node(1)], "7d"), {}, 1, false, false).range).toBe("3d");
expect(toPut(local([node(1)], "7d"), {}, 1).range).toBe("3d");
});
diff --git a/tests/features/atlas/telemetry-sample.test.ts b/tests/features/atlas/telemetry-sample.test.ts
index 0326738b..e8a9a200 100644
--- a/tests/features/atlas/telemetry-sample.test.ts
+++ b/tests/features/atlas/telemetry-sample.test.ts
@@ -127,3 +127,57 @@ describe("sparkValues", () => {
expect(sparkValues(line.slice(1))).toHaveLength(DOT_LIMIT * 2 - 3);
});
});
+
+describe("summarizeTelemetry sensors", () => {
+ const ina = (channel: number, voltageV: number) => ({ channel, voltageV, currentA: 0.122, powerW: 1.061 });
+ it("leaves the sensor tiles empty for readings without sensors", () => {
+ const s = summarizeTelemetry(readings, "24h", now);
+ for (const tile of ["humidity", "pressure", "gas", "power", "current", "sensorVoltage"] as const) expect(s[tile]).toEqual({ latest: null, values: [], points: [] });
+ expect(s.sensorChannel).toEqual({});
+ expect(s.gasIsIndex).toBe(false);
+ });
+ it("reads each tile from the lowest channel that carries it", () => {
+ const s = summarizeTelemetry(data([
+ point(3, { sensors: [{ channel: 2, humidityPct: 40, pressureHpa: 1010, gasOhms: 48_000 }, ina(4, 12.1), ina(3, 8.7)] }),
+ point(2, {}),
+ point(1, { sensors: [{ channel: 2, humidityPct: 45.5, pressureHpa: 1013.2, gasOhms: 50_000 }, ina(3, 8.6)] }),
+ ]), "24h", now);
+ expect(s.humidity.values).toEqual([40, 45.5]);
+ expect(s.pressure.latest).toBe(1013.2);
+ expect(s.gas.values).toEqual([48, 50]);
+ expect(s.sensorVoltage.values).toEqual([8.7, 8.6]);
+ expect(s.power.latest).toBe(1.061);
+ expect(s.current.latest).toBe(0.122);
+ expect(s.sensorChannel).toEqual({ humidity: 2, pressure: 2, gas: 2, power: 3, current: 3, sensorVoltage: 3 });
+ });
+ it("shows the air quality index on the gas tile when the sensor sends one", () => {
+ const s = summarizeTelemetry(data([point(1, { sensors: [{ channel: 2, humidityPct: 45.5, pressureHpa: 1013.2, iaq: 50, iaqAccuracy: 3 }] })]), "24h", now);
+ expect(s.gasIsIndex).toBe(true);
+ expect(s.gas.latest).toBe(50);
+ });
+ it("lets the lowest gas channel decide between resistance and index", () => {
+ const s = summarizeTelemetry(data([point(1, { sensors: [{ channel: 2, gasOhms: 50_000 }, { channel: 3, iaq: 42, iaqAccuracy: 3 }] })]), "24h", now);
+ expect(s.gasIsIndex).toBe(false);
+ expect(s.gas.latest).toBe(50);
+ expect(s.sensorChannel.gas).toBe(2);
+ });
+ it("skips sensors that are not what the contract says", () => {
+ const odd = [{ sensors: {} }, { sensors: [null, "x", { humidityPct: 40 }, { channel: 2, humidityPct: "wet" }, { channel: 3, humidityPct: 41 }] }, { sensors: null }] as unknown as Partial[];
+ const s = summarizeTelemetry(data(odd.map((extra, i) => point(3 - i, extra))), "24h", now);
+ expect(s.humidity.values).toEqual([41]);
+ expect(s.sensorChannel).toEqual({ humidity: 3 });
+ });
+ it("carries the air quality sensor's newest calibration status, and none for a resistance", () => {
+ const iaq = (hoursAgo: number, iaqAccuracy: number) => point(hoursAgo, { sensors: [{ channel: 2, iaq: 100, iaqAccuracy }] });
+ expect(summarizeTelemetry(data([iaq(3, 0), iaq(2, 1), point(1, {})]), "24h", now).gasAccuracy).toBe(1);
+ expect(summarizeTelemetry(data([iaq(2, 2), iaq(1, 3)]), "24h", now).gasAccuracy).toBe(3);
+ expect(summarizeTelemetry(data([point(1, { sensors: [{ channel: 2, gasOhms: 50_000 }] })]), "24h", now).gasAccuracy).toBeNull();
+ expect(summarizeTelemetry(readings, "24h", now).gasAccuracy).toBeNull();
+ });
+ it("shows the index when one channel sent a resistance earlier in the window and an index since", () => {
+ const s = summarizeTelemetry(data([point(3, { sensors: [{ channel: 2, gasOhms: 50_000 }] }), point(1, { sensors: [{ channel: 2, iaq: 42, iaqAccuracy: 2 }] })]), "24h", now);
+ expect(s.gasIsIndex).toBe(true);
+ expect(s.gas.values).toEqual([42]);
+ expect(s.gasAccuracy).toBe(2);
+ });
+});
diff --git a/tests/features/atlas/tile-graph.test.ts b/tests/features/atlas/tile-graph.test.ts
index cdcbb785..862517bd 100644
--- a/tests/features/atlas/tile-graph.test.ts
+++ b/tests/features/atlas/tile-graph.test.ts
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any -- poking into loose ECharts option shapes */
import { describe, expect, it } from "vitest";
import { summarizeActivity } from "../../../src/features/atlas/atlas";
-import { NODE_METRICS, OBSERVER_METRICS, readingPoints, slotPoints, telemetryMetrics, tileGraphOption } from "../../../src/features/atlas/tile-graph";
+import { AIR_QUALITY, NODE_METRICS, OBSERVER_METRICS, readingPoints, slotPoints, telemetryMetrics, tileGraphOption } from "../../../src/features/atlas/tile-graph";
import type { ChartColors } from "../../../src/features/stats/chartTheme";
import type { NodeActivity } from "../../../src/features/nodes/types";
@@ -91,6 +91,10 @@ describe("tileGraphOption", () => {
expect(format({ ...telemetryMetrics("c").signal, ...base }, 9)).toBe("9.0 dB");
expect(format({ ...telemetryMetrics("c").temperature, ...base }, 20)).toBe("20.0 °C");
expect(format({ ...telemetryMetrics("f").temperature, ...base }, 20)).toBe("68.0 °F");
+ const m = telemetryMetrics("c");
+ expect([m.humidity.format(45.5), m.pressure.format(1013.2), m.gas.format(50), m.power.format(1.061), m.current.format(0.122), m.sensorVoltage.format(8.7)])
+ .toEqual(["45.5%", "1013.2 hPa", "50.0 kΩ", "1.061 W", "0.122 A", "8.70 V"]);
+ expect(AIR_QUALITY.format(50.4)).toBe("IAQ 50");
});
it("starts counts at zero and labels the axis in the tile's words where a number would not read", () => {
diff --git a/tests/features/nodes/NodePollerSection.test.tsx b/tests/features/nodes/NodePollerSection.test.tsx
index 98157ddf..58b2861c 100644
--- a/tests/features/nodes/NodePollerSection.test.tsx
+++ b/tests/features/nodes/NodePollerSection.test.tsx
@@ -300,6 +300,9 @@ describe("NodePollerSection states", () => {
const { onViewNode } = mount({ claim: null, readings24h: 9, foreignReadings24h: 9, targets: [target({ ...bare, latestReadingRssi: -91.4, latestReadingSigned: true }), target({ ...bare, nodeId: null, publicKey: key("c0ffee11"), name: "Bravo" })] });
expect(await screen.findByText("Local mode. This observer reports no claim, so slots and login state are not known.")).toBeInTheDocument();
expect(document.querySelector("[data-claim-tags] [data-chip=local-observer]")).toHaveTextContent("Local");
+ // The tag shares the count's row, as the Signed chip does beside a claim's slot count.
+ const row = document.querySelector("[data-claim-tags]")!.parentElement!.parentElement!;
+ expect(row).toHaveTextContent(/^\d+\s*readings/);
expect(screen.getByRole("button", { name: /Runs in local mode: it polls repeaters its owner set up by hand and follows no server\./ })).toBeInTheDocument();
expect(screen.getByText("9")).toBeInTheDocument();
expect(screen.queryByRole("img")).not.toBeInTheDocument();
diff --git a/tests/features/nodes/NodeTelemetrySection.test.tsx b/tests/features/nodes/NodeTelemetrySection.test.tsx
index a9dac2c3..26cab6cb 100644
--- a/tests/features/nodes/NodeTelemetrySection.test.tsx
+++ b/tests/features/nodes/NodeTelemetrySection.test.tsx
@@ -177,13 +177,20 @@ describe("NodeTelemetrySection", () => {
it("lists them under the poller, flags the poller and links each one to its Poller view", async () => {
mockTelemetry.mockResolvedValue({ ...tele([point]), foreign: "some" });
- mockPolling.mockResolvedValue(polling({ foreign: [lakeside, { ...lakeside, observerId: "obs-local", name: "Shed", pollHost: null, signed: false, claimed: false }] }));
+ const shed = { ...lakeside, observerId: "obs-local", name: "Shed", pollHost: null, signed: false, claimed: false, local: true };
+ // A foreign poller that went quiet: its claim is stale, so claimed is false, but it is not local.
+ const quiet = { ...lakeside, observerId: "obs-quiet", name: "Quiet", pollHost: null, signed: false, claimed: false, local: false };
+ mockPolling.mockResolvedValue(polling({ foreign: [lakeside, shed, quiet] }));
const { onViewObserver } = renderSection();
expect(await screen.findByText("Also reported by")).toBeInTheDocument();
expect(screen.getByText("Also checked by an outside observer")).toBeInTheDocument();
expect(screen.getByText("Includes foreign readings")).toBeInTheDocument();
const rows = document.querySelectorAll("[data-foreign-observer]");
- expect(rows).toHaveLength(2);
+ expect(rows).toHaveLength(3);
+ expect(rows[2]!.querySelector("[data-chip=local-observer]")).toBeNull();
+ expect(rows[2]).toHaveTextContent("Foreign");
+ expect(rows[2]).toHaveTextContent("no current claim");
+ expect(rows[2]).not.toHaveTextContent("sends readings only");
expect(rows[0]).toHaveTextContent("Foreign");
expect(rows[0]).toHaveTextContent("Signed");
expect(rows[0]).toHaveTextContent("follows other.example.org");
@@ -208,7 +215,7 @@ describe("NodeTelemetrySection", () => {
});
it("calls the source local when every outside reporter sends no claim", async () => {
- const shed = { ...lakeside, observerId: "obs-local", name: "Shed", pollHost: null, signed: false, claimed: false };
+ const shed = { ...lakeside, observerId: "obs-local", name: "Shed", pollHost: null, signed: false, claimed: false, local: true };
mockTelemetry.mockResolvedValue({ ...tele([point]), foreign: "all" });
mockPolling.mockResolvedValue(polling({ poller: null, foreign: [shed] }));
renderSection();
@@ -221,7 +228,9 @@ describe("NodeTelemetrySection", () => {
mockTelemetry.mockResolvedValue(tele([], false));
mockPolling.mockResolvedValue(polling({ polled: false, latestReadingAt: null, poller: null, foreign: [lakeside] }));
renderSection();
- expect(await screen.findByText("Also reported by")).toBeInTheDocument();
+ // No poller of this server checks it, so they are not "also".
+ expect(await screen.findByText("Reported by")).toBeInTheDocument();
+ expect(screen.queryByText("Also reported by")).not.toBeInTheDocument();
expect(screen.getByText("Lakeside")).toBeInTheDocument();
});
diff --git a/tests/features/nodes/nodeTelemetryOptions.test.ts b/tests/features/nodes/nodeTelemetryOptions.test.ts
index 9a0e6a1f..da5da4ae 100644
--- a/tests/features/nodes/nodeTelemetryOptions.test.ts
+++ b/tests/features/nodes/nodeTelemetryOptions.test.ts
@@ -9,7 +9,7 @@ const colors: ChartColors = {
textBright: "#fff", textNormal: "#ccc", textMuted: "#999", textDim: "#666", bgBase: "#000", bgSurface: "#111",
bgRaised: "#222", border: "#333", borderSubtle: "#2a2a2a", series: ["#s0", "#s1", "#s2"],
};
-const labels = { battery: "Battery (V)", temperature: "Temperature (°C)", noise: "Noise floor (dBm)" };
+const labels = { battery: "Battery (V)", temperature: "Temperature (°C)", noise: "Noise floor (dBm)", channel: (n: number) => `Channel ${n}`, accuracy: (n: number) => (n >= 3 ? "Calibrated (3/3)" : `Calibrating (${n}/3)`) };
const H = 3_600_000;
const tele = (points: NodeTelemetry["points"], interval = "1h"): NodeTelemetry => ({ range: "24h", interval, polled: true, untrustedReadings: 0, points });
@@ -119,3 +119,73 @@ describe("buildNodeCharts", () => {
expect(air(full.points, "RX").symbol).not.toBe("none");
});
});
+
+describe("buildNodeCharts sensors", () => {
+ const bme = { channel: 2, temperatureC: 21.4, humidityPct: 45.5, pressureHpa: 1013.2, iaq: 50, iaqAccuracy: 3 };
+ const ina = (channel: number, voltageV: number) => ({ channel, voltageV, currentA: 0.122, powerW: 1.061 });
+ const names = (option: any) => option.series.map((s: any) => s.name);
+ const values = (option: any, i = 0) => option.series[i].data.map((d: any) => d[1]);
+
+ it("builds no sensor chart for readings without sensors", () => {
+ const charts = buildNodeCharts(tele([{ t: 0, readings: 1, batteryMv: 4000 }]), colors, labels, "c");
+ expect(charts.sensors).toBeUndefined();
+ });
+
+ it("builds one chart per value a channel carries, named by channel, and only those", () => {
+ const charts = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [bme, ina(3, 8.7)] }]), colors, labels, "c");
+ expect(Object.keys(charts.sensors!)).toEqual(["humidity", "pressure", "airQuality", "sensorVoltage", "current", "power"]);
+ expect(names(charts.sensors!.humidity)).toEqual(["Channel 2"]);
+ expect(values(charts.sensors!.humidity)).toEqual([45.5]);
+ expect(values(charts.sensors!.power)).toEqual([1.061]);
+ expect((charts.sensors!.humidity as any).legend).toBeUndefined();
+ });
+
+ it("draws one line per channel with a legend when two channels carry the same value", () => {
+ const charts = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [ina(4, 12.1), ina(3, 8.7)] }, { t: H, readings: 1, sensors: [ina(3, 8.6)] }]), colors, labels, "c");
+ const v = charts.sensors!.sensorVoltage as any;
+ expect(names(v)).toEqual(["Channel 3", "Channel 4"]);
+ expect(values(v, 0)).toEqual([8.7, 8.6]);
+ expect(values(v, 1)).toEqual([12.1, null]);
+ expect(v.legend).toBeDefined();
+ expect(v.series[0].itemStyle.color).not.toBe(v.series[1].itemStyle.color);
+ expect(v.series.every((s: any) => s.symbol === "circle" && s.connectNulls === false)).toBe(true);
+ });
+
+ it("shows gas resistance in kΩ", () => {
+ const charts = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [{ channel: 2, gasOhms: 50_000 }] }]), colors, labels, "c");
+ expect(values(charts.sensors!.gas)).toEqual([50]);
+ expect(charts.sensors!.airQuality).toBeUndefined();
+ });
+
+ it("adds sensor temperatures to the temperature chart, in the instance unit", () => {
+ const both = buildNodeCharts(tele([{ t: 0, readings: 1, temperatureC: 10, sensors: [bme] }]), colors, labels, "f");
+ expect(names(both.temperature)).toEqual(["Temperature (°C)", "Channel 2"]);
+ expect(values(both.temperature, 0)).toEqual([50]);
+ expect(values(both.temperature, 1)[0]).toBeCloseTo(70.52, 2);
+ const only = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [bme] }]), colors, labels, "c");
+ expect(names(only.temperature)).toEqual(["Channel 2"]);
+ });
+
+ it("never draws anything about a position", () => {
+ const charts = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [{ ...bme, lat: 45.1, lon: -74.2, altitude: 120 } as any] }]), colors, labels, "c");
+ expect(Object.keys(charts.sensors!)).toEqual(["humidity", "pressure", "airQuality"]);
+ });
+
+ it("draws what it can from sensors that are not what the contract says", () => {
+ const odd = [{ t: 0, readings: 1, sensors: {} }, { t: H, readings: 1, sensors: [null, { channel: 2, humidityPct: 41 }] }] as unknown as NodeTelemetry["points"];
+ const charts = buildNodeCharts(tele(odd), colors, labels, "c");
+ expect(values(charts.sensors!.humidity)).toEqual([null, 41]);
+ });
+
+ it("says how far an air quality sensor's calibration has got: one figure for the heading's chip, or on each line for several channels", () => {
+ const iaq = (channel: number, iaqAccuracy: number | undefined) => ({ channel, iaq: 100, iaqAccuracy });
+ const one = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [iaq(2, 0)] }, { t: H, readings: 1, sensors: [iaq(2, 1)] }, { t: 2 * H, readings: 1 }]), colors, labels, "c");
+ expect(one.airQualityAccuracy).toBe(1);
+ expect(names(one.sensors!.airQuality)).toEqual(["Channel 2"]);
+ const two = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [iaq(2, 3), iaq(3, 2)] }]), colors, labels, "c");
+ expect(two.airQualityAccuracy).toBeUndefined();
+ expect(names(two.sensors!.airQuality)).toEqual(["Channel 2 · Calibrated (3/3)", "Channel 3 · Calibrating (2/3)"]);
+ const unknown = buildNodeCharts(tele([{ t: 0, readings: 1, sensors: [iaq(2, undefined)] }, { t: H, readings: 1, sensors: [{ channel: 2, iaq: 90, iaqAccuracy: 7 }] }]), colors, labels, "c");
+ expect(unknown.airQualityAccuracy).toBeUndefined();
+ });
+});
diff --git a/tests/hooks/useFeatures.test.tsx b/tests/hooks/useFeatures.test.tsx
index f2ad8f42..520bed0c 100644
--- a/tests/hooks/useFeatures.test.tsx
+++ b/tests/hooks/useFeatures.test.tsx
@@ -4,7 +4,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { useDisplayUnits, useFeatures, useFeaturesLoading } from "../../src/hooks/useFeatures";
-const OFF = { polling: false, accounts: "off", registration: false, telemetryRequests: false, alerts: false, atlasTelemetry: false, atlas7d: false, atlasPoller: false, mapTelemetry: false, alertChannels: { email: false, push: false }, alertChannelsSent: false };
+const OFF = { polling: false, accounts: "off", registration: false, telemetryRequests: false, alerts: false, atlasTelemetry: false, atlas7d: false, atlasPoller: false, sensors: false, mapTelemetry: false, alertChannels: { email: false, push: false }, alertChannelsSent: false };
let client: QueryClient;
const wrapper = ({ children }: { children: ReactNode }) => {children};
const stubInfo = (body: unknown, ok = true) =>
@@ -35,7 +35,7 @@ describe("useFeatures", () => {
});
it("returns the server's values when present", async () => {
- const features = { polling: true, accounts: "local", registration: true, telemetryRequests: true, alerts: true, atlasTelemetry: true, atlas7d: true, atlasPoller: true, mapTelemetry: true, alertChannels: { email: false, push: true } };
+ const features = { polling: true, accounts: "local", registration: true, telemetryRequests: true, alerts: true, atlasTelemetry: true, atlas7d: true, atlasPoller: true, sensors: true, mapTelemetry: true, alertChannels: { email: false, push: true } };
stubInfo({ serverVersion: "2.3.0", features });
const { result } = renderHook(() => useFeatures(), { wrapper });
await waitFor(() => expect(result.current.polling).toBe(true));