-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobot_node.py
More file actions
1447 lines (1250 loc) · 67.2 KB
/
Copy pathrobot_node.py
File metadata and controls
1447 lines (1250 loc) · 67.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Real-Time Innovations, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
Robot Node — the DDS approach: Pure DDS (Data-Centric Everything)
Uses RTI Connext DDS for all communication — pub-sub for
state/intent/telemetry/video, rti.rpc Requester / SimpleReplier for
commands and charging-station slot negotiation.
DDS architecture:
• Types generated by rtiddsgen from robot_types.idl.
• QoS loaded from robot_qos.xml (Pattern-based profiles).
• writer.write() → middleware delivers via multicast; no per-subscriber threads.
• SimpleReplier for commands (DDS-native request-reply).
• Requester for slot negotiation — fan-out to all stations in one call.
• DDS liveliness for peer health monitoring.
• DDS SPDP for fleet discovery.
• DDS SampleInfo provides source_timestamp and reception_timestamp
with nanosecond precision.
• rti.rpc correlates via SampleIdentity (writer GUID + sequence number).
See README §1 (DDS-Natural design philosophy) and §8 (Thread Model).
"""
import rti.connextdds as dds
import rti.idl as idl
import rti.rpc as rpc
import time
import threading
import argparse
import random
import math
import os
import sys
from datetime import datetime
from typing import Dict, List, Optional
from enum import IntEnum
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'shared'))
from video_renderer import VideoRenderer
# Types generated by: rtiddsgen -language python robot_types.idl
from robot_types import (
RobotStatus, RobotIntentType, Command,
Position, Velocity3, Waypoint,
KinematicState, OperationalState, Intent, Telemetry, VideoFrame,
StationStatus, CoveragePoint,
CommandRequest, CommandResponse,
SlotReserve, SlotAssignment, SlotRelease, SlotReleaseAck,
)
# Convenience set for charge-related intents
_CHARGE_INTENTS = (RobotIntentType.INTENT_CHARGE_QUEUE,
RobotIntentType.INTENT_CHARGE_DOCK)
# ═════════════════════════════════════════════════════════════════════════════
# Compact log timestamp
# ═════════════════════════════════════════════════════════════════════════════
def _ts():
"""Return a compact HH:MM:SS timestamp for log lines."""
return datetime.now().strftime("%H:%M:%S")
# ═════════════════════════════════════════════════════════════════════════════
# RobotNode — Pure DDS robot participant
# ═════════════════════════════════════════════════════════════════════════════
class RobotNode:
"""
A robot node using pure DDS for all communications.
Pub-sub topics:
KinematicState (10 Hz), OperationalState (on change), Intent (on change),
Telemetry (1 Hz), VideoFrame (~5 fps).
Request-reply (via rti.rpc):
SimpleReplier: CommandRequest → CommandResponse (operator commands).
Requester: SlotReserve → SlotAssignment (reserve a charging slot),
SlotRelease → SlotReleaseAck (release when done).
Queue monitoring is pub-sub driven via StationStatus.
Threading:
~9 threads total regardless of fleet size (see README §8).
"""
def __init__(self, robot_id: str, domain_id: int = 0):
self.robot_id = robot_id
self.domain_id = domain_id
self.running = False
# ── Robot state ───────────────────────────────────────────────────
self.position = {"x": random.uniform(0, 100),
"y": random.uniform(0, 100), "z": 0.0}
self.status = RobotStatus.STATUS_MOVING
self.intent = RobotIntentType.INTENT_FOLLOW_PATH
self.battery_level = 100.0
self.goal: Optional[dict] = None
self.hold_position: Optional[dict] = None
self.speed = 2.0
self.heading = 0.0
self.velocity_x = 0.0
self.velocity_y = 0.0
self.velocity_z = 0.0
self.signal_strength = 95.0
# Path route — a loop of waypoints the robot cycles through
self.path_waypoints = self._generate_path_route()
self.path_index = 0
# ── Peer tracking (from DDS readers) ──────────────────────────────
self.other_robots_state: Dict[str, KinematicState] = {}
self.other_robots_intent: Dict[str, Intent] = {}
self.other_robots_operational: Dict[str, OperationalState] = {}
self._nearby_peers: set = set()
# ── Charging state ────────────────────────────────────────────────
self._charge_slot_id: Optional[str] = None
self._charge_station_id: Optional[str] = None
self._charge_dock: Optional[dict] = None
self._charge_wait_pos: Optional[dict] = None
self._charge_queue_rank: int = -1
self._charge_requested: bool = False
self._pre_charge_intent: Optional[RobotIntentType] = None
self._pre_charge_status: Optional[RobotStatus] = None
self._pre_charge_speed: float = 2.0
self._pre_charge_goal: Optional[dict] = None
self._pre_charge_hold: Optional[dict] = None
# Station dock positions learned from StationStatus topic
self._station_docks: Dict[str, dict] = {} # station_id → {"x","y"}
self.CHARGE_THRESHOLD = 20.0
self.CHARGE_FULL = 95.0
self.CHARGE_RATE = 2.0 # %/s while docked
# ── DDS entities ──────────────────────────────────────────────────
self.participant: Optional[dds.DomainParticipant] = None
self.writers: Dict[str, dds.DataWriter] = {}
self.readers: Dict[str, dds.DataReader] = {}
# ── Video rendering ───────────────────────────────────────────────
# fleet_robot_ids starts empty; peers are added dynamically from
# DDS discovery (other_robots_state keys). VideoRenderer uses
# the list only for consistent colour assignment.
self._fleet_robot_ids: List[str] = []
self.video_renderer = VideoRenderer(robot_id, self._fleet_robot_ids)
self._video_active = False # True while at least one UI streams
# ── RPC entities (rti.rpc) ────────────────────────────────────────
self.command_replier: Optional[rpc.SimpleReplier] = None
self.reserve_requester: Optional[rpc.Requester] = None
self.release_requester: Optional[rpc.Requester] = None
# ── OperationalState change tracking ──────────────────────────────
self._last_published_status: Optional[RobotStatus] = None
self._last_published_battery: Optional[float] = None
# ── Intent change tracking ────────────────────────────────────────
self._last_published_intent: Optional[RobotIntentType] = None
self._last_published_target: Optional[tuple] = None
self._last_published_path_index: Optional[int] = None
self._path_version: int = 0 # bumped on SET_PATH
self._last_published_path_version: int = -1
# ── Coverage tracking ─────────────────────────────────────────────
self._last_cov_x: float = float('nan')
self._last_cov_y: float = float('nan')
self._cov_working: bool = False # True once path_index >= 1 after CMD_FOLLOW_PATH
# ── Pre-idle state (saved by CMD_STOP, restored by CMD_RESUME) ────
self._pre_idle_status: Optional[RobotStatus] = None
# Locks
self.data_lock = threading.Lock()
# ── Path route generation ─────────────────────────────────────────────
def _generate_path_route(self) -> List[dict]:
"""Generate a path route — a loop of waypoints covering an area.
Each robot gets a slightly different route seeded by its id so
they naturally spread out across the arena.
"""
seed = hash(self.robot_id) & 0xFFFFFFFF
rng = random.Random(seed)
cx = rng.uniform(20, 80)
cy = rng.uniform(20, 80)
radius = rng.uniform(15, 30)
n_pts = rng.randint(5, 8)
waypoints = []
for i in range(n_pts):
angle = 2 * math.pi * i / n_pts
jx = rng.uniform(-5, 5)
jy = rng.uniform(-5, 5)
wx = max(5, min(95, cx + radius * math.cos(angle) + jx))
wy = max(5, min(95, cy + radius * math.sin(angle) + jy))
waypoints.append({"x": wx, "y": wy})
return waypoints
@property
def path_target(self):
"""The waypoint the robot is currently heading toward."""
return self.path_waypoints[self.path_index]
# ═════════════════════════════════════════════════════════════════════
# DDS initialisation
# ═════════════════════════════════════════════════════════════════════
def initialize_dds(self):
"""Create the DDS DomainParticipant, pub-sub entities, and RPC objects.
Pub-sub: 5 writers (kinematic, operational, intent, telemetry, video)
+ 4 readers (kinematic, operational, intent, station) with listeners.
RPC: 1 SimpleReplier (commands) + 3 Requesters (slot negotiation).
QoS profiles are loaded from robot_qos.xml (Pattern-based).
Types are generated by rtiddsgen from robot_types.idl.
"""
print(f"[{self.robot_id} {_ts()}] Initializing DDS on domain {self.domain_id}...")
# Resolve the path to robot_qos.xml relative to this script
script_dir = os.path.dirname(os.path.abspath(__file__))
qos_xml = os.path.join(script_dir, "robot_qos.xml")
qos_provider = dds.QosProvider(qos_xml)
participant_qos = qos_provider.participant_qos_from_profile(
"RobotQosLibrary::ParticipantProfile")
participant_qos.participant_name.name = self.robot_id
participant_qos.participant_name.role_name = "Tractor"
self.participant = dds.DomainParticipant(self.domain_id, participant_qos)
# ── Pub-Sub Topics (6 — command/slot handled by rti.rpc) ──
kin_topic = dds.Topic(self.participant, "KinematicState", KinematicState)
op_topic = dds.Topic(self.participant, "OperationalState", OperationalState)
intent_topic = dds.Topic(self.participant, "Intent", Intent)
telem_topic = dds.Topic(self.participant, "Telemetry", Telemetry)
video_topic = dds.Topic(self.participant, "VideoFrame", VideoFrame)
cov_topic = dds.Topic(self.participant, "CoveragePoint", CoveragePoint)
station_topic = dds.Topic(self.participant, "StationStatus", StationStatus)
publisher = dds.Publisher(self.participant)
subscriber = dds.Subscriber(self.participant)
# ── Pub-Sub Writers (6) ───────────────────────────────────────────
kin_w_qos = qos_provider.datawriter_qos_from_profile(
"RobotQosLibrary::KinematicStateProfile")
op_w_qos = qos_provider.datawriter_qos_from_profile(
"RobotQosLibrary::OperationalStateProfile")
intent_w_qos = qos_provider.datawriter_qos_from_profile(
"RobotQosLibrary::IntentProfile")
telem_w_qos = qos_provider.datawriter_qos_from_profile(
"RobotQosLibrary::TelemetryProfile")
video_w_qos = qos_provider.datawriter_qos_from_profile(
"RobotQosLibrary::VideoProfile")
cov_w_qos = qos_provider.datawriter_qos_from_profile(
"RobotQosLibrary::CoverageProfile")
self.writers['kinematic'] = dds.DataWriter(publisher, kin_topic, kin_w_qos)
self.writers['operational'] = dds.DataWriter(publisher, op_topic, op_w_qos)
self.writers['intent'] = dds.DataWriter(publisher, intent_topic, intent_w_qos)
self.writers['telemetry'] = dds.DataWriter(publisher, telem_topic, telem_w_qos)
self.writers['coverage'] = dds.DataWriter(publisher, cov_topic, cov_w_qos)
# ── Video DataWriter on a dedicated Publisher with partition ───
# The partition is set to this robot's ID. The UI's video
# Subscriber starts with partition '__NONE__' (matches nothing).
# When the operator selects a robot, the UI changes its
# Subscriber partition to that robot_id → DDS matches the
# writer/reader pair and triggers publication_matched_status.
# Only the matched robot renders; all others see current_count=0
# and skip rendering. No CFT, no property inspection, no
# polling — just partition-based matching, the most efficient
# DDS mechanism for selective data delivery.
video_pub_qos = dds.PublisherQos()
video_pub_qos.partition.name = [self.robot_id]
video_publisher = dds.Publisher(self.participant, video_pub_qos)
self.writers['video'] = dds.DataWriter(
video_publisher, video_topic, video_w_qos)
# ── Pub-Sub Readers (4) ───────────────────────────────────────────
kin_r_qos = qos_provider.datareader_qos_from_profile(
"RobotQosLibrary::KinematicStateProfile")
op_r_qos = qos_provider.datareader_qos_from_profile(
"RobotQosLibrary::OperationalStateProfile")
intent_r_qos = qos_provider.datareader_qos_from_profile(
"RobotQosLibrary::IntentProfile")
self.readers['kinematic'] = dds.DataReader(subscriber, kin_topic, kin_r_qos)
self.readers['operational'] = dds.DataReader(subscriber, op_topic, op_r_qos)
self.readers['intent'] = dds.DataReader(subscriber, intent_topic, intent_r_qos)
# ── StationStatus reader (learn station dock positions for 3D video) ─
station_r_qos = qos_provider.datareader_qos_from_profile(
"RobotQosLibrary::StationStatusProfile")
self.readers['station'] = dds.DataReader(subscriber, station_topic, station_r_qos)
# ── RPC: Command handling (robot = server) ────────────────────────
# SimpleReplier: receives CommandRequest, calls _handle_command,
# writes the returned CommandResponse back with SampleIdentity
# correlation.
self.command_replier = rpc.SimpleReplier(
request_type=CommandRequest,
reply_type=CommandResponse,
participant=self.participant,
service_name="RobotCommand",
handler=self._handle_command,
)
# ── RPC: Slot negotiation (robot = client) ────────────────────────
# Two Requester objects — one per request-reply pair.
self.reserve_requester = rpc.Requester(
request_type=SlotReserve,
reply_type=SlotAssignment,
participant=self.participant,
service_name="ChargingSlotReserve",
)
self.release_requester = rpc.Requester(
request_type=SlotRelease,
reply_type=SlotReleaseAck,
participant=self.participant,
service_name="ChargingSlotRelease",
)
# ── Pub-Sub Listeners ─────────────────────────────────────────────
self._setup_listeners()
print(f"[{self.robot_id} {_ts()}] DDS initialized — "
f"5 pub-sub + 1 SimpleReplier + 2 Requesters")
# ═════════════════════════════════════════════════════════════════════
# Listeners — DDS callbacks for received data
# ═════════════════════════════════════════════════════════════════════
def _setup_listeners(self):
"""Attach DDS DataReaderListeners for pub-sub data reception.
Only pub-sub readers (kinematic, operational, intent, station) get
listeners.
Command reception is handled by the SimpleReplier (§6.6 in spec).
Slot negotiation replies are read by Requester objects (§6.7).
DDS delivers to these callbacks automatically for every matched
writer in the domain.
"""
robot = self
# ── KinematicState listener ───────────────────────────────────────
class KinematicListener(dds.DataReaderListener):
def on_data_available(self, reader):
for sample in reader.take():
if sample.info.valid:
data = sample.data
if data.robot_id != robot.robot_id:
with robot.data_lock:
robot.other_robots_state[data.robot_id] = data
def on_liveliness_changed(self, reader, status):
"""Handle DDS liveliness changes for peer robots.
The middleware fires this callback within ~10 s of
lease expiry (30 s lease).
"""
if status.alive_count_change < 0:
print(f"[{robot.robot_id} {_ts()}] ⚠ Robot DEAD "
f"(alive={status.alive_count})")
elif status.alive_count_change > 0:
print(f"[{robot.robot_id} {_ts()}] ✓ Robot ALIVE "
f"(alive={status.alive_count})")
self.readers['kinematic'].set_listener(
KinematicListener(),
dds.StatusMask.DATA_AVAILABLE | dds.StatusMask.LIVELINESS_CHANGED)
# ── OperationalState listener ─────────────────────────────────────
class OperationalListener(dds.DataReaderListener):
def on_data_available(self, reader):
for sample in reader.take():
if sample.info.valid:
data = sample.data
if data.robot_id != robot.robot_id:
with robot.data_lock:
robot.other_robots_operational[data.robot_id] = data
self.readers['operational'].set_listener(
OperationalListener(), dds.StatusMask.DATA_AVAILABLE)
# ── Intent listener ───────────────────────────────────────────────
class IntentListener(dds.DataReaderListener):
def on_data_available(self, reader):
for sample in reader.take():
if sample.info.valid:
data = sample.data
if data.robot_id != robot.robot_id:
with robot.data_lock:
robot.other_robots_intent[data.robot_id] = data
self.readers['intent'].set_listener(
IntentListener(), dds.StatusMask.DATA_AVAILABLE)
# ── StationStatus listener (queue monitoring + dock positions) ────
# This listener serves two purposes:
# 1. Learn station dock positions for 3D rendering.
# 2. Monitor queue rank changes — when a queued robot sees its
# rank drop to 0 it navigates to the dock.
class StationStatusListener(dds.DataReaderListener):
def on_data_available(self, reader):
for sample in reader.take():
if sample.info.valid:
data = sample.data
with robot.data_lock:
robot._station_docks[data.station_id] = {
"x": data.dock_x,
"y": data.dock_y,
"queue_len": len(data.queue),
"is_occupied": data.is_occupied,
}
# Queue-rank monitoring (outside lock — may
# trigger RPC calls in _abort_charge).
if (robot._charge_station_id == data.station_id
and robot.intent in _CHARGE_INTENTS):
robot._on_station_status_update(data)
self.readers['station'].set_listener(
StationStatusListener(), dds.StatusMask.DATA_AVAILABLE)
# ═════════════════════════════════════════════════════════════════════
# Command handling
# ═════════════════════════════════════════════════════════════════════
def _handle_command(self, cmd: CommandRequest) -> CommandResponse:
"""Process an incoming command and return a response.
Called by the SimpleReplier for each incoming CommandRequest.
The return value is automatically written back with SampleIdentity
correlation.
"""
# Filter: only process commands addressed to this robot.
# All robots share the same service_name, so every robot's
# SimpleReplier receives every command.
if cmd.robot_id != self.robot_id:
return CommandResponse(
robot_id=self.robot_id,
success=True,
description="not addressed to me",
resulting_status=self.status,
resulting_intent=self.intent,
)
cmd_name = cmd.command.name
print(f"[{self.robot_id} {_ts()}] Received command: {cmd_name}")
success = True
description = ""
resulting_status = self.status
resulting_intent = self.intent
if cmd.command == Command.CMD_STOP:
self._pre_idle_status = self.status
self.status = RobotStatus.STATUS_IDLE
self.velocity_x = 0.0
self.velocity_y = 0.0
description = "Idle (paused)"
elif cmd.command == Command.CMD_FOLLOW_PATH:
if self._charge_slot_id:
self._abort_charge()
self.goal = None
self.hold_position = None
self.intent = RobotIntentType.INTENT_FOLLOW_PATH
self.status = RobotStatus.STATUS_MOVING
self._cov_working = False # reset — must reach waypoint[1] again
self._last_cov_x = float('nan')
self._last_cov_y = float('nan')
if cmd.goto_params is not None and cmd.goto_params.speed > 0:
self.speed = cmd.goto_params.speed
description = f"Following path at speed {self.speed:.1f}"
elif cmd.command == Command.CMD_GOTO:
if self._charge_slot_id:
self._abort_charge()
gp = cmd.goto_params
gx = gp.x if gp is not None else self.position["x"]
gy = gp.y if gp is not None else self.position["y"]
spd = gp.speed if gp is not None else 0
if spd > 0:
self.speed = spd
self.goal = {"x": gx, "y": gy}
self.hold_position = None
self.intent = RobotIntentType.INTENT_GOTO
self.status = RobotStatus.STATUS_MOVING
description = f"Moving to ({gx:.0f}, {gy:.0f}) at speed {self.speed:.1f}"
elif cmd.command == Command.CMD_RESUME:
if cmd.goto_params is not None and cmd.goto_params.speed > 0:
self.speed = cmd.goto_params.speed
if self._pre_idle_status is not None:
# Restore whatever status we had before STOP
self.status = self._pre_idle_status
self._pre_idle_status = None
elif self.intent == RobotIntentType.INTENT_FOLLOW_PATH:
self.hold_position = None
self.status = RobotStatus.STATUS_MOVING
elif self.intent == RobotIntentType.INTENT_GOTO:
if self.goal is not None:
self.hold_position = None
self.status = RobotStatus.STATUS_MOVING
elif self.hold_position is not None:
self.goal = dict(self.hold_position)
self.hold_position = None
self.status = RobotStatus.STATUS_MOVING
else:
self.hold_position = {
"x": self.position["x"],
"y": self.position["y"],
}
self.status = RobotStatus.STATUS_HOLDING
elif self.intent in _CHARGE_INTENTS:
if self.goal is not None:
self.status = RobotStatus.STATUS_MOVING
elif self.hold_position is not None:
self.status = RobotStatus.STATUS_HOLDING
else:
self.status = RobotStatus.STATUS_MOVING
else:
self.hold_position = {
"x": self.position["x"],
"y": self.position["y"],
}
self.status = RobotStatus.STATUS_HOLDING
description = f"Resumed ({self.intent.name}) at speed {self.speed:.1f}"
elif cmd.command == Command.CMD_SET_PATH:
wps = (cmd.set_path_params.waypoints
if cmd.set_path_params is not None else [])
if len(wps) < 2:
success = False
description = "Need at least 2 waypoints"
else:
self.path_waypoints = [{"x": w.x, "y": w.y} for w in wps]
self.path_index = self.path_index % len(self.path_waypoints)
self._path_version += 1
description = f"Path route set ({len(wps)} waypoints)"
print(f"[{self.robot_id} {_ts()}] Path route updated: {len(wps)} waypoints")
elif cmd.command == Command.CMD_CHARGE:
if self.status == RobotStatus.STATUS_CHARGING:
success = False
description = "Already charging"
elif self._charge_requested:
success = False
description = "Charge already in progress"
else:
self._charge_requested = True
threading.Thread(target=self._initiate_charge, daemon=True).start()
description = "Heading to charging station"
else:
success = False
description = f"Unknown command: {cmd_name}"
resulting_status = self.status
resulting_intent = self.intent
response = CommandResponse(
robot_id=self.robot_id,
success=success,
description=description,
resulting_status=resulting_status,
resulting_intent=resulting_intent,
)
print(f"[{self.robot_id} {_ts()}] → {description}")
return response
# ═════════════════════════════════════════════════════════════════════
# Charging station interaction (DDS request-reply)
# ═════════════════════════════════════════════════════════════════════
def _initiate_charge(self):
"""Begin the charging workflow with a single directed SlotReserve.
The robot already knows every station's queue length and dock
position from the StationStatus pub-sub topic. It picks the
best station locally (shortest queue, then closest) and sends
one SlotReserve. No offer/accept round-trip needed.
Queue monitoring is handled by StationStatusListener — when the
station publishes an updated queue, the listener calls
_on_station_status_update() which detects rank changes.
"""
if self.intent in _CHARGE_INTENTS:
self._charge_requested = False
return
# Stash current state
self._pre_charge_intent = self.intent
self._pre_charge_status = self.status
self._pre_charge_speed = self.speed
self._pre_charge_goal = dict(self.goal) if self.goal else None
self._pre_charge_hold = dict(self.hold_position) if self.hold_position else None
self._cov_working = False # stop recording coverage during charge cycle
print(f"[{self.robot_id} {_ts()}] ⚡ Battery {self.battery_level:.0f}% — requesting charge slot")
# Pick the best station from cached StationStatus data
best_sid = None
best_qlen = float('inf')
best_dist = float('inf')
for sid, info in self._station_docks.items():
qlen = info.get("queue_len", 0)
dist = math.hypot(info["x"] - self.position["x"],
info["y"] - self.position["y"])
if (qlen < best_qlen
or (qlen == best_qlen and dist < best_dist)):
best_sid = sid
best_qlen = qlen
best_dist = dist
if best_sid is None:
print(f"[{self.robot_id} {_ts()}] ✗ No charging stations known — staying on task")
self._charge_requested = False
return
dock = self._station_docks[best_sid]
print(f"[{self.robot_id} {_ts()}] ⚡ Best station: {best_sid} "
f"queue={best_qlen} dist={best_dist:.0f} "
f"dock=({dock['x']:.0f},{dock['y']:.0f})")
# Send SlotReserve — station_id makes it directed
request_id = self.reserve_requester.send_request(SlotReserve(
robot_id=self.robot_id,
station_id=best_sid,
battery_level=self.battery_level,
))
# Collect reply (may arrive from multiple stations due to fan-out)
try:
replies = self.reserve_requester.receive_replies(
dds.Duration.from_seconds(5),
related_request_id=request_id)
except dds.TimeoutError:
replies = []
assignment = None
for reply in replies:
if reply.info.valid:
d = reply.data
if d.granted and d.station_id == best_sid:
assignment = d
break
if assignment is None:
print(f"[{self.robot_id} {_ts()}] ✗ Slot not granted — staying on task")
self._charge_requested = False
return
# Guard against a command that changed intent while we were
# waiting for the RPC reply (e.g. rapid CHARGE → GOTO). If
# the handler already moved the robot to a non-charge intent,
# release the slot we just reserved and bail out.
if self.intent not in (self._pre_charge_intent, *_CHARGE_INTENTS):
print(f"[{self.robot_id} {_ts()}] ⚡ Intent changed to "
f"{self.intent.name} during reserve — releasing slot")
try:
self.release_requester.send_request(SlotRelease(
robot_id=self.robot_id,
slot_id=assignment.slot_id,
station_id=best_sid,
))
except Exception:
pass
self._charge_requested = False
return
print(f"[{self.robot_id} {_ts()}] ⚡ Reserved slot {assignment.slot_id} "
f"rank={assignment.queue_rank}")
# Store charge state
self._charge_slot_id = assignment.slot_id
self._charge_station_id = best_sid
self._charge_dock = {"x": assignment.dock_x, "y": assignment.dock_y}
self._charge_queue_rank = assignment.queue_rank
# Navigate to station
if assignment.queue_rank == 0:
self.goal = dict(self._charge_dock)
self.intent = RobotIntentType.INTENT_CHARGE_DOCK
print(f"[{self.robot_id} {_ts()}] ⚡ Heading to dock "
f"({self.goal['x']:.0f},{self.goal['y']:.0f})")
else:
wx, wy = self._wait_position(
self._charge_dock["x"], self._charge_dock["y"],
assignment.queue_rank)
self._charge_wait_pos = {"x": wx, "y": wy}
self.goal = dict(self._charge_wait_pos)
self.intent = RobotIntentType.INTENT_CHARGE_QUEUE
print(f"[{self.robot_id} {_ts()}] ⚡ Heading to wait position "
f"rank={assignment.queue_rank} "
f"goal=({self.goal['x']:.1f},{self.goal['y']:.1f})")
self.status = RobotStatus.STATUS_MOVING
self.hold_position = None
self.speed = 3.0
def _on_station_status_update(self, status: StationStatus):
"""React to a StationStatus update for our charging station.
Called from StationStatusListener when the station publishes
an updated queue.
If our rank dropped to 0 → navigate to dock.
If our rank changed → update wait position.
If we disappeared from the queue → abort charge.
"""
if not self._charge_slot_id:
return
# Find our rank in the published queue
my_rank = -1
for entry in status.queue:
if entry.robot_id == self.robot_id:
my_rank = entry.rank
break
if my_rank < 0:
# We're not in the queue — station may have expired us
if self.intent == RobotIntentType.INTENT_CHARGE_QUEUE:
print(f"[{self.robot_id} {_ts()}] ⚡ Disappeared from "
f"{status.station_id} queue — aborting charge")
self._abort_charge()
self.intent = self._pre_charge_intent or RobotIntentType.INTENT_FOLLOW_PATH
self.status = RobotStatus.STATUS_MOVING
self.speed = self._pre_charge_speed
self.goal = self._pre_charge_goal
self.hold_position = None
return
old_rank = self._charge_queue_rank
self._charge_queue_rank = my_rank
if my_rank == 0 and old_rank != 0:
# Promoted to dock!
self.goal = dict(self._charge_dock)
self.hold_position = None
self.intent = RobotIntentType.INTENT_CHARGE_DOCK
self.status = RobotStatus.STATUS_MOVING
print(f"[{self.robot_id} {_ts()}] ⚡ Queue advanced → heading to dock")
elif my_rank != old_rank and my_rank > 0:
wx, wy = self._wait_position(
self._charge_dock["x"], self._charge_dock["y"], my_rank)
self._charge_wait_pos = {"x": wx, "y": wy}
self.goal = dict(self._charge_wait_pos)
self.hold_position = None
self.status = RobotStatus.STATUS_MOVING
print(f"[{self.robot_id} {_ts()}] ⚡ Queue rank {old_rank} → {my_rank}")
@staticmethod
def _wait_position(dock_x: float, dock_y: float, rank: int) -> tuple:
"""Compute a waiting position near a station for a given queue rank.
Robots line up in a column extending toward the centre of the arena
(50, 50), each separated by ~8 units so collision avoidance doesn't
kick in.
"""
spacing = 8
offset = 10 + rank * spacing
dx = 1 if dock_x < 50 else -1
dy = 1 if dock_y < 50 else -1
if abs(50 - dock_x) >= abs(50 - dock_y):
return (dock_x + dx * offset, dock_y)
else:
return (dock_x, dock_y + dy * offset)
def _abort_charge(self):
"""Cancel an in-progress charge. Release the slot via Requester.
Fire-and-forget: we send the SlotRelease but do NOT wait for
the reply. This method is called from DDS callback threads
(SimpleReplier handler, StationStatusListener) where blocking
would stall the middleware's internal dispatch.
"""
if self._charge_slot_id:
try:
self.release_requester.send_request(SlotRelease(
robot_id=self.robot_id,
slot_id=self._charge_slot_id,
station_id=self._charge_station_id or "",
))
except Exception as e:
print(f"[{self.robot_id} {_ts()}] ⚠ Release failed: {e}")
print(f"[{self.robot_id} {_ts()}] ⚡ Charge aborted (slot released)")
self._clear_charge_state()
def _release_charge_slot(self):
"""Release the slot and resume prior task.
Fire-and-forget like _abort_charge — called from the
update_position thread; blocking it would pause the
simulation for up to 2 seconds.
"""
if self._charge_slot_id:
try:
self.release_requester.send_request(SlotRelease(
robot_id=self.robot_id,
slot_id=self._charge_slot_id,
station_id=self._charge_station_id or "",
))
except Exception as e:
print(f"[{self.robot_id} {_ts()}] ⚠ Release failed: {e}")
print(f"[{self.robot_id} {_ts()}] ⚡ Charging complete "
f"({self.battery_level:.0f}%) — resuming")
# Restore pre-charge state
if (self._pre_charge_intent == RobotIntentType.INTENT_GOTO
and self._pre_charge_goal is None
and self._pre_charge_hold is not None):
self.intent = RobotIntentType.INTENT_GOTO
self.goal = dict(self._pre_charge_hold)
self.hold_position = None
self.status = RobotStatus.STATUS_MOVING
self.speed = self._pre_charge_speed
else:
self.intent = self._pre_charge_intent or RobotIntentType.INTENT_FOLLOW_PATH
self.status = RobotStatus.STATUS_MOVING
self.speed = self._pre_charge_speed
self.goal = self._pre_charge_goal
self.hold_position = None
self._clear_charge_state()
def _clear_charge_state(self):
"""Reset all charge-related fields."""
self._charge_slot_id = None
self._charge_station_id = None
self._charge_dock = None
self._charge_wait_pos = None
self._charge_queue_rank = -1
self._charge_requested = False
self._pre_charge_intent = None
self._pre_charge_status = None
self._pre_charge_speed = 2.0
self._pre_charge_goal = None
self._pre_charge_hold = None
# Coverage must re-earn _cov_working by reaching a waypoint
self._cov_working = False
self._last_cov_x = float('nan')
self._last_cov_y = float('nan')
# ═════════════════════════════════════════════════════════════════════
# Collision avoidance
# ═════════════════════════════════════════════════════════════════════
AVOIDANCE_RADIUS = 12.0
AVOIDANCE_STRENGTH = 4.0
MIN_SEPARATION = 4.0
MAX_TURN_RATE = 2.0 # rad/s — non-holonomic steering limit
@property
def _is_docking(self) -> bool:
return (self.intent == RobotIntentType.INTENT_CHARGE_DOCK
and self.goal is not None)
def _compute_avoidance(self):
"""Return (dx, dy, hard_override) repulsion from nearby peers.
Inverse-square repulsion algorithm; see _compute_avoidance()
docstring for details.
"""
ax, ay = 0.0, 0.0
hard_override = False
mx, my = self.position["x"], self.position["y"]
docking = self._is_docking
near_station = (self.intent in _CHARGE_INTENTS
and self._charge_dock is not None)
if docking:
eff_radius = self.AVOIDANCE_RADIUS * 0.4
eff_strength = self.AVOIDANCE_STRENGTH * 0.3
elif near_station:
eff_radius = self.AVOIDANCE_RADIUS * 0.5
eff_strength = self.AVOIDANCE_STRENGTH * 0.25
else:
eff_radius = self.AVOIDANCE_RADIUS
eff_strength = self.AVOIDANCE_STRENGTH
with self.data_lock:
peers = {
rid: (s.position.x, s.position.y)
for rid, s in self.other_robots_state.items()
if rid != self.robot_id
}
docking_peers: set = set()
if near_station and not docking:
for rid in peers:
intent_msg = self.other_robots_intent.get(rid)
if (intent_msg
and intent_msg.intent_type == RobotIntentType.INTENT_CHARGE_DOCK):
docking_peers.add(rid)
for rid, (px, py) in peers.items():
dx = mx - px
dy = my - py
dist = math.sqrt(dx * dx + dy * dy)
was_nearby = rid in self._nearby_peers
is_nearby = dist < eff_radius
# Hysteresis: enter at eff_radius, clear at 115% to avoid
# log flicker when peers hover near the boundary.
is_clear = dist > eff_radius * 1.15
if is_nearby and not was_nearby:
print(f"[{self.robot_id} {_ts()}] ⚠ Peer {rid} nearby "
f"({dist:.1f} units) — avoiding")
self._nearby_peers.add(rid)
elif is_clear and was_nearby:
print(f"[{self.robot_id} {_ts()}] ✓ Peer {rid} clear "
f"({dist:.1f} units)")
self._nearby_peers.discard(rid)
if is_nearby and dist > 0.01:
ratio = eff_radius / dist
strength = eff_strength * ratio * ratio
if near_station and rid in docking_peers:
strength *= 3.0
ax += (dx / dist) * strength
ay += (dy / dist) * strength
if dist < self.MIN_SEPARATION and not near_station and not docking:
hard_override = True
return ax, ay, hard_override
def _steer_heading(self, desired_vx, desired_vy, dt):
"""Turn self.heading toward the desired velocity, clamped by MAX_TURN_RATE.
Returns (vx, vy) along the updated heading. Speed is reduced
when the heading error is large so the tractor decelerates into
sharp turns.
"""
desired_speed = math.sqrt(desired_vx**2 + desired_vy**2)
if desired_speed < 0.01:
return 0.0, 0.0
desired_heading = math.atan2(desired_vy, desired_vx)
diff = (desired_heading - self.heading + math.pi) % (2 * math.pi) - math.pi
max_turn = self.MAX_TURN_RATE * dt
self.heading += max(-max_turn, min(max_turn, diff))
self.heading = (self.heading + math.pi) % (2 * math.pi) - math.pi
# Slow down when turning hard — tractors decelerate into sharp turns
turn_factor = max(0.2, math.cos(min(abs(diff), math.pi / 2)))
speed = desired_speed * turn_factor
return math.cos(self.heading) * speed, math.sin(self.heading) * speed
# ═════════════════════════════════════════════════════════════════════
# Position update (movement tick)
# ═════════════════════════════════════════════════════════════════════
def update_position(self):
"""Simulate robot movement — 10 Hz tick loop.
Handles path following, GOTO, collision avoidance, battery drain,
signal strength simulation, and auto-charge.
"""
dt = 0.1
while self.running:
if self.status == RobotStatus.STATUS_MOVING:
vx, vy = 0.0, 0.0
if (self.intent in (RobotIntentType.INTENT_GOTO, *_CHARGE_INTENTS)
and self.goal is not None):
dx = self.goal["x"] - self.position["x"]
dy = self.goal["y"] - self.position["y"]
dist = (dx**2 + dy**2) ** 0.5
if dist <= self.speed * dt:
# Arrived
self.position["x"] = self.goal["x"]
self.position["y"] = self.goal["y"]
if dist > 0.01:
self.heading = math.atan2(dy, dx)
self.velocity_x = 0.0
self.velocity_y = 0.0
if self.intent == RobotIntentType.INTENT_CHARGE_DOCK:
print(f"[{self.robot_id} {_ts()}] Arrived at charging dock → CHARGING")
self.goal = None
self.status = RobotStatus.STATUS_CHARGING
elif self.intent == RobotIntentType.INTENT_CHARGE_QUEUE:
print(f"[{self.robot_id} {_ts()}] Arrived at charge wait pos "
f"(rank {self._charge_queue_rank})")
self.hold_position = {"x": self.goal["x"], "y": self.goal["y"]}
self.goal = None
self.status = RobotStatus.STATUS_HOLDING
else:
print(f"[{self.robot_id} {_ts()}] Reached goal "
f"({self.goal['x']:.1f}, {self.goal['y']:.1f}) → HOLDING")
self.hold_position = {"x": self.goal["x"], "y": self.goal["y"]}