"""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._effect_total = 0 self._read_total = 0 self._effects = deque(maxlen=MAX_LEDGER_ITEMS) self._reads = 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, "effects": list(self._effects), "reads": list(self._reads), "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") self._read_total += 1 self._reads.append({"sequence": self._read_total, "address": address, "quantity": quantity}) return [self._registers[register] for register in range(address, address + quantity)] 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() def handle_modbus_pdu(state, unit_id, pdu): """Return a reply PDU; None means deliberately close after a committed write.""" if unit_id != 1 or not isinstance(pdu, bytes) or not 1 <= len(pdu) <= MAX_PDU_BYTES: raise ValueError("invalid Modbus unit or PDU") function = pdu[0] if function in (3, 4): if len(pdu) != 5: raise ValueError("malformed read PDU") address, quantity = struct.unpack(">HH", pdu[1:]) values = state.read(address, quantity) return bytes([function, len(values) * 2]) + struct.pack(f">{len(values)}H", *values) if function == 6: if len(pdu) != 5: raise ValueError("malformed single-write PDU") address, value = struct.unpack(">HH", pdu[1:]) return None if state.write(address, [value]) else pdu if function == 16: if len(pdu) < 6: raise ValueError("malformed multi-write PDU") 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 ValueError("invalid multi-write count") values = list(struct.unpack(f">{quantity}H", pdu[6:])) return None if state.write(address, values) else bytes([16]) + pdu[1:5] raise ValueError("unsupported Modbus function") class _ModbusHandler(socketserver.BaseRequestHandler): def handle(self): self.request.settimeout(5) while True: try: header = _receive_exactly(self.request, 7) if header is None: return transaction, protocol, length, unit = struct.unpack(">HHHB", header) if protocol != 0 or not 2 <= length <= MAX_PDU_BYTES + 1: return pdu = _receive_exactly(self.request, length - 1) if pdu is None: return try: reply = handle_modbus_pdu(self.server.device_state, unit, pdu) except ValueError: return 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 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()