Merge scanner and MQTT contract refactoring
This commit is contained in:
commit
c3f1a55f72
|
|
@ -0,0 +1,5 @@
|
|||
# Edge Console 3.1.24
|
||||
|
||||
- Replaced the unbounded Modbus marker with an expiring, renewable scanner lease owned by Edge Console.
|
||||
- Edge Console now owns the complete `/dev/ttyS3` handoff: stop IT-Screen Client, scan, release the lease, and restore the Client even after a failed scan or an abandoned browser session.
|
||||
- Added exact session ownership checks, heartbeat/watchdog recovery, legacy-lock recovery, and regression coverage for scanner lifecycle and frontend API calls.
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
# Edge Console 3.1.25
|
||||
|
||||
- Identify IOMX-SNG-500 applications installed on an ExBd Nano base with a
|
||||
compound read-only fingerprint: the shared Nano identity plus SNG state,
|
||||
error and power registers.
|
||||
- Keep the ordinary ExBd Nano profile as a fallback when the application
|
||||
fingerprint does not match.
|
||||
- Retain the renewable scanner lease and abandoned-session recovery delivered
|
||||
in Console 3.1.24.
|
||||
|
|
@ -14,7 +14,7 @@
|
|||
"version": "1.0.1"
|
||||
},
|
||||
"stage_ui": {
|
||||
"version": "3.1.23"
|
||||
"version": "3.1.25"
|
||||
},
|
||||
"stage_avahi": {
|
||||
"version": "1.0.0"
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ from itscreen_registration import get_reverse_tunnel_diagnostics, configure_reve
|
|||
from modbus_backend import (
|
||||
ApiError as ModbusApiError,
|
||||
acquire_session as modbus_acquire_session,
|
||||
assert_session_owner as modbus_assert_session_owner,
|
||||
get_discovery_job as modbus_get_discovery_job,
|
||||
iomx04_apply_timed_relay as modbus_iomx04_apply_timed_relay,
|
||||
iomx04_set_relay as modbus_iomx04_set_relay,
|
||||
|
|
@ -40,7 +41,10 @@ from modbus_backend import (
|
|||
read_device_config as modbus_read_device_config,
|
||||
read_registers as modbus_read_registers,
|
||||
release_session as modbus_release_session,
|
||||
renew_session as modbus_renew_session,
|
||||
start_session_watchdog as modbus_start_session_watchdog,
|
||||
start_discovery as modbus_start_discovery,
|
||||
stop_session_watchdog as modbus_stop_session_watchdog,
|
||||
write_device_config as modbus_write_device_config,
|
||||
write_register as modbus_write_register,
|
||||
)
|
||||
|
|
@ -56,7 +60,7 @@ APP_DIR = "/opt/iomatex-console"
|
|||
PUBLIC_DIR = os.path.join(APP_DIR, "public")
|
||||
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
||||
CONFIG_PATH = "/etc/iomatex/console.json"
|
||||
UI_VERSION = "V 3.1.23"
|
||||
UI_VERSION = "V 3.1.25"
|
||||
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
|
||||
ZONEINFO_ROOT = "/usr/share/zoneinfo"
|
||||
|
||||
|
|
@ -4165,6 +4169,22 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/modbus/session/heartbeat":
|
||||
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_renew_session(
|
||||
str(payload.get("port", "")),
|
||||
str(payload.get("session_id", "")),
|
||||
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:
|
||||
|
|
@ -4175,6 +4195,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
str(payload.get("port", "")),
|
||||
bool(payload.get("restart_itscreen", False)),
|
||||
source="console_ui",
|
||||
session_id=str(payload.get("session_id", "")),
|
||||
))
|
||||
except ModbusApiError as exc:
|
||||
self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code)
|
||||
|
|
@ -4187,6 +4208,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
modbus_assert_session_owner(str(payload.get("port", "")), str(payload.get("session_id", "")))
|
||||
self.send_json(modbus_start_discovery(
|
||||
port=str(payload.get("port", "")),
|
||||
slave_range=list(payload.get("slave_range") or [1, 10]),
|
||||
|
|
@ -4226,6 +4248,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
modbus_assert_session_owner(str(payload.get("port", "")), str(payload.get("session_id", "")))
|
||||
self.send_json(modbus_read_device_config(
|
||||
port=str(payload.get("port", "")),
|
||||
family=str(payload.get("family", "")),
|
||||
|
|
@ -4245,6 +4268,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
modbus_assert_session_owner(str(payload.get("port", "")), str(payload.get("session_id", "")))
|
||||
self.send_json(modbus_write_device_config(
|
||||
port=str(payload.get("port", "")),
|
||||
family=str(payload.get("family", "")),
|
||||
|
|
@ -4265,6 +4289,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
modbus_assert_session_owner(str(payload.get("port", "")), str(payload.get("session_id", "")))
|
||||
self.send_json(modbus_read_registers(
|
||||
port=str(payload.get("port", "")),
|
||||
family=str(payload.get("family", "")),
|
||||
|
|
@ -4288,6 +4313,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
modbus_assert_session_owner(str(payload.get("port", "")), str(payload.get("session_id", "")))
|
||||
self.send_json(modbus_write_register(
|
||||
port=str(payload.get("port", "")),
|
||||
family=str(payload.get("family", "")),
|
||||
|
|
@ -4309,6 +4335,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
modbus_assert_session_owner(str(payload.get("port", "")), str(payload.get("session_id", "")))
|
||||
self.send_json(modbus_iomx04_set_relay(
|
||||
port=str(payload.get("port", "")),
|
||||
slave=int(payload.get("slave", 1)),
|
||||
|
|
@ -4328,6 +4355,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
try:
|
||||
modbus_assert_session_owner(str(payload.get("port", "")), str(payload.get("session_id", "")))
|
||||
self.send_json(modbus_iomx04_apply_timed_relay(
|
||||
port=str(payload.get("port", "")),
|
||||
slave=int(payload.get("slave", 1)),
|
||||
|
|
@ -4511,6 +4539,7 @@ def main():
|
|||
listen_ports = [port] + extra_ports
|
||||
servers = []
|
||||
threads = []
|
||||
modbus_start_session_watchdog()
|
||||
try:
|
||||
for listen_port in listen_ports:
|
||||
server = ThreadingHTTPServer((bind, listen_port), Handler)
|
||||
|
|
@ -4522,6 +4551,7 @@ def main():
|
|||
threads.append(thread)
|
||||
servers[0].serve_forever()
|
||||
finally:
|
||||
modbus_stop_session_watchdog()
|
||||
for server in servers:
|
||||
try:
|
||||
server.server_close()
|
||||
|
|
|
|||
|
|
@ -19,11 +19,15 @@ 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"
|
||||
MODBUS_SESSION_TTL_SEC = max(30, int(os.environ.get("IOMATEX_MODBUS_SESSION_TTL_SEC", "120")))
|
||||
DEFAULT_DISCOVER_TIMEOUT = 6.0
|
||||
DEFAULT_DISCOVERY_QUICK_TIMEOUT = 1.8
|
||||
DEFAULT_DISCOVERY_DEEP_TIMEOUT = 3.2
|
||||
DISCOVERY_JOBS: Dict[str, Dict[str, Any]] = {}
|
||||
DISCOVERY_JOBS_LOCK = threading.Lock()
|
||||
_ACTIVE_PORT_OPERATIONS: Dict[str, str] = {}
|
||||
_SESSION_WATCHDOG_STOP = threading.Event()
|
||||
_SESSION_WATCHDOG_THREAD: Optional[threading.Thread] = None
|
||||
SID_WRITE_ACK_OPTIONAL_FAMILIES = {"exbd_nano"}
|
||||
EM01_FAMILY = "iomx_em_01"
|
||||
EM01_FIXED_BAUD = 9600
|
||||
|
|
@ -80,6 +84,10 @@ def utc_now_iso() -> str:
|
|||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
|
||||
|
||||
def utc_iso_at(epoch: float) -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch))
|
||||
|
||||
|
||||
def ensure_runtime_dirs() -> None:
|
||||
os.makedirs(MODBUS_RUN_DIR, exist_ok=True)
|
||||
os.makedirs(os.path.dirname(MODBUS_AUDIT_LOG), exist_ok=True)
|
||||
|
|
@ -1924,6 +1932,10 @@ def acquire_lock(port: str, meta: Dict[str, Any]) -> Dict[str, Any]:
|
|||
payload = dict(meta)
|
||||
payload["port"] = port
|
||||
payload["created_at"] = utc_now_iso()
|
||||
payload["session_id"] = uuid.uuid4().hex
|
||||
payload["process_id"] = os.getpid()
|
||||
payload["expires_at"] = time.time() + MODBUS_SESSION_TTL_SEC
|
||||
payload["expires_at_iso"] = utc_iso_at(payload["expires_at"])
|
||||
fd = None
|
||||
try:
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
|
||||
|
|
@ -1953,6 +1965,49 @@ def release_lock(port: str) -> Optional[Dict[str, Any]]:
|
|||
return lock
|
||||
|
||||
|
||||
def lock_expired(lock: Optional[Dict[str, Any]], now: Optional[float] = None) -> bool:
|
||||
if not lock:
|
||||
return False
|
||||
try:
|
||||
expires_at = float(lock.get("expires_at", 0))
|
||||
except (TypeError, ValueError):
|
||||
expires_at = 0
|
||||
# PID is diagnostic only. A new Console worker must not reclaim a still
|
||||
# valid lease while the old worker is finishing a UART operation. Legacy
|
||||
# markers have no expiry and are therefore reclaimed immediately; a lease
|
||||
# left by a dead worker is bounded by the same TTL as an abandoned browser.
|
||||
return expires_at <= float(now if now is not None else time.time())
|
||||
|
||||
|
||||
def refresh_lock(port: str, session_id: str, updates: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
lock = read_lock(port)
|
||||
if not lock:
|
||||
raise ApiError("Modbus maintenance session no longer exists", 409)
|
||||
if not session_id or str(lock.get("session_id") or "") != str(session_id):
|
||||
raise ApiError("Modbus maintenance session owner changed", 409)
|
||||
payload = dict(lock)
|
||||
payload.pop("path", None)
|
||||
payload.update(dict(updates or {}))
|
||||
payload["process_id"] = os.getpid()
|
||||
payload["expires_at"] = time.time() + MODBUS_SESSION_TTL_SEC
|
||||
payload["expires_at_iso"] = utc_iso_at(payload["expires_at"])
|
||||
path = lock_path_for_port(port)
|
||||
temporary = f"{path}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
|
||||
try:
|
||||
with open(temporary, "x", encoding="utf-8") as fh:
|
||||
json.dump(payload, fh, indent=2, sort_keys=True)
|
||||
os.chmod(temporary, 0o644)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
try:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
except Exception:
|
||||
pass
|
||||
payload["path"] = path
|
||||
return payload
|
||||
|
||||
|
||||
def busy_processes(port: str) -> List[str]:
|
||||
if not os.path.exists(port) or not command_exists("fuser"):
|
||||
return []
|
||||
|
|
@ -2061,6 +2116,7 @@ def port_status(port: str) -> Dict[str, Any]:
|
|||
|
||||
|
||||
def list_ports_payload() -> Dict[str, Any]:
|
||||
reap_expired_sessions()
|
||||
ports = [port_status(port) for port in list_uart_ports()]
|
||||
return {"ok": True, "ports": ports, "generated_at": utc_now_iso()}
|
||||
|
||||
|
|
@ -2319,6 +2375,10 @@ def validate_profile(data: Dict[str, Any], source_path: str) -> Dict[str, Any]:
|
|||
if not isinstance(spec, dict):
|
||||
continue
|
||||
summary_registers[str(name)] = normalize_register_spec(spec)
|
||||
confirmation_registers = []
|
||||
for spec in (data.get("detection") or {}).get("confirm") or []:
|
||||
if isinstance(spec, dict):
|
||||
confirmation_registers.append(normalize_register_spec(spec))
|
||||
profile = {
|
||||
"family": family,
|
||||
"title": title or family,
|
||||
|
|
@ -2337,6 +2397,7 @@ def validate_profile(data: Dict[str, Any], source_path: str) -> Dict[str, Any]:
|
|||
},
|
||||
"registers": registers,
|
||||
"detection": normalize_detection_config(data, registers),
|
||||
"confirmation_registers": confirmation_registers,
|
||||
"summary_registers": summary_registers,
|
||||
"io_relationship": data.get("io_relationship") if family == "n4d8c12" else None,
|
||||
"comm_profiles": data.get("comm_profiles") or [],
|
||||
|
|
@ -2447,6 +2508,7 @@ def get_discovery_job(job_id: str) -> Dict[str, Any]:
|
|||
|
||||
|
||||
def ensure_port_locked(port: str) -> Dict[str, Any]:
|
||||
recover_expired_session(port)
|
||||
lock = read_lock(port)
|
||||
if not lock:
|
||||
raise ApiError("Acquire port before using Modbus operations", 409)
|
||||
|
|
@ -2455,6 +2517,13 @@ def ensure_port_locked(port: str) -> Dict[str, Any]:
|
|||
return lock
|
||||
|
||||
|
||||
def assert_session_owner(port: str, session_id: str) -> Dict[str, Any]:
|
||||
lock = ensure_port_locked(port)
|
||||
if not session_id or str(lock.get("session_id") or "") != str(session_id):
|
||||
raise ApiError("This Modbus maintenance session belongs to another browser or has expired", 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"]:
|
||||
|
|
@ -2483,9 +2552,90 @@ def session_operation(fn):
|
|||
return guarded
|
||||
|
||||
|
||||
def _port_operation_active(port: str) -> bool:
|
||||
with _SESSION_OPERATION_LOCK:
|
||||
return bool(_ACTIVE_PORT_OPERATIONS.get(port))
|
||||
|
||||
|
||||
def _begin_port_operation(port: str, operation_id: str) -> None:
|
||||
with _SESSION_OPERATION_LOCK:
|
||||
current = _ACTIVE_PORT_OPERATIONS.get(port)
|
||||
if current:
|
||||
raise ApiError("A Modbus operation is already using this port", 409)
|
||||
_ACTIVE_PORT_OPERATIONS[port] = operation_id
|
||||
|
||||
|
||||
def _end_port_operation(port: str, operation_id: str) -> None:
|
||||
with _SESSION_OPERATION_LOCK:
|
||||
if _ACTIVE_PORT_OPERATIONS.get(port) == operation_id:
|
||||
_ACTIVE_PORT_OPERATIONS.pop(port, None)
|
||||
|
||||
|
||||
def recover_expired_session(port: str) -> bool:
|
||||
with _SESSION_OPERATION_LOCK:
|
||||
lock = read_lock(port)
|
||||
if not lock or not lock_expired(lock) or _ACTIVE_PORT_OPERATIONS.get(port):
|
||||
return False
|
||||
restore_required = bool(lock.get("restore_itscreen") or lock.get("itscreen_stopped")) and bool(lock.get("itscreen_was_running"))
|
||||
if restore_required and not systemctl_is_active(ITSCREEN_SERVICE_UNIT):
|
||||
restored = start_itscreen_service_wait()
|
||||
if not restored.get("ok"):
|
||||
backend_log("modbus_session_recovery_failed", port=port, error=restored.get("error", ""))
|
||||
return False
|
||||
release_lock(port)
|
||||
try:
|
||||
append_audit({
|
||||
"action": "session_expired",
|
||||
"port": port,
|
||||
"itscreen_restarted": restore_required,
|
||||
"success": True,
|
||||
"source": str(lock.get("source") or "watchdog"),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
backend_log("modbus_session_recovered", port=port, itscreen_restarted=restore_required)
|
||||
return True
|
||||
|
||||
|
||||
def reap_expired_sessions() -> int:
|
||||
ensure_runtime_dirs()
|
||||
recovered = 0
|
||||
paths = glob.glob(os.path.join(MODBUS_RUN_DIR, "modbus-*.lock"))
|
||||
for path in paths:
|
||||
name = os.path.basename(path)
|
||||
port_name = name[len("modbus-"):-len(".lock")]
|
||||
if not port_name:
|
||||
continue
|
||||
try:
|
||||
recovered += 1 if recover_expired_session(f"/dev/{port_name}") else 0
|
||||
except Exception as exc:
|
||||
backend_log("modbus_session_recovery_error", port=f"/dev/{port_name}", error=str(exc))
|
||||
return recovered
|
||||
|
||||
|
||||
def start_session_watchdog(interval_sec: float = 5.0) -> None:
|
||||
global _SESSION_WATCHDOG_THREAD
|
||||
if _SESSION_WATCHDOG_THREAD and _SESSION_WATCHDOG_THREAD.is_alive():
|
||||
return
|
||||
_SESSION_WATCHDOG_STOP.clear()
|
||||
|
||||
def worker() -> None:
|
||||
reap_expired_sessions()
|
||||
while not _SESSION_WATCHDOG_STOP.wait(max(1.0, float(interval_sec))):
|
||||
reap_expired_sessions()
|
||||
|
||||
_SESSION_WATCHDOG_THREAD = threading.Thread(target=worker, name="modbus-session-watchdog", daemon=True)
|
||||
_SESSION_WATCHDOG_THREAD.start()
|
||||
|
||||
|
||||
def stop_session_watchdog() -> None:
|
||||
_SESSION_WATCHDOG_STOP.set()
|
||||
|
||||
|
||||
@session_operation
|
||||
def acquire_session(port: str, stop_itscreen: bool, source: str = "ui", owner: str = "modbus_tool") -> Dict[str, Any]:
|
||||
operations = []
|
||||
recover_expired_session(port)
|
||||
status_before = port_status(port)
|
||||
if not status_before["exists"]:
|
||||
raise ApiError("Port does not exist", 404)
|
||||
|
|
@ -2493,24 +2643,34 @@ def acquire_session(port: str, stop_itscreen: bool, source: str = "ui", owner: s
|
|||
raise ApiError("Port is already locked by modbus tool", 409)
|
||||
|
||||
itscreen_running = status_before["itscreen_running"]
|
||||
# A second RTU master on the production serial path is never safe. The
|
||||
# backend owns this rule; a stale browser option cannot bypass it.
|
||||
must_stop_itscreen = bool(itscreen_running and itscreen_conflict_expected(port))
|
||||
stopped_itscreen = False
|
||||
lock = None
|
||||
try:
|
||||
if stop_itscreen and itscreen_running:
|
||||
lock = acquire_lock(port, {
|
||||
"owner": owner,
|
||||
"source": source,
|
||||
"stop_itscreen": bool(stop_itscreen),
|
||||
"restore_itscreen": bool(must_stop_itscreen),
|
||||
"itscreen_was_running": bool(itscreen_running),
|
||||
"itscreen_stopped": False,
|
||||
})
|
||||
if must_stop_itscreen:
|
||||
operations.append({"level": "info", "message": "Stopping it-screen service before Modbus session"})
|
||||
# Even a failed stop may have partially stopped the runtime.
|
||||
stopped_itscreen = True
|
||||
stop_result = stop_itscreen_service_wait()
|
||||
if not stop_result.get("ok"):
|
||||
raise ApiError(stop_result.get("error") or "Failed to stop it-screen service", 502)
|
||||
lock = refresh_lock(port, str(lock.get("session_id") or ""), {"itscreen_stopped": True})
|
||||
operations.append({"level": "success", "message": "it-screen service stopped; Modbus port is ready"})
|
||||
ensure_port_available(port, allow_itscreen_conflict=False)
|
||||
lock = acquire_lock(port, {
|
||||
"owner": owner,
|
||||
"source": source,
|
||||
"stop_itscreen": bool(stop_itscreen),
|
||||
"itscreen_was_running": bool(itscreen_running),
|
||||
"itscreen_stopped": bool(stopped_itscreen),
|
||||
})
|
||||
busy = busy_processes(port)
|
||||
if busy:
|
||||
raise ApiError("Port is busy by another process", 409, json.dumps(busy))
|
||||
if systemctl_is_active(ITSCREEN_SERVICE_UNIT) and itscreen_conflict_expected(port):
|
||||
raise ApiError("it-screen is running and may conflict with Modbus master access", 409)
|
||||
except Exception as exc:
|
||||
if stopped_itscreen and itscreen_running:
|
||||
try:
|
||||
|
|
@ -2519,6 +2679,8 @@ def acquire_session(port: str, stop_itscreen: bool, source: str = "ui", owner: s
|
|||
raise RuntimeError(restored.get("error") or "Service restart failed")
|
||||
except Exception as recovery_error:
|
||||
raise ApiError(f"{exc}; automation restoration failed: {recovery_error}", 502) from exc
|
||||
if lock:
|
||||
release_lock(port)
|
||||
raise
|
||||
|
||||
payload = {
|
||||
|
|
@ -2534,7 +2696,7 @@ def acquire_session(port: str, stop_itscreen: bool, source: str = "ui", owner: s
|
|||
append_audit({
|
||||
"action": "session_acquire",
|
||||
"port": port,
|
||||
"stop_itscreen": bool(stop_itscreen),
|
||||
"stop_itscreen": bool(must_stop_itscreen),
|
||||
"itscreen_running": bool(itscreen_running),
|
||||
"itscreen_stopped": bool(stopped_itscreen),
|
||||
"success": True,
|
||||
|
|
@ -2551,21 +2713,35 @@ def acquire_session(port: str, stop_itscreen: bool, source: str = "ui", owner: s
|
|||
|
||||
|
||||
@session_operation
|
||||
def release_session(port: str, restart_itscreen: bool, source: str = "ui", owner: str = "modbus_tool") -> Dict[str, Any]:
|
||||
def release_session(
|
||||
port: str,
|
||||
restart_itscreen: bool,
|
||||
source: str = "ui",
|
||||
owner: str = "modbus_tool",
|
||||
session_id: str = "",
|
||||
internal: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
lock = read_lock(port)
|
||||
if not lock:
|
||||
raise ApiError("Port is not locked by modbus tool", 409)
|
||||
if lock.get("owner") == "io_relationship" and owner != "io_relationship":
|
||||
raise ApiError("An input/output mode operation owns this port", 409)
|
||||
if session_id and str(lock.get("session_id") or "") != str(session_id):
|
||||
raise ApiError("Modbus maintenance session owner changed", 409)
|
||||
if _ACTIVE_PORT_OPERATIONS.get(port) and not internal:
|
||||
raise ApiError("A Modbus operation is still using this port", 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")):
|
||||
# Restoration is derived from the lease, not from a browser checkbox. A
|
||||
# disconnected page cannot leave production polling stopped.
|
||||
must_restart = bool(lock.get("restore_itscreen")) and bool(lock.get("itscreen_was_running"))
|
||||
if must_restart and not systemctl_is_active(ITSCREEN_SERVICE_UNIT):
|
||||
operations.append({"level": "info", "message": "Starting it-screen service after Modbus session"})
|
||||
start_result = start_itscreen_service_wait()
|
||||
if not start_result.get("ok"):
|
||||
raise ApiError(start_result.get("error") or "Failed to start it-screen service", 502)
|
||||
restarted = True
|
||||
released = release_lock(port)
|
||||
payload = {
|
||||
"ok": True,
|
||||
"message": "Port released",
|
||||
|
|
@ -2577,7 +2753,7 @@ def release_session(port: str, restart_itscreen: bool, source: str = "ui", owner
|
|||
append_audit({
|
||||
"action": "session_release",
|
||||
"port": port,
|
||||
"restart_itscreen": bool(restart_itscreen),
|
||||
"restart_itscreen": bool(must_restart),
|
||||
"itscreen_restarted": bool(restarted),
|
||||
"success": True,
|
||||
"source": source,
|
||||
|
|
@ -2585,6 +2761,18 @@ def release_session(port: str, restart_itscreen: bool, source: str = "ui", owner
|
|||
return payload
|
||||
|
||||
|
||||
@session_operation
|
||||
def renew_session(port: str, session_id: str, source: str = "ui") -> Dict[str, Any]:
|
||||
lock = refresh_lock(port, session_id)
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "Modbus maintenance session renewed",
|
||||
"port": port,
|
||||
"lock": lock,
|
||||
"source": source,
|
||||
}
|
||||
|
||||
|
||||
def decode_comm_profile(profile: Dict[str, Any], register_value: Optional[int]) -> Dict[str, Any]:
|
||||
comm_profiles = profile.get("comm_profiles") or []
|
||||
result = {
|
||||
|
|
@ -2899,6 +3087,38 @@ def discover_devices(
|
|||
best_error = read_result.get("error_type") or best_error
|
||||
continue
|
||||
family_detection = evaluate_family_detection(profile, read_result, register)
|
||||
if family_detection["state"] == "recognized" and profile.get("confirmation_registers"):
|
||||
confirmation_results = []
|
||||
for confirmation in profile["confirmation_registers"]:
|
||||
confirmation_result = read_register_spec(
|
||||
profile=profile,
|
||||
port=port,
|
||||
slave=slave,
|
||||
baud=int(baud),
|
||||
parity=str(parity),
|
||||
register=confirmation,
|
||||
register_name="detection_confirmation",
|
||||
timeout=timeout_value,
|
||||
retries=retries_value,
|
||||
)
|
||||
confirmation_results.append({
|
||||
"register": dict(confirmation),
|
||||
"ok": bool(confirmation_result.get("ok")),
|
||||
"values": confirmation_result.get("values") or [],
|
||||
"error_type": confirmation_result.get("error_type") or "",
|
||||
})
|
||||
if not confirmation_result.get("ok"):
|
||||
break
|
||||
family_detection["confirmationRegisters"] = confirmation_results
|
||||
if len(confirmation_results) != len(profile["confirmation_registers"]) or not all(
|
||||
item["ok"] for item in confirmation_results
|
||||
):
|
||||
family_detection.update({
|
||||
"state": "confirmation_failed",
|
||||
"familyKey": "",
|
||||
"familyLabel": "Application fingerprint did not match",
|
||||
"matched": False,
|
||||
})
|
||||
if log_collector and is_string_rule:
|
||||
decoded_family = family_detection.get("modelString") or family_detection.get("rawValue") or ""
|
||||
raw_registers = family_detection.get("rawRegisters") or []
|
||||
|
|
@ -3087,8 +3307,9 @@ def start_discovery(
|
|||
deep: bool = False,
|
||||
source: str = "ui",
|
||||
) -> Dict[str, Any]:
|
||||
ensure_port_locked(port)
|
||||
lease = ensure_port_locked(port)
|
||||
job_id = uuid.uuid4().hex
|
||||
_begin_port_operation(port, job_id)
|
||||
start_slave = max(1, int(slave_range[0]))
|
||||
end_slave = max(start_slave, int(slave_range[1]))
|
||||
baud_candidates = [int(item) for item in (baudrates or [9600]) if int(item) > 0]
|
||||
|
|
@ -3131,6 +3352,8 @@ def start_discovery(
|
|||
append_discovery_job_log(job_id, level, message, **meta)
|
||||
|
||||
def worker() -> None:
|
||||
result = None
|
||||
failure = None
|
||||
try:
|
||||
result = discover_devices(
|
||||
port=port,
|
||||
|
|
@ -3141,10 +3364,28 @@ def start_discovery(
|
|||
source=source,
|
||||
log_collector=log,
|
||||
)
|
||||
except Exception as exc:
|
||||
failure = exc
|
||||
finally:
|
||||
try:
|
||||
release_session(
|
||||
port,
|
||||
True,
|
||||
source=source,
|
||||
owner=str(lease.get("owner") or "modbus_tool"),
|
||||
session_id=str(lease.get("session_id") or ""),
|
||||
internal=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
failure = failure or exc
|
||||
finally:
|
||||
_end_port_operation(port, job_id)
|
||||
|
||||
if failure is None and result is not None:
|
||||
update_discovery_job(
|
||||
job_id,
|
||||
state="completed",
|
||||
message="Scan completed",
|
||||
message="Scan completed; production polling restored",
|
||||
devices=result.get("devices", []),
|
||||
progress={
|
||||
"current_slave": end_slave,
|
||||
|
|
@ -3156,16 +3397,16 @@ def start_discovery(
|
|||
},
|
||||
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:
|
||||
append_discovery_job_log(job_id, "success", f"Scan completed. Found {len(result.get('devices', []))} device(s). Production polling restored.")
|
||||
else:
|
||||
update_discovery_job(
|
||||
job_id,
|
||||
state="failed",
|
||||
message="Scan failed",
|
||||
error=str(exc),
|
||||
error=str(failure),
|
||||
completed_at=utc_now_iso(),
|
||||
)
|
||||
append_discovery_job_log(job_id, "error", f"Scan failed: {exc}")
|
||||
append_discovery_job_log(job_id, "error", f"Scan failed: {failure}")
|
||||
|
||||
thread = threading.Thread(target=worker, name=f"modbus-discovery-{job_id}", daemon=True)
|
||||
thread.start()
|
||||
|
|
|
|||
|
|
@ -18,9 +18,9 @@ class IoApiTest(unittest.TestCase):
|
|||
self.addCleanup(self.server.shutdown)
|
||||
p=mock.patch.object(app.Handler,'log_message');p.start();self.addCleanup(p.stop)
|
||||
|
||||
def post(self, data, content_type='application/json'):
|
||||
def post(self, data, content_type='application/json', path='/api/modbus/io-relationship'):
|
||||
c=http.client.HTTPConnection(*self.server.server_address)
|
||||
c.request('POST','/api/modbus/io-relationship',json.dumps(data),{'Content-Type':content_type})
|
||||
c.request('POST',path,json.dumps(data),{'Content-Type':content_type})
|
||||
r=c.getresponse();body=json.loads(r.read());c.close();return r.status,body
|
||||
|
||||
def test_authentication_required(self):
|
||||
|
|
@ -39,4 +39,13 @@ class IoApiTest(unittest.TestCase):
|
|||
args=dict(port='/dev/ttyS3',family='n4d8c12',slave=1,baud=9600,parity='none',mode=0,expected=1,confirmed=True)
|
||||
self.assertEqual((200,{'ok':True,'mode':0}),self.post(args));fn.assert_called_once_with(**args)
|
||||
|
||||
def test_authenticated_heartbeat_renews_exact_session(self):
|
||||
response={'ok':True,'lock':{'session_id':'lease-1'}}
|
||||
with mock.patch.object(app.Handler,'auth_session',return_value={'username':'iomatex'}),mock.patch.object(app,'modbus_renew_session',return_value=response) as fn:
|
||||
self.assertEqual((200,response),self.post(
|
||||
{'port':'/dev/ttyS3','session_id':'lease-1'},
|
||||
path='/api/modbus/session/heartbeat',
|
||||
))
|
||||
fn.assert_called_once_with('/dev/ttyS3','lease-1',source='console_ui')
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import contextlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest import mock
|
||||
import modbus_backend as mb
|
||||
|
|
@ -90,7 +93,11 @@ class IoRelationshipTest(unittest.TestCase):
|
|||
self.release.assert_called_once()
|
||||
|
||||
def test_other_register_clients_cannot_use_transaction_lock(self):
|
||||
with mock.patch.object(mb, 'read_lock', return_value={'owner': 'io_relationship'}):
|
||||
with mock.patch.object(mb, 'read_lock', return_value={
|
||||
'owner': 'io_relationship',
|
||||
'process_id': os.getpid(),
|
||||
'expires_at': time.time() + 60,
|
||||
}):
|
||||
with self.assertRaises(mb.ApiError): mb.ensure_port_locked('/dev/ttyS3')
|
||||
|
||||
def test_profile_does_not_guess_identity_from_mode_number(self):
|
||||
|
|
@ -103,7 +110,10 @@ class IoRelationshipTest(unittest.TestCase):
|
|||
|
||||
class SessionRecoveryTest(unittest.TestCase):
|
||||
def test_failed_stop_still_restores_previously_running_service(self):
|
||||
with mock.patch.object(mb, 'port_status', return_value={'exists':True,'locked':False,'itscreen_running':True}), \
|
||||
with tempfile.TemporaryDirectory() as directory, \
|
||||
mock.patch.object(mb, 'MODBUS_RUN_DIR', directory), \
|
||||
mock.patch.object(mb, 'MODBUS_AUDIT_LOG', str(Path(directory) / 'audit.log')), \
|
||||
mock.patch.object(mb, 'port_status', return_value={'exists':True,'locked':False,'itscreen_running':True}), \
|
||||
mock.patch.object(mb, 'stop_itscreen_service_wait', return_value={'ok':False,'error':'stop timeout'}), \
|
||||
mock.patch.object(mb, 'start_itscreen_service_wait', return_value={'ok':True}) as restart:
|
||||
with self.assertRaises(mb.ApiError): mb.acquire_session('/dev/ttyS3',True)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,43 @@
|
|||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
|
||||
SOURCE = (Path(__file__).resolve().parent.parent / "frontend" / "console.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
class ModbusSessionFrontendContractTest(unittest.TestCase):
|
||||
def test_scan_uses_one_backend_owned_pause_and_automatic_restore(self):
|
||||
scan = re.search(
|
||||
r"window\.__modbusScan = async function \(mode\) \{(?P<body>.*?)\n \};",
|
||||
SOURCE,
|
||||
re.S,
|
||||
)
|
||||
self.assertIsNotNone(scan)
|
||||
body = scan.group("body")
|
||||
self.assertIn("modbusEnsureSession({ actionLabel, stopItscreen: true", body)
|
||||
self.assertNotIn("/api/itscreen/service/stop", body)
|
||||
self.assertIn("stopModbusLeaseHeartbeat()", body)
|
||||
|
||||
def test_browser_renews_and_releases_exact_lease(self):
|
||||
self.assertIn('fetchJson("/api/modbus/session/heartbeat"', SOURCE)
|
||||
self.assertIn("session_id: sessionId", SOURCE)
|
||||
self.assertIn('window.addEventListener("pagehide", releaseModbusLeaseBeacon)', SOURCE)
|
||||
self.assertIn('navigator.sendBeacon("/api/modbus/session/release", body)', SOURCE)
|
||||
self.assertEqual(7, SOURCE.count("session_id: modbusSessionId()"))
|
||||
|
||||
def test_manual_stop_and_restart_toggles_are_not_exposed(self):
|
||||
session_panel = re.search(
|
||||
r"<summary>\$\{esc\(t\(\"Session / Port Control\"\)\)\}</summary>(?P<body>.*?)</details>",
|
||||
SOURCE,
|
||||
re.S,
|
||||
)
|
||||
self.assertIsNotNone(session_panel)
|
||||
body = session_panel.group("body")
|
||||
self.assertNotIn("__modbusSetToggle('stopItscreen'", body)
|
||||
self.assertNotIn("__modbusSetToggle('restartItscreen'", body)
|
||||
self.assertIn("automatically pauses production polling", body)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import modbus_backend as mb
|
||||
|
||||
|
||||
class ModbusSessionLeaseTest(unittest.TestCase):
|
||||
def test_live_lease_is_not_expired_only_because_worker_pid_changed(self):
|
||||
lease = {
|
||||
"expires_at": time.time() + 60,
|
||||
"process_id": os.getpid() + 1000,
|
||||
}
|
||||
|
||||
self.assertFalse(mb.lock_expired(lease))
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.run_dir = Path(self.temp.name)
|
||||
self.patches = [
|
||||
mock.patch.object(mb, "MODBUS_RUN_DIR", str(self.run_dir)),
|
||||
mock.patch.object(mb, "MODBUS_AUDIT_LOG", str(self.run_dir / "audit.log")),
|
||||
mock.patch.object(mb, "append_audit"),
|
||||
]
|
||||
for patcher in self.patches:
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
mb._ACTIVE_PORT_OPERATIONS.clear()
|
||||
self.addCleanup(mb._ACTIVE_PORT_OPERATIONS.clear)
|
||||
|
||||
def test_production_port_always_stops_and_restores_client(self):
|
||||
status = {"exists": True, "locked": False, "itscreen_running": True}
|
||||
with mock.patch.object(mb, "port_status", return_value=status), \
|
||||
mock.patch.object(mb, "busy_processes", return_value=[]), \
|
||||
mock.patch.object(mb, "stop_itscreen_service_wait", return_value={"ok": True}) as stop, \
|
||||
mock.patch.object(mb, "start_itscreen_service_wait", return_value={"ok": True}) as start, \
|
||||
mock.patch.object(mb, "systemctl_is_active", return_value=False):
|
||||
acquired = mb.acquire_session("/dev/ttyS3", False)
|
||||
stop.assert_called_once()
|
||||
self.assertTrue(acquired["lock"]["restore_itscreen"])
|
||||
self.assertTrue(acquired["lock"]["itscreen_stopped"])
|
||||
released = mb.release_session(
|
||||
"/dev/ttyS3",
|
||||
False,
|
||||
session_id=acquired["lock"]["session_id"],
|
||||
)
|
||||
start.assert_called_once()
|
||||
self.assertTrue(released["itscreen_restarted"])
|
||||
self.assertFalse(Path(mb.lock_path_for_port("/dev/ttyS3")).exists())
|
||||
|
||||
def test_legacy_or_expired_marker_is_reclaimed_and_service_restored(self):
|
||||
path = Path(mb.lock_path_for_port("/dev/ttyS3"))
|
||||
path.write_text(json.dumps({
|
||||
"port": "/dev/ttyS3",
|
||||
"owner": "modbus_tool",
|
||||
"itscreen_was_running": True,
|
||||
"restore_itscreen": True,
|
||||
}))
|
||||
with mock.patch.object(mb, "systemctl_is_active", return_value=False), \
|
||||
mock.patch.object(mb, "start_itscreen_service_wait", return_value={"ok": True}) as start:
|
||||
self.assertTrue(mb.recover_expired_session("/dev/ttyS3"))
|
||||
start.assert_called_once()
|
||||
self.assertFalse(path.exists())
|
||||
|
||||
def test_active_backend_operation_cannot_be_reaped_or_released_by_browser(self):
|
||||
lease = mb.acquire_lock("/dev/ttyS3", {"owner": "modbus_tool"})
|
||||
mb._begin_port_operation("/dev/ttyS3", "job-1")
|
||||
with mock.patch.object(mb, "lock_expired", return_value=True):
|
||||
self.assertFalse(mb.recover_expired_session("/dev/ttyS3"))
|
||||
with self.assertRaises(mb.ApiError):
|
||||
mb.release_session("/dev/ttyS3", True, session_id=lease["session_id"])
|
||||
self.assertTrue(Path(mb.lock_path_for_port("/dev/ttyS3")).exists())
|
||||
mb._end_port_operation("/dev/ttyS3", "job-1")
|
||||
|
||||
def test_only_browser_holding_session_id_can_use_port(self):
|
||||
lease = mb.acquire_lock("/dev/ttyS3", {"owner": "modbus_tool"})
|
||||
self.assertEqual(
|
||||
lease["session_id"],
|
||||
mb.assert_session_owner("/dev/ttyS3", lease["session_id"])["session_id"],
|
||||
)
|
||||
with self.assertRaises(mb.ApiError):
|
||||
mb.assert_session_owner("/dev/ttyS3", "another-session")
|
||||
|
||||
def test_discovery_releases_lease_after_worker_finishes(self):
|
||||
lease = mb.acquire_lock("/dev/ttyS3", {"owner": "modbus_tool"})
|
||||
with mock.patch.object(mb, "discover_devices", return_value={"devices": []}), \
|
||||
mock.patch.object(mb, "release_session", return_value={"ok": True}) as release:
|
||||
job = mb.start_discovery(
|
||||
port="/dev/ttyS3",
|
||||
slave_range=[1, 1],
|
||||
baudrates=[9600],
|
||||
parities=["none"],
|
||||
)
|
||||
deadline = time.time() + 2
|
||||
current = job
|
||||
while current.get("state") == "running" and time.time() < deadline:
|
||||
time.sleep(0.01)
|
||||
current = mb.get_discovery_job(job["job_id"])
|
||||
self.assertEqual("completed", current["state"])
|
||||
release.assert_called_once_with(
|
||||
"/dev/ttyS3",
|
||||
True,
|
||||
source="ui",
|
||||
owner="modbus_tool",
|
||||
session_id=lease["session_id"],
|
||||
internal=True,
|
||||
)
|
||||
self.assertFalse(mb._port_operation_active("/dev/ttyS3"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"sng_modbus_backend", Path(__file__).with_name("modbus_backend.py")
|
||||
)
|
||||
modbus = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(modbus)
|
||||
modbus.MODBUS_PROFILES_DIR = str(Path(__file__).resolve().parents[1] / "modbus_profiles")
|
||||
|
||||
|
||||
class SngDetectionProfileTest(unittest.TestCase):
|
||||
def test_sng_variant_precedes_generic_nano_and_requires_two_confirmations(self):
|
||||
profiles = modbus.load_profiles()
|
||||
families = [profile["family"] for profile in profiles]
|
||||
self.assertLess(families.index("iomx_sng_500"), families.index("exbd_nano"))
|
||||
|
||||
profile = next(item for item in profiles if item["family"] == "iomx_sng_500")
|
||||
self.assertEqual("exbd nano", profile["detection"]["family_register"]["match"][0])
|
||||
self.assertEqual(
|
||||
[(102, 2, "input"), (34, 1, "holding")],
|
||||
[
|
||||
(item["address"], item["count"], item["type"])
|
||||
for item in profile["confirmation_registers"]
|
||||
],
|
||||
)
|
||||
|
||||
def test_generic_nano_remains_available_as_fallback(self):
|
||||
profile = next(item for item in modbus.load_profiles() if item["family"] == "exbd_nano")
|
||||
self.assertFalse(profile["confirmation_registers"])
|
||||
self.assertIn("nano", profile["detection"]["family_register"]["match"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -92,6 +92,9 @@
|
|||
"Host / IP": "Хост / IP",
|
||||
"Updated": "Обновлено",
|
||||
"Session": "Сессия",
|
||||
"Console automatically pauses production polling only while a Modbus operation owns the port, then restores it.": "Console автоматически приостанавливает рабочий опрос только на время владения Modbus-портом и затем восстанавливает его.",
|
||||
"Modbus maintenance session expired; production polling was restored.": "Срок служебной Modbus-сессии истёк; рабочий опрос восстановлен.",
|
||||
"This Modbus port is owned by another maintenance session. Wait for its lease to expire.": "Этот Modbus-порт занят другой служебной сессией. Дождитесь окончания срока её lease.",
|
||||
"Primary navigation": "Основная навигация",
|
||||
"Stopping it-screen service before Modbus session": "Остановка сервиса it-screen перед Modbus-сеансом",
|
||||
"Starting it-screen service after Modbus session": "Запуск сервиса it-screen после Modbus-сеанса",
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@
|
|||
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
|
||||
{ mode: "custom", label: "Custom", host: "" }
|
||||
];
|
||||
const UI_VERSION = "V 3.1.20";
|
||||
const UI_VERSION = "V 3.1.25";
|
||||
const ITSCREEN_LOG_INITIAL_LINES = 50;
|
||||
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
|
||||
const ITSCREEN_LOG_BATCH_MS = 250;
|
||||
|
|
@ -1055,6 +1055,8 @@
|
|||
|
||||
function setAuthRequired(message) {
|
||||
resetSessionRequests();
|
||||
stopModbusLeaseHeartbeat();
|
||||
state.modbus.session = null;
|
||||
state.auth.loading = false;
|
||||
state.auth.authenticated = false;
|
||||
state.auth.busy = false;
|
||||
|
|
@ -3973,16 +3975,98 @@
|
|||
});
|
||||
}
|
||||
|
||||
let modbusLeaseHeartbeatTimer = null;
|
||||
let modbusLeaseHeartbeatBusy = false;
|
||||
|
||||
function stopModbusLeaseHeartbeat() {
|
||||
if (modbusLeaseHeartbeatTimer !== null) {
|
||||
window.clearInterval(modbusLeaseHeartbeatTimer);
|
||||
modbusLeaseHeartbeatTimer = null;
|
||||
}
|
||||
modbusLeaseHeartbeatBusy = false;
|
||||
}
|
||||
|
||||
async function renewModbusLease() {
|
||||
const log = modbusState();
|
||||
const sessionId = textValue(log.session && log.session.session_id, "");
|
||||
if (!sessionId || modbusLeaseHeartbeatBusy) return;
|
||||
modbusLeaseHeartbeatBusy = true;
|
||||
try {
|
||||
const payload = await fetchJson("/api/modbus/session/heartbeat", {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ port: log.port, session_id: sessionId })
|
||||
});
|
||||
if (textValue(log.session && log.session.session_id, "") === sessionId) {
|
||||
log.session = payload.lock || log.session;
|
||||
}
|
||||
} catch (error) {
|
||||
if (textValue(log.session && log.session.session_id, "") === sessionId) {
|
||||
log.session = null;
|
||||
stopModbusLeaseHeartbeat();
|
||||
appendModbusLog(t("Modbus maintenance session expired; production polling was restored."), "warn");
|
||||
loadModbus({ force: true, maxAgeMs: 0 }).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
modbusLeaseHeartbeatBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startModbusLeaseHeartbeat() {
|
||||
stopModbusLeaseHeartbeat();
|
||||
if (!textValue(modbusState().session && modbusState().session.session_id, "")) return;
|
||||
modbusLeaseHeartbeatTimer = window.setInterval(() => renewModbusLease().catch(() => {}), 30000);
|
||||
}
|
||||
|
||||
function modbusSessionId() {
|
||||
return textValue(modbusState().session && modbusState().session.session_id, "");
|
||||
}
|
||||
|
||||
async function releaseModbusLeaseSilently() {
|
||||
const log = modbusState();
|
||||
const sessionId = textValue(log.session && log.session.session_id, "");
|
||||
if (!sessionId) return true;
|
||||
try {
|
||||
await fetchJson("/api/modbus/session/release", {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ port: log.port, restart_itscreen: true, session_id: sessionId })
|
||||
});
|
||||
log.session = null;
|
||||
stopModbusLeaseHeartbeat();
|
||||
return true;
|
||||
} catch (error) {
|
||||
// An active backend operation owns restoration and releases in finally.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function releaseModbusLeaseBeacon() {
|
||||
const log = modbusState();
|
||||
const sessionId = textValue(log.session && log.session.session_id, "");
|
||||
if (!sessionId || !navigator.sendBeacon) return;
|
||||
const body = new Blob([JSON.stringify({
|
||||
port: log.port,
|
||||
restart_itscreen: true,
|
||||
session_id: sessionId
|
||||
})], { type: "application/json" });
|
||||
navigator.sendBeacon("/api/modbus/session/release", body);
|
||||
}
|
||||
|
||||
async function modbusEnsureSession(options = {}) {
|
||||
const log = modbusState();
|
||||
const portInfo = modbusSelectedPortStatus() || {};
|
||||
const stopItscreen = options.stopItscreen !== undefined ? !!options.stopItscreen : !!log.stopItscreen;
|
||||
const confirmItscreenStop = options.confirmItscreenStop !== undefined ? !!options.confirmItscreenStop : !!stopItscreen;
|
||||
const actionLabel = textValue(options.actionLabel, t("Modbus operation"));
|
||||
let effectiveStopItscreen = stopItscreen;
|
||||
if (log.session || portInfo.locked) {
|
||||
if (log.session) {
|
||||
return true;
|
||||
}
|
||||
if (portInfo.locked) {
|
||||
throw new Error(t("This Modbus port is owned by another maintenance session. Wait for its lease to expire."));
|
||||
}
|
||||
if (confirmItscreenStop && stopItscreen) {
|
||||
const portsPayload = await fetchJson("/api/modbus/ports", { cache: "no-store" });
|
||||
log.ports = Array.isArray(portsPayload.ports) ? portsPayload.ports : [];
|
||||
|
|
@ -3994,26 +4078,16 @@
|
|||
appendModbusLog(t("{action} was cancelled because it-screen is still running.", { action: actionLabel }), "warn");
|
||||
return false;
|
||||
}
|
||||
const stopPayload = await fetchJson("/api/itscreen/service/stop", {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: "{}"
|
||||
});
|
||||
appendModbusLog(translateUiText(stopPayload.message || t("Service stopped")), "warn");
|
||||
showToast("warn", t("it-screen service was stopped temporarily for Modbus scanning and writing."));
|
||||
effectiveStopItscreen = false;
|
||||
await loadItscreenInitialData({ force: true, maxAgeMs: 0 });
|
||||
await loadModbus({ force: true, maxAgeMs: 0 });
|
||||
}
|
||||
}
|
||||
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: effectiveStopItscreen })
|
||||
body: JSON.stringify({ port: log.port, stop_itscreen: stopItscreen })
|
||||
});
|
||||
log.session = payload.lock || null;
|
||||
startModbusLeaseHeartbeat();
|
||||
ingestModbusPayload(payload);
|
||||
appendModbusLog(translateUiText(payload.message || t("Port acquired")), "success");
|
||||
if (payload.itscreen_stopped) {
|
||||
|
|
@ -4024,41 +4098,6 @@
|
|||
return true;
|
||||
}
|
||||
|
||||
async function modbusStopItscreenIfNeeded(actionLabel) {
|
||||
const log = modbusState();
|
||||
if (!String(log.port || "").endsWith("ttyS3")) return true;
|
||||
const portsPayload = await fetchJson("/api/modbus/ports", { cache: "no-store" });
|
||||
log.ports = Array.isArray(portsPayload.ports) ? portsPayload.ports : [];
|
||||
const currentPortInfo = modbusSelectedPortStatus() || {};
|
||||
if (!currentPortInfo.itscreen_running) return true;
|
||||
const confirmed = window.confirm(t("it-screen is running on this serial path. {action} will stop it-screen temporarily because scan and write results are unreliable while it-screen is active.\n\nContinue?", { action: actionLabel }));
|
||||
if (!confirmed) {
|
||||
appendModbusLog(t("{action} was cancelled because it-screen is still running.", { action: actionLabel }), "warn");
|
||||
return false;
|
||||
}
|
||||
const stopPayload = await fetchJson("/api/itscreen/service/stop", {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: "{}"
|
||||
});
|
||||
appendModbusLog(translateUiText(stopPayload.message || t("Service stopped")), "warn");
|
||||
showToast("warn", t("it-screen service was stopped temporarily for Modbus scanning and writing."));
|
||||
await loadItscreenInitialData({ force: true, maxAgeMs: 0 });
|
||||
const deadline = Date.now() + 15000;
|
||||
while (Date.now() < deadline) {
|
||||
const verifyPortsPayload = await fetchJson("/api/modbus/ports", { cache: "no-store" });
|
||||
log.ports = Array.isArray(verifyPortsPayload.ports) ? verifyPortsPayload.ports : [];
|
||||
const verifyPortInfo = modbusSelectedPortStatus() || {};
|
||||
if (!verifyPortInfo.itscreen_running) {
|
||||
await loadModbus({ force: true, maxAgeMs: 0 });
|
||||
return true;
|
||||
}
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 350));
|
||||
}
|
||||
throw new Error(t("it-screen did not stop in time for {action}.", { action: actionLabel }));
|
||||
}
|
||||
|
||||
function renderModbusLogPanel() {
|
||||
const entries = modbusState().operationLog || [];
|
||||
return `
|
||||
|
|
@ -4703,14 +4742,7 @@
|
|||
<div class="key">${esc(t("Busy process"))}</div><div>${esc((portInfo.busy_process || []).join(", ") || t("None"))}</div>
|
||||
<div class="key">${esc(t("Lock owner"))}</div><div>${esc(textValue(portInfo.lock_owner, t("None")))}</div>
|
||||
</div>
|
||||
<label class="checkboxRow">
|
||||
<input type="checkbox" ${log.stopItscreen ? "checked" : ""} onchange="window.__modbusSetToggle('stopItscreen', this.checked)">
|
||||
<span>${esc(t("Stop it-screen while working with Modbus"))}</span>
|
||||
</label>
|
||||
<label class="checkboxRow">
|
||||
<input type="checkbox" ${log.restartItscreen ? "checked" : ""} onchange="window.__modbusSetToggle('restartItscreen', this.checked)">
|
||||
<span>${esc(t("Restart it-screen on release"))}</span>
|
||||
</label>
|
||||
<div class="formHint">${esc(t("Console automatically pauses production polling only while a Modbus operation owns the port, then restores it."))}</div>
|
||||
<div class="actionRow">
|
||||
<button class="actionBtn" type="button" ${modbusBusy("acquire") ? "disabled" : ""} onclick="window.__modbusAcquire()">${esc(modbusBusy("acquire") ? t("Acquiring...") : t("Acquire port"))}</button>
|
||||
<button class="actionBtn secondary" type="button" ${modbusBusy("release") ? "disabled" : ""} onclick="window.__modbusRelease()">${esc(modbusBusy("release") ? t("Releasing...") : t("Release port"))}</button>
|
||||
|
|
@ -6203,6 +6235,7 @@
|
|||
body: JSON.stringify({ port: log.port, stop_itscreen: !!log.stopItscreen })
|
||||
});
|
||||
log.session = payload.lock || null;
|
||||
startModbusLeaseHeartbeat();
|
||||
ingestModbusPayload(payload);
|
||||
appendModbusLog(translateUiText(payload.message || t("Port acquired")), "success");
|
||||
if (payload.itscreen_stopped) {
|
||||
|
|
@ -6231,9 +6264,14 @@
|
|||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ port: log.port, restart_itscreen: !!log.restartItscreen })
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
restart_itscreen: true,
|
||||
session_id: textValue(log.session && log.session.session_id, "")
|
||||
})
|
||||
});
|
||||
log.session = null;
|
||||
stopModbusLeaseHeartbeat();
|
||||
ingestModbusPayload(payload);
|
||||
appendModbusLog(translateUiText(payload.message || t("Port released")), "success");
|
||||
if (payload.itscreen_restarted) {
|
||||
|
|
@ -6271,10 +6309,8 @@
|
|||
if (state.activeTab === "modbus") renderActiveTab();
|
||||
try {
|
||||
const actionLabel = mode === "deep" ? t("Deep scan") : t("Quick scan");
|
||||
const canProceed = await modbusStopItscreenIfNeeded(actionLabel);
|
||||
if (!canProceed) return;
|
||||
appendModbusLog(mode === "deep" ? t("Deep scan started") : t("Quick scan started"), "info");
|
||||
const acquired = await modbusEnsureSession({ actionLabel, stopItscreen: false, confirmItscreenStop: false });
|
||||
const acquired = await modbusEnsureSession({ actionLabel, stopItscreen: true, confirmItscreenStop: true });
|
||||
if (!acquired) return;
|
||||
const payload = await fetchJson("/api/modbus/discover", {
|
||||
method: "POST",
|
||||
|
|
@ -6282,6 +6318,7 @@
|
|||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
session_id: modbusSessionId(),
|
||||
slave_range: [slaveFrom, slaveTo],
|
||||
baudrates,
|
||||
parities,
|
||||
|
|
@ -6303,10 +6340,14 @@
|
|||
log.discovery.total = Number(progress.total) || 0;
|
||||
log.discovery.currentSlave = Number(progress.current_slave) || null;
|
||||
if (log.discovery.state === "completed") {
|
||||
log.session = null;
|
||||
stopModbusLeaseHeartbeat();
|
||||
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") {
|
||||
log.session = null;
|
||||
stopModbusLeaseHeartbeat();
|
||||
throw new Error(statusPayload.error || t("Discovery failed"));
|
||||
}
|
||||
if (state.activeTab === "modbus") renderActiveTab();
|
||||
|
|
@ -6318,11 +6359,13 @@
|
|||
log.discovery.message = log.error;
|
||||
appendModbusLog(log.error, "error");
|
||||
showToast("error", log.error);
|
||||
if (!log.discovery.jobId) await releaseModbusLeaseSilently();
|
||||
} finally {
|
||||
if (log.discovery.state === "completed" && !log.error) {
|
||||
log.discovery.message = t("Scan completed");
|
||||
}
|
||||
log.busyAction = "";
|
||||
await loadModbus({ force: true, maxAgeMs: 0 }).catch(() => {});
|
||||
if (state.activeTab === "modbus") renderActiveTab();
|
||||
}
|
||||
};
|
||||
|
|
@ -6358,13 +6401,15 @@
|
|||
appendModbusLog(log.readConfigMessage, "warn");
|
||||
return;
|
||||
}
|
||||
await modbusEnsureSession({ stopItscreen: false });
|
||||
const acquired = await modbusEnsureSession({ actionLabel: t("Configuration read"), stopItscreen: true, confirmItscreenStop: true });
|
||||
if (!acquired) return;
|
||||
const payload = await fetchJson("/api/modbus/read-config", {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
session_id: modbusSessionId(),
|
||||
family,
|
||||
slave: current.slave,
|
||||
baud: current.baud,
|
||||
|
|
@ -6450,6 +6495,7 @@
|
|||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
session_id: modbusSessionId(),
|
||||
family: modbusEditorFamily(),
|
||||
current: {
|
||||
slave: Number(current.slave),
|
||||
|
|
@ -6514,6 +6560,7 @@
|
|||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
session_id: modbusSessionId(),
|
||||
family: modbusEditorFamily(),
|
||||
slave: Number(log.writeForm.slave || current.slave),
|
||||
baud: Number(log.writeForm.baud || current.baud),
|
||||
|
|
@ -6550,6 +6597,7 @@
|
|||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
session_id: modbusSessionId(),
|
||||
family: modbusEditorFamily(),
|
||||
slave: Number(log.writeForm.slave || current.slave),
|
||||
baud: Number(log.writeForm.baud || current.baud),
|
||||
|
|
@ -6584,6 +6632,7 @@
|
|||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
session_id: modbusSessionId(),
|
||||
slave: Number(current.slave),
|
||||
baud: Number(current.baud),
|
||||
relay: Number(log.iomx04Control && log.iomx04Control.relay || 1),
|
||||
|
|
@ -6616,6 +6665,7 @@
|
|||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
port: log.port,
|
||||
session_id: modbusSessionId(),
|
||||
slave: Number(current.slave),
|
||||
baud: Number(current.baud),
|
||||
relay: Number(log.iomx04Control && log.iomx04Control.relay || 1),
|
||||
|
|
@ -6854,6 +6904,7 @@
|
|||
state.auth.busy = true;
|
||||
syncActionMenu();
|
||||
try {
|
||||
await releaseModbusLeaseSilently();
|
||||
await fetchJson("/api/auth/logout", {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
|
|
@ -6876,6 +6927,9 @@
|
|||
cancelItscreenRequest();
|
||||
deactivateItscreenLogs();
|
||||
}
|
||||
if (state.activeTab === "modbus" && nextTab !== "modbus") {
|
||||
await releaseModbusLeaseSilently();
|
||||
}
|
||||
state.activeTab = nextTab;
|
||||
await loadForActiveTab();
|
||||
if (state.activeTab === "tscreen") {
|
||||
|
|
@ -6958,6 +7012,8 @@
|
|||
}
|
||||
});
|
||||
|
||||
window.addEventListener("pagehide", releaseModbusLeaseBeacon);
|
||||
|
||||
state.language = loadLanguagePreference();
|
||||
applyStaticTranslations();
|
||||
applyLanguage(state.language);
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@
|
|||
} catch (error) {}
|
||||
})();
|
||||
</script>
|
||||
<link rel="stylesheet" href="/console.css?v=3.1.23&rev=edge-runtime-profile-1">
|
||||
<link rel="stylesheet" href="/console.css?v=3.1.25&rev=edge-runtime-profile-1">
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
</main>
|
||||
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
|
||||
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
|
||||
<script src="/console.i18n.js?v=3.1.23&rev=edge-runtime-profile-1"></script>
|
||||
<script src="/console.js?v=3.1.23&rev=edge-runtime-profile-1"></script>
|
||||
<script src="/console.i18n.js?v=3.1.25&rev=edge-runtime-profile-1"></script>
|
||||
<script src="/console.js?v=3.1.25&rev=edge-runtime-profile-1"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,97 @@
|
|||
{
|
||||
"family": "iomx_sng_500",
|
||||
"title": "IOMATEX IOMX-SNG-500",
|
||||
"display_name": "IOMATEX IOMX-SNG-500",
|
||||
"transport": {
|
||||
"protocol": "modbus_rtu",
|
||||
"default_port": "/dev/ttyS3",
|
||||
"default_baud": 9600,
|
||||
"default_parity": "none",
|
||||
"default_databits": 8,
|
||||
"default_stopbits": 1,
|
||||
"scan_baud": [9600],
|
||||
"scan_parity": ["none"],
|
||||
"zero_based": false
|
||||
},
|
||||
"detection": {
|
||||
"type": "string",
|
||||
"function": "input",
|
||||
"start": 201,
|
||||
"count": 20,
|
||||
"encoding": "ascii",
|
||||
"cleanup": "collapse_spaces",
|
||||
"label": "201..220 (input)",
|
||||
"match": ["ExBd NANO"],
|
||||
"confirm": [
|
||||
{
|
||||
"address": 102,
|
||||
"count": 2,
|
||||
"type": "input",
|
||||
"label": "SNG state/error (102..103 input)"
|
||||
},
|
||||
{
|
||||
"address": 34,
|
||||
"count": 1,
|
||||
"type": "holding",
|
||||
"label": "SNG power (34 holding)"
|
||||
}
|
||||
],
|
||||
"empty_values": ["", "0", "65535"],
|
||||
"timeout_quick": 1.8,
|
||||
"timeout_deep": 3.2
|
||||
},
|
||||
"registers": {
|
||||
"test_read": {
|
||||
"address": 102,
|
||||
"count": 2,
|
||||
"type": "input"
|
||||
},
|
||||
"slave_id": {
|
||||
"address": 253,
|
||||
"count": 1,
|
||||
"type": "holding",
|
||||
"rw": true
|
||||
},
|
||||
"comm_profile": {
|
||||
"address": 255,
|
||||
"count": 1,
|
||||
"type": "holding",
|
||||
"rw": true
|
||||
}
|
||||
},
|
||||
"summary_registers": {
|
||||
"model_string": {
|
||||
"address": 201,
|
||||
"count": 20,
|
||||
"type": "input",
|
||||
"decode_mode": "uint16",
|
||||
"value_format": "ascii",
|
||||
"cleanup": "collapse_spaces"
|
||||
},
|
||||
"state": {
|
||||
"address": 102,
|
||||
"count": 1,
|
||||
"type": "input",
|
||||
"decode_mode": "uint16"
|
||||
},
|
||||
"errors": {
|
||||
"address": 103,
|
||||
"count": 1,
|
||||
"type": "input",
|
||||
"decode_mode": "uint16"
|
||||
},
|
||||
"power": {
|
||||
"address": 34,
|
||||
"count": 1,
|
||||
"type": "holding",
|
||||
"decode_mode": "uint16"
|
||||
}
|
||||
},
|
||||
"comm_profiles": [
|
||||
{ "register_value": 0, "baud": 1200, "parity": "none", "label": "1200" },
|
||||
{ "register_value": 1, "baud": 2400, "parity": "none", "label": "2400" },
|
||||
{ "register_value": 2, "baud": 4800, "parity": "none", "label": "4800" },
|
||||
{ "register_value": 3, "baud": 9600, "parity": "none", "label": "9600" },
|
||||
{ "register_value": 4, "baud": 19200, "parity": "none", "label": "19200" }
|
||||
]
|
||||
}
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"version": "3.1.23"
|
||||
"version": "3.1.25"
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue