modbus_test/utils/test_socket_server.py

59 lines
1.7 KiB
Python

import socket
import json
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 9760 # Port to listen on (non-privileged ports are > 1023)
def handle_client(conn, addr):
print(f"Connected by {addr}")
try:
while True:
data = conn.recv(1024)
if not data:
break
req = json.loads(data)
res = {"queryData": ["ok"]}
if "queryAddr" in req.keys() and "axis-0" in req["queryAddr"]:
res["queryData"] = [
-41.612457,
31.759747,
-26.773878,
74.869049,
-45.417992,
-20.86335,
]
if "queryAddr" in req and "world-0" in req["queryAddr"]:
res["queryData"] = [
1131.959351,
-588.689941,
1277.805054,
6.181231,
54.227802,
-100.604988,
]
if req["reqType"] == "command":
res["cmdReply"] = ["ok"]
conn.sendall(json.dumps(res).encode())
except json.JSONDecodeError as e:
print(f"JSON decode error: {e}")
except socket.error as e:
print(f"Socket error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
conn.close()
print(f"Connection with {addr} closed")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print(f"Server listening on {HOST}:{PORT}")
while True:
conn, addr = s.accept()
handle_client(conn, addr)