"""Deterministic, fixture-only Modbus TCP source and bounded control ledger. Register map (unit 1): 0 counter; 10..12 fixed array; 20..63 writable scalar/ array window. Control calls advance or set values explicitly; wall time never changes samples. A one-shot fault can discard a write response *after* recording its effect, which gives the integration gate a reproducible ambiguous outcome. """ from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json import os import socketserver import struct import threading MODBUS_PORT = 5020 CONTROL_PORT = 8080 MAX_PDU_BYTES = 253 MAX_CONTROL_BYTES = 4096 MAX_LEDGER_ITEMS = 1024 class DeviceState: def __init__(self): self._lock = threading.RLock() self._registers = {0: 0, 10: 7, 11: 11, 12: 13} self._registers.update({address: 0 for address in range(20, 64)}) self._registers.update({24: 7, 25: 11, 26: 13}) text = b"grpc data source" self._registers.update({40 + offset // 2: int.from_bytes(text[offset:offset + 2], "big") for offset in range(0, len(text), 2)}) self._effect_total = 0 self._read_total = 0 self._request_total = 0 self._rejected_write_total = 0 self._effects = deque(maxlen=MAX_LEDGER_ITEMS) self._reads = deque(maxlen=MAX_LEDGER_ITEMS) self._requests = deque(maxlen=MAX_LEDGER_ITEMS) self._rejected_writes = deque(maxlen=MAX_LEDGER_ITEMS) self._drop_next_write_response = False def snapshot(self): with self._lock: return { "counter": self._registers[0], "effect_total": self._effect_total, "read_total": self._read_total, "request_total": self._request_total, "rejected_write_total": self._rejected_write_total, "effects": list(self._effects), "reads": list(self._reads), "requests": list(self._requests), "rejected_writes": list(self._rejected_writes), "writable": {str(address): self._registers[address] for address in range(20, 64)}, "drop_next_write_response": self._drop_next_write_response, } def read(self, address, quantity): if type(address) is not int or type(quantity) is not int or not 1 <= quantity <= 125: raise ValueError("invalid read span") with self._lock: if any(register not in self._registers for register in range(address, address + quantity)): raise ValueError("unmapped read span") return [self._registers[register] for register in range(address, address + quantity)] def record_request(self, unit, pdu, outcome, exception_code=None, transaction=None): """Store only bounded structural metadata, never arbitrary request bytes.""" with self._lock: self._request_total += 1 function = pdu[0] if isinstance(pdu, bytes) and pdu else None record = { "sequence": self._request_total, "transaction": transaction if type(transaction) is int and 0 <= transaction <= 65535 else None, "unit": unit if type(unit) is int and 0 <= unit <= 255 else None, "function": function, "pdu_length": len(pdu) if isinstance(pdu, bytes) else None, "outcome": outcome, } if function in (3, 4, 6, 16) and len(pdu) >= 5: address, quantity = struct.unpack(">HH", pdu[1:5]) record.update(address=address, quantity=1 if function == 6 else quantity) if exception_code is not None: record["exception_code"] = exception_code self._requests.append(record) if function in (3, 4): self._read_total += 1 self._reads.append(dict(record)) if function in (6, 16, 23) and outcome == "exception": self._rejected_write_total += 1 self._rejected_writes.append(dict(record)) def write(self, address, values): if (type(address) is not int or not isinstance(values, list) or not 1 <= len(values) <= 44 or address < 20 or address + len(values) > 64 or any(type(value) is not int or not 0 <= value <= 65535 for value in values)): raise ValueError("write outside bounded fixture window") with self._lock: for offset, value in enumerate(values): self._registers[address + offset] = value self._effect_total += 1 self._effects.append({"sequence": self._effect_total, "address": address, "values": list(values)}) drop = self._drop_next_write_response self._drop_next_write_response = False return drop def apply_control(state, command): if not isinstance(command, dict) or not isinstance(command.get("action"), str): raise ValueError("control action required") action = command["action"] if action == "advance": steps = command.get("steps") if type(steps) is not int or not 1 <= steps <= 1000: raise ValueError("advance steps must be 1..1000") with state._lock: state._registers[0] = (state._registers[0] + steps) & 0xFFFF elif action == "set": address, value = command.get("address"), command.get("value") if type(address) is not int or not 20 <= address <= 63 or type(value) is not int or not 0 <= value <= 65535: raise ValueError("set requires writable address and uint16 value") with state._lock: state._registers[address] = value elif action == "drop_next_write_response": with state._lock: state._drop_next_write_response = True else: raise ValueError("unknown fixture control action") return state.snapshot() class _ModbusException(Exception): def __init__(self, code): self.code = code def handle_modbus_pdu(state, unit_id, pdu, transaction=None): """Return a reply PDU; None means deliberately close after a committed write.""" with state._lock: if not isinstance(pdu, bytes) or not 1 <= len(pdu) <= MAX_PDU_BYTES: state.record_request(unit_id, pdu, "invalid_frame", transaction=transaction) raise ValueError("invalid Modbus PDU") try: if unit_id != 1: # Fixture policy: there is only one target; preserve the requested unit. raise _ModbusException(11) reply = _execute_modbus_pdu(state, pdu) except _ModbusException as error: state.record_request(unit_id, pdu, "exception", error.code, transaction) return bytes([pdu[0] | 0x80, error.code]) state.record_request(unit_id, pdu, "dropped_response" if reply is None else "ok", transaction=transaction) return reply def _execute_modbus_pdu(state, pdu): function = pdu[0] if function in (3, 4): if len(pdu) != 5: raise _ModbusException(3) address, quantity = struct.unpack(">HH", pdu[1:]) if not 1 <= quantity <= 125: raise _ModbusException(3) try: values = state.read(address, quantity) except ValueError: raise _ModbusException(2) from None return bytes([function, len(values) * 2]) + struct.pack(f">{len(values)}H", *values) if function == 6: if len(pdu) != 5: raise _ModbusException(3) address, value = struct.unpack(">HH", pdu[1:]) if not 20 <= address <= 63: raise _ModbusException(2) return None if state.write(address, [value]) else pdu if function == 16: if len(pdu) < 6: raise _ModbusException(3) address, quantity, byte_count = struct.unpack(">HHB", pdu[1:6]) if not 1 <= quantity <= 44 or byte_count != 2 * quantity or len(pdu) != 6 + byte_count: raise _ModbusException(3) if address < 20 or address + quantity > 64: raise _ModbusException(2) values = list(struct.unpack(f">{quantity}H", pdu[6:])) return None if state.write(address, values) else bytes([16]) + pdu[1:5] raise _ModbusException(1) class _ModbusHandler(socketserver.BaseRequestHandler): def handle(self): self.request.settimeout(5) while True: try: header = _receive_exactly(self.request, 7) if header == b"": return if header is None: self.server.device_state.record_request(None, None, "invalid_frame") return transaction, protocol, length, unit = struct.unpack(">HHHB", header) if protocol != 0 or not 2 <= length <= MAX_PDU_BYTES + 1: self.server.device_state.record_request(unit, None, "invalid_frame", transaction=transaction) return pdu = _receive_exactly(self.request, length - 1) if not pdu: self.server.device_state.record_request(unit, None, "invalid_frame", transaction=transaction) return reply = handle_modbus_pdu(self.server.device_state, unit, pdu, transaction) if reply is None: return self.request.sendall(struct.pack(">HHHB", transaction, 0, len(reply) + 1, unit) + reply) except (OSError, TimeoutError): return def _receive_exactly(sock, length): chunks = bytearray() while len(chunks) < length: chunk = sock.recv(length - len(chunks)) if not chunk: return None if chunks else b"" chunks.extend(chunk) return bytes(chunks) class _ModbusServer(socketserver.ThreadingTCPServer): allow_reuse_address = True daemon_threads = True def __init__(self, address, state): super().__init__(address, _ModbusHandler) self.device_state = state class _ControlHandler(BaseHTTPRequestHandler): def log_message(self, _format, *_args): pass def _json(self, status, payload): data = json.dumps(payload, sort_keys=True).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_GET(self): if self.path != "/state": self._json(404, {"error": "unknown fixture path"}) return self._json(200, self.server.device_state.snapshot()) def do_POST(self): if self.path != "/control": self._json(404, {"error": "unknown fixture path"}) return try: length = int(self.headers.get("Content-Length", "")) if not 1 <= length <= MAX_CONTROL_BYTES: raise ValueError("control body exceeds fixture bound") command = json.loads(self.rfile.read(length)) result = apply_control(self.server.device_state, command) except (ValueError, UnicodeError, json.JSONDecodeError): self._json(400, {"error": "invalid fixture control"}) return self._json(200, result) def main(): state = DeviceState() modbus_port = int(os.environ.get("GRPC_DATA_MODBUS_PORT", MODBUS_PORT)) control_port = int(os.environ.get("GRPC_DATA_CONTROL_PORT", CONTROL_PORT)) with _ModbusServer(("0.0.0.0", modbus_port), state) as modbus, ThreadingHTTPServer(("0.0.0.0", control_port), _ControlHandler) as control: control.device_state = state threading.Thread(target=modbus.serve_forever, daemon=True).start() control.serve_forever() if __name__ == "__main__": main()