Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """
- Listen to the HMI to figure out what registers it wants to initialize.
- based on OnTheLine arduino code.
- """
- import socket
- import argparse
- HOST = "0.0.0.0"
- PORT = 2101
- def xor_bcc(data):
- b = 0
- for c in data:
- b ^= c
- return b
- def read_d(addr):
- if addr == 570:
- return 26
- if addr in (3498, 3499, 3500):
- return 0
- return 0
- def make_reply(addr, nbytes):
- words = nbytes // 2
- payload = b"\x06" # ACK
- payload += b"000" # device=00, status=0
- for i in range(words):
- payload += f"{read_d(addr+i):04X}".encode()
- bcc = xor_bcc(payload)
- payload += f"{bcc:02X}".encode()
- payload += b"\r"
- return payload
- def handle(sock):
- buf = b""
- while True:
- c = sock.recv(1)
- if not c:
- break
- buf += c
- if c != b"\r":
- continue
- #print("RX:", buf)
- print("RX HEX: ", " ".join(f"{b:02X}" for b in buf))
- print("RX ASCII:", repr(buf))
- if len(buf) >= 14 and buf[0] == 0x05:
- cmd = buf[4:6]
- if cmd == b"RD":
- addr = int(buf[6:10])
- nbytes = int(buf[10:12], 16)
- print(f"READ D{addr} ({nbytes//2} words)")
- reply = make_reply(addr, nbytes)
- print("TX:", reply)
- sock.sendall(reply)
- else:
- print("Unhandled command:", cmd)
- buf = b""
- def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--host", default=HOST)
- ap.add_argument("--port", default=PORT, type=int)
- args = ap.parse_args()
- s = socket.socket()
- s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s.bind((args.host, args.port))
- s.listen(1)
- print(f"Listening on {args.host}:{args.port}")
- while True:
- c, a = s.accept()
- print("Connected:", a)
- try:
- handle(c)
- finally:
- c.close()
- print("Disconnected")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment