Fix Edge heartbeat recovery after restart

This commit is contained in:
Andrei Smaliak 2026-10-13 06:13:32 +02:00
parent b06248fa9f
commit 2eeffa8b6f
12 changed files with 412 additions and 30 deletions

View File

@ -0,0 +1,5 @@
# Edge Console 3.1.23
- Adds a machine-readable runtime profile built from the Console's existing display, network, radio and Modbus diagnostics.
- Publishes explicit HDMI, Wi-Fi, Ethernet, Radio and RS485 states without introducing another daemon.
- Keeps the Console UI and MQTT health publisher on the same diagnostic sources.

View File

@ -0,0 +1,11 @@
# stage_mqtt 1.0.3 — independent Edge runtime heartbeat
Release date: 2026-10-12.
- Reuse the existing MQTT health timer to publish Edge OS reachability independently from It-screenClient.
- Publish a retained, device-scoped heartbeat every 15 seconds with a 45-second freshness contract.
- Include boot ID, uptime, Console status and the separate `itscreen-x11.service` state.
- Use the same canonical Edge identity in the generated bridge allow-list and heartbeat publisher.
- Deliver the heartbeat through the existing environment-scoped MQTT bridge with QoS 1.
Validation: MQTT installer contract tests; the existing legacy heartbeat was also verified live on DEV `g-box-8e6af561` with It-screenClient stopped.

View File

@ -0,0 +1,6 @@
# stage_mqtt 1.0.4 — unified Edge runtime profile
- Extends the retained Edge heartbeat contract to schema version 3.
- Includes Console-owned RS485, screen, radio, Wi-Fi and Ethernet states in the existing device-scoped health topic.
- Preserves independent Edge reachability and IT-Screen client service states.
- Starts the heartbeat schedule relative to timer activation and restarts the timer after installation, preventing an elapsed boot timer from leaving a running Edge marked unavailable.

View File

