From b98890f5ec4c8b212c8e79e3cc8929a2a650960a Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Tue, 7 Apr 2026 17:31:26 +0400 Subject: [PATCH] modbus rev --- stage_itscreen/stage_itscreen_install.sh | 3 +- stage_ui/console_core/backend/app.py | 2 +- .../console_core/backend/modbus_backend.py | 464 ++++++++++++++---- stage_ui/console_core/frontend/console.css | 7 +- stage_ui/console_core/frontend/console.js | 284 +++++++++-- .../iomx_nano_exbd_08_16_12.json | 23 +- 6 files changed, 642 insertions(+), 141 deletions(-) diff --git a/stage_itscreen/stage_itscreen_install.sh b/stage_itscreen/stage_itscreen_install.sh index cbda979..9126cf3 100755 --- a/stage_itscreen/stage_itscreen_install.sh +++ b/stage_itscreen/stage_itscreen_install.sh @@ -655,8 +655,7 @@ 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' +# Monitor presence is not required for startup; always attempt the dedicated X11 launch flow, including headless mode. 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 db2ba1e..eaf5fad 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -2389,7 +2389,7 @@ class Handler(BaseHTTPRequestHandler): self.send_json(modbus_write_device_config( port=str(payload.get("port", "")), family=str(payload.get("family", "")), - baudrate=int(payload.get("baudrate", 9600)), + baudrate=int((payload.get("current") or {}).get("baud") or payload.get("baudrate", 9600)), current=payload.get("current") or {}, target=payload.get("target") or {}, strategy=str(payload.get("strategy", "both")), diff --git a/stage_ui/console_core/backend/modbus_backend.py b/stage_ui/console_core/backend/modbus_backend.py index 5683ba5..5666f50 100644 --- a/stage_ui/console_core/backend/modbus_backend.py +++ b/stage_ui/console_core/backend/modbus_backend.py @@ -19,6 +19,7 @@ ITSCREEN_SERVICE_UNIT = "itscreen-x11.service" DEFAULT_DISCOVER_TIMEOUT = 6.0 DISCOVERY_JOBS: Dict[str, Dict[str, Any]] = {} DISCOVERY_JOBS_LOCK = threading.Lock() +SID_WRITE_ACK_OPTIONAL_FAMILIES = {"iomx_nano_exbd_08_16_12"} PORT_GLOBS = ( "/dev/ttyS*", @@ -162,7 +163,11 @@ def parse_mbpoll_values(stdout: str) -> List[Dict[str, Any]]: decoded = int(raw_value, 0) except Exception: try: - decoded = float(raw_value) + token_match = re.match(r"^-?(?:0[xX][0-9a-fA-F]+|\d+)", raw_value) + if token_match: + decoded = int(token_match.group(0), 0) + else: + decoded = float(raw_value) except Exception: decoded = raw_value values.append({ @@ -372,6 +377,105 @@ def read_profile_register( return result +def build_probe_diagnostics( + *, + profile: Dict[str, Any], + family: str, + port: str, + requested_slave: int, + requested_baud: int, + requested_parity: str, + expected_current: Optional[Dict[str, Any]], + test_result: Dict[str, Any], + slave_result: Optional[Dict[str, Any]], + comm_result: Optional[Dict[str, Any]], + current_slave_value: int, + current_baud_value: int, + current_parity_value: str, + decoded_comm: Dict[str, Any], +) -> Dict[str, Any]: + transport = profile["transport"] + registers = profile.get("registers") or {} + diagnostics: Dict[str, Any] = { + "family": family, + "port": port, + "addressing_mode": "zero-based" if bool(transport.get("zero_based", True)) else "one-based", + "selected_current": { + "slave": requested_slave, + "baud": requested_baud, + "parity": requested_parity, + }, + "registers": { + name: { + "address": int(data["address"]), + "count": int(data["count"]), + "type": str(data["type"]), + } + for name, data in registers.items() + }, + "reads": { + "test_read": { + "ok": bool(test_result.get("ok")), + "raw": [item.get("raw") for item in test_result.get("values", [])], + "decoded": [item.get("value") for item in test_result.get("values", [])], + }, + "slave_id": { + "ok": bool(slave_result.get("ok")) if slave_result else False, + "raw": [item.get("raw") for item in (slave_result or {}).get("values", [])], + "decoded": [item.get("value") for item in (slave_result or {}).get("values", [])], + } if slave_result is not None else None, + "comm_profile": { + "ok": bool(comm_result.get("ok")) if comm_result else False, + "raw": [item.get("raw") for item in (comm_result or {}).get("values", [])], + "decoded": { + "register_value": decoded_comm.get("register_value"), + "baud": decoded_comm.get("baud"), + "parity": decoded_comm.get("parity"), + "decoded": bool(decoded_comm.get("decoded")), + }, + } if comm_result is not None else None, + }, + "decoded_current": { + "slave": current_slave_value, + "baud": current_baud_value, + "parity": current_parity_value, + }, + "expected_current": None, + "mismatch_reasons": [], + "result": "pending", + } + if expected_current: + expected_slave = int(expected_current.get("slave", requested_slave)) + expected_baud = int(expected_current.get("baud", requested_baud)) + expected_parity = str(expected_current.get("parity", requested_parity)) + diagnostics["expected_current"] = { + "slave": expected_slave, + "baud": expected_baud, + "parity": expected_parity, + } + mismatch_reasons: List[str] = [] + if current_slave_value != expected_slave: + mismatch_reasons.append( + f"decoded slave_id mismatch: expected {expected_slave}, got {current_slave_value}" + ) + if comm_result is not None and bool(comm_result.get("ok")): + if decoded_comm.get("decoded"): + if current_baud_value != expected_baud: + mismatch_reasons.append( + f"decoded baud mismatch: expected {expected_baud}, got {current_baud_value}" + ) + if current_parity_value != expected_parity: + mismatch_reasons.append( + f"decoded parity mismatch: expected {expected_parity}, got {current_parity_value}" + ) + else: + mismatch_reasons.append( + "comm_profile read succeeded but could not be decoded to baud/parity business values" + ) + diagnostics["mismatch_reasons"] = mismatch_reasons + return diagnostics + + def device_probe( *, port: str, @@ -381,8 +485,12 @@ def device_probe( parity: str, timeout: float = DEFAULT_DISCOVER_TIMEOUT, retries: int = 1, + expected_current: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: profile = get_profile(family) + requested_slave = int(slave) + requested_baud = int(baud) + requested_parity = str(parity) test_result = read_profile_register( profile=profile, port=port, @@ -418,25 +526,62 @@ def device_probe( 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"))) + current_slave_value = int(slave_value) if slave_value is not None else requested_slave + current_baud_value = decoded_comm["baud"] if decoded_comm["decoded"] else requested_baud + current_parity_value = decoded_comm["parity"] if decoded_comm["decoded"] else requested_parity + diagnostics = build_probe_diagnostics( + profile=profile, + family=family, + port=port, + requested_slave=requested_slave, + requested_baud=requested_baud, + requested_parity=requested_parity, + expected_current=expected_current, + test_result=test_result, + slave_result=slave_result, + comm_result=comm_result, + current_slave_value=current_slave_value, + current_baud_value=current_baud_value, + current_parity_value=current_parity_value, + decoded_comm=decoded_comm, + ) + + comm_ok = bool(test_result.get("ok")) and (slave_result is None or bool(slave_result.get("ok"))) + mismatch_reasons = diagnostics.get("mismatch_reasons") or [] + ok = comm_ok and not mismatch_reasons + diagnostics["result"] = "ok" if ok else ("mismatch" if mismatch_reasons else "communication_failed") + backend_log( + "modbus_device_probe", + family=family, + port=port, + addressing_mode=diagnostics.get("addressing_mode"), + selected_current=diagnostics.get("selected_current"), + expected_current=diagnostics.get("expected_current"), + decoded_current=diagnostics.get("decoded_current"), + registers=diagnostics.get("registers"), + reads=diagnostics.get("reads"), + mismatch_reasons=mismatch_reasons, + ok=ok, + result=diagnostics.get("result"), + ) return { "ok": ok, "family": family, "port": port, "requested": { - "slave": int(slave), - "baud": int(baud), - "parity": str(parity), + "slave": requested_slave, + "baud": requested_baud, + "parity": requested_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), + "slave": current_slave_value, + "baud": current_baud_value, + "parity": current_parity_value, }, "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, + "slave_id": current_slave_value, + "baud": current_baud_value, + "parity": current_parity_value, "comm_profile_register": comm_value, "comm_profile_decoded": decoded_comm["decoded"], "supports_serial_write": bool(profile.get("capabilities", {}).get("supports_serial_write")), @@ -455,6 +600,7 @@ def device_probe( "test_read": test_result, "slave_id": slave_result, "comm_profile": comm_result, + "precheck_diagnostics": diagnostics, }, } @@ -687,6 +833,7 @@ def profiles_payload() -> Dict[str, Any]: "title": item["title"], "display_name": item["display_name"], "transport": item["transport"], + "comm_profiles": item.get("comm_profiles") or [], "supports_serial_write": bool(item.get("capabilities", {}).get("supports_serial_write")), "supports_id_write": bool(item.get("capabilities", {}).get("supports_id_write")), } @@ -890,6 +1037,15 @@ def encode_comm_profile(profile: Dict[str, Any], baud: int, parity: str) -> Opti return None +def comm_profile_entry_by_register_value(profile: Dict[str, Any], register_value: Optional[int]) -> Optional[Dict[str, Any]]: + if register_value is None: + return None + for item in profile.get("comm_profiles") or []: + if int(item.get("register_value")) == int(register_value): + return item + return None + + def discover_devices( *, port: str, @@ -1249,17 +1405,24 @@ def write_device_config( profile = get_profile(family) transport = profile["transport"] registers = profile["registers"] - strategy_value = str(strategy or "both").strip().lower() + strategy_value = str(strategy or "id").strip().lower() + if strategy_value == "baud": + strategy_value = "serial_only" + elif strategy_value == "id": + strategy_value = "id_only" + elif strategy_value == "baud_only": + strategy_value = "serial_only" 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")) + current_baud = int(current.get("baud") or baudrate or 9600) + write_baud = int(current_baud) + current_parity = str(current.get("parity") or "none").strip().lower() + target_comm_profile_value = target.get("comm_profile_value") + target_slave = int(target.get("slave", current_slave)) + target_baud = int(target.get("baud", current_baud)) + target_parity = str(target.get("parity", current_parity)) precheck = device_probe( port=port, @@ -1269,9 +1432,17 @@ def write_device_config( parity=str(current_parity), timeout=DEFAULT_DISCOVER_TIMEOUT, retries=1, + expected_current={ + "slave": current_slave, + "baud": current_baud, + "parity": current_parity, + }, ) operations = [{"level": "info", "message": "Pre-check started before write"}] if not precheck["ok"]: + diagnostics = ((precheck.get("debug") or {}).get("precheck_diagnostics") or {}) + mismatch_reasons = diagnostics.get("mismatch_reasons") or [] + failure_reason = mismatch_reasons[0] if mismatch_reasons else "Current device communication check failed" payload = { "ok": False, "stage": "precheck", @@ -1285,8 +1456,8 @@ def write_device_config( "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"}], + "recommended_next_step": failure_reason, + "operation_log": operations + [{"level": "error", "message": f"Pre-check failed; write not started: {failure_reason}"}], "debug": {"precheck": precheck["debug"]}, } append_audit({ @@ -1329,15 +1500,21 @@ def write_device_config( 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"): + if serial_changed and "comm_profile" not in registers: raise ApiError( - "Serial profile write is not configured for this family; complete comm_profiles mapping or use register explorer", + "Serial profile write is not configured for this family; complete comm_profile register mapping or use register explorer", 400, ) write_debug: Dict[str, Any] = {"precheck": precheck["debug"]} write_sent = False + id_write_ack_timed_out = False + serial_write_ack_timed_out = False if id_changed: + operations.append({ + "level": "info", + "message": f"strategy=id register={int(registers['slave_id']['address'])} ui_value={target_slave} register_value={target_slave}", + }) write_id = mbpoll_write_register( port=port, slave=current_slave, @@ -1352,43 +1529,61 @@ def write_device_config( 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) + error_type = str(write_id.get("error_type") or "") + ack_optional = family in SID_WRITE_ACK_OPTIONAL_FAMILIES and error_type == "timeout" + if ack_optional: + id_write_ack_timed_out = True + write_sent = True + operations.append({"level": "warn", "message": "Slave ID write response timed out"}) + operations.append({"level": "info", "message": "Post-write verification started after missing Slave ID write ACK"}) + time.sleep(0.8) + else: + 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 + else: + 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) + comm_value = int(target_comm_profile_value) if target_comm_profile_value is not None else 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) + comm_profile_entry = comm_profile_entry_by_register_value(profile, comm_value) or {} + if target_comm_profile_value is not None: + target_baud = int(comm_profile_entry.get("baud", target_baud)) + target_parity = str(comm_profile_entry.get("parity", target_parity)) + operations.append({ + "level": "info", + "message": f"strategy=baud register={int(registers['comm_profile']['address'])} ui_value={target_baud} register_value={comm_value}", + }) write_comm = mbpoll_write_register( port=port, slave=target_slave if id_changed else current_slave, @@ -1403,38 +1598,48 @@ def write_device_config( 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) + error_type = str(write_comm.get("error_type") or "") + ack_optional = family in SID_WRITE_ACK_OPTIONAL_FAMILIES and error_type == "timeout" + if ack_optional: + serial_write_ack_timed_out = True + write_sent = True + operations.append({"level": "warn", "message": "Baud write response timed out"}) + operations.append({"level": "info", "message": "Post-write verification started after missing baud write ACK"}) + time.sleep(1.0) + else: + 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 + else: + operations.append({"level": "success", "message": "Communication profile write command completed"}) + time.sleep(1.5) immediate_verify = device_probe( port=port, @@ -1446,17 +1651,80 @@ def write_device_config( retries=0, ) write_debug["immediate_target_verify"] = immediate_verify["debug"] + if id_write_ack_timed_out and id_changed: + old_slave_verify = device_probe( + port=port, + family=family, + slave=int(current_slave), + baud=int(write_baud), + parity=str(current_parity), + timeout=DEFAULT_DISCOVER_TIMEOUT, + retries=0, + ) + write_debug["old_slave_verify_after_timeout"] = old_slave_verify["debug"] + if old_slave_verify["ok"]: + operations.append({ + "level": "warn", + "message": f"Old SID {current_slave} still responds after missing write ACK", + }) + else: + operations.append({ + "level": "info", + "message": f"Old SID {current_slave} no longer responds after missing write ACK", + }) + if serial_write_ack_timed_out and serial_changed: + old_serial_verify = device_probe( + port=port, + family=family, + slave=int(target_slave if id_changed else current_slave), + baud=int(write_baud), + parity=str(current_parity), + timeout=DEFAULT_DISCOVER_TIMEOUT, + retries=0, + ) + write_debug["old_serial_verify_after_timeout"] = old_serial_verify["debug"] + if old_serial_verify["ok"]: + operations.append({ + "level": "warn", + "message": f"Old baud {current_baud} still responds after missing baud write ACK", + }) + else: + operations.append({ + "level": "info", + "message": f"Old baud {current_baud} no longer responds after missing baud write ACK", + }) if immediate_verify["ok"]: final_detected = { "slave": immediate_verify["current"]["slave"], "baud": immediate_verify["current"]["baud"], "parity": immediate_verify["current"]["parity"], } + success_message = f"Write verified. Device is now reachable at slave {final_detected['slave']}" + if id_write_ack_timed_out and id_changed: + operations.append({ + "level": "success", + "message": f"New SID {final_detected['slave']} responds; register {int(registers['slave_id']['address'])} matches requested Slave ID", + }) + operations.append({ + "level": "success", + "message": "Final result: SUCCESS (write applied despite missing ACK)", + }) + success_message = f"Write verified after missing ACK. Device is now reachable at slave {final_detected['slave']}" + if serial_write_ack_timed_out and serial_changed: + operations.append({ + "level": "success", + "message": f"New baud {final_detected['baud']} responds; register {int(registers['comm_profile']['address'])} matches requested profile value {comm_value}", + }) + operations.append({ + "level": "success", + "message": "Final result: SUCCESS (write applied despite missing ACK)", + }) + success_message = f"Write verified after missing ACK. Device is now reachable at slave {final_detected['slave']} with baud {final_detected['baud']}" payload = { "ok": True, "stage": "post_write_validation", "status": "verified_target", - "message": f"Write verified. Device is now reachable at slave {final_detected['slave']}", + "message": success_message, "write_baudrate": int(write_baud), "current_requested": current, "target_requested": target, @@ -1466,7 +1734,7 @@ def write_device_config( "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']}", + "recommended_next_step": success_message, "operation_log": operations + [{"level": "success", "message": f"Immediate verification succeeded on target slave {final_detected['slave']}"}], "debug": write_debug, } @@ -1484,6 +1752,24 @@ def write_device_config( }) return payload + if id_write_ack_timed_out and id_changed: + operations.append({ + "level": "error", + "message": f"New SID {target_slave} did not respond after missing write ACK", + }) + operations.append({ + "level": "error", + "message": "Final result: FAILED (post-write verification did not confirm the new Slave ID)", + }) + if serial_write_ack_timed_out and serial_changed: + operations.append({ + "level": "error", + "message": f"New baud {target_baud} did not respond after missing baud write ACK", + }) + operations.append({ + "level": "error", + "message": "Final result: FAILED (post-write verification did not confirm the new baud rate)", + }) operations.append({"level": "warn", "message": "Immediate target verification failed; rediscovery in progress"}) rediscovery = rediscover_after_write( port=port, diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index 11795f2..6bcb660 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -952,12 +952,15 @@ html[dir="rtl"] .itscreenLogsActions{ background:rgba(47,154,111,.1); } .compactActionRow{ + display:flex; + align-items:stretch; gap:8px; - flex-wrap:wrap; + flex-wrap:nowrap; } .compactBtn{ + flex:1 1 120px; padding:8px 10px; - min-height:auto; + min-height:36px; font-size:12px; } .statusBadge{ diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index 8d07def..cce023e 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -217,7 +217,7 @@ slave: "", baud: "9600", parity: "none", - strategy: "both" + strategy: "id" }, registerForm: { address: "0", @@ -2309,12 +2309,69 @@ return (modbusState().ports || []).find((item) => item.port === modbusState().port) || null; } - function modbusCanWrite() { + function modbusWriteCapabilities() { 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)); + const profile = modbusSelectedProfile() || {}; + return { + supportsIdWrite: !!((currentConfig && currentConfig.supports_id_write) || profile.supports_id_write), + supportsSerialWrite: !!((currentConfig && currentConfig.supports_serial_write) || profile.supports_serial_write) + }; + } + + function modbusDefaultWriteStrategy() { + const capabilities = modbusWriteCapabilities(); + if (capabilities.supportsIdWrite) return "id"; + if (capabilities.supportsSerialWrite) return "baud"; + return "id"; + } + + function normalizeModbusWriteStrategy(value) { + const raw = String(value || "").trim().toLowerCase(); + if (raw === "serial_only" || raw === "baud_only") return "baud"; + if (raw === "id_only") return "id"; + if (raw === "id" || raw === "baud") return raw; + return modbusDefaultWriteStrategy(); + } + + function modbusWriteStrategyForPayload(value) { + return normalizeModbusWriteStrategy(value); + } + + function sanitizePositiveIntegerInput(value) { + return String(value == null ? "" : value).replace(/[^\d]/g, ""); + } + + function modbusWriteSlaveValidationError(value) { + const normalized = sanitizePositiveIntegerInput(value); + if (!normalized) return t("New Slave ID must be a positive integer."); + if (!/^\d+$/.test(normalized)) return t("New Slave ID must be a positive integer."); + const parsed = Number(normalized); + if (!Number.isInteger(parsed) || parsed < 1 || parsed > 256) return t("New Slave ID must be an integer from 1 to 256."); + return ""; + } + + function modbusWriteValidationError() { + const log = modbusState(); + if (!(log.currentConfig && log.selectedDevice)) return ""; + const capabilities = modbusWriteCapabilities(); + const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); + if (strategy === "id") { + if (!capabilities.supportsIdWrite) return t("Slave ID write is not configured for this device family."); + return modbusWriteSlaveValidationError(log.writeForm.slave); + } + if (strategy === "baud" && !capabilities.supportsSerialWrite) { + return t("Baud rate write is not configured for this device family."); + } + return ""; + } + + function modbusCanWrite() { + const log = modbusState(); + const capabilities = modbusWriteCapabilities(); + const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); + const strategyAllowed = strategy === "id" ? capabilities.supportsIdWrite : capabilities.supportsSerialWrite; + return !!(log.currentConfig && log.selectedDevice && strategyAllowed && !modbusWriteValidationError()); } function modbusBusy(action) { @@ -2323,7 +2380,6 @@ function modbusCurrentConnection() { const log = modbusState(); - if (log.currentConfig && log.currentConfig.current) return log.currentConfig.current; if (log.selectedDevice) { return { slave: log.selectedDevice.slave, @@ -2331,6 +2387,7 @@ parity: log.selectedDevice.parity }; } + if (log.currentConfig && log.currentConfig.current) return log.currentConfig.current; const profile = modbusSelectedProfile(); return { slave: 1, @@ -2339,12 +2396,94 @@ }; } + function modbusCurrentSlaveFallback() { + const log = modbusState(); + const currentConfig = log.currentConfig && log.currentConfig.current_config; + const current = modbusCurrentConnection(); + return String( + textValue( + currentConfig && currentConfig.slave_id, + textValue(current && current.slave, "") + ) + ); + } + + function modbusWriteBaudOptions() { + const profile = modbusSelectedProfile() || {}; + const profileOptions = Array.isArray(profile.comm_profiles) ? profile.comm_profiles : []; + if (profile.family === "iomx_nano_exbd_08_16_12" && profileOptions.length) { + return profileOptions.map((item) => ({ + value: String(textValue(item.ui_value, item.baud)), + label: String(textValue(item.label, item.baud)), + baud: Number(item.baud), + registerValue: Number(item.register_value), + })); + } + return [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200].map((item) => ({ + value: String(item), + label: String(item), + baud: Number(item), + registerValue: null, + })); + } + + function modbusWriteTargetFromForm(current) { + const log = modbusState(); + const profile = modbusSelectedProfile() || {}; + const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); + if (strategy === "id") { + return { target: { slave: Number(log.writeForm.slave) }, strategy }; + } + if (profile.family === "iomx_nano_exbd_08_16_12") { + const selected = modbusWriteBaudOptions().find((item) => String(item.value) === String(log.writeForm.baud)); + if (!selected || !Number.isInteger(selected.registerValue)) { + return { target: { baud: Number(current.baud) }, strategy }; + } + return { + target: { + baud: Number(selected.baud), + comm_profile_value: Number(selected.registerValue), + }, + strategy, + }; + } + return { + target: { baud: Number(log.writeForm.baud) }, + strategy, + }; + } + function syncModbusWriteFormFromConfig() { const log = modbusState(); const current = modbusCurrentConnection(); - if (!log.writeForm.slave) log.writeForm.slave = String(current.slave || ""); + if (!log.writeForm.slave) log.writeForm.slave = modbusCurrentSlaveFallback(); if (!log.writeForm.baud) log.writeForm.baud = String(current.baud || "9600"); if (!log.writeForm.parity) log.writeForm.parity = textValue(current.parity, "none"); + log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); + } + + function updateModbusWriteFormUi() { + const slaveInput = document.getElementById("modbusWriteSlaveInput"); + const baudSelect = document.getElementById("modbusWriteBaudSelect"); + const strategySelect = document.getElementById("modbusWriteStrategySelect"); + const applyBtn = document.getElementById("modbusWriteApplyBtn"); + const errorNode = document.getElementById("modbusWriteError"); + const capabilities = modbusWriteCapabilities(); + const strategy = normalizeModbusWriteStrategy(modbusState().writeForm.strategy); + const validationError = modbusWriteValidationError(); + if (strategySelect) strategySelect.value = strategy; + if (slaveInput) { + slaveInput.disabled = !capabilities.supportsIdWrite || strategy !== "id"; + if (typeof slaveInput.setCustomValidity === "function") { + slaveInput.setCustomValidity(slaveInput.disabled ? "" : modbusWriteSlaveValidationError(modbusState().writeForm.slave)); + } + } + if (baudSelect) baudSelect.disabled = !capabilities.supportsSerialWrite || strategy !== "baud"; + if (applyBtn) applyBtn.disabled = !!(modbusBusy("write_config") || !modbusCanWrite()); + if (errorNode) { + errorNode.textContent = validationError || ""; + errorNode.hidden = !validationError; + } } function modbusWriteCurrentConfigView() { @@ -2505,8 +2644,10 @@ const requestedTarget = result.target_requested || {}; const fromSlave = textValue(requestedCurrent.slave, textValue(precheck.current && precheck.current.slave, "-")); const toSlave = textValue(finalConfig.slave, textValue(requestedTarget.slave, "-")); + const fromBaud = textValue(requestedCurrent.baud, textValue(precheck.current && precheck.current.baud, "-")); + const toBaud = textValue(finalConfig.baud, textValue(requestedTarget.baud, textValue(precheck.current && precheck.current.baud, "-"))); 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, "-"))) }); + if (fromBaud || toBaud) summaryRows.push({ label: t("Baud"), value: `${fromBaud} → ${toBaud}` }); 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); @@ -2544,6 +2685,7 @@ const scanStatus = textValue(log.discovery.message, scanRunning ? t("Scanning in progress. It may take some minutes.") : ""); const scanLogLines = modbusDiscoveryLogLines(); const writeCurrentConfig = modbusWriteCurrentConfigView(); + const writeBaudOptions = modbusWriteBaudOptions(); syncModbusWriteFormFromConfig(); return ` @@ -2637,36 +2779,35 @@
${esc(t("New values to write"))}
- - - - + + + + +
${esc(modbusWriteValidationError())}
${esc(t("Write is disabled until a device has been selected and its current config has been read."))}
${renderModbusWriteProcessLog()}
- +
@@ -2839,9 +2980,7 @@ 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"); - } + log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); } if (!log.operationLog.length && log.audit.length) { log.operationLog = log.audit.slice().reverse().map((item) => ({ @@ -3546,7 +3685,7 @@ 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"); + log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); } if (state.activeTab === "modbus") renderActiveTab(); }; @@ -3560,7 +3699,45 @@ }; window.__modbusSetWriteField = function (field, value) { - modbusState().writeForm[field] = value; + const log = modbusState(); + if (field === "slave") { + log.writeForm.slave = sanitizePositiveIntegerInput(value); + } else if (field === "strategy") { + log.writeForm.strategy = normalizeModbusWriteStrategy(value); + } else if (field === "parity") { + const normalized = String(value || "none").trim().toLowerCase(); + log.writeForm.parity = ["none", "even", "odd"].includes(normalized) ? normalized : "none"; + } else { + log.writeForm[field] = value; + } + updateModbusWriteFormUi(); + return log.writeForm[field]; + }; + + window.__modbusFilterPositiveIntegerKey = function (event) { + if (!event) return; + if (["e", "E", "+", "-", ".", ",", " "].includes(event.key)) { + event.preventDefault(); + } + }; + + window.__modbusHandleWriteSlaveInput = function (input) { + const nextValue = window.__modbusSetWriteField("slave", input && typeof input.value !== "undefined" ? input.value : ""); + const limitedValue = nextValue && Number(nextValue) > 256 ? "256" : nextValue; + if (limitedValue !== nextValue) { + window.__modbusSetWriteField("slave", limitedValue); + } + if (input && input.value !== limitedValue) input.value = limitedValue; + }; + + window.__modbusHandleWriteSlaveBlur = function (input) { + const fallback = modbusCurrentSlaveFallback(); + if (!modbusState().writeForm.slave) { + window.__modbusSetWriteField("slave", fallback); + } + if (input && input.value !== modbusState().writeForm.slave) { + input.value = modbusState().writeForm.slave; + } }; window.__modbusSetRegisterField = function (field, value) { @@ -3577,9 +3754,11 @@ const item = (log.discovery.devices || [])[index]; if (!item) return; log.selectedDevice = item; + log.currentConfig = null; log.writeForm.slave = String(item.slave); log.writeForm.baud = String(item.baud); log.writeForm.parity = item.parity; + log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); appendModbusLog(t("Device selected for configuration work"), "info"); if (state.activeTab === "modbus") renderActiveTab(); }; @@ -3733,9 +3912,17 @@ }) }); log.currentConfig = payload; + log.selectedDevice = { + port: log.port, + family: log.family, + slave: payload.current && payload.current.slave || current.slave, + baud: payload.current && payload.current.baud || current.baud, + parity: textValue(payload.current && payload.current.parity, current.parity) + }; 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); + log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); ingestModbusPayload(payload); appendModbusLog(t("Current config read completed"), "success"); } catch (error) { @@ -3751,6 +3938,13 @@ window.__modbusApplyConfig = async function () { const log = modbusState(); if (!modbusCanWrite()) return; + const validationError = modbusWriteValidationError(); + if (validationError) { + log.error = validationError; + updateModbusWriteFormUi(); + showToast("error", validationError); + return; + } log.busyAction = "write_config"; log.error = ""; log.lastWriteResult = null; @@ -3761,6 +3955,10 @@ try { await modbusEnsureSession(); const current = modbusCurrentConnection(); + if (!log.writeForm.slave) { + log.writeForm.slave = modbusCurrentSlaveFallback(); + } + const writeTarget = modbusWriteTargetFromForm(current); const response = await fetch("/api/modbus/write-config", { method: "POST", cache: "no-store", @@ -3773,12 +3971,8 @@ 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 + target: writeTarget.target, + strategy: modbusWriteStrategyForPayload(writeTarget.strategy) }) }); const payload = await response.json().catch(() => ({})); 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 index af548ac..e3af7a2 100644 --- 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 @@ -11,14 +11,33 @@ "default_stopbits": 1, "scan_baud": [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200], "scan_parity": ["none", "even", "odd"], - "zero_based": false + "zero_based": true }, "registers": { "test_read": { "address": 1, "count": 1, "type": "holding" + }, + "slave_id": { + "address": 252, + "count": 1, + "type": "holding", + "rw": true + }, + "comm_profile": { + "address": 254, + "count": 1, + "type": "holding", + "rw": true } }, - "comm_profiles": [] + "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" }, + { "register_value": 5, "baud": 9600, "parity": "none", "label": "Factory reset", "ui_value": "factory_reset" } + ] }