armdoc 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
armdoc/__init__.py ADDED
File without changes
armdoc/baseline.py ADDED
@@ -0,0 +1,106 @@
1
+ """Per-robot baselines: learn what normal looks like on this robot, then flag deviations. Pure statistics, no ROS, no training data.
2
+
3
+ `learn` turns message arrival times into a rate (median messages per second) and a jitter (median absolute deviation of that count). `check` compares the recent rate with that baseline."""
4
+ import json
5
+ import statistics
6
+
7
+ MIN_SECONDS = 5 # whole seconds of data needed to trust a stream's baseline
8
+ DROP_RATIO = 0.5 # recent rate below this fraction of the baseline is a drop
9
+ SPIKE_RATIO = 2.0 # recent rate above this multiple is a spike
10
+ WINDOW_S = 6.0 # look-back used by `check`
11
+
12
+
13
+ def per_second_counts(times):
14
+ """Messages per whole second, full seconds only (the first and last are partial)."""
15
+ times = sorted(times)
16
+ if len(times) < 2:
17
+ return []
18
+ t0 = times[0]
19
+ counts = {}
20
+ for t in times:
21
+ counts[int(t - t0)] = counts.get(int(t - t0), 0) + 1
22
+ last = int(times[-1] - t0)
23
+ return [counts.get(i, 0) for i in range(1, last)]
24
+
25
+
26
+ def learn(arrivals):
27
+ """{stream: [times]} -> {stream: {'hz', 'jitter', 'n'}}. The rate is the median messages per second, so bursts of
28
+ messages in one instant (TF) and a few stalls do not skew it. Streams seen for too few seconds are left out."""
29
+ out = {}
30
+ for stream, times in arrivals.items():
31
+ c = per_second_counts(list(times))
32
+ if len(c) < MIN_SECONDS:
33
+ continue
34
+ med = statistics.median(c)
35
+ if med <= 0:
36
+ continue
37
+ mad = statistics.median(abs(x - med) for x in c)
38
+ out[stream] = {'hz': round(float(med), 3), 'jitter': round(float(mad), 3), 'n': len(times)}
39
+ return out
40
+
41
+
42
+ def recent_rate(times, now, window=WINDOW_S):
43
+ t = [x for x in times if now - x <= window]
44
+ if len(t) < 3:
45
+ return None
46
+ return (len(t) - 1) / (t[-1] - t[0]) if t[-1] > t[0] else None
47
+
48
+
49
+ def check(baseline, arrivals, now, window=WINDOW_S):
50
+ """Findings as (level, code, msg). A stream with no recent messages is not reported here: the stale checks own that."""
51
+ found = []
52
+ for stream, b in sorted(baseline.items()):
53
+ r = recent_rate(arrivals.get(stream, []), now, window)
54
+ if r is None:
55
+ continue
56
+ if r < b['hz'] * DROP_RATIO:
57
+ found.append(('WARN', 'RATE_DROP', f'{stream} runs at {r:.1f} Hz, this robot normally gives {b["hz"]:.1f} Hz '
58
+ f'({r / b["hz"]:.0%} of normal)'))
59
+ elif r > b['hz'] * SPIKE_RATIO:
60
+ found.append(('WARN', 'RATE_SPIKE', f'{stream} runs at {r:.1f} Hz, this robot normally gives {b["hz"]:.1f} Hz '
61
+ f'({r / b["hz"]:.1f}x normal)'))
62
+ return found
63
+
64
+
65
+ def parse_expect(items):
66
+ """['scan:10', 'odom=20'] -> {'scan': {'hz': 10.0, 'jitter': 0.0, 'n': 0}}: rates stated with --expect, used like a
67
+ learned baseline and overriding it for the same stream. Raises ValueError on a bad item."""
68
+ out = {}
69
+ for item in items or ():
70
+ name, sep, hz = item.replace('=', ':').rpartition(':')
71
+ if not sep or not name.strip().strip('/'):
72
+ raise ValueError(f'--expect wants STREAM:HZ (e.g. joint_states:50), got {item!r}')
73
+ try:
74
+ rate = float(hz)
75
+ except ValueError:
76
+ raise ValueError(f'--expect {item!r}: {hz!r} is not a number') from None
77
+ if rate <= 0:
78
+ raise ValueError(f'--expect {item!r}: rate must be > 0')
79
+ out[name.strip().strip('/')] = {'hz': rate, 'jitter': 0.0, 'n': 0}
80
+ return out
81
+
82
+
83
+ def save(baseline, path):
84
+ with open(path, 'w') as f:
85
+ json.dump({'version': 1, 'streams': baseline}, f, indent=2, sort_keys=True)
86
+
87
+
88
+ def load(path):
89
+ """Read a baseline file written by `save`. Raises ValueError with a readable message (never a bare traceback, and never
90
+ a malformed entry that only crashes later inside `check`) for a missing file, bad JSON, no `streams`, or an entry
91
+ without a positive numeric `hz`."""
92
+ try:
93
+ with open(path) as f:
94
+ data = json.load(f)
95
+ except OSError as e:
96
+ raise ValueError(f'cannot read baseline file {path!r}: {e.strerror or e}') from None
97
+ except ValueError as e:
98
+ raise ValueError(f'baseline file {path!r} is not valid JSON ({e}); re-create it with --learn') from None
99
+ streams = data.get('streams') if isinstance(data, dict) else None
100
+ if not isinstance(streams, dict):
101
+ raise ValueError(f'baseline file {path!r} has no "streams" object; re-create it with --learn')
102
+ for name, entry in streams.items():
103
+ hz = entry.get('hz') if isinstance(entry, dict) else None
104
+ if isinstance(hz, bool) or not isinstance(hz, (int, float)) or not hz > 0:
105
+ raise ValueError(f'baseline file {path!r}: stream {name!r} needs a positive numeric "hz", got {entry!r}')
106
+ return streams
armdoc/cli.py ADDED
@@ -0,0 +1,15 @@
1
+ """Console entry point: `armdoc report ...` needs no ROS; everything else runs the live doctor."""
2
+ import sys
3
+
4
+
5
+ def main(argv=None):
6
+ argv = sys.argv[1:] if argv is None else argv
7
+ if argv and argv[0] == "report":
8
+ from armdoc.report import main as report_main
9
+ return report_main(argv[1:])
10
+ from armdoc.doctor import main as doctor_main
11
+ return doctor_main(argv)
12
+
13
+
14
+ if __name__ == "__main__":
15
+ sys.exit(main())
armdoc/core.py ADDED
@@ -0,0 +1,384 @@
1
+ """ROS-free diagnosis logic for armdoc: turns a snapshot of an arm's state into findings."""
2
+ import math
3
+ import re
4
+ import xml.etree.ElementTree as ET
5
+ from collections import deque
6
+ from dataclasses import dataclass, field
7
+
8
+ ERROR, WARN = "ERROR", "WARN"
9
+
10
+ # /rosout lines worth naming: (regex on the message, finding code). Patterns follow the MoveIt 2 and
11
+ # joint_trajectory_controller sources; checked against the pattern text, not yet against a stack that emits them.
12
+ LOG_PATTERNS = (
13
+ (re.compile(r"unable to sample any valid states for goal tree|goal state is in collision|goal state .*invalid", re.I),
14
+ "LOG_PLAN_GOAL_INVALID"),
15
+ (re.compile(r"start state (appears to be )?in collision|start state .*(invalid|out of bounds)", re.I), "LOG_START_STATE_BAD"),
16
+ (re.compile(r"start point deviates from current robot state|trajectory.*deviates", re.I), "LOG_START_DEVIATES"),
17
+ (re.compile(r"unable to identify any set of controllers|no controller .*(found|available)|controller .* is not known", re.I),
18
+ "LOG_NO_CONTROLLER"),
19
+ (re.compile(r"action client not connected|timed out waiting for .*(action|controller)", re.I), "LOG_ACTION_NOT_CONNECTED"),
20
+ (re.compile(r"didn'?t receive(d)? robot state|failed to fetch current robot state|couldn'?t receive full current joint state", re.I),
21
+ "LOG_ROBOT_STATE_STALE"),
22
+ (re.compile(r"(goal|path)[ _]tolerance[ _]?(violat|failed)|aborted due to .*tolerance|tolerance violat", re.I), "LOG_TOLERANCE_VIOLATED"),
23
+ (re.compile(r"controller handle .* reports status (aborted|canceled|rejected)|trajectory execution .*(failed|aborted)", re.I),
24
+ "LOG_EXEC_ABORTED"),
25
+ )
26
+ LOG_NODES = ("move_group", "moveit", "controller_manager", "ros2_control_node", "controller") # substring of the logger name
27
+ LOG_WINDOW_S = 30.0
28
+
29
+
30
+ def classify_log(msg):
31
+ """Finding code for a /rosout message, or None."""
32
+ for rx, code in LOG_PATTERNS:
33
+ if rx.search(msg):
34
+ return code
35
+ return None
36
+
37
+
38
+ def log_from(name):
39
+ """True for a logger name that belongs to the arm stack (move_group, a controller, the controller manager)."""
40
+ low = (name or "").lower()
41
+ return any(n in low for n in LOG_NODES)
42
+
43
+
44
+ @dataclass
45
+ class Finding:
46
+ level: str
47
+ code: str
48
+ msg: str
49
+
50
+ def __str__(self):
51
+ return f"{self.level:5} [{self.code}] {self.msg}"
52
+
53
+
54
+ @dataclass
55
+ class Config:
56
+ stale: float = 2.0 # s without joint_states / state topic before it counts as dead
57
+ grace: float = 20.0 # s after start before missing things are errors
58
+ near_limit: float = 0.01 # fraction of the joint range that counts as "at the limit"
59
+ vel_margin: float = 1.05
60
+ effort_frac: float = 0.95
61
+ effort_time: float = 2.0
62
+ track_err: float = 0.05 # rad of trajectory tracking error
63
+ track_time: float = 3.0
64
+ stall_time: float = 5.0 # goal active this long with no joint motion
65
+ stall_dist: float = 0.005 # rad
66
+ abort_count: int = 3
67
+ abort_window: float = 30.0
68
+ noise_rad: float = 0.002 # estimated per-sample position noise (rad) that counts as noisy
69
+ noise_window: float = 1.0 # s of joint_states used for the noise estimate
70
+ noise_min_samples: int = 10
71
+ noise_max_dt: float = 0.05 # skip the noise check below 20 Hz: coarse sampling aliases real motion
72
+ lag_max: float = 0.5 # s between a joint_states header stamp and its arrival
73
+ lag_window: float = 2.0
74
+ moveit_abort_count: int = 1 # aborted /move_action goals inside moveit_window that raise MOVEIT_PLAN_FAILED
75
+ moveit_window: float = 30.0
76
+
77
+
78
+ @dataclass
79
+ class State:
80
+ t0: float = 0.0
81
+ joints: dict = field(default_factory=dict) # name -> (pos, vel, effort)
82
+ joint_t: float = None
83
+ limits: dict = field(default_factory=dict) # name -> dict(lower, upper, velocity, effort)
84
+ controllers: list = None # [(name, type, state)] or None if never answered
85
+ arm_joints: set = None # joints claimed by arm controllers; None = check all
86
+ cm_missing: bool = False
87
+ track: dict = field(default_factory=dict) # controller -> (t, max abs error)
88
+ track_bad_since: dict = field(default_factory=dict)
89
+ moveit_nodes: bool = None # None = not asked to check
90
+ goal_active_since: float = None
91
+ pos_hist: deque = field(default_factory=lambda: deque(maxlen=4000))
92
+ js_times: deque = field(default_factory=lambda: deque(maxlen=6000)) # /joint_states receive times, for baselines
93
+ logs: dict = field(default_factory=dict) # LOG_* code -> [last message, [times]]
94
+ baseline: dict = None # learned per-robot rates (baseline.py), or None
95
+ aborts: deque = field(default_factory=deque)
96
+ lag_hist: deque = field(default_factory=lambda: deque(maxlen=2000)) # (receive time, header-stamp lag in s)
97
+ moveit_aborts: deque = field(default_factory=deque) # receive times of aborted /move_action goals
98
+ planning_scene: bool = None # None = unknown; False = move_group is up but no scene is served
99
+ eff_sat_since: dict = field(default_factory=dict)
100
+ traj_action_pubs: dict = field(default_factory=dict) # trajectory controller -> publishers on its action status topic
101
+ moveit_ctrl_names: list = None # controller_names move_group was configured with (None = unknown)
102
+
103
+
104
+ def parse_limits(urdf_xml):
105
+ """Joint limits from a URDF string: {joint: {lower, upper, velocity, effort}} for non-fixed joints."""
106
+ out = {}
107
+ try:
108
+ root = ET.fromstring(urdf_xml)
109
+ except ET.ParseError:
110
+ return out
111
+ for j in root.iter("joint"):
112
+ lim = j.find("limit")
113
+ if j.get("type") in ("fixed", "floating", "planar") or lim is None:
114
+ continue
115
+ g = lambda k: float(lim.get(k)) if lim.get(k) not in (None, "") else None
116
+ out[j.get("name")] = dict(lower=g("lower"), upper=g("upper"), velocity=g("velocity"), effort=g("effort"),
117
+ continuous=j.get("type") == "continuous")
118
+ return out
119
+
120
+
121
+ def feed_log(s, msg, now):
122
+ code = classify_log(msg)
123
+ if code:
124
+ entry = s.logs.setdefault(code, [msg, deque(maxlen=200)])
125
+ entry[0] = msg
126
+ entry[1].append(now)
127
+
128
+
129
+ def feed_joints(s, now, names, pos, vel, eff, lag=None):
130
+ """Record one joint_states sample. `lag` is receive time minus header stamp in seconds, when known."""
131
+ s.joint_t = now
132
+ s.js_times.append(now)
133
+ if lag is not None and math.isfinite(lag):
134
+ s.lag_hist.append((now, lag))
135
+ for i, n in enumerate(names):
136
+ g = lambda a: a[i] if i < len(a) else float("nan")
137
+ s.joints[n] = (g(pos), g(vel), g(eff))
138
+ s.pos_hist.append((now, {n: s.joints[n][0] for n in names}))
139
+
140
+
141
+ def _moved(s, now, window):
142
+ """Largest joint displacement over the last `window` seconds."""
143
+ old = None
144
+ for t, p in s.pos_hist:
145
+ if t >= now - window:
146
+ old = p
147
+ break
148
+ if old is None or not s.pos_hist:
149
+ return None
150
+ cur = s.pos_hist[-1][1]
151
+ return max((abs(cur[n] - old[n]) for n in cur if n in old), default=0.0)
152
+
153
+
154
+ def estimate_noise(s, now, c, joints=None):
155
+ """Per-joint position noise (rad, one sigma) from the fourth difference over the last `noise_window` seconds.
156
+
157
+ For white noise of sigma e the fourth difference (1, -4, 6, -4, 1) has variance 70 e^2, while smooth motion (even a
158
+ fast acceleration) cancels out of it, so this separates jitter from movement. Samples are treated as evenly spaced.
159
+ Returns {} when there are too few samples or the stream is too slow (`noise_max_dt`).
160
+ """
161
+ win = [(t, p) for t, p in s.pos_hist if t >= now - c.noise_window]
162
+ if len(win) < max(c.noise_min_samples, 6):
163
+ return {}
164
+ dts = sorted(win[i + 1][0] - win[i][0] for i in range(len(win) - 1))
165
+ if not dts or dts[len(dts) // 2] > c.noise_max_dt:
166
+ return {}
167
+ out = {}
168
+ for n in win[-1][1]:
169
+ if joints is not None and n not in joints:
170
+ continue
171
+ xs = [p.get(n, math.nan) for _, p in win]
172
+ acc, k = 0.0, 0
173
+ for i in range(len(xs) - 4):
174
+ a, b, d, e, g = xs[i:i + 5]
175
+ if not all(math.isfinite(v) for v in (a, b, d, e, g)):
176
+ continue
177
+ h = a - 4 * b + 6 * d - 4 * e + g
178
+ acc += h * h
179
+ k += 1
180
+ if k >= 5:
181
+ out[n] = math.sqrt(acc / k / 70.0)
182
+ return out
183
+
184
+
185
+ def is_arm_controller(name, typ):
186
+ """Controllers that drive arm joints (not broadcasters, not grippers)."""
187
+ if "broadcaster" in typ or "gripper" in name.lower() or "gripper" in typ.lower():
188
+ return False
189
+ return any(k in typ for k in ("trajectory", "effort", "position", "velocity", "impedance", "admittance"))
190
+
191
+
192
+ def looks_like_gripper(name):
193
+ n = name.lower()
194
+ return "gripper" in n or "finger" in n
195
+
196
+
197
+ def update_arm_joints(previous, claimed):
198
+ """Joints to check after a controller poll. An inactive controller claims no interfaces, so an empty `claimed`
199
+ keeps the last known set instead of widening the checks to every joint (which would judge gripper fingers resting
200
+ at their closed limit as arm joints). None until an arm controller has been seen active."""
201
+ return set(claimed) if claimed else previous
202
+
203
+
204
+ def evaluate(s, now, c=Config()):
205
+ f = []
206
+ up = now - s.t0
207
+ late = up > c.grace
208
+
209
+ if s.joint_t is None:
210
+ if late:
211
+ f.append(Finding(ERROR, "JOINT_STATES_NONE", "no /joint_states received (joint_state_broadcaster not running, or the sim is paused)"))
212
+ elif now - s.joint_t > c.stale:
213
+ f.append(Finding(ERROR, "JOINT_STATES_STALE", f"/joint_states silent for {now - s.joint_t:.1f}s "
214
+ "(controller manager or joint_state_broadcaster is down)"))
215
+
216
+ for code, (msg, times) in s.logs.items():
217
+ recent = [t for t in times if now - t <= LOG_WINDOW_S]
218
+ if recent:
219
+ f.append(Finding(WARN, code, f"{len(recent)}x in the last {LOG_WINDOW_S:.0f}s: {msg[:140]}"))
220
+
221
+ live = s.joint_t is not None and now - s.joint_t <= c.stale
222
+ if live and s.baseline:
223
+ from armdoc import baseline as bl
224
+ f.extend(Finding(lv, code, msg) for lv, code, msg in bl.check(s.baseline, {'joint_states': s.js_times}, now))
225
+ if live:
226
+ for n, (p, v, e) in s.joints.items():
227
+ if s.arm_joints is not None and n not in s.arm_joints:
228
+ continue
229
+ if not math.isfinite(p):
230
+ f.append(Finding(ERROR, "JOINT_NAN", f"{n} position is NaN/inf (diverged controller or bad state)"))
231
+ continue
232
+ lim = s.limits.get(n)
233
+ if not lim:
234
+ continue
235
+ lo, hi = lim.get("lower"), lim.get("upper")
236
+ if lo is not None and hi is not None and not lim.get("continuous") and hi > lo:
237
+ m = c.near_limit * (hi - lo)
238
+ if p < lo or p > hi:
239
+ f.append(Finding(ERROR, "LIMIT_POS", f"{n} at {p:.3f} is outside its limits [{lo:.3f}, {hi:.3f}]"))
240
+ elif (p < lo + m or p > hi - m) and not (s.arm_joints is None and looks_like_gripper(n)):
241
+ # arm joints not learned yet (e.g. attached while the arm controller was down): a gripper
242
+ # resting at its closed limit is normal, not a planning hazard
243
+ f.append(Finding(WARN, "NEAR_LIMIT", f"{n} at {p:.3f} is within {c.near_limit:.0%} of its "
244
+ f"limit [{lo:.3f}, {hi:.3f}]; planners often fail here"))
245
+ if lim.get("velocity") and math.isfinite(v) and abs(v) > lim["velocity"] * c.vel_margin:
246
+ f.append(Finding(WARN, "LIMIT_VEL", f"{n} moving at {v:.2f} rad/s, limit {lim['velocity']:.2f}"))
247
+ em = lim.get("effort")
248
+ if em and math.isfinite(e) and abs(e) >= c.effort_frac * em:
249
+ t0 = s.eff_sat_since.setdefault(n, now)
250
+ if now - t0 >= c.effort_time:
251
+ f.append(Finding(WARN, "EFFORT_SAT", f"{n} pinned at {abs(e):.1f} of {em:.1f} N*m for "
252
+ f"{now - t0:.0f}s (blocked by contact, or payload too heavy)"))
253
+ else:
254
+ s.eff_sat_since.pop(n, None)
255
+
256
+ if live:
257
+ noisy = {n: v for n, v in estimate_noise(s, now, c, s.arm_joints).items() if v > c.noise_rad}
258
+ if noisy:
259
+ n, v = max(noisy.items(), key=lambda kv: kv[1])
260
+ more = f" (and {len(noisy) - 1} more)" if len(noisy) > 1 else ""
261
+ f.append(Finding(WARN, "NOISY_JOINTS", f"{n} position jitter is about {v:.4f} rad{more}, above "
262
+ f"{c.noise_rad:g} rad (encoder or driver noise, or a loose connection)"))
263
+ recent = sorted(l for t, l in s.lag_hist if t >= now - c.lag_window)
264
+ if len(recent) >= 3 and recent[len(recent) // 2] > c.lag_max:
265
+ f.append(Finding(WARN, "STREAM_LAG", f"/joint_states arrive {recent[len(recent) // 2]:.2f}s after their "
266
+ f"header stamp (limit {c.lag_max:g}s): controllers and planners see old data"))
267
+
268
+ if s.cm_missing:
269
+ if late:
270
+ f.append(Finding(WARN, "NO_CONTROLLER_MANAGER", "/controller_manager/list_controllers is not answering"))
271
+ elif s.controllers is not None:
272
+ arm = [x for x in s.controllers if is_arm_controller(x[0], x[1])]
273
+ for name, typ, st in s.controllers:
274
+ if st != "active" and name in [a[0] for a in arm] and late:
275
+ f.append(Finding(ERROR, "CTRL_INACTIVE", f"controller {name} ({typ}) is {st}, not active"))
276
+ if arm and not any(x[2] == "active" for x in arm) and late:
277
+ f.append(Finding(ERROR, "NO_ACTIVE_ARM_CTRL", "no arm controller is active, so nothing can move the arm"))
278
+
279
+ if s.controllers is not None and late:
280
+ active_traj = [n for n, t, st in s.controllers if st == "active" and "joint_trajectory" in t]
281
+ for name in active_traj:
282
+ if s.traj_action_pubs.get(name) == 0:
283
+ f.append(Finding(ERROR, "NO_TRAJ_ACTION", f"controller {name} is active but its follow_joint_trajectory "
284
+ "action server is not on the graph; MoveIt reports 'Action client not connected'"))
285
+ if s.moveit_ctrl_names:
286
+ known = {n for n, _, _ in s.controllers}
287
+ missing = [n for n in s.moveit_ctrl_names if n not in known]
288
+ if missing:
289
+ f.append(Finding(ERROR, "MOVEIT_CTRL_MISMATCH", f"move_group is configured for controller(s) {missing} "
290
+ f"that ros2_control does not have (it has {sorted(known)}); MoveIt cannot execute"))
291
+
292
+ if s.moveit_nodes is False and late:
293
+ f.append(Finding(ERROR, "NO_MOVE_GROUP", "no move_group node on the graph; MoveIt requests will time out"))
294
+
295
+ if s.moveit_nodes is not None:
296
+ while s.moveit_aborts and now - s.moveit_aborts[0] > c.moveit_window:
297
+ s.moveit_aborts.popleft()
298
+ if len(s.moveit_aborts) >= c.moveit_abort_count:
299
+ f.append(Finding(WARN, "MOVEIT_PLAN_FAILED", f"{len(s.moveit_aborts)} MoveIt request(s) aborted in the "
300
+ f"last {c.moveit_window:.0f}s (planning or execution failed)"))
301
+ if s.moveit_nodes and s.planning_scene is False and late:
302
+ f.append(Finding(WARN, "NO_PLANNING_SCENE", "move_group is running but no planning scene is being "
303
+ "published or served; planning requests will fail or see an empty world"))
304
+
305
+ for ctrl, (t, err) in s.track.items():
306
+ if now - t > c.stale:
307
+ continue
308
+ if err > c.track_err:
309
+ t0 = s.track_bad_since.setdefault(ctrl, now)
310
+ if now - t0 >= c.track_time:
311
+ f.append(Finding(WARN, "TRACKING_ERROR", f"{ctrl} tracking error {err:.3f} rad for {now - t0:.0f}s "
312
+ "(gains too low, a collision, or the commanded path is too fast)"))
313
+ else:
314
+ s.track_bad_since.pop(ctrl, None)
315
+
316
+ if s.goal_active_since is not None and now - s.goal_active_since >= c.stall_time:
317
+ mv = _moved(s, now, c.stall_time)
318
+ if mv is not None and mv < c.stall_dist:
319
+ f.append(Finding(ERROR, "TRAJ_STALLED", f"a trajectory goal has been active for "
320
+ f"{now - s.goal_active_since:.0f}s but the joints moved {mv:.4f} rad"))
321
+
322
+ while s.aborts and now - s.aborts[0] > c.abort_window:
323
+ s.aborts.popleft()
324
+ if len(s.aborts) >= c.abort_count:
325
+ f.append(Finding(WARN, "GOAL_ABORTS", f"{len(s.aborts)} trajectory goals aborted or cancelled in "
326
+ f"{c.abort_window:.0f}s (check limits, collisions and controller tolerances)"))
327
+ return f
328
+
329
+
330
+ HINTS = {
331
+ "LOG_PLAN_GOAL_INVALID": "MoveIt cannot sample a valid goal: the target pose is in collision, out of reach or outside joint limits; try another pose, check the planning scene and the IK solver settings",
332
+ "LOG_START_STATE_BAD": "the planning start state is in collision or out of bounds: the arm is touching something in the scene, or joint_states disagrees with the model; check the planning scene and the joint limits",
333
+ "LOG_START_DEVIATES": "the trajectory starts away from where the arm really is: stale joint_states, a controller that moved after planning, or too tight allowed_start_tolerance; re-plan, or check the joint_states rate",
334
+ "LOG_NO_CONTROLLER": "move_group has no controller for the planned joints: compare moveit_controllers.yaml joint lists with the ros2_control controllers (armdoc also flags MOVEIT_CTRL_MISMATCH)",
335
+ "LOG_ACTION_NOT_CONNECTED": "move_group cannot reach the controller's follow_joint_trajectory action: the controller is inactive or named differently from moveit_controllers.yaml; `ros2 control list_controllers`, `ros2 action list`",
336
+ "LOG_ROBOT_STATE_STALE": "move_group is not getting fresh joint_states: the broadcaster is down, a clock mismatch (use_sim_time), or a remapped topic",
337
+ "LOG_TOLERANCE_VIOLATED": "the arm did not follow the trajectory within tolerance: too tight path or goal tolerances, a slow or saturated joint, or load; loosen constraints.*_tolerance or slow the trajectory",
338
+ "LOG_EXEC_ABORTED": "the controller aborted or rejected the trajectory: read the joint_trajectory_controller log just before this line (tolerance, invalid start, or an inactive state)",
339
+ "RATE_DROP": "/joint_states is much slower than this arm's learned normal: check CPU load, the controller manager update rate or a throttled bridge; re-learn with --learn if the change is intended",
340
+ "RATE_SPIKE": "/joint_states is much faster than this arm's learned normal: a duplicate publisher or a changed update_rate; re-learn with --learn if intended",
341
+ "JOINT_STATES_NONE": "start joint_state_broadcaster (ros2 control load_controller --set-state active joint_state_broadcaster)",
342
+ "JOINT_STATES_STALE": "check the controller manager and that the simulator is not paused",
343
+ "JOINT_NAN": "restart the controller; lower gains or the control period if it diverged",
344
+ "NEAR_LIMIT": "move the arm away from the joint limit before planning",
345
+ "LIMIT_POS": "the arm is outside its URDF limits; reset the joint or widen the limit",
346
+ "LIMIT_VEL": "slow the trajectory (velocity scaling) or raise the URDF velocity limit",
347
+ "EFFORT_SAT": "something is blocking the joint, or the payload is too heavy",
348
+ "NO_CONTROLLER_MANAGER": "start ros2_control_node, or pass --ns for a namespaced arm",
349
+ "CTRL_INACTIVE": "ros2 control set_controller_state <name> active",
350
+ "NO_ACTIVE_ARM_CTRL": "activate an arm controller (ros2 control list_controllers shows the state)",
351
+ "NO_MOVE_GROUP": "launch move_group, or drop --moveit",
352
+ "NO_TRAJ_ACTION": "the controller is active but did not create its action server: check its action_monitor / allow_partial_joints params and its log",
353
+ "MOVEIT_CTRL_MISMATCH": "make controller_names in moveit_controllers.yaml match `ros2 control list_controllers` exactly",
354
+ "TRACKING_ERROR": "raise controller gains, check for collisions, or slow the path",
355
+ "TRAJ_STALLED": "the controller accepted the goal but the joints do not move; check hardware or sim and the goal tolerances",
356
+ "NOISY_JOINTS": "check the encoder cable and driver; if the arm is fine, raise --noise-rad or filter the joint states",
357
+ "STREAM_LAG": "the driver or network is delaying joint states; check the CPU load, the DDS settings and the clock (use_sim_time)",
358
+ "MOVEIT_PLAN_FAILED": "ros2 topic echo /move_action/_action/status, then check the start state, limits and collisions in the planning scene",
359
+ "NO_PLANNING_SCENE": "check that move_group loaded its planning scene monitor (publish_planning_scene, robot_description_semantic)",
360
+ "GOAL_ABORTS": "check joint limits, collisions and goal_time / path tolerances in the controller config",
361
+ }
362
+
363
+
364
+ def verdict(findings):
365
+ """READY when nothing blocks motion; the second item names blocking codes and warnings."""
366
+ errors = [x.code for x in findings if x.level == ERROR]
367
+ warns = [x.code for x in findings if x.level == WARN]
368
+ return (not errors), errors, warns
369
+
370
+
371
+ def verdict_line(findings):
372
+ ok, errors, warns = verdict(findings)
373
+ if not ok:
374
+ return f"NOT READY - {len(errors)} blocking: {', '.join(errors)}"
375
+ return "READY" + (f" - {len(warns)} warning(s): {', '.join(warns)}" if warns else "")
376
+
377
+
378
+ def format_findings(findings, hints=False):
379
+ out = []
380
+ for x in findings:
381
+ out.append(str(x))
382
+ if hints and x.code in HINTS:
383
+ out.append(f" -> {HINTS[x.code]}")
384
+ return "\n".join(out) if out else "OK arm looks healthy"