"""Reference controller for the TB-4 toolbox service cell. The toolbox is worked in its own frame (tracker pose, averaged), mapped into the arm's command space by two guarded touches with the closed fingertips on the lid top, which take out the mount height and tilt. The screwdriver is found standing in its caddy in the overhead camera (orange handle top) and taken along its axis from above. Each fastener: the blade is lowered into the countersink with the arm yielding sideways (the servo lead is fed back into the command), spun under a light push until it drops into the slot, then turned a quarter turn. The screwdriver goes back into its caddy, the lid is lifted by its handle sleeve along its arc past the over-centre point onto the stay, the part named on the work order is picked from its compartment (identified by colour and height in the camera) and set in the receiving tray (found in the camera), the lid is lowered shut along the same arc, the fasteners are turned back and the screwdriver is stood back in its caddy. Gripper and camera faults are checked at every grip change and before reporting done. """ import math import mujoco import numpy as np # ---- toolbox drawing (toolbox frame: x into the box, y left, z up; origin bottom centre of the front face) ---- LATCH_X, LATCH_Y = 0.035, {"left": 0.11, "right": -0.11} LID_TOP_Z = 0.215 MOUTH = 0.0104 # slot mouth below the lid top HINGE = np.array([0.222, 0.208]) SLEEVE = np.array([-0.042, 0.192]) COMPARTMENTS = ((0.11, 0.12), (0.11, 0.04), (0.11, -0.04), (0.11, -0.12)) INSERT_Z = 0.125 PART_H = {"relay": 0.052, "fuse_carrier": 0.056, "pressure_switch": 0.048, "prox_sensor": 0.060} PART_HALF_Y = {"relay": 0.015, "fuse_carrier": 0.018, "pressure_switch": 0.016, "prox_sensor": 0.010} PART_RGB = {"relay": (0.82, 0.82, 0.80), "fuse_carrier": (0.78, 0.16, 0.14), "pressure_switch": (0.16, 0.55, 0.24), "prox_sensor": (0.90, 0.78, 0.12)} LID_MID = (0.1100, -0.0002) # middle of the lid top's red outline seen from above (toolbox frame) CADDY_H = 0.095 # caddy top above the bench TOOL_SEAT = 0.0848 # handle rear end above the dock top when seated # ---- screwdriver ---- TOOL_TIP = 0.171 # blade tip from the handle's rear end TOOL_GRIP = 0.0 # finger command on the 19 mm groove: about 33 N of squeeze GRIP_AT = 0.029 # pads a little above the grip groove: closing, the upper chamfer lifts the tool into it # ---- hand ---- TIP = 0.0089 # closed fingertip end past the tcp KP = np.array([1125.0, 1125.0, 875.0, 875.0, 500.0, 500.0, 500.0]) CAM_POS = np.array([0.50, 0.0, 1.30]) Q_NOM = np.array([0.0, -0.3, 0.0, -2.2, 0.0, 2.0, 0.785]) NUL_W = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]) OPEN_TO_DEG = 97.0 # blade turn after it drops into the slot (opening, counter-clockwise from above) RELATCH_DEG = 86.0 # blade turn back (clockwise) LID_OPEN_DEG = 98.0 # past the over-centre point (91 deg); the lid settles on its stay LID_STAY_DEG = 100.0 class Abort(Exception): def __init__(self, fault): super().__init__(fault) self.fault = fault def Rh(approach, closing): z = np.asarray(approach, float); z = z / np.linalg.norm(z) y = np.asarray(closing, float); y = y - z * (y @ z); y = y / np.linalg.norm(y) return np.column_stack([np.cross(y, z), y, z]) def rot_about(axis, ang): q = np.zeros(4); mujoco.mju_axisAngle2Quat(q, np.asarray(axis, float), ang) R = np.zeros(9); mujoco.mju_quat2Mat(R, q); return R.reshape(3, 3) class Controller: CHECK_FAULTS = True ADMITTANCE = True SPIN_SEARCH = True RELATCH = True STOW = True REGISTER = True SPEED = 1.0 TURN_DEG = OPEN_TO_DEG CORRECT_OFFSET = False def __init__(self, model_info): self.info = model_info self.dt = float(model_info["control_dt_s"]) self.m = mujoco.MjModel.from_xml_path(model_info["scene_xml"]) self.kd = mujoco.MjData(self.m) self.md = mujoco.MjData(self.m) self.sid = self.m.site("robot/tcp").id self.nu = len(model_info["actuator_names"]) self.jlo = self.m.jnt_range[:7, 0] + 0.03 self.jhi = self.m.jnt_range[:7, 1] - 0.03 self.fa = [int(self.m.jnt_qposadr[self.m.joint(f"robot/finger_joint{i}").id]) for i in (1, 2)] cam = model_info["cameras"][0] self.IW, self.IH = cam["width"], cam["height"] self.f = (self.IH / 2) / math.tan(math.radians(cam["fovy_deg"]) / 2) # ------------------------------------------------------------------ interface def reset(self, obs): self.obs = obs self.q = np.array(obs["ctrl"][:7], float) self.grip = float(obs["ctrl"][7]) self.q_prev = self.q.copy() self.ff = False self.toolz = 0.0 self.Rc = np.eye(3) self.tc = np.zeros(3) self.readings = [] self.last_stamp = None self.stamp_age = 0 self.last_img = None self.noise_seen = False self.frozen = False self.repeats = 0 self.fast_stamps = 0 self.last_tcp = None self.log = [] self.holding = False self.tool_off = np.zeros(2) self.flat_yaw = 0.0 self.blade_world = math.pi / 2 self.latch_at = {} self.dz = self.box_dz = 0.0 self.trace = [] self._ingest(obs) self.gen = self._run() def act(self, obs): self.obs = obs self._ingest(obs) ph = getattr(self, "phase", "") if ph != getattr(self, "_last_phase", None): self._last_phase = ph self.trace.append((round(float(obs["time"]), 2), ph, np.round(self._pose()[0], 3).tolist(), round(self._fingers(), 4))) try: if self.CHECK_FAULTS and self.frozen: raise Abort("perception_freeze") return next(self.gen) except StopIteration: return {"status": "done"} except Abort as a: return {"status": "abort", "fault": a.fault} except Exception as e: # never raise into the cell: hold still, then report done self.log.append(("error", repr(e))) self.gen = self._hold_then_done() return self._cmd() def _hold_then_done(self): yield from self._hold(1.0) def _ingest(self, obs): if not hasattr(self, "fhist"): self.fhist = [] self.fhist.append(0.5 * float(obs["qpos"][7] + obs["qpos"][8])) del self.fhist[:-10] st = obs.get("camera_stamp") img = obs.get("images", {}).get("overhead") if st is None: return if self.last_stamp is None or st != self.last_stamp: if self.last_stamp is not None and self.stamp_age <= 2: self.fast_stamps += 1 # the camera runs at 1 Hz: a new stamp on consecutive ticks is a replay if self.fast_stamps >= 3: self.frozen = True else: self.fast_stamps = 0 self.last_stamp = st self.stamp_age = 0 if img is not None: tcp = self._pose()[0] if hasattr(self, "q") else None if self.last_img is not None and tcp is not None and self.last_tcp is not None: in_view = all(0.30 < p[0] < 0.75 and abs(p[1]) < 0.32 for p in (tcp, self.last_tcp)) if np.array_equal(img, self.last_img) and in_view and float(np.linalg.norm(tcp - self.last_tcp)) > 0.03: self.repeats += 1 # the arm moved in view but the picture did not change if self.repeats >= 2: self.frozen = True elif not np.array_equal(img, self.last_img): self.repeats = 0 self.last_img = img self.last_tcp = tcp pose = obs["objects"].get("toolbox") if pose is not None and len(self.readings) < 30: self.readings.append(np.array(pose, float)) self.stamp_age += 1 if self.stamp_age > 120: # no new frame for 2.4 s (the camera runs at 1 Hz, frames may be one late) self.frozen = True # ------------------------------------------------------------------ kinematics def _off(self): """Controlled point in the hand frame: toolz along the approach axis plus the tool's sideways offset.""" return np.array([self.tool_off[0], self.tool_off[1], self.toolz]) if self.toolz else np.array([0, 0, 0.0]) def _fk(self, data, q, toolz=None): data.qpos[:7] = q mujoco.mj_kinematics(self.m, data) mujoco.mj_comPos(self.m, data) R = data.site_xmat[self.sid].reshape(3, 3).copy() off = self._off() if toolz is None else np.array([0, 0, toolz]) return data.site_xpos[self.sid] + R @ off, R def _jac(self, data, R): jp = np.zeros((3, self.m.nv)); jr = np.zeros((3, self.m.nv)) mujoco.mj_jacSite(self.m, data, jp, jr, self.sid) r = R @ self._off() jp = jp[:, :7] - np.cross(r, jr[:, :7].T).T return jp, jr[:, :7] def _ik(self, pos, R, q0=None, iters=3, damp=2e-5): q = (self.q if q0 is None else q0).copy() for _ in range(iters): p, Rc = self._fk(self.kd, q) jp, jr = self._jac(self.kd, Rc) quat = np.zeros(4); er = np.zeros(3) mujoco.mju_mat2Quat(quat, (R @ Rc.T).flatten()) mujoco.mju_quat2Vel(er, quat, 1.0) e = np.concatenate([pos - p, er]) J = np.vstack([jp, jr]) Jp = J.T @ np.linalg.inv(J @ J.T + damp * np.eye(6)) dq = Jp @ e nul = (np.eye(7) - Jp @ J) @ (0.05 * (Q_NOM - q) * NUL_W) q = np.clip(q + np.clip(dq + nul, -0.08, 0.08), self.jlo, self.jhi) return q def _ik_full(self, pos, R, q0=None): """Converged IK from a seed (used to plan the end of a move); returns (q, error).""" q = self._ik(pos, R, q0, iters=60, damp=1e-4) p, Rc = self._fk(self.kd, q) quat = np.zeros(4); er = np.zeros(3) mujoco.mju_mat2Quat(quat, (R @ Rc.T).flatten()); mujoco.mju_quat2Vel(er, quat, 1.0) return q, float(np.linalg.norm(pos - p)) + 0.05 * float(np.linalg.norm(er)) def _sag(self, q): self.kd.qpos[:7] = q self.kd.qpos[self.fa] = self.grip self.kd.qvel[:] = 0 mujoco.mj_forward(self.m, self.kd) return q + (self.kd.qfrc_bias[:7] - self.kd.qfrc_gravcomp[:7]) / KP def _cmd(self): out = np.zeros(self.nu) out[:7] = self._sag(self.q) if self.ff: out[:7] += 0.2 * (self.q - self.q_prev) / self.dt self.q_prev = self.q.copy() out[7] = self.grip return out def _pose(self): return self._fk(self.kd, self.q) def _meas(self): q = np.asarray(self.obs["qpos"][:7], float) p, R = self._fk(self.md, q) jp, _ = self._jac(self.md, R) return p, jp @ np.asarray(self.obs["qvel"][:7], float) # ------------------------------------------------------------------ frames def W(self, p_tb): """Toolbox-frame point -> command space.""" return self.O + self.R @ np.asarray(p_tb, float) + np.array([0.0, 0.0, self.box_dz]) def Wd(self, d_tb): return self.R @ np.asarray(d_tb, float) def Wworld(self, p): return np.asarray(p, float) + np.array([0.0, 0.0, self.dz]) # ------------------------------------------------------------------ motion def _hold(self, seconds): for _ in range(max(1, round(seconds / self.dt))): yield self._cmd() def _move(self, pos, R, v=0.25, wmax=1.5, acc=1.0): """Straight line of the controlled point to `pos` with the hand turning to R (slerp).""" v = v * self.SPEED if getattr(self, "holding", False): v, acc, wmax = min(v, 0.20), min(acc, 0.5), min(wmax, 0.5) p0, R0 = self._pose() pos = np.asarray(pos, float) q0 = np.zeros(4); q1 = np.zeros(4) mujoco.mju_mat2Quat(q0, R0.flatten()); mujoco.mju_mat2Quat(q1, np.asarray(R, float).flatten()) if q0 @ q1 < 0: q1 = -q1 ang = 2 * math.acos(min(1.0, abs(float(q0 @ q1)))) dist = float(np.linalg.norm(pos - p0)) T = max(1.5 * dist / v, math.sqrt(6.0 * dist / acc) if dist > 0 else 0.0, 1.5 * ang / wmax, 3 * self.dt) if dist > 0.05 or ang > 0.3: # keep every joint under about 1.5 rad/s q_end, _ = self._ik_full(pos, np.asarray(R, float)) T = max(T, 1.6 * float(np.max(np.abs(q_end - self.q))) / 1.5) n = max(2, round(T / self.dt)) for k in range(1, n + 1): s = k / n s = s * s * (3 - 2 * s) qs = np.zeros(4) mujoco.mju_slerp(qs, q0, q1, s) if hasattr(mujoco, "mju_slerp") else None if not hasattr(mujoco, "mju_slerp"): qs = (1 - s) * q0 + s * q1 qs = qs / np.linalg.norm(qs) Rs = np.zeros(9); mujoco.mju_quat2Mat(Rs, qs) self.q = self._ik(p0 + s * (pos - p0), Rs.reshape(3, 3)) yield self._cmd() for _ in range(4): self.q = self._ik(pos, np.asarray(R, float)) yield self._cmd() def _joint_move(self, q_goal, wmax=1.2): q0 = self.q.copy() T = max(0.3, 1.6 * float(np.max(np.abs(q_goal - q0))) / (wmax * self.SPEED)) n = max(2, round(T / self.dt)) for k in range(1, n + 1): s = k / n s = s * s * (3 - 2 * s) self.q = q0 + s * (q_goal - q0) yield self._cmd() def _goto(self, pos, R, v=0.3, transit=0.50): """Lift to a transit height, cross over, come down: every leg a straight Cartesian line.""" p0, R0 = self._pose() pos = np.asarray(pos, float) if float(np.linalg.norm(pos[:2] - p0[:2])) > 0.06: zt = min(0.58, max(transit, p0[2], pos[2])) if p0[2] < zt - 0.005: yield from self._move(np.array([p0[0], p0[1], zt]), R0, v=v) yield from self._move(np.array([pos[0], pos[1], zt]), R, v=v) yield from self._move(pos, R, v=v) def _press(self, dvec, max_dist, v, R, cap=0.0025, settle=0.25, k_lat=0.3, max_lat=0.010): """Guarded, compliant move of the controlled point along dvec at speed v. Where the point really is comes from the joint velocities (integrated, so joint offsets and noise drop out); the command advances only while it leads the real point by less than `cap` along dvec, and follows the real point sideways (a wall or a countersink pushing the tool aside moves the command too). Stops when the point has stood still for `settle` seconds against the cap. Returns (hit, real point, command).""" dvec = np.asarray(dvec, float); dvec = dvec / np.linalg.norm(dvec) for _ in range(25): # let the arm settle on the command first _, vm = self._meas() if float(np.linalg.norm(vm)) < 0.001: break yield self._cmd() base = self._pose()[0] cmd, real, side = base.copy(), base.copy(), np.zeros(3) self.ff = True s, still, k = 0.0, 0, 0 hit, hist = False, [] while True: k += 1 _, vm = self._meas() real = real + vm * self.dt lead = cmd - real la = float(lead @ dvec) if k <= 12: la0 = la # lead in free motion (start offset and servo lag) la = la - la0 lat = (real - cmd) - dvec * float((real - cmd) @ dvec) side = side + k_lat * lat n = float(np.linalg.norm(side)) if n > max_lat: side = side * max_lat / n if la < cap: s += v * self.dt * min(1.0, k / 5.0) if s >= max_dist: break hist.append(side.copy()) lat_rest = len(hist) < 10 or float(np.linalg.norm(hist[-1] - hist[-10])) < 0.0002 if la > 0.7 * cap and float(np.linalg.norm(vm)) < 0.002 and lat_rest: still += 1 else: still = 0 if still * self.dt >= settle: hit = True break cmd = base + dvec * s + side self.q = self._ik(cmd, R) yield self._cmd() self.ff = False return hit, real, cmd # ------------------------------------------------------------------ job def _run(self): while len(self.readings) < 3: yield self._cmd() pose = np.mean(np.array(self.readings), axis=0) self.O = pose[:3].copy() Rm = np.zeros(9); mujoco.mju_quat2Mat(Rm, pose[3:7] / np.linalg.norm(pose[3:7])) self.R = Rm.reshape(3, 3) self.order = self.obs["io"]["work_order"] # camera registration: the lid top's edges in the image against the tracked toolbox pose give the camera's # mounting error (a shift of a few mm at bench height), taken out of every camera point after this self.cam_bias = np.zeros(3) edges = self._box_in_view() if edges is not None: mid = np.array([0.5 * (edges[0] + edges[1]) - LID_MID[0], 0.5 * (edges[2] + edges[3]) - LID_MID[1], 0.0]) if float(np.linalg.norm(mid)) < 0.025: self.cam_bias = self.R @ mid self.log.append(("camera shift mm", np.round(1000 * self.cam_bias, 1).tolist())) tool = self._find_tool() tray = self._find_tray() if tool is None: tool = yield from self._look_for_tool() self.dock = tool["centre"].copy() # the screwdriver's axis is the dock's bore (world xy) self.log.append(("dock mm", np.round(1000 * self.dock, 1).tolist())) yield from self._touch_handle() pose = np.mean(np.array(self.readings), axis=0) self.O = pose[:3].copy() # 1. screwdriver out of its dock, both fasteners open, screwdriver back yield from self._fetch_tool() yield from self._touch_lid() for side in ("left", "right"): yield from self._latch(side, +1) yield from self._stow_tool() # 2. lid onto its stay, part out, lid shut yield from self._lid(0.0, LID_OPEN_DEG) yield from self._part(tray) yield from self._lid(LID_STAY_DEG, 0.0) # 3. fasteners turned back, screwdriver back in its dock if self.RELATCH: yield from self._fetch_tool() for side in ("left", "right"): yield from self._latch(side, -1) if self.STOW: yield from self._stow_tool() yield from self._park() yield from self._grip_check() t_wait = 0 while t_wait < 1.1: # one more fresh camera frame before reporting done yield self._cmd() t_wait += self.dt def _fresh_frame(self): st0 = self.last_stamp while self.last_stamp == st0: yield self._cmd() def _look_for_tool(self): for _ in range(4): yield from self._clear_view() yield from self._fresh_frame() t = self._find_tool() if t is not None: return t raise Abort("tool_lost") # ---- height: one guarded touch with the closed fingertips on the screwdriver's handle top def _touch_handle(self): """Height of the screwdriver's handle top (and so of the bench) in the arm's frame: one light guarded touch with the closed fingertips.""" self.phase = "touch" yield from self._grip_to(0.0, 0.2) self.toolz = TIP c = self.dock R = self._down(self._grip_yaw()) yield from self._goto(np.array([c[0], c[1], CADDY_H + TOOL_SEAT + 0.026]), R, v=0.5) hit, cp, cm = yield from self._press((0, 0, -1), 0.05, 0.012, R, cap=0.0005, settle=0.12, k_lat=0.0) if not hit: raise Abort("tool_lost") self.top_z = float(cp[2]) self.dz = self.top_z - CADDY_H - TOOL_SEAT # bench height in the arm's frame self.box_dz = self.dz self.q = self._ik(cp + [0, 0, 0.004], R) yield from self._hold(0.1) self.toolz = 0.0 def _touch_lid(self): """Lid top height beside the left fastener: a light touch with the blade tip.""" self.phase = "touch_lid" R = self._pose()[1] pt = self.W((LATCH_X + 0.032, LATCH_Y["left"], LID_TOP_Z + 0.02)) yield from self._goto(pt, R, v=0.45, transit=0.42) hit, cp, cm = yield from self._press((0, 0, -1), 0.045, 0.012, R, cap=0.0005, settle=0.12, k_lat=0.0) if hit: self.box_dz = float(cp[2] - (self.O[2] + LID_TOP_Z)) yield from self._move(cp + [0, 0, 0.012], R, v=0.1) def _down(self, yaw): return Rh(np.array([0.0, 0, -1]), np.array([math.cos(yaw), math.sin(yaw), 0.0])) def _yaw_for_q7(self, pos, q7): seed = Q_NOM.copy() seed[0] = math.atan2(pos[1], pos[0]) q, _ = self._ik_full(pos, self._down(0.0), q0=seed) return float(q[6] - q7) def _grip_yaw(self): c = self.dock yaw = self._yaw_for_q7(np.array([c[0], c[1], 0.15]), -1.0) return self.flat_yaw + math.pi / 4 * round((yaw - self.flat_yaw) / (math.pi / 4)) # pads on two flats # ---- screwdriver def _fetch_tool(self): self.phase = "fetch_tool" self.toolz = 0.0 c = self.dock top = self.top_z grip = np.array([c[0], c[1], top - GRIP_AT]) R = self._down(self._grip_yaw()) again = getattr(self, "release", None) is not None if again: # take it back exactly where it was let go of grip, R = self.release p = self._pose()[0] if float(np.linalg.norm(p[:2] - grip[:2])) < 0.01 and p[2] < top + 0.03: yield from self._move(np.array([grip[0], grip[1], top + 0.012]), R, v=0.1) # straight up off the touch yield from self._grip_to(0.04, 0.2) yield from self._goto(grip + [0, 0, 0.045], R, v=0.45) yield from self._move(grip, R, v=0.08) fbias = self._fingers() - 0.04 # the open fingers stand at their stop yield from self._grip_to(TOOL_GRIP, 0.3) yield from self._hold(0.15) # the dock coupling locks 0.2 s after the pads close f = self._fingers() - fbias if not (0.005 < f < 0.016): raise Abort("dead_gripper" if f > 0.03 else "tool_lost") self.holding = True pc = self._pose()[0] self.grip_pose = (pc.copy(), R.copy()) # hand pose with the screwdriver seated (the coupling keeps it) if not again: self.tool_off = (R.T @ (np.array([c[0], c[1], pc[2]]) - pc))[:2] self.blade_rel = self.blade_world - self._yaw_now() grip_at = self.top_z - pc[2] # pads below the handle top (the tool stands seated) # out of the dock along its bore, yielding sideways so the blade follows the bore yield from self._press((0, 0, 1), 0.10, 0.05, R, cap=0.02, k_lat=0.3) yield from self._move(self._pose()[0] + [0, 0, 0.04], R, v=0.12) self.grip_at = grip_at self.toolz = TOOL_TIP - grip_at def _stow_tool(self): """Stand the screwdriver back in its dock. The coupling holds it exactly as it stood in the dock when it was taken, so the hand goes back to the pose it gripped in: above it first, then down on a slow guarded move that yields sideways. A move that stalls short of the seat (blade on the lead-in or the bore wall) backs off and comes in again on a small offset circle; the pads open only once the hand is at the seat height.""" self.phase = "stow_tool" gp, R = self.grip_pose self.toolz = 0.0 yield from self._goto(gp + np.array([0, 0, 0.10]), R, v=0.35, transit=0.45) yield from self._move(gp + np.array([0, 0, 0.025]), R, v=0.08) seated, cp = False, gp for k in range(6): ofs = np.zeros(3) if k == 0 else 0.0012 * np.array([math.cos(1.9 * k), math.sin(1.9 * k), 0.0]) start = gp + ofs + np.array([0, 0, 0.025]) if k: yield from self._move(self._pose()[0] + np.array([0, 0, 0.02]), R, v=0.05) yield from self._move(start, R, v=0.05) # stop at the first touch of the handle on its seat: no push into the cone hit, cp, cm = yield from self._press((0, 0, -1), 0.032, 0.015, R, cap=0.0008, settle=0.08, k_lat=0.1, max_lat=0.004) self.log.append(("stow", k, round(1000 * float(cp[2] - gp[2]), 1), hit)) if float(cp[2] - gp[2]) < 0.006: seated = True break # hover just clear of the seat and let go: the coupling opens in the dock and the screwdriver settles itself self.q = self._ik(np.array([cp[0], cp[1], float(cp[2]) + 0.0012]), R) yield from self._hold(0.1) self.release = (self._pose()[0] + np.array([0, 0, 0.0005]), R) self.flat_yaw = self._yaw_now() self.blade_world = self.flat_yaw + self.blade_rel yield from self._grip_to(0.03, 0.25) yield from self._hold(0.1) self.holding = False p = self._pose()[0] yield from self._move(p + [0, 0, 0.05], R, v=0.10) # ---- fastener def _yaw_now(self): Rn = self._pose()[1] return math.atan2(Rn[1, 1], Rn[0, 1]) def _spiral(self, mouth, cp, R): """Light push down while the command circles out from the axis (up to 5 mm): the blade finds the bore.""" c0 = cp.copy() hit, depth = False, float(self.W(mouth)[2] - cp[2]) for k in range(1, 161): a = 2 * math.pi * k / 40.0 r = 0.005 * k / 160.0 tgt = c0 + np.array([r * math.cos(a), r * math.sin(a), -0.002]) self.q = self._ik(tgt, R) yield self._cmd() if k % 10 == 0: pm = self._pose()[0] _, vm = self._meas() if k % 20 == 0: hit, cp2, cm = yield from self._press((0, 0, -1), 0.006, 0.01, R) depth = float(self.W(mouth)[2] - cp2[2]) if depth > MOUTH - 0.0005: return hit, cp2, depth c0 = c0 + np.array([0, 0, 0.0]) return hit, cp, depth def _slide(self, cp, yaw, push=0.0025, drop=0.0012, span=0.0035): """Blade resting on the fastener head beside the slot: slide it across the slot direction, either way, under a light push until it drops in (the screwdriver sits in the hand a mm or two off where it was first measured after it has been docked and taken again). Returns (found, real tip point).""" b = yaw + self.blade_rel across = np.array([-math.sin(b), math.cos(b), 0.0]) hold = cp - np.array([0, 0, push]) real, o = cp.copy(), 0.0 for tgt in (span, -span, 0.0): while abs(o - tgt) > 1e-7: o += max(-0.003 * self.dt, min(0.003 * self.dt, tgt - o)) self.q = self._ik(hold + across * o, self._down(yaw)) yield self._cmd() _, vm = self._meas() real = real + vm * self.dt if cp[2] - real[2] > drop: yield from self._hold(0.15) return True, real return False, cp def _seek(self, cp, yaw0, push=0.0025, drop=0.0012): """Blade resting on the fastener head: sweep the hand yaw a little either way under a light push until the blade drops into the slot (the real tip goes down by `drop`). Returns (found, yaw, real tip point).""" real = cp.copy() hold = cp - np.array([0, 0, push]) yaw = yaw0 for tdeg in (5, -5, 10, -10, 16, -16, 22, -22, 0): tgt = yaw0 + math.radians(tdeg) while abs(yaw - tgt) > 1e-4: step = math.radians(12.0) * self.dt yaw += max(-step, min(step, tgt - yaw)) self.q = self._ik(hold, self._down(yaw)) yield self._cmd() _, vm = self._meas() real = real + vm * self.dt if cp[2] - real[2] > drop: yield from self._hold(0.15) return True, yaw, real return False, yaw0, cp def _latch(self, side, direction): """direction +1: open (counter-clockwise seen from above), -1: close (clockwise).""" self.phase = f"latch_{side}_{direction}" self.toolz = TOOL_TIP - self.grip_at mouth = np.array([LATCH_X, LATCH_Y[side], LID_TOP_Z]) box_yaw = math.atan2(self.R[1, 0], self.R[0, 0]) a0 = 0.0 if direction > 0 else self.latch_at.get(side, math.radians(OPEN_TO_DEG - 8.0)) want = box_yaw + a0 - self.blade_rel # hand yaw that puts the blade along the slot (mod 180 deg) q7_aim = 1.25 if direction > 0 else -1.25 y_now, q7_now = self._yaw_now(), float(self.q[6]) best = None for k in range(-3, 4): y = want + k * math.pi q7 = q7_now - (y - y_now) if -2.7 < q7 < 2.7 and (best is None or abs(q7 - q7_aim) < abs(best[1] - q7_aim)): best = (y, q7) yaw0 = best[0] pre = self.W(mouth + [0, 0, 0.012]) yield from self._goto(pre + [0, 0, 0.03], self._down(yaw0), v=0.35, transit=0.42) yield from self._move(pre, self._down(yaw0), v=0.08) hit, cp, cm = yield from self._press((0, 0, -1), 0.04, 0.015, self._down(yaw0)) depth = float(self.W(mouth)[2] - cp[2]) if depth < MOUTH - 0.0012: # held up on the countersink wall: spiral down to the bore hit, cp, depth = yield from self._spiral(mouth, cp, self._down(yaw0)) yaw = yaw0 if depth < MOUTH + 0.0018: # blade on the head face, not in the slot found, cp = yield from self._slide(cp, yaw0) if not found: found, yaw, cp = yield from self._seek(cp, yaw0) self.log.append((side, direction, "seek", round(1000 * depth, 1), found, round(math.degrees(yaw - yaw0), 1))) depth = float(self.W(mouth)[2] - cp[2]) self.log.append((side, direction, "depth mm", round(1000 * depth, 1), hit)) if direction > 0 and depth > MOUTH + 0.0018: # the blade is in the slot (across it to 0.3 mm, along it to 1 mm in the bore): where the tip really is # corrects the screwdriver's offset in the hand, which came from the camera e = (self.W(mouth) - cp)[:2] if float(np.linalg.norm(e)) < 0.016: Rn = self._pose()[1] gain = 0.5 if getattr(self, "off_fixed", False) else 1.0 self.off_fixed = True self.tool_off = self.tool_off + gain * (Rn.T @ np.array([e[0], e[1], 0.0]))[:2] self.log.append((side, "offset fix mm", np.round(1000 * e, 1).tolist())) a_now = a0 + (yaw - yaw0) # blade angle from the box x axis (the slot follows it) hold_pt = cp - np.array([0, 0, 0.003]) # keep a light push on the blade while turning self.q = self._ik(hold_pt, self._down(yaw)) yield from self._hold(0.1) a_end = math.radians(OPEN_TO_DEG) if direction > 0 else 0.0 turn = a_end - a_now n = max(2, round(abs(turn) / math.radians(45) / self.dt)) real, sway = self._pose()[0].copy(), np.zeros(3) for k in range(1, n + 1): s = k / n s = s * s * (3 - 2 * s) # the hand turns about where it believes the tip is; where the slot holds the tip elsewhere, the arm yields # sideways to it (the controlled point follows its measured drift) instead of levering the blade _, vm = self._meas() real = real + vm * self.dt lat = real - (hold_pt + sway) lat[2] = 0.0 sway = sway + 0.15 * lat nn = float(np.linalg.norm(sway)) if nn > 0.003: sway = sway * 0.003 / nn self.q = self._ik(hold_pt + sway, self._down(yaw + s * turn)) yield self._cmd() hold_pt = hold_pt + sway yield from self._hold(0.3) # let the wrist catch up: the blade still bears on the slot back = direction * math.radians(7.0) # then turn back through the blade's play in the slot, so it n = round(0.3 / self.dt) # comes out free instead of dragging along a slot wall for k in range(1, n + 1): self.q = self._ik(hold_pt + np.array([0, 0, 0.0025 * k / n]), self._down(yaw + turn - back * k / n)) yield self._cmd() yield from self._hold(0.15) if direction > 0: self.latch_at[side] = a_end - back # the slot trails the blade by about its play yield from self._press((0, 0, 1), 0.03, 0.02, self._down(yaw + turn - back), cap=0.02, k_lat=0.05, max_lat=0.002) # ------------------------------------------------------------------ gripper def _fingers(self): h = self.fhist[-5:] if self.fhist else [0.5 * float(self.obs["qpos"][7] + self.obs["qpos"][8])] return float(np.mean(h)) def _grip_to(self, target, seconds=0.4, check=True): f0 = self._fingers() g0 = self.grip n = max(1, round(seconds / self.dt)) for k in range(1, n + 1): self.grip = g0 + (target - g0) * k / n yield self._cmd() yield from self._hold(0.2) f1 = self._fingers() if check and self.CHECK_FAULTS and abs(target - g0) > 0.006 and abs(f1 - f0) < 0.0015: raise Abort("dead_gripper") def _grip_check(self): """Before reporting done: the open fingers must follow a small close-and-open.""" if not self.CHECK_FAULTS: return g0 = self.grip f0 = self._fingers() yield from self._grip_to(g0 - 0.012, 0.25, check=False) f1 = self._fingers() if abs(f1 - f0) < 0.004: raise Abort("dead_gripper") yield from self._grip_to(g0, 0.25, check=False) # ------------------------------------------------------------------ camera def _cloud(self): img = self.obs["images"]["overhead"].astype(np.float32) dep = self.obs["depth"]["overhead"].astype(np.float32) v, u = np.mgrid[0:self.IH, 0:self.IW] D = dep bias = getattr(self, "cam_bias", np.zeros(3)) X = CAM_POS[0] - D * (v - (self.IH - 1) / 2) / self.f - bias[0] Y = CAM_POS[1] - D * (u - (self.IW - 1) / 2) / self.f - bias[1] Z = CAM_POS[2] - D return img, np.stack([X, Y, Z], -1), D > 0.05 def _box_in_view(self): """Lid top (red) in the camera, in the toolbox frame from the tracker: robust edges and centre.""" img, P, ok = self._cloud() r, g, b = img[..., 0], img[..., 1], img[..., 2] loc = (P - self.O) @ self.R near = (loc[..., 0] > -0.06) & (loc[..., 0] < 0.29) & (np.abs(loc[..., 1]) < 0.24) & (loc[..., 2] > 0.19) mask = ok & near & (r > 70) & (g < 0.30 * r) & (b < 0.30 * r) if mask.sum() < 200: return None L = loc[mask] return np.array([np.percentile(L[:, 0], 2), np.percentile(L[:, 0], 98), np.percentile(L[:, 1], 2), np.percentile(L[:, 1], 98)]) def _find_tray(self): img, P, ok = self._cloud() r, g, b = img[..., 0], img[..., 1], img[..., 2] mask = ok & (b > 60) & (b > 1.5 * r) & (b > 1.2 * g) & (P[..., 2] < 0.05) if mask.sum() < 10: return None pts = P[mask] return np.array([np.median(pts[:, 0]), np.median(pts[:, 1]), 0.0]) def _identify_parts(self): img, P, ok = self._cloud() out = {} for k, (cx, cy) in enumerate(COMPARTMENTS): loc = (P - self.O) @ self.R sel = ok & (np.abs(loc[..., 0] - cx) < 0.010) & (np.abs(loc[..., 1] - cy) < 0.010) & (loc[..., 2] > INSERT_Z + 0.03) if sel.sum() < 2: sel = ok & (np.abs(loc[..., 0] - cx) < 0.014) & (np.abs(loc[..., 1] - cy) < 0.014) & (loc[..., 2] > INSERT_Z + 0.02) if sel.sum() == 0: continue rgb = img[sel].mean(axis=0) / 255.0 h = float(np.median(loc[..., 2][sel])) - INSERT_Z best, bd = None, 1e9 for name, ref in PART_RGB.items(): ref = np.asarray(ref) # compare chromaticity (gain-free) and height d = float(np.linalg.norm(rgb / max(rgb.sum(), 1e-6) - ref / ref.sum())) + 2.0 * abs(h - PART_H[name]) if d < bd: best, bd = name, d out[k] = (best, round(bd, 3), round(h, 3)) return out def _find_tool(self): """Screwdriver standing in its caddy: top of the orange handle -> axis position (world) and top height.""" img, P, ok = self._cloud() r, g, b = img[..., 0], img[..., 1], img[..., 2] mask = ok & (r > 80) & (g > 0.22 * r) & (g < 0.75 * r) & (b < 0.35 * r) & (P[..., 2] > 0.12) loc = (P - self.O) @ self.R on_box = (loc[..., 0] > -0.03) & (loc[..., 0] < 0.25) & (loc[..., 1] > -0.20) & (loc[..., 1] < 0.20) mask = mask & ~on_box if mask.sum() < 4: return None pts = P[mask] c = np.median(pts, axis=0) pts = pts[np.linalg.norm(pts[:, :2] - c[:2], axis=1) < 0.025] if len(pts) < 4: return None top = float(np.percentile(pts[:, 2], 90)) pts = pts[pts[:, 2] > top - 0.005] # the handle's end face only (its sides lean in the view) return {"centre": np.array([pts[:, 0].mean(), pts[:, 1].mean(), top]), "n": int(len(pts))} # ---- lid def _sleeve_at(self, deg): th = math.radians(deg) v = SLEEVE - HINGE x = v[0] * math.cos(th) + v[1] * math.sin(th) z = -v[0] * math.sin(th) + v[1] * math.cos(th) return np.array([HINGE[0] + x, 0.0, HINGE[1] + z]) def _lid_R(self, deg): """Hand on the sleeve from above, fingers closing across it (the sleeve turns in its brackets).""" return Rh(self.Wd((0, 0, -1.0)), self.Wd((1.0, 0, 0))) def _lid(self, a0, a1): self.phase = f"lid_{a0:.0f}_{a1:.0f}" self.toolz = 0.0 R = self._lid_R(0) s0 = self.W(self._sleeve_at(a0)) up = self.Wd((0, 0, 1.0)) yield from self._grip_to(0.019, 0.2) # the inner finger goes between the sleeve and the lid front yield from self._goto(s0 + up * 0.08, R, v=0.4, transit=0.45) yield from self._move(s0, R, v=0.15) yield from self._grip_to(0.0, 0.25) n = max(2, round(abs(a1 - a0) / 20.0 / self.dt / self.SPEED)) self.ff = True for k in range(1, n + 1): s = k / n s = s * s * (3 - 2 * s) a = a0 + s * (a1 - a0) self.q = self._ik(self.W(self._sleeve_at(a)), R) yield self._cmd() self.ff = False yield from self._hold(0.2) yield from self._grip_to(0.019, 0.2) p = self._pose()[0] yield from self._move(p + up * 0.03, R, v=0.15) # fingers clear of the sleeve (arm near full reach) if a1 > a0: yield from self._move(self._pose()[0] + self.Wd((-0.10, 0, 0.0)), R, v=0.15) else: yield from self._move(self._pose()[0] + up * 0.05 + self.Wd((-0.04, 0, 0.0)), R, v=0.15) # ---- part def _part(self, tray): self.phase = "part" yield from self._clear_view() yield from self._fresh_frame() yield from self._fresh_frame() ids = self._identify_parts() self.parts_seen = ids self.log.append(("parts", ids)) name = self.order["part"] cands = [(v[1], kk) for kk, v in ids.items() if v[0] == name] if not cands: return k = min(cands)[1] if tray is None: tray = self._find_tray() cx, cy = COMPARTMENTS[k] h = PART_H[name] R = Rh((0, 0, -1), self.Wd((0, 1, 0))) # gripper housing across the box, clear of the open lid top = INSERT_Z + h # open only as wide as the part needs: at the outer compartments a wide-open finger meets the box side yield from self._grip_to(min(0.04, PART_HALF_Y[name] + 0.0115), 0.2) yield from self._goto(self.W((cx, cy, top + 0.10)), R, v=0.4) yield from self._move(self.W((cx, cy, top - 0.018)), R, v=0.12) yield from self._grip_to(0.0, 0.35) self.holding = True yield from self._move(self.W((cx, cy, top + 0.12)), R, v=0.15) if tray is None: return tp = self.Wworld((tray[0], tray[1], 0.006 + h - 0.018 + 0.003)) yield from self._goto(tp + [0, 0, 0.10], R, v=0.4) yield from self._move(tp, R, v=0.1) yield from self._grip_to(0.03, 0.3) self.holding = False yield from self._move(tp + [0, 0, 0.10], R, v=0.2) def _clear_view(self): yield from self._goto(self.Wworld((0.18, 0.12, 0.45)), Rh((0, 0, -1), (0, 1, 0)), v=0.45) def _park(self): self.phase = "park" yield from self._clear_view()