Live status of my MeshCore repeater on the Colorado Front Range, updated every 5 minutes straight from the Pi.
Loading repeater status…
See it on BEACON
This repeater is also an observer on BEACON, the Colorado Mesh Group’s online mesh analyzer. An observer forwards a copy of every packet it hears to a shared server over the internet, using MQTT.
BEACON pulls together reports from dozens of observers across Colorado. That lets it show what no single repeater can: which nodes are active, the paths messages take across the state, and how busy and noisy the channel is at each site. This page shows what my repeater hears. BEACON shows how the whole network is doing.
Build your own: the code behind this page
Everything that runs this page is below. You need an openHop repeater on a Raspberry Pi and a WordPress site. You’re welcome to use and adapt it.
- Install the WordPress plugin and copy the feed key from Settings > Repeater Feed.
- Create an API token in the openHop dashboard.
- Copy the Pi script and installer into a folder on the Pi and run
bash install.sh. - Put
[repeater_status]on a page.
It never sends your location, your neighbors’ locations, keys, or MQTT settings, and nothing on your network accepts outside connections. Tested on openHop 1.1.5; other versions may report some numbers differently.
repeater_status_push.py · The Pi script, 338 lines
Python 3, no extra packages. Runs every 5 minutes from cron. Reads openHop's API on the Pi and sends a trimmed snapshot out to your site.
#!/usr/bin/env python3
"""
repeater_status_push.py - send a public-safe snapshot of an openHop repeater
to the openHop Repeater Status WordPress plugin on your website.
Free to use and adapt.
Runs on the Pi (from cron, every 5 minutes). Reads openHop's local API,
keeps ONLY the fields listed below, and POSTs them to the website.
Nothing on the Pi is exposed to the internet: this script only makes
outbound requests.
Never sent: GPS coordinates (ours or neighbours'), public keys, MQTT /
broker settings, tokens, or any other config.
Settings come from ~/.repeater-status.env (see install.sh):
OPENHOP_URL default http://127.0.0.1:8000
OPENHOP_TOKEN an openHop API token (X-API-Key)
SITE_URL https://<your-site>/wp-json/repeater-status/v1/repeater
SITE_KEY the feed key shown in WordPress under Settings > Repeater Feed
"""
import json
import os
import sys
import time
import urllib.error
import urllib.request
ENV_FILE = os.path.expanduser(os.environ.get("RS_ENV") or "~/.repeater-status.env")
TIMEOUT = 20
NEIGHBOR_DAYS = 7 # neighbours heard within this many days
NEIGHBOR_LIMIT = 150
NOISE_BUCKET_SECS = 900 # 15-minute buckets for the noise chart
PACKET_TYPES = {0: "Request", 1: "Response", 2: "Text Message", 3: "Acknowledgment",
4: "Node Advertisement", 5: "Group Text Message", 6: "Group Datagram",
7: "Anonymous Request", 8: "Returned Path", 9: "Trace", 10: "Multi-part Packet",
11: "Control", 15: "Custom Packet"}
def load_env(path):
cfg = {}
try:
with open(path) as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
cfg[k.strip()] = v.strip().strip('"').strip("'")
except FileNotFoundError:
pass
for k in ("OPENHOP_URL", "OPENHOP_TOKEN", "SITE_URL", "SITE_KEY", "NODE_NAME"):
if os.environ.get(k):
cfg[k] = os.environ[k]
cfg.setdefault("OPENHOP_URL", "http://127.0.0.1:8000")
return cfg
def api_get(cfg, path, **params):
"""GET /api/<path> from openHop. Returns the 'data' part, or the whole
body for endpoints that don't wrap. None on any failure."""
qs = "&".join(f"{k}={v}" for k, v in params.items())
url = f"{cfg['OPENHOP_URL'].rstrip('/')}/api/{path}" + (f"?{qs}" if qs else "")
req = urllib.request.Request(url, headers={"X-API-Key": cfg.get("OPENHOP_TOKEN", "")})
try:
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
body = json.loads(resp.read().decode("utf-8"))
except (urllib.error.URLError, ValueError, OSError) as exc:
print(f"warn: {path}: {exc}", file=sys.stderr)
return None
if isinstance(body, dict) and "success" in body:
return body.get("data") if body.get("success") else None
return body
def num(v, nd=1):
try:
if v is None:
return None
return round(float(v), nd)
except (TypeError, ValueError):
return None
def text(v, limit=48):
if v is None:
return None
return str(v).replace("\x00", "")[:limit]
def build_snapshot(cfg):
now = time.time()
snap = {"schema": 1, "generated_at": int(now)}
# --- core stats (contains lots we must NOT forward; pick fields only) ---
stats = api_get(cfg, "stats") or {}
conf = stats.get("config") if isinstance(stats.get("config"), dict) else {}
radio = conf.get("radio") if isinstance(conf.get("radio"), dict) else {}
node_name = conf.get("node_name")
if not node_name or node_name == "Unknown":
rep = conf.get("repeater") if isinstance(conf.get("repeater"), dict) else {}
node_name = rep.get("node_name")
node_name = cfg.get("NODE_NAME") or (node_name if node_name and node_name != "Unknown" else None)
snap["node"] = {
"name": text(node_name or stats.get("site_name") or "Repeater"),
"version": text(stats.get("version"), 32),
"core_version": text(stats.get("core_version"), 32),
"uptime_seconds": int(stats.get("uptime_seconds") or 0),
"radio_status": text(stats.get("radio_status"), 24),
"radio": {
"freq_mhz": num((radio.get("frequency") or 0) / 1e6, 3) if radio.get("frequency") else None,
"bw_khz": num((radio.get("bandwidth") or 0) / 1e3, 1) if radio.get("bandwidth") else None,
"sf": radio.get("spreading_factor"),
"cr": radio.get("coding_rate"),
},
}
snap["now"] = {
"noise_floor_dbm": num(stats.get("noise_floor_dbm")),
"rx_per_hour": stats.get("rx_per_hour"),
"forwarded_per_hour": stats.get("forwarded_per_hour"),
"airtime_utilization_percent": num(stats.get("utilization_percent")),
"rx_total": stats.get("rx_count"),
"forwarded_total": stats.get("forwarded_count"),
"dropped_total": stats.get("dropped_count"),
}
# --- noise floor: 24 h stats + 15-minute buckets ---
nf_stats = (api_get(cfg, "noise_floor_stats", hours=24) or {}).get("stats") or {}
snap["noise_24h"] = {
"min": num(nf_stats.get("min_noise_floor")),
"avg": num(nf_stats.get("avg_noise_floor")),
"max": num(nf_stats.get("max_noise_floor")),
"buckets": [],
}
hist = (api_get(cfg, "noise_floor_history", hours=24) or {}).get("history") or []
buckets = {}
for row in hist:
try:
ts = float(row["timestamp"])
val = float(row["noise_floor_dbm"])
except (KeyError, TypeError, ValueError):
continue
b = int(ts // NOISE_BUCKET_SECS) * NOISE_BUCKET_SECS
buckets.setdefault(b, []).append(val)
snap["noise_24h"]["buckets"] = [
[b, num(sum(v) / len(v)), num(min(v)), num(max(v))] for b, v in sorted(buckets.items())
]
# --- packets over 24 h ---
ps = api_get(cfg, "packet_stats", hours=24) or {}
snap["packets_24h"] = {
"total": ps.get("total_packets"),
"forwarded": ps.get("transmitted_packets"),
"dropped": ps.get("dropped_packets"),
"avg_rssi": num(ps.get("avg_rssi")),
"avg_snr": num(ps.get("avg_snr")),
"types": [],
"drop_reasons": [
{"reason": text(r.get("reason"), 40), "count": r.get("count")}
for r in (ps.get("drop_reasons") or [])[:8]
if isinstance(r, dict)
],
}
# Packet types: use packet_stats (plain SQL counts). Some versions'
# packet_type_stats returns RRD counters, which are not per-day counts.
type_rows = []
for t in ps.get("packet_types") or []:
if not isinstance(t, dict):
continue
try:
code = int(t.get("type"))
except (TypeError, ValueError):
continue
type_rows.append({"name": PACKET_TYPES.get(code, f"Type {code}"), "count": t.get("count")})
if not type_rows:
pts = api_get(cfg, "packet_type_stats", hours=24)
if isinstance(pts, dict) and pts.get("data_source") == "sqlite" and isinstance(pts.get("packet_type_totals"), dict):
type_rows = [{"name": text(k, 40), "count": v} for k, v in pts["packet_type_totals"].items()]
type_rows = [t for t in type_rows if isinstance(t.get("count"), int) and t["count"] > 0]
snap["packets_24h"]["types"] = sorted(type_rows, key=lambda t: -t["count"])[:12]
crc = api_get(cfg, "crc_error_count", hours=24) or {}
snap["packets_24h"]["crc_errors"] = crc.get("crc_error_count")
# --- packets per hour: difference of rolling packet_stats windows ---
# packet_stats(hours=N) counts packets in the last N hours, so the hour
# that ended (h-1) hours ago is window(h) - window(h-1). Plain SQL counts,
# so this works the same on every openHop version.
windows = {0: {"total_packets": 0, "transmitted_packets": 0, "dropped_packets": 0}}
for h in range(1, 25):
w = ps if h == 24 else api_get(cfg, "packet_stats", hours=h)
windows[h] = w if isinstance(w, dict) else None
hourly = []
for h in range(24, 0, -1):
a, b = windows.get(h), windows.get(h - 1)
if not a or b is None:
continue
def d(k):
return max(0, int(a.get(k) or 0) - int(b.get(k) or 0))
hourly.append({"t": int(now - h * 3600), "rx": d("total_packets"), "tx": d("transmitted_packets"), "drop": d("dropped_packets")})
snap["hourly"] = hourly
# /stats' rx_per_hour counts a short in-memory list (it tops out around
# 50), so use the real count for the last 60 minutes instead.
if hourly:
snap["now"]["rx_per_hour"] = hourly[-1]["rx"]
snap["now"]["forwarded_per_hour"] = hourly[-1]["tx"]
# --- neighbours: names and signal only (no keys, no coordinates) ---
neighbors = stats.get("neighbors") if isinstance(stats.get("neighbors"), dict) else {}
rows = []
for info in neighbors.values():
if not isinstance(info, dict):
continue
last = info.get("last_seen")
try:
last = float(last)
except (TypeError, ValueError):
continue
if now - last > NEIGHBOR_DAYS * 86400:
continue
rows.append({
"name": text(info.get("node_name") or "(unnamed)"),
"type": text(info.get("contact_type") or ("Repeater" if info.get("is_repeater") else ""), 24),
"repeater": bool(info.get("is_repeater")),
"direct": bool(info.get("zero_hop")),
"last_seen": int(last),
"first_seen": int(float(info["first_seen"])) if info.get("first_seen") else None,
"rssi": num(info.get("rssi"), 0),
"snr": num(info.get("snr")),
"adverts": info.get("advert_count"),
})
rows.sort(key=lambda r: -r["last_seen"])
day = [r for r in rows if now - r["last_seen"] < 86400]
snap["neighbor_counts"] = {
"heard_7d": len(rows),
"heard_24h": len(day),
"direct_24h": sum(1 for r in day if r["direct"]),
}
snap["neighbors"] = rows[:NEIGHBOR_LIMIT]
# --- airtime over the last 24 h ---
# utilization_percent in /stats is "share of the TX duty-cycle budget used
# in the last 60 s" (default budget 3.6 s/min = 6 %), not share of time.
# Here we work out real percentages of the day instead.
duty = conf.get("duty_cycle") if isinstance(conf.get("duty_cycle"), dict) else {}
max_duty = num(duty.get("max_airtime_percent"), 2)
snap["now"]["duty_cycle_limit_percent"] = max_duty
try:
sf = int(radio.get("spreading_factor") or 9)
bw = int(radio.get("bandwidth") or 62500)
cr = int(radio.get("coding_rate") or 5)
pre = int(radio.get("preamble_length") or 17)
except (TypeError, ValueError):
sf, bw, cr, pre = 9, 62500, 5, 17
at = api_get(cfg, "airtime_chart_data", start_timestamp=int(now - 86400), end_timestamp=int(now),
bucket_seconds=3600, sf=sf, bw_hz=bw, cr=cr, preamble=pre) or {}
tx_ms = rx_only_ms = 0.0
for b in at.get("buckets") or []:
try:
tx_ms += float(b.get("tx_ms") or 0)
rx_only_ms += float(b.get("rx_ms") or 0)
except (TypeError, ValueError):
continue
day_ms = 86400 * 1000.0
if at.get("buckets") is not None:
# every forwarded packet was first heard, then sent again
heard_ms = rx_only_ms + tx_ms
snap["airtime_24h"] = {
"tx_percent": num(100 * tx_ms / day_ms, 2),
"heard_percent": num(100 * heard_ms / day_ms, 2),
"channel_percent": num(100 * (heard_ms + tx_ms) / day_ms, 2),
}
# --- host health (no hostnames, IPs or OS details) ---
hw = api_get(cfg, "hardware_stats") or {}
temps = hw.get("temperatures") if isinstance(hw.get("temperatures"), dict) else {}
cpu_temp = None
for k, v in temps.items():
if "cpu" in k.lower() or "soc" in k.lower() or cpu_temp is None:
cpu_temp = v
snap["host"] = {
"cpu_percent": num((hw.get("cpu") or {}).get("usage_percent")),
"memory_percent": num((hw.get("memory") or {}).get("usage_percent")),
"disk_percent": num((hw.get("disk") or {}).get("usage_percent")),
"temp_c": num(cpu_temp),
}
return snap
def post(cfg, snap):
data = json.dumps(snap, separators=(",", ":")).encode("utf-8")
req = urllib.request.Request(
cfg["SITE_URL"],
data=data,
method="POST",
headers={
"Content-Type": "application/json",
"X-Feed-Key": cfg["SITE_KEY"],
"User-Agent": "repeater-status-push/1",
},
)
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
return resp.status, resp.read().decode("utf-8")[:200]
def main():
cfg = load_env(ENV_FILE)
missing = [k for k in ("OPENHOP_TOKEN", "SITE_URL", "SITE_KEY") if not cfg.get(k)]
if missing:
print(f"error: missing {', '.join(missing)} in {ENV_FILE}", file=sys.stderr)
return 2
# If openHop itself isn't answering (still starting after a reboot, or
# stopped), send nothing: the page then shows "Delayed"/"Offline" instead
# of a snapshot full of zeros.
if not api_get(cfg, "stats"):
print("error: openHop is not answering; nothing sent", file=sys.stderr)
return 1
snap = build_snapshot(cfg)
if "--dry-run" in sys.argv:
print(json.dumps(snap, indent=2))
return 0
try:
status, body = post(cfg, snap)
except urllib.error.HTTPError as exc:
print(f"error: website returned {exc.code}: {exc.read().decode('utf-8', 'replace')[:200]}", file=sys.stderr)
return 1
except (urllib.error.URLError, OSError) as exc:
print(f"error: could not reach website: {exc}", file=sys.stderr)
return 1
if "--verbose" in sys.argv:
print(f"ok {status}: {body}")
return 0
if __name__ == "__main__":
sys.exit(main())
install.sh · The installer, 59 lines
Run once on the Pi. Saves your token and feed key in a private file, tests both ends, and sets up the 5-minute schedule.
#!/bin/bash
# install.sh - set up the repeater status feed on this Pi.
# Free to use and adapt.
# Run from the folder that holds repeater_status_push.py:
# bash install.sh
set -euo pipefail
DEST="$HOME/repeater-status"
ENV_FILE="$HOME/.repeater-status.env"
SCRIPT="$DEST/repeater_status_push.py"
here="$(cd "$(dirname "$0")" && pwd)"
mkdir -p "$DEST"
cp "$here/repeater_status_push.py" "$SCRIPT"
chmod 755 "$SCRIPT"
if [[ -f "$ENV_FILE" ]]; then
echo "Keeping existing settings in $ENV_FILE"
else
echo
echo "Your website address (for example https://example.com):"
read -r SITE_BASE
SITE_URL="${SITE_BASE%/}/wp-json/repeater-status/v1/repeater"
echo "Paste the openHop API token (input hidden), then press Enter:"
read -rs OPENHOP_TOKEN; echo
echo "Paste the website feed key from WordPress > Settings > Repeater Feed (input hidden):"
read -rs SITE_KEY; echo
umask 077
cat > "$ENV_FILE" <<EOF
OPENHOP_URL=http://127.0.0.1:8000
OPENHOP_TOKEN=$OPENHOP_TOKEN
SITE_URL=$SITE_URL
SITE_KEY=$SITE_KEY
EOF
chmod 600 "$ENV_FILE"
echo "Saved settings to $ENV_FILE (readable only by you)"
fi
echo
echo "Test 1: reading openHop..."
if ! /usr/bin/python3 "$SCRIPT" --dry-run > /tmp/repeater-status-dryrun.json; then
echo "Could not build a snapshot. Check the openHop token in $ENV_FILE"; exit 1
fi
python3 - <<'PY'
import json
s = json.load(open("/tmp/repeater-status-dryrun.json"))
print(f" node: {s['node']['name']} noise: {s['now']['noise_floor_dbm']} dBm "
f"packets 24h: {s['packets_24h']['total']} neighbours: {len(s['neighbors'])}")
PY
echo "Test 2: sending to the website..."
/usr/bin/python3 "$SCRIPT" --verbose
CRON_LINE="*/5 * * * * /usr/bin/python3 $SCRIPT 2>> $DEST/errors.log"
{ crontab -l 2>/dev/null | grep -v "repeater_status_push.py" || true; echo "$CRON_LINE"; } | crontab -
echo
echo "Done. The repeater page will update every 5 minutes."
echo "Errors, if any, go to $DEST/errors.log"
repeater-status.php · The WordPress plugin, 312 lines
Save as repeater-status/repeater-status.php, zip the folder, and upload it under Plugins. Then put [repeater_status] on any page.
<?php
/**
* Plugin Name: openHop Repeater Status
* Description: Live public status page for an openHop MeshCore repeater. The repeater pushes a snapshot every few minutes; visitors see it with the [repeater_status] shortcode.
* Version: 1.0.2
* License: GPL-2.0-or-later
* Requires at least: 6.0
* Requires PHP: 7.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'OHRS_VERSION', '1.0.2' );
define( 'OHRS_MAX_BYTES', 400000 );
/* ------------------------------------------------------------------ */
/* Setup */
/* ------------------------------------------------------------------ */
register_activation_hook( __FILE__, 'ohrs_activate' );
function ohrs_activate() {
if ( ! get_option( 'ohrs_feed_key' ) ) {
add_option( 'ohrs_feed_key', ohrs_new_key(), '', 'no' );
}
}
function ohrs_new_key() {
return wp_generate_password( 48, false, false );
}
/* ------------------------------------------------------------------ */
/* REST API: POST (repeater pushes) and GET (page reads) */
/* ------------------------------------------------------------------ */
add_action( 'rest_api_init', function () {
register_rest_route(
'repeater-status/v1',
'/repeater',
array(
array(
'methods' => 'POST',
'callback' => 'ohrs_receive',
'permission_callback' => 'ohrs_check_key',
),
array(
'methods' => 'GET',
'callback' => 'ohrs_serve',
'permission_callback' => '__return_true',
),
)
);
} );
function ohrs_check_key( WP_REST_Request $request ) {
$expected = (string) get_option( 'ohrs_feed_key', '' );
$given = (string) $request->get_header( 'x_feed_key' );
if ( '' === $expected || '' === $given || ! hash_equals( $expected, $given ) ) {
return new WP_Error( 'ohrs_forbidden', 'Bad or missing feed key.', array( 'status' => 403 ) );
}
return true;
}
function ohrs_receive( WP_REST_Request $request ) {
$body = $request->get_body();
if ( strlen( $body ) > OHRS_MAX_BYTES ) {
return new WP_Error( 'ohrs_too_big', 'Snapshot too large.', array( 'status' => 413 ) );
}
$data = json_decode( $body, true );
if ( ! is_array( $data ) || ( $data['schema'] ?? null ) !== 1 ) {
return new WP_Error( 'ohrs_bad_json', 'Expected a schema 1 snapshot.', array( 'status' => 400 ) );
}
update_option( 'ohrs_snapshot', wp_json_encode( $data ), 'no' );
update_option( 'ohrs_received', time(), 'no' );
return rest_ensure_response( array( 'ok' => true, 'received_at' => time() ) );
}
function ohrs_serve() {
$raw = get_option( 'ohrs_snapshot', '' );
$snapshot = $raw ? json_decode( $raw, true ) : null;
$response = rest_ensure_response(
array(
'received_at' => (int) get_option( 'ohrs_received', 0 ),
'server_time' => time(),
'snapshot' => $snapshot,
)
);
$response->header( 'Cache-Control', 'no-store, max-age=0' );
return $response;
}
/* ------------------------------------------------------------------ */
/* Settings page: Settings > Repeater Feed */
/* ------------------------------------------------------------------ */
add_action( 'admin_menu', function () {
add_options_page( 'Repeater Feed', 'Repeater Feed', 'manage_options', 'repeater-status', 'ohrs_settings_page' );
} );
function ohrs_settings_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
if ( isset( $_POST['ohrs_regen'] ) && check_admin_referer( 'ohrs_regen' ) ) {
update_option( 'ohrs_feed_key', ohrs_new_key(), 'no' );
echo '<div class="notice notice-warning"><p>New feed key created. Update SITE_KEY on the Pi or the page will stop updating.</p></div>';
}
$key = (string) get_option( 'ohrs_feed_key', '' );
$received = (int) get_option( 'ohrs_received', 0 );
?>
<div class="wrap">
<h1>Repeater Feed</h1>
<p>Your repeater sends its status here every few minutes. Put <code>[repeater_status]</code> on any page to show it.</p>
<table class="form-table" role="presentation">
<tr>
<th scope="row">Feed URL</th>
<td><code><?php echo esc_html( rest_url( 'repeater-status/v1/repeater' ) ); ?></code></td>
</tr>
<tr>
<th scope="row">Feed key</th>
<td>
<input type="text" class="regular-text code" readonly value="<?php echo esc_attr( $key ); ?>" onclick="this.select()" style="width:32em">
<p class="description">This goes in SITE_KEY on the Pi. Keep it private: anyone with it can change what the page shows.</p>
</td>
</tr>
<tr>
<th scope="row">Last update</th>
<td><?php echo $received ? esc_html( human_time_diff( $received ) . ' ago (' . wp_date( 'M j, g:i a', $received ) . ')' ) : 'Nothing received yet.'; ?></td>
</tr>
</table>
<form method="post">
<?php wp_nonce_field( 'ohrs_regen' ); ?>
<p><button class="button" name="ohrs_regen" value="1" onclick="return confirm('Make a new key? The Pi stops updating until you change SITE_KEY there.');">Make a new key</button></p>
</form>
</div>
<?php
}
/* ------------------------------------------------------------------ */
/* Shortcode: [repeater_status] */
/* ------------------------------------------------------------------ */
add_shortcode( 'repeater_status', 'ohrs_shortcode' );
function ohrs_shortcode() {
// CSS and JS go through the script/style queue, not the post content,
// so content filters (texturize, autop, entity encoding) can't touch them.
if ( ! wp_script_is( 'repeater-status', 'enqueued' ) ) {
wp_register_style( 'repeater-status', false, array(), OHRS_VERSION );
wp_enqueue_style( 'repeater-status' );
wp_add_inline_style( 'repeater-status', ohrs_css() );
wp_register_script( 'repeater-status', false, array(), OHRS_VERSION, true );
wp_enqueue_script( 'repeater-status' );
wp_add_inline_script( 'repeater-status', ohrs_js() );
}
return '<div class="ohrs" data-endpoint="' . esc_url( rest_url( 'repeater-status/v1/repeater' ) ) . '"><p class="ohrs-loading">Loading repeater status…</p></div>';
}
function ohrs_css() {
return <<<'CSS'
.ohrs{--rs-ink:currentColor;--rs-muted:color-mix(in srgb,currentColor 58%,transparent);--rs-line:color-mix(in srgb,currentColor 14%,transparent);--rs-card:color-mix(in srgb,currentColor 3.5%,transparent);--rs-a:#2a6fdb;--rs-b:#e0812a;--rs-ok:#1f9d55;--rs-warn:#d69e2e;--rs-bad:#d64545;font-variant-numeric:tabular-nums}
.ohrs *{box-sizing:border-box}
.ohrs-head{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:.5rem 1rem;margin-bottom:1.25rem}
.ohrs-head h2{margin:0;font-size:1.6rem}
.ohrs-pill{display:inline-flex;align-items:center;gap:.45em;font-size:.85rem;padding:.25em .75em;border-radius:999px;border:1px solid var(--rs-line)}
.ohrs-pill i{width:.6em;height:.6em;border-radius:50%;background:var(--rs-c,var(--rs-ok));display:inline-block}
.ohrs-sub{color:var(--rs-muted);font-size:.9rem;margin:.25rem 0 0}
.ohrs-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.75rem;margin:0 0 1.5rem}
.ohrs-card{background:var(--rs-card);border:1px solid var(--rs-line);border-radius:10px;padding:.85rem 1rem}
.ohrs-card .k{font-size:.78rem;text-transform:uppercase;letter-spacing:.06em;color:var(--rs-muted)}
.ohrs-card .v{font-size:1.7rem;font-weight:600;line-height:1.2;margin:.2rem 0}
.ohrs-card .v small{font-size:.9rem;font-weight:400;color:var(--rs-muted)}
.ohrs-card .s{font-size:.82rem;color:var(--rs-muted)}
.ohrs-panel{border:1px solid var(--rs-line);border-radius:10px;padding:1rem 1rem .75rem;margin:0 0 1.25rem}
.ohrs-panel h3{margin:0 0 .15rem;font-size:1.05rem}
.ohrs-panel .note{margin:0 0 .6rem;font-size:.85rem;color:var(--rs-muted)}
.ohrs-grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:1.25rem}
.ohrs svg{display:block;width:100%;height:auto;overflow:visible}
.ohrs svg text{fill:var(--rs-muted);font-size:11px}
.ohrs-legend{display:flex;gap:1rem;font-size:.82rem;color:var(--rs-muted);margin:.35rem 0 0}
.ohrs-legend span:before{content:"";display:inline-block;width:.8em;height:.8em;border-radius:2px;margin-right:.35em;vertical-align:-1px;background:var(--sw)}
.ohrs-bars{list-style:none;margin:0;padding:0}
.ohrs-bars li{display:grid;grid-template-columns:minmax(0,11rem) 1fr 3.5rem;gap:.6rem;align-items:center;font-size:.85rem;margin:.3rem 0}
.ohrs-bars .lbl{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.ohrs-bars .trk{display:block;height:.6rem;background:var(--rs-line);border-radius:3px;overflow:hidden}
.ohrs-bars .fil{display:block;height:100%;background:var(--rs-a)}
.ohrs-bars .num{text-align:right;color:var(--rs-muted)}
.ohrs-tablewrap{overflow-x:auto}
.ohrs table{width:100%;border-collapse:collapse;font-size:.88rem}
.ohrs th,.ohrs td{text-align:left;padding:.45rem .5rem;border-bottom:1px solid var(--rs-line);white-space:nowrap}
.ohrs th{font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;color:var(--rs-muted);font-weight:600}
.ohrs td.n{text-align:right}
.ohrs th.n{text-align:right}
.ohrs td.name{white-space:normal;min-width:10rem;font-weight:500}
.ohrs .tag{font-size:.72rem;padding:.1em .5em;border-radius:4px;border:1px solid var(--rs-line);color:var(--rs-muted)}
.ohrs .tag.d{border-color:var(--rs-ok);color:var(--rs-ok)}
.ohrs-foot{font-size:.8rem;color:var(--rs-muted);margin-top:.5rem}
.ohrs-more{margin-top:.6rem;font:inherit;font-size:.85rem;background:none;border:1px solid var(--rs-line);border-radius:6px;padding:.35rem .8rem;cursor:pointer;color:inherit}
CSS;
}
function ohrs_js() {
return <<<'JS'
(function(){
"use strict";
var NS="http://www.w3.org/2000/svg";
function el(tag,attrs,kids){var e=document.createElement(tag);if(attrs)for(var k in attrs){if(k==="text")e.textContent=attrs[k];else if(k==="cls")e.className=attrs[k];else e.setAttribute(k,attrs[k]);}(kids||[]).forEach(function(c){if(c!=null)e.appendChild(typeof c==="string"?document.createTextNode(c):c);});return e;}
function sv(tag,attrs){var e=document.createElementNS(NS,tag);for(var k in attrs){if(k==="text")e.textContent=attrs[k];else e.setAttribute(k,attrs[k]);}return e;}
function fmt(n,d){if(n===null||n===undefined||isNaN(n))return"\u2013";return Number(n).toLocaleString(undefined,{maximumFractionDigits:d===undefined?0:d,minimumFractionDigits:d||0});}
function ago(sec){if(sec<0)sec=0;if(sec<90)return"just now";var m=Math.round(sec/60);if(m<60)return m+" min ago";var h=Math.round(m/60);if(h<48)return h+" h ago";return Math.round(h/24)+" days ago";}
function dur(sec){sec=Math.max(0,sec|0);var d=Math.floor(sec/86400),h=Math.floor(sec%86400/3600),m=Math.floor(sec%3600/60);return d?d+"d "+h+"h":h?h+"h "+m+"m":m+"m";}
function hourLbl(ts){var d=new Date(ts*1000);return d.toLocaleTimeString(undefined,{hour:"numeric"});}
function card(k,v,unit,s){return el("div",{cls:"ohrs-card"},[el("div",{cls:"k",text:k}),el("div",{cls:"v"},[String(v),unit?el("small",{text:" "+unit}):null]),s?el("div",{cls:"s",text:s}):null]);}
function panel(title,note,body){return el("section",{cls:"ohrs-panel"},[el("h3",{text:title}),note?el("p",{cls:"note",text:note}):null].concat(body));}
function noiseChart(b){
var W=640,H=230,L=44,R=10,T=22,B=26;
var svg=sv("svg",{viewBox:"0 0 "+W+" "+H,role:"img","aria-label":"Noise floor over the last 24 hours"});
if(!b.length){svg.appendChild(sv("text",{x:L,y:H/2,text:"No noise floor data yet"}));return svg;}
var t0=b[0][0],t1=b[b.length-1][0];if(t1===t0)t1=t0+900;
var lo=Infinity,hi=-Infinity;b.forEach(function(r){lo=Math.min(lo,r[2]);hi=Math.max(hi,r[3]);});
lo=Math.floor((lo-2)/5)*5;hi=Math.ceil((hi+2)/5)*5;if(hi-lo<10)hi=lo+10;
function x(t){return L+(t-t0)/(t1-t0)*(W-L-R);}function y(v){return T+(hi-v)/(hi-lo)*(H-T-B);}
for(var v=lo;v<=hi;v+=5){if((hi-lo)>30&&v%10)continue;svg.appendChild(sv("line",{x1:L,x2:W-R,y1:y(v),y2:y(v),stroke:"currentColor","stroke-opacity":.1}));svg.appendChild(sv("text",{x:L-6,y:y(v)+4,"text-anchor":"end",text:v}));}
var band="",line="";b.forEach(function(r,i){band+=(i?"L":"M")+x(r[0]).toFixed(1)+","+y(r[3]).toFixed(1);line+=(i?"L":"M")+x(r[0]).toFixed(1)+","+y(r[1]).toFixed(1);});
for(var i=b.length-1;i>=0;i--)band+="L"+x(b[i][0]).toFixed(1)+","+y(b[i][2]).toFixed(1);
svg.appendChild(sv("path",{d:band+"Z",fill:"var(--rs-a)","fill-opacity":.15}));
svg.appendChild(sv("path",{d:line,fill:"none",stroke:"var(--rs-a)","stroke-width":2,"stroke-linejoin":"round"}));
var step=Math.max(3600*3,Math.ceil((t1-t0)/6/3600)*3600);for(var t=Math.ceil(t0/step)*step;t<=t1;t+=step){svg.appendChild(sv("text",{x:x(t),y:H-6,"text-anchor":"middle",text:hourLbl(t)}));}
svg.appendChild(sv("text",{x:L-6,y:9,"text-anchor":"end",text:"dBm"}));
return svg;
}
function hourlyChart(rows){
var W=640,H=230,L=44,R=10,T=22,B=26;
var svg=sv("svg",{viewBox:"0 0 "+W+" "+H,role:"img","aria-label":"Packets per hour"});
if(!rows.length){svg.appendChild(sv("text",{x:L,y:H/2,text:"No hourly data yet"}));return svg;}
var mx=1;rows.forEach(function(r){mx=Math.max(mx,r.rx,r.tx);});
var mag=Math.pow(10,Math.floor(Math.log10(mx))),top=mag*10;[1,1.2,1.5,2,2.5,3,4,5,6,8,10].some(function(f){if(f*mag>=mx){top=f*mag;return true;}});
function y(v){return T+(1-v/top)*(H-T-B);}
[0,.5,1].forEach(function(f){var v=top*f;svg.appendChild(sv("line",{x1:L,x2:W-R,y1:y(v),y2:y(v),stroke:"currentColor","stroke-opacity":.1}));svg.appendChild(sv("text",{x:L-6,y:y(v)+4,"text-anchor":"end",text:fmt(v)}));});
var slot=(W-L-R)/rows.length,bw=Math.max(2,slot*.36);
rows.forEach(function(r,i){var x0=L+i*slot+slot*.12;
var a=sv("rect",{x:x0,y:y(r.rx),width:bw,height:Math.max(0,y(0)-y(r.rx)),fill:"var(--rs-a)",rx:1.5});a.appendChild(sv("title",{text:hourLbl(r.t)+": "+r.rx+" received"}));svg.appendChild(a);
var c=sv("rect",{x:x0+bw+1,y:y(r.tx),width:bw,height:Math.max(0,y(0)-y(r.tx)),fill:"var(--rs-b)",rx:1.5});c.appendChild(sv("title",{text:hourLbl(r.t)+": "+r.tx+" forwarded"}));svg.appendChild(c);
if(i%4===0)svg.appendChild(sv("text",{x:L+i*slot+slot/2,y:H-6,"text-anchor":"middle",text:hourLbl(r.t)}));});
return svg;
}
function typeBars(types,color){
if(!types||!types.length)return el("p",{cls:"note",text:"Nothing in the last 24 hours."});
var mx=Math.max.apply(null,types.map(function(t){return t.count;}));
return el("ul",{cls:"ohrs-bars"},types.map(function(t){var name=String(t.name||"").replace(/\s*\([A-Z_]+\)$/,"");
return el("li",null,[el("span",{cls:"lbl",title:t.name,text:name}),el("span",{cls:"trk"},[el("span",{cls:"fil",style:"width:"+(100*t.count/mx).toFixed(1)+"%"+(color?";background:"+color:"")})]),el("span",{cls:"num",text:fmt(t.count)})]);}));
}
function neighborTable(list,now){
if(!list||!list.length)return [el("p",{cls:"note",text:"No neighbors heard in the last week."})];
var head=el("tr",null,["Name","Type","Path","Last heard","SNR","RSSI"].map(function(h,i){return el("th",{cls:i>3?"n":"",text:h});}));
var tbody=el("tbody");var shown=0,LIMIT=25;
function row(n){return el("tr",null,[el("td",{cls:"name",text:n.name||"(unnamed)"}),el("td",{text:n.type||(n.repeater?"Repeater":"")}),el("td",null,[el("span",{cls:"tag"+(n.direct?" d":""),text:n.direct?"direct":"via mesh"})]),el("td",{text:ago(now-n.last_seen)}),el("td",{cls:"n",text:n.snr==null?"\u2013":fmt(n.snr,1)+" dB"}),el("td",{cls:"n",text:n.rssi==null?"\u2013":fmt(n.rssi)+" dBm"})]);}
function more(){list.slice(shown,shown+LIMIT).forEach(function(n){tbody.appendChild(row(n));});shown=Math.min(list.length,shown+LIMIT);btn.style.display=shown<list.length?"":"none";btn.textContent="Show more ("+(list.length-shown)+" left)";}
var btn=el("button",{cls:"ohrs-more",type:"button"});btn.addEventListener("click",more);
var wrap=el("div",{cls:"ohrs-tablewrap"},[el("table",null,[el("thead",null,[head]),tbody])]);
more();return [wrap,btn];
}
function render(root,payload){
var s=payload.snapshot,now=payload.server_time||Math.floor(Date.now()/1000);
root.textContent="";
if(!s){root.appendChild(el("p",{text:"The repeater hasn't reported in yet."}));return;}
var age=now-(payload.received_at||s.generated_at);
var state=age<900?["Online","var(--rs-ok)"]:age<3600?["Delayed","var(--rs-warn)"]:["Offline","var(--rs-bad)"];
var node=s.node||{},r=node.radio||{},nw=s.now||{},nz=s.noise_24h||{},pk=s.packets_24h||{},host=s.host||{};
var nb=s.neighbors||[];var nc=s.neighbor_counts||{};var nb24=nb.filter(function(n){return now-n.last_seen<86400;});var heard24=nc.heard_24h!=null?nc.heard_24h:nb24.length;var direct=nc.direct_24h!=null?nc.direct_24h:nb24.filter(function(n){return n.direct;}).length;var heard7=nc.heard_7d!=null?nc.heard_7d:nb.length;
var radioBits=[r.freq_mhz?fmt(r.freq_mhz,3)+" MHz":null,r.bw_khz?fmt(r.bw_khz,1)+" kHz":null,r.sf?"SF"+r.sf:null,r.cr?"CR"+r.cr:null].filter(Boolean).join(" \u00b7 ");
root.appendChild(el("div",{cls:"ohrs-head"},[
el("div",null,[el("h2",{text:node.name||"Repeater"}),el("p",{cls:"ohrs-sub",text:["MeshCore repeater (openHop "+(node.version||"?")+")",radioBits].filter(Boolean).join(" \u00b7 ")})]),
el("span",{cls:"ohrs-pill",style:"--rs-c:"+state[1]},[el("i"),state[0]+" \u00b7 updated "+ago(age)])]));
root.appendChild(el("div",{cls:"ohrs-cards"},[
card("Noise floor",fmt(nw.noise_floor_dbm,1),"dBm","24 h avg "+fmt(nz.avg,1)+" \u00b7 range "+fmt(nz.min,0)+" to "+fmt(nz.max,0)),
card("Packets heard",fmt(pk.total),"","last 24 h \u00b7 "+fmt(nw.rx_per_hour)+" in the last hour"),
card("Forwarded",fmt(pk.forwarded),"","last 24 h \u00b7 "+fmt(pk.dropped)+" not repeated"),
card("Neighbors",fmt(heard24),"","heard in 24 h \u00b7 "+fmt(direct)+" direct"),
(s.airtime_24h?card("Channel busy",fmt(s.airtime_24h.channel_percent,1),"%","of the last 24 h \u00b7 this repeater transmitting "+fmt(s.airtime_24h.tx_percent,1)+"%"):card("TX budget used",fmt(nw.airtime_utilization_percent,1),"%","of the duty-cycle limit, last minute")),
card("Uptime",dur(node.uptime_seconds),"",host.temp_c!=null?"Pi at "+fmt(host.temp_c,0)+" \u00b0C \u00b7 CPU "+fmt(host.cpu_percent,0)+"%":"")
]));
root.appendChild(el("div",{cls:"ohrs-grid2"},[
panel("Noise floor, last 24 hours","Line is the 15-minute average; the band shows the lowest and highest readings. Lower is quieter.",[noiseChart(nz.buckets||[])]),
panel("Packets per hour","Everything the repeater heard, and what it passed on.",[hourlyChart(s.hourly||[]),el("div",{cls:"ohrs-legend"},[el("span",{style:"--sw:var(--rs-a)",text:"Received"}),el("span",{style:"--sw:var(--rs-b)",text:"Forwarded"})])])
]));
var drops=(pk.drop_reasons||[]).map(function(d){return {name:String(d.reason||"other").replace(/_/g," ").replace(/^./,function(c){return c.toUpperCase();}),count:d.count};});
root.appendChild(el("div",{cls:"ohrs-grid2"},[
panel("Packet types, last 24 hours",(pk.avg_snr!=null?"Average SNR "+fmt(pk.avg_snr,1)+" dB, RSSI "+fmt(pk.avg_rssi,0)+" dBm":"")+(pk.crc_errors!=null?" \u00b7 "+fmt(pk.crc_errors)+" CRC errors":""),[typeBars(pk.types)]),
panel("Why packets weren't repeated",(drops.length&&/dup/i.test(drops[0].name))?"Mostly duplicates: another repeater already passed them on, which is normal on a busy mesh.":"Packets the repeater heard but chose not to pass on.",[typeBars(drops,"var(--rs-b)")])
]));
root.appendChild(panel("Neighbors",fmt(heard7)+" nodes heard in the last 7 days"+(heard7>nb.length?" (showing the "+nb.length+" most recent)":"")+", most recent first. \u201cDirect\u201d means heard without another hop.",neighborTable(nb,now)));
root.appendChild(el("p",{cls:"ohrs-foot",text:"Data comes straight from the repeater every 5 minutes. Locations are intentionally not shown."}));
}
function load(root){
var url=root.getAttribute("data-endpoint");url+=(url.indexOf("?")<0?"?":"&")+"t="+Date.now();
fetch(url,{credentials:"omit",cache:"no-store"}).then(function(r){return r.json();}).then(function(p){render(root,p);}).catch(function(){if(!root.querySelector(".ohrs-head"))root.textContent="Couldn't load repeater status right now.";});
}
function init(){document.querySelectorAll(".ohrs").forEach(function(root){load(root);setInterval(function(){if(!document.hidden)load(root);},5*60*1000);});}
if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",init);else init();
})();
JS;
}