diff --git a/stage_ui/console_core/backend/itscreen_registration.py b/stage_ui/console_core/backend/itscreen_registration.py index ffd02c1..604ccae 100644 --- a/stage_ui/console_core/backend/itscreen_registration.py +++ b/stage_ui/console_core/backend/itscreen_registration.py @@ -3,6 +3,7 @@ import json import os import queue import re +import sys import threading import time from urllib.parse import urlparse @@ -23,6 +24,20 @@ 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}$") +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"] + + +def _debug(message): + try: + print(f"[itscreen-registration] {message}", file=sys.stderr) + except Exception: + pass def _device_hostname(): @@ -52,6 +67,55 @@ def _device_identity(): } +def _contract_catalog(): + return {item["contract_prefix"]: dict(item) for item in SETTINGS_CONTRACTS} + + +def _contract_by_prefix(contract_prefix): + return _contract_catalog().get(str(contract_prefix or "").strip()) + + +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: + return "it-screen" + return "" + + +def _build_contract_topics(device_id, contract_prefix): + contract = _contract_by_prefix(contract_prefix) + if not contract: + raise ValueError("Unknown settings contract") + base = f"{contract['base_prefix']}/{device_id}" + return { + "contract_prefix": contract["contract_prefix"], + "base_prefix": contract["base_prefix"], + "request_topic": f"{base}/sub", + "response_topic": f"{base}/pub", + "category": SETTINGS_CATEGORY, + } + + +def get_candidate_settings_topics(device_id, preferred_contract=None, server_host_hint=None): + ordered = [] + seen = set() + for candidate in (preferred_contract, _host_contract_hint(server_host_hint), DEFAULT_CONTRACT_PREFIX): + if candidate and candidate not in seen and _contract_by_prefix(candidate): + ordered.append(candidate) + seen.add(candidate) + for contract in SETTINGS_CONTRACTS: + candidate = contract["contract_prefix"] + if candidate in seen: + continue + ordered.append(candidate) + seen.add(candidate) + return [_build_contract_topics(device_id, contract_prefix) for contract_prefix in ordered] + + def validate_host(host): value = str(host or "").strip().lower() if not value: @@ -81,6 +145,9 @@ def _default_state(): "organization": "", "device_name": "", "device_id": identity["device_id"], + "contract_prefix": "", + "request_topic": "", + "response_topic": "", "registered": False, "logged": False, "status": "idle", @@ -121,6 +188,9 @@ def save_state(state): "organization": str(state.get("organization", "") or ""), "device_name": str(state.get("device_name", "") or ""), "device_id": str(state.get("device_id", "") or _device_identity()["device_id"]), + "contract_prefix": str(state.get("contract_prefix", "") or ""), + "request_topic": str(state.get("request_topic", "") or ""), + "response_topic": str(state.get("response_topic", "") or ""), "registered": bool(state.get("registered", False)), "logged": bool(state.get("logged", False)), "status": str(state.get("status", "idle") or "idle"), @@ -149,11 +219,6 @@ def _parse_mqtt_url(raw_url): return host, port -def _topics(device_id): - base = f"it-screen/$devices/settings/{device_id}" - return {"sub": f"{base}/sub", "pub": f"{base}/pub"} - - def _truncate_empty(value): text = str(value or "").strip() return text @@ -227,32 +292,45 @@ def _device_name_from_payload(payload): return "" -def _normalize_registration_payload(server_state, persisted=None, source="mqtt"): +def _normalize_registration_payload(server_state, persisted=None, source="mqtt", contract_meta=None): payload = server_state if isinstance(server_state, dict) else {} + persisted = persisted or {} identity = _device_identity() username = _text_or_default(payload.get("username")) device_name = _device_name_from_payload(payload) + host = _truncate_empty(payload.get("host")) or _truncate_empty(payload.get("server")) + password = _truncate_empty(payload.get("password")) + meta = dict(contract_meta or {}) + contract_prefix = _truncate_empty(meta.get("contract_prefix")) or _truncate_empty(persisted.get("contract_prefix")) + request_topic = _truncate_empty(meta.get("request_topic")) or _truncate_empty(persisted.get("request_topic")) + response_topic = _truncate_empty(meta.get("response_topic")) or _truncate_empty(persisted.get("response_topic")) + category = _truncate_empty(meta.get("category")) or SETTINGS_CATEGORY 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")), + "server": _text_or_default(host), + "host": _text_or_default(host), "organization": _text_or_default(payload.get("organization")), "token": _text_or_default(payload.get("token")), + "contract_prefix": _text_or_default(contract_prefix), + "request_topic": _text_or_default(request_topic), + "response_topic": _text_or_default(response_topic), + "category": _text_or_default(category), + "password_present": bool(password), "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, + "password_state": "Password set" if 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", { + "last_event": persisted.get("last_event", { "action": "", "operation": "", "status": "", "timestamp": "", }), - "raw": dict(payload), + "raw_payload": dict(payload), } @@ -268,14 +346,14 @@ def _public_error(exc): class MqttSettingsSession: - def __init__(self, device_id): + def __init__(self, device_id, contract_meta): if mqtt is None: raise RuntimeError("Device settings service is unavailable") self.device_id = device_id self.queue = queue.Queue() self.connected = threading.Event() self.error = None - self.topics = _topics(device_id) + self.contract_meta = dict(contract_meta or {}) self.client = mqtt.Client(client_id=f"console-core-{device_id}-{int(time.time() * 1000)}", clean_session=True) self.client.on_connect = self._on_connect self.client.on_message = self._on_message @@ -285,7 +363,7 @@ class MqttSettingsSession: if rc != 0: self.error = f"MQTT connect failed ({rc})" return - result, _ = client.subscribe(self.topics["pub"], qos=0) + result, _ = client.subscribe(self.contract_meta["response_topic"], qos=0) if result != mqtt.MQTT_ERR_SUCCESS: self.error = "Device settings service is unavailable" return @@ -337,7 +415,7 @@ class MqttSettingsSession: def publish(self, payload): self._drain() - result = self.client.publish(self.topics["sub"], json.dumps(payload), qos=0, retain=False) + result = self.client.publish(self.contract_meta["request_topic"], json.dumps(payload), qos=0, retain=False) deadline = time.time() + PUBLISH_TIMEOUT_SEC while time.time() < deadline: if result.is_published(): @@ -384,13 +462,13 @@ class MqttSettingsSession: def get_server_state(self): return self.publish_and_wait( - {"action": "get", "category": "server"}, - lambda item: isinstance(item, dict) and item.get("category") == "server", + {"action": "get", "category": SETTINGS_CATEGORY}, + lambda item: isinstance(item, dict) and item.get("category") == SETTINGS_CATEGORY, timeout=REPLY_TIMEOUT_SEC, ) def set_server(self, host): - self.publish({"action": "set", "category": "server", "host": host}) + self.publish({"action": "set", "category": SETTINGS_CATEGORY, "host": host}) def wait_registered_event(self, timeout=REGISTER_TIMEOUT_SEC): deadline = time.time() + timeout @@ -428,21 +506,69 @@ def _build_public_status(state, error_text=""): return output +def publish_settings_request(session, payload): + session.publish(payload) + + +def wait_settings_response(session, payload, predicate, timeout=REPLY_TIMEOUT_SEC): + return session.publish_and_wait(payload, predicate, timeout=timeout) + + +def normalize_settings_response(server_state, persisted=None, source="mqtt", contract_meta=None): + return _normalize_registration_payload(server_state, persisted=persisted, source=source, contract_meta=contract_meta) + + +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) + last_error = None + for contract_meta in candidates: + _debug( + f"{operation_name}: trying contract={contract_meta['contract_prefix']} " + f"request={contract_meta['request_topic']} response={contract_meta['response_topic']}" + ) + try: + with MqttSettingsSession(device_id, contract_meta) as session: + result = callback(session, contract_meta) + _debug(f"{operation_name}: selected contract={contract_meta['contract_prefix']}") + return contract_meta, result + except Exception as exc: + last_error = exc + _debug( + f"{operation_name}: contract={contract_meta['contract_prefix']} failed: " + f"{_truncate_empty(str(exc)) or exc.__class__.__name__}" + ) + if last_error is not None: + raise last_error + raise RuntimeError("Device settings service is unavailable") + + def get_registration_status(): persisted = load_state() state = dict(persisted) try: - with MqttSettingsSession(state["device_id"]) as session: + def _status_flow(session, _contract_meta): session.login() - server_state = session.get_server_state() + return session.get_server_state() + + contract_meta, server_state = _with_settings_contract( + state["device_id"], + persisted, + "status", + _status_flow, + server_host_hint=state.get("host", ""), + ) current = { - "host": _truncate_empty(server_state.get("host")), + "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), "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", @@ -476,7 +602,7 @@ def register_device(host): save_state(working) try: - with MqttSettingsSession(working["device_id"]) as session: + def _register_flow(session, contract_meta): session.login() current_server_state = session.get_server_state() if _bool_value((current_server_state or {}).get("registered"), default=False): @@ -485,8 +611,28 @@ def register_device(host): event = session.wait_registered_event() event_payload = _extract_response_payload(event.get("responseText")) server_state = session.get_server_state() + return { + "event": event, + "event_payload": event_payload, + "server_state": server_state, + "contract_meta": contract_meta, + } + + contract_meta, flow = _with_settings_contract( + working["device_id"], + persisted, + "register", + _register_flow, + server_host_hint=validated_host, + ) + event = flow["event"] + event_payload = flow["event_payload"] + server_state = flow["server_state"] merged = _extract_registration_fields(server_state, event_payload, working) merged["host"] = validated_host + merged["contract_prefix"] = _truncate_empty(contract_meta.get("contract_prefix")) + merged["request_topic"] = _truncate_empty(contract_meta.get("request_topic")) + merged["response_topic"] = _truncate_empty(contract_meta.get("response_topic")) merged["status"] = "ready" if merged.get("registered") else "error" merged["last_event"] = { "action": str(event.get("action", "") or ""), diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index e311ddb..a9f85da 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -209,14 +209,16 @@ scanLog: [], checked: 0, total: 0, - currentSlave: null + currentSlave: null, + followingBottom: true, + viewportOffsetFromBottom: 0, + forceScroll: false }, selectedDevice: null, currentConfig: null, lastWriteResult: null, readConfigStatus: "idle", readConfigMessage: "", - confirmStopItscreenOpen: false, writeLog: [], writeForm: { slave: "", @@ -1006,6 +1008,14 @@ return notSpecified(payload && (payload.server || payload.host)); } + function itscreenContractLabel(payload) { + const contract = textValue(payload && payload.contract_prefix, ""); + if (contract === "it-screen") return "it-screen"; + if (contract === "iomatex") return "iomatex"; + if (contract === "universal") return "device/settings"; + return t("Not specified"); + } + function itscreenResponseDetails() { return textValue(state.itscreen.details, ""); } @@ -1075,6 +1085,9 @@ { label: t("Device name"), value: notSpecified(payload && payload.device_name) }, { label: t("Organization"), value: notSpecified(payload && payload.organization) }, { label: t("Token"), value: notSpecified(payload && payload.token) }, + { label: t("Detected contract"), value: itscreenContractLabel(payload) }, + { label: t("Request topic"), value: notSpecified(payload && payload.request_topic) }, + { label: t("Response topic"), value: notSpecified(payload && payload.response_topic) }, { label: t("Registered"), value: itscreenBooleanLabel(!!(payload && payload.registered), "registered") }, { label: t("Logged"), value: itscreenBooleanLabel(!!(payload && payload.logged), "logged") }, { label: t("Password state"), value: displayValue(payload && payload.password_state, t("Not specified")) } @@ -1895,6 +1908,9 @@
${esc(t("Reading configuration requires exclusive access to the Modbus port."))}
${esc(t("The it-screen client will be temporarily stopped."))}