modbus not working well

This commit is contained in:
Andrei Smaliak 2026-04-09 11:20:02 +04:00
parent 1193fa6cc1
commit 7f6559d5be
6 changed files with 1603 additions and 363 deletions

View File

@ -47,10 +47,12 @@ DEFAULT_CONFIG = {
} }
_CACHE = {"expires_at": 0.0, "payload": None} _CACHE = {"expires_at": 0.0, "payload": None}
_HEALTH_SERVICES_CACHE = {"expires_at": 0.0, "payload": None}
_CPU_SAMPLE = {"total": None, "idle": None} _CPU_SAMPLE = {"total": None, "idle": None}
_NET_SAMPLE = {} _NET_SAMPLE = {}
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None} _WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
_ITSCREEN_CONFIG_CACHE = {"expires_at": 0.0, "payload": None} _ITSCREEN_CONFIG_CACHE = {"expires_at": 0.0, "payload": None}
_ITSCREEN_STATUS_CACHE = {"expires_at": 0.0, "payload": None}
_WIFI_RESCAN_MIN_INTERVAL_SEC = 30.0 _WIFI_RESCAN_MIN_INTERVAL_SEC = 30.0
AP_ENV_PATH = "/etc/iomatex/ap.env" AP_ENV_PATH = "/etc/iomatex/ap.env"
WIFI_ENV_PATH = "/etc/iomatex/wifi.env" WIFI_ENV_PATH = "/etc/iomatex/wifi.env"
@ -800,6 +802,10 @@ def ap_status_card():
def invalidate_cache(): def invalidate_cache():
_CACHE["payload"] = None _CACHE["payload"] = None
_CACHE["expires_at"] = 0.0 _CACHE["expires_at"] = 0.0
_HEALTH_SERVICES_CACHE["payload"] = None
_HEALTH_SERVICES_CACHE["expires_at"] = 0.0
_ITSCREEN_STATUS_CACHE["payload"] = None
_ITSCREEN_STATUS_CACHE["expires_at"] = 0.0
def parse_key_value_lines(text): def parse_key_value_lines(text):
@ -1317,9 +1323,11 @@ def get_network_summary():
} }
return { return {
"ok": True, "ok": True,
"generated_at": utc_now_iso(),
"iface": iface, "iface": iface,
"desired_profile": profile, "desired_profile": profile,
"ap_status": ap_status, "ap_status": ap_status,
"access_point": normalize_card(ap_status_card()),
"wifi": { "wifi": {
"connected": wifi_summary["connected"], "connected": wifi_summary["connected"],
"state": wifi_summary["state"] or script_status.get("NM_STATE", "unknown"), "state": wifi_summary["state"] or script_status.get("NM_STATE", "unknown"),
@ -1536,13 +1544,8 @@ def load_providers():
return providers return providers
def build_status_payload(): def build_provider_context():
now = time.time() return {
cfg = load_config()
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
return _CACHE["payload"]
context = {
"file_exists": file_exists, "file_exists": file_exists,
"any_exists": any_exists, "any_exists": any_exists,
"read_text": read_text, "read_text": read_text,
@ -1554,6 +1557,9 @@ def build_status_payload():
"get_identity_payload": get_identity_payload, "get_identity_payload": get_identity_payload,
"get_audio_diagnostics": get_audio_diagnostics, "get_audio_diagnostics": get_audio_diagnostics,
} }
def collect_provider_cards(context):
cards = [] cards = []
provider_names = [] provider_names = []
for path, provider in load_providers(): for path, provider in load_providers():
@ -1576,6 +1582,16 @@ def build_status_payload():
result = [result] result = [result]
for card in result or []: for card in result or []:
cards.append(normalize_card(card)) cards.append(normalize_card(card))
return cards, provider_names
def build_status_payload():
now = time.time()
cfg = load_config()
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
return _CACHE["payload"]
cards, provider_names = collect_provider_cards(build_provider_context())
payload = { payload = {
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
@ -1589,6 +1605,34 @@ def build_status_payload():
return payload return payload
def build_health_services_payload():
now = time.time()
cfg = load_config()
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
return _HEALTH_SERVICES_CACHE["payload"]
allowed_ids = {
"itscreen",
"mosquitto",
"mqtt_bridge",
"zigbee2mqtt",
"cockpit",
"reverse_tunnel",
"display",
"edge_api",
}
cards, _ = collect_provider_cards(build_provider_context())
payload = {
"ok": True,
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"identity": get_identity_payload(),
"services": [card for card in cards if card.get("id") in allowed_ids],
}
_HEALTH_SERVICES_CACHE["payload"] = payload
_HEALTH_SERVICES_CACHE["expires_at"] = now + max(1, int(cfg.get("cache_ttl_sec", 3)))
return payload
def find_service_card(service_id): def find_service_card(service_id):
payload = build_status_payload() payload = build_status_payload()
for card in payload.get("services", []): for card in payload.get("services", []):
@ -1620,37 +1664,79 @@ def get_itscreen_service_status():
try: try:
unit = systemd_unit(ITSCREEN_SERVICE_UNIT) unit = systemd_unit(ITSCREEN_SERVICE_UNIT)
status, status_label = normalize_service_status(unit) status, status_label = normalize_service_status(unit)
configured = bool(unit.get("installed"))
active = bool(unit.get("active", False))
errors = []
if unit.get("active_state") == "failed":
errors.append("Service failed")
if unit.get("result") and unit.get("result") not in ("success", "done"):
errors.append(f"Result: {unit['result']}")
if unit.get("exec_main_status") and unit.get("exec_main_status") not in ("0", ""):
errors.append(f"Exit status: {unit['exec_main_status']}")
warnings = []
if bool(unit.get("installed")) and not configured:
warnings.append("Service unit not found")
return { return {
"ok": True, "ok": True,
"id": "itscreen",
"name": "itscreen", "name": "itscreen",
"title": "IT-Screen App",
"unit": ITSCREEN_SERVICE_UNIT, "unit": ITSCREEN_SERVICE_UNIT,
"installed": bool(unit.get("installed", False)), "installed": bool(unit.get("installed", False)),
"active": bool(unit.get("active", False)), "configured": configured,
"active": active,
"state": "active" if active else ("failed" if status == "failed" else ("not installed" if not unit.get("installed") else "inactive")),
"status": status, "status": status,
"status_label": status_label, "status_label": status_label,
"status_text": status_label,
"active_state": str(unit.get("active_state", "") or ""), "active_state": str(unit.get("active_state", "") or ""),
"sub_state": str(unit.get("sub_state", "") or ""), "sub_state": str(unit.get("sub_state", "") or ""),
"errors": errors[:2],
"warnings": warnings[:2],
"capabilities": {
"can_start": bool(unit.get("installed")) and status != "running",
"can_stop": bool(unit.get("installed")) and status not in ("stopped", "not_installed"),
},
} }
except Exception as exc: except Exception as exc:
return { return {
"ok": False, "ok": False,
"id": "itscreen",
"name": "itscreen", "name": "itscreen",
"title": "IT-Screen App",
"unit": ITSCREEN_SERVICE_UNIT, "unit": ITSCREEN_SERVICE_UNIT,
"installed": False, "installed": False,
"configured": False,
"active": False, "active": False,
"state": "unknown",
"status": "unknown", "status": "unknown",
"status_label": "Unknown", "status_label": "Unknown",
"status_text": "Unknown",
"errors": ["Could not read service status"],
"warnings": [],
"error": "Could not read service status", "error": "Could not read service status",
"details": str(exc), "details": str(exc),
"capabilities": {
"can_start": False,
"can_stop": False,
},
} }
def build_itscreen_status_payload(): def build_itscreen_status_payload():
return { now = time.time()
cached = _ITSCREEN_STATUS_CACHE
if cached["payload"] is not None and cached["expires_at"] > now:
return cached["payload"]
payload = {
"ok": True, "ok": True,
"service": get_itscreen_service_status(), "service": get_itscreen_service_status(),
"registration": get_registration_status(), "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"identity": get_identity_payload(),
} }
cached["payload"] = payload
cached["expires_at"] = now + 3.0
return payload
def systemctl_show_property(unit_name, property_name, timeout=5): def systemctl_show_property(unit_name, property_name, timeout=5):
@ -2239,6 +2325,12 @@ class Handler(BaseHTTPRequestHandler):
return return
self.send_json(payload) self.send_json(payload)
return return
if parsed.path == "/api/health/services":
try:
self.send_json(build_health_services_payload())
except Exception as exc:
self.send_json({"ok": False, "error": str(exc), "services": []}, code=500)
return
if parsed.path == "/api/ap/status": if parsed.path == "/api/ap/status":
try: try:
self.send_json(public_ap_status()) self.send_json(public_ap_status())
@ -2539,10 +2631,9 @@ class Handler(BaseHTTPRequestHandler):
try: try:
self.send_json(modbus_start_discovery( self.send_json(modbus_start_discovery(
port=str(payload.get("port", "")), port=str(payload.get("port", "")),
family=str(payload.get("family", "")),
slave_range=list(payload.get("slave_range") or [1, 10]), slave_range=list(payload.get("slave_range") or [1, 10]),
baud=int(payload.get("baud", 9600)), baudrates=list(payload.get("baudrates") or [payload.get("baud", 9600)]),
parity=str(payload.get("parity", "none")), parities=list(payload.get("parities") or [payload.get("parity", "none")]),
deep=bool(payload.get("deep", False)), deep=bool(payload.get("deep", False)),
source="console_ui", source="console_ui",
)) ))
@ -2664,7 +2755,9 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return return
try: try:
self.send_json(register_device(str(payload.get("host", "")))) response = register_device(str(payload.get("host", "")))
invalidate_cache()
self.send_json(response)
except ValueError as exc: except ValueError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=400) self.send_json({"ok": False, "error": str(exc)}, code=400)
except RuntimeError as exc: except RuntimeError as exc:
@ -2678,7 +2771,9 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return return
try: try:
self.send_json(register_device(str(payload.get("host", "")))) response = register_device(str(payload.get("host", "")))
invalidate_cache()
self.send_json(response)
except ValueError as exc: except ValueError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=400) self.send_json({"ok": False, "error": str(exc)}, code=400)
except RuntimeError as exc: except RuntimeError as exc:
@ -2688,7 +2783,9 @@ class Handler(BaseHTTPRequestHandler):
return return
if parsed.path == "/api/itscreen/registration/reset": if parsed.path == "/api/itscreen/registration/reset":
try: try:
self.send_json(reset_registration()) response = reset_registration()
invalidate_cache()
self.send_json(response)
except Exception as exc: except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500) self.send_json({"ok": False, "error": str(exc)}, code=500)
return return

File diff suppressed because it is too large Load Diff

View File

@ -997,10 +997,28 @@ html[dir="rtl"] .itscreenLogsActions{
gap:14px; gap:14px;
align-items:start; align-items:start;
} }
.modbusLayout{
grid-template-columns:repeat(2,minmax(0,1fr));
}
.modbusDiscoveryGrid{ .modbusDiscoveryGrid{
grid-template-columns:repeat(2,minmax(220px,1fr)); grid-template-columns:repeat(2,minmax(220px,1fr));
row-gap:16px; row-gap:16px;
} }
.modbusBottomRow{
display:grid;
grid-template-columns:minmax(0,2fr) minmax(320px,1fr);
gap:18px;
align-items:start;
}
.modbusWriteCard,
.modbusSideColumn,
.modbusLogCard{
min-width:0;
}
.modbusSideColumn{
display:grid;
gap:18px;
}
.modbusTableWrap{ .modbusTableWrap{
overflow:auto; overflow:auto;
border:1px solid var(--line); border:1px solid var(--line);
@ -1055,6 +1073,14 @@ html[dir="rtl"] .itscreenLogsActions{
background:rgba(14,122,83,.12); background:rgba(14,122,83,.12);
color:var(--accent); color:var(--accent);
} }
.statusBadge.is-warn{
background:rgba(154,106,0,.14);
color:var(--warn);
}
.statusBadge.is-error{
background:rgba(196,78,82,.14);
color:var(--danger);
}
.modbusLogPanel{ .modbusLogPanel{
display:grid; display:grid;
gap:10px; gap:10px;
@ -1208,8 +1234,10 @@ html[dir="rtl"] .itscreenLogsActions{
.itscreenCards{grid-template-columns:1fr} .itscreenCards{grid-template-columns:1fr}
.itscreenLogsToolbar{grid-template-columns:1fr} .itscreenLogsToolbar{grid-template-columns:1fr}
.itscreenLogsActions{justify-content:flex-start} .itscreenLogsActions{justify-content:flex-start}
.modbusLayout{grid-template-columns:1fr}
.modbusGrid{grid-template-columns:1fr} .modbusGrid{grid-template-columns:1fr}
.modbusDiscoveryGrid{grid-template-columns:1fr} .modbusDiscoveryGrid{grid-template-columns:1fr}
.modbusBottomRow{grid-template-columns:1fr}
.passwordInputRow{grid-template-columns:1fr} .passwordInputRow{grid-template-columns:1fr}
.authCard{padding:22px} .authCard{padding:22px}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{ {
"family": "iomx_nano_exbd_08_16_12", "family": "exbd_nano",
"title": "IOMX NANO_ExBd-08/16-12", "title": "ExBd Nano",
"display_name": "IOMX NANO_ExBd-08/16-12", "display_name": "ExBd Nano",
"transport": { "transport": {
"protocol": "modbus_rtu", "protocol": "modbus_rtu",
"default_port": "/dev/ttyS3", "default_port": "/dev/ttyS3",
@ -11,27 +11,86 @@
"default_stopbits": 1, "default_stopbits": 1,
"scan_baud": [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200], "scan_baud": [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200],
"scan_parity": ["none", "even", "odd"], "scan_parity": ["none", "even", "odd"],
"zero_based": true "zero_based": false
},
"detection": {
"type": "string",
"function": "input",
"start": 201,
"count": 20,
"encoding": "ascii",
"cleanup": "collapse_spaces",
"label": "201..220 (input)",
"match": ["ExBd", "NANO", "exbd_nano"],
"empty_values": ["", "0", "65535"],
"timeout_quick": 1.8,
"timeout_deep": 3.2
}, },
"registers": { "registers": {
"test_read": { "test_read": {
"address": 1, "address": 201,
"count": 1, "count": 1,
"type": "holding" "type": "holding"
}, },
"slave_id": { "slave_id": {
"address": 252, "address": 253,
"count": 1, "count": 1,
"type": "holding", "type": "holding",
"rw": true "rw": true
}, },
"comm_profile": { "comm_profile": {
"address": 254, "address": 255,
"count": 1, "count": 1,
"type": "holding", "type": "holding",
"rw": true "rw": true
} }
}, },
"summary_registers": {
"model_string": {
"address": 201,
"count": 20,
"type": "input",
"decode_mode": "uint16",
"value_format": "ascii",
"cleanup": "collapse_spaces"
},
"firmware_string": {
"address": 251,
"count": 16,
"type": "input",
"decode_mode": "uint16",
"value_format": "ascii",
"cleanup": "token_first"
},
"firmware_version": {
"address": 321,
"count": 4,
"type": "input",
"decode_mode": "uint16",
"value_format": "version_tuple"
},
"serial_number": {
"address": 267,
"count": 6,
"type": "input",
"decode_mode": "uint16",
"value_format": "ascii"
},
"relationship": {
"address": 254,
"count": 1,
"type": "holding",
"decode_mode": "uint16",
"value_format": "enum",
"enum_map": {
"0": "Unrelated",
"1": "Self-locking",
"2": "Interlocking",
"3": "Momentary",
"4": "Two-channel interlocking"
}
}
},
"comm_profiles": [ "comm_profiles": [
{ "register_value": 0, "baud": 1200, "parity": "none", "label": "1200" }, { "register_value": 0, "baud": 1200, "parity": "none", "label": "1200" },
{ "register_value": 1, "baud": 2400, "parity": "none", "label": "2400" }, { "register_value": 1, "baud": 2400, "parity": "none", "label": "2400" },

View File

@ -13,6 +13,17 @@
"scan_parity": ["none", "even", "odd"], "scan_parity": ["none", "even", "odd"],
"zero_based": true "zero_based": true
}, },
"detection": {
"family_register": {
"address": 0,
"count": 1,
"type": "holding",
"decode_mode": "uint16"
},
"empty_values": ["", "0", "65535"],
"timeout_quick": 1.8,
"timeout_deep": 3.2
},
"registers": { "registers": {
"test_read": { "test_read": {
"address": 0, "address": 0,