modbus_test/utils/test_socket_server.py

65 lines
1.8 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"] = [
-60,
40,
-10,
-60,
-75,
0,
]
if "queryAddr" in req and "world-0" in req["queryAddr"]:
res["queryData"] = [
643.622,
-1289.604,
254.682,
124.70,
24.209,
-58.492,
# 0,
# 0,
# 0,
# 0,
# 0,
# 0,
]
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)