Moronbot commited on
Commit
ed9e147
·
verified ·
1 Parent(s): 8b07362

Upload 23 files

Browse files
.gitattributes CHANGED
@@ -57,3 +57,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ piper/meshes/base_link.STL filter=lfs diff=lfs merge=lfs -text
61
+ piper/meshes/gripper_base.STL filter=lfs diff=lfs merge=lfs -text
62
+ piper/meshes/link1.STL filter=lfs diff=lfs merge=lfs -text
63
+ piper/meshes/link2.STL filter=lfs diff=lfs merge=lfs -text
64
+ piper/meshes/link3.STL filter=lfs diff=lfs merge=lfs -text
65
+ piper/meshes/link4.STL filter=lfs diff=lfs merge=lfs -text
66
+ piper/meshes/link5.STL filter=lfs diff=lfs merge=lfs -text
67
+ piper/meshes/link7.STL filter=lfs diff=lfs merge=lfs -text
68
+ piper/meshes/link8.STL filter=lfs diff=lfs merge=lfs -text
20250615_122804.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84dbf7432940a15d4fd61f954b6161608633dd009322798c350924b96f40d8fe
3
+ size 303843325
20250615_160013.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38c17a908948793ef2f869e0dde32a0340cf6ce024ad90a4ed0711f1b55a2ef9
3
+ size 53574832
iphone_teleop_with_prepared_data.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import socket, struct, json
2
+
3
+ # ---- UDP Setup ----
4
+ UDP_IP = "0.0.0.0"
5
+ UDP_PORT = 8000
6
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
7
+ sock.bind((UDP_IP, UDP_PORT))
8
+ print(f"Listening on UDP {UDP_IP}:{UDP_PORT}…")
9
+
10
+ # ---- Linear mapping function ----
11
+ def map_value(x, in_min, in_max, out_min, out_max):
12
+ """Linearly map x from [in_min, in_max] to [out_min, out_max]."""
13
+ # Optional: clamp x to [in_min, in_max]
14
+ if x < in_min: x = in_min
15
+ if x > in_max: x = in_max
16
+ return (x - in_min) / (in_max - in_min) * (out_max - out_min) + out_min
17
+
18
+ # ---- Input and output ranges ----
19
+ # D1 → X
20
+ D1_IN_MIN, D1_IN_MAX = -1.0, 1.0
21
+ X_OUT_MIN, X_OUT_MAX = 200_000, 500_000
22
+
23
+ # D2 → Z
24
+ D2_IN_MIN, D2_IN_MAX = -1.0, 1.0
25
+ Z_OUT_MIN, Z_OUT_MAX = 140_000, 250_000
26
+
27
+ # D3 → Y
28
+ D3_IN_MIN, D3_IN_MAX = -3.0, 0.0
29
+ Y_OUT_MIN, Y_OUT_MAX = -100_000, 200_000
30
+
31
+ # R (degrees) → Z_rotation
32
+ R_IN_MIN, R_IN_MAX = -90.0, 90.0
33
+ R_OUT_MIN, R_OUT_MAX = 0.0, 50_000.0
34
+
35
+ # GX (0–1) → Gripper_Value
36
+ GX_IN_MIN, GX_IN_MAX = 0.0, 1.0
37
+ GRIP_CLOSE, GRIP_OPEN = 0.0, 80_000.0
38
+
39
+ # ---- Main loop ----
40
+ while True:
41
+ data, addr = sock.recvfrom(4096)
42
+ if len(data) < 4:
43
+ continue
44
+
45
+ # Strip 4-byte little-endian length prefix
46
+ length, = struct.unpack('<I', data[:4])
47
+ payload = data[4:4+length]
48
+
49
+ try:
50
+ msg = json.loads(payload)
51
+ except json.JSONDecodeError as e:
52
+ print(f"⚠️ JSON decode error: {e}")
53
+ continue
54
+
55
+ msg_type = msg.get('__id')
56
+
57
+ if msg_type == 'PoseStateMessage':
58
+ # raw values
59
+ pos = msg.get('gripperDeltaPosition', [0.0, 0.0, 0.0])
60
+ tx, ty, tz = pos if len(pos) == 3 else (0.0, 0.0, 0.0)
61
+ angle = msg.get('gripperRotateDegrees', 0.0)
62
+ open_amt = msg.get('gripperOpenAmount', 0.0)
63
+
64
+ # mapped values
65
+ X_val = map_value(tx, D1_IN_MIN, D1_IN_MAX, X_OUT_MIN, X_OUT_MAX)
66
+ Z_val = map_value(ty, D2_IN_MIN, D2_IN_MAX, Z_OUT_MIN, Z_OUT_MAX)
67
+ Y_val = map_value(tz, D3_IN_MIN, D3_IN_MAX, Y_OUT_MIN, Y_OUT_MAX)
68
+ Z_rotation = map_value(angle, R_IN_MIN, R_IN_MAX, R_OUT_MIN, R_OUT_MAX)
69
+ Gripper_Value = map_value(open_amt, GX_IN_MIN, GX_IN_MAX, GRIP_CLOSE, GRIP_OPEN)
70
+
71
+ # print everything
72
+ print(
73
+ f"[Pose] delta=({tx:.3f},{ty:.3f},{tz:.3f}), "
74
+ f"gripperRotate={angle:.1f}°, gripperOpen={open_amt:.2f}"
75
+ )
76
+ print(
77
+ f" → MAPPED: "
78
+ f"X={X_val:.0f}, Y={Y_val:.0f}, Z={Z_val:.0f}, "
79
+ f"Z_rotation={Z_rotation:.0f}, Gripper_Value={Gripper_Value:.0f}"
80
+ )
81
+
82
+ elif msg_type == 'HelloMessage':
83
+ print(f"[Hello] {msg.get('message')}")
84
+
85
+ else:
86
+ print(f"[{msg_type}] {msg}")
piper/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ python lerobot/scripts/control_robot.py \
2
+ --robot.type=piper \
3
+ --robot.port=can0 \
4
+ --robot.max_relative_target=5.0 \
5
+ --control.type=teleoperate
6
+
piper/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # lerobot/common/robots/piper/__init__.py
2
+
3
+ from .config_piper import PiperConfig
4
+ from .piper import PiperRobot
5
+
6
+ __all__ = ["PiperConfig", "PiperRobot"]
piper/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (243 Bytes). View file
 