@ -8,13 +8,13 @@
"version": "1.0.0"
},
"stage_mqtt": {
"version": "1.0.2"
"version": "1.0.4"
},
"stage_z2m": {
"version": "1.0.1"
},
"stage_ui": {
"version": "3.1.22"
"version": "3.1.23"
},
"stage_avahi": {
"version": "1.0.0"

View File

@ -431,7 +431,7 @@ __TLS__
cat >>"$BRIDGE_CONF" <<__MAP__
# IOMATEX v1 edge contract: this edge publishes only its health and receives only its commands.
topic ${BRIDGE_BASE_TOPIC}/health/${DEVICE_ID} out 0 "" ""
topic ${BRIDGE_BASE_TOPIC}/health/${DEVICE_ID} out 1 "" ""
topic ${BRIDGE_BASE_TOPIC}/command/${DEVICE_ID}/# in 0 "" ""
# Legacy iomatex contract: device telemetry OUT.
@ -792,6 +792,8 @@ cat >"$HEALTH_SH" <<'__IOMATEX_HEALTH_SH__'
set -euo pipefail
ENV_FILE="/etc/iomatex/mqtt_bridge.env"
STATE_FILE="/run/iomatex-mqtt-health.state"
started_at_ms="$(date +%s%3N)"
get_kv(){
local k="$1" line
@ -799,22 +801,118 @@ get_kv(){
[[ -n "$line" ]] && echo "${line#${k}=}" || echo ""
}
resolve_edge_name(){
local value=""
if [[ -f /userdata/device-id ]]; then
value="$(tr -d ' \n\r' < /userdata/device-id 2>/dev/null || true)"
fi
if printf '%s\n' "${value:-}" | grep -Eq '^g-box-[a-f0-9]{8}$'; then
printf '%s\n' "$value"
return 0
fi
value="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
value="${value%%.*}"
[[ -n "${value:-}" ]] && printf '%s\n' "$value" || printf '%s\n' "unknown-edge"
}
unit_property(){
systemctl show "$1" -p "$2" --value 2>/dev/null | tr -d '\n\r' || true
}
if ! systemctl is-active --quiet mosquitto; then
systemctl start mosquitto || systemctl restart mosquitto || true
fi
h="$(if [[ -f /userdata/device-id ]]; then tr -d ' \n\r' < /userdata/device-id; else hostname -s 2>/dev/null || hostname; fi)"
h="$(resolve_edge_name)"
BRIDGE_BASE_TOPIC="$(get_kv BRIDGE_BASE_TOPIC)"; : "${BRIDGE_BASE_TOPIC:=v1/edge}"
boot_id="$(tr -d '\n\r' < /proc/sys/kernel/random/boot_id 2>/dev/null || true)"
uptime_seconds="$(cut -d. -f1 /proc/uptime 2>/dev/null || echo 0)"
client_active_state="$(unit_property itscreen-x11.service ActiveState)"; : "${client_active_state:=unknown}"
client_sub_state="$(unit_property itscreen-x11.service SubState)"; : "${client_sub_state:=unknown}"
console_active_state="$(unit_property iomatex-console.service ActiveState)"; : "${console_active_state:=unknown}"
console_version="$(sed -n 's/^UI_VERSION = "\(.*\)"/\1/p' /opt/iomatex-console/backend/app.py 2>/dev/null | head -n1)"
ts_main="$(date -u '+%F, %T UTC')"
tz_off="$(date '+%z')"
tz_fmt="(${tz_off:0:3})"
time_str="${ts_main}, time zone ${tz_fmt}"
runtime_profile="$(python3 /opt/iomatex-console/backend/app.py --runtime-profile-json 2>/dev/null || true)"
observed_at_ms="$(date +%s%3N)"
payload="{\"status\":\"ok\",\"time\":\"${time_str}\",\"hostname\":\"${h}\"}"
payload="$(
EDGE_DEVICE_ID="$h" \
EDGE_OBSERVED_AT_MS="$observed_at_ms" \
EDGE_BOOT_ID="$boot_id" \
EDGE_UPTIME_SECONDS="$uptime_seconds" \
EDGE_CLIENT_ACTIVE_STATE="$client_active_state" \
EDGE_CLIENT_SUB_STATE="$client_sub_state" \
EDGE_CONSOLE_ACTIVE_STATE="$console_active_state" \
EDGE_CONSOLE_VERSION="$console_version" \
EDGE_RUNTIME_PROFILE="$runtime_profile" \
python3 - <<'__IOMATEX_HEALTH_JSON__'
import json
import os
try:
profile = json.loads(os.environ.get("EDGE_RUNTIME_PROFILE") or "{}")
except (TypeError, ValueError):
profile = {}
interfaces = profile.get("interfaces")
if not isinstance(interfaces, dict):
interfaces = {
key: {"state": "unknown"}
for key in ("rs485", "screen", "radio", "wifi", "ethernet")
}
payload = {
"schema_version": 3,
"state": "reachable",
"device_id": os.environ["EDGE_DEVICE_ID"],
"observed_at_ms": int(os.environ["EDGE_OBSERVED_AT_MS"]),
"valid_for_ms": 45000,
"boot_id": os.environ.get("EDGE_BOOT_ID", ""),
"uptime_seconds": int(os.environ.get("EDGE_UPTIME_SECONDS") or 0),
"client": {
"unit": "itscreen-x11.service",
"active_state": os.environ.get("EDGE_CLIENT_ACTIVE_STATE", "unknown"),
"sub_state": os.environ.get("EDGE_CLIENT_SUB_STATE", "unknown"),
},
"console": {
"active_state": os.environ.get("EDGE_CONSOLE_ACTIVE_STATE", "unknown"),
"version": os.environ.get("EDGE_CONSOLE_VERSION", ""),
},
"interfaces": interfaces,
}
print(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
__IOMATEX_HEALTH_JSON__
)"
topic="${BRIDGE_BASE_TOPIC}/health/${h}"
mosquitto_pub -h 127.0.0.1 -p 1883 -t "${topic}" -m "${payload}" >/dev/null 2>&1 || true
mosquitto_pub -h 127.0.0.1 -p 1883 -q 1 -r -t "${topic}" -m "${payload}"
finished_at_ms="$(date +%s%3N)"
duration_ms="$((finished_at_ms - started_at_ms))"
interface_summary="$(
EDGE_RUNTIME_PROFILE="$runtime_profile" python3 - <<'__IOMATEX_HEALTH_SUMMARY__'
import json
import os
try:
profile = json.loads(os.environ.get("EDGE_RUNTIME_PROFILE") or "{}")
except (TypeError, ValueError):
profile = {}
interfaces = profile.get("interfaces") or {}
print(",".join(
f"{name}={str((interfaces.get(name) or {}).get('state') or 'unknown')}"
for name in ("rs485", "screen", "radio", "wifi", "ethernet")
))
__IOMATEX_HEALTH_SUMMARY__
)"
previous_summary="$(cat "$STATE_FILE" 2>/dev/null || true)"
if [[ "$interface_summary" != "$previous_summary" ]]; then
printf '%s\n' "$interface_summary" >"$STATE_FILE"
echo "Health state changed: device=${h} duration_ms=${duration_ms} ${interface_summary}"
elif (( duration_ms >= 10000 )); then
echo "Health publish is slow: device=${h} duration_ms=${duration_ms} ${interface_summary}"
fi
__IOMATEX_HEALTH_SH__
chmod 0755 "$HEALTH_SH"
chown root:root "$HEALTH_SH"
@ -833,12 +931,13 @@ __IOMATEX_HEALTH_SVC__
cat >/etc/systemd/system/iomatex-mqtt-health.timer <<'__IOMATEX_HEALTH_TIMER__'
[Unit]
Description=Run IOMATEX MQTT health check every minute
Description=Publish IOMATEX Edge runtime heartbeat every 15 seconds
[Timer]
OnBootSec=20s
OnCalendar=*-*-* *:*:00
OnActiveSec=5s
OnUnitActiveSec=15s
AccuracySec=1s
RandomizedDelaySec=2s
Persistent=true
[Install]
@ -849,6 +948,7 @@ step "Enable services and apply config now"
systemctl daemon-reload
systemctl enable mosquitto >/dev/null 2>&1 || true
systemctl enable --now iomatex-mqtt-health.timer
systemctl restart iomatex-mqtt-health.timer
/usr/local/sbin/iomatex-mqtt-apply --print || true
step "Run first health publish immediately"
@ -882,7 +982,7 @@ echo "Actual health topic from env:"
echo " $(grep -m1 '^BRIDGE_BASE_TOPIC=' "$ENV_FILE" 2>/dev/null | cut -d= -f2)/health/${HOSTNAME_SHORT}"
echo
echo "Expected payload example:"
echo " {\"status\":\"ok\",\"time\":\"$(date -u '+%F, %T UTC'), time zone ($(date '+%z' | sed -E 's/^([+-][0-9]{2}).*/\1/'))\",\"hostname\":\"${HOSTNAME_SHORT}\"}"
echo " {\"schema_version\":2,\"state\":\"reachable\",\"device_id\":\"${HOSTNAME_SHORT}\",\"observed_at_ms\":...,\"valid_for_ms\":45000,...}"
echo
echo "Manual remote set + report:"
echo " sudo iomatex-mqtt-remote-set"

View File

@ -17,7 +17,7 @@ class MqttBridgeContractTest(unittest.TestCase):
def test_health_and_commands_are_device_scoped(self):
self.assertIn(
"topic ${BRIDGE_BASE_TOPIC}/health/${DEVICE_ID} out",
"topic ${BRIDGE_BASE_TOPIC}/health/${DEVICE_ID} out 1",
self.source,
)
self.assertIn(
@ -25,6 +25,45 @@ class MqttBridgeContractTest(unittest.TestCase):
self.source,
)
def test_health_is_retained_fresh_and_independent_from_client(self):
for contract in (
'"schema_version": 3',
'"state": "reachable"',
'"observed_at_ms": int(',
'"valid_for_ms": 45000',
'"boot_id": os.environ.get(',
'"uptime_seconds": int(',
'"client": {',
'unit_property itscreen-x11.service ActiveState',
'mosquitto_pub -h 127.0.0.1 -p 1883 -q 1 -r',
'OnActiveSec=5s',
'OnUnitActiveSec=15s',
'systemctl restart iomatex-mqtt-health.timer',
):
self.assertIn(contract, self.source)
self.assertNotIn('OnBootSec=5s', self.source)
def test_health_uses_console_owned_interface_profile(self):
self.assertIn(
'python3 /opt/iomatex-console/backend/app.py --runtime-profile-json',
self.source,
)
self.assertIn('"interfaces": interfaces', self.source)
for interface_name in ("rs485", "screen", "radio", "wifi", "ethernet"):
self.assertIn(f'"{interface_name}"', self.source)
def test_health_timestamp_and_transition_logging_follow_diagnostics(self):
health_script_offset = self.source.index("__IOMATEX_HEALTH_SH__")
profile_offset = self.source.index(
'runtime_profile="$(python3 /opt/iomatex-console/backend/app.py --runtime-profile-json'
)
observed_offset = self.source.index('observed_at_ms="$(date +%s%3N)"')
state_file_offset = self.source.index('STATE_FILE="/run/iomatex-mqtt-health.state"')
self.assertGreater(state_file_offset, health_script_offset)
self.assertGreater(observed_offset, profile_offset)
self.assertIn('Health state changed:', self.source)
self.assertIn('Health publish is slow:', self.source)
def test_legacy_telemetry_and_commands_are_directional(self):
for prefix in ("iomatex", "it-screen"):
self.assertIn(

View File

@ -1,3 +1,3 @@
{
"version": "1.0.2"
"version": "1.0.4"
}

View File

@ -56,7 +56,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 3.1.22"
UI_VERSION = "V 3.1.23"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo"
@ -2044,7 +2044,7 @@ def summarize_interface(iface, kind="ethernet"):
}
def get_network_summary():
def get_network_summary(include_service_cards=True):
iface = get_primary_interface()
profile = read_wifi_profile_state()
script_status = parse_wifi_status_script()
@ -2069,8 +2069,10 @@ def get_network_summary():
"iface": iface,
"service_state": "unknown",
}
cards, _ = collect_provider_cards(build_provider_context())
avahi_card = next((card for card in cards if card.get("id") == "avahi"), None)
avahi_card = None
if include_service_cards:
cards, _ = collect_provider_cards(build_provider_context())
avahi_card = next((card for card in cards if card.get("id") == "avahi"), None)
return {
"ok": True,
"generated_at": utc_now_iso(),
@ -2484,7 +2486,7 @@ def normalize_card(card):
return item
def load_providers():
def load_providers(entrypoint="get_cards"):
providers = []
for path in sorted(glob.glob(os.path.join(PROVIDERS_DIR, "*.py"))):
name = "provider_" + os.path.basename(path).replace(".", "_")
@ -2496,8 +2498,9 @@ def load_providers():
spec.loader.exec_module(module)
except Exception:
continue
if hasattr(module, "get_cards"):
providers.append((path, module.get_cards))
provider = getattr(module, entrypoint, None)
if provider:
providers.append((path, provider))
return providers
@ -2517,10 +2520,10 @@ def build_provider_context():
}
def collect_provider_cards(context):
def collect_provider_cards(context, entrypoint="get_cards"):
cards = []
provider_names = []
for path, provider in load_providers():
for path, provider in load_providers(entrypoint):
provider_names.append(os.path.basename(path))
try:
result = provider(context)
@ -2567,6 +2570,126 @@ def build_status_payload():
return payload
def _runtime_interface_state(active=False, configured=True, raw_state="", disabled=False):
normalized = str(raw_state or "").strip().lower().replace("_", "-")
if disabled:
return "disabled"
if active:
return "available"
if normalized in {"degraded", "driver-degraded", "failed", "error"}:
return "degraded"
if configured is False or normalized in {
"inactive", "disconnected", "driver-unavailable", "not-installed",
"installed-not-configured", "coordinator-missing", "unavailable",
}:
return "unavailable"
return "unknown"
def build_runtime_profile_payload():
observed_at_ms = int(time.time() * 1000)
interfaces = {
key: {"state": "unknown"}
for key in ("rs485", "screen", "radio", "wifi", "ethernet")
}
try:
runtime_cards, _ = collect_provider_cards(
build_provider_context(),
entrypoint="get_runtime_cards",
)
cards = {
card.get("id"): card
for card in runtime_cards
if isinstance(card, dict) and card.get("id")
}
display = cards.get("display") or {}
display_status = display.get("display_status") or {}
display_mode = display.get("display_mode") or {}
screen_connected = bool(display_status.get("connected"))
interfaces["screen"] = {
"state": _runtime_interface_state(
active=screen_connected,
configured=bool(display.get("configured", True)),
raw_state=display.get("state"),
),
"connected": screen_connected,
"interface": display_status.get("interface") or "",
"connector": display_status.get("connector") or "",
"monitor_name": display_status.get("monitor_name") or "",
"hdmi_connected": bool(display_mode.get("hdmi_connected")),
"status_text": display.get("status_text") or "",
}
radio = cards.get("zigbee2mqtt") or {}
interfaces["radio"] = {
"state": _runtime_interface_state(
active=bool(radio.get("active")),
configured=bool(radio.get("configured")),
raw_state=radio.get("state"),
),
"installed": bool(radio.get("installed")),
"configured": bool(radio.get("configured")),
"active": bool(radio.get("active")),
"coordinator_ready": bool(radio.get("coordinator_ready")),
"status_text": radio.get("status_text") or "",
}
except Exception as exc:
interfaces["screen"]["error"] = str(exc)
interfaces["radio"]["error"] = str(exc)
try:
network = get_network_summary(include_service_cards=False)
script_status = network.get("script_status") or {}
for key in ("wifi", "ethernet"):
source = (network.get("interfaces") or {}).get(key) or {}
wifi_radio = str(script_status.get("WIFI_RADIO") or "").strip().lower()
disabled = key == "wifi" and wifi_radio in {"disabled", "off", "no"}
interfaces[key] = {
"state": _runtime_interface_state(
active=bool(source.get("connected")),
configured=bool(source.get("present")),
raw_state=source.get("status") or source.get("state"),
disabled=disabled,
),
"connected": bool(source.get("connected")),
"present": bool(source.get("present")),
"interface": source.get("interface") or "",
"connection": source.get("connection") or "",
"status": source.get("status") or "",
"status_text": source.get("status_text") or "",
"is_default_route": bool(source.get("is_default_route")),
}
except Exception as exc:
interfaces["wifi"]["error"] = str(exc)
interfaces["ethernet"]["error"] = str(exc)
try:
ports = (modbus_list_ports_payload().get("ports") or [])
existing_ports = [port for port in ports if port.get("exists")]
interfaces["rs485"] = {
"state": "available" if existing_ports else "unavailable",
"active": any(port.get("busy_by_service") for port in existing_ports),
"ports": [
{
"port": port.get("port") or "",
"exists": True,
"busy_by_service": bool(port.get("busy_by_service")),
"status": port.get("status") or "",
}
for port in existing_ports
],
}
except Exception as exc:
interfaces["rs485"]["error"] = str(exc)
return {
"schema_version": 1,
"observed_at_ms": observed_at_ms,
"interfaces": interfaces,
}
def build_health_services_payload():
now = time.time()
cfg = load_config()
@ -4373,6 +4496,10 @@ class Handler(BaseHTTPRequestHandler):
def main():
if "--runtime-profile-json" in sys.argv:
print(json.dumps(build_runtime_profile_payload(), ensure_ascii=False, separators=(",", ":")))
return
cfg = load_config()
bind = str(cfg.get("bind", DEFAULT_CONFIG["bind"]))
port = int(cfg.get("port", DEFAULT_CONFIG["port"]))

