119 lines
7.0 KiB
Python
119 lines
7.0 KiB
Python
"""端到端验证:命令右臂把【法兰参考点】移到某锚点目标点【正上方 clearance 米】悬停(不下板面、不碰桌)。
|
||
稳健做法:用全精度 IK(种子=当前关节)求目标关节角 → MoveJ(关节空间,避开笛卡尔奇异) → 慢速。姿态取当前(或绕z微调找可达)。
|
||
|
||
前提:臂已上使能;板别动。外部运行、可急停/掉使能。
|
||
用法:.venv/bin/python scripts/move_flange_to.py --capture data/real_align --corner 0 --clearance 0.10 --speed 0.3
|
||
"""
|
||
import argparse, json, time, threading
|
||
from pathlib import Path
|
||
import numpy as np, roslibpy
|
||
from scipy.spatial.transform import Rotation as Rot
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
|
||
|
||
def angle_diagnostics(current, target):
|
||
current, target = np.asarray(current, float), np.asarray(target, float)
|
||
if current.shape != (7,) or target.shape != (7,) or not np.isfinite([current, target]).all():
|
||
raise ValueError('需要7个有限关节角')
|
||
delta = target-current
|
||
nearest_delta = (delta+np.pi) % (2*np.pi)-np.pi
|
||
return delta, nearest_delta, np.flatnonzero(np.abs(delta-nearest_delta)>1e-6)
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--capture", default="data/real_align"); ap.add_argument("--corner", type=int, default=None)
|
||
ap.add_argument("--target", default=None, help="物体顶面基座坐标 x,y,z(逗号),悬停在其上方(替代 --corner)")
|
||
ap.add_argument("--clearance", type=float, default=0.10); ap.add_argument("--speed", type=float, default=0.3)
|
||
ap.add_argument("--accel", type=float, default=0.3); ap.add_argument("--host", default="192.168.10.21")
|
||
ap.add_argument("--port", type=int, default=9090); ap.add_argument("--yes", action="store_true")
|
||
ap.add_argument('--diagnose-only', action='store_true', help='只读状态/IK/FK,不发送运动')
|
||
a = ap.parse_args()
|
||
cam = json.loads((ROOT / a.capture / "camera.json").read_text())
|
||
d = np.array(cam["fingertip_offset_m"])
|
||
if a.target:
|
||
tb = np.array([float(x) for x in a.target.split(",")]) # 物体顶面基座坐标
|
||
else:
|
||
assert a.corner is not None, "给 --corner 或 --target"
|
||
T_bb = np.array(cam["T_base_board"]); objp = np.array(cam["board_objp"]); C, R_ = cam["board_grid"]; k = a.corner
|
||
assert k % C < C - 1 and k // C < R_ - 1, "该角点无右下方格,用 0~6/8~14/16~22/24~30"
|
||
tb = T_bb[:3, :3] @ ((objp[k + 1] + objp[k + C]) / 2) + T_bb[:3, 3]
|
||
hover = tb + np.array([0, 0, a.clearance])
|
||
|
||
ros = roslibpy.Ros(host=a.host, port=a.port); ros.run(timeout=8)
|
||
def call(s, t, arg):
|
||
sv = roslibpy.Service(ros, s, t); b = {}; ev = threading.Event()
|
||
sv.call(roslibpy.ServiceRequest(arg), lambda r: (b.update(r), ev.set()), lambda e: (b.update(err=str(e)), ev.set())); ev.wait(8); return b
|
||
box = {}; tp = roslibpy.Topic(ros, "/right/arm_state", "lbot_arm_interfaces/msg/ArmState"); tp.subscribe(lambda m: box.__setitem__("m", m))
|
||
t0 = time.time()
|
||
while "m" not in box and time.time() - t0 < 8:
|
||
time.sleep(0.1)
|
||
time.sleep(0.3)
|
||
if 'm' not in box:
|
||
tp.unsubscribe(); ros.terminate(); raise SystemExit('未收到状态,未发送运动')
|
||
m = box["m"]; q = m["pose"]["orientation"]; J = [float(x) for x in m["joint_state"]["position"]]
|
||
cur = np.array([m["pose"]["position"][c] for c in "xyz"])
|
||
R0 = Rot.from_quat([q["x"], q["y"], q["z"], q["w"]])
|
||
|
||
# 用当前姿态(不行就绕 z 微调)求 IK;种子=当前关节 → 解相近、MoveJ 路径平滑
|
||
sol = None
|
||
for dz in [0, -30, 30, -60, 60]:
|
||
R = R0 * Rot.from_euler("z", dz, degrees=True)
|
||
armtip = hover - R.as_matrix() @ d
|
||
fe = R.as_euler("xyz")
|
||
ik = call("/right/ik", "lbot_arm_interfaces/srv/InverseKinematics",
|
||
{"joints": J, "position": {"x": float(armtip[0]), "y": float(armtip[1]), "z": float(armtip[2])},
|
||
"euler": {"x": float(fe[0]), "y": float(fe[1]), "z": float(fe[2])}})
|
||
if ik.get("success"):
|
||
sol = (dz, [float(x) for x in ik["joints"]], armtip); break
|
||
if sol is None:
|
||
print("IK 全部失败——目标不可达(降低 clearance 或换 corner)"); tp.unsubscribe(); ros.terminate(); return
|
||
dz, Jt, armtip = sol
|
||
print(f"目标点(基座) = {tb.round(4).tolist()};标定触点悬停点 = {hover.round(4).tolist()}")
|
||
print(f"IK 成功(姿态绕z {dz}°);当前关节 {[round(x,3) for x in J]}")
|
||
print(f" 目标关节 {[round(x,3) for x in Jt]}")
|
||
try:
|
||
delta, nearest, wrapped = angle_diagnostics(J, Jt)
|
||
except ValueError as exc:
|
||
tp.unsubscribe(); ros.terminate(); raise SystemExit(str(exc))
|
||
if len(wrapped):
|
||
for index in wrapped:
|
||
print(f'J{index+1}: 数值位移{np.degrees(delta[index]):.2f}°,最近等价位移{np.degrees(nearest[index]):.2f}°')
|
||
print('角度圈数/物理限位尚未确认:不自动加减2π,也不沿整圈数值差插值。未发送运动。')
|
||
tp.unsubscribe(); ros.terminate(); return
|
||
# FK 逐点验证路径:不撞桌(x>0.15且z<-0.235)、不近左臂(y>0.12)
|
||
def fkp(Jx):
|
||
r = call("/right/fk", "lbot_arm_interfaces/srv/ForwardKinematics", {"joints": [float(x) for x in Jx]})
|
||
return np.array([r["position"][c] for c in "xyz"]) if r.get("success") else None
|
||
Ja, Jb = np.array(J), np.array(Jt); tbad, lbad = [], []
|
||
for s in np.linspace(0, 1, 13):
|
||
p = fkp((1 - s) * Ja + s * Jb)
|
||
if p is None:
|
||
print('FK查询失败,未发送运动'); tp.unsubscribe(); ros.terminate(); return
|
||
if p.shape != (3,) or not np.isfinite(p).all():
|
||
print('FK数据无效,未发送运动'); tp.unsubscribe(); ros.terminate(); return
|
||
if p[0] > 0.15 and p[2] < -0.235:
|
||
tbad.append((round(float(p[0]), 2), round(float(p[2]), 3)))
|
||
if p[1] > 0.12:
|
||
lbad.append(round(float(p[1]), 2))
|
||
if tbad or lbad:
|
||
print(f"旧阈值诊断警告:桌高采样{tbad}、侧向采样{lbad}。这些不是实际碰撞结论。")
|
||
print('缺少替代路径验收,本次仅输出诊断,不发送运动。')
|
||
tp.unsubscribe(); ros.terminate(); return
|
||
print('末端粗检未触发旧阈值;不代表整臂碰撞验证通过。')
|
||
if a.diagnose_only:
|
||
print('只读诊断结束,未发送运动'); tp.unsubscribe(); ros.terminate(); return
|
||
print(f"走 MoveJ 关节空间、speed={a.speed} rad/s、慢速。")
|
||
if not a.yes and input("确认发送 MoveJ?y 执行: ").strip().lower() != "y":
|
||
print("已取消"); tp.unsubscribe(); ros.terminate(); return
|
||
res = call("/right/movej", "lbot_arm_interfaces/srv/MoveJ",
|
||
{"joints": Jt, "speed": float(a.speed), "acce": float(a.accel), "block": False})
|
||
print("MoveJ 结果:", res)
|
||
print(f"请核对标定触点是否在目标 {a.corner if a.corner is not None else a.target} 正上方 {a.clearance*100:.0f}cm;服务回复不等于到位。")
|
||
tp.unsubscribe(); ros.terminate()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|