diff --git a/stage_ui/bump_ui_version.sh b/stage_ui/bump_ui_version.sh new file mode 100755 index 0000000..6e06785 --- /dev/null +++ b/stage_ui/bump_ui_version.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BACKEND_FILE="$SCRIPT_DIR/console_core/backend/app.py" +FRONTEND_FILE="$SCRIPT_DIR/console_core/frontend/console.js" + +extract_version() { + sed -n 's/.*V \([0-9][0-9.]*\).*/\1/p' "$1" | head -n 1 +} + +current_version="$(extract_version "$BACKEND_FILE")" +if [[ -z "$current_version" ]]; then + echo "Failed to detect current UI version in $BACKEND_FILE" >&2 + exit 1 +fi + +if [[ $# -gt 1 ]]; then + echo "Usage: $0 [MAJOR.MINOR.PATCH]" >&2 + exit 1 +fi + +if [[ $# -eq 1 ]]; then + next_version="$1" +else + IFS='.' read -r major minor patch <<<"$current_version" + if [[ -z "${major:-}" || -z "${minor:-}" || -z "${patch:-}" ]]; then + echo "Current version must be in MAJOR.MINOR.PATCH format, got: $current_version" >&2 + exit 1 + fi + next_version="${major}.${minor}.$((patch + 1))" +fi + +if [[ ! "$next_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Version must be in MAJOR.MINOR.PATCH format, got: $next_version" >&2 + exit 1 +fi + +old_label="V $current_version" +new_label="V $next_version" + +sed -i "s/${old_label}/${new_label}/g" "$BACKEND_FILE" "$FRONTEND_FILE" + +echo "UI version bumped: $old_label -> $new_label" +echo "Updated files:" +echo " $BACKEND_FILE" +echo " $FRONTEND_FILE" diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index 1663a57..ce9fcbc 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -24,6 +24,8 @@ from modbus_backend import ( ApiError as ModbusApiError, acquire_session as modbus_acquire_session, 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, list_ports_payload as modbus_list_ports_payload, profiles_payload as modbus_profiles_payload, read_audit as modbus_read_audit, @@ -39,7 +41,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 2.2.36" +UI_VERSION = "V 2.2.46" DEFAULT_CONFIG = { "bind": "0.0.0.0", @@ -3291,6 +3293,44 @@ class Handler(BaseHTTPRequestHandler): except Exception as exc: self.send_json({"ok": False, "error": str(exc)}, code=500) return + if parsed.path == "/api/modbus/iomx04/relay": + 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_iomx04_set_relay( + port=str(payload.get("port", "")), + slave=int(payload.get("slave", 1)), + baud=int(payload.get("baud", 9600)), + relay=int(payload.get("relay", 1)), + enabled=bool(payload.get("enabled", False)), + source="console_ui", + )) + except ModbusApiError as exc: + self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return + if parsed.path == "/api/modbus/iomx04/timed-relay": + 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_iomx04_apply_timed_relay( + port=str(payload.get("port", "")), + slave=int(payload.get("slave", 1)), + baud=int(payload.get("baud", 9600)), + relay=int(payload.get("relay", 1)), + duration_ds=int(payload.get("duration_ds", 150)), + source="console_ui", + )) + except ModbusApiError as exc: + self.send_json({"ok": False, "error": exc.message, "details": exc.details}, code=exc.code) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return if parsed.path == "/api/actions/audio-test": payload = self.read_json_body() if payload is None: diff --git a/stage_ui/console_core/backend/modbus_backend.py b/stage_ui/console_core/backend/modbus_backend.py index 1d0caf8..8498132 100644 --- a/stage_ui/console_core/backend/modbus_backend.py +++ b/stage_ui/console_core/backend/modbus_backend.py @@ -32,6 +32,22 @@ EXBD_WRITE_FAST_TIMEOUT = 2.0 EXBD_WRITE_POST_SLEEP = 0.2 EXBD_COMM_PROFILE_REGISTER = 0x00FF EXBD_BAUD_WRITE_POST_SLEEP = 0.3 +IOMX04_FAMILY = "iomx_04_04_p_07_24" +IOMX04_DISPLAY_NAME = "IOMATEX IOMX-04/04-P-07-24" +IOMX04_FACTORY_SLAVE = 255 +IOMX04_DEFAULT_BAUD = 9600 +IOMX04_BAUD_REGISTER = 0x03E8 +IOMX04_BAUD_WRITE_REGISTER = 0x03E9 +IOMX04_SID_WRITE_REGISTER = 0x0000 +IOMX04_TIMED_RELAY_REGISTER = 0x0003 +IOMX04_TIMED_RELAY_REGISTER_STEP = 0x0005 +IOMX04_SUPPORTED_BAUD_CODES = {2: 4800, 3: 9600, 4: 19200} +IOMX04_BAUD_TO_CODE = {value: key for key, value in IOMX04_SUPPORTED_BAUD_CODES.items()} +IOMX04_FINGERPRINT_REGISTERS = [ + {"address": 0, "count": 8, "type": "coil", "label": "coil0..7 (fc01)"}, + {"address": 0, "count": 8, "type": "discrete", "label": "di0..7 (fc02)"}, + {"address": IOMX04_BAUD_REGISTER, "count": 1, "type": "holding", "label": "0x03E8 (baud_code)"}, +] PT100_FAMILY = "rs485_pt100_tzt" PT100_DISPLAY_NAME = "RS485 PT100 Temperature Sensor" PT100_BAUD_CODE_MAP = {1: 2400, 2: 4800, 3: 9600} @@ -715,6 +731,17 @@ def termios_baud_constant(baud: int) -> int: return speed +def termios_parity_flags(parity: str) -> int: + value = str(parity or "none").strip().lower() + if value == "none": + return 0 + if value == "even": + return termios.PARENB + if value == "odd": + return termios.PARENB | termios.PARODD + raise ApiError(f"Unsupported parity: {parity}", 400) + + def serial_write_raw_frame( *, port: str, @@ -830,6 +857,634 @@ def write_em01_slave_id( return result +def serial_exchange_raw_frame( + *, + port: str, + baud: int, + parity: str, + frame: bytes, + timeout: float = 1.0, + expect_response: bool = True, +) -> Dict[str, Any]: + fd = None + started = time.monotonic() + response = bytearray() + try: + speed = termios_baud_constant(baud) + fd = os.open(port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) + attrs = termios.tcgetattr(fd) + attrs[0] = 0 + attrs[1] = 0 + attrs[2] = termios.CLOCAL | termios.CREAD | termios.CS8 | termios_parity_flags(parity) + attrs[3] = 0 + attrs[4] = speed + attrs[5] = speed + attrs[6][termios.VMIN] = 0 + attrs[6][termios.VTIME] = 0 + termios.tcflush(fd, termios.TCIOFLUSH) + termios.tcsetattr(fd, termios.TCSANOW, attrs) + total_sent = 0 + while total_sent < len(frame): + sent = os.write(fd, frame[total_sent:]) + if sent <= 0: + raise OSError("Serial write returned 0 bytes") + total_sent += sent + termios.tcdrain(fd) + if expect_response: + deadline = time.monotonic() + max(float(timeout), 0.1) + last_rx = None + while time.monotonic() < deadline: + ready, _, _ = select.select([fd], [], [], 0.05) + if not ready: + if response and last_rx is not None and (time.monotonic() - last_rx) >= 0.05: + break + continue + chunk = os.read(fd, 256) + if not chunk: + continue + response.extend(chunk) + last_rx = time.monotonic() + elapsed_ms = int((time.monotonic() - started) * 1000) + payload = { + "ok": True, + "write_sent": True, + "bytes_sent": len(frame), + "frame_hex": " ".join(f"{byte:02X}" for byte in frame), + "response_hex": " ".join(f"{byte:02X}" for byte in response), + "response_bytes": len(response), + "elapsed_ms": elapsed_ms, + } + backend_log( + "modbus_raw_serial_exchange", + port=port, + baud=int(baud), + parity=str(parity), + frame_hex=payload["frame_hex"], + response_hex=payload["response_hex"], + response_bytes=payload["response_bytes"], + elapsed_ms=elapsed_ms, + ok=True, + ) + return payload + except ApiError: + raise + except Exception as exc: + elapsed_ms = int((time.monotonic() - started) * 1000) + payload = { + "ok": False, + "write_sent": False, + "bytes_sent": 0, + "frame_hex": " ".join(f"{byte:02X}" for byte in frame), + "response_hex": " ".join(f"{byte:02X}" for byte in response), + "response_bytes": len(response), + "elapsed_ms": elapsed_ms, + "error_type": "serial_exchange_failed", + "error": str(exc), + } + backend_log( + "modbus_raw_serial_exchange", + port=port, + baud=int(baud), + parity=str(parity), + frame_hex=payload["frame_hex"], + response_hex=payload["response_hex"], + response_bytes=payload["response_bytes"], + elapsed_ms=elapsed_ms, + ok=False, + error=str(exc), + ) + return payload + finally: + if fd is not None: + try: + os.close(fd) + except Exception: + pass + + +def build_modbus_rtu_frame(slave: int, function: int, payload: bytes) -> bytes: + body = bytes([int(slave) & 0xFF, int(function) & 0xFF]) + payload + crc = calcModbusCrc(body) + return body + bytes([crc & 0xFF, (crc >> 8) & 0xFF]) + + +def decode_modbus_rtu_response(frame: bytes, *, slave: int, function: int) -> Dict[str, Any]: + raw = bytes(frame or b"") + if len(raw) < 5: + raise ApiError("Raw Modbus response is too short", 502) + body = raw[:-2] + crc_received = raw[-2] | (raw[-1] << 8) + crc_expected = calcModbusCrc(body) + if crc_received != crc_expected: + raise ApiError("Raw Modbus response CRC mismatch", 502) + if body[0] != (int(slave) & 0xFF): + raise ApiError("Raw Modbus response slave mismatch", 502) + if body[1] == ((int(function) & 0xFF) | 0x80): + exception_code = body[2] if len(body) > 2 else None + raise ApiError(f"Raw Modbus exception code: {exception_code}", 502) + if body[1] != (int(function) & 0xFF): + raise ApiError("Raw Modbus response function mismatch", 502) + payload_bytes = body[2:] + return { + "slave": int(body[0]), + "function": int(body[1]), + "data": [int(byte) for byte in payload_bytes], + "data_hex": " ".join(f"{byte:02X}" for byte in payload_bytes), + "frame_hex": " ".join(f"{byte:02X}" for byte in raw), + } + + +def raw_modbus_request( + *, + port: str, + slave: int, + baud: int, + parity: str, + function: int, + payload: bytes, + timeout: float = 1.0, + expect_response: bool = True, +) -> Dict[str, Any]: + frame = build_modbus_rtu_frame(slave, function, payload) + result = serial_exchange_raw_frame( + port=port, + baud=baud, + parity=parity, + frame=frame, + timeout=timeout, + expect_response=expect_response, + ) + result["function"] = int(function) + result["slave"] = int(slave) + response_raw = bytes.fromhex(result.get("response_hex", "").replace(" ", "")) if result.get("response_hex") else b"" + result["response_raw_hex"] = " ".join(f"{byte:02X}" for byte in response_raw) + if not result.get("ok"): + return result + if not expect_response: + result["decoded"] = {} + return result + try: + decoded = decode_modbus_rtu_response(response_raw, slave=slave, function=function) + result["decoded"] = decoded + except ApiError as exc: + result["ok"] = False + result["error_type"] = "invalid_response" + result["error"] = str(exc.message) + result["decoded"] = {} + return result + + +def iomx04_read_bits( + *, + port: str, + slave: int, + baud: int, + parity: str, + function: int, + start: int, + count: int, + timeout: float = 1.0, +) -> Dict[str, Any]: + response = raw_modbus_request( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=function, + payload=bytes([ + (int(start) >> 8) & 0xFF, + int(start) & 0xFF, + (int(count) >> 8) & 0xFF, + int(count) & 0xFF, + ]), + timeout=timeout, + ) + if not response.get("ok"): + return response + data = bytes(response["decoded"].get("data") or b"") + if not data: + return {"ok": False, "error_type": "invalid_response", "error": "Missing bit payload", **response} + byte_count = data[0] + raw_bytes = data[1:1 + byte_count] + bits = [] + for index in range(int(count)): + byte_index = index // 8 + bit_index = index % 8 + value = 1 if byte_index < len(raw_bytes) and (raw_bytes[byte_index] & (1 << bit_index)) else 0 + bits.append(value) + response["values"] = bits + response["bitmap"] = raw_bytes[0] if raw_bytes else 0 + return response + + +def iomx04_read_holding_register( + *, + port: str, + slave: int, + baud: int, + parity: str, + address: int, + count: int = 1, + timeout: float = 1.0, +) -> Dict[str, Any]: + response = raw_modbus_request( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=0x03, + payload=bytes([ + (int(address) >> 8) & 0xFF, + int(address) & 0xFF, + (int(count) >> 8) & 0xFF, + int(count) & 0xFF, + ]), + timeout=timeout, + ) + if not response.get("ok"): + return response + data = bytes(response["decoded"].get("data") or b"") + if not data: + return {"ok": False, "error_type": "invalid_response", "error": "Missing register payload", **response} + byte_count = data[0] + raw_bytes = data[1:1 + byte_count] + if len(raw_bytes) != int(count) * 2: + return {"ok": False, "error_type": "invalid_response", "error": "Unexpected register payload length", **response} + values = [] + for index in range(0, len(raw_bytes), 2): + values.append((raw_bytes[index] << 8) | raw_bytes[index + 1]) + response["values"] = values + return response + + +def iomx04_write_single_coil( + *, + port: str, + slave: int, + baud: int, + parity: str, + coil: int, + enabled: bool, + timeout: float = 1.0, +) -> Dict[str, Any]: + value = 0xFF00 if bool(enabled) else 0x0000 + return raw_modbus_request( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=0x05, + payload=bytes([ + (int(coil) >> 8) & 0xFF, + int(coil) & 0xFF, + (value >> 8) & 0xFF, + value & 0xFF, + ]), + timeout=timeout, + ) + + +def iomx04_write_multiple_registers( + *, + port: str, + slave: int, + baud: int, + parity: str, + address: int, + values: List[int], + timeout: float = 1.0, + expect_response: bool = True, +) -> Dict[str, Any]: + payload_bytes = bytearray() + for value in values or []: + payload_bytes.append((int(value) >> 8) & 0xFF) + payload_bytes.append(int(value) & 0xFF) + return raw_modbus_request( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=0x10, + payload=bytes([ + (int(address) >> 8) & 0xFF, + int(address) & 0xFF, + (len(values) >> 8) & 0xFF, + len(values) & 0xFF, + len(payload_bytes) & 0xFF, + ]) + bytes(payload_bytes), + timeout=timeout, + expect_response=expect_response, + ) + + +def iomx04_baud_meta(code: Optional[int]) -> Dict[str, Any]: + mapped_baud = IOMX04_SUPPORTED_BAUD_CODES.get(int(code)) if code is not None else None + return { + "code": None if code is None else int(code), + "baud": mapped_baud, + "parity": "none" if mapped_baud is not None else None, + "label": str(mapped_baud) if mapped_baud is not None else "", + } + + +def iomx04_bitmap_text(bits: List[int], active_count: int = 4) -> str: + normalized = [int(item) for item in (bits or [])[:active_count]] + return ", ".join(f"{index + 1}:{'ON' if value else 'OFF'}" for index, value in enumerate(normalized)) + + +def iomx04_detection_from_reads( + *, + slave: int, + baud: int, + coils: List[int], + inputs: List[int], + baud_code: int, +) -> Dict[str, Any]: + raw_value = f"fc01={coils[:8]}, fc02={inputs[:8]}, baud_code={int(baud_code)}" + return { + "state": "recognized", + "familyKey": IOMX04_FAMILY, + "familyLabel": IOMX04_DISPLAY_NAME, + "modelString": f"4 relays / 4 inputs, baud {IOMX04_SUPPORTED_BAUD_CODES.get(int(baud_code), baud)}", + "rawValue": raw_value, + "rawString": raw_value, + "rawRegisters": [int(baud_code)], + "rawBytesHex": "", + "register": dict(IOMX04_FINGERPRINT_REGISTERS[-1]), + "detectionRegisters": [dict(item) for item in IOMX04_FINGERPRINT_REGISTERS], + "matched": True, + "protocol": "modbus_rtu", + "addressing": "zero_based", + "confidence": "high", + } + + +def detect_iomx04_candidate( + *, + port: str, + slave: int, + baud: int, + parity: str, + timeout: float, + log_collector=None, +) -> Optional[Dict[str, Any]]: + if str(parity).strip().lower() != "none": + return None + coils_result = iomx04_read_bits( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=0x01, + start=0, + count=8, + timeout=timeout, + ) + if not coils_result.get("ok"): + return None + inputs_result = iomx04_read_bits( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=0x02, + start=0, + count=8, + timeout=timeout, + ) + if not inputs_result.get("ok"): + return None + baud_result = iomx04_read_holding_register( + port=port, + slave=slave, + baud=baud, + parity=parity, + address=IOMX04_BAUD_REGISTER, + count=1, + timeout=timeout, + ) + if not baud_result.get("ok"): + return None + baud_values = baud_result.get("values") or [] + baud_code = int(baud_values[0]) if baud_values else None + if baud_code not in IOMX04_SUPPORTED_BAUD_CODES: + return None + detection = iomx04_detection_from_reads( + slave=int(slave), + baud=int(baud), + coils=list(coils_result.get("values") or []), + inputs=list(inputs_result.get("values") or []), + baud_code=int(baud_code), + ) + if log_collector: + log_collector( + "info", + f"Slave {slave}: IOMX-04 fingerprint matched fc01/fc02/fc03(0x03E8={baud_code})", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=detection.get("rawValue", ""), + result="iomx04_fingerprint", + ) + return { + "port": port, + "slave": int(slave), + "baud": int(baud), + "parity": str(parity), + "status": "ok", + "confidence": "high", + "action": "Select", + "test_register": { + "address": IOMX04_BAUD_REGISTER, + "count": 1, + "type": "holding", + "value": int(baud_code), + }, + "familyDetection": detection, + "family": IOMX04_FAMILY, + "family_display_name": IOMX04_DISPLAY_NAME, + "raw_family_value": detection.get("rawValue", ""), + "configReadable": True, + "protocol": "modbus_rtu", + "addressing": "zero_based", + "relay_bitmap": int(coils_result.get("bitmap", 0)), + "input_bitmap": int(inputs_result.get("bitmap", 0)), + } + + +def probe_iomx04_device( + *, + port: str, + slave: int, + baud: int, + parity: str, + timeout: float, +) -> Dict[str, Any]: + coils_result = iomx04_read_bits( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=0x01, + start=0, + count=8, + timeout=timeout, + ) + inputs_result = iomx04_read_bits( + port=port, + slave=slave, + baud=baud, + parity=parity, + function=0x02, + start=0, + count=8, + timeout=timeout, + ) + baud_result = iomx04_read_holding_register( + port=port, + slave=slave, + baud=baud, + parity=parity, + address=IOMX04_BAUD_REGISTER, + count=1, + timeout=timeout, + ) + ok = bool(coils_result.get("ok")) and bool(inputs_result.get("ok")) and bool(baud_result.get("ok")) + baud_values = baud_result.get("values") or [] + baud_code = int(baud_values[0]) if baud_values else None + current_baud = IOMX04_SUPPORTED_BAUD_CODES.get(baud_code, int(baud)) + detection = iomx04_detection_from_reads( + slave=int(slave), + baud=int(current_baud), + coils=list(coils_result.get("values") or []), + inputs=list(inputs_result.get("values") or []), + baud_code=int(baud_code or IOMX04_BAUD_TO_CODE.get(current_baud, 0)), + ) if ok and baud_code in IOMX04_SUPPORTED_BAUD_CODES else {} + return { + "ok": ok and baud_code in IOMX04_SUPPORTED_BAUD_CODES, + "family": IOMX04_FAMILY, + "port": port, + "requested": {"slave": int(slave), "baud": int(baud), "parity": str(parity)}, + "current": {"slave": int(slave), "baud": int(current_baud), "parity": "none"}, + "current_config": { + "slave_id": int(slave), + "baud": int(current_baud), + "parity": "none", + "comm_profile_register": None if baud_code is None else int(baud_code), + "comm_profile_decoded": baud_code in IOMX04_SUPPORTED_BAUD_CODES, + "supports_serial_write": True, + "supports_id_write": True, + "relay_bitmap": int(coils_result.get("bitmap", 0)), + "input_bitmap": int(inputs_result.get("bitmap", 0)), + }, + "current_config_summary": { + "familyKey": IOMX04_FAMILY, + "familyLabel": IOMX04_DISPLAY_NAME, + "modelString": detection.get("modelString", "4 relays / 4 inputs"), + "modelRaw": detection.get("rawValue", ""), + "firmwareString": "", + "firmwareRaw": "", + "firmwareVersion": {}, + "serial": {"cleaned": "", "raw": "", "hex": ""}, + "slaveId": int(slave), + "baudCode": None if baud_code is None else int(baud_code), + "baudDisplay": int(current_baud), + "baudLabel": str(current_baud), + "parity": "none", + "relationshipCode": None, + "relationshipLabel": "", + "detectionRegisters": [dict(item) for item in IOMX04_FINGERPRINT_REGISTERS], + "summaryRegisters": {}, + "rawSummary": {}, + "extraRows": [ + {"label": "Relay bitmap", "value": f"0x{int(coils_result.get('bitmap', 0)):02X}"}, + {"label": "Relay state", "value": iomx04_bitmap_text(list(coils_result.get("values") or []))}, + {"label": "Input bitmap", "value": f"0x{int(inputs_result.get('bitmap', 0)):02X}"}, + {"label": "Input state", "value": iomx04_bitmap_text(list(inputs_result.get("values") or []))}, + ], + "warning": "", + }, + "raw_values": { + "coils": list(coils_result.get("values") or []), + "discrete_inputs": list(inputs_result.get("values") or []), + "baud_code": [] if baud_code is None else [int(baud_code)], + }, + "test_register": {"address": IOMX04_BAUD_REGISTER, "value": baud_code}, + "debug": { + "coils": coils_result, + "discrete_inputs": inputs_result, + "baud_code": baud_result, + }, + } + + +def iomx04_write_slave_id( + *, + port: str, + current_slave: int, + target_slave: int, + baud: int, +) -> Dict[str, Any]: + return iomx04_write_multiple_registers( + port=port, + slave=0, + baud=baud, + parity="none", + address=IOMX04_SID_WRITE_REGISTER, + values=[int(target_slave)], + timeout=0.6, + expect_response=False, + ) + + +def iomx04_write_baud_code( + *, + port: str, + slave: int, + baud: int, + target_baud: int, +) -> Dict[str, Any]: + baud_code = IOMX04_BAUD_TO_CODE.get(int(target_baud)) + if baud_code is None: + raise ApiError("Requested baud is not supported by IOMX-04 profile", 400) + result = iomx04_write_multiple_registers( + port=port, + slave=slave, + baud=baud, + parity="none", + address=IOMX04_BAUD_WRITE_REGISTER, + values=[int(baud_code)], + timeout=1.0, + expect_response=True, + ) + result["baud_code"] = int(baud_code) + return result + + +def iomx04_write_timed_relay( + *, + port: str, + slave: int, + baud: int, + relay: int, + duration_ds: int, +) -> Dict[str, Any]: + relay_index = int(relay) + if relay_index < 1 or relay_index > 4: + raise ApiError("Relay index must be in range 1..4", 400) + timed_register = IOMX04_TIMED_RELAY_REGISTER + ((relay_index - 1) * IOMX04_TIMED_RELAY_REGISTER_STEP) + return iomx04_write_multiple_registers( + port=port, + slave=slave, + baud=baud, + parity="none", + address=timed_register, + values=[0x0004, int(duration_ds)], + timeout=1.0, + expect_response=True, + ) + + def buildExbdCommProfileWriteFrame(currentSid: int, registerValue: int) -> bytes: payload = bytes([ int(currentSid) & 0xFF, @@ -1068,6 +1723,14 @@ def device_probe( expected_current: Optional[Dict[str, Any]] = None, include_summary: bool = True, ) -> Dict[str, Any]: + if str(family or "").strip() == IOMX04_FAMILY: + return probe_iomx04_device( + port=port, + slave=int(slave), + baud=int(baud), + parity=str(parity), + timeout=timeout, + ) profile = get_profile(family) requested_slave = int(slave) requested_baud = int(baud) @@ -1326,6 +1989,49 @@ def systemctl_control(unit_name: str, action: str) -> None: raise ApiError(f"Failed to {action} {unit_name}", 502, stderr) +def itscreen_runtime_busy() -> bool: + checks = ( + ["pgrep", "-u", "itscreen", "-x", "itscreen"], + ["pgrep", "-u", "itscreen", "-x", "openbox"], + ["pgrep", "-u", "itscreen", "-f", "/usr/local/bin/itscreen-session-launch"], + ["pgrep", "-f", "/usr/bin/xinit /usr/local/bin/itscreen-session"], + ["pgrep", "-f", r"(^|/)(Xorg|X)([[:space:]].*)?[[:space:]]:0([[:space:]]|$)"], + ) + for cmd in checks: + rc, _, _ = run(cmd, timeout=5.0) + if rc == 0: + return True + return False + + +def stop_itscreen_service_wait(timeout_sec: float = 15.0) -> Dict[str, Any]: + systemctl_stop_error = "" + rc, _, stderr = run(["systemctl", "stop", ITSCREEN_SERVICE_UNIT], timeout=20.0) + if rc != 0: + systemctl_stop_error = stderr or "Failed to stop service" + deadline = time.monotonic() + max(float(timeout_sec), 1.0) + while time.monotonic() < deadline: + if not systemctl_is_active(ITSCREEN_SERVICE_UNIT) and not itscreen_runtime_busy(): + return {"ok": True} + time.sleep(0.3) + return { + "ok": False, + "error": systemctl_stop_error or "Timed out while waiting for it-screen to stop", + } + + +def start_itscreen_service_wait(timeout_sec: float = 20.0) -> Dict[str, Any]: + rc, _, stderr = run(["systemctl", "start", ITSCREEN_SERVICE_UNIT], timeout=25.0) + if rc != 0: + return {"ok": False, "error": stderr or "Failed to start service"} + deadline = time.monotonic() + max(float(timeout_sec), 1.0) + while time.monotonic() < deadline: + if systemctl_is_active(ITSCREEN_SERVICE_UNIT): + return {"ok": True} + time.sleep(0.3) + return {"ok": False, "error": "Timed out while waiting for it-screen to start"} + + def itscreen_conflict_expected(port: str) -> bool: return os.path.basename(port) == "ttyS3" @@ -1769,9 +2475,11 @@ def acquire_session(port: str, stop_itscreen: bool, source: str = "ui") -> Dict[ stopped_itscreen = False if stop_itscreen and itscreen_running: operations.append({"level": "info", "message": "Stopping it-screen service before Modbus session"}) - systemctl_control(ITSCREEN_SERVICE_UNIT, "stop") + 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) stopped_itscreen = True - time.sleep(1.0) + operations.append({"level": "success", "message": "it-screen service stopped; Modbus port is ready"}) try: ensure_port_available(port, allow_itscreen_conflict=False) @@ -1785,7 +2493,7 @@ def acquire_session(port: str, stop_itscreen: bool, source: str = "ui") -> Dict[ except Exception: if stopped_itscreen and itscreen_running: try: - systemctl_control(ITSCREEN_SERVICE_UNIT, "start") + start_itscreen_service_wait() except Exception: pass raise @@ -1820,7 +2528,9 @@ def release_session(port: str, restart_itscreen: bool, source: str = "ui") -> Di restarted = False if restart_itscreen and bool((released or {}).get("itscreen_was_running")): operations.append({"level": "info", "message": "Starting it-screen service after Modbus session"}) - systemctl_control(ITSCREEN_SERVICE_UNIT, "start") + 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 payload = { "ok": True, @@ -2228,6 +2938,17 @@ def discover_devices( break if best_candidate and best_candidate.get("familyDetection", {}).get("state") == "recognized": break + if not (best_candidate and best_candidate.get("familyDetection", {}).get("state") == "recognized"): + iomx04_candidate = detect_iomx04_candidate( + port=port, + slave=int(slave), + baud=int(baud), + parity=str(parity), + timeout=DEFAULT_DISCOVERY_DEEP_TIMEOUT if deep else DEFAULT_DISCOVERY_QUICK_TIMEOUT, + log_collector=log_collector, + ) + if iomx04_candidate: + best_candidate = iomx04_candidate if not (best_candidate and best_candidate.get("familyDetection", {}).get("state") == "recognized"): pt100_candidate = detect_pt100_oem_candidate( port=port, @@ -2688,6 +3409,11 @@ def write_device_config( "Baud rate is not changeable on EM-01. Register 0x62 updates, but actual UART speed remains 9600.", 400, ) + if family == IOMX04_FAMILY and id_changed and serial_changed: + raise ApiError( + "Change Slave ID and Baud Rate separately for IOMX-04/04-P-07-24.", + 400, + ) if family == PT100_FAMILY and id_changed and serial_changed: raise ApiError( "Change Slave ID and Baud Rate separately for RS485 PT100 Temperature Sensor.", @@ -2698,6 +3424,127 @@ def write_device_config( write_sent = False id_write_ack_timed_out = False serial_write_ack_timed_out = False + if family == IOMX04_FAMILY: + if id_changed: + operations.append({ + "level": "info", + "message": "IOMX-04 uses raw FC16 broadcast write on register 0x0000 for Slave ID change", + }) + write_id = iomx04_write_slave_id( + port=port, + current_slave=current_slave, + target_slave=target_slave, + baud=write_baud, + ) + write_debug["slave_id_write"] = write_id + write_sent = bool(write_id.get("write_sent")) + if not write_sent: + return { + "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": False, + "target_verified": False, + "rediscovery_attempted": False, + "rediscovery_found": False, + "final_detected_config": None, + "recommended_next_step": "Check serial port access and IOMX-04 communication state", + "operation_log": operations + [{"level": "error", "message": "IOMX-04 broadcast Slave ID write failed"}], + "debug": write_debug, + } + operations.append({"level": "success", "message": "IOMX-04 broadcast Slave ID write frame sent"}) + time.sleep(0.25) + if serial_changed: + operations.append({ + "level": "info", + "message": f"IOMX-04 uses raw FC16 write on register 0x03E9 for baud {target_baud}", + }) + write_comm = iomx04_write_baud_code( + port=port, + slave=target_slave if id_changed else current_slave, + baud=write_baud, + target_baud=target_baud, + ) + write_debug["comm_profile_write"] = write_comm + write_sent = write_sent or bool(write_comm.get("write_sent")) + if not write_comm.get("ok"): + return { + "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": bool(write_sent), + "target_verified": False, + "rediscovery_attempted": False, + "rediscovery_found": False, + "final_detected_config": None, + "recommended_next_step": "Check serial port access and IOMX-04 communication state", + "operation_log": operations + [{"level": "error", "message": "IOMX-04 baud write failed"}], + "debug": write_debug, + } + operations.append({"level": "success", "message": "IOMX-04 baud write command completed"}) + time.sleep(0.35) + immediate_verify = device_probe( + port=port, + family=family, + slave=int(target_slave), + baud=int(target_baud), + parity="none", + timeout=DEFAULT_DISCOVER_TIMEOUT, + retries=0, + include_summary=True, + ) + write_debug["immediate_target_verify"] = immediate_verify["debug"] + if immediate_verify.get("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']} with baud {final_detected['baud']}" + return { + "ok": True, + "stage": "post_write_validation", + "status": "verified_target", + "message": success_message, + "write_baudrate": int(write_baud), + "current_requested": current, + "target_requested": target, + "write_sent": bool(write_sent), + "target_verified": True, + "rediscovery_attempted": False, + "rediscovery_found": True, + "found": True, + "final_detected_config": final_detected, + "recommended_next_step": success_message, + "operation_log": operations + [{"level": "success", "message": success_message}], + "debug": write_debug, + } + return { + "ok": False, + "stage": "post_write_validation", + "status": "write_unconfirmed", + "message": "Write command was sent, but IOMX-04 did not confirm the new communication settings", + "write_baudrate": int(write_baud), + "current_requested": current, + "target_requested": target, + "write_sent": bool(write_sent), + "target_verified": False, + "rediscovery_attempted": False, + "rediscovery_found": False, + "found": False, + "final_detected_config": None, + "recommended_next_step": f"Re-read IOMX-04 on slave {target_slave} at baud {target_baud}", + "operation_log": operations + [{"level": "error", "message": "IOMX-04 readback failed after write"}], + "debug": write_debug, + } if family == EM01_FAMILY and id_changed: operations.append({ "level": "info", @@ -3387,6 +4234,48 @@ def read_registers( source: str = "ui", ) -> Dict[str, Any]: ensure_port_locked(port) + if family == IOMX04_FAMILY: + if str(parity or "none").strip().lower() != "none": + raise ApiError("IOMX-04 uses parity none only", 400) + if str(register_type or "").strip().lower() in ("coil", "discrete"): + function = 0x01 if str(register_type).strip().lower() == "coil" else 0x02 + result = iomx04_read_bits( + port=port, + slave=int(slave), + baud=int(baud), + parity="none", + function=function, + start=int(address), + count=int(count), + timeout=DEFAULT_DISCOVER_TIMEOUT, + ) + if not result.get("ok"): + raise ApiError("Register read failed", 502, json.dumps(result)) + return { + "ok": True, + "values": [{"address": int(address) + index, "raw": str(value), "value": int(value)} for index, value in enumerate(result.get("values") or [])], + "stdout_lines": [result.get("response_hex", "")], + "stderr_lines": [], + "operation_log": [{"level": "success", "message": "Register read completed"}], + } + result = iomx04_read_holding_register( + port=port, + slave=int(slave), + baud=int(baud), + parity="none", + address=int(address), + count=int(count), + timeout=DEFAULT_DISCOVER_TIMEOUT, + ) + if not result.get("ok"): + raise ApiError("Register read failed", 502, json.dumps(result)) + return { + "ok": True, + "values": [{"address": int(address) + index, "raw": str(value), "value": int(value)} for index, value in enumerate(result.get("values") or [])], + "stdout_lines": [result.get("response_hex", "")], + "stderr_lines": [], + "operation_log": [{"level": "success", "message": "Register read completed"}], + } transport = transport_defaults(family) result = mbpoll_read( port=port, @@ -3436,6 +4325,27 @@ def write_register( source: str = "ui", ) -> Dict[str, Any]: ensure_port_locked(port) + if family == IOMX04_FAMILY: + if int(address) < 0: + raise ApiError("Invalid register address", 400) + result = iomx04_write_baud_code( + port=port, + slave=int(slave), + baud=int(baud), + target_baud=int(value), + ) if int(address) == IOMX04_BAUD_WRITE_REGISTER else None + if result is None: + raise ApiError("Use dedicated IOMX-04 relay controls or write-config flow for this device", 400) + if not result.get("ok"): + raise ApiError("Register write failed", 502, json.dumps(result)) + return { + "ok": True, + "message": "Register write completed", + "debug": result, + "stdout_lines": [result.get("response_hex", "")], + "stderr_lines": [], + "operation_log": [{"level": "success", "message": "Register write completed"}], + } if family == EM01_FAMILY and int(address) == EM01_BAUD_REGISTER: raise ApiError( "Baud rate is not changeable on EM-01. Register 0x62 updates, but actual UART speed remains 9600.", @@ -3473,3 +4383,81 @@ def write_register( "stderr_lines": result["stderr_lines"], "operation_log": [{"level": "success", "message": "Register write completed"}], } + + +def iomx04_set_relay( + *, + port: str, + slave: int, + baud: int, + relay: int, + enabled: bool, + source: str = "ui", +) -> Dict[str, Any]: + ensure_port_locked(port) + relay_index = int(relay) + if relay_index < 1 or relay_index > 4: + raise ApiError("Relay index must be in range 1..4", 400) + result = iomx04_write_single_coil( + port=port, + slave=int(slave), + baud=int(baud), + parity="none", + coil=relay_index - 1, + enabled=bool(enabled), + ) + if not result.get("ok"): + raise ApiError("Relay write failed", 502, json.dumps(result)) + append_audit({ + "action": "iomx04_relay_write", + "port": port, + "family": IOMX04_FAMILY, + "slave": int(slave), + "relay": relay_index, + "enabled": bool(enabled), + "success": True, + "source": source, + }) + return { + "ok": True, + "message": f"Relay {relay_index} turned {'ON' if enabled else 'OFF'}", + "debug": result, + "operation_log": [{"level": "success", "message": f"Relay {relay_index} turned {'ON' if enabled else 'OFF'}"}], + } + + +def iomx04_apply_timed_relay( + *, + port: str, + slave: int, + baud: int, + relay: int, + duration_ds: int, + source: str = "ui", +) -> Dict[str, Any]: + ensure_port_locked(port) + result = iomx04_write_timed_relay( + port=port, + slave=int(slave), + baud=int(baud), + relay=int(relay), + duration_ds=int(duration_ds), + ) + if not result.get("ok"): + raise ApiError("Timed relay write failed", 502, json.dumps(result)) + append_audit({ + "action": "iomx04_timed_relay_write", + "port": port, + "family": IOMX04_FAMILY, + "slave": int(slave), + "relay": int(relay), + "duration_ds": int(duration_ds), + "success": True, + "source": source, + }) + return { + "ok": True, + "message": f"Relay {int(relay)} timed ON started for {round(int(duration_ds) / 10.0, 1)} sec", + "debug": result, + "operation_log": [{"level": "success", "message": f"Relay {int(relay)} timed ON started"}], + } diff --git a/stage_ui/console_core/frontend/console.i18n.js b/stage_ui/console_core/frontend/console.i18n.js index 43bdd30..d95d918 100644 --- a/stage_ui/console_core/frontend/console.i18n.js +++ b/stage_ui/console_core/frontend/console.i18n.js @@ -32,6 +32,15 @@ "Host / IP": "Хост / IP", "Updated": "Обновлено", "Primary navigation": "Основная навигация", + "Stopping it-screen service before Modbus session": "Остановка сервиса it-screen перед Modbus-сеансом", + "Starting it-screen service after Modbus session": "Запуск сервиса it-screen после Modbus-сеанса", + "Stop it-screen while working with Modbus": "Останавливать it-screen во время работы с Modbus", + "Restart it-screen on release": "Перезапускать it-screen после освобождения порта", + "it-screen service was stopped temporarily for Modbus scanning and writing.": "Сервис it-screen был временно остановлен для сканирования и записи Modbus.", + "it-screen service was restarted after the Modbus session.": "Сервис it-screen был перезапущен после Modbus-сеанса.", + "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?": "it-screen сейчас работает на этом последовательном порту. Для действия «{action}» сервис it-screen будет временно остановлен, потому что результаты сканирования и записи ненадёжны, пока it-screen активен.\n\nПродолжить?", + "{action} was cancelled because it-screen is still running.": "Действие «{action}» отменено, потому что it-screen всё ещё запущен.", + "it-screen did not stop in time for {action}.": "Сервис it-screen не остановился вовремя для действия «{action}».", "Not available": "Недоступно", "Not specified": "Не указано", "Unknown": "Неизвестно", @@ -440,6 +449,15 @@ "Host / IP": "Host / IP", "Updated": "Zaktualizowano", "Primary navigation": "Nawigacja główna", + "Stopping it-screen service before Modbus session": "Zatrzymywanie usługi it-screen przed sesją Modbus", + "Starting it-screen service after Modbus session": "Uruchamianie usługi it-screen po sesji Modbus", + "Stop it-screen while working with Modbus": "Zatrzymaj it-screen podczas pracy z Modbus", + "Restart it-screen on release": "Uruchom ponownie it-screen po zwolnieniu portu", + "it-screen service was stopped temporarily for Modbus scanning and writing.": "Usługa it-screen została tymczasowo zatrzymana na czas skanowania i zapisu Modbus.", + "it-screen service was restarted after the Modbus session.": "Usługa it-screen została ponownie uruchomiona po sesji Modbus.", + "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?": "it-screen działa obecnie na tej ścieżce szeregowej. Operacja „{action}” tymczasowo zatrzyma it-screen, ponieważ wyniki skanowania i zapisu są niewiarygodne, gdy it-screen jest aktywny.\n\nKontynuować?", + "{action} was cancelled because it-screen is still running.": "Operacja „{action}” została anulowana, ponieważ it-screen nadal działa.", + "it-screen did not stop in time for {action}.": "Usługa it-screen nie zatrzymała się na czas dla operacji „{action}”.", "Not available": "Niedostępne", "Not specified": "Nie podano", "Unknown": "Nieznane", @@ -826,6 +844,15 @@ "Host / IP": "المضيف / IP", "Updated": "آخر تحديث", "Primary navigation": "التنقل الرئيسي", + "Stopping it-screen service before Modbus session": "إيقاف خدمة it-screen قبل جلسة Modbus", + "Starting it-screen service after Modbus session": "تشغيل خدمة it-screen بعد جلسة Modbus", + "Stop it-screen while working with Modbus": "أوقف it-screen أثناء العمل مع Modbus", + "Restart it-screen on release": "أعد تشغيل it-screen بعد تحرير المنفذ", + "it-screen service was stopped temporarily for Modbus scanning and writing.": "تم إيقاف خدمة it-screen مؤقتًا أثناء فحص وكتابة Modbus.", + "it-screen service was restarted after the Modbus session.": "تمت إعادة تشغيل خدمة it-screen بعد جلسة Modbus.", + "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?": "خدمة it-screen تعمل حاليًا على هذا المسار التسلسلي. سيؤدي الإجراء \"{action}\" إلى إيقاف it-screen مؤقتًا لأن نتائج الفحص والكتابة تكون غير موثوقة أثناء نشاط it-screen.\n\nهل تريد المتابعة؟", + "{action} was cancelled because it-screen is still running.": "تم إلغاء الإجراء \"{action}\" لأن خدمة it-screen ما زالت قيد التشغيل.", + "it-screen did not stop in time for {action}.": "لم تتوقف خدمة it-screen في الوقت المناسب لتنفيذ الإجراء \"{action}\".", "Not available": "غير متاح", "Not specified": "غير محدد", "Unknown": "غير معروف", @@ -1217,6 +1244,15 @@ "Host / IP": "होस्ट / IP", "Updated": "अपडेट किया गया", "Primary navigation": "मुख्य नेविगेशन", + "Stopping it-screen service before Modbus session": "Modbus सत्र से पहले it-screen सेवा रोकी जा रही है", + "Starting it-screen service after Modbus session": "Modbus सत्र के बाद it-screen सेवा शुरू की जा रही है", + "Stop it-screen while working with Modbus": "Modbus के साथ काम करते समय it-screen रोकें", + "Restart it-screen on release": "रिलीज़ के बाद it-screen फिर से चालू करें", + "it-screen service was stopped temporarily for Modbus scanning and writing.": "Modbus स्कैनिंग और लिखने के लिए it-screen सेवा अस्थायी रूप से रोकी गई थी।", + "it-screen service was restarted after the Modbus session.": "Modbus सत्र के बाद it-screen सेवा फिर से शुरू की गई।", + "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?": "इस serial path पर it-screen अभी चल रहा है। \"{action}\" के लिए it-screen को अस्थायी रूप से रोका जाएगा, क्योंकि it-screen सक्रिय रहने पर scan और write के परिणाम भरोसेमंद नहीं होते।\n\nक्या जारी रखें?", + "{action} was cancelled because it-screen is still running.": "\"{action}\" रद्द कर दिया गया क्योंकि it-screen अभी भी चल रहा है।", + "it-screen did not stop in time for {action}.": "\"{action}\" के लिए it-screen सेवा समय पर बंद नहीं हुई।", "Not available": "उपलब्ध नहीं", "Not specified": "निर्दिष्ट नहीं", "Nothing to copy": "कॉपी करने के लिए कुछ नहीं", diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index d5397bc..f93cbe2 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -44,7 +44,7 @@ { mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" }, { mode: "custom", label: "Custom", host: "" } ]; - const UI_VERSION = "V 2.2.36"; + const UI_VERSION = "V 2.2.46"; const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BATCH_MS = 250; @@ -243,6 +243,10 @@ decodeMode: "uint16", value: "", lastResult: null + }, + iomx04Control: { + relay: "1", + timedSeconds: "15" } }, networkForm: { @@ -2857,7 +2861,7 @@ return entries.map((item) => ({ timestamp: new Date().toISOString(), level: textValue(item.level, "info"), - message: textValue(item.message, "") + message: translateUiText(textValue(item.message, "")) })).filter((item) => item.message); } @@ -2936,6 +2940,11 @@ return profile.family === "exbd_nano"; } + function modbusIomx04FamilySelected() { + const profile = modbusSelectedProfile() || {}; + return profile.family === "iomx_04_04_p_07_24"; + } + function modbusEm01BaudComment() { return t("Baud rate is not changeable on EM-01. Register 0x62 updates, but actual UART speed remains 9600."); } @@ -3134,6 +3143,9 @@ if (modbusEditorFamily() === "rs485_pt100_tzt") { log.writeForm.parity = "none"; } + if (modbusIomx04FamilySelected()) { + log.writeForm.parity = "none"; + } if (modbusEm01FamilySelected()) { log.writeForm.baud = "9600"; log.writeForm.parity = "none"; @@ -3258,22 +3270,88 @@ 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) { return true; } + if (confirmItscreenStop && stopItscreen) { + const portsPayload = await fetchJson("/api/modbus/ports", { cache: "no-store" }); + log.ports = Array.isArray(portsPayload.ports) ? portsPayload.ports : []; + const currentPortInfo = modbusSelectedPortStatus() || {}; + const itscreenConflict = !!(currentPortInfo.itscreen_running && String(log.port || "").endsWith("ttyS3")); + if (itscreenConflict) { + 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.")); + 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: stopItscreen }) + body: JSON.stringify({ port: log.port, stop_itscreen: effectiveStopItscreen }) }); log.session = payload.lock || null; ingestModbusPayload(payload); - appendModbusLog(payload.message || t("Port acquired"), "success"); + appendModbusLog(translateUiText(payload.message || t("Port acquired")), "success"); + if (payload.itscreen_stopped) { + appendModbusLog(t("it-screen service was stopped temporarily for Modbus scanning and writing."), "warn"); + showToast("warn", t("it-screen service was stopped temporarily for Modbus scanning and writing.")); + } await loadModbus({ force: true, maxAgeMs: 0 }); 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 ` @@ -3494,6 +3572,7 @@ return ` ${summary.warning ? `` : ""}
${renderKeyValueRows(rows.concat(extraRows))}
+ ${modbusIomx04FamilySelected() ? renderIomx04RelayControls() : ""}
${esc(t("Raw register details"))}
${esc(JSON.stringify(currentConfig.raw_values || {}, null, 2))}
@@ -3501,6 +3580,40 @@ `; } + function renderIomx04RelayControls() { + const control = modbusState().iomx04Control || {}; + return ` +
+
${esc(t("Relay control"))}
+
+ + +
+
+ + + +
+
${esc(t("Timed relay uses the hardware auto-off mode and is suitable for watchdog behavior."))}
+
+ `; + } + function renderModbusReadConfigState() { const log = modbusState(); if (log.readConfigStatus === "success" && log.readConfigMessage) { @@ -3690,7 +3803,7 @@ id: "modbusDiscoverySlaveFromInput", value: log.discovery.slaveFrom, min: 1, - max: 247, + max: 255, step: 1, oninput: "window.__modbusSetDiscovery('slaveFrom', this.value)" })} @@ -3701,7 +3814,7 @@ id: "modbusDiscoverySlaveToInput", value: log.discovery.slaveTo, min: 1, - max: 247, + max: 255, step: 1, oninput: "window.__modbusSetDiscovery('slaveTo', this.value)" })} @@ -3800,12 +3913,12 @@ ` } - ${modbusEm01FamilySelected() ? `
${esc(modbusEm01BaudComment())}
` : ((modbusExbdFamilySelected() || modbusEditorFamily() === "rs485_pt100_tzt") ? ` + ${modbusEm01FamilySelected() ? `
${esc(modbusEm01BaudComment())}
` : ((modbusExbdFamilySelected() || modbusEditorFamily() === "rs485_pt100_tzt" || modbusIomx04FamilySelected()) ? ` -
${esc(modbusEditorFamily() === "rs485_pt100_tzt" ? t("Parity is fixed to none on this PT100 sensor.") : modbusExbdParityComment())}
+
${esc(modbusEditorFamily() === "rs485_pt100_tzt" ? t("Parity is fixed to none on this PT100 sensor.") : (modbusIomx04FamilySelected() ? t("Parity is fixed to none on this IOMX-04 board.") : modbusExbdParityComment()))}
` : `