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"))}

+
+ ${entries.length ? entries.map((entry) => ` +
+ ${esc(formatUtc(entry.timestamp))} + ${esc(entry.message)} +
+ `).join("") : `
${esc(t("No Modbus operations yet."))}
`} +
+
+ `; + } + + function renderModbusFoundDevices() { + const devices = modbusState().discovery.devices || []; + if (!devices.length) { + return `
${esc(t("No devices discovered yet."))}
`; + } + return ` +
+ + + + + + + + + + + + + + + ${devices.map((item, index) => ` + + + + + + + + + + + `).join("")} + +
${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")} +
+ + +
+
+
+ `; + } + + function renderModbusCurrentConfig() { + const currentConfig = modbusState().currentConfig; + if (!currentConfig) { + return `
${esc(t("Select a discovered device and read its config."))}
`; + } + const rows = [ + { label: t("Current slave id"), value: textValue(currentConfig.current_config && currentConfig.current_config.slave_id, "-") }, + { label: t("Current baud"), value: textValue(currentConfig.current_config && currentConfig.current_config.baud, t("Unknown")) }, + { label: t("Current parity"), value: textValue(currentConfig.current_config && currentConfig.current_config.parity, t("Unknown")) }, + { label: t("Config register values"), value: JSON.stringify(currentConfig.raw_values || {}) }, + { label: t("Last successful read"), value: textValue(currentConfig.last_successful_read, "-") }, + { label: t("Last communication timestamp"), value: textValue(currentConfig.last_communication_timestamp, "-") } + ]; + return `
${renderKeyValueRows(rows)}
`; + } + + function modbusWriteStatusMeta() { + const result = modbusState().lastWriteResult; + if (!result) return ""; + const status = textValue(result.status, ""); + const isSuccess = result.ok === true && status === "verified_target"; + const level = isSuccess ? "success" : (status === "found_elsewhere" || status === "write_unconfirmed" ? "warn" : "error"); + const message = textValue(result.message || result.recommended_next_step, status || t("Unknown")); + const summaryRows = []; + const finalConfig = result.final_detected_config || {}; + const debug = result.debug || {}; + const precheck = debug.precheck || {}; + const requestedCurrent = result.current_requested || {}; + const requestedTarget = result.target_requested || {}; + const fromSlave = textValue(requestedCurrent.slave, textValue(precheck.current && precheck.current.slave, "-")); + const toSlave = textValue(finalConfig.slave, textValue(requestedTarget.slave, "-")); + if (fromSlave || toSlave) summaryRows.push({ label: t("Slave ID"), value: `${fromSlave} → ${toSlave}` }); + summaryRows.push({ label: t("Baud"), value: textValue(finalConfig.baud, textValue(requestedTarget.baud, textValue(precheck.current && precheck.current.baud, "-"))) }); + summaryRows.push({ label: t("Parity"), value: textValue(finalConfig.parity, textValue(requestedTarget.parity, textValue(precheck.current && precheck.current.parity, "-"))) }); + summaryRows.push({ label: t("Verification status"), value: textValue(result.status, "-") }); + const technicalJson = JSON.stringify(result.debug || {}, null, 2); + return ` + +
${renderKeyValueRows(summaryRows)}
+
+ ${esc(t("Technical details"))} +
${esc(technicalJson)}
+
+ `; + } + + function renderModbusWriteProcessLog() { + const entries = modbusState().writeLog || []; + return ` +
+

${esc(t("Technical/process log"))}

+
+ ${entries.length ? entries.map((entry) => `
[${esc(formatUtc(entry.timestamp))}] ${esc(entry.message)}
`).join("") : `
${esc(t("No write log yet"))}
`} +
+
+ `; + } + + function renderModbusTab() { + const log = modbusState(); + const profile = modbusSelectedProfile(); + const profileTransport = (profile && profile.transport) || {}; + const supportsSerialWrite = !!(profile && profile.supports_serial_write) || !!(log.currentConfig && log.currentConfig.current_config && log.currentConfig.current_config.supports_serial_write); + const supportsIdWrite = !!(profile && profile.supports_id_write) || !!(log.currentConfig && log.currentConfig.current_config && log.currentConfig.current_config.supports_id_write); + const portInfo = modbusSelectedPortStatus() || {}; + const zeroBased = !!profileTransport.zero_based; + const scanRunning = modbusScanRunning(); + const scanStatus = textValue(log.discovery.message, scanRunning ? t("Scanning in progress. It may take some minutes.") : ""); + const scanLogLines = modbusDiscoveryLogLines(); + const writeCurrentConfig = modbusWriteCurrentConfigView(); + syncModbusWriteFormFromConfig(); + + return ` +
+
+
+

${esc(t("Device Family"))}

+ ${log.error ? `` : ""} + +
${esc(t("Families are loaded from backend profile JSON files."))}
+
+
${esc(t("Default port"))}
${esc(textValue(profileTransport.default_port, "-"))}
+
${esc(t("Default profile"))}
${esc(`${textValue(profileTransport.default_baud, "9600")}-${textValue(profileTransport.default_databits, "8")}${textValue(profileTransport.default_parity, "N")[0].toUpperCase()}${textValue(profileTransport.default_stopbits, "1")}`)}
+
${esc(t("Addressing"))}
${esc(zeroBased ? t("Zero-based") : t("One-based"))}
+
${esc(t("Serial profile write"))}
${esc(supportsSerialWrite ? t("Configured") : t("Not configured"))}
+
+
+ +
+

${esc(t("Discovery"))}

+
+ + + + + +
+
+ + + ${scanRunning ? `
${esc(t("Scanning in progress. It may take some minutes."))}${log.discovery.currentSlave ? ` ${esc(t("Current slave"))}: ${esc(String(log.discovery.currentSlave))}` : ""}${log.discovery.total ? ` (${esc(String(log.discovery.checked || 0))}/${esc(String(log.discovery.total))})` : ""}
` : ""} +
+ ${scanStatus && !scanRunning ? `
${esc(scanStatus)}
` : ""} +
${esc(zeroBased ? t("Use zero-based addressing for this device family.") : t("This device family uses one-based addressing."))}
+
+

${esc(t("Scan log"))}

+
${scanLogLines.length ? scanLogLines.map((line) => `
${esc(line)}
`).join("") : `
${esc(t("No scan activity yet."))}
`}
+
+
+ +
+

${esc(t("Found Devices Table"))}

+ ${renderModbusFoundDevices()} +
+ +
+

${esc(t("Current Config"))}

+ ${renderModbusCurrentConfig()} +
+ +
+

${esc(t("Configuration Write"))}

+ ${modbusWriteStatusMeta()} + ${!supportsSerialWrite ? `
${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}
` : ""} +
+
${esc(t("Current config"))}
+
+ ${renderKeyValueRows([ + { label: t("Slave ID"), value: writeCurrentConfig.slave }, + { label: t("Baud"), value: writeCurrentConfig.baud }, + { label: t("Parity"), value: writeCurrentConfig.parity }, + { label: t("Verification status"), value: writeCurrentConfig.status } + ])} +
+
+
+
${esc(t("New values to write"))}
+ + + + +
+
${esc(t("Write is disabled until a device has been selected and its current config has been read."))}
+ ${renderModbusWriteProcessLog()} +
+ +
+
+ +
+
+

${esc(t("Advanced"))}

+
+ +
+
+ ${log.advancedOpen ? ` +
+

${esc(t("Session / Port Control"))}

+ ${portInfo.itscreen_running ? `` : ""} +
+
${esc(t("Port status"))}
${esc(textValue(portInfo.status, "-"))}
+
${esc(t("Busy process"))}
${esc((portInfo.busy_process || []).join(", ") || t("None"))}
+
${esc(t("Lock owner"))}
${esc(textValue(portInfo.lock_owner, t("None")))}
+
+ + +
+ + +
+
+
+ + + + + +
+
+ + +
+ ${log.registerForm.lastResult ? `
${esc(JSON.stringify(log.registerForm.lastResult, null, 2))}
` : `
${esc(t("Register explorer is intended for engineering/debug mode."))}
`} + ` : `
${esc(t("Simple mode covers acquire, scan, read config, apply changes, rediscovery, and release."))}
`} +
+ + ${renderModbusLogPanel()} +
+
+ `; + } + function renderActiveTab() { if (state.activeTab === "tscreen") { captureItscreenLogViewport(); @@ -2224,6 +2752,10 @@ updateApFormUi(); return; } + if (state.activeTab === "modbus") { + nodes.content.innerHTML = renderModbusTab(); + return; + } if (state.activeTab === "tscreen") { nodes.content.innerHTML = renderTscreenTab(); updateItscreenLogsUi(); @@ -2280,6 +2812,58 @@ syncNetworkFormFromBackend(); } + async function loadModbus(options = {}) { + const log = modbusState(); + const force = !!options.force; + const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : 8000; + if (!force && log.request) return log.request; + if (!force && log.loadedAt && Date.now() - log.loadedAt < maxAgeMs) return log; + log.loading = true; + log.request = (async () => { + try { + const [portsPayload, profilesPayload, auditPayload] = await Promise.all([ + fetchJson("/api/modbus/ports", { cache: "no-store" }), + fetchJson("/api/modbus/profiles", { cache: "no-store" }), + fetchJson("/api/modbus/audit?limit=80", { cache: "no-store" }) + ]); + log.ports = Array.isArray(portsPayload.ports) ? portsPayload.ports : []; + log.profiles = Array.isArray(profilesPayload.profiles) ? profilesPayload.profiles : []; + log.audit = Array.isArray(auditPayload.entries) ? auditPayload.entries : []; + if (!log.port && log.ports.length) log.port = log.ports[0].port; + if (!log.family && log.profiles.length) log.family = log.profiles[0].family; + if (log.family && !log.profiles.some((item) => item.family === log.family) && log.profiles.length) { + log.family = log.profiles[0].family; + } + const selectedProfile = modbusSelectedProfile(); + if (selectedProfile && selectedProfile.transport) { + if (!log.port && selectedProfile.transport.default_port) log.port = selectedProfile.transport.default_port; + log.discovery.baud = String(selectedProfile.transport.default_baud || 9600); + log.discovery.parity = textValue(selectedProfile.transport.default_parity, "none"); + if (!["id_only", "serial_only", "both", "read_only"].includes(log.writeForm.strategy)) { + log.writeForm.strategy = selectedProfile.supports_id_write ? (selectedProfile.supports_serial_write ? "both" : "id_only") : (selectedProfile.supports_serial_write ? "serial_only" : "read_only"); + } + } + if (!log.operationLog.length && log.audit.length) { + log.operationLog = log.audit.slice().reverse().map((item) => ({ + timestamp: item.timestamp || new Date().toISOString(), + level: item.success === false ? "error" : "info", + message: item.message || `${item.action || "modbus"} ${item.port || ""}`.trim() + })).slice(0, 80); + } + log.error = ""; + log.loadedAt = Date.now(); + return log; + } catch (error) { + log.error = error.message || t("Failed to load Modbus data"); + throw error; + } finally { + log.loading = false; + log.request = null; + } + })(); + return log.request; + } + function syncItscreenFormFromBackend() { const payload = itscreenRegistration(); const host = textValue(payload.server, textValue(payload.host, "")); @@ -2451,6 +3035,8 @@ await loadStatus(); if (state.activeTab === "network") { await loadNetwork(); + } else if (state.activeTab === "modbus") { + await loadModbus(); } else if (state.activeTab === "tscreen") { await loadItscreen(); } else if (state.activeTab === "health") { @@ -2943,6 +3529,370 @@ updateItscreenLogsUi(); }; + window.__modbusSetPort = function (value) { + modbusState().port = value; + if (state.activeTab === "modbus") renderActiveTab(); + }; + + window.__modbusSetFamily = function (value) { + const log = modbusState(); + log.family = value; + log.currentConfig = null; + log.selectedDevice = null; + log.lastWriteResult = null; + const profile = modbusSelectedProfile(); + if (profile && profile.transport) { + log.discovery.baud = String(profile.transport.default_baud || 9600); + log.discovery.parity = textValue(profile.transport.default_parity, "none"); + log.writeForm.baud = String(profile.transport.default_baud || 9600); + log.writeForm.parity = textValue(profile.transport.default_parity, "none"); + log.writeForm.strategy = profile.supports_id_write ? (profile.supports_serial_write ? "both" : "id_only") : (profile.supports_serial_write ? "serial_only" : "read_only"); + } + if (state.activeTab === "modbus") renderActiveTab(); + }; + + window.__modbusSetToggle = function (field, checked) { + modbusState()[field] = !!checked; + }; + + window.__modbusSetDiscovery = function (field, value) { + modbusState().discovery[field] = value; + }; + + window.__modbusSetWriteField = function (field, value) { + modbusState().writeForm[field] = value; + }; + + window.__modbusSetRegisterField = function (field, value) { + modbusState().registerForm[field] = value; + }; + + window.__modbusToggleAdvanced = function () { + modbusState().advancedOpen = !modbusState().advancedOpen; + if (state.activeTab === "modbus") renderActiveTab(); + }; + + window.__modbusSelectDevice = function (index) { + const log = modbusState(); + const item = (log.discovery.devices || [])[index]; + if (!item) return; + log.selectedDevice = item; + log.writeForm.slave = String(item.slave); + log.writeForm.baud = String(item.baud); + log.writeForm.parity = item.parity; + appendModbusLog(t("Device selected for configuration work"), "info"); + if (state.activeTab === "modbus") renderActiveTab(); + }; + + window.__modbusAcquire = async function () { + const log = modbusState(); + log.busyAction = "acquire"; + log.error = ""; + if (state.activeTab === "modbus") renderActiveTab(); + try { + 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 }); + showToast("success", payload.message || t("Port acquired")); + } catch (error) { + log.error = error.message || t("Failed to acquire port"); + appendModbusLog(log.error, "error"); + showToast("error", log.error); + } finally { + log.busyAction = ""; + if (state.activeTab === "modbus") renderActiveTab(); + } + }; + + window.__modbusRelease = async function () { + const log = modbusState(); + log.busyAction = "release"; + log.error = ""; + if (state.activeTab === "modbus") renderActiveTab(); + try { + const payload = await fetchJson("/api/modbus/session/release", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ port: log.port, restart_itscreen: !!log.restartItscreen }) + }); + log.session = null; + ingestModbusPayload(payload); + appendModbusLog(payload.message || t("Port released"), "success"); + await loadModbus({ force: true, maxAgeMs: 0 }); + showToast("success", payload.message || t("Port released")); + } catch (error) { + log.error = error.message || t("Failed to release port"); + appendModbusLog(log.error, "error"); + showToast("error", log.error); + } finally { + log.busyAction = ""; + if (state.activeTab === "modbus") renderActiveTab(); + } + }; + + window.__modbusScan = async function (mode) { + const log = modbusState(); + const slaveFrom = Number(log.discovery.slaveFrom) || 1; + const slaveTo = Number(log.discovery.slaveTo) || 10; + const baud = Number(log.discovery.baud) || 9600; + const parity = textValue(log.discovery.parity, "none"); + log.busyAction = mode === "deep" ? "scan_deep" : "scan_quick"; + log.error = ""; + log.discovery.devices = []; + log.discovery.scanLog = []; + log.discovery.jobId = ""; + log.discovery.state = "running"; + log.discovery.message = t("Scanning in progress. It may take some minutes."); + appendModbusLog(mode === "deep" ? t("Deep scan started") : t("Quick scan started"), "info"); + if (state.activeTab === "modbus") renderActiveTab(); + try { + await modbusEnsureSession(); + const payload = await fetchJson("/api/modbus/discover", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + port: log.port, + family: log.family, + slave_range: [slaveFrom, slaveTo], + baud, + parity, + deep: mode === "deep" + }) + }); + log.discovery.jobId = textValue(payload.job_id, ""); + if (!log.discovery.jobId) { + throw new Error(t("Discovery job was not started")); + } + while (log.discovery.jobId) { + const statusPayload = await fetchJson(`/api/modbus/discover/${encodeURIComponent(log.discovery.jobId)}`, { cache: "no-store" }); + log.discovery.state = textValue(statusPayload.state, "running"); + log.discovery.message = textValue(statusPayload.message, ""); + log.discovery.devices = Array.isArray(statusPayload.devices) ? statusPayload.devices : []; + log.discovery.scanLog = Array.isArray(statusPayload.scan_log) ? statusPayload.scan_log : []; + const progress = statusPayload.progress || {}; + log.discovery.checked = Number(progress.checked) || 0; + log.discovery.total = Number(progress.total) || 0; + log.discovery.currentSlave = Number(progress.current_slave) || null; + if (log.discovery.state === "completed") { + appendModbusLog(log.discovery.devices.length ? t("{count} devices found", { count: log.discovery.devices.length }) : t("No Modbus devices found"), log.discovery.devices.length ? "success" : "warn"); + break; + } + if (log.discovery.state === "failed") { + throw new Error(statusPayload.error || t("Discovery failed")); + } + if (state.activeTab === "modbus") renderActiveTab(); + await new Promise((resolve) => window.setTimeout(resolve, 500)); + } + } catch (error) { + log.error = error.message || t("Discovery failed"); + log.discovery.state = "failed"; + log.discovery.message = log.error; + appendModbusLog(log.error, "error"); + showToast("error", log.error); + } finally { + if (log.discovery.state === "completed" && !log.error) { + log.discovery.message = t("Scan completed"); + } + log.busyAction = ""; + if (state.activeTab === "modbus") renderActiveTab(); + } + }; + + window.__modbusReadConfigFromDiscovery = async function (index) { + window.__modbusSelectDevice(index); + await window.__modbusReadConfig(); + }; + + window.__modbusReadConfig = async function () { + const log = modbusState(); + const current = modbusCurrentConnection(); + log.busyAction = "read_config"; + log.error = ""; + if (state.activeTab === "modbus") renderActiveTab(); + try { + await modbusEnsureSession(); + const payload = await fetchJson("/api/modbus/read-config", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + port: log.port, + family: log.family, + slave: current.slave, + baud: current.baud, + parity: current.parity + }) + }); + log.currentConfig = payload; + log.writeForm.slave = String(payload.current && payload.current.slave || current.slave); + log.writeForm.baud = String(payload.current && payload.current.baud || current.baud); + log.writeForm.parity = textValue(payload.current && payload.current.parity, current.parity); + ingestModbusPayload(payload); + appendModbusLog(t("Current config read completed"), "success"); + } catch (error) { + log.error = error.message || t("Failed to read current config"); + appendModbusLog(log.error, "error"); + showToast("error", log.error); + } finally { + log.busyAction = ""; + if (state.activeTab === "modbus") renderActiveTab(); + } + }; + + window.__modbusApplyConfig = async function () { + const log = modbusState(); + if (!modbusCanWrite()) return; + log.busyAction = "write_config"; + log.error = ""; + log.lastWriteResult = null; + log.writeLog = []; + appendModbusWriteLog(t("Write started; backend validation will confirm the final device state"), "info"); + appendModbusLog(t("Write started; backend validation will confirm the final device state"), "info"); + if (state.activeTab === "modbus") renderActiveTab(); + try { + await modbusEnsureSession(); + const current = modbusCurrentConnection(); + const response = await fetch("/api/modbus/write-config", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + port: log.port, + family: log.family, + current: { + slave: Number(current.slave), + baud: Number(current.baud), + parity: current.parity + }, + target: { + slave: Number(log.writeForm.slave), + baud: Number(log.writeForm.baud), + parity: log.writeForm.parity + }, + strategy: log.writeForm.strategy + }) + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok && payload.ok !== false) { + throw new Error(payload.error || `HTTP ${response.status}`); + } + log.lastWriteResult = payload; + ingestModbusPayload(payload); + ingestModbusWritePayload(payload); + if (payload.final_detected_config) { + log.selectedDevice = { + port: log.port, + family: log.family, + slave: payload.final_detected_config.slave, + baud: payload.final_detected_config.baud, + parity: payload.final_detected_config.parity + }; + if (payload.status === "verified_target" || payload.status === "found_elsewhere") { + await window.__modbusReadConfig(); + } + } + const status = textValue(payload.status, ""); + const level = payload.ok === true && status === "verified_target" + ? "success" + : (status === "found_elsewhere" || status === "write_unconfirmed" ? "warn" : "error"); + const message = payload.message || payload.recommended_next_step || t("Configuration write completed"); + appendModbusWriteLog(message, level); + appendModbusLog(message, level); + showToast(level, message); + if (payload.ok === false && level === "error") { + log.error = message; + } + } catch (error) { + log.error = error.message || t("Failed to apply Modbus changes"); + appendModbusWriteLog(log.error, "error"); + appendModbusLog(log.error, "error"); + showToast("error", log.error); + } finally { + log.busyAction = ""; + if (state.activeTab === "modbus") { + renderActiveTab(); + scrollModbusWriteLogToBottom(); + } + } + }; + + window.__modbusReadRegister = async function () { + const log = modbusState(); + const current = modbusCurrentConnection(); + log.busyAction = "register_read"; + log.error = ""; + try { + await modbusEnsureSession(); + const payload = await fetchJson("/api/modbus/register/read", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + port: log.port, + family: log.family, + slave: Number(current.slave), + baud: Number(current.baud), + parity: current.parity, + address: Number(log.registerForm.address), + count: Number(log.registerForm.count), + register_type: log.registerForm.registerType, + decode_mode: log.registerForm.decodeMode + }) + }); + log.registerForm.lastResult = payload; + ingestModbusPayload(payload); + appendModbusLog(t("Register read completed"), "success"); + } catch (error) { + log.error = error.message || t("Register read failed"); + appendModbusLog(log.error, "error"); + } finally { + log.busyAction = ""; + if (state.activeTab === "modbus") renderActiveTab(); + } + }; + + window.__modbusWriteRegister = async function () { + const log = modbusState(); + const current = modbusCurrentConnection(); + log.busyAction = "register_write"; + log.error = ""; + try { + await modbusEnsureSession(); + const payload = await fetchJson("/api/modbus/register/write", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + port: log.port, + family: log.family, + slave: Number(current.slave), + baud: Number(current.baud), + parity: current.parity, + address: Number(log.registerForm.address), + value: Number(log.registerForm.value) + }) + }); + log.registerForm.lastResult = payload; + ingestModbusPayload(payload); + appendModbusLog(payload.message || t("Register write completed"), "success"); + } catch (error) { + log.error = error.message || t("Register write failed"); + appendModbusLog(log.error, "error"); + } finally { + log.busyAction = ""; + if (state.activeTab === "modbus") renderActiveTab(); + } + }; + nodes.tabs.forEach((button) => { button.addEventListener("click", async () => { const nextTab = button.dataset.tab; diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 638aa32..5d10997 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -85,6 +85,7 @@ diff --git a/stage_ui/console_core/modbus_profiles/iomx_nano_exbd_08_16_12.json b/stage_ui/console_core/modbus_profiles/iomx_nano_exbd_08_16_12.json new file mode 100644 index 0000000..af548ac --- /dev/null +++ b/stage_ui/console_core/modbus_profiles/iomx_nano_exbd_08_16_12.json @@ -0,0 +1,24 @@ +{ + "family": "iomx_nano_exbd_08_16_12", + "title": "IOMX NANO_ExBd-08/16-12", + "display_name": "IOMX NANO_ExBd-08/16-12", + "transport": { + "protocol": "modbus_rtu", + "default_port": "/dev/ttyS3", + "default_baud": 9600, + "default_parity": "none", + "default_databits": 8, + "default_stopbits": 1, + "scan_baud": [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200], + "scan_parity": ["none", "even", "odd"], + "zero_based": false + }, + "registers": { + "test_read": { + "address": 1, + "count": 1, + "type": "holding" + } + }, + "comm_profiles": [] +} diff --git a/stage_ui/console_core/modbus_profiles/ultrasonic_water_meter.json b/stage_ui/console_core/modbus_profiles/ultrasonic_water_meter.json new file mode 100644 index 0000000..ac5db2c --- /dev/null +++ b/stage_ui/console_core/modbus_profiles/ultrasonic_water_meter.json @@ -0,0 +1,36 @@ +{ + "family": "ultrasonic_water_meter", + "title": "Ultrasonic Water Flow Meter IOMX WM 214C", + "display_name": "Ultrasonic Water Flow Meter IOMX WM 214C", + "transport": { + "protocol": "modbus_rtu", + "default_port": "/dev/ttyS3", + "default_baud": 9600, + "default_parity": "none", + "default_databits": 8, + "default_stopbits": 1, + "scan_baud": [2400, 4800, 9600], + "scan_parity": ["none", "even", "odd"], + "zero_based": true + }, + "registers": { + "test_read": { + "address": 0, + "count": 1, + "type": "holding" + }, + "slave_id": { + "address": 1543, + "count": 1, + "type": "holding", + "rw": true + }, + "comm_profile": { + "address": 1544, + "count": 1, + "type": "holding", + "rw": true + } + }, + "comm_profiles": [] +} diff --git a/stage_ui/ui_installer.sh b/stage_ui/ui_installer.sh index 8d2273f..a2425b3 100644 --- a/stage_ui/ui_installer.sh +++ b/stage_ui/ui_installer.sh @@ -28,6 +28,7 @@ PUBLIC_DIR="${APP_DIR}/public" BACKEND_DIR="${APP_DIR}/backend" PROVIDERS_DIR="${APP_DIR}/providers.d" FRONTEND_DIR="${APP_DIR}/frontend" +MODBUS_PROFILES_DIR="${APP_DIR}/modbus_profiles" SERVICE_NAME="iomatex-console.service" LEGACY_SERVICE_NAME="iomatex-webipc.service" CFG_PATH="/etc/iomatex/console.json" @@ -44,6 +45,7 @@ STAGE_PUBLIC_DIR="${STAGE_DIR}/public" STAGE_BACKEND_DIR="${STAGE_DIR}/backend" STAGE_PROVIDERS_DIR="${STAGE_DIR}/providers.d" STAGE_FRONTEND_DIR="${STAGE_DIR}/frontend" +STAGE_MODBUS_PROFILES_DIR="${STAGE_DIR}/modbus_profiles" copy_tree() { local src="$1" @@ -72,7 +74,7 @@ rollback_deploy() { wait_for_local_http() { local attempt - for attempt in $(seq 1 15); do + for attempt in $(seq 1 30); do if ! systemctl is-active --quiet "${SERVICE_NAME}"; then sleep 1 continue @@ -85,7 +87,7 @@ wait_for_local_http() { import sys import urllib.request try: - with urllib.request.urlopen("http://127.0.0.1/api/status", timeout=2) as response: + with urllib.request.urlopen("http://127.0.0.1/api/status", timeout=5) as response: sys.exit(0 if response.status == 200 else 1) except Exception: sys.exit(1) @@ -135,6 +137,9 @@ step "Validate source tree" for path in \ "$SRC_ROOT/backend/app.py" \ "$SRC_ROOT/backend/itscreen_registration.py" \ + "$SRC_ROOT/backend/modbus_backend.py" \ + "$SRC_ROOT/modbus_profiles/ultrasonic_water_meter.json" \ + "$SRC_ROOT/modbus_profiles/iomx_nano_exbd_08_16_12.json" \ "$SRC_ROOT/frontend/index.html" \ "$SRC_ROOT/frontend/console.i18n.js" \ "$SRC_ROOT/frontend/console.js" \ @@ -148,7 +153,7 @@ done step "Ensure runtime packages exist" apt-get update -apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw +apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw mbpoll psmisc python3 --version echo "Skip setcap: service runs as root and can bind port 80 without extra capabilities" @@ -163,7 +168,7 @@ if [ -d "$LEGACY_APP_DIR" ]; then mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR" fi rm -rf "$STAGE_DIR" -mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR" +mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR" "$STAGE_MODBUS_PROFILES_DIR" cat > "$CFG_PATH" <