Add stage_ui console core and legacy reference
This commit is contained in:
parent
074ed3f201
commit
582c30d03d
|
|
@ -0,0 +1,17 @@
|
||||||
|
# IOMATEX Console Architecture
|
||||||
|
|
||||||
|
## Core responsibilities
|
||||||
|
- Serve one fast local diagnostics UI.
|
||||||
|
- Expose one normalized status endpoint: `/api/status`.
|
||||||
|
- Load provider modules from `providers.d`.
|
||||||
|
- Cache recent status briefly to avoid repeated shell work on every page render.
|
||||||
|
|
||||||
|
## Addon responsibilities
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
## Future `ui_backend` role
|
||||||
|
- 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.
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,351 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
import glob
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
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")
|
||||||
|
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
||||||
|
CONFIG_PATH = "/etc/iomatex/console.json"
|
||||||
|
|
||||||
|
DEFAULT_CONFIG = {
|
||||||
|
"bind": "0.0.0.0",
|
||||||
|
"port": 8099,
|
||||||
|
"cache_ttl_sec": 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
_CACHE = {"expires_at": 0.0, "payload": None}
|
||||||
|
|
||||||
|
|
||||||
|
def load_config():
|
||||||
|
data = dict(DEFAULT_CONFIG)
|
||||||
|
try:
|
||||||
|
with open(CONFIG_PATH, "r", encoding="utf-8") as fh:
|
||||||
|
loaded = json.load(fh)
|
||||||
|
if isinstance(loaded, dict):
|
||||||
|
data.update(loaded)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def run(cmd, timeout=4):
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
cmd,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
timeout=timeout,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
return proc.returncode, (proc.stdout or "").strip(), (proc.stderr or "").strip()
|
||||||
|
except Exception as exc:
|
||||||
|
return 1, "", str(exc)
|
||||||
|
|
||||||
|
|
||||||
|
def file_exists(path):
|
||||||
|
return os.path.exists(path)
|
||||||
|
|
||||||
|
|
||||||
|
def any_exists(paths):
|
||||||
|
return any(os.path.exists(path) for path in paths)
|
||||||
|
|
||||||
|
|
||||||
|
def read_text(path):
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8", errors="ignore") as fh:
|
||||||
|
return fh.read()
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def read_env_file(path):
|
||||||
|
data = {}
|
||||||
|
try:
|
||||||
|
with open(path, "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)
|
||||||
|
value = value.strip().strip('"').strip("'")
|
||||||
|
data[key.strip()] = value
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
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",
|
||||||
|
"ActiveState",
|
||||||
|
"SubState",
|
||||||
|
"UnitFileState",
|
||||||
|
"Result",
|
||||||
|
"ExecMainStatus",
|
||||||
|
"FragmentPath",
|
||||||
|
]
|
||||||
|
cmd = ["systemctl", "show", unit_name, "--no-page"]
|
||||||
|
for prop in properties:
|
||||||
|
cmd.extend(["-p", prop])
|
||||||
|
rc, stdout, stderr = run(cmd)
|
||||||
|
data = {
|
||||||
|
"unit": unit_name,
|
||||||
|
"load_state": "not-found",
|
||||||
|
"active_state": "inactive",
|
||||||
|
"sub_state": "dead",
|
||||||
|
"unit_file_state": "unknown",
|
||||||
|
"result": "",
|
||||||
|
"exec_main_status": "",
|
||||||
|
"fragment_path": "",
|
||||||
|
"installed": False,
|
||||||
|
"active": False,
|
||||||
|
"raw_error": stderr if rc != 0 else "",
|
||||||
|
}
|
||||||
|
if stdout:
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
if "=" not in line:
|
||||||
|
continue
|
||||||
|
key, value = line.split("=", 1)
|
||||||
|
key = key.strip()
|
||||||
|
value = value.strip()
|
||||||
|
if key == "LoadState":
|
||||||
|
data["load_state"] = value or "not-found"
|
||||||
|
elif key == "ActiveState":
|
||||||
|
data["active_state"] = value or "inactive"
|
||||||
|
elif key == "SubState":
|
||||||
|
data["sub_state"] = value or "dead"
|
||||||
|
elif key == "UnitFileState":
|
||||||
|
data["unit_file_state"] = value or "unknown"
|
||||||
|
elif key == "Result":
|
||||||
|
data["result"] = value
|
||||||
|
elif key == "ExecMainStatus":
|
||||||
|
data["exec_main_status"] = value
|
||||||
|
elif key == "FragmentPath":
|
||||||
|
data["fragment_path"] = value
|
||||||
|
data["installed"] = data["load_state"] != "not-found" or bool(data["fragment_path"])
|
||||||
|
data["active"] = data["active_state"] == "active"
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_card(card):
|
||||||
|
item = dict(card)
|
||||||
|
item.setdefault("id", "unknown")
|
||||||
|
item.setdefault("title", item["id"])
|
||||||
|
item["installed"] = bool(item.get("installed", False))
|
||||||
|
item["configured"] = bool(item.get("configured", False))
|
||||||
|
item["active"] = bool(item.get("active", False))
|
||||||
|
item["state"] = str(item.get("state", "unknown"))
|
||||||
|
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()]
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def load_providers():
|
||||||
|
providers = []
|
||||||
|
for path in sorted(glob.glob(os.path.join(PROVIDERS_DIR, "*.py"))):
|
||||||
|
name = "provider_" + os.path.basename(path).replace(".", "_")
|
||||||
|
spec = importlib.util.spec_from_file_location(name, path)
|
||||||
|
if not spec or not spec.loader:
|
||||||
|
continue
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
try:
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if hasattr(module, "get_cards"):
|
||||||
|
providers.append((path, module.get_cards))
|
||||||
|
return providers
|
||||||
|
|
||||||
|
|
||||||
|
def build_status_payload():
|
||||||
|
now = time.time()
|
||||||
|
cfg = load_config()
|
||||||
|
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||||
|
return _CACHE["payload"]
|
||||||
|
|
||||||
|
context = {
|
||||||
|
"file_exists": file_exists,
|
||||||
|
"any_exists": any_exists,
|
||||||
|
"read_text": read_text,
|
||||||
|
"read_env_file": read_env_file,
|
||||||
|
"systemd_unit": systemd_unit,
|
||||||
|
"http_probe": http_probe,
|
||||||
|
}
|
||||||
|
cards = []
|
||||||
|
provider_names = []
|
||||||
|
for path, provider in load_providers():
|
||||||
|
provider_names.append(os.path.basename(path))
|
||||||
|
try:
|
||||||
|
result = provider(context)
|
||||||
|
except Exception as exc:
|
||||||
|
result = [{
|
||||||
|
"id": os.path.splitext(os.path.basename(path))[0],
|
||||||
|
"title": os.path.basename(path),
|
||||||
|
"installed": False,
|
||||||
|
"configured": False,
|
||||||
|
"active": False,
|
||||||
|
"state": "error",
|
||||||
|
"status_text": "Provider error",
|
||||||
|
"errors": [str(exc)],
|
||||||
|
"warnings": [],
|
||||||
|
}]
|
||||||
|
if isinstance(result, dict):
|
||||||
|
result = [result]
|
||||||
|
for card in result or []:
|
||||||
|
cards.append(normalize_card(card))
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||||
|
"edge": detect_edge_identity(),
|
||||||
|
"services": cards,
|
||||||
|
"providers": provider_names,
|
||||||
|
}
|
||||||
|
_CACHE["payload"] = payload
|
||||||
|
_CACHE["expires_at"] = now + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, fmt, *args):
|
||||||
|
return
|
||||||
|
|
||||||
|
def send_json(self, payload, code=200):
|
||||||
|
body = json.dumps(payload, indent=2).encode("utf-8")
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def send_file(self, path, content_type):
|
||||||
|
try:
|
||||||
|
with open(path, "rb") as fh:
|
||||||
|
data = fh.read()
|
||||||
|
except FileNotFoundError:
|
||||||
|
self.send_error(404)
|
||||||
|
return
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", content_type)
|
||||||
|
self.send_header("Content-Length", str(len(data)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(data)
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
parsed = urlparse(self.path)
|
||||||
|
if parsed.path == "/api/status":
|
||||||
|
self.send_json(build_status_payload())
|
||||||
|
return
|
||||||
|
if parsed.path in ("/", "/index.html"):
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8")
|
||||||
|
return
|
||||||
|
if parsed.path == "/console.css":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8")
|
||||||
|
return
|
||||||
|
if parsed.path == "/console.js":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8")
|
||||||
|
return
|
||||||
|
if parsed.path == "/logo.png":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png")
|
||||||
|
return
|
||||||
|
if parsed.path == "/favicon.png":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "favicon.png"), "image/png")
|
||||||
|
return
|
||||||
|
self.send_error(404)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
cfg = load_config()
|
||||||
|
bind = str(cfg.get("bind", DEFAULT_CONFIG["bind"]))
|
||||||
|
port = int(cfg.get("port", DEFAULT_CONFIG["port"]))
|
||||||
|
server = ThreadingHTTPServer((bind, port), Handler)
|
||||||
|
print(f"[console] http://{bind}:{port}", file=sys.stderr)
|
||||||
|
server.serve_forever()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,80 @@
|
||||||
|
:root{
|
||||||
|
--bg:#eef2f0;
|
||||||
|
--panel:#ffffff;
|
||||||
|
--ink:#16211d;
|
||||||
|
--muted:#66736d;
|
||||||
|
--line:#d7e0db;
|
||||||
|
--accent:#0e7a53;
|
||||||
|
--warn:#9a6a00;
|
||||||
|
--error:#b93434;
|
||||||
|
--shadow:0 12px 32px rgba(16,24,20,.08);
|
||||||
|
}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{
|
||||||
|
margin:0;
|
||||||
|
font-family:system-ui,-apple-system,"Segoe UI",sans-serif;
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at top left, rgba(14,122,83,.10), transparent 32%),
|
||||||
|
linear-gradient(180deg, #f7faf8 0%, var(--bg) 100%);
|
||||||
|
color:var(--ink);
|
||||||
|
}
|
||||||
|
.shell{max-width:1100px;margin:0 auto;padding:28px 18px 40px}
|
||||||
|
.hero{
|
||||||
|
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}
|
||||||
|
.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;
|
||||||
|
}
|
||||||
|
.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}
|
||||||
|
.actions button{
|
||||||
|
border:0;border-radius:999px;background:var(--ink);color:#fff;padding:12px 18px;font-weight:700;cursor:pointer;
|
||||||
|
box-shadow:var(--shadow);
|
||||||
|
}
|
||||||
|
.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;
|
||||||
|
}
|
||||||
|
.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;
|
||||||
|
}
|
||||||
|
.card{padding:18px}
|
||||||
|
.cardTop{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
|
||||||
|
.card h2{margin:0;font-size:19px}
|
||||||
|
.badge{
|
||||||
|
display:inline-flex;align-items:center;gap:8px;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:700;
|
||||||
|
background:#edf4f0;color:var(--ink);
|
||||||
|
}
|
||||||
|
.dot{width:9px;height:9px;border-radius:50%}
|
||||||
|
.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}
|
||||||
|
.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}
|
||||||
|
.pillRow{display:flex;gap:8px;flex-wrap:wrap}
|
||||||
|
.pill{
|
||||||
|
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;background:#f5f7f6;color:var(--ink);
|
||||||
|
}
|
||||||
|
.pill.good{background:rgba(14,122,83,.10);color:var(--accent)}
|
||||||
|
.pill.bad{background:rgba(185,52,52,.10);color:var(--error)}
|
||||||
|
.msgList{margin:8px 0 0;padding-left:18px;color:var(--muted)}
|
||||||
|
.empty{
|
||||||
|
padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center;
|
||||||
|
}
|
||||||
|
@media (max-width:720px){
|
||||||
|
.summary{grid-template-columns:1fr}
|
||||||
|
.meta{grid-template-columns:1fr 1fr}
|
||||||
|
.brand{align-items:flex-start}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,115 @@
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const nodes = {
|
||||||
|
refreshBtn: document.getElementById("refreshBtn"),
|
||||||
|
cards: document.getElementById("cards"),
|
||||||
|
lastUpdate: document.getElementById("lastUpdate"),
|
||||||
|
providerCount: document.getElementById("providerCount"),
|
||||||
|
serviceCount: document.getElementById("serviceCount"),
|
||||||
|
edgeName: document.getElementById("edgeName")
|
||||||
|
};
|
||||||
|
|
||||||
|
function esc(value) {
|
||||||
|
return (value ?? "").toString().replace(/[&<>"']/g, (m) => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
"\"": """,
|
||||||
|
"'": "'"
|
||||||
|
}[m]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function boolPill(label, value) {
|
||||||
|
return `<span class="pill ${value ? "good" : "bad"}">${esc(label)}: ${value ? "yes" : "no"}</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
const tone = statusTone(card);
|
||||||
|
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
|
||||||
|
const errors = Array.isArray(card.errors) ? card.errors : [];
|
||||||
|
|
||||||
|
return `
|
||||||
|
<article class="panel card">
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<div class="meta">
|
||||||
|
<div class="key">ID</div><div>${esc(card.id)}</div>
|
||||||
|
<div class="key">State</div><div>${esc(card.state || "-")}</div>
|
||||||
|
<div class="key">Status</div><div>${esc(card.status_text || "-")}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="list">
|
||||||
|
<div class="listTitle">Flags</div>
|
||||||
|
<div class="pillRow">
|
||||||
|
${boolPill("Installed", !!card.installed)}
|
||||||
|
${boolPill("Configured", !!card.configured)}
|
||||||
|
${boolPill("Active", !!card.active)}
|
||||||
|
</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 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.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>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes.cards.innerHTML = services.map(renderCard).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
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);
|
||||||
|
} catch (error) {
|
||||||
|
nodes.cards.innerHTML = `<div class="empty">Failed to load status: ${esc(error.message || String(error))}</div>`;
|
||||||
|
} finally {
|
||||||
|
nodes.refreshBtn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes.refreshBtn.addEventListener("click", load);
|
||||||
|
load();
|
||||||
|
})();
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>IOMATEX Console</title>
|
||||||
|
<link rel="icon" type="image/png" href="/favicon.png">
|
||||||
|
<link rel="stylesheet" href="/console.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="shell">
|
||||||
|
<header class="hero">
|
||||||
|
<div class="brand">
|
||||||
|
<img class="brandLogo" src="/logo.png" alt="IOMATEX logo">
|
||||||
|
<div>
|
||||||
|
<div class="eyebrow">IOMATEX</div>
|
||||||
|
<h1>Console</h1>
|
||||||
|
<p class="sub">Lightweight diagnostics for installed services.</p>
|
||||||
|
<p class="edgeName" id="edgeName">Edge: unknown</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button id="refreshBtn" type="button">Refresh</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="panel summary">
|
||||||
|
<div class="summaryItem">
|
||||||
|
<span class="label">Last update</span>
|
||||||
|
<strong id="lastUpdate">-</strong>
|
||||||
|
</div>
|
||||||
|
<div class="summaryItem">
|
||||||
|
<span class="label">Providers</span>
|
||||||
|
<strong id="providerCount">-</strong>
|
||||||
|
</div>
|
||||||
|
<div class="summaryItem">
|
||||||
|
<span class="label">Cards</span>
|
||||||
|
<strong id="serviceCount">-</strong>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="cards" class="cards" aria-live="polite"></section>
|
||||||
|
</main>
|
||||||
|
<script src="/console.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -0,0 +1,389 @@
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import pwd
|
||||||
|
|
||||||
|
|
||||||
|
def _service_card(service_id, title, unit_name, installed, configured, active, state, status_text, errors=None, warnings=None):
|
||||||
|
return {
|
||||||
|
"id": service_id,
|
||||||
|
"title": title,
|
||||||
|
"installed": installed,
|
||||||
|
"configured": configured,
|
||||||
|
"active": active,
|
||||||
|
"state": state,
|
||||||
|
"status_text": status_text,
|
||||||
|
"errors": errors or [],
|
||||||
|
"warnings": warnings or [],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _short_unit_errors(unit):
|
||||||
|
errors = []
|
||||||
|
if unit["active_state"] == "failed":
|
||||||
|
errors.append("Service failed")
|
||||||
|
if unit["result"] and unit["result"] not in ("success", "done"):
|
||||||
|
errors.append(f"Result: {unit['result']}")
|
||||||
|
if unit["exec_main_status"] and unit["exec_main_status"] not in ("0", ""):
|
||||||
|
errors.append(f"Exit status: {unit['exec_main_status']}")
|
||||||
|
if unit["raw_error"]:
|
||||||
|
errors.append(unit["raw_error"])
|
||||||
|
return errors[:2]
|
||||||
|
|
||||||
|
|
||||||
|
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 failed:
|
||||||
|
return "failed", "Failed"
|
||||||
|
return "inactive", "Inactive"
|
||||||
|
|
||||||
|
|
||||||
|
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 _find_first_existing(paths):
|
||||||
|
for path in paths:
|
||||||
|
if os.path.exists(path):
|
||||||
|
return path
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _read_text(path):
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8", errors="ignore") as fh:
|
||||||
|
return fh.read()
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
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 itscreen_card(ctx):
|
||||||
|
unit = ctx["systemd_unit"]("itscreen-x11.service")
|
||||||
|
installed = ctx["any_exists"]([
|
||||||
|
"/opt/itscreen/bin/itscreen",
|
||||||
|
"/etc/systemd/system/itscreen-x11.service",
|
||||||
|
"/lib/systemd/system/itscreen-x11.service",
|
||||||
|
])
|
||||||
|
configured = ctx["any_exists"]([
|
||||||
|
"/etc/systemd/system/itscreen-x11.service",
|
||||||
|
"/lib/systemd/system/itscreen-x11.service",
|
||||||
|
])
|
||||||
|
warnings = []
|
||||||
|
if installed and not configured:
|
||||||
|
warnings.append("Service unit not found")
|
||||||
|
active = _strict_active(installed, configured, unit)
|
||||||
|
state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed")
|
||||||
|
return _service_card(
|
||||||
|
"itscreen",
|
||||||
|
"IT-Screen App",
|
||||||
|
"itscreen-x11.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
_short_unit_errors(unit),
|
||||||
|
warnings,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def mosquitto_card(ctx):
|
||||||
|
unit = ctx["systemd_unit"]("mosquitto.service")
|
||||||
|
installed = ctx["any_exists"]([
|
||||||
|
"/etc/mosquitto/mosquitto.conf",
|
||||||
|
"/lib/systemd/system/mosquitto.service",
|
||||||
|
"/etc/systemd/system/mosquitto.service",
|
||||||
|
])
|
||||||
|
configured = ctx["file_exists"]("/etc/mosquitto/mosquitto.conf")
|
||||||
|
warnings = []
|
||||||
|
if installed and not configured:
|
||||||
|
warnings.append("Main config missing")
|
||||||
|
active = _strict_active(installed, configured, unit)
|
||||||
|
state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed")
|
||||||
|
return _service_card(
|
||||||
|
"mosquitto",
|
||||||
|
"Mosquitto MQTT",
|
||||||
|
"mosquitto.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
_short_unit_errors(unit),
|
||||||
|
warnings,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def mqtt_bridge_card(ctx):
|
||||||
|
env = ctx["read_env_file"]("/etc/iomatex/mqtt_bridge.env")
|
||||||
|
installed = ctx["any_exists"]([
|
||||||
|
"/etc/iomatex/mqtt_bridge.env",
|
||||||
|
"/usr/local/sbin/iomatex-mqtt-apply",
|
||||||
|
"/etc/systemd/system/iomatex-mqtt-bridge.service",
|
||||||
|
])
|
||||||
|
enabled = str(env.get("ENABLE_BRIDGE", "0")).strip() == "1"
|
||||||
|
configured = bool(env.get("REMOTE_HOST", "").strip())
|
||||||
|
bridge_service = ctx["systemd_unit"]("iomatex-mqtt-bridge.service")
|
||||||
|
bridge_path = ctx["systemd_unit"]("iomatex-mqtt-bridge.path")
|
||||||
|
active = bool(bridge_service["active"] or bridge_path["active"])
|
||||||
|
warnings = []
|
||||||
|
errors = []
|
||||||
|
if installed and not enabled:
|
||||||
|
warnings.append("Bridge disabled")
|
||||||
|
if installed and enabled and not configured:
|
||||||
|
errors.append("REMOTE_HOST is empty")
|
||||||
|
state, status_text = _lifecycle(installed, configured, active)
|
||||||
|
if installed and configured and not active and not enabled:
|
||||||
|
status_text = "Disabled"
|
||||||
|
return _service_card(
|
||||||
|
"mqtt_bridge",
|
||||||
|
"MQTT Bridge",
|
||||||
|
"iomatex-mqtt-bridge.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
errors[:2],
|
||||||
|
warnings[:2],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def zigbee_card(ctx):
|
||||||
|
unit = ctx["systemd_unit"]("zigbee2mqtt.service")
|
||||||
|
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
|
||||||
|
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)
|
||||||
|
|
||||||
|
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']}")
|
||||||
|
|
||||||
|
return _service_card(
|
||||||
|
"zigbee2mqtt",
|
||||||
|
"Zigbee2MQTT",
|
||||||
|
"zigbee2mqtt.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
errors[:2],
|
||||||
|
warnings[:2],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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))
|
||||||
|
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")
|
||||||
|
|
||||||
|
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]}")
|
||||||
|
elif active:
|
||||||
|
state, status_text = "active", "Active"
|
||||||
|
elif active_units:
|
||||||
|
state, status_text = "degraded", "Degraded"
|
||||||
|
warnings.append(f"Active tunnels: {', '.join(active_units)}")
|
||||||
|
else:
|
||||||
|
state, status_text = "inactive", "Inactive"
|
||||||
|
|
||||||
|
return _service_card(
|
||||||
|
"reverse_tunnel",
|
||||||
|
"Reverse Tunnel",
|
||||||
|
"iomatex-rt-*.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
errors[:2],
|
||||||
|
warnings[:2],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def placeholder_card(service_id, title):
|
||||||
|
state, status_text = _lifecycle(False, False, False)
|
||||||
|
return _service_card(
|
||||||
|
service_id,
|
||||||
|
title,
|
||||||
|
"",
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_cards(ctx):
|
||||||
|
return [
|
||||||
|
itscreen_card(ctx),
|
||||||
|
mosquitto_card(ctx),
|
||||||
|
mqtt_bridge_card(ctx),
|
||||||
|
zigbee_card(ctx),
|
||||||
|
reverse_tunnel_card(ctx),
|
||||||
|
placeholder_card("display", "Display"),
|
||||||
|
placeholder_card("edge_api", "Edge API"),
|
||||||
|
]
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Legacy UI Reference
|
||||||
|
|
||||||
|
These files preserve the previous WebIPC-based UI implementation as reference only:
|
||||||
|
|
||||||
|
- `ui_installer.sh`
|
||||||
|
- `ui_addon_itscreen.sh`
|
||||||
|
- `ui_addon_display.sh`
|
||||||
|
|
||||||
|
The new `stage_ui/ui_installer.sh` installs the lightweight Console core instead of the legacy Node/Express UI.
|
||||||
|
|
@ -0,0 +1,207 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
APP="/opt/iomatex-process1-webipc"
|
||||||
|
ADDON_FRONT="$APP/public/addons"
|
||||||
|
SERVICE="iomatex-webipc.service"
|
||||||
|
|
||||||
|
echo "[1/4] prepare dirs"
|
||||||
|
mkdir -p "$ADDON_FRONT"
|
||||||
|
|
||||||
|
echo "[2/4] write x11 addon"
|
||||||
|
cat > "$ADDON_FRONT/x11.js" <<'JS'
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
if (window.__iomatexX11AddonLoaded) return;
|
||||||
|
window.__iomatexX11AddonLoaded = true;
|
||||||
|
|
||||||
|
const ui = window.IOMATEX_UI;
|
||||||
|
if (!ui) return;
|
||||||
|
|
||||||
|
const state = ui.state;
|
||||||
|
|
||||||
|
state.x11Addon = state.x11Addon || {
|
||||||
|
data: null,
|
||||||
|
busy: { refresh: false },
|
||||||
|
message: ""
|
||||||
|
};
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return (s ?? "").toString().replace(/[&<>"']/g, m => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
'"': """,
|
||||||
|
"'": "'"
|
||||||
|
}[m]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBusy(key, v) {
|
||||||
|
state.x11Addon.busy[key] = !!v;
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMsg(msg) {
|
||||||
|
state.x11Addon.message = (msg || "").toString();
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function btn(label, kind, fnName, busyKey, busyLabel) {
|
||||||
|
const busy = !!state.x11Addon.busy[busyKey];
|
||||||
|
return `<button class="${kind || ""}" ${busy ? "disabled" : ""} onclick="${busy ? "return false" : fnName}">${esc(busy ? busyLabel : label)}</button>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDisplay() {
|
||||||
|
const j = await ui.call("/api/display/hdmi");
|
||||||
|
state.x11Addon.data = j;
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshDisplay() {
|
||||||
|
setBusy("refresh", true);
|
||||||
|
setMsg("Refreshing display information...");
|
||||||
|
try {
|
||||||
|
await ui.loadDetail("x11").catch(() => {});
|
||||||
|
await loadDisplay();
|
||||||
|
setMsg("Display information updated.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("refresh", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderConnector(c) {
|
||||||
|
return `
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">${esc(c.edid?.monitor_name || c.connector || "Connector")}</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Connector</div><b class="mono">${esc(c.connector || "-")}</b>
|
||||||
|
<div>Type</div><b class="mono">${esc(c.kind || "-")}</b>
|
||||||
|
<div>Status</div><b class="mono">${esc(c.status || "-")}</b>
|
||||||
|
<div>Connected</div><b class="mono">${esc(c.connected ? "yes" : "no")}</b>
|
||||||
|
<div>Enabled</div><b class="mono">${esc(c.enabled || "-")}</b>
|
||||||
|
<div>DPMS</div><b class="mono">${esc(c.dpms || "-")}</b>
|
||||||
|
<div>Preferred mode</div><b class="mono">${esc(c.preferred_mode || "-")}</b>
|
||||||
|
<div>Modes</div><b class="mono">${esc((c.modes || []).join(", ") || "-")}</b>
|
||||||
|
<div>Monitor</div><b class="mono">${esc(c.edid?.monitor_name || "-")}</b>
|
||||||
|
<div>Vendor</div><b class="mono">${esc(c.edid?.manufacturer_id || "-")}</b>
|
||||||
|
<div>Product code</div><b class="mono">${esc(c.edid?.product_code || "-")}</b>
|
||||||
|
<div>Serial</div><b class="mono">${esc(c.edid?.serial_text || "-")}</b>
|
||||||
|
<div>Size</div><b class="mono">${esc(c.edid?.size_cm || "-")}</b>
|
||||||
|
<div>Diagonal</div><b class="mono">${esc(c.edid?.size_inch || "-")}</b>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderX11Detail(service) {
|
||||||
|
const d = state.x11Addon.data || {};
|
||||||
|
const sum = d.summary || {};
|
||||||
|
const first = sum.first_connected_hdmi || null;
|
||||||
|
const connectors = Array.isArray(d.connectors) ? d.connectors : [];
|
||||||
|
const connected = connectors.filter(x => x.connected);
|
||||||
|
const hdmi = Array.isArray(d.hdmi) ? d.hdmi : [];
|
||||||
|
const status = service.status || {};
|
||||||
|
|
||||||
|
document.getElementById("viewTitle").textContent = service.title || "Display";
|
||||||
|
document.getElementById("viewSub").textContent = service.desc || "";
|
||||||
|
document.getElementById("viewActions").innerHTML =
|
||||||
|
`<button class="primary" onclick="window.__x11Refresh()">Refresh</button>`;
|
||||||
|
|
||||||
|
document.getElementById("view").innerHTML = `
|
||||||
|
<div class="stack">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Display summary</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Active</div><b class="mono">${esc(status.active || "-")}</b>
|
||||||
|
<div>Started</div><b class="mono">${esc(status.started_at || "-")}</b>
|
||||||
|
<div>State</div><b class="mono">${esc(status.summary || "-")}</b>
|
||||||
|
<div>Running</div><b class="mono">${esc(status.running_for_text || "-")}</b>
|
||||||
|
<div>HDMI connected</div><b class="mono">${esc(sum.hdmi_connected ? "yes" : "no")}</b>
|
||||||
|
<div>Connected displays</div><b class="mono">${esc(String(sum.connected_count ?? 0))}</b>
|
||||||
|
<div>Connected HDMI</div><b class="mono">${esc(String(sum.connected_hdmi_count ?? 0))}</b>
|
||||||
|
<div>Connector</div><b class="mono">${esc(first?.connector || "-")}</b>
|
||||||
|
<div>Monitor</div><b class="mono">${esc(first?.edid?.monitor_name || "-")}</b>
|
||||||
|
<div>Preferred mode</div><b class="mono">${esc(first?.preferred_mode || "-")}</b>
|
||||||
|
<div>Vendor</div><b class="mono">${esc(first?.edid?.manufacturer_id || "-")}</b>
|
||||||
|
</div>
|
||||||
|
<div class="btns" style="margin-top:14px">
|
||||||
|
${btn("Refresh", "primary", "window.__x11Refresh()", "refresh", "Refreshing...")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Connected connectors</div>
|
||||||
|
${connected.length ? connected.map(renderConnector).join("") : `<div class="small">No connected connectors detected.</div>`}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">HDMI connectors</div>
|
||||||
|
${hdmi.length ? hdmi.map(renderConnector).join("") : `<div class="small">No HDMI connectors found.</div>`}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">All DRM connectors</div>
|
||||||
|
${connectors.length ? connectors.map(renderConnector).join("") : `<div class="small">No DRM connectors found.</div>`}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Message</div>
|
||||||
|
<div class="small mono">${esc(state.x11Addon.message || "Ready")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevLoadTabData = ui.loadTabData.bind(ui);
|
||||||
|
const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){};
|
||||||
|
const prevRender = ui.render.bind(ui);
|
||||||
|
|
||||||
|
ui.loadTabData = async function () {
|
||||||
|
if (state.tab === "x11") {
|
||||||
|
await ui.loadDetail("x11");
|
||||||
|
await loadDisplay().catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevLoadTabData();
|
||||||
|
};
|
||||||
|
|
||||||
|
ui.refreshDetail = async function () {
|
||||||
|
if (state.tab === "x11") {
|
||||||
|
await ui.loadDetail("x11");
|
||||||
|
await loadDisplay().catch(() => {});
|
||||||
|
ui.render();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRefreshDetail();
|
||||||
|
};
|
||||||
|
window.refreshDetail = ui.refreshDetail;
|
||||||
|
|
||||||
|
ui.render = function () {
|
||||||
|
if (state.tab === "x11" && state.detail?.service?.key === "x11") {
|
||||||
|
renderX11Detail(state.detail.service);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRender();
|
||||||
|
};
|
||||||
|
window.render = ui.render;
|
||||||
|
|
||||||
|
window.__x11Refresh = refreshDisplay;
|
||||||
|
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await loadDisplay().catch(() => {});
|
||||||
|
if (state.tab === "x11") ui.render();
|
||||||
|
} catch (_) {}
|
||||||
|
}, 0);
|
||||||
|
})();
|
||||||
|
JS
|
||||||
|
|
||||||
|
echo "[3/4] restart"
|
||||||
|
systemctl restart "$SERVICE"
|
||||||
|
|
||||||
|
echo "[4/4] done"
|
||||||
|
echo "Installed frontend: $ADDON_FRONT/x11.js"
|
||||||
|
echo "Restarted: $SERVICE"
|
||||||
|
|
@ -0,0 +1,765 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
APP="/opt/iomatex-process1-webipc"
|
||||||
|
ADDON_BACK="$APP/addons/backend"
|
||||||
|
ADDON_FRONT="$APP/public/addons"
|
||||||
|
CFG="/etc/iomatex/webipc-itscreen.json"
|
||||||
|
SERVICE="iomatex-webipc.service"
|
||||||
|
|
||||||
|
echo "[1/6] prepare dirs"
|
||||||
|
mkdir -p "$ADDON_BACK" "$ADDON_FRONT" /etc/iomatex
|
||||||
|
|
||||||
|
echo "[2/6] config"
|
||||||
|
if [ ! -f "$CFG" ]; then
|
||||||
|
cat > "$CFG" <<'EOF'
|
||||||
|
{
|
||||||
|
"server": "",
|
||||||
|
"deviceId": "",
|
||||||
|
"token": "",
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"topicNamespace": ""
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[3/6] backend addon"
|
||||||
|
cat > "$ADDON_BACK/itscreen.js" <<'JS'
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const os = require("os");
|
||||||
|
const mqtt = require("mqtt");
|
||||||
|
|
||||||
|
const CFG = "/etc/iomatex/webipc-itscreen.json";
|
||||||
|
const MQTT = "mqtt://127.0.0.1:1883";
|
||||||
|
const LOGIN_PASSWORD = "eXXI0wkHBmNBnVbE";
|
||||||
|
const TOPIC_NAMESPACES = ["it-screen", "iomatex"];
|
||||||
|
const ITSERVICE = "itscreen-x11.service";
|
||||||
|
|
||||||
|
function readCfg() {
|
||||||
|
try {
|
||||||
|
const j = JSON.parse(fs.readFileSync(CFG, "utf8"));
|
||||||
|
return {
|
||||||
|
server: (j.server || "").toString(),
|
||||||
|
deviceId: (j.deviceId || "").toString(),
|
||||||
|
token: (j.token || "").toString(),
|
||||||
|
username: (j.username || "").toString(),
|
||||||
|
password: (j.password || "").toString(),
|
||||||
|
topicNamespace: (j.topicNamespace || "").toString()
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
server: "",
|
||||||
|
deviceId: "",
|
||||||
|
token: "",
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
topicNamespace: ""
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeCfg(o) {
|
||||||
|
const safe = {
|
||||||
|
server: (o.server || "").toString().trim(),
|
||||||
|
deviceId: (o.deviceId || "").toString().trim(),
|
||||||
|
token: (o.token || "").toString().trim(),
|
||||||
|
username: (o.username || "").toString().trim(),
|
||||||
|
password: (o.password || "").toString().trim(),
|
||||||
|
topicNamespace: (o.topicNamespace || "").toString().trim()
|
||||||
|
};
|
||||||
|
fs.writeFileSync(CFG, JSON.stringify(safe, null, 2) + "\n", "utf8");
|
||||||
|
return safe;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeNamespace(ns) {
|
||||||
|
ns = (ns || "").toString().trim();
|
||||||
|
return TOPIC_NAMESPACES.includes(ns) ? ns : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDeviceId(cfg) {
|
||||||
|
return (cfg.deviceId || os.hostname()).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function topicPair(cfg, namespace) {
|
||||||
|
const id = getDeviceId(cfg);
|
||||||
|
const ns = normalizeNamespace(namespace) || "it-screen";
|
||||||
|
const base = `${ns}/$devices/settings/${id}`;
|
||||||
|
return {
|
||||||
|
namespace: ns,
|
||||||
|
deviceId: id,
|
||||||
|
sub: `${base}/sub`,
|
||||||
|
pub: `${base}/pub`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function getNamespaceOrder(cfg) {
|
||||||
|
const preferred = normalizeNamespace(cfg.topicNamespace);
|
||||||
|
if (preferred) return [preferred].concat(TOPIC_NAMESPACES.filter(x => x !== preferred));
|
||||||
|
return TOPIC_NAMESPACES.slice();
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasRegistrationData(obj) {
|
||||||
|
if (!obj || typeof obj !== "object") return false;
|
||||||
|
const server = (obj.server || obj.host || "").toString().trim();
|
||||||
|
const username = (obj.username || "").toString().trim();
|
||||||
|
const password = (obj.password || "").toString().trim();
|
||||||
|
return !!(server && username && password);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = function(app, ctx) {
|
||||||
|
const mqttc = mqtt.connect(MQTT, {
|
||||||
|
reconnectPeriod: 1000,
|
||||||
|
connectTimeout: 4000,
|
||||||
|
keepalive: 30,
|
||||||
|
clean: true
|
||||||
|
});
|
||||||
|
|
||||||
|
let loginState = {
|
||||||
|
ok: false,
|
||||||
|
lastTs: null,
|
||||||
|
lastError: null,
|
||||||
|
lastNamespace: null
|
||||||
|
};
|
||||||
|
|
||||||
|
let sendQueue = Promise.resolve();
|
||||||
|
|
||||||
|
function saveNamespaceIfChanged(namespace) {
|
||||||
|
const ns = normalizeNamespace(namespace);
|
||||||
|
if (!ns) return readCfg();
|
||||||
|
const cur = readCfg();
|
||||||
|
if (cur.topicNamespace === ns) return cur;
|
||||||
|
return writeCfg({
|
||||||
|
server: cur.server,
|
||||||
|
deviceId: cur.deviceId || getDeviceId(cur),
|
||||||
|
token: cur.token,
|
||||||
|
username: cur.username,
|
||||||
|
password: cur.password,
|
||||||
|
topicNamespace: ns
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendOne(cfg, namespace, payload, timeout = 3000) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const tp = topicPair(cfg, namespace);
|
||||||
|
let done = false;
|
||||||
|
|
||||||
|
const finish = (obj) => {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
mqttc.removeListener("message", onMsg);
|
||||||
|
try { mqttc.unsubscribe(tp.pub); } catch {}
|
||||||
|
resolve(obj);
|
||||||
|
};
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
note: "timeout",
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
});
|
||||||
|
}, timeout);
|
||||||
|
|
||||||
|
function onMsg(t, b) {
|
||||||
|
if (t !== tp.pub) return;
|
||||||
|
const raw = b ? b.toString() : "";
|
||||||
|
let parsed = null;
|
||||||
|
try { parsed = JSON.parse(raw); } catch { parsed = { raw }; }
|
||||||
|
finish(Object.assign({
|
||||||
|
ok: true,
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
}, parsed));
|
||||||
|
}
|
||||||
|
|
||||||
|
mqttc.subscribe(tp.pub, (subErr) => {
|
||||||
|
if (subErr) {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
note: "subscribe_failed",
|
||||||
|
error: subErr.message,
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
mqttc.on("message", onMsg);
|
||||||
|
|
||||||
|
mqttc.publish(tp.sub, JSON.stringify(payload), (pubErr) => {
|
||||||
|
if (pubErr) {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
note: "publish_failed",
|
||||||
|
error: pubErr.message,
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(cfg, payload, timeout = 3000) {
|
||||||
|
const namespaces = getNamespaceOrder(cfg);
|
||||||
|
|
||||||
|
const runOne = async () => {
|
||||||
|
let last = null;
|
||||||
|
for (const ns of namespaces) {
|
||||||
|
const r = await sendOne(cfg, ns, payload, timeout);
|
||||||
|
last = r;
|
||||||
|
if (r && (r.result === true || r.category || r.action || (r.ok && !r.note))) {
|
||||||
|
saveNamespaceIfChanged(ns);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return last || { ok: false, note: "no_namespace_tried" };
|
||||||
|
};
|
||||||
|
|
||||||
|
sendQueue = sendQueue.then(runOne, runOne);
|
||||||
|
return sendQueue;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doLogin(cfg) {
|
||||||
|
const r = await send(cfg, {
|
||||||
|
action: "login",
|
||||||
|
password: LOGIN_PASSWORD
|
||||||
|
}, 4000);
|
||||||
|
|
||||||
|
loginState.lastTs = Date.now();
|
||||||
|
loginState.lastNamespace = (r && r.namespace) || null;
|
||||||
|
|
||||||
|
if (r && r.action === "login" && r.result === true) {
|
||||||
|
loginState.ok = true;
|
||||||
|
loginState.lastError = null;
|
||||||
|
} else {
|
||||||
|
loginState.ok = false;
|
||||||
|
loginState.lastError = (r && (r.note || r.error || r.raw)) || "login_failed";
|
||||||
|
}
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureLogin(cfg) {
|
||||||
|
return doLogin(cfg);
|
||||||
|
}
|
||||||
|
|
||||||
|
app.get("/api/addon/itscreen/config", (req, res) => {
|
||||||
|
const cfg = readCfg();
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: cfg,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(cfg) },
|
||||||
|
topics: getNamespaceOrder(cfg).map(ns => topicPair(cfg, ns))
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/config/clear", (req, res) => {
|
||||||
|
const cleared = writeCfg({
|
||||||
|
server: "",
|
||||||
|
deviceId: "",
|
||||||
|
token: "",
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
topicNamespace: ""
|
||||||
|
});
|
||||||
|
|
||||||
|
loginState = {
|
||||||
|
ok: false,
|
||||||
|
lastTs: Date.now(),
|
||||||
|
lastError: "config_cleared",
|
||||||
|
lastNamespace: null
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: cleared,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: false }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/login", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const cfg = readCfg();
|
||||||
|
const r = await doLogin(cfg);
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: readCfg(),
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(readCfg()) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message, login: loginState });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get("/api/addon/itscreen/get_server", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const cfg = readCfg();
|
||||||
|
const loginR = await ensureLogin(cfg);
|
||||||
|
|
||||||
|
if (!(loginR && loginR.result === true)) {
|
||||||
|
const current = readCfg();
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: current,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(current) },
|
||||||
|
result: { ok: false, note: "login_failed_before_get", login_result: loginR }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const cfg2 = readCfg();
|
||||||
|
const r = await send(cfg2, {
|
||||||
|
action: "get",
|
||||||
|
category: "server"
|
||||||
|
}, 4000);
|
||||||
|
|
||||||
|
const currentCfg = readCfg();
|
||||||
|
|
||||||
|
if (r && r.category === "server") {
|
||||||
|
const merged = writeCfg({
|
||||||
|
server: (r.host || currentCfg.server || "").toString(),
|
||||||
|
deviceId: currentCfg.deviceId || getDeviceId(cfg2),
|
||||||
|
token: currentCfg.token,
|
||||||
|
username: (r.username || currentCfg.username || "").toString(),
|
||||||
|
password: (r.password || currentCfg.password || "").toString(),
|
||||||
|
topicNamespace: (r.namespace || currentCfg.topicNamespace || "").toString()
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: merged,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(merged) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: currentCfg,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(currentCfg) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message, login: loginState });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/register", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const body = req.body || {};
|
||||||
|
const cfg = readCfg();
|
||||||
|
|
||||||
|
const server = (body.server || "").toString().trim();
|
||||||
|
const username = (body.username || "").toString().trim();
|
||||||
|
const password = (body.password || "").toString().trim();
|
||||||
|
const token = (body.token || "").toString().trim();
|
||||||
|
|
||||||
|
if (!server) return res.status(400).json({ ok: false, error: "server is required" });
|
||||||
|
if (!username) return res.status(400).json({ ok: false, error: "username is required" });
|
||||||
|
if (!password) return res.status(400).json({ ok: false, error: "password is required" });
|
||||||
|
|
||||||
|
const loginR = await ensureLogin(cfg);
|
||||||
|
|
||||||
|
if (!(loginR && loginR.result === true)) {
|
||||||
|
const current = readCfg();
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: current,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(current) },
|
||||||
|
result: { ok: false, note: "login_failed_before_set", login_result: loginR }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const cfg2 = readCfg();
|
||||||
|
const payload = {
|
||||||
|
action: "set",
|
||||||
|
category: "server",
|
||||||
|
host: server,
|
||||||
|
username,
|
||||||
|
password
|
||||||
|
};
|
||||||
|
|
||||||
|
const r = await send(cfg2, payload, 5000);
|
||||||
|
|
||||||
|
if (r && r.result === true) {
|
||||||
|
const saved = writeCfg({
|
||||||
|
server,
|
||||||
|
deviceId: cfg2.deviceId || getDeviceId(cfg2),
|
||||||
|
token,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
topicNamespace: r.namespace || cfg2.topicNamespace || ""
|
||||||
|
});
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: saved,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(saved) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = readCfg();
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: current,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(current) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message, login: loginState });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/service/:action", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const action = (req.params.action || "").toLowerCase();
|
||||||
|
if (!["restart", "stop", "start"].includes(action)) {
|
||||||
|
return res.status(400).json({ ok: false, error: "bad action" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const r = await ctx.run("/bin/systemctl", [action, ITSERVICE], 12000);
|
||||||
|
if (!r.ok) {
|
||||||
|
return res.status(502).json({ ok: false, error: r.err || r.out || "systemctl failed" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = await ctx.run("/bin/systemctl", ["is-active", ITSERVICE], 6000);
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
action,
|
||||||
|
unit: ITSERVICE,
|
||||||
|
active: (status.out || status.err || "").trim() || "unknown"
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
JS
|
||||||
|
|
||||||
|
echo "[4/6] frontend addon"
|
||||||
|
cat > "$ADDON_FRONT/itscreen.js" <<'JS'
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
if (window.__iomatexItscreenAddonLoaded) return;
|
||||||
|
window.__iomatexItscreenAddonLoaded = true;
|
||||||
|
|
||||||
|
const ui = window.IOMATEX_UI;
|
||||||
|
if (!ui) return;
|
||||||
|
|
||||||
|
const state = ui.state;
|
||||||
|
|
||||||
|
state.itscreenAddon = state.itscreenAddon || {
|
||||||
|
cfg: {},
|
||||||
|
result: {},
|
||||||
|
login: {},
|
||||||
|
registration: { configured: false },
|
||||||
|
busy: {
|
||||||
|
refresh: false,
|
||||||
|
login: false,
|
||||||
|
register: false,
|
||||||
|
clear: false,
|
||||||
|
restart: false,
|
||||||
|
stop: false,
|
||||||
|
start: false
|
||||||
|
},
|
||||||
|
message: ""
|
||||||
|
};
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return (s ?? "").toString().replace(/[&<>"']/g, m => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
'"': """,
|
||||||
|
"'": "'"
|
||||||
|
}[m]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMsg(msg) {
|
||||||
|
state.itscreenAddon.message = (msg || "").toString();
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBusy(key, v) {
|
||||||
|
state.itscreenAddon.busy[key] = !!v;
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function inputValue(id) {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
return el ? el.value.trim() : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function btn(label, kind, fnName, busyKey, busyLabel) {
|
||||||
|
const busy = !!state.itscreenAddon.busy[busyKey];
|
||||||
|
return `<button class="${kind || ""}" ${busy ? "disabled" : ""} onclick="${busy ? "return false" : fnName}">${esc(busy ? busyLabel : label)}</button>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadConfigOnly() {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/config");
|
||||||
|
state.itscreenAddon.cfg = j.config || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshRemote() {
|
||||||
|
setBusy("refresh", true);
|
||||||
|
setMsg("Refreshing registration...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/get_server");
|
||||||
|
state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = j.result || {};
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
setMsg("Registration data refreshed.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("refresh", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doLogin() {
|
||||||
|
setBusy("login", true);
|
||||||
|
setMsg("Login in progress...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/login", { method: "POST", body: "{}" });
|
||||||
|
state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = j.result || {};
|
||||||
|
setMsg(j.login?.ok ? "Login OK." : "Login failed.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("login", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doRegister() {
|
||||||
|
const server = inputValue("its_server");
|
||||||
|
const username = inputValue("its_user");
|
||||||
|
const password = inputValue("its_pass");
|
||||||
|
const token = inputValue("its_token");
|
||||||
|
|
||||||
|
if (!server) return setMsg("Server is required.");
|
||||||
|
if (!username) return setMsg("Username is required.");
|
||||||
|
if (!password) return setMsg("Password is required.");
|
||||||
|
|
||||||
|
setBusy("register", true);
|
||||||
|
setMsg("Saving registration...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/register", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ server, username, password, token })
|
||||||
|
});
|
||||||
|
state.itscreenAddon.cfg = j.config || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = j.result || {};
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
await ui.loadDetail("itscreen").catch(() => {});
|
||||||
|
setMsg(j.result?.result === true ? "Registration saved." : "Registration request sent.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("register", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doClear() {
|
||||||
|
setBusy("clear", true);
|
||||||
|
setMsg("Clearing registration...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/config/clear", { method: "POST", body: "{}" });
|
||||||
|
state.itscreenAddon.cfg = j.config || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = {};
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
await ui.loadDetail("itscreen").catch(() => {});
|
||||||
|
setMsg("Registration cleared.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("clear", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function serviceAction(action) {
|
||||||
|
setBusy(action, true);
|
||||||
|
setMsg(`Service ${action}...`);
|
||||||
|
try {
|
||||||
|
const j = await ui.call(`/api/addon/itscreen/service/${encodeURIComponent(action)}`, {
|
||||||
|
method: "POST",
|
||||||
|
body: "{}"
|
||||||
|
});
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
await ui.loadDetail("itscreen").catch(() => {});
|
||||||
|
setMsg(`Service ${action} done. Current state: ${j.active || "unknown"}`);
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(action, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderItscreenDetail(service) {
|
||||||
|
const cfg = state.itscreenAddon.cfg || {};
|
||||||
|
const login = state.itscreenAddon.login || {};
|
||||||
|
const reg = state.itscreenAddon.registration || { configured: false };
|
||||||
|
|
||||||
|
const deviceId = (cfg.deviceId || state.health?.hostname || "unknown").toString();
|
||||||
|
|
||||||
|
document.getElementById("viewTitle").textContent = service.title;
|
||||||
|
document.getElementById("viewSub").textContent = service.desc || "";
|
||||||
|
document.getElementById("viewActions").innerHTML =
|
||||||
|
`<button class="primary" onclick="window.__itscreenRefresh()">Refresh</button>`;
|
||||||
|
|
||||||
|
document.getElementById("view").innerHTML = `
|
||||||
|
<div class="stack">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Service status</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Active</div><b class="mono">${esc(service.status?.active || "-")}</b>
|
||||||
|
<div>Started</div><b class="mono">${esc(service.status?.started_at || "-")}</b>
|
||||||
|
<div>State</div><b class="mono">${esc(service.status?.summary || "-")}</b>
|
||||||
|
<div>Running</div><b class="mono">${esc(service.status?.running_for_text || "-")}</b>
|
||||||
|
<div>Unit file</div><b class="mono">${esc(service.status?.unit_file_state || "-")}</b>
|
||||||
|
<div>Unit</div><b class="mono">${esc(service.unit || "-")}</b>
|
||||||
|
</div>
|
||||||
|
<div class="btns" style="margin-top:14px">
|
||||||
|
${btn("Start", "", "window.__itscreenStart()", "start", "Starting...")}
|
||||||
|
${btn("Stop", "danger", "window.__itscreenStop()", "stop", "Stopping...")}
|
||||||
|
${btn("Restart", "primary", "window.__itscreenRestart()", "restart", "Restarting...")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Registration</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Configured</div><b class="mono">${esc(reg.configured ? "yes" : "no")}</b>
|
||||||
|
<div>Device ID</div><b class="mono">${esc(deviceId)}</b>
|
||||||
|
<div>Server</div><b class="mono">${esc(cfg.server || "-")}</b>
|
||||||
|
<div>Username</div><b class="mono">${esc(cfg.username || "-")}</b>
|
||||||
|
<div>Password</div><b class="mono">${esc(cfg.password ? "******" : "-")}</b>
|
||||||
|
<div>Token</div><b class="mono">${esc(cfg.token || "-")}</b>
|
||||||
|
<div>Namespace</div><b class="mono">${esc(cfg.topicNamespace || "-")}</b>
|
||||||
|
<div>Login</div><b class="mono">${esc(login.ok ? "ok" : "not ok")}</b>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Server</div>
|
||||||
|
<input id="its_server" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.server || "")}" placeholder="rest.dev.it-screen.com">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Username</div>
|
||||||
|
<input id="its_user" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.username || "")}" placeholder="device_xxxxx">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Password</div>
|
||||||
|
<input id="its_pass" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.password || "")}" placeholder="device password">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Token</div>
|
||||||
|
<input id="its_token" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.token || "")}" placeholder="95687">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="btns" style="margin-top:14px">
|
||||||
|
${btn("Login", "", "window.__itscreenLogin()", "login", "Working...")}
|
||||||
|
${btn("Refresh registration", "", "window.__itscreenRefresh()", "refresh", "Working...")}
|
||||||
|
${btn("Save registration", "primary", "window.__itscreenRegister()", "register", "Saving...")}
|
||||||
|
${btn("Clear registration", "danger", "window.__itscreenClear()", "clear", "Clearing...")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Message</div>
|
||||||
|
<div class="small mono">${esc(state.itscreenAddon.message || "Ready")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevLoadTabData = ui.loadTabData.bind(ui);
|
||||||
|
const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){};
|
||||||
|
const prevRender = ui.render.bind(ui);
|
||||||
|
|
||||||
|
ui.loadTabData = async function () {
|
||||||
|
if (state.tab === "itscreen") {
|
||||||
|
await ui.loadDetail("itscreen");
|
||||||
|
await loadConfigOnly().catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevLoadTabData();
|
||||||
|
};
|
||||||
|
|
||||||
|
ui.refreshDetail = async function () {
|
||||||
|
if (state.tab === "itscreen") {
|
||||||
|
await ui.loadDetail("itscreen");
|
||||||
|
await loadConfigOnly().catch(() => {});
|
||||||
|
ui.render();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRefreshDetail();
|
||||||
|
};
|
||||||
|
window.refreshDetail = ui.refreshDetail;
|
||||||
|
|
||||||
|
ui.render = function () {
|
||||||
|
if (state.tab === "itscreen" && state.detail?.service?.key === "itscreen") {
|
||||||
|
renderItscreenDetail(state.detail.service);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRender();
|
||||||
|
};
|
||||||
|
window.render = ui.render;
|
||||||
|
|
||||||
|
window.__itscreenRefresh = refreshRemote;
|
||||||
|
window.__itscreenLogin = doLogin;
|
||||||
|
window.__itscreenRegister = doRegister;
|
||||||
|
window.__itscreenClear = doClear;
|
||||||
|
window.__itscreenRestart = () => serviceAction("restart");
|
||||||
|
window.__itscreenStop = () => serviceAction("stop");
|
||||||
|
window.__itscreenStart = () => serviceAction("start");
|
||||||
|
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await loadConfigOnly().catch(() => {});
|
||||||
|
if (state.tab === "itscreen") ui.render();
|
||||||
|
} catch (_) {}
|
||||||
|
}, 0);
|
||||||
|
})();
|
||||||
|
JS
|
||||||
|
|
||||||
|
echo "[5/6] restart"
|
||||||
|
systemctl restart "$SERVICE"
|
||||||
|
|
||||||
|
echo "[6/6] done"
|
||||||
|
echo "Installed backend: $ADDON_BACK/itscreen.js"
|
||||||
|
echo "Installed frontend: $ADDON_FRONT/itscreen.js"
|
||||||
|
echo "Restarted: $SERVICE"
|
||||||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue