Dashboard_local
This commit is contained in:
parent
1f22546aa0
commit
fce014a283
|
|
@ -5,20 +5,54 @@ This stage deploys standalone dashboards on dedicated ports without touching the
|
|||
## Model
|
||||
- `dashboard_id = port`
|
||||
- current runtime source directory: `/var/lib/itscreen/Downloads/it-screen/`
|
||||
- component source file for auto-generated editors: `/var/lib/itscreen/data/it-screen/it-screen/items.json`
|
||||
- deployed runtime lives in `/opt/iomatex-dashboards/`
|
||||
- one systemd instance serves one dashboard: `iomatex-dashboard@<port>.service`
|
||||
- one sync service auto-creates component dashboard instances from `items.json`: `iomatex-component-dashboards.service`
|
||||
- one path watcher reacts to `items.json` changes: `iomatex-component-dashboards.path`
|
||||
- current HTML selection mode: newest `.html` file by modification time
|
||||
- dashboard server proxies bridge API:
|
||||
- `/api/bridge/event` -> `http://127.0.0.1:8787/api/event`
|
||||
- `/api/bridge/component` -> `http://127.0.0.1:8787/api/component`
|
||||
- `/api/bridge/health` -> `http://127.0.0.1:8787/api/health`
|
||||
|
||||
## Current behavior for `5678`
|
||||
- service reads `.html` files from `/var/lib/itscreen/Downloads/it-screen/`
|
||||
- if at least one `.html` file exists, `/` returns the selected file as the dashboard entrypoint
|
||||
- if no `.html` file exists, `/` returns fallback page: `No dashboard HTML file found`
|
||||
- non-HTML static files from the same directory remain directly accessible by path
|
||||
- HTML for LAN clients should call same-origin bridge routes, for example `/api/bridge/event`
|
||||
## Modes
|
||||
- `static`
|
||||
- existing behavior
|
||||
- one HTML dashboard on a fixed port
|
||||
- `/` serves the selected `.html` from `/var/lib/itscreen/Downloads/it-screen/`
|
||||
- `component_index`
|
||||
- common entry page on the main dashboard port
|
||||
- reads `elements[]` from `items.json`
|
||||
- shows a select with all available ids
|
||||
- opens the selected dashboard on `http://localhost:<id>`
|
||||
- `component`
|
||||
- one lightweight page per `elements[].id`
|
||||
- service port equals the element id, for example `5771 -> http://localhost:5771`
|
||||
- `/` serves a built-in minimal component page
|
||||
- `GET /api/component` reads the current component from `items.json`
|
||||
|
||||
## Current main step
|
||||
- the main dashboard instance is configured in `component_index` mode
|
||||
- the entry page lists all `elements[].id`
|
||||
- each dedicated dashboard page currently shows only:
|
||||
- `id`
|
||||
- `title`
|
||||
- `duration`
|
||||
|
||||
## Component dashboard behavior
|
||||
- installer deploys the runtime and starts `iomatex-component-dashboards.service`
|
||||
- installer also enables `iomatex-component-dashboards.path`
|
||||
- the sync service reads `/var/lib/itscreen/data/it-screen/it-screen/items.json`
|
||||
- ids are taken from `elements[].id`
|
||||
- for every id it writes `/etc/iomatex/dashboards.d/<id>.env` with `DASHBOARD_MODE=component`
|
||||
- then it enables `iomatex-dashboard@<id>.service`
|
||||
- the entry page is served by the main dashboard port in `component_index` mode
|
||||
- each component page reads the component by id and shows only `id`, `title`, `duration`
|
||||
- `items.json` changes are handled by `systemd.path`, not by polling loops
|
||||
- sync uses a short debounce window before reading the file
|
||||
- existing `:<id>` dashboards are kept running when only component content changes, because pages read fresh data directly from `items.json`
|
||||
- dashboards are created for new ids and removed for stale ids
|
||||
|
||||
## Install
|
||||
```bash
|
||||
|
|
@ -30,6 +64,17 @@ sudo bash stage_dashboards/dashboard_installer.sh
|
|||
ls -lah /var/lib/itscreen/Downloads/it-screen/
|
||||
curl -I http://127.0.0.1:5678/
|
||||
curl http://127.0.0.1:5678/
|
||||
curl http://127.0.0.1:5678/api/components-index
|
||||
systemctl status iomatex-dashboard@5678.service --no-pager -n 40
|
||||
journalctl -u iomatex-dashboard@5678.service --no-pager -n 50
|
||||
systemctl status iomatex-component-dashboards.service --no-pager -n 50
|
||||
systemctl status iomatex-component-dashboards.path --no-pager -n 50
|
||||
curl http://127.0.0.1:5771/api/component
|
||||
```
|
||||
|
||||
## Example check for component `5771`
|
||||
```bash
|
||||
systemctl status iomatex-dashboard@5771.service --no-pager -n 40
|
||||
curl -I http://127.0.0.1:5771/
|
||||
curl http://127.0.0.1:5771/api/component | jq '.component | {id, title, duration}'
|
||||
```
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,238 @@
|
|||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from component_dashboard import DEFAULT_ITEMS_PATH, extract_elements_list
|
||||
|
||||
|
||||
DEFAULT_CFG_DIR = "/etc/iomatex/dashboards.d"
|
||||
DEFAULT_APP_DIR = "/opt/iomatex-dashboards"
|
||||
DEFAULT_SOURCE_DIR = "/var/lib/itscreen/Downloads/it-screen"
|
||||
DEFAULT_SELECTION_MODE = "newest"
|
||||
DEFAULT_BIND = "0.0.0.0"
|
||||
DEFAULT_BRIDGE_URL = "http://127.0.0.1:8787"
|
||||
DEFAULT_TEMPLATE_NAME = "iomatex-dashboard@{}.service"
|
||||
DEFAULT_STATE_PATH = "/var/lib/iomatex-dashboards/component_sync_state.json"
|
||||
DEFAULT_DEBOUNCE_SECONDS = 2.0
|
||||
|
||||
|
||||
def log(message):
|
||||
print(f"[component-dashboard-sync] {message}", file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def build_parser():
|
||||
parser = argparse.ArgumentParser(description="Sync component dashboards from items.json into systemd instances")
|
||||
parser.add_argument("--items-path", default=os.environ.get("DASHBOARD_ITEMS_PATH", DEFAULT_ITEMS_PATH))
|
||||
parser.add_argument("--cfg-dir", default=os.environ.get("DASHBOARD_CFG_DIR", DEFAULT_CFG_DIR))
|
||||
parser.add_argument("--app-dir", default=os.environ.get("DASHBOARD_APP_DIR", DEFAULT_APP_DIR))
|
||||
parser.add_argument("--bind", default=os.environ.get("DASHBOARD_BIND", DEFAULT_BIND))
|
||||
parser.add_argument("--source-dir", default=os.environ.get("DASHBOARD_SOURCE_DIR", DEFAULT_SOURCE_DIR))
|
||||
parser.add_argument("--selection-mode", default=os.environ.get("DASHBOARD_SELECTION_MODE", DEFAULT_SELECTION_MODE))
|
||||
parser.add_argument("--bridge-url", default=os.environ.get("DASHBOARD_BRIDGE_URL", DEFAULT_BRIDGE_URL))
|
||||
parser.add_argument("--template-name", default=os.environ.get("DASHBOARD_SERVICE_TEMPLATE", DEFAULT_TEMPLATE_NAME))
|
||||
parser.add_argument("--state-path", default=os.environ.get("DASHBOARD_SYNC_STATE_PATH", DEFAULT_STATE_PATH))
|
||||
parser.add_argument(
|
||||
"--debounce-seconds",
|
||||
type=float,
|
||||
default=float(os.environ.get("DASHBOARD_SYNC_DEBOUNCE_SECONDS", str(DEFAULT_DEBOUNCE_SECONDS))),
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def load_component_records(items_path):
|
||||
target = Path(items_path)
|
||||
if not target.exists():
|
||||
log(f"items.json not found at {target}; nothing to sync")
|
||||
return {}
|
||||
payload = json.loads(target.read_text(encoding="utf-8"))
|
||||
_container, elements = extract_elements_list(payload)
|
||||
desired = {}
|
||||
for element in elements:
|
||||
if not isinstance(element, dict):
|
||||
continue
|
||||
component_id = str(element.get("id", "")).strip()
|
||||
if not component_id:
|
||||
continue
|
||||
desired[component_id] = {
|
||||
"id": component_id,
|
||||
"fingerprint": element_fingerprint(element),
|
||||
}
|
||||
return desired
|
||||
|
||||
|
||||
def element_fingerprint(element):
|
||||
payload = json.dumps(element, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def parse_env_file(path):
|
||||
data = {}
|
||||
if not path.exists():
|
||||
return data
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("#") or "=" not in stripped:
|
||||
continue
|
||||
key, value = stripped.split("=", 1)
|
||||
data[key.strip()] = value.strip()
|
||||
return data
|
||||
|
||||
|
||||
def discover_managed_components(cfg_dir):
|
||||
managed = {}
|
||||
cfg_path = Path(cfg_dir)
|
||||
if not cfg_path.exists():
|
||||
return managed
|
||||
for env_path in cfg_path.glob("*.env"):
|
||||
component_id = env_path.stem
|
||||
config = parse_env_file(env_path)
|
||||
if config.get("DASHBOARD_MODE") == "component":
|
||||
managed[component_id] = env_path
|
||||
return managed
|
||||
|
||||
|
||||
def load_previous_state(state_path):
|
||||
path = Path(state_path)
|
||||
if not path.exists():
|
||||
return {"components": {}}
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
except Exception as exc:
|
||||
log(f"failed to read previous state {path}: {exc}")
|
||||
return {"components": {}}
|
||||
if not isinstance(payload, dict):
|
||||
return {"components": {}}
|
||||
components = payload.get("components")
|
||||
if not isinstance(components, dict):
|
||||
return {"components": {}}
|
||||
return {"components": components}
|
||||
|
||||
|
||||
def save_state(state_path, components):
|
||||
path = Path(state_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
"updated_at": int(time.time()),
|
||||
"components": components,
|
||||
}
|
||||
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def wait_for_stable_items_file(items_path, debounce_seconds):
|
||||
target = Path(items_path)
|
||||
if debounce_seconds <= 0:
|
||||
return
|
||||
if not target.exists():
|
||||
time.sleep(debounce_seconds)
|
||||
return
|
||||
while True:
|
||||
before = target.stat().st_mtime_ns
|
||||
time.sleep(debounce_seconds)
|
||||
if not target.exists():
|
||||
return
|
||||
after = target.stat().st_mtime_ns
|
||||
if before == after:
|
||||
return
|
||||
log(f"items.json changed again during debounce window; waiting another {debounce_seconds:.1f}s")
|
||||
|
||||
|
||||
def write_component_env(env_path, component_id, args):
|
||||
content = "\n".join(
|
||||
[
|
||||
f"DASHBOARD_ID={component_id}",
|
||||
f"DASHBOARD_PORT={component_id}",
|
||||
"DASHBOARD_MODE=component",
|
||||
f"DASHBOARD_BIND={args.bind}",
|
||||
f"DASHBOARD_APP_DIR={args.app_dir}",
|
||||
f"DASHBOARD_ROOT={args.app_dir}/dashboards/{component_id}",
|
||||
f"DASHBOARD_SOURCE_DIR={args.source_dir}",
|
||||
f"DASHBOARD_SELECTION_MODE={args.selection_mode}",
|
||||
f"DASHBOARD_BRIDGE_URL={args.bridge_url}",
|
||||
f"DASHBOARD_ITEMS_PATH={args.items_path}",
|
||||
"",
|
||||
]
|
||||
)
|
||||
env_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
env_path.write_text(content, encoding="utf-8")
|
||||
|
||||
|
||||
def run_systemctl(*arguments):
|
||||
command = ["systemctl", *arguments]
|
||||
result = subprocess.run(
|
||||
command,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
stderr = (result.stderr or "").strip()
|
||||
if stderr:
|
||||
log(f"{' '.join(command)} -> {stderr}")
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def is_service_active(service_name):
|
||||
result = subprocess.run(
|
||||
["systemctl", "is-active", "--quiet", service_name],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def main():
|
||||
args = build_parser().parse_args()
|
||||
wait_for_stable_items_file(args.items_path, args.debounce_seconds)
|
||||
desired_records = load_component_records(args.items_path)
|
||||
desired_ids = sorted(desired_records, key=lambda item: int(item) if item.isdigit() else item)
|
||||
managed = discover_managed_components(args.cfg_dir)
|
||||
previous_state = load_previous_state(args.state_path)
|
||||
previous_components = previous_state.get("components", {})
|
||||
desired_set = set(desired_ids)
|
||||
managed_set = set(managed)
|
||||
|
||||
log(f"desired component dashboards: {', '.join(desired_ids) if desired_ids else 'none'}")
|
||||
|
||||
for stale_id in sorted(managed_set - desired_set, key=lambda item: int(item) if item.isdigit() else item):
|
||||
service_name = args.template_name.format(stale_id)
|
||||
log(f"removing stale component dashboard {stale_id}")
|
||||
run_systemctl("disable", "--now", service_name)
|
||||
try:
|
||||
managed[stale_id].unlink()
|
||||
except OSError as exc:
|
||||
log(f"failed to remove env file for {stale_id}: {exc}")
|
||||
|
||||
for component_id in desired_ids:
|
||||
env_path = Path(args.cfg_dir) / f"{component_id}.env"
|
||||
existing = parse_env_file(env_path)
|
||||
if env_path.exists() and existing.get("DASHBOARD_MODE", "static") != "component":
|
||||
log(f"skipping component dashboard {component_id}: {env_path} is managed by another dashboard mode")
|
||||
continue
|
||||
write_component_env(env_path, component_id, args)
|
||||
service_name = args.template_name.format(component_id)
|
||||
previous = previous_components.get(component_id)
|
||||
current = desired_records.get(component_id, {})
|
||||
if is_service_active(service_name):
|
||||
if previous and previous.get("fingerprint") == current.get("fingerprint"):
|
||||
log(f"keeping active component dashboard {component_id} unchanged")
|
||||
else:
|
||||
log(f"keeping active component dashboard {component_id}; content changed but restart is not required")
|
||||
continue
|
||||
log(f"starting component dashboard {component_id}")
|
||||
run_systemctl("enable", "--now", service_name)
|
||||
|
||||
save_state(args.state_path, desired_records)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -12,6 +12,13 @@ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
|||
from pathlib import Path
|
||||
from urllib.parse import urlencode, urlparse
|
||||
|
||||
from component_dashboard import (
|
||||
DEFAULT_ITEMS_PATH,
|
||||
ItemsCatalogStore,
|
||||
ItemsComponentStore,
|
||||
render_component_dashboard_html,
|
||||
render_component_index_html,
|
||||
)
|
||||
from dashboard_locator import DEFAULT_SELECTION_MODE, select_dashboard_html
|
||||
|
||||
|
||||
|
|
@ -20,6 +27,7 @@ DEFAULT_PORT = 5678
|
|||
DEFAULT_APP_DIR = "/opt/iomatex-dashboards"
|
||||
DEFAULT_SOURCE_DIR = "/var/lib/itscreen/Downloads/it-screen"
|
||||
DEFAULT_BRIDGE_URL = "http://127.0.0.1:8787"
|
||||
DEFAULT_MODE = "static"
|
||||
|
||||
|
||||
def env_int(name, default):
|
||||
|
|
@ -37,6 +45,7 @@ def build_parser():
|
|||
parser.add_argument("--bind", default=os.environ.get("DASHBOARD_BIND", DEFAULT_BIND))
|
||||
parser.add_argument("--port", type=int, default=env_int("DASHBOARD_PORT", DEFAULT_PORT))
|
||||
parser.add_argument("--dashboard-id", default=os.environ.get("DASHBOARD_ID", ""))
|
||||
parser.add_argument("--mode", default=os.environ.get("DASHBOARD_MODE", DEFAULT_MODE))
|
||||
parser.add_argument("--root", default=os.environ.get("DASHBOARD_ROOT", ""))
|
||||
parser.add_argument("--source-dir", default=os.environ.get("DASHBOARD_SOURCE_DIR", DEFAULT_SOURCE_DIR))
|
||||
parser.add_argument(
|
||||
|
|
@ -44,6 +53,7 @@ def build_parser():
|
|||
default=os.environ.get("DASHBOARD_SELECTION_MODE", DEFAULT_SELECTION_MODE),
|
||||
)
|
||||
parser.add_argument("--bridge-url", default=os.environ.get("DASHBOARD_BRIDGE_URL", DEFAULT_BRIDGE_URL))
|
||||
parser.add_argument("--items-path", default=os.environ.get("DASHBOARD_ITEMS_PATH", DEFAULT_ITEMS_PATH))
|
||||
return parser
|
||||
|
||||
|
||||
|
|
@ -79,22 +89,28 @@ class BridgeProxy:
|
|||
|
||||
|
||||
class DashboardHandler(SimpleHTTPRequestHandler):
|
||||
server_version = "IOMATEXDashboardHTTP/0.2"
|
||||
server_version = "IOMATEXDashboardHTTP/0.3"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args,
|
||||
directory=None,
|
||||
dashboard_id=None,
|
||||
dashboard_mode=DEFAULT_MODE,
|
||||
source_dir=None,
|
||||
selection_mode=None,
|
||||
bridge_proxy=None,
|
||||
component_store=None,
|
||||
catalog_store=None,
|
||||
**kwargs,
|
||||
):
|
||||
self.dashboard_id = str(dashboard_id or "").strip()
|
||||
self.dashboard_mode = str(dashboard_mode or DEFAULT_MODE).strip().lower() or DEFAULT_MODE
|
||||
self.source_dir = Path(source_dir).resolve() if source_dir else None
|
||||
self.selection_mode = str(selection_mode or DEFAULT_SELECTION_MODE).strip().lower()
|
||||
self.bridge_proxy = bridge_proxy
|
||||
self.component_store = component_store
|
||||
self.catalog_store = catalog_store
|
||||
super().__init__(*args, directory=directory, **kwargs)
|
||||
|
||||
def select_entrypoint(self):
|
||||
|
|
@ -178,6 +194,22 @@ class DashboardHandler(SimpleHTTPRequestHandler):
|
|||
self.wfile.write(payload)
|
||||
|
||||
def serve_entrypoint(self):
|
||||
if self.dashboard_mode == "component":
|
||||
payload = render_component_dashboard_html(self.dashboard_id).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
return
|
||||
if self.dashboard_mode == "component_index":
|
||||
payload = render_component_index_html(self.dashboard_id).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
return
|
||||
selection = self.select_entrypoint()
|
||||
if not selection:
|
||||
self.send_fallback_page()
|
||||
|
|
@ -289,6 +321,54 @@ class DashboardHandler(SimpleHTTPRequestHandler):
|
|||
return
|
||||
self.bridge_request(method, bridge_path, parsed.query)
|
||||
|
||||
def write_json(self, status, payload):
|
||||
encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(encoded)))
|
||||
self.end_headers()
|
||||
self.wfile.write(encoded)
|
||||
|
||||
def route_component_api(self, method):
|
||||
if self.component_store is None:
|
||||
self.write_json(500, {"ok": False, "error": "Component store is unavailable"})
|
||||
return
|
||||
|
||||
if method == "GET":
|
||||
try:
|
||||
component, payload = self.component_store.load_component()
|
||||
except FileNotFoundError as exc:
|
||||
self.write_json(404, {"ok": False, "error": str(exc)})
|
||||
return
|
||||
except KeyError as exc:
|
||||
self.write_json(404, {"ok": False, "error": str(exc)})
|
||||
return
|
||||
except Exception as exc:
|
||||
self.write_json(500, {"ok": False, "error": str(exc)})
|
||||
return
|
||||
self.write_json(200, self.component_store.response_payload(component, payload))
|
||||
return
|
||||
|
||||
if method != "POST":
|
||||
self.write_json(405, {"ok": False, "error": "Method is not allowed"})
|
||||
return
|
||||
|
||||
self.write_json(405, {"ok": False, "error": "Apply is not enabled in this step"})
|
||||
|
||||
def route_components_index_api(self):
|
||||
if self.catalog_store is None:
|
||||
self.write_json(500, {"ok": False, "error": "Catalog store is unavailable"})
|
||||
return
|
||||
try:
|
||||
elements = self.catalog_store.load_elements()
|
||||
except FileNotFoundError as exc:
|
||||
self.write_json(404, {"ok": False, "error": str(exc)})
|
||||
return
|
||||
except Exception as exc:
|
||||
self.write_json(500, {"ok": False, "error": str(exc)})
|
||||
return
|
||||
self.write_json(200, self.catalog_store.response_payload(elements))
|
||||
|
||||
def do_OPTIONS(self):
|
||||
if self.path.split("?", 1)[0].split("#", 1)[0].startswith("/api/bridge"):
|
||||
self.route_bridge("OPTIONS")
|
||||
|
|
@ -299,6 +379,12 @@ class DashboardHandler(SimpleHTTPRequestHandler):
|
|||
|
||||
def do_GET(self):
|
||||
path = self.path.split("?", 1)[0].split("#", 1)[0]
|
||||
if path == "/api/components-index":
|
||||
self.route_components_index_api()
|
||||
return
|
||||
if path == "/api/component":
|
||||
self.route_component_api("GET")
|
||||
return
|
||||
if path.startswith("/api/bridge"):
|
||||
self.route_bridge("GET")
|
||||
return
|
||||
|
|
@ -321,24 +407,39 @@ def main():
|
|||
dashboard_id = str(args.dashboard_id or args.port).strip()
|
||||
if not dashboard_id:
|
||||
raise SystemExit("dashboard id is required")
|
||||
dashboard_mode = str(args.mode or DEFAULT_MODE).strip().lower() or DEFAULT_MODE
|
||||
|
||||
root = resolve_dashboard_root(app_dir, dashboard_id, args.root)
|
||||
source_dir = Path(args.source_dir or DEFAULT_SOURCE_DIR).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
source_dir.mkdir(parents=True, exist_ok=True)
|
||||
bridge_proxy = BridgeProxy(args.bridge_url)
|
||||
component_store = None
|
||||
catalog_store = None
|
||||
|
||||
if dashboard_mode == "component":
|
||||
source_dir = root
|
||||
component_store = ItemsComponentStore(args.items_path, dashboard_id)
|
||||
catalog_store = ItemsCatalogStore(args.items_path)
|
||||
elif dashboard_mode == "component_index":
|
||||
source_dir = root
|
||||
catalog_store = ItemsCatalogStore(args.items_path)
|
||||
else:
|
||||
source_dir = Path(args.source_dir or DEFAULT_SOURCE_DIR).resolve()
|
||||
source_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
handler = functools.partial(
|
||||
DashboardHandler,
|
||||
directory=str(source_dir),
|
||||
dashboard_id=dashboard_id,
|
||||
dashboard_mode=dashboard_mode,
|
||||
source_dir=str(source_dir),
|
||||
selection_mode=args.selection_mode,
|
||||
bridge_proxy=bridge_proxy,
|
||||
component_store=component_store,
|
||||
catalog_store=catalog_store,
|
||||
)
|
||||
server = ThreadingHTTPServer((str(args.bind), int(args.port)), handler)
|
||||
print(
|
||||
f"[dashboard:{dashboard_id}] serving source_dir={source_dir} mode={args.selection_mode} bridge_url={args.bridge_url} on http://{args.bind}:{args.port}",
|
||||
f"[dashboard:{dashboard_id}] serving mode={dashboard_mode} source_dir={source_dir} html_mode={args.selection_mode} bridge_url={args.bridge_url} on http://{args.bind}:{args.port}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
server.serve_forever()
|
||||
|
|
|
|||
|
|
@ -27,12 +27,18 @@ APP_DIR="/opt/iomatex-dashboards"
|
|||
BACKEND_DIR="${APP_DIR}/backend"
|
||||
DASHBOARDS_DIR="${APP_DIR}/dashboards"
|
||||
SERVICE_TEMPLATE_NAME="iomatex-dashboard@.service"
|
||||
COMPONENT_SYNC_SERVICE_NAME="iomatex-component-dashboards.service"
|
||||
COMPONENT_SYNC_PATH_NAME="iomatex-component-dashboards.path"
|
||||
SERVICE_INSTANCE_PORT="${DASHBOARD_PORT:-5678}"
|
||||
SERVICE_INSTANCE_NAME="iomatex-dashboard@${SERVICE_INSTANCE_PORT}.service"
|
||||
CFG_DIR="/etc/iomatex/dashboards.d"
|
||||
CFG_PATH="${CFG_DIR}/${SERVICE_INSTANCE_PORT}.env"
|
||||
MAIN_MODE="${DASHBOARD_MAIN_MODE:-component_index}"
|
||||
APP_BIND="${DASHBOARD_BIND:-0.0.0.0}"
|
||||
SOURCE_DIR="${DASHBOARD_SOURCE_DIR:-/var/lib/itscreen/Downloads/it-screen}"
|
||||
ITEMS_PATH="${DASHBOARD_ITEMS_PATH:-/var/lib/itscreen/data/it-screen/it-screen/items.json}"
|
||||
SYNC_STATE_PATH="${DASHBOARD_SYNC_STATE_PATH:-/var/lib/iomatex-dashboards/component_sync_state.json}"
|
||||
SYNC_DEBOUNCE_SECONDS="${DASHBOARD_SYNC_DEBOUNCE_SECONDS:-2}"
|
||||
SELECTION_MODE="${DASHBOARD_SELECTION_MODE:-newest}"
|
||||
BRIDGE_URL="${DASHBOARD_BRIDGE_URL:-http://127.0.0.1:8787}"
|
||||
ts="$(date +%s)"
|
||||
|
|
@ -75,6 +81,23 @@ systemctl_try() {
|
|||
systemctl "$@" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
restart_component_instances() {
|
||||
local env_path component_id service_name
|
||||
[ -d "${CFG_DIR}" ] || return 0
|
||||
for env_path in "${CFG_DIR}"/*.env; do
|
||||
[ -e "${env_path}" ] || continue
|
||||
if ! grep -q '^DASHBOARD_MODE=component$' "${env_path}"; then
|
||||
continue
|
||||
fi
|
||||
component_id="$(basename "${env_path}" .env)"
|
||||
service_name="iomatex-dashboard@${component_id}.service"
|
||||
echo "Restarting component dashboard ${component_id}"
|
||||
if ! systemctl restart "${service_name}"; then
|
||||
echo "WARNING: failed to restart ${service_name}" >&2
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
wait_for_local_http() {
|
||||
local attempt max_attempts url code probe_host
|
||||
max_attempts=30
|
||||
|
|
@ -109,17 +132,23 @@ wait_for_local_http() {
|
|||
}
|
||||
|
||||
rollback_deploy() {
|
||||
systemctl_try stop "${COMPONENT_SYNC_PATH_NAME}"
|
||||
systemctl_try disable "${COMPONENT_SYNC_PATH_NAME}"
|
||||
systemctl_try stop "${COMPONENT_SYNC_SERVICE_NAME}"
|
||||
systemctl_try disable "${COMPONENT_SYNC_SERVICE_NAME}"
|
||||
systemctl_try stop "${SERVICE_INSTANCE_NAME}"
|
||||
rm -rf "${APP_DIR}"
|
||||
if [ -d "${PREV_DIR}" ]; then
|
||||
mv "${PREV_DIR}" "${APP_DIR}"
|
||||
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||
systemctl_try start "${COMPONENT_SYNC_PATH_NAME}"
|
||||
systemctl_try start "${COMPONENT_SYNC_SERVICE_NAME}"
|
||||
systemctl_try start "${SERVICE_INSTANCE_NAME}"
|
||||
fi
|
||||
}
|
||||
|
||||
step_n=0
|
||||
TOTAL_STEPS=8
|
||||
TOTAL_STEPS=9
|
||||
|
||||
step() {
|
||||
local label="$1"
|
||||
|
|
@ -137,6 +166,8 @@ step() {
|
|||
step "Validate source tree"
|
||||
require_file "${SRC_ROOT}/backend/static_server.py"
|
||||
require_file "${SRC_ROOT}/backend/dashboard_locator.py"
|
||||
require_file "${SRC_ROOT}/backend/component_dashboard.py"
|
||||
require_file "${SRC_ROOT}/backend/component_dashboard_sync.py"
|
||||
EDGE_IP="$(detect_edge_ip || true)"
|
||||
if [ -n "${EDGE_IP}" ]; then
|
||||
echo "Detected EDGE_IP=${EDGE_IP}"
|
||||
|
|
@ -152,6 +183,7 @@ python3 --version
|
|||
|
||||
step "Prepare directories"
|
||||
mkdir -p "${CFG_DIR}"
|
||||
mkdir -p "$(dirname "${SYNC_STATE_PATH}")"
|
||||
rm -rf "${STAGE_DIR}"
|
||||
mkdir -p "${STAGE_BACKEND_DIR}" "${STAGE_DASHBOARDS_DIR}"
|
||||
|
||||
|
|
@ -160,17 +192,21 @@ copy_tree "${SRC_ROOT}/backend" "${STAGE_BACKEND_DIR}"
|
|||
copy_tree "${SRC_ROOT}/dashboards" "${STAGE_DASHBOARDS_DIR}"
|
||||
require_file "${STAGE_BACKEND_DIR}/static_server.py"
|
||||
require_file "${STAGE_BACKEND_DIR}/dashboard_locator.py"
|
||||
require_file "${STAGE_BACKEND_DIR}/component_dashboard.py"
|
||||
require_file "${STAGE_BACKEND_DIR}/component_dashboard_sync.py"
|
||||
|
||||
step "Write instance config and systemd template"
|
||||
cat > "${CFG_PATH}" <<EOF
|
||||
DASHBOARD_ID=${SERVICE_INSTANCE_PORT}
|
||||
DASHBOARD_PORT=${SERVICE_INSTANCE_PORT}
|
||||
DASHBOARD_MODE=${MAIN_MODE}
|
||||
DASHBOARD_BIND=${APP_BIND}
|
||||
DASHBOARD_APP_DIR=${APP_DIR}
|
||||
DASHBOARD_ROOT=${APP_DIR}/dashboards/${SERVICE_INSTANCE_PORT}
|
||||
DASHBOARD_SOURCE_DIR=${SOURCE_DIR}
|
||||
DASHBOARD_SELECTION_MODE=${SELECTION_MODE}
|
||||
DASHBOARD_BRIDGE_URL=${BRIDGE_URL}
|
||||
DASHBOARD_ITEMS_PATH=${ITEMS_PATH}
|
||||
EOF
|
||||
|
||||
cat > "/etc/systemd/system/${SERVICE_TEMPLATE_NAME}" <<'UNIT'
|
||||
|
|
@ -183,12 +219,14 @@ Wants=network-online.target
|
|||
Type=simple
|
||||
Environment="DASHBOARD_ID=%i"
|
||||
Environment="DASHBOARD_PORT=%i"
|
||||
Environment="DASHBOARD_MODE=static"
|
||||
Environment="DASHBOARD_BIND=0.0.0.0"
|
||||
Environment="DASHBOARD_APP_DIR=/opt/iomatex-dashboards"
|
||||
Environment="DASHBOARD_ROOT=/opt/iomatex-dashboards/dashboards/%i"
|
||||
Environment="DASHBOARD_SOURCE_DIR=/var/lib/itscreen/Downloads/it-screen"
|
||||
Environment="DASHBOARD_SELECTION_MODE=newest"
|
||||
Environment="DASHBOARD_BRIDGE_URL=http://127.0.0.1:8787"
|
||||
Environment="DASHBOARD_ITEMS_PATH=/var/lib/itscreen/data/it-screen/it-screen/items.json"
|
||||
EnvironmentFile=-/etc/iomatex/dashboards.d/%i.env
|
||||
WorkingDirectory=/opt/iomatex-dashboards
|
||||
ExecStart=/usr/bin/python3 /opt/iomatex-dashboards/backend/static_server.py
|
||||
|
|
@ -201,8 +239,52 @@ Group=root
|
|||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
|
||||
cat > "/etc/systemd/system/${COMPONENT_SYNC_SERVICE_NAME}" <<'UNIT'
|
||||
[Unit]
|
||||
Description=IOMATEX Component Dashboard Sync
|
||||
After=local-fs.target network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
Environment="DASHBOARD_BIND=0.0.0.0"
|
||||
Environment="DASHBOARD_APP_DIR=/opt/iomatex-dashboards"
|
||||
Environment="DASHBOARD_SOURCE_DIR=/var/lib/itscreen/Downloads/it-screen"
|
||||
Environment="DASHBOARD_SELECTION_MODE=newest"
|
||||
Environment="DASHBOARD_BRIDGE_URL=http://127.0.0.1:8787"
|
||||
Environment="DASHBOARD_ITEMS_PATH=/var/lib/itscreen/data/it-screen/it-screen/items.json"
|
||||
Environment="DASHBOARD_SYNC_STATE_PATH=/var/lib/iomatex-dashboards/component_sync_state.json"
|
||||
Environment="DASHBOARD_SYNC_DEBOUNCE_SECONDS=2"
|
||||
Environment="DASHBOARD_CFG_DIR=/etc/iomatex/dashboards.d"
|
||||
Environment="DASHBOARD_SERVICE_TEMPLATE=iomatex-dashboard@{}.service"
|
||||
WorkingDirectory=/opt/iomatex-dashboards
|
||||
ExecStart=/usr/bin/python3 /opt/iomatex-dashboards/backend/component_dashboard_sync.py
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
|
||||
cat > "/etc/systemd/system/${COMPONENT_SYNC_PATH_NAME}" <<UNIT
|
||||
[Unit]
|
||||
Description=Watch items.json for component dashboard sync
|
||||
|
||||
[Path]
|
||||
PathModified=${ITEMS_PATH}
|
||||
PathChanged=${ITEMS_PATH}
|
||||
Unit=${COMPONENT_SYNC_SERVICE_NAME}
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
|
||||
step "Validate runtime"
|
||||
python3 -m py_compile "${STAGE_BACKEND_DIR}/static_server.py" "${STAGE_BACKEND_DIR}/dashboard_locator.py"
|
||||
python3 -m py_compile \
|
||||
"${STAGE_BACKEND_DIR}/static_server.py" \
|
||||
"${STAGE_BACKEND_DIR}/dashboard_locator.py" \
|
||||
"${STAGE_BACKEND_DIR}/component_dashboard.py" \
|
||||
"${STAGE_BACKEND_DIR}/component_dashboard_sync.py"
|
||||
|
||||
step "Activate dashboard service"
|
||||
if [ -d "${APP_DIR}" ]; then
|
||||
|
|
@ -211,6 +293,8 @@ if [ -d "${APP_DIR}" ]; then
|
|||
fi
|
||||
mv "${STAGE_DIR}" "${APP_DIR}"
|
||||
systemctl daemon-reload
|
||||
systemctl_try disable --now "${COMPONENT_SYNC_PATH_NAME}"
|
||||
systemctl_try disable --now "${COMPONENT_SYNC_SERVICE_NAME}"
|
||||
systemctl_try stop "${SERVICE_INSTANCE_NAME}"
|
||||
systemctl_try reset-failed "${SERVICE_INSTANCE_NAME}"
|
||||
if ! systemctl enable --now "${SERVICE_INSTANCE_NAME}"; then
|
||||
|
|
@ -218,6 +302,17 @@ if ! systemctl enable --now "${SERVICE_INSTANCE_NAME}"; then
|
|||
rollback_deploy
|
||||
exit 1
|
||||
fi
|
||||
if ! systemctl enable --now "${COMPONENT_SYNC_SERVICE_NAME}"; then
|
||||
echo "ERROR: failed to start ${COMPONENT_SYNC_SERVICE_NAME}; rolling back deploy" >&2
|
||||
rollback_deploy
|
||||
exit 1
|
||||
fi
|
||||
if ! systemctl enable --now "${COMPONENT_SYNC_PATH_NAME}"; then
|
||||
echo "ERROR: failed to start ${COMPONENT_SYNC_PATH_NAME}; rolling back deploy" >&2
|
||||
rollback_deploy
|
||||
exit 1
|
||||
fi
|
||||
restart_component_instances
|
||||
|
||||
step "Smoke-check"
|
||||
if ! wait_for_local_http; then
|
||||
|
|
@ -237,6 +332,12 @@ echo "Dashboards dir: ${DASHBOARDS_DIR}"
|
|||
echo "Backend dir: ${BACKEND_DIR}"
|
||||
echo "Instance config: ${CFG_PATH}"
|
||||
echo "Dashboard source dir: ${SOURCE_DIR}"
|
||||
echo "Items path: ${ITEMS_PATH}"
|
||||
echo "Sync state path: ${SYNC_STATE_PATH}"
|
||||
echo "Sync debounce seconds: ${SYNC_DEBOUNCE_SECONDS}"
|
||||
echo "Main dashboard mode: ${MAIN_MODE}"
|
||||
echo "HTML selection mode: ${SELECTION_MODE}"
|
||||
echo "Bridge proxy url: ${BRIDGE_URL}"
|
||||
echo "Systemd template: /etc/systemd/system/${SERVICE_TEMPLATE_NAME}"
|
||||
echo "Component sync service: /etc/systemd/system/${COMPONENT_SYNC_SERVICE_NAME}"
|
||||
echo "Component sync path: /etc/systemd/system/${COMPONENT_SYNC_PATH_NAME}"
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -39,6 +39,7 @@ APP_DIR = "/opt/iomatex-console"
|
|||
PUBLIC_DIR = os.path.join(APP_DIR, "public")
|
||||
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
||||
CONFIG_PATH = "/etc/iomatex/console.json"
|
||||
UI_VERSION = "V 2.2.1"
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"bind": "0.0.0.0",
|
||||
|
|
@ -865,6 +866,7 @@ def get_identity_payload():
|
|||
"mdns_hostname": f"{hostname}.local" if hostname else "",
|
||||
"edge_id": get_edge_id(),
|
||||
"os_label": get_os_label(),
|
||||
"ui_version": UI_VERSION,
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -27,10 +27,9 @@ DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
|
|||
SETTINGS_CATEGORY = "server"
|
||||
SETTINGS_CONTRACTS = (
|
||||
{"contract_prefix": "it-screen", "base_prefix": "it-screen/$devices/settings"},
|
||||
{"contract_prefix": "iomatex", "base_prefix": "iomatex/$devices/settings"},
|
||||
{"contract_prefix": "universal", "base_prefix": "device/settings"},
|
||||
)
|
||||
DEFAULT_CONTRACT_PREFIX = SETTINGS_CONTRACTS[0]["contract_prefix"]
|
||||
DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices")
|
||||
|
||||
|
||||
def _debug(message):
|
||||
|
|
@ -79,13 +78,31 @@ def _host_contract_hint(host):
|
|||
value = str(host or "").strip().lower()
|
||||
if not value:
|
||||
return ""
|
||||
if "iomatex" in value:
|
||||
return "iomatex"
|
||||
if "it-screen" in value:
|
||||
if "it-screen" in value or "iomatex" in value:
|
||||
return "it-screen"
|
||||
return ""
|
||||
|
||||
|
||||
def get_candidate_device_topics(device_id, server_host_hint=None):
|
||||
value = str(server_host_hint or "").strip().lower()
|
||||
ordered = []
|
||||
if "iomatex" in value:
|
||||
ordered.extend(("iomatex/devices", "it-screen/devices", "devices"))
|
||||
elif "it-screen" in value:
|
||||
ordered.extend(("it-screen/devices", "iomatex/devices", "devices"))
|
||||
else:
|
||||
ordered.extend(("devices", "it-screen/devices", "iomatex/devices"))
|
||||
seen = set()
|
||||
topics = []
|
||||
for prefix in ordered:
|
||||
if prefix in seen:
|
||||
continue
|
||||
seen.add(prefix)
|
||||
topics.append({"topic_prefix": prefix, "topic": prefix})
|
||||
topics.append({"topic_prefix": prefix, "topic": f"{prefix}/{device_id}"})
|
||||
return topics
|
||||
|
||||
|
||||
def _build_contract_topics(device_id, contract_prefix):
|
||||
contract = _contract_by_prefix(contract_prefix)
|
||||
if not contract:
|
||||
|
|
@ -282,6 +299,74 @@ def _extract_registration_fields(server_state, event_payload, persisted):
|
|||
return merged
|
||||
|
||||
|
||||
def _iter_registration_payload_candidates(payload):
|
||||
if not isinstance(payload, dict):
|
||||
return
|
||||
yield payload
|
||||
for key in ("data", "registration", "device", "server", "payload"):
|
||||
nested = payload.get(key)
|
||||
if isinstance(nested, dict):
|
||||
yield nested
|
||||
|
||||
|
||||
def _looks_like_registration_payload(payload):
|
||||
for candidate in _iter_registration_payload_candidates(payload):
|
||||
if any(candidate.get(key) not in (None, "") for key in (
|
||||
"host", "server", "username", "password", "token",
|
||||
"organization", "registered", "logged", "device_name", "name"
|
||||
)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _merge_device_registration_payload(server_state, device_payload):
|
||||
if not isinstance(device_payload, dict):
|
||||
return dict(server_state or {})
|
||||
merged = dict(server_state or {})
|
||||
for candidate in _iter_registration_payload_candidates(device_payload):
|
||||
for key in ("host", "server", "username", "password", "token", "organization", "registered", "logged"):
|
||||
if candidate.get(key) not in (None, ""):
|
||||
merged[key] = candidate.get(key)
|
||||
for key in ("device_name", "name", "given_name", "display_name"):
|
||||
if candidate.get(key) not in (None, ""):
|
||||
merged["device_name"] = candidate.get(key)
|
||||
break
|
||||
return merged
|
||||
|
||||
|
||||
def _payload_matches_device(candidate, device_id):
|
||||
if not isinstance(candidate, dict):
|
||||
return False
|
||||
device_id = str(device_id or "").strip()
|
||||
if not device_id:
|
||||
return False
|
||||
for key in ("device_id", "deviceId", "id", "hostname", "name"):
|
||||
value = _truncate_empty(candidate.get(key))
|
||||
if value == device_id:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _extract_device_payload(payload, device_id):
|
||||
if isinstance(payload, dict):
|
||||
if _payload_matches_device(payload, device_id) or _looks_like_registration_payload(payload):
|
||||
return payload
|
||||
for key in ("devices", "items", "data", "payload", "registrations"):
|
||||
nested = payload.get(key)
|
||||
extracted = _extract_device_payload(nested, device_id)
|
||||
if extracted:
|
||||
return extracted
|
||||
nested = payload.get(device_id)
|
||||
if isinstance(nested, dict):
|
||||
return nested
|
||||
if isinstance(payload, list):
|
||||
for item in payload:
|
||||
extracted = _extract_device_payload(item, device_id)
|
||||
if extracted:
|
||||
return extracted
|
||||
return {}
|
||||
|
||||
|
||||
def _device_name_from_payload(payload):
|
||||
if not isinstance(payload, dict):
|
||||
return ""
|
||||
|
|
@ -467,6 +552,32 @@ class MqttSettingsSession:
|
|||
timeout=REPLY_TIMEOUT_SEC,
|
||||
)
|
||||
|
||||
def read_retained_topic_payload(self, topic, timeout=1.5):
|
||||
self._drain()
|
||||
result, _ = self.client.subscribe(topic, qos=0)
|
||||
if result != mqtt.MQTT_ERR_SUCCESS:
|
||||
raise RuntimeError("Device registration topic subscribe failed")
|
||||
deadline = time.time() + timeout
|
||||
try:
|
||||
while time.time() < deadline:
|
||||
if self.error:
|
||||
raise RuntimeError(self.error)
|
||||
try:
|
||||
candidate = self.queue.get(timeout=0.25)
|
||||
except queue.Empty:
|
||||
continue
|
||||
if isinstance(candidate, dict) and candidate.get("__invalid_json__") is not None:
|
||||
continue
|
||||
extracted = _extract_device_payload(candidate, self.device_id)
|
||||
if _looks_like_registration_payload(extracted):
|
||||
return extracted
|
||||
finally:
|
||||
try:
|
||||
self.client.unsubscribe(topic)
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def set_server(self, host):
|
||||
self.publish({"action": "set", "category": SETTINGS_CATEGORY, "host": host})
|
||||
|
||||
|
|
@ -518,6 +629,22 @@ def normalize_settings_response(server_state, persisted=None, source="mqtt", con
|
|||
return _normalize_registration_payload(server_state, persisted=persisted, source=source, contract_meta=contract_meta)
|
||||
|
||||
|
||||
def _read_device_registration_snapshot(session, device_id, server_host_hint=""):
|
||||
last_payload = {}
|
||||
for topic_meta in get_candidate_device_topics(device_id, server_host_hint=server_host_hint):
|
||||
topic = topic_meta["topic"]
|
||||
_debug(f"device-status: trying retained topic={topic}")
|
||||
payload = session.read_retained_topic_payload(topic)
|
||||
if _looks_like_registration_payload(payload):
|
||||
_debug(f"device-status: selected retained topic={topic}")
|
||||
snapshot = dict(payload)
|
||||
snapshot["__topic__"] = topic
|
||||
snapshot["__topic_prefix__"] = topic_meta["topic_prefix"]
|
||||
return snapshot
|
||||
last_payload = payload if isinstance(payload, dict) else {}
|
||||
return last_payload
|
||||
|
||||
|
||||
def _with_settings_contract(device_id, persisted, operation_name, callback, server_host_hint=""):
|
||||
preferred = _truncate_empty((persisted or {}).get("contract_prefix"))
|
||||
candidates = get_candidate_settings_topics(device_id, preferred_contract=preferred, server_host_hint=server_host_hint)
|
||||
|
|
@ -549,29 +676,41 @@ def get_registration_status():
|
|||
try:
|
||||
def _status_flow(session, _contract_meta):
|
||||
session.login()
|
||||
return session.get_server_state()
|
||||
server_state = session.get_server_state()
|
||||
device_state = _read_device_registration_snapshot(
|
||||
session,
|
||||
state["device_id"],
|
||||
server_host_hint=_truncate_empty(server_state.get("host")) or _truncate_empty(server_state.get("server")),
|
||||
)
|
||||
return {
|
||||
"server_state": server_state,
|
||||
"device_state": device_state,
|
||||
}
|
||||
|
||||
contract_meta, server_state = _with_settings_contract(
|
||||
contract_meta, status_flow = _with_settings_contract(
|
||||
state["device_id"],
|
||||
persisted,
|
||||
"status",
|
||||
_status_flow,
|
||||
server_host_hint=state.get("host", ""),
|
||||
)
|
||||
server_state = status_flow["server_state"]
|
||||
device_state = status_flow.get("device_state") or {}
|
||||
merged_state = _merge_device_registration_payload(server_state, device_state)
|
||||
current = {
|
||||
"host": _truncate_empty(server_state.get("host")) or _truncate_empty(server_state.get("server")),
|
||||
"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),
|
||||
"host": _truncate_empty(merged_state.get("host")) or _truncate_empty(merged_state.get("server")),
|
||||
"username": _truncate_empty(merged_state.get("username")),
|
||||
"password": _truncate_empty(merged_state.get("password")),
|
||||
"token": _truncate_empty(merged_state.get("token")),
|
||||
"organization": _truncate_empty(merged_state.get("organization")),
|
||||
"device_name": _device_name_from_payload(merged_state),
|
||||
"device_id": _device_identity()["device_id"],
|
||||
"contract_prefix": _truncate_empty(contract_meta.get("contract_prefix")),
|
||||
"request_topic": _truncate_empty(contract_meta.get("request_topic")),
|
||||
"response_topic": _truncate_empty(contract_meta.get("response_topic")),
|
||||
"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",
|
||||
"registered": _bool_value(merged_state.get("registered"), default=False),
|
||||
"logged": _bool_value(merged_state.get("logged"), default=False),
|
||||
"status": "ready" if _bool_value(merged_state.get("registered"), default=False) else "not_registered",
|
||||
"last_event": persisted.get("last_event", {
|
||||
"action": "",
|
||||
"operation": "",
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@
|
|||
{ mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" },
|
||||
{ mode: "custom", label: "Custom", host: "" }
|
||||
];
|
||||
const UI_VERSION = "V 2.2.1";
|
||||
const ITSCREEN_LOG_INITIAL_LINES = 50;
|
||||
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
|
||||
const ITSCREEN_LOG_BATCH_MS = 250;
|
||||
|
|
@ -477,7 +478,7 @@
|
|||
if (nodes.brandEyebrow) nodes.brandEyebrow.textContent = "IOMATEX G-Box";
|
||||
if (nodes.heroTitle) nodes.heroTitle.textContent = t("Edge Automation Gateway");
|
||||
if (nodes.capabilityBadge) nodes.capabilityBadge.textContent = t("Digital DNA ready");
|
||||
if (nodes.osLabel) nodes.osLabel.textContent = t("Unified diagnostics, network operations and gateway commissioning.");
|
||||
if (nodes.osLabel) nodes.osLabel.textContent = `${t("Unified diagnostics, network operations and gateway commissioning.")} · ${UI_VERSION}`;
|
||||
if (nodes.edgeSerialLabel) nodes.edgeSerialLabel.textContent = t("Edge Serial Number");
|
||||
if (nodes.hostIpLabel) nodes.hostIpLabel.textContent = t("Host / IP");
|
||||
if (nodes.updatedLabel) nodes.updatedLabel.textContent = t("Updated");
|
||||
|
|
@ -1039,6 +1040,7 @@
|
|||
|
||||
function itscreenContractLabel(payload) {
|
||||
const contract = textValue(payload && payload.contract_prefix, "");
|
||||
if (contract === "v1-edge") return "v1/edge/device/settings";
|
||||
if (contract === "it-screen") return "it-screen";
|
||||
if (contract === "iomatex") return "iomatex";
|
||||
if (contract === "universal") return "device/settings";
|
||||
|
|
@ -3421,7 +3423,8 @@
|
|||
state.identity = safe;
|
||||
nodes.edgeId.textContent = safe.serial_number || "-";
|
||||
nodes.hostName.textContent = currentHostLabel();
|
||||
nodes.osLabel.textContent = t("Unified diagnostics, network operations and gateway commissioning.");
|
||||
const uiVersion = textValue(safe.ui_version, UI_VERSION);
|
||||
nodes.osLabel.textContent = `${t("Unified diagnostics, network operations and gateway commissioning.")} · ${uiVersion}`;
|
||||
}
|
||||
|
||||
function updateHeaderMeta(payload) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue