-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnector.py
More file actions
53 lines (45 loc) · 1.72 KB
/
Connector.py
File metadata and controls
53 lines (45 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import socket
import json
import time
class CoppeliaClient:
def __init__(self, host='127.0.0.1', port=50002):
self.host = host
self.port = port
self.sock = None
self.buffer = ""
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.host, self.port))
self.sock.settimeout(0.1)
def send_motor_command(self, left_speed, right_speed,state=0,reward=0,action=0):
cmd = {"command": "set_speed", "L": left_speed, "R": right_speed,"State":state,"Reward":reward,"Action":action}
msg = json.dumps(cmd) + "\n"
self.sock.sendall(msg.encode())
def start_simulation(self):
cmd = {"command": "start_simulation"}
msg = json.dumps(cmd) + "\n"
self.sock.sendall(msg.encode())
def stop_simulation(self):
cmd = {"command": "stop_simulation"}
msg = json.dumps(cmd) + "\n"
self.sock.sendall(msg.encode())
def receive_sensor_data(self):
try:
data = self.sock.recv(1024).decode()
if not data:
return None
self.buffer += data
if "\n" in self.buffer:
line, self.buffer = self.buffer.split("\n", 1)
sensor_msg = json.loads(line)
if sensor_msg.get("type") == "sensor_update":
return sensor_msg["sensors"]
except socket.timeout:
pass
except Exception as e:
print(f"[CoppeliaClient] Error receiving sensor data: {e}")
return None
def close(self):
if self.sock:
self.sock.close()
self.sock = None