Added uae and common registartion topics support devise/s..
This commit is contained in:
parent
31f1d975a7
commit
1193fa6cc1
|
|
@ -3,6 +3,7 @@ import json
|
||||||
import os
|
import os
|
||||||
import queue
|
import queue
|
||||||
import re
|
import re
|
||||||
|
import sys
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from urllib.parse import urlparse
|
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])?)*$")
|
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_PATH = "/userdata/device-id"
|
||||||
DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
|
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():
|
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):
|
def validate_host(host):
|
||||||
value = str(host or "").strip().lower()
|
value = str(host or "").strip().lower()
|
||||||
if not value:
|
if not value:
|
||||||
|
|
@ -81,6 +145,9 @@ def _default_state():
|
||||||
"organization": "",
|
"organization": "",
|
||||||
"device_name": "",
|
"device_name": "",
|
||||||
"device_id": identity["device_id"],
|
"device_id": identity["device_id"],
|
||||||
|
"contract_prefix": "",
|
||||||
|
"request_topic": "",
|
||||||
|
"response_topic": "",
|
||||||
"registered": False,
|
"registered": False,
|
||||||
"logged": False,
|
"logged": False,
|
||||||
"status": "idle",
|
"status": "idle",
|
||||||
|
|
@ -121,6 +188,9 @@ def save_state(state):
|
||||||
"organization": str(state.get("organization", "") or ""),
|
"organization": str(state.get("organization", "") or ""),
|
||||||
"device_name": str(state.get("device_name", "") or ""),
|
"device_name": str(state.get("device_name", "") or ""),
|
||||||
"device_id": str(state.get("device_id", "") or _device_identity()["device_id"]),
|
"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)),
|
"registered": bool(state.get("registered", False)),
|
||||||
"logged": bool(state.get("logged", False)),
|
"logged": bool(state.get("logged", False)),
|
||||||
"status": str(state.get("status", "idle") or "idle"),
|
"status": str(state.get("status", "idle") or "idle"),
|
||||||
|
|
@ -149,11 +219,6 @@ def _parse_mqtt_url(raw_url):
|
||||||
return host, port
|
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):
|
def _truncate_empty(value):
|
||||||
text = str(value or "").strip()
|
text = str(value or "").strip()
|
||||||
return text
|
return text
|
||||||
|
|
@ -227,32 +292,45 @@ def _device_name_from_payload(payload):
|
||||||
return ""
|
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 {}
|
payload = server_state if isinstance(server_state, dict) else {}
|
||||||
|
persisted = persisted or {}
|
||||||
identity = _device_identity()
|
identity = _device_identity()
|
||||||
username = _text_or_default(payload.get("username"))
|
username = _text_or_default(payload.get("username"))
|
||||||
device_name = _device_name_from_payload(payload)
|
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 {
|
return {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"source": source,
|
"source": source,
|
||||||
"device_id": identity["device_id"],
|
"device_id": identity["device_id"],
|
||||||
"device_name": _text_or_default(device_name),
|
"device_name": _text_or_default(device_name),
|
||||||
"server": _text_or_default(payload.get("host")),
|
"server": _text_or_default(host),
|
||||||
"host": _text_or_default(payload.get("host")),
|
"host": _text_or_default(host),
|
||||||
"organization": _text_or_default(payload.get("organization")),
|
"organization": _text_or_default(payload.get("organization")),
|
||||||
"token": _text_or_default(payload.get("token")),
|
"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),
|
"registered": _bool_value(payload.get("registered"), default=False),
|
||||||
"logged": _bool_value(payload.get("logged"), 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,
|
"username": username,
|
||||||
"status": "ready" if _bool_value(payload.get("registered"), default=False) else "not_registered",
|
"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": "",
|
"action": "",
|
||||||
"operation": "",
|
"operation": "",
|
||||||
"status": "",
|
"status": "",
|
||||||
"timestamp": "",
|
"timestamp": "",
|
||||||
}),
|
}),
|
||||||
"raw": dict(payload),
|
"raw_payload": dict(payload),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -268,14 +346,14 @@ def _public_error(exc):
|
||||||
|
|
||||||
|
|
||||||
class MqttSettingsSession:
|
class MqttSettingsSession:
|
||||||
def __init__(self, device_id):
|
def __init__(self, device_id, contract_meta):
|
||||||
if mqtt is None:
|
if mqtt is None:
|
||||||
raise RuntimeError("Device settings service is unavailable")
|
raise RuntimeError("Device settings service is unavailable")
|
||||||
self.device_id = device_id
|
self.device_id = device_id
|
||||||
self.queue = queue.Queue()
|
self.queue = queue.Queue()
|
||||||
self.connected = threading.Event()
|
self.connected = threading.Event()
|
||||||
self.error = None
|
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 = 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_connect = self._on_connect
|
||||||
self.client.on_message = self._on_message
|
self.client.on_message = self._on_message
|
||||||
|
|
@ -285,7 +363,7 @@ class MqttSettingsSession:
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
self.error = f"MQTT connect failed ({rc})"
|
self.error = f"MQTT connect failed ({rc})"
|
||||||
return
|
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:
|
if result != mqtt.MQTT_ERR_SUCCESS:
|
||||||
self.error = "Device settings service is unavailable"
|
self.error = "Device settings service is unavailable"
|
||||||
return
|
return
|
||||||
|
|
@ -337,7 +415,7 @@ class MqttSettingsSession:
|
||||||
|
|
||||||
def publish(self, payload):
|
def publish(self, payload):
|
||||||
self._drain()
|
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
|
deadline = time.time() + PUBLISH_TIMEOUT_SEC
|
||||||
while time.time() < deadline:
|
while time.time() < deadline:
|
||||||
if result.is_published():
|
if result.is_published():
|
||||||
|
|
@ -384,13 +462,13 @@ class MqttSettingsSession:
|
||||||
|
|
||||||
def get_server_state(self):
|
def get_server_state(self):
|
||||||
return self.publish_and_wait(
|
return self.publish_and_wait(
|
||||||
{"action": "get", "category": "server"},
|
{"action": "get", "category": SETTINGS_CATEGORY},
|
||||||
lambda item: isinstance(item, dict) and item.get("category") == "server",
|
lambda item: isinstance(item, dict) and item.get("category") == SETTINGS_CATEGORY,
|
||||||
timeout=REPLY_TIMEOUT_SEC,
|
timeout=REPLY_TIMEOUT_SEC,
|
||||||
)
|
)
|
||||||
|
|
||||||
def set_server(self, host):
|
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):
|
def wait_registered_event(self, timeout=REGISTER_TIMEOUT_SEC):
|
||||||
deadline = time.time() + timeout
|
deadline = time.time() + timeout
|
||||||
|
|
@ -428,21 +506,69 @@ def _build_public_status(state, error_text=""):
|
||||||
return output
|
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():
|
def get_registration_status():
|
||||||
persisted = load_state()
|
persisted = load_state()
|
||||||
state = dict(persisted)
|
state = dict(persisted)
|
||||||
try:
|
try:
|
||||||
with MqttSettingsSession(state["device_id"]) as session:
|
def _status_flow(session, _contract_meta):
|
||||||
session.login()
|
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 = {
|
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")),
|
"username": _truncate_empty(server_state.get("username")),
|
||||||
"password": _truncate_empty(server_state.get("password")),
|
"password": _truncate_empty(server_state.get("password")),
|
||||||
"token": _truncate_empty(server_state.get("token")),
|
"token": _truncate_empty(server_state.get("token")),
|
||||||
"organization": _truncate_empty(server_state.get("organization")),
|
"organization": _truncate_empty(server_state.get("organization")),
|
||||||
"device_name": _device_name_from_payload(server_state),
|
"device_name": _device_name_from_payload(server_state),
|
||||||
"device_id": _device_identity()["device_id"],
|
"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),
|
"registered": _bool_value(server_state.get("registered"), default=False),
|
||||||
"logged": _bool_value(server_state.get("logged"), 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",
|
"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)
|
save_state(working)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with MqttSettingsSession(working["device_id"]) as session:
|
def _register_flow(session, contract_meta):
|
||||||
session.login()
|
session.login()
|
||||||
current_server_state = session.get_server_state()
|
current_server_state = session.get_server_state()
|
||||||
if _bool_value((current_server_state or {}).get("registered"), default=False):
|
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 = session.wait_registered_event()
|
||||||
event_payload = _extract_response_payload(event.get("responseText"))
|
event_payload = _extract_response_payload(event.get("responseText"))
|
||||||
server_state = session.get_server_state()
|
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 = _extract_registration_fields(server_state, event_payload, working)
|
||||||
merged["host"] = validated_host
|
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["status"] = "ready" if merged.get("registered") else "error"
|
||||||
merged["last_event"] = {
|
merged["last_event"] = {
|
||||||
"action": str(event.get("action", "") or ""),
|
"action": str(event.get("action", "") or ""),
|
||||||
|
|
|
||||||
|
|
@ -209,14 +209,16 @@
|
||||||
scanLog: [],
|
scanLog: [],
|
||||||
checked: 0,
|
checked: 0,
|
||||||
total: 0,
|
total: 0,
|
||||||
currentSlave: null
|
currentSlave: null,
|
||||||
|
followingBottom: true,
|
||||||
|
viewportOffsetFromBottom: 0,
|
||||||
|
forceScroll: false
|
||||||
},
|
},
|
||||||
selectedDevice: null,
|
selectedDevice: null,
|
||||||
currentConfig: null,
|
currentConfig: null,
|
||||||
lastWriteResult: null,
|
lastWriteResult: null,
|
||||||
readConfigStatus: "idle",
|
readConfigStatus: "idle",
|
||||||
readConfigMessage: "",
|
readConfigMessage: "",
|
||||||
confirmStopItscreenOpen: false,
|
|
||||||
writeLog: [],
|
writeLog: [],
|
||||||
writeForm: {
|
writeForm: {
|
||||||
slave: "",
|
slave: "",
|
||||||
|
|
@ -1006,6 +1008,14 @@
|
||||||
return notSpecified(payload && (payload.server || payload.host));
|
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() {
|
function itscreenResponseDetails() {
|
||||||
return textValue(state.itscreen.details, "");
|
return textValue(state.itscreen.details, "");
|
||||||
}
|
}
|
||||||
|
|
@ -1075,6 +1085,9 @@
|
||||||
{ label: t("Device name"), value: notSpecified(payload && payload.device_name) },
|
{ label: t("Device name"), value: notSpecified(payload && payload.device_name) },
|
||||||
{ label: t("Organization"), value: notSpecified(payload && payload.organization) },
|
{ label: t("Organization"), value: notSpecified(payload && payload.organization) },
|
||||||
{ label: t("Token"), value: notSpecified(payload && payload.token) },
|
{ 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("Registered"), value: itscreenBooleanLabel(!!(payload && payload.registered), "registered") },
|
||||||
{ label: t("Logged"), value: itscreenBooleanLabel(!!(payload && payload.logged), "logged") },
|
{ label: t("Logged"), value: itscreenBooleanLabel(!!(payload && payload.logged), "logged") },
|
||||||
{ label: t("Password state"), value: displayValue(payload && payload.password_state, t("Not specified")) }
|
{ label: t("Password state"), value: displayValue(payload && payload.password_state, t("Not specified")) }
|
||||||
|
|
@ -1895,6 +1908,9 @@
|
||||||
<div class="key">${esc(t("Device name"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.device_name))}</div>
|
<div class="key">${esc(t("Device name"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.device_name))}</div>
|
||||||
<div class="key">${esc(t("Organization"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.organization))}</div>
|
<div class="key">${esc(t("Organization"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.organization))}</div>
|
||||||
<div class="key">${esc(t("Token"))}</div><div class="wrapValue" title="${esc(notSpecified(payload && payload.token))}">${esc(compactToken(payload && payload.token))}</div>
|
<div class="key">${esc(t("Token"))}</div><div class="wrapValue" title="${esc(notSpecified(payload && payload.token))}">${esc(compactToken(payload && payload.token))}</div>
|
||||||
|
<div class="key">${esc(t("Detected contract"))}</div><div>${esc(itscreenContractLabel(payload))}</div>
|
||||||
|
<div class="key">${esc(t("Request topic"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.request_topic))}</div>
|
||||||
|
<div class="key">${esc(t("Response topic"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.response_topic))}</div>
|
||||||
<div class="key">${esc(t("Registered"))}</div><div>${esc(itscreenBooleanLabel(!!(payload && payload.registered), "registered"))}</div>
|
<div class="key">${esc(t("Registered"))}</div><div>${esc(itscreenBooleanLabel(!!(payload && payload.registered), "registered"))}</div>
|
||||||
<div class="key">${esc(t("Logged"))}</div><div>${esc(itscreenBooleanLabel(!!(payload && payload.logged), "logged"))}</div>
|
<div class="key">${esc(t("Logged"))}</div><div>${esc(itscreenBooleanLabel(!!(payload && payload.logged), "logged"))}</div>
|
||||||
<div class="key">${esc(t("Password state"))}</div><div>${esc(displayValue(payload && payload.password_state, t("Not specified")))}</div>
|
<div class="key">${esc(t("Password state"))}</div><div>${esc(displayValue(payload && payload.password_state, t("Not specified")))}</div>
|
||||||
|
|
@ -2595,6 +2611,46 @@
|
||||||
return entries.map((entry) => `[${formatUtc(entry.timestamp)}] ${entry.message}`);
|
return entries.map((entry) => `[${formatUtc(entry.timestamp)}] ${entry.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function captureModbusScanLogViewport() {
|
||||||
|
const discovery = modbusState().discovery;
|
||||||
|
const body = document.getElementById("modbusScanLogBody");
|
||||||
|
if (!body) return;
|
||||||
|
const offset = body.scrollHeight - body.clientHeight - body.scrollTop;
|
||||||
|
discovery.followingBottom = offset <= 8;
|
||||||
|
discovery.viewportOffsetFromBottom = Math.max(0, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindModbusScanLogViewport() {
|
||||||
|
const body = document.getElementById("modbusScanLogBody");
|
||||||
|
if (!body || body.dataset.bound === "1") return;
|
||||||
|
body.dataset.bound = "1";
|
||||||
|
body.addEventListener("scroll", () => {
|
||||||
|
const discovery = modbusState().discovery;
|
||||||
|
const offset = body.scrollHeight - body.clientHeight - body.scrollTop;
|
||||||
|
discovery.followingBottom = offset <= 8;
|
||||||
|
discovery.viewportOffsetFromBottom = Math.max(0, offset);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateModbusScanLogViewport() {
|
||||||
|
if (state.activeTab !== "modbus") return;
|
||||||
|
const discovery = modbusState().discovery;
|
||||||
|
const body = document.getElementById("modbusScanLogBody");
|
||||||
|
if (!body) return;
|
||||||
|
|
||||||
|
bindModbusScanLogViewport();
|
||||||
|
|
||||||
|
if (discovery.followingBottom || discovery.forceScroll) {
|
||||||
|
body.scrollTop = body.scrollHeight;
|
||||||
|
discovery.followingBottom = true;
|
||||||
|
discovery.viewportOffsetFromBottom = 0;
|
||||||
|
} else {
|
||||||
|
const nextTop = Math.max(0, body.scrollHeight - body.clientHeight - (discovery.viewportOffsetFromBottom || 0));
|
||||||
|
body.scrollTop = nextTop;
|
||||||
|
}
|
||||||
|
discovery.forceScroll = false;
|
||||||
|
}
|
||||||
|
|
||||||
function appendModbusWriteLog(message, level = "info") {
|
function appendModbusWriteLog(message, level = "info") {
|
||||||
if (!message) return;
|
if (!message) return;
|
||||||
const log = modbusState();
|
const log = modbusState();
|
||||||
|
|
@ -2620,9 +2676,10 @@
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function modbusEnsureSession() {
|
async function modbusEnsureSession(options = {}) {
|
||||||
const log = modbusState();
|
const log = modbusState();
|
||||||
const portInfo = modbusSelectedPortStatus() || {};
|
const portInfo = modbusSelectedPortStatus() || {};
|
||||||
|
const stopItscreen = options.stopItscreen !== undefined ? !!options.stopItscreen : !!log.stopItscreen;
|
||||||
if (log.session || portInfo.locked) {
|
if (log.session || portInfo.locked) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
@ -2630,7 +2687,7 @@
|
||||||
method: "POST",
|
method: "POST",
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ port: log.port, stop_itscreen: !!log.stopItscreen })
|
body: JSON.stringify({ port: log.port, stop_itscreen: stopItscreen })
|
||||||
});
|
});
|
||||||
log.session = payload.lock || null;
|
log.session = payload.lock || null;
|
||||||
ingestModbusPayload(payload);
|
ingestModbusPayload(payload);
|
||||||
|
|
@ -2728,22 +2785,6 @@
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderModbusReadConfigDialog() {
|
|
||||||
if (!modbusState().confirmStopItscreenOpen) return "";
|
|
||||||
return `
|
|
||||||
<div class="modalBackdrop" role="presentation">
|
|
||||||
<div class="modalCard" role="dialog" aria-modal="true" aria-labelledby="modbusStopItscreenTitle">
|
|
||||||
<h3 id="modbusStopItscreenTitle">${esc(t("Stop it-screen client?"))}</h3>
|
|
||||||
<p>${esc(t("Reading configuration requires exclusive access to the Modbus port."))}<br>${esc(t("The it-screen client will be temporarily stopped."))}</p>
|
|
||||||
<div class="actionRow">
|
|
||||||
<button class="actionBtn secondary" type="button" onclick="window.__modbusCancelReadConfigPrompt()">${esc(t("Cancel"))}</button>
|
|
||||||
<button class="actionBtn" type="button" onclick="window.__modbusConfirmReadConfigPrompt()">${esc(t("Stop and continue"))}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function modbusWriteStatusMeta() {
|
function modbusWriteStatusMeta() {
|
||||||
const result = modbusState().lastWriteResult;
|
const result = modbusState().lastWriteResult;
|
||||||
if (!result) return "";
|
if (!result) return "";
|
||||||
|
|
@ -2863,7 +2904,7 @@
|
||||||
<div class="formHint">${esc(zeroBased ? t("Use zero-based addressing for this device family.") : t("This device family uses one-based addressing."))}</div>
|
<div class="formHint">${esc(zeroBased ? t("Use zero-based addressing for this device family.") : t("This device family uses one-based addressing."))}</div>
|
||||||
<article class="scanLogCard">
|
<article class="scanLogCard">
|
||||||
<div class="cardTop"><div><h2>${esc(t("Scan log"))}</h2></div></div>
|
<div class="cardTop"><div><h2>${esc(t("Scan log"))}</h2></div></div>
|
||||||
<div class="modbusScanLogBody">${scanLogLines.length ? scanLogLines.map((line) => `<div class="logLine">${esc(line)}</div>`).join("") : `<div class="logEmpty">${esc(t("No scan activity yet."))}</div>`}</div>
|
<div class="modbusScanLogBody" id="modbusScanLogBody">${scanLogLines.length ? scanLogLines.map((line) => `<div class="logLine">${esc(line)}</div>`).join("") : `<div class="logEmpty">${esc(t("No scan activity yet."))}</div>`}</div>
|
||||||
</article>
|
</article>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
|
|
@ -2993,7 +3034,6 @@
|
||||||
|
|
||||||
${renderModbusLogPanel()}
|
${renderModbusLogPanel()}
|
||||||
</div>
|
</div>
|
||||||
${renderModbusReadConfigDialog()}
|
|
||||||
</section>
|
</section>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
@ -3025,7 +3065,9 @@
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (state.activeTab === "modbus") {
|
if (state.activeTab === "modbus") {
|
||||||
|
captureModbusScanLogViewport();
|
||||||
nodes.content.innerHTML = renderModbusTab();
|
nodes.content.innerHTML = renderModbusTab();
|
||||||
|
updateModbusScanLogViewport();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (state.activeTab === "tscreen") {
|
if (state.activeTab === "tscreen") {
|
||||||
|
|
@ -3873,7 +3915,6 @@
|
||||||
log.lastWriteResult = null;
|
log.lastWriteResult = null;
|
||||||
log.readConfigStatus = "idle";
|
log.readConfigStatus = "idle";
|
||||||
log.readConfigMessage = "";
|
log.readConfigMessage = "";
|
||||||
log.confirmStopItscreenOpen = false;
|
|
||||||
const profile = modbusSelectedProfile();
|
const profile = modbusSelectedProfile();
|
||||||
if (profile && profile.transport) {
|
if (profile && profile.transport) {
|
||||||
log.discovery.baud = String(profile.transport.default_baud || 9600);
|
log.discovery.baud = String(profile.transport.default_baud || 9600);
|
||||||
|
|
@ -4027,6 +4068,9 @@
|
||||||
log.discovery.jobId = "";
|
log.discovery.jobId = "";
|
||||||
log.discovery.state = "running";
|
log.discovery.state = "running";
|
||||||
log.discovery.message = t("Scanning in progress. It may take some minutes.");
|
log.discovery.message = t("Scanning in progress. It may take some minutes.");
|
||||||
|
log.discovery.followingBottom = true;
|
||||||
|
log.discovery.viewportOffsetFromBottom = 0;
|
||||||
|
log.discovery.forceScroll = true;
|
||||||
appendModbusLog(mode === "deep" ? t("Deep scan started") : t("Quick scan started"), "info");
|
appendModbusLog(mode === "deep" ? t("Deep scan started") : t("Quick scan started"), "info");
|
||||||
if (state.activeTab === "modbus") renderActiveTab();
|
if (state.activeTab === "modbus") renderActiveTab();
|
||||||
try {
|
try {
|
||||||
|
|
@ -4088,19 +4132,7 @@
|
||||||
await window.__modbusReadConfig();
|
await window.__modbusReadConfig();
|
||||||
};
|
};
|
||||||
|
|
||||||
async function getItscreenServiceStatusFresh() {
|
async function executeModbusReadConfig() {
|
||||||
try {
|
|
||||||
const payload = await fetchJson("/api/itscreen/status", { cache: "no-store" });
|
|
||||||
state.itscreen.data = payload;
|
|
||||||
state.itscreen.error = "";
|
|
||||||
state.itscreen.details = "";
|
|
||||||
return payload.service || {};
|
|
||||||
} catch (error) {
|
|
||||||
return itscreenService() || {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function executeModbusReadConfig(options = {}) {
|
|
||||||
const log = modbusState();
|
const log = modbusState();
|
||||||
log.busyAction = "read_config";
|
log.busyAction = "read_config";
|
||||||
log.error = "";
|
log.error = "";
|
||||||
|
|
@ -4108,12 +4140,8 @@
|
||||||
log.readConfigMessage = "";
|
log.readConfigMessage = "";
|
||||||
if (state.activeTab === "modbus") renderActiveTab();
|
if (state.activeTab === "modbus") renderActiveTab();
|
||||||
try {
|
try {
|
||||||
if (options.stopItscreenFirst) {
|
|
||||||
log.stopItscreen = true;
|
|
||||||
appendModbusLog(t("it-screen client will be stopped for Modbus access"), "warn");
|
|
||||||
}
|
|
||||||
const current = modbusCurrentConnection();
|
const current = modbusCurrentConnection();
|
||||||
await modbusEnsureSession();
|
await modbusEnsureSession({ stopItscreen: false });
|
||||||
const payload = await fetchJson("/api/modbus/read-config", {
|
const payload = await fetchJson("/api/modbus/read-config", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
|
|
@ -4156,25 +4184,7 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
window.__modbusCancelReadConfigPrompt = function () {
|
|
||||||
modbusState().confirmStopItscreenOpen = false;
|
|
||||||
if (state.activeTab === "modbus") renderActiveTab();
|
|
||||||
};
|
|
||||||
|
|
||||||
window.__modbusConfirmReadConfigPrompt = async function () {
|
|
||||||
modbusState().confirmStopItscreenOpen = false;
|
|
||||||
if (state.activeTab === "modbus") renderActiveTab();
|
|
||||||
await executeModbusReadConfig({ stopItscreenFirst: true });
|
|
||||||
};
|
|
||||||
|
|
||||||
window.__modbusReadConfig = async function () {
|
window.__modbusReadConfig = async function () {
|
||||||
const log = modbusState();
|
|
||||||
const service = await getItscreenServiceStatusFresh();
|
|
||||||
if (service && service.active) {
|
|
||||||
log.confirmStopItscreenOpen = true;
|
|
||||||
if (state.activeTab === "modbus") renderActiveTab();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await executeModbusReadConfig();
|
await executeModbusReadConfig();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue