
-
+
IOMATEX
Console
+
host: -
Lightweight diagnostics for installed services.
-
Edge: unknown
diff --git a/stage_ui/console_core/providers/00_core_services.py b/stage_ui/console_core/providers/00_core_services.py
index 387ab7a..8f540d6 100644
--- a/stage_ui/console_core/providers/00_core_services.py
+++ b/stage_ui/console_core/providers/00_core_services.py
@@ -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"),
]
diff --git a/stage_ui/ui_installer.sh b/stage_ui/ui_installer.sh
index a43b176..bc82557 100644
--- a/stage_ui/ui_installer.sh
+++ b/stage_ui/ui_installer.sh
@@ -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" <"$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}" </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 <:${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}"