diff --git a/Stage_4 (Reverse tunel)/Help_info.txt b/stage_reverse_tunnel/Help_info.txt
similarity index 100%
rename from Stage_4 (Reverse tunel)/Help_info.txt
rename to stage_reverse_tunnel/Help_info.txt
diff --git a/Stage_4 (Reverse tunel)/Helper для VPS .sh b/stage_reverse_tunnel/Helper для VPS .sh
similarity index 100%
rename from Stage_4 (Reverse tunel)/Helper для VPS .sh
rename to stage_reverse_tunnel/Helper для VPS .sh
diff --git a/Stage_4 (Reverse tunel)/port.js b/stage_reverse_tunnel/port.js
similarity index 100%
rename from Stage_4 (Reverse tunel)/port.js
rename to stage_reverse_tunnel/port.js
diff --git a/Stage_4 (Reverse tunel)/stage_reverce_tonel.sh b/stage_reverse_tunnel/stage_reverce_tunnel.sh
similarity index 100%
rename from Stage_4 (Reverse tunel)/stage_reverce_tonel.sh
rename to stage_reverse_tunnel/stage_reverce_tunnel.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 0000000..014b6e4
Binary files /dev/null and b/stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc differ
diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py
new file mode 100644
index 0000000..dc853bd
--- /dev/null
+++ b/stage_ui/console_core/backend/app.py
@@ -0,0 +1,351 @@
+#!/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.error import HTTPError, URLError
+from urllib.parse import urlparse
+from urllib.request import Request, urlopen
+
+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 http_probe(url, timeout=2, max_bytes=4096):
+ req = Request(url, headers={"User-Agent": "iomatex-console/1.0"})
+ try:
+ with urlopen(req, timeout=timeout) as resp:
+ body = resp.read(max_bytes).decode("utf-8", errors="ignore")
+ return {
+ "ok": True,
+ "status": getattr(resp, "status", 200),
+ "body": body,
+ "error": "",
+ }
+ except HTTPError as exc:
+ body = ""
+ try:
+ body = exc.read(max_bytes).decode("utf-8", errors="ignore")
+ except Exception:
+ body = ""
+ return {
+ "ok": False,
+ "status": exc.code,
+ "body": body,
+ "error": str(exc),
+ }
+ except URLError as exc:
+ return {
+ "ok": False,
+ "status": 0,
+ "body": "",
+ "error": str(exc),
+ }
+ except Exception as exc:
+ return {
+ "ok": False,
+ "status": 0,
+ "body": "",
+ "error": str(exc),
+ }
+
+
+def read_machine_info():
+ data = {}
+ try:
+ with open("/etc/machine-info", "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)
+ data[key.strip()] = value.strip().strip('"').strip("'")
+ except Exception:
+ pass
+ return data
+
+
+def detect_edge_identity():
+ machine_info = read_machine_info()
+ pretty_name = machine_info.get("PRETTY_HOSTNAME", "").strip()
+
+ hostname = ""
+ rc, stdout, _stderr = run(["hostname", "-s"])
+ if rc == 0 and stdout.strip():
+ hostname = stdout.strip()
+ if not hostname:
+ hostname = read_text("/etc/hostname").strip().splitlines()[0] if read_text("/etc/hostname").strip() else ""
+ if not hostname:
+ hostname = "unknown"
+
+ return {
+ "name": pretty_name or hostname,
+ "hostname": hostname,
+ "pretty_name": pretty_name or "",
+ }
+
+
+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,
+ "http_probe": http_probe,
+ }
+ 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()),
+ "edge": detect_edge_identity(),
+ "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..8b7f044
--- /dev/null
+++ b/stage_ui/console_core/frontend/console.css
@@ -0,0 +1,80 @@
+: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)}
+.edgeName{margin:8px 0 0;color:var(--ink);font-size:14px;font-weight:600}
+.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)}
+.dot.neutral{background:var(--muted)}
+.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..3d01333
--- /dev/null
+++ b/stage_ui/console_core/frontend/console.js
@@ -0,0 +1,115 @@
+(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"),
+ edgeName: document.getElementById("edgeName")
+ };
+
+ 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.state === "not installed") return "neutral";
+ if (card.state === "failed" || card.state === "degraded") return "error";
+ 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")}
+
+
+
+
+
+
+
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 : [];
+ const edgeName = payload.edge && payload.edge.name ? payload.edge.name : "unknown";
+
+ nodes.lastUpdate.textContent = payload.generated_at || "-";
+ nodes.providerCount.textContent = String(providers.length);
+ nodes.serviceCount.textContent = String(services.length);
+ nodes.edgeName.textContent = `Edge: ${edgeName}`;
+
+ 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..6c2e953
--- /dev/null
+++ b/stage_ui/console_core/frontend/index.html
@@ -0,0 +1,46 @@
+
+
+
+
+
+ IOMATEX Console
+
+
+
+
+
+
+
+

