Merge HDMI and UI changes from stage-hdmi into stage-ui-refactor

This commit is contained in:
Andrei Smaliak 2026-03-15 15:42:55 +04:00
parent 582c30d03d
commit d26765cbf4
7 changed files with 775 additions and 328 deletions

View File

@ -3,6 +3,7 @@
## Core responsibilities
- Serve one fast local diagnostics UI.
- Expose one normalized status endpoint: `/api/status`.
- Expose focused lightweight detail endpoints when a core card needs richer data, for example `/api/display`.
- Load provider modules from `providers.d`.
- Cache recent status briefly to avoid repeated shell work on every page render.
@ -10,6 +11,7 @@
- Add new service cards without changing core frontend or server flow.
- Read only the service-specific files and units they need.
- Return normalized card objects using the shared card contract.
- Prefer Linux-local sources such as DRM/sysfs for hardware diagnostics and degrade cleanly when fields are missing.
## Future `ui_backend` role
- Keep this Console focused on lightweight diagnostics.

View File

@ -7,9 +7,7 @@ import subprocess
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from urllib.request import Request, urlopen
APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
@ -68,6 +66,14 @@ def read_text(path):
return ""
def read_bytes(path):
try:
with open(path, "rb") as fh:
return fh.read()
except Exception:
return b""
def read_env_file(path):
data = {}
try:
@ -84,80 +90,6 @@ def read_env_file(path):
return data
def http_probe(url, timeout=2, max_bytes=4096):
req = Request(url, headers={"User-Agent": "iomatex-console/1.0"})
try:
with urlopen(req, timeout=timeout) as resp:
body = resp.read(max_bytes).decode("utf-8", errors="ignore")
return {
"ok": True,
"status": getattr(resp, "status", 200),
"body": body,
"error": "",
}
except HTTPError as exc:
body = ""
try:
body = exc.read(max_bytes).decode("utf-8", errors="ignore")
except Exception:
body = ""
return {
"ok": False,
"status": exc.code,
"body": body,
"error": str(exc),
}
except URLError as exc:
return {
"ok": False,
"status": 0,
"body": "",
"error": str(exc),
}
except Exception as exc:
return {
"ok": False,
"status": 0,
"body": "",
"error": str(exc),
}
def read_machine_info():
data = {}
try:
with open("/etc/machine-info", "r", encoding="utf-8", errors="ignore") as fh:
for raw in fh:
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
data[key.strip()] = value.strip().strip('"').strip("'")
except Exception:
pass
return data
def detect_edge_identity():
machine_info = read_machine_info()
pretty_name = machine_info.get("PRETTY_HOSTNAME", "").strip()
hostname = ""
rc, stdout, _stderr = run(["hostname", "-s"])
if rc == 0 and stdout.strip():
hostname = stdout.strip()
if not hostname:
hostname = read_text("/etc/hostname").strip().splitlines()[0] if read_text("/etc/hostname").strip() else ""
if not hostname:
hostname = "unknown"
return {
"name": pretty_name or hostname,
"hostname": hostname,
"pretty_name": pretty_name or "",
}
def systemd_unit(unit_name):
properties = [
"LoadState",
@ -222,6 +154,10 @@ def normalize_card(card):
item["status_text"] = str(item.get("status_text", item["state"]))
item["errors"] = [str(x) for x in item.get("errors", []) if str(x).strip()]
item["warnings"] = [str(x) for x in item.get("warnings", []) if str(x).strip()]
item["details"] = [detail for detail in item.get("details", []) if isinstance(detail, dict)]
item["connectors"] = [connector for connector in item.get("connectors", []) if isinstance(connector, dict)]
status = item.get("display_status")
item["display_status"] = status if isinstance(status, dict) else {}
return item
@ -252,9 +188,10 @@ def build_status_payload():
"file_exists": file_exists,
"any_exists": any_exists,
"read_text": read_text,
"read_bytes": read_bytes,
"read_env_file": read_env_file,
"systemd_unit": systemd_unit,
"http_probe": http_probe,
"run": run,
}
cards = []
provider_names = []
@ -281,7 +218,7 @@ def build_status_payload():
payload = {
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"edge": detect_edge_identity(),
"hostname": os.uname().nodename,
"services": cards,
"providers": provider_names,
}
@ -290,6 +227,17 @@ def build_status_payload():
return payload
def find_service_card(service_id):
payload = build_status_payload()
for card in payload.get("services", []):
if card.get("id") == service_id:
return {
"generated_at": payload.get("generated_at", ""),
"service": card,
}
return None
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
return
@ -320,6 +268,13 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/api/status":
self.send_json(build_status_payload())
return
if parsed.path == "/api/display":
payload = find_service_card("display")
if payload is None:
self.send_json({"error": "Display card not found"}, code=404)
return
self.send_json(payload)
return
if parsed.path in ("/", "/index.html"):
self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8")
return

View File

