diff --git a/stage_ui/console_core/ARCHITECTURE.md b/stage_ui/console_core/ARCHITECTURE.md index 435dd79..942bdb9 100644 --- a/stage_ui/console_core/ARCHITECTURE.md +++ b/stage_ui/console_core/ARCHITECTURE.md @@ -4,6 +4,7 @@ - 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`. +- Expose focused operational endpoints for top-level tabs, for example `/api/health/summary`, `/api/network/summary`, `/api/network/scan`. - Load provider modules from `providers.d`. - Cache recent status briefly to avoid repeated shell work on every page render. @@ -17,3 +18,4 @@ - Keep this Console focused on lightweight diagnostics. - Future `ui_backend` can own richer workflows: actions, forms, provisioning, and service-specific control paths. - The normalized card contract can remain stable while richer backend features evolve separately. +- When a workflow already exists as a proven edge shell helper, backend should call that helper rather than rewrite the behavior in frontend. diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index b4a4e9f..bbd7f29 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -4,6 +4,7 @@ import hashlib import importlib.util import json import os +import shutil import re import subprocess import sys @@ -19,16 +20,21 @@ CONFIG_PATH = "/etc/iomatex/console.json" DEFAULT_CONFIG = { "bind": "0.0.0.0", - "port": 8099, + "port": 80, "cache_ttl_sec": 3, } _CACHE = {"expires_at": 0.0, "payload": None} +_CPU_SAMPLE = {"total": None, "idle": None} +_NET_SAMPLE = {} AP_ENV_PATH = "/etc/iomatex/ap.env" +WIFI_ENV_PATH = "/etc/iomatex/wifi.env" AP_SYNC_SCRIPT = "/usr/local/sbin/iomatex-ap-sync-config" AP_RESET_SCRIPT = "/usr/local/sbin/iomatex-ap-reset-password" AP_UP_SCRIPT = "/usr/local/sbin/iomatex-ap-up" AP_DOWN_SCRIPT = "/usr/local/sbin/iomatex-ap-down" +WIFI_STATUS_SCRIPT = "/usr/local/sbin/iomatex-wifi-status" +WIFI_SETUP_SCRIPT = "/usr/local/sbin/iomatex-wifi-setup" AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$") @@ -260,6 +266,402 @@ def invalidate_cache(): _CACHE["expires_at"] = 0.0 +def parse_key_value_lines(text): + data = {} + for raw in str(text or "").splitlines(): + line = raw.strip() + if not line or "=" not in line: + continue + key, value = line.split("=", 1) + data[key.strip()] = value.strip() + return data + + +def get_edge_id(): + return get_device_serial() or get_system_hostname() or "unknown" + + +def load_os_release(): + data = {} + for raw in read_text("/etc/os-release").splitlines(): + line = raw.strip() + if not line or "=" not in line: + continue + key, value = line.split("=", 1) + data[key.strip()] = value.strip().strip('"').strip("'") + return data + + +def get_os_label(): + info = load_os_release() + version = info.get("VERSION_ID", "").strip() + if version: + return f"IOMATEX Edge OS · v{version}" + pretty = info.get("PRETTY_NAME", "").strip() + if pretty: + return pretty + return "IOMATEX Edge OS" + + +def get_identity_payload(): + hostname = get_system_hostname() or os.uname().nodename + return { + "hostname": hostname, + "edge_id": get_edge_id(), + "os_label": get_os_label(), + } + + +def _read_cpu_snapshot(): + raw = read_text("/proc/stat") + for line in raw.splitlines(): + if line.startswith("cpu "): + parts = [int(part) for part in line.split()[1:] if part.isdigit()] + if len(parts) < 4: + break + idle = parts[3] + (parts[4] if len(parts) > 4 else 0) + total = sum(parts) + return total, idle + return None, None + + +def get_cpu_usage_percent(): + total, idle = _read_cpu_snapshot() + if total is None: + return None + previous_total = _CPU_SAMPLE["total"] + previous_idle = _CPU_SAMPLE["idle"] + _CPU_SAMPLE["total"] = total + _CPU_SAMPLE["idle"] = idle + if previous_total is None or previous_idle is None or total <= previous_total: + return None + total_delta = total - previous_total + idle_delta = idle - previous_idle + busy = total_delta - idle_delta + if total_delta <= 0: + return None + return round((busy / total_delta) * 100.0, 1) + + +def get_load_average(): + try: + values = os.getloadavg() + return [round(value, 2) for value in values] + except Exception: + return [] + + +def read_thermal_sensors(): + sensors = [] + base = "/sys/class/thermal" + if not os.path.isdir(base): + return sensors + try: + entries = sorted(name for name in os.listdir(base) if name.startswith("thermal_zone")) + except Exception: + return sensors + for entry in entries: + zone = os.path.join(base, entry) + name = read_text(os.path.join(zone, "type")).strip() or entry + raw_temp = read_text(os.path.join(zone, "temp")).strip() + if not raw_temp: + sensors.append({"name": name, "value_c": None, "label": "not available"}) + continue + try: + value = int(raw_temp) / 1000.0 + sensors.append({"name": name, "value_c": round(value, 1), "label": f"{value:.1f} C"}) + except Exception: + sensors.append({"name": name, "value_c": None, "label": "not available"}) + return sensors + + +def get_disk_usage(): + try: + usage = shutil.disk_usage("/") + except Exception: + return {} + total = usage.total + used = usage.used + free = usage.free + percent = round((used / total) * 100.0, 1) if total else 0.0 + return { + "total_bytes": total, + "used_bytes": used, + "free_bytes": free, + "used_percent": percent, + } + + +def get_health_summary(): + sensors = read_thermal_sensors() + disk = get_disk_usage() + cpu_usage = get_cpu_usage_percent() + return { + "ok": True, + "cpu_usage_percent": cpu_usage, + "load_average": get_load_average(), + "disk": disk, + "temperatures": sensors, + } + + +def nmcli_available(): + return bool(shutil.which("nmcli")) + + +def parse_wifi_status_script(): + if not file_exists(WIFI_STATUS_SCRIPT): + return {} + rc, stdout, _ = run([WIFI_STATUS_SCRIPT], timeout=8) + return parse_key_value_lines(stdout if rc == 0 else "") + + +def get_primary_interface(): + env = read_env_file(AP_ENV_PATH) + return str(env.get("IFACE", "wlan0")).strip() or "wlan0" + + +def nmcli_device_state(iface): + rc, stdout, _ = run(["nmcli", "-t", "-f", "DEVICE,STATE,CONNECTION", "dev"], timeout=8) + if rc != 0: + return {} + for raw in stdout.splitlines(): + parts = raw.split(":") + if len(parts) < 3 or parts[0] != iface: + continue + return { + "device": parts[0], + "state": parts[1], + "connection": ":".join(parts[2:]) or "", + } + return {} + + +def ip_addresses_for_iface(iface): + rc, stdout, _ = run(["ip", "-4", "-o", "addr", "show", "dev", iface], timeout=8) + ipv4 = [] + if rc == 0: + for raw in stdout.splitlines(): + parts = raw.split() + if len(parts) >= 4: + ipv4.append(parts[3]) + rc, stdout, _ = run(["ip", "-6", "-o", "addr", "show", "dev", iface], timeout=8) + ipv6 = [] + if rc == 0: + for raw in stdout.splitlines(): + parts = raw.split() + if len(parts) >= 4: + ipv6.append(parts[3]) + return {"ipv4": ipv4, "ipv6": ipv6} + + +def gateway_for_iface(iface): + rc, stdout, _ = run(["ip", "route", "show", "default", "dev", iface], timeout=8) + if rc != 0: + return "" + parts = stdout.split() + if "via" in parts: + index = parts.index("via") + if index + 1 < len(parts): + return parts[index + 1] + return "" + + +def dns_servers_for_iface(iface): + if nmcli_available(): + rc, stdout, _ = run(["nmcli", "-g", "IP4.DNS", "dev", "show", iface], timeout=8) + if rc == 0: + values = [line.strip() for line in stdout.splitlines() if line.strip()] + if values: + return values + dns = [] + for raw in read_text("/etc/resolv.conf").splitlines(): + line = raw.strip() + if line.startswith("nameserver "): + dns.append(line.split(None, 1)[1].strip()) + return dns + + +def get_active_ssid(iface): + if nmcli_available(): + rc, stdout, _ = run(["nmcli", "-g", "GENERAL.CONNECTION", "dev", "show", iface], timeout=8) + if rc == 0 and stdout.strip(): + return stdout.strip() + rc, stdout, _ = run(["iw", "dev", iface, "link"], timeout=8) + if rc == 0: + for line in stdout.splitlines(): + line = line.strip() + if line.startswith("SSID:"): + return line.split(":", 1)[1].strip() + return "" + + +def read_wifi_profile_state(): + env = read_env_file(WIFI_ENV_PATH) + return { + "profile": str(env.get("WIFI_PROFILE", "")).strip(), + "ssid": str(env.get("WIFI_SSID", "")).strip(), + "ip4": str(env.get("WIFI_IP4", "")).strip(), + } + + +def _read_netdev_bytes(iface): + raw = read_text("/proc/net/dev") + for line in raw.splitlines(): + if ":" not in line: + continue + name, rest = line.split(":", 1) + if name.strip() != iface: + continue + values = rest.split() + if len(values) >= 16: + return int(values[0]), int(values[8]) + return None, None + + +def get_network_activity(iface): + rx, tx = _read_netdev_bytes(iface) + now = time.time() + if rx is None or tx is None: + return {"rx_bytes_per_sec": None, "tx_bytes_per_sec": None} + sample = _NET_SAMPLE.get(iface) + _NET_SAMPLE[iface] = {"rx": rx, "tx": tx, "at": now} + if not sample: + return {"rx_bytes_per_sec": None, "tx_bytes_per_sec": None} + elapsed = max(now - sample["at"], 0.001) + return { + "rx_bytes_per_sec": round(max(rx - sample["rx"], 0) / elapsed, 1), + "tx_bytes_per_sec": round(max(tx - sample["tx"], 0) / elapsed, 1), + } + + +def get_network_summary(): + iface = get_primary_interface() + profile = read_wifi_profile_state() + script_status = parse_wifi_status_script() + nm_state = nmcli_device_state(iface) + addresses = ip_addresses_for_iface(iface) + gateway = gateway_for_iface(iface) + dns = dns_servers_for_iface(iface) + current_ssid = get_active_ssid(iface) + activity = get_network_activity(iface) + try: + ap_status = public_ap_status() + except Exception: + ap_status = { + "ok": False, + "ap_enabled": False, + "ssid": build_ap_ssid(), + "password_mode": "factory", + "iface": iface, + "service_state": "unknown", + } + return { + "ok": True, + "iface": iface, + "desired_profile": profile, + "ap_status": ap_status, + "wifi": { + "connected": nm_state.get("state") == "connected", + "state": nm_state.get("state") or script_status.get("NM_STATE", "unknown"), + "connection": nm_state.get("connection") or script_status.get("NM_CONNECTION", ""), + "ssid": current_ssid or profile["ssid"], + }, + "addresses": addresses, + "gateway": gateway, + "dns": dns, + "activity": activity, + "script_status": script_status, + } + + +def scan_wifi_networks(): + if not nmcli_available(): + return {"ok": False, "error": "nmcli not found", "networks": []} + iface = get_primary_interface() + rescan_rc, _, rescan_stderr = run(["nmcli", "device", "wifi", "rescan", "ifname", iface], timeout=18) + if rescan_rc != 0: + if "not authorized" in rescan_stderr.lower(): + rescan_warning = "Wi-Fi rescan requires elevated privileges. Showing cached results." + elif "not found" in rescan_stderr.lower() or "no such device" in rescan_stderr.lower(): + return {"ok": False, "error": "Wi-Fi device is missing", "networks": []} + else: + rescan_warning = rescan_stderr or "Wi-Fi rescan failed. Showing cached results." + else: + rescan_warning = "" + time.sleep(2.0) + rc, stdout, stderr = run( + ["nmcli", "-t", "-f", "IN-USE,SSID,SIGNAL,SECURITY", "device", "wifi", "list", "ifname", iface], + timeout=18, + ) + if rc != 0: + error_text = (stderr or "Failed to list Wi-Fi networks").strip() + lowered = error_text.lower() + if "not authorized" in lowered: + error_text = "Not authorized to read Wi-Fi scan results" + elif "not found" in lowered or "no such device" in lowered: + error_text = "Wi-Fi device is missing" + return {"ok": False, "error": error_text, "networks": []} + + def unescape_nmcli(value): + return value.replace("\\:", ":").replace("\\\\", "\\").strip() + + best_by_ssid = {} + hidden_index = 0 + for raw_line in stdout.splitlines(): + line = raw_line.strip() + if not line or ":" not in line: + continue + in_use_raw, remainder = line.split(":", 1) + tail = remainder.rsplit(":", 2) + if len(tail) != 3: + continue + ssid_raw, signal, security = tail + ssid = unescape_nmcli(ssid_raw) + hidden = not bool(ssid) + if hidden: + hidden_index += 1 + ssid = f"Hidden network {hidden_index}" + try: + signal_value = int(signal) + except Exception: + signal_value = None + current = { + "ssid": ssid, + "signal": signal_value, + "security": unescape_nmcli(security), + "in_use": in_use_raw.strip() == "*", + "hidden": hidden, + } + existing = best_by_ssid.get(ssid) + if existing is None: + best_by_ssid[ssid] = current + continue + existing_score = (1 if existing["in_use"] else 0, existing["signal"] if existing["signal"] is not None else -1) + current_score = (1 if current["in_use"] else 0, current["signal"] if current["signal"] is not None else -1) + if current_score > existing_score: + best_by_ssid[ssid] = current + networks = list(best_by_ssid.values()) + networks.sort(key=lambda item: (0 if item["in_use"] else 1, -(item["signal"] if item["signal"] is not None else -1), item["ssid"].lower())) + response = {"ok": True, "networks": networks} + if rescan_warning: + response["warning"] = rescan_warning + if not networks: + response["message"] = "No Wi-Fi networks found" + return response + + +def apply_wifi_profile(ssid, password): + if not ssid.strip(): + raise RuntimeError("SSID is required") + if file_exists(WIFI_SETUP_SCRIPT): + rc, stdout, stderr = run([WIFI_SETUP_SCRIPT, ssid, password], timeout=45) + if rc != 0: + raise RuntimeError(stderr or stdout or "Failed to apply Wi-Fi profile") + return {"message": stdout or "Wi-Fi profile applied"} + raise RuntimeError("iomatex-wifi-setup is not installed") + + def systemd_unit(unit_name): properties = [ "LoadState", @@ -392,6 +794,7 @@ def build_status_payload(): payload = { "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "hostname": os.uname().nodename, + "identity": get_identity_payload(), "services": cards, "providers": provider_names, } @@ -463,6 +866,30 @@ class Handler(BaseHTTPRequestHandler): except Exception as exc: self.send_json({"ok": False, "error": str(exc)}, code=500) return + if parsed.path == "/api/health/summary": + try: + self.send_json({ + **get_health_summary(), + "identity": get_identity_payload(), + }) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return + if parsed.path == "/api/network/summary": + try: + self.send_json({ + **get_network_summary(), + "identity": get_identity_payload(), + }) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return + if parsed.path == "/api/network/scan": + try: + self.send_json(scan_wifi_networks()) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc), "networks": []}, code=500) + return if parsed.path in ("/", "/index.html"): self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8") return @@ -563,6 +990,24 @@ class Handler(BaseHTTPRequestHandler): }) return + if parsed.path == "/api/network/profile/apply": + payload = self.read_json_body() + if payload is None: + self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) + return + ssid = str(payload.get("ssid", "")) + password = str(payload.get("password", "")) + try: + result = apply_wifi_profile(ssid, password) + self.send_json({ + "ok": True, + "message": result["message"], + "network": get_network_summary(), + }) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return + self.send_error(404) diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index fef3529..590befb 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -18,13 +18,13 @@ body{ linear-gradient(180deg, #f7faf8 0%, var(--bg) 100%); color:var(--ink); } -.shell{max-width:1100px;margin:0 auto;padding:28px 18px 40px} +.shell{max-width:1180px;margin:0 auto;padding:28px 18px 40px} .hero{ - display:flex;justify-content:space-between;gap:16px;align-items:center;flex-wrap:wrap; + display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:16px;align-items:center; margin-bottom:18px; } .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} +.brandCopy{display:flex;flex-direction:column;justify-content:center;gap:4px;min-width:0} .brandLogo{ 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; @@ -33,22 +33,76 @@ body{ .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)} +.osLabel{font-size:14px;color:var(--ink);font-weight:400} +.identityPanel{ + display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;padding:14px 16px;min-width:300px; +} +.identityItem{display:flex;flex-direction:column;gap:4px} +.identityItem strong{font-size:15px} .actions button{ border:0;border-radius:999px;background:var(--ink);color:#fff;padding:12px 18px;font-weight:700;cursor:pointer; box-shadow:var(--shadow); } +.actions button, +.tabBtn, +.actionBtn, +.toggleInlineBtn, +.scanRow, +.field input{ + transition:background-color .16s ease,border-color .16s ease,color .16s ease,box-shadow .16s ease,transform .06s ease,opacity .16s ease; +} +.actions button:hover, +.actionBtn:hover:not(:disabled), +.tabBtn:hover:not(:disabled), +.toggleInlineBtn:hover:not(:disabled){ + box-shadow:0 10px 24px rgba(16,24,20,.10); +} +.actions button:active, +.actionBtn:active:not(:disabled), +.tabBtn:active:not(:disabled), +.toggleInlineBtn:active:not(:disabled), +.scanRow:active{ + transform:translateY(1px); +} +.actions button:focus-visible, +.tabBtn:focus-visible, +.actionBtn:focus-visible, +.toggleInlineBtn:focus-visible, +.scanRow:focus-visible, +.field input:focus-visible{ + outline:none; + box-shadow:0 0 0 3px rgba(14,122,83,.18); +} .panel{ background:var(--panel);border:1px solid var(--line);border-radius:18px;box-shadow:var(--shadow); } -.summary{ - display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;padding:16px 18px;margin-bottom:18px; +.tabs{ + display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px; +} +.tabBtn{ + border:1px solid var(--line);background:rgba(255,255,255,.8);color:var(--ink); + border-radius:999px;padding:10px 16px;font-size:14px;font-weight:700;cursor:pointer; +} +.tabBtn.is-active{ + background:var(--ink);color:#fff;border-color:var(--ink); +} +.tabBtn:hover:not(.is-active):not(:disabled){ + background:#f7faf8;border-color:#bfd0c8; +} +.tabContent{display:grid;gap:18px} +.tabPanel{display:grid;gap:18px} +.sectionHead{display:flex;justify-content:space-between;gap:12px;align-items:flex-end;flex-wrap:wrap} +.sectionHead h2{margin:0;font-size:22px} +.sectionHead p{margin:0;color:var(--muted)} +.summaryGrid{ + display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;padding:16px 18px; } .summaryItem{display:flex;flex-direction:column;gap:4px} .label{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)} .cards{ - display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px; + display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px; } +.wideCard{grid-column:span 2} .card{padding:18px} .cardTop{display:flex;justify-content:space-between;gap:12px;align-items:flex-start} .card h2{margin:0;font-size:19px} @@ -60,7 +114,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e .dot.ok{background:var(--accent)} .dot.warn{background:var(--warn)} .dot.error{background:var(--error)} -.meta{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;margin-top:16px;font-size:13px} +.meta{display:grid;grid-template-columns:140px 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)} @@ -75,14 +129,14 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e .empty{ padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center; } -.accessPointCard{grid-column:span 2} -.displayCard{grid-column:span 2} -.displayHero{ +.emptyInline{color:var(--muted);font-size:14px} +.displayCard,.accessPointCard{grid-column:span 2} +.displayHero,.apHero{ 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} +.displayHero.is-connected,.apHero.is-enabled{background:rgba(14,122,83,.08)} +.displayHero.is-empty,.apHero.is-disabled{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} @@ -93,13 +147,6 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e .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} -.apHero{ - 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; -} -.apHero.is-enabled{background:rgba(14,122,83,.08)} -.apHero.is-disabled{background:#f7f8f7} .modeBadge{ display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700; } @@ -109,18 +156,23 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e .actionBtn{ border:0;border-radius:12px;background:var(--ink);color:#fff;padding:10px 14px;font-weight:700;cursor:pointer; } +.actionBtn:hover:not(:disabled){background:#22302b} .actionBtn.secondary{background:#eef3f1;color:var(--ink);border:1px solid var(--line)} +.actionBtn.secondary:hover:not(:disabled){background:#e4ece8} .actionBtn:disabled{opacity:.5;cursor:not-allowed} .apForm{display:grid;gap:12px} .field{display:grid;gap:6px;font-size:13px;color:var(--ink)} -.passwordField{display:flex;gap:8px;align-items:center} .field input{ width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:#fff;color:var(--ink); } +.field input:hover{border-color:#bfd0c8} +.field input:focus-visible{border-color:var(--accent)} +.passwordField{display:flex;gap:8px;align-items:center} .passwordField input{flex:1 1 auto} .toggleInlineBtn{ border:1px solid var(--line);border-radius:12px;background:#f6f8f7;color:var(--ink);padding:10px 12px;font-weight:700;cursor:pointer;white-space:nowrap; } +.toggleInlineBtn:hover:not(:disabled){background:#edf3f0} .formHint{font-size:12px;color:var(--muted)} .formError{font-size:12px;color:var(--error);font-weight:600} .banner{ @@ -128,12 +180,51 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e } .banner.success{background:rgba(14,122,83,.10);color:var(--accent)} .banner.error{background:rgba(185,52,52,.10);color:var(--error)} +.scanList{display:grid;gap:10px} +.scanRow{ + display:flex;justify-content:space-between;gap:12px;align-items:center; + border:1px solid var(--line);border-radius:12px;background:#fbfcfb;padding:12px 14px; +} +.scanRow:hover{background:#f4f8f6;border-color:#bfd0c8} +.scanMain{display:grid;gap:6px;min-width:0} +.scanTopLine{display:flex;gap:8px;align-items:center;flex-wrap:wrap} +.scanSsid{font-weight:700} +.scanMeta{color:var(--muted);font-size:13px} +.scanHeader{display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap} +.scanStatus{font-size:13px;color:var(--muted)} +.scanActiveBadge,.scanHiddenBadge{ + display:inline-flex;align-items:center;border-radius:999px;padding:4px 8px;font-size:11px;font-weight:700; +} +.scanActiveBadge{background:rgba(14,122,83,.10);color:var(--accent)} +.scanHiddenBadge{background:#edf3f1;color:var(--muted)} +.scanSignalRow{display:flex;gap:10px;align-items:center;flex-wrap:wrap} +.scanSignalText{font-size:13px;color:var(--muted)} +.signalBars{display:inline-flex;align-items:flex-end;gap:3px;height:16px} +.signalBar{ + width:4px;border-radius:999px;background:#d7e0db;display:inline-block; +} +.signalBar:nth-child(1){height:5px} +.signalBar:nth-child(2){height:8px} +.signalBar:nth-child(3){height:11px} +.signalBar:nth-child(4){height:14px} +.signalBar.is-on{background:var(--accent)} +.loadingInline{display:inline-flex;align-items:center;gap:8px;color:var(--muted);font-size:13px} +.loadingDot{ + width:10px;height:10px;border-radius:50%;background:var(--accent);display:inline-block; + animation:pulse 1s ease-in-out infinite; +} +@keyframes pulse{ + 0%,100%{opacity:.35;transform:scale(.9)} + 50%{opacity:1;transform:scale(1)} +} +@media (max-width:940px){ + .hero{grid-template-columns:1fr} + .identityPanel{min-width:0} +} @media (max-width:720px){ - .summary{grid-template-columns:1fr} + .summaryGrid{grid-template-columns:1fr} .meta{grid-template-columns:1fr 1fr} - .brand{align-items:center} .brandLogo{width:58px;height:58px} - .accessPointCard{grid-column:auto} - .displayCard{grid-column:auto} + .wideCard,.displayCard,.accessPointCard{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 070b730..17dd254 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -3,12 +3,32 @@ const nodes = { refreshBtn: document.getElementById("refreshBtn"), - cards: document.getElementById("cards"), - lastUpdate: document.getElementById("lastUpdate"), - providerCount: document.getElementById("providerCount"), - serviceCount: document.getElementById("serviceCount"), - deviceName: document.getElementById("deviceName") + tabs: Array.from(document.querySelectorAll("[data-tab]")), + edgeId: document.getElementById("edgeId"), + hostName: document.getElementById("hostName"), + osLabel: document.getElementById("osLabel"), + content: document.getElementById("tabContent") }; + + const state = { + activeTab: "health", + status: null, + health: null, + network: null, + scan: { ok: true, networks: [], error: "", warning: "", message: "", loading: false, scannedAt: "" }, + networkForm: { + ssid: "", + password: "", + busy: false, + message: "", + error: "", + dirty: false, + focused: false, + seeded: false + }, + isPolling: false + }; + const apUi = { formOpen: false, resetOpen: false, @@ -24,7 +44,6 @@ showConfirmPassword: false, showResetPassword: false }; - let latestPayload = null; function esc(value) { return (value ?? "").toString().replace(/[&<>"']/g, (m) => ({ @@ -36,13 +55,52 @@ }[m])); } + function attrValue(value) { + return encodeURIComponent((value ?? "").toString()); + } + + function textValue(value, fallback) { + const text = (value ?? "").toString().trim(); + return text || fallback; + } + function boolPill(label, value) { return `${esc(label)}: ${value ? "yes" : "no"}`; } - function textValue(value, fallback = "Not available") { + function bytesHuman(value) { + if (value === null || value === undefined || Number.isNaN(Number(value))) return "Not available"; + const units = ["B", "KB", "MB", "GB", "TB"]; + let number = Number(value); + let unit = 0; + while (number >= 1024 && unit < units.length - 1) { + number /= 1024; + unit += 1; + } + return `${number.toFixed(number >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`; + } + + function formatRate(value) { + if (value === null || value === undefined) return "Not available"; + return `${bytesHuman(value)}/s`; + } + + function formatUtc(value) { const text = (value ?? "").toString().trim(); - return text || fallback; + if (!text) return "-"; + const date = new Date(text); + if (Number.isNaN(date.getTime())) return text; + const pad = (number) => String(number).padStart(2, "0"); + return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())} (UTC)`; + } + + function signalQuality(signal) { + const value = Number(signal); + if (!Number.isFinite(value) || value <= 0) return { label: "Unknown", className: "is-weak", bars: 0, value: null }; + if (value >= 80) return { label: "Excellent", className: "is-excellent", bars: 4, value }; + if (value >= 60) return { label: "Good", className: "is-good", bars: 3, value }; + if (value >= 40) return { label: "Fair", className: "is-fair", bars: 2, value }; + return { label: "Weak", className: "is-weak", bars: 1, value }; } function statusTone(card) { @@ -51,69 +109,20 @@ return "warn"; } - function clearApFeedback() { - apUi.message = ""; - apUi.error = ""; - } - - function changePasswordError() { - const current = apUi.currentPassword.trim(); - const next = apUi.newPassword.trim(); - const confirm = apUi.confirmPassword.trim(); - if (!current) return "Current password is required"; - if (!next) return "Password must be at least 8 characters long"; - if (next.length < 8) return "Password must be at least 8 characters long"; - if (!/^[a-z0-9]+$/.test(next)) return "Password must contain only lowercase letters and digits"; - if (next !== confirm) return "Passwords do not match"; - return ""; - } - - async function postJson(url, body) { - const response = await fetch(url, { - method: "POST", - cache: "no-store", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body) - }); - const payload = await response.json().catch(() => ({})); - if (!response.ok || payload.ok === false) { - throw new Error(payload.error || `HTTP ${response.status}`); - } - return payload; - } - function renderKeyValueRows(items) { return items.map((item) => `
${esc(item.label || "-")}
-
${esc(textValue(item.value))}
+
${esc(textValue(item.value, "Not available"))}
`).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 } - ]; - + function renderSimplePanel(title, rows, extraClass = "") { return ` -
-
- ${esc(textValue(connector.connector, "Connector"))} - ${esc(statusText)} +
+
+

${esc(title)}

-
${renderKeyValueRows(rows)}
+
${renderKeyValueRows(rows)}
`; } @@ -127,6 +136,28 @@ const connectedCount = connectors.filter((item) => item && item.connected).length; const status = card.display_status || {}; + function renderConnector(connector) { + const rows = [ + { label: "Interface", value: connector.interface }, + { label: "Connector", value: connector.connector }, + { label: "Status", value: connector.connected ? "Connected" : connector.status }, + { 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 } + ]; + return ` +
+
+ ${esc(textValue(connector.connector, "Connector"))} + ${esc(connector.connected ? "Connected" : textValue(connector.status, "Unknown"))} +
+
${renderKeyValueRows(rows)}
+
+ `; + } + return `
@@ -135,7 +166,6 @@
${esc(card.status_text || card.state || "Unknown")}
-
Display status
@@ -146,33 +176,34 @@ ${esc(`Primary: ${textValue(status.connector, "Not available")}`)}
-
${renderKeyValueRows(details)}
-
Connectors
- ${connectors.length - ? `
${connectors.map(renderConnector).join("")}
` - : `
No DRM connectors detected.
`} + ${connectors.length ? `
${connectors.map(renderConnector).join("")}
` : `
No DRM connectors detected.
`}
- - ${warnings.length ? ` -
-
Warnings
- -
- ` : ""} - - ${errors.length ? ` -
-
Errors
- -
- ` : ""} + ${warnings.length ? `
Warnings
` : ""} + ${errors.length ? `
Errors
` : ""}
`; } + function clearApFeedback() { + apUi.message = ""; + apUi.error = ""; + } + + function changePasswordError() { + const current = apUi.currentPassword.trim(); + const next = apUi.newPassword.trim(); + const confirm = apUi.confirmPassword.trim(); + if (!current) return "Current password is required"; + if (!next || next.length < 8 || !/^[a-z0-9]+$/.test(next)) { + return "Password must be at least 8 characters long and contain only lowercase letters and digits"; + } + if (next !== confirm) return "Passwords do not match"; + return ""; + } + function updateApFeedback() { const success = document.getElementById("apBannerSuccess"); const error = document.getElementById("apBannerError"); @@ -245,7 +276,7 @@
${esc(mode === "custom" ? "Custom" : "Factory")} - ${esc(`SSID: ${textValue(ap.ssid)}`)} + ${esc(`SSID: ${textValue(ap.ssid, "Not available")}`)}
@@ -260,9 +291,7 @@ - ${mode === "custom" - ? `` - : ""} + ${mode === "custom" ? `` : ""} @@ -326,7 +355,7 @@ `; } - function renderCard(card) { + function renderServiceCard(card) { if (card.id === "display") return renderDisplayCard(card); if (card.id === "access_point") return renderAccessPointCard(card); @@ -343,20 +372,12 @@
${esc(card.status_text || card.state || "Unknown")}
-
ID
${esc(card.id)}
State
${esc(card.state || "-")}
Status
${esc(card.status_text || "-")}
- - ${details.length ? ` -
-
Details
-
${renderKeyValueRows(details)}
-
- ` : ""} - + ${details.length ? `
Details
${renderKeyValueRows(details)}
` : ""}
Flags
@@ -365,58 +386,320 @@ ${boolPill("Active", !!card.active)}
- - ${warnings.length ? ` -
-
Warnings
- -
- ` : ""} - - ${errors.length ? ` -
-
Errors
- -
- ` : ""} + ${warnings.length ? `
Warnings
` : ""} + ${errors.length ? `
Errors
` : ""} `; } - function render(payload) { - latestPayload = payload; - const services = Array.isArray(payload.services) ? payload.services : []; - const providers = Array.isArray(payload.providers) ? payload.providers : []; + function renderHealthTab() { + const payload = state.status || { services: [], providers: [] }; + const health = state.health || {}; + const metrics = [ + { label: "CPU usage", value: health.cpu_usage_percent === null || health.cpu_usage_percent === undefined ? "Collecting..." : `${health.cpu_usage_percent}%` }, + { label: "Load average", value: Array.isArray(health.load_average) && health.load_average.length ? health.load_average.join(" / ") : "Not available" }, + { label: "Disk usage", value: health.disk && health.disk.used_percent !== undefined ? `${health.disk.used_percent}% used` : "Not available" } + ]; + const temps = Array.isArray(health.temperatures) ? health.temperatures : []; + const serviceCards = (payload.services || []).filter((card) => card.id !== "access_point"); - nodes.lastUpdate.textContent = payload.generated_at || "-"; - nodes.deviceName.textContent = `host: ${payload.hostname || "-"}`; - nodes.providerCount.textContent = String(providers.length); - nodes.serviceCount.textContent = String(services.length); + return ` +
+
+
Providers${esc(String((payload.providers || []).length))}
+
Cards${esc(String((payload.services || []).length))}
+
Updated${esc(formatUtc(payload.generated_at))}
+
- if (!services.length) { - nodes.cards.innerHTML = `
No service cards returned by providers.
`; +
+ ${renderSimplePanel("Health Summary", metrics, "wideCard")} + ${renderSimplePanel( + "Thermals", + temps.length ? temps.map((item) => ({ label: item.name, value: item.label || "not available" })) : [{ label: "Sensors", value: "not available" }], + "wideCard" + )} +
+ +
+

Installed Services

+

Core diagnostics and service state from providers.

+
+
${serviceCards.map(renderServiceCard).join("") || `
No service cards available.
`}
+
+ `; + } + + function networkValidationError() { + if (!state.networkForm.ssid.trim()) return "SSID is required"; + return ""; + } + + function networkFormIsInteractive() { + const active = document.activeElement; + return !!(state.activeTab === "network" && active && active.closest && active.closest("[data-network-form]")); + } + + function syncNetworkFormFromBackend() { + const desired = (state.network && state.network.desired_profile) || {}; + if (!state.networkForm.seeded) { + state.networkForm.ssid = desired.ssid || ""; + state.networkForm.seeded = true; return; } - - nodes.cards.innerHTML = services.map(renderCard).join(""); - } - - function rerender() { - if (latestPayload) { - render(latestPayload); - updateApFormUi(); + if (!state.networkForm.dirty && !state.networkForm.focused) { + state.networkForm.ssid = desired.ssid || ""; } } - async function load() { + function updateNetworkFormUi() { + const applyBtn = document.getElementById("wifiApplyBtn"); + const errorNode = document.getElementById("wifiFormError"); + const successNode = document.getElementById("wifiFormSuccess"); + const validationError = networkValidationError(); + if (applyBtn) applyBtn.disabled = !!(state.networkForm.busy || validationError); + if (errorNode) { + errorNode.textContent = validationError || state.networkForm.error || ""; + errorNode.hidden = !(validationError || state.networkForm.error); + } + if (successNode) { + successNode.textContent = state.networkForm.message || ""; + successNode.hidden = !state.networkForm.message; + } + } + + function renderScanRows() { + const payload = state.scan || { networks: [] }; + if (payload.loading) { + return `
Scanning nearby Wi-Fi networks...
`; + } + if (!payload.ok) { + return `
Scan failed: ${esc(payload.error || "Unknown error")}
`; + } + if (!payload.networks.length) { + return `
${esc(payload.message || "No Wi-Fi networks found.")}
`; + } + return ` +
+ ${payload.networks.map((item) => ` + ${(() => { + const quality = signalQuality(item.signal); + return ` +
+
+
+ ${esc(item.ssid || "Hidden network")} + ${item.in_use ? `Current` : ""} + ${item.hidden ? `Hidden` : ""} +
+
${esc(textValue(item.security, "Open"))}
+
+ + ${esc(quality.value === null ? quality.label : `${quality.label} · ${quality.value}%`)} +
+
+ +
+ `; + })()} + `).join("")} +
+ `; + } + + function renderNetworkTab() { + const network = state.network || {}; + const desired = network.desired_profile || {}; + const wifi = network.wifi || {}; + const addresses = network.addresses || { ipv4: [], ipv6: [] }; + const activity = network.activity || {}; + const accessPointCard = (state.status && state.status.services || []).find((item) => item.id === "access_point"); + + return ` +
+
+
+
+
+

Desired Wi-Fi Profile

+
${esc(wifi.connected ? "Connected" : "Not connected")}
+
+
+
+ + +
This uses the existing edge Wi-Fi setup flow and applies the profile through backend only.
+ + +
+ + +
+
+
+ +
+
+
+
+

Available Networks

+
${state.scan.loading ? "Scan in progress" : esc(`${(state.scan.networks || []).length} networks found`)}
+
+ +
+
+ ${state.scan.warning ? `` : ""} + ${renderScanRows()} +
+ + ${renderSimplePanel("Current Network Status", [ + { label: "State", value: wifi.state || "unknown" }, + { label: "Current SSID", value: wifi.ssid || desired.ssid || "Not available" }, + { label: "Connection", value: wifi.connection || "Not available" }, + { label: "Interface", value: network.iface || "wlan0" }, + { label: "Gateway", value: network.gateway || "Not available" }, + { label: "DNS", value: (network.dns || []).join(", ") || "Not available" } + ], "wideCard")} + + ${renderSimplePanel("Addresses and Throughput", [ + { label: "IPv4", value: (addresses.ipv4 || []).join(", ") || "Not available" }, + { label: "IPv6", value: (addresses.ipv6 || []).join(", ") || "Not available" }, + { label: "Incoming", value: formatRate(activity.rx_bytes_per_sec) }, + { label: "Outgoing", value: formatRate(activity.tx_bytes_per_sec) }, + { label: "Desired profile", value: desired.profile || "Not available" } + ], "wideCard")} +
+ + ${accessPointCard ? `
${renderAccessPointCard(accessPointCard)}
` : ""} +
+ `; + } + + function renderTscreenTab() { + return ` +
+
+

It-Screen

+

Foundation layout for the next major module.

+
+
+ ${renderSimplePanel("Device Registration", [ + { label: "Status", value: "Ready for future backend contract" }, + { label: "Planned", value: "Registration, ownership, claims" } + ], "wideCard")} + ${renderSimplePanel("Runtime Role", [ + { label: "Planned", value: "Current role, device purpose, timers" }, + { label: "Interfaces", value: "Display, network, control surfaces" } + ], "wideCard")} + ${renderSimplePanel("Logs and Events", [ + { label: "Planned", value: "Operational logs and traceability" }, + { label: "Status", value: "Placeholder section prepared" } + ], "wideCard")} +
+
+ `; + } + + function renderActiveTab() { + nodes.tabs.forEach((button) => { + button.classList.toggle("is-active", button.dataset.tab === state.activeTab); + }); + if (state.activeTab === "network") { + nodes.content.innerHTML = renderNetworkTab(); + updateNetworkFormUi(); + updateApFormUi(); + return; + } + if (state.activeTab === "tscreen") { + nodes.content.innerHTML = renderTscreenTab(); + return; + } + nodes.content.innerHTML = renderHealthTab(); + } + + function updateIdentity(identity) { + const safe = identity || {}; + nodes.edgeId.textContent = safe.edge_id || "-"; + nodes.hostName.textContent = safe.hostname || "-"; + nodes.osLabel.textContent = safe.os_label || "IOMATEX Edge OS"; + } + + async function fetchJson(url, options) { + const response = await fetch(url, options || { cache: "no-store" }); + const payload = await response.json().catch(() => ({})); + if (!response.ok || payload.ok === false) { + throw new Error(payload.error || `HTTP ${response.status}`); + } + return payload; + } + + async function loadStatus() { + state.status = await fetchJson("/api/status", { cache: "no-store" }); + updateIdentity(state.status.identity || {}); + } + + async function loadHealth() { + state.health = await fetchJson("/api/health/summary", { cache: "no-store" }); + updateIdentity(state.health.identity || state.status?.identity || {}); + } + + async function loadNetwork() { + state.network = await fetchJson("/api/network/summary", { cache: "no-store" }); + updateIdentity(state.network.identity || state.status?.identity || {}); + syncNetworkFormFromBackend(); + } + + async function loadScan() { + state.scan.loading = true; + state.scan.error = ""; + try { + const payload = await fetchJson("/api/network/scan", { cache: "no-store" }); + state.scan = { + ok: true, + networks: Array.isArray(payload.networks) ? payload.networks : [], + error: "", + warning: payload.warning || "", + message: payload.message || "", + loading: false, + scannedAt: new Date().toISOString() + }; + } catch (error) { + state.scan = { ok: false, error: error.message || "Failed to scan networks", warning: "", message: "", networks: [], loading: false, scannedAt: "" }; + } + } + + async function loadForActiveTab(options = {}) { + const preserveEditing = !!options.preserveEditing; nodes.refreshBtn.disabled = true; try { - const response = await fetch("/api/status", { cache: "no-store" }); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - const payload = await response.json(); - render(payload); + await loadStatus(); + if (state.activeTab === "network") { + await loadNetwork(); + if (!preserveEditing || !networkFormIsInteractive()) { + await loadScan(); + } + } else if (state.activeTab === "health") { + await loadHealth(); + } + if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive())) { + renderActiveTab(); + } else { + updateNetworkFormUi(); + } } catch (error) { - nodes.cards.innerHTML = `
Failed to load status: ${esc(error.message || String(error))}
`; + nodes.content.innerHTML = `
Failed to load ${esc(state.activeTab)}: ${esc(error.message || String(error))}
`; } finally { nodes.refreshBtn.disabled = false; } @@ -433,7 +716,7 @@ apUi.showConfirmPassword = false; } clearApFeedback(); - rerender(); + renderActiveTab(); }; window.__toggleApReset = function () { @@ -443,7 +726,7 @@ apUi.showResetPassword = false; } clearApFeedback(); - rerender(); + renderActiveTab(); }; window.__setApField = function (field, value) { @@ -466,28 +749,32 @@ } apUi.busy = true; clearApFeedback(); - rerender(); + renderActiveTab(); try { - await postJson("/api/ap/password/change", { - current_password: apUi.currentPassword, - new_password: apUi.newPassword, - confirm_password: apUi.confirmPassword + await fetchJson("/api/ap/password/change", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + current_password: apUi.currentPassword, + new_password: apUi.newPassword, + confirm_password: apUi.confirmPassword + }) }); apUi.message = "Access point password changed. Reconnect using the new password."; apUi.formOpen = false; apUi.currentPassword = ""; apUi.newPassword = ""; apUi.confirmPassword = ""; - apUi.showCurrentPassword = false; - apUi.showNewPassword = false; - apUi.showConfirmPassword = false; - await load(); + await loadStatus(); + await loadNetwork(); + renderActiveTab(); } catch (error) { apUi.error = error.message || "Failed to apply AP password change"; - await load(); + renderActiveTab(); } finally { apUi.busy = false; - await load(); + updateApFormUi(); } }; @@ -500,25 +787,106 @@ if (!window.confirm("Reset Access Point password to factory mode?")) return; apUi.busy = true; clearApFeedback(); - rerender(); + renderActiveTab(); try { - await postJson("/api/ap/password/reset", { - current_password: apUi.resetPassword + await fetchJson("/api/ap/password/reset", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ current_password: apUi.resetPassword }) }); apUi.message = "Access point password reset to factory mode."; apUi.resetOpen = false; apUi.resetPassword = ""; - apUi.showResetPassword = false; - await load(); + await loadStatus(); + await loadNetwork(); + renderActiveTab(); } catch (error) { - apUi.error = error.message || "Failed to apply AP password change"; - await load(); + apUi.error = error.message || "Failed to reset AP password"; + renderActiveTab(); } finally { apUi.busy = false; - await load(); + updateApFormUi(); } }; - nodes.refreshBtn.addEventListener("click", load); - load(); + window.__setNetworkField = function (field, value) { + state.networkForm[field] = value; + state.networkForm.dirty = true; + state.networkForm.error = ""; + state.networkForm.message = ""; + updateNetworkFormUi(); + }; + + window.__setNetworkFormFocus = function (focused) { + state.networkForm.focused = !!focused; + }; + + window.__selectScannedSsid = function (ssid) { + state.networkForm.ssid = ssid; + state.networkForm.dirty = true; + const input = document.getElementById("wifiSsid"); + if (input) input.value = ssid; + updateNetworkFormUi(); + }; + + window.__scanNetworks = async function () { + if (state.scan.loading) return; + state.scan.loading = true; + renderActiveTab(); + await loadScan(); + if (state.activeTab === "network") renderActiveTab(); + }; + + window.__applyWifiProfile = async function () { + const validationError = networkValidationError(); + if (validationError) { + state.networkForm.error = validationError; + updateNetworkFormUi(); + return; + } + state.networkForm.busy = true; + state.networkForm.error = ""; + state.networkForm.message = ""; + updateNetworkFormUi(); + try { + const payload = await fetchJson("/api/network/profile/apply", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + ssid: state.networkForm.ssid, + password: state.networkForm.password + }) + }); + state.networkForm.message = payload.message || "Wi-Fi profile applied"; + state.networkForm.password = ""; + state.networkForm.dirty = false; + await loadNetwork(); + await loadStatus(); + renderActiveTab(); + } catch (error) { + state.networkForm.error = error.message || "Failed to apply Wi-Fi profile"; + updateNetworkFormUi(); + } finally { + state.networkForm.busy = false; + updateNetworkFormUi(); + } + }; + + nodes.tabs.forEach((button) => { + button.addEventListener("click", async () => { + const nextTab = button.dataset.tab; + if (!nextTab || nextTab === state.activeTab) return; + state.activeTab = nextTab; + await loadForActiveTab(); + }); + }); + + nodes.refreshBtn.addEventListener("click", loadForActiveTab); + + loadForActiveTab(); + setInterval(() => { + loadForActiveTab({ preserveEditing: true }).catch(() => {}); + }, 15000); })(); diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index ac8a1b4..f58e080 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -14,32 +14,33 @@
IOMATEX
-

