From 582c30d03da1f6901e10747d190013f88e60a6f3 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Sun, 15 Mar 2026 13:50:45 +0400 Subject: [PATCH] Add stage_ui console core and legacy reference --- .../Help_info.txt | 0 .../Helper для VPS .sh | 0 .../port.js | 0 .../stage_reverce_tunnel.sh | 0 stage_ui/console_core/ARCHITECTURE.md | 17 + .../backend/__pycache__/app.cpython-312.pyc | Bin 0 -> 17123 bytes stage_ui/console_core/backend/app.py | 351 +++ stage_ui/console_core/frontend/console.css | 80 + stage_ui/console_core/frontend/console.js | 115 + stage_ui/console_core/frontend/index.html | 46 + .../providers/00_core_services.py | 389 ++++ .../00_core_services.cpython-312.pyc | Bin 0 -> 16461 bytes stage_ui/legacy_reference/README.md | 9 + stage_ui/legacy_reference/ui_addon_display.sh | 207 ++ .../legacy_reference/ui_addon_itscreen.sh | 765 +++++++ stage_ui/legacy_reference/ui_installer.sh | 1910 +++++++++++++++++ 16 files changed, 3889 insertions(+) rename {Stage_4 (Reverse tunel) => stage_reverse_tunnel}/Help_info.txt (100%) rename {Stage_4 (Reverse tunel) => stage_reverse_tunnel}/Helper для VPS .sh (100%) rename {Stage_4 (Reverse tunel) => stage_reverse_tunnel}/port.js (100%) rename Stage_4 (Reverse tunel)/stage_reverce_tonel.sh => stage_reverse_tunnel/stage_reverce_tunnel.sh (100%) create mode 100644 stage_ui/console_core/ARCHITECTURE.md create mode 100644 stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc create mode 100644 stage_ui/console_core/backend/app.py create mode 100644 stage_ui/console_core/frontend/console.css create mode 100644 stage_ui/console_core/frontend/console.js create mode 100644 stage_ui/console_core/frontend/index.html create mode 100644 stage_ui/console_core/providers/00_core_services.py create mode 100644 stage_ui/console_core/providers/__pycache__/00_core_services.cpython-312.pyc create mode 100644 stage_ui/legacy_reference/README.md create mode 100755 stage_ui/legacy_reference/ui_addon_display.sh create mode 100755 stage_ui/legacy_reference/ui_addon_itscreen.sh create mode 100755 stage_ui/legacy_reference/ui_installer.sh diff --git a/Stage_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 0000000000000000000000000000000000000000..014b6e4f5701728c5d8402eaa0c56c4ba59f6d12 GIT binary patch literal 17123 zcmch8dsG`|mS>f!^p?;Ife>#H57`Fn_(A+k^Ryk?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2}FFevjw+?STj!By$s?335H}B=l3E#`BGMrd^=dtlVnhx~S;?*tRF5Cu zr^59meZz?pL;xac"']/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")}
+
+
+ +
+
ID
${esc(card.id)}
+
State
${esc(card.state || "-")}
+
Status
${esc(card.status_text || "-")}
+
+ +
+
Flags
+
+ ${boolPill("Installed", !!card.installed)} + ${boolPill("Configured", !!card.configured)} + ${boolPill("Active", !!card.active)} +
+
+ + ${warnings.length ? ` +
+
Warnings
+
    ${warnings.map((x) => `
  • ${esc(x)}
  • `).join("")}
+
+ ` : ""} + + ${errors.length ? ` +
+
Errors
+
    ${errors.map((x) => `
  • ${esc(x)}
  • `).join("")}
+
+ ` : ""} +
+ `; + } + + function render(payload) { + const services = Array.isArray(payload.services) ? payload.services : []; + const providers = Array.isArray(payload.providers) ? payload.providers : []; + 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 0000000000000000000000000000000000000000..a6311b3b68ec616e875eaf341ab5e1f23ba1a89d GIT binary patch literal 16461 zcmdUWX>c3om0&l{1{ycO`w%EnBq521PEz+lQY3ZI8;Oo(#Wq5sAqo@;(A}U&BA|?9 zJQXr=ji6*^MC~{gIF%pJI8#ekvJ-9X)UHxBsd3f(0SKrBwfV!T@sG_vh4gM>Zq?Sl z_cgi!P>{-TQaiOx_QQ9)@BY4beXsx3Y&KHx{B-ai14s8!)W2awepLCuW)cGTD30Rj zDe9W^OJAc&Ty;&w)pDwL>1%3E{VsJ)!)Z9}`!uI}S9MLx=^;hOF#z?P0U*N}0U9_K zppi2HWH~cH6K4Tv=BxlMoDHCrvjeno4uE#f3DCj006Mt}fG(~QUw$?`9>TgYUpR2fFKQt(>=#-5nH9WY z|9n`~`FTFX3nDW&#s>qz3E=_dF^WdP&)*98{N4b^YoSk~VKx{DdxK-seqIN0UXOr5 zU_gKa;8_GF00Ktc%CmI<8l3QZX9Hc(DIqlF_xeJ-ziWmM-3oAiUg+xXCMn*0t3v0@ zf@qdwUf&qc@ph;ZTNb(i#Hdd#)j4}*uA(tl>CQPwxN0W^ez14tY|d5xgOP;lcTS^8 z_lz=Xb(>Ix^3e$M4~~gUI0dQqU}_iXC~Th^Naj>G+hH8`C_PzRB43bGf0$3DVVO7$ zmf#!Z5U0IG^Hnb>sgtq(j{1?Rq!ztW3kh+|OKLGdEd=YiT8yL?SNYbV6v;1Y7Y_(q zOTjiWjff^`i+H6SqPsp8fK9Yzxgu=?w-gt3ykD4|3O`VZdSTY*^9zEg;X*-wgt<&I zj=Dv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OO85XM<83+SgeNkor|~)^ak#p4?DF(q~1VTeN4` z<_#?*LenOT@)gG34BNJ8(Asse;m=K!qY{)zQ2Py@b(0my@9L{r>#>aK*oGRCKEtF_ zs|{J}sf_8=h8B{bF0=K{;PT*|k>!z<-i)bbLyyT!aWc3)wr{dJhYs%QE!5t9Pn>=C zuK@u$xZ3})`sX7*=ubKOVi(iSzTAP{C(g?sTuY255B}3DANM~#{AWe^UW$TBsHAAxcTzxLf z41yH^GcP`z&emVd)?8FFhqBBtX72oP+x@m5ci!(zR%dJX|APPJ+(&c2y#3MbM^o9J zD+>03EOYQTtZTiYEvZe;uKF_#$I}d01eU+`)LfNoI3-666}g5k5?T6IuC^5&Lf@d5 z&%=7R8=j{izyORh1(~$>9R^Q0%Ih)$um#Xf6%nW?0;1PoX*bLx* zyPLzyZZN*s1e$I3(_d_=U_XAb*-E+k=`TKUUKa4U{Z-Wkx9&gNF0|@?O_?w3)&1I{ zL0Id&uwVDvSm?_$0Zv#2 zsn??(IVU;9tBUM%8XoUj$S1mm4{^7Bj%S;h8uR&Ygr?wATj^v!hB8xlvQI+*PBu7? z3?vV&?#k4_AuRD10s9eL`2bY@;d&iXj4!+XL5l*Jfxm@7@eC9ksf$M~>zGBFs-kxm z>>fpB@rI8)MQKRv$OH4IlCQ!G*D9R4;Eg+>C(hTR9&R{cY8FI2TxF5~@V+GTEbtt45H~yJKgoXr72t#je+dA*LuvXGiv5H#d_oyFbu6vhs5jD; z&uXb7CqJhQ^v;cHnm)0?Xd%O literal 0 HcmV?d00001 diff --git a/stage_ui/legacy_reference/README.md b/stage_ui/legacy_reference/README.md new file mode 100644 index 0000000..d4b139e --- /dev/null +++ b/stage_ui/legacy_reference/README.md @@ -0,0 +1,9 @@ +# Legacy UI Reference + +These files preserve the previous WebIPC-based UI implementation as reference only: + +- `ui_installer.sh` +- `ui_addon_itscreen.sh` +- `ui_addon_display.sh` + +The new `stage_ui/ui_installer.sh` installs the lightweight Console core instead of the legacy Node/Express UI. diff --git a/stage_ui/legacy_reference/ui_addon_display.sh b/stage_ui/legacy_reference/ui_addon_display.sh new file mode 100755 index 0000000..1adac0d --- /dev/null +++ b/stage_ui/legacy_reference/ui_addon_display.sh @@ -0,0 +1,207 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP="/opt/iomatex-process1-webipc" +ADDON_FRONT="$APP/public/addons" +SERVICE="iomatex-webipc.service" + +echo "[1/4] prepare dirs" +mkdir -p "$ADDON_FRONT" + +echo "[2/4] write x11 addon" +cat > "$ADDON_FRONT/x11.js" <<'JS' +(function () { + "use strict"; + + if (window.__iomatexX11AddonLoaded) return; + window.__iomatexX11AddonLoaded = true; + + const ui = window.IOMATEX_UI; + if (!ui) return; + + const state = ui.state; + + state.x11Addon = state.x11Addon || { + data: null, + busy: { refresh: false }, + message: "" + }; + + function esc(s) { + return (s ?? "").toString().replace(/[&<>"']/g, m => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }[m])); + } + + function setBusy(key, v) { + state.x11Addon.busy[key] = !!v; + ui.render(); + } + + function setMsg(msg) { + state.x11Addon.message = (msg || "").toString(); + ui.render(); + } + + function btn(label, kind, fnName, busyKey, busyLabel) { + const busy = !!state.x11Addon.busy[busyKey]; + return ``; + } + + async function loadDisplay() { + const j = await ui.call("/api/display/hdmi"); + state.x11Addon.data = j; + return j; + } + + async function refreshDisplay() { + setBusy("refresh", true); + setMsg("Refreshing display information..."); + try { + await ui.loadDetail("x11").catch(() => {}); + await loadDisplay(); + setMsg("Display information updated."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("refresh", false); + } + } + + function renderConnector(c) { + return ` +
+
${esc(c.edid?.monitor_name || c.connector || "Connector")}
+
+
Connector
${esc(c.connector || "-")} +
Type
${esc(c.kind || "-")} +
Status
${esc(c.status || "-")} +
Connected
${esc(c.connected ? "yes" : "no")} +
Enabled
${esc(c.enabled || "-")} +
DPMS
${esc(c.dpms || "-")} +
Preferred mode
${esc(c.preferred_mode || "-")} +
Modes
${esc((c.modes || []).join(", ") || "-")} +
Monitor
${esc(c.edid?.monitor_name || "-")} +
Vendor
${esc(c.edid?.manufacturer_id || "-")} +
Product code
${esc(c.edid?.product_code || "-")} +
Serial
${esc(c.edid?.serial_text || "-")} +
Size
${esc(c.edid?.size_cm || "-")} +
Diagonal
${esc(c.edid?.size_inch || "-")} +
+
+ `; + } + + function renderX11Detail(service) { + const d = state.x11Addon.data || {}; + const sum = d.summary || {}; + const first = sum.first_connected_hdmi || null; + const connectors = Array.isArray(d.connectors) ? d.connectors : []; + const connected = connectors.filter(x => x.connected); + const hdmi = Array.isArray(d.hdmi) ? d.hdmi : []; + const status = service.status || {}; + + document.getElementById("viewTitle").textContent = service.title || "Display"; + document.getElementById("viewSub").textContent = service.desc || ""; + document.getElementById("viewActions").innerHTML = + ``; + + document.getElementById("view").innerHTML = ` +
+
+
Display summary
+
+
Active
${esc(status.active || "-")} +
Started
${esc(status.started_at || "-")} +
State
${esc(status.summary || "-")} +
Running
${esc(status.running_for_text || "-")} +
HDMI connected
${esc(sum.hdmi_connected ? "yes" : "no")} +
Connected displays
${esc(String(sum.connected_count ?? 0))} +
Connected HDMI
${esc(String(sum.connected_hdmi_count ?? 0))} +
Connector
${esc(first?.connector || "-")} +
Monitor
${esc(first?.edid?.monitor_name || "-")} +
Preferred mode
${esc(first?.preferred_mode || "-")} +
Vendor
${esc(first?.edid?.manufacturer_id || "-")} +
+
+ ${btn("Refresh", "primary", "window.__x11Refresh()", "refresh", "Refreshing...")} +
+
+ +
+
Connected connectors
+ ${connected.length ? connected.map(renderConnector).join("") : `
No connected connectors detected.
`} +
+ +
+
HDMI connectors
+ ${hdmi.length ? hdmi.map(renderConnector).join("") : `
No HDMI connectors found.
`} +
+ +
+
All DRM connectors
+ ${connectors.length ? connectors.map(renderConnector).join("") : `
No DRM connectors found.
`} +
+ +
+
Message
+
${esc(state.x11Addon.message || "Ready")}
+
+
+ `; + } + + const prevLoadTabData = ui.loadTabData.bind(ui); + const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){}; + const prevRender = ui.render.bind(ui); + + ui.loadTabData = async function () { + if (state.tab === "x11") { + await ui.loadDetail("x11"); + await loadDisplay().catch(() => {}); + return; + } + return prevLoadTabData(); + }; + + ui.refreshDetail = async function () { + if (state.tab === "x11") { + await ui.loadDetail("x11"); + await loadDisplay().catch(() => {}); + ui.render(); + return; + } + return prevRefreshDetail(); + }; + window.refreshDetail = ui.refreshDetail; + + ui.render = function () { + if (state.tab === "x11" && state.detail?.service?.key === "x11") { + renderX11Detail(state.detail.service); + return; + } + return prevRender(); + }; + window.render = ui.render; + + window.__x11Refresh = refreshDisplay; + + setTimeout(async () => { + try { + await loadDisplay().catch(() => {}); + if (state.tab === "x11") ui.render(); + } catch (_) {} + }, 0); +})(); +JS + +echo "[3/4] restart" +systemctl restart "$SERVICE" + +echo "[4/4] done" +echo "Installed frontend: $ADDON_FRONT/x11.js" +echo "Restarted: $SERVICE" \ No newline at end of file diff --git a/stage_ui/legacy_reference/ui_addon_itscreen.sh b/stage_ui/legacy_reference/ui_addon_itscreen.sh new file mode 100755 index 0000000..b1ace3b --- /dev/null +++ b/stage_ui/legacy_reference/ui_addon_itscreen.sh @@ -0,0 +1,765 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP="/opt/iomatex-process1-webipc" +ADDON_BACK="$APP/addons/backend" +ADDON_FRONT="$APP/public/addons" +CFG="/etc/iomatex/webipc-itscreen.json" +SERVICE="iomatex-webipc.service" + +echo "[1/6] prepare dirs" +mkdir -p "$ADDON_BACK" "$ADDON_FRONT" /etc/iomatex + +echo "[2/6] config" +if [ ! -f "$CFG" ]; then +cat > "$CFG" <<'EOF' +{ + "server": "", + "deviceId": "", + "token": "", + "username": "", + "password": "", + "topicNamespace": "" +} +EOF +fi + +echo "[3/6] backend addon" +cat > "$ADDON_BACK/itscreen.js" <<'JS' +"use strict"; + +const fs = require("fs"); +const os = require("os"); +const mqtt = require("mqtt"); + +const CFG = "/etc/iomatex/webipc-itscreen.json"; +const MQTT = "mqtt://127.0.0.1:1883"; +const LOGIN_PASSWORD = "eXXI0wkHBmNBnVbE"; +const TOPIC_NAMESPACES = ["it-screen", "iomatex"]; +const ITSERVICE = "itscreen-x11.service"; + +function readCfg() { + try { + const j = JSON.parse(fs.readFileSync(CFG, "utf8")); + return { + server: (j.server || "").toString(), + deviceId: (j.deviceId || "").toString(), + token: (j.token || "").toString(), + username: (j.username || "").toString(), + password: (j.password || "").toString(), + topicNamespace: (j.topicNamespace || "").toString() + }; + } catch { + return { + server: "", + deviceId: "", + token: "", + username: "", + password: "", + topicNamespace: "" + }; + } +} + +function writeCfg(o) { + const safe = { + server: (o.server || "").toString().trim(), + deviceId: (o.deviceId || "").toString().trim(), + token: (o.token || "").toString().trim(), + username: (o.username || "").toString().trim(), + password: (o.password || "").toString().trim(), + topicNamespace: (o.topicNamespace || "").toString().trim() + }; + fs.writeFileSync(CFG, JSON.stringify(safe, null, 2) + "\n", "utf8"); + return safe; +} + +function normalizeNamespace(ns) { + ns = (ns || "").toString().trim(); + return TOPIC_NAMESPACES.includes(ns) ? ns : ""; +} + +function getDeviceId(cfg) { + return (cfg.deviceId || os.hostname()).trim(); +} + +function topicPair(cfg, namespace) { + const id = getDeviceId(cfg); + const ns = normalizeNamespace(namespace) || "it-screen"; + const base = `${ns}/$devices/settings/${id}`; + return { + namespace: ns, + deviceId: id, + sub: `${base}/sub`, + pub: `${base}/pub` + }; +} + +function getNamespaceOrder(cfg) { + const preferred = normalizeNamespace(cfg.topicNamespace); + if (preferred) return [preferred].concat(TOPIC_NAMESPACES.filter(x => x !== preferred)); + return TOPIC_NAMESPACES.slice(); +} + +function hasRegistrationData(obj) { + if (!obj || typeof obj !== "object") return false; + const server = (obj.server || obj.host || "").toString().trim(); + const username = (obj.username || "").toString().trim(); + const password = (obj.password || "").toString().trim(); + return !!(server && username && password); +} + +module.exports = function(app, ctx) { + const mqttc = mqtt.connect(MQTT, { + reconnectPeriod: 1000, + connectTimeout: 4000, + keepalive: 30, + clean: true + }); + + let loginState = { + ok: false, + lastTs: null, + lastError: null, + lastNamespace: null + }; + + let sendQueue = Promise.resolve(); + + function saveNamespaceIfChanged(namespace) { + const ns = normalizeNamespace(namespace); + if (!ns) return readCfg(); + const cur = readCfg(); + if (cur.topicNamespace === ns) return cur; + return writeCfg({ + server: cur.server, + deviceId: cur.deviceId || getDeviceId(cur), + token: cur.token, + username: cur.username, + password: cur.password, + topicNamespace: ns + }); + } + + function sendOne(cfg, namespace, payload, timeout = 3000) { + return new Promise((resolve) => { + const tp = topicPair(cfg, namespace); + let done = false; + + const finish = (obj) => { + if (done) return; + done = true; + clearTimeout(timer); + mqttc.removeListener("message", onMsg); + try { mqttc.unsubscribe(tp.pub); } catch {} + resolve(obj); + }; + + const timer = setTimeout(() => { + finish({ + ok: false, + note: "timeout", + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }); + }, timeout); + + function onMsg(t, b) { + if (t !== tp.pub) return; + const raw = b ? b.toString() : ""; + let parsed = null; + try { parsed = JSON.parse(raw); } catch { parsed = { raw }; } + finish(Object.assign({ + ok: true, + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }, parsed)); + } + + mqttc.subscribe(tp.pub, (subErr) => { + if (subErr) { + finish({ + ok: false, + note: "subscribe_failed", + error: subErr.message, + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }); + return; + } + + mqttc.on("message", onMsg); + + mqttc.publish(tp.sub, JSON.stringify(payload), (pubErr) => { + if (pubErr) { + finish({ + ok: false, + note: "publish_failed", + error: pubErr.message, + namespace: tp.namespace, + topic_sub: tp.sub, + topic_pub: tp.pub + }); + } + }); + }); + }); + } + + function send(cfg, payload, timeout = 3000) { + const namespaces = getNamespaceOrder(cfg); + + const runOne = async () => { + let last = null; + for (const ns of namespaces) { + const r = await sendOne(cfg, ns, payload, timeout); + last = r; + if (r && (r.result === true || r.category || r.action || (r.ok && !r.note))) { + saveNamespaceIfChanged(ns); + return r; + } + } + return last || { ok: false, note: "no_namespace_tried" }; + }; + + sendQueue = sendQueue.then(runOne, runOne); + return sendQueue; + } + + async function doLogin(cfg) { + const r = await send(cfg, { + action: "login", + password: LOGIN_PASSWORD + }, 4000); + + loginState.lastTs = Date.now(); + loginState.lastNamespace = (r && r.namespace) || null; + + if (r && r.action === "login" && r.result === true) { + loginState.ok = true; + loginState.lastError = null; + } else { + loginState.ok = false; + loginState.lastError = (r && (r.note || r.error || r.raw)) || "login_failed"; + } + + return r; + } + + async function ensureLogin(cfg) { + return doLogin(cfg); + } + + app.get("/api/addon/itscreen/config", (req, res) => { + const cfg = readCfg(); + res.json({ + ok: true, + config: cfg, + login: loginState, + registration: { configured: hasRegistrationData(cfg) }, + topics: getNamespaceOrder(cfg).map(ns => topicPair(cfg, ns)) + }); + }); + + app.post("/api/addon/itscreen/config/clear", (req, res) => { + const cleared = writeCfg({ + server: "", + deviceId: "", + token: "", + username: "", + password: "", + topicNamespace: "" + }); + + loginState = { + ok: false, + lastTs: Date.now(), + lastError: "config_cleared", + lastNamespace: null + }; + + res.json({ + ok: true, + config: cleared, + login: loginState, + registration: { configured: false } + }); + }); + + app.post("/api/addon/itscreen/login", async (req, res) => { + try { + const cfg = readCfg(); + const r = await doLogin(cfg); + res.json({ + ok: true, + config: readCfg(), + login: loginState, + registration: { configured: hasRegistrationData(readCfg()) }, + result: r + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message, login: loginState }); + } + }); + + app.get("/api/addon/itscreen/get_server", async (req, res) => { + try { + const cfg = readCfg(); + const loginR = await ensureLogin(cfg); + + if (!(loginR && loginR.result === true)) { + const current = readCfg(); + return res.json({ + ok: true, + config: current, + login: loginState, + registration: { configured: hasRegistrationData(current) }, + result: { ok: false, note: "login_failed_before_get", login_result: loginR } + }); + } + + const cfg2 = readCfg(); + const r = await send(cfg2, { + action: "get", + category: "server" + }, 4000); + + const currentCfg = readCfg(); + + if (r && r.category === "server") { + const merged = writeCfg({ + server: (r.host || currentCfg.server || "").toString(), + deviceId: currentCfg.deviceId || getDeviceId(cfg2), + token: currentCfg.token, + username: (r.username || currentCfg.username || "").toString(), + password: (r.password || currentCfg.password || "").toString(), + topicNamespace: (r.namespace || currentCfg.topicNamespace || "").toString() + }); + + return res.json({ + ok: true, + config: merged, + login: loginState, + registration: { configured: hasRegistrationData(merged) }, + result: r + }); + } + + res.json({ + ok: true, + config: currentCfg, + login: loginState, + registration: { configured: hasRegistrationData(currentCfg) }, + result: r + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message, login: loginState }); + } + }); + + app.post("/api/addon/itscreen/register", async (req, res) => { + try { + const body = req.body || {}; + const cfg = readCfg(); + + const server = (body.server || "").toString().trim(); + const username = (body.username || "").toString().trim(); + const password = (body.password || "").toString().trim(); + const token = (body.token || "").toString().trim(); + + if (!server) return res.status(400).json({ ok: false, error: "server is required" }); + if (!username) return res.status(400).json({ ok: false, error: "username is required" }); + if (!password) return res.status(400).json({ ok: false, error: "password is required" }); + + const loginR = await ensureLogin(cfg); + + if (!(loginR && loginR.result === true)) { + const current = readCfg(); + return res.json({ + ok: true, + config: current, + login: loginState, + registration: { configured: hasRegistrationData(current) }, + result: { ok: false, note: "login_failed_before_set", login_result: loginR } + }); + } + + const cfg2 = readCfg(); + const payload = { + action: "set", + category: "server", + host: server, + username, + password + }; + + const r = await send(cfg2, payload, 5000); + + if (r && r.result === true) { + const saved = writeCfg({ + server, + deviceId: cfg2.deviceId || getDeviceId(cfg2), + token, + username, + password, + topicNamespace: r.namespace || cfg2.topicNamespace || "" + }); + return res.json({ + ok: true, + config: saved, + login: loginState, + registration: { configured: hasRegistrationData(saved) }, + result: r + }); + } + + const current = readCfg(); + res.json({ + ok: true, + config: current, + login: loginState, + registration: { configured: hasRegistrationData(current) }, + result: r + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message, login: loginState }); + } + }); + + app.post("/api/addon/itscreen/service/:action", async (req, res) => { + try { + const action = (req.params.action || "").toLowerCase(); + if (!["restart", "stop", "start"].includes(action)) { + return res.status(400).json({ ok: false, error: "bad action" }); + } + + const r = await ctx.run("/bin/systemctl", [action, ITSERVICE], 12000); + if (!r.ok) { + return res.status(502).json({ ok: false, error: r.err || r.out || "systemctl failed" }); + } + + const status = await ctx.run("/bin/systemctl", ["is-active", ITSERVICE], 6000); + res.json({ + ok: true, + action, + unit: ITSERVICE, + active: (status.out || status.err || "").trim() || "unknown" + }); + } catch (e) { + res.status(502).json({ ok: false, error: e.message }); + } + }); +}; +JS + +echo "[4/6] frontend addon" +cat > "$ADDON_FRONT/itscreen.js" <<'JS' +(function () { + "use strict"; + + if (window.__iomatexItscreenAddonLoaded) return; + window.__iomatexItscreenAddonLoaded = true; + + const ui = window.IOMATEX_UI; + if (!ui) return; + + const state = ui.state; + + state.itscreenAddon = state.itscreenAddon || { + cfg: {}, + result: {}, + login: {}, + registration: { configured: false }, + busy: { + refresh: false, + login: false, + register: false, + clear: false, + restart: false, + stop: false, + start: false + }, + message: "" + }; + + function esc(s) { + return (s ?? "").toString().replace(/[&<>"']/g, m => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }[m])); + } + + function setMsg(msg) { + state.itscreenAddon.message = (msg || "").toString(); + ui.render(); + } + + function setBusy(key, v) { + state.itscreenAddon.busy[key] = !!v; + ui.render(); + } + + function inputValue(id) { + const el = document.getElementById(id); + return el ? el.value.trim() : ""; + } + + function btn(label, kind, fnName, busyKey, busyLabel) { + const busy = !!state.itscreenAddon.busy[busyKey]; + return ``; + } + + async function loadConfigOnly() { + const j = await ui.call("/api/addon/itscreen/config"); + state.itscreenAddon.cfg = j.config || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + return j; + } + + async function refreshRemote() { + setBusy("refresh", true); + setMsg("Refreshing registration..."); + try { + const j = await ui.call("/api/addon/itscreen/get_server"); + state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = j.result || {}; + await ui.loadMain().catch(() => {}); + setMsg("Registration data refreshed."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("refresh", false); + } + } + + async function doLogin() { + setBusy("login", true); + setMsg("Login in progress..."); + try { + const j = await ui.call("/api/addon/itscreen/login", { method: "POST", body: "{}" }); + state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = j.result || {}; + setMsg(j.login?.ok ? "Login OK." : "Login failed."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("login", false); + } + } + + async function doRegister() { + const server = inputValue("its_server"); + const username = inputValue("its_user"); + const password = inputValue("its_pass"); + const token = inputValue("its_token"); + + if (!server) return setMsg("Server is required."); + if (!username) return setMsg("Username is required."); + if (!password) return setMsg("Password is required."); + + setBusy("register", true); + setMsg("Saving registration..."); + try { + const j = await ui.call("/api/addon/itscreen/register", { + method: "POST", + body: JSON.stringify({ server, username, password, token }) + }); + state.itscreenAddon.cfg = j.config || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = j.result || {}; + await ui.loadMain().catch(() => {}); + await ui.loadDetail("itscreen").catch(() => {}); + setMsg(j.result?.result === true ? "Registration saved." : "Registration request sent."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("register", false); + } + } + + async function doClear() { + setBusy("clear", true); + setMsg("Clearing registration..."); + try { + const j = await ui.call("/api/addon/itscreen/config/clear", { method: "POST", body: "{}" }); + state.itscreenAddon.cfg = j.config || {}; + state.itscreenAddon.login = j.login || {}; + state.itscreenAddon.registration = j.registration || { configured: false }; + state.itscreenAddon.result = {}; + await ui.loadMain().catch(() => {}); + await ui.loadDetail("itscreen").catch(() => {}); + setMsg("Registration cleared."); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy("clear", false); + } + } + + async function serviceAction(action) { + setBusy(action, true); + setMsg(`Service ${action}...`); + try { + const j = await ui.call(`/api/addon/itscreen/service/${encodeURIComponent(action)}`, { + method: "POST", + body: "{}" + }); + await ui.loadMain().catch(() => {}); + await ui.loadDetail("itscreen").catch(() => {}); + setMsg(`Service ${action} done. Current state: ${j.active || "unknown"}`); + } catch (e) { + setMsg(e.message || String(e)); + } finally { + setBusy(action, false); + } + } + + function renderItscreenDetail(service) { + const cfg = state.itscreenAddon.cfg || {}; + const login = state.itscreenAddon.login || {}; + const reg = state.itscreenAddon.registration || { configured: false }; + + const deviceId = (cfg.deviceId || state.health?.hostname || "unknown").toString(); + + document.getElementById("viewTitle").textContent = service.title; + document.getElementById("viewSub").textContent = service.desc || ""; + document.getElementById("viewActions").innerHTML = + ``; + + document.getElementById("view").innerHTML = ` +
+
+
Service status
+
+
Active
${esc(service.status?.active || "-")} +
Started
${esc(service.status?.started_at || "-")} +
State
${esc(service.status?.summary || "-")} +
Running
${esc(service.status?.running_for_text || "-")} +
Unit file
${esc(service.status?.unit_file_state || "-")} +
Unit
${esc(service.unit || "-")} +
+
+ ${btn("Start", "", "window.__itscreenStart()", "start", "Starting...")} + ${btn("Stop", "danger", "window.__itscreenStop()", "stop", "Stopping...")} + ${btn("Restart", "primary", "window.__itscreenRestart()", "restart", "Restarting...")} +
+
+ +
+
Registration
+
+
Configured
${esc(reg.configured ? "yes" : "no")} +
Device ID
${esc(deviceId)} +
Server
${esc(cfg.server || "-")} +
Username
${esc(cfg.username || "-")} +
Password
${esc(cfg.password ? "******" : "-")} +
Token
${esc(cfg.token || "-")} +
Namespace
${esc(cfg.topicNamespace || "-")} +
Login
${esc(login.ok ? "ok" : "not ok")} +
+ +
+
Server
+ +
+ +
+
Username
+ +
+ +
+
Password
+ +
+ +
+
Token
+ +
+ +
+ ${btn("Login", "", "window.__itscreenLogin()", "login", "Working...")} + ${btn("Refresh registration", "", "window.__itscreenRefresh()", "refresh", "Working...")} + ${btn("Save registration", "primary", "window.__itscreenRegister()", "register", "Saving...")} + ${btn("Clear registration", "danger", "window.__itscreenClear()", "clear", "Clearing...")} +
+
+ +
+
Message
+
${esc(state.itscreenAddon.message || "Ready")}
+
+
+ `; + } + + const prevLoadTabData = ui.loadTabData.bind(ui); + const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){}; + const prevRender = ui.render.bind(ui); + + ui.loadTabData = async function () { + if (state.tab === "itscreen") { + await ui.loadDetail("itscreen"); + await loadConfigOnly().catch(() => {}); + return; + } + return prevLoadTabData(); + }; + + ui.refreshDetail = async function () { + if (state.tab === "itscreen") { + await ui.loadDetail("itscreen"); + await loadConfigOnly().catch(() => {}); + ui.render(); + return; + } + return prevRefreshDetail(); + }; + window.refreshDetail = ui.refreshDetail; + + ui.render = function () { + if (state.tab === "itscreen" && state.detail?.service?.key === "itscreen") { + renderItscreenDetail(state.detail.service); + return; + } + return prevRender(); + }; + window.render = ui.render; + + window.__itscreenRefresh = refreshRemote; + window.__itscreenLogin = doLogin; + window.__itscreenRegister = doRegister; + window.__itscreenClear = doClear; + window.__itscreenRestart = () => serviceAction("restart"); + window.__itscreenStop = () => serviceAction("stop"); + window.__itscreenStart = () => serviceAction("start"); + + setTimeout(async () => { + try { + await loadConfigOnly().catch(() => {}); + if (state.tab === "itscreen") ui.render(); + } catch (_) {} + }, 0); +})(); +JS + +echo "[5/6] restart" +systemctl restart "$SERVICE" + +echo "[6/6] done" +echo "Installed backend: $ADDON_BACK/itscreen.js" +echo "Installed frontend: $ADDON_FRONT/itscreen.js" +echo "Restarted: $SERVICE" \ No newline at end of file diff --git a/stage_ui/legacy_reference/ui_installer.sh b/stage_ui/legacy_reference/ui_installer.sh new file mode 100755 index 0000000..e3471eb --- /dev/null +++ b/stage_ui/legacy_reference/ui_installer.sh @@ -0,0 +1,1910 @@ +#!/usr/bin/env bash +set -euo pipefail + +# IOMATEX WebIPC Engineer Console (light core) v4.2.0 +# Base UI: +# - honest read-only statuses +# - addon-first service pages +# - no stop/restart in core +# - MQTT Bridge shown as runtime feature of Mosquitto + +if head -c 3 "$0" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then + echo "ERROR: UTF-8 BOM detected. Save as UTF-8 (without BOM)." >&2 + exit 1 +fi +if grep -q $'\r' "$0" 2>/dev/null; then + echo "ERROR: CRLF detected. Convert file to UNIX (LF) EOL." >&2 + exit 1 +fi + +need_root(){ [ "$(id -u)" -eq 0 ] || { echo "Run as root: sudo bash $0"; exit 1; }; } +need_root + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +APP_DIR="/opt/iomatex-process1-webipc" +APP_PORT="${WEBIPC_PORT:-8099}" +APP_BIND="${WEBIPC_BIND:-0.0.0.0}" + +ADDONS_DIR="${APP_DIR}/addons" +ADDONS_BACKEND_DIR="${ADDONS_DIR}/backend" +ADDONS_PUBLIC_DIR="${APP_DIR}/public/addons" + +MQTT_URL_DEFAULT="${WEBIPC_MQTT_URL:-mqtt://127.0.0.1:1883}" +MQTT_REPLY_MS_DEFAULT="${WEBIPC_MQTT_REPLY_MS:-2200}" +MQTT_NS_DEFAULT="${WEBIPC_MQTT_NS:-}" +LOGIN_PASSWORD_DEFAULT="${WEBIPC_LOGIN_PASSWORD:-eXXI0wkHBmNBnVbE}" + +SERVICE_NAME="iomatex-webipc.service" +CFG_PATH="/etc/iomatex/webipc.json" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +SRC_LOGO="${LOGO_SOURCE:-$SCRIPT_DIR/iomatex_logo_source.png}" + +echo "[0/10] Cleanup previous install artifacts (safe, keep config)" +ts="$(date +%s)" +systemctl stop "${SERVICE_NAME}" 2>/dev/null || true +systemctl disable "${SERVICE_NAME}" 2>/dev/null || true +rm -f "/etc/systemd/system/${SERVICE_NAME}" 2>/dev/null || true +rm -rf "/etc/systemd/system/${SERVICE_NAME}.d" 2>/dev/null || true +systemctl daemon-reload || true +systemctl reset-failed "${SERVICE_NAME}" 2>/dev/null || true + +if [ -d "$APP_DIR" ]; then + mv -f "$APP_DIR" "${APP_DIR}.prev.${ts}" || rm -rf "$APP_DIR" +fi + +echo "[1/10] Ensure runtime packages exist" +if ! command -v node >/dev/null 2>&1; then + apt-get update + apt-get install -y ca-certificates curl gnupg + curl -fsSL https://deb.nodesource.com/setup_20.x | bash - + apt-get install -y nodejs +fi +apt-get update +apt-get install -y python3 python3-pil +node -v +npm -v + +echo "[2/10] Prepare directories + config" +mkdir -p "$APP_DIR/public" "$ADDONS_BACKEND_DIR" "$ADDONS_PUBLIC_DIR" /etc/iomatex +if [ ! -f "$CFG_PATH" ]; then + cat >"$CFG_PATH" <<'JSON' +{ + "server": "", + "deviceId": "", + "token": "", + "clientId": "", + "registeredAt": "" +} +JSON +fi + +echo "[3/10] Write package.json" +cat > "$APP_DIR/package.json" <<'JSON' +{ + "name": "iomatex-process1-webipc", + "version": "4.2.0", + "private": true, + "main": "server.js", + "type": "commonjs", + "dependencies": { + "express": "^4.19.2", + "mqtt": "^5.7.2" + } +} +JSON + +echo "[4/10] Write server.js" +cat > "$APP_DIR/server.js" <<'JS' +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const os = require("os"); +const express = require("express"); +const mqtt = require("mqtt"); +const { execFile } = require("child_process"); + +const BIND = process.env.WEBIPC_BIND || "0.0.0.0"; +const PORT = parseInt(process.env.WEBIPC_PORT || "8099", 10); +const CFG_PATH = process.env.WEBIPC_CONFIG || "/etc/iomatex/webipc.json"; +const MQTT_URL = process.env.WEBIPC_MQTT_URL || "mqtt://127.0.0.1:1883"; +const MQTT_NS = (process.env.WEBIPC_MQTT_NS || "").trim(); +const MQTT_REPLY_MS = parseInt(process.env.WEBIPC_MQTT_REPLY_MS || "2200", 10); +const LOGIN_PASSWORD = (process.env.WEBIPC_LOGIN_PASSWORD || "").toString().trim(); +const LOGIN_ENABLED = LOGIN_PASSWORD.length > 0; +const MQTT_BRIDGE_ENV = "/etc/iomatex/mqtt_bridge.env"; +const DRM_ROOT = "/sys/class/drm"; +const APP_DIR = "/opt/iomatex-process1-webipc"; +const ADDONS_BACKEND_DIR = path.join(APP_DIR, "addons", "backend"); +const ADDONS_PUBLIC_DIR = path.join(APP_DIR, "public", "addons"); + +const app = express(); +app.disable("x-powered-by"); +app.use(express.json({ limit: "256kb" })); +app.use(express.static(path.join(__dirname, "public"), { etag: false, maxAge: 0 })); +app.use("/addons", express.static(ADDONS_PUBLIC_DIR, { etag: false, maxAge: 0 })); + +function run(cmd, args, timeout = 8000) { + return new Promise((resolve) => { + execFile(cmd, args, { timeout, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => { + if (err) return resolve({ ok: false, err: (stderr || err.message || "").trim(), out: (stdout || "").trim() }); + resolve({ ok: true, out: (stdout || "").trim(), err: (stderr || "").trim() }); + }); + }); +} +function runShell(cmd, timeout = 10000) { + return run("/bin/bash", ["-lc", cmd], timeout); +} +function readJson(p, fallback) { + try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return fallback; } +} +function writeConfig(obj) { + const safe = { + server: (obj.server || "").toString().trim(), + deviceId: (obj.deviceId || "").toString().trim(), + token: (obj.token || "").toString().trim(), + clientId: (obj.clientId || "").toString().trim(), + registeredAt: (obj.registeredAt || "").toString().trim() + }; + fs.mkdirSync(path.dirname(CFG_PATH), { recursive: true }); + fs.writeFileSync(CFG_PATH, JSON.stringify(safe, null, 2) + "\n", "utf8"); + return safe; +} +function readConfig() { + return readJson(CFG_PATH, { server: "", deviceId: "", token: "", clientId: "", registeredAt: "" }); +} +function readFirstInt(p) { + try { return parseInt(fs.readFileSync(p, "utf8").trim(), 10); } catch { return null; } +} +function cpuTempC() { + const t = readFirstInt("/sys/class/thermal/thermal_zone0/temp"); + return (t == null || Number.isNaN(t)) ? null : Math.round((t / 1000) * 10) / 10; +} +function loadAvg() { + const la = os.loadavg(); + return { "1m": Math.round(la[0] * 100) / 100, "5m": Math.round(la[1] * 100) / 100, "15m": Math.round(la[2] * 100) / 100 }; +} +function memInfo() { + try { + const m = fs.readFileSync("/proc/meminfo", "utf8"); + const get = (k) => { const r = new RegExp("^" + k + ":\\s+(\\d+)", "m").exec(m); return r ? parseInt(r[1], 10) : null; }; + const total = get("MemTotal"); + const avail = get("MemAvailable"); + if (!total || !avail) return null; + const used = total - avail; + return { total_kb: total, used_kb: used, avail_kb: avail, used_pct: Math.round((used / total) * 1000) / 10 }; + } catch { return null; } +} + +function nsFromServer(host) { + const h = (host || "").toString().toLowerCase(); + if (h.includes("iomatex")) return "iomatex"; + return "it-screen"; +} +function mqttTopics(cfg, payload) { + const server = (payload.server || cfg.server || "").trim(); + const deviceId = (payload.deviceId || cfg.deviceId || os.hostname()).trim(); + const ns = MQTT_NS || nsFromServer(server); + const base = `${ns}/$devices/settings/${deviceId}`; + return { ns, deviceId, sub: `${base}/sub`, pub: `${base}/pub` }; +} + +function fmtDuration(sec) { + sec = parseInt(sec || 0, 10); + if (!Number.isFinite(sec) || sec < 0) return "-"; + const d = Math.floor(sec / 86400); sec %= 86400; + const h = Math.floor(sec / 3600); sec %= 3600; + const m = Math.floor(sec / 60); sec %= 60; + if (d > 0) return `${d}d ${h}h ${m}m`; + if (h > 0) return `${h}h ${m}m`; + if (m > 0) return `${m}m ${sec}s`; + return `${sec}s`; +} +function getBootEpochMs() { + return Date.now() - Math.floor(os.uptime() * 1000); +} +function monotonicUsecToEpochText(usec) { + const u = parseInt(usec || "0", 10); + if (!Number.isFinite(u) || u <= 0) return ""; + const ms = getBootEpochMs() + Math.floor(u / 1000); + return new Date(ms).toISOString().replace("T", " ").replace("Z", " UTC"); +} +function runningForSec(usec) { + const u = parseInt(usec || "0", 10); + if (!Number.isFinite(u) || u <= 0) return null; + const bootMs = getBootEpochMs(); + const startMs = bootMs + Math.floor(u / 1000); + return Math.max(0, Math.floor((Date.now() - startMs) / 1000)); +} +function fmtRate(bytesPerSec) { + const v = Number(bytesPerSec || 0); + if (!Number.isFinite(v) || v < 0) return "-"; + if (v >= 1024 * 1024) return `${Math.round((v / (1024 * 1024)) * 100) / 100} MB/s`; + if (v >= 1024) return `${Math.round((v / 1024) * 100) / 100} KB/s`; + return `${Math.round(v)} B/s`; +} + +function parseEnvFile(p) { + try { + const raw = fs.readFileSync(p, "utf8"); + const out = {}; + for (const line0 of raw.split("\n")) { + const line = line0.trim(); + if (!line || line.startsWith("#")) continue; + const m = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/); + if (!m) continue; + let v = m[2].trim(); + if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1); + out[m[1]] = v; + } + return out; + } catch { + return {}; + } +} +function maskSecret(v) { + v = (v || "").toString().trim(); + return v ? "******" : "-"; +} +function bridgeConfigSummary() { + const env = parseEnvFile(MQTT_BRIDGE_ENV); + const enabledRaw = (env.ENABLE_BRIDGE || env.BRIDGE_ENABLED || "").toString().trim().toLowerCase(); + const enabled = ["1", "true", "yes", "on"].includes(enabledRaw); + const remote_host = env.REMOTE_HOST || env.BRIDGE_REMOTE_HOST || env.MQTT_REMOTE_HOST || ""; + const remote_port = env.REMOTE_PORT || env.BRIDGE_REMOTE_PORT || env.MQTT_REMOTE_PORT || ""; + const username = env.REMOTE_USERNAME || env.BRIDGE_REMOTE_USERNAME || env.MQTT_REMOTE_USERNAME || env.USERNAME || ""; + const password = env.REMOTE_PASSWORD || env.BRIDGE_REMOTE_PASSWORD || env.MQTT_REMOTE_PASSWORD || env.PASSWORD || ""; + const client_id = env.BRIDGE_CLIENT_ID || env.CLIENT_ID || env.MQTT_CLIENT_ID || ""; + const configured = !!(enabled && remote_host && remote_port); + return { + env_exists: fs.existsSync(MQTT_BRIDGE_ENV), + enabled, + configured, + remote_host, + remote_port, + username, + password_masked: maskSecret(password), + client_id, + raw: env + }; +} +function bridgeConfPath() { + return "/etc/mosquitto/conf.d/50-iomatex-bridge.conf"; +} +function bridgeConfSummary() { + const p = bridgeConfPath(); + const exists = fs.existsSync(p); + let text = ""; + try { text = exists ? fs.readFileSync(p, "utf8") : ""; } catch {} + const has_connection = /(^|\n)\s*connection\s+iomatex_bridge\s*$/m.test(text); + const has_address = /(^|\n)\s*address\s+\S+:\d+\s*$/m.test(text); + const has_v1_edge = /(^|\n)\s*topic\s+v1\/edge\/#\s+(out|in)\s+/m.test(text); + return { + path: p, + exists, + has_connection, + has_address, + has_v1_edge, + valid: !!(exists && has_connection && has_address) + }; +} + +function detectX11State(raw) { + const envDisp = process.env.DISPLAY || ""; + const xSock = fs.existsSync("/tmp/.X11-unix/X0") || fs.existsSync("/tmp/.X11-unix/X1"); + const hasProc = /\bXorg\b|\bXwayland\b|\sX\s/.test(raw || ""); + const active = !!(envDisp || xSock || hasProc); + return { + active, + display: envDisp || (fs.existsSync("/tmp/.X11-unix/X0") ? ":0" : ""), + x_socket: xSock, + note: active ? "display stack detected" : "display stack not detected" + }; +} + +function readText(p) { + try { return fs.readFileSync(p, "utf8").trim(); } catch { return ""; } +} +function readBuf(p) { + try { return fs.readFileSync(p); } catch { return null; } +} +function fileExists(p) { + try { fs.accessSync(p); return true; } catch { return false; } +} +function cleanAscii(buf) { + return (buf || Buffer.alloc(0)).toString("ascii").replace(/\0/g, "").replace(/\r/g, "").replace(/\n/g, "").trim(); +} +function parseManufacturerId(b1, b2) { + const word = ((b1 << 8) | b2) & 0xffff; + const c1 = String.fromCharCode(((word >> 10) & 0x1f) + 64); + const c2 = String.fromCharCode(((word >> 5) & 0x1f) + 64); + const c3 = String.fromCharCode((word & 0x1f) + 64); + const s = `${c1}${c2}${c3}`.replace(/@/g, ""); + return /^[A-Z]{3}$/.test(s) ? s : ""; +} +function parseEdid(edid) { + if (!edid || edid.length < 128) { + return { + present: false, + monitor_name: "", + serial_text: "", + manufacturer_id: "", + product_code: "", + size_cm: "", + size_inch: "", + raw_length: edid ? edid.length : 0 + }; + } + + let monitorName = ""; + let serialText = ""; + + for (let off = 54; off + 18 <= edid.length; off += 18) { + const d = edid.slice(off, off + 18); + if (d[0] === 0x00 && d[1] === 0x00 && d[2] === 0x00 && d[3] === 0xfc) monitorName = cleanAscii(d.slice(5, 18)); + if (d[0] === 0x00 && d[1] === 0x00 && d[2] === 0x00 && d[3] === 0xff) serialText = cleanAscii(d.slice(5, 18)); + } + + const manufacturerId = parseManufacturerId(edid[8], edid[9]); + const productCode = "0x" + Buffer.from([edid[10], edid[11]]).reverse().toString("hex").toUpperCase(); + const widthCm = edid[21] || 0; + const heightCm = edid[22] || 0; + + let sizeInch = ""; + if (widthCm > 0 && heightCm > 0) { + const diagCm = Math.sqrt((widthCm * widthCm) + (heightCm * heightCm)); + sizeInch = (diagCm / 2.54).toFixed(1) + "\""; + } + + return { + present: true, + monitor_name: monitorName, + serial_text: serialText, + manufacturer_id: manufacturerId, + product_code: productCode, + size_cm: (widthCm && heightCm) ? `${widthCm} x ${heightCm} cm` : "", + size_inch: sizeInch, + raw_length: edid.length + }; +} +function connectorKind(name) { + const n = (name || "").toUpperCase(); + if (n.includes("HDMI")) return "hdmi"; + if (n.includes("DP-") || n.includes("DISPLAYPORT") || n.includes("DP")) return "dp"; + if (n.includes("EDP")) return "edp"; + if (n.includes("LVDS")) return "lvds"; + if (n.includes("DSI")) return "dsi"; + if (n.includes("VGA")) return "vga"; + if (n.includes("DVI")) return "dvi"; + return "other"; +} +function listDrmConnectors() { + try { + if (!fileExists(DRM_ROOT)) return []; + return fs.readdirSync(DRM_ROOT) + .filter((name) => fileExists(path.join(DRM_ROOT, name, "status"))) + .sort() + .map((name) => path.join(DRM_ROOT, name)); + } catch { + return []; + } +} +function readModes(dir) { + const txt = readText(path.join(dir, "modes")); + return txt ? txt.split("\n").map(x => x.trim()).filter(Boolean) : []; +} +function readConnector(dir) { + const name = path.basename(dir); + const status = readText(path.join(dir, "status")) || "unknown"; + const enabled = readText(path.join(dir, "enabled")) || ""; + const dpms = readText(path.join(dir, "dpms")) || ""; + const modes = readModes(dir); + const edid = parseEdid(readBuf(path.join(dir, "edid"))); + + return { + connector: name, + kind: connectorKind(name), + status, + enabled, + dpms, + connected: status === "connected", + modes, + preferred_mode: modes[0] || "", + edid + }; +} +function getDisplaySnapshot() { + const connectors = listDrmConnectors().map(readConnector); + const hdmi = connectors.filter(x => x.kind === "hdmi"); + const connectedHdmi = hdmi.filter(x => x.connected); + const anyConnected = connectors.some(x => x.connected); + + return { + ok: true, + hostname: os.hostname(), + drm_root: DRM_ROOT, + any_connected: anyConnected, + connectors, + hdmi, + connected_hdmi: connectedHdmi, + summary: { + connector_count: connectors.length, + hdmi_count: hdmi.length, + connected_count: connectors.filter(x => x.connected).length, + connected_hdmi_count: connectedHdmi.length, + hdmi_connected: connectedHdmi.length > 0, + first_connected_hdmi: connectedHdmi[0] || null + } + }; +} + +let mqttClient = null; +let mqttLast = { ok: false, note: "not_connected" }; +let mqttServerState = null; +let loginState = { enabled: LOGIN_ENABLED, ok: false, last_ts: null, last_error: null, password_set: LOGIN_ENABLED }; + +const networkCache = { + iface: "", + rx_bytes: null, + tx_bytes: null, + ts_ms: null, + download_bps: null, + upload_bps: null, + last: null +}; + +function mqttEnsure() { + if (mqttClient) return mqttClient; + mqttClient = mqtt.connect(MQTT_URL, { + reconnectPeriod: 1000, + connectTimeout: 4000, + keepalive: 30, + clean: true + }); + mqttClient.on("connect", () => { mqttLast = { ok: true, note: "connected", url: MQTT_URL }; }); + mqttClient.on("reconnect", () => { mqttLast = { ok: false, note: "reconnecting" }; }); + mqttClient.on("close", () => { mqttLast = { ok: false, note: "closed" }; }); + mqttClient.on("error", (e) => { mqttLast = { ok: false, note: "error", message: e.message }; }); + mqttClient.on("message", (topic, buf) => { + const raw = (buf || Buffer.from("")).toString(); + let parsed = null; + try { parsed = JSON.parse(raw); } catch { parsed = { raw }; } + if (parsed && typeof parsed === "object" && parsed.category === "server" && typeof parsed.host === "string") mqttServerState = parsed; + if (parsed && typeof parsed === "object" && parsed.action === "login") { + loginState.ok = !!parsed.result; + loginState.last_ts = Date.now(); + loginState.last_error = parsed.result ? null : "login_failed"; + } + }); + return mqttClient; +} + +let mqttLock = Promise.resolve(); +function mqttSendWaitReply(cfg, payload, opts = {}) { + const client = mqttEnsure(); + const { sub, pub, ns, deviceId } = mqttTopics(cfg, payload); + const msg = Object.assign({}, payload); + delete msg.ts; + const maxWait = Math.max(300, Math.min(parseInt(opts.reply_ms || MQTT_REPLY_MS, 10) || MQTT_REPLY_MS, 15000)); + + const runOne = () => new Promise((resolve) => { + client.subscribe(pub, { qos: 0 }, (err) => { + if (err) return resolve({ ok: false, note: "subscribe_failed", error: err.message, ns, deviceId }); + const t0 = Date.now(); + const timer = setTimeout(() => { + client.removeListener("message", onMsg); + resolve({ ok: true, sent: true, note: "sent_no_reply", topic_sub: sub, topic_pub: pub, ms: Date.now() - t0, ns, deviceId }); + }, maxWait); + + function onMsg(topic, buf) { + if (topic !== pub) return; + clearTimeout(timer); + client.removeListener("message", onMsg); + const raw = (buf || Buffer.from("")).toString(); + let parsed = null; + try { parsed = JSON.parse(raw); } catch { parsed = { raw }; } + resolve({ ok: true, sent: true, reply: parsed, topic_sub: sub, topic_pub: pub, ms: Date.now() - t0, ns, deviceId }); + } + + client.on("message", onMsg); + client.publish(sub, JSON.stringify(msg), { qos: 0, retain: false }, (perr) => { + if (perr) { + clearTimeout(timer); + client.removeListener("message", onMsg); + resolve({ ok: false, note: "publish_failed", error: perr.message, ns, deviceId }); + } + }); + }); + }); + + mqttLock = mqttLock.then(runOne, runOne); + return mqttLock; +} + +async function ensureLoggedForRegistration(cfg) { + if (!LOGIN_ENABLED) return { ok: true, skipped: true }; + if (loginState.ok === true) return { ok: true, reused: true }; + const deviceId = (cfg.deviceId || os.hostname()).trim(); + const payload = { action: "login", password: LOGIN_PASSWORD, deviceId, server: cfg.server || "" }; + const r = await mqttSendWaitReply(cfg, payload, { reply_ms: 3500 }); + if (r && r.reply && r.reply.action === "login") { + loginState.ok = !!r.reply.result; + loginState.last_ts = Date.now(); + loginState.last_error = r.reply.result ? null : "login_failed"; + } else { + loginState.last_ts = Date.now(); + loginState.last_error = r.note || "no_reply"; + } + return r; +} + +const SERVICES = { + itscreen: { + key: "itscreen", + title: "Itscreen", + unit: "itscreen-x11.service", + desc: "Main itscreen runtime (X11).", + paths: ["/etc/iomatex/webipc.json", "/etc/systemd/system/itscreen-x11.service", "/lib/systemd/system/itscreen-x11.service"], + access: { kind: "none" } + }, + x11: { + key: "x11", + title: "Display", + unit: "display stack", + desc: "Display stack and HDMI monitor status for local screen output.", + paths: ["/sys/class/drm", "/tmp/.X11-unix", "/usr/bin/Xorg", "/etc/X11"], + access: { kind: "none" } + }, + cockpit: { + key: "cockpit", + title: "Cockpit", + unit: "cockpit.service", + socket: "cockpit.socket", + desc: "Cockpit web administration.", + paths: ["/etc/cockpit/cockpit.conf", "/lib/systemd/system/cockpit.service", "/lib/systemd/system/cockpit.socket"], + access: { kind: "url", url: "http://127.0.0.1:9090", label: "Open Cockpit" } + }, + mosquitto: { + key: "mosquitto", + title: "Mosquitto", + unit: "mosquitto.service", + desc: "Local MQTT broker.", + paths: ["/etc/mosquitto/mosquitto.conf", "/etc/mosquitto/conf.d", "/lib/systemd/system/mosquitto.service"], + access: { kind: "none" } + }, + bridge: { + key: "bridge", + title: "MQTT Bridge", + unit: "mqtt bridge runtime", + desc: "Bridge runtime inside Mosquitto.", + paths: ["/etc/iomatex/mqtt_bridge.env", "/etc/mosquitto/conf.d/50-iomatex-bridge.conf", "/etc/systemd/system/iomatex-mqtt-bridge.service"], + access: { kind: "none" } + }, + z2m: { + key: "z2m", + title: "Zigbee2MQTT", + unit: "zigbee2mqtt.service", + desc: "Zigbee2MQTT runtime.", + paths: ["/opt/zigbee2mqtt/data/configuration.yaml", "/opt/zigbee2mqtt/data/state.json", "/etc/systemd/system/zigbee2mqtt.service"], + access: { kind: "url", url: "http://127.0.0.1:8081", label: "Open Z2M" } + }, + rtcockpit: { + key: "rtcockpit", + title: "RT Cockpit", + unit: "iomatex-rt-cockpit.service", + desc: "Reverse SSH tunnel for Cockpit.", + paths: ["/etc/systemd/system/iomatex-rt-cockpit.service", "/usr/local/sbin", "/etc/iomatex"], + access: { kind: "none" } + }, + rtz2m: { + key: "rtz2m", + title: "RT Z2M", + unit: "iomatex-rt-z2m.service", + desc: "Reverse SSH tunnel for Zigbee2MQTT.", + paths: ["/etc/systemd/system/iomatex-rt-z2m.service", "/usr/local/sbin", "/etc/iomatex"], + access: { kind: "none" } + }, + rtwebui: { + key: "rtwebui", + title: "RT Iomatex", + unit: "iomatex-rt-webui.service", + desc: "Reverse SSH tunnel for IOMATEX Web UI.", + paths: ["/etc/systemd/system/iomatex-rt-webui.service", "/usr/local/sbin", "/etc/iomatex"], + access: { kind: "none" } + } +}; + +function parseShow(out) { + const o = {}; + for (const line of (out || "").split("\n")) { + const i = line.indexOf("="); + if (i > 0) o[line.slice(0, i)] = line.slice(i + 1); + } + return o; +} + +async function systemdShow(unit) { + const show = await run("/bin/systemctl", [ + "show", unit, "--no-page", + "--property=Id,Description,LoadState,ActiveState,SubState,UnitFileState,ExecMainStartTimestamp,ExecMainStartTimestampMonotonic,ActiveEnterTimestamp,ActiveEnterTimestampMonotonic,FragmentPath,TriggeredBy,Triggers,ExecStart" + ], 8000); + return parseShow(show.out || ""); +} +async function systemctlIsActive(unit) { + const r = await run("/bin/systemctl", ["is-active", unit], 6000); + const txt = (r.out || r.err || "").trim(); + return txt || "unknown"; +} +async function systemctlIsEnabled(unit) { + const r = await run("/bin/systemctl", ["is-enabled", unit], 6000); + const txt = (r.out || r.err || "").trim(); + return txt || "unknown"; +} + +function enrichShow(p) { + const startMono = p.ExecMainStartTimestampMonotonic || p.ActiveEnterTimestampMonotonic || ""; + const started_at = p.ExecMainStartTimestamp || p.ActiveEnterTimestamp || monotonicUsecToEpochText(startMono) || ""; + const running_sec = runningForSec(startMono); + return { + started_at: started_at || "", + running_for_sec: running_sec, + running_for_text: running_sec == null ? "-" : fmtDuration(running_sec) + }; +} + +async function unitStatus(unit) { + const p = await systemdShow(unit); + const load = (p.LoadState || "").trim() || "unknown"; + const sub = (p.SubState || "").trim() || ""; + const activeShow = (p.ActiveState || "").trim() || "unknown"; + const activeReal = await systemctlIsActive(unit); + const enabledReal = await systemctlIsEnabled(unit); + const extra = enrichShow(p); + + if (load === "not-found" || activeReal === "not-found") { + return { + unit, + load_state: "not-found", + active: "not_installed", + sub: "", + unit_file_state: "not_installed", + badge: "gray", + summary: "not installed", + show: p, + started_at: "", + running_for_text: "-", + error_text: `${unit} is not installed` + }; + } + + let active = activeReal || activeShow || "unknown"; + let badge = "gray"; + let summary = "inactive"; + let errorText = ""; + + if (load === "error" || active === "failed" || sub === "failed") { + badge = "red"; + summary = "error"; + active = "failed"; + } else if (active === "active" || activeShow === "active") { + badge = "green"; + summary = "active"; + active = "active"; + } else if (active === "activating" || active === "deactivating" || activeShow === "activating" || activeShow === "deactivating") { + badge = "amber"; + summary = active; + } else if (active === "inactive") { + badge = "gray"; + summary = "inactive"; + } else { + badge = "gray"; + summary = active || "unknown"; + } + + if (active === "failed") { + const err = await runShell(`journalctl -u '${unit}' -n 30 --no-pager -o short-iso 2>/dev/null || true`, 9000); + errorText = (err.out || "").trim() || "Service failed"; + } + + return { + unit, + load_state: load, + active, + sub, + unit_file_state: enabledReal || (p.UnitFileState || "").trim() || "unknown", + badge, + summary, + show: p, + started_at: extra.started_at, + running_for_text: extra.running_for_text, + error_text: errorText + }; +} + +async function cockpitStatus() { + const svc = await unitStatus("cockpit.service"); + const sock = await unitStatus("cockpit.socket"); + + if (svc.summary === "not installed" && sock.summary === "not installed") { + return { + unit: "cockpit.service", + load_state: "not-found", + active: "not_installed", + sub: "", + unit_file_state: "not_installed", + badge: "gray", + summary: "not installed", + show: {}, + started_at: "", + running_for_text: "-", + error_text: "cockpit.service is not installed" + }; + } + + let badge = "gray"; + let summary = "inactive"; + let active = "inactive"; + let errorText = ""; + + if (svc.badge === "red" || sock.badge === "red") { + badge = "red"; + summary = "error"; + active = "failed"; + errorText = [svc.error_text || "", sock.error_text || ""].filter(Boolean).join("\n\n") || "Cockpit failed"; + } else if (svc.active === "active" || sock.active === "active") { + badge = "green"; + summary = "active"; + active = "active"; + } else if (svc.active === "activating" || svc.active === "deactivating" || sock.active === "activating" || sock.active === "deactivating") { + badge = "amber"; + summary = "transition"; + active = "activating"; + } + + return { + unit: "cockpit.service", + load_state: svc.load_state, + active, + sub: svc.sub || sock.sub || "", + unit_file_state: svc.unit_file_state || sock.unit_file_state || "unknown", + badge, + summary, + show: { + service: svc.show || {}, + socket: sock.show || {} + }, + started_at: svc.started_at || sock.started_at || "", + running_for_text: svc.running_for_text || sock.running_for_text || "-", + error_text: errorText + }; +} + +async function x11Status() { + const p = await runShell(`ps -ef 2>/dev/null | grep -E 'Xorg|Xwayland|\\sX\\s' | grep -v grep || true`, 7000); + const x = detectX11State(p.out || ""); + const display = getDisplaySnapshot(); + + let badge = "gray"; + let summary = "inactive"; + let active = "inactive"; + + if (display.summary.hdmi_connected) { + badge = "green"; + summary = "hdmi connected"; + active = x.active ? "active" : "inactive"; + } else if (display.any_connected) { + badge = "amber"; + summary = "display connected"; + active = x.active ? "active" : "inactive"; + } else if (x.active) { + badge = "green"; + summary = "display stack active"; + active = "active"; + } + + return { + unit: "display stack", + load_state: x.active ? "detected" : "not_detected", + active, + sub: x.display || "", + unit_file_state: "-", + badge, + summary, + show: { FragmentPath: "-", ExecMainStartTimestamp: "-", XProcessList: p.out || "" }, + started_at: "-", + running_for_text: "-", + error_text: "", + x11: x, + display + }; +} + +async function getReverseTunnelSnapshot() { + const cmd = `extip="$(curl -4 -s https://api.ipify.org || true)"; ps -eo args | grep -F '/usr/lib/autossh/autossh' | grep -F ' -R 127.0.0.1:' | grep -v grep | while read -r line; do sshp="$(printf '%s\\n' "$line" | sed -nE 's/.* -p ([0-9]+) .*/\\1/p')"; remote="$(printf '%s\\n' "$line" | sed -nE 's/.* -R 127\\.0\\.0\\.1:([0-9]+):127\\.0\\.0\\.1:([0-9]+) .*/\\1/p')"; localp="$(printf '%s\\n' "$line" | sed -nE 's/.* -R 127\\.0\\.0\\.1:([0-9]+):127\\.0\\.0\\.1:([0-9]+) .*/\\2/p')"; user="$(printf '%s\\n' "$line" | sed -nE 's/.* ([^ @]+)@([^ ]+)$/\\1/p')"; host="$(printf '%s\\n' "$line" | sed -nE 's/.* ([^ @]+)@([^ ]+)$/\\2/p')"; svc="unknown"; unit=""; [ "$localp" = "9090" ] && svc="cockpit" && unit="iomatex-rt-cockpit.service"; [ "$localp" = "8081" ] && svc="z2m" && unit="iomatex-rt-z2m.service"; [ "$localp" = "8099" ] && svc="webui" && unit="iomatex-rt-webui.service"; state="$(systemctl is-active "$unit" 2>/dev/null || echo unknown)"; printf '%s|%s|%s|%s|%s|%s|127.0.0.1:%s|%s\\n' "$svc" "$state" "$host" "$remote" "$user" "$sshp" "$localp" "$extip"; done | sort`; + const r = await runShell(cmd, 15000); + const rows = []; + for (const line of (r.out || "").split("\n")) { + const s = line.trim(); + if (!s) continue; + const [svc, state, host, remote, user, ssh_port, local_target, extip] = s.split("|"); + rows.push({ svc, state, host, remote, user, ssh_port, local_target, extip }); + } + return rows; +} + +async function reverseTunnelStatus(unit, svcKey) { + const s = await unitStatus(unit); + if (s.summary === "not installed") return s; + + const rows = await getReverseTunnelSnapshot(); + let row = null; + if (svcKey === "rtcockpit") row = rows.find(x => x.svc === "cockpit") || null; + if (svcKey === "rtz2m") row = rows.find(x => x.svc === "z2m") || null; + if (svcKey === "rtwebui") row = rows.find(x => x.svc === "webui") || null; + + return Object.assign({}, s, { + tunnel: row || { svc: "", state: "", host: "", remote: "", user: "", ssh_port: "", local_target: "", extip: "" } + }); +} + +function parseZ2MPortFromConfig() { + const cfg = "/opt/zigbee2mqtt/data/configuration.yaml"; + try { + const raw = fs.readFileSync(cfg, "utf8"); + let m = raw.match(/^\s*port:\s*["']?([^"'\n#]+)["']?\s*$/m); + if (m && m[1]) return m[1].trim(); + m = raw.match(/^\s*serial:\s*\n(?:.*\n){0,20}?\s*port:\s*["']?([^"'\n#]+)["']?\s*$/m); + if (m && m[1]) return m[1].trim(); + return ""; + } catch { + return ""; + } +} + +async function getUsbStickInfo() { + const configuredPort = parseZ2MPortFromConfig(); + let configuredExists = false; + let configuredResolved = ""; + + if (configuredPort) { + try { + configuredExists = fs.existsSync(configuredPort); + if (configuredExists) configuredResolved = fs.realpathSync(configuredPort); + } catch {} + } + + const byid = await runShell(`ls -l /dev/serial/by-id 2>/dev/null || true`, 5000); + const tty = await runShell(`ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null || true`, 5000); + const lsusb = await run("/usr/bin/lsusb", [], 8000); + + const byidLines = (byid.out || "").split("\n").map(x => x.trim()).filter(Boolean); + const likelyById = byidLines.filter(x => /(zigbee|sonoff|cc2652|ember|ezsp|zbdongle|nabu|slae|thirdreality|tubeszb)/i.test(x)); + + const usbLikely = ((lsusb.out || "").split("\n").map(x => x.trim()).filter(Boolean)) + .filter(x => /(zigbee|sonoff|cc2652|ezsp|ember|nabu|slae|silicon labs|texas instruments|tubeszb|dongle)/i.test(x)); + + const connected = configuredPort + ? configuredExists + : (likelyById.length > 0 || usbLikely.length > 0); + + return { + connected, + configured_port: configuredPort || "", + configured_port_exists: configuredExists, + configured_port_resolved: configuredResolved, + by_id: byid.out || "", + tty: tty.out || "", + lsusb: lsusb.out || "", + likely_by_id_count: likelyById.length, + likely_usb_count: usbLikely.length + }; +} + +function getIfaceCounters(iface) { + try { + const rx = parseInt(fs.readFileSync(`/sys/class/net/${iface}/statistics/rx_bytes`, "utf8").trim(), 10); + const tx = parseInt(fs.readFileSync(`/sys/class/net/${iface}/statistics/tx_bytes`, "utf8").trim(), 10); + if (!Number.isFinite(rx) || !Number.isFinite(tx)) return null; + return { rx, tx }; + } catch { + return null; + } +} + +async function networkStatus() { + const def = await runShell(`ip route show default 2>/dev/null | awk '/default/ {print $5; exit}'`, 5000); + let iface = (def.out || "").trim(); + + if (!iface) { + const alt = await runShell(`ip -o link show | awk -F': ' '$2!="lo"{print $2}' | head -n1`, 5000); + iface = (alt.out || "").trim(); + } + + let ipv4 = ""; + let connType = ""; + let linkSpeed = "-"; + let internet = false; + let internetText = "offline"; + let gateway = "-"; + let dns = "-"; + let uploadText = "-"; + let downloadText = "-"; + + if (iface) { + connType = iface.startsWith("wl") ? "wlan0" : (iface.startsWith("en") || iface.startsWith("eth") ? "eth0" : iface); + + const ip4 = await runShell(`ip -4 -o addr show dev '${iface}' 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n1`, 5000); + ipv4 = (ip4.out || "").trim(); + + const gw = await runShell(`ip route show default 2>/dev/null | awk '/default/ && $5=="${iface}" {print $3; exit}'`, 5000); + gateway = (gw.out || "").trim() || "-"; + + const dnsR = await runShell(`awk '/^nameserver /{print $2}' /etc/resolv.conf 2>/dev/null | paste -sd, -`, 5000); + dns = (dnsR.out || "").trim() || "-"; + + if (iface.startsWith("wl")) { + const iw = await runShell(`command -v iw >/dev/null 2>&1 && iw dev '${iface}' link 2>/dev/null | awk -F': ' '/tx bitrate/ {print $2; exit}' || true`, 6000); + linkSpeed = (iw.out || "").trim() || "-"; + } else { + try { + const s = fs.readFileSync(`/sys/class/net/${iface}/speed`, "utf8").trim(); + if (s && s !== "-1") linkSpeed = `${s} Mb/s`; + } catch {} + } + + const now = Date.now(); + const counters = getIfaceCounters(iface); + + if (counters) { + if (networkCache.iface === iface && networkCache.ts_ms != null && networkCache.rx_bytes != null && networkCache.tx_bytes != null) { + const dt = Math.max(1, (now - networkCache.ts_ms) / 1000); + networkCache.download_bps = Math.max(0, (counters.rx - networkCache.rx_bytes) / dt); + networkCache.upload_bps = Math.max(0, (counters.tx - networkCache.tx_bytes) / dt); + } + networkCache.iface = iface; + networkCache.rx_bytes = counters.rx; + networkCache.tx_bytes = counters.tx; + networkCache.ts_ms = now; + } + + uploadText = networkCache.upload_bps == null ? "-" : fmtRate(networkCache.upload_bps); + downloadText = networkCache.download_bps == null ? "-" : fmtRate(networkCache.download_bps); + } + + const ping = await run("/usr/bin/timeout", ["4", "/bin/ping", "-c", "1", "-W", "2", "1.1.1.1"], 5000); + internet = !!ping.ok; + internetText = internet ? "online" : "offline"; + + const result = { + ok: true, + iface: iface || "", + connection_type: connType || "-", + ipv4: ipv4 || "-", + gateway, + dns, + internet, + internet_text: internetText, + link_speed: linkSpeed, + upload: uploadText, + download: downloadText, + checked_at: new Date().toISOString() + }; + + networkCache.last = result; + return result; +} + +async function getBridgeRuntimeStatus() { + const apply = await unitStatus("iomatex-mqtt-bridge.service"); + const mosq = await unitStatus("mosquitto.service"); + const env = bridgeConfigSummary(); + const conf = bridgeConfSummary(); + + let badge = "gray"; + let summary = "not configured"; + let active = "inactive"; + let error_text = ""; + + if (!env.env_exists && !conf.exists) { + badge = "gray"; + summary = "not configured"; + active = "inactive"; + } else if (!env.enabled) { + badge = "gray"; + summary = "disabled"; + active = "inactive"; + } else if (mosq.active === "failed" || apply.active === "failed") { + badge = "red"; + summary = "error"; + active = "failed"; + error_text = [mosq.error_text || "", apply.error_text || ""].filter(Boolean).join("\n\n") || "Bridge error"; + } else if (mosq.active === "active" && conf.valid) { + badge = "green"; + summary = "active"; + active = "active"; + } else if (mosq.active === "inactive" && conf.valid) { + badge = "gray"; + summary = "inactive"; + active = "inactive"; + } else { + badge = "amber"; + summary = "partial"; + active = "inactive"; + } + + return { + unit: "mqtt bridge runtime", + load_state: conf.exists ? "loaded" : "not-found", + active, + sub: summary, + unit_file_state: apply.unit_file_state || "-", + badge, + summary, + show: { + apply_unit: apply.show || {}, + mosquitto_unit: mosq.show || {}, + bridge_conf: conf, + bridge_env: env + }, + started_at: mosq.started_at || "", + running_for_text: mosq.running_for_text || "-", + error_text, + bridge_cfg: env, + bridge_conf: conf, + apply_unit: apply, + mosquitto_unit: mosq + }; +} + +async function getServiceStatus(def) { + if (def.key === "cockpit") return cockpitStatus(); + if (def.key === "x11") return x11Status(); + if (def.key === "bridge") return getBridgeRuntimeStatus(); + if (def.key === "rtcockpit" || def.key === "rtz2m" || def.key === "rtwebui") return reverseTunnelStatus(def.unit, def.key); + return unitStatus(def.unit); +} + +async function getServiceDetail(key) { + const def = SERVICES[key]; + if (!def) return null; + + const status = await getServiceStatus(def); + const access = Object.assign({}, def.access); + let extra = {}; + + if (key === "z2m") extra.usb = await getUsbStickInfo(); + if (key === "bridge") { + extra.bridge_cfg = status.bridge_cfg || bridgeConfigSummary(); + extra.bridge_conf = status.bridge_conf || bridgeConfSummary(); + extra.apply_unit = status.apply_unit || await unitStatus("iomatex-mqtt-bridge.service"); + extra.mosquitto_unit = status.mosquitto_unit || await unitStatus("mosquitto.service"); + } + if (key === "x11") { + extra.x11 = status.x11 || {}; + extra.display = status.display || getDisplaySnapshot(); + } + + return { + ok: true, + service: { + key: def.key, + title: def.title, + unit: def.unit, + desc: def.desc, + paths: def.paths, + access, + status, + extra, + addon_required: true + } + }; +} + +function frontendAddonKeys() { + try { + if (!fs.existsSync(ADDONS_PUBLIC_DIR)) return []; + return fs.readdirSync(ADDONS_PUBLIC_DIR) + .filter(x => x.endsWith(".js")) + .map(x => path.basename(x, ".js")) + .sort(); + } catch { + return []; + } +} + +app.get("/api/health", (req, res) => { + res.json({ + ok: true, + web: true, + mqtt_url: MQTT_URL, + mqtt: mqttLast, + login: { + enabled: loginState.enabled, + ok: loginState.ok, + last_ts: loginState.last_ts, + last_error: loginState.last_error, + password_set: loginState.password_set + }, + config: CFG_PATH, + addons_backend_dir: ADDONS_BACKEND_DIR, + addons_frontend_dir: ADDONS_PUBLIC_DIR + }); +}); + +app.get("/api/addons", (req, res) => { + try { + const items = fs.existsSync(ADDONS_PUBLIC_DIR) + ? fs.readdirSync(ADDONS_PUBLIC_DIR) + .filter(x => x.endsWith(".js")) + .sort() + .map(x => ({ name: x, key: path.basename(x, ".js"), url: `/addons/${x}` })) + : []; + res.json({ ok: true, addons: items }); + } catch (e) { + res.status(500).json({ ok: false, error: e.message }); + } +}); + +app.get("/api/config", (req, res) => res.json({ ok: true, config: readConfig() })); + +app.get("/api/display/hdmi", (req, res) => { + res.json(getDisplaySnapshot()); +}); + +app.get("/api/edge/health", async (req, res) => { + const net = await networkStatus(); + res.json({ + ok: true, + hostname: os.hostname(), + uptime_sec: Math.floor(os.uptime()), + temp_c: cpuTempC(), + mem: memInfo(), + load: loadAvg(), + network: net + }); +}); + +app.get("/api/main/services", async (req, res) => { + const items = []; + const errors = []; + const addonKeys = frontendAddonKeys(); + + for (const key of Object.keys(SERVICES)) { + const def = SERVICES[key]; + const status = await getServiceStatus(def); + let meta = {}; + + if (key === "bridge") { + meta.bridge_cfg = status.bridge_cfg || bridgeConfigSummary(); + meta.bridge_conf = status.bridge_conf || bridgeConfSummary(); + } + if (key === "x11") meta.display = status.display || getDisplaySnapshot(); + if (key === "z2m") meta.usb = await getUsbStickInfo(); + if (key === "rtcockpit" || key === "rtz2m" || key === "rtwebui") meta.tunnel = status.tunnel || {}; + + items.push({ + key, + title: def.title, + unit: def.unit, + desc: def.desc, + access: def.access, + status, + meta, + addon_installed: addonKeys.includes(key) + }); + + if (status.badge === "red") { + errors.push({ + key, + title: def.title, + unit: def.unit, + summary: status.summary, + text: status.error_text || "Service failed" + }); + } + } + + res.json({ ok: true, items, errors }); +}); + +app.get("/api/service/:key", async (req, res) => { + const j = await getServiceDetail(req.params.key); + if (!j) return res.status(404).json({ ok: false, error: "unknown service" }); + + const addonKeys = frontendAddonKeys(); + j.service.addon_installed = addonKeys.includes(j.service.key); + + res.json(j); +}); + +app.post("/api/service/:key/:action", async (req, res) => { + return res.status(400).json({ ok: false, error: "service actions are disabled in base installer; install addon" }); +}); + +function loadBackendAddons() { + const loaded = []; + if (!fs.existsSync(ADDONS_BACKEND_DIR)) return loaded; + + for (const file of fs.readdirSync(ADDONS_BACKEND_DIR).filter(x => x.endsWith(".js")).sort()) { + const full = path.join(ADDONS_BACKEND_DIR, file); + try { + const mod = require(full); + if (typeof mod === "function") { + mod(app, { + app, + fs, + path, + os, + run, + runShell, + readJson, + writeConfig, + readConfig, + mqttEnsure, + mqttSendWaitReply, + ensureLoggedForRegistration, + LOGIN_PASSWORD, + LOGIN_ENABLED, + MQTT_URL, + MQTT_NS, + MQTT_REPLY_MS, + CFG_PATH + }); + loaded.push(file); + } + } catch (e) { + console.error(`[addon-backend] failed to load ${file}: ${e.message}`); + } + } + return loaded; +} + +const loadedBackendAddons = loadBackendAddons(); + +app.listen(PORT, BIND, async () => { + try { mqttEnsure(); } catch {} + try { await networkStatus(); } catch {} + console.log(`[webipc] http://${BIND}:${PORT} (mqtt ${MQTT_URL})`); + if (loadedBackendAddons.length) console.log(`[webipc] backend addons: ${loadedBackendAddons.join(", ")}`); +}); +JS + +echo "[5/10] Write minimal branded UI" +cat > "$APP_DIR/public/index.html" <<'HTML' + + + + + + IOMATEX Edge Console + + + + +
+
+
+
+ +
+
IOMATEX Edge Console
+
Loading…
+
+
+
+
API
+
host: …
+
mqtt: …
+
+
+
+
+ +
+
+
+
+
Main
+
Services overview
+
+
+
+
+
+ +
+
+
+
Errors
+
Only failed services from Main
+
+
+
+
+
+
+
+ + + + +HTML + +echo "[6/10] Write logo and favicon from source image" +if [ ! -f "$SRC_LOGO" ]; then + echo "ERROR: logo source image not found: $SRC_LOGO" >&2 + echo "Put source image here: $SCRIPT_DIR/iomatex_logo_source.png" >&2 + exit 1 +fi + +python3 - "$SRC_LOGO" "$APP_DIR/public/logo.png" "$APP_DIR/public/favicon.png" <<'PY' +import sys +from PIL import Image + +src = sys.argv[1] +logo_out = sys.argv[2] +fav_out = sys.argv[3] + +img = Image.open(src).convert("RGBA") + +logo = img.copy() +logo.thumbnail((96, 96)) +logo.save(logo_out, format="PNG") + +fav = img.copy() +fav.thumbnail((64, 64)) +fav.save(fav_out, format="PNG") + +print("Generated logo.png and favicon.png") +PY + +echo "[7/10] Write addon placeholders" +cat > "$ADDONS_BACKEND_DIR/README.txt" <<'TXT' +Place backend addons here as .js files. +Module format: +module.exports = function(app, ctx) { + app.get("/api/example", (req, res) => res.json({ ok: true })); +}; +TXT + +cat > "$ADDONS_PUBLIC_DIR/README.txt" <<'TXT' +Place frontend addons here as .js files. +They are auto-loaded from /api/addons after main UI boot. +Recommended addon file name = service key, for example: +mosquitto.js +bridge.js +z2m.js +Use window.IOMATEX_UI to access core state and helpers. +TXT + +echo "[8/10] npm install" +cd "$APP_DIR" +npm install --omit=dev + +echo "[9/10] Install systemd service" +cat > "/etc/systemd/system/${SERVICE_NAME}" <:${APP_PORT}" +echo "API health: curl -s http://127.0.0.1:${APP_PORT}/api/health | cat" +echo "Main services: curl -s http://127.0.0.1:${APP_PORT}/api/main/services | cat" +echo "Display API: curl -s http://127.0.0.1:${APP_PORT}/api/display/hdmi | cat" +echo "Addon list: curl -s http://127.0.0.1:${APP_PORT}/api/addons | cat" +echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40" +echo "Previous install: ${APP_DIR}.prev.${ts}" +echo "Backend addons dir: ${ADDONS_BACKEND_DIR}" +echo "Frontend addons dir: ${ADDONS_PUBLIC_DIR}" +echo "Logo source expected at: ${SRC_LOGO}" \ No newline at end of file