piper/__pycache__/config_piper.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
piper/__pycache__/piper.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
piper/config_piper.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # lerobot/common/robots/piper/config_piper.py
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Optional
5
+ from lerobot.common.cameras import CameraConfig
6
+ from ..config import RobotConfig
7
+
8
+ @RobotConfig.register_subclass("piper")
9
+ @dataclass
10
+ class PiperConfig(RobotConfig):
11
+ """
12
+ Configuration for PiperRobot integration in (older) LeRobot.
13
+ """
14
+ # Provide either a CAN port string. If None, auto-detect in connect().
15
+ port: Optional[str] = None
16
+
17
+ # Limit on per-step change for joint positions (in radians). Smaller for safety.
18
+ # Similar to ViperXConfig.max_relative_target.
19
+ max_relative_target: Optional[float] = 5.0
20
+
21
+ # Speed for gripper control (units per PiperControl API). Adjust as needed.
22
+ gripper_speed: float = 0.1
23
+
24
+ # Camera configurations, if using cameras. Hydra or manual code can set this dict.
25
+ cameras: dict[str, CameraConfig] = field(default_factory=dict)
26
+
27
+ def __post_init__(self):
28
+ # If your RobotConfig base defines a __post_init__, chain it; otherwise ignore.
29
+ try:
30
+ super().__post_init__()
31
+ except Exception:
32
+ pass
33
+ # We allow port=None for auto-detect; if you want strict, uncomment:
34
+ # if not self.port:
35
+ # raise ValueError("PiperConfig: port must be specified or allow auto-detect")
piper/meshes/base_link.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd4a3d6d0266205fe3f725f048645be66592c23564db22e08b0807d5569b2c64
3
+ size 607384
piper/meshes/gripper_base.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2895bfa6f1eef2d0ad2cb9dfdedd5f6c760ec07388bcde2b4d1e412e1189c9cb
3
+ size 649484
piper/meshes/link1.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ee6e1d67c0241f42a0dbaf5c676d19230375ed078ee1943bb8c4c37ab303d14
3
+ size 447784
piper/meshes/link2.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d37675b699b643f2e15348de99aed535fac10dc5f09a79b8e4b0acfaf4e0378
3
+ size 3658384
piper/meshes/link3.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8ae51f17c0c7f6d67b753922e2cc269f5e8372a65734f859231639a64fe8fad
3
+ size 1845784
piper/meshes/link4.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:efa33022976218f246f736a6133494b5d0e5486e8b50b52900c42f285ae85558
3
+ size 877984
piper/meshes/link5.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1c69d1c7f6f8c60e2c82331c0f444725200ed4053d3e5ec23aa82cb5db5b29f
3
+ size 833684
piper/meshes/link6.STL ADDED
Binary file (58.9 kB). View file
 
