|
| 1 | +"""Common helpers for Modbus operation handlers.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import logging |
| 7 | + |
| 8 | +import toml |
| 9 | +from pymodbus.client import ModbusSerialClient, ModbusTcpClient |
| 10 | + |
| 11 | + |
| 12 | +def parse_json_arguments(arguments: str | list[str]) -> dict: |
| 13 | + """Parse JSON arguments which may be a string or list of segments. |
| 14 | +
|
| 15 | + Raises ValueError on invalid JSON. |
| 16 | + """ |
| 17 | + if isinstance(arguments, str): |
| 18 | + raw = arguments |
| 19 | + else: |
| 20 | + raw = arguments[0] if len(arguments) == 1 else ",".join(arguments) |
| 21 | + try: |
| 22 | + return json.loads(raw) |
| 23 | + except json.JSONDecodeError as err: |
| 24 | + raise ValueError(f"Invalid JSON payload: {err}") from err |
| 25 | + |
| 26 | + |
| 27 | +def resolve_target_device( |
| 28 | + ip_address: str, slave_id: int, devices_path |
| 29 | +) -> tuple[dict, str]: |
| 30 | + """Resolve device connection parameters from ip or devices.toml. |
| 31 | +
|
| 32 | + Returns (target_device, protocol). |
| 33 | + """ |
| 34 | + if ip_address: |
| 35 | + ip = ip_address or "127.0.0.1" |
| 36 | + protocol = "TCP" |
| 37 | + target_device = { |
| 38 | + "protocol": "TCP", |
| 39 | + "ip": ip, |
| 40 | + "port": 502, |
| 41 | + "address": slave_id, |
| 42 | + } |
| 43 | + else: |
| 44 | + devices_cfg = toml.load(devices_path) |
| 45 | + devices = devices_cfg.get("device", []) or [] |
| 46 | + target_device = next( |
| 47 | + (d for d in devices if d.get("address") == slave_id), None |
| 48 | + ) or next((d for d in devices if d.get("protocol") == "TCP"), None) |
| 49 | + if target_device is None: |
| 50 | + raise ValueError(f"No suitable device found in {devices_path}") |
| 51 | + protocol = target_device.get("protocol") |
| 52 | + return target_device, protocol # type: ignore[return-value] |
| 53 | + |
| 54 | + |
| 55 | +def backfill_serial_defaults( |
| 56 | + target_device: dict, protocol: str, base_config: dict |
| 57 | +) -> None: |
| 58 | + """For RTU devices, backfill serial settings from base config if missing.""" |
| 59 | + if protocol == "RTU": |
| 60 | + serial_defaults = base_config.get("serial") or {} |
| 61 | + for key in ["port", "baudrate", "stopbits", "parity", "databits"]: |
| 62 | + if target_device.get(key) is None and key in serial_defaults: |
| 63 | + target_device[key] = serial_defaults[key] |
| 64 | + |
| 65 | + |
| 66 | +def build_modbus_client(target_device: dict, protocol: str): |
| 67 | + """Create a pymodbus client for given target and protocol.""" |
| 68 | + if protocol == "TCP": |
| 69 | + return ModbusTcpClient( |
| 70 | + host=target_device["ip"], |
| 71 | + port=target_device["port"], |
| 72 | + auto_open=True, |
| 73 | + auto_close=True, |
| 74 | + debug=True, |
| 75 | + ) |
| 76 | + if protocol == "RTU": |
| 77 | + return ModbusSerialClient( |
| 78 | + port=target_device["port"], |
| 79 | + baudrate=target_device["baudrate"], |
| 80 | + stopbits=target_device["stopbits"], |
| 81 | + parity=target_device["parity"], |
| 82 | + bytesize=target_device["databits"], |
| 83 | + ) |
| 84 | + raise ValueError("Expected protocol to be RTU or TCP. Got " + str(protocol) + ".") |
| 85 | + |
| 86 | + |
| 87 | +def close_client_quietly(client) -> None: |
| 88 | + """Close a pymodbus client and ignore any exceptions.""" |
| 89 | + try: |
| 90 | + client.close() |
| 91 | + except Exception: |
| 92 | + pass |
| 93 | + |
| 94 | + |
| 95 | +def prepare_client( |
| 96 | + ip_address: str, |
| 97 | + slave_id: int, |
| 98 | + devices_path, |
| 99 | + base_config: dict, |
| 100 | +): |
| 101 | + """Resolve target device, backfill defaults, and build a Modbus client.""" |
| 102 | + target_device, protocol = resolve_target_device(ip_address, slave_id, devices_path) |
| 103 | + backfill_serial_defaults(target_device, protocol, base_config) |
| 104 | + return build_modbus_client(target_device, protocol) |
| 105 | + |
| 106 | + |
| 107 | +def apply_loglevel(logger, base_config: dict) -> None: |
| 108 | + """Apply log level from base configuration to given logger.""" |
| 109 | + loglevel = base_config["modbus"].get("loglevel") or "INFO" |
| 110 | + logger.setLevel(getattr(logging, loglevel.upper(), logging.INFO)) |
| 111 | + |
| 112 | + |
| 113 | +def parse_register_params(payload: dict) -> dict: |
| 114 | + """Parse and validate register operation parameters into a single dict. |
| 115 | +
|
| 116 | + Returns a dict with keys: ip_address, slave_id, register, start_bit, num_bits, write_value. |
| 117 | + """ |
| 118 | + ip_address = (payload.get("ipAddress") or "").strip() |
| 119 | + try: |
| 120 | + return { |
| 121 | + "ip_address": ip_address, |
| 122 | + "slave_id": int(payload["address"]), |
| 123 | + "register": int(payload["register"]), |
| 124 | + "start_bit": int(payload.get("startBit", 0)), |
| 125 | + "num_bits": int(payload.get("noBits", 16)), |
| 126 | + "write_value": int(payload["value"]), |
| 127 | + } |
| 128 | + except KeyError as err: |
| 129 | + raise ValueError(f"Missing required field: {err}") from err |
| 130 | + except (TypeError, ValueError) as err: |
| 131 | + raise ValueError(f"Invalid numeric field: {err}") from err |
| 132 | + |
| 133 | + |
| 134 | +def compute_masked_value( |
| 135 | + current_value: int, start_bit: int, num_bits: int, write_value: int |
| 136 | +) -> int: |
| 137 | + """Validate bit-field and compute new register value with masked bits applied.""" |
| 138 | + if start_bit < 0 or num_bits <= 0 or start_bit + num_bits > 16: |
| 139 | + raise ValueError( |
| 140 | + "startBit and noBits must define a range within a 16-bit register" |
| 141 | + ) |
| 142 | + max_value = (1 << num_bits) - 1 |
| 143 | + if write_value < 0 or write_value > max_value: |
| 144 | + raise ValueError(f"value must be within 0..{max_value} for noBits={num_bits}") |
| 145 | + mask = ((1 << num_bits) - 1) << start_bit |
| 146 | + return (current_value & ~mask) | ((write_value << start_bit) & mask) |
0 commit comments