View File

@ -0,0 +1,87 @@
import importlib.util
import pathlib
import sys
import unittest
from unittest import mock
BACKEND_DIR = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(BACKEND_DIR))
SPEC = importlib.util.spec_from_file_location("iomatex_console_runtime_profile", BACKEND_DIR / "app.py")
app = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(app)
class RuntimeProfileTest(unittest.TestCase):
def test_uses_console_diagnostics_for_all_interfaces(self):
runtime_cards = [
{
"id": "display",
"configured": True,
"active": True,
"state": "active",
"status_text": "Monitor connected by HDMI",
"display_status": {
"connected": True,
"interface": "HDMI",
"connector": "card0-HDMI-A-1",
"monitor_name": "Philips FTV",
},
"display_mode": {"hdmi_connected": True},
},
{
"id": "zigbee2mqtt",
"installed": True,
"configured": True,
"active": True,
"state": "active",
"coordinator_ready": True,
"status_text": "Running",
},
]
network = {
"interfaces": {
"wifi": {
"present": False,
"connected": False,
"interface": "wlan0",
"status": "not available",
"status_text": "Wi-Fi interface not available",
},
"ethernet": {
"present": True,
"connected": True,
"interface": "eth0",
"status": "connected",
"status_text": "Connected",
"is_default_route": True,
},
},
"script_status": {"WIFI_RADIO": "disabled"},
}
modbus = {
"ports": [{"port": "/dev/ttyS3", "exists": True, "busy_by_service": True}]
}
with mock.patch.object(app, "collect_provider_cards", return_value=(runtime_cards, ["00_core_services.py"])) as collect_cards, \
mock.patch.object(app, "get_network_summary", return_value=network) as get_network, \
mock.patch.object(app, "modbus_list_ports_payload", return_value=modbus):
payload = app.build_runtime_profile_payload()
collect_cards.assert_called_once_with(
mock.ANY,
entrypoint="get_runtime_cards",
)
get_network.assert_called_once_with(include_service_cards=False)
interfaces = payload["interfaces"]
self.assertEqual("available", interfaces["screen"]["state"])
self.assertTrue(interfaces["screen"]["hdmi_connected"])
self.assertEqual("available", interfaces["radio"]["state"])
self.assertEqual("disabled", interfaces["wifi"]["state"])
self.assertEqual("available", interfaces["ethernet"]["state"])
self.assertEqual("available", interfaces["rs485"]["state"])
self.assertNotIn("busy_process", interfaces["rs485"]["ports"][0])
if __name__ == "__main__":
unittest.main()

