diff --git a/.gitignore b/.gitignore
index 3e132a1..857d398 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,4 @@ __pycache__/
*.zip
*:Zone.Identifier
+client/
diff --git a/stage_itscreen/stage_itscreen_install.sh b/stage_itscreen/stage_itscreen_install.sh
index 3d2d5cf..cbda979 100755
--- a/stage_itscreen/stage_itscreen_install.sh
+++ b/stage_itscreen/stage_itscreen_install.sh
@@ -655,6 +655,8 @@ RuntimeDirectoryMode=0755
Environment=ITSCREEN_DISPLAY=:0
Environment=ITSCREEN_VT=vt7
ExecStartPre=/usr/bin/nm-online -s -q --timeout=45
+# Fix intermittent black screen caused by HDMI/DRM/X startup race on RK3568.
+ExecStartPre=/bin/bash -ec 'for ((i=0; i<15; i++)); do if [[ -e /sys/class/drm/card0-HDMI-A-1 ]] && [[ "$(< /sys/class/drm/card0-HDMI-A-1/status)" == "connected" ]]; then /bin/sleep 2; exit 0; fi; /bin/sleep 1; done; echo "HDMI not ready after timeout" >&2; exit 1'
ExecStartPre=/usr/local/bin/itscreen-x11-cleanup
ExecStart=/usr/local/bin/itscreen-x11-launch
ExecStopPost=/usr/local/bin/itscreen-x11-cleanup
diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py
index a11926b..db2ba1e 100644
--- a/stage_ui/console_core/backend/app.py
+++ b/stage_ui/console_core/backend/app.py
@@ -15,6 +15,20 @@ from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from itscreen_registration import get_registration_status, register_device, reset_registration
+from modbus_backend import (
+ ApiError as ModbusApiError,
+ acquire_session as modbus_acquire_session,
+ get_discovery_job as modbus_get_discovery_job,
+ list_ports_payload as modbus_list_ports_payload,
+ profiles_payload as modbus_profiles_payload,
+ read_audit as modbus_read_audit,
+ read_device_config as modbus_read_device_config,
+ read_registers as modbus_read_registers,
+ release_session as modbus_release_session,
+ start_discovery as modbus_start_discovery,
+ write_device_config as modbus_write_device_config,
+ write_register as modbus_write_register,
+)
APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
@@ -1886,13 +1900,20 @@ class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
return
+ def _write_response_body(self, body):
+ try:
+ self.wfile.write(body)
+ except (BrokenPipeError, ConnectionResetError):
+ return False
+ return True
+
def send_json(self, payload, code=200):
body = json.dumps(payload, indent=2).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
- self.wfile.write(body)
+ self._write_response_body(body)
def send_html(self, html, code=200, extra_headers=None):
body = html.encode("utf-8")
@@ -1905,7 +1926,7 @@ class Handler(BaseHTTPRequestHandler):
for key, value in extra_headers.items():
self.send_header(key, value)
self.end_headers()
- self.wfile.write(body)
+ self._write_response_body(body)
def send_redirect(self, location, code=302, extra_headers=None):
self.send_response(code)
@@ -1938,7 +1959,7 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
- self.wfile.write(data)
+ self._write_response_body(data)
def send_sse_headers(self):
self.send_response(200)
@@ -2082,6 +2103,40 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc), "networks": []}, code=500)
return
+ if parsed.path == "/api/modbus/ports":
+ try:
+ self.send_json(modbus_list_ports_payload())
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/modbus/profiles":
+ try:
+ self.send_json(modbus_profiles_payload())
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/modbus/audit":
+ try:
+ limit = int((query.get("limit") or [120])[0])
+ self.send_json(modbus_read_audit(limit))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path.startswith("/api/modbus/discover/"):
+ job_id = parsed.path.rsplit("/", 1)[-1]
+ try:
+ self.send_json(modbus_get_discovery_job(job_id))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
if parsed.path == "/api/itscreen/status":
try:
self.send_json(build_itscreen_status_payload())
@@ -2254,6 +2309,141 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
+ if parsed.path == "/api/modbus/session/acquire":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(modbus_acquire_session(
+ str(payload.get("port", "")),
+ bool(payload.get("stop_itscreen", False)),
+ source="console_ui",
+ ))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/modbus/session/release":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(modbus_release_session(
+ str(payload.get("port", "")),
+ bool(payload.get("restart_itscreen", False)),
+ source="console_ui",
+ ))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/modbus/discover":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(modbus_start_discovery(
+ port=str(payload.get("port", "")),
+ family=str(payload.get("family", "")),
+ slave_range=list(payload.get("slave_range") or [1, 10]),
+ baud=int(payload.get("baud", 9600)),
+ parity=str(payload.get("parity", "none")),
+ deep=bool(payload.get("deep", False)),
+ source="console_ui",
+ ))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details, "devices": [], "scan_log": []}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc), "devices": [], "scan_log": []}, code=500)
+ return
+ if parsed.path == "/api/modbus/read-config":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(modbus_read_device_config(
+ port=str(payload.get("port", "")),
+ family=str(payload.get("family", "")),
+ slave=int(payload.get("slave", 1)),
+ baud=int(payload.get("baud", 9600)),
+ parity=str(payload.get("parity", "none")),
+ source="console_ui",
+ ))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/modbus/write-config":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(modbus_write_device_config(
+ port=str(payload.get("port", "")),
+ family=str(payload.get("family", "")),
+ baudrate=int(payload.get("baudrate", 9600)),
+ current=payload.get("current") or {},
+ target=payload.get("target") or {},
+ strategy=str(payload.get("strategy", "both")),
+ source="console_ui",
+ ))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/modbus/register/read":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(modbus_read_registers(
+ port=str(payload.get("port", "")),
+ family=str(payload.get("family", "")),
+ slave=int(payload.get("slave", 1)),
+ baud=int(payload.get("baud", 9600)),
+ parity=str(payload.get("parity", "none")),
+ address=int(payload.get("address", 0)),
+ count=int(payload.get("count", 1)),
+ register_type=str(payload.get("register_type", "holding")),
+ decode_mode=str(payload.get("decode_mode", "uint16")),
+ source="console_ui",
+ ))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
+ if parsed.path == "/api/modbus/register/write":
+ payload = self.read_json_body()
+ if payload is None:
+ self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
+ return
+ try:
+ self.send_json(modbus_write_register(
+ port=str(payload.get("port", "")),
+ family=str(payload.get("family", "")),
+ slave=int(payload.get("slave", 1)),
+ baud=int(payload.get("baud", 9600)),
+ parity=str(payload.get("parity", "none")),
+ address=int(payload.get("address", 0)),
+ value=int(payload.get("value", 0)),
+ source="console_ui",
+ ))
+ except ModbusApiError as exc:
+ self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
+ except Exception as exc:
+ self.send_json({"ok": False, "error": str(exc)}, code=500)
+ return
if parsed.path == "/api/actions/audio-test":
payload = self.read_json_body()
if payload is None:
diff --git a/stage_ui/console_core/backend/modbus_backend.py b/stage_ui/console_core/backend/modbus_backend.py
new file mode 100644
index 0000000..5683ba5
--- /dev/null
+++ b/stage_ui/console_core/backend/modbus_backend.py
@@ -0,0 +1,1645 @@
+#!/usr/bin/env python3
+import glob
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import threading
+import time
+import uuid
+from typing import Any, Dict, List, Optional, Tuple
+
+APP_DIR = "/opt/iomatex-console"
+MODBUS_PROFILES_DIR = os.path.join(APP_DIR, "modbus_profiles")
+MODBUS_RUN_DIR = "/run/iomatex"
+MODBUS_AUDIT_LOG = "/var/log/iomatex-console/modbus-audit.log"
+ITSCREEN_SERVICE_UNIT = "itscreen-x11.service"
+DEFAULT_DISCOVER_TIMEOUT = 6.0
+DISCOVERY_JOBS: Dict[str, Dict[str, Any]] = {}
+DISCOVERY_JOBS_LOCK = threading.Lock()
+
+PORT_GLOBS = (
+ "/dev/ttyS*",
+ "/dev/ttyUSB*",
+ "/dev/ttyAMA*",
+ "/dev/ttyACM*",
+)
+
+
+class ApiError(Exception):
+ def __init__(self, message: str, code: int = 400, details: Optional[str] = None):
+ super().__init__(message)
+ self.message = message
+ self.code = code
+ self.details = details or ""
+
+
+def utc_now_iso() -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+
+def ensure_runtime_dirs() -> None:
+ os.makedirs(MODBUS_RUN_DIR, exist_ok=True)
+ os.makedirs(os.path.dirname(MODBUS_AUDIT_LOG), exist_ok=True)
+
+
+def run(cmd: List[str], timeout: float = 5.0) -> Tuple[int, str, str]:
+ try:
+ proc = subprocess.run(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=timeout,
+ check=False,
+ )
+ return proc.returncode, (proc.stdout or "").strip(), (proc.stderr or "").strip()
+ except subprocess.TimeoutExpired as exc:
+ stdout = (exc.stdout or "").strip() if isinstance(exc.stdout, str) else ""
+ stderr = (exc.stderr or "").strip() if isinstance(exc.stderr, str) else ""
+ return 124, stdout, stderr or "Command timed out"
+ except Exception as exc:
+ return 1, "", str(exc)
+
+
+def command_exists(name: str) -> bool:
+ return shutil.which(name) is not None
+
+
+def backend_log(event: str, **fields: Any) -> None:
+ payload = {"timestamp": utc_now_iso(), "event": event}
+ payload.update(fields)
+ try:
+ print(json.dumps(payload, ensure_ascii=True, sort_keys=True), file=sys.stderr, flush=True)
+ except Exception:
+ pass
+
+
+def classify_mbpoll_error(stdout: str, stderr: str, returncode: int) -> str:
+ text = "\n".join(part for part in [stdout, stderr] if part).lower()
+ if returncode == 124 or "timed out" in text or "time-out" in text:
+ return "timeout"
+ if "illegal data address" in text:
+ return "illegal_data_address"
+ if "illegal data value" in text:
+ return "illegal_data_value"
+ if "device or resource busy" in text or "resource busy" in text:
+ return "port_busy"
+ if "permission denied" in text:
+ return "permission_denied"
+ if "no such file" in text:
+ return "port_missing"
+ if "i/o error" in text or "input/output error" in text:
+ return "io_error"
+ if "modbus exception" in text:
+ return "modbus_exception"
+ if "crc" in text:
+ return "crc_error"
+ if "failed" in text:
+ return "failed"
+ return "unknown"
+
+
+def trim_lines(text: str, limit: int = 20) -> List[str]:
+ lines = [line.rstrip() for line in (text or "").splitlines() if line.strip()]
+ if len(lines) > limit:
+ return lines[:limit] + [f"... ({len(lines) - limit} more lines)"]
+ return lines
+
+
+def summarize_text(text: str, limit: int = 4000) -> str:
+ value = (text or "").strip()
+ if len(value) <= limit:
+ return value
+ return value[:limit] + f"\n... ({len(value) - limit} more chars)"
+
+
+def mbpoll_register_type(register_type: str, decode_mode: str) -> str:
+ reg = str(register_type or "holding").strip().lower()
+ decode = str(decode_mode or "uint16").strip().lower()
+ table = {
+ "holding": "4",
+ "input": "3",
+ "coil": "0",
+ "discrete": "1",
+ }
+ code = table.get(reg)
+ if not code:
+ raise ApiError(f"Unsupported register type: {register_type}", 400)
+ if reg in ("coil", "discrete"):
+ return code
+ if decode in ("hex",):
+ return f"{code}:hex"
+ if decode in ("int", "int32"):
+ return f"{code}:int"
+ if decode in ("float", "float32"):
+ return f"{code}:float"
+ if decode in ("string",):
+ return f"{code}:string"
+ if decode in ("int16", "signed"):
+ return f"{code}:int16"
+ return code
+
+
+def mbpoll_parity_name(parity: str) -> str:
+ value = str(parity or "none").strip().lower()
+ if value not in ("none", "even", "odd"):
+ raise ApiError(f"Unsupported parity: {parity}", 400)
+ return value
+
+
+def parse_mbpoll_values(stdout: str) -> List[Dict[str, Any]]:
+ values = []
+ for line in (stdout or "").splitlines():
+ match = re.match(r"^\[(\d+)\]:\s*(.+?)\s*$", line.strip())
+ if not match:
+ continue
+ raw_value = match.group(2).strip()
+ decoded: Any = raw_value
+ try:
+ decoded = int(raw_value, 0)
+ except Exception:
+ try:
+ decoded = float(raw_value)
+ except Exception:
+ decoded = raw_value
+ values.append({
+ "address": int(match.group(1)),
+ "raw": raw_value,
+ "value": decoded,
+ })
+ return values
+
+
+def mbpoll_read(
+ *,
+ port: str,
+ slave: int,
+ address: int,
+ count: int,
+ baud: int,
+ parity: str,
+ register_type: str,
+ data_bits: int = 8,
+ stop_bits: int = 1,
+ zero_based: bool = True,
+ timeout: float = DEFAULT_DISCOVER_TIMEOUT,
+ decode_mode: str = "uint16",
+ retries: int = 1,
+) -> Dict[str, Any]:
+ if not command_exists("mbpoll"):
+ raise ApiError("mbpoll is not installed", 503)
+ cmd = [
+ "mbpoll",
+ "-m",
+ "rtu",
+ "-1",
+ "-a",
+ str(int(slave)),
+ "-b",
+ str(int(baud)),
+ "-d",
+ str(int(data_bits)),
+ "-s",
+ str(int(stop_bits)),
+ "-P",
+ mbpoll_parity_name(parity),
+ "-t",
+ mbpoll_register_type(register_type, decode_mode),
+ "-r",
+ str(int(address)),
+ "-c",
+ str(int(count)),
+ "-o",
+ f"{float(timeout):.2f}",
+ ]
+ if zero_based:
+ cmd.append("-0")
+ cmd.append(port)
+
+ attempts = max(1, int(retries) + 1)
+ last_result = None
+ for attempt in range(1, attempts + 1):
+ rc, stdout, stderr = run(cmd, timeout=timeout + 2.0)
+ values = parse_mbpoll_values(stdout)
+ result = {
+ "ok": rc == 0 and bool(values),
+ "returncode": rc,
+ "stdout_lines": trim_lines(stdout),
+ "stderr_lines": trim_lines(stderr),
+ "values": values,
+ "error_type": classify_mbpoll_error(stdout, stderr, rc) if rc != 0 or not values else "",
+ "attempt": attempt,
+ "command": cmd,
+ }
+ last_result = result
+ if result["ok"]:
+ return result
+ return last_result or {
+ "ok": False,
+ "returncode": 1,
+ "stdout_lines": [],
+ "stderr_lines": [],
+ "values": [],
+ "error_type": "unknown",
+ "attempt": attempts,
+ "command": cmd,
+ }
+
+
+def mbpoll_write_register(
+ *,
+ port: str,
+ slave: int,
+ address: int,
+ value: int,
+ baud: int,
+ parity: str,
+ data_bits: int = 8,
+ stop_bits: int = 1,
+ zero_based: bool = True,
+ timeout: float = DEFAULT_DISCOVER_TIMEOUT,
+) -> Dict[str, Any]:
+ if not command_exists("mbpoll"):
+ raise ApiError("mbpoll is not installed", 503)
+ cmd = [
+ "mbpoll",
+ "-m",
+ "rtu",
+ "-1",
+ "-a",
+ str(int(slave)),
+ "-b",
+ str(int(baud)),
+ "-d",
+ str(int(data_bits)),
+ "-s",
+ str(int(stop_bits)),
+ "-P",
+ mbpoll_parity_name(parity),
+ "-t",
+ "4",
+ "-r",
+ str(int(address)),
+ "-o",
+ f"{float(timeout):.2f}",
+ ]
+ if zero_based:
+ cmd.append("-0")
+ cmd.append(port)
+ cmd.append(str(int(value)))
+ started = time.monotonic()
+ rc, stdout, stderr = run(cmd, timeout=timeout + 2.0)
+ elapsed_ms = int((time.monotonic() - started) * 1000)
+ payload = {
+ "ok": rc == 0,
+ "returncode": rc,
+ "stdout": summarize_text(stdout),
+ "stderr": summarize_text(stderr),
+ "stdout_lines": trim_lines(stdout),
+ "stderr_lines": trim_lines(stderr),
+ "error_type": "" if rc == 0 else classify_mbpoll_error(stdout, stderr, rc),
+ "command": cmd,
+ "elapsed_ms": elapsed_ms,
+ "write_sent": rc == 0,
+ }
+ backend_log(
+ "modbus_write_register",
+ command=cmd,
+ exit_code=rc,
+ elapsed_ms=elapsed_ms,
+ stdout=payload["stdout"],
+ stderr=payload["stderr"],
+ ok=payload["ok"],
+ port=port,
+ slave=int(slave),
+ address=int(address),
+ value=int(value),
+ )
+ return payload
+
+
+def read_profile_register(
+ *,
+ profile: Dict[str, Any],
+ port: str,
+ slave: int,
+ baud: int,
+ parity: str,
+ register_name: str,
+ timeout: float = DEFAULT_DISCOVER_TIMEOUT,
+ retries: int = 1,
+ decode_mode: str = "uint16",
+) -> Dict[str, Any]:
+ reg = (profile.get("registers") or {}).get(register_name)
+ if not reg:
+ return {
+ "ok": False,
+ "returncode": 0,
+ "stdout": "",
+ "stderr": "",
+ "stdout_lines": [],
+ "stderr_lines": [],
+ "values": [],
+ "error_type": "unsupported_register",
+ "attempt": 0,
+ "command": [],
+ }
+ transport = profile["transport"]
+ result = mbpoll_read(
+ port=port,
+ slave=int(slave),
+ address=int(reg["address"]),
+ count=int(reg["count"]),
+ baud=int(baud),
+ parity=str(parity),
+ register_type=str(reg["type"]),
+ data_bits=int(transport["default_databits"]),
+ stop_bits=int(transport["default_stopbits"]),
+ zero_based=bool(transport.get("zero_based", True)),
+ timeout=timeout,
+ decode_mode=decode_mode,
+ retries=retries,
+ )
+ result["register_name"] = register_name
+ result["register"] = {
+ "address": int(reg["address"]),
+ "count": int(reg["count"]),
+ "type": str(reg["type"]),
+ }
+ return result
+
+
+def device_probe(
+ *,
+ port: str,
+ family: str,
+ slave: int,
+ baud: int,
+ parity: str,
+ timeout: float = DEFAULT_DISCOVER_TIMEOUT,
+ retries: int = 1,
+) -> Dict[str, Any]:
+ profile = get_profile(family)
+ test_result = read_profile_register(
+ profile=profile,
+ port=port,
+ slave=slave,
+ baud=baud,
+ parity=parity,
+ register_name="test_read",
+ timeout=timeout,
+ retries=retries,
+ )
+ slave_result = read_profile_register(
+ profile=profile,
+ port=port,
+ slave=slave,
+ baud=baud,
+ parity=parity,
+ register_name="slave_id",
+ timeout=timeout,
+ retries=retries,
+ ) if "slave_id" in (profile.get("registers") or {}) else None
+ comm_result = read_profile_register(
+ profile=profile,
+ port=port,
+ slave=slave,
+ baud=baud,
+ parity=parity,
+ register_name="comm_profile",
+ timeout=timeout,
+ retries=retries,
+ ) if "comm_profile" in (profile.get("registers") or {}) else None
+
+ test_value = test_result["values"][0]["value"] if test_result.get("ok") and test_result.get("values") else None
+ slave_value = slave_result["values"][0]["value"] if slave_result and slave_result.get("ok") and slave_result.get("values") else None
+ comm_value = comm_result["values"][0]["value"] if comm_result and comm_result.get("ok") and comm_result.get("values") else None
+ decoded_comm = decode_comm_profile(profile, comm_value)
+ ok = bool(test_result.get("ok")) and (slave_result is None or bool(slave_result.get("ok")))
+ return {
+ "ok": ok,
+ "family": family,
+ "port": port,
+ "requested": {
+ "slave": int(slave),
+ "baud": int(baud),
+ "parity": str(parity),
+ },
+ "current": {
+ "slave": int(slave_value) if slave_value is not None else int(slave),
+ "baud": decoded_comm["baud"] if decoded_comm["decoded"] else int(baud),
+ "parity": decoded_comm["parity"] if decoded_comm["decoded"] else str(parity),
+ },
+ "current_config": {
+ "slave_id": int(slave_value) if slave_value is not None else None,
+ "baud": decoded_comm["baud"] if decoded_comm["decoded"] else None,
+ "parity": decoded_comm["parity"] if decoded_comm["decoded"] else None,
+ "comm_profile_register": comm_value,
+ "comm_profile_decoded": decoded_comm["decoded"],
+ "supports_serial_write": bool(profile.get("capabilities", {}).get("supports_serial_write")),
+ "supports_id_write": bool(profile.get("capabilities", {}).get("supports_id_write")),
+ },
+ "raw_values": {
+ key: [item.get("value") for item in result.get("values", [])]
+ for key, result in (("test_read", test_result), ("slave_id", slave_result), ("comm_profile", comm_result))
+ if result and result.get("values")
+ },
+ "test_register": {
+ "address": int(profile["registers"]["test_read"]["address"]),
+ "value": test_value,
+ },
+ "debug": {
+ "test_read": test_result,
+ "slave_id": slave_result,
+ "comm_profile": comm_result,
+ },
+ }
+
+
+def list_uart_ports() -> List[str]:
+ ports = set()
+ for pattern in PORT_GLOBS:
+ for path in glob.glob(pattern):
+ if os.path.exists(path):
+ ports.add(path)
+ return sorted(ports)
+
+
+def safe_port_name(port: str) -> str:
+ name = os.path.basename(str(port or "").strip())
+ if not name or "/" in name or name in (".", ".."):
+ raise ApiError("Invalid port", 400)
+ return name
+
+
+def lock_path_for_port(port: str) -> str:
+ return os.path.join(MODBUS_RUN_DIR, f"modbus-{safe_port_name(port)}.lock")
+
+
+def read_lock(port: str) -> Optional[Dict[str, Any]]:
+ path = lock_path_for_port(port)
+ try:
+ with open(path, "r", encoding="utf-8") as fh:
+ data = json.load(fh)
+ if isinstance(data, dict):
+ data["path"] = path
+ return data
+ except FileNotFoundError:
+ return None
+ except Exception:
+ return {"path": path, "owner": "unknown", "created_at": "", "stale": True}
+ return None
+
+
+def acquire_lock(port: str, meta: Dict[str, Any]) -> Dict[str, Any]:
+ ensure_runtime_dirs()
+ path = lock_path_for_port(port)
+ payload = dict(meta)
+ payload["port"] = port
+ payload["created_at"] = utc_now_iso()
+ fd = None
+ try:
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ json.dump(payload, fh, indent=2, sort_keys=True)
+ fd = None
+ payload["path"] = path
+ return payload
+ except FileExistsError:
+ existing = read_lock(port) or {}
+ raise ApiError("Port is already locked by modbus tool", 409, json.dumps(existing))
+ finally:
+ if fd is not None:
+ try:
+ os.close(fd)
+ except Exception:
+ pass
+
+
+def release_lock(port: str) -> Optional[Dict[str, Any]]:
+ lock = read_lock(port)
+ path = lock_path_for_port(port)
+ try:
+ os.unlink(path)
+ except FileNotFoundError:
+ return None
+ return lock
+
+
+def busy_processes(port: str) -> List[str]:
+ if not os.path.exists(port) or not command_exists("fuser"):
+ return []
+ rc, stdout, stderr = run(["fuser", port], timeout=3.0)
+ text = " ".join(part for part in [stdout, stderr] if part).strip()
+ if rc != 0 and not text:
+ return []
+ pids = []
+ for token in re.findall(r"\d+", text):
+ if token not in pids:
+ pids.append(token)
+ rows = []
+ for pid in pids:
+ cmdline = ""
+ try:
+ with open(f"/proc/{pid}/cmdline", "rb") as fh:
+ cmdline = fh.read().replace(b"\x00", b" ").decode("utf-8", errors="ignore").strip()
+ except Exception:
+ cmdline = ""
+ if not cmdline:
+ rows.append(pid)
+ else:
+ rows.append(f"{pid}:{cmdline}")
+ return rows
+
+
+def systemctl_is_active(unit_name: str) -> bool:
+ rc, stdout, _ = run(["systemctl", "is-active", unit_name], timeout=5.0)
+ return rc == 0 and stdout.strip() == "active"
+
+
+def systemctl_control(unit_name: str, action: str) -> None:
+ rc, _, stderr = run(["systemctl", action, unit_name], timeout=20.0)
+ if rc != 0:
+ raise ApiError(f"Failed to {action} {unit_name}", 502, stderr)
+
+
+def itscreen_conflict_expected(port: str) -> bool:
+ return os.path.basename(port) == "ttyS3"
+
+
+def port_status(port: str) -> Dict[str, Any]:
+ lock = read_lock(port)
+ busy = busy_processes(port)
+ itscreen_running = systemctl_is_active(ITSCREEN_SERVICE_UNIT)
+ busy_by_service = bool(busy) or (itscreen_running and itscreen_conflict_expected(port) and not lock)
+ status = "free"
+ if lock:
+ status = "locked by modbus tool"
+ elif busy_by_service:
+ status = "busy by service"
+ return {
+ "port": port,
+ "exists": os.path.exists(port),
+ "locked": bool(lock),
+ "lock_owner": (lock or {}).get("owner") or "",
+ "lock_meta": lock,
+ "busy_process": busy,
+ "busy_by_service": busy_by_service,
+ "itscreen_running": itscreen_running,
+ "status": status,
+ }
+
+
+def list_ports_payload() -> Dict[str, Any]:
+ ports = [port_status(port) for port in list_uart_ports()]
+ return {"ok": True, "ports": ports, "generated_at": utc_now_iso()}
+
+
+def append_audit(event: Dict[str, Any]) -> None:
+ ensure_runtime_dirs()
+ payload = dict(event)
+ payload.setdefault("timestamp", utc_now_iso())
+ with open(MODBUS_AUDIT_LOG, "a", encoding="utf-8") as fh:
+ fh.write(json.dumps(payload, ensure_ascii=True, sort_keys=True) + "\n")
+
+
+def read_audit(limit: int = 120) -> Dict[str, Any]:
+ try:
+ with open(MODBUS_AUDIT_LOG, "r", encoding="utf-8") as fh:
+ lines = fh.readlines()
+ except FileNotFoundError:
+ lines = []
+ rows = []
+ for line in lines[-max(1, int(limit)):]:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ rows.append(json.loads(line))
+ except Exception:
+ rows.append({"timestamp": utc_now_iso(), "message": line, "level": "info"})
+ return {"ok": True, "entries": rows}
+
+
+def validate_profile(data: Dict[str, Any], source_path: str) -> Dict[str, Any]:
+ if not isinstance(data, dict):
+ raise ApiError(f"Invalid profile format: {source_path}", 500)
+ family = str(data.get("family", "")).strip()
+ title = str(data.get("title", family)).strip()
+ display_name = str(data.get("display_name", title or family)).strip()
+ transport = data.get("transport") or {}
+ registers = data.get("registers") or {}
+ test_read = registers.get("test_read") or {}
+ if not family or not isinstance(transport, dict) or not isinstance(registers, dict):
+ raise ApiError(f"Invalid profile schema: {source_path}", 500)
+ if "address" not in test_read or "count" not in test_read or "type" not in test_read:
+ raise ApiError(f"Profile {family} is missing test_read register", 500)
+ profile = {
+ "family": family,
+ "title": title or family,
+ "display_name": display_name or title or family,
+ "transport": {
+ "protocol": str(transport.get("protocol", "modbus_rtu")),
+ "default_port": str(transport.get("default_port", "/dev/ttyS3")),
+ "default_baud": int(transport.get("default_baud", 9600)),
+ "default_parity": str(transport.get("default_parity", "none")),
+ "default_databits": int(transport.get("default_databits", 8)),
+ "default_stopbits": int(transport.get("default_stopbits", 1)),
+ "scan_baud": [int(item) for item in transport.get("scan_baud", [9600])],
+ "scan_parity": [str(item) for item in transport.get("scan_parity", ["none"])],
+ "zero_based": bool(transport.get("zero_based", True)),
+ },
+ "registers": registers,
+ "comm_profiles": data.get("comm_profiles") or [],
+ "capabilities": {
+ "supports_id_write": bool((registers.get("slave_id") or {}).get("rw")),
+ "supports_serial_write": bool(data.get("comm_profiles") or []),
+ },
+ "source_path": source_path,
+ }
+ return profile
+
+
+def load_profiles() -> List[Dict[str, Any]]:
+ profiles = []
+ for path in sorted(glob.glob(os.path.join(MODBUS_PROFILES_DIR, "*.json"))):
+ try:
+ with open(path, "r", encoding="utf-8") as fh:
+ loaded = json.load(fh)
+ profiles.append(validate_profile(loaded, path))
+ except ApiError:
+ raise
+ except Exception as exc:
+ raise ApiError(f"Failed to load profile {os.path.basename(path)}", 500, str(exc))
+ return profiles
+
+
+def profiles_payload() -> Dict[str, Any]:
+ profiles = load_profiles()
+ return {
+ "ok": True,
+ "profiles": [
+ {
+ "family": item["family"],
+ "title": item["title"],
+ "display_name": item["display_name"],
+ "transport": item["transport"],
+ "supports_serial_write": bool(item.get("capabilities", {}).get("supports_serial_write")),
+ "supports_id_write": bool(item.get("capabilities", {}).get("supports_id_write")),
+ }
+ for item in profiles
+ ],
+ }
+
+
+def get_profile(family: str) -> Dict[str, Any]:
+ family_name = str(family or "").strip()
+ for profile in load_profiles():
+ if profile["family"] == family_name:
+ return profile
+ raise ApiError("Unknown Modbus family", 404)
+
+
+def discovery_job_snapshot(job: Dict[str, Any]) -> Dict[str, Any]:
+ return {
+ "ok": True,
+ "job_id": job["job_id"],
+ "state": job["state"],
+ "message": job.get("message", ""),
+ "progress": dict(job.get("progress") or {}),
+ "devices": list(job.get("devices") or []),
+ "scan_log": list(job.get("scan_log") or []),
+ "started_at": job.get("started_at"),
+ "updated_at": job.get("updated_at"),
+ "completed_at": job.get("completed_at"),
+ "error": job.get("error", ""),
+ "family": job.get("family", ""),
+ "family_display_name": job.get("family_display_name", ""),
+ "port": job.get("port", ""),
+ "deep": bool(job.get("deep")),
+ }
+
+
+def update_discovery_job(job_id: str, **fields: Any) -> None:
+ with DISCOVERY_JOBS_LOCK:
+ job = DISCOVERY_JOBS.get(job_id)
+ if not job:
+ return
+ job.update(fields)
+ job["updated_at"] = utc_now_iso()
+
+
+def append_discovery_job_log(job_id: str, level: str, message: str, **extra: Any) -> None:
+ entry = {
+ "timestamp": utc_now_iso(),
+ "level": level,
+ "message": message,
+ }
+ if extra:
+ entry["meta"] = extra
+ with DISCOVERY_JOBS_LOCK:
+ job = DISCOVERY_JOBS.get(job_id)
+ if not job:
+ return
+ job.setdefault("scan_log", []).append(entry)
+ if len(job["scan_log"]) > 500:
+ job["scan_log"] = job["scan_log"][-500:]
+ job["updated_at"] = utc_now_iso()
+
+
+def get_discovery_job(job_id: str) -> Dict[str, Any]:
+ with DISCOVERY_JOBS_LOCK:
+ job = DISCOVERY_JOBS.get(str(job_id or "").strip())
+ if not job:
+ raise ApiError("Discovery job not found", 404)
+ return discovery_job_snapshot(job)
+
+
+def ensure_port_locked(port: str) -> Dict[str, Any]:
+ lock = read_lock(port)
+ if not lock:
+ raise ApiError("Acquire port before using Modbus operations", 409)
+ return lock
+
+
+def ensure_port_available(port: str, allow_itscreen_conflict: bool = False) -> Dict[str, Any]:
+ status = port_status(port)
+ if not status["exists"]:
+ raise ApiError("Port does not exist", 404)
+ if status["locked"]:
+ raise ApiError("Port is already locked by modbus tool", 409)
+ if status["busy_process"]:
+ raise ApiError("Port is busy by another process", 409, json.dumps(status["busy_process"]))
+ if status["itscreen_running"] and itscreen_conflict_expected(port) and not allow_itscreen_conflict:
+ raise ApiError("it-screen is running and may conflict with Modbus master access", 409)
+ return status
+
+
+def acquire_session(port: str, stop_itscreen: bool, source: str = "ui") -> Dict[str, Any]:
+ operations = []
+ status_before = port_status(port)
+ if not status_before["exists"]:
+ raise ApiError("Port does not exist", 404)
+ if status_before["locked"]:
+ raise ApiError("Port is already locked by modbus tool", 409)
+
+ itscreen_running = status_before["itscreen_running"]
+ stopped_itscreen = False
+ if stop_itscreen and itscreen_running:
+ operations.append({"level": "info", "message": "Stopping it-screen service before Modbus session"})
+ systemctl_control(ITSCREEN_SERVICE_UNIT, "stop")
+ stopped_itscreen = True
+ time.sleep(1.0)
+
+ try:
+ ensure_port_available(port, allow_itscreen_conflict=False)
+ lock = acquire_lock(port, {
+ "owner": "modbus_tool",
+ "source": source,
+ "stop_itscreen": bool(stop_itscreen),
+ "itscreen_was_running": bool(itscreen_running),
+ "itscreen_stopped": bool(stopped_itscreen),
+ })
+ except Exception:
+ if stopped_itscreen and itscreen_running:
+ try:
+ systemctl_control(ITSCREEN_SERVICE_UNIT, "start")
+ except Exception:
+ pass
+ raise
+
+ payload = {
+ "ok": True,
+ "message": "Port acquired",
+ "port": port,
+ "lock": lock,
+ "itscreen_running": itscreen_running,
+ "itscreen_stopped": stopped_itscreen,
+ "operation_log": operations + [{"level": "success", "message": "Port acquired and locked for Modbus tool"}],
+ }
+ append_audit({
+ "action": "session_acquire",
+ "port": port,
+ "stop_itscreen": bool(stop_itscreen),
+ "itscreen_running": bool(itscreen_running),
+ "itscreen_stopped": bool(stopped_itscreen),
+ "success": True,
+ "source": source,
+ })
+ return payload
+
+
+def release_session(port: str, restart_itscreen: bool, source: str = "ui") -> Dict[str, Any]:
+ lock = read_lock(port)
+ if not lock:
+ raise ApiError("Port is not locked by modbus tool", 409)
+ operations = [{"level": "info", "message": "Releasing Modbus port lock"}]
+ released = release_lock(port)
+ restarted = False
+ if restart_itscreen and bool((released or {}).get("itscreen_was_running")):
+ operations.append({"level": "info", "message": "Starting it-screen service after Modbus session"})
+ systemctl_control(ITSCREEN_SERVICE_UNIT, "start")
+ restarted = True
+ payload = {
+ "ok": True,
+ "message": "Port released",
+ "port": port,
+ "lock": released,
+ "itscreen_restarted": restarted,
+ "operation_log": operations + [{"level": "success", "message": "Port released"}],
+ }
+ append_audit({
+ "action": "session_release",
+ "port": port,
+ "restart_itscreen": bool(restart_itscreen),
+ "itscreen_restarted": bool(restarted),
+ "success": True,
+ "source": source,
+ })
+ return payload
+
+
+def decode_comm_profile(profile: Dict[str, Any], register_value: Optional[int]) -> Dict[str, Any]:
+ comm_profiles = profile.get("comm_profiles") or []
+ result = {
+ "decoded": False,
+ "register_value": register_value,
+ "baud": None,
+ "parity": None,
+ }
+ if register_value is None:
+ return result
+ for item in comm_profiles:
+ if int(item.get("register_value")) == int(register_value):
+ result.update({
+ "decoded": True,
+ "baud": int(item.get("baud")),
+ "parity": str(item.get("parity")),
+ })
+ return result
+ return result
+
+
+def encode_comm_profile(profile: Dict[str, Any], baud: int, parity: str) -> Optional[int]:
+ for item in profile.get("comm_profiles") or []:
+ if int(item.get("baud")) == int(baud) and str(item.get("parity")) == str(parity):
+ return int(item.get("register_value"))
+ return None
+
+
+def discover_devices(
+ *,
+ port: str,
+ family: str,
+ slave_range: List[int],
+ baud: int,
+ parity: str,
+ deep: bool = False,
+ source: str = "ui",
+ log_collector=None,
+) -> Dict[str, Any]:
+ ensure_port_locked(port)
+ profile = get_profile(family)
+ reg = profile["registers"]["test_read"]
+ start_slave = max(1, int(slave_range[0]))
+ end_slave = max(start_slave, int(slave_range[1]))
+ results = []
+ operations = [{
+ "level": "info",
+ "message": f"Scan started on {port} for {profile['display_name']} at {int(baud)} {str(parity)}",
+ }]
+ if log_collector:
+ log_collector("info", f"Selected port: {port}")
+ log_collector("info", f"Family: {profile['display_name']}")
+ log_collector("info", f"Slave range: {start_slave}..{end_slave}")
+ log_collector("info", f"Baud: {int(baud)}")
+ log_collector("info", f"Parity: {str(parity)}")
+ for slave in range(start_slave, end_slave + 1):
+ operations.append({
+ "level": "info",
+ "message": f"Checking slave {slave} at {int(baud)} {str(parity)}",
+ })
+ if log_collector:
+ log_collector("info", f"Checking slave {slave}", slave=slave, phase="check")
+ read_result = mbpoll_read(
+ port=port,
+ slave=slave,
+ address=int(reg["address"]),
+ count=int(reg["count"]),
+ baud=int(baud),
+ parity=str(parity),
+ register_type=str(reg["type"]),
+ data_bits=int(profile["transport"]["default_databits"]),
+ stop_bits=int(profile["transport"]["default_stopbits"]),
+ zero_based=bool(profile["transport"].get("zero_based", True)),
+ timeout=DEFAULT_DISCOVER_TIMEOUT + (1.0 if deep else 0.0),
+ retries=1 if deep else 0,
+ )
+ if not read_result["ok"]:
+ error_type = read_result.get("error_type") or "no_response"
+ friendly = {
+ "timeout": "no response",
+ "crc_error": "CRC error",
+ "port_busy": "port busy",
+ "modbus_exception": "Modbus exception",
+ }.get(error_type, error_type.replace("_", " "))
+ if log_collector:
+ log_collector("warn", f"Slave {slave}: {friendly}", slave=slave, result=friendly)
+ continue
+ first_value = read_result["values"][0] if read_result["values"] else {}
+ found = {
+ "port": port,
+ "family": family,
+ "family_display_name": profile["display_name"],
+ "slave": slave,
+ "baud": int(baud),
+ "parity": str(parity),
+ "test_register": {
+ "address": int(reg["address"]),
+ "count": int(reg["count"]),
+ "type": str(reg["type"]),
+ "value": first_value.get("value"),
+ },
+ "status": "ok",
+ "confidence": "high",
+ "action": "Select",
+ }
+ results.append(found)
+ if log_collector:
+ log_collector("success", f"Found device at slave {slave}", slave=slave, baud=int(baud), parity=str(parity), result="found")
+ append_audit({
+ "action": "discover",
+ "port": port,
+ "family": family,
+ "slave_range": [start_slave, end_slave],
+ "baud": int(baud),
+ "parity": str(parity),
+ "deep": bool(deep),
+ "result_count": len(results),
+ "success": True,
+ "source": source,
+ })
+ return {
+ "ok": True,
+ "message": "Discovery completed",
+ "port": port,
+ "family": family,
+ "family_display_name": profile["display_name"],
+ "devices": results,
+ "operation_log": operations[-60:],
+ "deep": bool(deep),
+ }
+
+
+def start_discovery(
+ *,
+ port: str,
+ family: str,
+ slave_range: List[int],
+ baud: int,
+ parity: str,
+ deep: bool = False,
+ source: str = "ui",
+) -> Dict[str, Any]:
+ ensure_port_locked(port)
+ profile = get_profile(family)
+ job_id = uuid.uuid4().hex
+ start_slave = max(1, int(slave_range[0]))
+ end_slave = max(start_slave, int(slave_range[1]))
+ job = {
+ "job_id": job_id,
+ "state": "running",
+ "message": "Scanning in progress. It may take some minutes.",
+ "port": port,
+ "family": family,
+ "family_display_name": profile["display_name"],
+ "deep": bool(deep),
+ "devices": [],
+ "scan_log": [],
+ "error": "",
+ "progress": {
+ "current_slave": None,
+ "checked": 0,
+ "total": end_slave - start_slave + 1,
+ "baud": int(baud),
+ "parity": str(parity),
+ "slave_range": [start_slave, end_slave],
+ },
+ "started_at": utc_now_iso(),
+ "updated_at": utc_now_iso(),
+ "completed_at": "",
+ }
+ with DISCOVERY_JOBS_LOCK:
+ DISCOVERY_JOBS[job_id] = job
+
+ def log(level: str, message: str, **meta: Any) -> None:
+ if "slave" in meta:
+ with DISCOVERY_JOBS_LOCK:
+ job_ref = DISCOVERY_JOBS.get(job_id)
+ if job_ref:
+ checked = int(job_ref.get("progress", {}).get("checked", 0))
+ if meta.get("phase") == "check":
+ job_ref["progress"]["current_slave"] = int(meta["slave"])
+ else:
+ job_ref["progress"]["checked"] = max(checked, int(meta["slave"]) - start_slave + 1)
+ job_ref["updated_at"] = utc_now_iso()
+ append_discovery_job_log(job_id, level, message, **meta)
+
+ def worker() -> None:
+ try:
+ result = discover_devices(
+ port=port,
+ family=family,
+ slave_range=[start_slave, end_slave],
+ baud=int(baud),
+ parity=str(parity),
+ deep=bool(deep),
+ source=source,
+ log_collector=log,
+ )
+ update_discovery_job(
+ job_id,
+ state="completed",
+ message="Scan completed",
+ devices=result.get("devices", []),
+ progress={
+ "current_slave": end_slave,
+ "checked": end_slave - start_slave + 1,
+ "total": end_slave - start_slave + 1,
+ "baud": int(baud),
+ "parity": str(parity),
+ "slave_range": [start_slave, end_slave],
+ },
+ completed_at=utc_now_iso(),
+ )
+ append_discovery_job_log(job_id, "success", f"Scan completed. Found {len(result.get('devices', []))} device(s).")
+ except Exception as exc:
+ update_discovery_job(
+ job_id,
+ state="failed",
+ message="Scan failed",
+ error=str(exc),
+ completed_at=utc_now_iso(),
+ )
+ append_discovery_job_log(job_id, "error", f"Scan failed: {exc}")
+
+ thread = threading.Thread(target=worker, name=f"modbus-discovery-{job_id}", daemon=True)
+ thread.start()
+ return discovery_job_snapshot(job)
+
+
+def read_device_config(
+ *,
+ port: str,
+ family: str,
+ slave: int,
+ baud: int,
+ parity: str,
+ source: str = "ui",
+) -> Dict[str, Any]:
+ ensure_port_locked(port)
+ operations = [{"level": "info", "message": "Reading current device configuration"}]
+ probe = device_probe(
+ port=port,
+ family=family,
+ slave=int(slave),
+ baud=int(baud),
+ parity=str(parity),
+ timeout=DEFAULT_DISCOVER_TIMEOUT,
+ retries=1,
+ )
+ if not probe["ok"]:
+ raise ApiError("Failed to read current device configuration", 502, json.dumps(probe["debug"]))
+
+ payload = {
+ "ok": True,
+ "status": "ok",
+ "family": family,
+ "port": port,
+ "current": probe["current"],
+ "current_config": probe["current_config"],
+ "raw_values": probe["raw_values"],
+ "test_register": probe["test_register"],
+ "last_successful_read": utc_now_iso(),
+ "last_communication_timestamp": utc_now_iso(),
+ "operation_log": operations + [{"level": "success", "message": "Configuration read completed"}],
+ "debug": probe["debug"],
+ }
+ append_audit({
+ "action": "read_config",
+ "port": port,
+ "family": family,
+ "slave": int(slave),
+ "baud": int(baud),
+ "parity": str(parity),
+ "success": True,
+ "source": source,
+ })
+ return payload
+
+
+def rediscover_after_write(
+ *,
+ port: str,
+ family: str,
+ target_slave: int,
+ target_baud: int,
+ target_parity: str,
+) -> Dict[str, Any]:
+ profile = get_profile(family)
+ same_serial = discover_devices(
+ port=port,
+ family=family,
+ slave_range=[1, 10],
+ baud=target_baud,
+ parity=target_parity,
+ deep=False,
+ source="rediscovery",
+ )
+ same_devices = same_serial.get("devices", [])
+ exact_target = next((item for item in same_devices if item["slave"] == target_slave and item["baud"] == target_baud and item["parity"] == target_parity), None)
+ if exact_target:
+ return {
+ "found": True,
+ "target_verified": True,
+ "classification": "verified_target",
+ "mode": "same_serial",
+ "device": exact_target,
+ "devices": same_devices,
+ "recommended_next_step": "Configuration applied and rediscovered successfully",
+ "operation_log": [{"level": "success", "message": "Device found with new communication profile"}],
+ }
+ same_elsewhere = same_devices[0] if same_devices else None
+ if same_elsewhere:
+ return {
+ "found": True,
+ "target_verified": False,
+ "classification": "found_elsewhere",
+ "mode": "same_serial",
+ "device": same_elsewhere,
+ "devices": same_devices,
+ "recommended_next_step": f"Rediscovery found device at slave {same_elsewhere['slave']} with the current serial profile",
+ "operation_log": [{"level": "warn", "message": f"Rediscovery found device at slave {same_elsewhere['slave']} instead of requested target"}],
+ }
+
+ transport = profile["transport"]
+ deep_devices = []
+ for scan_baud in [int(item) for item in transport.get("scan_baud", [target_baud])]:
+ for scan_parity in [str(item) for item in transport.get("scan_parity", [target_parity])]:
+ deep = discover_devices(
+ port=port,
+ family=family,
+ slave_range=[1, 10],
+ baud=scan_baud,
+ parity=scan_parity,
+ deep=True,
+ source="rediscovery",
+ )
+ deep_devices.extend(deep.get("devices", []))
+ for item in deep_devices:
+ if item["slave"] == target_slave:
+ return {
+ "found": True,
+ "target_verified": True,
+ "classification": "verified_target",
+ "mode": "deep",
+ "device": item,
+ "devices": deep_devices,
+ "recommended_next_step": "Device found after deep scan",
+ "operation_log": [{"level": "warn", "message": "Device found after deep scan"}],
+ }
+ if deep_devices:
+ found_elsewhere = deep_devices[0]
+ return {
+ "found": True,
+ "target_verified": False,
+ "classification": "found_elsewhere",
+ "mode": "deep",
+ "device": found_elsewhere,
+ "devices": deep_devices,
+ "recommended_next_step": f"Rediscovery found device at slave {found_elsewhere['slave']} with a different profile",
+ "operation_log": [{"level": "warn", "message": f"Rediscovery found device at slave {found_elsewhere['slave']} with a different profile"}],
+ }
+ return {
+ "found": False,
+ "target_verified": False,
+ "classification": "write_unconfirmed",
+ "mode": "deep",
+ "device": None,
+ "devices": [],
+ "recommended_next_step": "Device not found after write; deep scan recommended",
+ "operation_log": [{"level": "warn", "message": "Device not found after write; deep scan recommended"}],
+ }
+
+
+def write_device_config(
+ *,
+ port: str,
+ family: str,
+ baudrate: int = 9600,
+ current: Dict[str, Any],
+ target: Dict[str, Any],
+ strategy: str,
+ source: str = "ui",
+) -> Dict[str, Any]:
+ ensure_port_locked(port)
+ profile = get_profile(family)
+ transport = profile["transport"]
+ registers = profile["registers"]
+ strategy_value = str(strategy or "both").strip().lower()
+ if strategy_value not in ("id_only", "serial_only", "both"):
+ raise ApiError("Invalid apply strategy", 400)
+
+ current_slave = int(current.get("slave"))
+ write_baud = int(baudrate or current.get("baud") or 9600)
+ current_baud = int(current.get("baud") or write_baud)
+ current_parity = str(current.get("parity"))
+ target_slave = int(target.get("slave"))
+ target_baud = int(target.get("baud"))
+ target_parity = str(target.get("parity"))
+
+ precheck = device_probe(
+ port=port,
+ family=family,
+ slave=int(current_slave),
+ baud=int(write_baud),
+ parity=str(current_parity),
+ timeout=DEFAULT_DISCOVER_TIMEOUT,
+ retries=1,
+ )
+ operations = [{"level": "info", "message": "Pre-check started before write"}]
+ if not precheck["ok"]:
+ payload = {
+ "ok": False,
+ "stage": "precheck",
+ "status": "precheck_failed",
+ "message": "Current device could not be verified before write",
+ "write_baudrate": int(write_baud),
+ "current_requested": current,
+ "target_requested": target,
+ "write_sent": False,
+ "target_verified": False,
+ "rediscovery_attempted": False,
+ "rediscovery_found": False,
+ "final_detected_config": None,
+ "recommended_next_step": "Verify current slave communication before writing",
+ "operation_log": operations + [{"level": "error", "message": "Pre-check failed; write not started"}],
+ "debug": {"precheck": precheck["debug"]},
+ }
+ append_audit({
+ "action": "write_config",
+ "port": port,
+ "family": family,
+ "current": current,
+ "target": target,
+ "strategy": strategy_value,
+ "status": "precheck_failed",
+ "success": False,
+ "source": source,
+ })
+ return payload
+ operations.append({"level": "success", "message": "Pre-check passed; current device communication is confirmed"})
+
+ id_changed = target_slave != int(precheck["current_config"]["slave_id"])
+ serial_changed = target_baud != current_baud or target_parity != current_parity
+
+ if strategy_value == "id_only":
+ serial_changed = False
+ elif strategy_value == "serial_only":
+ id_changed = False
+
+ if not id_changed and not serial_changed:
+ return {
+ "ok": True,
+ "message": "No configuration changes requested",
+ "write_baudrate": int(write_baud),
+ "current_requested": current,
+ "target_requested": target,
+ "write_done": False,
+ "rediscovery_attempted": False,
+ "found": True,
+ "final_detected_config": precheck["current"],
+ "operation_log": operations + [{"level": "info", "message": "Target config matches current config"}],
+ "debug": {"precheck": precheck["debug"]},
+ }
+
+ if id_changed and not profile.get("capabilities", {}).get("supports_id_write"):
+ raise ApiError("Slave ID write is not configured for this family", 400)
+
+ if serial_changed and not profile.get("comm_profiles"):
+ raise ApiError(
+ "Serial profile write is not configured for this family; complete comm_profiles mapping or use register explorer",
+ 400,
+ )
+
+ write_debug: Dict[str, Any] = {"precheck": precheck["debug"]}
+ write_sent = False
+ if id_changed:
+ write_id = mbpoll_write_register(
+ port=port,
+ slave=current_slave,
+ address=int(registers["slave_id"]["address"]),
+ value=target_slave,
+ baud=write_baud,
+ parity=current_parity,
+ data_bits=int(transport["default_databits"]),
+ stop_bits=int(transport["default_stopbits"]),
+ zero_based=bool(transport.get("zero_based", True)),
+ )
+ write_debug["slave_id_write"] = write_id
+ write_sent = bool(write_id.get("write_sent"))
+ if not write_id["ok"]:
+ payload = {
+ "ok": False,
+ "stage": "write",
+ "status": "write_failed",
+ "message": "Slave ID write command failed",
+ "write_baudrate": int(write_baud),
+ "current_requested": current,
+ "target_requested": target,
+ "write_sent": write_sent,
+ "target_verified": False,
+ "rediscovery_attempted": False,
+ "rediscovery_found": False,
+ "final_detected_config": None,
+ "recommended_next_step": "Check write command debug and device communication state",
+ "operation_log": operations + [{"level": "error", "message": "Slave ID write command failed"}],
+ "debug": write_debug,
+ }
+ append_audit({
+ "action": "write_config",
+ "port": port,
+ "family": family,
+ "current": current,
+ "target": target,
+ "strategy": strategy_value,
+ "status": "write_failed",
+ "success": False,
+ "debug": {"slave_id_write": write_id},
+ "source": source,
+ })
+ return payload
+ operations.append({"level": "success", "message": "Slave ID write command completed"})
+ time.sleep(0.8)
+
+ if serial_changed:
+ comm_value = encode_comm_profile(profile, target_baud, target_parity)
+ if comm_value is None:
+ raise ApiError("Requested baud/parity is not supported by profile mapping", 400)
+ write_comm = mbpoll_write_register(
+ port=port,
+ slave=target_slave if id_changed else current_slave,
+ address=int(registers["comm_profile"]["address"]),
+ value=comm_value,
+ baud=write_baud,
+ parity=current_parity,
+ data_bits=int(transport["default_databits"]),
+ stop_bits=int(transport["default_stopbits"]),
+ zero_based=bool(transport.get("zero_based", True)),
+ )
+ write_debug["comm_profile_write"] = write_comm
+ write_sent = write_sent or bool(write_comm.get("write_sent"))
+ if not write_comm["ok"]:
+ payload = {
+ "ok": False,
+ "stage": "write",
+ "status": "write_failed",
+ "message": "Communication profile write command failed",
+ "write_baudrate": int(write_baud),
+ "current_requested": current,
+ "target_requested": target,
+ "write_sent": write_sent,
+ "target_verified": False,
+ "rediscovery_attempted": False,
+ "rediscovery_found": False,
+ "final_detected_config": None,
+ "recommended_next_step": "Check write command debug and serial profile mapping",
+ "operation_log": operations + [{"level": "error", "message": "Communication profile write command failed"}],
+ "debug": write_debug,
+ }
+ append_audit({
+ "action": "write_config",
+ "port": port,
+ "family": family,
+ "current": current,
+ "target": target,
+ "strategy": strategy_value,
+ "status": "write_failed",
+ "success": False,
+ "debug": {"comm_profile_write": write_comm},
+ "source": source,
+ })
+ return payload
+ operations.append({"level": "success", "message": "Communication profile write command completed"})
+ time.sleep(1.5)
+
+ immediate_verify = device_probe(
+ port=port,
+ family=family,
+ slave=int(target_slave),
+ baud=int(target_baud),
+ parity=str(target_parity),
+ timeout=DEFAULT_DISCOVER_TIMEOUT,
+ retries=0,
+ )
+ write_debug["immediate_target_verify"] = immediate_verify["debug"]
+ if immediate_verify["ok"]:
+ final_detected = {
+ "slave": immediate_verify["current"]["slave"],
+ "baud": immediate_verify["current"]["baud"],
+ "parity": immediate_verify["current"]["parity"],
+ }
+ payload = {
+ "ok": True,
+ "stage": "post_write_validation",
+ "status": "verified_target",
+ "message": f"Write verified. Device is now reachable at slave {final_detected['slave']}",
+ "write_baudrate": int(write_baud),
+ "current_requested": current,
+ "target_requested": target,
+ "write_sent": True,
+ "target_verified": True,
+ "rediscovery_attempted": False,
+ "rediscovery_found": True,
+ "found": True,
+ "final_detected_config": final_detected,
+ "recommended_next_step": f"Write verified. Device is now reachable at slave {final_detected['slave']}",
+ "operation_log": operations + [{"level": "success", "message": f"Immediate verification succeeded on target slave {final_detected['slave']}"}],
+ "debug": write_debug,
+ }
+ append_audit({
+ "action": "write_config",
+ "port": port,
+ "family": family,
+ "current": current,
+ "target": target,
+ "strategy": strategy_value,
+ "status": "verified_target",
+ "success": True,
+ "final_detected_config": final_detected,
+ "source": source,
+ })
+ return payload
+
+ operations.append({"level": "warn", "message": "Immediate target verification failed; rediscovery in progress"})
+ rediscovery = rediscover_after_write(
+ port=port,
+ family=family,
+ target_slave=target_slave,
+ target_baud=target_baud,
+ target_parity=target_parity,
+ )
+ final_detected = None
+ if rediscovery.get("found") and rediscovery.get("device"):
+ final_detected = {
+ "slave": rediscovery["device"]["slave"],
+ "baud": rediscovery["device"]["baud"],
+ "parity": rediscovery["device"]["parity"],
+ }
+ write_debug["rediscovery"] = rediscovery
+
+ status = str(rediscovery.get("classification") or "write_unconfirmed")
+ ok = bool(rediscovery.get("target_verified"))
+ message = ""
+ if status == "verified_target" and final_detected:
+ message = f"Write verified. Device is now reachable at slave {final_detected['slave']}"
+ elif status == "found_elsewhere" and final_detected:
+ message = f"Rediscovery found device at a different address: slave {final_detected['slave']}"
+ else:
+ message = "Write command was sent, but target slave was not confirmed after rediscovery"
+ payload = {
+ "ok": ok,
+ "stage": "post_write_validation",
+ "status": status,
+ "message": message,
+ "write_baudrate": int(write_baud),
+ "current_requested": current,
+ "target_requested": target,
+ "write_done": True,
+ "write_sent": True,
+ "target_verified": bool(rediscovery.get("target_verified")),
+ "rediscovery_attempted": True,
+ "rediscovery_found": bool(rediscovery.get("found")),
+ "found": bool(rediscovery.get("found")),
+ "final_detected_config": final_detected,
+ "recommended_next_step": rediscovery.get("recommended_next_step"),
+ "operation_log": operations + rediscovery.get("operation_log", []),
+ "debug": write_debug,
+ }
+ append_audit({
+ "action": "write_config",
+ "port": port,
+ "family": family,
+ "current": current,
+ "target": target,
+ "write_baudrate": int(write_baud),
+ "strategy": strategy_value,
+ "status": status,
+ "write_sent": True,
+ "target_verified": bool(rediscovery.get("target_verified")),
+ "found": bool(rediscovery.get("found")),
+ "final_detected_config": final_detected,
+ "success": ok,
+ "source": source,
+ })
+ return payload
+
+
+def read_registers(
+ *,
+ port: str,
+ family: str,
+ slave: int,
+ baud: int,
+ parity: str,
+ address: int,
+ count: int,
+ register_type: str,
+ decode_mode: str,
+ source: str = "ui",
+) -> Dict[str, Any]:
+ ensure_port_locked(port)
+ profile = get_profile(family)
+ result = mbpoll_read(
+ port=port,
+ slave=int(slave),
+ address=int(address),
+ count=int(count),
+ baud=int(baud),
+ parity=str(parity),
+ register_type=str(register_type),
+ data_bits=int(profile["transport"]["default_databits"]),
+ stop_bits=int(profile["transport"]["default_stopbits"]),
+ zero_based=bool(profile["transport"].get("zero_based", True)),
+ decode_mode=str(decode_mode or "uint16"),
+ retries=1,
+ )
+ if not result["ok"]:
+ raise ApiError("Register read failed", 502, json.dumps(result))
+ append_audit({
+ "action": "register_read",
+ "port": port,
+ "family": family,
+ "slave": int(slave),
+ "address": int(address),
+ "count": int(count),
+ "register_type": register_type,
+ "success": True,
+ "source": source,
+ })
+ return {
+ "ok": True,
+ "values": result["values"],
+ "stdout_lines": result["stdout_lines"],
+ "stderr_lines": result["stderr_lines"],
+ "operation_log": [{"level": "success", "message": "Register read completed"}],
+ }
+
+
+def write_register(
+ *,
+ port: str,
+ family: str,
+ slave: int,
+ baud: int,
+ parity: str,
+ address: int,
+ value: int,
+ source: str = "ui",
+) -> Dict[str, Any]:
+ ensure_port_locked(port)
+ profile = get_profile(family)
+ result = mbpoll_write_register(
+ port=port,
+ slave=int(slave),
+ address=int(address),
+ value=int(value),
+ baud=int(baud),
+ parity=str(parity),
+ data_bits=int(profile["transport"]["default_databits"]),
+ stop_bits=int(profile["transport"]["default_stopbits"]),
+ zero_based=bool(profile["transport"].get("zero_based", True)),
+ )
+ if not result["ok"]:
+ raise ApiError("Register write failed", 502, json.dumps(result))
+ append_audit({
+ "action": "register_write",
+ "port": port,
+ "family": family,
+ "slave": int(slave),
+ "address": int(address),
+ "value": int(value),
+ "success": True,
+ "source": source,
+ })
+ return {
+ "ok": True,
+ "message": "Register write completed",
+ "debug": result,
+ "stdout_lines": result["stdout_lines"],
+ "stderr_lines": result["stderr_lines"],
+ "operation_log": [{"level": "success", "message": "Register write completed"}],
+ }
diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css
index 1c196a5..11795f2 100644
--- a/stage_ui/console_core/frontend/console.css
+++ b/stage_ui/console_core/frontend/console.css
@@ -906,6 +906,169 @@ html[dir="rtl"] .itscreenLogsActions{
.logEmpty{
color:var(--log-empty);
}
+.checkboxRow{
+ display:flex;
+ align-items:flex-start;
+ gap:10px;
+ font-size:14px;
+ color:var(--muted);
+}
+.checkboxRow input{margin-top:3px}
+.modbusGrid{
+ display:grid;
+ grid-template-columns:repeat(2,minmax(0,1fr));
+ gap:14px;
+ align-items:start;
+}
+.modbusDiscoveryGrid{
+ grid-template-columns:repeat(2,minmax(220px,1fr));
+ row-gap:16px;
+}
+.modbusTableWrap{
+ overflow:auto;
+ border:1px solid var(--line);
+ border-radius:14px;
+}
+.modbusTable{
+ width:100%;
+ border-collapse:collapse;
+ font-size:14px;
+}
+.modbusTable th,
+.modbusTable td{
+ padding:10px 12px;
+ border-bottom:1px solid var(--line);
+ text-align:left;
+ vertical-align:top;
+}
+.modbusTable th{
+ font-size:12px;
+ text-transform:uppercase;
+ letter-spacing:.08em;
+ color:var(--muted);
+ background:rgba(255,255,255,.03);
+}
+.modbusTable tr.is-selected{
+ background:rgba(47,154,111,.1);
+}
+.compactActionRow{
+ gap:8px;
+ flex-wrap:wrap;
+}
+.compactBtn{
+ padding:8px 10px;
+ min-height:auto;
+ font-size:12px;
+}
+.statusBadge{
+ display:inline-flex;
+ align-items:center;
+ padding:4px 10px;
+ border-radius:999px;
+ font-size:12px;
+ font-weight:700;
+ text-transform:uppercase;
+ letter-spacing:.04em;
+ background:rgba(255,255,255,.06);
+}
+.statusBadge.is-ok{
+ background:rgba(14,122,83,.12);
+ color:var(--accent);
+}
+.modbusLogPanel{
+ display:grid;
+ gap:10px;
+ max-height:320px;
+ overflow:auto;
+ padding-right:4px;
+}
+.modbusLogEntry{
+ display:grid;
+ gap:4px;
+ padding:10px 12px;
+ border:1px solid var(--line);
+ border-radius:12px;
+ background:rgba(255,255,255,.03);
+}
+.modbusLogEntry.is-success{border-color:rgba(47,154,111,.4)}
+.modbusLogEntry.is-warn{border-color:rgba(224,176,72,.4)}
+.modbusLogEntry.is-error{border-color:rgba(196,78,82,.5)}
+.modbusLogTime{
+ font-size:12px;
+ color:var(--muted);
+}
+.modbusLogMessage{
+ font-size:14px;
+ line-height:1.45;
+}
+.modbusScanActions{
+ align-items:center;
+ margin-top:16px;
+}
+.modbusScanLogBody{
+ min-height:180px;
+ max-height:280px;
+ overflow:auto;
+ padding:12px 14px;
+ border:1px solid var(--line);
+ border-radius:14px;
+ background:var(--log-bg);
+ color:var(--log-ink);
+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
+ font-size:12px;
+ line-height:1.5;
+}
+.scanLogCard{
+ margin-top:16px;
+}
+.advancedSection{
+ display:grid;
+ gap:12px;
+ margin-bottom:18px;
+}
+.technicalDetails{
+ margin-top:12px;
+}
+.technicalDetails summary{
+ cursor:pointer;
+ color:var(--muted);
+ font-size:13px;
+}
+.technicalDetails .diagBlock{
+ margin-top:10px;
+ max-height:260px;
+}
+.modbusSummaryMeta{
+ margin-top:12px;
+}
+.writeConfigSection{
+ display:grid;
+ gap:12px;
+ margin-top:14px;
+}
+.sectionTitle{
+ font-size:13px;
+ font-weight:700;
+ color:var(--muted);
+ letter-spacing:.04em;
+ text-transform:uppercase;
+}
+.writeLogCard{
+ margin-top:14px;
+}
+.modbusWriteLogBody{
+ min-height:160px;
+ max-height:160px;
+ overflow-y:auto;
+ padding:12px 14px;
+ border:1px solid var(--line);
+ border-radius:14px;
+ background:var(--log-bg);
+ color:var(--log-ink);
+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
+ font-size:12px;
+ line-height:1.5;
+}
@keyframes pulse{
0%,100%{opacity:.35;transform:scale(.9)}
50%{opacity:1;transform:scale(1)}
@@ -930,6 +1093,8 @@ html[dir="rtl"] .itscreenLogsActions{
.itscreenCards{grid-template-columns:1fr}
.itscreenLogsToolbar{grid-template-columns:1fr}
.itscreenLogsActions{justify-content:flex-start}
+ .modbusGrid{grid-template-columns:1fr}
+ .modbusDiscoveryGrid{grid-template-columns:1fr}
}
@media (max-width:680px){
.menuToggleBtn{
@@ -956,4 +1121,8 @@ html[dir="rtl"] .itscreenLogsActions{
}
.tunnelTableHead{display:none}
.tunnelCompactRow{padding:9px 0}
+ .modbusTable th,
+ .modbusTable td{
+ min-width:120px;
+ }
}
diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js
index 9c91dd1..8d07def 100644
--- a/stage_ui/console_core/frontend/console.js
+++ b/stage_ui/console_core/frontend/console.js
@@ -23,6 +23,7 @@
rebootMenuLabel: document.getElementById("rebootMenuLabel"),
tabHealth: document.getElementById("tabHealth"),
tabNetwork: document.getElementById("tabNetwork"),
+ tabModbus: document.getElementById("tabModbus"),
tabTscreen: document.getElementById("tabTscreen"),
tabGbox: document.getElementById("tabGbox"),
edgeId: document.getElementById("edgeId"),
@@ -176,6 +177,57 @@
}
},
scan: { ok: true, networks: [], error: "", warning: "", message: "", loading: false, scannedAt: "", expanded: false, lastTriggeredAt: 0 },
+ modbus: {
+ loading: false,
+ ports: [],
+ profiles: [],
+ audit: [],
+ error: "",
+ loadedAt: 0,
+ request: null,
+ operationLog: [],
+ busyAction: "",
+ stopItscreen: true,
+ restartItscreen: true,
+ port: "/dev/ttyS3",
+ family: "ultrasonic_water_meter",
+ mode: "simple",
+ advancedOpen: false,
+ session: null,
+ discovery: {
+ slaveFrom: "1",
+ slaveTo: "10",
+ baud: "9600",
+ parity: "none",
+ devices: [],
+ lastMode: "quick",
+ jobId: "",
+ state: "idle",
+ message: "",
+ scanLog: [],
+ checked: 0,
+ total: 0,
+ currentSlave: null
+ },
+ selectedDevice: null,
+ currentConfig: null,
+ lastWriteResult: null,
+ writeLog: [],
+ writeForm: {
+ slave: "",
+ baud: "9600",
+ parity: "none",
+ strategy: "both"
+ },
+ registerForm: {
+ address: "0",
+ count: "1",
+ registerType: "holding",
+ decodeMode: "uint16",
+ value: "",
+ lastResult: null
+ }
+ },
networkForm: {
ssid: "",
password: "",
@@ -388,6 +440,7 @@
if (nodes.rebootMenuLabel) nodes.rebootMenuLabel.textContent = t("Reboot");
if (nodes.tabHealth) nodes.tabHealth.textContent = t("Health");
if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network");
+ if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus");
if (nodes.tabTscreen) nodes.tabTscreen.textContent = t("It-Screen");
if (nodes.tabGbox) nodes.tabGbox.textContent = t("G-Box Instructions and Manual");
const nav = document.querySelector(".tabs");
@@ -2211,6 +2264,481 @@
}
}
+ function modbusState() {
+ return state.modbus;
+ }
+
+ function modbusOperationLogEntries(payload) {
+ const entries = Array.isArray(payload && payload.operation_log) ? payload.operation_log : [];
+ return entries.map((item) => ({
+ timestamp: new Date().toISOString(),
+ level: textValue(item.level, "info"),
+ message: textValue(item.message, "")
+ })).filter((item) => item.message);
+ }
+
+ function appendModbusLog(message, level = "info") {
+ if (!message) return;
+ const log = modbusState();
+ log.operationLog = [{ timestamp: new Date().toISOString(), level, message }].concat(log.operationLog || []).slice(0, 160);
+ }
+
+ function ingestModbusPayload(payload) {
+ const log = modbusState();
+ const entries = modbusOperationLogEntries(payload);
+ if (entries.length) {
+ log.operationLog = entries.concat(log.operationLog || []).slice(0, 160);
+ }
+ }
+
+ function parseIntCsv(value, fallback) {
+ const items = String(value || "").split(",").map((item) => Number(String(item).trim())).filter((item) => Number.isFinite(item) && item > 0);
+ return items.length ? items : fallback;
+ }
+
+ function parseTextCsv(value, fallback) {
+ const items = String(value || "").split(",").map((item) => String(item).trim().toLowerCase()).filter(Boolean);
+ return items.length ? items : fallback;
+ }
+
+ function modbusSelectedProfile() {
+ return (modbusState().profiles || []).find((item) => item.family === modbusState().family) || null;
+ }
+
+ function modbusSelectedPortStatus() {
+ return (modbusState().ports || []).find((item) => item.port === modbusState().port) || null;
+ }
+
+ function modbusCanWrite() {
+ const log = modbusState();
+ const currentConfig = log.currentConfig && log.currentConfig.current_config;
+ const supportsIdWrite = !!(currentConfig && currentConfig.supports_id_write);
+ const supportsSerialWrite = !!(currentConfig && currentConfig.supports_serial_write);
+ return !!(log.currentConfig && log.selectedDevice && (supportsIdWrite || supportsSerialWrite));
+ }
+
+ function modbusBusy(action) {
+ return modbusState().busyAction === action;
+ }
+
+ function modbusCurrentConnection() {
+ const log = modbusState();
+ if (log.currentConfig && log.currentConfig.current) return log.currentConfig.current;
+ if (log.selectedDevice) {
+ return {
+ slave: log.selectedDevice.slave,
+ baud: log.selectedDevice.baud,
+ parity: log.selectedDevice.parity
+ };
+ }
+ const profile = modbusSelectedProfile();
+ return {
+ slave: 1,
+ baud: Number(profile && profile.transport && profile.transport.default_baud) || 9600,
+ parity: textValue(profile && profile.transport && profile.transport.default_parity, "none")
+ };
+ }
+
+ function syncModbusWriteFormFromConfig() {
+ const log = modbusState();
+ const current = modbusCurrentConnection();
+ if (!log.writeForm.slave) log.writeForm.slave = String(current.slave || "");
+ if (!log.writeForm.baud) log.writeForm.baud = String(current.baud || "9600");
+ if (!log.writeForm.parity) log.writeForm.parity = textValue(current.parity, "none");
+ }
+
+ function modbusWriteCurrentConfigView() {
+ const log = modbusState();
+ const current = modbusCurrentConnection();
+ const currentConfig = log.currentConfig || {};
+ const currentMeta = currentConfig.current_config || {};
+ return {
+ slave: textValue(currentMeta.slave_id, textValue(current.slave, "-")),
+ baud: textValue(currentMeta.baud, textValue(current.baud, t("Unknown"))),
+ parity: textValue(currentMeta.parity, textValue(current.parity, t("Unknown"))),
+ status: textValue(log.lastWriteResult && log.lastWriteResult.status, textValue(currentConfig.status, "-"))
+ };
+ }
+
+ function modbusScanRunning() {
+ return modbusBusy("scan_quick") || modbusBusy("scan_deep");
+ }
+
+ function modbusDiscoveryLogLines() {
+ const entries = Array.isArray(modbusState().discovery.scanLog) ? modbusState().discovery.scanLog : [];
+ return entries.map((entry) => `[${formatUtc(entry.timestamp)}] ${entry.message}`);
+ }
+
+ function appendModbusWriteLog(message, level = "info") {
+ if (!message) return;
+ const log = modbusState();
+ log.writeLog = (log.writeLog || []).concat([{ timestamp: new Date().toISOString(), level, message }]).slice(-160);
+ }
+
+ function ingestModbusWritePayload(payload) {
+ const entries = Array.isArray(payload && payload.operation_log) ? payload.operation_log : [];
+ if (!entries.length) return;
+ const log = modbusState();
+ const mapped = entries.map((item) => ({
+ timestamp: new Date().toISOString(),
+ level: textValue(item.level, "info"),
+ message: textValue(item.message, "")
+ })).filter((item) => item.message);
+ log.writeLog = (log.writeLog || []).concat(mapped).slice(-160);
+ }
+
+ function scrollModbusWriteLogToBottom() {
+ window.requestAnimationFrame(() => {
+ const node = document.getElementById("modbusWriteLogBody");
+ if (node) node.scrollTop = node.scrollHeight;
+ });
+ }
+
+ async function modbusEnsureSession() {
+ const log = modbusState();
+ const portInfo = modbusSelectedPortStatus() || {};
+ if (log.session || portInfo.locked) {
+ return true;
+ }
+ const payload = await fetchJson("/api/modbus/session/acquire", {
+ method: "POST",
+ cache: "no-store",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ port: log.port, stop_itscreen: !!log.stopItscreen })
+ });
+ log.session = payload.lock || null;
+ ingestModbusPayload(payload);
+ appendModbusLog(payload.message || t("Port acquired"), "success");
+ await loadModbus({ force: true, maxAgeMs: 0 });
+ return true;
+ }
+
+ function renderModbusLogPanel() {
+ const entries = modbusState().operationLog || [];
+ return `
+ ${esc(t("Operation Log / Output"))}
| ${esc(t("Port"))} | +${esc(t("Family"))} | +${esc(t("Slave ID"))} | +${esc(t("Baud"))} | +${esc(t("Parity"))} | +${esc(t("Test register"))} | +${esc(t("Status"))} | +${esc(t("Action"))} | +
|---|---|---|---|---|---|---|---|
| ${esc(item.port)} | +${esc(item.family_display_name || item.family)} | +${esc(String(item.slave))} | +${esc(String(item.baud))} | +${esc(item.parity)} | +${esc(String(item.test_register && item.test_register.address))} | +${esc(item.status || "ok")} | +
+
+
+
+
+ |
+
${esc(technicalJson)}
+ ${esc(JSON.stringify(log.registerForm.lastResult, null, 2))}` : `