ubtech_dataset7 / ros2_deployment_inspire_right_arm.py
itdevhumanoid's picture
Upload 2 files
a5401a1 verified
Raw History Blame Contribute Delete
12.2 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ROS2 Deployment Script for Right Arm + Gripper + 2 Cameras
Data: Right Arm (7 DOF) + Gripper (1 DOF) = 8 DOF total
Cameras: Head Camera (640x360) + Wrist Camera (320x240)
"""
import os
import rclpy
from rclpy.node import Node
from rclpy.executors import MultiThreadedExecutor
import cv2
from typing import Tuple
import time
import numpy as np
from cv_bridge import CvBridge
from sensor_msgs.msg import Image, JointState
from std_msgs.msg import Header, Int32
# Import message types
try:
from bodyctrl_msgs.msg import CmdSetMotorPosition, MotorStatusMsg, SetMotorPosition
BODYCTRL_AVAILABLE = True
except ImportError:
from std_msgs.msg import String as CmdSetMotorPosition
from std_msgs.msg import String as MotorStatusMsg
from std_msgs.msg import String as SetMotorPosition
BODYCTRL_AVAILABLE = False
print("Warning: bodyctrl_msgs package is not available, will use String message type as replacement")
# Use message_filters for message synchronization
from message_filters import ApproximateTimeSynchronizer, Subscriber
from action_policy import PolicyAgent
class PolicyAgentNode(Node):
"""
Policy Agent Node for Right Arm + Gripper
Observation: 8 DOF (arm 7 + gripper 1) + 2 cameras
Action: 8 DOF (arm 7 + gripper 1)
"""
def __init__(self):
super().__init__('policy_agent_node')
# DEBUG
self.cnt = 0
# Update this path to your trained model
model_path = "/home/ubuntu/bwr/imitation_learning_models/tienkung_xsens_act7_2/pretrained_model"
self.action_policy = PolicyAgent(model_path)
# ========== ARM STATUS ==========
self.joint_state_sub = self.create_subscription(
MotorStatusMsg,
'/arm/status',
self.arm_callback,
10)
self.left_jpos = None
self.right_jpos = None
# ========== GRIPPER STATE ==========
self.gripper_state = 0.0 # Default: open (0)
self.gripper_sub = self.create_subscription(
Int32,
'/gripper/right/grip',
self.gripper_callback,
10)
# ========== CAMERAS ==========
self.bridge = CvBridge()
self.head_image = None
self.wrist_image = None
# Head camera (640x360)
self.head_camera_sub = self.create_subscription(
Image,
'/camera/color/image_raw',
self.head_camera_callback,
10)
# Wrist camera (320x240)
self.wrist_camera_sub = self.create_subscription(
Image,
'/hand_camera/color/right/image_raw',
self.wrist_camera_callback,
10)
# ========== CONTROL PUBLISHERS ==========
# Arm control
self.dual_arm_controller = self.create_publisher(
CmdSetMotorPosition,
'/arm/cmd_pos',
10)
# Gripper control
self.gripper_publisher = self.create_publisher(
Int32,
'/gripper/right/cmd',
10)
self.get_logger().info('PolicyAgentNode initialization completed')
self.get_logger().info(' Data: Right Arm (7) + Gripper (1) + 2 Cameras')
def arm_callback(self, msg):
"""Callback for arm status"""
tmp_arms_status = []
for val in msg.status:
tmp_arms_status.append(val.pos)
self.left_jpos = np.array(tmp_arms_status[:7])
self.right_jpos = np.array(tmp_arms_status[7:])
def gripper_callback(self, msg: Int32):
"""Callback for gripper state (Int32: 0=open, 1=closed)"""
# Convert int to float: 0 -> 0.0 (open), 1 -> 1.0 (closed)
self.gripper_state = float(msg.data)
def head_camera_callback(self, msg: Image):
"""Callback for head camera"""
try:
self.head_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='rgb8')
# Resize to 640x360 if needed
if self.head_image.shape[1] != 640 or self.head_image.shape[0] != 360:
self.head_image = cv2.resize(self.head_image, (640, 360))
except Exception as e:
self.get_logger().error(f"Error converting head image: {e}")
def wrist_camera_callback(self, msg: Image):
"""Callback for wrist camera"""
try:
self.wrist_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='rgb8')
# Resize to 320x240 if needed
if self.wrist_image.shape[1] != 320 or self.wrist_image.shape[0] != 240:
self.wrist_image = cv2.resize(self.wrist_image, (320, 240))
except Exception as e:
self.get_logger().error(f"Error converting wrist image: {e}")
def get_current_arm_status(self):
"""Get current RIGHT arm status (7 DOF)"""
if self.right_jpos is None:
self.get_logger().warning('Right arm status not ready yet')
return np.zeros(7)
return np.array(self.right_jpos)
def get_current_state(self):
"""Get combined state: arm(7) + gripper(1) = 8 DOF"""
arm_state = self.get_current_arm_status()
gripper = np.array([self.gripper_state])
return np.concatenate([arm_state, gripper])
def _construct_right_arm_ctrl_msg(self, target_joint: np.ndarray):
"""Construct control message for right arm only (7 DOF)"""
msg = CmdSetMotorPosition()
msg.header = Header()
msg.header.stamp = self.get_clock().now().to_msg()
# Control right arm only (motor indices 21-27 for right arm)
# Matching ros2_deployment_inspire_head.py motor IDs
for idx, val in enumerate(target_joint):
cmd = SetMotorPosition()
cmd.name = 21 + idx # Right arm motors: 21, 22, 23, 24, 25, 26, 27
cmd.pos = float(val)
cmd.spd = 0.5
cmd.cur = 5.0
msg.cmds.append(cmd)
return msg
def _construct_dual_arm_ctrl_msg(self, target_joint: np.ndarray):
"""Construct control message for both arms (14 DOF)"""
msg = CmdSetMotorPosition()
msg.header = Header()
msg.header.stamp = self.get_clock().now().to_msg()
for idx, val in enumerate(target_joint):
cmd = SetMotorPosition()
if idx < 7:
# Left arm motors: 11-17
cmd.name = 11 + idx
else:
# Right arm motors: 21-27 (matching ros2_deployment_inspire_head.py)
cmd.name = 14 + idx
cmd.pos = float(val)
cmd.spd = 2.0
cmd.cur = 5.0
msg.cmds.append(cmd)
return msg
def publish_action(self, action: np.ndarray):
"""
Publish action to robot
Args:
action: [8d] = arm(7) + gripper(1)
"""
# Extract arm action (first 7 values)
arm_action = action[:7]
# Extract gripper action (last value)
gripper_action = action[7] if len(action) > 7 else 0.0
# Publish arm control
self.dual_arm_controller.publish(self._construct_right_arm_ctrl_msg(arm_action))
# Publish gripper control
gripper_msg = Int32()
gripper_msg.data = 1 if gripper_action > 0.5 else 0 # Threshold at 0.5
self.gripper_publisher.publish(gripper_msg)
def get_obs(self):
"""Get observations for policy inference"""
obs = {
'images': {
'camera_head': None,
'camera_wrist': None
},
'arm_gripper_joints': None
}
# Get state: arm(7) + gripper(1) = 8 DOF
state = self.get_current_state()
# Check images
if self.head_image is None or self.wrist_image is None:
self.get_logger().warning("Images not ready yet")
return None
obs['images']['camera_head'] = self.head_image
obs['images']['camera_wrist'] = self.wrist_image
obs['arm_gripper_joints'] = state
return obs
def reset_home(self):
"""Reset both arms to initial position"""
# Initial position for both arms (14 DOF)
# Adjust these values based on your robot's home position
state_home = [
-0.1525799448897199,
0.06799564128968774,
0.1352429110829423,
-0.1,
0.12439771977866568,
-0.36139144432253956,
-0.00591924481275605,
-0.6,
-0.003778287841052544,
-0.13665378849680831,
-0.8683540414019328,
-0.287210096964022,
-0.4483082608478825,
0.19435190805574742
]
self.get_logger().info("Resetting both arms to initial position...")
time.sleep(3)
# Get current status
if self.left_jpos is None or self.right_jpos is None:
self.get_logger().warning('Arm status not ready yet, using zeros')
current_status = np.zeros(14)
else:
current_status = np.concatenate([self.left_jpos, self.right_jpos])
# Debug: Log current and target positions
self.get_logger().info(f"Current left arm (7 DOF): {self.left_jpos}")
self.get_logger().info(f"Current right arm (7 DOF): {self.right_jpos}")
self.get_logger().info(f"Current combined (14 DOF): {current_status}")
self.get_logger().info(f"Target home (14 DOF): {state_home}")
# Calculate difference
diff = np.array(state_home) - current_status
self.get_logger().info(f"Difference (target - current): {diff}")
self.get_logger().info(f"Max difference: {np.max(np.abs(diff)):.4f} rad")
# Move to initial position
fine_step = 500
step_array = np.linspace(current_status, state_home, fine_step)
for stp in step_array:
self.dual_arm_controller.publish(self._construct_dual_arm_ctrl_msg(stp))
time.sleep(1.0/400.0)
# Open gripper
gripper_msg = Int32()
gripper_msg.data = 0 # Open
self.gripper_publisher.publish(gripper_msg)
self.get_logger().info("Reset to initial position completed")
self.get_logger().info("Note: During inference, only right arm + gripper will be controlled")
def warm_up(self):
"""Wait for subscribers to receive messages"""
time.sleep(3)
self.get_logger().info('System warm-up completed')
def run(self):
"""Run the main loop"""
self.warm_up()
self.get_logger().info("Starting reset home")
self.reset_home()
self.get_logger().info("Ending reset home")
self.get_logger().info("Starting main loop")
while rclpy.ok():
# Get observations
obs = self.get_obs()
if obs is None:
self.get_logger().warning("Observations not ready yet")
time.sleep(0.1)
continue
print(f"State (8 DOF): {obs['arm_gripper_joints']}")
# Run inference
action = self.action_policy.inference(obs)
action_np = action[0].numpy()
# Publish action
self.publish_action(action_np)
# Match data collection FPS (30Hz)
time.sleep(0.033)
def main(args=None):
rclpy.init(args=args)
try:
node = PolicyAgentNode()
executor = MultiThreadedExecutor(num_threads=3)
executor.add_node(node)
import threading
executor_thread = threading.Thread(target=executor.spin, daemon=True)
executor_thread.start()
node.run()
except KeyboardInterrupt:
pass
finally:
rclpy.shutdown()
if __name__ == '__main__':
main()