From 3ae0472417c9cdc731442df7cc56dd6cd65ee014 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Sun, 15 Mar 2026 07:41:49 +0400 Subject: [PATCH] Add UI console core and legacy reference --- stage_ui/console_core/ARCHITECTURE.md | 17 + .../backend/__pycache__/app.cpython-312.pyc | Bin 0 -> 14006 bytes stage_ui/console_core/backend/app.py | 273 +++ stage_ui/console_core/frontend/console.css | 78 + stage_ui/console_core/frontend/console.js | 110 + stage_ui/console_core/frontend/index.html | 45 + .../providers/00_core_services.py | 192 ++ .../00_core_services.cpython-312.pyc | Bin 0 -> 6435 bytes stage_ui/legacy_reference/README.md | 9 + stage_ui/legacy_reference/ui_addon_display.sh | 207 ++ .../legacy_reference/ui_addon_itscreen.sh | 765 +++++++ stage_ui/legacy_reference/ui_installer.sh | 1910 +++++++++++++++++ 12 files changed, 3606 insertions(+) create mode 100644 stage_ui/console_core/ARCHITECTURE.md create mode 100644 stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc create mode 100644 stage_ui/console_core/backend/app.py create mode 100644 stage_ui/console_core/frontend/console.css create mode 100644 stage_ui/console_core/frontend/console.js create mode 100644 stage_ui/console_core/frontend/index.html create mode 100644 stage_ui/console_core/providers/00_core_services.py create mode 100644 stage_ui/console_core/providers/__pycache__/00_core_services.cpython-312.pyc create mode 100644 stage_ui/legacy_reference/README.md create mode 100755 stage_ui/legacy_reference/ui_addon_display.sh create mode 100755 stage_ui/legacy_reference/ui_addon_itscreen.sh create mode 100755 stage_ui/legacy_reference/ui_installer.sh diff --git a/stage_ui/console_core/ARCHITECTURE.md b/stage_ui/console_core/ARCHITECTURE.md new file mode 100644 index 0000000..16b21b5 --- /dev/null +++ b/stage_ui/console_core/ARCHITECTURE.md @@ -0,0 +1,17 @@ +# IOMATEX Console Architecture + +## Core responsibilities +- Serve one fast local diagnostics UI. +- Expose one normalized status endpoint: `/api/status`. +- Load provider modules from `providers.d`. +- Cache recent status briefly to avoid repeated shell work on every page render. + +## Addon responsibilities +- Add new service cards without changing core frontend or server flow. +- Read only the service-specific files and units they need. +- Return normalized card objects using the shared card contract. + +## Future `ui_backend` role +- Keep this Console focused on lightweight diagnostics. +- Future `ui_backend` can own richer workflows: actions, forms, provisioning, and service-specific control paths. +- The normalized card contract can remain stable while richer backend features evolve separately. diff --git a/stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc b/stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5d14b801a481367848103c492ff29d9730c1e81 GIT binary patch literal 14006 zcmcgTYfv1=nKL`H?>DfpEN=;fRuUjt53HxnQ<5biS&}80SlO(07FYzkWM&Y8TP*BS z61b=WM9#6qN`aG98JBbwQkSd9msCZT?XoMmt72Ic)?@B2RdLmw|6xg0cJQD3zTTbL z1+8RXUHO{YZ@RyJOi%aM-?RCX*=(R74XOV*aJr15{)z=Tsgs!ptu#eVP#ne4T~ur0 zNw=yXGtnA=lo_)eN&Yvwc7qy{WMBHJEv{U;&hyzGjPTmOlvl0;%Lr%L)DtYS*}v8 z4z7^1UZq=eIUAJnI6FWmmjy7N%LeG;asU=^4uFMRF2Eu#4`8v1I!JNOs}z^-*WYB4 zvn=6UP*>_N;|eZrq$pmeqWq;dlOIG={d7O=F8UP9EpC;RTkjS8hfbe9ank?YUcVq7 z@&>ssKQCpU?%@4iE)Zhbb|e;}tO)FajeLfu}`f4RyR3JRev zzohBuz0ei#4H$d)(4_$9=Y?u+Aiu^h`sAiH$)?qvLMS+(-C9ll0>6O8{}eyL%}DHp zK#-Hzo)9leW}nyB;rEDQmq+mX+LNC_!ORW*%RK?!FL=D7r0wzccZIy1Pp-$O27Wl= z1Bwun2r!Yv>Le3XbiNrG)s-D2dW-AN77qF%1+BxEd?63;NLjEKYv ze=-r!lxUXQUQvm1R;lOhVXD)rpp{HmC67o`Vd@mMp4vtUbf1c*UWCu0scTy-$y0t-E50Q^DF9Jv90Q9+(>`W7sBmz>m`;8_(aLl*wkG2!qL;7 z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(Z2TV)d>=s$0douSIYP?<@gw({$tAiF=c@Ke^L$qPL=(| zP&%ZIo2{c~N6wDEH1blUa{B3*dCQOiLLn2{aqWa@+!Q%G-5s;-7&6B#?ja-mGln@A z7*yPm3x1p|)sSV`MCBLGuu*;0kmkNdPum_iO?1iqVwx_!ucPVO`#Lq9b>C*DZTCx` z0?FkFu(N%QOoTdCB1<(86p*3^?+_Pa#!vph7{zt6td(F!XmE6<+ E0WvIA?EnA( literal 0 HcmV?d00001 diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py new file mode 100644 index 0000000..edf2e04 --- /dev/null +++ b/stage_ui/console_core/backend/app.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +import glob +import importlib.util +import json +import os +import subprocess +import sys +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlparse + +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" + +DEFAULT_CONFIG = { + "bind": "0.0.0.0", + "port": 8099, + "cache_ttl_sec": 3, +} + +_CACHE = {"expires_at": 0.0, "payload": None} + + +def load_config(): + data = dict(DEFAULT_CONFIG) + try: + with open(CONFIG_PATH, "r", encoding="utf-8") as fh: + loaded = json.load(fh) + if isinstance(loaded, dict): + data.update(loaded) + except Exception: + pass + return data + + +def run(cmd, timeout=4): + try: + proc = subprocess.run( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=timeout, + check=False, + ) + return proc.returncode, (proc.stdout or "").strip(), (proc.stderr or "").strip() + except Exception as exc: + return 1, "", str(exc) + + +def file_exists(path): + return os.path.exists(path) + + +def any_exists(paths): + return any(os.path.exists(path) for path in paths) + + +def read_text(path): + try: + with open(path, "r", encoding="utf-8", errors="ignore") as fh: + return fh.read() + except Exception: + return "" + + +def read_env_file(path): + data = {} + try: + with open(path, "r", encoding="utf-8", errors="ignore") as fh: + for raw in fh: + line = raw.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, value = line.split("=", 1) + value = value.strip().strip('"').strip("'") + data[key.strip()] = value + except Exception: + pass + return data + + +def systemd_unit(unit_name): + properties = [ + "LoadState", + "ActiveState", + "SubState", + "UnitFileState", + "Result", + "ExecMainStatus", + "FragmentPath", + ] + cmd = ["systemctl", "show", unit_name, "--no-page"] + for prop in properties: + cmd.extend(["-p", prop]) + rc, stdout, stderr = run(cmd) + data = { + "unit": unit_name, + "load_state": "not-found", + "active_state": "inactive", + "sub_state": "dead", + "unit_file_state": "unknown", + "result": "", + "exec_main_status": "", + "fragment_path": "", + "installed": False, + "active": False, + "raw_error": stderr if rc != 0 else "", + } + if stdout: + for line in stdout.splitlines(): + if "=" not in line: + continue + key, value = line.split("=", 1) + key = key.strip() + value = value.strip() + if key == "LoadState": + data["load_state"] = value or "not-found" + elif key == "ActiveState": + data["active_state"] = value or "inactive" + elif key == "SubState": + data["sub_state"] = value or "dead" + elif key == "UnitFileState": + data["unit_file_state"] = value or "unknown" + elif key == "Result": + data["result"] = value + elif key == "ExecMainStatus": + data["exec_main_status"] = value + elif key == "FragmentPath": + data["fragment_path"] = value + data["installed"] = data["load_state"] != "not-found" or bool(data["fragment_path"]) + data["active"] = data["active_state"] == "active" + return data + + +def normalize_card(card): + item = dict(card) + item.setdefault("id", "unknown") + item.setdefault("title", item["id"]) + item["installed"] = bool(item.get("installed", False)) + item["configured"] = bool(item.get("configured", False)) + item["active"] = bool(item.get("active", False)) + item["state"] = str(item.get("state", "unknown")) + item["status_text"] = str(item.get("status_text", item["state"])) + item["errors"] = [str(x) for x in item.get("errors", []) if str(x).strip()] + item["warnings"] = [str(x) for x in item.get("warnings", []) if str(x).strip()] + return item + + +def load_providers(): + providers = [] + for path in sorted(glob.glob(os.path.join(PROVIDERS_DIR, "*.py"))): + name = "provider_" + os.path.basename(path).replace(".", "_") + spec = importlib.util.spec_from_file_location(name, path) + if not spec or not spec.loader: + continue + module = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(module) + except Exception: + continue + if hasattr(module, "get_cards"): + providers.append((path, module.get_cards)) + return providers + + +def build_status_payload(): + now = time.time() + cfg = load_config() + if _CACHE["payload"] is not None and now < _CACHE["expires_at"]: + return _CACHE["payload"] + + context = { + "file_exists": file_exists, + "any_exists": any_exists, + "read_text": read_text, + "read_env_file": read_env_file, + "systemd_unit": systemd_unit, + } + cards = [] + provider_names = [] + for path, provider in load_providers(): + provider_names.append(os.path.basename(path)) + try: + result = provider(context) + except Exception as exc: + result = [{ + "id": os.path.splitext(os.path.basename(path))[0], + "title": os.path.basename(path), + "installed": False, + "configured": False, + "active": False, + "state": "error", + "status_text": "Provider error", + "errors": [str(exc)], + "warnings": [], + }] + if isinstance(result, dict): + result = [result] + for card in result or []: + cards.append(normalize_card(card)) + + payload = { + "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "services": cards, + "providers": provider_names, + } + _CACHE["payload"] = payload + _CACHE["expires_at"] = now + max(1, int(cfg.get("cache_ttl_sec", 3))) + return payload + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, fmt, *args): + return + + def send_json(self, payload, code=200): + body = json.dumps(payload, indent=2).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def send_file(self, path, content_type): + try: + with open(path, "rb") as fh: + data = fh.read() + except FileNotFoundError: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + parsed = urlparse(self.path) + if parsed.path == "/api/status": + self.send_json(build_status_payload()) + return + if parsed.path in ("/", "/index.html"): + self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8") + return + if parsed.path == "/console.css": + self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8") + return + if parsed.path == "/console.js": + self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8") + return + if parsed.path == "/logo.png": + self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png") + return + if parsed.path == "/favicon.png": + self.send_file(os.path.join(PUBLIC_DIR, "favicon.png"), "image/png") + return + self.send_error(404) + + +def main(): + cfg = load_config() + bind = str(cfg.get("bind", DEFAULT_CONFIG["bind"])) + port = int(cfg.get("port", DEFAULT_CONFIG["port"])) + server = ThreadingHTTPServer((bind, port), Handler) + print(f"[console] http://{bind}:{port}", file=sys.stderr) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css new file mode 100644 index 0000000..01e29bd --- /dev/null +++ b/stage_ui/console_core/frontend/console.css @@ -0,0 +1,78 @@ +:root{ + --bg:#eef2f0; + --panel:#ffffff; + --ink:#16211d; + --muted:#66736d; + --line:#d7e0db; + --accent:#0e7a53; + --warn:#9a6a00; + --error:#b93434; + --shadow:0 12px 32px rgba(16,24,20,.08); +} +*{box-sizing:border-box} +body{ + margin:0; + font-family:system-ui,-apple-system,"Segoe UI",sans-serif; + background: + radial-gradient(circle at top left, rgba(14,122,83,.10), transparent 32%), + linear-gradient(180deg, #f7faf8 0%, var(--bg) 100%); + color:var(--ink); +} +.shell{max-width:1100px;margin:0 auto;padding:28px 18px 40px} +.hero{ + display:flex;justify-content:space-between;gap:16px;align-items:center;flex-wrap:wrap; + margin-bottom:18px; +} +.brand{display:flex;align-items:center;gap:14px;min-width:0} +.brandLogo{ + width:40px;height:40px;object-fit:contain;display:block;flex:0 0 auto; + border-radius:10px;background:#fff;border:1px solid var(--line);padding:4px; +} +.eyebrow{font-size:12px;letter-spacing:.16em;text-transform:uppercase;color:var(--accent);font-weight:700} +h1{margin:4px 0 4px;font-size:34px;line-height:1} +.sub{margin:0;color:var(--muted)} +.actions button{ + border:0;border-radius:999px;background:var(--ink);color:#fff;padding:12px 18px;font-weight:700;cursor:pointer; + box-shadow:var(--shadow); +} +.panel{ + background:var(--panel);border:1px solid var(--line);border-radius:18px;box-shadow:var(--shadow); +} +.summary{ + display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;padding:16px 18px;margin-bottom:18px; +} +.summaryItem{display:flex;flex-direction:column;gap:4px} +.label{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)} +.cards{ + display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px; +} +.card{padding:18px} +.cardTop{display:flex;justify-content:space-between;gap:12px;align-items:flex-start} +.card h2{margin:0;font-size:19px} +.badge{ + display:inline-flex;align-items:center;gap:8px;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:700; + background:#edf4f0;color:var(--ink); +} +.dot{width:9px;height:9px;border-radius:50%} +.dot.ok{background:var(--accent)} +.dot.warn{background:var(--warn)} +.dot.error{background:var(--error)} +.meta{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;margin-top:16px;font-size:13px} +.meta .key{color:var(--muted)} +.list{margin-top:14px;padding-top:14px;border-top:1px solid var(--line)} +.listTitle{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:8px} +.pillRow{display:flex;gap:8px;flex-wrap:wrap} +.pill{ + display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;background:#f5f7f6;color:var(--ink); +} +.pill.good{background:rgba(14,122,83,.10);color:var(--accent)} +.pill.bad{background:rgba(185,52,52,.10);color:var(--error)} +.msgList{margin:8px 0 0;padding-left:18px;color:var(--muted)} +.empty{ + padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center; +} +@media (max-width:720px){ + .summary{grid-template-columns:1fr} + .meta{grid-template-columns:1fr 1fr} + .brand{align-items:flex-start} +} diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js new file mode 100644 index 0000000..891d535 --- /dev/null +++ b/stage_ui/console_core/frontend/console.js @@ -0,0 +1,110 @@ +(function () { + "use strict"; + + const nodes = { + refreshBtn: document.getElementById("refreshBtn"), + cards: document.getElementById("cards"), + lastUpdate: document.getElementById("lastUpdate"), + providerCount: document.getElementById("providerCount"), + serviceCount: document.getElementById("serviceCount") + }; + + function esc(value) { + return (value ?? "").toString().replace(/[&<>"']/g, (m) => ({ + "&": "&", + "<": "<", + ">": ">", + "\"": """, + "'": "'" + }[m])); + } + + function boolPill(label, value) { + return `${esc(label)}: ${value ? "yes" : "no"}`; + } + + function statusTone(card) { + if (card.errors && card.errors.length) return "error"; + if (card.active) return "ok"; + return "warn"; + } + + function renderCard(card) { + const tone = statusTone(card); + const warnings = Array.isArray(card.warnings) ? card.warnings : []; + const errors = Array.isArray(card.errors) ? card.errors : []; + + return ` +
+
+
+

