diff --git a/.gitattributes b/.gitattributes
index 018010d21238474966a97cac788c8ade1e395efc..b696d1d30394fadbfe96a7069ad0087f36df0ddb 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -169,3 +169,6 @@ simulation/assets/g1/configuration/g1_29dof_rev_1_0_with_inspire_hand_retarget_i
simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/mdp/__pycache__/events.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
simulation/modules/IsaacLab/source/isaaclab_physx/isaaclab_physx/assets/articulation/__pycache__/articulation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.o filter=lfs diff=lfs merge=lfs -text
+third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.o filter=lfs diff=lfs merge=lfs -text
+third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.o filter=lfs diff=lfs merge=lfs -text
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand.xml
new file mode 100644
index 0000000000000000000000000000000000000000..a53cd991faf3a296bf67acbf78cd702ce15c31d0
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand.xml
@@ -0,0 +1,748 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand_rev_1_0_activatedfinger.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand_rev_1_0_activatedfinger.xml
new file mode 100644
index 0000000000000000000000000000000000000000..b508fe4cc13dac807c94af2b115c034e88e69b0f
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand_rev_1_0_activatedfinger.xml
@@ -0,0 +1,669 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ -->
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/lift_box_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/lift_box_43dof.xml
new file mode 100644
index 0000000000000000000000000000000000000000..3ac8a3f5cc0fbf2c34c374cec1448cee00b0ce41
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/lift_box_43dof.xml
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_bottle_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_bottle_43dof.xml
new file mode 100644
index 0000000000000000000000000000000000000000..cf4d4da2fff09f0d8205335dfdacbe82cc1b3ccb
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_bottle_43dof.xml
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_cube_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_cube_43dof.xml
new file mode 100644
index 0000000000000000000000000000000000000000..cb61b70167dfeb6786d911b6bdb34f4dd91ef8a4
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_cube_43dof.xml
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof.xml
new file mode 100644
index 0000000000000000000000000000000000000000..0b60f2f83228277ea83ebea17a0ede1eb7a5383b
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof.xml
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof_activated3dex.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof_activated3dex.xml
new file mode 100644
index 0000000000000000000000000000000000000000..2916dfb9ecf0566ebd2def70c03155be1ce91edb
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof_activated3dex.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_43dof.xml
new file mode 100644
index 0000000000000000000000000000000000000000..d66b23dce5da38aa29ff78d153ac86bf406740e5
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_43dof.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/robot_model.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/robot_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..27a1ed5c66b73cddeb6f3f7dce5a3276e83871fc
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/robot_model.py
@@ -0,0 +1,772 @@
+from typing import List, Optional, Set, Union
+
+import numpy as np
+import pinocchio as pin
+
+from decoupled_wbc.control.robot_model.supplemental_info import RobotSupplementalInfo
+
+
+class RobotModel:
+ def __init__(
+ self,
+ urdf_path,
+ asset_path,
+ set_floating_base=False,
+ supplemental_info: Optional[RobotSupplementalInfo] = None,
+ ):
+ self.pinocchio_wrapper = pin.RobotWrapper.BuildFromURDF(
+ filename=urdf_path,
+ package_dirs=[asset_path],
+ root_joint=pin.JointModelFreeFlyer() if set_floating_base else None,
+ )
+ self.is_floating_base_model = set_floating_base
+
+ self.joint_to_dof_index = {}
+ # Assume we only have single-dof joints
+ # First two names correspond to universe and floating base joints
+ names = (
+ self.pinocchio_wrapper.model.names[2:]
+ if set_floating_base
+ else self.pinocchio_wrapper.model.names[1:]
+ )
+ for name in names:
+ j_id = self.pinocchio_wrapper.model.getJointId(name)
+ jmodel = self.pinocchio_wrapper.model.joints[j_id]
+ self.joint_to_dof_index[name] = jmodel.idx_q
+
+ # Store joint limits only for actual joints (excluding floating base)
+ # if set floating base is true and the robot can move in the world
+ # then we don't want to impose joint limits for the 7 dofs corresponding
+ # to the floating base dofs.
+ root_nq = 7 if set_floating_base else 0
+ self.upper_joint_limits = self.pinocchio_wrapper.model.upperPositionLimit[root_nq:].copy()
+ self.lower_joint_limits = self.pinocchio_wrapper.model.lowerPositionLimit[root_nq:].copy()
+
+ # Set up supplemental info if provided
+ self.supplemental_info = supplemental_info
+ if self.supplemental_info is not None:
+ # Cache indices for body and hand actuated joints separately
+ self._body_actuated_joint_indices = [
+ self.dof_index(name) for name in self.supplemental_info.body_actuated_joints
+ ]
+ self._left_hand_actuated_joint_indices = [
+ self.dof_index(name) for name in self.supplemental_info.left_hand_actuated_joints
+ ]
+ self._right_hand_actuated_joint_indices = [
+ self.dof_index(name) for name in self.supplemental_info.right_hand_actuated_joints
+ ]
+ self._hand_actuated_joint_indices = (
+ self._left_hand_actuated_joint_indices + self._right_hand_actuated_joint_indices
+ )
+
+ # Cache indices for joint groups, handling nested groups
+ self._joint_group_indices = {}
+ for group_name, group_info in self.supplemental_info.joint_groups.items():
+ indices = []
+ # Add indices for direct joints
+ indices.extend([self.dof_index(name) for name in group_info["joints"]])
+ # Add indices from subgroups
+ for subgroup_name in group_info["groups"]:
+ indices.extend(self.get_joint_group_indices(subgroup_name))
+ self._joint_group_indices[group_name] = sorted(set(indices))
+
+ # Update joint limits from supplemental info if available
+ if (
+ hasattr(self.supplemental_info, "joint_limits")
+ and self.supplemental_info.joint_limits
+ ):
+ for joint_name, limits in self.supplemental_info.joint_limits.items():
+ if joint_name in self.joint_to_dof_index:
+ idx = self.joint_to_dof_index[joint_name] - root_nq
+ self.lower_joint_limits[idx] = limits[0]
+ self.upper_joint_limits[idx] = limits[1]
+
+ # Initialize default body pose
+ self.default_body_pose = self.q_zero.copy()
+
+ # Update with supplemental info if available
+ if self.supplemental_info is not None:
+ default_joint_q = self.supplemental_info.default_joint_q
+ for joint, joint_values in default_joint_q.items():
+ # Get the joint name mapping for this type
+ joint_mapping = self.supplemental_info.joint_name_mapping[joint]
+
+ # Handle both single joint names and left/right mappings
+ if isinstance(joint_mapping, str):
+ # Single joint (e.g., waist joints)
+ if joint_mapping in self.joint_to_dof_index:
+ joint_idx = self.dof_index(joint_mapping)
+ self.default_body_pose[joint_idx] = (
+ joint_values # joint_values is the value for single joints
+ )
+ else:
+ # Left/right mapping (e.g., arm joints)
+ for side, value in joint_values.items():
+ if side in joint_mapping and joint_mapping[side] in self.joint_to_dof_index:
+ joint_idx = self.dof_index(joint_mapping[side])
+ self.default_body_pose[joint_idx] = value
+
+ # Initialize initial body pose
+ self.initial_body_pose = self.default_body_pose.copy()
+
+ @property
+ def num_dofs(self) -> int:
+ """Get the number of degrees of freedom of the robot (floating base pose + joints)."""
+ return self.pinocchio_wrapper.model.nq
+
+ @property
+ def q_zero(self) -> np.ndarray:
+ """Get the zero pose of the robot."""
+ return self.pinocchio_wrapper.q0
+
+ @property
+ def joint_names(self) -> List[str]:
+ """Get the names of the joints of the robot."""
+ return list(self.joint_to_dof_index.keys())
+
+ @property
+ def num_joints(self) -> int:
+ """Get the number of joints of the robot."""
+ return len(self.joint_to_dof_index)
+
+ def dof_index(self, joint_name: str) -> int:
+ """
+ Get the index in the degrees of freedom vector corresponding
+ to the single-DoF joint with name `joint_name`.
+ """
+ if joint_name not in self.joint_to_dof_index:
+ raise ValueError(
+ f"Unknown joint name: '{joint_name}'. "
+ f"Available joints: {list(self.joint_to_dof_index.keys())}"
+ )
+ return self.joint_to_dof_index[joint_name]
+
+ def get_body_actuated_joint_indices(self) -> List[int]:
+ """
+ Get the indices of body actuated joints in the full configuration.
+ Ordering is that of the actuated joints as defined in the supplemental info.
+ Requires supplemental_info to be provided.
+ """
+ if self.supplemental_info is None:
+ raise ValueError("supplemental_info must be provided to use this method")
+ return self._body_actuated_joint_indices
+
+ def get_hand_actuated_joint_indices(self, side: str = "both") -> List[int]:
+ """
+ Get the indices of hand actuated joints in the full configuration.
+ Ordering is that of the actuated joints as defined in the supplemental info.
+ Requires supplemental_info to be provided.
+
+ Args:
+ side: String specifying which hand to get indices for ('left', 'right', or 'both')
+ """
+ if self.supplemental_info is None:
+ raise ValueError("supplemental_info must be provided to use this method")
+
+ if side.lower() == "both":
+ return self._hand_actuated_joint_indices
+ elif side.lower() == "left":
+ return self._left_hand_actuated_joint_indices
+ elif side.lower() == "right":
+ return self._right_hand_actuated_joint_indices
+ else:
+ raise ValueError("side must be 'left', 'right', or 'both'")
+
+ def get_joint_group_indices(self, group_names: Union[str, Set[str]]) -> List[int]:
+ """
+ Get the indices of joints in one or more groups in the full configuration.
+ Requires supplemental_info to be provided.
+ The returned indices are sorted in ascending order, so that the joint ordering
+ of the full model is preserved.
+
+ Args:
+ group_names: Either a single group name (str) or a set of group names (Set[str])
+
+ Returns:
+ List of joint indices in sorted order with no duplicates
+ """
+ if self.supplemental_info is None:
+ raise ValueError("supplemental_info must be provided to use this method")
+
+ # Convert single string to set for uniform handling
+ if isinstance(group_names, str):
+ group_names = {group_names}
+
+ # Collect indices from all groups
+ all_indices = set()
+ for group_name in group_names:
+ if group_name not in self._joint_group_indices:
+ raise ValueError(f"Unknown joint group: {group_name}")
+ all_indices.update(self._joint_group_indices[group_name])
+
+ return sorted(all_indices)
+
+ def cache_forward_kinematics(self, q: np.ndarray, auto_clip=True) -> None:
+ """
+ Perform forward kinematics to update the pose of every joint and frame
+ in the Pinocchio data structures for the given configuration `q`.
+
+ :param q: A numpy array of shape (num_dofs,) representing the robot configuration.
+ """
+ if q.shape[0] != self.num_dofs:
+ raise ValueError(f"Expected q of length {self.num_dofs}, got {q.shape[0]} instead.")
+
+ # Apply auto-clip if enabled
+ if auto_clip:
+ q = self.clip_configuration(q)
+
+ pin.framesForwardKinematics(self.pinocchio_wrapper.model, self.pinocchio_wrapper.data, q)
+
+ def compute_gravity_compensation_torques(
+ self, q: np.ndarray, joint_groups: Union[str, List[str], Set[str]] = None, auto_clip=True
+ ) -> np.ndarray:
+ """
+ Compute gravity compensation torques for specified joint groups using pinocchio.
+
+ :param q: Robot configuration (joint positions)
+ :param joint_groups: Joint groups to compensate (e.g., "arms", ["left_arm", "waist"],
+ {"left_arm", "waist"}). If None, compensates all joints
+ :param auto_clip: Whether to automatically clip joint values to limits
+ :return: Array of gravity compensation torques for all DOFs (zero for non-compensated joints)
+ """
+ if q.shape[0] != self.num_dofs:
+ raise ValueError(f"Expected q of length {self.num_dofs}, got {q.shape[0]} instead.")
+
+ # Apply auto-clip if enabled
+ if auto_clip:
+ q = self.clip_configuration(q)
+
+ try:
+ # Cache forward kinematics for the current configuration
+ self.cache_forward_kinematics(q, auto_clip=False) # Already clipped if needed
+
+ # Compute gravity vector using RNEA with zero velocity and acceleration
+ v = np.zeros(self.num_dofs)
+ a = np.zeros(self.num_dofs)
+
+ gravity_torques_full = pin.rnea(
+ self.pinocchio_wrapper.model, self.pinocchio_wrapper.data, q, v, a
+ )
+
+ # If no joint groups specified, return full gravity torques
+ if joint_groups is None:
+ return gravity_torques_full
+
+ # Convert list to set for get_joint_group_indices compatibility
+ if isinstance(joint_groups, list):
+ joint_groups = set(joint_groups)
+
+ # Get joint indices for specified groups - get_joint_group_indices handles str and Set[str]
+ try:
+ compensated_joint_indices = self.get_joint_group_indices(joint_groups)
+ except ValueError as e:
+ raise ValueError(f"Error resolving joint groups {joint_groups}: {e}")
+
+ # Create mask for joints that should receive gravity compensation
+ compensation_mask = np.zeros(self.num_dofs, dtype=bool)
+ for joint_idx in compensated_joint_indices:
+ if 0 <= joint_idx < len(compensation_mask):
+ compensation_mask[joint_idx] = True
+
+ # Apply mask to only compensate specified joints
+ compensated_torques = np.zeros_like(gravity_torques_full)
+ compensated_torques[compensation_mask] = gravity_torques_full[compensation_mask]
+
+ return compensated_torques
+
+ except Exception as e:
+ raise RuntimeError(f"Error computing gravity compensation: {e}")
+
+ def clip_configuration(self, q: np.ndarray, margin: float = 1e-6) -> np.ndarray:
+ """
+ Clip the configuration to stay within joint limits with a small tolerance.
+
+ :param q: Configuration to clip
+ :param margin: Tolerance to keep away from joint limits
+ :return: Clipped configuration
+ """
+ q_clipped = q.copy()
+
+ # Only clip joint positions, not floating base
+ root_nq = 7 if self.is_floating_base_model else 0
+ q_clipped[root_nq:] = np.clip(
+ q[root_nq:], self.lower_joint_limits + margin, self.upper_joint_limits - margin
+ )
+
+ return q_clipped
+
+ def frame_placement(self, frame_name: str) -> pin.SE3:
+ """
+ Returns the SE3 transform of the specified frame in the world coordinate system.
+ Note: make sure cache_forward_kinematics() has been previously called.
+
+ :param frame_name: Name of the frame, e.g. "link_elbow_frame", "hand_imu_frame", etc.
+ :return: A pin.SE3 object representing the pose of the frame.
+ """
+ model = self.pinocchio_wrapper.model
+ data = self.pinocchio_wrapper.data
+
+ frame_id = model.getFrameId(frame_name)
+ if frame_id < 0 or frame_id >= len(model.frames):
+ valid_frames = [f.name for f in model.frames]
+ raise ValueError(f"Unknown frame '{frame_name}'. Valid frames: {valid_frames}")
+
+ # Pinocchio's data.oMf[frame_id] is a pin.SE3.
+ return data.oMf[frame_id].copy()
+
+ def get_body_actuated_joints(self, q: np.ndarray) -> np.ndarray:
+ """
+ Get the configuration of body actuated joints from a full configuration.
+
+ :param q: Configuration in full space
+ :return: Configuration of body actuated joints
+ """
+ indices = self.get_body_actuated_joint_indices()
+
+ return q[indices]
+
+ def get_hand_actuated_joints(self, q: np.ndarray, side: str = "both") -> np.ndarray:
+ """
+ Get the configuration of hand actuated joints from a full configuration.
+
+ Args:
+ q: Configuration in full space
+ side: String specifying which hand to get joints for ('left', 'right', or 'both')
+ """
+ indices = self.get_hand_actuated_joint_indices(side)
+ return q[indices]
+
+ def get_configuration_from_actuated_joints(
+ self,
+ body_actuated_joint_values: np.ndarray,
+ hand_actuated_joint_values: Optional[np.ndarray] = None,
+ left_hand_actuated_joint_values: Optional[np.ndarray] = None,
+ right_hand_actuated_joint_values: Optional[np.ndarray] = None,
+ ) -> np.ndarray:
+ """
+ Get the full configuration from the body and hand actuated joint configurations.
+ Can specify either both hands together or left and right hands separately.
+
+ Args:
+ body_actuated_joint_values: Configuration of body actuated joints
+ hand_actuated_joint_values: Configuration of both hands' actuated joints (optional)
+ left_hand_actuated_joint_values: Configuration of left hand actuated joints (optional)
+ right_hand_actuated_joint_values: Configuration of right hand actuated joints (optional)
+
+ Returns:
+ Full configuration including body and hand joints
+ """
+ q = self.pinocchio_wrapper.q0.copy()
+ q[self.get_body_actuated_joint_indices()] = body_actuated_joint_values
+
+ # Handle hand configurations
+ if hand_actuated_joint_values is not None:
+ # Use combined hand configuration
+ q[self.get_hand_actuated_joint_indices("both")] = hand_actuated_joint_values
+ else:
+ # Use separate hand configurations
+ if left_hand_actuated_joint_values is not None:
+ q[self.get_hand_actuated_joint_indices("left")] = left_hand_actuated_joint_values
+ if right_hand_actuated_joint_values is not None:
+ q[self.get_hand_actuated_joint_indices("right")] = right_hand_actuated_joint_values
+
+ return q
+
+ def reset_forward_kinematics(self) -> None:
+ """
+ Reset the forward kinematics to the initial configuration.
+ """
+ self.cache_forward_kinematics(self.q_zero)
+
+ def get_initial_upper_body_pose(self) -> np.ndarray:
+ """
+ Get the initial upper body pose of the robot.
+ """
+ return self.initial_body_pose[self.get_joint_group_indices("upper_body")]
+
+ def get_default_body_pose(self) -> np.ndarray:
+ """
+ Get the default body pose of the robot.
+ """
+ return self.default_body_pose
+
+ def set_initial_body_pose(self, q: np.ndarray, q_idx=None) -> None:
+ """
+ Set the initial body pose of the robot.
+ """
+ if q_idx is None:
+ self.initial_body_pose = q
+ else:
+ self.initial_body_pose[q_idx] = q
+
+
+class ReducedRobotModel(RobotModel):
+ """
+ A class that creates a reduced order robot model by fixing certain joints.
+ This class maintains a mapping between the reduced state space and the full state space.
+ """
+
+ def __init__(
+ self,
+ full_robot_model: RobotModel,
+ fixed_joints: List[str],
+ fixed_values: Optional[List[float]] = None,
+ ):
+ """
+ Create a reduced order robot model by fixing specified joints.
+
+ :param full_robot_model: The original robot model
+ :param fixed_joints: List of joint names to fix
+ :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial
+ joint positions (q0) from the full robot model.
+ """
+ self.full_robot = full_robot_model
+ self.supplemental_info = full_robot_model.supplemental_info
+
+ # If fixed_values is None, use q0 from the full robot model
+ if fixed_values is None:
+ fixed_values = []
+ for joint_name in fixed_joints:
+ full_idx = full_robot_model.dof_index(joint_name)
+ fixed_values.append(full_robot_model.pinocchio_wrapper.q0[full_idx])
+ elif len(fixed_joints) != len(fixed_values):
+ raise ValueError("fixed_joints and fixed_values must have the same length")
+
+ # Store fixed joints and their values
+ self.fixed_joints = fixed_joints
+ self.fixed_values = fixed_values
+
+ # Create mapping between reduced and full state spaces
+ self.reduced_to_full = []
+ self.full_to_reduced = {}
+
+ # Initialize with floating base indices if present
+ if full_robot_model.is_floating_base_model:
+ self.reduced_to_full.extend(range(7)) # Floating base indices
+ for i in range(7):
+ self.full_to_reduced[i] = i
+
+ # Add active joint indices
+ for joint_name in full_robot_model.joint_names:
+ if joint_name not in fixed_joints:
+ full_idx = full_robot_model.dof_index(joint_name)
+ reduced_idx = len(self.reduced_to_full)
+ self.reduced_to_full.append(full_idx)
+ self.full_to_reduced[full_idx] = reduced_idx
+
+ # Create a reduced Pinocchio model using buildReducedModel
+ # First, get the list of joint IDs to lock
+ locked_joint_ids = []
+ for joint_name in fixed_joints:
+ joint_id = full_robot_model.pinocchio_wrapper.model.getJointId(joint_name)
+ if (full_robot_model.is_floating_base_model and joint_id > 1) or (
+ not full_robot_model.is_floating_base_model and joint_id > 0
+ ):
+ locked_joint_ids.append(joint_id)
+
+ # First build the reduced kinematic model
+ reduced_model = pin.buildReducedModel(
+ full_robot_model.pinocchio_wrapper.model,
+ locked_joint_ids,
+ full_robot_model.pinocchio_wrapper.q0,
+ )
+
+ # Then build the reduced geometry models using the reduced kinematic model
+ self.pinocchio_wrapper = pin.RobotWrapper(
+ model=reduced_model,
+ )
+
+ # Create joint to dof index mapping
+ self.joint_to_dof_index = {}
+ # Assume we only have single-dof joints
+ # First two names correspond to universe and floating base joints
+ names = (
+ self.pinocchio_wrapper.model.names[2:]
+ if self.full_robot.is_floating_base_model
+ else self.pinocchio_wrapper.model.names[1:]
+ )
+ for name in names:
+ j_id = self.pinocchio_wrapper.model.getJointId(name)
+ jmodel = self.pinocchio_wrapper.model.joints[j_id]
+ self.joint_to_dof_index[name] = jmodel.idx_q
+
+ # Initialize joint limits
+ root_nq = 7 if self.full_robot.is_floating_base_model else 0
+ self.lower_joint_limits = self.pinocchio_wrapper.model.lowerPositionLimit[root_nq:].copy()
+ self.upper_joint_limits = self.pinocchio_wrapper.model.upperPositionLimit[root_nq:].copy()
+
+ # Update joint limits from supplemental info if available
+ if self.supplemental_info is not None:
+ if (
+ hasattr(self.supplemental_info, "joint_limits")
+ and self.supplemental_info.joint_limits
+ ):
+ for joint_name, limits in self.supplemental_info.joint_limits.items():
+ if joint_name in self.joint_to_dof_index:
+ idx = self.joint_to_dof_index[joint_name] - root_nq
+ self.lower_joint_limits[idx] = limits[0]
+ self.upper_joint_limits[idx] = limits[1]
+
+ # Get full indices for body and hand actuated joints
+ full_body_indices = full_robot_model.get_body_actuated_joint_indices()
+ full_hand_indices = full_robot_model.get_hand_actuated_joint_indices("both")
+ full_left_hand_indices = full_robot_model.get_hand_actuated_joint_indices("left")
+ full_right_hand_indices = full_robot_model.get_hand_actuated_joint_indices("right")
+
+ # Map to reduced indices
+ self._body_actuated_joint_indices = []
+ for idx in full_body_indices:
+ if idx in self.full_to_reduced:
+ self._body_actuated_joint_indices.append(self.full_to_reduced[idx])
+
+ self._hand_actuated_joint_indices = []
+ for idx in full_hand_indices:
+ if idx in self.full_to_reduced:
+ self._hand_actuated_joint_indices.append(self.full_to_reduced[idx])
+
+ self._left_hand_actuated_joint_indices = []
+ for idx in full_left_hand_indices:
+ if idx in self.full_to_reduced:
+ self._left_hand_actuated_joint_indices.append(self.full_to_reduced[idx])
+
+ self._right_hand_actuated_joint_indices = []
+ for idx in full_right_hand_indices:
+ if idx in self.full_to_reduced:
+ self._right_hand_actuated_joint_indices.append(self.full_to_reduced[idx])
+
+ # Cache indices for joint groups in reduced space
+ self._joint_group_indices = {}
+ for group_name in self.supplemental_info.joint_groups:
+ full_indices = full_robot_model.get_joint_group_indices(group_name)
+ reduced_indices = []
+ for idx in full_indices:
+ if idx in self.full_to_reduced:
+ reduced_indices.append(self.full_to_reduced[idx])
+ self._joint_group_indices[group_name] = sorted(set(reduced_indices))
+
+ # Initialize default body pose in reduced space
+ self.default_body_pose = self.full_to_reduced_configuration(
+ full_robot_model.default_body_pose
+ )
+
+ # Initialize initial body pose in reduced space
+ self.initial_body_pose = self.full_to_reduced_configuration(
+ full_robot_model.initial_body_pose
+ )
+
+ @property
+ def num_joints(self) -> int:
+ """Get the number of active joints in the reduced model."""
+ return len(self.joint_names)
+
+ @property
+ def joint_names(self) -> List[str]:
+ """Get the names of the active joints in the reduced model."""
+ return [name for name in self.full_robot.joint_names if name not in self.fixed_joints]
+
+ @classmethod
+ def from_fixed_groups(
+ cls,
+ full_robot_model: RobotModel,
+ fixed_group_names: List[str],
+ fixed_values: Optional[List[float]] = None,
+ ) -> "ReducedRobotModel":
+ """
+ Create a reduced order robot model by fixing all joints in specified groups.
+
+ :param full_robot_model: The original robot model
+ :param fixed_group_names: List of joint group names to fix
+ :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial
+ joint positions (q0) from the full robot model.
+ :return: A ReducedRobotModel instance
+ """
+ if full_robot_model.supplemental_info is None:
+ raise ValueError("supplemental_info must be provided to use this method")
+
+ # Get all joints in the groups, including those from subgroups
+ fixed_joints = set() # Use a set to avoid duplicates
+
+ for group_name in fixed_group_names:
+ if group_name not in full_robot_model.supplemental_info.joint_groups:
+ raise ValueError(f"Unknown joint group: {group_name}")
+
+ group_info = full_robot_model.supplemental_info.joint_groups[group_name]
+
+ # Add direct joints
+ fixed_joints.update(group_info["joints"])
+
+ # Add joints from subgroups
+ for subgroup_name in group_info["groups"]:
+ subgroup_joints = full_robot_model.get_joint_group_indices(subgroup_name)
+ fixed_joints.update([full_robot_model.joint_names[idx] for idx in subgroup_joints])
+
+ # Convert set back to list for compatibility with the original constructor
+ return cls(full_robot_model, list(fixed_joints), fixed_values)
+
+ @classmethod
+ def from_fixed_group(
+ cls,
+ full_robot_model: RobotModel,
+ fixed_group_name: str,
+ fixed_values: Optional[List[float]] = None,
+ ) -> "ReducedRobotModel":
+ """
+ Create a reduced order robot model by fixing all joints in a specified group.
+ This is a convenience method that calls from_fixed_groups with a single group.
+
+ :param full_robot_model: The original robot model
+ :param fixed_group_name: Name of the joint group to fix
+ :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial
+ joint positions (q0) from the full robot model.
+ :return: A ReducedRobotModel instance
+ """
+ return cls.from_fixed_groups(full_robot_model, [fixed_group_name], fixed_values)
+
+ @classmethod
+ def from_active_group(
+ cls,
+ full_robot_model: RobotModel,
+ active_group_name: str,
+ fixed_values: Optional[List[float]] = None,
+ ) -> "ReducedRobotModel":
+ """
+ Create a reduced order robot model by fixing all joints EXCEPT those in the specified group.
+ This is a convenience method that calls from_active_groups with a single group.
+
+ :param full_robot_model: The original robot model
+ :param active_group_name: Name of the joint group to keep active (all other joints will be fixed)
+ :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial
+ joint positions (q0) from the full robot model.
+ :return: A ReducedRobotModel instance
+ """
+ return cls.from_active_groups(full_robot_model, [active_group_name], fixed_values)
+
+ @classmethod
+ def from_active_groups(
+ cls,
+ full_robot_model: RobotModel,
+ active_group_names: List[str],
+ fixed_values: Optional[List[float]] = None,
+ ) -> "ReducedRobotModel":
+ """
+ Create a reduced order robot model by fixing all joints EXCEPT those in the specified groups.
+ This is useful when you want to keep multiple groups active and fix everything else.
+
+ :param full_robot_model: The original robot model
+ :param active_group_names: List of joint group names to keep active (all other joints will be fixed)
+ :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial
+ joint positions (q0) from the full robot model.
+ :return: A ReducedRobotModel instance
+ """
+ if full_robot_model.supplemental_info is None:
+ raise ValueError("supplemental_info must be provided to use this method")
+
+ # Get all joints in the active groups, including those from subgroups
+ active_joints = set()
+
+ def add_group_joints(group_name: str):
+ if group_name not in full_robot_model.supplemental_info.joint_groups:
+ raise ValueError(f"Unknown joint group: {group_name}")
+
+ group_info = full_robot_model.supplemental_info.joint_groups[group_name]
+
+ # Add direct joints
+ if "joints" in group_info:
+ active_joints.update(group_info["joints"])
+
+ # Add joints from subgroups
+ if "groups" in group_info:
+ for subgroup_name in group_info["groups"]:
+ add_group_joints(subgroup_name)
+
+ for group_name in active_group_names:
+ add_group_joints(group_name)
+
+ # Get all joints from the model
+ all_joints = set(full_robot_model.joint_names)
+
+ # The fixed joints are all joints minus the active joints
+ fixed_joints = list(all_joints - active_joints)
+
+ return cls(full_robot_model, fixed_joints, fixed_values)
+
+ def reduced_to_full_configuration(self, q_reduced: np.ndarray) -> np.ndarray:
+ """
+ Convert a reduced configuration to the full configuration space.
+
+ :param q_reduced: Configuration in reduced space
+ :return: Configuration in full space with fixed joints set to their fixed values
+ """
+ if q_reduced.shape[0] != self.num_dofs:
+ raise ValueError(
+ f"Expected q_reduced of length {self.num_dofs}, got {q_reduced.shape[0]} instead"
+ )
+
+ q_full = np.zeros(self.full_robot.num_dofs)
+
+ # Set active joints
+ for reduced_idx, full_idx in enumerate(self.reduced_to_full):
+ q_full[full_idx] = q_reduced[reduced_idx]
+
+ # Set fixed joints
+ for joint_name, value in zip(self.fixed_joints, self.fixed_values):
+ full_idx = self.full_robot.dof_index(joint_name)
+ q_full[full_idx] = value
+
+ return q_full
+
+ def full_to_reduced_configuration(self, q_full: np.ndarray) -> np.ndarray:
+ """
+ Convert a full configuration to the reduced configuration space.
+
+ :param q_full: Configuration in full space
+ :return: Configuration in reduced space
+ """
+ if q_full.shape[0] != self.full_robot.num_dofs:
+ raise ValueError(
+ f"Expected q_full of length {self.full_robot.num_dofs}, got {q_full.shape[0]} instead"
+ )
+
+ q_reduced = np.zeros(self.num_dofs)
+
+ # Copy active joints
+ for reduced_idx, full_idx in enumerate(self.reduced_to_full):
+ q_reduced[reduced_idx] = q_full[full_idx]
+
+ return q_reduced
+
+ def cache_forward_kinematics(self, q_reduced: np.ndarray, auto_clip=True) -> None:
+ """
+ Perform forward kinematics using the reduced configuration.
+
+ :param q_reduced: Configuration in reduced space
+ """
+ # First update the full robot's forward kinematics
+ q_full = self.reduced_to_full_configuration(q_reduced)
+ self.full_robot.cache_forward_kinematics(q_full, auto_clip)
+
+ # Then update the reduced model's forward kinematics
+ pin.framesForwardKinematics(
+ self.pinocchio_wrapper.model, self.pinocchio_wrapper.data, q_reduced
+ )
+
+ def clip_configuration(self, q_reduced: np.ndarray, margin: float = 1e-6) -> np.ndarray:
+ """
+ Clip the reduced configuration to stay within joint limits with a small tolerance.
+
+ :param q_reduced: Configuration to clip
+ :param margin: Tolerance to keep away from joint limits
+ :return: Clipped configuration
+ """
+ q_full = self.reduced_to_full_configuration(q_reduced)
+ q_full_clipped = self.full_robot.clip_configuration(q_full, margin)
+ return self.full_to_reduced_configuration(q_full_clipped)
+
+ def reset_forward_kinematics(self):
+ """
+ Reset the forward kinematics to the initial configuration.
+ """
+ # Reset full robot's forward kinematics
+ self.full_robot.reset_forward_kinematics()
+ # Reset reduced model's forward kinematics
+ self.cache_forward_kinematics(self.q_zero)
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d2e1e650777c31d84ac48f823e9a1b864a65132
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/__init__.py
@@ -0,0 +1,5 @@
+from decoupled_wbc.control.robot_model.supplemental_info.robot_supplemental_info import (
+ RobotSupplementalInfo,
+)
+
+__all__ = ["RobotSupplementalInfo"]
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/g1_supplemental_info.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/g1_supplemental_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..da7dc659fa4a531f57a897df23ea886d6e8934df
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/g1_supplemental_info.py
@@ -0,0 +1,330 @@
+from dataclasses import dataclass
+from enum import Enum
+
+import numpy as np
+
+from decoupled_wbc.control.robot_model.supplemental_info.robot_supplemental_info import (
+ RobotSupplementalInfo,
+)
+
+
+class WaistLocation(Enum):
+ """Enum for waist location configuration."""
+
+ LOWER_BODY = "lower_body"
+ UPPER_BODY = "upper_body"
+ LOWER_AND_UPPER_BODY = "lower_and_upper_body"
+
+
+class ElbowPose(Enum):
+ """Enum for elbow pose configuration."""
+
+ LOW = "low"
+ HIGH = "high"
+
+
+@dataclass
+class G1SupplementalInfo(RobotSupplementalInfo):
+ """
+ Supplemental information for the G1 robot.
+
+ Args:
+ waist_location: Where to place waist joints in the joint groups
+ elbow_pose: Which elbow pose configuration to use for default joint positions
+ """
+
+ def __init__(
+ self,
+ waist_location: WaistLocation = WaistLocation.LOWER_BODY,
+ elbow_pose: ElbowPose = ElbowPose.LOW,
+ ):
+ name = "G1_G1ThreeFinger"
+
+ # Define all actuated joints
+ body_actuated_joints = [
+ # Left leg
+ "left_hip_pitch_joint",
+ "left_hip_roll_joint",
+ "left_hip_yaw_joint",
+ "left_knee_joint",
+ "left_ankle_pitch_joint",
+ "left_ankle_roll_joint",
+ # Right leg
+ "right_hip_pitch_joint",
+ "right_hip_roll_joint",
+ "right_hip_yaw_joint",
+ "right_knee_joint",
+ "right_ankle_pitch_joint",
+ "right_ankle_roll_joint",
+ # Waist
+ "waist_yaw_joint",
+ "waist_roll_joint",
+ "waist_pitch_joint",
+ # Left arm
+ "left_shoulder_pitch_joint",
+ "left_shoulder_roll_joint",
+ "left_shoulder_yaw_joint",
+ "left_elbow_joint",
+ "left_wrist_roll_joint",
+ "left_wrist_pitch_joint",
+ "left_wrist_yaw_joint",
+ # Right arm
+ "right_shoulder_pitch_joint",
+ "right_shoulder_roll_joint",
+ "right_shoulder_yaw_joint",
+ "right_elbow_joint",
+ "right_wrist_roll_joint",
+ "right_wrist_pitch_joint",
+ "right_wrist_yaw_joint",
+ ]
+
+ left_hand_actuated_joints = [
+ # Left hand
+ "left_hand_thumb_0_joint",
+ "left_hand_thumb_1_joint",
+ "left_hand_thumb_2_joint",
+ "left_hand_index_0_joint",
+ "left_hand_index_1_joint",
+ "left_hand_middle_0_joint",
+ "left_hand_middle_1_joint",
+ ]
+
+ right_hand_actuated_joints = [
+ # Right hand
+ "right_hand_thumb_0_joint",
+ "right_hand_thumb_1_joint",
+ "right_hand_thumb_2_joint",
+ "right_hand_index_0_joint",
+ "right_hand_index_1_joint",
+ "right_hand_middle_0_joint",
+ "right_hand_middle_1_joint",
+ ]
+
+ # Define joint limits from URDF
+ joint_limits = {
+ # Left leg
+ "left_hip_pitch_joint": [-2.5307, 2.8798],
+ "left_hip_roll_joint": [-0.5236, 2.9671],
+ "left_hip_yaw_joint": [-2.7576, 2.7576],
+ "left_knee_joint": [-0.087267, 2.8798],
+ "left_ankle_pitch_joint": [-0.87267, 0.5236],
+ "left_ankle_roll_joint": [-0.2618, 0.2618],
+ # Right leg
+ "right_hip_pitch_joint": [-2.5307, 2.8798],
+ "right_hip_roll_joint": [-2.9671, 0.5236],
+ "right_hip_yaw_joint": [-2.7576, 2.7576],
+ "right_knee_joint": [-0.087267, 2.8798],
+ "right_ankle_pitch_joint": [-0.87267, 0.5236],
+ "right_ankle_roll_joint": [-0.2618, 0.2618],
+ # Waist
+ "waist_yaw_joint": [-2.618, 2.618],
+ "waist_roll_joint": [-0.52, 0.52],
+ "waist_pitch_joint": [-0.52, 0.52],
+ # Left arm
+ "left_shoulder_pitch_joint": [-3.0892, 2.6704],
+ "left_shoulder_roll_joint": [0.19, 2.2515],
+ "left_shoulder_yaw_joint": [-2.618, 2.618],
+ "left_elbow_joint": [-1.0472, 2.0944],
+ "left_wrist_roll_joint": [-1.972222054, 1.972222054],
+ "left_wrist_pitch_joint": [-1.614429558, 1.614429558],
+ "left_wrist_yaw_joint": [-1.614429558, 1.614429558],
+ # Right arm
+ "right_shoulder_pitch_joint": [-3.0892, 2.6704],
+ "right_shoulder_roll_joint": [-2.2515, -0.19],
+ "right_shoulder_yaw_joint": [-2.618, 2.618],
+ "right_elbow_joint": [-1.0472, 2.0944],
+ "right_wrist_roll_joint": [-1.972222054, 1.972222054],
+ "right_wrist_pitch_joint": [-1.614429558, 1.614429558],
+ "right_wrist_yaw_joint": [-1.614429558, 1.614429558],
+ # Left hand
+ "left_hand_thumb_0_joint": [-1.04719755, 1.04719755],
+ "left_hand_thumb_1_joint": [-0.72431163, 1.04719755],
+ "left_hand_thumb_2_joint": [0, 1.74532925],
+ "left_hand_index_0_joint": [-1.57079632, 0],
+ "left_hand_index_1_joint": [-1.74532925, 0],
+ "left_hand_middle_0_joint": [-1.57079632, 0],
+ "left_hand_middle_1_joint": [-1.74532925, 0],
+ # Right hand
+ "right_hand_thumb_0_joint": [-1.04719755, 1.04719755],
+ "right_hand_thumb_1_joint": [-0.72431163, 1.04719755],
+ "right_hand_thumb_2_joint": [0, 1.74532925],
+ "right_hand_index_0_joint": [-1.57079632, 0],
+ "right_hand_index_1_joint": [-1.74532925, 0],
+ "right_hand_middle_0_joint": [-1.57079632, 0],
+ "right_hand_middle_1_joint": [-1.74532925, 0],
+ }
+
+ # Define joint groups
+ joint_groups = {
+ # Body groups
+ "waist": {
+ "joints": ["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"],
+ "groups": [],
+ },
+ # Leg groups
+ "left_leg": {
+ "joints": [
+ "left_hip_pitch_joint",
+ "left_hip_roll_joint",
+ "left_hip_yaw_joint",
+ "left_knee_joint",
+ "left_ankle_pitch_joint",
+ "left_ankle_roll_joint",
+ ],
+ "groups": [],
+ },
+ "right_leg": {
+ "joints": [
+ "right_hip_pitch_joint",
+ "right_hip_roll_joint",
+ "right_hip_yaw_joint",
+ "right_knee_joint",
+ "right_ankle_pitch_joint",
+ "right_ankle_roll_joint",
+ ],
+ "groups": [],
+ },
+ "legs": {"joints": [], "groups": ["left_leg", "right_leg"]},
+ # Arm groups
+ "left_arm": {
+ "joints": [
+ "left_shoulder_pitch_joint",
+ "left_shoulder_roll_joint",
+ "left_shoulder_yaw_joint",
+ "left_elbow_joint",
+ "left_wrist_roll_joint",
+ "left_wrist_pitch_joint",
+ "left_wrist_yaw_joint",
+ ],
+ "groups": [],
+ },
+ "right_arm": {
+ "joints": [
+ "right_shoulder_pitch_joint",
+ "right_shoulder_roll_joint",
+ "right_shoulder_yaw_joint",
+ "right_elbow_joint",
+ "right_wrist_roll_joint",
+ "right_wrist_pitch_joint",
+ "right_wrist_yaw_joint",
+ ],
+ "groups": [],
+ },
+ "arms": {"joints": [], "groups": ["left_arm", "right_arm"]},
+ # Hand groups
+ "left_hand": {
+ "joints": [
+ "left_hand_index_0_joint",
+ "left_hand_index_1_joint",
+ "left_hand_middle_0_joint",
+ "left_hand_middle_1_joint",
+ "left_hand_thumb_0_joint",
+ "left_hand_thumb_1_joint",
+ "left_hand_thumb_2_joint",
+ ],
+ "groups": [],
+ },
+ "right_hand": {
+ "joints": [
+ "right_hand_index_0_joint",
+ "right_hand_index_1_joint",
+ "right_hand_middle_0_joint",
+ "right_hand_middle_1_joint",
+ "right_hand_thumb_0_joint",
+ "right_hand_thumb_1_joint",
+ "right_hand_thumb_2_joint",
+ ],
+ "groups": [],
+ },
+ "hands": {"joints": [], "groups": ["left_hand", "right_hand"]},
+ # Full body groups
+ "lower_body": {"joints": [], "groups": ["waist", "legs"]},
+ "upper_body_no_hands": {"joints": [], "groups": ["arms"]},
+ "body": {"joints": [], "groups": ["lower_body", "upper_body_no_hands"]},
+ "upper_body": {"joints": [], "groups": ["upper_body_no_hands", "hands"]},
+ }
+
+ # Define joint name mapping from generic types to robot-specific names
+ joint_name_mapping = {
+ # Waist joints
+ "waist_pitch": "waist_pitch_joint",
+ "waist_roll": "waist_roll_joint",
+ "waist_yaw": "waist_yaw_joint",
+ # Shoulder joints
+ "shoulder_pitch": {
+ "left": "left_shoulder_pitch_joint",
+ "right": "right_shoulder_pitch_joint",
+ },
+ "shoulder_roll": {
+ "left": "left_shoulder_roll_joint",
+ "right": "right_shoulder_roll_joint",
+ },
+ "shoulder_yaw": {
+ "left": "left_shoulder_yaw_joint",
+ "right": "right_shoulder_yaw_joint",
+ },
+ # Elbow joints
+ "elbow_pitch": {"left": "left_elbow_joint", "right": "right_elbow_joint"},
+ # Wrist joints
+ "wrist_pitch": {"left": "left_wrist_pitch_joint", "right": "right_wrist_pitch_joint"},
+ "wrist_roll": {"left": "left_wrist_roll_joint", "right": "right_wrist_roll_joint"},
+ "wrist_yaw": {"left": "left_wrist_yaw_joint", "right": "right_wrist_yaw_joint"},
+ }
+
+ root_frame_name = "pelvis"
+
+ hand_frame_names = {"left": "left_wrist_yaw_link", "right": "right_wrist_yaw_link"}
+
+ elbow_calibration_joint_angles = {"left": 0.0, "right": 0.0}
+
+ hand_rotation_correction = np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])
+
+ # Configure default joint positions based on elbow pose
+ if elbow_pose == ElbowPose.HIGH:
+ default_joint_q = {
+ "shoulder_roll": {"left": 0.5, "right": -0.5},
+ "shoulder_pitch": {"left": -0.2, "right": -0.2},
+ "shoulder_yaw": {"left": -0.5, "right": 0.5},
+ "wrist_roll": {"left": -0.5, "right": 0.5},
+ "wrist_yaw": {"left": 0.5, "right": -0.5},
+ "wrist_pitch": {"left": -0.2, "right": -0.2},
+ }
+ else: # ElbowPose.LOW
+ default_joint_q = {
+ "shoulder_roll": {"left": 0.2, "right": -0.2},
+ }
+
+ teleop_upper_body_motion_scale = 1.0
+
+ # Configure joint groups based on waist location
+ modified_joint_groups = joint_groups.copy()
+ if waist_location == WaistLocation.UPPER_BODY:
+ # Move waist from lower_body to upper_body_no_hands
+ modified_joint_groups["lower_body"] = {"joints": [], "groups": ["legs"]}
+ modified_joint_groups["upper_body_no_hands"] = {
+ "joints": [],
+ "groups": ["arms", "waist"],
+ }
+ elif waist_location == WaistLocation.LOWER_AND_UPPER_BODY:
+ # Add waist to upper_body_no_hands while keeping it in lower_body
+ modified_joint_groups["upper_body_no_hands"] = {
+ "joints": [],
+ "groups": ["arms", "waist"],
+ }
+ # For LOWER_BODY, keep default joint_groups as is
+
+ super().__init__(
+ name=name,
+ body_actuated_joints=body_actuated_joints,
+ left_hand_actuated_joints=left_hand_actuated_joints,
+ right_hand_actuated_joints=right_hand_actuated_joints,
+ joint_limits=joint_limits,
+ joint_groups=modified_joint_groups,
+ root_frame_name=root_frame_name,
+ hand_frame_names=hand_frame_names,
+ elbow_calibration_joint_angles=elbow_calibration_joint_angles,
+ joint_name_mapping=joint_name_mapping,
+ hand_rotation_correction=hand_rotation_correction,
+ default_joint_q=default_joint_q,
+ teleop_upper_body_motion_scale=teleop_upper_body_motion_scale,
+ )
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/robot_supplemental_info.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/robot_supplemental_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4d66cfe71bbe1b0b26a19297477126a794b863f
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/robot_supplemental_info.py
@@ -0,0 +1,91 @@
+from dataclasses import dataclass
+from typing import Dict, List, Union
+
+import numpy as np
+
+
+@dataclass
+class RobotSupplementalInfo:
+ """
+ Base class for robot-specific information that is not easily extractable from URDF.
+ This includes information about actuated joints, joint hierarchies, etc.
+ """
+
+ name: str
+
+ # List of body actuated joint names (excluding hands)
+ body_actuated_joints: List[str]
+
+ # List of left hand actuated joint names
+ left_hand_actuated_joints: List[str]
+
+ # List of right hand actuated joint names
+ right_hand_actuated_joints: List[str]
+
+ # Dictionary of joint groups, where each group is a dictionary with:
+ # - "joints": list of joint names
+ # - "groups": list of subgroup names (optional)
+ # Example: {
+ # "right_arm": {
+ # "joints": ["right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_elbow_joint"],
+ # "groups": []
+ # },
+ # "left_arm": {
+ # "joints": ["left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_elbow_joint"],
+ # "groups": []
+ # },
+ # "upper_body": {
+ # "joints": ["torso_pitch_joint", "torso_yaw_joint", "torso_roll_joint"],
+ # "groups": ["right_arm", "left_arm"]
+ # }
+ # }
+ joint_groups: Dict[str, Dict[str, List[str]]]
+
+ # Name of the root frame
+ root_frame_name: str
+
+ # Dictionary of hand frame names
+ # Example: {
+ # "left": "left_hand_frame",
+ # "right": "right_hand_frame"
+ # }
+ hand_frame_names: Dict[str, str]
+
+ # Dictionary of joint limits
+ # Example: {
+ # "left_shoulder_pitch_joint": [-np.pi / 2, np.pi / 2],
+ # "right_shoulder_pitch_joint": [-np.pi / 2, np.pi / 2]
+ # }
+ joint_limits: Dict[str, List[float]]
+
+ # Dictionary of elbow calibration joint angles
+ # Example: {
+ # "left": -90.0,
+ # "right": -90.0
+ # }
+ elbow_calibration_joint_angles: Dict[str, float]
+
+ # Dictionary of joint name mapping from generic types to robot-specific names
+ # Example: {
+ # "waist_pitch": "waist_pitch_joint",
+ # "shoulder_pitch": {
+ # "left": "left_shoulder_pitch_joint",
+ # "right": "right_shoulder_pitch_joint"
+ # },
+ # "elbow_pitch": {
+ # "left": "left_elbow_pitch_joint",
+ # "right": "right_elbow_pitch_joint"
+ # }
+ # }
+ joint_name_mapping: Dict[str, Union[str, Dict[str, str]]]
+
+ # Maps from generic joint names to robot-specific joint values
+ # Example: {
+ # "waist_roll": 0.2,
+ # "elbow_pitch": {"left": 1.0, "right": 1.0}
+ # }
+ default_joint_q: Dict[str, Union[float, Dict[str, float]]]
+
+ hand_rotation_correction: np.ndarray
+
+ teleop_upper_body_motion_scale: float
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/composed_camera.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/composed_camera.py
new file mode 100644
index 0000000000000000000000000000000000000000..675a93563148b01926222c5854149b09d82317b3
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/composed_camera.py
@@ -0,0 +1,440 @@
+from collections import deque
+from dataclasses import dataclass
+import queue
+import threading
+import time
+from typing import Any, Dict, Optional
+
+# we need to import these first in this order to avoid TSL segmentation fault
+# caused by zed and oak libraries
+try:
+ import cv2 # noqa
+ import depthai as dai # noqa
+ import pyzed.sl as sl # noqa
+except ImportError:
+ print(
+ """
+ Some of the camera specific dependencies are not installed. If you are
+ not running this on the robot, having these libraries is optional.
+ """
+ )
+
+import numpy as np # noqa
+
+from decoupled_wbc.control.base.sensor import Sensor
+from decoupled_wbc.control.sensor.sensor_server import (
+ ImageMessageSchema,
+ SensorClient,
+ SensorServer,
+ CameraMountPosition,
+)
+
+
+def read_qr_code(data):
+ current_time = time.monotonic()
+ detector = cv2.QRCodeDetector()
+ for key, img in data["images"].items():
+ decoded_time, bbox, _ = detector.detectAndDecode(img)
+ if bbox is not None and decoded_time:
+ print(f"{key} latency: {(current_time - float(decoded_time)) * 1e3:.1f} ms")
+ else:
+ print(f"{key} QR code not detected.")
+
+
+@dataclass
+class ComposedCameraConfig:
+ """Camera configuration for composed camera"""
+
+ ego_view_camera: Optional[str] = "oak"
+ """Camera type for ego view: oak, realsense, zed, or None"""
+
+ ego_view_device_id: Optional[str] = None
+ """Device ID for ego view camera (optional, used for OAK cameras)"""
+
+ head_camera: Optional[str] = None
+ """Camera type for head view: oak, oak_mono, realsense, zed or None"""
+
+ head_device_id: Optional[str] = None
+ """Device ID for head camera (optional, used for OAK cameras)"""
+
+ left_wrist_camera: Optional[str] = None
+ """Camera type for left wrist view: oak, realsense, zed or None"""
+
+ left_wrist_device_id: Optional[str] = None
+ """Device ID for left wrist camera (optional, used for OAK cameras)"""
+
+ right_wrist_camera: Optional[str] = None
+ """Camera type for right wrist view: oak, realsense, zed or None"""
+
+ right_wrist_device_id: Optional[str] = None
+ """Device ID for right wrist camera (optional, used for OAK cameras)"""
+
+ fps: int = 30
+ """Rate at which the composed camera will publish the images. Since composed camera
+ can read from multiple cameras, it will publish all the images.
+ Note that OAK can only run at 30 FPS. 20 FPS will cause large latency.
+ """
+
+ # Server configuration
+ run_as_server: bool = True
+ """Whether to run as server or client"""
+
+ server: bool = True
+ """Whether to run the camera as a server"""
+
+ port: int = 5555
+ """Port number for server/client communication"""
+
+ test_latency: bool = False
+ """Whether to test latency"""
+
+ # Queue configuration
+ queue_size: int = 3
+ """Size of each camera's image queue"""
+
+ def __post_init__(self):
+ # runyu: Note that this is a hack to make the config work with G1 camera server in orin
+ # we should not use this hack in the future
+ self.run_as_server: bool = self.server
+
+
+class ComposedCameraSensor(Sensor, SensorServer):
+
+ def __init__(self, config: ComposedCameraConfig):
+ self.config = config
+ self.camera_queues: Dict[str, queue.Queue] = {}
+ self.camera_threads: Dict[str, threading.Thread] = {}
+ self.shutdown_events: Dict[str, threading.Event] = {}
+ self.error_events: Dict[str, threading.Event] = {}
+ self.error_messages: Dict[str, str] = {}
+ self._observation_spaces: Dict[str, Any] = {}
+
+ camera_configs = self._get_camera_configs()
+
+ # Then create worker threads
+ for mount_position, camera_config in camera_configs.items():
+ # Create queue and shutdown event for this camera
+ camera_queue = queue.Queue(maxsize=config.queue_size)
+ shutdown_event = threading.Event()
+ error_event = threading.Event()
+
+ self.camera_queues[mount_position] = camera_queue
+ self.shutdown_events[mount_position] = shutdown_event
+ self.error_events[mount_position] = error_event
+
+ # Start camera thread
+ thread = threading.Thread(
+ target=self._camera_worker_wrapper,
+ args=(
+ mount_position,
+ camera_config["camera_type"],
+ camera_config["device_id"],
+ camera_queue,
+ shutdown_event,
+ error_event,
+ ),
+ )
+ thread.start()
+ self.camera_threads[mount_position] = thread
+
+ if config.run_as_server:
+ self.start_server(config.port)
+
+ def _get_camera_configs(self) -> Dict[str, str]:
+ """Get camera configurations as mount_position -> camera_type mapping"""
+ camera_configs = {}
+
+ if self.config.ego_view_camera is not None:
+ camera_configs[CameraMountPosition.EGO_VIEW.value] = {
+ "camera_type": self.config.ego_view_camera,
+ "device_id": self.config.ego_view_device_id,
+ }
+
+ if self.config.head_camera is not None:
+ camera_configs[CameraMountPosition.HEAD.value] = {
+ "camera_type": self.config.head_camera,
+ "device_id": self.config.head_device_id,
+ }
+
+ if self.config.left_wrist_camera is not None:
+ camera_configs[CameraMountPosition.LEFT_WRIST.value] = {
+ "camera_type": self.config.left_wrist_camera,
+ "device_id": self.config.left_wrist_device_id,
+ }
+
+ if self.config.right_wrist_camera is not None:
+ camera_configs[CameraMountPosition.RIGHT_WRIST.value] = {
+ "camera_type": self.config.right_wrist_camera,
+ "device_id": self.config.right_wrist_device_id,
+ }
+
+ return camera_configs
+
+ def _camera_worker_wrapper(
+ self,
+ mount_position: str,
+ camera_type: str,
+ device_id: Optional[str],
+ image_queue: queue.Queue,
+ shutdown_event: threading.Event,
+ error_event: threading.Event,
+ ):
+ """Worker thread that continuously captures from a single camera"""
+ try:
+ camera = self._instantiate_camera(mount_position, camera_type, device_id)
+ self._observation_spaces[mount_position] = camera.observation_space()
+
+ consecutive_failures = 0
+ max_consecutive_failures = 5
+
+ while not shutdown_event.is_set():
+ frame = camera.read()
+ if frame:
+ consecutive_failures = 0 # Reset on successful read
+ # Non-blocking queue put with frame dropping
+ try:
+ image_queue.put_nowait(frame)
+ except queue.Full:
+ # Remove oldest frame and add new one
+ try:
+ image_queue.get_nowait()
+ image_queue.put_nowait(frame)
+ except queue.Empty:
+ pass
+ else:
+ consecutive_failures += 1
+ if consecutive_failures >= max_consecutive_failures:
+ error_msg = (
+ f"Camera {mount_position} ({camera_type}) dropped: "
+ f"failed to read {consecutive_failures} consecutive frames"
+ )
+ print(f"[ERROR] {error_msg}")
+ self.error_messages[mount_position] = error_msg
+ error_event.set()
+ break
+
+ camera.close()
+
+ except Exception as e:
+ error_msg = f"Camera {mount_position} ({camera_type}) error: {str(e)}"
+ print(f"[ERROR] {error_msg}")
+ self.error_messages[mount_position] = error_msg
+ error_event.set()
+
+ def _instantiate_camera(
+ self, mount_position: str, camera_type: str, device_id: Optional[str] = None
+ ) -> Sensor:
+ """
+ Instantiate a camera sensor based on the camera type.
+
+ Args:
+ camera_type: Type of camera ("oak", "oak_mono", "realsense", "zed")
+ device_id: Optional device ID for the camera (used for OAK cameras)
+
+ Returns:
+ Sensor instance for the specified camera type
+ """
+ if camera_type in ("oak", "oak_mono"):
+ from decoupled_wbc.control.sensor.oak import OAKConfig, OAKSensor
+
+ oak_config = OAKConfig()
+ if camera_type == "oak_mono":
+ oak_config.enable_mono_cameras = True
+ print("Initializing OAK sensor for camera type: ", camera_type)
+ return OAKSensor(config=oak_config, mount_position=mount_position, device_id=device_id)
+ elif camera_type == "realsense":
+ from decoupled_wbc.control.sensor.realsense import RealSenseSensor
+
+ print("Initializing RealSense sensor for camera type: ", camera_type)
+ return RealSenseSensor(mount_position=mount_position)
+ elif camera_type == "zed":
+ from decoupled_wbc.control.sensor.zed import ZEDSensor
+
+ print("Initializing ZED sensor for camera type: ", camera_type)
+ return ZEDSensor(mount_position=mount_position)
+ elif camera_type.endswith(".mp4"):
+ from decoupled_wbc.control.sensor.dummy import ReplayDummySensor
+
+ print("Initializing Replay Dummy Sensor for camera type: ", camera_type)
+ return ReplayDummySensor(video_path=camera_type)
+ else:
+ raise ValueError(f"Unsupported camera type: {camera_type}")
+
+ def _check_for_errors(self):
+ """Check if any camera thread has encountered an error and raise exception if so."""
+ for mount_position, error_event in self.error_events.items():
+ if error_event.is_set():
+ error_msg = self.error_messages.get(
+ mount_position, f"Camera {mount_position} encountered an unknown error"
+ )
+ raise RuntimeError(error_msg)
+
+ def read(self):
+ """Read frames from all cameras."""
+ # Check for errors from camera threads
+ self._check_for_errors()
+
+ message = {}
+ for mount_position, camera_queue in self.camera_queues.items():
+ frame = self._get_latest_from_queue(camera_queue)
+ if frame is not None:
+ message[mount_position] = frame
+ return message
+
+ def _get_latest_from_queue(self, camera_queue: queue.Queue) -> Optional[Dict[str, Any]]:
+ """Get most recent frame, discard older ones"""
+ latest = None
+ try:
+ while True:
+ latest = camera_queue.get_nowait()
+ except queue.Empty:
+ pass
+ return latest
+
+ def close(self):
+ """Close all cameras."""
+ # Signal all worker threads to shutdown
+ for shutdown_event in self.shutdown_events.values():
+ shutdown_event.set()
+
+ # Wait for all threads to finish
+ for thread in self.camera_threads.values():
+ thread.join(timeout=5.0)
+
+ # Clear queues
+ for camera_queue in self.camera_queues.values():
+ try:
+ while True:
+ camera_queue.get_nowait()
+ except queue.Empty:
+ pass
+
+ # Stop server if running
+ if self.config.run_as_server:
+ self.stop_server()
+
+ def serialize_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
+ """Merge all camera data into a single ImageMessageSchema."""
+ all_timestamps = {}
+ all_images = {}
+
+ for _, camera_data in message.items():
+ all_timestamps.update(camera_data.get("timestamps", {}))
+ all_images.update(camera_data.get("images", {}))
+
+ # Create a single ImageMessageSchema with all data
+ img_schema = ImageMessageSchema(timestamps=all_timestamps, images=all_images)
+ return img_schema.serialize()
+
+ def run_server(self):
+ """Run the server."""
+ idx = 0
+ server_start_time = time.monotonic()
+ fps_print_time = time.monotonic()
+ frame_interval = 1.0 / self.config.fps
+
+ while True:
+ # Calculate when this frame should ideally complete
+ target_time = server_start_time + (idx + 1) * frame_interval
+
+ message = self.read()
+ if message:
+ if self.config.test_latency:
+ read_qr_code(message)
+
+ serialized_message = self.serialize_message(message)
+ self.send_message(serialized_message)
+ idx += 1
+
+ if idx % 10 == 0:
+ print(f"Image sending FPS: {10 / (time.monotonic() - fps_print_time):.2f}")
+ fps_print_time = time.monotonic()
+
+ # Sleep to maintain precise timing
+ current_time = time.monotonic()
+ sleep_time = target_time - current_time
+ if sleep_time > 0:
+ time.sleep(sleep_time)
+ else:
+ # If we're behind, increment idx to stay on schedule
+ if not message:
+ idx += 1
+
+ def observation_space(self):
+ """Return the observation space."""
+ import gymnasium as gym
+
+ return gym.spaces.Dict(self._observation_spaces)
+
+
+class ComposedCameraClientSensor(Sensor, SensorClient):
+ """Class that serves as client for multiple different cameras."""
+
+ def __init__(self, server_ip: str = "localhost", port: int = 5555):
+ self.start_client(server_ip, port)
+
+ # Initialize tracking variables
+ self._latest_message = {}
+ self._avg_time_per_frame = deque(maxlen=20)
+ self._msg_received_time = 0
+ self._start_time = 0.0 # Initialize _start_time
+ self.idx = 0
+
+ print("Initialized composed camera client sensor")
+
+ def read(self, **kwargs) -> Optional[Dict[str, Any]]:
+ self._start_time = time.time()
+ message = self.receive_message()
+ if not message:
+ return None
+ self.idx += 1
+
+ self._latest_message = ImageMessageSchema.deserialize(message).asdict()
+
+ # if self.idx % 10 == 0:
+ # for image_key, image_time in self._latest_message["timestamps"].items():
+ # image_latency = (time.time() - image_time) * 1000
+ # print(f"Image latency for {image_key}: {image_latency:.2f} ms")
+
+ self._msg_received_time = time.time()
+ self._avg_time_per_frame.append(self._msg_received_time - self._start_time)
+
+ return self._latest_message
+
+ def close(self):
+ """Close the client connection."""
+ self.stop_client()
+
+ def fps(self) -> float:
+ """Get the current FPS of the client."""
+ if len(self._avg_time_per_frame) == 0:
+ return 0.0
+ return float(1 / np.mean(self._avg_time_per_frame))
+
+
+if __name__ == "__main__":
+ """Test function for ComposedCamera."""
+ import tyro
+
+ config = tyro.cli(ComposedCameraConfig)
+
+ if config.run_as_server:
+ composed_camera = ComposedCameraSensor(config)
+ print("Running composed camera server...")
+ composed_camera.run_server()
+
+ else:
+ # Client mode
+ composed_client = ComposedCameraClientSensor(server_ip="localhost", port=config.port)
+
+ try:
+ while True:
+ data = composed_client.read()
+ if data is not None:
+ print(f"FPS: {composed_client.fps():.2f}")
+ if "timestamp" in data:
+ print(f"Timestamp: {data['timestamp']}")
+ time.sleep(0.1)
+ except KeyboardInterrupt:
+ print("Stopping client...")
+ composed_client.close()
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/oak.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/oak.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae7b532b8f03135e262801c42ad254bf49dca5d2
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/oak.py
@@ -0,0 +1,324 @@
+import time
+from typing import Any, Dict, Optional, Tuple
+
+import cv2
+import depthai as dai
+import gymnasium as gym
+import numpy as np
+
+from decoupled_wbc.control.base.sensor import Sensor
+from decoupled_wbc.control.sensor.sensor_server import (
+ CameraMountPosition,
+ ImageMessageSchema,
+ SensorServer,
+)
+
+
+class OAKConfig:
+ """Configuration for the OAK camera."""
+
+ color_image_dim: Tuple[int, int] = (640, 480) # RGB camera resolution
+ monochrome_image_dim: Tuple[int, int] = (640, 480) # Monochrome camera resolution
+ fps: int = 30
+ enable_color: bool = True # Enable CAM_A (RGB)
+ enable_mono_cameras: bool = False # Enable CAM_B & CAM_C (Monochrome stereo pair)
+ mount_position: str = CameraMountPosition.EGO_VIEW.value
+
+
+class OAKSensor(Sensor, SensorServer):
+ """Sensor for the OAK camera family."""
+
+ def __init__(
+ self,
+ run_as_server: bool = False,
+ port: int = 5555,
+ config: OAKConfig = OAKConfig(),
+ device_id: Optional[str] = None,
+ mount_position: str = CameraMountPosition.EGO_VIEW.value,
+ ):
+ """Initialize the OAK camera."""
+ self.config = config
+ self.mount_position = mount_position
+ self._run_as_server = run_as_server
+
+ device_infos = dai.Device.getAllAvailableDevices()
+ assert len(device_infos) > 0, f"No OAK devices found for {mount_position}"
+ print(f"Device infos: {device_infos}")
+ if device_id is not None:
+ device_found = False
+ for device_info in device_infos:
+ if device_info.getDeviceId() == device_id:
+ self.device = dai.Device(device_info)
+ device_found = True
+ break
+ if not device_found:
+ raise ValueError(f"Device with ID {device_id} not found")
+ else:
+ self.device = dai.Device()
+
+ print(f"Connected to OAK device: {self.device.getDeviceName(), self.device.getDeviceId()}")
+ print(f"Device ID: {self.device.getDeviceId()}")
+
+ sockets: list[dai.CameraBoardSocket] = self.device.getConnectedCameras()
+ print(f"Available cameras: {[str(s) for s in sockets]}")
+
+ # Create pipeline (without context manager to persist across method calls)
+ self.pipeline = dai.Pipeline(self.device)
+ self.output_queues = {}
+
+ # Configure RGB camera (CAM_A)
+ if config.enable_color and dai.CameraBoardSocket.CAM_A in sockets:
+ self.cam_rgb = self.pipeline.create(dai.node.Camera)
+ cam_socket = dai.CameraBoardSocket.CAM_A
+ self.cam_rgb = self.cam_rgb.build(cam_socket)
+ # Create RGB output queue
+ self.output_queues["color"] = self.cam_rgb.requestOutput(
+ config.color_image_dim,
+ fps=config.fps,
+ ).createOutputQueue()
+ print("Enabled CAM_A (RGB)")
+
+ # Configure Monochrome cameras (CAM_B & CAM_C)
+ if config.enable_mono_cameras:
+ if dai.CameraBoardSocket.CAM_B in sockets:
+ self.cam_mono_left = self.pipeline.create(dai.node.Camera)
+ cam_socket = dai.CameraBoardSocket.CAM_B
+ self.cam_mono_left = self.cam_mono_left.build(cam_socket)
+ # Create mono left output queue
+ self.output_queues["mono_left"] = self.cam_mono_left.requestOutput(
+ config.monochrome_image_dim,
+ fps=config.fps,
+ ).createOutputQueue()
+ print("Enabled CAM_B (Monochrome Left)")
+
+ if dai.CameraBoardSocket.CAM_C in sockets:
+ self.cam_mono_right = self.pipeline.create(dai.node.Camera)
+ cam_socket = dai.CameraBoardSocket.CAM_C
+ self.cam_mono_right = self.cam_mono_right.build(cam_socket)
+ # Create mono right output queue
+ self.output_queues["mono_right"] = self.cam_mono_right.requestOutput(
+ config.monochrome_image_dim,
+ fps=config.fps,
+ ).createOutputQueue()
+ print("Enabled CAM_C (Monochrome Right)")
+
+ assert len(self.output_queues) > 0, "No output queues enabled"
+ # auto exposure compensation, for CoRL demo
+ # cam_q_in = self.cam_rgb.inputControl.createInputQueue()
+ # ctrl = dai.CameraControl()
+ # ctrl.setAutoExposureEnable()
+ # ctrl.setAutoExposureCompensation(-2)
+ # cam_q_in.send(ctrl)
+
+ # Start pipeline on device
+ self.pipeline.start()
+
+ if run_as_server:
+ self.start_server(port)
+
+ def read(self) -> Optional[Dict[str, Any]]:
+ """Read images from the camera."""
+ if not self.pipeline.isRunning():
+ print(f"[ERROR] OAK pipeline stopped for {self.mount_position}")
+ return None
+
+ # Check if device is still connected
+ if not self.device.isPipelineRunning():
+ print(f"[ERROR] OAK device disconnected for {self.mount_position}")
+ return None
+
+ timestamps = {}
+ images = {}
+ rgb_frame_time = None
+
+ # Get color frame if enabled
+ if "color" in self.output_queues:
+ try:
+ rgb_frame = self.output_queues["color"].get()
+ rgb_frame_time = rgb_frame.getTimestamp()
+ if rgb_frame is not None:
+ images[self.mount_position] = rgb_frame.getCvFrame()[..., ::-1] # BGR to RGB
+ timestamps[self.mount_position] = (
+ rgb_frame_time - dai.Clock.now()
+ ).total_seconds() + time.time()
+ except Exception as e:
+ print(f"[ERROR] Failed to read color frame from {self.mount_position}: {e}")
+ return None
+
+ # Get mono frames if enabled
+ if "mono_left" in self.output_queues:
+ try:
+ mono_left_frame = self.output_queues["mono_left"].get()
+ mono_left_frame_time = mono_left_frame.getTimestamp()
+ if mono_left_frame is not None:
+ key = f"{self.mount_position}_left_mono"
+ images[key] = mono_left_frame.getCvFrame()
+ timestamps[key] = (
+ mono_left_frame_time - dai.Clock.now()
+ ).total_seconds() + time.time()
+ except Exception as e:
+ print(f"[ERROR] Failed to read mono_left frame from {self.mount_position}: {e}")
+ return None
+
+ if "mono_right" in self.output_queues:
+ try:
+ mono_right_frame = self.output_queues["mono_right"].get()
+ mono_right_frame_time = mono_right_frame.getTimestamp()
+ if mono_right_frame is not None:
+ key = f"{self.mount_position}_right_mono"
+ images[key] = mono_right_frame.getCvFrame()
+ timestamps[key] = (
+ mono_right_frame_time - dai.Clock.now()
+ ).total_seconds() + time.time()
+ except Exception as e:
+ print(f"[ERROR] Failed to read mono_right frame from {self.mount_position}: {e}")
+ return None
+
+ if (
+ rgb_frame_time is not None
+ and (rgb_frame_time - dai.Clock.now()).total_seconds() <= -0.2
+ ):
+ print(
+ f"[{self.mount_position}] OAK latency too large: "
+ f"{(dai.Clock.now() - rgb_frame_time).total_seconds() * 1000}ms"
+ )
+
+ return {
+ "timestamps": timestamps,
+ "images": images,
+ }
+
+ def serialize(self, data: Dict[str, Any]) -> Dict[str, Any]:
+ """Serialize data using ImageMessageSchema."""
+ serialized_msg = ImageMessageSchema(timestamps=data["timestamps"], images=data["images"])
+ return serialized_msg.serialize()
+
+ def observation_space(self) -> gym.Space:
+ spaces = {}
+
+ if self.config.enable_color:
+ spaces["color_image"] = gym.spaces.Box(
+ low=0,
+ high=255,
+ shape=(self.config.color_image_dim[1], self.config.color_image_dim[0], 3),
+ dtype=np.uint8,
+ )
+
+ if self.config.enable_mono_cameras:
+ spaces["mono_left_image"] = gym.spaces.Box(
+ low=0,
+ high=255,
+ shape=(self.config.monochrome_image_dim[1], self.config.monochrome_image_dim[0]),
+ dtype=np.uint8,
+ )
+ spaces["mono_right_image"] = gym.spaces.Box(
+ low=0,
+ high=255,
+ shape=(self.config.monochrome_image_dim[1], self.config.monochrome_image_dim[0]),
+ dtype=np.uint8,
+ )
+
+ return gym.spaces.Dict(spaces)
+
+ def close(self):
+ """Close the camera connection."""
+ if self._run_as_server:
+ self.stop_server()
+ if hasattr(self, "pipeline") and self.pipeline.isRunning():
+ self.pipeline.stop()
+ self.device.close()
+
+ def run_server(self):
+ """Run the server."""
+ if not self._run_as_server:
+ raise ValueError("This function is only available when run_as_server is True")
+
+ while True:
+ frame = self.read()
+ if frame is None:
+ continue
+
+ msg = self.serialize(frame)
+ self.send_message({self.mount_position: msg})
+
+ def __del__(self):
+ self.close()
+
+
+if __name__ == "__main__":
+ """Test function for OAK camera."""
+
+ import argparse
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--server", action="store_true", help="Run as server")
+ parser.add_argument("--client", action="store_true", help="Run as client")
+ parser.add_argument("--host", type=str, default="localhost", help="Server IP address")
+ parser.add_argument("--port", type=int, default=5555, help="Port number")
+ parser.add_argument("--device-id", type=str, default=None, help="Specific device ID")
+ parser.add_argument(
+ "--enable-mono", action="store_true", help="Enable monochrome cameras (CAM_B & CAM_C)"
+ )
+ parser.add_argument("--mount-position", type=str, default="ego_view", help="Mount position")
+ parser.add_argument("--show-image", action="store_true", help="Display images")
+ args = parser.parse_args()
+
+ oak_config = OAKConfig()
+ if args.enable_mono:
+ oak_config.enable_mono_cameras = True
+
+ if args.server:
+ # Run as server
+ oak = OAKSensor(
+ run_as_server=True,
+ port=args.port,
+ config=oak_config,
+ device_id=args.device_id,
+ mount_position=args.mount_position,
+ )
+ print(f"Starting OAK server on port {args.port}")
+ oak.run_server()
+
+ else:
+ # Run standalone
+ oak = OAKSensor(run_as_server=False, config=oak_config, device_id=args.device_id)
+ print("Running OAK camera in standalone mode")
+
+ while True:
+ frame = oak.read()
+ if frame is None:
+ print("Waiting for frame...")
+ time.sleep(0.5)
+ continue
+
+ if "color_image" in frame:
+ print(f"Color image shape: {frame['color_image'].shape}")
+ if "mono_left_image" in frame:
+ print(f"Mono left image shape: {frame['mono_left_image'].shape}")
+ if "mono_right_image" in frame:
+ print(f"Mono right image shape: {frame['mono_right_image'].shape}")
+ if "depth_image" in frame:
+ print(f"Depth image shape: {frame['depth_image'].shape}")
+
+ if args.show_image:
+ if "color_image" in frame:
+ cv2.imshow("Color Image", frame["color_image"])
+
+ if "mono_left_image" in frame:
+ cv2.imshow("Mono Left", frame["mono_left_image"])
+ if "mono_right_image" in frame:
+ cv2.imshow("Mono Right", frame["mono_right_image"])
+
+ if "depth_image" in frame:
+ depth_colormap = cv2.applyColorMap(
+ cv2.convertScaleAbs(frame["depth_image"], alpha=0.03), cv2.COLORMAP_JET
+ )
+ cv2.imshow("Depth Image", depth_colormap)
+
+ if cv2.waitKey(1) == ord("q"):
+ break
+
+ time.sleep(0.01)
+
+ cv2.destroyAllWindows()
+ oak.close()
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/sensor_server.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/sensor_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..28453377963567928c5a54c9e44662bfa9650df2
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/sensor_server.py
@@ -0,0 +1,128 @@
+import base64
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, Dict
+
+import cv2
+import msgpack
+import msgpack_numpy as m
+import numpy as np
+import zmq
+
+
+@dataclass
+class ImageMessageSchema:
+ """
+ This is a standardized message schema for image data.
+ Any camera should use this schema to serialize (send to queue) and
+ deserialize (receive from queue) the image data.
+
+ """
+
+ timestamps: Dict[str, float]
+ """Dictionary of timestamps, keyed by image identifier (e.g., {"ego_view": 123.45})"""
+ images: Dict[str, np.ndarray]
+ """Dictionary of images, keyed by image identifier (e.g., {"ego_view": array, "ego_view_left_mono": array})"""
+
+ def serialize(self) -> Dict[str, Any]:
+ """Serialize the message for transmission."""
+ serialized_msg = {"timestamps": self.timestamps, "images": {}}
+ for key, image in self.images.items():
+ serialized_msg["images"][key] = ImageUtils.encode_image(image)
+ return serialized_msg
+
+ @staticmethod
+ def deserialize(data: Dict[str, Any]) -> "ImageMessageSchema":
+ """Deserialize received message data."""
+ timestamps = data.get("timestamps", {})
+ images = {}
+ for key, value in data.get("images", {}).items():
+ if isinstance(value, str):
+ images[key] = ImageUtils.decode_image(value)
+ else:
+ images[key] = value
+ return ImageMessageSchema(timestamps=timestamps, images=images)
+
+ def asdict(self) -> Dict[str, Any]:
+ """Convert to dictionary format."""
+ return {"timestamps": self.timestamps, "images": self.images}
+
+
+class SensorServer:
+ def start_server(self, port: int):
+ self.context = zmq.Context()
+ self.socket = self.context.socket(zmq.PUB)
+ self.socket.setsockopt(zmq.SNDHWM, 20) # high water mark
+ self.socket.setsockopt(zmq.LINGER, 0)
+ self.socket.bind(f"tcp://*:{port}")
+ print(f"Sensor server running at tcp://*:{port}")
+
+ self.message_sent = 0
+ self.message_dropped = 0
+
+ def stop_server(self):
+ self.socket.close()
+ self.context.term()
+
+ def send_message(self, data: Dict[str, Any]):
+ try:
+ packed = msgpack.packb(data, use_bin_type=True)
+ self.socket.send(packed, flags=zmq.NOBLOCK)
+ except zmq.Again:
+ self.message_dropped += 1
+ print(f"[Warning] message dropped: {self.message_dropped}")
+ self.message_sent += 1
+
+ if self.message_sent % 100 == 0:
+ print(
+ f"[Sensor server] Message sent: {self.message_sent}, message dropped: {self.message_dropped}"
+ )
+
+
+class SensorClient:
+ def start_client(self, server_ip: str, port: int):
+ self.context = zmq.Context()
+ self.socket = self.context.socket(zmq.SUB)
+ self.socket.setsockopt_string(zmq.SUBSCRIBE, "")
+ self.socket.setsockopt(zmq.CONFLATE, True) # last msg only.
+ self.socket.setsockopt(zmq.RCVHWM, 3) # queue size 3 for receive buffer
+ self.socket.connect(f"tcp://{server_ip}:{port}")
+
+ def stop_client(self):
+ self.socket.close()
+ self.context.term()
+
+ def receive_message(self):
+ packed = self.socket.recv()
+ return msgpack.unpackb(packed, object_hook=m.decode)
+
+
+class CameraMountPosition(Enum):
+ EGO_VIEW = "ego_view"
+ HEAD = "head"
+ LEFT_WRIST = "left_wrist"
+ RIGHT_WRIST = "right_wrist"
+
+
+class ImageUtils:
+ @staticmethod
+ def encode_image(image: np.ndarray) -> str:
+ _, color_buffer = cv2.imencode(".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), 80])
+ return base64.b64encode(color_buffer).decode("utf-8")
+
+ @staticmethod
+ def encode_depth_image(image: np.ndarray) -> str:
+ depth_compressed = cv2.imencode(".png", image)[1].tobytes()
+ return base64.b64encode(depth_compressed).decode("utf-8")
+
+ @staticmethod
+ def decode_image(image: str) -> np.ndarray:
+ color_data = base64.b64decode(image)
+ color_array = np.frombuffer(color_data, dtype=np.uint8)
+ return cv2.imdecode(color_array, cv2.IMREAD_COLOR)
+
+ @staticmethod
+ def decode_depth_image(image: str) -> np.ndarray:
+ depth_data = base64.b64decode(image)
+ depth_array = np.frombuffer(depth_data, dtype=np.uint8)
+ return cv2.imdecode(depth_array, cv2.IMREAD_UNCHANGED)
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientLogging.hpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientLogging.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..a7469d706945cadaa8bc238926d81406f130ad56
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientLogging.hpp
@@ -0,0 +1,158 @@
+#ifndef __CLIENT_LOGGING_HPP__
+#define __CLIENT_LOGGING_HPP__
+#include
+#include
+#include
+#include
+
+namespace ManusSDK
+{
+ class ClientLog
+ {
+ public:
+ //Simple
+ static void debug(const char* p_String)
+ {
+ std::cout << "DEBUG: " << p_String << std::endl;
+ }
+
+ static void info(const char* p_String)
+ {
+ std::cout << "INFO: " << p_String << std::endl;
+ }
+
+ static void warn(const char* p_String)
+ {
+ std::cout << "WARN: " << p_String << std::endl;
+ }
+
+ static void error(const char* p_String)
+ {
+ std::cout << "ERROR: " << p_String << std::endl;
+ }
+
+ static void print(const char* p_String)
+ {
+ std::cout << p_String << std::endl;
+ }
+
+ //Templated
+ template
+ static void debug(const char* p_Format, Args &&...p_Args)
+ {
+ std::string formatted_string = p_Format;
+ replacePlaceholders(formatted_string, std::forward(p_Args)...);
+ std::cout << "DEBUG: " << formatted_string << std::endl;
+ }
+
+ template
+ static void info(const char* p_Format, Args &&...p_Args)
+ {
+ std::string formatted_string = p_Format;
+ replacePlaceholders(formatted_string, std::forward(p_Args)...);
+ std::cout << "INFO: " << formatted_string << std::endl;
+ }
+
+ template
+ static void warn(const char* p_Format, Args &&...p_Args)
+ {
+ std::string formatted_string = p_Format;
+ replacePlaceholders(formatted_string, std::forward(p_Args)...);
+ std::cout << "WARN: " << formatted_string << std::endl;
+ }
+
+ template
+ static void error(const char* p_Format, Args &&...p_Args)
+ {
+ std::string formatted_string = p_Format;
+ replacePlaceholders(formatted_string, std::forward(p_Args)...);
+ std::cout << "ERROR: " << formatted_string << std::endl;
+ }
+
+ template
+ static void print(const char* p_Format, Args &&...p_Args)
+ {
+ std::string formatted_string = p_Format;
+ replacePlaceholders(formatted_string, std::forward(p_Args)...);
+ std::cout << formatted_string << std::endl;
+ }
+
+ template
+ static void printWithPadding(const char* p_Format, int p_Padding, Args &&...p_Args)
+ {
+ std::string formatted_string = p_Format;
+ replacePlaceholdersWithPadding(formatted_string, p_Padding, std::forward(p_Args)...);
+ std::cout << formatted_string << std::endl;
+ }
+
+ private:
+ // Base case for recursion: no arguments left
+ static void replacePlaceholders(std::string&) {
+ // No more arguments, so nothing to replace
+ }
+
+ // Replace placeholders {} with actual values (only supports empty curly brackets, no formatting)
+ template
+ static void replacePlaceholders(std::string& p_Format, T&& p_Value, Args&&... p_Args) {
+ size_t pos = p_Format.find("{}");
+ if (pos != std::string::npos) {
+ p_Format.replace(pos, 2, to_string(std::forward(p_Value)));
+ replacePlaceholders(p_Format, std::forward(p_Args)...);
+ }
+ }
+
+ // Base case for recursion: no arguments left
+ static void replacePlaceholdersWithPadding(std::string&, int p_Padding) {
+ // No more arguments, so nothing to replace
+ }
+ // Replace placeholders {} with actual values (only supports empty curly brackets, no formatting)
+ template
+ static void replacePlaceholdersWithPadding(std::string& p_Format, int p_Padding, T&& p_Value, Args&&... p_Args) {
+ size_t pos = p_Format.find("{}");
+ if (pos != std::string::npos) {
+ std::ostringstream oss;
+ oss << std::setw(p_Padding) << to_string(std::forward(p_Value));
+ p_Format.replace(pos, 2, oss.str());
+ replacePlaceholdersWithPadding(p_Format, p_Padding, std::forward(p_Args)...);
+ }
+ }
+
+ // Utility to convert various types to string
+ template
+ static std::string to_string(const T& p_Value) {
+ std::ostringstream oss;
+ oss << p_Value;
+ return oss.str();
+ }
+
+ // Specialization for uint8_t
+ static std::string to_string(const uint8_t& p_Value) {
+ std::ostringstream oss;
+ oss << static_cast(p_Value);
+ return oss.str();
+ }
+
+ // Specialization for uint16_t
+ static std::string to_string(const uint16_t& p_Value) {
+ std::ostringstream oss;
+ oss << static_cast(p_Value);
+ return oss.str();
+ }
+
+ // Specialization for uint32_t
+ static std::string to_string(const uint32_t& p_Value) {
+ std::ostringstream oss;
+ oss << std::hex << p_Value;
+ return oss.str();
+ }
+
+ // Specialization for bool
+ static std::string to_string(const bool& p_Value) {
+ std::ostringstream oss;
+ oss << std::setw(5) << (p_Value ? "true" : "false");
+ return oss.str();
+ }
+ };
+}
+
+#endif
diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.cpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..3c702818fee1ea5a6edadae910d4962859af9394
--- /dev/null
+++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.cpp
@@ -0,0 +1,559 @@
+#include "ClientPlatformSpecific.hpp"
+
+// signal types
+#include
+// std::filesystem
+#include
+// std::*fstream
+#include
+// CoreSdk_ShutDown
+#include "ManusSDK.h"
+// std::map
+#include