UI: burger menu, audio diagnostics simplification, dark theme toggle, layout fixes
- moved actions to burger menu (fixed top-right) - fixed menu toggle behavior (open/close, ESC, outside click) - simplified audio UI (removed low-level ALSA blocks) - added audio test actions (HDMI/analog) - implemented dark/light theme toggle (icon-based) - fixed header/banner layout overlap - added reboot action - cleanup legacy UI scripts
This commit is contained in:
parent
fe936cec87
commit
0702558212
|
|
@ -479,7 +479,6 @@ stage_candidates() {
|
|||
stage_ui)
|
||||
printf '%s\n' "ui_installer.sh"
|
||||
printf '%s\n' "stage_ui_install.sh"
|
||||
printf '%s\n' "stage_display_addon.sh"
|
||||
;;
|
||||
stage_itscreen)
|
||||
printf '%s\n' "stage_itscreen_install.sh"
|
||||
|
|
|
|||
|
|
@ -6,12 +6,14 @@ import json
|
|||
import os
|
||||
import shutil
|
||||
import re
|
||||
import select
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import datetime
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlparse
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
from itscreen_registration import get_registration_status, register_device, reset_registration
|
||||
|
||||
APP_DIR = "/opt/iomatex-console"
|
||||
|
|
@ -29,6 +31,7 @@ _CACHE = {"expires_at": 0.0, "payload": None}
|
|||
_CPU_SAMPLE = {"total": None, "idle": None}
|
||||
_NET_SAMPLE = {}
|
||||
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
|
||||
_ITSCREEN_CONFIG_CACHE = {"expires_at": 0.0, "payload": None}
|
||||
_WIFI_RESCAN_MIN_INTERVAL_SEC = 30.0
|
||||
AP_ENV_PATH = "/etc/iomatex/ap.env"
|
||||
WIFI_ENV_PATH = "/etc/iomatex/wifi.env"
|
||||
|
|
@ -41,6 +44,11 @@ WIFI_SETUP_SCRIPT = "/usr/local/sbin/iomatex-wifi-setup"
|
|||
DEVICE_ID_PATH = "/userdata/device-id"
|
||||
DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
|
||||
AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$")
|
||||
ITSCREEN_SERVICE_UNIT = "itscreen-x11.service"
|
||||
ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf"
|
||||
ITSCREEN_CONFIG_CACHE_TTL_SEC = 3.0
|
||||
ITSCREEN_LOG_DEFAULT_LINES = 50
|
||||
ITSCREEN_LOG_MAX_LINES = 300
|
||||
DEFAULT_AP_UI_PORT = "80"
|
||||
CAPTIVE_PORTAL_PATH = "/portal"
|
||||
CAPTIVE_PORTAL_ALIASES = {
|
||||
|
|
@ -102,6 +110,274 @@ def run(cmd, timeout=4):
|
|||
return 1, "", str(exc)
|
||||
|
||||
|
||||
def command_exists(name):
|
||||
return shutil.which(name) is not None
|
||||
|
||||
|
||||
def utc_now_iso():
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
|
||||
|
||||
def trim_output_lines(text, limit=12, width=220):
|
||||
lines = []
|
||||
for raw in (text or "").splitlines():
|
||||
line = raw.strip()
|
||||
if not line:
|
||||
continue
|
||||
if len(line) > width:
|
||||
line = line[: width - 3] + "..."
|
||||
lines.append(line)
|
||||
if len(lines) > limit:
|
||||
lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"]
|
||||
return lines
|
||||
|
||||
|
||||
def parse_alsa_cards():
|
||||
raw = read_text("/proc/asound/cards")
|
||||
cards = []
|
||||
current = None
|
||||
for line in raw.splitlines():
|
||||
match = re.match(r"^\s*(\d+)\s+\[(.*?)\s*\]:\s*(.*)$", line)
|
||||
if match:
|
||||
current = {
|
||||
"index": int(match.group(1)),
|
||||
"id": match.group(2).strip(),
|
||||
"name": match.group(3).strip(),
|
||||
"description": "",
|
||||
}
|
||||
cards.append(current)
|
||||
continue
|
||||
if current and line.startswith(" "):
|
||||
extra = line.strip()
|
||||
if extra:
|
||||
current["description"] = extra
|
||||
return cards
|
||||
|
||||
|
||||
def get_alsa_card(card_index):
|
||||
for card in parse_alsa_cards():
|
||||
if card.get("index") == card_index:
|
||||
return card
|
||||
return {}
|
||||
|
||||
|
||||
def audio_route_info():
|
||||
pactl_error_lines = []
|
||||
if command_exists("pactl"):
|
||||
rc, stdout, stderr = run(["pactl", "info"], timeout=4)
|
||||
if rc == 0:
|
||||
info = {}
|
||||
for line in (stdout or "").splitlines():
|
||||
if ":" not in line:
|
||||
continue
|
||||
key, value = line.split(":", 1)
|
||||
info[key.strip()] = value.strip()
|
||||
sink = info.get("Default Sink")
|
||||
server_name = info.get("Server Name")
|
||||
summary = sink or server_name or "PulseAudio/PipeWire route detected"
|
||||
return {
|
||||
"type": "pulse",
|
||||
"summary": summary,
|
||||
"details": trim_output_lines(stdout, limit=6),
|
||||
}
|
||||
pactl_error_lines = trim_output_lines(stderr or stdout, limit=4)
|
||||
|
||||
rc, stdout, stderr = run(["aplay", "-L"], timeout=4)
|
||||
if rc == 0:
|
||||
has_default = any(line.strip() == "default" for line in (stdout or "").splitlines())
|
||||
return {
|
||||
"type": "alsa" if has_default else "unknown",
|
||||
"summary": "ALSA default device is available" if has_default else "Logical ALSA devices listed",
|
||||
"details": pactl_error_lines + trim_output_lines(stdout, limit=8 - len(pactl_error_lines)),
|
||||
}
|
||||
return {
|
||||
"type": "unknown",
|
||||
"summary": trim_output_lines(stderr or stdout, limit=1)[0] if trim_output_lines(stderr or stdout, limit=1) else "Audio route unavailable",
|
||||
"details": pactl_error_lines + trim_output_lines(stderr or stdout, limit=max(1, 4 - len(pactl_error_lines))),
|
||||
}
|
||||
|
||||
|
||||
def read_audio_device_status(card_index, pcm_index):
|
||||
card = get_alsa_card(card_index)
|
||||
pcm_root = f"/proc/asound/card{card_index}/pcm{pcm_index}p"
|
||||
info_path = os.path.join(pcm_root, "info")
|
||||
status_path = os.path.join(pcm_root, "sub0/status")
|
||||
hw_params_path = os.path.join(pcm_root, "sub0/hw_params")
|
||||
|
||||
info_text = read_text(info_path).strip()
|
||||
status_text = read_text(status_path).strip()
|
||||
hw_params_text = read_text(hw_params_path).strip()
|
||||
|
||||
status_lower = status_text.lower()
|
||||
if not os.path.exists(pcm_root):
|
||||
status = "error"
|
||||
summary = "PCM playback device not found"
|
||||
elif not status_text:
|
||||
status = "error"
|
||||
summary = "Playback status is unavailable"
|
||||
elif "closed" in status_lower:
|
||||
status = "available"
|
||||
summary = "Playback device is idle"
|
||||
else:
|
||||
status = "busy"
|
||||
summary = trim_output_lines(status_text, limit=1)[0] if trim_output_lines(status_text, limit=1) else "Playback device is busy"
|
||||
|
||||
short_description = ""
|
||||
info_lines = trim_output_lines(info_text, limit=6)
|
||||
if info_lines:
|
||||
short_description = info_lines[0]
|
||||
elif card.get("description"):
|
||||
short_description = card["description"]
|
||||
|
||||
return {
|
||||
"status": status,
|
||||
"summary": summary,
|
||||
"card_name": card.get("name") or card.get("id") or f"card {card_index}",
|
||||
"card_id": card.get("id", ""),
|
||||
"description": short_description,
|
||||
"info_lines": info_lines,
|
||||
"status_lines": trim_output_lines(status_text, limit=6),
|
||||
"hw_params_lines": trim_output_lines(hw_params_text, limit=6),
|
||||
}
|
||||
|
||||
|
||||
AUDIO_TARGETS = {
|
||||
"hdmi": {
|
||||
"label": "HDMI audio",
|
||||
"device": "hw:1,0",
|
||||
"card_index": 1,
|
||||
"pcm_index": 0,
|
||||
"description": "Digital audio over HDMI output",
|
||||
},
|
||||
"analog": {
|
||||
"label": "Analog audio",
|
||||
"device": "hw:0,0",
|
||||
"card_index": 0,
|
||||
"pcm_index": 0,
|
||||
"description": "Analog audio via rockchip-rk809 codec",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_audio_diagnostics():
|
||||
cards = parse_alsa_cards()
|
||||
aplay_l_rc, aplay_l_out, aplay_l_err = run(["aplay", "-l"], timeout=4)
|
||||
aplay_L_rc, aplay_L_out, aplay_L_err = run(["aplay", "-L"], timeout=4)
|
||||
route = audio_route_info()
|
||||
devices = {}
|
||||
|
||||
for target, config in AUDIO_TARGETS.items():
|
||||
device_state = read_audio_device_status(config["card_index"], config["pcm_index"])
|
||||
devices[target] = {
|
||||
"target": target,
|
||||
"label": config["label"],
|
||||
"device": config["device"],
|
||||
"card_index": config["card_index"],
|
||||
"pcm_index": config["pcm_index"],
|
||||
"description": config["description"],
|
||||
**device_state,
|
||||
}
|
||||
|
||||
return {
|
||||
"devices": devices,
|
||||
"parameters": {
|
||||
"aplay_hardware": trim_output_lines(aplay_l_out if aplay_l_rc == 0 else (aplay_l_err or aplay_l_out), limit=12),
|
||||
"aplay_logical": trim_output_lines(aplay_L_out if aplay_L_rc == 0 else (aplay_L_err or aplay_L_out), limit=12),
|
||||
"default_route": route,
|
||||
"alsa_cards": cards,
|
||||
},
|
||||
"generated_at": utc_now_iso(),
|
||||
}
|
||||
|
||||
|
||||
def classify_audio_test_result(returncode, output):
|
||||
text = (output or "").lower()
|
||||
if returncode == 0:
|
||||
return "success"
|
||||
if "device or resource busy" in text or "busy" in text:
|
||||
return "busy"
|
||||
return "failed"
|
||||
|
||||
|
||||
def perform_audio_test(target):
|
||||
config = AUDIO_TARGETS.get(target)
|
||||
if not config:
|
||||
raise ValueError("Unknown audio target")
|
||||
if not command_exists("speaker-test"):
|
||||
raise RuntimeError("speaker-test command is not available")
|
||||
|
||||
cmd = [
|
||||
"speaker-test",
|
||||
"-D",
|
||||
config["device"],
|
||||
"-c",
|
||||
"2",
|
||||
"-l",
|
||||
"1",
|
||||
"-t",
|
||||
"sine",
|
||||
"-f",
|
||||
"440",
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
timeout=6,
|
||||
check=False,
|
||||
)
|
||||
output = "\n".join(part for part in [(proc.stdout or "").strip(), (proc.stderr or "").strip()] if part).strip()
|
||||
return {
|
||||
"ok": proc.returncode == 0,
|
||||
"target": target,
|
||||
"device": config["device"],
|
||||
"result": classify_audio_test_result(proc.returncode, output),
|
||||
"returncode": proc.returncode,
|
||||
"output": trim_output_lines(output, limit=10),
|
||||
"tested_at": utc_now_iso(),
|
||||
}
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
output = "\n".join(part for part in [(exc.stdout or "").strip(), (exc.stderr or "").strip()] if part).strip()
|
||||
return {
|
||||
"ok": False,
|
||||
"target": target,
|
||||
"device": config["device"],
|
||||
"result": "failed",
|
||||
"returncode": None,
|
||||
"output": trim_output_lines(output or "Audio test timed out", limit=10),
|
||||
"tested_at": utc_now_iso(),
|
||||
}
|
||||
|
||||
|
||||
def request_reboot():
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["sudo", "-n", "reboot"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
timeout=4,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "Reboot requested. Connection may drop shortly.",
|
||||
"requested_at": utc_now_iso(),
|
||||
}
|
||||
stdout = (proc.stdout or "").strip()
|
||||
stderr = (proc.stderr or "").strip()
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(stderr or stdout or "Failed to request reboot")
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "Reboot requested. Connection may drop shortly.",
|
||||
"requested_at": utc_now_iso(),
|
||||
}
|
||||
|
||||
|
||||
def file_exists(path):
|
||||
return os.path.exists(path)
|
||||
|
||||
|
|
@ -1076,6 +1352,7 @@ def build_status_payload():
|
|||
"run": run,
|
||||
"get_ap_status_card": ap_status_card,
|
||||
"get_identity_payload": get_identity_payload,
|
||||
"get_audio_diagnostics": get_audio_diagnostics,
|
||||
}
|
||||
cards = []
|
||||
provider_names = []
|
||||
|
|
@ -1123,6 +1400,394 @@ def find_service_card(service_id):
|
|||
return None
|
||||
|
||||
|
||||
def normalize_service_status(unit):
|
||||
if not isinstance(unit, dict):
|
||||
return "unknown", "Unknown"
|
||||
if not unit.get("installed"):
|
||||
return "not_installed", "Not installed"
|
||||
active_state = str(unit.get("active_state", "") or "").strip().lower()
|
||||
result = str(unit.get("result", "") or "").strip().lower()
|
||||
if active_state == "active":
|
||||
return "running", "Running"
|
||||
if active_state == "failed" or result == "failed":
|
||||
return "failed", "Failed"
|
||||
if active_state in ("inactive", "deactivating", "activating", "reloading"):
|
||||
return "stopped", "Stopped"
|
||||
return "unknown", "Unknown"
|
||||
|
||||
|
||||
def get_itscreen_service_status():
|
||||
try:
|
||||
unit = systemd_unit(ITSCREEN_SERVICE_UNIT)
|
||||
status, status_label = normalize_service_status(unit)
|
||||
return {
|
||||
"ok": True,
|
||||
"name": "itscreen",
|
||||
"unit": ITSCREEN_SERVICE_UNIT,
|
||||
"installed": bool(unit.get("installed", False)),
|
||||
"active": bool(unit.get("active", False)),
|
||||
"status": status,
|
||||
"status_label": status_label,
|
||||
"active_state": str(unit.get("active_state", "") or ""),
|
||||
"sub_state": str(unit.get("sub_state", "") or ""),
|
||||
}
|
||||
except Exception as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"name": "itscreen",
|
||||
"unit": ITSCREEN_SERVICE_UNIT,
|
||||
"installed": False,
|
||||
"active": False,
|
||||
"status": "unknown",
|
||||
"status_label": "Unknown",
|
||||
"error": "Could not read service status",
|
||||
"details": str(exc),
|
||||
}
|
||||
|
||||
|
||||
def build_itscreen_status_payload():
|
||||
return {
|
||||
"ok": True,
|
||||
"service": get_itscreen_service_status(),
|
||||
"registration": get_registration_status(),
|
||||
}
|
||||
|
||||
|
||||
def systemctl_show_property(unit_name, property_name, timeout=5):
|
||||
rc, stdout, stderr = run(["systemctl", "show", unit_name, "-p", property_name], timeout=timeout)
|
||||
if rc != 0:
|
||||
raise RuntimeError(stderr or f"Failed to read {property_name}")
|
||||
line = (stdout or "").strip()
|
||||
if not line:
|
||||
return ""
|
||||
if "=" not in line:
|
||||
return line
|
||||
_, _, value = line.partition("=")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def parse_systemctl_timestamp(raw_value):
|
||||
text = str(raw_value or "").strip()
|
||||
if not text or text.lower() in ("n/a", "0"):
|
||||
return None
|
||||
parts = text.split()
|
||||
if len(parts) >= 3 and parts[0].isalpha():
|
||||
text = " ".join(parts[1:3])
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def parse_int_value(raw_value):
|
||||
text = str(raw_value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return int(text)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def parse_text_value(raw_value):
|
||||
text = str(raw_value or "").strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def parse_bool_value(raw_value):
|
||||
text = str(raw_value or "").strip().lower()
|
||||
if text == "true":
|
||||
return True
|
||||
if text == "false":
|
||||
return False
|
||||
return None
|
||||
|
||||
|
||||
def format_local_iso_from_ms(timestamp_ms):
|
||||
parsed = parse_int_value(timestamp_ms)
|
||||
if parsed is None or parsed <= 0:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromtimestamp(parsed / 1000.0).strftime("%Y-%m-%dT%H:%M:%S")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def format_interval_human(seconds_value):
|
||||
seconds = parse_int_value(seconds_value)
|
||||
if seconds is None:
|
||||
return None
|
||||
if seconds <= 0:
|
||||
return "0 min" if seconds == 0 else None
|
||||
if seconds % 60 == 0:
|
||||
minutes = seconds // 60
|
||||
return f"{minutes} min"
|
||||
return f"{seconds} sec"
|
||||
|
||||
|
||||
def normalize_timestamp_ms(raw_value):
|
||||
parsed = parse_int_value(raw_value)
|
||||
if parsed is None:
|
||||
return None
|
||||
if parsed == 0:
|
||||
return 0
|
||||
if abs(parsed) < 10 ** 11:
|
||||
return parsed * 1000
|
||||
return parsed
|
||||
|
||||
|
||||
def read_simple_key_value_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 "=" not in line:
|
||||
continue
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
key = key.strip()
|
||||
if not key:
|
||||
continue
|
||||
data[key] = value.strip()
|
||||
except Exception:
|
||||
return {}
|
||||
return data
|
||||
|
||||
|
||||
def parse_itscreen_config_file(path):
|
||||
if not os.path.exists(path):
|
||||
return {"status": "not_installed"}
|
||||
try:
|
||||
raw = read_simple_key_value_file(path)
|
||||
except Exception:
|
||||
return {"status": "error", "message": "invalid config format"}
|
||||
if not isinstance(raw, dict) or not raw:
|
||||
return {"status": "error", "message": "invalid config format"}
|
||||
|
||||
interval_sec = parse_int_value(raw.get("updateInterval"))
|
||||
last_update_ms = normalize_timestamp_ms(raw.get("lastUpdateTime"))
|
||||
updated_at_sec = parse_int_value(raw.get("updatedAt"))
|
||||
last_contact_ts = last_update_ms
|
||||
if last_contact_ts is None and updated_at_sec is not None and updated_at_sec > 0:
|
||||
last_contact_ts = updated_at_sec * 1000
|
||||
|
||||
next_contact_ts = None
|
||||
if last_contact_ts is not None and interval_sec is not None:
|
||||
next_contact_ts = last_contact_ts + (interval_sec * 1000)
|
||||
|
||||
next_shutdown_ts = normalize_timestamp_ms(raw.get("nextOffTime"))
|
||||
next_startup_ts = normalize_timestamp_ms(raw.get("nextOnTime"))
|
||||
if next_shutdown_ts == 0:
|
||||
next_shutdown_ts = None
|
||||
if next_startup_ts == 0:
|
||||
next_startup_ts = None
|
||||
|
||||
return {
|
||||
"registration": {
|
||||
"registered": parse_bool_value(raw.get("isRegistered")),
|
||||
"server": parse_text_value(raw.get("server")),
|
||||
},
|
||||
"sync": {
|
||||
"interval_sec": interval_sec,
|
||||
"interval_human": format_interval_human(interval_sec),
|
||||
"last_contact_ts": last_contact_ts,
|
||||
"last_contact_iso": format_local_iso_from_ms(last_contact_ts),
|
||||
},
|
||||
"schedule": {
|
||||
"shutdown_enabled": parse_bool_value(raw.get("enableOffTime")),
|
||||
"shutdown_time": parse_text_value(raw.get("strOffTime")),
|
||||
"startup_enabled": parse_bool_value(raw.get("enableOnTime")),
|
||||
"startup_time": parse_text_value(raw.get("strOnTime")),
|
||||
"next_shutdown_ts": next_shutdown_ts,
|
||||
"next_shutdown_iso": format_local_iso_from_ms(next_shutdown_ts),
|
||||
"next_startup_ts": next_startup_ts,
|
||||
"next_startup_iso": format_local_iso_from_ms(next_startup_ts),
|
||||
},
|
||||
"reboot": {
|
||||
"enabled": parse_bool_value(raw.get("enableReboot")),
|
||||
"repeat_enabled": parse_bool_value(raw.get("enableRebootRepeat")),
|
||||
"repeat_interval": parse_int_value(raw.get("rebootRepeatTime")),
|
||||
"daily_time": parse_text_value(raw.get("rebootTime")),
|
||||
},
|
||||
"meta": {
|
||||
"updated_at_sec": updated_at_sec,
|
||||
"startup_delay": parse_int_value(raw.get("startupDelay")),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def read_itscreen_config_status():
|
||||
now = time.time()
|
||||
cached = _ITSCREEN_CONFIG_CACHE
|
||||
if cached["payload"] is not None and cached["expires_at"] > now:
|
||||
return cached["payload"]
|
||||
payload = parse_itscreen_config_file(ITSCREEN_CONFIG_PATH)
|
||||
cached["payload"] = payload
|
||||
cached["expires_at"] = now + ITSCREEN_CONFIG_CACHE_TTL_SEC
|
||||
return payload
|
||||
|
||||
|
||||
def get_itscreen_runtime_payload():
|
||||
now = datetime.now()
|
||||
payload = {
|
||||
"current_time": now.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"service_started_at": None,
|
||||
"uptime_seconds": None,
|
||||
"service_state": "unknown",
|
||||
"registration": {
|
||||
"registered": None,
|
||||
"server": None,
|
||||
},
|
||||
"sync": {
|
||||
"interval_sec": None,
|
||||
"interval_human": None,
|
||||
"last_contact_ts": None,
|
||||
"last_contact_iso": None,
|
||||
"next_contact_ts": None,
|
||||
"next_contact_iso": None,
|
||||
},
|
||||
"schedule": {
|
||||
"shutdown_enabled": None,
|
||||
"shutdown_time": None,
|
||||
"startup_enabled": None,
|
||||
"startup_time": None,
|
||||
"next_shutdown_ts": None,
|
||||
"next_shutdown_iso": None,
|
||||
"next_startup_ts": None,
|
||||
"next_startup_iso": None,
|
||||
},
|
||||
"reboot": {
|
||||
"enabled": None,
|
||||
"repeat_enabled": None,
|
||||
"repeat_interval": None,
|
||||
"daily_time": None,
|
||||
},
|
||||
"meta": {
|
||||
"updated_at_sec": None,
|
||||
"startup_delay": None,
|
||||
},
|
||||
}
|
||||
config_status = read_itscreen_config_status()
|
||||
if isinstance(config_status, dict):
|
||||
if config_status.get("status") == "not_installed":
|
||||
return {"status": "not_installed"}
|
||||
if config_status.get("status") == "error":
|
||||
return {"status": "error", "message": "invalid config format"}
|
||||
payload.update(config_status)
|
||||
sync = payload.get("sync") or {}
|
||||
payload["sync"]["next_contact_ts"] = (
|
||||
sync.get("last_contact_ts") + (sync.get("interval_sec") * 1000)
|
||||
if sync.get("last_contact_ts") is not None and sync.get("interval_sec") is not None
|
||||
else None
|
||||
)
|
||||
payload["sync"]["next_contact_iso"] = format_local_iso_from_ms(payload["sync"]["next_contact_ts"])
|
||||
try:
|
||||
active_state = str(systemctl_show_property(ITSCREEN_SERVICE_UNIT, "ActiveState") or "").strip().lower()
|
||||
if active_state in ("active", "inactive", "failed"):
|
||||
payload["service_state"] = active_state
|
||||
elif active_state:
|
||||
payload["service_state"] = "unknown"
|
||||
if payload["service_state"] != "active":
|
||||
return payload
|
||||
started_at = parse_systemctl_timestamp(systemctl_show_property(ITSCREEN_SERVICE_UNIT, "ActiveEnterTimestamp"))
|
||||
if not started_at:
|
||||
return payload
|
||||
uptime_seconds = int(max(0, (now - started_at).total_seconds()))
|
||||
payload["service_started_at"] = started_at.strftime("%Y-%m-%d %H:%M:%S")
|
||||
payload["uptime_seconds"] = uptime_seconds
|
||||
return payload
|
||||
except Exception:
|
||||
return payload
|
||||
|
||||
|
||||
def control_itscreen_service(action):
|
||||
action_name = str(action or "").strip().lower()
|
||||
if action_name not in ("start", "stop"):
|
||||
raise ValueError("Unsupported action")
|
||||
current = get_itscreen_service_status()
|
||||
if not current.get("installed"):
|
||||
raise RuntimeError("It-screen service is not installed")
|
||||
rc, _, stderr = run(["systemctl", action_name, ITSCREEN_SERVICE_UNIT], timeout=20)
|
||||
if rc != 0:
|
||||
verb = "start" if action_name == "start" else "stop"
|
||||
raise RuntimeError(f"Failed to {verb} service")
|
||||
invalidate_cache()
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "Service started" if action_name == "start" else "Service stopped",
|
||||
**build_itscreen_status_payload(),
|
||||
}
|
||||
|
||||
|
||||
def clamp_itscreen_log_lines(value, default=ITSCREEN_LOG_DEFAULT_LINES):
|
||||
try:
|
||||
parsed = int(value)
|
||||
except Exception:
|
||||
parsed = default
|
||||
return max(1, min(parsed, ITSCREEN_LOG_MAX_LINES))
|
||||
|
||||
|
||||
def read_itscreen_logs(lines):
|
||||
count = clamp_itscreen_log_lines(lines)
|
||||
if not shutil.which("journalctl"):
|
||||
raise RuntimeError("journalctl is unavailable")
|
||||
cmd = [
|
||||
"journalctl",
|
||||
"-u",
|
||||
ITSCREEN_SERVICE_UNIT,
|
||||
"-n",
|
||||
str(count),
|
||||
"--no-pager",
|
||||
"-o",
|
||||
"short-iso",
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
raise RuntimeError("journalctl is unavailable") from exc
|
||||
except Exception as exc:
|
||||
raise RuntimeError(str(exc)) from exc
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError((proc.stderr or "").strip() or "Failed to read service logs")
|
||||
return {
|
||||
"ok": True,
|
||||
"unit": ITSCREEN_SERVICE_UNIT,
|
||||
"lines": [line.rstrip("\n") for line in (proc.stdout or "").splitlines()],
|
||||
}
|
||||
|
||||
|
||||
def terminate_process(proc):
|
||||
if not proc:
|
||||
return
|
||||
try:
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=2)
|
||||
except Exception:
|
||||
try:
|
||||
proc.kill()
|
||||
proc.wait(timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
if proc.stdout:
|
||||
proc.stdout.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def restart_service_card(service_id):
|
||||
allowed_units = {
|
||||
"zigbee2mqtt": "zigbee2mqtt.service",
|
||||
|
|
@ -1201,6 +1866,83 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def send_sse_headers(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
|
||||
self.send_header("Pragma", "no-cache")
|
||||
self.send_header("Connection", "keep-alive")
|
||||
self.send_header("X-Accel-Buffering", "no")
|
||||
self.end_headers()
|
||||
|
||||
def stream_itscreen_logs(self):
|
||||
if not shutil.which("journalctl"):
|
||||
self.send_json({"ok": False, "error": "Logs are unavailable"}, code=503)
|
||||
return
|
||||
proc = None
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
[
|
||||
"journalctl",
|
||||
"-u",
|
||||
ITSCREEN_SERVICE_UNIT,
|
||||
"-f",
|
||||
"-n",
|
||||
"0",
|
||||
"--no-pager",
|
||||
"-o",
|
||||
"short-iso",
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
self.send_sse_headers()
|
||||
self.wfile.write(b": connected\n\n")
|
||||
self.wfile.flush()
|
||||
last_keepalive_at = time.time()
|
||||
while True:
|
||||
if proc.poll() is not None:
|
||||
stderr_text = ""
|
||||
try:
|
||||
stderr_text = (proc.stderr.read() or "").strip() if proc.stderr else ""
|
||||
except Exception:
|
||||
stderr_text = ""
|
||||
if proc.returncode not in (0, None):
|
||||
payload = json.dumps({"message": stderr_text or "Log stream disconnected"})
|
||||
self.wfile.write(f"event: error\ndata: {payload}\n\n".encode("utf-8"))
|
||||
self.wfile.flush()
|
||||
break
|
||||
ready = []
|
||||
if proc.stdout:
|
||||
try:
|
||||
ready, _, _ = select.select([proc.stdout], [], [], 1.0)
|
||||
except Exception:
|
||||
ready = []
|
||||
if not ready:
|
||||
if time.time() - last_keepalive_at >= 15:
|
||||
self.wfile.write(b": keepalive\n\n")
|
||||
self.wfile.flush()
|
||||
last_keepalive_at = time.time()
|
||||
continue
|
||||
line = proc.stdout.readline() if proc.stdout else ""
|
||||
if not line:
|
||||
continue
|
||||
payload = json.dumps({"line": line.rstrip("\n")})
|
||||
self.wfile.write(f"event: log\ndata: {payload}\n\n".encode("utf-8"))
|
||||
self.wfile.flush()
|
||||
last_keepalive_at = time.time()
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
except Exception as exc:
|
||||
try:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=503)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
terminate_process(proc)
|
||||
|
||||
def handle_captive_portal_probe(self, parsed):
|
||||
if not captive_portal_is_active():
|
||||
return False
|
||||
|
|
@ -1223,6 +1965,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
|
||||
def do_GET(self):
|
||||
parsed = urlparse(self.path)
|
||||
query = parse_qs(parsed.query or "")
|
||||
if self.handle_captive_portal_probe(parsed):
|
||||
return
|
||||
if parsed.path == "/api/status":
|
||||
|
|
@ -1265,6 +2008,45 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc), "networks": []}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/status":
|
||||
try:
|
||||
self.send_json(build_itscreen_status_payload())
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/runtime":
|
||||
try:
|
||||
self.send_json(get_itscreen_runtime_payload())
|
||||
except Exception as exc:
|
||||
self.send_json({
|
||||
"current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"service_started_at": None,
|
||||
"uptime_seconds": None,
|
||||
"service_state": "unknown",
|
||||
"update_interval": None,
|
||||
"last_contact_ts": None,
|
||||
"next_contact_ts": None,
|
||||
"enable_reboot": None,
|
||||
"enable_reboot_repeat": None,
|
||||
"reboot_repeat_time": None,
|
||||
"reboot_time": None,
|
||||
"enable_off_time": None,
|
||||
"enable_on_time": None,
|
||||
"next_off_time": None,
|
||||
"next_on_time": None,
|
||||
"error": str(exc),
|
||||
})
|
||||
return
|
||||
if parsed.path == "/api/itscreen/logs":
|
||||
try:
|
||||
lines = clamp_itscreen_log_lines((query.get("lines") or [ITSCREEN_LOG_DEFAULT_LINES])[0])
|
||||
self.send_json(read_itscreen_logs(lines))
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": "Logs are unavailable", "details": str(exc), "lines": []}, code=503)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/logs/stream":
|
||||
self.stream_itscreen_logs()
|
||||
return
|
||||
if parsed.path == "/api/itscreen/registration":
|
||||
try:
|
||||
self.send_json(get_registration_status())
|
||||
|
|
@ -1395,6 +2177,30 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/actions/audio-test":
|
||||
payload = self.read_json_body()
|
||||
if payload is None:
|
||||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
target = str(payload.get("target", "")).strip().lower()
|
||||
if target not in AUDIO_TARGETS:
|
||||
self.send_json({"ok": False, "error": "target must be hdmi or analog"}, code=400)
|
||||
return
|
||||
try:
|
||||
self.send_json(perform_audio_test(target))
|
||||
except ValueError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=400)
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/actions/reboot":
|
||||
try:
|
||||
self.send_json(request_reboot())
|
||||
except RuntimeError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/registration/register":
|
||||
payload = self.read_json_body()
|
||||
if payload is None:
|
||||
|
|
@ -1409,12 +2215,46 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/register":
|
||||
payload = self.read_json_body()
|
||||
if payload is None:
|
||||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
self.send_json(register_device(str(payload.get("host", ""))))
|
||||
except ValueError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=400)
|
||||
except RuntimeError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=502)
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/registration/reset":
|
||||
try:
|
||||
self.send_json(reset_registration())
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/service/start":
|
||||
try:
|
||||
self.send_json(control_itscreen_service("start"))
|
||||
except ValueError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=400)
|
||||
except RuntimeError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=502)
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/service/stop":
|
||||
try:
|
||||
self.send_json(control_itscreen_service("stop"))
|
||||
except ValueError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=400)
|
||||
except RuntimeError as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=502)
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/service/restart":
|
||||
payload = self.read_json_body()
|
||||
if payload is None:
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import json
|
|||
import os
|
||||
import queue
|
||||
import re
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
|
@ -17,9 +16,10 @@ except Exception:
|
|||
STATE_PATH = "/etc/iomatex/itscreen_registration.json"
|
||||
MQTT_URL = os.environ.get("ITSCREEN_MQTT_URL", "mqtt://127.0.0.1:1883").strip() or "mqtt://127.0.0.1:1883"
|
||||
LOGIN_PASSWORD = os.environ.get("ITSCREEN_DEVICE_PASSWORD", "eXXI0wkHBmNBnVbE").strip() or "eXXI0wkHBmNBnVbE"
|
||||
DEFAULT_SERVER = "rest.uae.iomatex.com"
|
||||
REGISTER_TIMEOUT_SEC = 25
|
||||
REPLY_TIMEOUT_SEC = 6
|
||||
PUBLISH_TIMEOUT_SEC = 2
|
||||
NOT_SPECIFIED = "Not specified"
|
||||
HOST_RE = re.compile(r"^(?=.{1,253}$)(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$")
|
||||
DEVICE_ID_PATH = "/userdata/device-id"
|
||||
DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
|
||||
|
|
@ -56,12 +56,16 @@ def validate_host(host):
|
|||
value = str(host or "").strip().lower()
|
||||
if not value:
|
||||
raise ValueError("Invalid server host")
|
||||
if any(ch.isspace() for ch in value):
|
||||
raise ValueError("Invalid server host")
|
||||
if "://" in value:
|
||||
raise ValueError("Invalid server host")
|
||||
if "/" in value:
|
||||
raise ValueError("Invalid server host")
|
||||
if value.endswith("."):
|
||||
value = value[:-1]
|
||||
if value and not value.startswith("rest."):
|
||||
value = f"rest.{value}"
|
||||
if not HOST_RE.fullmatch(value):
|
||||
raise ValueError("Invalid server host")
|
||||
return value
|
||||
|
|
@ -70,12 +74,12 @@ def validate_host(host):
|
|||
def _default_state():
|
||||
identity = _device_identity()
|
||||
return {
|
||||
"host": DEFAULT_SERVER,
|
||||
"host": "",
|
||||
"username": "",
|
||||
"password": "",
|
||||
"token": "",
|
||||
"organization": "",
|
||||
"device_name": identity["device_name"],
|
||||
"device_name": "",
|
||||
"device_id": identity["device_id"],
|
||||
"registered": False,
|
||||
"logged": False,
|
||||
|
|
@ -103,8 +107,6 @@ def load_state():
|
|||
pass
|
||||
identity = _device_identity()
|
||||
state["device_id"] = identity["device_id"]
|
||||
state["device_name"] = state.get("device_name") or identity["device_name"]
|
||||
state["host"] = state.get("host") or DEFAULT_SERVER
|
||||
return state
|
||||
|
||||
|
||||
|
|
@ -112,12 +114,12 @@ def save_state(state):
|
|||
os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True)
|
||||
safe = _default_state()
|
||||
safe.update({
|
||||
"host": str(state.get("host", DEFAULT_SERVER) or DEFAULT_SERVER),
|
||||
"host": str(state.get("host", "") or ""),
|
||||
"username": str(state.get("username", "") or ""),
|
||||
"password": str(state.get("password", "") or ""),
|
||||
"token": str(state.get("token", "") or ""),
|
||||
"organization": str(state.get("organization", "") or ""),
|
||||
"device_name": str(state.get("device_name", "") or _device_identity()["device_name"]),
|
||||
"device_name": str(state.get("device_name", "") or ""),
|
||||
"device_id": str(state.get("device_id", "") or _device_identity()["device_id"]),
|
||||
"registered": bool(state.get("registered", False)),
|
||||
"logged": bool(state.get("logged", False)),
|
||||
|
|
@ -157,6 +159,25 @@ def _truncate_empty(value):
|
|||
return text
|
||||
|
||||
|
||||
def _text_or_default(value, default=NOT_SPECIFIED):
|
||||
text = _truncate_empty(value)
|
||||
return text or default
|
||||
|
||||
|
||||
def _bool_value(value, default=False):
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in ("true", "1", "yes", "on"):
|
||||
return True
|
||||
if normalized in ("false", "0", "no", "off", ""):
|
||||
return False
|
||||
if value is None:
|
||||
return default
|
||||
return bool(value)
|
||||
|
||||
|
||||
def _extract_response_payload(response_text):
|
||||
raw = str(response_text or "").strip()
|
||||
if not raw:
|
||||
|
|
@ -196,6 +217,56 @@ def _extract_registration_fields(server_state, event_payload, persisted):
|
|||
return merged
|
||||
|
||||
|
||||
def _device_name_from_payload(payload):
|
||||
if not isinstance(payload, dict):
|
||||
return ""
|
||||
for key in ("device_name", "name", "given_name", "display_name", "username"):
|
||||
text = _truncate_empty(payload.get(key))
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _normalize_registration_payload(server_state, persisted=None, source="mqtt"):
|
||||
payload = server_state if isinstance(server_state, dict) else {}
|
||||
identity = _device_identity()
|
||||
username = _text_or_default(payload.get("username"))
|
||||
device_name = _device_name_from_payload(payload)
|
||||
return {
|
||||
"ok": True,
|
||||
"source": source,
|
||||
"device_id": identity["device_id"],
|
||||
"device_name": _text_or_default(device_name),
|
||||
"server": _text_or_default(payload.get("host")),
|
||||
"host": _text_or_default(payload.get("host")),
|
||||
"organization": _text_or_default(payload.get("organization")),
|
||||
"token": _text_or_default(payload.get("token")),
|
||||
"registered": _bool_value(payload.get("registered"), default=False),
|
||||
"logged": _bool_value(payload.get("logged"), default=False),
|
||||
"password_state": "Password set" if _truncate_empty(payload.get("password")) else NOT_SPECIFIED,
|
||||
"username": username,
|
||||
"status": "ready" if _bool_value(payload.get("registered"), default=False) else "not_registered",
|
||||
"last_event": (persisted or {}).get("last_event", {
|
||||
"action": "",
|
||||
"operation": "",
|
||||
"status": "",
|
||||
"timestamp": "",
|
||||
}),
|
||||
"raw": dict(payload),
|
||||
}
|
||||
|
||||
|
||||
def _public_error(exc):
|
||||
text = _truncate_empty(str(exc))
|
||||
if isinstance(exc, TimeoutError):
|
||||
return "It-screen status is unavailable", "MQTT response timeout"
|
||||
if text == "Invalid MQTT payload":
|
||||
return "It-screen status is unavailable", "Invalid MQTT payload"
|
||||
if text:
|
||||
return "It-screen status is unavailable", text
|
||||
return "It-screen status is unavailable", "Unknown backend error"
|
||||
|
||||
|
||||
class MqttSettingsSession:
|
||||
def __init__(self, device_id):
|
||||
if mqtt is None:
|
||||
|
|
@ -229,7 +300,7 @@ class MqttSettingsSession:
|
|||
try:
|
||||
payload = json.loads(raw)
|
||||
except Exception:
|
||||
payload = {"raw": raw}
|
||||
payload = {"__invalid_json__": raw}
|
||||
self.queue.put(payload)
|
||||
|
||||
def __enter__(self):
|
||||
|
|
@ -267,7 +338,11 @@ class MqttSettingsSession:
|
|||
def publish(self, payload):
|
||||
self._drain()
|
||||
result = self.client.publish(self.topics["sub"], json.dumps(payload), qos=0, retain=False)
|
||||
result.wait_for_publish(timeout=2)
|
||||
deadline = time.time() + PUBLISH_TIMEOUT_SEC
|
||||
while time.time() < deadline:
|
||||
if result.is_published():
|
||||
return
|
||||
time.sleep(0.05)
|
||||
if not result.is_published():
|
||||
raise RuntimeError("MQTT publish failed")
|
||||
|
||||
|
|
@ -281,19 +356,31 @@ class MqttSettingsSession:
|
|||
candidate = self.queue.get(timeout=0.25)
|
||||
except queue.Empty:
|
||||
continue
|
||||
if isinstance(candidate, dict) and candidate.get("__invalid_json__") is not None:
|
||||
raise RuntimeError("Invalid MQTT payload")
|
||||
if predicate(candidate):
|
||||
return candidate
|
||||
raise TimeoutError("No response from device")
|
||||
|
||||
def login(self):
|
||||
reply = self.publish_and_wait(
|
||||
{"action": "login", "password": LOGIN_PASSWORD},
|
||||
lambda item: isinstance(item, dict) and item.get("action") == "login",
|
||||
timeout=REPLY_TIMEOUT_SEC,
|
||||
)
|
||||
if not reply.get("result"):
|
||||
raise RuntimeError(reply.get("note") or reply.get("error") or "Login failed")
|
||||
return reply
|
||||
self.publish({"action": "login", "password": LOGIN_PASSWORD})
|
||||
deadline = time.time() + 1.0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
candidate = self.queue.get(timeout=0.1)
|
||||
except queue.Empty:
|
||||
continue
|
||||
if isinstance(candidate, dict) and candidate.get("__invalid_json__") is not None:
|
||||
raise RuntimeError("Invalid MQTT payload")
|
||||
if not isinstance(candidate, dict):
|
||||
continue
|
||||
if candidate.get("action") != "login":
|
||||
continue
|
||||
if candidate.get("result") is False:
|
||||
raise RuntimeError(candidate.get("note") or candidate.get("error") or "Login failed")
|
||||
if candidate.get("result") is True:
|
||||
return True
|
||||
return True
|
||||
|
||||
def get_server_state(self):
|
||||
return self.publish_and_wait(
|
||||
|
|
@ -333,25 +420,9 @@ class MqttSettingsSession:
|
|||
|
||||
|
||||
def _build_public_status(state, error_text=""):
|
||||
output = {
|
||||
"ok": True,
|
||||
"registered": bool(state.get("registered", False)),
|
||||
"logged": bool(state.get("logged", False)),
|
||||
"host": _truncate_empty(state.get("host")) or DEFAULT_SERVER,
|
||||
"username": _truncate_empty(state.get("username")),
|
||||
"password": _truncate_empty(state.get("password")),
|
||||
"token": _truncate_empty(state.get("token")) or None,
|
||||
"organization": _truncate_empty(state.get("organization")) or None,
|
||||
"device_name": _truncate_empty(state.get("device_name")) or _device_identity()["device_name"],
|
||||
"device_id": _device_identity()["device_id"],
|
||||
"status": _truncate_empty(state.get("status")) or "idle",
|
||||
"last_event": state.get("last_event", {
|
||||
"action": "",
|
||||
"operation": "",
|
||||
"status": "",
|
||||
"timestamp": "",
|
||||
}),
|
||||
}
|
||||
normalized = _normalize_registration_payload(state, persisted=state)
|
||||
normalized["status"] = _truncate_empty(state.get("status")) or normalized.get("status") or "idle"
|
||||
output = dict(normalized)
|
||||
if error_text:
|
||||
output["error"] = error_text
|
||||
return output
|
||||
|
|
@ -364,15 +435,36 @@ def get_registration_status():
|
|||
with MqttSettingsSession(state["device_id"]) as session:
|
||||
session.login()
|
||||
server_state = session.get_server_state()
|
||||
state = _extract_registration_fields(server_state, {}, state)
|
||||
state["logged"] = bool(server_state.get("logged"))
|
||||
state["registered"] = bool(server_state.get("registered"))
|
||||
state["status"] = "ready" if state["registered"] else "not_registered"
|
||||
save_state(state)
|
||||
return _build_public_status(state)
|
||||
current = {
|
||||
"host": _truncate_empty(server_state.get("host")),
|
||||
"username": _truncate_empty(server_state.get("username")),
|
||||
"password": _truncate_empty(server_state.get("password")),
|
||||
"token": _truncate_empty(server_state.get("token")),
|
||||
"organization": _truncate_empty(server_state.get("organization")),
|
||||
"device_name": _device_name_from_payload(server_state),
|
||||
"device_id": _device_identity()["device_id"],
|
||||
"registered": _bool_value(server_state.get("registered"), default=False),
|
||||
"logged": _bool_value(server_state.get("logged"), default=False),
|
||||
"status": "ready" if _bool_value(server_state.get("registered"), default=False) else "not_registered",
|
||||
"last_event": persisted.get("last_event", {
|
||||
"action": "",
|
||||
"operation": "",
|
||||
"status": "",
|
||||
"timestamp": "",
|
||||
}),
|
||||
}
|
||||
save_state(current)
|
||||
return _build_public_status(current)
|
||||
except Exception as exc:
|
||||
state["status"] = "error" if persisted.get("status") != "registering" else persisted.get("status")
|
||||
return _build_public_status(state, str(exc))
|
||||
fallback = _build_public_status(state)
|
||||
error_text, details = _public_error(exc)
|
||||
return {
|
||||
"ok": False,
|
||||
"error": error_text,
|
||||
"details": details,
|
||||
"data": fallback,
|
||||
}
|
||||
|
||||
|
||||
def register_device(host):
|
||||
|
|
@ -386,7 +478,9 @@ def register_device(host):
|
|||
try:
|
||||
with MqttSettingsSession(working["device_id"]) as session:
|
||||
session.login()
|
||||
session.get_server_state()
|
||||
current_server_state = session.get_server_state()
|
||||
if _bool_value((current_server_state or {}).get("registered"), default=False):
|
||||
raise RuntimeError("Device is already registered")
|
||||
session.set_server(validated_host)
|
||||
event = session.wait_registered_event()
|
||||
event_payload = _extract_response_payload(event.get("responseText"))
|
||||
|
|
|
|||
|
|
@ -7,15 +7,58 @@
|
|||
--accent:#0e7a53;
|
||||
--warn:#9a6a00;
|
||||
--error:#b93434;
|
||||
--surface-soft:#fbfcfb;
|
||||
--surface-muted:#f5f7f6;
|
||||
--surface-strong:#edf4f0;
|
||||
--bg-top:#f7faf8;
|
||||
--surface-empty:rgba(255,255,255,.6);
|
||||
--surface-connected:rgba(14,122,83,.08);
|
||||
--surface-idle:#f7f8f7;
|
||||
--button-primary:#16211d;
|
||||
--button-primary-hover:#22302b;
|
||||
--button-secondary:#eef3f1;
|
||||
--button-secondary-hover:#e4ece8;
|
||||
--button-danger:#7a1f1f;
|
||||
--button-danger-hover:#632020;
|
||||
--log-bg:#0f1714;
|
||||
--log-ink:#d9e4de;
|
||||
--log-empty:#93a39a;
|
||||
--shadow:0 12px 32px rgba(16,24,20,.08);
|
||||
}
|
||||
[data-theme="dark"]{
|
||||
--bg:#0f1513;
|
||||
--panel:#16211d;
|
||||
--ink:#eef5f1;
|
||||
--muted:#9cac9f;
|
||||
--line:#2a3833;
|
||||
--accent:#46c48d;
|
||||
--warn:#f0bc4f;
|
||||
--error:#ff7f7f;
|
||||
--surface-soft:#1a2622;
|
||||
--surface-muted:#1d2b26;
|
||||
--surface-strong:#21312b;
|
||||
--bg-top:#18211e;
|
||||
--surface-empty:rgba(22,33,29,.78);
|
||||
--surface-connected:rgba(70,196,141,.12);
|
||||
--surface-idle:#1a2521;
|
||||
--button-primary:#46c48d;
|
||||
--button-primary-hover:#59d89f;
|
||||
--button-secondary:#21312b;
|
||||
--button-secondary-hover:#294038;
|
||||
--button-danger:#c44b4b;
|
||||
--button-danger-hover:#d55f5f;
|
||||
--log-bg:#0b1110;
|
||||
--log-ink:#d8e6df;
|
||||
--log-empty:#86968e;
|
||||
--shadow:0 16px 40px rgba(0,0,0,.28);
|
||||
}
|
||||
*{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%);
|
||||
linear-gradient(180deg, var(--bg-top) 0%, var(--bg) 100%);
|
||||
color:var(--ink);
|
||||
}
|
||||
.shell{max-width:1180px;margin:0 auto;padding:28px 18px 40px}
|
||||
|
|
@ -57,18 +100,119 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
padding-top:6px;
|
||||
}
|
||||
.identityItem strong{font-size:15px}
|
||||
.hero{
|
||||
grid-template-columns:minmax(0,1.7fr) minmax(280px,.95fr) auto;
|
||||
align-items:start;
|
||||
}
|
||||
.actions{
|
||||
position:static;
|
||||
min-width:0;
|
||||
padding-top:0;
|
||||
}
|
||||
.menuToggleBtn{
|
||||
position:fixed;
|
||||
top:18px;
|
||||
right:18px;
|
||||
width:42px;
|
||||
height:42px;
|
||||
min-width:42px;
|
||||
padding:0;
|
||||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
background:var(--surface-soft);
|
||||
color:var(--ink);
|
||||
display:inline-flex;
|
||||
flex-direction:column;
|
||||
align-items:center;
|
||||
justify-content:center;
|
||||
gap:4px;
|
||||
cursor:pointer;
|
||||
box-shadow:var(--shadow);
|
||||
z-index:90;
|
||||
}
|
||||
.menuToggleBtn span{
|
||||
width:16px;
|
||||
height:2px;
|
||||
border-radius:999px;
|
||||
background:currentColor;
|
||||
display:block;
|
||||
}
|
||||
.menuToggleBtn.is-open{
|
||||
background:var(--surface-strong);
|
||||
}
|
||||
.actionMenu{
|
||||
position:fixed;
|
||||
top:68px;
|
||||
right:18px;
|
||||
width:min(240px,calc(100vw - 32px));
|
||||
display:grid;
|
||||
gap:6px;
|
||||
padding:10px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:16px;
|
||||
background:var(--panel);
|
||||
box-shadow:var(--shadow);
|
||||
z-index:85;
|
||||
}
|
||||
.actionMenu[hidden]{
|
||||
display:none !important;
|
||||
}
|
||||
.menuActionBtn{
|
||||
width:100%;
|
||||
border:0;
|
||||
border-radius:12px;
|
||||
background:transparent;
|
||||
color:var(--ink);
|
||||
padding:10px 12px;
|
||||
display:flex;
|
||||
align-items:center;
|
||||
justify-content:flex-end;
|
||||
gap:12px;
|
||||
flex-wrap:wrap;
|
||||
justify-content:flex-start;
|
||||
gap:10px;
|
||||
text-align:left;
|
||||
cursor:pointer;
|
||||
font:inherit;
|
||||
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);
|
||||
.menuActionBtn:hover:not(:disabled){
|
||||
background:var(--surface-soft);
|
||||
}
|
||||
.actions button,
|
||||
.menuActionBtn.is-danger{
|
||||
color:var(--error);
|
||||
}
|
||||
.menuActionBtn.is-danger:hover:not(:disabled){
|
||||
background:rgba(185,52,52,.10);
|
||||
}
|
||||
.menuActionIcon{
|
||||
width:18px;
|
||||
height:18px;
|
||||
display:inline-flex;
|
||||
align-items:center;
|
||||
justify-content:center;
|
||||
flex:0 0 18px;
|
||||
}
|
||||
.menuActionIcon svg{
|
||||
width:18px;
|
||||
height:18px;
|
||||
fill:none;
|
||||
stroke:currentColor;
|
||||
stroke-width:1.8;
|
||||
stroke-linecap:round;
|
||||
stroke-linejoin:round;
|
||||
}
|
||||
.menuActionLabel{
|
||||
flex:1 1 auto;
|
||||
}
|
||||
.menuBackdrop{
|
||||
position:fixed;
|
||||
inset:0;
|
||||
background:rgba(9,13,12,.14);
|
||||
z-index:80;
|
||||
}
|
||||
.menuBackdrop[hidden]{
|
||||
display:none !important;
|
||||
}
|
||||
.menuToggleBtn,
|
||||
.menuActionBtn,
|
||||
.tabBtn,
|
||||
.actionBtn,
|
||||
.toggleInlineBtn,
|
||||
|
|
@ -76,20 +220,23 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.field input{
|
||||
transition:background-color .16s ease,border-color .16s ease,color .16s ease,box-shadow .16s ease,transform .06s ease,opacity .16s ease;
|
||||
}
|
||||
.actions button:hover,
|
||||
.menuToggleBtn:hover,
|
||||
.menuActionBtn:hover:not(:disabled),
|
||||
.actionBtn:hover:not(:disabled),
|
||||
.tabBtn:hover:not(:disabled),
|
||||
.toggleInlineBtn:hover:not(:disabled){
|
||||
box-shadow:0 10px 24px rgba(16,24,20,.10);
|
||||
}
|
||||
.actions button:active,
|
||||
.menuToggleBtn:active,
|
||||
.menuActionBtn:active:not(:disabled),
|
||||
.actionBtn:active:not(:disabled),
|
||||
.tabBtn:active:not(:disabled),
|
||||
.toggleInlineBtn:active:not(:disabled),
|
||||
.scanRow:active{
|
||||
transform:translateY(1px);
|
||||
}
|
||||
.actions button:focus-visible,
|
||||
.menuToggleBtn:focus-visible,
|
||||
.menuActionBtn:focus-visible,
|
||||
.tabBtn:focus-visible,
|
||||
.actionBtn:focus-visible,
|
||||
.toggleInlineBtn:focus-visible,
|
||||
|
|
@ -105,14 +252,14 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px;
|
||||
}
|
||||
.tabBtn{
|
||||
border:1px solid var(--line);background:rgba(255,255,255,.8);color:var(--ink);
|
||||
border:1px solid var(--line);background:var(--surface-soft);color:var(--ink);
|
||||
border-radius:999px;padding:10px 16px;font-size:14px;font-weight:700;cursor:pointer;
|
||||
}
|
||||
.tabBtn.is-active{
|
||||
background:var(--ink);color:#fff;border-color:var(--ink);
|
||||
background:var(--button-primary);color:#fff;border-color:var(--button-primary);
|
||||
}
|
||||
.tabBtn:hover:not(.is-active):not(:disabled){
|
||||
background:#f7faf8;border-color:#bfd0c8;
|
||||
background:var(--surface-soft);border-color:var(--line);
|
||||
}
|
||||
.tabContent{display:grid;gap:18px}
|
||||
.tabPanel{display:grid;gap:18px}
|
||||
|
|
@ -130,15 +277,15 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
padding:12px 14px;
|
||||
border-radius:14px;
|
||||
box-shadow:var(--shadow);
|
||||
background:#ffffff;
|
||||
background:var(--panel);
|
||||
border:1px solid var(--line);
|
||||
color:var(--ink);
|
||||
font-size:13px;
|
||||
transition:opacity .2s ease,transform .2s ease;
|
||||
}
|
||||
.toast.success{border-color:rgba(14,122,83,.22);background:#f2faf6}
|
||||
.toast.error{border-color:rgba(185,52,52,.22);background:#fff4f4}
|
||||
.toast.warn{border-color:rgba(154,106,0,.24);background:#fff8ec}
|
||||
.toast.success{border-color:rgba(14,122,83,.22);background:rgba(14,122,83,.10)}
|
||||
.toast.error{border-color:rgba(185,52,52,.22);background:rgba(185,52,52,.10)}
|
||||
.toast.warn{border-color:rgba(154,106,0,.24);background:rgba(154,106,0,.10)}
|
||||
.toast.is-leaving{opacity:0;transform:translateY(8px)}
|
||||
.sectionHead{display:flex;justify-content:space-between;gap:12px;align-items:flex-end;flex-wrap:wrap}
|
||||
.sectionHead h2{margin:0;font-size:22px}
|
||||
|
|
@ -147,6 +294,10 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.cards{
|
||||
display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;
|
||||
}
|
||||
.itscreenCards{
|
||||
grid-template-columns:repeat(2,minmax(0,1fr));
|
||||
align-items:start;
|
||||
}
|
||||
.wideCard{grid-column:span 2}
|
||||
.card{padding:18px}
|
||||
.cards > .card{height:100%}
|
||||
|
|
@ -156,7 +307,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.cardSubtitle{margin:6px 0 0;color:var(--muted);font-size:13px}
|
||||
.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);
|
||||
background:var(--surface-strong);color:var(--ink);
|
||||
}
|
||||
.dot{width:9px;height:9px;border-radius:50%}
|
||||
.dot.ok{background:var(--accent)}
|
||||
|
|
@ -188,7 +339,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.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);
|
||||
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;background:var(--surface-muted);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)}
|
||||
|
|
@ -202,7 +353,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.tunnelSummaryItem{
|
||||
border:1px solid var(--line);
|
||||
border-radius:12px;
|
||||
background:#fbfcfb;
|
||||
background:var(--surface-soft);
|
||||
padding:10px 12px;
|
||||
display:grid;
|
||||
gap:4px;
|
||||
|
|
@ -224,7 +375,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.tunnelAccordion{
|
||||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
background:#fbfcfb;
|
||||
background:var(--surface-soft);
|
||||
overflow:hidden;
|
||||
}
|
||||
.tunnelAccordionToggle{
|
||||
|
|
@ -241,7 +392,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
cursor:pointer;
|
||||
font:inherit;
|
||||
}
|
||||
.tunnelAccordionToggle:hover{background:#f3f7f5}
|
||||
.tunnelAccordionToggle:hover{background:var(--surface-muted)}
|
||||
.tunnelAccordionLabel{font-size:13px;font-weight:700}
|
||||
.connectorSummaryText{
|
||||
margin-left:auto;
|
||||
|
|
@ -312,7 +463,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
}
|
||||
.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;
|
||||
padding:32px;border:1px dashed var(--line);border-radius:18px;background:var(--surface-empty);color:var(--muted);text-align:center;
|
||||
}
|
||||
.emptyInline{color:var(--muted);font-size:14px}
|
||||
.displayCard,.accessPointCard{grid-column:span 2}
|
||||
|
|
@ -320,14 +471,14 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
margin-top:16px;padding:16px 18px;border-radius:16px;border:1px solid var(--line);
|
||||
display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap;
|
||||
}
|
||||
.displayHero.is-connected,.apHero.is-enabled{background:rgba(14,122,83,.08)}
|
||||
.displayHero.is-empty,.apHero.is-disabled{background:#f7f8f7}
|
||||
.displayHero.is-connected,.apHero.is-enabled{background:var(--surface-connected)}
|
||||
.displayHero.is-empty,.apHero.is-disabled{background:var(--surface-idle)}
|
||||
.apExplanation{
|
||||
margin-top:14px;
|
||||
padding:14px 16px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
background:#fbfcfb;
|
||||
background:var(--surface-soft);
|
||||
}
|
||||
.apExplanation p{
|
||||
margin:8px 0 0;
|
||||
|
|
@ -347,7 +498,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.networkInterfaceBlock{
|
||||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
background:#fbfcfb;
|
||||
background:var(--surface-soft);
|
||||
padding:14px;
|
||||
}
|
||||
.networkInterfaceHead{
|
||||
|
|
@ -397,7 +548,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
padding:14px;
|
||||
background:#fbfcfb;
|
||||
background:var(--surface-soft);
|
||||
}
|
||||
.manualSteps{
|
||||
margin:10px 0 0;
|
||||
|
|
@ -408,18 +559,83 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.manualNotes{margin-top:10px}
|
||||
.connectorList{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
|
||||
.connectorListCompact{gap:10px}
|
||||
.connectorCard{border:1px solid var(--line);border-radius:14px;padding:11px 12px;background:#fbfcfb}
|
||||
.connectorCard{border:1px solid var(--line);border-radius:14px;padding:11px 12px;background:var(--surface-soft)}
|
||||
.connectorHead{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:8px}
|
||||
.connectorSubhead{margin-top:3px;color:var(--muted);font-size:12px}
|
||||
.connectorState{font-size:12px;font-weight:700;border-radius:999px;padding:6px 10px}
|
||||
.connectorState.is-connected{background:rgba(14,122,83,.10);color:var(--accent)}
|
||||
.connectorState.is-idle{background:rgba(154,106,0,.10);color:var(--warn)}
|
||||
.connectorState.is-error{background:rgba(185,52,52,.10);color:var(--error)}
|
||||
.connectorMeta{
|
||||
margin-top:0;
|
||||
grid-template-columns:110px 1fr;
|
||||
gap:6px 10px;
|
||||
font-size:12px;
|
||||
}
|
||||
.audioDeviceGrid{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(2,minmax(0,1fr));
|
||||
gap:12px;
|
||||
margin-top:12px;
|
||||
}
|
||||
.audioDeviceCard,
|
||||
.audioParamsCard{
|
||||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
background:var(--surface-soft);
|
||||
padding:14px;
|
||||
}
|
||||
.audioDeviceHead{
|
||||
display:flex;
|
||||
justify-content:space-between;
|
||||
gap:10px;
|
||||
align-items:flex-start;
|
||||
flex-wrap:wrap;
|
||||
}
|
||||
.audioDeviceSubhead{
|
||||
margin-top:4px;
|
||||
color:var(--muted);
|
||||
font-size:12px;
|
||||
}
|
||||
.audioDeviceMeta{
|
||||
margin-top:6px;
|
||||
color:var(--muted);
|
||||
font-size:12px;
|
||||
}
|
||||
.audioActionRow{
|
||||
display:flex;
|
||||
gap:10px;
|
||||
align-items:center;
|
||||
flex-wrap:wrap;
|
||||
margin-top:12px;
|
||||
}
|
||||
.audioTestSummary{
|
||||
display:flex;
|
||||
gap:8px;
|
||||
align-items:center;
|
||||
flex-wrap:wrap;
|
||||
margin-top:12px;
|
||||
}
|
||||
.audioTestTime{
|
||||
color:var(--muted);
|
||||
font-size:12px;
|
||||
}
|
||||
.diagBlock{
|
||||
margin:0;
|
||||
padding:10px 12px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:12px;
|
||||
background:var(--panel);
|
||||
color:var(--ink);
|
||||
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
|
||||
font-size:12px;
|
||||
line-height:1.45;
|
||||
white-space:pre-wrap;
|
||||
word-break:break-word;
|
||||
}
|
||||
.testOutput{
|
||||
margin-top:12px;
|
||||
}
|
||||
.modeBadge{
|
||||
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;
|
||||
}
|
||||
|
|
@ -430,22 +646,31 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
border:0;border-radius:12px;background:var(--ink);color:#fff;padding:10px 14px;font-weight:700;cursor:pointer;
|
||||
display:inline-flex;align-items:center;justify-content:center;text-decoration:none;
|
||||
}
|
||||
.actionBtn:hover:not(:disabled){background:#22302b}
|
||||
.actionBtn.secondary{background:#eef3f1;color:var(--ink);border:1px solid var(--line)}
|
||||
.actionBtn.secondary:hover:not(:disabled){background:#e4ece8}
|
||||
.actionBtn{background:var(--button-primary)}
|
||||
.actionBtn:hover:not(:disabled){background:var(--button-primary-hover)}
|
||||
.actionBtn.secondary{background:var(--button-secondary);color:var(--ink);border:1px solid var(--line)}
|
||||
.actionBtn.secondary:hover:not(:disabled){background:var(--button-secondary-hover)}
|
||||
.actionBtn:disabled{opacity:.5;cursor:not-allowed}
|
||||
.serviceActionRow{align-items:center}
|
||||
.actionBadge{
|
||||
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;
|
||||
background:#edf3f1;color:var(--muted);font-size:12px;font-weight:700;
|
||||
background:var(--surface-strong);color:var(--muted);font-size:12px;font-weight:700;
|
||||
}
|
||||
.actionBadge-ok{color:var(--accent)}
|
||||
.actionBadge-warn{color:var(--warn)}
|
||||
.actionBadge-error{color:var(--error)}
|
||||
.apForm{display:grid;gap:12px}
|
||||
.field{display:grid;gap:6px;font-size:13px;color:var(--ink)}
|
||||
.field input{
|
||||
width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:#fff;color:var(--ink);
|
||||
width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel);color:var(--ink);
|
||||
}
|
||||
.field input:hover{border-color:#bfd0c8}
|
||||
.field select{
|
||||
width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel);color:var(--ink);
|
||||
}
|
||||
.field input:hover{border-color:var(--line)}
|
||||
.field select:hover{border-color:var(--line)}
|
||||
.field input:focus-visible{border-color:var(--accent)}
|
||||
.field select:focus-visible{border-color:var(--accent)}
|
||||
.wrapValue{
|
||||
display:flex;
|
||||
align-items:center;
|
||||
|
|
@ -470,7 +695,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
padding:12px 14px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
background:#fbfcfb;
|
||||
background:var(--surface-soft);
|
||||
}
|
||||
.choiceRow input{margin-top:3px}
|
||||
.choiceRow span{font-weight:700}
|
||||
|
|
@ -483,9 +708,9 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.passwordField{display:flex;gap:8px;align-items:center}
|
||||
.passwordField input{flex:1 1 auto}
|
||||
.toggleInlineBtn{
|
||||
border:1px solid var(--line);border-radius:12px;background:#f6f8f7;color:var(--ink);padding:10px 12px;font-weight:700;cursor:pointer;white-space:nowrap;
|
||||
border:1px solid var(--line);border-radius:12px;background:var(--surface-muted);color:var(--ink);padding:10px 12px;font-weight:700;cursor:pointer;white-space:nowrap;
|
||||
}
|
||||
.toggleInlineBtn:hover:not(:disabled){background:#edf3f0}
|
||||
.toggleInlineBtn:hover:not(:disabled){background:var(--surface-strong)}
|
||||
.formHint{font-size:12px;color:var(--muted)}
|
||||
.formError{font-size:12px;color:var(--error);font-weight:600}
|
||||
.banner{
|
||||
|
|
@ -501,9 +726,9 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
}
|
||||
.scanRow{
|
||||
display:flex;justify-content:space-between;gap:12px;align-items:center;
|
||||
border:1px solid var(--line);border-radius:12px;background:#fbfcfb;padding:12px 14px;
|
||||
border:1px solid var(--line);border-radius:12px;background:var(--surface-soft);padding:12px 14px;
|
||||
}
|
||||
.scanRow:hover{background:#f4f8f6;border-color:#bfd0c8}
|
||||
.scanRow:hover{background:var(--surface-muted);border-color:var(--line)}
|
||||
.scanMain{display:grid;gap:6px;min-width:0}
|
||||
.scanTopLine{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
||||
.scanSsid{font-weight:700}
|
||||
|
|
@ -514,7 +739,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
display:inline-flex;align-items:center;border-radius:999px;padding:4px 8px;font-size:11px;font-weight:700;
|
||||
}
|
||||
.scanActiveBadge{background:rgba(14,122,83,.10);color:var(--accent)}
|
||||
.scanHiddenBadge{background:#edf3f1;color:var(--muted)}
|
||||
.scanHiddenBadge{background:var(--surface-strong);color:var(--muted)}
|
||||
.scanSignalRow{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
|
||||
.scanSignalText{font-size:13px;color:var(--muted)}
|
||||
.signalBars{display:inline-flex;align-items:flex-end;gap:3px;height:16px}
|
||||
|
|
@ -531,6 +756,86 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
width:10px;height:10px;border-radius:50%;background:var(--accent);display:inline-block;
|
||||
animation:pulse 1s ease-in-out infinite;
|
||||
}
|
||||
.itscreenLogsCard{
|
||||
display:grid;
|
||||
gap:14px;
|
||||
grid-column:1 / -1;
|
||||
}
|
||||
.itscreenLogsToolbar{
|
||||
display:grid;
|
||||
grid-template-columns:minmax(220px,1fr) auto auto;
|
||||
gap:12px;
|
||||
align-items:end;
|
||||
}
|
||||
.itscreenLogsSearchField{margin:0}
|
||||
.itscreenLogsActions{
|
||||
display:flex;
|
||||
gap:10px;
|
||||
flex-wrap:wrap;
|
||||
justify-content:flex-end;
|
||||
}
|
||||
.itscreenLogsToggle{
|
||||
display:inline-flex;
|
||||
align-items:center;
|
||||
gap:8px;
|
||||
align-self:center;
|
||||
padding:10px 12px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:12px;
|
||||
background:var(--surface-soft);
|
||||
font-size:13px;
|
||||
font-weight:600;
|
||||
}
|
||||
.itscreenLogsToggle input{margin:0}
|
||||
.itscreenLogsSummary{
|
||||
display:flex;
|
||||
justify-content:space-between;
|
||||
gap:10px;
|
||||
align-items:center;
|
||||
flex-wrap:wrap;
|
||||
}
|
||||
.logStatus{
|
||||
display:inline-flex;
|
||||
align-items:center;
|
||||
border-radius:999px;
|
||||
padding:6px 10px;
|
||||
font-size:12px;
|
||||
font-weight:700;
|
||||
}
|
||||
.logStatus-ok{background:rgba(14,122,83,.10);color:var(--accent)}
|
||||
.logStatus-warn{background:rgba(154,106,0,.10);color:var(--warn)}
|
||||
.logStatus-error{background:rgba(185,52,52,.10);color:var(--error)}
|
||||
.itscreenLogsCount{
|
||||
color:var(--muted);
|
||||
font-size:12px;
|
||||
}
|
||||
.itscreenLogsBody{
|
||||
min-height:340px;
|
||||
max-height:420px;
|
||||
overflow:auto;
|
||||
padding:12px 14px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:14px;
|
||||
background:var(--log-bg);
|
||||
color:var(--log-ink);
|
||||
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
|
||||
font-size:12px;
|
||||
line-height:1.45;
|
||||
}
|
||||
.logLine{
|
||||
white-space:pre-wrap;
|
||||
word-break:break-word;
|
||||
}
|
||||
.logLine + .logLine{margin-top:4px}
|
||||
.itscreenLogsBody mark{
|
||||
background:rgba(255,214,102,.35);
|
||||
color:#fff4cc;
|
||||
padding:0 1px;
|
||||
border-radius:3px;
|
||||
}
|
||||
.logEmpty{
|
||||
color:var(--log-empty);
|
||||
}
|
||||
@keyframes pulse{
|
||||
0%,100%{opacity:.35;transform:scale(.9)}
|
||||
50%{opacity:1;transform:scale(1)}
|
||||
|
|
@ -539,6 +844,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.hero{grid-template-columns:1fr}
|
||||
.identityPanel{min-width:0}
|
||||
.gboxHero{grid-template-columns:1fr}
|
||||
.itscreenCards{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
}
|
||||
@media (max-width:720px){
|
||||
.meta{grid-template-columns:1fr 1fr}
|
||||
|
|
@ -549,9 +855,22 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.tunnelSummaryGrid{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.brandDevice{width:min(70vw, 260px);max-height:180px}
|
||||
.wideCard,.displayCard,.accessPointCard{grid-column:auto}
|
||||
.audioDeviceGrid{grid-template-columns:1fr}
|
||||
.displayHeroText{font-size:18px}
|
||||
.itscreenCards{grid-template-columns:1fr}
|
||||
.itscreenLogsToolbar{grid-template-columns:1fr}
|
||||
.itscreenLogsActions{justify-content:flex-start}
|
||||
}
|
||||
@media (max-width:680px){
|
||||
.menuToggleBtn{
|
||||
top:16px;
|
||||
right:16px;
|
||||
}
|
||||
.actionMenu{
|
||||
top:64px;
|
||||
right:16px;
|
||||
width:min(240px,calc(100vw - 24px));
|
||||
}
|
||||
.connectorSummaryText{
|
||||
width:100%;
|
||||
margin-left:0;
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -5,6 +5,16 @@
|
|||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>IOMATEX Console</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<script>
|
||||
(function () {
|
||||
try {
|
||||
var theme = localStorage.getItem("consoleTheme");
|
||||
if (theme === "dark" || theme === "light") {
|
||||
document.documentElement.setAttribute("data-theme", theme);
|
||||
}
|
||||
} catch (error) {}
|
||||
})();
|
||||
</script>
|
||||
<link rel="stylesheet" href="/console.css">
|
||||
</head>
|
||||
<body>
|
||||
|
|
@ -34,7 +44,23 @@
|
|||
</div>
|
||||
</section>
|
||||
<div class="actions">
|
||||
<button id="refreshBtn" type="button">Refresh</button>
|
||||
<button id="menuToggleBtn" class="menuToggleBtn" type="button" aria-label="Open menu" aria-expanded="false" aria-controls="actionMenu" title="Open menu">
|
||||
<span></span><span></span><span></span>
|
||||
</button>
|
||||
<div id="actionMenu" class="actionMenu" hidden>
|
||||
<button id="themeToggleBtn" class="menuActionBtn" type="button" aria-label="Switch theme" title="Switch theme">
|
||||
<span class="menuActionIcon" id="themeToggleIcon" aria-hidden="true"></span>
|
||||
<span class="menuActionLabel">Theme</span>
|
||||
</button>
|
||||
<button id="refreshBtn" class="menuActionBtn" type="button">
|
||||
<span class="menuActionIcon" aria-hidden="true">↻</span>
|
||||
<span class="menuActionLabel">Refresh</span>
|
||||
</button>
|
||||
<button id="rebootBtn" class="menuActionBtn is-danger" type="button">
|
||||
<span class="menuActionIcon" aria-hidden="true">⏻</span>
|
||||
<span class="menuActionLabel">Reboot</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
|
@ -47,6 +73,7 @@
|
|||
|
||||
<section id="tabContent" class="tabContent" aria-live="polite"></section>
|
||||
</main>
|
||||
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
|
||||
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
|
||||
<script src="/console.js"></script>
|
||||
</body>
|
||||
|
|
|
|||
|
|
@ -798,6 +798,7 @@ def display_card(ctx):
|
|||
connected = [item for item in connectors if item["connected"]]
|
||||
connected.sort(key=_connector_priority, reverse=True)
|
||||
primary = connected[0] if connected else {}
|
||||
audio = ctx["get_audio_diagnostics"]()
|
||||
|
||||
drm_available = bool(ctx["file_exists"](DRM_ROOT))
|
||||
active = bool(primary)
|
||||
|
|
@ -829,6 +830,7 @@ def display_card(ctx):
|
|||
warnings[:2],
|
||||
details=_display_details(primary),
|
||||
connectors=connectors,
|
||||
audio_diagnostics=audio,
|
||||
display_status={
|
||||
"connected": active,
|
||||
"interface": interface,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,5 @@
|
|||
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.
|
||||
|
|
|
|||
|
|
@ -1,207 +0,0 @@
|
|||
#!/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"
|
||||
|
|
@ -1,765 +0,0 @@
|
|||
#!/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"
|
||||
|
|
@ -1,207 +0,0 @@
|
|||
#!/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"
|
||||
|
|
@ -1,765 +0,0 @@
|
|||
#!/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"
|
||||
Loading…
Reference in New Issue