${esc(card.title)}

+
${esc(card.status_text || card.state || "Unknown")}
+
+
+ +
+
ID
${esc(card.id)}
+
State
${esc(card.state || "-")}
+
Status
${esc(card.status_text || "-")}
+
+ +
+
Flags
+
+ ${boolPill("Installed", !!card.installed)} + ${boolPill("Configured", !!card.configured)} + ${boolPill("Active", !!card.active)} +
+
+ + ${warnings.length ? ` +
+
Warnings
+
    ${warnings.map((x) => `
  • ${esc(x)}
  • `).join("")}
+
+ ` : ""} + + ${errors.length ? ` +
+
Errors
+
    ${errors.map((x) => `
  • ${esc(x)}
  • `).join("")}
+
+ ` : ""} +
+ `; + } + + function render(payload) { + const services = Array.isArray(payload.services) ? payload.services : []; + const providers = Array.isArray(payload.providers) ? payload.providers : []; + + nodes.lastUpdate.textContent = payload.generated_at || "-"; + nodes.providerCount.textContent = String(providers.length); + nodes.serviceCount.textContent = String(services.length); + + if (!services.length) { + nodes.cards.innerHTML = `
No service cards returned by providers.
`; + return; + } + + nodes.cards.innerHTML = services.map(renderCard).join(""); + } + + async function load() { + nodes.refreshBtn.disabled = true; + try { + const response = await fetch("/api/status", { cache: "no-store" }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const payload = await response.json(); + render(payload); + } catch (error) { + nodes.cards.innerHTML = `
Failed to load status: ${esc(error.message || String(error))}
`; + } finally { + nodes.refreshBtn.disabled = false; + } + } + + nodes.refreshBtn.addEventListener("click", load); + load(); +})(); diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html new file mode 100644 index 0000000..6698b92 --- /dev/null +++ b/stage_ui/console_core/frontend/index.html @@ -0,0 +1,45 @@ + + + + + + IOMATEX Console + + + + +
+
+
+ +
+
IOMATEX
+

Console

+

Lightweight diagnostics for installed services.

+
+
+
+ +
+
+ +
+
+ Last update + - +
+
+ Providers + - +
+
+ Cards + - +
+
+ +
+
+ + + diff --git a/stage_ui/console_core/providers/00_core_services.py b/stage_ui/console_core/providers/00_core_services.py new file mode 100644 index 0000000..d665cb7 --- /dev/null +++ b/stage_ui/console_core/providers/00_core_services.py @@ -0,0 +1,192 @@ +def _service_card(service_id, title, unit_name, installed, configured, active, state, status_text, errors=None, warnings=None): + return { + "id": service_id, + "title": title, + "installed": installed, + "configured": configured, + "active": active, + "state": state, + "status_text": status_text, + "errors": errors or [], + "warnings": warnings or [], + } + + +def _short_unit_errors(unit): + errors = [] + if unit["active_state"] == "failed": + errors.append("Service failed") + if unit["result"] and unit["result"] not in ("success", "done"): + errors.append(f"Result: {unit['result']}") + if unit["exec_main_status"] and unit["exec_main_status"] not in ("0", ""): + errors.append(f"Exit status: {unit['exec_main_status']}") + if unit["raw_error"]: + errors.append(unit["raw_error"]) + return errors[:2] + + +def _lifecycle(installed, configured, active, *, failed=False): + if not installed: + return "not installed", "Not installed" + if active: + return "active", "Active" + if not configured: + return "installed_not_configured", "Not configured" + if failed: + return "failed", "Failed" + return "inactive", "Inactive" + + +def _strict_active(installed, configured, unit): + return bool(installed and configured and unit["active"]) + + +def itscreen_card(ctx): + unit = ctx["systemd_unit"]("itscreen-x11.service") + installed = ctx["any_exists"]([ + "/opt/itscreen/bin/itscreen", + "/etc/systemd/system/itscreen-x11.service", + "/lib/systemd/system/itscreen-x11.service", + ]) + configured = ctx["any_exists"]([ + "/etc/systemd/system/itscreen-x11.service", + "/lib/systemd/system/itscreen-x11.service", + ]) + warnings = [] + if installed and not configured: + warnings.append("Service unit not found") + active = _strict_active(installed, configured, unit) + state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed") + return _service_card( + "itscreen", + "IT-Screen App", + "itscreen-x11.service", + installed, + configured, + active, + state, + status_text, + _short_unit_errors(unit), + warnings, + ) + + +def mosquitto_card(ctx): + unit = ctx["systemd_unit"]("mosquitto.service") + installed = ctx["any_exists"]([ + "/etc/mosquitto/mosquitto.conf", + "/lib/systemd/system/mosquitto.service", + "/etc/systemd/system/mosquitto.service", + ]) + configured = ctx["file_exists"]("/etc/mosquitto/mosquitto.conf") + warnings = [] + if installed and not configured: + warnings.append("Main config missing") + active = _strict_active(installed, configured, unit) + state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed") + return _service_card( + "mosquitto", + "Mosquitto MQTT", + "mosquitto.service", + installed, + configured, + active, + state, + status_text, + _short_unit_errors(unit), + warnings, + ) + + +def mqtt_bridge_card(ctx): + env = ctx["read_env_file"]("/etc/iomatex/mqtt_bridge.env") + installed = ctx["any_exists"]([ + "/etc/iomatex/mqtt_bridge.env", + "/usr/local/sbin/iomatex-mqtt-apply", + "/etc/systemd/system/iomatex-mqtt-bridge.service", + ]) + enabled = str(env.get("ENABLE_BRIDGE", "0")).strip() == "1" + configured = bool(env.get("REMOTE_HOST", "").strip()) + bridge_service = ctx["systemd_unit"]("iomatex-mqtt-bridge.service") + bridge_path = ctx["systemd_unit"]("iomatex-mqtt-bridge.path") + active = bool(bridge_service["active"] or bridge_path["active"]) + warnings = [] + errors = [] + if installed and not enabled: + warnings.append("Bridge disabled") + if installed and enabled and not configured: + errors.append("REMOTE_HOST is empty") + state, status_text = _lifecycle(installed, configured, active) + if installed and configured and not active and not enabled: + status_text = "Disabled" + return _service_card( + "mqtt_bridge", + "MQTT Bridge", + "iomatex-mqtt-bridge.service", + installed, + configured, + active, + state, + status_text, + errors[:2], + warnings[:2], + ) + + +def zigbee_card(ctx): + unit = ctx["systemd_unit"]("zigbee2mqtt.service") + app_footprint = ctx["any_exists"]([ + "/opt/zigbee2mqtt/package.json", + "/opt/zigbee2mqtt/index.js", + ]) + unit_footprint = ctx["any_exists"]([ + "/etc/systemd/system/zigbee2mqtt.service", + "/lib/systemd/system/zigbee2mqtt.service", + ]) + installed = bool(app_footprint or unit_footprint or unit["installed"]) + configured = installed and ctx["file_exists"]("/opt/zigbee2mqtt/data/configuration.yaml") + active = _strict_active(installed, configured, unit) + warnings = [] + if installed and not configured: + warnings.append("configuration.yaml missing") + state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed") + return _service_card( + "zigbee2mqtt", + "Zigbee2MQTT", + "zigbee2mqtt.service", + installed, + configured, + active, + state, + status_text, + _short_unit_errors(unit), + warnings, + ) + + +def placeholder_card(service_id, title): + state, status_text = _lifecycle(False, False, False) + return _service_card( + service_id, + title, + "", + False, + False, + False, + state, + status_text, + [], + [], + ) + + +def get_cards(ctx): + return [ + itscreen_card(ctx), + mosquitto_card(ctx), + mqtt_bridge_card(ctx), + zigbee_card(ctx), + placeholder_card("reverse_tunnel", "Reverse Tunnel"), + placeholder_card("display", "Display"), + placeholder_card("edge_api", "Edge API"), + ] diff --git a/stage_ui/console_core/providers/__pycache__/00_core_services.cpython-312.pyc b/stage_ui/console_core/providers/__pycache__/00_core_services.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf2c3f9a952401a4fceab5a09f465fcb0e918b7d GIT binary patch literal 6435 zcmdT|O>7&-72f6F4!I&JQWC8nTc$0^5|dbz{G-~n?8KI(SV~MMwt*CG9D?So<&`N? znO!*&u?mPHK$TONT*RO$p!8B3?jc1{)VKB+pcm2<5PG3Qf%ejyYa2cIQ1s3057#my zq`7sa9nQ|Yc{4lv-uJ#Ye+>o$99+*Lf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`}0 z4pgAx+yRZV@X7hscAL!<9db?dX^yoy7wnYF;)M>}ffMu=tqyKFFTf#zkkUg$x&!CI zQd(Wk=cQaRblG^0UuDm_03-o6Z&eq74X_GgC(W59xrnBL9L3MRGn?=dni`Xnw4jle zP`4m-j}ts|MTMSGm`7B8;0f#_DC9k8{S(~E+fbCae;^2?b=13!Vr8X{`nFMbrK67a zZKICzR2_B0bG0W?ef3lwP13%e&DlC+5K!ygyjDkJkHd&&x5&(H;UGT+P(aVI87vq^ z!$9NvmdjSePTN?1%pCqXnp`a4<(zbe{0vmlH&ISQ@z~At{8N|6`=0C#@Uh3e+{rV~ mI6r^zNjJ}*euDa-W3n5Hi8vH9{9Y)}1bN@nxSu!D@Bae3s0`Zx literal 0 HcmV?d00001 diff --git a/stage_ui/legacy_reference/README.md b/stage_ui/legacy_reference/README.md new file mode 100644 index 0000000..d4b139e --- /dev/null +++ b/stage_ui/legacy_reference/README.md @@ -0,0 +1,9 @@ +# Legacy UI Reference + +These files preserve the previous WebIPC-based UI implementation as reference only: + +- `ui_installer.sh` +- `ui_addon_itscreen.sh` +- `ui_addon_display.sh` + +The new `stage_ui/ui_installer.sh` installs the lightweight Console core instead of the legacy Node/Express UI. diff --git a/stage_ui/legacy_reference/ui_addon_display.sh b/stage_ui/legacy_reference/ui_addon_display.sh new file mode 100755 index 0000000..1adac0d --- /dev/null +++ b/stage_ui/legacy_reference/ui_addon_display.sh @@ -0,0 +1,207 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP="/opt/iomatex-process1-webipc" +ADDON_FRONT="$APP/public/addons" +SERVICE="iomatex-webipc.service" + +echo "[1/4] prepare dirs" +mkdir -p "$ADDON_FRONT" + +echo "[2/4] write x11 addon" +cat > "$ADDON_FRONT/x11.js" <<'JS' +(function () { + "use strict"; + + if (window.__iomatexX11AddonLoaded) return; + window.__iomatexX11AddonLoaded = true; + + const ui = window.IOMATEX_UI; + if (!ui) return; + + const state = ui.state; + + state.x11Addon = state.x11Addon || { + data: null, + busy: { refresh: false }, + message: "" + }; + + function esc(s) { + return (s ?? "").toString().replace(/[&<>"']/g, m => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }[m])); + } + + function setBusy(key, v) { + state.x11Addon.busy[key] = !!v; + ui.render(); + } + + function setMsg(msg) { + state.x11Addon.message = (msg || "").toString(); + ui.render(); + } + + function btn(label, kind, fnName, busyKey, busyLabel) { + const busy = !!state.x11Addon.busy[busyKey]; + return ``; + } + + async function loadDisplay() { + const j = await ui.call("/api/display/hdmi"); + state.x11Addon.data = j; + return j; + } + + async function refreshDisplay() { + setBusy("refresh", true); + setMsg("Refreshing display information..."); + try { + await ui.loadDetail("x11").catch(() => {}); + await loadDisplay(); + setMsg("Display information updated."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("refresh", false); + } + } + + function renderConnector(c) { + return ` +
+
${esc(c.edid?.monitor_name || c.connector || "Connector")}
+
+
Connector
${esc(c.connector || "-")} +
Type
${esc(c.kind || "-")} +
Status
${esc(c.status || "-")} +
Connected
${esc(c.connected ? "yes" : "no")} +
Enabled
${esc(c.enabled || "-")} +
DPMS
${esc(c.dpms || "-")} +
Preferred mode
${esc(c.preferred_mode || "-")} +
Modes
${esc((c.modes || []).join(", ") || "-")} +
Monitor
${esc(c.edid?.monitor_name || "-")} +
Vendor
${esc(c.edid?.manufacturer_id || "-")} +
Product code
${esc(c.edid?.product_code || "-")} +
Serial
${esc(c.edid?.serial_text || "-")} +
Size
${esc(c.edid?.size_cm || "-")} +
Diagonal
${esc(c.edid?.size_inch || "-")} +
+
+ `; + } + + function renderX11Detail(service) { + const d = state.x11Addon.data || {}; + const sum = d.summary || {}; + const first = sum.first_connected_hdmi || null; + const connectors = Array.isArray(d.connectors) ? d.connectors : []; + const connected = connectors.filter(x => x.connected); + const hdmi = Array.isArray(d.hdmi) ? d.hdmi : []; + const status = service.status || {}; + + document.getElementById("viewTitle").textContent = service.title || "Display"; + document.getElementById("viewSub").textContent = service.desc || ""; + document.getElementById("viewActions").innerHTML = + ``; + + document.getElementById("view").innerHTML = ` +
+
+
Display summary
+
+
Active
${esc(status.active || "-")} +
Started
${esc(status.started_at || "-")} +
State
${esc(status.summary || "-")} +
Running
${esc(status.running_for_text || "-")} +
HDMI connected
${esc(sum.hdmi_connected ? "yes" : "no")} +
Connected displays
${esc(String(sum.connected_count ?? 0))} +
Connected HDMI
${esc(String(sum.connected_hdmi_count ?? 0))} +
Connector
${esc(first?.connector || "-")} +
Monitor
${esc(first?.edid?.monitor_name || "-")} +
Preferred mode
${esc(first?.preferred_mode || "-")} +
Vendor
${esc(first?.edid?.manufacturer_id || "-")} +
+
+ ${btn("Refresh", "primary", "window.__x11Refresh()", "refresh", "Refreshing...")} +
+
+ +
+
Connected connectors
+ ${connected.length ? connected.map(renderConnector).join("") : `
No connected connectors detected.
`} +
+ +
+
HDMI connectors
+ ${hdmi.length ? hdmi.map(renderConnector).join("") : `
No HDMI connectors found.
`} +
+ +
+
All DRM connectors
+ ${connectors.length ? connectors.map(renderConnector).join("") : `
No DRM connectors found.
`} +
+ +
+
Message
+
${esc(state.x11Addon.message || "Ready")}
+
+
+ `; + } + + const prevLoadTabData = ui.loadTabData.bind(ui); + const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){}; + const prevRender = ui.render.bind(ui); + + ui.loadTabData = async function () { + if (state.tab === "x11") { + await ui.loadDetail("x11"); + await loadDisplay().catch(() => {}); + return; + } + return prevLoadTabData(); + }; + + ui.refreshDetail = async function () { + if (state.tab === "x11") { + await ui.loadDetail("x11"); + await loadDisplay().catch(() => {}); + ui.render(); + return; + } + return prevRefreshDetail(); + }; + window.refreshDetail = ui.refreshDetail; + + ui.render = function () { + if (state.tab === "x11" && state.detail?.service?.key === "x11") { + renderX11Detail(state.detail.service); + return; + } + return prevRender(); + }; + window.render = ui.render; + + window.__x11Refresh = refreshDisplay; + + setTimeout(async () => { + try { + await loadDisplay().catch(() => {}); + if (state.tab === "x11") ui.render(); + } catch (_) {} + }, 0); +})(); +JS + +echo "[3/4] restart" +systemctl restart "$SERVICE" + +echo "[4/4] done" +echo "Installed frontend: $ADDON_FRONT/x11.js" +echo "Restarted: $SERVICE" \ No newline at end of file diff --git a/stage_ui/legacy_reference/ui_addon_itscreen.sh b/stage_ui/legacy_reference/ui_addon_itscreen.sh new file mode 100755 index 0000000..b1ace3b --- /dev/null +++ b/stage_ui/legacy_reference/ui_addon_itscreen.sh @@ -0,0 +1,765 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP="/opt/iomatex-process1-webipc" +ADDON_BACK="$APP/addons/backend" +ADDON_FRONT="$APP/public/addons" +CFG="/etc/iomatex/webipc-itscreen.json" +SERVICE="iomatex-webipc.service" + +echo "[1/6] prepare dirs" +mkdir -p "$ADDON_BACK" "$ADDON_FRONT" /etc/iomatex + +echo "[2/6] config" +if [ ! -f "$CFG" ]; then +cat > "$CFG" <<'EOF' +{ + "server": "", + "deviceId": "", + "token": "", + "username": "", + "password": "", + "topicNamespace": "" +} +EOF +fi + +echo "[3/6] backend addon" +cat > "$ADDON_BACK/itscreen.js" <<'JS' +"use strict"; + +const fs = require("fs"); +const os = require("os"); +const mqtt = require("mqtt"); + +const CFG = "/etc/iomatex/webipc-itscreen.json"; +const MQTT = "mqtt://127.0.0.1:1883"; +const LOGIN_PASSWORD = "eXXI0wkHBmNBnVbE"; +const TOPIC_NAMESPACES = ["it-screen", "iomatex"]; +const ITSERVICE = "itscreen-x11.service"; + +function readCfg() { + try { + const j = JSON.parse(fs.readFileSync(CFG, "utf8")); + return { + server: (j.server || "").toString(), + deviceId: (j.deviceId || "").toString(), + token: (j.token || "").toString(), + username: (j.username || "").toString(), + password: (j.password || "").toString(), + topicNamespace: (j.topicNamespace || "").toString() + }; + } catch { + return { + server: "", + deviceId: "", + token: "", + username: "", + password: "", + topicNamespace: "" + }; + } +} + +function writeCfg(o) { + const safe = { + server: (o.server || "").toString().trim(), + deviceId: (o.deviceId || "").toString().trim(), + token: (o.token || "").toString().trim(), + username: (o.username || "").toString().trim(), + password: (o.password || "").toString().trim(), + topicNamespace: (o.topicNamespace || "").toString().trim() + }; + fs.writeFileSync(CFG, JSON.stringify(safe, null, 2) + "\n", "utf8"); + return safe; +} + +function normalizeNamespace(ns) { + ns = (ns || "").toString().trim(); + return TOPIC_NAMESPACES.includes(ns) ? ns : ""; +} + +function getDeviceId(cfg) { + return (cfg.deviceId || os.hostname()).trim(); +} + +function topicPair(cfg, namespace) { + const id = getDeviceId(cfg); + const ns = normalizeNamespace(namespace) || "it-screen"; + const base = `${ns}/$devices/settings/${id}`; + return { + namespace: ns, + deviceId: id, + sub: `${base}/sub`, + pub: `${base}/pub` + }; +} + +function getNamespaceOrder(cfg) { + const preferred = normalizeNamespace(cfg.topicNamespace); + if (preferred) return [preferred].concat(TOPIC_NAMESPACES.filter(x => x !== preferred)); + return TOPIC_NAMESPACES.slice(); +} + +function hasRegistrationData(obj) { + if (!obj || typeof obj !== "object") return false; + const server = (obj.server || obj.host || "").toString().trim(); + const username = (obj.username || "").toString().trim(); + const password = (obj.password || "").toString().trim(); + return !!(server && username && password); +} + +module.exports = function(app, ctx) { + const mqttc = mqtt.connect(MQTT, { + reconnectPeriod: 1000, + connectTimeout: 4000, + keepalive: 30, + clean: true + }); + + let loginState = { + ok: false, + lastTs: null, + lastError: null, + lastNamespace: null + }; + + let sendQueue = Promise.resolve(); + + function saveNamespaceIfChanged(namespace) { + const ns = normalizeNamespace(namespace); + if (!ns) return readCfg(); + const cur = readCfg(); + if (cur.topicNamespace === ns) return cur; + return writeCfg({ + server: cur.server, + deviceId: cur.deviceId || getDeviceId(cur), + token: cur.token, + username: cur.username, + password: cur.password, + topicNamespace: ns + }); + } + + function sendOne(cfg, namespace, payload, timeout = 3000) { + return new Promise((resolve) => { + const tp = topicPair(cfg, namespace); + let done = false; + + const finish = (obj) => { + if (done) return; + done = true; + clearTimeout(timer); + mqttc.removeListener("message", onMsg); + try { mqttc.unsubscribe(tp.pub); } catch {} + resolve(obj); + }; + + const timer = setTimeout(() => { + finish({ + ok: false, + note: "timeout", + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }); + }, timeout); + + function onMsg(t, b) { + if (t !== tp.pub) return; + const raw = b ? b.toString() : ""; + let parsed = null; + try { parsed = JSON.parse(raw); } catch { parsed = { raw }; } + finish(Object.assign({ + ok: true, + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }, parsed)); + } + + mqttc.subscribe(tp.pub, (subErr) => { + if (subErr) { + finish({ + ok: false, + note: "subscribe_failed", + error: subErr.message, + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }); + return; + } + + mqttc.on("message", onMsg); + + mqttc.publish(tp.sub, JSON.stringify(payload), (pubErr) => { + if (pubErr) { + finish({ + ok: false, + note: "publish_failed", + error: pubErr.message, + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }); + } + }); + }); + }); + } + + function send(cfg, payload, timeout = 3000) { + const namespaces = getNamespaceOrder(cfg); + + const runOne = async () => { + let last = null; + for (const ns of namespaces) { + const r = await sendOne(cfg, ns, payload, timeout); + last = r; + if (r && (r.result === true || r.category || r.action || (r.ok && !r.note))) { + saveNamespaceIfChanged(ns); + return r; + } + } + return last || { ok: false, note: "no_namespace_tried" }; + }; + + sendQueue = sendQueue.then(runOne, runOne); + return sendQueue; + } + + async function doLogin(cfg) { + const r = await send(cfg, { + action: "login", + password: LOGIN_PASSWORD + }, 4000); + + loginState.lastTs = Date.now(); + loginState.lastNamespace = (r && r.namespace) || null; + + if (r && r.action === "login" && r.result === true) { + loginState.ok = true; + loginState.lastError = null; + } else { + loginState.ok = false; + loginState.lastError = (r && (r.note || r.error || r.raw)) || "login_failed"; + } + + return r; + } + + async function ensureLogin(cfg) { + return doLogin(cfg); + } + + app.get("/api/addon/itscreen/config", (req, res) => { + const cfg = readCfg(); + res.json({ + ok: true, + config: cfg, + login: loginState, + registration: { configured: hasRegistrationData(cfg) }, + topics: getNamespaceOrder(cfg).map(ns => topicPair(cfg, ns)) + }); + }); + + app.post("/api/addon/itscreen/config/clear", (req, res) => { + const cleared = writeCfg({ + server: "", + deviceId: "", + token: "", + username: "", + password: "", + topicNamespace: "" + }); + + loginState = { + ok: false, + lastTs: Date.now(), + lastError: "config_cleared", + lastNamespace: null + }; + + res.json({ + ok: true, + config: cleared, + login: loginState, + registration: { configured: false } + }); + }); + + app.post("/api/addon/itscreen/login", async (req, res) => { + try { + const cfg = readCfg(); + const r = await doLogin(cfg); + res.json({ + ok: true, + config: readCfg(), + login: loginState, + registration: { configured: hasRegistrationData(readCfg()) }, + result: r + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message, login: loginState }); + } + }); + + app.get("/api/addon/itscreen/get_server", async (req, res) => { + try { + const cfg = readCfg(); + const loginR = await ensureLogin(cfg); + + if (!(loginR && loginR.result === true)) { + const current = readCfg(); + return res.json({ + ok: true, + config: current, + login: loginState, + registration: { configured: hasRegistrationData(current) }, + result: { ok: false, note: "login_failed_before_get", login_result: loginR } + }); + } + + const cfg2 = readCfg(); + const r = await send(cfg2, { + action: "get", + category: "server" + }, 4000); + + const currentCfg = readCfg(); + + if (r && r.category === "server") { + const merged = writeCfg({ + server: (r.host || currentCfg.server || "").toString(), + deviceId: currentCfg.deviceId || getDeviceId(cfg2), + token: currentCfg.token, + username: (r.username || currentCfg.username || "").toString(), + password: (r.password || currentCfg.password || "").toString(), + topicNamespace: (r.namespace || currentCfg.topicNamespace || "").toString() + }); + + return res.json({ + ok: true, + config: merged, + login: loginState, + registration: { configured: hasRegistrationData(merged) }, + result: r + }); + } + + res.json({ + ok: true, + config: currentCfg, + login: loginState, + registration: { configured: hasRegistrationData(currentCfg) }, + result: r + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message, login: loginState }); + } + }); + + app.post("/api/addon/itscreen/register", async (req, res) => { + try { + const body = req.body || {}; + const cfg = readCfg(); + + const server = (body.server || "").toString().trim(); + const username = (body.username || "").toString().trim(); + const password = (body.password || "").toString().trim(); + const token = (body.token || "").toString().trim(); + + if (!server) return res.status(400).json({ ok: false, error: "server is required" }); + if (!username) return res.status(400).json({ ok: false, error: "username is required" }); + if (!password) return res.status(400).json({ ok: false, error: "password is required" }); + + const loginR = await ensureLogin(cfg); + + if (!(loginR && loginR.result === true)) { + const current = readCfg(); + return res.json({ + ok: true, + config: current, + login: loginState, + registration: { configured: hasRegistrationData(current) }, + result: { ok: false, note: "login_failed_before_set", login_result: loginR } + }); + } + + const cfg2 = readCfg(); + const payload = { + action: "set", + category: "server", + host: server, + username, + password + }; + + const r = await send(cfg2, payload, 5000); + + if (r && r.result === true) { + const saved = writeCfg({ + server, + deviceId: cfg2.deviceId || getDeviceId(cfg2), + token, + username, + password, + topicNamespace: r.namespace || cfg2.topicNamespace || "" + }); + return res.json({ + ok: true, + config: saved, + login: loginState, + registration: { configured: hasRegistrationData(saved) }, + result: r + }); + } + + const current = readCfg(); + res.json({ + ok: true, + config: current, + login: loginState, + registration: { configured: hasRegistrationData(current) }, + result: r + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message, login: loginState }); + } + }); + + app.post("/api/addon/itscreen/service/:action", async (req, res) => { + try { + const action = (req.params.action || "").toLowerCase(); + if (!["restart", "stop", "start"].includes(action)) { + return res.status(400).json({ ok: false, error: "bad action" }); + } + + const r = await ctx.run("/bin/systemctl", [action, ITSERVICE], 12000); + if (!r.ok) { + return res.status(502).json({ ok: false, error: r.err || r.out || "systemctl failed" }); + } + + const status = await ctx.run("/bin/systemctl", ["is-active", ITSERVICE], 6000); + res.json({ + ok: true, + action, + unit: ITSERVICE, + active: (status.out || status.err || "").trim() || "unknown" + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message }); + } + }); +}; +JS + +echo "[4/6] frontend addon" +cat > "$ADDON_FRONT/itscreen.js" <<'JS' +(function () { + "use strict"; + + if (window.__iomatexItscreenAddonLoaded) return; + window.__iomatexItscreenAddonLoaded = true; + + const ui = window.IOMATEX_UI; + if (!ui) return; + + const state = ui.state; + + state.itscreenAddon = state.itscreenAddon || { + cfg: {}, + result: {}, + login: {}, + registration: { configured: false }, + busy: { + refresh: false, + login: false, + register: false, + clear: false, + restart: false, + stop: false, + start: false + }, + message: "" + }; + + function esc(s) { + return (s ?? "").toString().replace(/[&<>"']/g, m => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }[m])); + } + + function setMsg(msg) { + state.itscreenAddon.message = (msg || "").toString(); + ui.render(); + } + + function setBusy(key, v) { + state.itscreenAddon.busy[key] = !!v; + ui.render(); + } + + function inputValue(id) { + const el = document.getElementById(id); + return el ? el.value.trim() : ""; + } + + function btn(label, kind, fnName, busyKey, busyLabel) { + const busy = !!state.itscreenAddon.busy[busyKey]; + return ``; + } + + async function loadConfigOnly() { + const j = await ui.call("/api/addon/itscreen/config"); + state.itscreenAddon.cfg = j.config || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + return j; + } + + async function refreshRemote() { + setBusy("refresh", true); + setMsg("Refreshing registration..."); + try { + const j = await ui.call("/api/addon/itscreen/get_server"); + state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = j.result || {}; + await ui.loadMain().catch(() => {}); + setMsg("Registration data refreshed."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("refresh", false); + } + } + + async function doLogin() { + setBusy("login", true); + setMsg("Login in progress..."); + try { + const j = await ui.call("/api/addon/itscreen/login", { method: "POST", body: "{}" }); + state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = j.result || {}; + setMsg(j.login?.ok ? "Login OK." : "Login failed."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("login", false); + } + } + + async function doRegister() { + const server = inputValue("its_server"); + const username = inputValue("its_user"); + const password = inputValue("its_pass"); + const token = inputValue("its_token"); + + if (!server) return setMsg("Server is required."); + if (!username) return setMsg("Username is required."); + if (!password) return setMsg("Password is required."); + + setBusy("register", true); + setMsg("Saving registration..."); + try { + const j = await ui.call("/api/addon/itscreen/register", { + method: "POST", + body: JSON.stringify({ server, username, password, token }) + }); + state.itscreenAddon.cfg = j.config || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = j.result || {}; + await ui.loadMain().catch(() => {}); + await ui.loadDetail("itscreen").catch(() => {}); + setMsg(j.result?.result === true ? "Registration saved." : "Registration request sent."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("register", false); + } + } + + async function doClear() { + setBusy("clear", true); + setMsg("Clearing registration..."); + try { + const j = await ui.call("/api/addon/itscreen/config/clear", { method: "POST", body: "{}" }); + state.itscreenAddon.cfg = j.config || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = {}; + await ui.loadMain().catch(() => {}); + await ui.loadDetail("itscreen").catch(() => {}); + setMsg("Registration cleared."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("clear", false); + } + } + + async function serviceAction(action) { + setBusy(action, true); + setMsg(`Service ${action}...`); + try { + const j = await ui.call(`/api/addon/itscreen/service/${encodeURIComponent(action)}`, { + method: "POST", + body: "{}" + }); + await ui.loadMain().catch(() => {}); + await ui.loadDetail("itscreen").catch(() => {}); + setMsg(`Service ${action} done. Current state: ${j.active || "unknown"}`); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy(action, false); + } + } + + function renderItscreenDetail(service) { + const cfg = state.itscreenAddon.cfg || {}; + const login = state.itscreenAddon.login || {}; + const reg = state.itscreenAddon.registration || { configured: false }; + + const deviceId = (cfg.deviceId || state.health?.hostname || "unknown").toString(); + + document.getElementById("viewTitle").textContent = service.title; + document.getElementById("viewSub").textContent = service.desc || ""; + document.getElementById("viewActions").innerHTML = + ``; + + document.getElementById("view").innerHTML = ` +
+
+
Service status
+
+
Active
${esc(service.status?.active || "-")} +
Started
${esc(service.status?.started_at || "-")} +
State
${esc(service.status?.summary || "-")} +
Running
${esc(service.status?.running_for_text || "-")} +
Unit file
${esc(service.status?.unit_file_state || "-")} +
Unit
${esc(service.unit || "-")} +
+
+ ${btn("Start", "", "window.__itscreenStart()", "start", "Starting...")} + ${btn("Stop", "danger", "window.__itscreenStop()", "stop", "Stopping...")} + ${btn("Restart", "primary", "window.__itscreenRestart()", "restart", "Restarting...")} +
+
+ +
+
Registration
+
+
Configured
${esc(reg.configured ? "yes" : "no")} +
Device ID
${esc(deviceId)} +
Server
${esc(cfg.server || "-")} +
Username
${esc(cfg.username || "-")} +
Password
${esc(cfg.password ? "******" : "-")} +
Token
${esc(cfg.token || "-")} +
Namespace
${esc(cfg.topicNamespace || "-")} +
Login
${esc(login.ok ? "ok" : "not ok")} +
+ +
+
Server
+ +
+ +
+
Username
+ +
+ +
+
Password
+ +
+ +
+
Token
+ +
+ +
+ ${btn("Login", "", "window.__itscreenLogin()", "login", "Working...")} + ${btn("Refresh registration", "", "window.__itscreenRefresh()", "refresh", "Working...")} + ${btn("Save registration", "primary", "window.__itscreenRegister()", "register", "Saving...")} + ${btn("Clear registration", "danger", "window.__itscreenClear()", "clear", "Clearing...")} +
+
+ +
+
Message
+
${esc(state.itscreenAddon.message || "Ready")}
+
+
+ `; + } + + const prevLoadTabData = ui.loadTabData.bind(ui); + const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){}; + const prevRender = ui.render.bind(ui); + + ui.loadTabData = async function () { + if (state.tab === "itscreen") { + await ui.loadDetail("itscreen"); + await loadConfigOnly().catch(() => {}); + return; + } + return prevLoadTabData(); + }; + + ui.refreshDetail = async function () { + if (state.tab === "itscreen") { + await ui.loadDetail("itscreen"); + await loadConfigOnly().catch(() => {}); + ui.render(); + return; + } + return prevRefreshDetail(); + }; + window.refreshDetail = ui.refreshDetail; + + ui.render = function () { + if (state.tab === "itscreen" && state.detail?.service?.key === "itscreen") { + renderItscreenDetail(state.detail.service); + return; + } + return prevRender(); + }; + window.render = ui.render; + + window.__itscreenRefresh = refreshRemote; + window.__itscreenLogin = doLogin; + window.__itscreenRegister = doRegister; + window.__itscreenClear = doClear; + window.__itscreenRestart = () => serviceAction("restart"); + window.__itscreenStop = () => serviceAction("stop"); + window.__itscreenStart = () => serviceAction("start"); + + setTimeout(async () => { + try { + await loadConfigOnly().catch(() => {}); + if (state.tab === "itscreen") ui.render(); + } catch (_) {} + }, 0); +})(); +JS + +echo "[5/6] restart" +systemctl restart "$SERVICE" + +echo "[6/6] done" +echo "Installed backend: $ADDON_BACK/itscreen.js" +echo "Installed frontend: $ADDON_FRONT/itscreen.js" +echo "Restarted: $SERVICE" \ No newline at end of file diff --git a/stage_ui/legacy_reference/ui_installer.sh b/stage_ui/legacy_reference/ui_installer.sh new file mode 100755 index 0000000..e3471eb --- /dev/null +++ b/stage_ui/legacy_reference/ui_installer.sh @@ -0,0 +1,1910 @@ +#!/usr/bin/env bash +set -euo pipefail + +# IOMATEX WebIPC Engineer Console (light core) v4.2.0 +# Base UI: +# - honest read-only statuses +# - addon-first service pages +# - no stop/restart in core +# - MQTT Bridge shown as runtime feature of Mosquitto + +if head -c 3 "$0" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then + echo "ERROR: UTF-8 BOM detected. Save as UTF-8 (without BOM)." >&2 + exit 1 +fi +if grep -q $'\r' "$0" 2>/dev/null; then + echo "ERROR: CRLF detected. Convert file to UNIX (LF) EOL." >&2 + exit 1 +fi + +need_root(){ [ "$(id -u)" -eq 0 ] || { echo "Run as root: sudo bash $0"; exit 1; }; } +need_root + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +APP_DIR="/opt/iomatex-process1-webipc" +APP_PORT="${WEBIPC_PORT:-8099}" +APP_BIND="${WEBIPC_BIND:-0.0.0.0}" + +ADDONS_DIR="${APP_DIR}/addons" +ADDONS_BACKEND_DIR="${ADDONS_DIR}/backend" +ADDONS_PUBLIC_DIR="${APP_DIR}/public/addons" + +MQTT_URL_DEFAULT="${WEBIPC_MQTT_URL:-mqtt://127.0.0.1:1883}" +MQTT_REPLY_MS_DEFAULT="${WEBIPC_MQTT_REPLY_MS:-2200}" +MQTT_NS_DEFAULT="${WEBIPC_MQTT_NS:-}" +LOGIN_PASSWORD_DEFAULT="${WEBIPC_LOGIN_PASSWORD:-eXXI0wkHBmNBnVbE}" + +SERVICE_NAME="iomatex-webipc.service" +CFG_PATH="/etc/iomatex/webipc.json" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +SRC_LOGO="${LOGO_SOURCE:-$SCRIPT_DIR/iomatex_logo_source.png}" + +echo "[0/10] Cleanup previous install artifacts (safe, keep config)" +ts="$(date +%s)" +systemctl stop "${SERVICE_NAME}" 2>/dev/null || true +systemctl disable "${SERVICE_NAME}" 2>/dev/null || true +rm -f "/etc/systemd/system/${SERVICE_NAME}" 2>/dev/null || true +rm -rf "/etc/systemd/system/${SERVICE_NAME}.d" 2>/dev/null || true +systemctl daemon-reload || true +systemctl reset-failed "${SERVICE_NAME}" 2>/dev/null || true + +if [ -d "$APP_DIR" ]; then + mv -f "$APP_DIR" "${APP_DIR}.prev.${ts}" || rm -rf "$APP_DIR" +fi + +echo "[1/10] Ensure runtime packages exist" +if ! command -v node >/dev/null 2>&1; then + apt-get update + apt-get install -y ca-certificates curl gnupg + curl -fsSL https://deb.nodesource.com/setup_20.x | bash - + apt-get install -y nodejs +fi +apt-get update +apt-get install -y python3 python3-pil +node -v +npm -v + +echo "[2/10] Prepare directories + config" +mkdir -p "$APP_DIR/public" "$ADDONS_BACKEND_DIR" "$ADDONS_PUBLIC_DIR" /etc/iomatex +if [ ! -f "$CFG_PATH" ]; then + cat >"$CFG_PATH" <<'JSON' +{ + "server": "", + "deviceId": "", + "token": "", + "clientId": "", + "registeredAt": "" +} +JSON +fi + +echo "[3/10] Write package.json" +cat > "$APP_DIR/package.json" <<'JSON' +{ + "name": "iomatex-process1-webipc", + "version": "4.2.0", + "private": true, + "main": "server.js", + "type": "commonjs", + "dependencies": { + "express": "^4.19.2", + "mqtt": "^5.7.2" + } +} +JSON + +echo "[4/10] Write server.js" +cat > "$APP_DIR/server.js" <<'JS' +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const os = require("os"); +const express = require("express"); +const mqtt = require("mqtt"); +const { execFile } = require("child_process"); + +const BIND = process.env.WEBIPC_BIND || "0.0.0.0"; +const PORT = parseInt(process.env.WEBIPC_PORT || "8099", 10); +const CFG_PATH = process.env.WEBIPC_CONFIG || "/etc/iomatex/webipc.json"; +const MQTT_URL = process.env.WEBIPC_MQTT_URL || "mqtt://127.0.0.1:1883"; +const MQTT_NS = (process.env.WEBIPC_MQTT_NS || "").trim(); +const MQTT_REPLY_MS = parseInt(process.env.WEBIPC_MQTT_REPLY_MS || "2200", 10); +const LOGIN_PASSWORD = (process.env.WEBIPC_LOGIN_PASSWORD || "").toString().trim(); +const LOGIN_ENABLED = LOGIN_PASSWORD.length > 0; +const MQTT_BRIDGE_ENV = "/etc/iomatex/mqtt_bridge.env"; +const DRM_ROOT = "/sys/class/drm"; +const APP_DIR = "/opt/iomatex-process1-webipc"; +const ADDONS_BACKEND_DIR = path.join(APP_DIR, "addons", "backend"); +const ADDONS_PUBLIC_DIR = path.join(APP_DIR, "public", "addons"); + +const app = express(); +app.disable("x-powered-by"); +app.use(express.json({ limit: "256kb" })); +app.use(express.static(path.join(__dirname, "public"), { etag: false, maxAge: 0 })); +app.use("/addons", express.static(ADDONS_PUBLIC_DIR, { etag: false, maxAge: 0 })); + +function run(cmd, args, timeout = 8000) { + return new Promise((resolve) => { + execFile(cmd, args, { timeout, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => { + if (err) return resolve({ ok: false, err: (stderr || err.message || "").trim(), out: (stdout || "").trim() }); + resolve({ ok: true, out: (stdout || "").trim(), err: (stderr || "").trim() }); + }); + }); +} +function runShell(cmd, timeout = 10000) { + return run("/bin/bash", ["-lc", cmd], timeout); +} +function readJson(p, fallback) { + try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return fallback; } +} +function writeConfig(obj) { + const safe = { + server: (obj.server || "").toString().trim(), + deviceId: (obj.deviceId || "").toString().trim(), + token: (obj.token || "").toString().trim(), + clientId: (obj.clientId || "").toString().trim(), + registeredAt: (obj.registeredAt || "").toString().trim() + }; + fs.mkdirSync(path.dirname(CFG_PATH), { recursive: true }); + fs.writeFileSync(CFG_PATH, JSON.stringify(safe, null, 2) + "\n", "utf8"); + return safe; +} +function readConfig() { + return readJson(CFG_PATH, { server: "", deviceId: "", token: "", clientId: "", registeredAt: "" }); +} +function readFirstInt(p) { + try { return parseInt(fs.readFileSync(p, "utf8").trim(), 10); } catch { return null; } +} +function cpuTempC() { + const t = readFirstInt("/sys/class/thermal/thermal_zone0/temp"); + return (t == null || Number.isNaN(t)) ? null : Math.round((t / 1000) * 10) / 10; +} +function loadAvg() { + const la = os.loadavg(); + return { "1m": Math.round(la[0] * 100) / 100, "5m": Math.round(la[1] * 100) / 100, "15m": Math.round(la[2] * 100) / 100 }; +} +function memInfo() { + try { + const m = fs.readFileSync("/proc/meminfo", "utf8"); + const get = (k) => { const r = new RegExp("^" + k + ":\\s+(\\d+)", "m").exec(m); return r ? parseInt(r[1], 10) : null; }; + const total = get("MemTotal"); + const avail = get("MemAvailable"); + if (!total || !avail) return null; + const used = total - avail; + return { total_kb: total, used_kb: used, avail_kb: avail, used_pct: Math.round((used / total) * 1000) / 10 }; + } catch { return null; } +} + +function nsFromServer(host) { + const h = (host || "").toString().toLowerCase(); + if (h.includes("iomatex")) return "iomatex"; + return "it-screen"; +} +function mqttTopics(cfg, payload) { + const server = (payload.server || cfg.server || "").trim(); + const deviceId = (payload.deviceId || cfg.deviceId || os.hostname()).trim(); + const ns = MQTT_NS || nsFromServer(server); + const base = `${ns}/$devices/settings/${deviceId}`; + return { ns, deviceId, sub: `${base}/sub`, pub: `${base}/pub` }; +} + +function fmtDuration(sec) { + sec = parseInt(sec || 0, 10); + if (!Number.isFinite(sec) || sec < 0) return "-"; + const d = Math.floor(sec / 86400); sec %= 86400; + const h = Math.floor(sec / 3600); sec %= 3600; + const m = Math.floor(sec / 60); sec %= 60; + if (d > 0) return `${d}d ${h}h ${m}m`; + if (h > 0) return `${h}h ${m}m`; + if (m > 0) return `${m}m ${sec}s`; + return `${sec}s`; +} +function getBootEpochMs() { + return Date.now() - Math.floor(os.uptime() * 1000); +} +function monotonicUsecToEpochText(usec) { + const u = parseInt(usec || "0", 10); + if (!Number.isFinite(u) || u <= 0) return ""; + const ms = getBootEpochMs() + Math.floor(u / 1000); + return new Date(ms).toISOString().replace("T", " ").replace("Z", " UTC"); +} +function runningForSec(usec) { + const u = parseInt(usec || "0", 10); + if (!Number.isFinite(u) || u <= 0) return null; + const bootMs = getBootEpochMs(); + const startMs = bootMs + Math.floor(u / 1000); + return Math.max(0, Math.floor((Date.now() - startMs) / 1000)); +} +function fmtRate(bytesPerSec) { + const v = Number(bytesPerSec || 0); + if (!Number.isFinite(v) || v < 0) return "-"; + if (v >= 1024 * 1024) return `${Math.round((v / (1024 * 1024)) * 100) / 100} MB/s`; + if (v >= 1024) return `${Math.round((v / 1024) * 100) / 100} KB/s`; + return `${Math.round(v)} B/s`; +} + +function parseEnvFile(p) { + try { + const raw = fs.readFileSync(p, "utf8"); + const out = {}; + for (const line0 of raw.split("\n")) { + const line = line0.trim(); + if (!line || line.startsWith("#")) continue; + const m = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/); + if (!m) continue; + let v = m[2].trim(); + if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1); + out[m[1]] = v; + } + return out; + } catch { + return {}; + } +} +function maskSecret(v) { + v = (v || "").toString().trim(); + return v ? "******" : "-"; +} +function bridgeConfigSummary() { + const env = parseEnvFile(MQTT_BRIDGE_ENV); + const enabledRaw = (env.ENABLE_BRIDGE || env.BRIDGE_ENABLED || "").toString().trim().toLowerCase(); + const enabled = ["1", "true", "yes", "on"].includes(enabledRaw); + const remote_host = env.REMOTE_HOST || env.BRIDGE_REMOTE_HOST || env.MQTT_REMOTE_HOST || ""; + const remote_port = env.REMOTE_PORT || env.BRIDGE_REMOTE_PORT || env.MQTT_REMOTE_PORT || ""; + const username = env.REMOTE_USERNAME || env.BRIDGE_REMOTE_USERNAME || env.MQTT_REMOTE_USERNAME || env.USERNAME || ""; + const password = env.REMOTE_PASSWORD || env.BRIDGE_REMOTE_PASSWORD || env.MQTT_REMOTE_PASSWORD || env.PASSWORD || ""; + const client_id = env.BRIDGE_CLIENT_ID || env.CLIENT_ID || env.MQTT_CLIENT_ID || ""; + const configured = !!(enabled && remote_host && remote_port); + return { + env_exists: fs.existsSync(MQTT_BRIDGE_ENV), + enabled, + configured, + remote_host, + remote_port, + username, + password_masked: maskSecret(password), + client_id, + raw: env + }; +} +function bridgeConfPath() { + return "/etc/mosquitto/conf.d/50-iomatex-bridge.conf"; +} +function bridgeConfSummary() { + const p = bridgeConfPath(); + const exists = fs.existsSync(p); + let text = ""; + try { text = exists ? fs.readFileSync(p, "utf8") : ""; } catch {} + const has_connection = /(^|\n)\s*connection\s+iomatex_bridge\s*$/m.test(text); + const has_address = /(^|\n)\s*address\s+\S+:\d+\s*$/m.test(text); + const has_v1_edge = /(^|\n)\s*topic\s+v1\/edge\/#\s+(out|in)\s+/m.test(text); + return { + path: p, + exists, + has_connection, + has_address, + has_v1_edge, + valid: !!(exists && has_connection && has_address) + }; +} + +function detectX11State(raw) { + const envDisp = process.env.DISPLAY || ""; + const xSock = fs.existsSync("/tmp/.X11-unix/X0") || fs.existsSync("/tmp/.X11-unix/X1"); + const hasProc = /\bXorg\b|\bXwayland\b|\sX\s/.test(raw || ""); + const active = !!(envDisp || xSock || hasProc); + return { + active, + display: envDisp || (fs.existsSync("/tmp/.X11-unix/X0") ? ":0" : ""), + x_socket: xSock, + note: active ? "display stack detected" : "display stack not detected" + }; +} + +function readText(p) { + try { return fs.readFileSync(p, "utf8").trim(); } catch { return ""; } +} +function readBuf(p) { + try { return fs.readFileSync(p); } catch { return null; } +} +function fileExists(p) { + try { fs.accessSync(p); return true; } catch { return false; } +} +function cleanAscii(buf) { + return (buf || Buffer.alloc(0)).toString("ascii").replace(/\0/g, "").replace(/\r/g, "").replace(/\n/g, "").trim(); +} +function parseManufacturerId(b1, b2) { + const word = ((b1 << 8) | b2) & 0xffff; + const c1 = String.fromCharCode(((word >> 10) & 0x1f) + 64); + const c2 = String.fromCharCode(((word >> 5) & 0x1f) + 64); + const c3 = String.fromCharCode((word & 0x1f) + 64); + const s = `${c1}${c2}${c3}`.replace(/@/g, ""); + return /^[A-Z]{3}$/.test(s) ? s : ""; +} +function parseEdid(edid) { + if (!edid || edid.length < 128) { + return { + present: false, + monitor_name: "", + serial_text: "", + manufacturer_id: "", + product_code: "", + size_cm: "", + size_inch: "", + raw_length: edid ? edid.length : 0 + }; + } + + let monitorName = ""; + let serialText = ""; + + for (let off = 54; off + 18 <= edid.length; off += 18) { + const d = edid.slice(off, off + 18); + if (d[0] === 0x00 && d[1] === 0x00 && d[2] === 0x00 && d[3] === 0xfc) monitorName = cleanAscii(d.slice(5, 18)); + if (d[0] === 0x00 && d[1] === 0x00 && d[2] === 0x00 && d[3] === 0xff) serialText = cleanAscii(d.slice(5, 18)); + } + + const manufacturerId = parseManufacturerId(edid[8], edid[9]); + const productCode = "0x" + Buffer.from([edid[10], edid[11]]).reverse().toString("hex").toUpperCase(); + const widthCm = edid[21] || 0; + const heightCm = edid[22] || 0; + + let sizeInch = ""; + if (widthCm > 0 && heightCm > 0) { + const diagCm = Math.sqrt((widthCm * widthCm) + (heightCm * heightCm)); + sizeInch = (diagCm / 2.54).toFixed(1) + "\""; + } + + return { + present: true, + monitor_name: monitorName, + serial_text: serialText, + manufacturer_id: manufacturerId, + product_code: productCode, + size_cm: (widthCm && heightCm) ? `${widthCm} x ${heightCm} cm` : "", + size_inch: sizeInch, + raw_length: edid.length + }; +} +function connectorKind(name) { + const n = (name || "").toUpperCase(); + if (n.includes("HDMI")) return "hdmi"; + if (n.includes("DP-") || n.includes("DISPLAYPORT") || n.includes("DP")) return "dp"; + if (n.includes("EDP")) return "edp"; + if (n.includes("LVDS")) return "lvds"; + if (n.includes("DSI")) return "dsi"; + if (n.includes("VGA")) return "vga"; + if (n.includes("DVI")) return "dvi"; + return "other"; +} +function listDrmConnectors() { + try { + if (!fileExists(DRM_ROOT)) return []; + return fs.readdirSync(DRM_ROOT) + .filter((name) => fileExists(path.join(DRM_ROOT, name, "status"))) + .sort() + .map((name) => path.join(DRM_ROOT, name)); + } catch { + return []; + } +} +function readModes(dir) { + const txt = readText(path.join(dir, "modes")); + return txt ? txt.split("\n").map(x => x.trim()).filter(Boolean) : []; +} +function readConnector(dir) { + const name = path.basename(dir); + const status = readText(path.join(dir, "status")) || "unknown"; + const enabled = readText(path.join(dir, "enabled")) || ""; + const dpms = readText(path.join(dir, "dpms")) || ""; + const modes = readModes(dir); + const edid = parseEdid(readBuf(path.join(dir, "edid"))); + + return { + connector: name, + kind: connectorKind(name), + status, + enabled, + dpms, + connected: status === "connected", + modes, + preferred_mode: modes[0] || "", + edid + }; +} +function getDisplaySnapshot() { + const connectors = listDrmConnectors().map(readConnector); + const hdmi = connectors.filter(x => x.kind === "hdmi"); + const connectedHdmi = hdmi.filter(x => x.connected); + const anyConnected = connectors.some(x => x.connected); + + return { + ok: true, + hostname: os.hostname(), + drm_root: DRM_ROOT, + any_connected: anyConnected, + connectors, + hdmi, + connected_hdmi: connectedHdmi, + summary: { + connector_count: connectors.length, + hdmi_count: hdmi.length, + connected_count: connectors.filter(x => x.connected).length, + connected_hdmi_count: connectedHdmi.length, + hdmi_connected: connectedHdmi.length > 0, + first_connected_hdmi: connectedHdmi[0] || null + } + }; +} + +let mqttClient = null; +let mqttLast = { ok: false, note: "not_connected" }; +let mqttServerState = null; +let loginState = { enabled: LOGIN_ENABLED, ok: false, last_ts: null, last_error: null, password_set: LOGIN_ENABLED }; + +const networkCache = { + iface: "", + rx_bytes: null, + tx_bytes: null, + ts_ms: null, + download_bps: null, + upload_bps: null, + last: null +}; + +function mqttEnsure() { + if (mqttClient) return mqttClient; + mqttClient = mqtt.connect(MQTT_URL, { + reconnectPeriod: 1000, + connectTimeout: 4000, + keepalive: 30, + clean: true + }); + mqttClient.on("connect", () => { mqttLast = { ok: true, note: "connected", url: MQTT_URL }; }); + mqttClient.on("reconnect", () => { mqttLast = { ok: false, note: "reconnecting" }; }); + mqttClient.on("close", () => { mqttLast = { ok: false, note: "closed" }; }); + mqttClient.on("error", (e) => { mqttLast = { ok: false, note: "error", message: e.message }; }); + mqttClient.on("message", (topic, buf) => { + const raw = (buf || Buffer.from("")).toString(); + let parsed = null; + try { parsed = JSON.parse(raw); } catch { parsed = { raw }; } + if (parsed && typeof parsed === "object" && parsed.category === "server" && typeof parsed.host === "string") mqttServerState = parsed; + if (parsed && typeof parsed === "object" && parsed.action === "login") { + loginState.ok = !!parsed.result; + loginState.last_ts = Date.now(); + loginState.last_error = parsed.result ? null : "login_failed"; + } + }); + return mqttClient; +} + +let mqttLock = Promise.resolve(); +function mqttSendWaitReply(cfg, payload, opts = {}) { + const client = mqttEnsure(); + const { sub, pub, ns, deviceId } = mqttTopics(cfg, payload); + const msg = Object.assign({}, payload); + delete msg.ts; + const maxWait = Math.max(300, Math.min(parseInt(opts.reply_ms || MQTT_REPLY_MS, 10) || MQTT_REPLY_MS, 15000)); + + const runOne = () => new Promise((resolve) => { + client.subscribe(pub, { qos: 0 }, (err) => { + if (err) return resolve({ ok: false, note: "subscribe_failed", error: err.message, ns, deviceId }); + const t0 = Date.now(); + const timer = setTimeout(() => { + client.removeListener("message", onMsg); + resolve({ ok: true, sent: true, note: "sent_no_reply", topic_sub: sub, topic_pub: pub, ms: Date.now() - t0, ns, deviceId }); + }, maxWait); + + function onMsg(topic, buf) { + if (topic !== pub) return; + clearTimeout(timer); + client.removeListener("message", onMsg); + const raw = (buf || Buffer.from("")).toString(); + let parsed = null; + try { parsed = JSON.parse(raw); } catch { parsed = { raw }; } + resolve({ ok: true, sent: true, reply: parsed, topic_sub: sub, topic_pub: pub, ms: Date.now() - t0, ns, deviceId }); + } + + client.on("message", onMsg); + client.publish(sub, JSON.stringify(msg), { qos: 0, retain: false }, (perr) => { + if (perr) { + clearTimeout(timer); + client.removeListener("message", onMsg); + resolve({ ok: false, note: "publish_failed", error: perr.message, ns, deviceId }); + } + }); + }); + }); + + mqttLock = mqttLock.then(runOne, runOne); + return mqttLock; +} + +async function ensureLoggedForRegistration(cfg) { + if (!LOGIN_ENABLED) return { ok: true, skipped: true }; + if (loginState.ok === true) return { ok: true, reused: true }; + const deviceId = (cfg.deviceId || os.hostname()).trim(); + const payload = { action: "login", password: LOGIN_PASSWORD, deviceId, server: cfg.server || "" }; + const r = await mqttSendWaitReply(cfg, payload, { reply_ms: 3500 }); + if (r && r.reply && r.reply.action === "login") { + loginState.ok = !!r.reply.result; + loginState.last_ts = Date.now(); + loginState.last_error = r.reply.result ? null : "login_failed"; + } else { + loginState.last_ts = Date.now(); + loginState.last_error = r.note || "no_reply"; + } + return r; +} + +const SERVICES = { + itscreen: { + key: "itscreen", + title: "Itscreen", + unit: "itscreen-x11.service", + desc: "Main itscreen runtime (X11).", + paths: ["/etc/iomatex/webipc.json", "/etc/systemd/system/itscreen-x11.service", "/lib/systemd/system/itscreen-x11.service"], + access: { kind: "none" } + }, + x11: { + key: "x11", + title: "Display", + unit: "display stack", + desc: "Display stack and HDMI monitor status for local screen output.", + paths: ["/sys/class/drm", "/tmp/.X11-unix", "/usr/bin/Xorg", "/etc/X11"], + access: { kind: "none" } + }, + cockpit: { + key: "cockpit", + title: "Cockpit", + unit: "cockpit.service", + socket: "cockpit.socket", + desc: "Cockpit web administration.", + paths: ["/etc/cockpit/cockpit.conf", "/lib/systemd/system/cockpit.service", "/lib/systemd/system/cockpit.socket"], + access: { kind: "url", url: "http://127.0.0.1:9090", label: "Open Cockpit" } + }, + mosquitto: { + key: "mosquitto", + title: "Mosquitto", + unit: "mosquitto.service", + desc: "Local MQTT broker.", + paths: ["/etc/mosquitto/mosquitto.conf", "/etc/mosquitto/conf.d", "/lib/systemd/system/mosquitto.service"], + access: { kind: "none" } + }, + bridge: { + key: "bridge", + title: "MQTT Bridge", + unit: "mqtt bridge runtime", + desc: "Bridge runtime inside Mosquitto.", + paths: ["/etc/iomatex/mqtt_bridge.env", "/etc/mosquitto/conf.d/50-iomatex-bridge.conf", "/etc/systemd/system/iomatex-mqtt-bridge.service"], + access: { kind: "none" } + }, + z2m: { + key: "z2m", + title: "Zigbee2MQTT", + unit: "zigbee2mqtt.service", + desc: "Zigbee2MQTT runtime.", + paths: ["/opt/zigbee2mqtt/data/configuration.yaml", "/opt/zigbee2mqtt/data/state.json", "/etc/systemd/system/zigbee2mqtt.service"], + access: { kind: "url", url: "http://127.0.0.1:8081", label: "Open Z2M" } + }, + rtcockpit: { + key: "rtcockpit", + title: "RT Cockpit", + unit: "iomatex-rt-cockpit.service", + desc: "Reverse SSH tunnel for Cockpit.", + paths: ["/etc/systemd/system/iomatex-rt-cockpit.service", "/usr/local/sbin", "/etc/iomatex"], + access: { kind: "none" } + }, + rtz2m: { + key: "rtz2m", + title: "RT Z2M", + unit: "iomatex-rt-z2m.service", + desc: "Reverse SSH tunnel for Zigbee2MQTT.", + paths: ["/etc/systemd/system/iomatex-rt-z2m.service", "/usr/local/sbin", "/etc/iomatex"], + access: { kind: "none" } + }, + rtwebui: { + key: "rtwebui", + title: "RT Iomatex", + unit: "iomatex-rt-webui.service", + desc: "Reverse SSH tunnel for IOMATEX Web UI.", + paths: ["/etc/systemd/system/iomatex-rt-webui.service", "/usr/local/sbin", "/etc/iomatex"], + access: { kind: "none" } + } +}; + +function parseShow(out) { + const o = {}; + for (const line of (out || "").split("\n")) { + const i = line.indexOf("="); + if (i > 0) o[line.slice(0, i)] = line.slice(i + 1); + } + return o; +} + +async function systemdShow(unit) { + const show = await run("/bin/systemctl", [ + "show", unit, "--no-page", + "--property=Id,Description,LoadState,ActiveState,SubState,UnitFileState,ExecMainStartTimestamp,ExecMainStartTimestampMonotonic,ActiveEnterTimestamp,ActiveEnterTimestampMonotonic,FragmentPath,TriggeredBy,Triggers,ExecStart" + ], 8000); + return parseShow(show.out || ""); +} +async function systemctlIsActive(unit) { + const r = await run("/bin/systemctl", ["is-active", unit], 6000); + const txt = (r.out || r.err || "").trim(); + return txt || "unknown"; +} +async function systemctlIsEnabled(unit) { + const r = await run("/bin/systemctl", ["is-enabled", unit], 6000); + const txt = (r.out || r.err || "").trim(); + return txt || "unknown"; +} + +function enrichShow(p) { + const startMono = p.ExecMainStartTimestampMonotonic || p.ActiveEnterTimestampMonotonic || ""; + const started_at = p.ExecMainStartTimestamp || p.ActiveEnterTimestamp || monotonicUsecToEpochText(startMono) || ""; + const running_sec = runningForSec(startMono); + return { + started_at: started_at || "", + running_for_sec: running_sec, + running_for_text: running_sec == null ? "-" : fmtDuration(running_sec) + }; +} + +async function unitStatus(unit) { + const p = await systemdShow(unit); + const load = (p.LoadState || "").trim() || "unknown"; + const sub = (p.SubState || "").trim() || ""; + const activeShow = (p.ActiveState || "").trim() || "unknown"; + const activeReal = await systemctlIsActive(unit); + const enabledReal = await systemctlIsEnabled(unit); + const extra = enrichShow(p); + + if (load === "not-found" || activeReal === "not-found") { + return { + unit, + load_state: "not-found", + active: "not_installed", + sub: "", + unit_file_state: "not_installed", + badge: "gray", + summary: "not installed", + show: p, + started_at: "", + running_for_text: "-", + error_text: `${unit} is not installed` + }; + } + + let active = activeReal || activeShow || "unknown"; + let badge = "gray"; + let summary = "inactive"; + let errorText = ""; + + if (load === "error" || active === "failed" || sub === "failed") { + badge = "red"; + summary = "error"; + active = "failed"; + } else if (active === "active" || activeShow === "active") { + badge = "green"; + summary = "active"; + active = "active"; + } else if (active === "activating" || active === "deactivating" || activeShow === "activating" || activeShow === "deactivating") { + badge = "amber"; + summary = active; + } else if (active === "inactive") { + badge = "gray"; + summary = "inactive"; + } else { + badge = "gray"; + summary = active || "unknown"; + } + + if (active === "failed") { + const err = await runShell(`journalctl -u '${unit}' -n 30 --no-pager -o short-iso 2>/dev/null || true`, 9000); + errorText = (err.out || "").trim() || "Service failed"; + } + + return { + unit, + load_state: load, + active, + sub, + unit_file_state: enabledReal || (p.UnitFileState || "").trim() || "unknown", + badge, + summary, + show: p, + started_at: extra.started_at, + running_for_text: extra.running_for_text, + error_text: errorText + }; +} + +async function cockpitStatus() { + const svc = await unitStatus("cockpit.service"); + const sock = await unitStatus("cockpit.socket"); + + if (svc.summary === "not installed" && sock.summary === "not installed") { + return { + unit: "cockpit.service", + load_state: "not-found", + active: "not_installed", + sub: "", + unit_file_state: "not_installed", + badge: "gray", + summary: "not installed", + show: {}, + started_at: "", + running_for_text: "-", + error_text: "cockpit.service is not installed" + }; + } + + let badge = "gray"; + let summary = "inactive"; + let active = "inactive"; + let errorText = ""; + + if (svc.badge === "red" || sock.badge === "red") { + badge = "red"; + summary = "error"; + active = "failed"; + errorText = [svc.error_text || "", sock.error_text || ""].filter(Boolean).join("\n\n") || "Cockpit failed"; + } else if (svc.active === "active" || sock.active === "active") { + badge = "green"; + summary = "active"; + active = "active"; + } else if (svc.active === "activating" || svc.active === "deactivating" || sock.active === "activating" || sock.active === "deactivating") { + badge = "amber"; + summary = "transition"; + active = "activating"; + } + + return { + unit: "cockpit.service", + load_state: svc.load_state, + active, + sub: svc.sub || sock.sub || "", + unit_file_state: svc.unit_file_state || sock.unit_file_state || "unknown", + badge, + summary, + show: { + service: svc.show || {}, + socket: sock.show || {} + }, + started_at: svc.started_at || sock.started_at || "", + running_for_text: svc.running_for_text || sock.running_for_text || "-", + error_text: errorText + }; +} + +async function x11Status() { + const p = await runShell(`ps -ef 2>/dev/null | grep -E 'Xorg|Xwayland|\\sX\\s' | grep -v grep || true`, 7000); + const x = detectX11State(p.out || ""); + const display = getDisplaySnapshot(); + + let badge = "gray"; + let summary = "inactive"; + let active = "inactive"; + + if (display.summary.hdmi_connected) { + badge = "green"; + summary = "hdmi connected"; + active = x.active ? "active" : "inactive"; + } else if (display.any_connected) { + badge = "amber"; + summary = "display connected"; + active = x.active ? "active" : "inactive"; + } else if (x.active) { + badge = "green"; + summary = "display stack active"; + active = "active"; + } + + return { + unit: "display stack", + load_state: x.active ? "detected" : "not_detected", + active, + sub: x.display || "", + unit_file_state: "-", + badge, + summary, + show: { FragmentPath: "-", ExecMainStartTimestamp: "-", XProcessList: p.out || "" }, + started_at: "-", + running_for_text: "-", + error_text: "", + x11: x, + display + }; +} + +async function getReverseTunnelSnapshot() { + const cmd = `extip="$(curl -4 -s https://api.ipify.org || true)"; ps -eo args | grep -F '/usr/lib/autossh/autossh' | grep -F ' -R 127.0.0.1:' | grep -v grep | while read -r line; do sshp="$(printf '%s\\n' "$line" | sed -nE 's/.* -p ([0-9]+) .*/\\1/p')"; remote="$(printf '%s\\n' "$line" | sed -nE 's/.* -R 127\\.0\\.0\\.1:([0-9]+):127\\.0\\.0\\.1:([0-9]+) .*/\\1/p')"; localp="$(printf '%s\\n' "$line" | sed -nE 's/.* -R 127\\.0\\.0\\.1:([0-9]+):127\\.0\\.0\\.1:([0-9]+) .*/\\2/p')"; user="$(printf '%s\\n' "$line" | sed -nE 's/.* ([^ @]+)@([^ ]+)$/\\1/p')"; host="$(printf '%s\\n' "$line" | sed -nE 's/.* ([^ @]+)@([^ ]+)$/\\2/p')"; svc="unknown"; unit=""; [ "$localp" = "9090" ] && svc="cockpit" && unit="iomatex-rt-cockpit.service"; [ "$localp" = "8081" ] && svc="z2m" && unit="iomatex-rt-z2m.service"; [ "$localp" = "8099" ] && svc="webui" && unit="iomatex-rt-webui.service"; state="$(systemctl is-active "$unit" 2>/dev/null || echo unknown)"; printf '%s|%s|%s|%s|%s|%s|127.0.0.1:%s|%s\\n' "$svc" "$state" "$host" "$remote" "$user" "$sshp" "$localp" "$extip"; done | sort`; + const r = await runShell(cmd, 15000); + const rows = []; + for (const line of (r.out || "").split("\n")) { + const s = line.trim(); + if (!s) continue; + const [svc, state, host, remote, user, ssh_port, local_target, extip] = s.split("|"); + rows.push({ svc, state, host, remote, user, ssh_port, local_target, extip }); + } + return rows; +} + +async function reverseTunnelStatus(unit, svcKey) { + const s = await unitStatus(unit); + if (s.summary === "not installed") return s; + + const rows = await getReverseTunnelSnapshot(); + let row = null; + if (svcKey === "rtcockpit") row = rows.find(x => x.svc === "cockpit") || null; + if (svcKey === "rtz2m") row = rows.find(x => x.svc === "z2m") || null; + if (svcKey === "rtwebui") row = rows.find(x => x.svc === "webui") || null; + + return Object.assign({}, s, { + tunnel: row || { svc: "", state: "", host: "", remote: "", user: "", ssh_port: "", local_target: "", extip: "" } + }); +} + +function parseZ2MPortFromConfig() { + const cfg = "/opt/zigbee2mqtt/data/configuration.yaml"; + try { + const raw = fs.readFileSync(cfg, "utf8"); + let m = raw.match(/^\s*port:\s*["']?([^"'\n#]+)["']?\s*$/m); + if (m && m[1]) return m[1].trim(); + m = raw.match(/^\s*serial:\s*\n(?:.*\n){0,20}?\s*port:\s*["']?([^"'\n#]+)["']?\s*$/m); + if (m && m[1]) return m[1].trim(); + return ""; + } catch { + return ""; + } +} + +async function getUsbStickInfo() { + const configuredPort = parseZ2MPortFromConfig(); + let configuredExists = false; + let configuredResolved = ""; + + if (configuredPort) { + try { + configuredExists = fs.existsSync(configuredPort); + if (configuredExists) configuredResolved = fs.realpathSync(configuredPort); + } catch {} + } + + const byid = await runShell(`ls -l /dev/serial/by-id 2>/dev/null || true`, 5000); + const tty = await runShell(`ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null || true`, 5000); + const lsusb = await run("/usr/bin/lsusb", [], 8000); + + const byidLines = (byid.out || "").split("\n").map(x => x.trim()).filter(Boolean); + const likelyById = byidLines.filter(x => /(zigbee|sonoff|cc2652|ember|ezsp|zbdongle|nabu|slae|thirdreality|tubeszb)/i.test(x)); + + const usbLikely = ((lsusb.out || "").split("\n").map(x => x.trim()).filter(Boolean)) + .filter(x => /(zigbee|sonoff|cc2652|ezsp|ember|nabu|slae|silicon labs|texas instruments|tubeszb|dongle)/i.test(x)); + + const connected = configuredPort + ? configuredExists + : (likelyById.length > 0 || usbLikely.length > 0); + + return { + connected, + configured_port: configuredPort || "", + configured_port_exists: configuredExists, + configured_port_resolved: configuredResolved, + by_id: byid.out || "", + tty: tty.out || "", + lsusb: lsusb.out || "", + likely_by_id_count: likelyById.length, + likely_usb_count: usbLikely.length + }; +} + +function getIfaceCounters(iface) { + try { + const rx = parseInt(fs.readFileSync(`/sys/class/net/${iface}/statistics/rx_bytes`, "utf8").trim(), 10); + const tx = parseInt(fs.readFileSync(`/sys/class/net/${iface}/statistics/tx_bytes`, "utf8").trim(), 10); + if (!Number.isFinite(rx) || !Number.isFinite(tx)) return null; + return { rx, tx }; + } catch { + return null; + } +} + +async function networkStatus() { + const def = await runShell(`ip route show default 2>/dev/null | awk '/default/ {print $5; exit}'`, 5000); + let iface = (def.out || "").trim(); + + if (!iface) { + const alt = await runShell(`ip -o link show | awk -F': ' '$2!="lo"{print $2}' | head -n1`, 5000); + iface = (alt.out || "").trim(); + } + + let ipv4 = ""; + let connType = ""; + let linkSpeed = "-"; + let internet = false; + let internetText = "offline"; + let gateway = "-"; + let dns = "-"; + let uploadText = "-"; + let downloadText = "-"; + + if (iface) { + connType = iface.startsWith("wl") ? "wlan0" : (iface.startsWith("en") || iface.startsWith("eth") ? "eth0" : iface); + + const ip4 = await runShell(`ip -4 -o addr show dev '${iface}' 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n1`, 5000); + ipv4 = (ip4.out || "").trim(); + + const gw = await runShell(`ip route show default 2>/dev/null | awk '/default/ && $5=="${iface}" {print $3; exit}'`, 5000); + gateway = (gw.out || "").trim() || "-"; + + const dnsR = await runShell(`awk '/^nameserver /{print $2}' /etc/resolv.conf 2>/dev/null | paste -sd, -`, 5000); + dns = (dnsR.out || "").trim() || "-"; + + if (iface.startsWith("wl")) { + const iw = await runShell(`command -v iw >/dev/null 2>&1 && iw dev '${iface}' link 2>/dev/null | awk -F': ' '/tx bitrate/ {print $2; exit}' || true`, 6000); + linkSpeed = (iw.out || "").trim() || "-"; + } else { + try { + const s = fs.readFileSync(`/sys/class/net/${iface}/speed`, "utf8").trim(); + if (s && s !== "-1") linkSpeed = `${s} Mb/s`; + } catch {} + } + + const now = Date.now(); + const counters = getIfaceCounters(iface); + + if (counters) { + if (networkCache.iface === iface && networkCache.ts_ms != null && networkCache.rx_bytes != null && networkCache.tx_bytes != null) { + const dt = Math.max(1, (now - networkCache.ts_ms) / 1000); + networkCache.download_bps = Math.max(0, (counters.rx - networkCache.rx_bytes) / dt); + networkCache.upload_bps = Math.max(0, (counters.tx - networkCache.tx_bytes) / dt); + } + networkCache.iface = iface; + networkCache.rx_bytes = counters.rx; + networkCache.tx_bytes = counters.tx; + networkCache.ts_ms = now; + } + + uploadText = networkCache.upload_bps == null ? "-" : fmtRate(networkCache.upload_bps); + downloadText = networkCache.download_bps == null ? "-" : fmtRate(networkCache.download_bps); + } + + const ping = await run("/usr/bin/timeout", ["4", "/bin/ping", "-c", "1", "-W", "2", "1.1.1.1"], 5000); + internet = !!ping.ok; + internetText = internet ? "online" : "offline"; + + const result = { + ok: true, + iface: iface || "", + connection_type: connType || "-", + ipv4: ipv4 || "-", + gateway, + dns, + internet, + internet_text: internetText, + link_speed: linkSpeed, + upload: uploadText, + download: downloadText, + checked_at: new Date().toISOString() + }; + + networkCache.last = result; + return result; +} + +async function getBridgeRuntimeStatus() { + const apply = await unitStatus("iomatex-mqtt-bridge.service"); + const mosq = await unitStatus("mosquitto.service"); + const env = bridgeConfigSummary(); + const conf = bridgeConfSummary(); + + let badge = "gray"; + let summary = "not configured"; + let active = "inactive"; + let error_text = ""; + + if (!env.env_exists && !conf.exists) { + badge = "gray"; + summary = "not configured"; + active = "inactive"; + } else if (!env.enabled) { + badge = "gray"; + summary = "disabled"; + active = "inactive"; + } else if (mosq.active === "failed" || apply.active === "failed") { + badge = "red"; + summary = "error"; + active = "failed"; + error_text = [mosq.error_text || "", apply.error_text || ""].filter(Boolean).join("\n\n") || "Bridge error"; + } else if (mosq.active === "active" && conf.valid) { + badge = "green"; + summary = "active"; + active = "active"; + } else if (mosq.active === "inactive" && conf.valid) { + badge = "gray"; + summary = "inactive"; + active = "inactive"; + } else { + badge = "amber"; + summary = "partial"; + active = "inactive"; + } + + return { + unit: "mqtt bridge runtime", + load_state: conf.exists ? "loaded" : "not-found", + active, + sub: summary, + unit_file_state: apply.unit_file_state || "-", + badge, + summary, + show: { + apply_unit: apply.show || {}, + mosquitto_unit: mosq.show || {}, + bridge_conf: conf, + bridge_env: env + }, + started_at: mosq.started_at || "", + running_for_text: mosq.running_for_text || "-", + error_text, + bridge_cfg: env, + bridge_conf: conf, + apply_unit: apply, + mosquitto_unit: mosq + }; +} + +async function getServiceStatus(def) { + if (def.key === "cockpit") return cockpitStatus(); + if (def.key === "x11") return x11Status(); + if (def.key === "bridge") return getBridgeRuntimeStatus(); + if (def.key === "rtcockpit" || def.key === "rtz2m" || def.key === "rtwebui") return reverseTunnelStatus(def.unit, def.key); + return unitStatus(def.unit); +} + +async function getServiceDetail(key) { + const def = SERVICES[key]; + if (!def) return null; + + const status = await getServiceStatus(def); + const access = Object.assign({}, def.access); + let extra = {}; + + if (key === "z2m") extra.usb = await getUsbStickInfo(); + if (key === "bridge") { + extra.bridge_cfg = status.bridge_cfg || bridgeConfigSummary(); + extra.bridge_conf = status.bridge_conf || bridgeConfSummary(); + extra.apply_unit = status.apply_unit || await unitStatus("iomatex-mqtt-bridge.service"); + extra.mosquitto_unit = status.mosquitto_unit || await unitStatus("mosquitto.service"); + } + if (key === "x11") { + extra.x11 = status.x11 || {}; + extra.display = status.display || getDisplaySnapshot(); + } + + return { + ok: true, + service: { + key: def.key, + title: def.title, + unit: def.unit, + desc: def.desc, + paths: def.paths, + access, + status, + extra, + addon_required: true + } + }; +} + +function frontendAddonKeys() { + try { + if (!fs.existsSync(ADDONS_PUBLIC_DIR)) return []; + return fs.readdirSync(ADDONS_PUBLIC_DIR) + .filter(x => x.endsWith(".js")) + .map(x => path.basename(x, ".js")) + .sort(); + } catch { + return []; + } +} + +app.get("/api/health", (req, res) => { + res.json({ + ok: true, + web: true, + mqtt_url: MQTT_URL, + mqtt: mqttLast, + login: { + enabled: loginState.enabled, + ok: loginState.ok, + last_ts: loginState.last_ts, + last_error: loginState.last_error, + password_set: loginState.password_set + }, + config: CFG_PATH, + addons_backend_dir: ADDONS_BACKEND_DIR, + addons_frontend_dir: ADDONS_PUBLIC_DIR + }); +}); + +app.get("/api/addons", (req, res) => { + try { + const items = fs.existsSync(ADDONS_PUBLIC_DIR) + ? fs.readdirSync(ADDONS_PUBLIC_DIR) + .filter(x => x.endsWith(".js")) + .sort() + .map(x => ({ name: x, key: path.basename(x, ".js"), url: `/addons/${x}` })) + : []; + res.json({ ok: true, addons: items }); + } catch (e) { + res.status(500).json({ ok: false, error: e.message }); + } +}); + +app.get("/api/config", (req, res) => res.json({ ok: true, config: readConfig() })); + +app.get("/api/display/hdmi", (req, res) => { + res.json(getDisplaySnapshot()); +}); + +app.get("/api/edge/health", async (req, res) => { + const net = await networkStatus(); + res.json({ + ok: true, + hostname: os.hostname(), + uptime_sec: Math.floor(os.uptime()), + temp_c: cpuTempC(), + mem: memInfo(), + load: loadAvg(), + network: net + }); +}); + +app.get("/api/main/services", async (req, res) => { + const items = []; + const errors = []; + const addonKeys = frontendAddonKeys(); + + for (const key of Object.keys(SERVICES)) { + const def = SERVICES[key]; + const status = await getServiceStatus(def); + let meta = {}; + + if (key === "bridge") { + meta.bridge_cfg = status.bridge_cfg || bridgeConfigSummary(); + meta.bridge_conf = status.bridge_conf || bridgeConfSummary(); + } + if (key === "x11") meta.display = status.display || getDisplaySnapshot(); + if (key === "z2m") meta.usb = await getUsbStickInfo(); + if (key === "rtcockpit" || key === "rtz2m" || key === "rtwebui") meta.tunnel = status.tunnel || {}; + + items.push({ + key, + title: def.title, + unit: def.unit, + desc: def.desc, + access: def.access, + status, + meta, + addon_installed: addonKeys.includes(key) + }); + + if (status.badge === "red") { + errors.push({ + key, + title: def.title, + unit: def.unit, + summary: status.summary, + text: status.error_text || "Service failed" + }); + } + } + + res.json({ ok: true, items, errors }); +}); + +app.get("/api/service/:key", async (req, res) => { + const j = await getServiceDetail(req.params.key); + if (!j) return res.status(404).json({ ok: false, error: "unknown service" }); + + const addonKeys = frontendAddonKeys(); + j.service.addon_installed = addonKeys.includes(j.service.key); + + res.json(j); +}); + +app.post("/api/service/:key/:action", async (req, res) => { + return res.status(400).json({ ok: false, error: "service actions are disabled in base installer; install addon" }); +}); + +function loadBackendAddons() { + const loaded = []; + if (!fs.existsSync(ADDONS_BACKEND_DIR)) return loaded; + + for (const file of fs.readdirSync(ADDONS_BACKEND_DIR).filter(x => x.endsWith(".js")).sort()) { + const full = path.join(ADDONS_BACKEND_DIR, file); + try { + const mod = require(full); + if (typeof mod === "function") { + mod(app, { + app, + fs, + path, + os, + run, + runShell, + readJson, + writeConfig, + readConfig, + mqttEnsure, + mqttSendWaitReply, + ensureLoggedForRegistration, + LOGIN_PASSWORD, + LOGIN_ENABLED, + MQTT_URL, + MQTT_NS, + MQTT_REPLY_MS, + CFG_PATH + }); + loaded.push(file); + } + } catch (e) { + console.error(`[addon-backend] failed to load ${file}: ${e.message}`); + } + } + return loaded; +} + +const loadedBackendAddons = loadBackendAddons(); + +app.listen(PORT, BIND, async () => { + try { mqttEnsure(); } catch {} + try { await networkStatus(); } catch {} + console.log(`[webipc] http://${BIND}:${PORT} (mqtt ${MQTT_URL})`); + if (loadedBackendAddons.length) console.log(`[webipc] backend addons: ${loadedBackendAddons.join(", ")}`); +}); +JS + +echo "[5/10] Write minimal branded UI" +cat > "$APP_DIR/public/index.html" <<'HTML' + + + + + + IOMATEX Edge Console + + + + +
+
+
+
+ +
+
IOMATEX Edge Console
+
Loading…
+
+
+
+
API
+
host: …
+
mqtt: …
+
+
+
+
+ +
+
+
+
+
Main
+
Services overview
+
+
+
+
+
+ +
+
+
+
Errors
+
Only failed services from Main
+
+
+
+
+
+
+
+ + + + +HTML + +echo "[6/10] Write logo and favicon from source image" +if [ ! -f "$SRC_LOGO" ]; then + echo "ERROR: logo source image not found: $SRC_LOGO" >&2 + echo "Put source image here: $SCRIPT_DIR/iomatex_logo_source.png" >&2 + exit 1 +fi + +python3 - "$SRC_LOGO" "$APP_DIR/public/logo.png" "$APP_DIR/public/favicon.png" <<'PY' +import sys +from PIL import Image + +src = sys.argv[1] +logo_out = sys.argv[2] +fav_out = sys.argv[3] + +img = Image.open(src).convert("RGBA") + +logo = img.copy() +logo.thumbnail((96, 96)) +logo.save(logo_out, format="PNG") + +fav = img.copy() +fav.thumbnail((64, 64)) +fav.save(fav_out, format="PNG") + +print("Generated logo.png and favicon.png") +PY + +echo "[7/10] Write addon placeholders" +cat > "$ADDONS_BACKEND_DIR/README.txt" <<'TXT' +Place backend addons here as .js files. +Module format: +module.exports = function(app, ctx) { + app.get("/api/example", (req, res) => res.json({ ok: true })); +}; +TXT + +cat > "$ADDONS_PUBLIC_DIR/README.txt" <<'TXT' +Place frontend addons here as .js files. +They are auto-loaded from /api/addons after main UI boot. +Recommended addon file name = service key, for example: +mosquitto.js +bridge.js +z2m.js +Use window.IOMATEX_UI to access core state and helpers. +TXT + +echo "[8/10] npm install" +cd "$APP_DIR" +npm install --omit=dev + +echo "[9/10] Install systemd service" +cat > "/etc/systemd/system/${SERVICE_NAME}" <:${APP_PORT}" +echo "API health: curl -s http://127.0.0.1:${APP_PORT}/api/health | cat" +echo "Main services: curl -s http://127.0.0.1:${APP_PORT}/api/main/services | cat" +echo "Display API: curl -s http://127.0.0.1:${APP_PORT}/api/display/hdmi | cat" +echo "Addon list: curl -s http://127.0.0.1:${APP_PORT}/api/addons | cat" +echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40" +echo "Previous install: ${APP_DIR}.prev.${ts}" +echo "Backend addons dir: ${ADDONS_BACKEND_DIR}" +echo "Frontend addons dir: ${ADDONS_PUBLIC_DIR}" +echo "Logo source expected at: ${SRC_LOGO}" \ No newline at end of file