diff --git a/stage_ui/console_core/ARCHITECTURE.md b/stage_ui/console_core/ARCHITECTURE.md index 16b21b5..435dd79 100644 --- a/stage_ui/console_core/ARCHITECTURE.md +++ b/stage_ui/console_core/ARCHITECTURE.md @@ -3,6 +3,7 @@ ## Core responsibilities - Serve one fast local diagnostics UI. - Expose one normalized status endpoint: `/api/status`. +- Expose focused lightweight detail endpoints when a core card needs richer data, for example `/api/display`. - Load provider modules from `providers.d`. - Cache recent status briefly to avoid repeated shell work on every page render. @@ -10,6 +11,7 @@ - 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. +- Prefer Linux-local sources such as DRM/sysfs for hardware diagnostics and degrade cleanly when fields are missing. ## Future `ui_backend` role - Keep this Console focused on lightweight diagnostics. diff --git a/stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc b/stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc index e5d14b8..a816318 100644 Binary files a/stage_ui/console_core/backend/__pycache__/app.cpython-312.pyc 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 index edf2e04..6505c82 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -66,6 +66,14 @@ def read_text(path): return "" +def read_bytes(path): + try: + with open(path, "rb") as fh: + return fh.read() + except Exception: + return b"" + + def read_env_file(path): data = {} try: @@ -146,6 +154,10 @@ def normalize_card(card): 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()] + item["details"] = [detail for detail in item.get("details", []) if isinstance(detail, dict)] + item["connectors"] = [connector for connector in item.get("connectors", []) if isinstance(connector, dict)] + status = item.get("display_status") + item["display_status"] = status if isinstance(status, dict) else {} return item @@ -176,8 +188,10 @@ def build_status_payload(): "file_exists": file_exists, "any_exists": any_exists, "read_text": read_text, + "read_bytes": read_bytes, "read_env_file": read_env_file, "systemd_unit": systemd_unit, + "run": run, } cards = [] provider_names = [] @@ -204,6 +218,7 @@ def build_status_payload(): payload = { "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "hostname": os.uname().nodename, "services": cards, "providers": provider_names, } @@ -212,6 +227,17 @@ def build_status_payload(): return payload +def find_service_card(service_id): + payload = build_status_payload() + for card in payload.get("services", []): + if card.get("id") == service_id: + return { + "generated_at": payload.get("generated_at", ""), + "service": card, + } + return None + + class Handler(BaseHTTPRequestHandler): def log_message(self, fmt, *args): return @@ -242,6 +268,13 @@ class Handler(BaseHTTPRequestHandler): if parsed.path == "/api/status": self.send_json(build_status_payload()) return + if parsed.path == "/api/display": + payload = find_service_card("display") + if payload is None: + self.send_json({"error": "Display card not found"}, code=404) + return + self.send_json(payload) + return if parsed.path in ("/", "/index.html"): self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8") return diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index 01e29bd..45d7301 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -23,14 +23,17 @@ body{ 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} +.brand{display:flex;align-items:center;gap:16px;min-width:0} +.brandCopy{display:flex;flex-direction:column;justify-content:center;gap:3px;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; + width:68px;height:68px;object-fit:contain;display:block;flex:0 0 auto; + border-radius:18px;background:rgba(255,255,255,.9);border:1px solid rgba(215,224,219,.9);padding:7px; + box-shadow:0 10px 24px rgba(16,24,20,.06); } -.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)} +.eyebrow{font-size:11px;letter-spacing:.18em;text-transform:uppercase;color:var(--accent);font-weight:600} +h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03em} +.sub{margin:0;color:var(--muted);font-weight:300} +.subHost{font-size:13px;font-weight:500;color:var(--ink)} .actions button{ border:0;border-radius:999px;background:var(--ink);color:#fff;padding:12px 18px;font-weight:700;cursor:pointer; box-shadow:var(--shadow); @@ -58,6 +61,7 @@ h1{margin:4px 0 4px;font-size:34px;line-height:1} .dot.warn{background:var(--warn)} .dot.error{background:var(--error)} .meta{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;margin-top:16px;font-size:13px} +.compactMeta{margin-top:0} .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} @@ -71,8 +75,29 @@ h1{margin:4px 0 4px;font-size:34px;line-height:1} .empty{ padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center; } +.displayCard{grid-column:span 2} +.displayHero{ + margin-top:16px;padding:16px 18px;border-radius:16px;border:1px solid var(--line); + display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap; +} +.displayHero.is-connected{background:rgba(14,122,83,.08)} +.displayHero.is-empty{background:#f7f8f7} +.displayHeroLabel{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:6px} +.displayHeroText{font-size:20px;font-weight:700} +.displayHeroMeta{display:flex;gap:10px;flex-wrap:wrap;color:var(--muted);font-size:13px} +.connectorList{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px} +.connectorCard{border:1px solid var(--line);border-radius:14px;padding:14px;background:#fbfcfb} +.connectorHead{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:12px} +.connectorState{font-size:12px;font-weight:700;border-radius:999px;padding:6px 10px} +.connectorState.is-connected{background:rgba(14,122,83,.10);color:var(--accent)} +.connectorState.is-idle{background:rgba(154,106,0,.10);color:var(--warn)} +.connectorMeta{margin-top:0} +.emptyInline{color:var(--muted);font-size:14px} @media (max-width:720px){ .summary{grid-template-columns:1fr} .meta{grid-template-columns:1fr 1fr} - .brand{align-items:flex-start} + .brand{align-items:center} + .brandLogo{width:58px;height:58px} + .displayCard{grid-column:auto} + .displayHeroText{font-size:18px} } diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index 891d535..12063c1 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -6,7 +6,8 @@ cards: document.getElementById("cards"), lastUpdate: document.getElementById("lastUpdate"), providerCount: document.getElementById("providerCount"), - serviceCount: document.getElementById("serviceCount") + serviceCount: document.getElementById("serviceCount"), + deviceName: document.getElementById("deviceName") }; function esc(value) { @@ -23,16 +24,115 @@ return `${esc(label)}: ${value ? "yes" : "no"}`; } + function textValue(value, fallback = "Not available") { + const text = (value ?? "").toString().trim(); + return text || fallback; + } + function statusTone(card) { if (card.errors && card.errors.length) return "error"; if (card.active) return "ok"; return "warn"; } - function renderCard(card) { + function renderKeyValueRows(items) { + return items.map((item) => ` +
${esc(item.label || "-")}
+
${esc(textValue(item.value))}
+ `).join(""); + } + + function renderConnector(connector) { + const statusText = connector.connected + ? `Connected by ${textValue(connector.interface, connector.connector || "display")}` + : textValue(connector.status, "Unknown"); + + const rows = [ + { label: "Interface", value: connector.interface }, + { label: "Connector", value: connector.connector }, + { label: "Status", value: statusText }, + { label: "Monitor", value: connector.monitor_name }, + { label: "Manufacturer", value: connector.manufacturer }, + { label: "Current resolution", value: connector.current_resolution }, + { label: "Refresh rate", value: connector.refresh_rate }, + { label: "Preferred mode", value: connector.preferred_mode }, + { label: "Physical size", value: connector.physical_size }, + { label: "Diagonal", value: connector.diagonal } + ]; + + return ` +
+
+ ${esc(textValue(connector.connector, "Connector"))} + ${esc(statusText)} +
+
${renderKeyValueRows(rows)}
+
+ `; + } + + function renderDisplayCard(card) { const tone = statusTone(card); const warnings = Array.isArray(card.warnings) ? card.warnings : []; const errors = Array.isArray(card.errors) ? card.errors : []; + const details = Array.isArray(card.details) ? card.details : []; + const connectors = Array.isArray(card.connectors) ? card.connectors : []; + const connectedCount = connectors.filter((item) => item && item.connected).length; + const status = card.display_status || {}; + + return ` +
+
+
+

