RemiFabre commited on
Commit
fe284fb
·
1 Parent(s): bc81b43

docs: expand module/class docstrings and add explanatory comments for design and loops

Browse files
src/reachy_mini_conversation_demo/moves.py CHANGED
@@ -1,9 +1,35 @@
1
- """Movement system with sequential primary moves and additive secondary moves.
2
-
3
- This module implements the movement architecture from main_works.py:
4
- - Primary moves (sequential): emotions, dances, goto, breathing
5
- - Secondary moves (additive): speech offsets + face tracking
6
- - Single set_target() control point with pose fusion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  """
8
 
9
  from __future__ import annotations
@@ -126,8 +152,9 @@ def combine_full_body(
126
  primary_head, primary_antennas, primary_body_yaw = primary_pose
127
  secondary_head, secondary_antennas, secondary_body_yaw = secondary_pose
128
 
129
- # Combine head poses using compose_world_offset
130
- # primary_head is T_abs, secondary_head is T_off_world
 
131
  combined_head = compose_world_offset(
132
  primary_head, secondary_head, reorthonormalize=True
133
  )
@@ -190,12 +217,26 @@ class MovementState:
190
 
191
 
192
  class MovementManager:
193
- """Enhanced movement manager that reproduces main_works.py behavior.
194
-
195
- - Sequential primary moves via queue
196
- - Additive secondary moves (speech + face tracking)
197
- - Single set_target control loop with pose fusion
198
- - Automatic breathing after inactivity
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  """
200
 
201
  def __init__(
@@ -272,17 +313,28 @@ class MovementManager:
272
  self._shared_is_listening = self._is_listening
273
 
274
  def queue_move(self, move: Move) -> None:
275
- """Add a move to the primary move queue."""
 
 
 
 
276
  self._command_queue.put(("queue_move", move))
277
 
278
  def clear_queue(self) -> None:
279
- """Clear all queued moves and stop current move."""
 
 
 
280
  self._command_queue.put(("clear_queue", None))
281
 
282
  def set_speech_offsets(
283
  self, offsets: Tuple[float, float, float, float, float, float]
284
  ) -> None:
285
- """Set speech head offsets (secondary move)."""
 
 
 
 
286
  with self._speech_offsets_lock:
287
  self._pending_speech_offsets = offsets
288
  self._speech_offsets_dirty = True
@@ -290,23 +342,30 @@ class MovementManager:
290
  def set_offsets(
291
  self, offsets: Tuple[float, float, float, float, float, float]
292
  ) -> None:
293
- """Compatibility alias for set_speech_offsets."""
294
  self.set_speech_offsets(offsets)
295
 
296
  def set_face_tracking_offsets(
297
  self, offsets: Tuple[float, float, float, float, float, float]
298
  ) -> None:
299
- """Set face tracking offsets (secondary move)."""
 
 
 
300
  with self._face_offsets_lock:
301
  self._pending_face_offsets = offsets
302
  self._face_offsets_dirty = True
303
 
304
  def set_moving_state(self, duration: float) -> None:
305
- """Set legacy moving state for goto moves."""
 
 
 
 
306
  self._command_queue.put(("set_moving_state", duration))
307
 
308
  def is_idle(self):
309
- """Check if the robot is idle based on inactivity delay."""
310
  with self._shared_state_lock:
311
  last_activity = self._shared_last_activity_time
312
  listening = self._shared_is_listening
@@ -319,11 +378,19 @@ class MovementManager:
319
  return time_since_activity >= self.idle_inactivity_delay
320
 
321
  def mark_user_activity(self) -> None:
322
- """Record recent user activity to delay idle behaviours."""
323
  self._command_queue.put(("mark_activity", None))
324
 
325
  def set_listening(self, listening: bool) -> None:
326
- """Toggle listening mode, freezing antennas when active."""
 
 
 
 
 
 
 
 
327
  with self._shared_state_lock:
328
  if self._shared_is_listening == listening:
329
  return
@@ -576,14 +643,14 @@ class MovementManager:
576
  self.state.face_tracking_offsets = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
577
 
578
  def start(self) -> None:
579
- """Start the move worker loop in a thread."""
580
  self._stop_event.clear()
581
  self._thread = threading.Thread(target=self.working_loop, daemon=True)
582
  self._thread.start()
583
  logger.info("Move worker started")
584
 
585
  def stop(self) -> None:
586
- """Stop the move worker loop."""
587
  self._stop_event.set()
588
  if self._thread is not None:
589
  self._thread.join()
@@ -623,26 +690,26 @@ class MovementManager:
623
  freq_min = min(freq_min, last_freq)
624
  prev_loop_start = loop_start
625
 
626
- # 1. Poll external signals and commands
627
  self._poll_signals(current_time)
628
 
629
- # 2. Sequential move management
630
  self._manage_move_queue(current_time)
631
 
632
- # 3. Automatic behaviours (breathing)
633
  self._manage_breathing(current_time)
634
 
635
- # 4. Update vision offsets
636
  self._update_face_tracking(current_time)
637
 
638
- # 5. Build pose snapshots
639
  primary_full_body_pose = self._get_primary_pose(current_time)
640
  secondary_full_body_pose = self._get_secondary_pose()
641
  global_full_body_pose = combine_full_body(
642
  primary_full_body_pose, secondary_full_body_pose
643
  )
644
 
645
- # 6. Blend listening state for antennas
646
  head, antennas, body_yaw = global_full_body_pose
647
  now_monotonic = self._now()
648
  listening = self._is_listening
@@ -676,7 +743,7 @@ class MovementManager:
676
  float(antennas[1]),
677
  )
678
 
679
- # 7. Single set_target call - the only control point
680
  try:
681
  self.current_robot.set_target(
682
  head=head, antennas=antennas_cmd, body_yaw=body_yaw
@@ -699,7 +766,7 @@ class MovementManager:
699
  (head, antennas_cmd, body_yaw)
700
  )
701
 
702
- # 8. Timing bookkeeping + adaptive sleep for 100Hz
703
  computation_time = self._now() - loop_start
704
  potential_freq = (
705
  1.0 / computation_time if computation_time > 0 else float("inf")
@@ -711,7 +778,7 @@ class MovementManager:
711
  if sleep_time > 0:
712
  time.sleep(sleep_time)
713
 
714
- # 9. Periodic telemetry
715
  if loop_count % print_interval_loops == 0 and freq_count > 0:
716
  variance = freq_m2 / freq_count if freq_count > 0 else 0.0
717
  lowest = freq_min if freq_min != float("inf") else 0.0
 
1
+ """
2
+ Movement system with sequential primary moves and additive secondary moves.
3
+
4
+ Design overview
5
+ - Primary moves (emotions, dances, goto, breathing) are mutually exclusive and run
6
+ sequentially.
7
+ - Secondary moves (speech sway, face tracking) are additive offsets applied on top
8
+ of the current primary pose.
9
+ - There is a single control point to the robot: `ReachyMini.set_target`.
10
+ - The control loop runs near 100 Hz and is phase-aligned via a monotonic clock.
11
+ - Idle behaviour starts an infinite `BreathingMove` after a short inactivity delay
12
+ unless listening is active.
13
+
14
+ Threading model
15
+ - A dedicated worker thread owns all real-time state and issues `set_target`
16
+ commands.
17
+ - Other threads communicate via a command queue (enqueue moves, mark activity,
18
+ toggle listening).
19
+ - Secondary offset producers set pending values guarded by locks; the worker
20
+ snaps them atomically.
21
+
22
+ Units and frames
23
+ - Secondary offsets are interpreted as metres for x/y/z and radians for
24
+ roll/pitch/yaw in the world frame (unless noted by `compose_world_offset`).
25
+ - Antennas and `body_yaw` are in radians.
26
+ - Head pose composition uses `compose_world_offset(primary_head, secondary_head)`;
27
+ the secondary offset must therefore be expressed in the world frame.
28
+
29
+ Safety
30
+ - Listening freezes antennas, then blends them back on unfreeze.
31
+ - Breathing is guarded to avoid duplicate enqueues.
32
+ - `set_target` errors are rate-limited in logs.
33
  """
34
 
35
  from __future__ import annotations
 
152
  primary_head, primary_antennas, primary_body_yaw = primary_pose
153
  secondary_head, secondary_antennas, secondary_body_yaw = secondary_pose
154
 
155
+ # Combine head poses using compose_world_offset; the secondary pose must be an
156
+ # offset expressed in the world frame (T_off_world) applied to the absolute
157
+ # primary transform (T_abs).
158
  combined_head = compose_world_offset(
159
  primary_head, secondary_head, reorthonormalize=True
160
  )
 
217
 
218
 
219
  class MovementManager:
220
+ """Coordinate sequential moves, additive offsets, and robot output at 100 Hz.
221
+
222
+ Responsibilities:
223
+ - Own a real-time loop that samples the current primary move (if any), fuses
224
+ secondary offsets, and calls `set_target` exactly once per tick.
225
+ - Start an idle `BreathingMove` after `idle_inactivity_delay` when not
226
+ listening and no moves are queued.
227
+ - Expose thread-safe APIs so other threads can enqueue moves, mark activity,
228
+ or feed secondary offsets without touching internal state.
229
+
230
+ Timing:
231
+ - All elapsed-time calculations rely on `time.monotonic()` through `self._now`
232
+ to avoid wall-clock jumps.
233
+ - The loop attempts 100 Hz by sleeping toward the next absolute tick to limit
234
+ drift.
235
+
236
+ Concurrency:
237
+ - External threads communicate via `_command_queue` messages.
238
+ - Secondary offsets are staged via dirty flags guarded by locks and consumed
239
+ atomically inside the worker loop.
240
  """
241
 
242
  def __init__(
 
313
  self._shared_is_listening = self._is_listening
314
 
315
  def queue_move(self, move: Move) -> None:
316
+ """Queue a primary move to run after the currently executing one.
317
+
318
+ Thread-safe: the move is enqueued via the worker command queue so the
319
+ control loop remains the sole mutator of movement state.
320
+ """
321
  self._command_queue.put(("queue_move", move))
322
 
323
  def clear_queue(self) -> None:
324
+ """Stop the active move and discard any queued primary moves.
325
+
326
+ Thread-safe: executed by the worker thread via the command queue.
327
+ """
328
  self._command_queue.put(("clear_queue", None))
329
 
330
  def set_speech_offsets(
331
  self, offsets: Tuple[float, float, float, float, float, float]
332
  ) -> None:
333
+ """Update speech-induced secondary offsets (x, y, z, roll, pitch, yaw).
334
+
335
+ Offsets are interpreted as metres for translation and radians for
336
+ rotation in the world frame. Thread-safe via a pending snapshot.
337
+ """
338
  with self._speech_offsets_lock:
339
  self._pending_speech_offsets = offsets
340
  self._speech_offsets_dirty = True
 
342
  def set_offsets(
343
  self, offsets: Tuple[float, float, float, float, float, float]
344
  ) -> None:
345
+ """Compatibility alias for :meth:`set_speech_offsets`."""
346
  self.set_speech_offsets(offsets)
347
 
348
  def set_face_tracking_offsets(
349
  self, offsets: Tuple[float, float, float, float, float, float]
350
  ) -> None:
351
+ """Update face-tracking secondary offsets (x, y, z, roll, pitch, yaw).
352
+
353
+ Offsets are staged atomically and applied in the worker thread.
354
+ """
355
  with self._face_offsets_lock:
356
  self._pending_face_offsets = offsets
357
  self._face_offsets_dirty = True
358
 
359
  def set_moving_state(self, duration: float) -> None:
360
+ """Mark the robot as actively moving for the provided duration.
361
+
362
+ Legacy hook used by goto helpers to keep inactivity and breathing logic
363
+ aware of manual motions. Thread-safe via the command queue.
364
+ """
365
  self._command_queue.put(("set_moving_state", duration))
366
 
367
  def is_idle(self):
368
+ """Return True when the robot has been inactive longer than the idle delay."""
369
  with self._shared_state_lock:
370
  last_activity = self._shared_last_activity_time
371
  listening = self._shared_is_listening
 
378
  return time_since_activity >= self.idle_inactivity_delay
379
 
380
  def mark_user_activity(self) -> None:
381
+ """Record external activity and postpone idle behaviours (thread-safe)."""
382
  self._command_queue.put(("mark_activity", None))
383
 
384
  def set_listening(self, listening: bool) -> None:
385
+ """Enable or disable listening mode without touching shared state directly.
386
+
387
+ While listening:
388
+ - Antenna positions are frozen at the last commanded values.
389
+ - Blending is reset so that upon unfreezing the antennas return smoothly.
390
+ - Idle breathing is suppressed.
391
+
392
+ Thread-safe: the change is posted to the worker command queue.
393
+ """
394
  with self._shared_state_lock:
395
  if self._shared_is_listening == listening:
396
  return
 
643
  self.state.face_tracking_offsets = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
644
 
645
  def start(self) -> None:
646
+ """Start the worker thread that drives the 100 Hz control loop."""
647
  self._stop_event.clear()
648
  self._thread = threading.Thread(target=self.working_loop, daemon=True)
649
  self._thread.start()
650
  logger.info("Move worker started")
651
 
652
  def stop(self) -> None:
653
+ """Request the worker thread to stop and wait for it to exit."""
654
  self._stop_event.set()
655
  if self._thread is not None:
656
  self._thread.join()
 
690
  freq_min = min(freq_min, last_freq)
691
  prev_loop_start = loop_start
692
 
693
+ # 1) Poll external commands and apply pending offsets (atomic snapshot)
694
  self._poll_signals(current_time)
695
 
696
+ # 2) Manage the primary move queue (start new move, end finished move)
697
  self._manage_move_queue(current_time)
698
 
699
+ # 3) Manage automatic idle behaviours (breathing)
700
  self._manage_breathing(current_time)
701
 
702
+ # 4) Update vision-based secondary offsets
703
  self._update_face_tracking(current_time)
704
 
705
+ # 5) Build primary and secondary full-body poses, then fuse them
706
  primary_full_body_pose = self._get_primary_pose(current_time)
707
  secondary_full_body_pose = self._get_secondary_pose()
708
  global_full_body_pose = combine_full_body(
709
  primary_full_body_pose, secondary_full_body_pose
710
  )
711
 
712
+ # 6) Apply listening antenna freeze or blend-back
713
  head, antennas, body_yaw = global_full_body_pose
714
  now_monotonic = self._now()
715
  listening = self._is_listening
 
743
  float(antennas[1]),
744
  )
745
 
746
+ # 7) Single set_target call - the only control point
747
  try:
748
  self.current_robot.set_target(
749
  head=head, antennas=antennas_cmd, body_yaw=body_yaw
 
766
  (head, antennas_cmd, body_yaw)
767
  )
768
 
769
+ # 8) Adaptive sleep to align to next tick, then publish shared state
770
  computation_time = self._now() - loop_start
771
  potential_freq = (
772
  1.0 / computation_time if computation_time > 0 else float("inf")
 
778
  if sleep_time > 0:
779
  time.sleep(sleep_time)
780
 
781
+ # 9) Periodic telemetry on loop frequency
782
  if loop_count % print_interval_loops == 0 and freq_count > 0:
783
  variance = freq_m2 / freq_count if freq_count > 0 else 0.0
784
  lowest = freq_min if freq_min != float("inf") else 0.0