View File

@ -23,7 +23,7 @@
} catch (error) {}
})();
</script>
<link rel="stylesheet" href="/console.css?v=3.1.22&amp;rev=camera-snapshot-1">
<link rel="stylesheet" href="/console.css?v=3.1.23&amp;rev=edge-runtime-profile-1">
</head>
<body>
<main class="shell">
@ -109,7 +109,7 @@
</main>
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
<script src="/console.i18n.js?v=3.1.22&amp;rev=camera-snapshot-1"></script>
<script src="/console.js?v=3.1.22&amp;rev=camera-snapshot-1"></script>
<script src="/console.i18n.js?v=3.1.23&amp;rev=edge-runtime-profile-1"></script>
<script src="/console.js?v=3.1.23&amp;rev=edge-runtime-profile-1"></script>
</body>
</html>

View File

@ -597,7 +597,7 @@ def zigbee_card(ctx):
warnings.append("configuration.yaml is incomplete or invalid")
elif not coordinator_ready and runtime_ready:
state = "degraded"
status_text = "Degraded"
status_text = "USB coordinator not found"
errors.append("No coordinator")
warnings.append("Hint: check USB / serial port")
elif runtime_ready:
@ -1056,3 +1056,10 @@ def get_cards(ctx):
display_card(ctx),
*managed_system_cards(ctx),
]
def get_runtime_cards(ctx):
return [
display_card(ctx),
zigbee_card(ctx),
]

View File

@ -1,3 +1,3 @@
{
"version": "3.1.22"
"version": "3.1.23"
}