${esc(card.title)}

+
${esc(card.status_text || card.state || "Unknown")}
+
+
+ +
+
+
Display status
+
${esc(card.status_text || "Monitor is not connected")}
+
+
+ ${esc(`Connected connectors: ${connectedCount}`)} + ${esc(`Primary: ${textValue(status.connector, "Not available")}`)} +
+
+ +
${renderKeyValueRows(details)}
+ +
+
Connectors
+ ${connectors.length + ? `
${connectors.map(renderConnector).join("")}
` + : `
No DRM connectors detected.
`} +
+ + ${warnings.length ? ` +
+
Warnings
+ +
+ ` : ""} + + ${errors.length ? ` +
+
Errors
+ +
+ ` : ""} +
+ `; + } + + function renderCard(card) { + if (card.id === "display") return renderDisplayCard(card); + + const tone = statusTone(card); + const warnings = Array.isArray(card.warnings) ? card.warnings : []; + const errors = Array.isArray(card.errors) ? card.errors : []; + const details = Array.isArray(card.details) ? card.details : []; return `
@@ -49,6 +149,13 @@
Status
${esc(card.status_text || "-")}
+ ${details.length ? ` +
+
Details
+
${renderKeyValueRows(details)}
+
+ ` : ""} +
Flags
@@ -80,6 +187,7 @@ const providers = Array.isArray(payload.providers) ? payload.providers : []; nodes.lastUpdate.textContent = payload.generated_at || "-"; + nodes.deviceName.textContent = `host: ${payload.hostname || "-"}`; nodes.providerCount.textContent = String(providers.length); nodes.serviceCount.textContent = String(services.length); diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 6698b92..ac8a1b4 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -12,9 +12,10 @@
-
+
IOMATEX

