From 4c56019ddc6c7f9081fd0adee617ab223f137e74 Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Thu, 3 Sep 2026 09:54:52 +0700 Subject: [PATCH] test(eval): them check_tilt_tf - kiem TF tai runtime Kiem dung nhung gia dinh ma kiem tra tinh (xacro, bien dich) khong cham toi: 1. Moi canh tren doan base_footprint..base_link co DUNG MOT nguon phat. Hai nguon cung phat mot canh la loi kho truy nhat: TF khong bao gi ca, no chi cho ket qua nhay lung tung. 2. Do nghieng trong TF co bam theo IMU khong. 3. Chuoi TF con lien khong. Tu nhan dien topology nen dung duoc cho ca hai che do: mot canh tinh (use_sim=true) hay hai canh dong (use_sim=false). --fake-imu ROLL PITCH bom IMU dung yen o do nghieng cho truoc, nho vay kiem duoc nhanh phan cung MA KHONG CAN phan cung. Cong thuc da kiem chung vong kin tren 6 ca, |a| dung 9.80665 nen qua duoc accel_gate. Chinh bo kiem nay da bat duoc that bai cua cach lam floating truoc do. --- src/slam_eval/CMakeLists.txt | 1 + src/slam_eval/scripts/check_tilt_tf.py | 252 +++++++++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100755 src/slam_eval/scripts/check_tilt_tf.py diff --git a/src/slam_eval/CMakeLists.txt b/src/slam_eval/CMakeLists.txt index b65f093..bccb091 100644 --- a/src/slam_eval/CMakeLists.txt +++ b/src/slam_eval/CMakeLists.txt @@ -10,6 +10,7 @@ catkin_install_python(PROGRAMS scripts/repeatability.py scripts/resource_profile.py scripts/watch_loc.py + scripts/check_tilt_tf.py DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) diff --git a/src/slam_eval/scripts/check_tilt_tf.py b/src/slam_eval/scripts/check_tilt_tf.py new file mode 100755 index 0000000..255774e --- /dev/null +++ b/src/slam_eval/scripts/check_tilt_tf.py @@ -0,0 +1,252 @@ +#!/usr/bin/env python3 +""" +check_tilt_tf - Kiem chung TAI RUNTIME viec dua do nghieng vao TF. + +Chay SAU khi da launch voi tilt_in_tf:=true. Kiem dung nhung gia dinh ma +kiem tra tinh (xacro, bien dich) KHONG the tra loi: + + 1. Canh base_footprint -> base_link co ton tai khong + 2. Co DUNG MOT node phat canh do khong + ⚠️ Neu robot_state_publisher van phat (khop khong thanh floating) thi + se co HAI nguon tranh nhau. TF khong bao loi - no chi cho ket qua + nhay lung tung. Day la loai loi kho truy nhat. + 3. Do nghieng trong TF co KHOP voi IMU khong + 4. Chuoi map -> odom -> base_footprint -> base_link -> laser_link con lien + 5. gravity_align co con ra cloud khong (bat khi chay kem perception) + +Dung: + rosrun slam_eval check_tilt_tf.py + rosrun slam_eval check_tilt_tf.py --expect-tilt # khi tilt_in_tf:=true +""" + +import argparse +import math +import sys +from collections import Counter + +import rospy +import tf2_ros +from sensor_msgs.msg import Imu, LaserScan, PointCloud2 +from tf2_msgs.msg import TFMessage + + +def rpy(q): + sr = 2.0 * (q.w * q.x + q.y * q.z) + cr = 1.0 - 2.0 * (q.x * q.x + q.y * q.y) + sp = max(-1.0, min(1.0, 2.0 * (q.w * q.y - q.z * q.x))) + return math.degrees(math.atan2(sr, cr)), math.degrees(math.asin(sp)) + + +class Check(object): + def __init__(self): + self.pubs = Counter() # ai phat canh base_footprint->base_link + self.imu = None + self.cloud = 0 + self.scan = 0 + # ⚠️ PHAI khoi tao TRUOC khi dang ky Subscriber. Callback co the chay + # ngay giua chung __init__ - da mac loi nay: on_tf_static ban vao + # static_edges khi no chua ton tai -> AttributeError moi ban tin. + self.static_edges = set() + rospy.Subscriber('/tf', TFMessage, self.on_tf, queue_size=200) + rospy.Subscriber('/tf_static', TFMessage, self.on_tf_static, queue_size=50) + rospy.Subscriber('/imu/data_raw', Imu, lambda m: setattr(self, 'imu', m)) + rospy.Subscriber('/perception/cloud_aligned', PointCloud2, + lambda m: setattr(self, 'cloud', self.cloud + 1)) + rospy.Subscriber('/scan', LaserScan, + lambda m: setattr(self, 'scan', self.scan + 1)) + + # Cac frame nam tren doan base_footprint -> base_link. Topology doi theo + # use_sim nen KHONG dem theo mot cap co dinh: + # use_sim=true : base_footprint -> base_link (1 canh, tinh) + # use_sim=false : base_footprint -> base_roll_link -> base_link (2 canh, dong) + CHAIN = ('base_footprint', 'base_roll_link', 'base_link') + + def _count(self, msg, tag): + for t in msg.transforms: + par = t.header.frame_id.lstrip('/') + ch = t.child_frame_id.lstrip('/') + if par in self.CHAIN and ch in self.CHAIN: + self.pubs[(par, ch, tag)] += 1 + + def on_tf(self, msg): + self._count(msg, '/tf (dong)') + + def on_tf_static(self, msg): + self._count(msg, '/tf_static (tinh)') + for t in msg.transforms: + self.static_edges.add((t.header.frame_id, t.child_frame_id)) + + +def _start_fake_imu(roll, pitch): + """Bom IMU dung yen o mot do nghieng cho truoc. + + Accelerometer khi DUNG YEN chi do TRONG LUC, chieu nguoc lai trong he cua + no. Nghieng (roll, pitch) thi vector g trong he IMU la: + ax = -g*sin(pitch) + ay = g*sin(roll)*cos(pitch) + az = g*cos(roll)*cos(pitch) + Chuan hoa ve dung 9.80665 de qua duoc cong accel_gate cua base_tilt_tf. + """ + g = 9.80665 + ax = -g * math.sin(pitch) + ay = g * math.sin(roll) * math.cos(pitch) + az = g * math.cos(roll) * math.cos(pitch) + pub = rospy.Publisher('/imu/data_raw', Imu, queue_size=10) + + def tick(_evt): + # Timer chay tren thread rieng va con song sau khi rospy da shutdown + # -> publish() se nem "publish() to a closed topic". Chan o day. + if rospy.is_shutdown(): + return + m = Imu() + m.header.stamp = rospy.Time.now() + m.header.frame_id = 'imu_link' + m.linear_acceleration.x = ax + m.linear_acceleration.y = ay + m.linear_acceleration.z = az + # gyro = 0: dung yen, de bo loc bu chi con phan accel keo ve + try: + pub.publish(m) + except rospy.ROSException: + pass + + return rospy.Timer(rospy.Duration(1.0 / 200.0), tick) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--expect-tilt', action='store_true', + help='dat khi chay nhanh phan cung (use_sim:=false)') + ap.add_argument('--fake-imu', nargs=2, type=float, metavar=('ROLL', 'PITCH'), + help='bom IMU gia voi do nghieng cho truoc (do). Dung de ' + 'kiem nhanh phan cung MA KHONG CAN phan cung: neu TF ' + 'bam theo con so nay thi duong day da thong.') + ap.add_argument('--secs', type=float, default=12.0) + a, _ = ap.parse_known_args() + + rospy.init_node('check_tilt_tf', anonymous=True, disable_signals=True) + c = Check() + buf = tf2_ros.Buffer() + tf2_ros.TransformListener(buf) + + fake = None + if a.fake_imu: + fake = _start_fake_imu(math.radians(a.fake_imu[0]), + math.radians(a.fake_imu[1])) + print('bom IMU gia: roll %.2f° pitch %.2f°' % tuple(a.fake_imu)) + + print('thu thap %.0f s ...' % a.secs) + rospy.sleep(a.secs) + + fail = 0 + print('=' * 66) + + # ---- 1 + 2: ai phat canh base_footprint -> base_link ---- + print('1. CANH TF TREN DOAN base_footprint .. base_link') + if not c.pubs: + print(' KHONG CANH NAO -> cay TF DUT LAM DOI') + fail += 1 + # gom theo canh: moi canh phai co DUNG MOT nguon + per_edge = {} + for (par, ch, tag), n in c.pubs.items(): + per_edge.setdefault((par, ch), {})[tag] = n + for (par, ch), srcs in sorted(per_edge.items()): + detail = ', '.join('%s %d' % (t, n) for t, n in srcs.items()) + print(' %-16s -> %-16s %s' % (par, ch, detail)) + if len(srcs) > 1: + print(' HAI NGUON CUNG PHAT CANH NAY -> TF se nhay lung tung.') + print(' Nguyen nhan thuong gap: khop van la `fixed` nen') + print(' robot_state_publisher phat song song voi base_tilt_tf.') + fail += 1 + if per_edge: + n_edge = len(per_edge) + want = 2 if a.expect_tilt else 1 + ok = (n_edge == want) + print(' -> %d canh, moi canh mot nguon. Ky vong %d %s' + % (n_edge, want, + '(base_footprint -> base_roll_link -> base_link)' if a.expect_tilt + else '(base_footprint -> base_link)')) + if not ok: + fail += 1 + + # ---- 3: do nghieng trong TF co khop IMU khong ---- + print('\n2. DO NGHIENG TRONG TF vs IMU') + try: + tr = buf.lookup_transform('base_footprint', 'base_link', + rospy.Time(0), rospy.Duration(2.0)).transform + r, p = rpy(tr.rotation) + print(' TF : roll %7.3f° pitch %7.3f° z %.4f m' % (r, p, tr.translation.z)) + if c.imu: + acc = c.imu.linear_acceleration + n = math.sqrt(acc.x ** 2 + acc.y ** 2 + acc.z ** 2) + if n > 1e-3: + ri = math.degrees(math.atan2(acc.y, acc.z)) + pi_ = math.degrees(math.atan2(-acc.x, + math.sqrt(acc.y ** 2 + acc.z ** 2))) + print(' IMU : roll %7.3f° pitch %7.3f° (tho, 1 mau)' % (ri, pi_)) + d = max(abs(r - ri), abs(p - pi_)) + if a.expect_tilt and d > 3.0: + print(' Lech %.2f° - TF khong bam theo IMU.' % d) + fail += 1 + else: + print(' IMU : khong co du lieu') + if a.fake_imu: + want_r, want_p = a.fake_imu + d = max(abs(r - want_r), abs(p - want_p)) + print(' BOM: roll %7.3f° pitch %7.3f° -> lech %.3f°' + % (want_r, want_p, d)) + if d > 0.5: + print(' TF KHONG bam theo IMU bom vao. Duong day dut o dau do:') + print(' - ten khop trong base_tilt_tf.py co khop URDF khong') + print(' - base_tilt_tf.py co dang chay khong') + print(' - robot_state_publisher co nhan /joint_states khong') + fail += 1 + else: + print(' -> TF bam dung theo IMU. Duong day THONG.') + elif not a.expect_tilt and max(abs(r), abs(p)) > 0.01: + print(' Ky vong PHANG khi use_sim:=true, nhung TF co nghieng.') + fail += 1 + except Exception as e: + print(' KHONG TRA DUOC TF: %s' % e) + fail += 1 + + # ---- 4: chuoi TF con lien khong ---- + # --fake-imu = chay tren ban lam viec, chi co L0 (URDF + RSP + base_tilt_tf). + # Khong co LiDAR, khong co SLAM, nen map/odom/scan VANG LA DUNG. + bench = bool(a.fake_imu) + + print('\n3. CHUOI TF') + for src, dst, need in (('map', 'base_footprint', not bench), + ('odom', 'base_link', not bench), + ('base_footprint', 'laser_link', True), + ('base_footprint', 'camera_link', True)): + try: + buf.lookup_transform(src, dst, rospy.Time(0), rospy.Duration(1.0)) + print(' %-16s -> %-18s OK' % (src, dst)) + except Exception as e: + tag = 'DUT (%s)' % type(e).__name__ if need else 'vang - dung, L0 khong co SLAM' + print(' %-16s -> %-18s %s' % (src, dst, tag)) + if need: + fail += 1 + + # ---- 5: cam bien con chay khong ---- + print('\n4. LUONG DU LIEU (trong %.0f s)' % a.secs) + if bench: + print(' bo qua - L0 tren ban lam viec khong co LiDAR va perception') + else: + print(' /scan %5d' % c.scan) + print(' /perception/cloud_aligned %5d %s' + % (c.cloud, '' if c.cloud else '<- gravity_align im lang')) + if c.scan == 0: + fail += 1 + + print('=' * 66) + print('KET LUAN:', 'DAT' if fail == 0 else 'CHUA DAT - %d van de' % fail) + return 0 if fail == 0 else 1 + + +if __name__ == '__main__': + try: + sys.exit(main()) + except rospy.ROSInterruptException: + pass