Add waagen simulator

This commit is contained in:
2023-08-11 18:43:38 +02:00
parent 399a3032b0
commit 6e0b79ee95
4 changed files with 106 additions and 0 deletions

81
waagen/simulator.py Executable file
View File

@ -0,0 +1,81 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SysTec IT3000A uses CRC16-modbus
import argparse
import socket
import datetime
import random
import time
import crcmod.predefined
IDENT_NR = 0
def crc16_modbus(data: bytes) -> int:
crc = crcmod.predefined.Crc('modbus')
crc.update(data)
return int(crc.hexdigest(), 16)
def handle_systec_it3000a(req: bytes) -> bytes:
global IDENT_NR
if not req.startswith(b'<') or not req.endswith(b'>'):
return b'<01>\r\n'
req = req[1:-1]
if len(req) > 3:
return b'<02>\r\n'
if req.startswith(b'RN'):
incr = True
elif req.startswith(b'RM'):
incr = False
else:
return b'<02>\r\n'
if incr:
time.sleep(random.randint(0, 40) / 10.0)
gew = random.randint(40, 4000)
m = random.randint(1, 10)
match m:
case 1:
return b'<12>\r\n'
case 2:
incr = False
gew = 0
if incr:
IDENT_NR += 1
now = datetime.datetime.now()
data = f'0000{now:%d.%m.%y%H:%M}{IDENT_NR if incr else 0:4}1{gew:8}{0:8}{gew:8}kg {1:3}'.encode('ascii')
return b'<' + data + f'{crc16_modbus(data):8}'.encode('ascii') + b'>\r\n'
def main() -> None:
s = socket.socket()
s.bind(('0.0.0.0', 1234))
s.listen()
print('Ready for connections')
while True:
c, a = s.accept()
print(f'Accepting connection from {a}')
try:
while True:
req = c.recv(1024)
print(req.decode('ascii'), end='')
res = handle_systec_it3000a(req)
print(res.decode('ascii'), end='')
c.send(res)
except:
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser()
args = parser.parse_args()
main()