aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authors-ol <s+removethis@s-ol.nu>2024-02-27 23:19:29 +0000
committers-ol <s+removethis@s-ol.nu>2024-02-27 23:19:29 +0000
commit5ef21005fd604aae752940ca868313775b2335df (patch)
tree6bcd38123df189b0726fb58580b54f265057e44a
parentinitial web control (diff)
downloadt937-serial-5ef21005fd604aae752940ca868313775b2335df.tar.gz
t937-serial-5ef21005fd604aae752940ca868313775b2335df.zip
initial python simulator
-rw-r--r--simulator/__init__.py74
1 files changed, 74 insertions, 0 deletions
diff --git a/simulator/__init__.py b/simulator/__init__.py
new file mode 100644
index 0000000..c8ea719
--- /dev/null
+++ b/simulator/__init__.py
@@ -0,0 +1,74 @@
+import serial
+import sys
+import time
+
+ADDR_CTRL = bytes([0xdb, 0x96])
+ADDR_OVEN = bytes([0xaa, 0x55])
+
+def u16(b):
+ assert len(b) == 2
+ return b[0] << 8 | b[1]
+
+class MessageParser:
+ def __init__(self):
+ self.buffer = bytes()
+
+ def encode(self, addr, func, data):
+ msg = addr + bytes([func, len(data)]) + data
+ chk = sum(msg)
+ return msg + bytes([chk >> 8, chk & 0xff])
+
+ def try_read_message(self, data):
+ if not data:
+ return
+ self.buffer += data
+
+ if len(self.buffer) < 4 + 2:
+ return
+
+ data_len = self.buffer[3]
+ msg_len = 4 + data_len + 2
+ if len(self.buffer) < msg_len:
+ return
+
+ (msg, self.buffer) = (self.buffer[:msg_len], self.buffer[msg_len:])
+ assert sum(msg[:-2]) == u16(msg[-2:])
+ assert msg[:2] == ADDR_OVEN
+
+ func = msg[2]
+ data = msg[4:4+data_len]
+
+ return (func, data)
+
+def run(port):
+ parser = MessageParser()
+
+ print("broadcasting connection...")
+ while True:
+ port.write(parser.encode(ADDR_CTRL, 0x01, bytes([0x01, 0x00])))
+ time.sleep(1)
+ msg = parser.try_read_message(port.read(port.in_waiting))
+
+ if msg:
+ if msg[0] == 0xf1 and msg[1] == bytes([0x02, 0x00]):
+ break
+
+ print("unexpected message", msg)
+
+ print("accepting connection...")
+ port.write(parser.encode(ADDR_CTRL, 0x01, bytes([0x02, 0x00])))
+
+ while True:
+ port.write(parser.encode(ADDR_CTRL, 0x02, bytes([0, 26])*3))
+ time.sleep(1)
+ msg = parser.try_read_message(port.read(port.in_waiting))
+
+ if msg:
+ print(msg)
+ break
+
+
+if __name__ == "__main__":
+ port = sys.argv[-1]
+ with serial.Serial(port, timeout=1) as ser:
+ run(ser)