#!/usr/bin/env python3 """Generate dashboards/meshcore-repeater.json (the Grafana dashboard). Edit the panels here, run `python3 dashboards/generate.py`, commit both files. The JSON works both for provisioning (stack/) and for a manual import: the datasource and the job label are dashboard variables, nothing points at a particular Grafana. """ import json import sys from pathlib import Path if {"-h", "--help"} & set(sys.argv[1:]): print((__doc__ or "").strip()) sys.exit(0) DS = {"type": "prometheus", "uid": "${datasource}"} SEL = 'job=~"$job", node="$node"' def q(expr, legend=None, ref="A"): t = {"datasource": DS, "expr": expr.replace("SEL", SEL).replace("[W]", "[$window]"), "refId": ref} if legend: t["legendFormat"] = legend return t def steps(*pairs): return {"mode": "absolute", "steps": [{"color": c, "value": v} for v, c in pairs]} def stat(pid, title, x, y, expr, unit, thr, desc=None, **defaults): p = { "id": pid, "type": "stat", "title": title, "datasource": DS, "gridPos": {"h": 5, "w": 4, "x": x, "y": y}, "fieldConfig": {"defaults": {"unit": unit, "thresholds": thr, **defaults}, "overrides": []}, "options": { "colorMode": "value", "graphMode": "area", "justifyMode": "auto", "textMode": "auto", "reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False}, }, "targets": [q(expr)], } if desc: p["description"] = desc return p def ts(pid, title, x, y, w, targets, unit, desc=None, h=8, overrides=None, **custom): p = { "id": pid, "type": "timeseries", "title": title, "datasource": DS, "gridPos": {"h": h, "w": w, "x": x, "y": y}, "fieldConfig": { "defaults": { "unit": unit, "color": {"mode": "palette-classic"}, "custom": { "drawStyle": "line", "lineWidth": 1, "fillOpacity": 10, "showPoints": "never", "spanNulls": 3600000, **custom, }, }, "overrides": overrides or [], }, "options": { "legend": {"displayMode": "list", "placement": "bottom", "showLegend": True}, "tooltip": {"mode": "multi", "sort": "none"}, }, "targets": [q(e, leg, chr(65 + i)) for i, (e, leg) in enumerate(targets)], } if desc: p["description"] = desc return p def mirrored(up, down): """Overrides: `up` series above zero, `down` series drawn below it. The axis label is rotated and reads bottom to top, so it names the lower (down) half first. negative-Y flips only the drawing; tooltip and legend keep the real (positive) value. Fixed colours, so TX/RX look the same in every panel. """ def color(name, c): return { "matcher": {"id": "byName", "options": name}, "properties": [{"id": "color", "value": {"mode": "fixed", "fixedColor": c}}], } out = [color(name, c) for name, c in up] for name, c in down: o = color(name, c) o["properties"].append({"id": "custom.transform", "value": "negative-Y"}) out.append(o) return out TX, RX, ERR = "orange", "blue", "red" def row(pid, title, y): return { "id": pid, "type": "row", "title": title, "collapsed": False, "panels": [], "gridPos": {"h": 1, "w": 24, "x": 0, "y": y}, } BATTERY_PCT = ( "Lineární odhad z napětí: 3,30 V = 0 %, 4,20 V = 100 % (Li-ion článek). LiFePO4 nebo jiný článek " "má jinou křivku; uprav výraz v panelu." ) TEMP = "Externí senzor, pokud ho uzel má a exportér je přihlášený jako admin; jinak teplota MCU." TX_TROUBLE = ( "TX start fail / TX timeout posílají jen některé forky firmwaru; na běžném firmwaru tu nic není. " "Rostoucí timeout = rádio vysílání nedokončuje." ) panels = [ stat( 1, "Baterie % (odhad z napětí)", 0, 0, "clamp(100 * (meshcore_battery_millivolts{SEL} - 3300) / 900, 0, 100)", "percent", steps((None, "red"), (20, "orange"), (40, "yellow"), (60, "green")), BATTERY_PCT, min=0, max=100, ), stat( 2, "Teplota", 4, 0, "meshcore_temperature_celsius{SEL}", "celsius", steps((None, "blue"), (0, "green"), (40, "orange")), TEMP, ), stat(3, "Uptime", 8, 0, "meshcore_uptime_seconds{SEL}", "s", steps((None, "green"))), stat( 4, "Stáří posledního čtení", 12, 0, "time() - meshcore_last_scrape_success_timestamp{SEL}", "s", steps((None, "green"), (4000, "yellow"), (7500, "red")), "Kdy naposledy uzel odpověděl. Při výchozím intervalu 1 h je normál do ~3600 s.", ), stat( 5, "Fronta TX", 16, 0, "meshcore_queue_length{SEL}", "none", steps((None, "green"), (3, "yellow"), (8, "red")) ), stat( 6, "Šumové pozadí", 20, 0, "meshcore_noise_floor_dbm{SEL}", "dBm", steps((None, "green"), (-105, "yellow"), (-95, "red")), "Čím níž, tím líp. Nad −100 dBm uzel hůř slyší slabé signály (rušení, blízký vysílač).", ), ts( 10, "Baterie (mV)", 0, 5, 12, [("meshcore_battery_millivolts{SEL}", "baterie")], "mV", axisSoftMin=3000, axisSoftMax=4300, ), ts( 11, "Teplota a vlhkost", 12, 5, 12, [("meshcore_temperature_celsius{SEL}", "teplota (°C)"), ("meshcore_humidity_percent{SEL}", "vlhkost (%)")], "celsius", TEMP, overrides=[ { "matcher": {"id": "byName", "options": "vlhkost (%)"}, "properties": [{"id": "unit", "value": "humidity"}, {"id": "custom.axisPlacement", "value": "right"}], } ], ), ts( 12, "Provoz — pakety za hodinu", 0, 13, 12, [ ("rate(meshcore_packets_received_total{SEL}[W]) * 3600", "přijato"), ("rate(meshcore_packets_sent_total{SEL}[W]) * 3600", "odesláno"), ("rate(meshcore_receive_errors_total{SEL}[W]) * 3600", "chyby příjmu (CRC)"), ], "none", "Nad nulou odeslané pakety, pod nulou přijaté a chyby příjmu.", overrides=mirrored([("odesláno", TX)], [("přijato", RX), ("chyby příjmu (CRC)", ERR)]), axisLabel="↓ přijato / ↑ odesláno", ), ts( 13, "Signál — RSSI / SNR / šum", 12, 13, 12, [ ("meshcore_last_rssi_dbm{SEL}", "RSSI posledního paketu (dBm)"), ("meshcore_last_snr_db{SEL}", "SNR posledního paketu (dB)"), ("meshcore_noise_floor_dbm{SEL}", "šumové pozadí (dBm)"), ], "none", ), ts( 14, "Airtime za hodinu (s)", 0, 21, 12, [ ("rate(meshcore_tx_airtime_seconds_total{SEL}[W]) * 3600", "vysílání"), ("rate(meshcore_rx_airtime_seconds_total{SEL}[W]) * 3600", "příjem"), ], "s", "Nad nulou čas vysílání, pod nulou čas příjmu.", overrides=mirrored([("vysílání", TX)], [("příjem", RX)]), axisLabel="↓ příjem / ↑ vysílání", ), ts( 15, "Přeposílání a potíže s vysíláním (za hodinu)", 12, 21, 12, [ ("rate(meshcore_packets_sent_flood_total{SEL}[W]) * 3600", "flood přeposláno"), ("rate(meshcore_packets_sent_direct_total{SEL}[W]) * 3600", "direct přeposláno"), ("rate(meshcore_flood_duplicates_total{SEL}[W]) * 3600", "flood duplikáty"), ("rate(meshcore_tx_start_fail_total{SEL}[W]) * 3600", "TX start fail"), ("rate(meshcore_tx_timeout_total{SEL}[W]) * 3600", "TX timeout"), ], "none", TX_TROUBLE, ), row(20, "Baterie a duty cycle", 29), stat( 21, "Trend baterie (mV/h, + nabíjí)", 0, 30, "deriv(meshcore_battery_millivolts{SEL}[W]) * 3600", "none", steps((None, "red"), (0, "green")), "Změna napětí za hodinu, spočítaná z okna `Okno`.", decimals=0, ), stat( 22, "TX duty cycle", 4, 30, "rate(meshcore_tx_airtime_seconds_total{SEL}[W]) * 100", "percent", steps((None, "green"), (5, "yellow"), (10, "red")), "Podíl času, kdy uzel vysílá. Pásmo 869,4–869,65 MHz v EU dovoluje 10 %.", decimals=2, ), ts( 23, "Duty cycle %", 8, 30, 16, [ ("rate(meshcore_tx_airtime_seconds_total{SEL}[W]) * 100", "vysílání (TX)"), ("rate(meshcore_rx_airtime_seconds_total{SEL}[W]) * 100", "příjem (RX)"), ], "percent", "Nad nulou podíl času vysílání (limit pásma 10 %), pod nulou příjmu.", h=6, overrides=mirrored([("vysílání (TX)", TX)], [("příjem (RX)", RX)]), axisLabel="↓ RX / ↑ TX", ), ] # the two stat panels in the last row are 6 high to match the graph for p in panels: if p["id"] in (21, 22): p["gridPos"].update(h=6) dashboard = { "uid": "meshcore-repeater", "title": "MeshCore — repeater $node", "description": "Stav MeshCore repeaterů čtený přes mesh (meshcore-exporter).", "tags": ["meshcore", "lora"], "editable": True, "graphTooltip": 1, "refresh": "5m", "schemaVersion": 39, "time": {"from": "now-24h", "to": "now"}, "timezone": "browser", "templating": { "list": [ { "name": "datasource", "label": "Zdroj dat", "type": "datasource", "query": "prometheus", "current": {}, "hide": 0, }, { "name": "job", "label": "Job", "type": "textbox", "query": "meshcore_exporter", "current": {"text": "meshcore_exporter", "value": "meshcore_exporter"}, "hide": 0, "description": "Hodnota labelu job, pod kterým Prometheus exportér scrapuje (regex).", }, { "name": "window", "label": "Okno", "type": "custom", "query": "1h,3h,6h,12h", "current": {"text": "3h", "value": "3h"}, "options": [{"text": w, "value": w, "selected": w == "3h"} for w in ("1h", "3h", "6h", "12h")], "hide": 0, "description": "Okno pro rychlosti a duty cycle. Data se mění jen při čtení repeateru, " "takže okno má být aspoň 2–3× interval čtení (výchozí 1 h → 3h).", }, { "name": "node", "label": "Repeater", "type": "query", "datasource": DS, "definition": 'label_values(meshcore_uptime_seconds{job=~"$job"}, node)', "query": {"query": 'label_values(meshcore_uptime_seconds{job=~"$job"}, node)', "refId": "node"}, "refresh": 2, "sort": 1, "current": {}, "hide": 0, }, ] }, "annotations": {"list": []}, "panels": panels, } out = Path(__file__).with_name("meshcore-repeater.json") out.write_text(json.dumps(dashboard, indent=2, ensure_ascii=False) + "\n") print(f"wrote {out}")