@ -23,15 +23,17 @@ body{
display:flex;justify-content:space-between;gap:16px;align-items:center;flex-wrap:wrap;
margin-bottom:18px;
}
.brand{display:flex;align-items:center;gap:14px;min-width:0}
.brand{display:flex;align-items:center;gap:16px;min-width:0}
.brandCopy{display:flex;flex-direction:column;justify-content:center;gap:3px;min-width:0}
.brandLogo{
width:40px;height:40px;object-fit:contain;display:block;flex:0 0 auto;
border-radius:10px;background:#fff;border:1px solid var(--line);padding:4px;
width:68px;height:68px;object-fit:contain;display:block;flex:0 0 auto;
border-radius:18px;background:rgba(255,255,255,.9);border:1px solid rgba(215,224,219,.9);padding:7px;
box-shadow:0 10px 24px rgba(16,24,20,.06);
}
.eyebrow{font-size:12px;letter-spacing:.16em;text-transform:uppercase;color:var(--accent);font-weight:700}
h1{margin:4px 0 4px;font-size:34px;line-height:1}
.sub{margin:0;color:var(--muted)}
.edgeName{margin:8px 0 0;color:var(--ink);font-size:14px;font-weight:600}
.eyebrow{font-size:11px;letter-spacing:.18em;text-transform:uppercase;color:var(--accent);font-weight:600}
h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03em}
.sub{margin:0;color:var(--muted);font-weight:300}
.subHost{font-size:13px;font-weight:500;color:var(--ink)}
.actions button{
border:0;border-radius:999px;background:var(--ink);color:#fff;padding:12px 18px;font-weight:700;cursor:pointer;
box-shadow:var(--shadow);
@ -58,8 +60,8 @@ h1{margin:4px 0 4px;font-size:34px;line-height:1}
.dot.ok{background:var(--accent)}
.dot.warn{background:var(--warn)}
.dot.error{background:var(--error)}
.dot.neutral{background:var(--muted)}
.meta{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;margin-top:16px;font-size:13px}
.compactMeta{margin-top:0}
.meta .key{color:var(--muted)}
.list{margin-top:14px;padding-top:14px;border-top:1px solid var(--line)}
.listTitle{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:8px}
@ -73,8 +75,29 @@ h1{margin:4px 0 4px;font-size:34px;line-height:1}
.empty{
padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center;
}
.displayCard{grid-column:span 2}
.displayHero{
margin-top:16px;padding:16px 18px;border-radius:16px;border:1px solid var(--line);
display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap;
}
.displayHero.is-connected{background:rgba(14,122,83,.08)}
.displayHero.is-empty{background:#f7f8f7}
.displayHeroLabel{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:6px}
.displayHeroText{font-size:20px;font-weight:700}
.displayHeroMeta{display:flex;gap:10px;flex-wrap:wrap;color:var(--muted);font-size:13px}
.connectorList{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
.connectorCard{border:1px solid var(--line);border-radius:14px;padding:14px;background:#fbfcfb}
.connectorHead{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:12px}
.connectorState{font-size:12px;font-weight:700;border-radius:999px;padding:6px 10px}
.connectorState.is-connected{background:rgba(14,122,83,.10);color:var(--accent)}
.connectorState.is-idle{background:rgba(154,106,0,.10);color:var(--warn)}
.connectorMeta{margin-top:0}
.emptyInline{color:var(--muted);font-size:14px}
@media (max-width:720px){
.summary{grid-template-columns:1fr}
.meta{grid-template-columns:1fr 1fr}
.brand{align-items:flex-start}
.brand{align-items:center}
.brandLogo{width:58px;height:58px}
.displayCard{grid-column:auto}
.displayHeroText{font-size:18px}
}

View File

@ -7,7 +7,7 @@
lastUpdate: document.getElementById("lastUpdate"),
providerCount: document.getElementById("providerCount"),
serviceCount: document.getElementById("serviceCount"),
edgeName: document.getElementById("edgeName")
deviceName: document.getElementById("deviceName")
};
function esc(value) {
@ -24,18 +24,115 @@
return `<span class="pill ${value ? "good" : "bad"}">${esc(label)}: ${value ? "yes" : "no"}</span>`;
}
function textValue(value, fallback = "Not available") {
const text = (value ?? "").toString().trim();
return text || fallback;
}
function statusTone(card) {
if (card.state === "not installed") return "neutral";
if (card.state === "failed" || card.state === "degraded") return "error";
if (card.errors && card.errors.length) return "error";
if (card.active) return "ok";
return "warn";
}
function renderCard(card) {
function renderKeyValueRows(items) {
return items.map((item) => `
<div class="key">${esc(item.label || "-")}</div>
<div>${esc(textValue(item.value))}</div>
`).join("");
}
function renderConnector(connector) {
const statusText = connector.connected
? `Connected by ${textValue(connector.interface, connector.connector || "display")}`
: textValue(connector.status, "Unknown");
const rows = [
{ label: "Interface", value: connector.interface },
{ label: "Connector", value: connector.connector },
{ label: "Status", value: statusText },
{ label: "Monitor", value: connector.monitor_name },
{ label: "Manufacturer", value: connector.manufacturer },
{ label: "Current resolution", value: connector.current_resolution },
{ label: "Refresh rate", value: connector.refresh_rate },
{ label: "Preferred mode", value: connector.preferred_mode },
{ label: "Physical size", value: connector.physical_size },
{ label: "Diagonal", value: connector.diagonal }
];
return `
<article class="connectorCard">
<div class="connectorHead">
<strong>${esc(textValue(connector.connector, "Connector"))}</strong>
<span class="connectorState ${connector.connected ? "is-connected" : "is-idle"}">${esc(statusText)}</span>
</div>
<div class="meta connectorMeta">${renderKeyValueRows(rows)}</div>
</article>
`;
}
function renderDisplayCard(card) {
const tone = statusTone(card);
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
const errors = Array.isArray(card.errors) ? card.errors : [];
const details = Array.isArray(card.details) ? card.details : [];
const connectors = Array.isArray(card.connectors) ? card.connectors : [];
const connectedCount = connectors.filter((item) => item && item.connected).length;
const status = card.display_status || {};
return `
<article class="panel card displayCard">
<div class="cardTop">
<div>
<h2>${esc(card.title)}</h2>
<div class="badge"><span class="dot ${tone}"></span>${esc(card.status_text || card.state || "Unknown")}</div>
</div>
</div>
<section class="displayHero ${status.connected ? "is-connected" : "is-empty"}">
<div>
<div class="displayHeroLabel">Display status</div>
<div class="displayHeroText">${esc(card.status_text || "Monitor is not connected")}</div>
</div>
<div class="displayHeroMeta">
<span>${esc(`Connected connectors: ${connectedCount}`)}</span>
<span>${esc(`Primary: ${textValue(status.connector, "Not available")}`)}</span>
</div>
</section>
<div class="meta">${renderKeyValueRows(details)}</div>
<div class="list">
<div class="listTitle">Connectors</div>
${connectors.length
? `<div class="connectorList">${connectors.map(renderConnector).join("")}</div>`
: `<div class="emptyInline">No DRM connectors detected.</div>`}
</div>
${warnings.length ? `
<div class="list">
<div class="listTitle">Warnings</div>
<ul class="msgList">${warnings.map((x) => `<li>${esc(x)}</li>`).join("")}</ul>
</div>
` : ""}
${errors.length ? `
<div class="list">
<div class="listTitle">Errors</div>
<ul class="msgList">${errors.map((x) => `<li>${esc(x)}</li>`).join("")}</ul>
</div>
` : ""}
</article>
`;
}
function renderCard(card) {
if (card.id === "display") return renderDisplayCard(card);
const tone = statusTone(card);
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
const errors = Array.isArray(card.errors) ? card.errors : [];
const details = Array.isArray(card.details) ? card.details : [];
return `
<article class="panel card">
@ -52,6 +149,13 @@
<div class="key">Status</div><div>${esc(card.status_text || "-")}</div>
</div>
${details.length ? `
<div class="list">
<div class="listTitle">Details</div>
<div class="meta compactMeta">${renderKeyValueRows(details)}</div>
</div>
` : ""}
<div class="list">
<div class="listTitle">Flags</div>
<div class="pillRow">
@ -81,12 +185,11 @@
function render(payload) {
const services = Array.isArray(payload.services) ? payload.services : [];
const providers = Array.isArray(payload.providers) ? payload.providers : [];
const edgeName = payload.edge && payload.edge.name ? payload.edge.name : "unknown";
nodes.lastUpdate.textContent = payload.generated_at || "-";
nodes.deviceName.textContent = `host: ${payload.hostname || "-"}`;
nodes.providerCount.textContent = String(providers.length);
nodes.serviceCount.textContent = String(services.length);
nodes.edgeName.textContent = `Edge: ${edgeName}`;
if (!services.length) {
nodes.cards.innerHTML = `<div class="empty">No service cards returned by providers.</div>`;

View File

@ -12,11 +12,11 @@
<header class="hero">
<div class="brand">
<img class="brandLogo" src="/logo.png" alt="IOMATEX logo">
<div>
<div class="brandCopy">
<div class="eyebrow">IOMATEX</div>
<h1>Console</h1>
<p class="sub subHost" id="deviceName">host: -</p>
<p class="sub">Lightweight diagnostics for installed services.</p>
<p class="edgeName" id="edgeName">Edge: unknown</p>
</div>
</div>
<div class="actions">

View File

@ -1,10 +1,18 @@
import glob
import math
import os
import pwd
import re
def _service_card(service_id, title, unit_name, installed, configured, active, state, status_text, errors=None, warnings=None):
return {
DRM_ROOT = "/sys/class/drm"
REVERSE_TUNNEL_SERVICES = (
{"name": "cockpit", "unit": "iomatex-rt-cockpit.service", "local_port": 9090},
{"name": "z2m", "unit": "iomatex-rt-z2m.service", "local_port": 8081},
{"name": "webui", "unit": "iomatex-rt-webui.service", "local_port": 8099},
)
def _service_card(service_id, title, unit_name, installed, configured, active, state, status_text, errors=None, warnings=None, **extra):
card = {
"id": service_id,
"title": title,
"installed": installed,
@ -15,6 +23,8 @@ def _service_card(service_id, title, unit_name, installed, configured, active, s
"errors": errors or [],
"warnings": warnings or [],
}
card.update(extra)
return card
def _short_unit_errors(unit):
@ -33,10 +43,10 @@ def _short_unit_errors(unit):
def _lifecycle(installed, configured, active, *, failed=False):
if not installed:
return "not installed", "Not installed"
if not configured:
return "not configured", "Not configured"
if active:
return "active", "Active"
if not configured:
return "installed_not_configured", "Not configured"
if failed:
return "failed", "Failed"
return "inactive", "Inactive"
@ -46,108 +56,308 @@ def _strict_active(installed, configured, unit):
return bool(installed and configured and unit["active"])
def _service_failed(unit):
return bool(
unit["active_state"] == "failed"
or (unit["result"] and unit["result"] not in ("success", "done"))
or (unit["exec_main_status"] and unit["exec_main_status"] not in ("0", ""))
)
def _fallback(value, default="Not available"):
text = str(value or "").strip()
return text if text else default
def _find_first_existing(paths):
for path in paths:
if os.path.exists(path):
return path
return ""
def _read_trimmed(ctx, path):
return ctx["read_text"](path).strip()
def _read_text(path):
try:
with open(path, "r", encoding="utf-8", errors="ignore") as fh:
return fh.read()
except Exception:
return ""
def _clean_ascii(blob):
return (blob or b"").decode("ascii", errors="ignore").replace("\x00", "").replace("\r", "").replace("\n", "").strip()
def _has_any_serial_device():
if os.path.exists("/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0"):
return True
if glob.glob("/dev/serial/by-id/*"):
return True
if glob.glob("/dev/ttyUSB*"):
return True
if glob.glob("/dev/ttyACM*"):
return True
return False
def _extract_yaml_scalar(text, section, key):
in_section = False
section_prefix = f"{section}:"
key_prefix = f"{key}:"
for raw in text.splitlines():
line = raw.rstrip()
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if not raw.startswith((" ", "\t")):
in_section = stripped == section_prefix
continue
if in_section and stripped.startswith(key_prefix):
return stripped.split(":", 1)[1].strip().strip('"').strip("'")
return ""
def _z2m_config_path():
return "/opt/zigbee2mqtt/data/configuration.yaml"
def _z2m_has_minimal_config():
cfg_path = _z2m_config_path()
if not os.path.exists(cfg_path):
return False
cfg_text = _read_text(cfg_path)
return bool(
_extract_yaml_scalar(cfg_text, "mqtt", "server")
and _extract_yaml_scalar(cfg_text, "mqtt", "base_topic")
)
def _probe_z2m_gateway(ctx):
probe = ctx["http_probe"]("http://127.0.0.1:8081/")
body = (probe.get("body") or "").lower()
if "service z2m not installed" in body:
return {"reachable": False, "summary": "not installed", "error": ""}
if "service z2m not configured" in body:
return {"reachable": False, "summary": "not configured", "error": ""}
if "service z2m unavailable" in body:
return {"reachable": False, "summary": "ui unavailable", "error": ""}
if probe.get("ok"):
return {"reachable": True, "summary": "reachable", "error": ""}
return {"reachable": False, "summary": "unreachable", "error": probe.get("error", "")}
def _iomatex_home():
try:
return pwd.getpwnam("iomatex").pw_dir
except KeyError:
return "/home/iomatex"
def _reverse_tunnel_key_paths():
home = _iomatex_home()
hostname = os.uname().nodename
key_base = os.path.join(home, ".ssh", f"iomatex-{hostname}")
return key_base, key_base + ".pub"
def _reverse_tunnel_unit_names():
return [
("cockpit", "iomatex-rt-cockpit.service"),
("z2m", "iomatex-rt-z2m.service"),
("webui", "iomatex-rt-webui.service"),
def _parse_manufacturer_id(b1, b2):
word = ((b1 << 8) | b2) & 0xFFFF
letters = [
chr(((word >> 10) & 0x1F) + 64),
chr(((word >> 5) & 0x1F) + 64),
chr((word & 0x1F) + 64),
]
value = "".join(letters).replace("@", "")
return value if len(value) == 3 and value.isalpha() else ""
def _parse_detailed_timing(block):
if len(block) < 18:
return {}
pixel_clock_khz = ((block[1] << 8) | block[0]) * 10
if pixel_clock_khz <= 0:
return {}
h_active = block[2] | ((block[4] & 0xF0) << 4)
h_blanking = block[3] | ((block[4] & 0x0F) << 8)
v_active = block[5] | ((block[7] & 0xF0) << 4)
v_blanking = block[6] | ((block[7] & 0x0F) << 8)
total_pixels = (h_active + h_blanking) * (v_active + v_blanking)
refresh_hz = ""
if total_pixels > 0:
refresh_hz = f"{round((pixel_clock_khz * 1000) / total_pixels, 2):g} Hz"
return {
"resolution": f"{h_active} x {v_active}" if h_active and v_active else "",
"refresh_rate": refresh_hz,
}
def _parse_edid(edid):
if len(edid) < 128:
return {
"present": False,
"monitor_name": "",
"serial_text": "",
"manufacturer": "",
"product_code": "",
"size_cm": "",
"diagonal": "",
"preferred_resolution": "",
"preferred_refresh_rate": "",
"raw_length": len(edid),
}
monitor_name = ""
serial_text = ""
preferred_resolution = ""
preferred_refresh_rate = ""
for offset in range(54, min(len(edid), 126), 18):
block = edid[offset:offset + 18]
if len(block) < 18:
continue
if block[:4] == b"\x00\x00\x00\xfc":
monitor_name = _clean_ascii(block[5:18])
continue
if block[:4] == b"\x00\x00\x00\xff":
serial_text = _clean_ascii(block[5:18])
continue
if not preferred_resolution:
timing = _parse_detailed_timing(block)
preferred_resolution = timing.get("resolution", "")
preferred_refresh_rate = timing.get("refresh_rate", "")
manufacturer = _parse_manufacturer_id(edid[8], edid[9])
product_code = f"0x{edid[11]:02X}{edid[10]:02X}"
width_cm = edid[21] or 0
height_cm = edid[22] or 0
diagonal = ""
if width_cm and height_cm:
diagonal_cm = math.sqrt((width_cm * width_cm) + (height_cm * height_cm))
diagonal = f"{(diagonal_cm / 2.54):.1f}\""
return {
"present": True,
"monitor_name": monitor_name,
"serial_text": serial_text,
"manufacturer": manufacturer,
"product_code": product_code,
"size_cm": f"{width_cm} x {height_cm} cm" if width_cm and height_cm else "",
"diagonal": diagonal,
"preferred_resolution": preferred_resolution,
"preferred_refresh_rate": preferred_refresh_rate,
"raw_length": len(edid),
}
def _connector_interface(name):
upper = (name or "").upper()
if "HDMI" in upper:
return "HDMI"
if "DP-" in upper or upper.startswith("DP") or "DISPLAYPORT" in upper:
return "DP"
if "EDP" in upper:
return "eDP"
if "LVDS" in upper:
return "LVDS"
if "DSI" in upper:
return "DSI"
if "VGA" in upper:
return "VGA"
if "DVI" in upper:
return "DVI"
return "Other"
def _connector_priority(connector):
interface = connector.get("interface")
connected = 1 if connector.get("connected") else 0
preferred = {
"HDMI": 6,
"DP": 5,
"eDP": 4,
"LVDS": 3,
"DSI": 2,
}.get(interface, 1)
mode_bonus = 1 if connector.get("current_resolution") else 0
return (connected, preferred, mode_bonus, connector.get("connector", ""))
def _read_modes(ctx, connector_dir):
raw = _read_trimmed(ctx, os.path.join(connector_dir, "modes"))
if not raw:
return []
return [line.strip() for line in raw.splitlines() if line.strip()]
def _read_connector(ctx, connector_dir):
connector = os.path.basename(connector_dir)
interface = _connector_interface(connector)
status = _read_trimmed(ctx, os.path.join(connector_dir, "status")) or "unknown"
enabled = _read_trimmed(ctx, os.path.join(connector_dir, "enabled"))
dpms = _read_trimmed(ctx, os.path.join(connector_dir, "dpms"))
modes = _read_modes(ctx, connector_dir)
current_mode = _read_trimmed(ctx, os.path.join(connector_dir, "mode"))
edid = _parse_edid(ctx["read_bytes"](os.path.join(connector_dir, "edid")))
current_resolution = current_mode or (modes[0] if modes else "") or edid["preferred_resolution"]
refresh_rate = edid["preferred_refresh_rate"]
preferred_mode = ""
if edid["preferred_resolution"] and edid["preferred_refresh_rate"]:
preferred_mode = f"{edid['preferred_resolution']} @ {edid['preferred_refresh_rate']}"
elif edid["preferred_resolution"]:
preferred_mode = edid["preferred_resolution"]
elif modes:
preferred_mode = modes[0]
monitor_name = edid["monitor_name"] or connector
return {
"connector": connector,
"interface": interface,
"status": status,
"enabled": enabled,
"dpms": dpms,
"connected": status == "connected",
"modes": modes,
"current_resolution": current_resolution,
"refresh_rate": refresh_rate,
"preferred_mode": preferred_mode,
"monitor_name": monitor_name,
"manufacturer": edid["manufacturer"],
"product_code": edid["product_code"],
"serial": edid["serial_text"],
"physical_size": edid["size_cm"],
"diagonal": edid["diagonal"],
"edid_present": edid["present"],
"edid_raw_length": edid["raw_length"],
}
def _list_connector_dirs(ctx):
if not ctx["file_exists"](DRM_ROOT):
return []
try:
entries = sorted(os.listdir(DRM_ROOT))
except Exception:
return []
result = []
for entry in entries:
connector_dir = os.path.join(DRM_ROOT, entry)
if ctx["file_exists"](os.path.join(connector_dir, "status")):
result.append(connector_dir)
return result
def _display_details(primary):
primary = primary or {}
return [
{"label": "Interface", "value": _fallback(primary.get("interface"))},
{"label": "Monitor", "value": _fallback(primary.get("monitor_name"))},
{"label": "Manufacturer", "value": _fallback(primary.get("manufacturer"))},
{"label": "Current resolution", "value": _fallback(primary.get("current_resolution"))},
{"label": "Refresh rate", "value": _fallback(primary.get("refresh_rate"))},
{"label": "Preferred mode", "value": _fallback(primary.get("preferred_mode"))},
{"label": "Physical size", "value": _fallback(primary.get("physical_size"))},
{"label": "Diagonal", "value": _fallback(primary.get("diagonal"))},
{"label": "Serial", "value": _fallback(primary.get("serial"))},
{"label": "Product code", "value": _fallback(primary.get("product_code"))},
]
def _z2m_parse_config(ctx):
config_path = "/opt/zigbee2mqtt/data/configuration.yaml"
raw = ctx["read_text"](config_path)
port = ""
adapter = ""
if raw:
port_match = re.search(r'^\s*port:\s*["\']?([^"\'\n#]+)["\']?\s*$', raw, re.MULTILINE)
if port_match:
port = port_match.group(1).strip()
adapter_match = re.search(r'^\s*adapter:\s*["\']?([^"\'\n#]+)["\']?\s*$', raw, re.MULTILINE)
if adapter_match:
adapter = adapter_match.group(1).strip()
return {
"config_path": config_path,
"raw": raw,
"exists": bool(raw),
"port": port,
"adapter": adapter,
}
def _z2m_usb_diagnostics(ctx):
config = _z2m_parse_config(ctx)
port = config["port"]
adapter = config["adapter"]
port_exists = False
resolved_port = ""
network_port = "://" in port or port.startswith("tcp:") or port.startswith("socket:")
if port and not network_port:
port_exists = ctx["file_exists"](port)
if port_exists:
try:
resolved_port = os.path.realpath(port)
except Exception:
resolved_port = port
by_id_entries = []
by_id_path = "/dev/serial/by-id"
if os.path.isdir(by_id_path):
try:
by_id_entries = sorted(os.listdir(by_id_path))
except Exception:
by_id_entries = []
likely_by_id = [
entry for entry in by_id_entries
if re.search(r"(zigbee|sonoff|cc2652|ember|ezsp|zbdongle|nabu|slae|thirdreality|tubeszb)", entry, re.IGNORECASE)
]
rc, lsusb_out, _ = ctx["run"](["/usr/bin/lsusb"], timeout=8)
usb_lines = [line.strip() for line in lsusb_out.splitlines() if line.strip()] if rc == 0 else []
likely_usb = [
line for line in usb_lines
if re.search(r"(zigbee|sonoff|cc2652|ezsp|ember|nabu|slae|silicon labs|texas instruments|tubeszb|dongle)", line, re.IGNORECASE)
]
coordinator_present = False
reason = ""
if not config["exists"]:
reason = "configuration.yaml missing"
elif not port:
reason = "Coordinator not set in USB"
elif network_port:
coordinator_present = True
elif port_exists:
coordinator_present = True
else:
reason = "USB coordinator not found"
configured = bool(config["exists"] and port and (network_port or port_exists))
return {
"configured": configured,
"reason": reason,
"config_exists": config["exists"],
"config_path": config["config_path"],
"configured_port": port,
"configured_port_exists": port_exists,
"configured_port_resolved": resolved_port,
"adapter": adapter,
"coordinator_present": coordinator_present,
"likely_by_id_count": len(likely_by_id),
"likely_usb_count": len(likely_usb),
}
def itscreen_card(ctx):
@ -247,41 +457,35 @@ def zigbee_card(ctx):
app_footprint = ctx["any_exists"]([
"/opt/zigbee2mqtt/package.json",
"/opt/zigbee2mqtt/index.js",
"/opt/zigbee2mqtt/data",
])
unit_footprint = ctx["any_exists"]([
"/etc/systemd/system/zigbee2mqtt.service",
"/lib/systemd/system/zigbee2mqtt.service",
])
installed = bool(app_footprint or unit_footprint or unit["installed"])
has_config = _z2m_has_minimal_config()
has_coordinator = _has_any_serial_device()
configured = bool(installed and has_config and has_coordinator)
failed = bool(installed and has_config and has_coordinator and _service_failed(unit))
service_active = _strict_active(installed, configured, unit)
gateway = _probe_z2m_gateway(ctx) if installed else {"reachable": False, "summary": "not installed", "error": ""}
active = service_active
usb = _z2m_usb_diagnostics(ctx)
configured = bool(installed and usb["configured"])
active = bool(installed and configured and unit["active"])
warnings = []
errors = []
if installed and not has_config:
warnings.append("configuration.yaml missing or incomplete")
if installed and has_config and not has_coordinator:
warnings.append("Zigbee coordinator not detected")
if failed:
errors.extend(_short_unit_errors(unit))
state, status_text = _lifecycle(installed, configured, service_active, failed=failed)
errors = _short_unit_errors(unit)
if state == "active" and not gateway["reachable"]:
state = "degraded"
status_text = "UI unavailable"
warnings.append("Gateway on localhost:8081 is not serving the Zigbee2MQTT UI")
elif state == "inactive" and gateway["summary"] == "ui unavailable":
warnings.append("Gateway on localhost:8081 reports UI unavailable")
elif state == "not configured" and gateway["summary"] == "not configured":
warnings.append("Gateway on localhost:8081 reports not configured")
if gateway["error"] and state in ("degraded", "inactive"):
warnings.append(f"Gateway probe error: {gateway['error']}")
if not installed:
state = "not installed"
status_text = "Not installed"
warnings.append("Service Zigbee2MQTT not installed")
elif not configured:
state = "installed_not_configured"
status_text = "Not configured"
warnings.append(usb["reason"] or "Coordinator not set in USB")
elif unit["active_state"] == "failed":
state = "failed"
status_text = "Failed"
elif active:
state = "active"
status_text = "Active"
else:
state = "inactive"
status_text = "Inactive"
return _service_card(
"zigbee2mqtt",
@ -292,72 +496,181 @@ def zigbee_card(ctx):
active,
state,
status_text,
errors[:2],
errors,
warnings[:2],
details=[
{"label": "Coordinator", "value": usb["reason"] if not configured else "USB coordinator detected"},
{"label": "USB port", "value": usb["configured_port"] or "Not set"},
{"label": "Resolved device", "value": usb["configured_port_resolved"] or "Not available"},
{"label": "Adapter", "value": usb["adapter"] or "Auto"},
],
)
def _reverse_tunnel_unit_names():
return [item["unit"] for item in REVERSE_TUNNEL_SERVICES]
def _reverse_tunnel_key_paths(ctx):
hostname = _read_trimmed(ctx, "/etc/hostname").split(".", 1)[0]
edge_user = "iomatex"
edge_home = ""
rc, stdout, _ = ctx["run"](["getent", "passwd", edge_user])
if rc == 0 and stdout:
parts = stdout.split(":")
if len(parts) >= 6:
edge_home = parts[5].strip()
homes = []
for item in [edge_home, f"/home/{edge_user}", f"/var/lib/{edge_user}"]:
item = str(item or "").strip()
if item and item not in homes:
homes.append(item)
paths = []
for home in homes:
ssh_dir = os.path.join(home, ".ssh")
if hostname:
paths.extend([
os.path.join(ssh_dir, f"iomatex-{hostname}"),
os.path.join(ssh_dir, f"iomatex-{hostname}.pub"),
])
paths.extend([
os.path.join(ssh_dir, "id_ed25519"),
os.path.join(ssh_dir, "id_ed25519.pub"),
])
return paths
def reverse_tunnel_card(ctx):
units = [(name, ctx["systemd_unit"](service)) for name, service in _reverse_tunnel_unit_names()]
wrapper_paths = [
f"/usr/local/sbin/iomatex-rt-{name}.sh"
for name, _service in _reverse_tunnel_unit_names()
]
key_path, key_pub_path = _reverse_tunnel_key_paths()
installed = bool(
any(unit["installed"] for _name, unit in units)
or any(os.path.exists(path) for path in wrapper_paths)
or os.path.exists(key_path)
or os.path.exists(key_pub_path)
)
configured = bool(
installed
and all(unit["installed"] for _name, unit in units)
and all(os.path.exists(path) for path in wrapper_paths)
and os.path.exists(key_path)
and os.path.exists(key_pub_path)
)
active_units = [name for name, unit in units if unit["active"]]
failed_units = [(name, unit) for name, unit in units if _service_failed(unit)]
active = bool(configured and len(active_units) == len(units))
service_states = []
installed_checks = []
configured_checks = []
warnings = []
errors = []
if installed and not all(unit["installed"] for _name, unit in units):
warnings.append("One or more systemd tunnel units are missing")
if installed and not all(os.path.exists(path) for path in wrapper_paths):
warnings.append("One or more tunnel wrapper scripts are missing")
if installed and not (os.path.exists(key_path) and os.path.exists(key_pub_path)):
warnings.append("Tunnel SSH key is missing")
key_paths = _reverse_tunnel_key_paths(ctx)
key_present = any(ctx["file_exists"](path) for path in key_paths)
for item in REVERSE_TUNNEL_SERVICES:
unit = ctx["systemd_unit"](item["unit"])
unit_path = unit.get("fragment_path", "").strip()
script_path = f"/usr/local/sbin/iomatex-rt-{item['name']}.sh"
unit_file_candidates = [
unit_path,
f"/etc/systemd/system/{item['unit']}",
f"/lib/systemd/system/{item['unit']}",
]
has_unit = any(path and ctx["file_exists"](path) for path in unit_file_candidates) or unit["installed"]
has_script = ctx["file_exists"](script_path)
is_active = unit["active"]
installed_checks.append(has_unit or has_script)
configured_checks.append(has_script and key_present)
service_states.append({
"name": item["name"],
"unit": item["unit"],
"local_port": item["local_port"],
"installed": has_unit or has_script,
"configured": has_script and key_present,
"active": is_active,
"active_state": unit["active_state"],
})
if has_unit and has_script and not is_active:
warnings.append(f"{item['name']} tunnel inactive")
if unit["active_state"] == "failed":
errors.append(f"{item['name']} tunnel failed")
installed = any(installed_checks)
configured = all(configured_checks) if installed else False
active_count = sum(1 for item in service_states if item["active"])
total = len(service_states)
active = active_count == total and total > 0
if not installed:
state, status_text = _lifecycle(False, False, False)
elif not configured:
state, status_text = "not configured", "Not configured"
elif failed_units:
state, status_text = "failed", "Failed"
for name, unit in failed_units:
errors.append(f"{name}: {(_short_unit_errors(unit) or ['Service failed'])[0]}")
state = "not installed"
status_text = "Not installed"
elif active:
state, status_text = "active", "Active"
elif active_units:
state, status_text = "degraded", "Degraded"
warnings.append(f"Active tunnels: {', '.join(active_units)}")
state = "active"
status_text = "Active"
elif active_count > 0:
state = "degraded"
status_text = f"Partial ({active_count}/{total})"
elif configured:
state = "inactive"
status_text = "Inactive"
else:
state, status_text = "inactive", "Inactive"
state = "installed_not_configured"
status_text = "Not configured"
if installed and not key_present:
warnings.append("Reverse tunnel SSH key not found")
warnings.extend(
f"{item['name']} -> 127.0.0.1:{item['local_port']}"
for item in service_states
if item["installed"] and not item["active"]
)
return _service_card(
"reverse_tunnel",
"Reverse Tunnel",
"iomatex-rt-*.service",
",".join(_reverse_tunnel_unit_names()),
installed,
configured,
active,
state,
status_text,
errors[:2],
warnings[:3],
)
def display_card(ctx):
connector_dirs = _list_connector_dirs(ctx)
connectors = [_read_connector(ctx, path) for path in connector_dirs]
connected = [item for item in connectors if item["connected"]]
connected.sort(key=_connector_priority, reverse=True)
primary = connected[0] if connected else {}
drm_available = bool(ctx["file_exists"](DRM_ROOT))
active = bool(primary)
interface = primary.get("interface", "")
connector_name = primary.get("connector", "")
if active:
status_text = f"Monitor connected by {interface or connector_name or 'display'}"
state = "active"
else:
status_text = "Monitor is not connected"
state = "inactive" if drm_available else "unavailable"
warnings = []
if not drm_available:
warnings.append("DRM sysfs is not available")
elif connectors and not active:
warnings.append("No active DRM connector detected")
return _service_card(
"display",
"Display",
"",
True,
drm_available,
active,
state,
status_text,
[],
warnings[:2],
details=_display_details(primary),
connectors=connectors,
display_status={
"connected": active,
"interface": interface,
"connector": connector_name,
"monitor_name": primary.get("monitor_name", ""),
"manufacturer": primary.get("manufacturer", ""),
},
)
@ -384,6 +697,6 @@ def get_cards(ctx):
mqtt_bridge_card(ctx),
zigbee_card(ctx),
reverse_tunnel_card(ctx),
placeholder_card("display", "Display"),
display_card(ctx),
placeholder_card("edge_api", "Edge API"),
]

View File

@ -11,100 +11,151 @@ if grep -q $'\r' "$0" 2>/dev/null; then
fi
need_root() {
[ "$(id -u)" -eq 0 ] || { echo "Run as root: sudo bash $0"; exit 1; }
[ "$(id -u)" -eq 0 ] || {
echo "Run as root: sudo bash $0" >&2
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
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CORE_DIR="${SCRIPT_DIR}/console_core"
SRC_ROOT="${SCRIPT_DIR}/console_core"
APP_DIR="/opt/iomatex-console"
BACKEND_DIR="${APP_DIR}/backend"
PUBLIC_DIR="${APP_DIR}/public"
BACKEND_DIR="${APP_DIR}/backend"
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"
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}"
ts="$(date +%s)"
PREV_DIR="${APP_DIR}.prev.${ts}"
LEGACY_APP_DIR="/opt/iomatex-process1-webipc"
LEGACY_PREV_DIR="${LEGACY_APP_DIR}.prev.${ts}"
log "Install lightweight Console core dependencies"
copy_tree() {
local src="$1"
local dst="$2"
mkdir -p "$dst"
cp -a "${src}/." "$dst/"
}
echo "[0/8] Validate source tree"
for path in \
"$SRC_ROOT/backend/app.py" \
"$SRC_ROOT/frontend/index.html" \
"$SRC_ROOT/frontend/console.js" \
"$SRC_ROOT/frontend/console.css" \
"$SRC_ROOT/providers/00_core_services.py"; do
[ -f "$path" ] || {
echo "ERROR: required source file is missing: $path" >&2
exit 1
}
done
echo "[1/8] Ensure runtime packages exist"
apt-get update
apt-get install -y python3
apt-get install -y python3 python3-pil
python3 --version
log "Prepare directories"
mkdir -p "$BACKEND_DIR" "$PUBLIC_DIR" "$PROVIDERS_DIR" "$CONFIG_DIR"
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
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
echo "[3/8] Prepare directories and preserve previous install"
mkdir -p /etc/iomatex
if [ -d "$APP_DIR" ]; then
rm -rf "$PREV_DIR"
mv "$APP_DIR" "$PREV_DIR"
fi
if [ -d "$LEGACY_APP_DIR" ]; then
rm -rf "$LEGACY_PREV_DIR"
mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR"
fi
mkdir -p "$APP_DIR" "$PUBLIC_DIR" "$BACKEND_DIR" "$PROVIDERS_DIR"
if [ ! -f "$CONFIG_PATH" ]; then
log "Write default config"
cat >"$CONFIG_PATH" <<'JSON'
if [ ! -f "$CFG_PATH" ]; then
cat > "$CFG_PATH" <<JSON
{
"bind": "0.0.0.0",
"port": 8099,
"bind": "${APP_BIND}",
"port": ${APP_PORT},
"cache_ttl_sec": 3
}
JSON
chmod 0644 "$CONFIG_PATH"
fi
log "Write systemd unit"
cat >"$SYSTEMD_UNIT" <<'EOF'
echo "[4/8] Install console core files"
copy_tree "$SRC_ROOT/backend" "$BACKEND_DIR"
install -m 0644 "$SRC_ROOT/frontend/index.html" "$PUBLIC_DIR/index.html"
install -m 0644 "$SRC_ROOT/frontend/console.js" "$PUBLIC_DIR/console.js"
install -m 0644 "$SRC_ROOT/frontend/console.css" "$PUBLIC_DIR/console.css"
copy_tree "$SRC_ROOT/providers" "$PROVIDERS_DIR"
rm -rf "$PROVIDERS_DIR/__pycache__" "$BACKEND_DIR/__pycache__"
echo "[5/8] Generate logo and favicon"
if [ ! -f "$SRC_LOGO" ]; then
echo "ERROR: logo source image not found: $SRC_LOGO" >&2
exit 1
fi
python3 - "$SRC_LOGO" "$PUBLIC_DIR/logo.png" "$PUBLIC_DIR/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")
PY
echo "[6/8] Install systemd service"
cat > "/etc/systemd/system/${SERVICE_NAME}" <<UNIT
[Unit]
Description=IOMATEX Console
Description=IOMATEX Console Core
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/iomatex-console/backend/app.py
WorkingDirectory=${APP_DIR}
ExecStart=/usr/bin/python3 ${BACKEND_DIR}/app.py
Restart=always
RestartSec=2
User=root
Group=root
[Install]
WantedBy=multi-user.target
EOF
chmod 0644 "$SYSTEMD_UNIT"
UNIT
log "Reload and restart Console service"
echo "[7/8] Validate and restart"
python3 -m py_compile "$BACKEND_DIR/app.py" "$PROVIDERS_DIR/00_core_services.py"
systemctl daemon-reload
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
systemctl enable --now "${SERVICE_NAME}"
cat <<EOF
IOMATEX Console installed.
Path : ${APP_DIR}
URL : http://127.0.0.1:8099/
Service : ${SERVICE_NAME}
Config : ${CONFIG_PATH}
Providers : ${PROVIDERS_DIR}
Legacy ref : ${SCRIPT_DIR}/legacy_reference
EOF
echo "[8/8] Summary"
echo "Web UI: http://<EDGE-IP>:${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"
echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40"
echo "Install dir: ${APP_DIR}"
echo "Providers dir: ${PROVIDERS_DIR}"
echo "Public dir: ${PUBLIC_DIR}"
echo "Config: ${CFG_PATH}"
echo "Previous install backup: ${PREV_DIR}"
echo "Legacy backup: ${LEGACY_PREV_DIR}"