Console

+

host: -

Lightweight diagnostics for installed services.

diff --git a/stage_ui/console_core/providers/00_core_services.py b/stage_ui/console_core/providers/00_core_services.py index d665cb7..8f540d6 100644 --- a/stage_ui/console_core/providers/00_core_services.py +++ b/stage_ui/console_core/providers/00_core_services.py @@ -1,5 +1,18 @@ -def _service_card(service_id, title, unit_name, installed, configured, active, state, status_text, errors=None, warnings=None): - return { +import math +import os +import re + + +DRM_ROOT = "/sys/class/drm" +REVERSE_TUNNEL_SERVICES = ( + {"name": "cockpit", "unit": "iomatex-rt-cockpit.service", "local_port": 9090}, + {"name": "z2m", "unit": "iomatex-rt-z2m.service", "local_port": 8081}, + {"name": "webui", "unit": "iomatex-rt-webui.service", "local_port": 8099}, +) + + +def _service_card(service_id, title, unit_name, installed, configured, active, state, status_text, errors=None, warnings=None, **extra): + card = { "id": service_id, "title": title, "installed": installed, @@ -10,6 +23,8 @@ def _service_card(service_id, title, unit_name, installed, configured, active, s "errors": errors or [], "warnings": warnings or [], } + card.update(extra) + return card def _short_unit_errors(unit): @@ -41,6 +56,310 @@ def _strict_active(installed, configured, unit): return bool(installed and configured and unit["active"]) +def _fallback(value, default="Not available"): + text = str(value or "").strip() + return text if text else default + + +def _read_trimmed(ctx, path): + return ctx["read_text"](path).strip() + + +def _clean_ascii(blob): + return (blob or b"").decode("ascii", errors="ignore").replace("\x00", "").replace("\r", "").replace("\n", "").strip() + + +def _parse_manufacturer_id(b1, b2): + word = ((b1 << 8) | b2) & 0xFFFF + letters = [ + chr(((word >> 10) & 0x1F) + 64), + chr(((word >> 5) & 0x1F) + 64), + chr((word & 0x1F) + 64), + ] + value = "".join(letters).replace("@", "") + return value if len(value) == 3 and value.isalpha() else "" + + +def _parse_detailed_timing(block): + if len(block) < 18: + return {} + pixel_clock_khz = ((block[1] << 8) | block[0]) * 10 + if pixel_clock_khz <= 0: + return {} + + h_active = block[2] | ((block[4] & 0xF0) << 4) + h_blanking = block[3] | ((block[4] & 0x0F) << 8) + v_active = block[5] | ((block[7] & 0xF0) << 4) + v_blanking = block[6] | ((block[7] & 0x0F) << 8) + total_pixels = (h_active + h_blanking) * (v_active + v_blanking) + refresh_hz = "" + if total_pixels > 0: + refresh_hz = f"{round((pixel_clock_khz * 1000) / total_pixels, 2):g} Hz" + return { + "resolution": f"{h_active} x {v_active}" if h_active and v_active else "", + "refresh_rate": refresh_hz, + } + + +def _parse_edid(edid): + if len(edid) < 128: + return { + "present": False, + "monitor_name": "", + "serial_text": "", + "manufacturer": "", + "product_code": "", + "size_cm": "", + "diagonal": "", + "preferred_resolution": "", + "preferred_refresh_rate": "", + "raw_length": len(edid), + } + + monitor_name = "" + serial_text = "" + preferred_resolution = "" + preferred_refresh_rate = "" + + for offset in range(54, min(len(edid), 126), 18): + block = edid[offset:offset + 18] + if len(block) < 18: + continue + if block[:4] == b"\x00\x00\x00\xfc": + monitor_name = _clean_ascii(block[5:18]) + continue + if block[:4] == b"\x00\x00\x00\xff": + serial_text = _clean_ascii(block[5:18]) + continue + if not preferred_resolution: + timing = _parse_detailed_timing(block) + preferred_resolution = timing.get("resolution", "") + preferred_refresh_rate = timing.get("refresh_rate", "") + + manufacturer = _parse_manufacturer_id(edid[8], edid[9]) + product_code = f"0x{edid[11]:02X}{edid[10]:02X}" + width_cm = edid[21] or 0 + height_cm = edid[22] or 0 + + diagonal = "" + if width_cm and height_cm: + diagonal_cm = math.sqrt((width_cm * width_cm) + (height_cm * height_cm)) + diagonal = f"{(diagonal_cm / 2.54):.1f}\"" + + return { + "present": True, + "monitor_name": monitor_name, + "serial_text": serial_text, + "manufacturer": manufacturer, + "product_code": product_code, + "size_cm": f"{width_cm} x {height_cm} cm" if width_cm and height_cm else "", + "diagonal": diagonal, + "preferred_resolution": preferred_resolution, + "preferred_refresh_rate": preferred_refresh_rate, + "raw_length": len(edid), + } + + +def _connector_interface(name): + upper = (name or "").upper() + if "HDMI" in upper: + return "HDMI" + if "DP-" in upper or upper.startswith("DP") or "DISPLAYPORT" in upper: + return "DP" + if "EDP" in upper: + return "eDP" + if "LVDS" in upper: + return "LVDS" + if "DSI" in upper: + return "DSI" + if "VGA" in upper: + return "VGA" + if "DVI" in upper: + return "DVI" + return "Other" + + +def _connector_priority(connector): + interface = connector.get("interface") + connected = 1 if connector.get("connected") else 0 + preferred = { + "HDMI": 6, + "DP": 5, + "eDP": 4, + "LVDS": 3, + "DSI": 2, + }.get(interface, 1) + mode_bonus = 1 if connector.get("current_resolution") else 0 + return (connected, preferred, mode_bonus, connector.get("connector", "")) + + +def _read_modes(ctx, connector_dir): + raw = _read_trimmed(ctx, os.path.join(connector_dir, "modes")) + if not raw: + return [] + return [line.strip() for line in raw.splitlines() if line.strip()] + + +def _read_connector(ctx, connector_dir): + connector = os.path.basename(connector_dir) + interface = _connector_interface(connector) + status = _read_trimmed(ctx, os.path.join(connector_dir, "status")) or "unknown" + enabled = _read_trimmed(ctx, os.path.join(connector_dir, "enabled")) + dpms = _read_trimmed(ctx, os.path.join(connector_dir, "dpms")) + modes = _read_modes(ctx, connector_dir) + current_mode = _read_trimmed(ctx, os.path.join(connector_dir, "mode")) + edid = _parse_edid(ctx["read_bytes"](os.path.join(connector_dir, "edid"))) + + current_resolution = current_mode or (modes[0] if modes else "") or edid["preferred_resolution"] + refresh_rate = edid["preferred_refresh_rate"] + preferred_mode = "" + if edid["preferred_resolution"] and edid["preferred_refresh_rate"]: + preferred_mode = f"{edid['preferred_resolution']} @ {edid['preferred_refresh_rate']}" + elif edid["preferred_resolution"]: + preferred_mode = edid["preferred_resolution"] + elif modes: + preferred_mode = modes[0] + + monitor_name = edid["monitor_name"] or connector + return { + "connector": connector, + "interface": interface, + "status": status, + "enabled": enabled, + "dpms": dpms, + "connected": status == "connected", + "modes": modes, + "current_resolution": current_resolution, + "refresh_rate": refresh_rate, + "preferred_mode": preferred_mode, + "monitor_name": monitor_name, + "manufacturer": edid["manufacturer"], + "product_code": edid["product_code"], + "serial": edid["serial_text"], + "physical_size": edid["size_cm"], + "diagonal": edid["diagonal"], + "edid_present": edid["present"], + "edid_raw_length": edid["raw_length"], + } + + +def _list_connector_dirs(ctx): + if not ctx["file_exists"](DRM_ROOT): + return [] + try: + entries = sorted(os.listdir(DRM_ROOT)) + except Exception: + return [] + result = [] + for entry in entries: + connector_dir = os.path.join(DRM_ROOT, entry) + if ctx["file_exists"](os.path.join(connector_dir, "status")): + result.append(connector_dir) + return result + + +def _display_details(primary): + primary = primary or {} + return [ + {"label": "Interface", "value": _fallback(primary.get("interface"))}, + {"label": "Monitor", "value": _fallback(primary.get("monitor_name"))}, + {"label": "Manufacturer", "value": _fallback(primary.get("manufacturer"))}, + {"label": "Current resolution", "value": _fallback(primary.get("current_resolution"))}, + {"label": "Refresh rate", "value": _fallback(primary.get("refresh_rate"))}, + {"label": "Preferred mode", "value": _fallback(primary.get("preferred_mode"))}, + {"label": "Physical size", "value": _fallback(primary.get("physical_size"))}, + {"label": "Diagonal", "value": _fallback(primary.get("diagonal"))}, + {"label": "Serial", "value": _fallback(primary.get("serial"))}, + {"label": "Product code", "value": _fallback(primary.get("product_code"))}, + ] + + +def _z2m_parse_config(ctx): + config_path = "/opt/zigbee2mqtt/data/configuration.yaml" + raw = ctx["read_text"](config_path) + port = "" + adapter = "" + if raw: + port_match = re.search(r'^\s*port:\s*["\']?([^"\'\n#]+)["\']?\s*$', raw, re.MULTILINE) + if port_match: + port = port_match.group(1).strip() + adapter_match = re.search(r'^\s*adapter:\s*["\']?([^"\'\n#]+)["\']?\s*$', raw, re.MULTILINE) + if adapter_match: + adapter = adapter_match.group(1).strip() + return { + "config_path": config_path, + "raw": raw, + "exists": bool(raw), + "port": port, + "adapter": adapter, + } + + +def _z2m_usb_diagnostics(ctx): + config = _z2m_parse_config(ctx) + port = config["port"] + adapter = config["adapter"] + port_exists = False + resolved_port = "" + network_port = "://" in port or port.startswith("tcp:") or port.startswith("socket:") + + if port and not network_port: + port_exists = ctx["file_exists"](port) + if port_exists: + try: + resolved_port = os.path.realpath(port) + except Exception: + resolved_port = port + + by_id_entries = [] + by_id_path = "/dev/serial/by-id" + if os.path.isdir(by_id_path): + try: + by_id_entries = sorted(os.listdir(by_id_path)) + except Exception: + by_id_entries = [] + + likely_by_id = [ + entry for entry in by_id_entries + if re.search(r"(zigbee|sonoff|cc2652|ember|ezsp|zbdongle|nabu|slae|thirdreality|tubeszb)", entry, re.IGNORECASE) + ] + + rc, lsusb_out, _ = ctx["run"](["/usr/bin/lsusb"], timeout=8) + usb_lines = [line.strip() for line in lsusb_out.splitlines() if line.strip()] if rc == 0 else [] + likely_usb = [ + line for line in usb_lines + if re.search(r"(zigbee|sonoff|cc2652|ezsp|ember|nabu|slae|silicon labs|texas instruments|tubeszb|dongle)", line, re.IGNORECASE) + ] + + coordinator_present = False + reason = "" + if not config["exists"]: + reason = "configuration.yaml missing" + elif not port: + reason = "Coordinator not set in USB" + elif network_port: + coordinator_present = True + elif port_exists: + coordinator_present = True + else: + reason = "USB coordinator not found" + + configured = bool(config["exists"] and port and (network_port or port_exists)) + return { + "configured": configured, + "reason": reason, + "config_exists": config["exists"], + "config_path": config["config_path"], + "configured_port": port, + "configured_port_exists": port_exists, + "configured_port_resolved": resolved_port, + "adapter": adapter, + "coordinator_present": coordinator_present, + "likely_by_id_count": len(likely_by_id), + "likely_usb_count": len(likely_usb), + } + + def itscreen_card(ctx): unit = ctx["systemd_unit"]("itscreen-x11.service") installed = ctx["any_exists"]([ @@ -144,12 +463,30 @@ def zigbee_card(ctx): "/lib/systemd/system/zigbee2mqtt.service", ]) installed = bool(app_footprint or unit_footprint or unit["installed"]) - configured = installed and ctx["file_exists"]("/opt/zigbee2mqtt/data/configuration.yaml") - active = _strict_active(installed, configured, unit) + usb = _z2m_usb_diagnostics(ctx) + configured = bool(installed and usb["configured"]) + active = bool(installed and configured and unit["active"]) warnings = [] - if installed and not configured: - warnings.append("configuration.yaml missing") - state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed") + errors = _short_unit_errors(unit) + + if not installed: + state = "not installed" + status_text = "Not installed" + warnings.append("Service Zigbee2MQTT not installed") + elif not configured: + state = "installed_not_configured" + status_text = "Not configured" + warnings.append(usb["reason"] or "Coordinator not set in USB") + elif unit["active_state"] == "failed": + state = "failed" + status_text = "Failed" + elif active: + state = "active" + status_text = "Active" + else: + state = "inactive" + status_text = "Inactive" + return _service_card( "zigbee2mqtt", "Zigbee2MQTT", @@ -159,8 +496,181 @@ def zigbee_card(ctx): active, state, status_text, - _short_unit_errors(unit), - warnings, + errors, + warnings[:2], + details=[ + {"label": "Coordinator", "value": usb["reason"] if not configured else "USB coordinator detected"}, + {"label": "USB port", "value": usb["configured_port"] or "Not set"}, + {"label": "Resolved device", "value": usb["configured_port_resolved"] or "Not available"}, + {"label": "Adapter", "value": usb["adapter"] or "Auto"}, + ], + ) + + +def _reverse_tunnel_unit_names(): + return [item["unit"] for item in REVERSE_TUNNEL_SERVICES] + + +def _reverse_tunnel_key_paths(ctx): + hostname = _read_trimmed(ctx, "/etc/hostname").split(".", 1)[0] + edge_user = "iomatex" + edge_home = "" + rc, stdout, _ = ctx["run"](["getent", "passwd", edge_user]) + if rc == 0 and stdout: + parts = stdout.split(":") + if len(parts) >= 6: + edge_home = parts[5].strip() + + homes = [] + for item in [edge_home, f"/home/{edge_user}", f"/var/lib/{edge_user}"]: + item = str(item or "").strip() + if item and item not in homes: + homes.append(item) + + paths = [] + for home in homes: + ssh_dir = os.path.join(home, ".ssh") + if hostname: + paths.extend([ + os.path.join(ssh_dir, f"iomatex-{hostname}"), + os.path.join(ssh_dir, f"iomatex-{hostname}.pub"), + ]) + paths.extend([ + os.path.join(ssh_dir, "id_ed25519"), + os.path.join(ssh_dir, "id_ed25519.pub"), + ]) + return paths + + +def reverse_tunnel_card(ctx): + service_states = [] + installed_checks = [] + configured_checks = [] + warnings = [] + errors = [] + + key_paths = _reverse_tunnel_key_paths(ctx) + key_present = any(ctx["file_exists"](path) for path in key_paths) + + for item in REVERSE_TUNNEL_SERVICES: + unit = ctx["systemd_unit"](item["unit"]) + unit_path = unit.get("fragment_path", "").strip() + script_path = f"/usr/local/sbin/iomatex-rt-{item['name']}.sh" + unit_file_candidates = [ + unit_path, + f"/etc/systemd/system/{item['unit']}", + f"/lib/systemd/system/{item['unit']}", + ] + has_unit = any(path and ctx["file_exists"](path) for path in unit_file_candidates) or unit["installed"] + has_script = ctx["file_exists"](script_path) + is_active = unit["active"] + + installed_checks.append(has_unit or has_script) + configured_checks.append(has_script and key_present) + service_states.append({ + "name": item["name"], + "unit": item["unit"], + "local_port": item["local_port"], + "installed": has_unit or has_script, + "configured": has_script and key_present, + "active": is_active, + "active_state": unit["active_state"], + }) + + if has_unit and has_script and not is_active: + warnings.append(f"{item['name']} tunnel inactive") + if unit["active_state"] == "failed": + errors.append(f"{item['name']} tunnel failed") + + installed = any(installed_checks) + configured = all(configured_checks) if installed else False + active_count = sum(1 for item in service_states if item["active"]) + total = len(service_states) + active = active_count == total and total > 0 + + if not installed: + state = "not installed" + status_text = "Not installed" + elif active: + state = "active" + status_text = "Active" + elif active_count > 0: + state = "degraded" + status_text = f"Partial ({active_count}/{total})" + elif configured: + state = "inactive" + status_text = "Inactive" + else: + state = "installed_not_configured" + status_text = "Not configured" + + if installed and not key_present: + warnings.append("Reverse tunnel SSH key not found") + + warnings.extend( + f"{item['name']} -> 127.0.0.1:{item['local_port']}" + for item in service_states + if item["installed"] and not item["active"] + ) + + return _service_card( + "reverse_tunnel", + "Reverse Tunnel", + ",".join(_reverse_tunnel_unit_names()), + installed, + configured, + active, + state, + status_text, + errors[:2], + warnings[:3], + ) + + +def display_card(ctx): + connector_dirs = _list_connector_dirs(ctx) + connectors = [_read_connector(ctx, path) for path in connector_dirs] + connected = [item for item in connectors if item["connected"]] + connected.sort(key=_connector_priority, reverse=True) + primary = connected[0] if connected else {} + + drm_available = bool(ctx["file_exists"](DRM_ROOT)) + active = bool(primary) + interface = primary.get("interface", "") + connector_name = primary.get("connector", "") + if active: + status_text = f"Monitor connected by {interface or connector_name or 'display'}" + state = "active" + else: + status_text = "Monitor is not connected" + state = "inactive" if drm_available else "unavailable" + + warnings = [] + if not drm_available: + warnings.append("DRM sysfs is not available") + elif connectors and not active: + warnings.append("No active DRM connector detected") + + return _service_card( + "display", + "Display", + "", + True, + drm_available, + active, + state, + status_text, + [], + warnings[:2], + details=_display_details(primary), + connectors=connectors, + display_status={ + "connected": active, + "interface": interface, + "connector": connector_name, + "monitor_name": primary.get("monitor_name", ""), + "manufacturer": primary.get("manufacturer", ""), + }, ) @@ -186,7 +696,7 @@ def get_cards(ctx): mosquitto_card(ctx), mqtt_bridge_card(ctx), zigbee_card(ctx), - placeholder_card("reverse_tunnel", "Reverse Tunnel"), - placeholder_card("display", "Display"), + reverse_tunnel_card(ctx), + display_card(ctx), 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 index cf2c3f9..8838899 100644 Binary files a/stage_ui/console_core/providers/__pycache__/00_core_services.cpython-312.pyc and b/stage_ui/console_core/providers/__pycache__/00_core_services.cpython-312.pyc differ diff --git a/stage_ui/ui_installer.sh b/stage_ui/ui_installer.sh old mode 100755 new mode 100644 index e3471eb..bc82557 --- a/stage_ui/ui_installer.sh +++ b/stage_ui/ui_installer.sh @@ -1,13 +1,6 @@ #!/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 @@ -17,1812 +10,103 @@ if grep -q $'\r' "$0" 2>/dev/null; then exit 1 fi -need_root(){ [ "$(id -u)" -eq 0 ] || { echo "Run as root: sudo bash $0"; exit 1; }; } +need_root() { + [ "$(id -u)" -eq 0 ] || { + echo "Run as root: sudo bash $0" >&2 + 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_ROOT="${SCRIPT_DIR}/console_core" +APP_DIR="/opt/iomatex-console" +PUBLIC_DIR="${APP_DIR}/public" +BACKEND_DIR="${APP_DIR}/backend" +PROVIDERS_DIR="${APP_DIR}/providers.d" +SERVICE_NAME="iomatex-console.service" +LEGACY_SERVICE_NAME="iomatex-webipc.service" +CFG_PATH="/etc/iomatex/console.json" SRC_LOGO="${LOGO_SOURCE:-$SCRIPT_DIR/iomatex_logo_source.png}" - -echo "[0/10] Cleanup previous install artifacts (safe, keep config)" +APP_BIND="${CONSOLE_BIND:-0.0.0.0}" +APP_PORT="${CONSOLE_PORT:-8099}" 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 +PREV_DIR="${APP_DIR}.prev.${ts}" +LEGACY_APP_DIR="/opt/iomatex-process1-webipc" +LEGACY_PREV_DIR="${LEGACY_APP_DIR}.prev.${ts}" -if [ -d "$APP_DIR" ]; then - mv -f "$APP_DIR" "${APP_DIR}.prev.${ts}" || rm -rf "$APP_DIR" -fi +copy_tree() { + local src="$1" + local dst="$2" + mkdir -p "$dst" + cp -a "${src}/." "$dst/" +} -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 +echo "[0/8] Validate source tree" +for path in \ + "$SRC_ROOT/backend/app.py" \ + "$SRC_ROOT/frontend/index.html" \ + "$SRC_ROOT/frontend/console.js" \ + "$SRC_ROOT/frontend/console.css" \ + "$SRC_ROOT/providers/00_core_services.py"; do + [ -f "$path" ] || { + echo "ERROR: required source file is missing: $path" >&2 + exit 1 + } +done + +echo "[1/8] Ensure runtime packages exist" apt-get update apt-get install -y python3 python3-pil -node -v -npm -v +python3 --version + +echo "[2/8] Stop previous service" +systemctl stop "${SERVICE_NAME}" 2>/dev/null || true +systemctl disable "${SERVICE_NAME}" 2>/dev/null || true +systemctl reset-failed "${SERVICE_NAME}" 2>/dev/null || true +systemctl stop "${LEGACY_SERVICE_NAME}" 2>/dev/null || true +systemctl disable "${LEGACY_SERVICE_NAME}" 2>/dev/null || true +systemctl reset-failed "${LEGACY_SERVICE_NAME}" 2>/dev/null || true + +echo "[3/8] Prepare directories and preserve previous install" +mkdir -p /etc/iomatex +if [ -d "$APP_DIR" ]; then + rm -rf "$PREV_DIR" + mv "$APP_DIR" "$PREV_DIR" +fi +if [ -d "$LEGACY_APP_DIR" ]; then + rm -rf "$LEGACY_PREV_DIR" + mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR" +fi +mkdir -p "$APP_DIR" "$PUBLIC_DIR" "$BACKEND_DIR" "$PROVIDERS_DIR" -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' + cat > "$CFG_PATH" < "$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" +echo "[4/8] Install console core files" +copy_tree "$SRC_ROOT/backend" "$BACKEND_DIR" +install -m 0644 "$SRC_ROOT/frontend/index.html" "$PUBLIC_DIR/index.html" +install -m 0644 "$SRC_ROOT/frontend/console.js" "$PUBLIC_DIR/console.js" +install -m 0644 "$SRC_ROOT/frontend/console.css" "$PUBLIC_DIR/console.css" +copy_tree "$SRC_ROOT/providers" "$PROVIDERS_DIR" +rm -rf "$PROVIDERS_DIR/__pycache__" "$BACKEND_DIR/__pycache__" + +echo "[5/8] Generate logo and favicon" 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' +python3 - "$SRC_LOGO" "$PUBLIC_DIR/logo.png" "$PUBLIC_DIR/favicon.png" <<'PY' import sys from PIL import Image @@ -1831,61 +115,27 @@ 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" +echo "[6/8] 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 "Status API: curl -s http://127.0.0.1:${APP_PORT}/api/status | cat" +echo "Display API: curl -s http://127.0.0.1:${APP_PORT}/api/display | 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 +echo "Install dir: ${APP_DIR}" +echo "Providers dir: ${PROVIDERS_DIR}" +echo "Public dir: ${PUBLIC_DIR}" +echo "Config: ${CFG_PATH}" +echo "Previous install backup: ${PREV_DIR}" +echo "Legacy backup: ${LEGACY_PREV_DIR}"