-
Notifications
You must be signed in to change notification settings - Fork 0
/
robot_node.py
142 lines (121 loc) · 4.85 KB
/
robot_node.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import pickle
import threading
from typing import Any, Dict
import numpy as np
import zmq
from robots.robot import Robot
DEFAULT_ROBOT_PORT = 6000
class ZMQServerRobot:
def __init__(
self,
robot: Robot,
port: int = DEFAULT_ROBOT_PORT,
host: str = "192.168.2.2",
):
self._robot = robot
self._context = zmq.Context()
self._socket = self._context.socket(zmq.REP)
addr = f"tcp://{host}:{port}"
debug_message = f"Robot Sever Binding to {addr}, Robot: {robot}"
print(debug_message)
self._timout_message = f"Timeout in Robot Server, Robot: {robot}"
self._socket.bind(addr)
self._stop_event = threading.Event()
def serve(self) -> None:
"""Serve the leader robot state over ZMQ."""
self._socket.setsockopt(zmq.RCVTIMEO, 1000) # Set timeout to 1000 ms
while not self._stop_event.is_set():
try:
# Wait for next request from client
message = self._socket.recv()
request = pickle.loads(message)
# Call the appropriate method based on the request
method = request.get("method")
args = request.get("args", {})
result: Any
if method == "num_dofs":
result = self._robot.num_dofs()
elif method == "get_joint_state":
result = self._robot.get_joint_state()
elif method == "command_joint_state":
result = self._robot.command_joint_state(**args)
elif method == "command_eef_pose":
result = self._robot.command_eef_pose(**args)
elif method == "get_observations":
result = self._robot.get_observations()
else:
result = {"error": "Invalid method"}
print(result)
raise NotImplementedError(
f"Invalid method: {method}, {args, result}"
)
self._socket.send(pickle.dumps(result))
except zmq.Again:
print(self._timout_message)
# Timeout occurred, check if the stop event is set
def stop(self) -> None:
"""Signal the server to stop serving."""
self._stop_event.set()
class ZMQClientRobot(Robot):
"""A class representing a ZMQ client for a leader robot."""
def __init__(self, port: int = DEFAULT_ROBOT_PORT, host: str = "192.168.2.1"):
self._context = zmq.Context()
self._socket = self._context.socket(zmq.REQ)
self._socket.connect(f"tcp://{host}:{port}")
def num_dofs(self) -> int:
"""Get the number of joints in the robot.
Returns:
int: The number of joints in the robot.
"""
request = {"method": "num_dofs"}
send_message = pickle.dumps(request)
self._socket.send(send_message)
result = pickle.loads(self._socket.recv())
return result
def get_joint_state(self) -> np.ndarray:
"""Get the current state of the leader robot.
Returns:
T: The current state of the leader robot.
"""
request = {"method": "get_joint_state"}
send_message = pickle.dumps(request)
self._socket.send(send_message)
result = pickle.loads(self._socket.recv())
return result
def command_joint_state(self, joint_state: np.ndarray) -> None:
"""Command the leader robot to the given state.
Args:
joint_state (T): The state to command the leader robot to.
"""
request = {
"method": "command_joint_state",
"args": {"joint_state": joint_state},
}
send_message = pickle.dumps(request)
self._socket.send(send_message)
result = pickle.loads(self._socket.recv())
return result
def command_eef_pose(self, eef_pose: np.ndarray, num_step: int = 80) -> None:
"""Command the leader robot to the given state.
Args:
eef_pose: end effector pose command to step the environment with.
"""
request = {
"method": "command_eef_pose",
"args": {"eef_pose": eef_pose,
"num_step": num_step},
}
send_message = pickle.dumps(request)
self._socket.send(send_message)
result = pickle.loads(self._socket.recv())
return result
def get_observations(self) -> Dict[str, np.ndarray]:
"""Get the current observations of the leader robot.
Returns:
Dict[str, np.ndarray]: The current observations of the leader robot.
"""
request = {"method": "get_observations"}
send_message = pickle.dumps(request)
self._socket.send(send_message)
result = pickle.loads(self._socket.recv())
return result