Console

-

host: -

-

Lightweight diagnostics for installed services.

+

Edge Console

+

IOMATEX Edge OS

+

Unified diagnostics, network operations and It-Screen foundation.

+
+
+ Edge ID + - +
+
+ Hostname + - +
+
-
-
- Last update - - -
-
- Providers - - -
-
- Cards - - -
-
+ -
+
diff --git a/stage_ui/console_core/providers/00_core_services.py b/stage_ui/console_core/providers/00_core_services.py index 5a42da9..ad70adf 100644 --- a/stage_ui/console_core/providers/00_core_services.py +++ b/stage_ui/console_core/providers/00_core_services.py @@ -7,7 +7,7 @@ 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}, + {"name": "webui", "unit": "iomatex-rt-webui.service", "local_port": 80}, ) diff --git a/stage_ui/ui_installer.sh b/stage_ui/ui_installer.sh index bc82557..d53f905 100644 --- a/stage_ui/ui_installer.sh +++ b/stage_ui/ui_installer.sh @@ -32,11 +32,20 @@ LEGACY_SERVICE_NAME="iomatex-webipc.service" CFG_PATH="/etc/iomatex/console.json" SRC_LOGO="${LOGO_SOURCE:-$SCRIPT_DIR/iomatex_logo_source.png}" APP_BIND="${CONSOLE_BIND:-0.0.0.0}" -APP_PORT="${CONSOLE_PORT:-8099}" +APP_PORT="${CONSOLE_PORT:-80}" ts="$(date +%s)" PREV_DIR="${APP_DIR}.prev.${ts}" LEGACY_APP_DIR="/opt/iomatex-process1-webipc" LEGACY_PREV_DIR="${LEGACY_APP_DIR}.prev.${ts}" +IFACE="wlan0" +AP_IP="10.10.10.1" +AP_CIDR="${AP_IP}/24" +DHCP_START="10.10.10.50" +DHCP_END="10.10.10.150" +DHCP_LEASE="12h" +UI_PORT="80" +COUNTRY_CODE="NL" +AP_CHANNEL="6" copy_tree() { local src="$1" @@ -45,6 +54,93 @@ copy_tree() { cp -a "${src}/." "$dst/" } +systemctl_try() { + systemctl "$@" >/dev/null 2>&1 || true +} + +stop_disable_reset_unit() { + local unit="$1" + systemctl_try stop "$unit" + systemctl_try disable "$unit" + systemctl_try reset-failed "$unit" +} + +remove_if_exists() { + local path="$1" + [ -e "$path" ] && rm -f "$path" + return 0 +} + +have() { + command -v "$1" >/dev/null 2>&1 +} + +trim_text() { + printf '%s' "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' +} + +load_env_value() { + local path="$1" + local key="$2" + awk -F= -v k="$key" ' + $0 ~ "^[[:space:]]*" k "=" { + v = substr($0, index($0, "=") + 1) + gsub(/^[[:space:]]+|[[:space:]]+$/, "", v) + gsub(/^["\047]|["\047]$/, "", v) + print v + exit + } + ' "$path" 2>/dev/null || true +} + +get_system_hostname() { + local host="" + host="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)" + host="$(trim_text "$host")" + [ -n "$host" ] || host="iomatex" + printf '%s\n' "$host" +} + +get_device_serial() { + local serial="" + serial="$(grep -m1 '^Serial' /proc/cpuinfo 2>/dev/null | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')" + [ -n "$serial" ] || { echo "ERROR: failed to read device serial from /proc/cpuinfo" >&2; exit 1; } + printf '%s\n' "$serial" +} + +build_ap_ssid() { + printf 'Iomatex %s\n' "$1" +} + +generate_factory_ap_password() { + local serial="$1" + local digest password + digest="$(printf '%s' "iomatex_the_best${serial}" | sha256sum | awk '{print $1}' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')" + password="${digest:0:8}" + [[ "$password" =~ ^[a-z0-9]{8}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; } + printf '%s\n' "$password" +} + +normalize_password_mode() { + local mode + mode="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')" + case "$mode" in + custom) printf 'custom\n' ;; + *) printf 'factory\n' ;; + esac +} + +get_active_ap_password() { + local mode="$1" + local custom_password="$2" + local factory_password="$3" + if [[ "$mode" == "custom" && -n "$custom_password" ]]; then + printf '%s\n' "$custom_password" + return 0 + fi + printf '%s\n' "$factory_password" +} + echo "[0/8] Validate source tree" for path in \ "$SRC_ROOT/backend/app.py" \ @@ -60,16 +156,21 @@ done echo "[1/8] Ensure runtime packages exist" apt-get update -apt-get install -y python3 python3-pil +apt-get install -y python3 python3-pil network-manager iw hostapd dnsmasq rfkill iptables +if update-alternatives --list iptables >/dev/null 2>&1; then + update-alternatives --set iptables /usr/sbin/iptables-legacy >/dev/null 2>&1 || true +fi +if update-alternatives --list ip6tables >/dev/null 2>&1; then + update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy >/dev/null 2>&1 || true +fi python3 --version +echo "[1/8] Skip setcap: service runs as root and can bind port 80 without extra capabilities" +systemctl_try disable --now hostapd +systemctl_try disable --now dnsmasq 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 +stop_disable_reset_unit "${SERVICE_NAME}" +stop_disable_reset_unit "${LEGACY_SERVICE_NAME}" echo "[3/8] Prepare directories and preserve previous install" mkdir -p /etc/iomatex @@ -81,17 +182,72 @@ 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" +mkdir -p "$APP_DIR" "$PUBLIC_DIR" "$BACKEND_DIR" "$PROVIDERS_DIR" /etc/hostapd /etc/dnsmasq.d /usr/local/sbin -if [ ! -f "$CFG_PATH" ]; then - cat > "$CFG_PATH" < "$CFG_PATH" < /etc/iomatex/ap.env < /etc/hostapd/iomatex-ap.conf < /etc/dnsmasq.d/iomatex-ap.conf < /usr/local/sbin/iomatex-ap-sync-config <<'EOF' +#!/usr/bin/env bash +set -euo pipefail + +ENV_PATH="/etc/iomatex/ap.env" +HOSTAPD_PATH="/etc/hostapd/iomatex-ap.conf" +COUNTRY_CODE="NL" +AP_CHANNEL="6" + +trim_text() { + printf '%s' "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' +} + +get_system_hostname() { + local host="" + host="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)" + host="$(trim_text "$host")" + [[ -n "$host" ]] || { echo "ERROR: failed to determine system hostname" >&2; exit 1; } + printf '%s\n' "$host" +} + +get_device_serial() { + local serial="" + serial="$(grep -m1 '^Serial' /proc/cpuinfo 2>/dev/null | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')" + [[ -n "$serial" ]] || { echo "ERROR: failed to read device serial from /proc/cpuinfo" >&2; exit 1; } + printf '%s\n' "$serial" +} + +build_ap_ssid() { printf 'Iomatex %s\n' "$1"; } + +generate_factory_ap_password() { + local serial="$1" + local digest password + digest="$(printf '%s' "iomatex_the_best${serial}" | sha256sum | awk '{print $1}' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')" + password="${digest:0:8}" + [[ "$password" =~ ^[a-z0-9]{8}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; } + printf '%s\n' "$password" +} + +normalize_password_mode() { + local mode + mode="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')" + case "$mode" in + custom) printf 'custom\n' ;; + *) printf 'factory\n' ;; + esac +} + +get_active_ap_password() { + local mode="$1" custom_password="$2" factory_password="$3" + if [[ "$mode" == "custom" && -n "$custom_password" ]]; then + printf '%s\n' "$custom_password" + return 0 + fi + printf '%s\n' "$factory_password" +} + +IFACE="wlan0" +AP_IP="10.10.10.1" +AP_CIDR="${AP_IP}/24" +DHCP_START="10.10.10.50" +DHCP_END="10.10.10.150" +DHCP_LEASE="12h" +UI_PORT="80" +PASSWORD_MODE="factory" +CUSTOM_PASSWORD="" + +if [[ -f "$ENV_PATH" ]]; then + . "$ENV_PATH" +fi + +PASSWORD_MODE="$(normalize_password_mode "${PASSWORD_MODE:-factory}")" +CUSTOM_PASSWORD="${CUSTOM_PASSWORD:-}" +if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then + PASSWORD_MODE="factory" +fi + +HOSTNAME_SHORT="$(get_system_hostname)" +DEVICE_SERIAL="$(get_device_serial)" +SSID="$(build_ap_ssid "$HOSTNAME_SHORT")" +FACTORY_PASSWORD="$(generate_factory_ap_password "$DEVICE_SERIAL")" +ACTIVE_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_PASSWORD")" + +tmp_env="$(mktemp)" +cat >"$tmp_env" <"$tmp_hostapd" < /usr/local/sbin/iomatex-ap-reset-password <<'EOF' +#!/usr/bin/env bash +set -euo pipefail + +ENV_PATH="/etc/iomatex/ap.env" +IFACE="wlan0" +AP_IP="10.10.10.1" +AP_CIDR="${AP_IP}/24" +DHCP_START="10.10.10.50" +DHCP_END="10.10.10.150" +DHCP_LEASE="12h" +UI_PORT="80" +SSID="" + +if [[ -f "$ENV_PATH" ]]; then + . "$ENV_PATH" +fi + +tmp_env="$(mktemp)" +cat >"$tmp_env" </dev/null 2>&1 || true +if command -v nmcli >/dev/null 2>&1; then + nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true +fi +/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true +echo "OK: AP password reset to factory mode" +EOF +chmod 0755 /usr/local/sbin/iomatex-ap-reset-password + +cat > /usr/local/sbin/iomatex-ap-up <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +/usr/local/sbin/iomatex-ap-sync-config >/dev/null 2>&1 || true +. /etc/iomatex/ap.env + +rfkill unblock all >/dev/null 2>&1 || true + +if command -v nmcli >/dev/null 2>&1; then + nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true + nmcli dev set "$IFACE" managed no >/dev/null 2>&1 || true +fi + +ip link set "$IFACE" up >/dev/null 2>&1 || true +ip addr flush dev "$IFACE" >/dev/null 2>&1 || true +ip addr add "$AP_CIDR" dev "$IFACE" + +systemctl start iomatex-console.service >/dev/null 2>&1 || true +systemctl start iomatex-dnsmasq.service +systemctl start iomatex-hostapd.service + +iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true +iptables -t nat -A PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true +EOF +chmod 0755 /usr/local/sbin/iomatex-ap-up + +cat > /usr/local/sbin/iomatex-ap-down <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +systemctl stop iomatex-hostapd.service 2>/dev/null || true +systemctl stop iomatex-dnsmasq.service 2>/dev/null || true +iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true +ip addr flush dev "$IFACE" 2>/dev/null || true + +if command -v nmcli >/dev/null 2>&1; then + nmcli dev set "$IFACE" managed yes >/dev/null 2>&1 || true +fi +EOF +chmod 0755 /usr/local/sbin/iomatex-ap-down + +cat > /usr/local/sbin/iomatex-wifi-status <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +ap_active=0 +systemctl is-active --quiet iomatex-hostapd.service && ap_active=1 + +nm_state="n/a" +nm_con="n/a" +if command -v nmcli >/dev/null 2>&1; then + nm_state="$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)" + nm_con="$(nmcli -t -f DEVICE,CONNECTION dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)" +fi + +sta_connected=no +if command -v iw >/dev/null 2>&1; then + iw dev "$IFACE" link 2>/dev/null | grep -q "^Connected to " && sta_connected=yes +fi + +ip4="$(ip -4 -o addr show dev "$IFACE" 2>/dev/null | awk '{print $4}' | head -n1 || true)" + +echo "IFACE=$IFACE" +echo "AP_ACTIVE=$ap_active" +echo "NM_STATE=$nm_state" +echo "NM_CONNECTION=$nm_con" +echo "STA_CONNECTED=$sta_connected" +echo "IP4=$ip4" +echo "WATCH_STATE=$(cat /run/iomatex-ap.state 2>/dev/null || echo n/a)" +EOF +chmod 0755 /usr/local/sbin/iomatex-wifi-status + +cat > /usr/local/sbin/iomatex-wifi-setup <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +SSID_IN="${1:-}" +PASS_IN="${2:-}" + +[ -n "$SSID_IN" ] || { echo "ERROR: SSID required" >&2; exit 2; } +command -v nmcli >/dev/null 2>&1 || { echo "ERROR: nmcli not found" >&2; exit 3; } + +LOCK="/run/iomatex-wifi-setup.lock" +exec 9>"$LOCK" +flock -n 9 || { echo "ERROR: busy" >&2; exit 4; } + +AP_LOCK="/run/iomatex-ap.lock" +exec 8>"$AP_LOCK" +flock 8 + +CN="$(echo "$SSID_IN" | tr -cd "[:alnum:] ._-" | sed -E "s/[[:space:]]+/ /g" | cut -c1-64)" +[ -n "$CN" ] || CN="iomatex-wifi" + +sta_ok() { + nmcli -t -f DEVICE,STATE dev | grep -q "^${IFACE}:connected$" || return 1 + ip -4 -o addr show dev "$IFACE" 2>/dev/null | grep -q "inet " || return 1 + return 0 +} + +wait_for_nm_device_ready() { + local attempt state="" + for attempt in $(seq 1 20); do + state="$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)" + case "$state" in + disconnected|connecting|connected) + return 0 + ;; + esac + sleep 1 + done + echo "ERROR: NetworkManager did not reclaim $IFACE (state=${state:-unknown})" >&2 + return 1 +} + +/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true + +nmcli dev set "$IFACE" managed yes >/dev/null 2>&1 || true +ip addr flush dev "$IFACE" >/dev/null 2>&1 || true +ip link set "$IFACE" up >/dev/null 2>&1 || true +wait_for_nm_device_ready + +existing_type="$(nmcli -g connection.type con show "$CN" 2>/dev/null || true)" +case "$existing_type" in + "" ) + nmcli con add type wifi ifname "$IFACE" con-name "$CN" ssid "$SSID_IN" >/dev/null + ;; + wifi|802-11-wireless) + nmcli con mod "$CN" connection.interface-name "$IFACE" 802-11-wireless.ssid "$SSID_IN" >/dev/null + ;; + * ) + nmcli con delete id "$CN" >/dev/null 2>&1 || true + nmcli con add type wifi ifname "$IFACE" con-name "$CN" ssid "$SSID_IN" >/dev/null + ;; +esac + +if [ -n "$PASS_IN" ]; then + nmcli con mod "$CN" wifi-sec.key-mgmt wpa-psk wifi-sec.psk "$PASS_IN" >/dev/null +else + nmcli con mod "$CN" wifi-sec.key-mgmt none >/dev/null 2>&1 || true +fi + +nmcli con mod "$CN" connection.autoconnect yes connection.autoconnect-priority 10 ipv4.method auto ipv6.method ignore >/dev/null + +up_output="" +if ! up_output="$(nmcli --wait 25 con up id "$CN" 2>&1)"; then + echo "ERROR: failed to start Wi-Fi profile '$CN': ${up_output}" >&2 +else + echo "INFO: Wi-Fi profile '$CN' activation requested: ${up_output}" >&2 +fi + +sleep 10 + +if sta_ok; then + ip4="$(ip -4 -o addr show dev "$IFACE" 2>/dev/null | awk '{print $4}' | head -n1 || true)" + { echo "WIFI_PROFILE=\"$CN\""; echo "WIFI_SSID=\"$SSID_IN\""; echo "WIFI_IP4=\"${ip4:-}\""; } > /etc/iomatex/wifi.env + chmod 0644 /etc/iomatex/wifi.env + echo "OK: STA connected (profile=$CN) IP=${ip4:-n/a}" + exit 0 +fi + +/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true +echo "ERROR: STA not connected / no IPv4; AP restored (NM_STATE=$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d=\"$IFACE\" '\$1==d{print \$2; exit}' || echo unknown))" >&2 +exit 10 +EOF +chmod 0755 /usr/local/sbin/iomatex-wifi-setup + +cat > /usr/local/sbin/iomatex-ap-watch <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +STATE="/run/iomatex-ap.state" +LOCK="/run/iomatex-ap.lock" +exec 9>"$LOCK" +flock -n 9 || exit 0 + +eth_ok() { + [ "$(cat /sys/class/net/eth0/carrier 2>/dev/null || echo 0)" = "1" ] || return 1 + return 0 +} + +sta_ok() { + command -v nmcli >/dev/null 2>&1 || return 1 + nmcli -t -f DEVICE,STATE dev | grep -q "^${IFACE}:connected$" || return 1 + ip -4 -o addr show dev "$IFACE" 2>/dev/null | grep -q "inet " || return 1 + return 0 +} + +ap_is_up() { systemctl is-active --quiet iomatex-hostapd.service; } + +if eth_ok || sta_ok; then + ap_is_up && /usr/local/sbin/iomatex-ap-down || true + echo "uplink_ok" > "$STATE" + exit 0 +fi + +ap_is_up || /usr/local/sbin/iomatex-ap-up +echo "ap_on_no_uplink" > "$STATE" +EOF +chmod 0755 /usr/local/sbin/iomatex-ap-watch + +cat > /usr/local/sbin/iomatex-ap-resetd <<'EOF' +#!/usr/bin/env python3 +import os +import select +import struct +import subprocess +import sys +import time + +EVENT_PATH = "/dev/input/event8" +RESET_HELPER = "/usr/local/sbin/iomatex-ap-reset-password" +EV_KEY = 0x01 +KEY_VOLUMEUP = 115 +INPUT_EVENT = struct.Struct("llHHI") +HOLD_SECONDS = 10.0 +RETRY_DELAY_SECONDS = 1.0 + +def log(message): + timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + print(f"[{timestamp} UTC] {message}", flush=True) + +def run_reset(): + result = subprocess.run( + [RESET_HELPER], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + output = (result.stdout or "").strip() + if result.returncode == 0: + log(f"AP password reset helper completed: {output or 'success'}") + return True + log(f"ERROR: AP password reset helper failed: {output or result.returncode}") + return False + +def main(): + pressed_since = None + reset_triggered = False + event_fd = None + last_open_error = 0.0 + log("iomatex-ap-resetd started") + while True: + now = time.monotonic() + if event_fd is None: + try: + event_fd = os.open(EVENT_PATH, os.O_RDONLY) + log(f"button device opened: {EVENT_PATH}") + except Exception as exc: + if now - last_open_error >= 30.0: + log(f"WARNING: failed to open button device {EVENT_PATH}: {exc}") + last_open_error = now + time.sleep(RETRY_DELAY_SECONDS) + continue + + if pressed_since is not None and not reset_triggered and now - pressed_since >= HOLD_SECONDS: + reset_triggered = True + log(f"reset threshold reached: hold duration {now - pressed_since:.1f}s") + if run_reset(): + log("AP password reset to factory") + + try: + readable, _, _ = select.select([event_fd], [], [], 0.1) + except OSError as exc: + log(f"WARNING: button device select failed, reopening: {exc}") + try: + os.close(event_fd) + except Exception: + pass + event_fd = None + pressed_since = None + reset_triggered = False + continue + + if not readable: + continue + + payload = os.read(event_fd, INPUT_EVENT.size) + if len(payload) != INPUT_EVENT.size: + continue + _, _, event_type, event_code, event_value = INPUT_EVENT.unpack(payload) + if event_type != EV_KEY or event_code != KEY_VOLUMEUP: + continue + if event_value == 1: + if pressed_since is None: + pressed_since = time.monotonic() + reset_triggered = False + log("button press detected") + elif event_value == 0: + hold = 0.0 if pressed_since is None else time.monotonic() - pressed_since + log(f"button release detected: hold duration {hold:.1f}s") + pressed_since = None + reset_triggered = False + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + pass + except Exception as exc: + log(f"FATAL: {exc}") + sys.exit(1) +EOF +chmod 0755 /usr/local/sbin/iomatex-ap-resetd + +echo "[6/8] Generate logo and favicon" if [ ! -f "$SRC_LOGO" ]; then echo "ERROR: logo source image not found: $SRC_LOGO" >&2 exit 1 @@ -123,7 +756,39 @@ fav.thumbnail((64, 64)) fav.save(fav_out, format="PNG") PY -echo "[6/8] Install systemd service" +echo "[7/8] Install systemd service" +cat > /etc/systemd/system/iomatex-hostapd.service <<'UNIT' +[Unit] +Description=IOMATEX hostapd (AP) +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/sbin/hostapd -dd /etc/hostapd/iomatex-ap.conf +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +UNIT + +cat > /etc/systemd/system/iomatex-dnsmasq.service <<'UNIT' +[Unit] +Description=IOMATEX dnsmasq (DHCP/DNS for AP) +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/sbin/dnsmasq --no-daemon --conf-file=/etc/dnsmasq.d/iomatex-ap.conf +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +UNIT + cat > "/etc/systemd/system/${SERVICE_NAME}" < /etc/systemd/system/iomatex-ap-watch.service <<'UNIT' +[Unit] +Description=IOMATEX AP Watch +After=network-online.target +Wants=network-online.target -echo "[8/8] Summary" -echo "Web UI: http://:${APP_PORT}" -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" +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-ap-watch +UNIT + +cat > /etc/systemd/system/iomatex-ap-watch.timer <<'UNIT' +[Unit] +Description=IOMATEX AP Watch timer + +[Timer] +OnBootSec=20 +OnUnitActiveSec=15 +AccuracySec=2 +Unit=iomatex-ap-watch.service + +[Install] +WantedBy=timers.target +UNIT + +cat > /etc/systemd/system/iomatex-ap-resetd.service <<'UNIT' +[Unit] +Description=IOMATEX AP password reset daemon +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/local/sbin/iomatex-ap-resetd +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +UNIT + +echo "[8/8] Remove optional mDNS alias artifacts" +remove_if_exists /etc/avahi/services/iomatex-console.service +remove_if_exists /usr/local/sbin/iomatex-mdns-alias +remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service + +echo "[9/9] Validate and restart" +python3 -m py_compile "$BACKEND_DIR/app.py" "$PROVIDERS_DIR/00_core_services.py" +python3 -m py_compile /usr/local/sbin/iomatex-ap-resetd +systemctl daemon-reload +systemctl_try disable --now iomatex-mdns-alias.service +systemctl enable iomatex-ap-watch.timer >/dev/null 2>&1 || true +systemctl enable iomatex-ap-resetd.service >/dev/null 2>&1 || true +systemctl enable --now "${SERVICE_NAME}" +if systemctl is-active --quiet iomatex-ap-watch.timer; then + systemctl_try restart iomatex-ap-watch.timer +else + systemctl_try start iomatex-ap-watch.timer +fi +if systemctl is-active --quiet iomatex-ap-resetd.service; then + systemctl_try restart iomatex-ap-resetd.service +else + systemctl_try start iomatex-ap-resetd.service +fi +/usr/local/sbin/iomatex-ap-watch >/dev/null 2>&1 || true + +echo "[10/10] Summary" +echo "Web UI: http://" +echo "Status API: curl -s http://127.0.0.1/api/status | cat" +echo "Health API: curl -s http://127.0.0.1/api/health/summary | cat" +echo "Network API: curl -s http://127.0.0.1/api/network/summary | cat" +echo "Display API: curl -s http://127.0.0.1/api/display | cat" echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40" echo "Install dir: ${APP_DIR}" echo "Providers dir: ${PROVIDERS_DIR}"