piper/meshes/link7.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:475a7d8db056524d7659fadf5a2c307d62791047b6214d733dfc7846ed1c613d
3
+ size 104384
piper/meshes/link8.STL ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f88d534a85e28a33ef7d2061adacbd1d25214aa9325f9e464aad0f9e4b74606
3
+ size 104384
piper/piper.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # lerobot/common/robots/piper/piper.py
2
+
3
+ import logging
4
+ import time
5
+ import os
6
+ import xml.etree.ElementTree as ET
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from lerobot.common.constants import OBS_STATE
10
+ from lerobot.common.errors import DeviceAlreadyConnectedError, DeviceNotConnectedError
11
+ from lerobot.common.cameras.utils import make_cameras_from_configs
12
+ from ..utils import ensure_safe_goal_position
13
+ from .config_piper import PiperConfig
14
+ from ..robot import Robot
15
+
16
+ # Import PiperControl APIs; adjust import if your module path differs
17
+ from piper_control import piper_connect, piper_control
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class PiperRobot(Robot):
23
+ """
24
+ Hardware integration for AgileX Piper robot, using piper_control.PiperControl API.
25
+ """
26
+
27
+ config_class = PiperConfig
28
+ name = "piper"
29
+
30
+ def __init__(self, config: PiperConfig):
31
+ # Call base constructor
32
+ super().__init__(config)
33
+ self.config: PiperConfig = config
34
+ self.robot: Optional[piper_control.PiperControl] = None
35
+
36
+ # Parse URDF for joint names if available
37
+ try:
38
+ urdf_path = os.path.join(os.path.dirname(__file__), "piper.urdf")
39
+ joint_names = self._parse_actuated_joint_names_from_urdf(urdf_path)
40
+ # Standardize names if needed
41
+ self.joint_names: List[str] = [name.replace(" ", "_") for name in joint_names]
42
+ except Exception as e:
43
+ logger.warning(f"Could not parse URDF for joint names: {e}")
44
+ self.joint_names = []
45
+
46
+ # Instantiate cameras from config
47
+ if config.cameras:
48
+ try:
49
+ self.cameras = make_cameras_from_configs(config.cameras)
50
+ except Exception as e:
51
+ logger.warning(f"Failed to create cameras from configs: {e}")
52
+ self.cameras = {}
53
+ else:
54
+ self.cameras = {}
55
+
56
+ @property
57
+ def _motors_ft(self) -> Dict[str, type]:
58
+ """
59
+ Feature types for joint positions: "<joint_name>.pos": float.
60
+ If joint_names empty, may infer later in connect().
61
+ """
62
+ # If joint_names empty, try URDF parse again
63
+ if not getattr(self, "joint_names", None):
64
+ try:
65
+ urdf_path = os.path.join(os.path.dirname(__file__), "piper.urdf")
66
+ joint_names = self._parse_actuated_joint_names_from_urdf(urdf_path)
67
+ self.joint_names = [name.replace(" ", "_") for name in joint_names]
68
+ except Exception:
69
+ pass
70
+
71
+ # If still empty and hardware connected, infer generic
72
+ if not getattr(self, "joint_names", None) and self.robot:
73
+ try:
74
+ pos_list = self.robot.get_joint_positions()
75
+ n = len(pos_list)
76
+ self.joint_names = [f"joint{i+1}" for i in range(n)]
77
+ logger.warning(f"Inferred generic joint names: {self.joint_names}")
78
+ except Exception:
79
+ pass
80
+
81
+ return {f"{j}.pos": float for j in self.joint_names}
82
+
83
+ @property
84
+ def _cameras_ft(self) -> Dict[str, tuple]:
85
+ """
86
+ Feature types for cameras: "<cam_name>": (height, width, 3).
87
+ """
88
+ feats: Dict[str, tuple] = {}
89
+ for cam_name, cam_cfg in self.config.cameras.items():
90
+ h = getattr(cam_cfg, "height", None)
91
+ w = getattr(cam_cfg, "width", None)
92
+ if h is not None and w is not None:
93
+ feats[cam_name] = (h, w, 3)
94
+ else:
95
+ logger.warning(f"Camera config for '{cam_name}' missing width/height; skipping feature")
96
+ return feats
97
+
98
+ @property
99
+ def observation_features(self) -> Dict[str, Any]:
100
+ """
101
+ Observation schema: flatten state and cameras and gripper.
102
+ """
103
+ feats: Dict[str, Any] = {}
104
+ # Joint positions
105
+ feats.update(self._motors_ft)
106
+ # Cameras
107
+ feats.update(self._cameras_ft)
108
+ # Gripper state
109
+ feats["gripper.left_pos"] = float
110
+ feats["gripper.right_pos"] = float
111
+ return feats
112
+
113
+ @property
114
+ def action_features(self) -> Dict[str, type]:
115
+ """
116
+ Action schema: joint position targets and gripper control.
117
+ """
118
+ feats = dict(self._motors_ft)
119
+ feats["gripper.ctrl"] = float
120
+ return feats
121
+
122
+ @property
123
+ def is_connected(self) -> bool:
124
+ """
125
+ True if hardware API and all cameras (if any) are connected.
126
+ """
127
+ api_ok = False
128
+ if self.robot:
129
+ try:
130
+ _ = self.robot.get_joint_positions()
131
+ api_ok = True
132
+ except Exception:
133
+ api_ok = False
134
+ cams_ok = True
135
+ if hasattr(self, "cameras") and self.cameras:
136
+ cams_ok = all(getattr(cam, "is_connected", False) for cam in self.cameras.values())
137
+ return api_ok and cams_ok
138
+
139
+ def connect(self, calibrate: bool = True) -> None:
140
+ """
141
+ Connect to Piper hardware and cameras.
142
+ """
143
+ if self.is_connected:
144
+ raise DeviceAlreadyConnectedError(f"{self} already connected")
145
+
146
+ # 1) Determine CAN port
147
+ can_port = self.config.port
148
+ if not can_port:
149
+ ports = piper_connect.find_ports()
150
+ if not ports:
151
+ raise DeviceNotConnectedError("No CAN ports found for Piper; check hardware/drivers")
152
+ first = ports[0]
153
+ can_port = first[0] if isinstance(first, (tuple, list)) and first else first
154
+ logger.info(f"No port in config; auto-detected CAN port: {can_port}")
155
+ else:
156
+ if isinstance(can_port, (tuple, list)) and can_port:
157
+ can_port = can_port[0]
158
+
159
+ # 2) Activate CAN interface
160
+ try:
161
+ piper_connect.activate()
162
+ active = piper_connect.active_ports()
163
+ if not active:
164
+ raise DeviceNotConnectedError("Failed to activate any CAN port for Piper")
165
+ active_ifaces: List[str] = []
166
+ for item in active:
167
+ if isinstance(item, (tuple, list)) and item:
168
+ active_ifaces.append(item[0])
169
+ else:
170
+ active_ifaces.append(item)
171
+ if can_port not in active_ifaces:
172
+ logger.warning(
173
+ "Specified port %s not in active ports %s; using %s",
174
+ can_port, active_ifaces, active_ifaces[0] if active_ifaces else can_port
175
+ )
176
+ can_port = active_ifaces[0] if active_ifaces else can_port
177
+ except Exception as e:
178
+ raise DeviceNotConnectedError(f"Failed to activate CAN interface: {e}")
179
+
180
+ # 3) Instantiate PiperControl
181
+ try:
182
+ self.robot = piper_control.PiperControl(can_port=can_port)
183
+ except Exception as e:
184
+ raise DeviceNotConnectedError(f"Failed to construct PiperControl: {e}")
185
+
186
+ # 4) Enable/reset sequence
187
+ try:
188
+ self.robot.enable()
189
+ time.sleep(0.5)
190
+ try:
191
+ self.robot.reset()
192
+ except RuntimeError as e:
193
+ logger.warning(f"PiperControl.reset() warning: {e}")
194
+ time.sleep(0.5)
195
+ self.robot.enable()
196
+ time.sleep(0.5)
197
+ except Exception as e:
198
+ logger.warning(f"Enable/reset sequence exception: {e}")
199
+
200
+ # 5) Infer or adjust joint_names from hardware length
201
+ try:
202
+ pos_list = self.robot.get_joint_positions()
203
+ n_hw = len(pos_list)
204
+ if not getattr(self, "joint_names", None):
205
+ # No URDF names: generic
206
+ self.joint_names = [f"joint{i+1}" for i in range(n_hw)]
207
+ logger.info(f"Inferred joint names from hardware: {self.joint_names}")
208
+ else:
209
+ n_urdf = len(self.joint_names)
210
+ if n_urdf != n_hw:
211
+ if n_urdf > n_hw:
212
+ logger.warning(
213
+ "URDF joint count (%d) != hardware count (%d). Trimming to %d.",
214
+ n_urdf, n_hw, n_hw
215
+ )
216
+ self.joint_names = self.joint_names[:n_hw]
217
+ else:
218
+ logger.warning(
219
+ "URDF joint count (%d) < hardware count (%d). Padding generic names.",
220
+ n_urdf, n_hw
221
+ )
222
+ for i in range(n_urdf, n_hw):
223
+ self.joint_names.append(f"joint{i+1}")
224
+ logger.info(f"Adjusted joint_names: {self.joint_names}")
225
+ else:
226
+ logger.info(f"Using URDF joint_names matching hardware: {self.joint_names}")
227
+ except Exception as e:
228
+ logger.warning(f"Could not infer/adjust joint names: {e}")
229
+
230
+ # 6) Connect cameras
231
+ for cam_name, cam in self.cameras.items():
232
+ try:
233
+ cam.connect()
234
+ logger.info(f"Connected camera '{cam_name}'.")
235
+ except Exception as e:
236
+ logger.warning(f"Failed to connect camera '{cam_name}': {e}")
237
+
238
+ logger.info(f"{self} connected on CAN port {can_port}.")
239
+
240
+ # 7) Calibration stub if desired
241
+ if calibrate:
242
+ try:
243
+ self._run_calibration()
244
+ except NotImplementedError:
245
+ logger.info("Piper calibration not implemented; skipping.")
246
+ except Exception as e:
247
+ logger.warning(f"Calibration exception: {e}")
248
+
249
+ @property
250
+ def is_calibrated(self) -> bool:
251
+ """
252
+ Override: return True if calibration done. Here stub True.
253
+ """
254
+ return True
255
+
256
+ def calibrate(self) -> None:
257
+ """
258
+ Stub for calibration.
259
+ """
260
+ raise NotImplementedError("Piper calibration not implemented")
261
+
262
+ def configure(self) -> None:
263
+ """
264
+ Stub for any further configuration.
265
+ """
266
+ logger.info("PiperRobot.configure(): no-op.")
267
+
268
+ def _run_calibration(self):
269
+ """
270
+ Stub to skip calibration.
271
+ """
272
+ raise NotImplementedError("Piper hardware calibration not implemented")
273
+
274
+ def get_observation(self) -> Dict[str, Any]:
275
+ """
276
+ Read joint states, gripper state, and camera frames.
277
+ Returns a dict mapping "<joint_name>.pos" -> float, "gripper.left_pos"/right_pos, and camera images.
278
+ """
279
+ if not self.is_connected:
280
+ raise DeviceNotConnectedError(f"{self} is not connected.")
281
+
282
+ obs_dict: Dict[str, Any] = {}
283
+
284
+ # Read joint positions
285
+ try:
286
+ pos_list = self.robot.get_joint_positions() # list of floats
287
+ # Flatten using joint_names
288
+ for idx, pos in enumerate(pos_list):
289
+ if idx < len(self.joint_names):
290
+ name = self.joint_names[idx]
291
+ else:
292
+ name = f"joint{idx+1}"
293
+ obs_dict[f"{name}.pos"] = float(pos)
294
+ except Exception as e:
295
+ logger.error(f"Error reading joint positions: {e}")
296
+ raise DeviceNotConnectedError(f"Failed to read joint positions: {e}")
297
+
298
+ # Read gripper state
299
+ try:
300
+ gstate = self.robot.get_gripper_state()
301
+ if isinstance(gstate, (list, tuple)) and len(gstate) >= 2:
302
+ obs_dict["gripper.left_pos"] = float(gstate[0])
303
+ obs_dict["gripper.right_pos"] = float(gstate[1])
304
+ else:
305
+ val = float(gstate[0]) if isinstance(gstate, (list, tuple)) else float(gstate)
306
+ obs_dict["gripper.left_pos"] = val
307
+ obs_dict["gripper.right_pos"] = val
308
+ except Exception as e:
309
+ logger.warning(f"Failed to read gripper state: {e}")
310
+
311
+ # Read cameras
312
+ for cam_key, cam in self.cameras.items():
313
+ try:
314
+ frame = cam.async_read() if hasattr(cam, "async_read") else cam.read()
315
+ obs_dict[cam_key] = frame
316
+ except Exception as e:
317
+ logger.warning(f"Failed to read camera '{cam_key}': {e}")
318
+
319
+ return obs_dict
320
+
321
+ def send_action(self, action: Dict[str, float]) -> Dict[str, float]:
322
+ """
323
+ Send desired joint targets and gripper control.
324
+ action keys: "<joint_name>.pos" -> target, "gripper.ctrl" -> float.
325
+ Returns the dict of actual sent joint positions.
326
+ """
327
+ if not self.is_connected:
328
+ raise DeviceNotConnectedError(f"{self} is not connected.")
329
+
330
+ # Extract desired joint positions
331
+ goal_pos: Dict[str, float] = {}
332
+ for key, val in action.items():
333
+ if key.endswith(".pos"):
334
+ jname = key[:-4]
335
+ goal_pos[jname] = float(val)
336
+
337
+ # Read current positions
338
+ try:
339
+ current_positions = self.robot.get_joint_positions()
340
+ except Exception as e:
341
+ raise DeviceNotConnectedError(f"Failed to read joint positions for send_action: {e}")
342
+
343
+ # Safety clipping
344
+ if self.config.max_relative_target is not None:
345
+ current_states: Dict[str, float] = {}
346
+ for idx, pos in enumerate(current_positions):
347
+ if idx < len(self.joint_names):
348
+ name = self.joint_names[idx]
349
+ else:
350
+ name = f"joint{idx+1}"
351
+ current_states[name] = float(pos)
352
+ clip_dict: Dict[str, Any] = {}
353
+ for j, desired in goal_pos.items():
354
+ if j in current_states:
355
+ clip_dict[j] = (desired, current_states[j])
356
+ else:
357
+ logger.warning(f"send_action: joint {j} not in current_states; skipping clip")
358
+ clip_dict[j] = (desired, desired)
359
+ try:
360
+ safe_goal = ensure_safe_goal_position(clip_dict, self.config.max_relative_target)
361
+ goal_pos = safe_goal
362
+ except Exception as e:
363
+ logger.warning(f"Could not apply safety clipping: {e}")
364
+
365
+ # Prepare ordered list for PiperControl
366
+ positions_list: List[float] = []
367
+ for idx in range(len(self.joint_names)):
368
+ name = self.joint_names[idx]
369
+ if name in goal_pos:
370
+ positions_list.append(float(goal_pos[name]))
371
+ else:
372
+ # hold current
373
+ if idx < len(current_positions):
374
+ positions_list.append(float(current_positions[idx]))
375
+ else:
376
+ positions_list.append(0.0)
377
+
378
+ # Send joint positions
379
+ try:
380
+ self.robot.set_joint_positions(positions_list)
381
+ except Exception as e:
382
+ logger.error(f"Error sending joint commands: {e}")
383
+ raise DeviceNotConnectedError(f"Failed to send joint commands: {e}")
384
+
385
+ # Handle gripper control
386
+ if "gripper.ctrl" in action:
387
+ try:
388
+ gval = float(action["gripper.ctrl"])
389
+ speed = getattr(self.config, "gripper_speed", 0.1)
390
+ self.robot.set_gripper_ctrl(gval, speed)
391
+ except Exception as e:
392
+ logger.warning(f"Failed to send gripper ctrl: {e}")
393
+
394
+ # Return sent joint positions
395
+ sent: Dict[str, float] = {}
396
+ for idx, pos in enumerate(positions_list):
397
+ name = self.joint_names[idx] if idx < len(self.joint_names) else f"joint{idx+1}"
398
+ sent[f"{name}.pos"] = float(pos)
399
+ return sent
400
+
401
+ def disconnect(self):
402
+ """
403
+ Safely disconnect from Piper hardware and cameras.
404
+ """
405
+ if not self.robot:
406
+ raise DeviceNotConnectedError(f"{self} is not connected.")
407
+ # Attempt to disable or reset hardware
408
+ try:
409
+ if hasattr(self.robot, "disable"):
410
+ try:
411
+ self.robot.disable()
412
+ except Exception:
413
+ self.robot.reset()
414
+ else:
415
+ try:
416
+ self.robot.reset()
417
+ except Exception:
418
+ pass
419
+ except Exception as e:
420
+ logger.warning(f"Error during Piper disable/reset: {e}")
421
+
422
+ # Disconnect cameras
423
+ for cam in self.cameras.values():
424
+ try:
425
+ cam.disconnect()
426
+ except Exception:
427
+ pass
428
+
429
+ self.robot = None
430
+ logger.info(f"{self} disconnected.")
431
+
432
+ def _parse_actuated_joint_names_from_urdf(self, urdf_path: str) -> List[str]:
433
+ """
434
+ Parse URDF file to extract actuated joint names (revolute/prismatic) in order.
435
+ """
436
+ if not os.path.isfile(urdf_path):
437
+ raise FileNotFoundError(f"URDF file not found at {urdf_path}")
438
+ tree = ET.parse(urdf_path)
439
+ root = tree.getroot()
440
+ joint_names: List[str] = []
441
+ for joint in root.findall('joint'):
442
+ jtype = joint.attrib.get('type', '')
443
+ if jtype in ('revolute', 'prismatic'):
444
+ name = joint.attrib.get('name')
445
+ if name:
446
+ joint_names.append(name)
447
+ if not joint_names:
448
+ raise ValueError("No actuated joints found in URDF")
449
+ return joint_names
piper/piper.urdf ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <!-- This URDF was automatically created by SolidWorks to URDF Exporter! Originally created by Stephen Brawner (brawner@gmail.com)
3
+ Commit Version: 1.6.0-4-g7f85cfe Build Version: 1.6.7995.38578
4
+ For more information, please see http://wiki.ros.org/sw_urdf_exporter -->
5
+ <robot
6
+ name="piper">
7
+ <link name="dummy_link"/>
8
+ <joint name="base_to_dummy" type="fixed">
9
+ <parent link="dummy_link"/>
10
+ <child link="base_link"/>
11
+ <origin xyz="0 0 0" rpy="0 0 0"/>
12
+ </joint>
13
+
14
+ <link
15
+ name="base_link">
16
+ <inertial>
17
+ <origin
18
+ xyz="-0.00473641164191482 2.56829134630247E-05 0.041451518036016"
19
+ rpy="0 0 0" />
20
+ <mass
21
+ value="1.02" />
22
+ <inertia
23
+ ixx="0.00267433"
24
+ ixy="-0.00000073"
25
+ ixz="-0.00017389"
26
+ iyy="0.00282612"
27
+ iyz="0.0000004"
28
+ izz="0.00089624" />
29
+ </inertial>
30
+ <visual>
31
+ <origin
32
+ xyz="0 0 0"
33
+ rpy="0 0 0" />
34
+ <geometry>
35
+ <mesh
36
+ filename="package://piper_description/meshes/base_link.STL" />
37
+ </geometry>
38
+ <material
39
+ name="">
40
+ <color
41
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
42
+ </material>
43
+ </visual>
44
+ <collision>
45
+ <origin
46
+ xyz="0 0 0"
47
+ rpy="0 0 0" />
48
+ <geometry>
49
+ <mesh
50
+ filename="package://piper_description/meshes/base_link.STL" />
51
+ </geometry>
52
+ </collision>
53
+ </link>
54
+
55
+ <link
56
+ name="link1">
57
+ <inertial>
58
+ <origin
59
+ xyz="0.000121504734057468 0.000104632162460536 -0.00438597309559853"
60
+ rpy="0 0 0" />
61
+ <mass
62
+ value="0.71" />
63
+ <inertia
64
+ ixx="0.00048916"
65
+ ixy="-0.00000036"
66
+ ixz="-0.00000224"
67
+ iyy="0.00040472"
68
+ iyz="-0.00000242"
69
+ izz="0.00043982" />
70
+ </inertial>
71
+ <visual>
72
+ <origin
73
+ xyz="0 0 0"
74
+ rpy="0 0 0" />
75
+ <geometry>
76
+ <mesh
77
+ filename="package://piper_description/meshes/link1.STL" />
78
+ </geometry>
79
+ <material
80
+ name="">
81
+ <color
82
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
83
+ </material>
84
+ </visual>
85
+ <collision>
86
+ <origin
87
+ xyz="0 0 0"
88
+ rpy="0 0 0" />
89
+ <geometry>
90
+ <mesh
91
+ filename="package://piper_description/meshes/link1.STL" />
92
+ </geometry>
93
+ </collision>
94
+ </link>
95
+ <joint
96
+ name="joint1"
97
+ type="revolute">
98
+ <origin
99
+ xyz="0 0 0.123"
100
+ rpy="0 0 0" />
101
+ <parent
102
+ link="base_link" />
103
+ <child
104
+ link="link1" />
105
+ <axis
106
+ xyz="0 0 1" />
107
+ <limit
108
+ lower="-2.618"
109
+ upper="2.618"
110
+ effort="100"
111
+ velocity="5" />
112
+ </joint>
113
+ <link
114
+ name="link2">
115
+ <inertial>
116
+ <origin
117
+ xyz="0.198666145229743 -0.010926924140076 0.00142121714502687"
118
+ rpy="0 0 0" />
119
+ <mass
120
+ value="1.17" />
121
+ <inertia
122
+ ixx="0.00116918"
123
+ ixy="-0.00180037"
124
+ ixz="0.00025146"
125
+ iyy="0.06785384"
126
+ iyz="-0.00000455"
127
+ izz="0.06774489" />
128
+ </inertial>
129
+ <visual>
130
+ <origin
131
+ xyz="0 0 0"
132
+ rpy="0 0 0" />
133
+ <geometry>
134
+ <mesh
135
+ filename="package://piper_description/meshes/link2.STL" />
136
+ </geometry>
137
+ <material
138
+ name="">
139
+ <color
140
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
141
+ </material>
142
+ </visual>
143
+ <collision>
144
+ <origin
145
+ xyz="0 0 0"
146
+ rpy="0 0 0" />
147
+ <geometry>
148
+ <mesh
149
+ filename="package://piper_description/meshes/link2.STL" />
150
+ </geometry>
151
+ </collision>
152
+ </link>
153
+ <joint
154
+ name="joint2"
155
+ type="revolute">
156
+ <origin
157
+ xyz="0 0 0"
158
+ rpy="1.5708 -0.1359 -3.1416" />
159
+ <!-- rpy="1.5708 -0.10095-0.03490659 -3.1416" /> -->
160
+ <parent
161
+ link="link1" />
162
+ <child
163
+ link="link2" />
164
+ <axis
165
+ xyz="0 0 1" />
166
+ <limit
167
+ lower="0"
168
+ upper="3.14"
169
+ effort="100"
170
+ velocity="5" />
171
+ </joint>
172
+ <link
173
+ name="link3">
174
+ <inertial>
175
+ <origin
176
+ xyz="-0.0202737662122021 -0.133914995944595 -0.000458682652737356"
177
+ rpy="0 0 0" />
178
+ <mass
179
+ value="0.5" />
180
+ <inertia
181
+ ixx="0.01361711"
182
+ ixy="0.00165794"
183
+ ixz="-0.00000048"
184
+ iyy="0.00045024"
185
+ iyz="-0.00000045"
186
+ izz="0.01380322" />
187
+ </inertial>
188
+ <visual>
189
+ <origin
190
+ xyz="0 0 0"
191
+ rpy="0 0 0" />
192
+ <geometry>
193
+ <mesh
194
+ filename="package://piper_description/meshes/link3.STL" />
195
+ </geometry>
196
+ <material
197
+ name="">
198
+ <color
199
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
200
+ </material>
201
+ </visual>
202
+ <collision>
203
+ <origin
204
+ xyz="0 0 0"
205
+ rpy="0 0 0" />
206
+ <geometry>
207
+ <mesh
208
+ filename="package://piper_description/meshes/link3.STL" />
209
+ </geometry>
210
+ </collision>
211
+ </link>
212
+ <joint
213
+ name="joint3"
214
+ type="revolute">
215
+ <origin
216
+ xyz="0.28503 0 0"
217
+ rpy="0 0 -1.7939" />
218
+ <!-- rpy="0 0 -1.759-0.03490659" /> -->
219
+ <parent
220
+ link="link2" />
221
+ <child
222
+ link="link3" />
223
+ <axis
224
+ xyz="0 0 1" />
225
+ <limit
226
+ lower="-2.967"
227
+ upper="0"
228
+ effort="100"
229
+ velocity="5" />
230
+ </joint>
231
+ <link
232
+ name="link4">
233
+ <inertial>
234
+ <origin
235
+ xyz="-9.66635791618542E-05 0.000876064475651083 -0.00496880904640868"
236
+ rpy="0 0 0" />
237
+ <mass
238
+ value="0.38" />
239
+ <inertia
240
+ ixx="0.00018501"
241
+ ixy="0.00000054"
242
+ ixz="0.00000120"
243
+ iyy="0.00018965"
244
+ iyz="-0.00000841"
245
+ izz="0.00015484" />
246
+ </inertial>
247
+ <visual>
248
+ <origin
249
+ xyz="0 0 0"
250
+ rpy="0 0 0" />
251
+ <geometry>
252
+ <mesh
253
+ filename="package://piper_description/meshes/link4.STL" />
254
+ </geometry>
255
+ <material
256
+ name="">
257
+ <color
258
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
259
+ </material>
260
+ </visual>
261
+ <collision>
262
+ <origin
263
+ xyz="0 0 0"
264
+ rpy="0 0 0" />
265
+ <geometry>
266
+ <mesh
267
+ filename="package://piper_description/meshes/link4.STL" />
268
+ </geometry>
269
+ </collision>
270
+ </link>
271
+ <joint
272
+ name="joint4"
273
+ type="revolute">
274
+ <origin
275
+ xyz="-0.021984 -0.25075 0"
276
+ rpy="1.5708 0 0" />
277
+ <parent
278
+ link="link3" />
279
+ <child
280
+ link="link4" />
281
+ <axis
282
+ xyz="0 0 1" />
283
+ <limit
284
+ lower="-1.745"
285
+ upper="1.745"
286
+ effort="100"
287
+ velocity="5" />
288
+ </joint>
289
+ <link
290
+ name="link5">
291
+ <inertial>
292
+ <origin
293
+ xyz="-4.10554118924211E-05 -0.0566486692356075 -0.0037205791677906"
294
+ rpy="0 0 0" />
295
+ <mass
296
+ value="0.383" />
297
+ <inertia
298
+ ixx="0.00166169"
299
+ ixy="0.00000006"
300
+ ixz="-0.00000007"
301
+ iyy="0.00018510"
302
+ iyz="0.00001026"
303
+ izz="0.00164321" />
304
+ </inertial>
305
+ <visual>
306
+ <origin
307
+ xyz="0 0 0"
308
+ rpy="0 0 0" />
309
+ <geometry>
310
+ <mesh
311
+ filename="package://piper_description/meshes/link5.STL" />
312
+ </geometry>
313
+ <material
314
+ name="">
315
+ <color
316
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
317
+ </material>
318
+ </visual>
319
+ <collision>
320
+ <origin
321
+ xyz="0 0 0"
322
+ rpy="0 0 0" />
323
+ <geometry>
324
+ <mesh
325
+ filename="package://piper_description/meshes/link5.STL" />
326
+ </geometry>
327
+ </collision>
328
+ </link>
329
+ <joint
330
+ name="joint5"
331
+ type="revolute">
332
+ <origin
333
+ xyz="0 0 0"
334
+ rpy="-1.5708 0 0" />
335
+ <parent
336
+ link="link4" />
337
+ <child
338
+ link="link5" />
339
+ <axis
340
+ xyz="0 0 1" />
341
+ <limit
342
+ lower="-1.22"
343
+ upper="1.22"
344
+ effort="100"
345
+ velocity="5" />
346
+ </joint>
347
+ <link
348
+ name="link6">
349
+ <inertial>
350
+ <origin
351
+ xyz="-8.82590762930069E-05 9.0598378529832E-06 -0.002"
352
+ rpy="0 0 0" />
353
+ <mass
354
+ value="0.007" />
355
+ <inertia
356
+ ixx="5.73015540542155E-07"
357
+ ixy="-1.98305403089247E-22"
358
+ ixz="-7.2791893904596E-23"
359
+ iyy="5.73015540542155E-07"
360
+ iyz="-3.4146026640245E-24"
361
+ izz="1.06738869138926E-06" />
362
+ </inertial>
363
+ <visual>
364
+ <origin
365
+ xyz="0 0 0"
366
+ rpy="0 0 0" />
367
+ <geometry>
368
+ <mesh
369
+ filename="package://piper_description/meshes/link6.STL" />
370
+ </geometry>
371
+ <material
372
+ name="">
373
+ <color
374
+ rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
375
+ </material>
376
+ </visual>
377
+ <collision>
378
+ <origin
379
+ xyz="0 0 0"
380
+ rpy="0 0 0" />
381
+ <geometry>
382
+ <mesh
383
+ filename="package://piper_description/meshes/link6.STL" />
384
+ </geometry>
385
+ </collision>
386
+ </link>
387
+ <joint
388
+ name="joint6"
389
+ type="revolute">
390
+ <origin
391
+ xyz="8.8259E-05 -0.091 0"
392
+ rpy="1.5708 0 0" />
393
+ <parent
394
+ link="link5" />
395
+ <child
396
+ link="link6" />
397
+ <axis
398
+ xyz="0 0 1" />
399
+ <limit
400
+ lower="-2.0944"
401
+ upper="2.0944"
402
+ effort="100"
403
+ velocity="3" />
404
+ </joint>
405
+ <link
406
+ name="gripper_base">
407
+ <inertial>
408
+ <origin
409
+ xyz="-0.000183807162235591 8.05033155577911E-05 0.0321436689908876"
410
+ rpy="0 0 0" />
411
+ <mass
412
+ value="0.45" />
413
+ <inertia
414
+ ixx="0.00092934"
415
+ ixy="0.00000034"
416
+ ixz="-0.00000738"
417
+ iyy="0.00071447"
418
+ iyz="0.00000005"
419
+ izz="0.00039442" />
420
+ </inertial>
421
+ <visual>
422
+ <origin
423
+ xyz="0 0 0"
424
+ rpy="0 0 0" />
425
+ <geometry>
426
+ <mesh
427
+ filename="package://piper_description/meshes/gripper_base.STL" />
428
+ </geometry>
429
+ <material
430
+ name="">
431
+ <color
432
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
433
+ </material>
434
+ </visual>
435
+ <collision>
436
+ <origin
437
+ xyz="0 0 0"
438
+ rpy="0 0 0" />
439
+ <geometry>
440
+ <mesh
441
+ filename="package://piper_description/meshes/gripper_base.STL" />
442
+ </geometry>
443
+ </collision>
444
+ </link>
445
+ <joint
446
+ name="joint6_to_gripper_base"
447
+ type="fixed">
448
+ <origin
449
+ xyz="0 0 0"
450
+ rpy="0 0 0" />
451
+ <parent
452
+ link="link6" />
453
+ <child
454
+ link="gripper_base" />
455
+ </joint>
456
+ <link
457
+ name="link7">
458
+ <inertial>
459
+ <origin
460
+ xyz="0.00065123185041968 -0.0491929869131989 0.00972258769184025"
461
+ rpy="0 0 0" />
462
+ <mass
463
+ value="0.025" />
464
+ <inertia
465
+ ixx="0.00007371"
466
+ ixy="-0.00000113"
467
+ ixz="0.00000021"
468
+ iyy="0.00000781"
469
+ iyz="-0.00001372"
470
+ izz="0.0000747" />
471
+ </inertial>
472
+ <visual>
473
+ <origin
474
+ xyz="0 0 0"
475
+ rpy="0 0 0" />
476
+ <geometry>
477
+ <mesh
478
+ filename="package://piper_description/meshes/link7.STL" />
479
+ </geometry>
480
+ <material
481
+ name="">
482
+ <color
483
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
484
+ </material>
485
+ </visual>
486
+ <collision>
487
+ <origin
488
+ xyz="0 0 0"
489
+ rpy="0 0 0" />
490
+ <geometry>
491
+ <mesh
492
+ filename="package://piper_description/meshes/link7.STL" />
493
+ </geometry>
494
+ </collision>
495
+ </link>
496
+ <joint
497
+ name="joint7"
498
+ type="prismatic">
499
+ <origin
500
+ xyz="0 0 0.1358"
501
+ rpy="1.5708 0 0" />
502
+ <parent
503
+ link="gripper_base" />
504
+ <child
505
+ link="link7" />
506
+ <axis
507
+ xyz="0 0 1" />
508
+ <limit
509
+ lower="0"
510
+ upper="0.035"
511
+ effort="10"
512
+ velocity="1" />
513
+ </joint>
514
+ <link
515
+ name="link8">
516
+ <inertial>
517
+ <origin
518
+ xyz="0.000651231850419722 -0.0491929869131991 0.00972258769184024"
519
+ rpy="0 0 0" />
520
+ <mass
521
+ value="0.025" />
522
+ <inertia
523
+ ixx="0.00007371"
524
+ ixy="-0.00000113"
525
+ ixz="0.00000021"
526
+ iyy="0.00000781"
527
+ iyz="-0.00001372"
528
+ izz="0.0000747" />
529
+ </inertial>
530
+ <visual>
531
+ <origin
532
+ xyz="0 0 0"
533
+ rpy="0 0 0" />
534
+ <geometry>
535
+ <mesh
536
+ filename="package://piper_description/meshes/link8.STL" />
537
+ </geometry>
538
+ <material
539
+ name="">
540
+ <color
541
+ rgba="0.792156862745098 0.819607843137255 0.933333333333333 1" />
542
+ </material>
543
+ </visual>
544
+ <collision>
545
+ <origin
546
+ xyz="0 0 0"
547
+ rpy="0 0 0" />
548
+ <geometry>
549
+ <mesh
550
+ filename="package://piper_description/meshes/link8.STL" />
551
+ </geometry>
552
+ </collision>
553
+ </link>
554
+ <joint
555
+ name="joint8"
556
+ type="prismatic">
557
+ <origin
558
+ xyz="0 0 0.1358"
559
+ rpy="1.5708 0 -3.1416" />
560
+ <parent
561
+ link="gripper_base" />
562
+ <child
563
+ link="link8" />
564
+ <axis
565
+ xyz="0 0 -1" />
566
+ <limit
567
+ lower="-0.035"
568
+ upper="0"
569
+ effort="10"
570
+ velocity="1" />
571
+ </joint>
572
+ </robot>
piper/piper.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # lerobot/configs/robot/piper.yaml
2
+
3
+ name: piper
4
+ urdf_path: common/robots/piper/piper.urdf
5
+ base_link: base_link # update if your URDF’s base link name differs
6
+ end_effector_link: tool0 # update if your URDF’s end-effector link differs
7
+ control_mode: position
8
+ dof: 6
9
+ joint_names:
10
+ # Must match the joint names used by PiperRobot:
11
+ # If your URDF has joints named "joint1", "joint2", etc., list them here.
12
+ - joint1
13
+ - joint2
14
+ - joint3
15
+ - joint4
16
+ - joint5
17
+ - joint6
py_teleop_data_collect.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding:utf8 -*-
3
+
4
+ import os
5
+ import sys
6
+ import time
7
+ import math
8
+ import csv
9
+ import datetime
10
+
11
+ import pygame
12
+ import cv2
13
+ import numpy as np
14
+ import pyrealsense2 as rs
15
+
16
+ from piper_sdk import C_PiperInterface_V2
17
+
18
+ # Workspace bounds and fixed orientation
19
+ X_MIN, X_MAX = 200000, 500000
20
+ Y_MIN, Y_MAX = -100000, 200000
21
+ Z_MIN, Z_MAX = 140000, 250000
22
+ FIXED_RX = 177756
23
+ FIXED_RY = 6035
24
+ FIXED_RZ = -158440
25
+ ROTATION_RANGE = 50000 # ± rotation offset around Z
26
+ GRIP_OPEN, GRIP_CLOSE = 80000, 0
27
+ HEARTBEAT_CMD_1, HEARTBEAT_CMD_2 = 0x01, 0x02
28
+ HEARTBEAT_SPEED = 70
29
+ HEARTBEAT_FLAG = 0x00
30
+ LOOP_HZ = 30
31
+ DELAY_S = 0.01
32
+
33
+ # Key to end episode and exit
34
+ END_EPISODE_KEY = pygame.K_p
35
+
36
+
37
+ def enable_fun(piper: C_PiperInterface_V2, timeout: float = 5.0):
38
+ """
39
+ Enable all six motors and the gripper.
40
+ Exits on timeout if not all drivers report enabled.
41
+ """
42
+ start_time = time.time()
43
+ while True:
44
+ piper.EnableArm(7)
45
+ piper.GripperCtrl(GRIP_OPEN, 1000, 0x01, 0)
46
+ info = piper.GetArmLowSpdInfoMsgs()
47
+ flags = [
48
+ info.motor_1.foc_status.driver_enable_status,
49
+ info.motor_2.foc_status.driver_enable_status,
50
+ info.motor_3.foc_status.driver_enable_status,
51
+ info.motor_4.foc_status.driver_enable_status,
52
+ info.motor_5.foc_status.driver_enable_status,
53
+ info.motor_6.foc_status.driver_enable_status,
54
+ ]
55
+ print("Motor enabled states:", all(flags))
56
+ if all(flags):
57
+ print("Piper online ✅")
58
+ return
59
+ if time.time() - start_time > timeout:
60
+ print(f"Enable timeout after {timeout} seconds. Exiting.")
61
+ sys.exit(1)
62
+ time.sleep(1)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ # Initialize Piper
67
+ piper = C_PiperInterface_V2("can0")
68
+ piper.ConnectPort()
69
+ enable_fun(piper)
70
+
71
+ # Initial gripper open, heartbeat + center pose
72
+ piper.GripperCtrl(GRIP_OPEN, 1000, 0x01, 0)
73
+ piper.MotionCtrl_2(HEARTBEAT_CMD_1, HEARTBEAT_CMD_2, HEARTBEAT_SPEED, HEARTBEAT_FLAG)
74
+ init_x = (X_MIN + X_MAX) // 2
75
+ init_y = (Y_MIN + Y_MAX) // 2
76
+ init_z = (Z_MIN + Z_MAX) // 2
77
+ piper.EndPoseCtrl(init_x, init_y, init_z, FIXED_RX, FIXED_RY, FIXED_RZ)
78
+ time.sleep(DELAY_S)
79
+
80
+ # Setup data directories for this episode
81
+ episode_id = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
82
+ base_dir = os.path.join('data', episode_id)
83
+ color_dir = os.path.join(base_dir, 'color')
84
+ depth_dir = os.path.join(base_dir, 'depth')
85
+ cam_dir = os.path.join(base_dir, 'webcam')
86
+ os.makedirs(color_dir, exist_ok=True)
87
+ os.makedirs(depth_dir, exist_ok=True)
88
+ os.makedirs(cam_dir, exist_ok=True)
89
+
90
+ # Open CSV for logging
91
+ csv_path = os.path.join(base_dir, 'data.csv')
92
+ csv_file = open(csv_path, mode='w', newline='')
93
+ writer = csv.writer(csv_file)
94
+ headers = [
95
+ 'timestamp',
96
+ 'joint1', 'joint2', 'joint3', 'joint4', 'joint5', 'joint6',
97
+ 'x', 'y', 'z', 'rx', 'ry', 'rz', 'grip',
98
+ 'color_image', 'depth_image', 'webcam_image'
99
+ ]
100
+ writer.writerow(headers)
101
+
102
+ # Initialize cameras
103
+ rs_pipeline = rs.pipeline()
104
+ rs_config = rs.config()
105
+ rs_config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
106
+ rs_config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
107
+ rs_pipeline.start(rs_config)
108
+
109
+ cap = cv2.VideoCapture(10)
110
+ if not cap.isOpened():
111
+ print("Camera 8 failed to open.")
112
+ else:
113
+ print("Camera 8 opened successfully.")
114
+
115
+ # Initialize Pygame & controller
116
+ pygame.init()
117
+ pygame.joystick.init()
118
+ screen = pygame.display.set_mode((100, 100))
119
+ if pygame.joystick.get_count() == 0:
120
+ print("No joystick detected.")
121
+ sys.exit(1)
122
+ joystick = pygame.joystick.Joystick(0)
123
+ joystick.init()
124
+ print(f"Detected controller: {joystick.get_name()}")
125
+ clock = pygame.time.Clock()
126
+
127
+ try:
128
+ while True:
129
+ for event in pygame.event.get():
130
+ if event.type == pygame.QUIT:
131
+ raise KeyboardInterrupt
132
+ if event.type == pygame.KEYDOWN and event.key == END_EPISODE_KEY:
133
+ print("Ending episode and exiting script.")
134
+ sys.exit(0)
135
+
136
+ # Read inputs
137
+ raw_ly = joystick.get_axis(0)
138
+ raw_lx = joystick.get_axis(1)
139
+ raw_lt = joystick.get_axis(2)
140
+ raw_rx = joystick.get_axis(3)
141
+ raw_rt = joystick.get_axis(5)
142
+
143
+ # Map to workspace
144
+ mapped_x = int(X_MIN + (raw_lx + 1) * 0.5 * (X_MAX - X_MIN))
145
+ mapped_y = int(Y_MIN + (raw_ly + 1) * 0.5 * (Y_MAX - Y_MIN))
146
+ mapped_z = int(Z_MIN + (1 - (raw_lt + 1) * 0.5) * (Z_MAX - Z_MIN))
147
+ mapped_rz = int(FIXED_RZ + raw_rx * ROTATION_RANGE)
148
+ grip_val = int(GRIP_OPEN + (raw_rt + 1) * 0.5 * (GRIP_CLOSE - GRIP_OPEN))
149
+
150
+ # Send commands
151
+ piper.MotionCtrl_2(HEARTBEAT_CMD_1, HEARTBEAT_CMD_2, HEARTBEAT_SPEED, HEARTBEAT_FLAG)
152
+ piper.EndPoseCtrl(mapped_x, mapped_y, mapped_z, FIXED_RX, FIXED_RY, mapped_rz)
153
+ piper.GripperCtrl(grip_val, 1000, 0x01, 0)
154
+
155
+ # Timestamp
156
+ ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S_%f')
157
+
158
+ # Read joints
159
+ high_info = piper.GetArmHighSpdInfoMsgs()
160
+ try:
161
+ joints = [
162
+ getattr(high_info, f"motor_{i}").mechanical_angle
163
+ for i in range(1, 7)
164
+ ]
165
+ except Exception:
166
+ joints = [None] * 6
167
+
168
+ # Capture frames
169
+ frames = rs_pipeline.wait_for_frames()
170
+ color_frame = frames.get_color_frame()
171
+ depth_frame = frames.get_depth_frame()
172
+ color_image = np.asanyarray(color_frame.get_data())
173
+ depth_image = np.asanyarray(depth_frame.get_data())
174
+
175
+ ret_cam, cam_image = cap.read()
176
+ print("ret_cam:", ret_cam)
177
+ if cam_image is not None:
178
+ print("cam_image shape:", cam_image.shape)
179
+ cv2.imwrite("test_cam_output.png", cam_image)
180
+ else:
181
+ print("Camera frame is None")
182
+
183
+ # Save images
184
+ color_path = os.path.join(color_dir, f"color_{ts}.png")
185
+ depth_path = os.path.join(depth_dir, f"depth_{ts}.png")
186
+ cam_path = os.path.join(cam_dir, f"cam_{ts}.png")
187
+ cv2.imwrite(color_path, color_image)
188
+ cv2.imwrite(depth_path, depth_image)
189
+ if ret_cam:
190
+ cv2.imwrite(cam_path, cam_image)
191
+ else:
192
+ cam_path = ''
193
+
194
+ # Log data
195
+ row = [ts] + joints + [mapped_x, mapped_y, mapped_z,
196
+ FIXED_RX, FIXED_RY, mapped_rz,
197
+ grip_val,
198
+ color_path, depth_path, cam_path]
199
+ writer.writerow(row)
200
+ csv_file.flush()
201
+
202
+ # Feedback & throttle
203
+ print(f"{ts} | X:{mapped_x} Y:{mapped_y} Z:{mapped_z} RZ:{mapped_rz} Grip:{grip_val}")
204
+ clock.tick(LOOP_HZ)
205
+ time.sleep(DELAY_S)
206
+
207
+ except KeyboardInterrupt:
208
+ print("Interrupted by user, exiting.")
209
+
210
+ finally:
211
+ # Cleanup
212
+ csv_file.close()
213
+ rs_pipeline.stop()
214
+ cap.release()
215
+ pygame.quit()