File size: 6,232 Bytes
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Module 4 - Gripper & Physics Controller.



Owns the two parallel fingers and the physics-based grip-force model. The force

model reads real dynamics (mass, lateral friction) from the simulator and sizes

the clamp force from the minimum-friction-grasp condition, then clips it into

the Panda's hardware envelope [10 N, 140 N].

"""

import logging

import pybullet as pb

from . import config

logger = logging.getLogger(__name__)


class GripperController:
    """Drives the Panda fingers and computes a safe grasp force."""

    def __init__(self, robot_id,

                 finger_indices=None,

                 force_min=config.GRIP_FORCE_MIN,

                 force_max=config.GRIP_FORCE_MAX,

                 gravity=abs(config.GRAVITY)):
        self.robot_id = robot_id
        self.finger_indices = finger_indices or config.FINGER_JOINT_INDICES
        self.force_min = force_min
        self.force_max = force_max
        self.gravity = gravity
        self._constraint_id = None
        self._constrained_id = None

    # ------------------------------------------------------------------ #
    # Grasp-force model
    # ------------------------------------------------------------------ #
    @staticmethod
    def friction_grasp_force(mass, mu, gravity, accel=0.0,

                             safety_factor=2.0, n_contacts=2,

                             force_min=config.GRIP_FORCE_MIN,

                             force_max=config.GRIP_FORCE_MAX):
        """Minimum-friction grasp force, clamped to the hardware envelope.



            F_g = [m * (g + a) * Sf] / [n_contacts * mu]



        Robust to degenerate inputs: non-positive mass yields the floor force,

        and a (near-)frictionless contact is floored to avoid division blow-up

        (it simply saturates to ``force_max`` after clamping).

        """
        # Guard the divisor: a tiny positive floor keeps the math finite.
        mu_eff = max(float(mu), 1e-3)
        mass_eff = max(float(mass), 0.0)

        raw = (mass_eff * (gravity + accel) * safety_factor) / (n_contacts * mu_eff)

        # Clamp into [force_min, force_max]; never negative by construction.
        return float(min(max(raw, force_min), force_max))

    def calculate_optimal_force(self, object_id, accel=0.0, safety_factor=2.0):
        """Read mass + lateral friction from the sim and size the grip force."""
        dyn = pb.getDynamicsInfo(object_id, -1)
        mass = dyn[0]            # kg
        lateral_friction = dyn[1]
        return self.friction_grasp_force(
            mass, lateral_friction, self.gravity,
            accel=accel, safety_factor=safety_factor,
            force_min=self.force_min, force_max=self.force_max,
        )

    # ------------------------------------------------------------------ #
    # Low-level finger actuation
    # ------------------------------------------------------------------ #
    def _drive_fingers(self, target, force):
        for j in self.finger_indices:
            pb.setJointMotorControl2(
                self.robot_id, j, pb.POSITION_CONTROL,
                targetPosition=target, force=force,
            )

    def open(self, force=30.0):
        """Release any active grasp constraint, then open both fingers."""
        if self._constraint_id is not None:
            try:
                pb.removeConstraint(self._constraint_id)
            except Exception:
                pass
            self._constraint_id = None
            self._constrained_id = None
        self._drive_fingers(config.FINGER_OPEN, force)

    def close(self, force):
        """Close both fingers, driving toward closed with the given clamp force."""
        self._drive_fingers(config.FINGER_CLOSED, force)

    def grasp(self, object_id, accel=0.0):
        """Close fingers and attach object via a rigid constraint.



        Constraint-based grasping: the object is fixed to panda_hand in its

        current relative pose. This is robust to any object size/shape — the

        gripper visual closes but the hold is via the constraint, not friction.

        The returned force value is still physically-sized for logging.

        """
        force = self.calculate_optimal_force(object_id, accel=accel)
        self.close(force)

        # Compute object position in the hand's local frame
        hand_state = pb.getLinkState(self.robot_id, config.HAND_LINK_INDEX)
        hand_pos, hand_ori = hand_state[0], hand_state[1]
        obj_pos, obj_ori = pb.getBasePositionAndOrientation(object_id)
        inv_pos, inv_ori = pb.invertTransform(hand_pos, hand_ori)
        rel_pos, rel_ori = pb.multiplyTransforms(inv_pos, inv_ori, obj_pos, obj_ori)

        self._constraint_id = pb.createConstraint(
            parentBodyUniqueId=self.robot_id,
            parentLinkIndex=config.HAND_LINK_INDEX,
            childBodyUniqueId=object_id,
            childLinkIndex=-1,
            jointType=pb.JOINT_FIXED,
            jointAxis=[0, 0, 0],
            parentFramePosition=list(rel_pos),
            childFramePosition=[0, 0, 0],
            parentFrameOrientation=list(rel_ori),
            childFrameOrientation=[0, 0, 0, 1],
        )
        pb.changeConstraint(self._constraint_id, maxForce=500)
        self._constrained_id = object_id
        logger.debug(f"grasp object_id={object_id} force={force:.2f} N constraint={self._constraint_id}")
        return force

    # ------------------------------------------------------------------ #
    # State helpers
    # ------------------------------------------------------------------ #
    def finger_span(self):
        """Current total opening (sum of both finger positions, metres)."""
        return sum(pb.getJointState(self.robot_id, j)[0] for j in self.finger_indices)

    def is_holding(self, object_id, min_contacts=2):
        """True if the rigid grasp constraint for object_id is active."""
        holding = (self._constraint_id is not None and self._constrained_id == object_id)
        logger.debug(f"is_holding object_id={object_id} constraint={self._constraint_id} holding={holding}")
        return holding