+
+
IOMATEX
+
Console
+
Lightweight diagnostics for installed services.
+
Edge: unknown
+
+
+
+
+
+
+
+
+
+ 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..387ab7a
--- /dev/null
+++ b/stage_ui/console_core/providers/00_core_services.py
@@ -0,0 +1,389 @@
+import glob
+import os
+import pwd
+
+
+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 not configured:
+ return "not configured", "Not configured"
+ if active:
+ return "active", "Active"
+ if failed:
+ return "failed", "Failed"
+ return "inactive", "Inactive"
+
+
+def _strict_active(installed, configured, unit):
+ return bool(installed and configured and unit["active"])
+
+
+def _service_failed(unit):
+ return bool(
+ unit["active_state"] == "failed"
+ or (unit["result"] and unit["result"] not in ("success", "done"))
+ or (unit["exec_main_status"] and unit["exec_main_status"] not in ("0", ""))
+ )
+
+
+def _find_first_existing(paths):
+ for path in paths:
+ if os.path.exists(path):
+ return path
+ return ""
+
+
+def _read_text(path):
+ try:
+ with open(path, "r", encoding="utf-8", errors="ignore") as fh:
+ return fh.read()
+ except Exception:
+ return ""
+
+
+def _has_any_serial_device():
+ if os.path.exists("/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0"):
+ return True
+ if glob.glob("/dev/serial/by-id/*"):
+ return True
+ if glob.glob("/dev/ttyUSB*"):
+ return True
+ if glob.glob("/dev/ttyACM*"):
+ return True
+ return False
+
+
+def _extract_yaml_scalar(text, section, key):
+ in_section = False
+ section_prefix = f"{section}:"
+ key_prefix = f"{key}:"
+
+ for raw in text.splitlines():
+ line = raw.rstrip()
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ if not raw.startswith((" ", "\t")):
+ in_section = stripped == section_prefix
+ continue
+ if in_section and stripped.startswith(key_prefix):
+ return stripped.split(":", 1)[1].strip().strip('"').strip("'")
+ return ""
+
+
+def _z2m_config_path():
+ return "/opt/zigbee2mqtt/data/configuration.yaml"
+
+
+def _z2m_has_minimal_config():
+ cfg_path = _z2m_config_path()
+ if not os.path.exists(cfg_path):
+ return False
+ cfg_text = _read_text(cfg_path)
+ return bool(
+ _extract_yaml_scalar(cfg_text, "mqtt", "server")
+ and _extract_yaml_scalar(cfg_text, "mqtt", "base_topic")
+ )
+
+
+def _probe_z2m_gateway(ctx):
+ probe = ctx["http_probe"]("http://127.0.0.1:8081/")
+ body = (probe.get("body") or "").lower()
+ if "service z2m not installed" in body:
+ return {"reachable": False, "summary": "not installed", "error": ""}
+ if "service z2m not configured" in body:
+ return {"reachable": False, "summary": "not configured", "error": ""}
+ if "service z2m unavailable" in body:
+ return {"reachable": False, "summary": "ui unavailable", "error": ""}
+ if probe.get("ok"):
+ return {"reachable": True, "summary": "reachable", "error": ""}
+ return {"reachable": False, "summary": "unreachable", "error": probe.get("error", "")}
+
+
+def _iomatex_home():
+ try:
+ return pwd.getpwnam("iomatex").pw_dir
+ except KeyError:
+ return "/home/iomatex"
+
+
+def _reverse_tunnel_key_paths():
+ home = _iomatex_home()
+ hostname = os.uname().nodename
+ key_base = os.path.join(home, ".ssh", f"iomatex-{hostname}")
+ return key_base, key_base + ".pub"
+
+
+def _reverse_tunnel_unit_names():
+ return [
+ ("cockpit", "iomatex-rt-cockpit.service"),
+ ("z2m", "iomatex-rt-z2m.service"),
+ ("webui", "iomatex-rt-webui.service"),
+ ]
+
+
+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",
+ "/opt/zigbee2mqtt/data",
+ ])
+ 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"])
+ has_config = _z2m_has_minimal_config()
+ has_coordinator = _has_any_serial_device()
+ configured = bool(installed and has_config and has_coordinator)
+ failed = bool(installed and has_config and has_coordinator and _service_failed(unit))
+ service_active = _strict_active(installed, configured, unit)
+ gateway = _probe_z2m_gateway(ctx) if installed else {"reachable": False, "summary": "not installed", "error": ""}
+ active = service_active
+ warnings = []
+ errors = []
+ if installed and not has_config:
+ warnings.append("configuration.yaml missing or incomplete")
+ if installed and has_config and not has_coordinator:
+ warnings.append("Zigbee coordinator not detected")
+ if failed:
+ errors.extend(_short_unit_errors(unit))
+ state, status_text = _lifecycle(installed, configured, service_active, failed=failed)
+
+ if state == "active" and not gateway["reachable"]:
+ state = "degraded"
+ status_text = "UI unavailable"
+ warnings.append("Gateway on localhost:8081 is not serving the Zigbee2MQTT UI")
+ elif state == "inactive" and gateway["summary"] == "ui unavailable":
+ warnings.append("Gateway on localhost:8081 reports UI unavailable")
+ elif state == "not configured" and gateway["summary"] == "not configured":
+ warnings.append("Gateway on localhost:8081 reports not configured")
+
+ if gateway["error"] and state in ("degraded", "inactive"):
+ warnings.append(f"Gateway probe error: {gateway['error']}")
+
+ return _service_card(
+ "zigbee2mqtt",
+ "Zigbee2MQTT",
+ "zigbee2mqtt.service",
+ installed,
+ configured,
+ active,
+ state,
+ status_text,
+ errors[:2],
+ warnings[:2],
+ )
+
+
+def reverse_tunnel_card(ctx):
+ units = [(name, ctx["systemd_unit"](service)) for name, service in _reverse_tunnel_unit_names()]
+ wrapper_paths = [
+ f"/usr/local/sbin/iomatex-rt-{name}.sh"
+ for name, _service in _reverse_tunnel_unit_names()
+ ]
+ key_path, key_pub_path = _reverse_tunnel_key_paths()
+
+ installed = bool(
+ any(unit["installed"] for _name, unit in units)
+ or any(os.path.exists(path) for path in wrapper_paths)
+ or os.path.exists(key_path)
+ or os.path.exists(key_pub_path)
+ )
+ configured = bool(
+ installed
+ and all(unit["installed"] for _name, unit in units)
+ and all(os.path.exists(path) for path in wrapper_paths)
+ and os.path.exists(key_path)
+ and os.path.exists(key_pub_path)
+ )
+ active_units = [name for name, unit in units if unit["active"]]
+ failed_units = [(name, unit) for name, unit in units if _service_failed(unit)]
+ active = bool(configured and len(active_units) == len(units))
+ warnings = []
+ errors = []
+
+ if installed and not all(unit["installed"] for _name, unit in units):
+ warnings.append("One or more systemd tunnel units are missing")
+ if installed and not all(os.path.exists(path) for path in wrapper_paths):
+ warnings.append("One or more tunnel wrapper scripts are missing")
+ if installed and not (os.path.exists(key_path) and os.path.exists(key_pub_path)):
+ warnings.append("Tunnel SSH key is missing")
+
+ if not installed:
+ state, status_text = _lifecycle(False, False, False)
+ elif not configured:
+ state, status_text = "not configured", "Not configured"
+ elif failed_units:
+ state, status_text = "failed", "Failed"
+ for name, unit in failed_units:
+ errors.append(f"{name}: {(_short_unit_errors(unit) or ['Service failed'])[0]}")
+ elif active:
+ state, status_text = "active", "Active"
+ elif active_units:
+ state, status_text = "degraded", "Degraded"
+ warnings.append(f"Active tunnels: {', '.join(active_units)}")
+ else:
+ state, status_text = "inactive", "Inactive"
+
+ return _service_card(
+ "reverse_tunnel",
+ "Reverse Tunnel",
+ "iomatex-rt-*.service",
+ installed,
+ configured,
+ active,
+ state,
+ status_text,
+ errors[:2],
+ warnings[:2],
+ )
+
+
+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),
+ reverse_tunnel_card(ctx),
+ 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 0000000..a6311b3
Binary files /dev/null and b/stage_ui/console_core/providers/__pycache__/00_core_services.cpython-312.pyc differ
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")}
+
+
+
+
+
+
+
+
+
+
+
+ ${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