diff --git a/assets/locales/en.json b/assets/locales/en.json index ab32294..a3b0000 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1417,6 +1417,7 @@ "empty": "Alerts are set on radios in your Atlas. Add a radio there first.", "requestAttention": "You are always told when one of your telemetry requests needs attention.", "needsGoneQuiet": "Turn on {{name}} first.", + "goneQuietHint": "Short windows can false-alarm on radios that are only heard through their adverts.", "summaryNone": "No alerts on", "summaryOnCount_one": "{{count}} alert on", "summaryOnCount_other": "{{count}} alerts on", @@ -1431,6 +1432,7 @@ "kind": { "gone_quiet": "Gone quiet", "back_online": "Back online", + "telemetry_stopped": "Telemetry stopped", "battery_low": "Battery low", "battery_falling": "Battery falling", "rebooted": "Rebooted", @@ -1478,6 +1480,7 @@ "when": { "gone_quiet": "When the radio has not been heard for this long.", "back_online": "When the radio is heard again after it went quiet.", + "telemetry_stopped": "When no telemetry has arrived for this long.", "battery_low": "When the battery stays below this voltage.", "battery_falling": "When the battery drops faster than this in a day.", "rebooted": "When the radio restarts.", @@ -1506,7 +1509,7 @@ "alertReason": { "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.", @@ -1517,7 +1520,8 @@ "battery": "a battery level", "uptime": "its uptime", "temperature": "a temperature", - "noise": "a noise floor" + "noise": "a noise floor", + "telemetry": "telemetry" }, "errors": { "busy": "The server is busy. Try again in a moment.", @@ -1736,6 +1740,8 @@ "telemetryAll": "Foreign source", "telemetrySome": "Includes foreign readings", "alsoReportedBy": "Also reported by", + "reportedBy": "Reported by", + "claimStale": "no current claim", "alsoChecked": "Also checked by an outside observer", "signed": "Signed", "signedExplain": "This observer signs its polling announcements with its own key, and this site checked the signature. That confirms the announcement really came from this observer and wasn't changed on the way here.", @@ -1754,6 +1760,34 @@ }, "foreignPollerChip": { "label": "Foreign poller" + }, + "localPoller": { + "label": "Local poller", + "tag": "Local", + "explain": "Runs in local mode: it polls repeaters its owner set up by hand and follows no server.", + "readingsUnit": "readings", + "note": "Local mode. This observer reports no claim, so slots and login state are not known.", + "sourceExplain": "Polled by an observer in local mode, set up by its owner. This server does not manage it.", + "footer": "Local mode", + "repeaters": "Repeaters", + "sourceAll": "Local source", + "sourceSome": "Includes local readings" + }, + "sensors": { + "channel": "Channel {{n}}", + "humidity": "Humidity", + "pressure": "Pressure", + "gas": "Gas", + "airQuality": "Air quality", + "power": "Power", + "current": "Current", + "sensorVoltage": "Sensor voltage", + "distance": "Distance", + "moisture": "Moisture", + "light": "Light", + "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." } } } diff --git a/assets/locales/fr.json b/assets/locales/fr.json index b83b3ed..7830076 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1464,6 +1464,7 @@ "empty": "Les alertes se règlent sur les radios de votre Atlas. Ajoutez d'abord une radio.", "requestAttention": "Vous êtes toujours prévenu quand une de vos demandes de télémétrie demande votre attention.", "needsGoneQuiet": "Activez d'abord « {{name}} ».", + "goneQuietHint": "Un délai court peut donner de fausses alertes sur les radios entendues seulement par leurs annonces.", "summaryNone": "Aucune alerte activée", "summaryOnCount_one": "{{count}} alerte activée", "summaryOnCount_many": "{{count}} alertes activées", @@ -1480,6 +1481,7 @@ "kind": { "gone_quiet": "Silence", "back_online": "De retour", + "telemetry_stopped": "Télémétrie arrêtée", "battery_low": "Batterie faible", "battery_falling": "Batterie en baisse", "rebooted": "Redémarrage", @@ -1527,6 +1529,7 @@ "when": { "gone_quiet": "Quand la radio n'a pas été entendue depuis ce délai.", "back_online": "Quand la radio est de nouveau entendue après un silence.", + "telemetry_stopped": "Quand aucune télémétrie n'est arrivée depuis ce délai.", "battery_low": "Quand la batterie reste sous cette tension.", "battery_falling": "Quand la batterie baisse plus vite que cela en une journée.", "rebooted": "Quand la radio redémarre.", @@ -1555,7 +1558,7 @@ "alertReason": { "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.", @@ -1566,7 +1569,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": { "busy": "Le serveur est occupé. Réessayez dans un instant.", @@ -1787,6 +1791,8 @@ "telemetryAll": "Source externe", "telemetrySome": "Inclut des relevés externes", "alsoReportedBy": "Aussi signalé par", + "reportedBy": "Signalé par", + "claimStale": "aucune déclaration en cours", "alsoChecked": "Aussi interrogé par un observateur extérieur", "signed": "Signé", "signedExplain": "Cet observateur signe ses annonces d'interrogation avec sa propre clé, et ce site a vérifié la signature. Cela confirme que l'annonce vient bien de cet observateur et n'a pas été modifiée en chemin.", @@ -1805,6 +1811,34 @@ }, "foreignPollerChip": { "label": "Interrogateur externe" + }, + "localPoller": { + "label": "Interrogateur local", + "tag": "Local", + "explain": "Fonctionne en mode local : il interroge les répéteurs que son propriétaire a réglés à la main et ne suit aucun serveur.", + "readingsUnit": "mesures", + "note": "Mode local. Cet observateur n'envoie aucune déclaration, donc les places et l'état de connexion ne sont pas connus.", + "sourceExplain": "Interrogé par un observateur en mode local, réglé par son propriétaire. Ce serveur ne le gère pas.", + "footer": "Mode local", + "repeaters": "Répéteurs", + "sourceAll": "Source locale", + "sourceSome": "Inclut des mesures locales" + }, + "sensors": { + "channel": "Canal {{n}}", + "humidity": "Humidité", + "pressure": "Pression", + "gas": "Gaz", + "airQuality": "Qualité de l’air", + "power": "Puissance", + "current": "Courant", + "sensorVoltage": "Tension du capteur", + "distance": "Distance", + "moisture": "Humidité du sol", + "light": "Luminosité", + "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." } } } diff --git a/assets/locales/sv.json b/assets/locales/sv.json index 4480e26..62f6d0c 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -1417,6 +1417,7 @@ "empty": "Aviseringar ställs in på radioapparater i din Atlas. Lägg först till en radio.", "requestAttention": "Du får alltid besked när en av dina telemetribegäranden behöver uppmärksamhet.", "needsGoneQuiet": "Slå först på {{name}}.", + "goneQuietHint": "Korta tider kan ge falsklarm för radior som bara hörs genom sina annonser.", "summaryNone": "Inga larm på", "summaryOnCount_one": "{{count}} larm på", "summaryOnCount_other": "{{count}} larm på", @@ -1431,6 +1432,7 @@ "kind": { "gone_quiet": "Tystnat", "back_online": "Tillbaka online", + "telemetry_stopped": "Telemetri upphört", "battery_low": "Lågt batteri", "battery_falling": "Fallande batteri", "rebooted": "Startade om", @@ -1478,6 +1480,7 @@ "when": { "gone_quiet": "När radion inte har hörts på så här länge.", "back_online": "När radion hörs igen efter att ha tystnat.", + "telemetry_stopped": "När ingen telemetri har kommit in på så här länge.", "battery_low": "När batteriet stannar under den här spänningen.", "battery_falling": "När batteriet sjunker snabbare än så här på ett dygn.", "rebooted": "När radion startar om.", @@ -1506,7 +1509,7 @@ "alertReason": { "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.", @@ -1517,7 +1520,8 @@ "battery": "batterinivå", "uptime": "drifttid", "temperature": "temperatur", - "noise": "brusnivå" + "noise": "brusnivå", + "telemetry": "telemetri" }, "errors": { "busy": "Servern är upptagen. Försök igen om en stund.", @@ -1736,6 +1740,8 @@ "telemetryAll": "Extern källa", "telemetrySome": "Innehåller externa mätvärden", "alsoReportedBy": "Rapporteras även av", + "reportedBy": "Rapporteras av", + "claimStale": "inget aktuellt anspråk", "alsoChecked": "Kontrolleras även av en utomstående observatör", "signed": "Signerad", "signedExplain": "Den här observatören signerar sina pollningsmeddelanden med sin egen nyckel, och den här sajten kontrollerade signaturen. Det bekräftar att meddelandet verkligen kom från den här observatören och inte ändrades på vägen hit.", @@ -1754,6 +1760,34 @@ }, "foreignPollerChip": { "label": "Extern pollare" + }, + "localPoller": { + "label": "Lokal pollare", + "tag": "Lokal", + "explain": "Körs i lokalt läge: den avläser repeatrar som ägaren har ställt in för hand och följer ingen server.", + "readingsUnit": "mätvärden", + "note": "Lokalt läge. Den här observatören skickar inget anspråk, så platser och inloggningsstatus är inte kända.", + "sourceExplain": "Avläses av en observatör i lokalt läge, inställd av ägaren. Den här servern hanterar den inte.", + "footer": "Lokalt läge", + "repeaters": "Repeatrar", + "sourceAll": "Lokal källa", + "sourceSome": "Innehåller lokala mätvärden" + }, + "sensors": { + "channel": "Kanal {{n}}", + "humidity": "Luftfuktighet", + "pressure": "Lufttryck", + "gas": "Gas", + "airQuality": "Luftkvalitet", + "power": "Effekt", + "current": "Ström", + "sensorVoltage": "Sensorspänning", + "distance": "Avstånd", + "moisture": "Markfuktighet", + "light": "Ljus", + "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." } } } diff --git a/ios/NotificationService/BeaconPush.swift b/ios/NotificationService/BeaconPush.swift index 75721af..27f7795 100644 --- a/ios/NotificationService/BeaconPush.swift +++ b/ios/NotificationService/BeaconPush.swift @@ -88,6 +88,7 @@ enum BeaconPush { switch n.kind { case "gone_quiet": return "\(name) has not been heard for \(plural(v, "hour"))." case "back_online": return "\(name) is back online." + case "telemetry_stopped": return "\(name) has sent no telemetry for \(plural(v, "hour"))." case "battery_low": return "\(name) battery is low: \(fixed(Double(v) / 1000, 2)) V." case "battery_falling": return "\(name) battery is falling by about \(fixed(Double(v) / 1000, 2)) V a day." diff --git a/lib/core/features.dart b/lib/core/features.dart index 9e22775..1895bef 100644 --- a/lib/core/features.dart +++ b/lib/core/features.dart @@ -12,6 +12,7 @@ class ServerFeatures { this.atlasTelemetry = false, this.atlasPoller = false, this.atlas7d = false, + this.sensors = false, this.mapTelemetry = false, this.appDeviceLabel = false, this.temperatureUnit = 'c', @@ -31,6 +32,7 @@ class ServerFeatures { atlasTelemetry = false, atlasPoller = false, atlas7d = false, + sensors = false, mapTelemetry = false, appDeviceLabel = false, temperatureUnit = 'c', @@ -55,6 +57,7 @@ class ServerFeatures { atlasTelemetry: f['atlasTelemetry'] == true, atlasPoller: f['atlasPoller'] == true, atlas7d: f['atlas7d'] == true, + sensors: f['sensors'] == true, mapTelemetry: f['mapTelemetry'] == true, appDeviceLabel: f['appDeviceLabel'] == true, temperatureUnit: d['temperatureUnit'] == 'f' ? 'f' : 'c', @@ -85,6 +88,9 @@ class ServerFeatures { /// The Atlas takes a 7 day range, and the account Atlas stores it. final bool atlas7d; + /// Readings carry sensor channels, and the account Atlas stores sensor tiles. + final bool sensors; + /// Map labels may carry the latest telemetry; the toggle hides without it. final bool mapTelemetry; diff --git a/lib/core/push_notice.dart b/lib/core/push_notice.dart index c54f4f4..2cfa90a 100644 --- a/lib/core/push_notice.dart +++ b/lib/core/push_notice.dart @@ -77,6 +77,8 @@ String? alertSentence(PushNotice n) { return '$name has not been heard for ${_plural(v, 'hour')}.'; case 'back_online': return '$name is back online.'; + case 'telemetry_stopped': + return '$name has sent no telemetry for ${_plural(v, 'hour')}.'; case 'battery_low': return '$name battery is low: ${(v / 1000).toStringAsFixed(2)} V.'; case 'battery_falling': diff --git a/lib/features/account/alert_rule_list.dart b/lib/features/account/alert_rule_list.dart index dbaa982..a021b3c 100644 --- a/lib/features/account/alert_rule_list.dart +++ b/lib/features/account/alert_rule_list.dart @@ -122,12 +122,7 @@ class _AlertRowState extends State<_AlertRow> { bool get enabled => widget.rule?['enabled'] == true; int? _stored(String field) => number(widget.rule?[field])?.toInt(); - List get options => widget.spec.input == AlertInput.hours - ? goneQuietHours( - textOf(widget.target['kind']), - widget.target['polled'] == true, - ) - : widget.spec.options; + List get options => widget.spec.options; @override void initState() { @@ -468,6 +463,11 @@ class _AlertRowState extends State<_AlertRow> { ), const SizedBox(height: 10), _input(), + if (kind == 'gone_quiet') + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text(trKey('alerts.goneQuietHint'), style: muted), + ), if (enabled && rule != null) Padding( padding: const EdgeInsets.only(top: 4), diff --git a/lib/features/account/alert_rules.dart b/lib/features/account/alert_rules.dart index 85b7d00..e3d27eb 100644 --- a/lib/features/account/alert_rules.dart +++ b/lib/features/account/alert_rules.dart @@ -18,8 +18,9 @@ class AlertKindSpec { /// The kinds in the order the rows are shown (the plan's table order). const alertKinds = [ - AlertKindSpec('gone_quiet', AlertInput.hours, [12, 24, 48]), + AlertKindSpec('gone_quiet', AlertInput.hours, quietHours), AlertKindSpec('back_online', AlertInput.none), + AlertKindSpec('telemetry_stopped', AlertInput.hours, quietHours), AlertKindSpec('battery_low', AlertInput.volts), AlertKindSpec('battery_falling', AlertInput.drop, [100, 200, 300]), AlertKindSpec('rebooted', AlertInput.none), @@ -29,20 +30,12 @@ const alertKinds = [ AlertKindSpec('observer_offline', AlertInput.minutes, [30, 60, 180, 360]), ]; -/// Gone quiet also offers 3 and 6 hours for observers and polled repeaters; -/// `polled` is the server's own answer for the radio. -List goneQuietHours(String targetKind, bool polled) { - final short = targetKind == 'observer' || polled; - return [ - if (short) ...[3, 6], - 12, - 24, - 48, - ]; -} +/// The hours gone_quiet and telemetry_stopped take, on every radio. +const quietHours = [3, 6, 12, 24, 48]; const defaultThreshold = { 'gone_quiet': 24, + 'telemetry_stopped': 12, 'battery_low': 3500, 'battery_falling': 200, 'noise_high': -90, @@ -137,6 +130,7 @@ const _what = { 'rebooted': 'uptime', 'temperature': 'temperature', 'noise_high': 'noise', + 'telemetry_stopped': 'telemetry', }; /// Why a kind is unavailable, in the user's language, read from the code. No diff --git a/lib/features/analytics/charts.dart b/lib/features/analytics/charts.dart index feb276a..c22f3bf 100644 --- a/lib/features/analytics/charts.dart +++ b/lib/features/analytics/charts.dart @@ -73,9 +73,29 @@ class AnalyticsEmptyState extends StatelessWidget { } class AnalyticsCard extends StatelessWidget { - const AnalyticsCard({super.key, required this.title, required this.child}); + const AnalyticsCard({ + super.key, + required this.title, + required this.child, + this.trailing, + }); final String title; final Widget child; + + /// Sits at the end of the title's line, or under it when the two do not fit. + final Widget? trailing; + + Widget _title(BuildContext context) => Text( + tr(title).toUpperCase(), + style: TextStyle( + fontFamily: 'JetBrainsMono', + fontWeight: FontWeight.w600, + fontSize: 11, + letterSpacing: .6, + color: BeaconColors.of(context).muted, + ), + ); + @override Widget build(BuildContext context) => Container( width: double.infinity, @@ -91,16 +111,19 @@ class AnalyticsCard extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - tr(title).toUpperCase(), - style: TextStyle( - fontFamily: 'JetBrainsMono', - fontWeight: FontWeight.w600, - fontSize: 11, - letterSpacing: .6, - color: BeaconColors.of(context).muted, + if (trailing == null) + _title(context) + else + SizedBox( + width: double.infinity, + child: Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + runSpacing: 4, + children: [_title(context), trailing!], + ), ), - ), const SizedBox(height: 10), child, ], diff --git a/lib/features/atlas/atlas.dart b/lib/features/atlas/atlas.dart index c9a4b00..9065b8b 100644 --- a/lib/features/atlas/atlas.dart +++ b/lib/features/atlas/atlas.dart @@ -56,7 +56,21 @@ const telemetryTileIds = [ 'packets', 'signal', 'errors', + ...sensorTileIds, ]; + +/// Tiles read from a repeater's sensor channels; only a server with +/// `features.sensors` stores them. +const sensorTileIds = [ + 'humidity', + 'pressure', + 'gas', + 'power', + 'current', + 'sensorVoltage', +]; +bool hasSensorTile(List? tiles) => + tiles?.any(sensorTileIds.contains) ?? false; const defaultTelemetryTiles = ['battery', 'noise', 'uptime', 'airtime']; final _uuid = RegExp( diff --git a/lib/features/atlas/atlas_card.dart b/lib/features/atlas/atlas_card.dart index 72ab6e8..dfbd4a7 100644 --- a/lib/features/atlas/atlas_card.dart +++ b/lib/features/atlas/atlas_card.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; @@ -428,7 +429,7 @@ class _AtlasCardState extends State { ? false : pollerData == null ? null - : pollerData['claim'] is Map; + : pollerData['claim'] is Map || isLocalPollerAnswer(pollerData); final showPoller = pollerTab == true || (pollerTab == null && widget.view == AtlasView.poller); @@ -517,10 +518,7 @@ class _AtlasCardState extends State { node?['isPoller'] == true || id != null) observerChip(), - if (node != null && isForeignPoller(node)) - foreignPollerChip() - else if (node?['isPoller'] == true) - pollerChip(), + if (node != null) ?pollerChipFor(node), ], ]; final title = ConstrainedBox( @@ -1140,11 +1138,21 @@ class _AtlasCardState extends State { widget.now, ); final tiles = pin.telemetryTiles ?? defaultTelemetryTiles; + // A gas sensor that sends an air quality index is named for what it shows. + String tileName(String tile) => trKey( + tile == 'gas' && sample.gasIsIaq + ? 'sensors.airQuality' + : sensorTileIds.contains(tile) + ? 'sensors.$tile' + : 'atlasTelemetry.$tile', + ); final free = { for (final tile in telemetryTileIds) + // Not every repeater has these, so they are offered only with data. if (!tiles.contains(tile) && - (tile != 'temperature' || sample.hasTemperature)) - tile: trKey('atlasTelemetry.$tile'), + (tile != 'temperature' || sample.has(tile)) && + (!sensorTileIds.contains(tile) || sample.has(tile))) + tile: tileName(tile), }; String rate(double v) => '${v < 10 ? v.toStringAsFixed(1) : formatCount(v.roundToDouble())}/h'; @@ -1194,17 +1202,34 @@ class _AtlasCardState extends State { if (latest != null && sample.rssi != null) { sub = '${sample.rssi!.round()} dBm'; } + case 'humidity': + format = (v) => '${v.toStringAsFixed(1)}%'; + case 'pressure': + format = (v) => '${v.toStringAsFixed(1)} hPa'; + case 'gas': + format = sample.gasIsIaq + ? (v) => 'IAQ ${v.round()}' + : (v) => '${v.toStringAsFixed(1)} kΩ'; + case 'power': + format = (v) => '${v.toStringAsFixed(3)} W'; + case 'current': + format = (v) => '${v.toStringAsFixed(3)} A'; + case 'sensorVoltage': + format = (v) => '${v.toStringAsFixed(2)} V'; default: peak = counter = true; format = rate; } final value = latest == null ? null : format(latest); final dots = values.length < dotsBelow; - final metric = trKey('atlasTelemetry.$tile'); + final metric = tileName(tile); + final iaq = tile == 'gas' && value != null + ? sample.gasIaqAccuracy + : null; return AtlasStatTile( key: ValueKey('telemetry-$tile'), label: TilePicker( - label: trKey('atlasTelemetry.$tile'), + label: metric, options: free, onPick: (next) => widget.onTelemetryTilesChange([ for (final (i, old) in tiles.indexed) i == slot ? next : old, @@ -1220,6 +1245,18 @@ class _AtlasCardState extends State { markPeak: peak && !dots, dots: dots, wrapSublabel: true, + // An index from a sensor still learning is not to be trusted yet. + caption: iaq == null + ? null + : AtlasPill( + '$iaq/3', + key: const ValueKey('pill-iaq'), + color: iaqColor(iaq, c), + ), + captionName: iaqStatus(iaq), + captionTip: iaq == null + ? null + : '${iaqStatus(iaq)}\n\n${trKey('sensors.accuracyHelp')}', onGraph: openGraph( metric, series[_slotAccent[slot]], @@ -1252,43 +1289,50 @@ class _AtlasCardState extends State { .replaceAll('{{name}}', pollerName)) : trKey('atlasTelemetry.notPolled'); final polledNow = polling['poller'] is Map; - final String? lead = polling.isEmpty - ? (latestAt == null - ? null - : '${trKey('atlasTelemetry.lastReading')} · ${ago(latestAt, widget.now)}') - : polledNow - ? [ - trKey('atlasFooter.polled'), - if (latestAt != null) ago(latestAt, widget.now), - ].join(' · ') - : trKey('atlasFooter.notPolled'); + // The footer always says when the last reading was. Readings from an + // observer this server does not manage are tagged there; with nobody here + // polling, the tag stands in for "Not polled". + final foreign = telemetryForeign(object(feed?.data)); + final outside = foreign != 'none'; + final localSource = allLocalReporters(polling); + final plain = polling.isNotEmpty && !outside; + final String? lead = polledNow + ? trKey('atlasFooter.polled') + : latestAt != null + ? trKey('atlasTelemetry.lastReading') + : plain + ? trKey('atlasFooter.notPolled') + : null; body.add( Column( key: _body, crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ - if (telemetryForeignTag(telemetryForeign(object(feed?.data))) - case final NodeChip tag) ...[ - Align(alignment: Alignment.centerLeft, child: tag), - const SizedBox(height: 10), - ], _TileGrid([ for (var slot = 0; slot < _telemetryTileCount; slot++) telemetryTile(tiles[slot], slot), ]), const SizedBox(height: 12), _Footer( - dot: polling.isEmpty ? null : _dot(c, polledNow), + dot: polledNow || plain ? _dot(c, polledNow) : null, left: lead, - right: polledNow && pollerName.isNotEmpty - ? trKey('atlasFooter.byPoller') - .replaceAll('{{name}}', pollerName) + age: latestAt == null ? null : ago(latestAt, widget.now), + tag: telemetryForeignTag(foreign, local: localSource, bare: true), + right: polledNow + ? (pollerName.isEmpty + ? '' + : trKey('atlasFooter.byPoller') + .replaceAll('{{name}}', pollerName)) + : plain && latestAt != null + ? trKey('atlasFooter.notPolled') : '', + keepRight: !polledNow, loading: feed?.loading ?? false, failed: feed?.error != null && !isNotFound(feed?.error), tip: [ - ?pollLine, + if (polledNow || !outside) ?pollLine, + if (outside) telemetrySourceExplanation(localSource), if (latestAt != null) '${trKey('atlasTelemetry.lastReading')} ${formatAbsolute(latestAt)}', trKey('atlasTelemetry.help'), @@ -1314,6 +1358,8 @@ class _AtlasCardState extends State { final slots = object(claim?['slots']); int n(String key) => number(slots[key])?.round() ?? 0; final targets = rows(pollerData?['targets']); + // Local mode has no claim: only the readings and the repeaters are known. + final local = pollerData != null && isLocalPollerAnswer(pollerData); // A 404 takes the tab away; any other failed refresh keeps the last answer. final refreshFailed = pollerQuery?.error != null; // An answer that could not be refreshed is not shown as a live claim. @@ -1401,44 +1447,51 @@ class _AtlasCardState extends State { ), ), ), - tile( - 'answering', - trKey('nodePoller.state.ok'), - claim == null - ? null - : '${targets.where((t) => t['state'] == 'ok').length}', - sublabel: fill('ofTargets', {'count': targets.length}), - visual: ExcludeSemantics( - child: visual( - Wrap( - spacing: 4, - runSpacing: 4, - clipBehavior: Clip.hardEdge, - children: [ - for (final (i, t) in targets.indexed) - Container( - key: ValueKey('atlas-poller-dot-$i'), - width: 6, - height: 6, - decoration: BoxDecoration( - color: switch (t['state']) { - 'ok' => c.success, - 'pending' => c.dim, - 'no_reply' => c.warning, - _ => c.danger, - }, - shape: BoxShape.circle, + if (local) + tile( + 'repeaters', + trKey('localPoller.repeaters'), + '${targets.length}', + ) + else + tile( + 'answering', + trKey('nodePoller.state.ok'), + claim == null + ? null + : '${targets.where((t) => t['state'] == 'ok').length}', + sublabel: fill('ofTargets', {'count': targets.length}), + visual: ExcludeSemantics( + child: visual( + Wrap( + spacing: 4, + runSpacing: 4, + clipBehavior: Clip.hardEdge, + children: [ + for (final (i, t) in targets.indexed) + Container( + key: ValueKey('atlas-poller-dot-$i'), + width: 6, + height: 6, + decoration: BoxDecoration( + color: switch (t['state']) { + 'ok' => c.success, + 'pending' => c.dim, + 'no_reply' => c.warning, + _ => c.danger, + }, + shape: BoxShape.circle, + ), ), - ), - ], + ], + ), ), ), ), - ), tile( 'readings', trKey('atlasPoller.readings'), - claim == null + claim == null && !local ? null : formatCount( number(pollerData?['readings24h'])?.roundToDouble() ?? @@ -1487,7 +1540,9 @@ class _AtlasCardState extends State { : live ? pollerColor : c.dim.withValues(alpha: .3), - left: claim == null + left: local + ? trKey('localPoller.footer') + : claim == null ? null : claim['live'] == true ? trKey( @@ -1507,7 +1562,7 @@ class _AtlasCardState extends State { trKey('nodePoller.meter') .replaceAll('{{used}}', '${n('used')}') .replaceAll('{{max}}', '${n('max')}'), - trKey('atlasPoller.help'), + trKey(local ? 'localPoller.note' : 'atlasPoller.help'), ], ), ], @@ -1563,13 +1618,17 @@ class _TileGrid extends StatelessWidget { ); } -/// One line that never wraps: the right side gives way first, then the left, a -/// failure never does, and the tip carries every fact in full. +/// One line that never wraps. The right side gives way first, then the left's +/// label, then its age, which drops out whole; a tag or failure never does, and +/// the tip carries every fact in full. class _Footer extends StatelessWidget { const _Footer({ this.left, this.dot, + this.age, + this.tag, required this.right, + this.keepRight = false, required this.loading, required this.failed, this.refreshFailed = false, @@ -1577,7 +1636,16 @@ class _Footer extends StatelessWidget { }); final String? left; final Color? dot; + + /// How long ago the left side's fact was; kept whole while the left gives way. + final String? age; + + /// Follows the left side and is never cut short: the left gives way to it. + final Widget? tag; final String right; + + /// The right side is a state, not a detail: the label gives way to it. + final bool keepRight; final bool loading, failed; /// A later read failed and the data shown is the earlier answer. @@ -1605,31 +1673,59 @@ class _Footer extends StatelessWidget { : loading ? tr('Loading…') : null; + final scaler = MediaQuery.textScalerOf(context); + final base = DefaultTextStyle.of(context).style.merge(style); + // What a text needs to show whole, so the layout can share out the row. + double wide(String? value) { + if (value == null || value.isEmpty) return 0; + final painter = TextPainter( + text: TextSpan(text: value, style: base), + textDirection: Directionality.of(context), + textScaler: scaler, + maxLines: 1, + )..layout(); + final width = painter.width.ceilToDouble(); + painter.dispose(); + return width; + } + + final aged = left != null && age != null; return CustomMultiChildLayout( - delegate: _FooterLayout(height), + delegate: _FooterLayout( + height, + label: wide(left), + sep: aged ? wide(_sep) : 0, + age: aged ? wide(age) : 0, + right: wide(right), + keepRight: keepRight, + ), children: [ + if (left != null && dot != null) + LayoutId( + id: 'dot', + child: Container( + key: const ValueKey('atlas-footer-dot'), + width: 6, + height: 6, + decoration: BoxDecoration(color: dot, shape: BoxShape.circle), + ), + ), if (left != null) LayoutId( id: 'left', - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (dot != null) ...[ - Container( - key: const ValueKey('atlas-footer-dot'), - width: 6, - height: 6, - decoration: BoxDecoration( - color: dot, - shape: BoxShape.circle, - ), - ), - const SizedBox(width: 6), - ], - Flexible(child: text(left!)), - ], - ), + child: ClipRect(child: text(left!)), ), + if (aged) + LayoutId( + id: 'sep', + child: ClipRect(child: text(_sep)), + ), + if (aged) + LayoutId( + id: 'age', + child: ClipRect(child: text(age!)), + ), + if (tag != null) LayoutId(id: 'tag', child: tag!), if (state != null) LayoutId( id: 'state', @@ -1642,18 +1738,37 @@ class _Footer extends StatelessWidget { : null, ), ), - LayoutId(id: 'right', child: text(right)), + LayoutId( + id: 'right', + child: ClipRect(child: text(right)), + ), if (tip.isNotEmpty) LayoutId(id: 'tip', child: AtlasInfoTip(tip)), ], ); } } +const _sep = ' · '; + // A custom layout, not a LayoutBuilder: cards sit in rows sized to the tallest one. class _FooterLayout extends MultiChildLayoutDelegate { - _FooterLayout(this.height); + _FooterLayout( + this.height, { + required this.label, + required this.sep, + required this.age, + required this.right, + required this.keepRight, + }); final double height; - static const _gap = 12.0; + + /// What each text needs to show whole. + final double label, sep, age, right; + final bool keepRight; + static const _gap = 12.0, _tagGap = 6.0, _dotGap = 6.0; + + /// Under these a cut text reads as noise, so it drops out instead. + static const _minRight = 40.0, _minLabel = 24.0; @override Size getSize(BoxConstraints constraints) => @@ -1675,25 +1790,78 @@ class _FooterLayout extends MultiChildLayoutDelegate { state = layoutChild('state', upTo(room)); room -= state.width + _gap; } + Size? tag; + if (hasChild('tag')) { + tag = layoutChild('tag', upTo(room)); + room -= tag.width + _tagGap; + } + var rightRoom = room; if (hasChild('left')) { - final left = layoutChild('left', upTo(room)); - positionChild('left', Offset(0, mid(left))); - x = left.width + _gap; - room -= left.width + _gap; + var lead = 0.0; + if (hasChild('dot')) { + final dot = layoutChild('dot', upTo(room)); + positionChild('dot', Offset(0, mid(dot))); + if (dot.width > 0) lead = dot.width + _dotGap; + } + final inner = room - lead; + double beside(double right) => right > 0 ? right + _gap : 0; + var rightWidth = right; + if (label + sep + age + beside(right) > inner) { + // A state keeps its place and the label gives way; a detail goes first. + rightWidth = keepRight + ? math.min(right, inner - age - _gap) + : inner - label - sep - age - _gap; + if (rightWidth < math.min(right, _minRight)) rightWidth = 0; + } + var labelRoom = math.min(label, inner - sep - age - beside(rightWidth)); + // With an age to show, a sliver of label and its dot give it the room. + final bare = age > 0 && labelRoom < math.min(label, _minLabel); + if (bare) labelRoom = 0; + final left = layoutChild('left', upTo(labelRoom)); + positionChild('left', Offset(lead, mid(left))); + var width = lead + left.width; + if (hasChild('sep')) { + final dotted = layoutChild('sep', upTo(bare ? 0 : sep)); + positionChild('sep', Offset(width, mid(dotted))); + width += dotted.width; + // An age that cannot show whole is left to the tip. + final ago = layoutChild( + 'age', + upTo(bare && inner < age ? 0 : room - width), + ); + positionChild('age', Offset(width, mid(ago))); + width += ago.width; + } + x = width + (tag == null ? _gap : _tagGap); + room -= width + _gap; + rightRoom = math.min(room, rightWidth); + } + if (tag != null) { + positionChild('tag', Offset(x, mid(tag))); + x += tag.width + _gap; } if (state != null) { positionChild('state', Offset(x, mid(state))); x += state.width + _gap; } - final right = layoutChild('right', upTo(room)); + final end = layoutChild( + 'right', + upTo(rightRoom < math.min(right, _minRight) ? 0 : rightRoom), + ); positionChild( 'right', - Offset(size.width - tip.width - right.width, mid(right)), + Offset(size.width - tip.width - end.width, mid(end)), ); } @override - bool shouldRelayout(_FooterLayout old) => old.height != height; + bool shouldRelayout(_FooterLayout old) => + old.height != height || + old.label != label || + old.sep != sep || + old.age != age || + old.right != right || + old.keepRight != keepRight; } /// A footer dot: lit while the fact it leads with is fresh. diff --git a/lib/features/atlas/atlas_grid.dart b/lib/features/atlas/atlas_grid.dart index 7d02c80..e093fdf 100644 --- a/lib/features/atlas/atlas_grid.dart +++ b/lib/features/atlas/atlas_grid.dart @@ -1,10 +1,11 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'atlas_widgets.dart'; -/// Cards in one, two or three columns, reordered by dragging a card's grip: +/// Cards in as many columns as fit, reordered by dragging a card's grip: /// the grabbed card follows the finger and the cards between its old and new /// slot slide into the neighbouring slot, so a drop lands where it looks. class AtlasGrid extends StatefulWidget { @@ -25,12 +26,10 @@ class AtlasGrid extends StatefulWidget { final void Function(int from, int to) onReorder; final double gap; - /// The web's md and xl breakpoints. - static int columnsFor(double width) => width >= 1280 - ? 3 - : width >= 768 - ? 2 - : 1; + /// As many columns as fit at the web's minimum card width, inside the screen's 16px padding. + static int columnsFor(double width, {double gap = 14}) => + math.max(1, ((width - 32 + gap) / (minCardWidth + gap)).floor()); + static const double minCardWidth = 380; @override State createState() => _AtlasGridState(); @@ -171,7 +170,10 @@ class _AtlasGridState extends State { @override Widget build(BuildContext context) { _slots.removeWhere((key, _) => !widget.keys.contains(key)); - final columns = AtlasGrid.columnsFor(MediaQuery.sizeOf(context).width); + final columns = AtlasGrid.columnsFor( + MediaQuery.sizeOf(context).width, + gap: widget.gap, + ); final count = widget.keys.length, from = _from; if (columns == 1) { return RaisedFlex( diff --git a/lib/features/atlas/atlas_screen.dart b/lib/features/atlas/atlas_screen.dart index b58a650..08c9738 100644 --- a/lib/features/atlas/atlas_screen.dart +++ b/lib/features/atlas/atlas_screen.dart @@ -542,100 +542,92 @@ class _AtlasScreenState extends State with WidgetsBindingObserver { Expanded( child: SingleChildScrollView( padding: const EdgeInsets.all(16), - child: Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 1568), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (store.notice case final notice?) - Padding( - padding: const EdgeInsets.only(bottom: 14), - child: Text(switch (notice.kind) { - AtlasNoticeKind.conflict => at('conflict'), - AtlasNoticeKind.overflow => at( - 'overflow', - count: notice.count, - ), - AtlasNoticeKind.failed => at('syncFailed'), - AtlasNoticeKind.overLimit => trKey( - 'atlasLimits.overLimit', - count: notice.limit, - ).replaceAll('{{remove}}', '${notice.count}'), - }, style: atlasMono(11, c.warning)), - ), - if (store.storageFailed) - Padding( - padding: const EdgeInsets.only(bottom: 14), - child: Text( - at('storageFailed'), - style: atlasMono(11, c.warning), - ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (store.notice case final notice?) + Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Text(switch (notice.kind) { + AtlasNoticeKind.conflict => at('conflict'), + AtlasNoticeKind.overflow => at( + 'overflow', + count: notice.count, ), - if (typed.isNotEmpty) - Padding( - padding: const EdgeInsets.only(bottom: 14), - child: AtlasPanel( - title: Text(at('matches').toUpperCase()), - child: _matches(c, hint, full), + AtlasNoticeKind.failed => at('syncFailed'), + AtlasNoticeKind.overLimit => trKey( + 'atlasLimits.overLimit', + count: notice.limit, + ).replaceAll('{{remove}}', '${notice.count}'), + }, style: atlasMono(11, c.warning)), + ), + if (store.storageFailed) + Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Text( + at('storageFailed'), + style: atlasMono(11, c.warning), + ), + ), + if (typed.isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 14), + child: AtlasPanel( + title: Text(at('matches').toUpperCase()), + child: _matches(c, hint, full), + ), + ), + if (saved.pins.isEmpty) + AtlasEmpty( + title: at('emptyTitle'), + subtitle: at('emptyDescription', args: {'limit': limit}), + ) + else + AtlasGrid( + keys: [for (final pin in saved.pins) pin.key], + onReorder: reorder, + itemBuilder: (context, index, handle) { + final pin = saved.pins[index]; + final counts = alertCounts(_alertTarget(pin)); + return AtlasCard( + onAlerts: alertsOn + ? (name) => _openAlerts(pin, name) + : null, + alertsOn: counts.on, + alertsFiring: counts.firing, + api: widget.api, + pin: pin, + range: range, + active: active, + now: now, + view: viewOf(pin), + onViewChange: (view) => setView(pin, view), + onPinView: (view) => pinView(pin, view), + onRemove: () => remove(pin), + onResolved: (id, observerId) => replace( + pin, + (other) => other.isNode + ? other.relinked(id, observerId) + : other, + relink: true, ), - ), - if (saved.pins.isEmpty) - AtlasEmpty( - title: at('emptyTitle'), - subtitle: at( - 'emptyDescription', - args: {'limit': limit}, + onUpgrade: (match, observerId) => + upgrade(pin, match, observerId), + onTilesChange: (tiles) => + replace(pin, (other) => other.withTiles(tiles)), + onTelemetryTilesChange: (tiles) => replace( + pin, + (other) => other.isNode + ? other.withTelemetryTiles(tiles) + : other, ), - ) - else - AtlasGrid( - keys: [for (final pin in saved.pins) pin.key], - onReorder: reorder, - itemBuilder: (context, index, handle) { - final pin = saved.pins[index]; - final counts = alertCounts(_alertTarget(pin)); - return AtlasCard( - onAlerts: alertsOn - ? (name) => _openAlerts(pin, name) - : null, - alertsOn: counts.on, - alertsFiring: counts.firing, - api: widget.api, - pin: pin, - range: range, - active: active, - now: now, - view: viewOf(pin), - onViewChange: (view) => setView(pin, view), - onPinView: (view) => pinView(pin, view), - onRemove: () => remove(pin), - onResolved: (id, observerId) => replace( - pin, - (other) => other.isNode - ? other.relinked(id, observerId) - : other, - relink: true, - ), - onUpgrade: (match, observerId) => - upgrade(pin, match, observerId), - onTilesChange: (tiles) => - replace(pin, (other) => other.withTiles(tiles)), - onTelemetryTilesChange: (tiles) => replace( - pin, - (other) => other.isNode - ? other.withTelemetryTiles(tiles) - : other, - ), - onOpen: widget.onOpen, - handle: handle, - editing: editing, - ); - }, - ), - ], - ), - ), + onOpen: widget.onOpen, + handle: handle, + editing: editing, + ); + }, + ), + ], ), ), ), diff --git a/lib/features/atlas/atlas_store.dart b/lib/features/atlas/atlas_store.dart index 46162a7..45dd7f2 100644 --- a/lib/features/atlas/atlas_store.dart +++ b/lib/features/atlas/atlas_store.dart @@ -73,6 +73,8 @@ class AtlasStore extends ChangeNotifier { bool _pollerSync = false; // Whether the server stores the 7 day range; otherwise the local copy keeps it. bool _weekSync = false; + // Whether the server stores sensor tiles; otherwise the local copy keeps them. + bool _sensorSync = false; bool _disposed = false; int _changes = 0; Future? _job; @@ -193,7 +195,11 @@ class AtlasStore extends ChangeNotifier { /// saved copy unless given. SavedAtlas _kept(SavedAtlas server, [SavedAtlas? local]) { local ??= saved; - var atlas = _telemetrySync ? server : carryTelemetry(server, local); + var atlas = !_telemetrySync + ? carryTelemetry(server, local) + : _sensorSync + ? server + : carrySensors(server, local); if (!_pollerSync) atlas = carryPoller(atlas, local); return _weekSync ? atlas : carryWeek(atlas, local); } @@ -205,6 +211,7 @@ class AtlasStore extends ChangeNotifier { _telemetrySync = features.atlasTelemetry; _pollerSync = features.atlasPoller; _weekSync = features.atlas7d; + _sensorSync = features.sensors; return true; } @@ -301,6 +308,7 @@ class AtlasStore extends ChangeNotifier { telemetry: _telemetrySync, poller: _pollerSync, week: _weekSync, + sensors: _sensorSync, ); doc = await account!.api.putAtlas( _revision!, diff --git a/lib/features/atlas/atlas_sync.dart b/lib/features/atlas/atlas_sync.dart index 2a0a9b9..a04ec6e 100644 --- a/lib/features/atlas/atlas_sync.dart +++ b/lib/features/atlas/atlas_sync.dart @@ -86,7 +86,7 @@ ServerAtlas? parseServerAtlas(Json doc) { /// observer by id, as a local pin only has that. An older server rejects the /// Telemetry fields, so without [telemetry] they stay out, and without [poller] /// so does a pinned Poller view. Without [week] a 7 day range goes out as three -/// days. +/// days, and without [sensors] tiles that hold a sensor tile stay out. Json atlasPutBody( SavedAtlas saved, Map keys, @@ -94,6 +94,7 @@ Json atlasPutBody( bool telemetry = true, bool poller = true, bool week = true, + bool sensors = true, }) => { 'baseRevision': revision, 'range': effectiveRange(saved.range, week).id, @@ -105,7 +106,8 @@ Json atlasPutBody( 'publicKey': pin.publicKey, 'name': pin.name, 'tiles': ?pin.tiles, - if (telemetry) 'telemetryTiles': ?pin.telemetryTiles, + if (telemetry && (sensors || !hasSensorTile(pin.telemetryTiles))) + 'telemetryTiles': ?pin.telemetryTiles, 'view': ?((pin.view == AtlasView.telemetry && !telemetry) || (pin.view == AtlasView.poller && !poller) @@ -204,6 +206,31 @@ SavedAtlas carryTelemetry(SavedAtlas server, SavedAtlas local) { ); } +/// Against a server that does not store sensor tiles, a card's tiles that hold +/// one went out as the default, so the local choice stays. +SavedAtlas carrySensors(SavedAtlas server, SavedAtlas local) { + final mine = {for (final pin in local.pins) pin.key: pin}; + return server.copyWith( + pins: [ + for (final pin in server.pins) + if (pin.isNode && + pin.telemetryTiles == null && + hasSensorTile(mine[pin.key]?.telemetryTiles)) + AtlasPin.node( + id: pin.id!, + publicKey: pin.publicKey!, + name: pin.name, + observerId: pin.observerId, + tiles: pin.tiles, + telemetryTiles: mine[pin.key]!.telemetryTiles, + view: pin.view, + ) + else + pin, + ], + ); +} + /// Against a server that does not store a pinned Poller view, the local copy /// keeps it. SavedAtlas carryPoller(SavedAtlas server, SavedAtlas local) { diff --git a/lib/features/atlas/atlas_widgets.dart b/lib/features/atlas/atlas_widgets.dart index ff521c9..0d49e89 100644 --- a/lib/features/atlas/atlas_widgets.dart +++ b/lib/features/atlas/atlas_widgets.dart @@ -1176,6 +1176,9 @@ class AtlasStatTile extends StatelessWidget { this.markPeak = false, this.presence, this.sublabel, + this.caption, + this.captionName, + this.captionTip, this.interpolateGaps = false, this.dots = false, this.wrapSublabel = false, @@ -1202,6 +1205,13 @@ class AtlasStatTile extends StatelessWidget { final List? presence; final String? sublabel; + /// A pill for the end of the label's row; it takes the sub-label's place + /// and drops under a label it does not fit beside. + final Widget? caption; + + /// What the pill is called, and what a tap on its corner explains. + final String? captionName, captionTip; + /// Replaces the sparkline. final Widget? visual; @@ -1306,7 +1316,8 @@ class AtlasStatTile extends StatelessWidget { ), ), ); - return Container( + final tip = caption == null ? null : captionTip; + final box = Container( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), decoration: BoxDecoration( color: c.surface, @@ -1316,27 +1327,30 @@ class AtlasStatTile extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Wrap( - alignment: WrapAlignment.spaceBetween, - crossAxisAlignment: WrapCrossAlignment.end, - spacing: 8, - runSpacing: 2, - children: [ - label, - if (sublabel != null) - Text( - sublabel!, - maxLines: wrapSublabel ? null : 1, - overflow: wrapSublabel ? null : TextOverflow.ellipsis, - style: TextStyle( - fontFamily: _mono, - fontSize: 9, - height: 1.5, - color: c.dim, + if (caption != null) + _LabelRow(children: [label, caption!]) + else + Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.end, + spacing: 8, + runSpacing: 2, + children: [ + label, + if (sublabel != null) + Text( + sublabel!, + maxLines: wrapSublabel ? null : 1, + overflow: wrapSublabel ? null : TextOverflow.ellipsis, + style: TextStyle( + fontFamily: _mono, + fontSize: 9, + height: 1.5, + color: c.dim, + ), ), - ), - ], - ), + ], + ), const SizedBox(height: 2), _value(c), const Spacer(), @@ -1345,6 +1359,34 @@ class AtlasStatTile extends StatelessWidget { ], ), ); + if (tip == null) return box; + // The pill is too small to tap: the tile's corner around it answers. + return Stack( + fit: StackFit.passthrough, + children: [ + box, + Positioned( + top: 0, + right: 0, + width: 48, + height: 48, + child: Tooltip( + message: tip, + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 12), + margin: const EdgeInsets.symmetric(horizontal: 16), + child: Semantics( + button: true, + label: captionName, + hint: tip, + child: const SizedBox.expand( + key: ValueKey('atlas-tile-caption-tap'), + ), + ), + ), + ), + ], + ); } } @@ -1415,6 +1457,133 @@ class TilePicker extends StatelessWidget { } } +/// A tile sized pill: a figure in [color], no taller than the tile label's line. +class AtlasPill extends StatelessWidget { + const AtlasPill(this.text, {super.key, required this.color}); + final String text; + final Color color; + @override + Widget build(BuildContext context) => Container( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1), + decoration: BoxDecoration( + color: color.withValues(alpha: .09), + border: Border.all(color: color.withValues(alpha: .3)), + borderRadius: BorderRadius.circular(3), + ), + child: Text( + text, + maxLines: 1, + softWrap: false, + style: TextStyle( + fontFamily: _mono, + fontSize: 9, + height: 1.2, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ); +} + +/// A tile label with a pill at the end of its first line. The label wraps at +/// its words to make room; when its longest word cannot sit beside the pill, +/// the pill goes under the label, at the right. +class _LabelRow extends MultiChildRenderObjectWidget { + const _LabelRow({required super.children}); + @override + RenderObject createRenderObject(BuildContext context) => _RenderLabelRow(); +} + +class _LabelRowSlot extends ContainerBoxParentData {} + +class _RenderLabelRow extends RenderBox + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { + static const _gap = 5.0, _under = 2.0; + + @override + void setupParentData(RenderBox child) { + if (child.parentData is! _LabelRowSlot) child.parentData = _LabelRowSlot(); + } + + RenderBox get _label => firstChild!; + RenderBox get _pill => lastChild!; + + /// The label's width beside the pill, or null when its longest word needs + /// the whole row. + double? _beside(double width, double pill) { + final room = width - pill - _gap; + return _label.getMinIntrinsicWidth(double.infinity) <= room ? room : null; + } + + double _height(double width) { + final pill = _pill.getMaxIntrinsicWidth(double.infinity); + final pillHeight = _pill.getMaxIntrinsicHeight(pill); + final beside = _beside(width, pill); + return beside != null + ? math.max(_label.getMaxIntrinsicHeight(beside), pillHeight) + : _label.getMaxIntrinsicHeight(width) + _under + pillHeight; + } + + @override + double computeMinIntrinsicWidth(double height) => math.max( + _label.getMinIntrinsicWidth(height), + _pill.getMaxIntrinsicWidth(height), + ); + @override + double computeMaxIntrinsicWidth(double height) => + _label.getMaxIntrinsicWidth(height) + + _gap + + _pill.getMaxIntrinsicWidth(height); + @override + double computeMinIntrinsicHeight(double width) => _height(width); + @override + double computeMaxIntrinsicHeight(double width) => _height(width); + + @override + Size computeDryLayout(BoxConstraints constraints) => constraints.constrain( + Size(constraints.maxWidth, _height(constraints.maxWidth)), + ); + + @override + void performLayout() { + final width = constraints.maxWidth; + _pill.layout(const BoxConstraints(), parentUsesSize: true); + final pill = _pill.size; + final beside = _beside(width, pill.width); + _label.layout( + BoxConstraints(maxWidth: beside ?? width), + parentUsesSize: true, + ); + final line = _label.getMinIntrinsicHeight(double.infinity); + (_label.parentData! as _LabelRowSlot).offset = Offset.zero; + (_pill.parentData! as _LabelRowSlot).offset = Offset( + width - pill.width, + beside != null + // Centred on the label's first line. + ? math.max(0, (line - pill.height) / 2) + : _label.size.height + _under, + ); + size = constraints.constrain( + Size( + width, + beside != null + ? math.max(_label.size.height, pill.height) + : _label.size.height + _under + pill.height, + ), + ); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => + defaultHitTestChildren(result, position: position); + + @override + void paint(PaintingContext context, Offset offset) => + defaultPaint(context, offset); +} + /// Faint beacon mark and a message, as the web's empty state. class AtlasEmpty extends StatelessWidget { const AtlasEmpty({super.key, required this.title, required this.subtitle}); diff --git a/lib/features/atlas/telemetry_sample.dart b/lib/features/atlas/telemetry_sample.dart index 86ccd69..b5bf0e4 100644 --- a/lib/features/atlas/telemetry_sample.dart +++ b/lib/features/atlas/telemetry_sample.dart @@ -33,6 +33,17 @@ const dotsBelow = 8; bool useDots(List values) => values.whereType().length < dotsBelow; +/// The reading field behind each sensor tile. Gas reads `iaq` instead on a +/// channel that reports it. +const sensorTileFields = { + 'humidity': 'humidityPct', + 'pressure': 'pressureHpa', + 'gas': 'gasOhms', + 'power': 'powerW', + 'current': 'currentA', + 'sensorVoltage': 'voltageV', +}; + class TelemetrySample { const TelemetrySample({ required this.values, @@ -44,11 +55,14 @@ class TelemetrySample { required this.rebooted, required this.readings, required this.latestAt, + this.gasIsIaq = false, + this.gasIaqAccuracy, }); /// Per tile id: one value per reading that carried it, oldest first. Battery /// is volts, airtime a percent of time, packets and errors per hour, signal - /// the SNR. + /// the SNR. A sensor tile holds the lowest channel that carries it; gas is + /// kΩ, or the air quality index when [gasIsIaq]. final Map> values; /// Per tile id: when each of [values] was read, epoch ms. @@ -70,8 +84,14 @@ class TelemetrySample { /// Newest reading in the window, epoch ms. final int? latestAt; + /// The gas tile's channel reports an air quality index, not a resistance. + final bool gasIsIaq; + + /// 0 to 3 beside the newest index on the gas tile's channel; 3 is calibrated. + final int? gasIaqAccuracy; + double? latest(String tile) => values[tile]!.lastOrNull; - bool get hasTemperature => values['temperature']!.isNotEmpty; + bool has(String tile) => values[tile]!.isNotEmpty; } /// Reads [telemetry] (the node readings route) into the window of [range] @@ -96,6 +116,20 @@ TelemetrySample summarizeTelemetry(Json? telemetry, AtlasRange range, int now) { // The same goes for transmit and receive together. double? share(double? v) => v == null || v > 100 ? null : v; double? txShare, rxShare, sent, rssi; + // Each sensor tile follows one channel, picked once over the whole window. + int? lowest(List channels) => channels.firstOrNull; + final gasChannel = lowest( + ({ + ...sensorChannels(points, 'gasOhms'), + ...sensorChannels(points, 'iaq'), + }).toList()..sort(), + ); + final gasIsIaq = + gasChannel != null && sensorChannels(points, 'iaq').contains(gasChannel); + final sensorChannel = { + for (final MapEntry(key: tile, value: field) in sensorTileFields.entries) + tile: tile == 'gas' ? gasChannel : lowest(sensorChannels(points, field)), + }; for (final p in points) { void put(String id, double? value) { if (value == null) return; @@ -122,6 +156,20 @@ TelemetrySample summarizeTelemetry(Json? telemetry, AtlasRange range, int now) { if (received != null) sent = rate(p, 'packetsSent', 3600); put('errors', rate(p, 'receiveErrors', 3600)); if (finite(p['lastSnrDb']) != null) rssi = finite(p['lastRssiDb']); + for (final s in rows(p['sensors'])) { + final channel = finite(s['channel'])?.toInt(); + for (final MapEntry(key: tile, value: field) + in sensorTileFields.entries) { + if (channel == null || channel != sensorChannel[tile]) continue; + if (tile != 'gas') { + put(tile, finite(s[field])); + } else if (gasIsIaq) { + put(tile, finite(s['iaq'])); + } else if (finite(s['gasOhms']) case final ohms?) { + put(tile, ohms / 1000); + } + } + } } final uptime = values['uptime']!; return TelemetrySample( @@ -137,5 +185,7 @@ TelemetrySample summarizeTelemetry(Json? telemetry, AtlasRange range, int now) { ].isNotEmpty, readings: points.length, latestAt: points.isEmpty ? null : finite(points.last['t'])?.toInt(), + gasIsIaq: gasIsIaq, + gasIaqAccuracy: gasIsIaq ? newestIaqAccuracy(points, gasChannel) : null, ); } diff --git a/lib/features/directory/directory_screen.dart b/lib/features/directory/directory_screen.dart index 2f20a71..fc8eb84 100644 --- a/lib/features/directory/directory_screen.dart +++ b/lib/features/directory/directory_screen.dart @@ -206,6 +206,8 @@ class _DirectoryScreenState extends State 'iatas', 'isObserver', 'isPoller', + 'isForeignPoller', + 'isLocalPoller', ]) { if (data.containsKey(key)) { if (data[key] == null && @@ -1317,10 +1319,7 @@ class _DirectoryScreenState extends State ), if (r['isObserver'] == true || r['isPoller'] == true) observerChip(iconOnly: true), - if (isForeignPoller(r)) - foreignPollerChip(iconOnly: true) - else if (r['isPoller'] == true) - pollerChip(iconOnly: true), + ?pollerChipFor(r, iconOnly: true), ], ), ), diff --git a/lib/features/directory/entity_detail_screen.dart b/lib/features/directory/entity_detail_screen.dart index 66c9cd9..242ed50 100644 --- a/lib/features/directory/entity_detail_screen.dart +++ b/lib/features/directory/entity_detail_screen.dart @@ -980,10 +980,7 @@ class _EntityDetailScreenState extends State d['isObserver'] == true || linkedObserverId != null) observerChip(), - if (isForeignPoller(d)) - foreignPollerChip() - else if (d['isPoller'] == true) - pollerChip(), + ?pollerChipFor(d), if (textOf(d['defaultScope']).isNotEmpty) NodeChip( key: const ValueKey('chip-scope'), diff --git a/lib/features/directory/foreign_source.dart b/lib/features/directory/foreign_source.dart index e0f727a..50a4fd0 100644 --- a/lib/features/directory/foreign_source.dart +++ b/lib/features/directory/foreign_source.dart @@ -29,22 +29,79 @@ NodeChip foreignChip({String? label, Key? key}) => NodeChip( explanation: trKey('foreignObservers.explain'), ); +/// The Local tag, for an observer in local mode; [explanation] shows on tap. +NodeChip localChip({String? explanation, Key? key}) => NodeChip( + key: key ?? const ValueKey('chip-local'), + color: foreignColor, + outline: true, + label: trKey('localPoller.tag').toUpperCase(), + explanation: explanation ?? trKey('localPoller.explain'), +); + +/// A poller in local mode, following no server; older servers send no `isLocalPoller`. +bool isLocalPoller(Json node) => + node['isPoller'] == true && node['isLocalPoller'] == true; + +/// The Poller chip for [node]: foreign, local or plain; null when it does not poll. +NodeChip? pollerChipFor(Json node, {bool iconOnly = false}) => + node['isPoller'] != true + ? null + : isForeignPoller(node) + ? foreignPollerChip(iconOnly: iconOnly) + : isLocalPoller(node) + ? localPollerChip(iconOnly: iconOnly) + : pollerChip(iconOnly: iconOnly); + /// A poller following another server; older servers send no `isForeignPoller`. bool isForeignPoller(Json node) => node['isPoller'] == true && node['isForeignPoller'] == true; -/// The telemetry section's tag for [foreign], or null for none. -NodeChip? telemetryForeignTag(String foreign) => switch (foreign) { - 'all' => foreignChip( - key: const ValueKey('telemetry-foreign-all'), - label: trKey('foreignObservers.telemetryAll'), - ), - 'some' => foreignChip( - key: const ValueKey('telemetry-foreign-some'), - label: trKey('foreignObservers.telemetrySome'), - ), - _ => null, -}; +/// Every foreign observer of a polling answer runs in local mode; false for none. +bool allLocalReporters(Json polling) { + final foreign = foreignReporters(polling); + return foreign.isNotEmpty && foreign.every((f) => f['local'] == true); +} + +NodeChip _localSourceTag(String key, String which, bool bare) => NodeChip( + key: ValueKey(key), + color: foreignColor, + outline: true, + label: trKey('localPoller.$which').toUpperCase(), + explanation: bare ? null : telemetrySourceExplanation(true), +); + +/// What a source tag means; a row that shows the tag bare says it in its own tip. +String telemetrySourceExplanation(bool local) => + trKey(local ? 'localPoller.sourceExplain' : 'foreignObservers.explain'); + +/// The telemetry section's tag for [foreign], or null for none; [local] words +/// it for readings that all come from local mode observers. [bare] drops the +/// tap explanation, for a row whose own tip carries it. +NodeChip? telemetryForeignTag( + String foreign, { + bool local = false, + bool bare = false, +}) { + if (foreign != 'all' && foreign != 'some') return null; + if (local) { + return _localSourceTag( + 'telemetry-local-$foreign', + foreign == 'all' ? 'sourceAll' : 'sourceSome', + bare, + ); + } + return NodeChip( + key: ValueKey('telemetry-foreign-$foreign'), + color: foreignColor, + outline: true, + label: trKey( + foreign == 'all' + ? 'foreignObservers.telemetryAll' + : 'foreignObservers.telemetrySome', + ).toUpperCase(), + explanation: bare ? null : telemetrySourceExplanation(false), + ); +} /// A claim whose signature checked out. It says who sent it, not that it is trusted. NodeChip signedChip(Color green) => NodeChip( diff --git a/lib/features/directory/node_chips.dart b/lib/features/directory/node_chips.dart index 861f552..021ff7c 100644 --- a/lib/features/directory/node_chips.dart +++ b/lib/features/directory/node_chips.dart @@ -201,6 +201,18 @@ NodeChip foreignPollerChip({bool iconOnly = false}) => NodeChip( explanation: iconOnly ? null : trKey('foreignObservers.explain'), ); +/// A poller in local mode: the Foreign poller chip's look under its own name. +NodeChip localPollerChip({bool iconOnly = false}) => NodeChip( + key: const ValueKey('chip-local-poller'), + color: pollerColor, + glyph: 'poller', + outline: true, + dashed: true, + label: iconOnly ? null : trKey('localPoller.label').toUpperCase(), + tooltip: trKey('localPoller.label'), + explanation: iconOnly ? null : trKey('localPoller.explain'), +); + NodeChip observerChip({bool iconOnly = false}) => NodeChip( key: const ValueKey('chip-observer'), color: observerColor, diff --git a/lib/features/directory/node_poller.dart b/lib/features/directory/node_poller.dart index 9207392..5a8d1cb 100644 --- a/lib/features/directory/node_poller.dart +++ b/lib/features/directory/node_poller.dart @@ -111,6 +111,10 @@ class _SeatPainter extends CustomPainter { old.kind != kind || old.border != border; } +/// A `/poller` answer with repeaters but no claim: an observer in local mode. +bool isLocalPollerAnswer(Json data) => + data['claim'] is! Map && rows(data['targets']).isNotEmpty; + /// The Poller view of a node: its slots and the repeaters it polls. class NodePollerSection extends StatelessWidget { const NodePollerSection({super.key, required this.data, this.onOpenNode}); @@ -124,6 +128,7 @@ class NodePollerSection extends StatelessWidget { final colors = BeaconColors.of(context); final claim = data['claim'] is Map ? object(data['claim']) : null; final foreignReadings = (number(data['foreignReadings24h']) ?? 0).round(); + if (isLocalPollerAnswer(data)) return _local(colors, foreignReadings); if (claim == null) { // No claim but foreign readings: an observer that only sends readings. if (foreignReadings > 0) { @@ -172,6 +177,68 @@ class NodePollerSection extends StatelessWidget { ); } + /// Local mode: the repeaters it sent readings for, with no claim to show. + Widget _local(BeaconColors colors, int foreignReadings) { + final targets = rows(data['targets']); + final readings = (number(data['readings24h']) ?? foreignReadings).round(); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + section(trKey('nodePoller.readings24h'), [ + // Same row as a claim's slot count: number, unit, tag at the right. + Row( + children: [ + Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + formatCount(readings.toDouble()), + key: const ValueKey('poller-local-readings'), + style: TextStyle( + fontFamily: _mono, + fontSize: 20, + fontWeight: FontWeight.w600, + color: colors.bright, + ), + ), + const SizedBox(width: 8), + Flexible( + child: Text( + trKey('localPoller.readingsUnit'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: _mono, + fontSize: 12, + color: colors.muted, + ), + ), + ), + ], + ), + ), + const SizedBox(width: 6), + localChip(), + ], + ), + const SizedBox(height: 6), + KeyedSubtree( + key: const ValueKey('poller-local-note'), + child: _note(trKey('localPoller.note'), colors), + ), + ]), + section(trKey('nodePoller.targets'), [ + for (final (i, t) in targets.indexed) ...[ + if (i > 0) const SizedBox(height: 8), + _card(t, colors, true, local: true), + ], + ]), + ], + ); + } + Widget _note(String text, BeaconColors colors) => Text(text, style: TextStyle(fontSize: 12, color: colors.muted)); @@ -437,11 +504,24 @@ class NodePollerSection extends StatelessWidget { } // A foreign claim's targets are all unassigned here, so the role tag is left off. - Widget _card(Json t, BeaconColors colors, bool foreign) => LayoutBuilder( - builder: (context, box) => _cardBody(t, colors, box.maxWidth, foreign), + // [local] also drops what only a claim tells: origin, last reply, SNR, evidence. + Widget _card( + Json t, + BeaconColors colors, + bool foreign, { + bool local = false, + }) => LayoutBuilder( + builder: (context, box) => + _cardBody(t, colors, box.maxWidth, foreign, local), ); - Widget _cardBody(Json t, BeaconColors colors, double width, bool foreign) { + Widget _cardBody( + Json t, + BeaconColors colors, + double width, + bool foreign, + bool local, + ) { final name = textOf(t['name']); final nodeId = textOf(t['nodeId']); final open = onOpenNode; @@ -542,17 +622,20 @@ class NodePollerSection extends StatelessWidget { spacing: 4, runSpacing: 4, children: [ - requested - ? _tag( - trKey('nodePoller.originRequested'), - colors.primary, - fill: colors.primary.withValues(alpha: .1), - ) - : _tag( - trKey('nodePoller.originOwn'), - colors.normal, - fill: colors.muted.withValues(alpha: .12), - ), + if (local) + ...const [] + else if (requested) + _tag( + trKey('nodePoller.originRequested'), + colors.primary, + fill: colors.primary.withValues(alpha: .1), + ) + else + _tag( + trKey('nodePoller.originOwn'), + colors.normal, + fill: colors.muted.withValues(alpha: .12), + ), if (!foreign) switch (role) { 'poller' => _tag( @@ -579,7 +662,7 @@ class NodePollerSection extends StatelessWidget { ), ], ), - if (state != null) ...[ + if (state != null && !local) ...[ const SizedBox(height: 5), Row( children: [ @@ -611,10 +694,12 @@ class NodePollerSection extends StatelessWidget { Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - ago(trKey('nodePoller.lastReply'), t['lastOk']), - const SizedBox(width: 8), - stat(trKey('nodePoller.snr'), _snr(t['claimedSnr']), signal), - const SizedBox(width: 8), + if (!local) ...[ + ago(trKey('nodePoller.lastReply'), t['lastOk']), + const SizedBox(width: 8), + stat(trKey('nodePoller.snr'), _snr(t['claimedSnr']), signal), + const SizedBox(width: 8), + ], // Uncoloured: the SNR beside it is the claim's, not this reading's. stat( trKey('pollerReading.rssi'), @@ -625,22 +710,23 @@ class NodePollerSection extends StatelessWidget { ago(trKey('nodePoller.reading'), t['latestReadingAt']), ], ), - const SizedBox(height: 7), - Text( - evidence > 0 - ? _fill('nodePoller.evidence', { - 'count': evidence, - 'snr': _snr(t['evidenceSnr']), - }) - : trKey('nodePoller.noEvidence'), - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontFamily: _mono, - fontSize: 11, - color: evidence > 0 ? colors.muted : colors.dim, + if (!local) const SizedBox(height: 7), + if (!local) + Text( + evidence > 0 + ? _fill('nodePoller.evidence', { + 'count': evidence, + 'snr': _snr(t['evidenceSnr']), + }) + : trKey('nodePoller.noEvidence'), + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: _mono, + fontSize: 11, + color: evidence > 0 ? colors.muted : colors.dim, + ), ), - ), ], ), ), diff --git a/lib/features/directory/node_telemetry.dart b/lib/features/directory/node_telemetry.dart index 2e1aaf0..da99f97 100644 --- a/lib/features/directory/node_telemetry.dart +++ b/lib/features/directory/node_telemetry.dart @@ -11,6 +11,7 @@ import '../analytics/transforms.dart'; import '../atlas/atlas.dart' show hourMs; import 'directory_widgets.dart'; import 'foreign_source.dart'; +import 'node_chips.dart'; import 'telemetry_request.dart'; const _ranges = {'24h': '24h', '7d': '168h', '30d': '720h'}; @@ -44,13 +45,159 @@ String? readingsLine(List points, String unit) { } /// Whether any point carries a value a chart in this section draws. -bool hasChartData(List points) => const [ - 'batteryMv', - 'temperatureC', - 'noiseFloorDb', - 'airtimeTxSecs', - 'airtimeRxSecs', -].any((k) => points.any((p) => number(p[k]) != null)); +bool hasChartData(List points) => + const [ + 'batteryMv', + 'temperatureC', + 'noiseFloorDb', + 'airtimeTxSecs', + 'airtimeRxSecs', + ].any((k) => points.any((p) => number(p[k]) != null)) || + [ + 'temperatureC', + for (final m in sensorMetrics) m.key, + ].any((k) => sensorChannels(points, k).isNotEmpty); + +/// A sensor measurement the section charts, one line per channel. +typedef SensorMetric = ({String key, String title, String unit, double scale}); + +/// Sensor temperature is not here: it joins the temperature chart. +const List sensorMetrics = [ + (key: 'humidityPct', title: 'humidity', unit: '%', scale: 1), + (key: 'pressureHpa', title: 'pressure', unit: ' hPa', scale: 1), + (key: 'gasOhms', title: 'gas', unit: ' kΩ', scale: .001), + (key: 'iaq', title: 'airQuality', unit: '', scale: 1), + (key: 'voltageV', title: 'sensorVoltage', unit: ' V', scale: 1), + (key: 'currentA', title: 'current', unit: ' A', scale: 1), + (key: 'powerW', title: 'power', unit: ' W', scale: 1), + (key: 'distanceM', title: 'distance', unit: ' m', scale: 1), + (key: 'percent', title: 'moisture', unit: '%', scale: 1), + (key: 'luminosityLux', title: 'light', unit: ' lux', scale: 1), +]; + +int? _channel(Json sensor) => number(sensor['channel'])?.toInt(); + +/// The channels that carry [key] in some point, lowest first. +List sensorChannels(List points, String key) => { + for (final p in points) + for (final s in rows(p['sensors'])) + if (number(s[key]) != null) ?_channel(s), +}.toList()..sort(); + +/// [points] as one sensor channel reported them, for [telemetrySeries]: every +/// point keeps its time, so a reading without the channel breaks the line. +List sensorPoints(List points, int channel) => [ + for (final p in points) + { + for (final s in rows(p['sensors'])) + if (_channel(s) == channel) ...s, + 't': p['t'], + }, +]; + +String channelLabel(int channel) => + trKey('sensors.channel').replaceAll('{{n}}', '$channel'); + +/// "Calibrating (1/3)" for a gas sensor still learning, "Calibrated (3/3)" +/// at 3, null for anything that is not an accuracy. +String? iaqStatus(Object? accuracy) => switch (accuracy) { + final int n when n == 3 => trKey('sensors.calibrated'), + final int n when n >= 0 && n < 3 => trKey( + 'sensors.calibrating', + ).replaceAll('{{n}}', '$n'), + _ => null, +}; + +/// The accuracy beside [channel]'s newest air quality index, or null when +/// that reading has none that makes sense. +int? newestIaqAccuracy(List points, int channel) { + num? newest; + Object? accuracy; + for (final p in points) { + final t = number(p['t']) ?? 0; + if (newest != null && t < newest) continue; + for (final s in rows(p['sensors'])) { + if (_channel(s) != channel || number(s['iaq']) == null) continue; + newest = t; + accuracy = s['iaqAccuracy']; + } + } + // JSON may write a whole number as 3.0. + return accuracy is num && + accuracy == accuracy.roundToDouble() && + accuracy >= 0 && + accuracy <= 3 + ? accuracy.toInt() + : null; +} + +/// Amber while the sensor learns, green once it is calibrated. +Color iaqColor(int accuracy, BeaconColors colors) => + accuracy == 3 ? colors.success : colors.warning; + +/// The calibration chip; a tap says what the number means. Null for no accuracy. +NodeChip? iaqChip(int? accuracy, BeaconColors colors) { + final status = iaqStatus(accuracy); + return status == null + ? null + : NodeChip( + key: const ValueKey('chip-iaq'), + color: iaqColor(accuracy!, colors), + label: status.toUpperCase(), + tooltip: status, + explanation: trKey('sensors.accuracyHelp'), + ); +} + +/// The accuracy the air quality chart's header shows: that of a lone channel. +int? airQualityAccuracy(List points) { + final channels = sensorChannels(points, 'iaq'); + return channels.length == 1 + ? newestIaqAccuracy(points, channels.single) + : null; +} + +/// The air quality lines. Several channels each say their own calibration. +Map> airQualitySeries( + List points, + int bucketMs, +) { + final channels = sensorChannels(points, 'iaq'); + String label(int channel) { + final status = channels.length > 1 + ? iaqStatus(newestIaqAccuracy(points, channel)) + : null; + final name = channelLabel(channel); + return status == null ? name : '$name · $status'; + } + + return { + for (final channel in channels) + label(channel): telemetrySeries( + sensorPoints(points, channel), + 'iaq', + bucketMs, + ), + }; +} + +/// One series per channel that carries [key], named by channel. +Map> sensorSeries( + List points, + String key, + int bucketMs, { + double scale = 1, + double Function(double)? convert, +}) => { + for (final channel in sensorChannels(points, key)) + channelLabel(channel): telemetrySeries( + sensorPoints(points, channel), + key, + bucketMs, + scale: scale, + convert: convert, + ), +}; /// One chart series. A bucket the server left out, or one without this field, is a /// null point, so the line breaks instead of bridging the gap. @@ -234,7 +381,10 @@ class _NodeTelemetrySectionState extends State { final poller = object(polling['poller']); final standbys = rows(polling['standbys']); final foreign = foreignReporters(polling); - final foreignTag = telemetryForeignTag(telemetryForeign(telemetry)); + final foreignTag = telemetryForeignTag( + telemetryForeign(telemetry), + local: allLocalReporters(polling), + ); if (!failed && points.isEmpty && poller.isEmpty && @@ -249,9 +399,11 @@ class _NodeTelemetrySectionState extends State { Widget chart( String title, Map> series, - String unit, - ) => AnalyticsCard( + String unit, { + Widget? trailing, + }) => AnalyticsCard( title: title, + trailing: trailing, child: TimeChart( unit: unit, showSingleSeriesToggle: false, @@ -260,6 +412,12 @@ class _NodeTelemetrySectionState extends State { ), ); final name = textOf(poller['name'], tr('Unknown')); + final sensorTemperature = sensorSeries( + points, + 'temperatureC', + bucketMs, + convert: (c) => toDisplayTemp(c, tempUnit), + ); return FoldSection( id: 'node-telemetry', title: trKey('nodeTelemetry.title'), @@ -335,17 +493,19 @@ class _NodeTelemetrySectionState extends State { scale: .001, ), }, ' V'), - if (has('temperatureC')) + if (has('temperatureC') || sensorTemperature.isNotEmpty) chart( trKey('nodeTelemetry.temperature') .replaceAll('{{unit}}', tempSymbol(tempUnit)), { - trKey('nodeTelemetry.temperatureSeries'): telemetrySeries( - points, - 'temperatureC', - bucketMs, - convert: (c) => toDisplayTemp(c, tempUnit), - ), + if (has('temperatureC')) + trKey('nodeTelemetry.temperatureSeries'): telemetrySeries( + points, + 'temperatureC', + bucketMs, + convert: (c) => toDisplayTemp(c, tempUnit), + ), + ...sensorTemperature, }, ' ${tempSymbol(tempUnit)}', ), @@ -362,6 +522,19 @@ class _NodeTelemetrySectionState extends State { 'RX': airtimeSeries(points, 'airtimeRxSecs', bucketMs), 'TX': airtimeSeries(points, 'airtimeTxSecs', bucketMs), }, '%'), + for (final m in sensorMetrics) + if ((m.key == 'iaq' + ? airQualitySeries(points, bucketMs) + : sensorSeries(points, m.key, bucketMs, scale: m.scale)) + case final lines when lines.isNotEmpty) + chart( + trKey('sensors.${m.title}'), + lines, + m.unit, + trailing: m.key == 'iaq' + ? iaqChip(airQualityAccuracy(points), colors) + : null, + ), if (poller.isNotEmpty || polling['latestReadingAt'] != null) InkWell( key: const ValueKey('poll-line'), @@ -415,18 +588,28 @@ class _NodeTelemetrySectionState extends State { label: trKey('foreignObservers.alsoChecked'), ), ), - if (foreign.isNotEmpty) ..._alsoReported(foreign, colors), + if (foreign.isNotEmpty) + ..._alsoReported(foreign, colors, also: poller.isNotEmpty), _request(), ], ); } /// Foreign observers that check this node; never its poller or a standby. - List _alsoReported(List foreign, BeaconColors colors) => [ + /// [also] is false when no poller of this server checks it. + List _alsoReported( + List foreign, + BeaconColors colors, { + bool also = true, + }) => [ Padding( padding: const EdgeInsets.only(top: 10, bottom: 2), child: Text( - trKey('foreignObservers.alsoReportedBy'), + trKey( + also + ? 'foreignObservers.alsoReportedBy' + : 'foreignObservers.reportedBy', + ), style: const TextStyle(fontWeight: FontWeight.w700), ), ), @@ -455,8 +638,13 @@ class _NodeTelemetrySectionState extends State { style: TextStyle(fontSize: 13, color: colors.primary), ), if ([ + // Older servers send no `local`. if (f['claimed'] == false) - trKey('foreignObservers.readingsOnly'), + trKey( + f['local'] == false + ? 'foreignObservers.claimStale' + : 'foreignObservers.readingsOnly', + ), textOf(f['pollHost']), if (f['latestReadingAt'] != null) age(f['latestReadingAt']), @@ -477,7 +665,14 @@ class _NodeTelemetrySectionState extends State { signedChip(colors.success), const SizedBox(width: 4), ], - foreignChip(key: ValueKey('foreign-tag-${f['observerId']}')), + // No claim at all: an observer in local mode. + if (f['local'] == true) + localChip( + key: ValueKey('local-tag-${f['observerId']}'), + explanation: trKey('localPoller.sourceExplain'), + ) + else + foreignChip(key: ValueKey('foreign-tag-${f['observerId']}')), ], ), ), diff --git a/pubspec.yaml b/pubspec.yaml index 84d8f1c..3a8f30f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "Native iOS and Android client for Beacon, the real-time MeshCore p # An app, not a package: never publish to pub.dev. publish_to: 'none' -version: 2.3.1+2 +version: 2.3.4+2 environment: sdk: ^3.13.4 diff --git a/store/apple/en-CA/whats_new.txt b/store/apple/en-CA/whats_new.txt index b48f17b..115901c 100644 --- a/store/apple/en-CA/whats_new.txt +++ b/store/apple/en-CA/whats_new.txt @@ -1,6 +1,5 @@ -New in 2.3.0 -- Repeater telemetry (beta): battery, temperature, airtime and counters on repeater pages, Atlas cards and the map. -- Poller view: see which repeaters a poller polls and how many slots it has free. -- Accounts: sign in and your Atlas follows you between the app and the web. -- Alerts by push or email: battery, offline, reboots and more. -- Atlas: new tabs, tags, a 7 day range and an edit mode. +New in 2.3.4 +- Sensors: repeaters with extra sensors show humidity, pressure, air quality, voltage, current and power, as charts on the node and as new Atlas tiles. +- Alerts work on any repeater that sends telemetry, plus a new Telemetry stopped alert. Gone quiet offers 3 and 6 hours on every radio. +- Atlas fills wide screens, and each Telemetry card says when its last reading was. +- Local pollers are tagged. diff --git a/test/atlas/atlas_screen_test.dart b/test/atlas/atlas_screen_test.dart index bb5307c..36e8275 100644 --- a/test/atlas/atlas_screen_test.dart +++ b/test/atlas/atlas_screen_test.dart @@ -81,6 +81,7 @@ class Server { Completer? holdObserver; bool activity404 = false; bool polling = true, atlasTelemetry = false, atlas7d = false; + bool sensors = false; int? atlasLimit; String temperatureUnit = 'c'; @@ -143,6 +144,7 @@ class Server { 'polling': polling, 'atlasTelemetry': atlasTelemetry, 'atlas7d': atlas7d, + 'sensors': sensors, }, 'display': {'temperatureUnit': temperatureUnit}, if (atlasLimit != null) 'limits': {'atlas': atlasLimit}, @@ -318,7 +320,10 @@ Future search(WidgetTester tester, String text) async { /// Whether the footer dot beside [text] is lit; fails when there is no dot. bool footerFresh(WidgetTester tester, String text) { final row = find - .ancestor(of: find.text(text), matching: find.byType(Row)) + .ancestor( + of: find.text(text), + matching: find.byType(CustomMultiChildLayout), + ) .first; final dot = find.descendant( of: row, @@ -539,9 +544,53 @@ void main() { // Readings exist but no counter pair: the counter tile says so. expect(find.text('No readings in this window'), findsNWidgets(2)); expect(find.text('Needs two status readings'), findsOneWidget); - expect(find.text('Polled · 12m ago'), findsOneWidget); + expect(find.text('Polled'), findsOneWidget); + expect(find.text('12m ago'), findsOneWidget); expect(find.text('by Roof'), findsOneWidget); - expect(footerFresh(tester, 'Polled · 12m ago'), isTrue); + expect(footerFresh(tester, 'Polled'), isTrue); + await close(tester); + }); + + testWidgets('readings from local mode observers only say Local', ( + tester, + ) async { + fake.telemetryForeign = 'some'; + fake.pollingDoc = { + ...fake.pollingDoc!, + 'foreign': [ + { + 'observerId': 'obs-local', + 'name': 'Shed', + 'claimed': false, + 'local': true, + }, + ], + }; + await pump(tester, pins: [nodePin()]); + await tester.tap(tab('telemetry')); + await tester.pumpAndSettle(); + expect(find.text('INCLUDES LOCAL READINGS'), findsOneWidget); + expect(find.text('INCLUDES FOREIGN READINGS'), findsNothing); + await close(tester); + + fake.telemetryForeign = 'all'; + fake.pollingDoc = { + ...fake.pollingDoc!, + 'foreign': [ + { + 'observerId': 'obs-local', + 'name': 'Shed', + 'claimed': false, + 'local': true, + }, + {'observerId': 'obs-lake', 'name': 'Lake', 'claimed': true}, + ], + }; + await pump(tester, pins: [nodePin()]); + await tester.tap(tab('telemetry')); + await tester.pumpAndSettle(); + expect(find.text('FOREIGN SOURCE'), findsOneWidget); + expect(find.text('LOCAL SOURCE'), findsNothing); await close(tester); }); @@ -552,15 +601,15 @@ void main() { await pump(tester, pins: [nodePin()]); await tester.tap(tab('telemetry')); await tester.pumpAndSettle(); - expect(find.text('Includes foreign readings'), findsOneWidget); + expect(find.text('INCLUDES FOREIGN READINGS'), findsOneWidget); await close(tester); fake.telemetryForeign = null; await pump(tester, pins: [nodePin()]); await tester.tap(tab('telemetry')); await tester.pumpAndSettle(); - expect(find.text('Includes foreign readings'), findsNothing); - expect(find.text('Foreign source'), findsNothing); + expect(find.text('INCLUDES FOREIGN READINGS'), findsNothing); + expect(find.text('FOREIGN SOURCE'), findsNothing); await close(tester); }); @@ -577,9 +626,10 @@ void main() { await pump(tester, pins: [nodePin()], size: Size(width, 844)); await tester.tap(tab('telemetry')); await tester.pumpAndSettle(); - final left = find.text('Polled · 49m ago'); + final left = find.text('49m ago'); final right = find.text('by MrAlders0n_G3_R1'); expect(left, findsOneWidget); + expect(find.text('Polled'), findsOneWidget); expect(right, findsOneWidget); expect( tester.renderObject(left).didExceedMaxLines, @@ -595,20 +645,336 @@ void main() { ); } - testWidgets('says when nobody is polling', (tester) async { - fake.pollingDoc = { + group('the footer', () { + const noPoller = { 'polled': true, - 'latestReadingAt': tick - 3 * 86400000, 'poller': null, 'standbys': [], }; - await pump(tester, pins: [nodePin()]); - await tester.tap(tab('telemetry')); - await tester.pumpAndSettle(); - expect(find.text('Not polled'), findsOneWidget); - expect(find.textContaining('by '), findsNothing); - expect(footerFresh(tester, 'Not polled'), isFalse); - await close(tester); + final localOnly = [ + { + 'observerId': 'obs-local', + 'name': 'Shed', + 'claimed': false, + 'local': true, + }, + ]; + Finder footerOf(Finder child) => find + .ancestor(of: child, matching: find.byType(CustomMultiChildLayout)) + .first; + Finder inFooter(Finder footer, Finder what) => + find.descendant(of: footer, matching: what); + // Every text the row shows, in the order it is read. + List rowTexts(WidgetTester tester, Finder footer) { + final texts = [ + for (final e in inFooter(footer, find.byType(Text)).evaluate()) + if ((e.widget as Text).data case final String data + when data.isNotEmpty && + data != 'i' && + tester.getSize(find.byWidget(e.widget)).width > 0) + (tester.getTopLeft(find.byWidget(e.widget)).dx, data), + ]..sort((a, b) => a.$1.compareTo(b.$1)); + return [for (final (_, text) in texts) text]; + } + + String tipOf(WidgetTester tester, Finder footer) { + final tips = inFooter(footer, find.byType(AtlasInfoTip)); + // One info marker for the row, and the tag does not open a note of its own. + expect(tips, findsOneWidget); + expect( + tester + .widgetList(inFooter(footer, find.byType(Tooltip))) + .where((t) => t.triggerMode == TooltipTriggerMode.tap), + hasLength(1), + ); + return tester.widget(tips).lines.join('\n'); + } + + final dot = find.byKey(const ValueKey('atlas-footer-dot')); + Future open(WidgetTester tester, {Size? size}) async { + // The test font is too wide for the row to show everything. + await realFont(tester); + await pump( + tester, + pins: [nodePin()], + size: size ?? const Size(390, 844), + ); + await tester.tap(tab('telemetry')); + await tester.pumpAndSettle(); + return footerOf(find.byType(AtlasInfoTip)); + } + + testWidgets('a poller: lit dot, Polled and the age, the tag, by whom', ( + tester, + ) async { + fake.telemetryForeign = 'all'; + final footer = await open(tester); + expect(rowTexts(tester, footer), [ + 'Polled', + ' · ', + '12m ago', + 'FOREIGN SOURCE', + 'by Roof', + ]); + expect(footerFresh(tester, 'Polled'), isTrue); + final tip = tipOf(tester, footer); + expect(tip, contains('Polled by Roof')); + expect(tip, contains("observer this site doesn't manage")); + await close(tester); + }); + + testWidgets('a poller with no reading yet has no age', (tester) async { + fake.readings = []; + fake.pollingDoc = { + 'polled': true, + 'poller': {'observerId': observerId, 'name': 'Roof'}, + 'standbys': [], + }; + final footer = await open(tester); + expect(rowTexts(tester, footer), ['Polled', 'by Roof']); + await close(tester); + }); + + testWidgets('no poller, outside readings: no dot, the last reading and ' + 'the tag in place of Not polled', (tester) async { + fake.telemetryForeign = 'all'; + fake.pollingDoc = {...noPoller, 'latestReadingAt': tick - 720000}; + final footer = await open(tester); + expect(rowTexts(tester, footer), [ + 'Last reading', + ' · ', + '12m ago', + 'FOREIGN SOURCE', + ]); + expect(dot, findsNothing); + // Under the tiles, not above them. + expect( + tester.getTopLeft(find.text('FOREIGN SOURCE')).dy, + greaterThan(tester.getBottomLeft(find.byType(AtlasStatTile).last).dy), + ); + final tip = tipOf(tester, footer); + expect(tip, contains("observer this site doesn't manage")); + expect(tip, isNot(contains('Not being polled'))); + expect(tip, contains('Last reading')); + await close(tester); + }); + + testWidgets('no poller, local mode readings: the local tag and note', ( + tester, + ) async { + fake.telemetryForeign = 'some'; + fake.pollingDoc = { + ...noPoller, + 'latestReadingAt': tick - 720000, + 'foreign': localOnly, + }; + final footer = await open(tester); + expect(rowTexts(tester, footer), [ + 'Last reading', + ' · ', + '12m ago', + 'INCLUDES LOCAL READINGS', + ]); + expect(dot, findsNothing); + final tip = tipOf(tester, footer); + expect(tip, contains('observer in local mode')); + expect(tip, isNot(contains('Not being polled'))); + await close(tester); + }); + + testWidgets('no poller, our own readings: dim dot, the last reading, ' + 'Not polled on the right', (tester) async { + fake.pollingDoc = {...noPoller, 'latestReadingAt': tick - 3 * 86400000}; + final footer = await open(tester); + expect(rowTexts(tester, footer), [ + 'Last reading', + ' · ', + '3d ago', + 'Not polled', + ]); + expect(footerFresh(tester, 'Last reading'), isFalse); + final row = tester.getRect(footer); + final info = tester.getRect( + inFooter(footer, find.byType(AtlasInfoTip)), + ); + expect( + tester.getRect(find.text('Not polled')).right, + moreOrLessEquals(info.left, epsilon: 1), + ); + expect(info.right, moreOrLessEquals(row.right, epsilon: 1)); + final tip = tipOf(tester, footer); + expect(tip, contains('Not being polled right now')); + expect(tip, isNot(contains("observer this site doesn't manage"))); + await close(tester); + }); + + testWidgets('the age comes from the newest point when the polling ' + 'answer has none', (tester) async { + fake.pollingDoc = noPoller; + final footer = await open(tester); + final texts = rowTexts(tester, footer); + expect(texts.first, 'Last reading'); + expect(texts[1], ' · '); + expect(texts.last, 'Not polled'); + await close(tester); + }); + + testWidgets('no poller and no reading ever: dim dot and Not polled', ( + tester, + ) async { + fake.readings = []; + fake.pollingDoc = noPoller; + final footer = await open(tester); + expect(rowTexts(tester, footer), ['Not polled']); + expect(footerFresh(tester, 'Not polled'), isFalse); + await close(tester); + }); + + testWidgets('polling answer missing: no dot, the last reading, the tag ' + 'if any', (tester) async { + fake.telemetryForeign = 'all'; + fake.pollingDoc = null; + var footer = await open(tester); + var texts = rowTexts(tester, footer); + expect(texts.first, 'Last reading'); + expect(texts[1], ' · '); + expect(texts.last, 'FOREIGN SOURCE'); + expect(texts, hasLength(4)); + expect(dot, findsNothing); + await close(tester); + + fake.telemetryForeign = null; + footer = await open(tester); + texts = rowTexts(tester, footer); + expect(texts, hasLength(3)); + expect(texts.first, 'Last reading'); + expect(dot, findsNothing); + await close(tester); + }); + + // Whole: every glyph on its one line, none cut. + void whole(WidgetTester tester, Finder text) { + final box = tester.renderObject(text); + expect(box.didExceedMaxLines, isFalse); + expect( + box.size.width, + greaterThanOrEqualTo(box.getMaxIntrinsicWidth(double.infinity) - .5), + ); + } + + for (final code in ['en', 'fr', 'sv']) { + for (final width in [320.0, 375.0]) { + for (final (name, foreign, local, polled) in [ + ('all', 'all', false, false), + ('some', 'some', false, false), + ('local all', 'all', true, false), + ('local some', 'some', true, false), + ('polled some', 'some', false, true), + ('polled local some', 'some', true, true), + ('polled', null, false, true), + ('not polled', null, false, false), + ]) { + testWidgets('$name fits one line at $width in $code', ( + tester, + ) async { + addTearDown(() => language = 'en'); + language = code; + fake.telemetryForeign = foreign; + fake.pollingDoc = { + 'polled': true, + 'latestReadingAt': tick - 49 * 60000, + 'poller': polled + ? {'observerId': observerId, 'name': 'MrAlders0n_G3_R1'} + : null, + 'standbys': [], + if (local) 'foreign': localOnly, + }; + final footer = await open(tester, size: Size(width, 844)); + expect(tester.takeException(), isNull); + final row = tester.getRect(footer); + final info = tester.getRect( + inFooter(footer, find.byType(AtlasInfoTip)), + ); + final age = inFooter(footer, find.textContaining('49')); + final ageBox = tester.renderObject(age); + // Whole or absent, never ellipsized. + final ageGone = ageBox.size.width == 0; + if (!ageGone) whole(tester, age); + var edge = tester.getRect(age).right; + final label = inFooter( + footer, + find.text( + trKey( + polled + ? 'atlasFooter.polled' + : 'atlasTelemetry.lastReading', + ), + ), + ); + final labelBox = tester.renderObject(label); + final labelCut = + labelBox.size.width < + labelBox.getMaxIntrinsicWidth(double.infinity) - .5; + // The age gives way last: only once its label is gone, and its dot with it. + if (ageGone) { + expect(labelBox.size.width, 0); + expect( + tester.getSize(inFooter(footer, find.text(' · '))).width, + 0, + ); + } + if (foreign != null) { + final chip = inFooter( + footer, + find.byKey( + ValueKey( + local + ? 'telemetry-local-$foreign' + : 'telemetry-foreign-$foreign', + ), + ), + ); + final box = tester.getRect(chip); + // The tag is whole: after the age, clear of the info marker. + expect(box.left, greaterThanOrEqualTo(edge)); + expect(box.right, lessThanOrEqualTo(info.left + .5)); + expect(box.top, greaterThanOrEqualTo(row.top)); + expect(box.bottom, lessThanOrEqualTo(row.bottom)); + whole( + tester, + find.descendant(of: chip, matching: find.byType(Text)), + ); + edge = box.right; + } else { + // Nothing squeezes the row here, so the age is whole. + expect(ageGone, isFalse); + } + final right = polled + ? trKey('atlasFooter.byPoller') + .replaceAll('{{name}}', 'MrAlders0n_G3_R1') + : foreign == null + ? trKey('atlasFooter.notPolled') + : null; + if (right != null) { + final text = inFooter(footer, find.text(right)); + final box = tester.getRect(text); + final cut = tester + .renderObject(text) + .didExceedMaxLines; + // The right side starts after everything else or is not there at all. + if (box.width > 0) { + expect(box.left, greaterThanOrEqualTo(edge)); + } + // A poller's name gives way before the label; Not polled is kept whole. + if (polled && labelCut) expect(box.width, 0); + if (!polled) expect(cut, isFalse); + if (!polled) expect(box.width, greaterThan(0)); + } + await close(tester); + }); + } + } + } }); testWidgets('a pinned card opens on it and follows the range', ( @@ -694,6 +1060,348 @@ void main() { await close(tester); }); + group('sensor tiles', () { + // The server's own example point, an hour old. + void withSensors() => fake.readings = [ + ...fake.readings, + { + 't': tick - 3600000, + 'readings': 2, + 'sensors': [ + { + 'channel': 2, + 'temperatureC': 21.4, + 'humidityPct': 45.5, + 'pressureHpa': 1013.2, + 'iaq': 50, + 'iaqAccuracy': 3, + }, + {'channel': 3, 'voltageV': 8.7, 'currentA': 0.122, 'powerW': 1.061}, + ], + }, + ]; + Future openPicker(WidgetTester tester) async { + await pump( + tester, + pins: [ + nodePin({'view': 'telemetry'}), + ], + ); + await tester.tap(find.text('NOISE FLOOR')); + await tester.pumpAndSettle(); + } + + const names = [ + 'Humidity', + 'Pressure', + // The fixture's gas sensor sends an air quality index, so the tile is named for it. + 'Air quality', + 'Power', + 'Current', + 'Sensor voltage', + ]; + + testWidgets('are offered with data on a server that has them', ( + tester, + ) async { + fake.sensors = true; + withSensors(); + await openPicker(tester); + for (final name in names) { + expect(find.text(name), findsOneWidget, reason: name); + } + await close(tester); + }); + + testWidgets('are offered by their data alone, flag or not', ( + tester, + ) async { + withSensors(); + await openPicker(tester); + for (final name in names) { + expect(find.text(name), findsOneWidget, reason: name); + } + await close(tester); + }); + + testWidgets('are not offered without readings for them', (tester) async { + fake.sensors = true; + await openPicker(tester); + for (final name in names) { + expect(find.text(name), findsNothing, reason: name); + } + expect(find.text('Packets'), findsOneWidget); + await close(tester); + }); + + testWidgets('only the ones with data are offered', (tester) async { + fake.sensors = true; + fake.readings = [ + { + 't': tick - 3600000, + 'sensors': [ + {'channel': 2, 'humidityPct': 45.5}, + ], + }, + ]; + await openPicker(tester); + expect(find.text('Humidity'), findsOneWidget); + expect(find.text('Pressure'), findsNothing); + await close(tester); + }); + + testWidgets('picking one stores it and shows its value', (tester) async { + fake.sensors = true; + withSensors(); + final prefs = await pump( + tester, + pins: [ + nodePin({'view': 'telemetry'}), + ], + ); + await tester.tap(find.text('NOISE FLOOR')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Humidity')); + await tester.pumpAndSettle(); + expect(savedPins(prefs).single['telemetryTiles'], [ + 'battery', + 'humidity', + 'uptime', + 'airtime', + ]); + expect(find.text('HUMIDITY'), findsOneWidget); + expect(find.text('45.5%'), findsOneWidget); + await close(tester); + }); + + for (final (tiles, shown) in [ + ( + ['humidity', 'pressure', 'gas', 'power'], + ['45.5%', '1013.2 hPa', 'IAQ 50', '1.061 W'], + ), + ( + ['current', 'sensorVoltage', 'battery', 'noise'], + ['0.122 A', '8.70 V'], + ), + ]) { + testWidgets('show ${shown.join(', ')}', (tester) async { + fake.sensors = true; + withSensors(); + await pump( + tester, + pins: [ + nodePin({'view': 'telemetry', 'telemetryTiles': tiles}), + ], + ); + for (final value in shown) { + expect(find.text(value), findsOneWidget, reason: value); + } + // A reading is not a counter: no per-hour rate, no pair needed. + expect(find.textContaining('/h'), findsNothing); + expect(find.text('Needs two status readings'), findsNothing); + await close(tester); + }); + } + + testWidgets('gas without an index is kilohms', (tester) async { + fake.sensors = true; + fake.readings = [ + { + 't': tick - 3600000, + 'sensors': [ + {'channel': 2, 'gasOhms': 50000}, + ], + }, + ]; + await pump( + tester, + pins: [ + nodePin({ + 'view': 'telemetry', + 'telemetryTiles': ['gas', 'noise', 'uptime', 'airtime'], + }), + ], + ); + expect(find.text('50.0 kΩ'), findsOneWidget); + await close(tester); + }); + + Future gasTile( + WidgetTester tester, + Map sensor, { + double width = 390, + }) async { + fake.sensors = true; + fake.readings = [ + { + 't': tick - 3600000, + // The neighbouring tile has a value too, so it has no caption. + 'noiseFloorDb': -110, + 'sensors': [ + {'channel': 2, ...sensor}, + ], + }, + ]; + await pump( + tester, + pins: [ + nodePin({ + 'view': 'telemetry', + 'telemetryTiles': ['gas', 'noise', 'uptime', 'airtime'], + }), + ], + size: Size(width, 844), + ); + } + + final tile = find.byKey(const ValueKey('telemetry-gas')); + final chip = find.descendant( + of: tile, + matching: find.byKey(const ValueKey('pill-iaq')), + ); + + testWidgets('an index still calibrating gets an amber chip', ( + tester, + ) async { + await gasTile(tester, {'iaq': 50, 'iaqAccuracy': 1}); + final colors = BeaconColors.of(tester.element(chip)); + expect(tester.widget(chip).text, '1/3'); + expect(tester.widget(chip).color, colors.warning); + expect(find.bySemanticsLabel('Calibrating (1/3)'), findsOneWidget); + // Tiles carry no channel caption. + expect(find.textContaining('Channel'), findsNothing); + await close(tester); + }); + + testWidgets('a calibrated index gets a green chip', (tester) async { + await gasTile(tester, {'iaq': 50, 'iaqAccuracy': 3}); + final colors = BeaconColors.of(tester.element(chip)); + expect(tester.widget(chip).text, '3/3'); + expect(tester.widget(chip).color, colors.success); + await close(tester); + }); + + testWidgets('tapping the chip says what the accuracy means', ( + tester, + ) async { + await gasTile(tester, {'iaq': 50, 'iaqAccuracy': 1}); + final help = trKey('sensors.accuracyHelp'); + expect(find.textContaining(help), findsNothing); + // The pill is small; the corner around it is the tap target. + final target = find.descendant( + of: tile, + matching: find.byKey(const ValueKey('atlas-tile-caption-tap')), + ); + expect(tester.getSize(target).shortestSide, greaterThanOrEqualTo(48)); + expect(tester.getRect(target).contains(tester.getCenter(chip)), isTrue); + await tester.tapAt(tester.getCenter(chip)); + await tester.pumpAndSettle(); + // The status in words first, then what it means. + expect(find.text('Calibrating (1/3)\n\n$help'), findsOneWidget); + await close(tester); + }); + + // Lines the name takes and whether the pill sits beside it, per case. + for (final (code, width, lines, beside) in [ + ('en', 320.0, 2, true), + ('en', 375.0, 1, true), + ('fr', 320.0, 3, true), + ('fr', 375.0, 2, true), + ('sv', 320.0, 1, false), + ('sv', 375.0, 1, true), + ]) { + testWidgets('the pill and a whole-word name share the tile at $width ' + 'in $code', (tester) async { + addTearDown(() => language = 'en'); + await realFont(tester); + language = code; + await gasTile(tester, {'iaq': 50, 'iaqAccuracy': 2}, width: width); + expect(tester.takeException(), isNull); + final box = tester.getRect(tile), pill = tester.getRect(chip); + expect(pill.left, greaterThanOrEqualTo(box.left + 14)); + expect(pill.right, lessThanOrEqualTo(box.right - 14)); + expect(pill.top, greaterThanOrEqualTo(box.top + 12)); + final nameText = find.descendant( + of: tile, + matching: find.text(trKey('sensors.airQuality').toUpperCase()), + ); + final name = tester.renderObject(nameText); + final label = tester.getRect(nameText); + final line = name.getFullHeightForCaret( + const TextPosition(offset: 0), + ); + // Wide enough for its longest word: no break inside one. + expect( + name.size.width, + greaterThanOrEqualTo(name.getMinIntrinsicWidth(double.infinity)), + ); + expect((label.height / line).round(), lines); + // Never taller than the name's line. + expect(pill.height, lessThanOrEqualTo(line)); + if (beside) { + expect(pill.left, greaterThanOrEqualTo(label.right)); + expect( + pill.center.dy, + moreOrLessEquals(label.top + line / 2, epsilon: 1), + ); + } else { + expect(pill.top, greaterThanOrEqualTo(label.bottom)); + expect(pill.right, moreOrLessEquals(box.right - 14, epsilon: 1)); + } + // A one line name leaves the value where its neighbour's is. + Finder value(String id) => find.descendant( + of: find.byKey(ValueKey('telemetry-$id')), + matching: find.byWidgetPredicate( + (w) => w is Text && w.style?.fontSize == 20, + ), + ); + if (lines == 1 && beside) { + expect( + tester.getTopLeft(value('gas')).dy, + tester.getTopLeft(value('noise')).dy, + ); + } + await close(tester); + }); + } + + testWidgets('an index with no accuracy has no chip', (tester) async { + await gasTile(tester, {'iaq': 50}); + expect(find.text('IAQ 50'), findsOneWidget); + expect(chip, findsNothing); + await close(tester); + }); + + testWidgets('raw gas has no chip', (tester) async { + await gasTile(tester, {'gasOhms': 50000, 'iaqAccuracy': 3}); + expect(find.text('50.0 kΩ'), findsOneWidget); + expect(chip, findsNothing); + await close(tester); + }); + + testWidgets('a chosen tile with no data says so', (tester) async { + await pump( + tester, + pins: [ + nodePin({ + 'view': 'telemetry', + 'telemetryTiles': ['humidity', 'battery', 'uptime', 'noise'], + }), + ], + ); + expect(find.text('HUMIDITY'), findsOneWidget); + final tile = find.byKey(const ValueKey('telemetry-humidity')); + expect( + find.descendant( + of: tile, + matching: find.text('No readings in this window'), + ), + findsOneWidget, + ); + await close(tester); + }); + }); + testWidgets('pins the view', (tester) async { final prefs = await pump(tester, pins: [nodePin()]); await edit(tester); @@ -1567,6 +2275,39 @@ void main() { await close(tester); }); + testWidgets('a local poller shows its readings and repeaters, no slots', ( + tester, + ) async { + fake.pollerDoc = { + 'claim': null, + 'readings24h': 48, + 'foreignReadings24h': 48, + 'targets': [ + for (final key in ['aa', 'bb']) + { + 'publicKey': key, + 'nodeId': key, + 'name': key, + 'role': 'unassigned', + 'state': '', + }, + ], + }; + fake.hill = {...fake.hill, 'isLocalPoller': true}; + await open(tester); + expect(find.text('LOCAL POLLER'), findsOneWidget); + expect(inTile('readings', '48'), findsOneWidget); + expect(inTile('repeaters', '2'), findsOneWidget); + // Slots and the claim stay, empty, so the card keeps its height. + expect(tile('slots'), findsOneWidget); + expect(tile('claim'), findsOneWidget); + expect(inTile('slots', '0/0'), findsNothing); + expect(tile('answering'), findsNothing); + expect(find.text('Local mode'), findsOneWidget); + expect(tester.takeException(), isNull); + await close(tester); + }); + testWidgets('is offered to a poller from any view', (tester) async { await open(tester, view: null); expect(find.text('OBSERVATIONS'), findsOneWidget); @@ -1815,7 +2556,7 @@ void main() { of: find .ancestor( of: find.text('Polling 2 repeaters'), - matching: find.byType(Row), + matching: find.byType(CustomMultiChildLayout), ) .first, matching: find.byKey(const ValueKey('atlas-footer-dot')), @@ -1941,6 +2682,9 @@ void main() { ); expect(AtlasGrid.columnsFor(390), 1); expect(AtlasGrid.columnsFor(1300), 3); + expect(AtlasGrid.columnsFor(820), 2); + expect(AtlasGrid.columnsFor(1920), 4); + expect(AtlasGrid.columnsFor(2560), 6); await close(tester); }); diff --git a/test/atlas/atlas_store_test.dart b/test/atlas/atlas_store_test.dart index db5e494..7cdd4b4 100644 --- a/test/atlas/atlas_store_test.dart +++ b/test/atlas/atlas_store_test.dart @@ -47,6 +47,7 @@ class FakeServer { bool infoDown = false; int? staleAfter; bool atlasTelemetry = false, atlas7d = false, atlasPoller = false; + bool sensors = false; Map get doc => { 'revision': revision, @@ -72,6 +73,7 @@ class FakeServer { 'atlasTelemetry': atlasTelemetry, 'atlas7d': atlas7d, 'atlasPoller': atlasPoller, + 'sensors': sensors, }, }); } @@ -109,6 +111,19 @@ class FakeServer { headers: {'content-type': 'application/json'}, ); } + // An older server does not know the sensor tiles. + if (!sensors && + (body['pins'] as List).any( + (p) => hasSensorTile((p['telemetryTiles'] as List?)?.cast()), + )) { + return http.Response( + jsonEncode({ + 'error': {'code': 'validation', 'message': 'bad tile'}, + }), + 422, + headers: {'content-type': 'application/json'}, + ); + } revision++; range = body['range'] as String; pins = [ @@ -254,6 +269,52 @@ void main() { }); }); + group('sensor tiles', () { + const tiles = ['battery', 'humidity', 'pressure', 'airtime']; + AtlasPin sensorPin() => AtlasPin.node( + id: nodeId, + publicKey: key, + name: 'Hill', + telemetryTiles: tiles, + view: AtlasView.telemetry, + ); + + test( + 'a server without them is not sent them and the local copy keeps them', + () async { + final fake = FakeServer()..atlasTelemetry = true; + final r = await rig(marked: true, fake: fake); + final store = r.store; + await store.idle; + store.update((v) => v.appended(sensorPin())); + await store.idle; + final sent = (jsonDecode(fake.puts.last.body)['pins'] as List).single; + expect((sent as Map).containsKey('telemetryTiles'), false); + expect(sent['view'], 'telemetry'); + expect(store.notice, isNull); + expect(store.saved.pins.single.telemetryTiles, tiles); + expect(cachedPins(r.prefs).single['telemetryTiles'], tiles); + // A reload takes the server copy and still keeps the local tiles. + await store.sync(); + expect(store.saved.pins.single.telemetryTiles, tiles); + }, + ); + + test('a server with the flag gets them', () async { + final fake = FakeServer() + ..atlasTelemetry = true + ..sensors = true; + final r = await rig(marked: true, fake: fake); + final store = r.store; + await store.idle; + store.update((v) => v.appended(sensorPin())); + await store.idle; + final sent = (jsonDecode(fake.puts.last.body)['pins'] as List).single; + expect(sent['telemetryTiles'], tiles); + expect(store.saved.pins.single.telemetryTiles, tiles); + }); + }); + group('pinned Poller view', () { AtlasPin pollerPin() => AtlasPin.node( id: nodeId, diff --git a/test/atlas/server_contract_test.dart b/test/atlas/server_contract_test.dart index 41ce3d5..8442d1a 100644 --- a/test/atlas/server_contract_test.dart +++ b/test/atlas/server_contract_test.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:beacon/core/json.dart'; import 'package:beacon/features/account/request_text.dart'; +import 'package:beacon/features/atlas/atlas.dart'; import 'package:beacon/features/atlas/atlas_sync.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -58,6 +59,31 @@ void main() { } }); + test('sensor tiles go only to a server that takes them', () { + final atlas = SavedAtlas( + pins: [ + AtlasPin.node( + id: '11111111-1111-4111-8111-111111111111', + publicKey: _a, + name: 'Hill', + telemetryTiles: const ['humidity', 'pressure', 'gas', 'power'], + ), + ], + ); + Json pin({required bool sensors}) => + (atlasPutBody(atlas, const {}, 7, sensors: sensors)['pins'] as List) + .cast() + .single; + // The server answers 422 to an id it does not know. + expect(pin(sensors: false).containsKey('telemetryTiles'), isFalse); + expect(pin(sensors: true)['telemetryTiles'], [ + 'humidity', + 'pressure', + 'gas', + 'power', + ]); + }); + // A telemetry request as GET /me/telemetry-requests marshals it: poller // carries state and stateAt on a new server, neither on an old one. Json request(String poller) => object( diff --git a/test/atlas/telemetry_sample_test.dart b/test/atlas/telemetry_sample_test.dart index 2047c3f..e397fa6 100644 --- a/test/atlas/telemetry_sample_test.dart +++ b/test/atlas/telemetry_sample_test.dart @@ -117,7 +117,7 @@ void main() { }); test('no temperature is offered when no reading has one', () { - expect(sample.hasTemperature, true); + expect(sample.has('temperature'), true); final points = (fixture()['points'] as List).cast>(); final without = summarizeTelemetry( { @@ -128,7 +128,7 @@ void main() { AtlasRange.day, tick, ); - expect(without.hasTemperature, false); + expect(without.has('temperature'), false); expect(without.latest('temperature'), isNull); }); @@ -155,6 +155,153 @@ void main() { }); }); + group('sensor tiles', () { + Map at(int h, List> sensors) => { + 't': hour(h), + 'readings': 1, + 'sensors': sensors, + }; + TelemetrySample read(List> points) => + summarizeTelemetry({'points': points}, AtlasRange.day, tick); + + test('readings without sensors have none', () { + final sample = summarizeTelemetry(fixture(), AtlasRange.day, tick); + for (final tile in sensorTileIds) { + expect(sample.has(tile), false, reason: tile); + expect(sample.latest(tile), isNull, reason: tile); + } + expect(sample.gasIsIaq, false); + expect(sample.latest('battery'), closeTo(4.226, 1e-9)); + }); + + test('each reads its field from the server example', () { + final sample = read([ + at(2, [ + { + 'channel': 2, + 'temperatureC': 21.4, + 'humidityPct': 45.5, + 'pressureHpa': 1013.2, + 'iaq': 50, + 'iaqAccuracy': 3, + }, + {'channel': 3, 'voltageV': 8.7, 'currentA': 0.122, 'powerW': 1.061}, + ]), + ]); + expect(sample.latest('humidity'), 45.5); + expect(sample.latest('pressure'), 1013.2); + expect(sample.latest('gas'), 50); + expect(sample.gasIsIaq, true); + expect(sample.latest('sensorVoltage'), 8.7); + expect(sample.latest('current'), 0.122); + expect(sample.latest('power'), 1.061); + expect(sample.times['power'], [hour(2)]); + // Sensor temperature is not the repeater's own. + expect(sample.has('temperature'), false); + }); + + test('the lowest channel in the window is the one followed', () { + final sample = read([ + at(3, [ + {'channel': 4, 'humidityPct': 70}, + ]), + at(2, [ + {'channel': 2, 'humidityPct': 40}, + {'channel': 4, 'humidityPct': 71}, + ]), + at(1, [ + {'channel': 4, 'humidityPct': 72}, + ]), + ]); + expect(sample.values['humidity'], [40]); + expect(sample.times['humidity'], [hour(2)]); + }); + + test('gas is kilohms from a channel with no air quality index', () { + final sample = read([ + at(2, [ + {'channel': 2, 'gasOhms': 50000}, + ]), + at(1, [ + {'channel': 2, 'gasOhms': 52500}, + {'channel': 3, 'iaq': 80}, + ]), + ]); + expect(sample.gasIsIaq, false); + expect(sample.values['gas'], [50, 52.5]); + }); + + test('gas follows the index when its channel reports one', () { + final sample = read([ + at(2, [ + {'channel': 2, 'gasOhms': 50000}, + {'channel': 1, 'iaq': 75}, + ]), + at(1, [ + {'channel': 1, 'iaq': 80, 'gasOhms': 61000}, + ]), + ]); + expect(sample.gasIsIaq, true); + expect(sample.values['gas'], [75, 80]); + }); + + test('the newest index gives the gas tile its accuracy', () { + final sample = read([ + at(1, [ + {'channel': 1, 'iaq': 80, 'iaqAccuracy': 1}, + ]), + at(3, [ + {'channel': 1, 'iaq': 75, 'iaqAccuracy': 3}, + ]), + at(2, [ + {'channel': 1, 'iaq': 78, 'iaqAccuracy': 2}, + ]), + ]); + expect(sample.gasIsIaq, true); + expect(sample.gasIaqAccuracy, 1); + }); + + test('raw gas has no accuracy', () { + final sample = read([ + at(1, [ + {'channel': 2, 'gasOhms': 50000, 'iaqAccuracy': 3}, + {'channel': 3, 'iaq': 80, 'iaqAccuracy': 3}, + ]), + ]); + expect(sample.gasIsIaq, false); + expect(sample.gasIaqAccuracy, isNull); + expect(read([]).gasIaqAccuracy, isNull); + }); + + test('an accuracy that is missing or makes no sense is none', () { + for (final odd in [null, 4, -1, 2.5, '3']) { + final sample = read([ + at(2, [ + {'channel': 1, 'iaq': 75, 'iaqAccuracy': 3}, + ]), + at(1, [ + {'channel': 1, 'iaq': 80, 'iaqAccuracy': ?odd}, + ]), + ]); + expect(sample.gasIsIaq, true, reason: '$odd'); + expect(sample.gasIaqAccuracy, isNull, reason: '$odd'); + } + }); + + test('odd sensor shapes are skipped', () { + final sample = read([ + {'t': hour(2), 'sensors': 'none'}, + {'t': hour(1), 'sensors': null}, + at(1, [ + {'humidityPct': 40}, + {'channel': 2, 'humidityPct': 'wet'}, + ]), + ]); + expect(sample.has('humidity'), false); + expect(sample.readings, 3); + }); + }); + group('dots or a line', () { test('under eight readings draws dots', () { expect(useDots([null, 1, null, 2, 3]), true); @@ -304,6 +451,25 @@ void main() { } }); + test('take the sensor tiles', () { + const tiles = ['humidity', 'pressure', 'gas', 'power']; + expect(parsed(pin({'telemetryTiles': tiles})).telemetryTiles, tiles); + const more = ['current', 'sensorVoltage', 'battery', 'noise']; + expect(parsed(pin({'telemetryTiles': more})).telemetryTiles, more); + expect(parsed(pin()).withTelemetryTiles(more).telemetryTiles, more); + final server = parseServerAtlas({ + 'revision': 3, + 'range': '24h', + 'pins': [ + pin({'telemetryTiles': tiles}), + ], + })!; + expect(server.atlas.pins.single.telemetryTiles, tiles); + expect(hasSensorTile(tiles), true); + expect(hasSensorTile(defaultTelemetryTiles), false); + expect(hasSensorTile(null), false); + }); + test('survive an export and an import', () { final p = parsed( pin({ @@ -391,6 +557,91 @@ void main() { expect((out[1] as Map)['view'], 'heard'); }); + group('sensor tiles', () { + const sensorTiles = ['battery', 'humidity', 'uptime', 'airtime']; + final withSensor = SavedAtlas( + pins: [ + AtlasPin.node( + id: nodeId, + publicKey: key, + name: 'Hill', + telemetryTiles: sensorTiles, + view: AtlasView.telemetry, + ), + AtlasPin.node( + id: nodeId, + publicKey: 'cd' * 32, + name: 'Ridge', + telemetryTiles: const ['noise', 'battery', 'uptime', 'airtime'], + ), + ], + ); + + test('go to a server with the flag', () { + final out = pins(atlasPutBody(withSensor, const {}, 1)); + expect((out[0] as Map)['telemetryTiles'], sensorTiles); + }); + + test('stay home without it, other tiles and the view still go', () { + final out = pins(atlasPutBody(withSensor, const {}, 1, sensors: false)); + expect((out[0] as Map).containsKey('telemetryTiles'), false); + expect((out[0] as Map)['view'], 'telemetry'); + expect((out[1] as Map)['telemetryTiles'], [ + 'noise', + 'battery', + 'uptime', + 'airtime', + ]); + }); + + test('the local copy keeps them over the server copy', () { + final server = parseServerAtlas({ + 'revision': 2, + 'range': '24h', + 'pins': [ + { + 'kind': 'node', + 'id': nodeId, + 'publicKey': key, + 'name': 'Hill', + 'view': 'telemetry', + }, + { + 'kind': 'node', + 'id': nodeId, + 'publicKey': 'cd' * 32, + 'name': 'Ridge', + }, + ], + })!; + final merged = carrySensors(server.atlas, withSensor); + expect(merged.pins[0].telemetryTiles, sensorTiles); + expect(merged.pins[0].view, AtlasView.telemetry); + // Tiles the server does store are the server's to say. + expect(merged.pins[1].telemetryTiles, isNull); + }); + + test('tiles the server sent win', () { + final server = parseServerAtlas({ + 'revision': 2, + 'range': '24h', + 'pins': [ + { + 'kind': 'node', + 'id': nodeId, + 'publicKey': key, + 'name': 'Hill', + 'telemetryTiles': ['noise', 'battery', 'uptime', 'airtime'], + }, + ], + })!; + expect( + carrySensors(server.atlas, withSensor).pins.single.telemetryTiles, + ['noise', 'battery', 'uptime', 'airtime'], + ); + }); + }); + test('the local copy keeps them over the server copy', () { final server = parseServerAtlas({ 'revision': 2, diff --git a/test/core/features_test.dart b/test/core/features_test.dart index 510b93a..6e87e6e 100644 --- a/test/core/features_test.dart +++ b/test/core/features_test.dart @@ -179,6 +179,23 @@ void main() { expect(off.mapTelemetry, false); }); + test('sensors is off unless the server says so', () { + expect(ServerFeatures.fromInfo({'features': {}}).sensors, false); + expect( + ServerFeatures.fromInfo({ + 'features': {'sensors': 'yes'}, + }).sensors, + false, + ); + expect( + ServerFeatures.fromInfo({ + 'features': {'sensors': true}, + }).sensors, + true, + ); + expect(const ServerFeatures.off().sensors, false); + }); + test('wrong types fall back to off', () { final f = ServerFeatures.fromInfo({ 'features': {'polling': 'yes', 'accounts': 3}, diff --git a/test/core/strings_coverage_test.dart b/test/core/strings_coverage_test.dart index 0ff8b3a..d3dedc2 100644 --- a/test/core/strings_coverage_test.dart +++ b/test/core/strings_coverage_test.dart @@ -89,6 +89,33 @@ void main() { } }); + test('gas sensor calibration is worded in every locale', () { + expect(en['sensors.calibrating'], 'Calibrating ({{n}}/3)'); + expect(fr['sensors.calibrating'], 'Calibrage en cours ({{n}}/3)'); + expect(sv['sensors.calibrating'], 'Kalibrerar ({{n}}/3)'); + expect(en['sensors.calibrated'], 'Calibrated (3/3)'); + expect(fr['sensors.calibrated'], 'Calibré (3/3)'); + expect(sv['sensors.calibrated'], 'Kalibrerad (3/3)'); + expect( + en['sensors.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.', + ); + expect( + fr['sensors.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.', + ); + expect( + sv['sensors.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.', + ); + }); + test('translations keep their placeholders', () { final placeholder = RegExp(r'\{\{\w+\}\}'); Set names(String text) => diff --git a/test/directory/foreign_poller_test.dart b/test/directory/foreign_poller_test.dart index 05885e9..45fc4ac 100644 --- a/test/directory/foreign_poller_test.dart +++ b/test/directory/foreign_poller_test.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:beacon/core/api.dart'; import 'package:beacon/features/directory/directory.dart'; +import 'package:beacon/features/directory/foreign_source.dart'; import 'package:beacon/features/directory/node_chips.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -12,6 +13,7 @@ import 'package:http/http.dart' as http; import 'package:http/testing.dart'; const _chip = ValueKey('chip-foreign-poller'); +const _local = ValueKey('chip-local-poller'); void _size(WidgetTester tester, double width, double textScale) { tester.view.physicalSize = Size(width, 900); @@ -115,6 +117,71 @@ Future _fonts() async { void main() { setUpAll(_fonts); + test('isLocalPoller reads the flag; an older server sends none', () { + expect(isLocalPoller({'isPoller': true, 'isLocalPoller': true}), isTrue); + expect(isLocalPoller({'isPoller': true, 'isLocalPoller': false}), isFalse); + expect(isLocalPoller({'isPoller': true}), isFalse); + expect(isLocalPoller({'isPoller': true, 'isLocalPoller': null}), isFalse); + // It shows only while the node polls. + expect(isLocalPoller({'isPoller': false, 'isLocalPoller': true}), isFalse); + }); + + group('local poller', () { + final local = {..._node(false), 'isLocalPoller': true}; + + testWidgets('the header gets one Local poller chip that explains itself', ( + tester, + ) async { + await _pumpDetail(tester, local); + expect(find.byKey(_local), findsOneWidget); + expect(find.text('LOCAL POLLER'), findsOneWidget); + expect(find.byKey(const ValueKey('chip-poller')), findsNothing); + expect(find.byKey(_chip), findsNothing); + final chip = tester.widget(find.byKey(_local)); + expect(chip.color, pollerColor); + expect(chip.glyph, 'poller'); + expect(chip.dashed, isTrue); + final tip = tester.widget( + find.descendant(of: find.byKey(_local), matching: find.byType(Tooltip)), + ); + expect( + tip.message, + 'Runs in local mode: it polls repeaters its owner set up by hand and ' + 'follows no server.', + ); + expect(tip.triggerMode, TooltipTriggerMode.tap); + }); + + for (final scale in [1.0, 1.5, 2.0]) { + testWidgets('fits 320 pt at text scale $scale', (tester) async { + await _pumpDetail( + tester, + {...local, 'nodeTypeName': 'room_server'}, + width: 320, + textScale: scale, + ); + expect(find.byKey(_local), findsOneWidget); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('the list row marks it, glyph only', (tester) async { + final handle = tester.ensureSemantics(); + await _pumpList(tester, [ + {...local, 'id': 'l', 'name': 'Local'}, + {..._node(true), 'id': 'f', 'name': 'Foreign'}, + {..._node(null), 'id': 'old', 'name': 'Old server'}, + ]); + expect(find.byKey(_local), findsOneWidget); + expect(find.byKey(_chip), findsOneWidget); + expect(find.byKey(const ValueKey('chip-poller')), findsOneWidget); + expect(find.text('LOCAL POLLER'), findsNothing); + expect(tester.widget(find.byKey(_local)).label, isNull); + expect(find.bySemanticsLabel('Local poller'), findsOneWidget); + handle.dispose(); + }); + }); + group('node detail header', () { testWidgets('a foreign poller gets one Foreign poller chip', ( tester, diff --git a/test/directory/node_poller_test.dart b/test/directory/node_poller_test.dart index 351d937..8e1c829 100644 --- a/test/directory/node_poller_test.dart +++ b/test/directory/node_poller_test.dart @@ -764,4 +764,84 @@ void main() { expect(find.text('This radio has no polling claim.'), findsNothing); }); }); + + group('local mode', () { + Json localTarget({bool signed = false}) => target( + role: 'unassigned', + state: '', + latestReadingAt: now - 5 * minute, + latestReadingRssi: -91, + latestReadingSigned: signed, + ); + Json local(List targets) => { + 'claim': null, + 'readings24h': 48, + 'foreignReadings24h': 48, + 'targets': targets, + }; + + testWidgets('no claim but repeaters: the note and the list', ( + tester, + ) async { + final opened = await pump(tester, local([localTarget()])); + expect( + find.text( + 'Local mode. This observer reports no claim, so slots and login ' + 'state are not known.', + ), + findsOneWidget, + ); + expect(find.text('LOCAL'), findsOneWidget); + expect(find.text('FOREIGN'), findsNothing); + // The count leads the section, with the Local tag on the same row. + final count = find.byKey(const ValueKey('poller-local-readings')); + expect(tester.widget(count).data, '48'); + expect(find.text('readings'), findsOneWidget); + expect( + (tester.getCenter(find.text('LOCAL')).dy - tester.getCenter(count).dy) + .abs(), + lessThan(8), + ); + expect(find.text('This radio has no polling claim.'), findsNothing); + // The note sits above the list. + expect( + tester.getTopLeft(find.byKey(const ValueKey('poller-local-note'))).dy, + lessThan(tester.getTopLeft(find.text('Carp Ridge')).dy), + ); + await tester.tap(find.text('Carp Ridge')); + expect(opened, ['n-1']); + }); + + testWidgets('a card keeps the reading and drops what a claim tells', ( + tester, + ) async { + await pump(tester, local([localTarget(signed: true)])); + expect(find.text('RSSI'), findsOneWidget); + expect(find.text('-91'), findsOneWidget); + expect(find.text('READING'), findsOneWidget); + expect(find.text('5m ago'), findsOneWidget); + expect(find.byKey(const ValueKey('reading-signed')), findsOneWidget); + for (final gone in ['OWN', 'REQUESTED', 'NOT ASSIGNED']) { + expect(find.text(gone), findsNothing, reason: gone); + } + expect(find.text('LAST REPLY'), findsNothing); + expect(find.text('SNR'), findsNothing); + expect(find.text('never'), findsNothing); + expect(find.textContaining('evidence'), findsNothing); + expect(find.byKey(const ValueKey('poller-meter')), findsNothing); + expect(find.text('slots used'), findsNothing); + }); + + for (final scale in [1.0, 2.0]) { + testWidgets('fits 320 pt at text scale $scale', (tester) async { + await pump( + tester, + local([localTarget(signed: true), localTarget()]), + width: 320, + textScale: scale, + ); + expect(tester.takeException(), isNull); + }); + } + }); } diff --git a/test/directory/node_telemetry_test.dart b/test/directory/node_telemetry_test.dart index 722d4b1..7672cf4 100644 --- a/test/directory/node_telemetry_test.dart +++ b/test/directory/node_telemetry_test.dart @@ -1,12 +1,17 @@ import 'dart:convert'; +import 'dart:io'; import 'package:beacon/core/api.dart'; import 'package:beacon/core/strings.dart'; +import 'package:beacon/core/theme.dart'; import 'package:beacon/core/units.dart'; import 'package:beacon/features/analytics/charts.dart'; +import 'package:beacon/features/analytics/transforms.dart'; import 'package:beacon/features/directory/directory.dart'; +import 'package:beacon/features/directory/node_chips.dart'; import 'package:beacon/features/directory/node_telemetry.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; @@ -123,6 +128,180 @@ void main() { }); }); + group('sensors', () { + Map sensed(int t, List> sensors) => + point(t, {'sensors': sensors}); + + test('points without sensors have no channels and no chart data', () { + final points = [ + point(0), + point(hour, {'sensors': null}), + ]; + expect(sensorChannels(points, 'humidityPct'), isEmpty); + expect(sensorSeries(points, 'humidityPct', hour), isEmpty); + expect(hasChartData(points), false); + }); + + test('a node with only sensor data has chart data', () { + for (final key in ['temperatureC', 'humidityPct', 'luminosityLux']) { + expect( + hasChartData([ + sensed(0, [ + {'channel': 2, key: 1.5}, + ]), + ]), + true, + reason: key, + ); + } + // A channel with nothing a chart draws is not data. + expect( + hasChartData([ + sensed(0, [ + {'channel': 2, 'iaqAccuracy': 3}, + ]), + ]), + false, + ); + }); + + test('one series per channel, lowest first, each with its own gaps', () { + final series = sensorSeries( + [ + sensed(0, [ + {'channel': 3, 'humidityPct': 60}, + {'channel': 2, 'humidityPct': 45.5}, + ]), + sensed(hour, [ + {'channel': 3, 'humidityPct': 61}, + ]), + // Three hours on: the line breaks after the second point. + sensed(4 * hour, [ + {'channel': 2, 'humidityPct': 47}, + ]), + ], + 'humidityPct', + hour, + ); + expect(series.keys, ['Channel 2', 'Channel 3']); + expect(series['Channel 2']!.map((p) => p.y), [45.5, null, null, 47]); + expect(series['Channel 3']!.map((p) => p.y), [60, 61, null, null]); + expect(series['Channel 2']!.map((p) => p.x), [ + 0, + hour, + 2 * hour, + 4 * hour, + ]); + }); + + test('an accuracy reads as calibrating until it reaches 3', () { + expect(iaqStatus(0), 'Calibrating (0/3)'); + expect(iaqStatus(1), 'Calibrating (1/3)'); + expect(iaqStatus(2), 'Calibrating (2/3)'); + expect(iaqStatus(3), 'Calibrated (3/3)'); + for (final odd in [null, 4, -1, 2.5, 3.0, '3', true]) { + expect(iaqStatus(odd), isNull, reason: '$odd'); + } + }); + + test('the newest index on a channel gives its accuracy', () { + final points = [ + sensed(2 * hour, [ + {'channel': 2, 'iaq': 60, 'iaqAccuracy': 1}, + {'channel': 3, 'iaq': 70, 'iaqAccuracy': 9}, + ]), + sensed(0, [ + {'channel': 2, 'iaq': 50, 'iaqAccuracy': 3}, + {'channel': 3, 'iaq': 70, 'iaqAccuracy': 3}, + ]), + // No index here, so this accuracy says nothing. + sensed(3 * hour, [ + {'channel': 2, 'iaqAccuracy': 2}, + ]), + ]; + expect(newestIaqAccuracy(points, 2), 1); + expect(newestIaqAccuracy(points, 3), isNull); + expect(newestIaqAccuracy(points, 4), isNull); + }); + + test('a lone air quality channel gives the chart its accuracy', () { + final points = [ + sensed(0, [ + {'channel': 2, 'iaq': 50, 'iaqAccuracy': 3}, + ]), + sensed(hour, [ + {'channel': 2, 'iaq': 55, 'iaqAccuracy': 1}, + ]), + ]; + expect(airQualityAccuracy(points), 1); + expect(airQualitySeries(points, hour).keys, ['Channel 2']); + expect(airQualitySeries(points, hour)['Channel 2']!.map((p) => p.y), [ + 50, + 55, + ]); + expect( + airQualityAccuracy([ + sensed(0, [ + {'channel': 2, 'iaq': 50}, + ]), + ]), + isNull, + ); + }); + + test('several air quality channels each say theirs in the legend', () { + final points = [ + sensed(0, [ + {'channel': 2, 'iaq': 50, 'iaqAccuracy': 3}, + {'channel': 3, 'iaq': 80, 'iaqAccuracy': 0}, + {'channel': 4, 'iaq': 90}, + ]), + ]; + expect(airQualityAccuracy(points), isNull); + expect(airQualitySeries(points, hour).keys, [ + 'Channel 2 · Calibrated (3/3)', + 'Channel 3 · Calibrating (0/3)', + 'Channel 4', + ]); + }); + + test('gas is kilohms, a line for every channel that sent a resistance', () { + final points = [ + sensed(0, [ + {'channel': 2, 'gasOhms': 50000}, + {'channel': 3, 'gasOhms': 61000, 'iaq': 50, 'iaqAccuracy': 3}, + ]), + ]; + expect(sensorChannels(points, 'gasOhms'), [2, 3]); + expect(sensorChannels(points, 'iaq'), [3]); + final gas = sensorMetrics.firstWhere((m) => m.key == 'gasOhms'); + final series = sensorSeries(points, gas.key, hour, scale: gas.scale); + expect(series.keys, ['Channel 2', 'Channel 3']); + expect(series['Channel 2']!.single.y, closeTo(50, 1e-9)); + expect(series['Channel 3']!.single.y, closeTo(61, 1e-9)); + }); + + test('an accuracy written as a whole decimal still counts', () { + final points = [ + sensed(0, [ + {'channel': 2, 'iaq': 50, 'iaqAccuracy': 2.0}, + ]), + ]; + expect(newestIaqAccuracy(points, 2), 2); + }); + + test('a sensor without a channel is skipped', () { + expect( + sensorChannels([ + sensed(0, [ + {'humidityPct': 45.5}, + ]), + ], 'humidityPct'), + isEmpty, + ); + }); + }); + group('section', () { Future> pump( WidgetTester tester, { @@ -135,8 +314,9 @@ void main() { void Function(String, String)? onOpen, String temperatureUnit = 'c', String? observerId, + double width = 800, }) async { - tester.view.physicalSize = const Size(800, 6000); + tester.view.physicalSize = Size(width, 6000); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final seen = []; @@ -407,6 +587,259 @@ void main() { expect(find.text('AIRTIME TX AND RX (% OF TIME)'), findsNothing); }); + Map> seriesOf(WidgetTester tester, String title) => + tester + .widget( + find.descendant( + of: find.ancestor( + of: find.text(title), + matching: find.byType(AnalyticsCard), + ), + matching: find.byType(TimeChart), + ), + ) + .series; + const sensorTitles = [ + 'HUMIDITY', + 'PRESSURE', + 'GAS', + 'AIR QUALITY', + 'SENSOR VOLTAGE', + 'CURRENT', + 'POWER', + 'DISTANCE', + 'MOISTURE', + 'LIGHT', + ]; + + testWidgets('no sensor chart without sensors', (tester) async { + await pump(tester, telemetry: data()); + for (final title in sensorTitles) { + expect(find.text(title), findsNothing, reason: title); + } + expect(seriesOf(tester, 'TEMPERATURE (°C)').keys, ['Temperature']); + }); + + testWidgets('a chart per sensor measurement, a line per channel', ( + tester, + ) async { + await pump( + tester, + telemetry: { + 'polled': true, + 'points': [ + point(now - 2 * hour, { + 'batteryMv': 3940, + 'sensors': [ + { + 'channel': 2, + 'temperatureC': 21.4, + 'humidityPct': 45.5, + 'pressureHpa': 1013.2, + 'iaq': 50, + 'iaqAccuracy': 3, + }, + { + 'channel': 3, + 'voltageV': 8.7, + 'currentA': 0.122, + 'powerW': 1.061, + 'humidityPct': 60, + }, + ], + }), + ], + }, + ); + expect(seriesOf(tester, 'HUMIDITY').keys, ['Channel 2', 'Channel 3']); + expect(seriesOf(tester, 'PRESSURE').keys, ['Channel 2']); + expect(seriesOf(tester, 'AIR QUALITY').keys, ['Channel 2']); + expect(seriesOf(tester, 'SENSOR VOLTAGE').keys, ['Channel 3']); + expect(seriesOf(tester, 'CURRENT').keys, ['Channel 3']); + expect(seriesOf(tester, 'POWER')['Channel 3']!.single.y, 1.061); + for (final title in ['GAS', 'DISTANCE', 'MOISTURE', 'LIGHT']) { + expect(find.text(title), findsNothing, reason: title); + } + // The repeater sent no temperature of its own; the sensor's still shows. + expect(seriesOf(tester, 'TEMPERATURE (°C)').keys, ['Channel 2']); + }); + + testWidgets('two air quality channels keep the title and label the lines', ( + tester, + ) async { + await pump( + tester, + telemetry: { + 'polled': true, + 'points': [ + point(now - hour, { + 'sensors': [ + {'channel': 2, 'iaq': 50, 'iaqAccuracy': 3}, + {'channel': 3, 'iaq': 80, 'iaqAccuracy': 1}, + ], + }), + ], + }, + ); + expect(seriesOf(tester, 'AIR QUALITY').keys, [ + 'Channel 2 · Calibrated (3/3)', + 'Channel 3 · Calibrating (1/3)', + ]); + expect(find.byKey(const ValueKey('chip-iaq')), findsNothing); + expect(tester.takeException(), isNull); + }); + + Map airQuality(Map sensor) => { + 'polled': true, + 'points': [ + point(now - hour, { + 'sensors': [ + {'channel': 2, 'iaq': 50, ...sensor}, + ], + }), + ], + }; + final iaqCard = find.ancestor( + of: find.text('AIR QUALITY'), + matching: find.byType(AnalyticsCard), + ); + final iaqChipIn = find.descendant( + of: iaqCard, + matching: find.byKey(const ValueKey('chip-iaq')), + ); + + testWidgets('one air quality channel puts its chip in the card header', ( + tester, + ) async { + await pump(tester, telemetry: airQuality({'iaqAccuracy': 1})); + final colors = BeaconColors.of(tester.element(iaqChipIn)); + expect(tester.widget(iaqChipIn).label, 'CALIBRATING (1/3)'); + expect(tester.widget(iaqChipIn).color, colors.warning); + expect(seriesOf(tester, 'AIR QUALITY').keys, ['Channel 2']); + // The chip ends the title's line. + expect( + tester.getCenter(iaqChipIn).dy, + moreOrLessEquals( + tester.getCenter(find.text('AIR QUALITY')).dy, + epsilon: 2, + ), + ); + expect( + tester.getRect(iaqChipIn).left, + greaterThan(tester.getRect(find.text('AIR QUALITY')).right), + ); + await tester.tap(iaqChipIn); + await tester.pumpAndSettle(); + expect(find.text(trKey('sensors.accuracyHelp')), findsOneWidget); + }); + + testWidgets('a calibrated channel gets a green chip, an unknown one none', ( + tester, + ) async { + await pump(tester, telemetry: airQuality({'iaqAccuracy': 3})); + final colors = BeaconColors.of(tester.element(iaqChipIn)); + expect(tester.widget(iaqChipIn).label, 'CALIBRATED (3/3)'); + expect(tester.widget(iaqChipIn).color, colors.success); + await pump(tester, telemetry: airQuality({})); + expect(iaqCard, findsOneWidget); + expect(iaqChipIn, findsNothing); + }); + + for (final code in supportedLanguages) { + for (final width in [320.0, 375.0]) { + testWidgets('the header chip fits the card at $width in $code', ( + tester, + ) async { + addTearDown(() => language = 'en'); + await tester.runAsync(() async { + final bytes = File('assets/fonts/JetBrainsMono.ttf') + .readAsBytesSync(); + await (FontLoader( + 'JetBrainsMono', + )..addFont(Future.value(ByteData.sublistView(bytes)))).load(); + }); + language = code; + await pump( + tester, + telemetry: airQuality({'iaqAccuracy': 2}), + width: width, + ); + expect(tester.takeException(), isNull); + final card = find.ancestor( + of: find.text(trKey('sensors.airQuality').toUpperCase()), + matching: find.byType(AnalyticsCard), + ); + final chip = find.descendant( + of: card, + matching: find.byKey(const ValueKey('chip-iaq')), + ); + expect( + tester.getRect(chip).left, + greaterThanOrEqualTo(tester.getRect(card).left), + ); + expect( + tester.getRect(chip).right, + lessThanOrEqualTo(tester.getRect(card).right), + ); + }); + } + } + + testWidgets('the less common measurements chart the same way', ( + tester, + ) async { + await pump( + tester, + telemetry: { + 'polled': true, + 'points': [ + point(now - hour, { + 'sensors': [ + { + 'channel': 2, + 'gasOhms': 50000, + 'distanceM': 1.5, + 'percent': 33, + 'luminosityLux': 120, + }, + ], + }), + ], + }, + ); + expect(seriesOf(tester, 'GAS')['Channel 2']!.single.y, closeTo(50, 1e-9)); + expect(seriesOf(tester, 'DISTANCE').keys, ['Channel 2']); + expect(seriesOf(tester, 'MOISTURE').keys, ['Channel 2']); + expect(seriesOf(tester, 'LIGHT').keys, ['Channel 2']); + expect(find.text('AIR QUALITY'), findsNothing); + }); + + testWidgets('sensor temperature joins the temperature chart in the unit', ( + tester, + ) async { + final telemetry = data(); + (telemetry['points'] as List).add( + point(now - hour, { + 'sensors': [ + {'channel': 2, 'temperatureC': 35}, + ], + }), + ); + await pump(tester, telemetry: telemetry, temperatureUnit: 'f'); + final series = seriesOf(tester, 'TEMPERATURE (°F)'); + expect(series.keys, ['Temperature', 'Channel 2']); + expect(series['Channel 2']!.last.y, closeTo(95, 1e-9)); + expect(find.text('TEMPERATURE (°F)'), findsOneWidget); + }); + + testWidgets('the channel label is translated', (tester) async { + language = 'fr'; + addTearDown(() => language = 'en'); + expect(channelLabel(2), 'Canal 2'); + language = 'sv'; + expect(channelLabel(3), 'Kanal 3'); + }); + testWidgets('the range dropdown asks for another window', (tester) async { final seen = await pump(tester, telemetry: data(), pollingBody: poller); await tester.tap(find.byType(DropdownButtonFormField).first); diff --git a/test/directory/telemetry_request_block_test.dart b/test/directory/telemetry_request_block_test.dart index bc67429..4cc6fa1 100644 --- a/test/directory/telemetry_request_block_test.dart +++ b/test/directory/telemetry_request_block_test.dart @@ -443,7 +443,7 @@ void main() { ]); }); - testWidgets('they are listed under Also reported by with a Foreign tag', ( + testWidgets('they are listed under Reported by with a Foreign tag', ( tester, ) async { final opened = []; @@ -453,7 +453,9 @@ void main() { foreign: [lakeside], onOpen: (kind, id) => opened.add('$kind:$id'), ); - expect(find.text('Also reported by'), findsOneWidget); + // No poller of this server checks it, so they are not "also". + expect(find.text('Reported by'), findsOneWidget); + expect(find.text('Also reported by'), findsNothing); expect(find.text('Lakeside'), findsOneWidget); expect(find.textContaining('other.example.org'), findsOneWidget); expect(find.text('FOREIGN'), findsOneWidget); @@ -486,13 +488,15 @@ void main() { 'pollHost': null, 'signed': false, 'claimed': false, + 'local': true, 'latestReadingAt': null, }, ], ); expect(tester.takeException(), isNull); expect(find.text('SIGNED'), findsOneWidget); - expect(find.text('FOREIGN'), findsNWidgets(2)); + expect(find.text('FOREIGN'), findsOneWidget); + expect(find.text('LOCAL'), findsOneWidget); expect(find.text('sends readings only'), findsOneWidget); // The signed, claimed entry gets no note. expect(find.textContaining('other.example.org'), findsOneWidget); @@ -507,6 +511,103 @@ void main() { }); } + testWidgets( + 'an unclaimed reporter is tagged Local, a claimed one Foreign', + (tester) async { + await pump( + tester, + readings: true, + foreign: [ + lakeside, + { + ...lakeside, + 'observerId': 'obs-local', + 'claimed': false, + 'local': true, + }, + // An older server sends no claimed: it stays Foreign. + {...lakeside, 'observerId': 'obs-old'}..remove('claimed'), + ], + ); + expect( + find.byKey(const ValueKey('local-tag-obs-local')), + findsOneWidget, + ); + expect(find.text('LOCAL'), findsOneWidget); + expect(find.text('FOREIGN'), findsNWidgets(2)); + await tester.tap(find.text('LOCAL')); + await tester.pump(const Duration(milliseconds: 300)); + expect( + find.text( + 'Polled by an observer in local mode, set up by its owner. This ' + 'server does not manage it.', + ), + findsOneWidget, + ); + await tester.pumpAndSettle(const Duration(seconds: 13)); + }, + ); + + testWidgets('the section tag says Local when every reporter is unclaimed', ( + tester, + ) async { + final local = { + ...lakeside, + 'observerId': 'obs-local', + 'claimed': false, + 'local': true, + }; + await pump( + tester, + readings: true, + telemetryForeign: 'all', + foreign: [local], + ); + expect(find.text('LOCAL SOURCE'), findsOneWidget); + expect(find.text('FOREIGN SOURCE'), findsNothing); + await tester.tap(find.text('LOCAL SOURCE')); + await tester.pump(const Duration(milliseconds: 300)); + expect( + find.text( + 'Polled by an observer in local mode, set up by its owner. This ' + 'server does not manage it.', + ), + findsOneWidget, + ); + await tester.pumpAndSettle(const Duration(seconds: 13)); + + await pump( + tester, + readings: true, + telemetryForeign: 'some', + foreign: [local], + ); + expect(find.text('INCLUDES LOCAL READINGS'), findsOneWidget); + expect(find.text('INCLUDES FOREIGN READINGS'), findsNothing); + + // One claimed reporter keeps the foreign wording. + await pump( + tester, + readings: true, + telemetryForeign: 'all', + foreign: [local, lakeside], + ); + expect(find.text('FOREIGN SOURCE'), findsOneWidget); + expect(find.text('LOCAL SOURCE'), findsNothing); + + // An older server sends no claimed: foreign. + await pump( + tester, + readings: true, + telemetryForeign: 'some', + foreign: [ + {...lakeside}..remove('claimed'), + ], + ); + expect(find.text('INCLUDES FOREIGN READINGS'), findsOneWidget); + expect(find.text('INCLUDES LOCAL READINGS'), findsNothing); + }); + testWidgets('a poller and a foreign observer say it is checked twice', ( tester, ) async { @@ -523,12 +624,12 @@ void main() { tester, ) async { await pump(tester, readings: true, telemetryForeign: 'all'); - expect(find.text('Foreign source'), findsOneWidget); + expect(find.text('FOREIGN SOURCE'), findsOneWidget); await pump(tester, readings: true, telemetryForeign: 'some'); - expect(find.text('Includes foreign readings'), findsOneWidget); + expect(find.text('INCLUDES FOREIGN READINGS'), findsOneWidget); await pump(tester, readings: true, telemetryForeign: 'none'); - expect(find.text('Foreign source'), findsNothing); - expect(find.text('Includes foreign readings'), findsNothing); + expect(find.text('FOREIGN SOURCE'), findsNothing); + expect(find.text('INCLUDES FOREIGN READINGS'), findsNothing); }); testWidgets('a 2.3.0 server without the fields shows nothing new', ( @@ -541,7 +642,7 @@ void main() { ); expect(find.text('Also reported by'), findsNothing); expect(find.text('FOREIGN'), findsNothing); - expect(find.text('Foreign source'), findsNothing); + expect(find.text('FOREIGN SOURCE'), findsNothing); expect(find.byKey(const ValueKey('also-checked')), findsNothing); }); }); diff --git a/test/features/account/alert_rules_test.dart b/test/features/account/alert_rules_test.dart index dac02d9..5bfa002 100644 --- a/test/features/account/alert_rules_test.dart +++ b/test/features/account/alert_rules_test.dart @@ -2,6 +2,25 @@ import 'package:beacon/features/account/alert_rules.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { + test('gone quiet and telemetry stopped take the same five hours', () { + for (final kind in ['gone_quiet', 'telemetry_stopped']) { + final spec = alertKinds.firstWhere((s) => s.kind == kind); + expect(spec.input, AlertInput.hours); + expect(spec.options, [3, 6, 12, 24, 48]); + } + expect(defaultThreshold['telemetry_stopped'], 12); + expect(defaultThreshold['gone_quiet'], 24); + }); + + test('telemetry stopped sits right after back online', () { + final order = [for (final s in alertKinds) s.kind]; + expect(order.sublist(0, 3), [ + 'gone_quiet', + 'back_online', + 'telemetry_stopped', + ]); + }); + test('temperature limits are typed in the instance unit', () { expect(parseTenths('95', 'f'), 350); expect(parseTenths('14', 'f'), -100); diff --git a/test/features/account/alert_wording_test.dart b/test/features/account/alert_wording_test.dart index 3b4fcf5..3a67f5f 100644 --- a/test/features/account/alert_wording_test.dart +++ b/test/features/account/alert_wording_test.dart @@ -8,6 +8,7 @@ import 'harness.dart'; const kinds = [ 'gone_quiet', 'back_online', + 'telemetry_stopped', 'battery_low', 'battery_falling', 'rebooted', @@ -21,6 +22,7 @@ const names = { 'en': [ 'Gone quiet', 'Back online', + 'Telemetry stopped', 'Battery low', 'Battery falling', 'Rebooted', @@ -32,6 +34,7 @@ const names = { 'fr': [ 'Silence', 'De retour', + 'Télémétrie arrêtée', 'Batterie faible', 'Batterie en baisse', 'Redémarrage', @@ -43,6 +46,7 @@ const names = { 'sv': [ 'Tystnat', 'Tillbaka online', + 'Telemetri upphört', 'Lågt batteri', 'Fallande batteri', 'Startade om', @@ -57,6 +61,7 @@ const whens = { 'en': [ 'When the radio has not been heard for this long.', 'When the radio is heard again after it went quiet.', + 'When no telemetry has arrived for this long.', 'When the battery stays below this voltage.', 'When the battery drops faster than this in a day.', 'When the radio restarts.', @@ -68,6 +73,7 @@ const whens = { 'fr': [ "Quand la radio n'a pas été entendue depuis ce délai.", 'Quand la radio est de nouveau entendue après un silence.', + "Quand aucune télémétrie n'est arrivée depuis ce délai.", 'Quand la batterie reste sous cette tension.', 'Quand la batterie baisse plus vite que cela en une journée.', 'Quand la radio redémarre.', @@ -79,6 +85,7 @@ const whens = { 'sv': [ 'När radion inte har hörts på så här länge.', 'När radion hörs igen efter att ha tystnat.', + 'När ingen telemetri har kommit in på så här länge.', 'När batteriet stannar under den här spänningen.', 'När batteriet sjunker snabbare än så här på ett dygn.', 'När radion startar om.', @@ -106,6 +113,7 @@ const others = { 'Alerts are set on radios in your Atlas. Add a radio there first.', 'alerts.requestAttention': 'You are always told when one of your telemetry requests needs attention.', 'alerts.needsGoneQuiet': 'Turn on {{name}} first.', + 'alerts.goneQuietHint': 'Short windows can false-alarm on radios that are only heard through their adverts.', 'alerts.voltsPerDay': '{{volts}} V per day', 'alerts.input.minutes': 'No report for', 'alerts.input.low': 'Low ({{symbol}})', @@ -115,6 +123,7 @@ const others = { 'alerts.empty': "Les alertes se règlent sur les radios de votre Atlas. Ajoutez d'abord une radio.", 'alerts.requestAttention': "Vous êtes toujours prévenu quand une de vos demandes de télémétrie demande votre attention.", 'alerts.needsGoneQuiet': 'Activez d\'abord « {{name}} ».', + 'alerts.goneQuietHint': 'Un délai court peut donner de fausses alertes sur les radios entendues seulement par leurs annonces.', 'alerts.voltsPerDay': '{{volts}} V par jour', 'alerts.input.minutes': 'Sans rapport depuis', 'alerts.input.low': 'Bas ({{symbol}})', @@ -124,6 +133,7 @@ const others = { 'alerts.empty': 'Aviseringar ställs in på radioapparater i din Atlas. Lägg först till en radio.', 'alerts.requestAttention': 'Du får alltid besked när en av dina telemetribegäranden behöver uppmärksamhet.', 'alerts.needsGoneQuiet': 'Slå först på {{name}}.', + 'alerts.goneQuietHint': 'Korta tider kan ge falsklarm för radior som bara hörs genom sina annonser.', 'alerts.voltsPerDay': '{{volts}} V per dygn', 'alerts.input.minutes': 'Ingen rapport på', 'alerts.input.low': 'Låg ({{symbol}})', diff --git a/test/features/account/alerts_section_test.dart b/test/features/account/alerts_section_test.dart index 607a3ca..5a105c4 100644 --- a/test/features/account/alerts_section_test.dart +++ b/test/features/account/alerts_section_test.dart @@ -16,6 +16,7 @@ import 'harness.dart'; const full = [ 'gone_quiet', 'back_online', + 'telemetry_stopped', 'clock', 'battery_low', 'battery_falling', @@ -633,6 +634,7 @@ void main() { final order = [ 'gone_quiet', 'back_online', + 'telemetry_stopped', 'battery_low', 'battery_falling', 'rebooted', @@ -690,7 +692,7 @@ void main() { expect(find.text('Server sentence one.'), findsOneWidget); expect( find.text( - 'Beacon is not polling this repeater. Request telemetry for it first.', + 'No telemetry is arriving for this repeater. Request telemetry for it first.', ), findsOneWidget, ); @@ -719,75 +721,83 @@ void main() { expect(find.text('Not checked yet'), findsOneWidget); }); - group('gone quiet hours', () { + group('quiet hours', () { + const hours = [3, 6, 12, 24, 48]; Future> options(WidgetTester tester, String id) async { final menu = tester.widget>(k(id)); return menu.items!.map((i) => i.value).toList(); } - testWidgets('3 and 6 for a target that reports telemetry', (tester) async { + testWidgets('gone quiet offers all five on a polled repeater', ( + tester, + ) async { await open(tester); - expect(await options(tester, 'alert-input-aabb-gone_quiet'), [ - 3, - 6, - 12, - 24, - 48, - ]); + expect(await options(tester, 'alert-input-aabb-gone_quiet'), hours); }); - testWidgets('3 and 6 for a polled repeater that lists no telemetry kind', ( - tester, - ) async { + testWidgets('gone quiet offers all five when not polled', (tester) async { + await open(tester); + expect(await options(tester, 'alert-input-ccdd-gone_quiet'), hours); + }); + + testWidgets('gone quiet offers all five on an observer', (tester) async { data['targets'] = [ - target(available: ['gone_quiet', 'clock']), + target(kind: 'observer', polled: false, available: ['gone_quiet']), ]; await open(tester); - expect(await options(tester, 'alert-input-aabb-gone_quiet'), [ - 3, - 6, - 12, - 24, - 48, - ]); + expect(await options(tester, 'alert-input-aabb-gone_quiet'), hours); }); - testWidgets('only 12, 24 and 48 when not polled, whatever it lists', ( + testWidgets('telemetry stopped offers the same five and starts at 12', ( tester, ) async { - data['targets'] = [target(polled: false)]; await open(tester); - expect(await options(tester, 'alert-input-aabb-gone_quiet'), [ - 12, - 24, - 48, - ]); + const id = 'alert-input-aabb-telemetry_stopped'; + expect(await options(tester, id), hours); + expect(tester.widget>(k(id)).value, 12); }); - testWidgets('3 and 6 for an observer', (tester) async { - data['targets'] = [ - target(kind: 'observer', available: ['gone_quiet']), - ]; + testWidgets('only gone quiet warns about short windows', (tester) async { + data['targets'] = [target()]; await open(tester); - expect(await options(tester, 'alert-input-aabb-gone_quiet'), [ - 3, - 6, - 12, - 24, - 48, - ]); + expect( + find.text( + 'Short windows can false-alarm on radios that are only heard ' + 'through their adverts.', + ), + findsOneWidget, + ); }); + }); - testWidgets('only 12, 24 and 48 otherwise', (tester) async { - await open(tester); - expect(await options(tester, 'alert-input-ccdd-gone_quiet'), [ - 12, - 24, - 48, - ]); + testWidgets('telemetry stopped is sent with the picked hours', ( + tester, + ) async { + await open(tester); + await pick(tester, 'alert-input-aabb-telemetry_stopped', '6 hours'); + await tap(tester, 'alert-switch-aabb-telemetry_stopped'); + expect(body(0), { + 'target': {'kind': 'node', 'publicKey': 'aabb'}, + 'kind': 'telemetry_stopped', + 'threshold': 6, + 'thresholdHigh': null, + 'enabled': true, }); }); + testWidgets('telemetry stopped shows why it is unavailable', (tester) async { + data['targets'] = [ + target( + available: ['gone_quiet', 'back_online'], + unavailable: {'telemetry_stopped': 'Server sentence.'}, + unavailableCodes: {'telemetry_stopped': 'repeaters_only'}, + ), + ]; + await open(tester); + expect(find.text('Only repeaters report telemetry.'), findsOneWidget); + expect(k('alert-switch-aabb-telemetry_stopped'), findsNothing); + }); + group('turning rules on and off', () { testWidgets('on sends the shown value, then the list is read again', ( tester, diff --git a/test/features/account/request_text_test.dart b/test/features/account/request_text_test.dart index d884139..56c003d 100644 --- a/test/features/account/request_text_test.dart +++ b/test/features/account/request_text_test.dart @@ -290,10 +290,16 @@ void main() { 'This observer does not report a battery level.', ), ('repeaters_only', 'rebooted', 'Only repeaters report its uptime.'), + ('repeaters_only', 'telemetry_stopped', 'Only repeaters report telemetry.'), ( 'not_polled', 'temperature', - 'Beacon is not polling this repeater. Request telemetry for it first.', + 'No telemetry is arriving for this repeater. Request telemetry for it first.', + ), + ( + 'not_polled', + 'telemetry_stopped', + 'No telemetry is arriving for this repeater. Request telemetry for it first.', ), ('no_data', 'noise_high', 'This repeater does not report a noise floor.'), ('observer_no_clock', 'clock', 'Observers have no clock drift value.'), diff --git a/test/fixtures/push_notice.json b/test/fixtures/push_notice.json index d4c8681..59c6903 100644 --- a/test/fixtures/push_notice.json +++ b/test/fixtures/push_notice.json @@ -65,6 +65,38 @@ "tempUnit": "f", "want": "Ridge Rptr is back online." }, + { + "kind": "telemetry_stopped", + "name": "Ridge Rptr", + "value": 1, + "detail": "", + "tempUnit": "c", + "want": "Ridge Rptr has sent no telemetry for 1 hour." + }, + { + "kind": "telemetry_stopped", + "name": "Ridge Rptr", + "value": 1, + "detail": "", + "tempUnit": "f", + "want": "Ridge Rptr has sent no telemetry for 1 hour." + }, + { + "kind": "telemetry_stopped", + "name": "Ridge Rptr", + "value": 12, + "detail": "", + "tempUnit": "c", + "want": "Ridge Rptr has sent no telemetry for 12 hours." + }, + { + "kind": "telemetry_stopped", + "name": "Ridge Rptr", + "value": 12, + "detail": "", + "tempUnit": "f", + "want": "Ridge Rptr has sent no telemetry for 12 hours." + }, { "kind": "clock", "name": "Hilltop", diff --git a/test/previews/account_previews_test.dart b/test/previews/account_previews_test.dart index 9bd7021..94794dd 100644 --- a/test/previews/account_previews_test.dart +++ b/test/previews/account_previews_test.dart @@ -163,6 +163,7 @@ void main() { 'polled': true, 'available': [ 'gone_quiet', + 'telemetry_stopped', 'battery_low', 'temperature', 'noise_high',