diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index 36e63f0..3ca206e 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -47,10 +47,12 @@ DEFAULT_CONFIG = { } _CACHE = {"expires_at": 0.0, "payload": None} +_HEALTH_SERVICES_CACHE = {"expires_at": 0.0, "payload": None} _CPU_SAMPLE = {"total": None, "idle": None} _NET_SAMPLE = {} _WIFI_SCAN_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 AP_ENV_PATH = "/etc/iomatex/ap.env" WIFI_ENV_PATH = "/etc/iomatex/wifi.env" @@ -800,6 +802,10 @@ def ap_status_card(): def invalidate_cache(): _CACHE["payload"] = None _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): @@ -1317,9 +1323,11 @@ def get_network_summary(): } return { "ok": True, + "generated_at": utc_now_iso(), "iface": iface, "desired_profile": profile, "ap_status": ap_status, + "access_point": normalize_card(ap_status_card()), "wifi": { "connected": wifi_summary["connected"], "state": wifi_summary["state"] or script_status.get("NM_STATE", "unknown"), @@ -1536,13 +1544,8 @@ def load_providers(): return providers -def build_status_payload(): - now = time.time() - cfg = load_config() - if _CACHE["payload"] is not None and now < _CACHE["expires_at"]: - return _CACHE["payload"] - - context = { +def build_provider_context(): + return { "file_exists": file_exists, "any_exists": any_exists, "read_text": read_text, @@ -1554,6 +1557,9 @@ def build_status_payload(): "get_identity_payload": get_identity_payload, "get_audio_diagnostics": get_audio_diagnostics, } + + +def collect_provider_cards(context): cards = [] provider_names = [] for path, provider in load_providers(): @@ -1576,6 +1582,16 @@ def build_status_payload(): result = [result] for card in result or []: 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 = { "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), @@ -1589,6 +1605,34 @@ def build_status_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): payload = build_status_payload() for card in payload.get("services", []): @@ -1620,37 +1664,79 @@ def get_itscreen_service_status(): try: unit = systemd_unit(ITSCREEN_SERVICE_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 { "ok": True, + "id": "itscreen", "name": "itscreen", + "title": "IT-Screen App", "unit": ITSCREEN_SERVICE_UNIT, "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_label": status_label, + "status_text": status_label, "active_state": str(unit.get("active_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: return { "ok": False, + "id": "itscreen", "name": "itscreen", + "title": "IT-Screen App", "unit": ITSCREEN_SERVICE_UNIT, "installed": False, + "configured": False, "active": False, + "state": "unknown", "status": "unknown", "status_label": "Unknown", + "status_text": "Unknown", + "errors": ["Could not read service status"], + "warnings": [], "error": "Could not read service status", "details": str(exc), + "capabilities": { + "can_start": False, + "can_stop": False, + }, } 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, "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): @@ -2239,6 +2325,12 @@ class Handler(BaseHTTPRequestHandler): return self.send_json(payload) 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": try: self.send_json(public_ap_status()) @@ -2539,10 +2631,9 @@ class Handler(BaseHTTPRequestHandler): try: self.send_json(modbus_start_discovery( port=str(payload.get("port", "")), - family=str(payload.get("family", "")), slave_range=list(payload.get("slave_range") or [1, 10]), - baud=int(payload.get("baud", 9600)), - parity=str(payload.get("parity", "none")), + baudrates=list(payload.get("baudrates") or [payload.get("baud", 9600)]), + parities=list(payload.get("parities") or [payload.get("parity", "none")]), deep=bool(payload.get("deep", False)), source="console_ui", )) @@ -2664,7 +2755,9 @@ class Handler(BaseHTTPRequestHandler): self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) return 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: self.send_json({"ok": False, "error": str(exc)}, code=400) except RuntimeError as exc: @@ -2678,7 +2771,9 @@ class Handler(BaseHTTPRequestHandler): self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) return 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: self.send_json({"ok": False, "error": str(exc)}, code=400) except RuntimeError as exc: @@ -2688,7 +2783,9 @@ class Handler(BaseHTTPRequestHandler): return if parsed.path == "/api/itscreen/registration/reset": try: - self.send_json(reset_registration()) + response = reset_registration() + invalidate_cache() + self.send_json(response) except Exception as exc: self.send_json({"ok": False, "error": str(exc)}, code=500) return diff --git a/stage_ui/console_core/backend/modbus_backend.py b/stage_ui/console_core/backend/modbus_backend.py index 5666f50..fb64369 100644 --- a/stage_ui/console_core/backend/modbus_backend.py +++ b/stage_ui/console_core/backend/modbus_backend.py @@ -17,9 +17,11 @@ MODBUS_RUN_DIR = "/run/iomatex" MODBUS_AUDIT_LOG = "/var/log/iomatex-console/modbus-audit.log" ITSCREEN_SERVICE_UNIT = "itscreen-x11.service" DEFAULT_DISCOVER_TIMEOUT = 6.0 +DEFAULT_DISCOVERY_QUICK_TIMEOUT = 1.8 +DEFAULT_DISCOVERY_DEEP_TIMEOUT = 3.2 DISCOVERY_JOBS: Dict[str, Dict[str, Any]] = {} DISCOVERY_JOBS_LOCK = threading.Lock() -SID_WRITE_ACK_OPTIONAL_FAMILIES = {"iomx_nano_exbd_08_16_12"} +SID_WRITE_ACK_OPTIONAL_FAMILIES = {"exbd_nano"} PORT_GLOBS = ( "/dev/ttyS*", @@ -117,6 +119,182 @@ def summarize_text(text: str, limit: int = 4000) -> str: return value[:limit] + f"\n... ({len(value) - limit} more chars)" +def normalize_register_spec(spec: Dict[str, Any], fallback_decode_mode: str = "uint16") -> Dict[str, Any]: + return { + "address": int(spec["address"]), + "count": int(spec.get("count", 1)), + "type": str(spec.get("type", "holding")), + "decode_mode": str(spec.get("decode_mode", fallback_decode_mode)), + "value_format": str(spec.get("value_format", spec.get("format", "")) or "").strip().lower(), + "cleanup": str(spec.get("cleanup", "") or "").strip().lower(), + "label": str(spec.get("label", "") or "").strip(), + "enum_map": { + str(key): str(value) + for key, value in (spec.get("enum_map") or {}).items() + }, + } + + +def decode_register_words(values: List[Any]) -> List[int]: + words: List[int] = [] + for item in values or []: + value = item.get("value") if isinstance(item, dict) else item + try: + words.append(int(value)) + except Exception: + continue + return words + + +def register_words_to_bytes(words: List[int]) -> bytes: + payload = bytearray() + for word in words or []: + normalized = int(word) & 0xFFFF + payload.append((normalized >> 8) & 0xFF) + payload.append(normalized & 0xFF) + return bytes(payload) + + +def clean_printable_string(value: str, *, collapse_spaces: bool = False, token_first: bool = False) -> str: + text = "".join(ch for ch in str(value or "") if 32 <= ord(ch) <= 126) + if collapse_spaces: + text = re.sub(r"\s+", " ", text) + text = text.strip() + if token_first and text: + text = text.split(" ", 1)[0] + return text + + +def decode_register_string(registers: List[Any], *, cleanup: str = "") -> Dict[str, Any]: + words = decode_register_words(registers) + raw_bytes = register_words_to_bytes(words) + raw_text = raw_bytes.decode("latin-1", errors="replace").replace("\x00", "").strip() + sanitized_bytes = bytes(byte for byte in raw_bytes if byte not in (0x00, 0xFF)) + cleaned_text = clean_printable_string( + sanitized_bytes.decode("latin-1", errors="ignore"), + collapse_spaces=cleanup in ("collapse_spaces", "token_first"), + token_first=cleanup == "token_first", + ) + return { + "words": words, + "raw_text": raw_text, + "cleaned": cleaned_text, + "hex": " ".join(f"{byte:02X}" for byte in raw_bytes), + } + + +def decodeRegistersToAscii(registers: List[Any]) -> str: + return decode_register_string(registers, cleanup="collapse_spaces").get("cleaned", "") + + +def map_baud_code(profile: Dict[str, Any], code: Optional[int]) -> Dict[str, Any]: + mapped = { + "code": code, + "baud": None, + "parity": None, + "label": "", + } + decoded = decode_comm_profile(profile, code) + if decoded.get("decoded"): + mapped.update({ + "baud": decoded.get("baud"), + "parity": decoded.get("parity"), + }) + entry = comm_profile_entry_by_register_value(profile, code) if code is not None else None + if entry: + mapped["label"] = str(entry.get("label") or entry.get("baud") or "") + elif mapped["baud"] is not None: + mapped["label"] = str(mapped["baud"]) + return mapped + + +def map_relationship_code(code: Optional[int], enum_map: Dict[str, str]) -> Dict[str, Any]: + normalized = None if code is None else int(code) + label = enum_map.get(str(normalized), "") if normalized is not None else "" + return { + "code": normalized, + "label": label or ("Unknown" if normalized is not None else ""), + } + + +def decode_detection_value(values: List[Any], rule: Dict[str, Any]) -> Dict[str, Any]: + data_type = str(rule.get("data_type") or rule.get("value_format") or "u16").strip().lower() + words = decode_register_words(values) + if data_type in ("string", "ascii"): + decoded = decode_register_string(values, cleanup=str(rule.get("cleanup") or "collapse_spaces")) + return { + "value": decoded["cleaned"] or decoded["raw_text"], + "normalized": str(decoded["cleaned"] or "").strip().lower(), + "raw_text": decoded["raw_text"], + "cleaned": decoded["cleaned"], + "hex": decoded["hex"], + "decoded_values": words, + } + if data_type == "u32": + combined: List[int] = [] + for index in range(0, len(words), 2): + if index + 1 >= len(words): + break + combined.append(((words[index] & 0xFFFF) << 16) | (words[index + 1] & 0xFFFF)) + value = combined[0] if combined else None + return { + "value": value, + "normalized": "" if value is None else str(value), + "raw_text": ",".join(str(item) for item in combined), + "cleaned": "" if value is None else str(value), + "hex": " ".join(f"{item:08X}" for item in combined), + "decoded_values": combined, + } + value = words[0] if words else None + return { + "value": value, + "normalized": "" if value is None else str(value).strip().lower(), + "raw_text": "" if value is None else str(value), + "cleaned": "" if value is None else str(value), + "hex": " ".join(f"{item & 0xFFFF:04X}" for item in words), + "decoded_values": words, + } + + +def format_firmware_version(registers: List[Any]) -> Dict[str, Any]: + words = decode_register_words(registers) + major = words[0] if len(words) > 0 else None + minor = words[1] if len(words) > 1 else None + patch = words[2] if len(words) > 2 else None + suffix = words[3] if len(words) > 3 else None + meaningful_suffix = suffix not in (None, -1, 0, 65535, "") + display = "" + if major is not None and minor is not None and patch is not None: + display = f"{major}.{minor}.{patch}" + if meaningful_suffix: + display = f"{display}-{suffix}" + return { + "major": major, + "minor": minor, + "patch": patch, + "suffix": suffix if meaningful_suffix else None, + "display": display, + "raw": words, + } + + +def transport_defaults(family: str = "") -> Dict[str, Any]: + if str(family or "").strip(): + profile = get_profile(family) + return profile["transport"] + return { + "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": True, + } + + def mbpoll_register_type(register_type: str, decode_mode: str) -> str: reg = str(register_type or "holding").strip().lower() decode = str(decode_mode or "uint16").strip().lower() @@ -377,6 +555,44 @@ def read_profile_register( return result +def read_register_spec( + *, + profile: Dict[str, Any], + port: str, + slave: int, + baud: int, + parity: str, + register: Dict[str, Any], + register_name: str, + timeout: float = DEFAULT_DISCOVER_TIMEOUT, + retries: int = 1, +) -> Dict[str, Any]: + transport = profile["transport"] + result = mbpoll_read( + port=port, + slave=int(slave), + address=int(register["address"]), + count=int(register["count"]), + baud=int(baud), + parity=str(parity), + register_type=str(register["type"]), + data_bits=int(transport["default_databits"]), + stop_bits=int(transport["default_stopbits"]), + zero_based=bool(transport.get("zero_based", True)), + timeout=timeout, + decode_mode=str(register.get("decode_mode", "uint16")), + retries=retries, + ) + result["register_name"] = register_name + result["register"] = { + "address": int(register["address"]), + "count": int(register["count"]), + "type": str(register["type"]), + "label": str(register.get("label") or ""), + } + return result + + def build_probe_diagnostics( *, profile: Dict[str, Any], @@ -521,6 +737,15 @@ def device_probe( timeout=timeout, retries=retries, ) if "comm_profile" in (profile.get("registers") or {}) else None + summary_results = read_summary_registers( + profile=profile, + port=port, + slave=slave, + baud=baud, + parity=parity, + timeout=timeout, + retries=retries, + ) 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 @@ -587,9 +812,26 @@ def device_probe( "supports_serial_write": bool(profile.get("capabilities", {}).get("supports_serial_write")), "supports_id_write": bool(profile.get("capabilities", {}).get("supports_id_write")), }, + "current_config_summary": build_current_config_summary( + profile=profile, + current={ + "slave": current_slave_value, + "baud": current_baud_value, + "parity": current_parity_value, + }, + current_config={ + "comm_profile_register": comm_value, + }, + summary_results=summary_results, + ), "raw_values": { key: [item.get("value") for item in result.get("values", [])] - for key, result in (("test_read", test_result), ("slave_id", slave_result), ("comm_profile", comm_result)) + for key, result in ( + ("test_read", test_result), + ("slave_id", slave_result), + ("comm_profile", comm_result), + *[(f"summary:{key}", value) for key, value in summary_results.items()], + ) if result and result.get("values") }, "test_register": { @@ -600,6 +842,7 @@ def device_probe( "test_read": test_result, "slave_id": slave_result, "comm_profile": comm_result, + "summary_registers": summary_results, "precheck_diagnostics": diagnostics, }, } @@ -770,6 +1013,215 @@ def read_audit(limit: int = 120) -> Dict[str, Any]: return {"ok": True, "entries": rows} +def normalize_detection_config(data: Dict[str, Any], registers: Dict[str, Any]) -> Dict[str, Any]: + detection = data.get("detection") or {} + def normalize_rule(spec: Dict[str, Any], fallback_match=None) -> Dict[str, Any]: + register = normalize_register_spec({ + "address": spec.get("start", spec.get("address")), + "count": spec.get("count", 1), + "type": spec.get("function", spec.get("type", "holding")), + "decode_mode": spec.get("decode_mode", "uint16"), + "value_format": spec.get("value_format", spec.get("type", "")), + "cleanup": spec.get("cleanup", ""), + "label": spec.get("label", ""), + "enum_map": spec.get("enum_map", {}), + }) + patterns = [] + raw_patterns = spec.get("match") + if isinstance(raw_patterns, list): + patterns = [str(item).strip().lower() for item in raw_patterns if str(item).strip()] + elif raw_patterns is not None and str(raw_patterns).strip(): + patterns = [str(raw_patterns).strip().lower()] + elif fallback_match: + patterns = [str(item).strip().lower() for item in fallback_match if str(item).strip()] + return { + "address": int(register["address"]), + "count": int(register["count"]), + "type": str(register["type"]), + "data_type": str(spec.get("type", register.get("value_format", "u16")) or "u16").strip().lower(), + "decode_mode": str(register.get("decode_mode", "uint16")), + "value_format": str(register.get("value_format", "ascii" if str(spec.get("type", "")).strip().lower() == "string" else "") or "").strip().lower(), + "cleanup": str(register.get("cleanup", "collapse_spaces" if str(spec.get("type", "")).strip().lower() == "string" else "") or "").strip().lower(), + "encoding": str(spec.get("encoding", "") or "").strip().lower(), + "label": str(register.get("label", "") or "").strip(), + "match": patterns, + "fallback_on_error_only": bool(spec.get("fallback_on_error_only", True)), + "probe_registers": [ + int(item) + for item in (spec.get("probe_registers") or []) + if str(item).strip() + ], + } + + rules: List[Dict[str, Any]] = [] + if all(key in detection for key in ("type", "function", "start")): + rules.append(normalize_rule(detection)) + for item in detection.get("alternatives") or []: + if isinstance(item, dict): + fallback = detection.get("match") or [] + merged = dict(detection) + merged.update(item) + rules.append(normalize_rule(merged, fallback_match=fallback)) + else: + probes_raw = detection.get("probes") or [] + family_register = detection.get("family_register") or registers.get("family_register") or registers.get("device_model") or registers.get("test_read") + if family_register: + probes_raw = [family_register] + list(probes_raw) + expected_patterns = [] + for item in detection.get("expected_patterns") or []: + if not isinstance(item, dict): + continue + if item.get("raw_contains"): + expected_patterns.append(str(item.get("raw_contains")).strip().lower()) + elif item.get("raw"): + expected_patterns.append(str(item.get("raw")).strip().lower()) + for item in probes_raw: + if isinstance(item, dict): + rules.append(normalize_rule(item, fallback_match=expected_patterns)) + deduped_rules: List[Dict[str, Any]] = [] + seen_rule_keys = set() + for rule in rules: + rule_key = ( + int(rule["address"]), + int(rule["count"]), + str(rule["type"]), + str(rule.get("value_format", "")), + ) + if rule_key in seen_rule_keys: + continue + seen_rule_keys.add(rule_key) + deduped_rules.append(rule) + if not deduped_rules: + raise ApiError(f"Profile {data.get('family', '')} is missing a detection.family_register definition", 500) + return { + "family_register": dict(deduped_rules[0]), + "rules": deduped_rules, + "empty_values": [str(item).strip().lower() for item in (detection.get("empty_values") or ["", "0", "65535"])], + # Quick discovery intentionally uses shorter timeouts and no retries to reduce scan latency. + "timeout_quick": float(detection.get("timeout_quick", DEFAULT_DISCOVERY_QUICK_TIMEOUT)), + "timeout_deep": float(detection.get("timeout_deep", DEFAULT_DISCOVERY_DEEP_TIMEOUT)), + } + + +def detection_register_label(register: Dict[str, Any]) -> str: + label = str(register.get("label") or "").strip() + if label: + return label + return f"{int(register['address'])}/{str(register['type'])}" + + +def normalize_detection_values(result: Dict[str, Any], register: Dict[str, Any]) -> Dict[str, Any]: + values = result.get("values") or [] + raw_values = [str(item.get("raw", "")).strip() for item in values] + raw_registers = decode_register_words(values) + raw_bytes = register_words_to_bytes(raw_registers) + decoded = decode_detection_value(values, register) + decoded_values = decoded["decoded_values"] + data_type = str(register.get("data_type") or register.get("value_format") or "").strip().lower() + if data_type in ("string", "ascii"): + raw_value = decoded["cleaned"] or "" + else: + raw_value = decoded["cleaned"] or decoded["raw_text"] or ",".join(item for item in raw_values if item) + model_string = decoded["cleaned"] if data_type in ("string", "ascii") else "" + raw_text = decoded["raw_text"] or raw_value + return { + "raw_values": raw_values, + "decoded_values": decoded_values, + "raw_value": raw_value, + "raw_text": raw_text, + "model_string": model_string, + "normalized": decoded["normalized"], + "raw_registers": raw_registers, + "raw_bytes_hex": " ".join(f"{byte:02X}" for byte in raw_bytes), + } + + +def is_empty_family_value(profile: Dict[str, Any], raw_value: str, decoded_values: List[Any]) -> bool: + empty_values = set(profile.get("detection", {}).get("empty_values") or []) + normalized_raw = str(raw_value or "").strip().lower() + if normalized_raw in empty_values: + return True + for value in decoded_values: + normalized = str(value).strip().lower() + if normalized in empty_values: + return True + return not normalized_raw and not [item for item in decoded_values if item not in ("", None, 0, 65535)] + + +def match_detection_pattern(patterns: List[str], normalized_value: str, decoded_values: List[Any], data_type: str = "") -> bool: + for pattern in patterns or []: + if pattern and pattern in normalized_value: + return True + if str(data_type or "").strip().lower() in ("string", "ascii"): + return False + normalized_decoded = {str(item).strip().lower() for item in decoded_values if item is not None} + for pattern in patterns or []: + if pattern in normalized_decoded: + return True + return False + + +def evaluate_family_detection(profile: Dict[str, Any], read_result: Dict[str, Any], register: Dict[str, Any]) -> Dict[str, Any]: + normalized = normalize_detection_values(read_result, register) + raw_value = normalized["raw_value"] + decoded_values = normalized["decoded_values"] + model_string = normalized["model_string"] + data_type = str(register.get("data_type") or register.get("value_format") or "").strip().lower() + if match_detection_pattern(register.get("match") or [], normalized.get("normalized") or str(raw_value or "").strip().lower(), decoded_values, data_type): + return { + "state": "recognized", + "familyKey": str(profile["family"]).strip(), + "familyLabel": str(profile["display_name"]).strip(), + "modelString": model_string or raw_value, + "rawValue": raw_value or model_string, + "rawString": normalized.get("raw_text") or "", + "rawRegisters": normalized.get("raw_registers") or [], + "rawBytesHex": normalized.get("raw_bytes_hex") or "", + "register": dict(register), + "detectionRegisters": [dict(item) for item in profile["detection"].get("rules") or [register]], + "matched": True, + } + if is_empty_family_value(profile, raw_value, decoded_values): + return { + "state": "unknown", + "familyKey": "", + "familyLabel": "Unknown device", + "modelString": "", + "rawValue": raw_value, + "rawString": normalized.get("raw_text") or "", + "rawRegisters": normalized.get("raw_registers") or [], + "rawBytesHex": normalized.get("raw_bytes_hex") or "", + "register": dict(register), + "detectionRegisters": [dict(item) for item in profile["detection"].get("rules") or [register]], + "matched": False, + } + return { + "state": "recognized" if not (register.get("match") or []) else "unrecognized_data", + "familyKey": profile["family"] if not (register.get("match") or []) else "", + "familyLabel": profile["display_name"] if not (register.get("match") or []) else "Family register has unknown data", + "modelString": model_string or raw_value, + "rawValue": raw_value, + "rawString": normalized.get("raw_text") or raw_value, + "rawRegisters": normalized.get("raw_registers") or [], + "rawBytesHex": normalized.get("raw_bytes_hex") or "", + "register": dict(register), + "detectionRegisters": [dict(item) for item in profile["detection"].get("rules") or [register]], + "matched": not (register.get("match") or []), + } + + +def profile_detection_score(candidate: Dict[str, Any]) -> int: + detection = candidate.get("familyDetection") or {} + state = str(detection.get("state") or "") + if state == "recognized": + return 3 if detection.get("matched") else 2 + if state == "unrecognized_data": + return 1 + if state == "unknown": + return 0 + return -1 + + def validate_profile(data: Dict[str, Any], source_path: str) -> Dict[str, Any]: if not isinstance(data, dict): raise ApiError(f"Invalid profile format: {source_path}", 500) @@ -783,6 +1235,11 @@ def validate_profile(data: Dict[str, Any], source_path: str) -> Dict[str, Any]: raise ApiError(f"Invalid profile schema: {source_path}", 500) if "address" not in test_read or "count" not in test_read or "type" not in test_read: raise ApiError(f"Profile {family} is missing test_read register", 500) + summary_registers = {} + for name, spec in (data.get("summary_registers") or {}).items(): + if not isinstance(spec, dict): + continue + summary_registers[str(name)] = normalize_register_spec(spec) profile = { "family": family, "title": title or family, @@ -799,6 +1256,8 @@ def validate_profile(data: Dict[str, Any], source_path: str) -> Dict[str, Any]: "zero_based": bool(transport.get("zero_based", True)), }, "registers": registers, + "detection": normalize_detection_config(data, registers), + "summary_registers": summary_registers, "comm_profiles": data.get("comm_profiles") or [], "capabilities": { "supports_id_write": bool((registers.get("slave_id") or {}).get("rw")), @@ -1046,93 +1505,393 @@ def comm_profile_entry_by_register_value(profile: Dict[str, Any], register_value return None +def read_summary_registers( + *, + profile: Dict[str, Any], + port: str, + slave: int, + baud: int, + parity: str, + timeout: float, + retries: int, +) -> Dict[str, Dict[str, Any]]: + summary_results: Dict[str, Dict[str, Any]] = {} + for name, register in (profile.get("summary_registers") or {}).items(): + summary_results[name] = read_register_spec( + profile=profile, + port=port, + slave=slave, + baud=baud, + parity=parity, + register=register, + register_name=f"summary:{name}", + timeout=timeout, + retries=retries, + ) + return summary_results + + +def summarize_register_value(register: Dict[str, Any], result: Optional[Dict[str, Any]]) -> Dict[str, Any]: + if not result or not result.get("ok"): + return {"ok": False} + value_format = str(register.get("value_format") or "").strip().lower() + values = result.get("values") or [] + if value_format == "ascii": + decoded = decode_register_string(values, cleanup=str(register.get("cleanup") or "")) + return { + "ok": True, + "raw": decoded["raw_text"], + "cleaned": decoded["cleaned"], + "hex": decoded["hex"], + "words": decoded["words"], + } + if value_format == "version_tuple": + version = format_firmware_version(values) + return {"ok": True, **version} + if value_format == "enum": + words = decode_register_words(values) + code = words[0] if words else None + enum_mapped = map_relationship_code(code, register.get("enum_map") or {}) + return {"ok": True, **enum_mapped, "raw": words} + words = decode_register_words(values) + return { + "ok": True, + "value": words[0] if words else None, + "raw": words, + } + + +def build_current_config_summary( + *, + profile: Dict[str, Any], + current: Dict[str, Any], + current_config: Dict[str, Any], + summary_results: Dict[str, Dict[str, Any]], +) -> Dict[str, Any]: + summary_registers = profile.get("summary_registers") or {} + model_result = summarize_register_value(summary_registers.get("model_string") or {}, summary_results.get("model_string")) + firmware_result = summarize_register_value(summary_registers.get("firmware_string") or {}, summary_results.get("firmware_string")) + firmware_version_result = summarize_register_value(summary_registers.get("firmware_version") or {}, summary_results.get("firmware_version")) + serial_result = summarize_register_value(summary_registers.get("serial_number") or {}, summary_results.get("serial_number")) + relationship_result = summarize_register_value(summary_registers.get("relationship") or {}, summary_results.get("relationship")) + baud_code = current_config.get("comm_profile_register") + baud_meta = map_baud_code(profile, baud_code) + return { + "familyKey": profile.get("family"), + "familyLabel": profile.get("display_name"), + "modelString": model_result.get("cleaned") or model_result.get("raw") or "", + "modelRaw": model_result.get("raw") or "", + "firmwareString": firmware_result.get("cleaned") or firmware_result.get("raw") or "", + "firmwareRaw": firmware_result.get("raw") or "", + "firmwareVersion": firmware_version_result if firmware_version_result.get("ok") else {}, + "serial": { + "cleaned": serial_result.get("cleaned") or "", + "raw": serial_result.get("raw") or "", + "hex": serial_result.get("hex") or "", + }, + "slaveId": current.get("slave"), + "baudCode": baud_meta.get("code"), + "baudDisplay": baud_meta.get("baud"), + "baudLabel": baud_meta.get("label"), + "parity": current.get("parity"), + "relationshipCode": relationship_result.get("code"), + "relationshipLabel": relationship_result.get("label"), + "detectionRegisters": [dict(item) for item in (profile.get("detection", {}).get("rules") or [])], + "summaryRegisters": { + name: { + "address": int(register["address"]), + "count": int(register["count"]), + "type": str(register["type"]), + } + for name, register in summary_registers.items() + }, + "rawSummary": { + name: result.get("values") if result and result.get("ok") else [] + for name, result in summary_results.items() + }, + } + + def discover_devices( *, port: str, - family: str, slave_range: List[int], - baud: int, - parity: str, + baudrates: List[int], + parities: List[str], deep: bool = False, source: str = "ui", log_collector=None, ) -> Dict[str, Any]: ensure_port_locked(port) - profile = get_profile(family) - reg = profile["registers"]["test_read"] + profiles = load_profiles() 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] + parity_candidates = [str(item).strip().lower() for item in (parities or ["none"]) if str(item).strip()] results = [] operations = [{ "level": "info", - "message": f"Scan started on {port} for {profile['display_name']} at {int(baud)} {str(parity)}", + "message": f"Scan started on {port} for baud(s) {','.join(str(item) for item in baud_candidates)} and parity {','.join(parity_candidates)}", }] if log_collector: log_collector("info", f"Selected port: {port}") - log_collector("info", f"Family: {profile['display_name']}") log_collector("info", f"Slave range: {start_slave}..{end_slave}") - log_collector("info", f"Baud: {int(baud)}") - log_collector("info", f"Parity: {str(parity)}") + log_collector("info", f"Baud rates: {','.join(str(item) for item in baud_candidates)}") + log_collector("info", f"Parity: {','.join(parity_candidates)}") for slave in range(start_slave, end_slave + 1): - operations.append({ - "level": "info", - "message": f"Checking slave {slave} at {int(baud)} {str(parity)}", - }) if log_collector: log_collector("info", f"Checking slave {slave}", slave=slave, phase="check") - read_result = mbpoll_read( - port=port, - slave=slave, - address=int(reg["address"]), - count=int(reg["count"]), - baud=int(baud), - parity=str(parity), - register_type=str(reg["type"]), - data_bits=int(profile["transport"]["default_databits"]), - stop_bits=int(profile["transport"]["default_stopbits"]), - zero_based=bool(profile["transport"].get("zero_based", True)), - timeout=DEFAULT_DISCOVER_TIMEOUT + (1.0 if deep else 0.0), - retries=1 if deep else 0, - ) - if not read_result["ok"]: - error_type = read_result.get("error_type") or "no_response" - friendly = { - "timeout": "no response", - "crc_error": "CRC error", - "port_busy": "port busy", - "modbus_exception": "Modbus exception", - }.get(error_type, error_type.replace("_", " ")) - if log_collector: - log_collector("warn", f"Slave {slave}: {friendly}", slave=slave, result=friendly) - continue - first_value = read_result["values"][0] if read_result["values"] else {} - found = { - "port": port, - "family": family, - "family_display_name": profile["display_name"], - "slave": slave, - "baud": int(baud), - "parity": str(parity), - "test_register": { - "address": int(reg["address"]), - "count": int(reg["count"]), - "type": str(reg["type"]), - "value": first_value.get("value"), - }, - "status": "ok", - "confidence": "high", - "action": "Select", - } - results.append(found) - if log_collector: - log_collector("success", f"Found device at slave {slave}", slave=slave, baud=int(baud), parity=str(parity), result="found") + found = None + for baud in baud_candidates: + if found: + break + for parity in parity_candidates: + operations.append({ + "level": "info", + "message": f"Checking slave {slave} at {int(baud)} {str(parity)}", + }) + best_candidate = None + best_error = "no_response" + for profile in profiles: + for register in profile["detection"].get("rules") or [profile["detection"]["family_register"]]: + register_range_end = int(register["address"]) + int(register["count"]) - 1 + is_string_rule = str(register.get("data_type") or register.get("value_format") or "").strip().lower() in ("string", "ascii") + if log_collector: + log_collector( + "info", + f"Slave {slave}: reading family string registers {int(register['address'])}..{register_range_end} ({str(register['type'])})" if is_string_rule else f"Slave {slave}: reading family register {detection_register_label(register)}", + slave=slave, + baud=int(baud), + parity=str(parity), + register=register, + family=profile["family"], + phase="family_register", + ) + timeout_value = float(profile["detection"]["timeout_deep"] if deep else profile["detection"]["timeout_quick"]) + retries_value = 1 if deep else 0 + read_result = None + if is_string_rule: + read_result = read_register_spec( + profile=profile, + port=port, + slave=slave, + baud=int(baud), + parity=str(parity), + register=register, + register_name="detection_probe", + timeout=timeout_value, + retries=retries_value, + ) + if log_collector: + command = " ".join(str(item) for item in (read_result.get("command") or [])) + if command: + log_collector( + "info", + f"Slave {slave}: MBPOLL COMMAND: {command}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=command, + result="mbpoll_command", + ) + if read_result.get("stdout"): + log_collector( + "info", + f"Slave {slave}: MBPOLL STDOUT: {read_result.get('stdout')}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=read_result.get("stdout") or "", + result="mbpoll_stdout", + ) + if read_result.get("stderr"): + log_collector( + "info", + f"Slave {slave}: MBPOLL STDERR: {read_result.get('stderr')}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=read_result.get("stderr") or "", + result="mbpoll_stderr", + ) + if read_result.get("ok") and log_collector: + block_words = decode_register_words(read_result.get("values") or []) + block_decoded = decode_register_string(read_result.get("values") or [], cleanup=str(register.get("cleanup") or "collapse_spaces")) + log_collector( + "info", + f"Slave {slave}: PARSED REGISTERS: {block_words}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=",".join(str(item) for item in block_words), + result="parsed_registers", + ) + log_collector( + "info", + f"Slave {slave}: DECODED STRING: {block_decoded.get('cleaned') or block_decoded.get('raw_text') or '-'}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=block_decoded.get("cleaned") or block_decoded.get("raw_text") or "", + result="decoded_string", + ) + else: + read_result = read_register_spec( + profile=profile, + port=port, + slave=slave, + baud=int(baud), + parity=str(parity), + register=register, + register_name="detection_probe", + timeout=timeout_value, + retries=retries_value, + ) + if not read_result["ok"]: + best_error = read_result.get("error_type") or best_error + continue + family_detection = evaluate_family_detection(profile, read_result, register) + if log_collector and is_string_rule: + decoded_family = family_detection.get("modelString") or family_detection.get("rawValue") or "" + raw_registers = family_detection.get("rawRegisters") or [] + raw_bytes_hex = family_detection.get("rawBytesHex") or "" + backend_log( + "modbus_detection_string", + port=port, + slave=int(slave), + baud=int(baud), + parity=str(parity), + family=str(profile.get("family") or ""), + register_start=int(register["address"]), + register_count=int(register["count"]), + raw_registers=raw_registers, + raw_bytes_hex=raw_bytes_hex, + decoded_string=decoded_family, + ) + log_collector( + "info", + f"Slave {slave}: RAW REGISTERS ({int(register['address'])}..{register_range_end}): {raw_registers}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=",".join(str(item) for item in raw_registers), + result="raw_registers", + ) + log_collector( + "info", + f"Slave {slave}: RAW BYTES: {raw_bytes_hex or '-'}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=raw_bytes_hex, + result="raw_bytes", + ) + log_collector( + "info", + f"Slave {slave}: DECODED STRING: {decoded_family or '-'}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=decoded_family, + result="decoded_string", + ) + first_value = read_result["values"][0] if read_result["values"] else {} + candidate = { + "port": port, + "slave": slave, + "baud": int(baud), + "parity": str(parity), + "status": "ok", + "confidence": "high" if family_detection["state"] == "recognized" else "medium", + "action": "Select", + "test_register": { + "address": int(register["address"]), + "count": int(register["count"]), + "type": str(register["type"]), + "value": first_value.get("value"), + }, + "familyDetection": family_detection, + "family": str(family_detection.get("familyKey") or ""), + "family_display_name": str(family_detection.get("familyLabel") or ""), + "raw_family_value": str(family_detection.get("rawValue") or ""), + "configReadable": family_detection["state"] == "recognized" and bool(family_detection.get("familyKey")), + } + if not best_candidate or profile_detection_score(candidate) > profile_detection_score(best_candidate): + best_candidate = candidate + if family_detection["state"] == "recognized": + break + if register.get("fallback_on_error_only", True): + break + if best_candidate and best_candidate.get("familyDetection", {}).get("state") == "recognized": + break + if best_candidate: + found = best_candidate + results.append(best_candidate) + detection = best_candidate["familyDetection"] + if log_collector: + if detection["state"] == "recognized": + matched_family = detection["familyLabel"] + detected_label = detection.get("modelString") or matched_family + backend_log( + "modbus_detection_match", + port=port, + slave=int(slave), + baud=int(baud), + parity=str(parity), + family_key=str(detection.get("familyKey") or ""), + family_label=str(matched_family), + model_string=str(detected_label), + ) + log_collector( + "success", + f"Slave {slave}: MATCHED FAMILY: {matched_family}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=detection.get("rawValue", ""), + result="recognized", + ) + elif detection["state"] == "unknown": + log_collector( + "warn", + f"Slave {slave}: empty family register, device remains unknown", + slave=slave, + baud=int(baud), + parity=str(parity), + result="unknown", + ) + else: + log_collector( + "warn", + f"Slave {slave}: family register has unknown data {detection.get('rawValue') or '-'}", + slave=slave, + baud=int(baud), + parity=str(parity), + raw_value=detection.get("rawValue", ""), + result="unrecognized_data", + ) + break + if log_collector: + friendly = { + "timeout": "no response / timeout", + "crc_error": "CRC error", + "port_busy": "port busy", + "modbus_exception": "Modbus exception", + }.get(best_error, str(best_error).replace("_", " ")) + log_collector( + "warn", + f"Slave {slave}: {friendly}", + slave=slave, + baud=int(baud), + parity=str(parity), + result=friendly, + ) append_audit({ "action": "discover", "port": port, - "family": family, "slave_range": [start_slave, end_slave], - "baud": int(baud), - "parity": str(parity), + "baudrates": baud_candidates, + "parities": parity_candidates, "deep": bool(deep), "result_count": len(results), "success": True, @@ -1142,8 +1901,6 @@ def discover_devices( "ok": True, "message": "Discovery completed", "port": port, - "family": family, - "family_display_name": profile["display_name"], "devices": results, "operation_log": operations[-60:], "deep": bool(deep), @@ -1153,25 +1910,23 @@ def discover_devices( def start_discovery( *, port: str, - family: str, slave_range: List[int], - baud: int, - parity: str, + baudrates: List[int], + parities: List[str], deep: bool = False, source: str = "ui", ) -> Dict[str, Any]: ensure_port_locked(port) - profile = get_profile(family) job_id = uuid.uuid4().hex 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] + parity_candidates = [str(item).strip().lower() for item in (parities or ["none"]) if str(item).strip()] job = { "job_id": job_id, "state": "running", "message": "Scanning in progress. It may take some minutes.", "port": port, - "family": family, - "family_display_name": profile["display_name"], "deep": bool(deep), "devices": [], "scan_log": [], @@ -1180,8 +1935,8 @@ def start_discovery( "current_slave": None, "checked": 0, "total": end_slave - start_slave + 1, - "baud": int(baud), - "parity": str(parity), + "baudrates": baud_candidates, + "parities": parity_candidates, "slave_range": [start_slave, end_slave], }, "started_at": utc_now_iso(), @@ -1208,10 +1963,9 @@ def start_discovery( try: result = discover_devices( port=port, - family=family, slave_range=[start_slave, end_slave], - baud=int(baud), - parity=str(parity), + baudrates=baud_candidates, + parities=parity_candidates, deep=bool(deep), source=source, log_collector=log, @@ -1225,8 +1979,8 @@ def start_discovery( "current_slave": end_slave, "checked": end_slave - start_slave + 1, "total": end_slave - start_slave + 1, - "baud": int(baud), - "parity": str(parity), + "baudrates": baud_candidates, + "parities": parity_candidates, "slave_range": [start_slave, end_slave], }, completed_at=utc_now_iso(), @@ -1277,6 +2031,7 @@ def read_device_config( "port": port, "current": probe["current"], "current_config": probe["current_config"], + "current_config_summary": probe.get("current_config_summary") or {}, "raw_values": probe["raw_values"], "test_register": probe["test_register"], "last_successful_read": utc_now_iso(), @@ -1305,13 +2060,11 @@ def rediscover_after_write( target_baud: int, target_parity: str, ) -> Dict[str, Any]: - profile = get_profile(family) same_serial = discover_devices( port=port, - family=family, slave_range=[1, 10], - baud=target_baud, - parity=target_parity, + baudrates=[target_baud], + parities=[target_parity], deep=False, source="rediscovery", ) @@ -1341,16 +2094,16 @@ def rediscover_after_write( "operation_log": [{"level": "warn", "message": f"Rediscovery found device at slave {same_elsewhere['slave']} instead of requested target"}], } + profile = get_profile(family) transport = profile["transport"] deep_devices = [] for scan_baud in [int(item) for item in transport.get("scan_baud", [target_baud])]: for scan_parity in [str(item) for item in transport.get("scan_parity", [target_parity])]: deep = discover_devices( port=port, - family=family, slave_range=[1, 10], - baud=scan_baud, - parity=scan_parity, + baudrates=[scan_baud], + parities=[scan_parity], deep=True, source="rediscovery", ) @@ -1848,7 +2601,7 @@ def read_registers( source: str = "ui", ) -> Dict[str, Any]: ensure_port_locked(port) - profile = get_profile(family) + transport = transport_defaults(family) result = mbpoll_read( port=port, slave=int(slave), @@ -1857,9 +2610,9 @@ def read_registers( baud=int(baud), parity=str(parity), register_type=str(register_type), - data_bits=int(profile["transport"]["default_databits"]), - stop_bits=int(profile["transport"]["default_stopbits"]), - zero_based=bool(profile["transport"].get("zero_based", True)), + data_bits=int(transport["default_databits"]), + stop_bits=int(transport["default_stopbits"]), + zero_based=bool(transport.get("zero_based", True)), decode_mode=str(decode_mode or "uint16"), retries=1, ) @@ -1897,7 +2650,7 @@ def write_register( source: str = "ui", ) -> Dict[str, Any]: ensure_port_locked(port) - profile = get_profile(family) + transport = transport_defaults(family) result = mbpoll_write_register( port=port, slave=int(slave), @@ -1905,9 +2658,9 @@ def write_register( value=int(value), baud=int(baud), parity=str(parity), - data_bits=int(profile["transport"]["default_databits"]), - stop_bits=int(profile["transport"]["default_stopbits"]), - zero_based=bool(profile["transport"].get("zero_based", True)), + data_bits=int(transport["default_databits"]), + stop_bits=int(transport["default_stopbits"]), + zero_based=bool(transport.get("zero_based", True)), ) if not result["ok"]: raise ApiError("Register write failed", 502, json.dumps(result)) diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index dff61e0..515e817 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -997,10 +997,28 @@ html[dir="rtl"] .itscreenLogsActions{ gap:14px; align-items:start; } +.modbusLayout{ + grid-template-columns:repeat(2,minmax(0,1fr)); +} .modbusDiscoveryGrid{ grid-template-columns:repeat(2,minmax(220px,1fr)); 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{ overflow:auto; border:1px solid var(--line); @@ -1055,6 +1073,14 @@ html[dir="rtl"] .itscreenLogsActions{ background:rgba(14,122,83,.12); 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{ display:grid; gap:10px; @@ -1208,8 +1234,10 @@ html[dir="rtl"] .itscreenLogsActions{ .itscreenCards{grid-template-columns:1fr} .itscreenLogsToolbar{grid-template-columns:1fr} .itscreenLogsActions{justify-content:flex-start} + .modbusLayout{grid-template-columns:1fr} .modbusGrid{grid-template-columns:1fr} .modbusDiscoveryGrid{grid-template-columns:1fr} + .modbusBottomRow{grid-template-columns:1fr} .passwordInputRow{grid-template-columns:1fr} .authCard{padding:22px} } diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index a9f85da..af4ac4d 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -144,8 +144,12 @@ const state = { activeTab: "health", + identity: null, status: null, health: null, + healthServices: null, + healthRequest: null, + networkRequest: null, network: null, itscreen: { loading: false, @@ -155,11 +159,15 @@ error: "", details: "", message: "", + registrationRequest: null, + registrationRequestController: null, + registrationLoadedAt: 0, serverMode: "uae", customHost: "", focused: false, loadedAt: 0, request: null, + requestController: null, logs: { buffer: [], queue: [], @@ -192,15 +200,14 @@ stopItscreen: true, restartItscreen: true, port: "/dev/ttyS3", - family: "ultrasonic_water_meter", - mode: "simple", - advancedOpen: false, + family: "", + manualFamily: "", session: null, discovery: { slaveFrom: "1", slaveTo: "10", - baud: "9600", - parity: "none", + baudRates: "9600", + parities: "none", devices: [], lastMode: "quick", jobId: "", @@ -1472,12 +1479,12 @@ } function currentAccessHost() { - const identity = state.status && state.status.identity; + const identity = state.identity || {}; return textValue(identity && identity.endpoint_host, textValue(identity && identity.primary_ipv4, textValue(identity && identity.hostname, window.location.hostname || "localhost"))); } function currentHostLabel() { - const identity = state.status && state.status.identity; + const identity = state.identity || {}; return textValue(identity && identity.host_label, textValue(identity && identity.hostname, window.location.hostname || "localhost")); } @@ -1568,7 +1575,7 @@ } function renderHealthTab() { - const payload = state.status || { services: [], providers: [] }; + const payload = state.healthServices || { services: [] }; const health = state.health || {}; const metrics = [ { label: t("CPU usage"), value: health.cpu_usage_percent === null || health.cpu_usage_percent === undefined ? t("Collecting...") : `${health.cpu_usage_percent}%` }, @@ -1780,7 +1787,7 @@ link_speed: "", is_default_route: network.active_uplink === "eth0" }; - const accessPointCard = (state.status && state.status.services || []).find((item) => item.id === "access_point"); + const accessPointCard = network.access_point || null; return `
@@ -1862,9 +1869,12 @@ const serverHost = itscreenResolvedHost() || t("Not specified"); const lastEvent = payload && payload.last_event || {}; const serviceBusy = busy === "service_start" || busy === "service_stop"; - const canStartService = !!(service.installed && service.status !== "running" && !serviceBusy); - const canStopService = !!(service.installed && service.status !== "stopped" && service.status !== "not_installed" && !serviceBusy); + const capabilities = (service && service.capabilities) || {}; + const canStartService = !!((typeof capabilities.can_start === "boolean" ? capabilities.can_start : (service.installed && service.status !== "running")) && !serviceBusy); + const canStopService = !!((typeof capabilities.can_stop === "boolean" ? capabilities.can_stop : (service.installed && service.status !== "stopped" && service.status !== "not_installed")) && !serviceBusy); const registerHelper = payload && payload.registered ? t("Device is already registered") : (hostError || t("Select the target cloud server and start registration.")); + const serviceWarnings = Array.isArray(service && service.warnings) ? service.warnings : []; + const serviceErrors = Array.isArray(service && service.errors) ? service.errors : []; if (state.itscreen.loading && !hasStatusPayload) { return `
${esc(t("Loading cloud registration status..."))}
`; @@ -1884,12 +1894,16 @@
${esc(t("Service status"))}
${esc(serviceMeta.label)}
${esc(t("Unit"))}
${esc(textValue(service && service.unit, "itscreen-x11.service"))}
+
${esc(t("State"))}
${esc(displayValue(service && service.state, "—"))}
+
${esc(t("Status"))}
${esc(displayValue(service && service.status_text, serviceMeta.label))}
+ ${serviceWarnings.length ? `
${esc(t("Warnings"))}
` : ""} + ${serviceErrors.length ? `
${esc(t("Errors"))}
` : ""} ${service && service.status === "not_installed" ? `
${esc(t("It-screen service is not installed on this device."))}
` : ""} @@ -2383,14 +2397,47 @@ return items.length ? items : fallback; } + function modbusSelectedDetection(device) { + return (device && device.familyDetection) || {}; + } + + function modbusEditorFamily() { + const log = modbusState(); + return textValue(log.family, ""); + } + function modbusSelectedProfile() { - return (modbusState().profiles || []).find((item) => item.family === modbusState().family) || null; + return (modbusState().profiles || []).find((item) => item.family === modbusEditorFamily()) || null; } function modbusSelectedPortStatus() { return (modbusState().ports || []).find((item) => item.port === modbusState().port) || null; } + function modbusHasRecognizedFamily(device) { + const detection = modbusSelectedDetection(device); + return detection.state === "recognized" && !!textValue(detection.familyKey, ""); + } + + function modbusConfigPanelReady() { + const log = modbusState(); + return !!(log.selectedDevice && log.readConfigStatus !== "idle"); + } + + function modbusRequiresLibrarySelection() { + const log = modbusState(); + return !!(modbusConfigPanelReady() && !modbusHasRecognizedFamily(log.selectedDevice) && !modbusEditorFamily()); + } + + function modbusRawMode() { + const log = modbusState(); + return !!(modbusConfigPanelReady() && log.selectedDevice && textValue(log.manualFamily, "") === "__new__"); + } + + function modbusStandardEditorEnabled() { + return !!(modbusConfigPanelReady() && modbusEditorFamily()); + } + function modbusWriteCapabilities() { const log = modbusState(); const currentConfig = log.currentConfig && log.currentConfig.current_config; @@ -2435,7 +2482,8 @@ function modbusWriteValidationError() { const log = modbusState(); - if (!(log.currentConfig && log.selectedDevice)) return ""; + if (modbusRawMode()) return ""; + if (!(log.currentConfig && log.selectedDevice && modbusStandardEditorEnabled())) return ""; const capabilities = modbusWriteCapabilities(); const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); if (strategy === "id") { @@ -2456,7 +2504,13 @@ function modbusWriteAccessState() { const log = modbusState(); if (!log.selectedDevice) { - return { enabled: false, reason: t("Select a device to enable write"), tone: "warn" }; + return { enabled: false, reason: t("Select a discovered device and click Read config."), tone: "warn" }; + } + if (modbusRawMode()) { + return { enabled: true, reason: t("Advanced/raw editor is active for this device."), tone: "success" }; + } + if (!modbusStandardEditorEnabled()) { + return { enabled: false, reason: t("Select device from library to continue"), tone: "warn" }; } if (!modbusHasValidCurrentConfig()) { if (log.readConfigStatus === "error" && log.readConfigMessage) { @@ -2468,6 +2522,7 @@ } function modbusCanWrite() { + if (modbusRawMode()) return false; const log = modbusState(); const capabilities = modbusWriteCapabilities(); const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); @@ -2492,8 +2547,8 @@ const profile = modbusSelectedProfile(); return { slave: 1, - baud: Number(profile && profile.transport && profile.transport.default_baud) || 9600, - parity: textValue(profile && profile.transport && profile.transport.default_parity, "none") + baud: Number(profile && profile.transport && profile.transport.default_baud) || Number(parseIntCsv(log.discovery.baudRates, [9600])[0]) || 9600, + parity: textValue(profile && profile.transport && profile.transport.default_parity, textValue(parseTextCsv(log.discovery.parities, ["none"])[0], "none")) }; } @@ -2512,7 +2567,7 @@ function modbusWriteBaudOptions() { const profile = modbusSelectedProfile() || {}; const profileOptions = Array.isArray(profile.comm_profiles) ? profile.comm_profiles : []; - if (profile.family === "iomx_nano_exbd_08_16_12" && profileOptions.length) { + if (profile.family === "exbd_nano" && profileOptions.length) { return profileOptions.map((item) => ({ value: String(textValue(item.ui_value, item.baud)), label: String(textValue(item.label, item.baud)), @@ -2535,7 +2590,7 @@ if (strategy === "id") { return { target: { slave: Number(log.writeForm.slave) }, strategy }; } - if (profile.family === "iomx_nano_exbd_08_16_12") { + if (profile.family === "exbd_nano") { const selected = modbusWriteBaudOptions().find((item) => String(item.value) === String(log.writeForm.baud)); if (!selected || !Number.isInteger(selected.registerValue)) { return { target: { baud: Number(current.baud) }, strategy }; @@ -2575,13 +2630,13 @@ const validationError = modbusWriteValidationError(); if (strategySelect) strategySelect.value = strategy; if (slaveInput) { - slaveInput.disabled = !writeAccess.enabled || !capabilities.supportsIdWrite || strategy !== "id"; + slaveInput.disabled = !writeAccess.enabled || modbusRawMode() || !capabilities.supportsIdWrite || strategy !== "id"; if (typeof slaveInput.setCustomValidity === "function") { slaveInput.setCustomValidity(slaveInput.disabled ? "" : modbusWriteSlaveValidationError(modbusState().writeForm.slave)); } } - if (strategySelect) strategySelect.disabled = !writeAccess.enabled; - if (baudSelect) baudSelect.disabled = !writeAccess.enabled || !capabilities.supportsSerialWrite || strategy !== "baud"; + if (strategySelect) strategySelect.disabled = !writeAccess.enabled || modbusRawMode(); + if (baudSelect) baudSelect.disabled = !writeAccess.enabled || modbusRawMode() || !capabilities.supportsSerialWrite || strategy !== "baud"; if (applyBtn) applyBtn.disabled = !!(modbusBusy("write_config") || !modbusCanWrite()); if (errorNode) { errorNode.textContent = validationError || writeAccess.reason || ""; @@ -2598,7 +2653,7 @@ slave: textValue(currentMeta.slave_id, textValue(current.slave, "-")), baud: textValue(currentMeta.baud, textValue(current.baud, t("Unknown"))), parity: textValue(currentMeta.parity, textValue(current.parity, t("Unknown"))), - status: textValue(log.lastWriteResult && log.lastWriteResult.status, textValue(currentConfig.status, "-")) + status: textValue(log.lastWriteResult && log.lastWriteResult.status, textValue(currentConfig.status, modbusRawMode() ? "raw" : "-")) }; } @@ -2699,7 +2754,7 @@ function renderModbusLogPanel() { const entries = modbusState().operationLog || []; return ` -
+

${esc(t("Operation Log / Output"))}

${entries.length ? entries.map((entry) => ` @@ -2713,6 +2768,49 @@ `; } + function modbusDeviceStatusMeta(item) { + const detection = modbusSelectedDetection(item); + const family = textValue(detection.familyLabel, t("Unknown device")); + const model = textValue(detection.modelString, ""); + if (detection.state === "recognized") { + return { + label: t("OK"), + tone: "ok", + family: model ? `${family} / ${model}` : family + }; + } + if (detection.state === "unrecognized_data") { + return { + label: t("Family register has unknown data"), + tone: "warn", + family: model || (detection.rawValue ? t("Family register has unknown data: {raw}", { raw: detection.rawValue }) : t("Family register has unknown data")) + }; + } + return { label: t("Unknown device"), tone: "warn", family: t("Unknown device") }; + } + + function modbusSummary(summary, fallback = {}) { + return { ...(fallback || {}), ...((summary && typeof summary === "object") ? summary : {}) }; + } + + function modbusDetectionRegisterSource(detection) { + const registers = Array.isArray(detection && detection.detectionRegisters) ? detection.detectionRegisters : []; + if (registers.length) { + return registers.map((item) => textValue(item.label, `${item.address}/${item.type}`)).join(", "); + } + const register = detection && detection.register; + return register ? textValue(register.label, `${register.address}/${register.type}`) : "-"; + } + + function modbusDetectionDebugValue(detection) { + const decoded = textValue(detection && (detection.modelString || detection.rawValue || detection.rawString), ""); + const rawRegisters = Array.isArray(detection && detection.rawRegisters) ? detection.rawRegisters : []; + if (decoded && rawRegisters.length) return `${decoded} [${rawRegisters.join(", ")}]`; + if (decoded) return decoded; + if (rawRegisters.length) return `[${rawRegisters.join(", ")}]`; + return "-"; + } + function renderModbusFoundDevices() { const devices = modbusState().discovery.devices || []; const log = modbusState(); @@ -2725,25 +2823,30 @@ ${esc(t("Port"))} - ${esc(t("Family"))} ${esc(t("Slave ID"))} ${esc(t("Baud"))} ${esc(t("Parity"))} - ${esc(t("Test register"))} + ${esc(t("Test register / detection register"))} ${esc(t("Status"))} + ${esc(t("Detected family / model"))} + ${esc(t("Raw family register"))} ${esc(t("Action"))} - ${devices.map((item, index) => ` + ${devices.map((item, index) => { + const detection = modbusSelectedDetection(item); + const status = modbusDeviceStatusMeta(item); + return ` ${esc(item.port)} - ${esc(item.family_display_name || item.family)} ${esc(String(item.slave))} ${esc(String(item.baud))} ${esc(item.parity)} - ${esc(String(item.test_register && item.test_register.address))} - ${esc(item.status || "ok")} + ${esc(modbusDetectionRegisterSource(detection))} + ${esc(status.label)} + ${esc(status.family)} + ${esc(modbusDetectionDebugValue(detection))}
@@ -2751,7 +2854,8 @@
- `).join("")} + `; + }).join("")}
@@ -2759,19 +2863,64 @@ } function renderModbusCurrentConfig() { - const currentConfig = modbusState().currentConfig; - if (!currentConfig) { + const selectedDevice = modbusState().selectedDevice; + if (!selectedDevice) { return `
${esc(t("Select a discovered device and read its config."))}
`; } + const detection = modbusSelectedDetection(selectedDevice); + const currentConfig = modbusState().currentConfig; + if (!currentConfig) { + const rows = [ + { label: t("Port"), value: textValue(selectedDevice.port, "-") }, + { label: t("Selected slave"), value: textValue(selectedDevice.slave, "-") }, + { label: t("Baud"), value: textValue(selectedDevice.baud, "-") }, + { 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 `
${renderKeyValueRows(rows)}
`; + } + const summary = modbusSummary(currentConfig.current_config_summary, { + familyLabel: textValue(detection.familyLabel, ""), + modelString: textValue(detection.modelString, ""), + modelRaw: textValue(detection.rawValue, ""), + slaveId: textValue(currentConfig.current_config && currentConfig.current_config.slave_id, textValue(selectedDevice.slave, "")), + baudCode: textValue(currentConfig.current_config && currentConfig.current_config.comm_profile_register, ""), + baudDisplay: textValue(currentConfig.current_config && currentConfig.current_config.baud, textValue(selectedDevice.baud, "")), + parity: textValue(currentConfig.current_config && currentConfig.current_config.parity, textValue(selectedDevice.parity, "")), + firmwareVersion: {}, + serial: {} + }); + const firmwareVersion = modbusSummary(summary.firmwareVersion, {}); + const serial = modbusSummary(summary.serial, {}); const rows = [ - { label: t("Current slave id"), value: textValue(currentConfig.current_config && currentConfig.current_config.slave_id, "-") }, - { label: t("Current baud"), value: textValue(currentConfig.current_config && currentConfig.current_config.baud, t("Unknown")) }, - { label: t("Current parity"), value: textValue(currentConfig.current_config && currentConfig.current_config.parity, t("Unknown")) }, - { label: t("Config register values"), value: JSON.stringify(currentConfig.raw_values || {}) }, + { label: t("Port"), value: textValue(currentConfig.port, textValue(selectedDevice.port, "-")) }, + { label: t("Selected slave"), value: textValue(summary.slaveId, "-") }, + { label: t("Baud"), value: textValue(summary.baudDisplay, t("Unknown")) }, + { label: t("Baud code"), value: textValue(summary.baudCode, "-") }, + { label: t("Parity"), value: textValue(summary.parity, t("Unknown")) }, + { label: t("Detected family"), value: textValue(summary.familyLabel, textValue(detection.familyLabel, t("Unknown device"))) }, + { 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) } ]; - return `
${renderKeyValueRows(rows)}
`; + return ` +
${renderKeyValueRows(rows)}
+
+ ${esc(t("Raw register details"))} +
${esc(JSON.stringify(currentConfig.raw_values || {}, null, 2))}
+
+ `; } function renderModbusReadConfigState() { @@ -2829,6 +2978,79 @@ `; } + function renderModbusDeviceLibrarySelector() { + const log = modbusState(); + const currentValue = textValue(log.manualFamily, ""); + return ` +
+
${esc(t("Device library"))}
+ +
+ `; + } + + function renderModbusRawEditor() { + const log = modbusState(); + return ` +
+
${esc(t("Advanced/raw editor"))}
+
${esc(t("New device (advanced/raw setup)"))}
+
+ + + + + + + + +
+
+ + +
+ ${log.registerForm.lastResult ? `
${esc(JSON.stringify(log.registerForm.lastResult, null, 2))}
` : `
${esc(t("Register explorer is intended for engineering/debug mode."))}
`} +
+ `; + } + function renderModbusTab() { const log = modbusState(); const profile = modbusSelectedProfile(); @@ -2847,27 +3069,10 @@ return `
-
-
-

${esc(t("Device Family"))}

- ${log.error ? `` : ""} - -
${esc(t("Families are loaded from backend profile JSON files."))}
-
-
${esc(t("Default port"))}
${esc(textValue(profileTransport.default_port, "-"))}
-
${esc(t("Default profile"))}
${esc(`${textValue(profileTransport.default_baud, "9600")}-${textValue(profileTransport.default_databits, "8")}${textValue(profileTransport.default_parity, "N")[0].toUpperCase()}${textValue(profileTransport.default_stopbits, "1")}`)}
-
${esc(t("Addressing"))}
${esc(zeroBased ? t("Zero-based") : t("One-based"))}
-
${esc(t("Serial profile write"))}
${esc(supportsSerialWrite ? t("Configured") : t("Not configured"))}
-
-
- +

${esc(t("Discovery"))}

+ ${log.error ? `` : ""}
@@ -2901,7 +3102,8 @@ ${scanRunning ? `
${esc(t("Scanning in progress. It may take some minutes."))}${log.discovery.currentSlave ? ` ${esc(t("Current slave"))}: ${esc(String(log.discovery.currentSlave))}` : ""}${log.discovery.total ? ` (${esc(String(log.discovery.checked || 0))}/${esc(String(log.discovery.total))})` : ""}
` : ""}
${scanStatus && !scanRunning ? `
${esc(scanStatus)}
` : ""} -
${esc(zeroBased ? t("Use zero-based addressing for this device family.") : t("This device family uses one-based addressing."))}
+
${esc(t("Detected automatically during discovery"))}
+
${esc(t("Use comma-separated baud rates and parity values if needed, for example 9600,19200 and none,even."))}

${esc(t("Scan log"))}

${scanLogLines.length ? scanLogLines.map((line) => `
${esc(line)}
`).join("") : `
${esc(t("No scan activity yet."))}
`}
@@ -2913,72 +3115,70 @@ ${renderModbusFoundDevices()}
-
+

${esc(t("Current Config"))}

${renderModbusReadConfigState()} ${renderModbusCurrentConfig()}
-
-

${esc(t("Configuration Write"))}

- ${modbusWriteStatusMeta()} - ${!supportsSerialWrite ? `
${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}
` : ""} - ${writeAccess.enabled ? "" : ``} -
-
${esc(t("Current config"))}
-
- ${renderKeyValueRows([ - { label: t("Slave ID"), value: writeCurrentConfig.slave }, - { label: t("Baud"), value: writeCurrentConfig.baud }, - { label: t("Parity"), value: writeCurrentConfig.parity }, - { label: t("Verification status"), value: writeCurrentConfig.status } - ])} -
-
-
-
${esc(t("New values to write"))}
- - - - -
${esc(modbusWriteValidationError())}
-
-
${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."))}
- ${renderModbusWriteProcessLog()} -
- -
-
- -
-
-

${esc(t("Advanced"))}

-
- -
-
- ${log.advancedOpen ? ` -
-

${esc(t("Session / Port Control"))}

+
+
+

${esc(t("Configuration Write"))}

+ ${modbusWriteStatusMeta()} + ${writeAccess.enabled ? "" : ``} + ${log.selectedDevice && !modbusConfigPanelReady() ? `
${esc(t("Read config to activate Configuration Write for the selected device."))}
` : ""} + ${modbusRequiresLibrarySelection() ? renderModbusDeviceLibrarySelector() : ""} + ${modbusStandardEditorEnabled() ? ` + ${!supportsSerialWrite ? `
${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}
` : ""} +
+
${esc(t("Current config"))}
+
+ ${renderKeyValueRows([ + { label: t("Device family"), value: textValue(profile && profile.display_name, t("Detected automatically during discovery")) }, + { label: t("Slave ID"), value: writeCurrentConfig.slave }, + { label: t("Baud"), value: writeCurrentConfig.baud }, + { label: t("Parity"), value: writeCurrentConfig.parity }, + { label: t("Verification status"), value: writeCurrentConfig.status } + ])} +
+
+
+
${esc(t("New values to write"))}
+ + + + +
${esc(modbusWriteValidationError())}
+
+
${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."))}
+ ${renderModbusWriteProcessLog()} +
+ +
+ ` : ""} + ${modbusRawMode() ? renderModbusRawEditor() : ""} + ${!modbusStandardEditorEnabled() && !modbusRawMode() ? `
${esc(t("Configuration Write stays disabled until a device is selected and family is resolved automatically or from the library."))}
` : ""} +
+ ${esc(t("Session / Port Control"))} ${portInfo.itscreen_running ? `` : ""}
${esc(t("Port status"))}
${esc(textValue(portInfo.status, "-"))}
@@ -2997,42 +3197,13 @@
-
-
- - - - - -
-
- - -
- ${log.registerForm.lastResult ? `
${esc(JSON.stringify(log.registerForm.lastResult, null, 2))}
` : `
${esc(t("Register explorer is intended for engineering/debug mode."))}
`} - ` : `
${esc(t("Simple mode covers acquire, scan, read config, apply changes, rediscovery, and release."))}
`} -
+ +
- ${renderModbusLogPanel()} +
+ ${renderModbusLogPanel()} +
+
`; @@ -3131,6 +3302,7 @@ function updateIdentity(identity) { const safe = identity || {}; + state.identity = safe; nodes.edgeId.textContent = safe.serial_number || "-"; nodes.hostName.textContent = currentHostLabel(); nodes.osLabel.textContent = t("Unified diagnostics, network operations and gateway commissioning."); @@ -3184,8 +3356,8 @@ } function replaceServiceCard(nextCard) { - if (!nextCard || !state.status || !Array.isArray(state.status.services)) return; - state.status.services = state.status.services.map((card) => (card && card.id === nextCard.id ? nextCard : card)); + if (!nextCard || !state.healthServices || !Array.isArray(state.healthServices.services)) return; + state.healthServices.services = state.healthServices.services.map((card) => (card && card.id === nextCard.id ? nextCard : card)); } async function loadStatus() { @@ -3194,15 +3366,54 @@ updateHeaderMeta(state.status); } + function cancelItscreenRequest() { + const requestController = state.itscreen.requestController; + state.itscreen.requestController = null; + if (!requestController || typeof requestController.abort !== "function") return; + requestController.abort(); + } + + function cancelItscreenRegistrationRequest() { + const requestController = state.itscreen.registrationRequestController; + state.itscreen.registrationRequestController = null; + if (!requestController || typeof requestController.abort !== "function") return; + requestController.abort(); + } + async function loadHealth() { - state.health = await fetchJson("/api/health/summary", { cache: "no-store" }); - updateIdentity(state.health.identity || state.status?.identity || {}); + if (state.healthRequest) return state.healthRequest; + state.healthRequest = (async () => { + const [summary, services] = await Promise.all([ + fetchJson("/api/health/summary", { cache: "no-store" }), + fetchJson("/api/health/services", { cache: "no-store" }) + ]); + state.health = summary; + state.healthServices = services; + updateIdentity(summary.identity || services.identity || state.identity || {}); + updateHeaderMeta(services.generated_at ? services : summary); + return summary; + })(); + try { + return await state.healthRequest; + } finally { + state.healthRequest = null; + } } async function loadNetwork() { - state.network = await fetchJson("/api/network/summary", { cache: "no-store" }); - updateIdentity(state.network.identity || state.status?.identity || {}); - syncNetworkFormFromBackend(); + if (state.networkRequest) return state.networkRequest; + state.networkRequest = (async () => { + state.network = await fetchJson("/api/network/summary", { cache: "no-store" }); + updateIdentity(state.network.identity || state.identity || {}); + updateHeaderMeta(state.network); + syncNetworkFormFromBackend(); + return state.network; + })(); + try { + return await state.networkRequest; + } finally { + state.networkRequest = null; + } } async function loadModbus(options = {}) { @@ -3223,17 +3434,11 @@ log.profiles = Array.isArray(profilesPayload.profiles) ? profilesPayload.profiles : []; log.audit = Array.isArray(auditPayload.entries) ? auditPayload.entries : []; if (!log.port && log.ports.length) log.port = log.ports[0].port; - if (!log.family && log.profiles.length) log.family = log.profiles[0].family; - if (log.family && !log.profiles.some((item) => item.family === log.family) && log.profiles.length) { - log.family = log.profiles[0].family; - } - const selectedProfile = modbusSelectedProfile(); - if (selectedProfile && selectedProfile.transport) { - if (!log.port && selectedProfile.transport.default_port) log.port = selectedProfile.transport.default_port; - log.discovery.baud = String(selectedProfile.transport.default_baud || 9600); - log.discovery.parity = textValue(selectedProfile.transport.default_parity, "none"); - log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); - } + if (log.family && !log.profiles.some((item) => item.family === log.family)) log.family = ""; + if (log.manualFamily && log.manualFamily !== "__new__" && !log.profiles.some((item) => item.family === log.manualFamily)) log.manualFamily = ""; + if (!textValue(log.discovery.baudRates, "")) log.discovery.baudRates = "9600"; + if (!textValue(log.discovery.parities, "")) log.discovery.parities = "none"; + log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); if (!log.operationLog.length && log.audit.length) { log.operationLog = log.audit.slice().reverse().map((item) => ({ timestamp: item.timestamp || new Date().toISOString(), @@ -3269,11 +3474,11 @@ } async function requestItscreenStatus() { - return fetchJson("/api/itscreen/status", { cache: "no-store" }); + return fetchJson("/api/itscreen/status", { cache: "no-store", signal: state.itscreen.requestController ? state.itscreen.requestController.signal : undefined }); } async function requestItscreenRuntime() { - const payload = await fetchJson("/api/itscreen/runtime", { cache: "no-store" }); + const payload = await fetchJson("/api/itscreen/runtime", { cache: "no-store", signal: state.itscreen.requestController ? state.itscreen.requestController.signal : undefined }); if (payload.status === "not_installed" || payload.status === "error") { return { current_time: textValue(payload.current_time, ""), @@ -3315,11 +3520,55 @@ }; } - async function loadItscreen(options = {}) { + async function requestItscreenRegistration() { + return fetchJson("/api/itscreen/registration", { + cache: "no-store", + signal: state.itscreen.registrationRequestController ? state.itscreen.registrationRequestController.signal : undefined + }); + } + + async function loadItscreenRegistration(options = {}) { + const force = !!options.force; + const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : 30000; + if (!force && state.itscreen.registrationRequest) return state.itscreen.registrationRequest; + if (!force && state.itscreen.registrationLoadedAt && Date.now() - state.itscreen.registrationLoadedAt < maxAgeMs) { + return itscreenRegistration(); + } + cancelItscreenRegistrationRequest(); + state.itscreen.registrationRequestController = typeof AbortController === "function" ? new AbortController() : null; + state.itscreen.registrationRequest = (async () => { + try { + const payload = await requestItscreenRegistration(); + const nextData = state.itscreen.data || {}; + state.itscreen.data = { ...nextData, registration: payload.ok === false ? (payload.data || nextData.registration || {}) : payload }; + const registration = state.itscreen.data.registration || {}; + state.itscreen.error = registration && registration.ok === false ? (registration.error || t("It-screen status is unavailable")) : ""; + state.itscreen.details = registration && registration.ok === false ? (registration.details || "") : ""; + state.itscreen.registrationLoadedAt = Date.now(); + syncItscreenFormFromBackend(); + if (state.activeTab === "tscreen") renderActiveTab(); + return state.itscreen.data.registration; + } catch (error) { + if (error && error.name === "AbortError") return itscreenRegistration(); + state.itscreen.error = error.message || t("Cloud registration status is unavailable"); + state.itscreen.details = ""; + if (state.activeTab === "tscreen") renderActiveTab(); + return itscreenRegistration(); + } finally { + state.itscreen.registrationRequestController = null; + state.itscreen.registrationRequest = null; + } + })(); + return state.itscreen.registrationRequest; + } + + async function loadItscreenInitialData(options = {}) { const force = !!options.force; const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : 10000; if (!force && state.itscreen.request) return state.itscreen.request; if (!force && state.itscreen.loadedAt && Date.now() - state.itscreen.loadedAt < maxAgeMs) return state.itscreen.data; + cancelItscreenRequest(); + state.itscreen.requestController = typeof AbortController === "function" ? new AbortController() : null; state.itscreen.loading = true; if (force) { state.itscreen.error = ""; @@ -3327,16 +3576,25 @@ } state.itscreen.request = (async () => { try { + // Initial IT-Screen render must not wait on MQTT-backed registration. const [payload, runtime] = await Promise.all([requestItscreenStatus(), requestItscreenRuntime()]); - state.itscreen.data = payload.ok === false ? (payload.data || state.itscreen.data) : payload; + const currentData = state.itscreen.data || {}; + state.itscreen.data = { ...currentData, ...(payload.ok === false ? (payload.data || {}) : payload) }; state.itscreen.runtime = runtime; - const registration = state.itscreen.data && state.itscreen.data.registration; - state.itscreen.error = registration && registration.ok === false ? (registration.error || t("It-screen status is unavailable")) : ""; - state.itscreen.details = registration && registration.ok === false ? (registration.details || "") : ""; + updateIdentity((payload && payload.identity) || state.identity || {}); state.itscreen.loadedAt = Date.now(); - syncItscreenFormFromBackend(); + if (!state.itscreen.registrationLoadedAt || force) { + window.setTimeout(() => { + if (state.activeTab === "tscreen" && state.auth.authenticated) { + loadItscreenRegistration({ force, maxAgeMs: 30000 }).catch(() => {}); + } + }, 0); + } return state.itscreen.data; } catch (error) { + if (error && error.name === "AbortError") { + return state.itscreen.data; + } state.itscreen.error = error.message || t("It-screen status is unavailable"); state.itscreen.details = ""; state.itscreen.runtime = state.itscreen.runtime || { @@ -3359,6 +3617,7 @@ return state.itscreen.data; } finally { state.itscreen.loading = false; + state.itscreen.requestController = null; state.itscreen.request = null; } })(); @@ -3405,15 +3664,16 @@ nodes.refreshBtn.disabled = true; if (nodes.rebootBtn) nodes.rebootBtn.disabled = state.rebootPending; try { - await loadStatus(); - if (state.activeTab === "network") { + if (state.activeTab === "health") { + await Promise.all([loadHealth(), loadItscreenInitialData()]); + } else if (state.activeTab === "network") { await loadNetwork(); } else if (state.activeTab === "modbus") { await loadModbus(); } else if (state.activeTab === "tscreen") { - await loadItscreen(); - } else if (state.activeTab === "health") { - await Promise.all([loadHealth(), loadItscreen()]); + await loadItscreenInitialData(); + } else { + await loadStatus(); } if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive()) && !(preserveEditing && state.activeTab === "tscreen" && itscreenFormIsInteractive())) { renderActiveTab(); @@ -3489,7 +3749,6 @@ apUi.currentPassword = ""; apUi.newPassword = ""; apUi.confirmPassword = ""; - await loadStatus(); await loadNetwork(); renderActiveTab(); } catch (error) { @@ -3521,7 +3780,6 @@ apUi.message = t("Access point password reset to factory mode."); apUi.resetOpen = false; apUi.resetPassword = ""; - await loadStatus(); await loadNetwork(); renderActiveTab(); } catch (error) { @@ -3602,7 +3860,6 @@ state.networkForm.password = ""; state.networkForm.dirty = false; await loadNetwork(); - await loadStatus(); renderActiveTab(); } catch (error) { state.networkForm.error = error.message || t("Failed to apply Wi-Fi profile"); @@ -3628,7 +3885,7 @@ replaceServiceCard(payload.service); } showToast("success", translateUiText(payload.message || t("Restart requested for {serviceId}", { serviceId }))); - await loadStatus(); + await loadHealth(); if (state.activeTab === "health") renderActiveTab(); } catch (error) { showToast("error", error.message || t("Failed to restart {serviceId}", { serviceId })); @@ -3651,7 +3908,7 @@ window.__copyReverseTunnelBootstrap = async function () { try { - const services = (state.status && state.status.services) || []; + const services = (state.healthServices && state.healthServices.services) || []; const card = services.find((item) => item && item.id === "reverse_tunnel"); const command = textValue(card && card.bootstrap_command, ""); if (!command) throw new Error(t("Bootstrap command is unavailable")); @@ -3680,7 +3937,7 @@ }); state.audioActions.results[target] = payload; showToast(payload.result === "success" ? "success" : (payload.result === "busy" ? "warn" : "error"), t("{target} audio test: {result}", { target: target === "hdmi" ? t("HDMI") : t("Analog"), result: payload.result || t("unknown") })); - await loadStatus(); + await loadHealth(); } catch (error) { state.audioActions.results[target] = { result: "failed", @@ -3752,7 +4009,8 @@ window.__itscreenRefresh = async function () { state.itscreen.busyAction = "refresh"; if (state.activeTab === "tscreen") renderActiveTab(); - await loadItscreen({ force: true, maxAgeMs: 0 }); + await loadItscreenInitialData({ force: true, maxAgeMs: 0 }); + await loadItscreenRegistration({ force: true, maxAgeMs: 0 }); state.itscreen.busyAction = ""; if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab(); }; @@ -3789,7 +4047,8 @@ showToast("error", state.itscreen.error); } finally { state.itscreen.busyAction = ""; - await loadItscreen({ force: true, maxAgeMs: 0 }); + await loadItscreenInitialData({ force: true, maxAgeMs: 0 }); + await loadItscreenRegistration({ force: true, maxAgeMs: 0 }); if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab(); } }; @@ -3805,16 +4064,19 @@ headers: { "Content-Type": "application/json" }, body: "{}" }); - state.itscreen.data = payload; + state.itscreen.data = { ...(state.itscreen.data || {}), ...payload }; state.itscreen.error = ""; state.itscreen.details = ""; - await loadStatus(); + replaceServiceCard(payload && payload.service ? payload.service : null); showToast("success", translateUiText(payload.message || t("Service {action}ed", { action }))); } catch (error) { showToast("error", error.message || t("Failed to {action} service", { action })); } finally { state.itscreen.busyAction = ""; - await loadItscreen({ force: true, maxAgeMs: 0 }); + await loadItscreenInitialData({ force: true, maxAgeMs: 0 }); + if (state.activeTab === "health") { + await loadHealth(); + } if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab(); } }; @@ -3840,7 +4102,8 @@ showToast("error", state.itscreen.error); } finally { state.itscreen.busyAction = ""; - await loadItscreen({ force: true, maxAgeMs: 0 }); + await loadItscreenInitialData({ force: true, maxAgeMs: 0 }); + await loadItscreenRegistration({ force: true, maxAgeMs: 0 }); if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab(); } }; @@ -3907,25 +4170,6 @@ if (state.activeTab === "modbus") renderActiveTab(); }; - window.__modbusSetFamily = function (value) { - const log = modbusState(); - log.family = value; - log.currentConfig = null; - log.selectedDevice = null; - log.lastWriteResult = null; - log.readConfigStatus = "idle"; - log.readConfigMessage = ""; - const profile = modbusSelectedProfile(); - if (profile && profile.transport) { - log.discovery.baud = String(profile.transport.default_baud || 9600); - log.discovery.parity = textValue(profile.transport.default_parity, "none"); - log.writeForm.baud = String(profile.transport.default_baud || 9600); - log.writeForm.parity = textValue(profile.transport.default_parity, "none"); - log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); - } - if (state.activeTab === "modbus") renderActiveTab(); - }; - window.__modbusSetToggle = function (field, checked) { modbusState()[field] = !!checked; }; @@ -3980,11 +4224,6 @@ modbusState().registerForm[field] = value; }; - window.__modbusToggleAdvanced = function () { - modbusState().advancedOpen = !modbusState().advancedOpen; - if (state.activeTab === "modbus") renderActiveTab(); - }; - window.__modbusSelectDevice = function (index) { const log = modbusState(); const item = (log.discovery.devices || [])[index]; @@ -3993,14 +4232,33 @@ log.currentConfig = null; log.readConfigStatus = "idle"; log.readConfigMessage = ""; + log.lastWriteResult = null; + log.manualFamily = ""; + log.family = modbusHasRecognizedFamily(item) ? textValue(item.familyDetection && item.familyDetection.familyKey, "") : ""; log.writeForm.slave = String(item.slave); log.writeForm.baud = String(item.baud); log.writeForm.parity = item.parity; log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); + log.registerForm.lastResult = null; appendModbusLog(t("Device selected for configuration work"), "info"); if (state.activeTab === "modbus") renderActiveTab(); }; + window.__modbusSelectLibraryFamily = async function (value) { + const log = modbusState(); + log.manualFamily = value; + log.family = value && value !== "__new__" ? value : ""; + log.currentConfig = null; + log.readConfigStatus = "idle"; + log.readConfigMessage = value === "__new__" ? t("Advanced/raw editor is active for this device.") : ""; + log.lastWriteResult = null; + log.registerForm.lastResult = null; + if (state.activeTab === "modbus") renderActiveTab(); + if (value && value !== "__new__" && log.selectedDevice) { + await executeModbusReadConfig({ familyOverride: value, autoSelected: true }); + } + }; + window.__modbusAcquire = async function () { const log = modbusState(); log.busyAction = "acquire"; @@ -4059,8 +4317,8 @@ const log = modbusState(); const slaveFrom = Number(log.discovery.slaveFrom) || 1; const slaveTo = Number(log.discovery.slaveTo) || 10; - const baud = Number(log.discovery.baud) || 9600; - const parity = textValue(log.discovery.parity, "none"); + const baudrates = parseIntCsv(log.discovery.baudRates, [9600]); + const parities = parseTextCsv(log.discovery.parities, ["none"]); log.busyAction = mode === "deep" ? "scan_deep" : "scan_quick"; log.error = ""; log.discovery.devices = []; @@ -4081,10 +4339,9 @@ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ port: log.port, - family: log.family, slave_range: [slaveFrom, slaveTo], - baud, - parity, + baudrates, + parities, deep: mode === "deep" }) }); @@ -4132,8 +4389,9 @@ await window.__modbusReadConfig(); }; - async function executeModbusReadConfig() { + async function executeModbusReadConfig(options = {}) { const log = modbusState(); + const family = textValue(options.familyOverride, modbusEditorFamily()); log.busyAction = "read_config"; log.error = ""; log.readConfigStatus = "loading"; @@ -4141,6 +4399,22 @@ if (state.activeTab === "modbus") renderActiveTab(); try { const current = modbusCurrentConnection(); + if (!family) { + log.currentConfig = { + ok: true, + status: "unknown", + family: "", + current: current, + current_config: null, + raw_values: {}, + last_successful_read: new Date().toISOString(), + last_communication_timestamp: new Date().toISOString() + }; + log.readConfigStatus = "success"; + log.readConfigMessage = t("Select device from library to continue"); + appendModbusLog(log.readConfigMessage, "warn"); + return; + } await modbusEnsureSession({ stopItscreen: false }); const payload = await fetchJson("/api/modbus/read-config", { method: "POST", @@ -4148,16 +4422,29 @@ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ port: log.port, - family: log.family, + family, slave: current.slave, baud: current.baud, parity: current.parity }) }); log.currentConfig = payload; + const configSummary = modbusSummary(payload.current_config_summary, {}); + log.family = family; log.selectedDevice = { port: log.port, - family: log.family, + family, + familyDetection: { + state: "recognized", + familyKey: family, + familyLabel: textValue(configSummary.familyLabel, textValue((modbusState().profiles || []).find((item) => item.family === family)?.display_name, family)), + modelString: textValue(configSummary.modelString, textValue(log.selectedDevice && log.selectedDevice.familyDetection && log.selectedDevice.familyDetection.modelString, "")), + rawValue: textValue(log.selectedDevice && log.selectedDevice.familyDetection && log.selectedDevice.familyDetection.rawValue, textValue(configSummary.modelRaw, "")), + register: (log.selectedDevice && log.selectedDevice.familyDetection && log.selectedDevice.familyDetection.register) || null, + detectionRegisters: Array.isArray(configSummary.detectionRegisters) && configSummary.detectionRegisters.length + ? configSummary.detectionRegisters + : ((log.selectedDevice && log.selectedDevice.familyDetection && log.selectedDevice.familyDetection.detectionRegisters) || []) + }, slave: payload.current && payload.current.slave || current.slave, baud: payload.current && payload.current.baud || current.baud, parity: textValue(payload.current && payload.current.parity, current.parity) @@ -4167,7 +4454,7 @@ log.writeForm.parity = textValue(payload.current && payload.current.parity, current.parity); log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); log.readConfigStatus = "success"; - log.readConfigMessage = t("Current config read completed"); + log.readConfigMessage = options.autoSelected ? t("Current config read completed") : t("Current config read completed"); ingestModbusPayload(payload); appendModbusLog(log.readConfigMessage, "success"); showToast("success", log.readConfigMessage); @@ -4190,6 +4477,7 @@ window.__modbusApplyConfig = async function () { const log = modbusState(); + if (!modbusEditorFamily()) return; if (!modbusCanWrite()) return; const validationError = modbusWriteValidationError(); if (validationError) { @@ -4218,7 +4506,7 @@ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ port: log.port, - family: log.family, + family: modbusEditorFamily(), current: { slave: Number(current.slave), baud: Number(current.baud), @@ -4281,10 +4569,10 @@ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ port: log.port, - family: log.family, - slave: Number(current.slave), - baud: Number(current.baud), - parity: current.parity, + family: modbusEditorFamily(), + slave: Number(log.writeForm.slave || current.slave), + baud: Number(log.writeForm.baud || current.baud), + parity: textValue(log.writeForm.parity, current.parity), address: Number(log.registerForm.address), count: Number(log.registerForm.count), register_type: log.registerForm.registerType, @@ -4316,10 +4604,10 @@ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ port: log.port, - family: log.family, - slave: Number(current.slave), - baud: Number(current.baud), - parity: current.parity, + family: modbusEditorFamily(), + slave: Number(log.writeForm.slave || current.slave), + baud: Number(log.writeForm.baud || current.baud), + parity: textValue(log.writeForm.parity, current.parity), address: Number(log.registerForm.address), value: Number(log.registerForm.value) }) @@ -4406,6 +4694,7 @@ const nextTab = button.dataset.tab; if (!nextTab || nextTab === state.activeTab) return; if (state.activeTab === "tscreen" && nextTab !== "tscreen") { + cancelItscreenRequest(); deactivateItscreenLogs(); } state.activeTab = nextTab; @@ -4470,6 +4759,7 @@ document.addEventListener("visibilitychange", () => { if (document.hidden) { closeActionMenu(); + cancelItscreenRequest(); deactivateItscreenLogs(); return; } @@ -4496,6 +4786,8 @@ }).catch(() => {}); setInterval(() => { if (!state.auth.authenticated) return; + // IT-Screen uses explicit activation and manual refresh to avoid fetch loops. + if (state.activeTab === "tscreen") return; loadForActiveTab({ preserveEditing: true }).catch(() => {}); }, 15000); })(); diff --git a/stage_ui/console_core/modbus_profiles/iomx_nano_exbd_08_16_12.json b/stage_ui/console_core/modbus_profiles/iomx_nano_exbd_08_16_12.json index e3af7a2..e8a8be1 100644 --- a/stage_ui/console_core/modbus_profiles/iomx_nano_exbd_08_16_12.json +++ b/stage_ui/console_core/modbus_profiles/iomx_nano_exbd_08_16_12.json @@ -1,7 +1,7 @@ { - "family": "iomx_nano_exbd_08_16_12", - "title": "IOMX NANO_ExBd-08/16-12", - "display_name": "IOMX NANO_ExBd-08/16-12", + "family": "exbd_nano", + "title": "ExBd Nano", + "display_name": "ExBd Nano", "transport": { "protocol": "modbus_rtu", "default_port": "/dev/ttyS3", @@ -11,27 +11,86 @@ "default_stopbits": 1, "scan_baud": [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200], "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": { "test_read": { - "address": 1, + "address": 201, "count": 1, "type": "holding" }, "slave_id": { - "address": 252, + "address": 253, "count": 1, "type": "holding", "rw": true }, "comm_profile": { - "address": 254, + "address": 255, "count": 1, "type": "holding", "rw": true } }, + "summary_registers": { + "model_string": { + "address": 201, + "count": 20, + "type": "input", + "decode_mode": "uint16", + "value_format": "ascii", + "cleanup": "collapse_spaces" + }, + "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": [ { "register_value": 0, "baud": 1200, "parity": "none", "label": "1200" }, { "register_value": 1, "baud": 2400, "parity": "none", "label": "2400" }, diff --git a/stage_ui/console_core/modbus_profiles/ultrasonic_water_meter.json b/stage_ui/console_core/modbus_profiles/ultrasonic_water_meter.json index ac5db2c..3f07bf6 100644 --- a/stage_ui/console_core/modbus_profiles/ultrasonic_water_meter.json +++ b/stage_ui/console_core/modbus_profiles/ultrasonic_water_meter.json @@ -13,6 +13,17 @@ "scan_parity": ["none", "even", "odd"], "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": { "test_read": { "address": 0,