2023-10-15 18:06:23 +02:00
|
|
|
|
2023-10-15 18:06:27 +02:00
|
|
|
import socket, zlib
|
2023-10-15 18:06:23 +02:00
|
|
|
|
|
|
|
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
|
|
|
|
PORT = 2000 # Port to listen on (non-privileged ports are > 1023)
|
|
|
|
|
2023-10-15 18:06:27 +02:00
|
|
|
def calculate_crc(data):
|
|
|
|
# Calculate the CRC32 checksum of the data
|
|
|
|
crc = zlib.crc32(data)
|
|
|
|
# Convert the CRC32 value to a 4-byte big-endian byte array
|
|
|
|
crc_bytes = crc.to_bytes(4, byteorder='big')
|
|
|
|
return crc_bytes
|
|
|
|
|
2023-10-15 18:06:23 +02:00
|
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
|
|
s.bind((HOST, PORT))
|
|
|
|
s.listen()
|
|
|
|
while True:
|
2023-10-15 18:06:27 +02:00
|
|
|
try:
|
|
|
|
conn, addr = s.accept()
|
|
|
|
with conn:
|
|
|
|
print(f"Connected by {addr}")
|
|
|
|
while True:
|
|
|
|
data = conn.recv(1024)
|
|
|
|
if not data:
|
|
|
|
break
|
|
|
|
print(f'RECV: {data.hex()} [{len(data)}]')
|
|
|
|
if data[0x11] == 0x01:
|
|
|
|
pckt = bytearray([0x01])
|
|
|
|
pckt.extend([0x00, 0x00, 0x00, 0x00]) # src
|
|
|
|
pckt.extend([0x00, 0x00, 0x00, 0xFF]) # dest
|
|
|
|
pckt.extend([0x00, 0x00, 0x00, 0x00]) # packet_id
|
|
|
|
pckt.extend(data[0x09:0x0D]) # reply_to
|
|
|
|
pckt.extend([0x01]) # command
|
|
|
|
pckt.extend([0x00, 0x04]) # data_length
|
|
|
|
pckt.extend([0x00, 0x00, 0x00, 0xFF])
|
|
|
|
|
|
|
|
# Calculate CRC for the received data
|
|
|
|
crc = calculate_crc(pckt)
|
|
|
|
# Append the CRC value to the data
|
|
|
|
data_with_crc = pckt + crc
|
|
|
|
# Send the modified data (with CRC) back to the client
|
|
|
|
conn.sendall(data_with_crc)
|
|
|
|
print(f'SEND: {data_with_crc.hex()} [{len(data_with_crc)}]')
|
|
|
|
except:
|
|
|
|
s.close()
|