modbus: fix baud write (FC03/FC06), add iomx_em_01 profile, UI updates

This commit is contained in:
Andrei Smaliak 2026-04-10 07:15:05 +04:00
parent 7f6559d5be
commit 42369bab4b
5 changed files with 851 additions and 57 deletions

View File

@ -3,9 +3,11 @@ import glob
import json
import os
import re
import select
import shutil
import subprocess
import sys
import termios
import threading
import time
import uuid
@ -22,6 +24,14 @@ DEFAULT_DISCOVERY_DEEP_TIMEOUT = 3.2
DISCOVERY_JOBS: Dict[str, Dict[str, Any]] = {}
DISCOVERY_JOBS_LOCK = threading.Lock()
SID_WRITE_ACK_OPTIONAL_FAMILIES = {"exbd_nano"}
EM01_FAMILY = "iomx_em_01"
EM01_FIXED_BAUD = 9600
EM01_BAUD_REGISTER = 0x62
EXBD_FAMILY = "exbd_nano"
EXBD_WRITE_FAST_TIMEOUT = 2.0
EXBD_WRITE_POST_SLEEP = 0.2
EXBD_COMM_PROFILE_REGISTER = 0x00FF
EXBD_BAUD_WRITE_POST_SLEEP = 0.3
PORT_GLOBS = (
"/dev/ttyS*",
@ -504,6 +514,197 @@ def mbpoll_write_register(
return payload
def calcModbusCrc(data: bytes) -> int:
crc = 0xFFFF
for byte in data:
crc ^= int(byte) & 0xFF
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
return crc & 0xFFFF
def buildEm01SlaveIdWriteFrame(currentSid: int, newSid: int) -> bytes:
payload = bytes([
int(currentSid) & 0xFF,
0x10,
0x00,
0x61,
0x00,
0x01,
0x02,
0x00,
int(newSid) & 0xFF,
])
crc = calcModbusCrc(payload)
return payload + bytes([crc & 0xFF, (crc >> 8) & 0xFF])
def termios_baud_constant(baud: int) -> int:
mapping = {
1200: termios.B1200,
2400: termios.B2400,
4800: termios.B4800,
9600: termios.B9600,
19200: termios.B19200,
38400: termios.B38400,
57600: termios.B57600,
115200: termios.B115200,
}
speed = mapping.get(int(baud))
if speed is None:
raise ApiError(f"Unsupported serial baud rate: {baud}", 400)
return speed
def serial_write_raw_frame(
*,
port: str,
baud: int,
frame: bytes,
timeout: float = 1.0,
) -> Dict[str, Any]:
fd = None
started = time.monotonic()
ack = 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
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)
deadline = time.monotonic() + max(float(timeout), 0.1)
while time.monotonic() < deadline:
ready, _, _ = select.select([fd], [], [], 0.05)
if not ready:
continue
chunk = os.read(fd, 256)
if not chunk:
continue
ack.extend(chunk)
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),
"ack_hex": " ".join(f"{byte:02X}" for byte in ack),
"ack_bytes": len(ack),
"elapsed_ms": elapsed_ms,
}
backend_log(
"modbus_raw_serial_write",
port=port,
baud=int(baud),
frame_hex=payload["frame_hex"],
ack_hex=payload["ack_hex"],
ack_bytes=payload["ack_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),
"ack_hex": " ".join(f"{byte:02X}" for byte in ack),
"ack_bytes": len(ack),
"elapsed_ms": elapsed_ms,
"error_type": "serial_write_failed",
"error": str(exc),
}
backend_log(
"modbus_raw_serial_write",
port=port,
baud=int(baud),
frame_hex=payload["frame_hex"],
ack_hex=payload["ack_hex"],
ack_bytes=payload["ack_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 write_em01_slave_id(
*,
port: str,
current_sid: int,
new_sid: int,
) -> Dict[str, Any]:
frame = buildEm01SlaveIdWriteFrame(current_sid, new_sid)
result = serial_write_raw_frame(
port=port,
baud=EM01_FIXED_BAUD,
frame=frame,
)
result["current_sid"] = int(current_sid)
result["new_sid"] = int(new_sid)
return result
def buildExbdCommProfileWriteFrame(currentSid: int, registerValue: int) -> bytes:
payload = bytes([
int(currentSid) & 0xFF,
0x06,
0x00,
0xFF,
0x00,
int(registerValue) & 0xFF,
])
crc = calcModbusCrc(payload)
return payload + bytes([crc & 0xFF, (crc >> 8) & 0xFF])
def write_exbd_comm_profile(
*,
port: str,
current_sid: int,
register_value: int,
baud: int,
) -> Dict[str, Any]:
frame = buildExbdCommProfileWriteFrame(current_sid, register_value)
result = serial_write_raw_frame(
port=port,
baud=int(baud),
frame=frame,
)
result["current_sid"] = int(current_sid)
result["register_value"] = int(register_value)
return result
def read_profile_register(
*,
profile: Dict[str, Any],
@ -657,6 +858,7 @@ def build_probe_diagnostics(
"parity": current_parity_value,
},
"expected_current": None,
"advisory_reasons": [],
"mismatch_reasons": [],
"result": "pending",
}
@ -669,11 +871,14 @@ def build_probe_diagnostics(
"baud": expected_baud,
"parity": expected_parity,
}
advisory_reasons: List[str] = []
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}"
)
reason = f"decoded slave_id mismatch: expected {expected_slave}, got {current_slave_value}"
if family == EM01_FAMILY:
advisory_reasons.append(reason)
else:
mismatch_reasons.append(reason)
if comm_result is not None and bool(comm_result.get("ok")):
if decoded_comm.get("decoded"):
if current_baud_value != expected_baud:
@ -685,9 +890,12 @@ def build_probe_diagnostics(
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"
)
reason = "comm_profile read succeeded but could not be decoded to baud/parity business values"
if family == EM01_FAMILY:
advisory_reasons.append(reason)
else:
mismatch_reasons.append(reason)
diagnostics["advisory_reasons"] = advisory_reasons
diagnostics["mismatch_reasons"] = mismatch_reasons
return diagnostics
@ -702,6 +910,7 @@ def device_probe(
timeout: float = DEFAULT_DISCOVER_TIMEOUT,
retries: int = 1,
expected_current: Optional[Dict[str, Any]] = None,
include_summary: bool = True,
) -> Dict[str, Any]:
profile = get_profile(family)
requested_slave = int(slave)
@ -745,12 +954,17 @@ def device_probe(
parity=parity,
timeout=timeout,
retries=retries,
)
) if include_summary else {}
test_value = test_result["values"][0]["value"] if test_result.get("ok") and test_result.get("values") else None
slave_value = slave_result["values"][0]["value"] if slave_result and slave_result.get("ok") and slave_result.get("values") else None
comm_value = comm_result["values"][0]["value"] if comm_result and comm_result.get("ok") and comm_result.get("values") else None
decoded_comm = decode_comm_profile(profile, comm_value)
if family == EM01_FAMILY:
current_slave_value = requested_slave
current_baud_value = EM01_FIXED_BAUD
current_parity_value = "none"
else:
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
@ -785,6 +999,7 @@ def device_probe(
decoded_current=diagnostics.get("decoded_current"),
registers=diagnostics.get("registers"),
reads=diagnostics.get("reads"),
include_summary=bool(include_summary),
mismatch_reasons=mismatch_reasons,
ok=ok,
result=diagnostics.get("result"),
@ -1244,6 +1459,7 @@ def validate_profile(data: Dict[str, Any], source_path: str) -> Dict[str, Any]:
"family": family,
"title": title or family,
"display_name": display_name or title or family,
"discovery_enabled": bool(data.get("discovery_enabled", True)),
"transport": {
"protocol": str(transport.get("protocol", "modbus_rtu")),
"default_port": str(transport.get("default_port", "/dev/ttyS3")),
@ -1623,7 +1839,7 @@ def discover_devices(
log_collector=None,
) -> Dict[str, Any]:
ensure_port_locked(port)
profiles = load_profiles()
profiles = [profile for profile in load_profiles() if bool(profile.get("discovery_enabled", True))]
start_slave = max(1, int(slave_range[0]))
end_slave = max(start_slave, int(slave_range[1]))
baud_candidates = [int(item) for item in (baudrates or [9600]) if int(item) > 0]
@ -2176,6 +2392,8 @@ def write_device_config(
target_slave = int(target.get("slave", current_slave))
target_baud = int(target.get("baud", current_baud))
target_parity = str(target.get("parity", current_parity))
exbd_fast_id_write = family == EXBD_FAMILY and strategy_value == "id_only" and target_slave != current_slave
exbd_fast_baud_write = family == EXBD_FAMILY and strategy_value == "serial_only" and target_baud != current_baud and target_parity == current_parity == "none"
precheck = device_probe(
port=port,
@ -2183,13 +2401,14 @@ def write_device_config(
slave=int(current_slave),
baud=int(write_baud),
parity=str(current_parity),
timeout=DEFAULT_DISCOVER_TIMEOUT,
retries=1,
timeout=EXBD_WRITE_FAST_TIMEOUT if (exbd_fast_id_write or exbd_fast_baud_write) else DEFAULT_DISCOVER_TIMEOUT,
retries=0 if (exbd_fast_id_write or exbd_fast_baud_write) else 1,
expected_current={
"slave": current_slave,
"baud": current_baud,
"parity": current_parity,
},
include_summary=not (exbd_fast_id_write or exbd_fast_baud_write),
)
operations = [{"level": "info", "message": "Pre-check started before write"}]
if not precheck["ok"]:
@ -2226,9 +2445,14 @@ def write_device_config(
})
return payload
operations.append({"level": "success", "message": "Pre-check passed; current device communication is confirmed"})
diagnostics = ((precheck.get("debug") or {}).get("precheck_diagnostics") or {})
for reason in diagnostics.get("advisory_reasons") or []:
operations.append({"level": "warn", "message": f"Pre-check advisory: {reason}"})
id_changed = target_slave != int(precheck["current_config"]["slave_id"])
serial_changed = target_baud != current_baud or target_parity != current_parity
if family == EM01_FAMILY:
id_changed = target_slave != int(current_slave)
if strategy_value == "id_only":
serial_changed = False
@ -2259,10 +2483,301 @@ def write_device_config(
400,
)
if family == EM01_FAMILY and serial_changed:
raise ApiError(
"Baud rate is not changeable on EM-01. Register 0x62 updates, but actual UART speed remains 9600.",
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 family == EM01_FAMILY and id_changed:
operations.append({
"level": "info",
"message": "EM-01 uses a raw FC10 frame for Slave ID write on register 0x61",
})
write_id = write_em01_slave_id(
port=port,
current_sid=current_slave,
new_sid=target_slave,
)
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(EM01_FIXED_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 serial port access and EM-01 communication state",
"operation_log": operations + [{"level": "error", "message": "EM-01 raw Slave ID write 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": "EM-01 raw Slave ID write frame sent"})
operations.append({"level": "info", "message": f"Readback started on new Slave ID {target_slave} at 9600 baud"})
time.sleep(0.2)
immediate_verify = device_probe(
port=port,
family=family,
slave=int(target_slave),
baud=int(EM01_FIXED_BAUD),
parity=str(current_parity),
timeout=DEFAULT_DISCOVER_TIMEOUT,
retries=1,
)
write_debug["immediate_target_verify"] = immediate_verify["debug"]
if immediate_verify["ok"]:
final_detected = {
"slave": immediate_verify["current"]["slave"],
"baud": immediate_verify["current"]["baud"],
"parity": immediate_verify["current"]["parity"],
}
success_message = f"Write verified. Device is now reachable at slave {final_detected['slave']}"
payload = {
"ok": True,
"stage": "post_write_validation",
"status": "verified_target",
"message": success_message,
"write_baudrate": int(EM01_FIXED_BAUD),
"current_requested": current,
"target_requested": target,
"write_sent": True,
"target_verified": True,
"rediscovery_attempted": False,
"rediscovery_found": True,
"found": True,
"final_detected_config": final_detected,
"recommended_next_step": success_message,
"operation_log": operations + [{"level": "success", "message": f"Readback confirmed new Slave ID {final_detected['slave']}"}],
"debug": write_debug,
}
append_audit({
"action": "write_config",
"port": port,
"family": family,
"current": current,
"target": target,
"strategy": strategy_value,
"status": "verified_target",
"success": True,
"final_detected_config": final_detected,
"source": source,
})
return payload
payload = {
"ok": False,
"stage": "post_write_validation",
"status": "write_unconfirmed",
"message": "Slave ID write was sent, but readback on the new Slave ID did not confirm the change",
"write_baudrate": int(EM01_FIXED_BAUD),
"current_requested": current,
"target_requested": target,
"write_sent": True,
"target_verified": False,
"rediscovery_attempted": False,
"rediscovery_found": False,
"found": False,
"final_detected_config": None,
"recommended_next_step": f"Re-read EM-01 on slave {target_slave} at 9600 baud",
"operation_log": operations + [{"level": "error", "message": f"Readback on new Slave ID {target_slave} failed"}],
"debug": write_debug,
}
append_audit({
"action": "write_config",
"port": port,
"family": family,
"current": current,
"target": target,
"strategy": strategy_value,
"status": "write_unconfirmed",
"success": False,
"write_sent": True,
"target_verified": False,
"source": source,
})
return payload
if exbd_fast_baud_write and serial_changed:
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)
operations.append({
"level": "info",
"message": f"ExBd uses mbpoll FC06 for baud profile write on holding register {int(registers['comm_profile']['address'])}",
})
write_comm = mbpoll_write_register(
port=port,
slave=int(current_slave),
address=int(registers["comm_profile"]["address"]),
value=comm_value,
baud=write_baud,
parity=current_parity,
data_bits=int(transport["default_databits"]),
stop_bits=int(transport["default_stopbits"]),
zero_based=bool(transport.get("zero_based", True)),
)
write_debug["comm_profile_write"] = write_comm
write_sent = bool(write_comm.get("write_sent"))
if not write_comm["ok"]:
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(EXBD_BAUD_WRITE_POST_SLEEP)
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 serial port access and ExBd communication state",
"operation_log": operations + [{"level": "error", "message": "ExBd baud 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": "ExBd baud write command completed"})
operations.append({"level": "info", "message": f"Readback started on baud {target_baud}"})
time.sleep(EXBD_BAUD_WRITE_POST_SLEEP)
immediate_verify = device_probe(
port=port,
family=family,
slave=int(current_slave),
baud=int(target_baud),
parity=str(target_parity),
timeout=EXBD_WRITE_FAST_TIMEOUT,
retries=0,
include_summary=False,
)
write_debug["immediate_target_verify"] = immediate_verify["debug"]
if immediate_verify["ok"]:
final_detected = {
"slave": immediate_verify["current"]["slave"],
"baud": immediate_verify["current"]["baud"],
"parity": immediate_verify["current"]["parity"],
}
success_message = f"Write verified. Device is now reachable at slave {final_detected['slave']} with baud {final_detected['baud']}"
if serial_write_ack_timed_out:
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": success_message,
"write_baudrate": int(write_baud),
"current_requested": current,
"target_requested": target,
"write_sent": True,
"target_verified": True,
"rediscovery_attempted": False,
"rediscovery_found": True,
"found": True,
"final_detected_config": final_detected,
"recommended_next_step": success_message,
"operation_log": operations + [{"level": "success", "message": f"Readback confirmed new baud {final_detected['baud']}"}],
"debug": write_debug,
}
append_audit({
"action": "write_config",
"port": port,
"family": family,
"current": current,
"target": target,
"strategy": strategy_value,
"status": "verified_target",
"success": True,
"final_detected_config": final_detected,
"source": source,
})
return payload
payload = {
"ok": False,
"stage": "post_write_validation",
"status": "write_unconfirmed",
"message": "Baud write was sent, but readback on the new baud rate did not confirm the change",
"write_baudrate": int(write_baud),
"current_requested": current,
"target_requested": target,
"write_sent": True,
"target_verified": False,
"rediscovery_attempted": False,
"rediscovery_found": False,
"found": False,
"final_detected_config": None,
"recommended_next_step": f"Re-read ExBd on slave {current_slave} at baud {target_baud}",
"operation_log": operations + [{"level": "error", "message": f"Readback on new baud {target_baud} failed"}],
"debug": write_debug,
}
append_audit({
"action": "write_config",
"port": port,
"family": family,
"current": current,
"target": target,
"strategy": strategy_value,
"status": "write_unconfirmed",
"success": False,
"write_sent": True,
"target_verified": False,
"source": source,
})
return payload
if id_changed:
operations.append({
"level": "info",
@ -2289,7 +2804,7 @@ def write_device_config(
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)
time.sleep(EXBD_WRITE_POST_SLEEP if exbd_fast_id_write else 0.8)
else:
payload = {
"ok": False,
@ -2323,7 +2838,7 @@ def write_device_config(
return payload
else:
operations.append({"level": "success", "message": "Slave ID write command completed"})
time.sleep(0.8)
time.sleep(EXBD_WRITE_POST_SLEEP if exbd_fast_id_write else 0.8)
if serial_changed:
comm_value = int(target_comm_profile_value) if target_comm_profile_value is not None else encode_comm_profile(profile, target_baud, target_parity)
@ -2400,8 +2915,9 @@ def write_device_config(
slave=int(target_slave),
baud=int(target_baud),
parity=str(target_parity),
timeout=DEFAULT_DISCOVER_TIMEOUT,
timeout=EXBD_WRITE_FAST_TIMEOUT if exbd_fast_id_write else DEFAULT_DISCOVER_TIMEOUT,
retries=0,
include_summary=not exbd_fast_id_write,
)
write_debug["immediate_target_verify"] = immediate_verify["debug"]
if id_write_ack_timed_out and id_changed:
@ -2411,8 +2927,9 @@ def write_device_config(
slave=int(current_slave),
baud=int(write_baud),
parity=str(current_parity),
timeout=DEFAULT_DISCOVER_TIMEOUT,
timeout=EXBD_WRITE_FAST_TIMEOUT if exbd_fast_id_write else DEFAULT_DISCOVER_TIMEOUT,
retries=0,
include_summary=not exbd_fast_id_write,
)
write_debug["old_slave_verify_after_timeout"] = old_slave_verify["debug"]
if old_slave_verify["ok"]:
@ -2650,6 +3167,11 @@ def write_register(
source: str = "ui",
) -> Dict[str, Any]:
ensure_port_locked(port)
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.",
400,
)
transport = transport_defaults(family)
result = mbpoll_write_register(
port=port,

View File

@ -235,10 +235,17 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
width:100%;
border:1px solid var(--line);
border-radius:12px;
background:var(--surface-soft);
background-color:var(--surface-soft);
background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' viewBox='0 0 22 22'%3E%3Cpath d='M6 8.5 11 13.5 16 8.5' fill='none' stroke='%2366736d' stroke-width='2.4' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
background-repeat:no-repeat;
background-position:right 14px center;
background-size:22px 22px;
color:var(--ink);
padding:10px 12px;
padding:10px 48px 10px 12px;
font:inherit;
appearance:none;
-webkit-appearance:none;
-moz-appearance:none;
}
.menuSelect:focus-visible{
outline:none;
@ -812,12 +819,71 @@ html[dir="rtl"] .itscreenLogsActions{
width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel);color:var(--ink);
}
.field select{
width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel);color:var(--ink);
width:100%;
padding:10px 48px 10px 12px;
border-radius:12px;
border:1px solid var(--line);
background-color:var(--panel);
background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' viewBox='0 0 22 22'%3E%3Cpath d='M6 8.5 11 13.5 16 8.5' fill='none' stroke='%2366736d' stroke-width='2.4' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
background-repeat:no-repeat;
background-position:right 14px center;
background-size:22px 22px;
color:var(--ink);
appearance:none;
-webkit-appearance:none;
-moz-appearance:none;
}
.field input:hover{border-color:var(--line)}
.field select:hover{border-color:var(--line)}
.field input:focus-visible{border-color:var(--accent)}
.field select:focus-visible{border-color:var(--accent)}
.numberStepper{
display:grid;
grid-template-columns:minmax(0,1fr) auto;
gap:8px;
align-items:stretch;
}
.numberStepper input{
min-width:0;
}
.numberStepper input[type="number"]{
-moz-appearance:textfield;
}
.numberStepper input[type="number"]::-webkit-outer-spin-button,
.numberStepper input[type="number"]::-webkit-inner-spin-button{
-webkit-appearance:none;
margin:0;
}
.numberStepperButtons{
display:grid;
grid-template-columns:repeat(2,minmax(40px,40px));
gap:6px;
}
.numberStepperBtn{
border:1px solid var(--line);
border-radius:12px;
background:var(--surface-soft);
color:var(--ink);
font:inherit;
font-size:20px;
font-weight:700;
line-height:1;
cursor:pointer;
min-width:40px;
padding:0;
}
.numberStepperBtn:hover:not(:disabled){
background:var(--surface-muted);
border-color:var(--line);
}
.numberStepperBtn:focus-visible{
outline:none;
box-shadow:0 0 0 3px rgba(14,122,83,.18);
}
.numberStepperBtn:disabled{
opacity:.5;
cursor:not-allowed;
}
.wrapValue{
display:flex;
align-items:center;
@ -1143,6 +1209,11 @@ html[dir="rtl"] .itscreenLogsActions{
.technicalDetails .diagBlock{
margin-top:10px;
max-height:260px;
max-width:100%;
overflow:auto;
white-space:pre;
word-break:normal;
overflow-wrap:normal;
}
.modbusSummaryMeta{
margin-top:12px;
@ -1162,6 +1233,9 @@ html[dir="rtl"] .itscreenLogsActions{
.writeLogCard{
margin-top:14px;
}
.modbusWriteApplyRow{
margin-top:28px;
}
.panel.is-disabled{
opacity:.6;
}
@ -1183,6 +1257,12 @@ html[dir="rtl"] .itscreenLogsActions{
font-size:12px;
line-height:1.5;
}
#modbusWriteApplyBtn{
background:#0e7a53;
}
#modbusWriteApplyBtn:hover:not(:disabled){
background:#129866;
}
.modalBackdrop{
position:fixed;
inset:0;

View File

@ -314,6 +314,28 @@
return encodeURIComponent((value ?? "").toString());
}
function renderNumberStepperInput(options) {
const id = textValue(options && options.id, "");
const value = options && typeof options.value !== "undefined" ? options.value : "";
const min = options && typeof options.min !== "undefined" ? ` min="${esc(options.min)}"` : "";
const max = options && typeof options.max !== "undefined" ? ` max="${esc(options.max)}"` : "";
const step = options && typeof options.step !== "undefined" ? ` step="${esc(options.step)}"` : "";
const inputMode = textValue(options && options.inputMode, "");
const oninput = textValue(options && options.oninput, "");
const onkeydown = textValue(options && options.onkeydown, "");
const onblur = textValue(options && options.onblur, "");
const disabled = options && options.disabled ? " disabled" : "";
return `
<div class="numberStepper">
<input${id ? ` id="${esc(id)}"` : ""} type="number"${min}${max}${step}${inputMode ? ` inputmode="${esc(inputMode)}"` : ""} value="${esc(value)}"${disabled}${onkeydown ? ` onkeydown="${esc(onkeydown)}"` : ""}${oninput ? ` oninput="${esc(oninput)}"` : ""}${onblur ? ` onblur="${esc(onblur)}"` : ""}>
<div class="numberStepperButtons">
<button class="numberStepperBtn" type="button"${disabled} onclick="window.__stepNumberInput('${esc(id)}', -1)">-</button>
<button class="numberStepperBtn" type="button"${disabled} onclick="window.__stepNumberInput('${esc(id)}', 1)">+</button>
</div>
</div>
`;
}
function textValue(value, fallback) {
const text = (value ?? "").toString().trim();
return text || fallback;
@ -2438,6 +2460,24 @@
return !!(modbusConfigPanelReady() && modbusEditorFamily());
}
function modbusEm01FamilySelected() {
const profile = modbusSelectedProfile() || {};
return profile.family === "iomx_em_01";
}
function modbusExbdFamilySelected() {
const profile = modbusSelectedProfile() || {};
return profile.family === "exbd_nano";
}
function modbusEm01BaudComment() {
return t("Baud rate is not changeable on EM-01. Register 0x62 updates, but actual UART speed remains 9600.");
}
function modbusExbdParityComment() {
return t("Parity is fixed to none on ExBd for baud rate configuration.");
}
function modbusWriteCapabilities() {
const log = modbusState();
const currentConfig = log.currentConfig && log.currentConfig.current_config;
@ -2456,6 +2496,7 @@
}
function normalizeModbusWriteStrategy(value) {
if (modbusEm01FamilySelected()) return "id";
const raw = String(value || "").trim().toLowerCase();
if (raw === "serial_only" || raw === "baud_only") return "baud";
if (raw === "id_only") return "id";
@ -2490,6 +2531,7 @@
if (!capabilities.supportsIdWrite) return t("Slave ID write is not configured for this device family.");
return modbusWriteSlaveValidationError(log.writeForm.slave);
}
if (modbusEm01FamilySelected()) return modbusEm01BaudComment();
if (strategy === "baud" && !capabilities.supportsSerialWrite) {
return t("Baud rate write is not configured for this device family.");
}
@ -2583,6 +2625,10 @@
}));
}
function modbusDiscoveryBaudOptions() {
return [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200];
}
function modbusWriteTargetFromForm(current) {
const log = modbusState();
const profile = modbusSelectedProfile() || {};
@ -2616,6 +2662,14 @@
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);
if (modbusExbdFamilySelected()) {
log.writeForm.parity = "none";
}
if (modbusEm01FamilySelected()) {
log.writeForm.baud = "9600";
log.writeForm.parity = "none";
log.writeForm.strategy = "id";
}
}
function updateModbusWriteFormUi() {
@ -2651,7 +2705,7 @@
const currentMeta = currentConfig.current_config || {};
return {
slave: textValue(currentMeta.slave_id, textValue(current.slave, "-")),
baud: textValue(currentMeta.baud, textValue(current.baud, t("Unknown"))),
baud: textValue(currentMeta.baud, textValue(current.baud, modbusEm01FamilySelected() ? "9600" : t("Unknown"))),
parity: textValue(currentMeta.parity, textValue(current.parity, t("Unknown"))),
status: textValue(log.lastWriteResult && log.lastWriteResult.status, textValue(currentConfig.status, modbusRawMode() ? "raw" : "-"))
};
@ -2877,8 +2931,6 @@
{ label: t("Parity"), value: textValue(selectedDevice.parity, "-") },
{ label: t("Detected family"), value: textValue(detection.familyLabel, t("Unknown device")) },
{ label: t("Model string"), value: textValue(detection.modelString, textValue(detection.rawValue, "-")) },
{ label: t("Detection register source(s)"), value: modbusDetectionRegisterSource(detection) },
{ label: t("Raw family register"), value: textValue(detection.rawValue, "-") },
];
return `<div class="meta compactMeta">${renderKeyValueRows(rows)}</div>`;
}
@ -2905,12 +2957,7 @@
{ label: t("Model string"), value: textValue(summary.modelString, textValue(detection.modelString, textValue(detection.rawValue, "-"))) },
{ label: t("Firmware string"), value: textValue(summary.firmwareString, "-") },
{ label: t("Firmware version numeric"), value: textValue(firmwareVersion.display, "-") },
{ label: t("Firmware suffix"), value: textValue(firmwareVersion.suffix, t("Not specified")) },
{ label: t("Serial number"), value: textValue(serial.cleaned, "-") },
{ label: t("Raw serial data"), value: textValue(serial.raw, textValue(serial.hex, "-")) },
{ label: t("Input/output relationship"), value: summary.relationshipLabel ? `${textValue(summary.relationshipCode, "-")} (${summary.relationshipLabel})` : textValue(summary.relationshipCode, "-") },
{ label: t("Detection register source(s)"), value: modbusDetectionRegisterSource(detection) },
{ label: t("Raw family register"), value: textValue(detection.rawValue, textValue(summary.modelRaw, "-")) },
{ label: t("Last successful read"), value: formatTimestamp(currentConfig.last_successful_read) },
{ label: t("Last communication timestamp"), value: formatTimestamp(currentConfig.last_communication_timestamp) }
];
@ -3005,7 +3052,14 @@
<div class="modbusGrid">
<label class="field">
<span>${esc(t("Slave ID"))}</span>
<input type="number" min="1" max="247" value="${esc(log.writeForm.slave)}" oninput="window.__modbusSetWriteField('slave', this.value)">
${renderNumberStepperInput({
id: "modbusRawSlaveInput",
value: log.writeForm.slave,
min: 1,
max: 247,
step: 1,
oninput: "window.__modbusSetWriteField('slave', this.value)"
})}
</label>
<label class="field">
<span>${esc(t("Baud Rate"))}</span>
@ -3019,7 +3073,13 @@
</label>
<label class="field">
<span>${esc(t("Register address"))}</span>
<input type="number" min="0" value="${esc(log.registerForm.address)}" oninput="window.__modbusSetRegisterField('address', this.value)">
${renderNumberStepperInput({
id: "modbusRegisterAddressInput",
value: log.registerForm.address,
min: 0,
step: 1,
oninput: "window.__modbusSetRegisterField('address', this.value)"
})}
</label>
<label class="field">
<span>${esc(t("Function / register type"))}</span>
@ -3029,7 +3089,14 @@
</label>
<label class="field">
<span>${esc(t("Count / payload length"))}</span>
<input type="number" min="1" max="20" value="${esc(log.registerForm.count)}" oninput="window.__modbusSetRegisterField('count', this.value)">
${renderNumberStepperInput({
id: "modbusRegisterCountInput",
value: log.registerForm.count,
min: 1,
max: 20,
step: 1,
oninput: "window.__modbusSetRegisterField('count', this.value)"
})}
</label>
<label class="field">
<span>${esc(t("Decode mode"))}</span>
@ -3039,7 +3106,12 @@
</label>
<label class="field">
<span>${esc(t("Value / payload"))}</span>
<input type="number" value="${esc(log.registerForm.value)}" oninput="window.__modbusSetRegisterField('value', this.value)">
${renderNumberStepperInput({
id: "modbusRegisterValueInput",
value: log.registerForm.value,
step: 1,
oninput: "window.__modbusSetRegisterField('value', this.value)"
})}
</label>
</div>
<div class="actionRow">
@ -3065,6 +3137,7 @@
const scanLogLines = modbusDiscoveryLogLines();
const writeCurrentConfig = modbusWriteCurrentConfigView();
const writeBaudOptions = modbusWriteBaudOptions();
const discoveryBaudOptions = modbusDiscoveryBaudOptions();
syncModbusWriteFormFromConfig();
return `
@ -3082,15 +3155,31 @@
</label>
<label class="field">
<span>${esc(t("Slave from"))}</span>
<input type="number" min="1" max="247" value="${esc(log.discovery.slaveFrom)}" oninput="window.__modbusSetDiscovery('slaveFrom', this.value)">
${renderNumberStepperInput({
id: "modbusDiscoverySlaveFromInput",
value: log.discovery.slaveFrom,
min: 1,
max: 247,
step: 1,
oninput: "window.__modbusSetDiscovery('slaveFrom', this.value)"
})}
</label>
<label class="field">
<span>${esc(t("Slave to"))}</span>
<input type="number" min="1" max="247" value="${esc(log.discovery.slaveTo)}" oninput="window.__modbusSetDiscovery('slaveTo', this.value)">
${renderNumberStepperInput({
id: "modbusDiscoverySlaveToInput",
value: log.discovery.slaveTo,
min: 1,
max: 247,
step: 1,
oninput: "window.__modbusSetDiscovery('slaveTo', this.value)"
})}
</label>
<label class="field">
<span>${esc(t("Baud rate(s)"))}</span>
<input type="text" value="${esc(log.discovery.baudRates)}" oninput="window.__modbusSetDiscovery('baudRates', this.value)">
<span>${esc(t("Baud rate"))}</span>
<select onchange="window.__modbusSetDiscovery('baudRates', this.value)">
${discoveryBaudOptions.map((item) => `<option value="${esc(String(item))}" ${String(log.discovery.baudRates) === String(item) ? "selected" : ""}>${esc(String(item))}</option>`).join("")}
</select>
</label>
<label class="field">
<span>${esc(t("Parity mode(s)"))}</span>
@ -3103,7 +3192,7 @@
</div>
${scanStatus && !scanRunning ? `<div class="formHint">${esc(scanStatus)}</div>` : ""}
<div class="formHint">${esc(t("Detected automatically during discovery"))}</div>
<div class="formHint">${esc(t("Use comma-separated baud rates and parity values if needed, for example 9600,19200 and none,even."))}</div>
<div class="formHint">${esc(t("Select one baud rate for discovery. Parity can still be comma-separated if needed."))}</div>
<article class="scanLogCard">
<div class="cardTop"><div><h2>${esc(t("Scan log"))}</h2></div></div>
<div class="modbusScanLogBody" id="modbusScanLogBody">${scanLogLines.length ? scanLogLines.map((line) => `<div class="logLine">${esc(line)}</div>`).join("") : `<div class="logEmpty">${esc(t("No scan activity yet."))}</div>`}</div>
@ -3129,7 +3218,10 @@
${log.selectedDevice && !modbusConfigPanelReady() ? `<div class="formHint">${esc(t("Read config to activate Configuration Write for the selected device."))}</div>` : ""}
${modbusRequiresLibrarySelection() ? renderModbusDeviceLibrarySelector() : ""}
${modbusStandardEditorEnabled() ? `
${!supportsSerialWrite ? `<div class="formHint">${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}</div>` : ""}
${modbusEm01FamilySelected()
? `<div class="formHint">${esc(modbusEm01BaudComment())}</div>`
: (!supportsSerialWrite ? `<div class="formHint">${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}</div>` : "")
}
<div class="writeConfigSection">
<div class="sectionTitle">${esc(t("Current config"))}</div>
<div class="meta compactMeta modbusSummaryMeta">
@ -3144,6 +3236,7 @@
</div>
<div class="writeConfigSection">
<div class="sectionTitle">${esc(t("New values to write"))}</div>
${modbusEm01FamilySelected() ? "" : `
<label class="field">
<span>${esc(t("Apply strategy"))}</span>
<select id="modbusWriteStrategySelect" onchange="window.__modbusSetWriteField('strategy', this.value)">
@ -3151,28 +3244,51 @@
<option value="baud" ${log.writeForm.strategy === "baud" ? "selected" : ""} ${supportsSerialWrite && writeAccess.enabled ? "" : "disabled"}>${esc(t("Baud rate only"))}</option>
</select>
</label>
`}
<label class="field">
<span>${esc(t("New Slave ID"))}</span>
<input id="modbusWriteSlaveInput" type="number" min="1" max="256" step="1" inputmode="numeric" value="${esc(log.writeForm.slave)}" ${supportsIdWrite && log.writeForm.strategy === "id" ? "" : "disabled"} onkeydown="window.__modbusFilterPositiveIntegerKey(event)" oninput="window.__modbusHandleWriteSlaveInput(this)" onblur="window.__modbusHandleWriteSlaveBlur(this)">
${renderNumberStepperInput({
id: "modbusWriteSlaveInput",
value: log.writeForm.slave,
min: 1,
max: 256,
step: 1,
inputMode: "numeric",
disabled: !(supportsIdWrite && log.writeForm.strategy === "id"),
onkeydown: "window.__modbusFilterPositiveIntegerKey(event)",
oninput: "window.__modbusHandleWriteSlaveInput(this)",
onblur: "window.__modbusHandleWriteSlaveBlur(this)"
})}
</label>
<label class="field">
<span>${esc(t("New Baud Rate"))}</span>
<select id="modbusWriteBaudSelect" ${supportsSerialWrite && log.writeForm.strategy === "baud" ? "" : "disabled"} onchange="window.__modbusSetWriteField('baud', this.value)">
${modbusEm01FamilySelected()
? `<input id="modbusWriteBaudSelect" type="text" value="9600" disabled readonly>`
: `<select id="modbusWriteBaudSelect" ${supportsSerialWrite && log.writeForm.strategy === "baud" ? "" : "disabled"} onchange="window.__modbusSetWriteField('baud', this.value)">
${writeBaudOptions.map((item) => `<option value="${esc(item.value)}" ${String(log.writeForm.baud || "9600") === String(item.value) ? "selected" : ""}>${esc(item.label)}</option>`).join("")}
</select>
</select>`
}
</label>
${modbusEm01FamilySelected() ? `<div class="formHint">${esc(modbusEm01BaudComment())}</div>` : (modbusExbdFamilySelected() ? `
<label class="field">
<span>${esc(t("New Parity"))}</span>
<input type="text" value="none" disabled readonly>
</label>
<div class="formHint">${esc(modbusExbdParityComment())}</div>
` : `
<label class="field">
<span>${esc(t("New Parity"))}</span>
<select onchange="window.__modbusSetWriteField('parity', this.value)">
${["none", "even", "odd"].map((item) => `<option value="${item}" ${log.writeForm.parity === item ? "selected" : ""}>${esc(item)}</option>`).join("")}
</select>
</label>
`)}
<div id="modbusWriteError" class="formHint" ${modbusWriteValidationError() ? "" : "hidden"}>${esc(modbusWriteValidationError())}</div>
</div>
<div class="formHint">${esc(writeAccess.enabled ? t("Configuration write is enabled.") : t("Write is disabled until a device has been selected and its current config has been read."))}</div>
${renderModbusWriteProcessLog()}
<div class="actionRow">
<button id="modbusWriteApplyBtn" class="actionBtn" type="button" ${modbusCanWrite() && !modbusBusy("write_config") ? "" : "disabled"} onclick="window.__modbusApplyConfig()">${esc(modbusBusy("write_config") ? t("Applying...") : t("Apply changes"))}</button>
<div class="actionRow modbusWriteApplyRow">
<button id="modbusWriteApplyBtn" class="actionBtn" type="button" ${modbusCanWrite() && !modbusBusy("write_config") ? "" : "disabled"} onclick="window.__modbusApplyConfig()">${esc(modbusBusy("write_config") ? t("Applying...") : (modbusEm01FamilySelected() ? t("Write Slave ID") : t("Apply changes")))}</button>
</div>
` : ""}
${modbusRawMode() ? renderModbusRawEditor() : ""}
@ -4178,6 +4294,25 @@
modbusState().discovery[field] = value;
};
window.__stepNumberInput = function (inputId, direction) {
const input = inputId ? document.getElementById(inputId) : null;
if (!input || input.disabled) return;
const stepAttr = Number(input.step);
const step = Number.isFinite(stepAttr) && stepAttr > 0 ? stepAttr : 1;
const minAttr = Number(input.min);
const maxAttr = Number(input.max);
const hasMin = input.min !== "" && Number.isFinite(minAttr);
const hasMax = input.max !== "" && Number.isFinite(maxAttr);
const currentAttr = Number(input.value);
let nextValue = Number.isFinite(currentAttr) ? currentAttr : (hasMin ? minAttr : 0);
nextValue += step * (direction < 0 ? -1 : 1);
if (hasMin) nextValue = Math.max(minAttr, nextValue);
if (hasMax) nextValue = Math.min(maxAttr, nextValue);
input.value = String(nextValue);
input.dispatchEvent(new Event("input", { bubbles: true }));
input.focus();
};
window.__modbusSetWriteField = function (field, value) {
const log = modbusState();
if (field === "slave") {

View File

@ -0,0 +1,56 @@
{
"family": "iomx_em_01",
"title": "IOMX EM-01",
"display_name": "IOMX EM-01",
"discovery_enabled": false,
"transport": {
"protocol": "modbus_rtu",
"default_port": "/dev/ttyS3",
"default_baud": 9600,
"default_parity": "none",
"default_databits": 8,
"default_stopbits": 1,
"scan_baud": [9600],
"scan_parity": ["none"],
"zero_based": false
},
"detection": {
"type": "u16",
"function": "holding",
"start": 99,
"count": 1,
"label": "r99 (format)",
"match": ["__iomx_em_01_manual_select__"],
"timeout_quick": 1.8,
"timeout_deep": 3.2
},
"registers": {
"test_read": {
"address": 97,
"count": 1,
"type": "holding"
},
"slave_id": {
"address": 97,
"count": 1,
"type": "holding",
"rw": true
},
"comm_profile": {
"address": 98,
"count": 1,
"type": "holding",
"rw": false
}
},
"summary_registers": {
"format": {
"address": 99,
"count": 1,
"type": "holding",
"decode_mode": "uint16",
"value_format": "uint16",
"label": "r99 (format)"
}
}
}

View File

@ -161,6 +161,7 @@ for path in \
"$SRC_ROOT/backend/modbus_backend.py" \
"$SRC_ROOT/modbus_profiles/ultrasonic_water_meter.json" \
"$SRC_ROOT/modbus_profiles/iomx_nano_exbd_08_16_12.json" \
"$SRC_ROOT/modbus_profiles/iomx_em_01.json" \
"$SRC_ROOT/frontend/index.html" \
"$SRC_ROOT/frontend/console.i18n.js" \
"$SRC_ROOT/frontend/console.js" \