126 lines
4.7 KiB
Python
126 lines
4.7 KiB
Python
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
|
"""A Modbus TCP device from a profile's register map, for showing the bridge
|
|
without the real device (the add-on's "simulate" option): one server per
|
|
device on 127.0.0.1, answering reads (functions 1-4) and writes (5, 6 and
|
|
16) of the profile's registers and coils. Values come from a trace (a device's history
|
|
as Home Assistant recorded it, one value per register key and step), played
|
|
in a loop; a written control keeps the value written.
|
|
|
|
Trace (/share/cantabile/trace-<profile>.json):
|
|
{"step_s": 60, "values": {"<register key>": [v0, v1, ...], ...}}
|
|
"""
|
|
import json
|
|
import socketserver
|
|
import struct
|
|
import threading
|
|
import time
|
|
|
|
import cantabile_modbus as mb
|
|
|
|
|
|
class Device:
|
|
def __init__(self, profile, trace):
|
|
self.regs = [r for r in profile["modbus"]["registers"] if r["type"] != "string"]
|
|
self.trace = trace or {"step_s": 60, "values": {}}
|
|
self.written = {}
|
|
self.lock = threading.Lock()
|
|
|
|
def value(self, r):
|
|
if r["key"] in self.written:
|
|
return self.written[r["key"]]
|
|
vs = self.trace["values"].get(r["key"]) or [0]
|
|
i = int(time.time() // max(1, self.trace.get("step_s", 60))) % len(vs)
|
|
return vs[i] if vs[i] is not None else 0
|
|
|
|
def words(self, table, start, count):
|
|
out = {}
|
|
for r in self.regs:
|
|
if r.get("table", "holding") != table:
|
|
continue
|
|
try:
|
|
ws = mb.encode(r, self.value(r))
|
|
except mb.ModbusError:
|
|
ws = [0] * mb.size(r)
|
|
for i, w in enumerate(ws):
|
|
out[r["address"] + i] = w
|
|
return [out.get(a, 0) for a in range(start, start + count)]
|
|
|
|
def write(self, start, words, table="holding"):
|
|
with self.lock:
|
|
for r in self.regs:
|
|
if r.get("write") and r.get("table", "holding") == table and r["address"] == start \
|
|
and len(words) >= mb.size(r):
|
|
self.written[r["key"]] = mb.decode(r, words)
|
|
return True
|
|
return False
|
|
|
|
|
|
def handler(dev, unit):
|
|
class H(socketserver.BaseRequestHandler):
|
|
def handle(self):
|
|
s = self.request
|
|
while True:
|
|
head = recv(s, 7)
|
|
if not head:
|
|
return
|
|
tid, _proto, length, uid = struct.unpack(">HHHB", head)
|
|
pdu = recv(s, length - 1)
|
|
if not pdu:
|
|
return
|
|
fc = pdu[0]
|
|
if uid != unit:
|
|
reply = bytes([fc | 0x80, 11])
|
|
elif fc in (1, 2):
|
|
start, count = struct.unpack(">HH", pdu[1:5])
|
|
bits = dev.words("coil" if fc == 1 else "discrete", start, count)
|
|
packed = bytes(sum(b << i for i, b in enumerate(bits[j:j + 8]) if b) for j in range(0, count, 8))
|
|
reply = bytes([fc, len(packed)]) + packed
|
|
elif fc == 5:
|
|
start, w = struct.unpack(">HH", pdu[1:5])
|
|
reply = pdu[:5] if dev.write(start, [1 if w == 0xFF00 else 0], "coil") else bytes([fc | 0x80, 2])
|
|
elif fc in (3, 4):
|
|
start, count = struct.unpack(">HH", pdu[1:5])
|
|
ws = dev.words("holding" if fc == 3 else "input", start, count)
|
|
reply = bytes([fc, 2 * count]) + struct.pack(f">{count}H", *ws)
|
|
elif fc == 6:
|
|
start, w = struct.unpack(">HH", pdu[1:5])
|
|
reply = pdu[:5] if dev.write(start, [w]) else bytes([fc | 0x80, 2])
|
|
elif fc == 16:
|
|
start, count = struct.unpack(">HH", pdu[1:5])
|
|
ws = list(struct.unpack(f">{count}H", pdu[6:6 + 2 * count]))
|
|
reply = pdu[:5] if dev.write(start, ws) else bytes([fc | 0x80, 2])
|
|
else:
|
|
reply = bytes([fc | 0x80, 1])
|
|
s.sendall(struct.pack(">HHHB", tid, 0, len(reply) + 1, uid) + reply)
|
|
return H
|
|
|
|
|
|
def recv(s, n):
|
|
out = b""
|
|
while len(out) < n:
|
|
c = s.recv(n - len(out))
|
|
if not c:
|
|
return b""
|
|
out += c
|
|
return out
|
|
|
|
|
|
class Server(socketserver.ThreadingTCPServer):
|
|
allow_reuse_address = True
|
|
daemon_threads = True
|
|
|
|
|
|
def serve(profile, trace, unit, port):
|
|
"""Start one simulated device on 127.0.0.1:<port> (a thread)."""
|
|
srv = Server(("127.0.0.1", port), handler(Device(profile, trace), unit))
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
return srv
|
|
|
|
|
|
def load_trace(path):
|
|
try:
|
|
with open(path) as f:
|
|
return json.load(f)
|
|
except (OSError, ValueError):
|
|
return None
|