From 074ed3f201ef10cbe8cb5737a317cb5286139780 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Sun, 15 Mar 2026 07:38:01 +0400 Subject: [PATCH] Update UI installer --- stage_ui/ui_installer.sh | 1938 ++------------------------------------ 1 file changed, 69 insertions(+), 1869 deletions(-) mode change 100755 => 100644 stage_ui/ui_installer.sh diff --git a/stage_ui/ui_installer.sh b/stage_ui/ui_installer.sh old mode 100755 new mode 100644 index e3471eb..a43b176 --- 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,1894 +10,101 @@ 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"; exit 1; } +} + +log() { + echo "[ui] $*" +} + +write_managed_file() { + local src="$1" + local dst="$2" + local mode="$3" + install -D -m "$mode" "$src" "$dst" +} + 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}" +CORE_DIR="${SCRIPT_DIR}/console_core" -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 +APP_DIR="/opt/iomatex-console" +BACKEND_DIR="${APP_DIR}/backend" +PUBLIC_DIR="${APP_DIR}/public" +PROVIDERS_DIR="${APP_DIR}/providers.d" +SYSTEMD_UNIT="/etc/systemd/system/iomatex-console.service" +CONFIG_DIR="/etc/iomatex" +CONFIG_PATH="${CONFIG_DIR}/console.json" +SERVICE_NAME="iomatex-console.service" -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 +log "Install lightweight Console core dependencies" apt-get update -apt-get install -y python3 python3-pil -node -v -npm -v +apt-get install -y python3 -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' +log "Prepare directories" +mkdir -p "$BACKEND_DIR" "$PUBLIC_DIR" "$PROVIDERS_DIR" "$CONFIG_DIR" + +log "Install Console core files" +write_managed_file "${CORE_DIR}/backend/app.py" "${BACKEND_DIR}/app.py" 0755 +write_managed_file "${CORE_DIR}/providers/00_core_services.py" "${PROVIDERS_DIR}/00_core_services.py" 0644 +write_managed_file "${CORE_DIR}/frontend/index.html" "${PUBLIC_DIR}/index.html" 0644 +write_managed_file "${CORE_DIR}/frontend/console.css" "${PUBLIC_DIR}/console.css" 0644 +write_managed_file "${CORE_DIR}/frontend/console.js" "${PUBLIC_DIR}/console.js" 0644 +write_managed_file "${CORE_DIR}/ARCHITECTURE.md" "${APP_DIR}/ARCHITECTURE.md" 0644 +write_managed_file "${SCRIPT_DIR}/iomatex_logo_source.png" "${PUBLIC_DIR}/logo.png" 0644 +write_managed_file "${SCRIPT_DIR}/iomatex_logo_source.png" "${PUBLIC_DIR}/favicon.png" 0644 + +if [ ! -f "$CONFIG_PATH" ]; then + log "Write default config" + cat >"$CONFIG_PATH" <<'JSON' { - "server": "", - "deviceId": "", - "token": "", - "clientId": "", - "registeredAt": "" + "bind": "0.0.0.0", + "port": 8099, + "cache_ttl_sec": 3 } JSON + chmod 0644 "$CONFIG_PATH" 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}" <"$SYSTEMD_UNIT" <<'EOF' [Unit] -Description=IOMATEX WebIPC Engineer Console (light core) +Description=IOMATEX Console After=network-online.target Wants=network-online.target [Service] Type=simple -WorkingDirectory=${APP_DIR} -ExecStart=/usr/bin/node ${APP_DIR}/server.js +ExecStart=/usr/bin/python3 /opt/iomatex-console/backend/app.py Restart=always RestartSec=2 -Environment=WEBIPC_BIND=${APP_BIND} -Environment=WEBIPC_PORT=${APP_PORT} -Environment=WEBIPC_CONFIG=${CFG_PATH} -Environment=WEBIPC_MQTT_URL=${MQTT_URL_DEFAULT} -Environment=WEBIPC_MQTT_REPLY_MS=${MQTT_REPLY_MS_DEFAULT} -Environment=WEBIPC_MQTT_NS=${MQTT_NS_DEFAULT} -Environment=WEBIPC_LOGIN_PASSWORD=${LOGIN_PASSWORD_DEFAULT} -User=root -Group=root [Install] WantedBy=multi-user.target -UNIT +EOF +chmod 0644 "$SYSTEMD_UNIT" +log "Reload and restart Console service" systemctl daemon-reload -node --check "${APP_DIR}/server.js" -systemctl enable --now "${SERVICE_NAME}" +systemctl enable "$SERVICE_NAME" >/dev/null 2>&1 || true +if systemctl is-active --quiet "$SERVICE_NAME"; then + systemctl restart "$SERVICE_NAME" +else + systemctl start "$SERVICE_NAME" +fi -echo "[10/10] Done" -echo "Web UI: http://:${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 +cat <