-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
1602 lines (1345 loc) · 54.4 KB
/
Copy pathapi_server.py
File metadata and controls
1602 lines (1345 loc) · 54.4 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
"""
Unitree G1 Robot API Server — v2
A production-grade FastAPI server for controlling the Unitree G1 humanoid
robot from a Raspberry Pi. Features:
- Real serial I/O with auto-detection and reconnection
- Velocity commands with safety ramping and watchdog
- Command sequencing / macro system
- WebSocket real-time telemetry streaming
- Documented state-transition actions via controller button combos
- Structured event logging
- YAML / env-var configuration
"""
from __future__ import annotations
import asyncio
import json as _json
import logging
import math
import time
import uuid
from contextlib import asynccontextmanager
from enum import Enum
from pathlib import Path
from typing import Any, Optional
import serial
import serial.tools.list_ports
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from config import AppConfig, load_config
from controller_protocol import ControllerButtons, ControllerState
from sequence_library import SequenceLibrary
from telemetry import EventLog, EventType
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("g1api")
# ---------------------------------------------------------------------------
# Pydantic models
# ---------------------------------------------------------------------------
class RobotMode(str, Enum):
IDLE = "idle"
DAMPING = "damping"
STAND = "stand"
WALKING = "walking"
RUNNING = "running"
class MoveCommand(BaseModel):
"""Velocity command for robot movement."""
vx: float = Field(0.0, description="Forward velocity m/s (neg = backward)")
vy: float = Field(0.0, description="Lateral velocity m/s (pos = left)")
vyaw: float = Field(0.0, description="Yaw rate rad/s (pos = CCW)")
duration: Optional[float] = Field(
None, ge=0.0, description="Auto-stop after N seconds"
)
class SequenceStep(BaseModel):
"""One step in a command sequence."""
action: str = Field(..., description="Action type: move, action, wait")
params: dict = Field(default_factory=dict)
duration: float = Field(
1.0, ge=0.0, description="How long this step runs (seconds)"
)
class SequenceCommand(BaseModel):
"""A sequence of steps to execute in order."""
name: str = Field("unnamed", description="Sequence name for logging")
steps: list[SequenceStep] = Field(..., min_length=1)
loop: bool = Field(False, description="Loop the sequence continuously")
class NavigateCommand(BaseModel):
"""Navigate to a position (requires vision/SLAM)."""
x: float = Field(..., description="Target X position (meters)")
y: float = Field(..., description="Target Y position (meters)")
heading: Optional[float] = Field(None, description="Target heading (radians)")
class SpeedModeCommand(BaseModel):
"""Switch between walk and run modes."""
mode: str = Field("walk", description="Speed mode: walk or run")
class RobotStatus(BaseModel):
mode: RobotMode = RobotMode.IDLE
speed_mode: str = "walk"
battery_percent: int = 0
controller_connected: bool = False
serial_connected: bool = False
api_control_active: bool = False
current_velocity: dict = {"vx": 0.0, "vy": 0.0, "vyaw": 0.0}
target_velocity: dict = {"vx": 0.0, "vy": 0.0, "vyaw": 0.0}
uptime_seconds: float = 0.0
active_sequence: Optional[str] = None
safety: dict = {"watchdog_ok": True, "ramping": False}
class ActionResponse(BaseModel):
success: bool
message: str
action: str
id: Optional[str] = None
# ---------------------------------------------------------------------------
# Available actions — documented button combos from official G1 Quick Start
# Source: https://support.unitree.com/home/en/G1_developer/quick_start
#
# These are verified state-transition combos for the G1 Basic (sitting boot,
# 1-DOF waist). Gesture actions (wave, bow, shake hand, etc.) require the
# DDS LocoClient / ArmActionClient network API and are NOT available via
# controller packet injection.
# ---------------------------------------------------------------------------
ACTION_MAP: dict[str, int] = {
"damping": ControllerButtons.L1 | ControllerButtons.A,
"stand_up": ControllerButtons.L1 | ControllerButtons.UP,
"sit_down": ControllerButtons.L1 | ControllerButtons.LEFT,
"start_control": ControllerButtons.R1 | ControllerButtons.X,
"toggle_walk": ControllerButtons.START,
"emergency_stop": ControllerButtons.L2 | ControllerButtons.B,
"debug_mode": ControllerButtons.L2 | ControllerButtons.R2,
}
# ---------------------------------------------------------------------------
# Safety Layer
# ---------------------------------------------------------------------------
class SafetyManager:
"""
Enforces velocity limits, ramping, and watchdog timeout.
- Clamps velocities to configured maximums
- Ramps velocity changes to limit acceleration
- Stops robot if no command received within watchdog timeout
"""
def __init__(self, config: AppConfig, event_log: EventLog):
self.cfg = config.safety
self._log = event_log
self._last_cmd_time: float = time.time()
self._current_vx: float = 0.0
self._current_vy: float = 0.0
self._current_vyaw: float = 0.0
self._last_tick: float = time.time()
self.watchdog_tripped = False
def clamp(self, vx: float, vy: float, vyaw: float) -> tuple[float, float, float]:
"""Clamp velocities to safety limits."""
orig = (vx, vy, vyaw)
vx = max(-self.cfg.max_vx, min(self.cfg.max_vx, vx))
vy = max(-self.cfg.max_vy, min(self.cfg.max_vy, vy))
vyaw = max(-self.cfg.max_vyaw, min(self.cfg.max_vyaw, vyaw))
if (vx, vy, vyaw) != orig:
self._log.record(
EventType.VELOCITY_CLAMPED,
{
"original": {"vx": orig[0], "vy": orig[1], "vyaw": orig[2]},
"clamped": {"vx": vx, "vy": vy, "vyaw": vyaw},
},
source="safety",
)
return vx, vy, vyaw
def ramp(
self, target_vx: float, target_vy: float, target_vyaw: float
) -> tuple[float, float, float]:
"""Apply acceleration ramping to smooth velocity changes."""
if not self.cfg.enable_ramp:
self._current_vx = target_vx
self._current_vy = target_vy
self._current_vyaw = target_vyaw
return target_vx, target_vy, target_vyaw
now = time.time()
dt = min(now - self._last_tick, 0.1) # cap to avoid jumps
self._last_tick = now
max_delta = self.cfg.velocity_ramp_rate * dt
def _approach(current: float, target: float) -> float:
diff = target - current
if abs(diff) <= max_delta:
return target
return current + math.copysign(max_delta, diff)
self._current_vx = _approach(self._current_vx, target_vx)
self._current_vy = _approach(self._current_vy, target_vy)
self._current_vyaw = _approach(self._current_vyaw, target_vyaw)
return self._current_vx, self._current_vy, self._current_vyaw
def feed_command(self):
"""Call on every new command to reset the watchdog."""
self._last_cmd_time = time.time()
self.watchdog_tripped = False
def check_watchdog(self) -> bool:
"""Returns True if watchdog is OK, False if timed out."""
if not self.cfg.enable_watchdog:
return True
elapsed = time.time() - self._last_cmd_time
if elapsed > self.cfg.watchdog_timeout:
if not self.watchdog_tripped:
self.watchdog_tripped = True
self._log.record(
EventType.WATCHDOG_TIMEOUT,
{
"elapsed": round(elapsed, 2),
"timeout": self.cfg.watchdog_timeout,
},
source="safety",
)
logger.warning("Watchdog timeout after %.1fs — stopping", elapsed)
return False
return True
def reset(self):
"""Reset ramp state to zero."""
self._current_vx = 0.0
self._current_vy = 0.0
self._current_vyaw = 0.0
self._last_tick = time.time()
@property
def is_ramping(self) -> bool:
return self.cfg.enable_ramp
# ---------------------------------------------------------------------------
# Serial Manager — handles real serial I/O with auto-reconnect
# ---------------------------------------------------------------------------
class SerialManager:
"""
Manages serial connections to the controller receiver and robot MCU.
Features:
- Auto-detection of CP210x USB receiver
- Non-blocking reads via asyncio
- Automatic reconnection on disconnect
- Simulation mode for development without hardware
"""
def __init__(self, config: AppConfig, event_log: EventLog):
self.cfg = config.serial
self.simulation = config.simulation
self._log = event_log
self._receiver: Optional[serial.Serial] = None
self._robot: Optional[serial.Serial] = None
self._read_buffer = bytearray()
@property
def receiver_connected(self) -> bool:
return self._receiver is not None and self._receiver.is_open
@property
def robot_connected(self) -> bool:
return self._robot is not None and self._robot.is_open
def auto_detect_port(self) -> Optional[str]:
"""Find CP210x controller receiver."""
for port in serial.tools.list_ports.comports():
desc = port.description or ""
if "CP210" in desc or (port.vid == 0x10C4 and port.pid == 0xEA60):
logger.info("Auto-detected controller receiver at %s", port.device)
return port.device
return None
def open_receiver(self) -> bool:
"""Open the controller receiver serial port."""
if self.simulation:
logger.info("Simulation mode — skipping receiver serial open")
return True
port = self.cfg.receiver_port
if self.cfg.auto_detect:
detected = self.auto_detect_port()
if detected:
port = detected
try:
self._receiver = serial.Serial(
port,
self.cfg.baud_rate,
timeout=self.cfg.timeout,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
)
self._receiver.reset_input_buffer()
self._log.record(EventType.SERIAL_OPEN, {"port": port, "role": "receiver"})
logger.info("Receiver serial opened: %s @ %d", port, self.cfg.baud_rate)
return True
except serial.SerialException as e:
logger.error("Cannot open receiver serial %s: %s", port, e)
return False
def open_robot(self) -> bool:
"""Open the robot MCU serial port."""
if self.simulation:
logger.info("Simulation mode — skipping robot serial open")
return True
try:
self._robot = serial.Serial(
self.cfg.robot_port,
self.cfg.baud_rate,
timeout=self.cfg.timeout,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
)
self._robot.reset_input_buffer()
self._log.record(
EventType.SERIAL_OPEN, {"port": self.cfg.robot_port, "role": "robot"}
)
logger.info(
"Robot serial opened: %s @ %d", self.cfg.robot_port, self.cfg.baud_rate
)
return True
except serial.SerialException as e:
logger.warning("Cannot open robot serial %s: %s", self.cfg.robot_port, e)
return False
def read_controller_packet(self) -> Optional[ControllerState]:
"""
Non-blocking read of a 40-byte controller packet.
Returns None if no complete packet available.
"""
if self.simulation or not self.receiver_connected:
return None
try:
waiting = self._receiver.in_waiting
if waiting > 0:
self._read_buffer.extend(self._receiver.read(min(waiting, 1024)))
except (serial.SerialException, OSError):
logger.warning("Receiver serial read error — will reconnect")
self._close_port(self._receiver)
self._receiver = None
return None
# Search for valid 40-byte packet with known header
HEADERS = [b"\xfe\xef", b"\xfe\xfe", b"\xaa\x55", b"\x55\xaa"]
for hdr in HEADERS:
idx = self._read_buffer.find(hdr)
if idx >= 0 and idx + 40 <= len(self._read_buffer):
packet = bytes(self._read_buffer[idx : idx + 40])
# Discard everything up to and including this packet
del self._read_buffer[: idx + 40]
try:
return ControllerState.from_bytes(packet)
except Exception:
pass
# Prevent buffer from growing unbounded
if len(self._read_buffer) > 4096:
self._read_buffer = self._read_buffer[-256:]
return None
def send_to_robot(self, state: ControllerState) -> bool:
"""Send a controller state packet to the robot MCU."""
if self.simulation:
return True
if not self.robot_connected:
return False
try:
self._robot.write(state.to_bytes())
return True
except (serial.SerialException, OSError):
logger.warning("Robot serial write error — will reconnect")
self._close_port(self._robot)
self._robot = None
return False
def try_reconnect(self):
"""Attempt to reconnect any disconnected ports."""
if not self.simulation:
if not self.receiver_connected:
self.open_receiver()
if not self.robot_connected:
self.open_robot()
def close(self):
"""Close all serial ports."""
self._close_port(self._receiver)
self._close_port(self._robot)
self._receiver = None
self._robot = None
self._log.record(EventType.SERIAL_CLOSE, {})
@staticmethod
def _close_port(port: Optional[serial.Serial]):
if port and port.is_open:
try:
port.close()
except Exception:
pass
# ---------------------------------------------------------------------------
# Sequence Runner
# ---------------------------------------------------------------------------
class SequenceRunner:
"""
Executes multi-step command sequences asynchronously.
Each sequence runs as an asyncio task. Only one sequence can be
active at a time — starting a new one cancels the current one.
"""
def __init__(self, controller: RobotController):
self._ctrl = controller
self._task: Optional[asyncio.Task] = None
self._active_name: Optional[str] = None
self._cancelled = False
@property
def active(self) -> Optional[str]:
return self._active_name
@property
def running(self) -> bool:
return self._task is not None and not self._task.done()
async def start(self, seq: SequenceCommand) -> str:
"""Start executing a sequence. Returns sequence ID."""
self.cancel()
seq_id = str(uuid.uuid4())[:8]
self._active_name = seq.name
self._cancelled = False
self._ctrl.event_log.record(
EventType.SEQUENCE_START,
{"id": seq_id, "name": seq.name, "steps": len(seq.steps), "loop": seq.loop},
source="sequence",
)
self._task = asyncio.create_task(self._run(seq, seq_id))
return seq_id
def cancel(self):
"""Cancel any running sequence."""
if self._task and not self._task.done():
self._cancelled = True
self._task.cancel()
self._active_name = None
async def _run(self, seq: SequenceCommand, seq_id: str):
try:
while True:
for i, step in enumerate(seq.steps):
if self._cancelled:
return
self._ctrl.event_log.record(
EventType.SEQUENCE_STEP,
{
"id": seq_id,
"step": i,
"action": step.action,
"params": step.params,
},
source="sequence",
)
await self._execute_step(step)
await asyncio.sleep(step.duration)
if not seq.loop:
break
except asyncio.CancelledError:
pass
finally:
# Return to idle
self._ctrl.clear_api_command()
self._active_name = None
self._ctrl.event_log.record(
EventType.SEQUENCE_END,
{"id": seq_id, "name": seq.name},
source="sequence",
)
async def _execute_step(self, step: SequenceStep):
"""Execute a single sequence step."""
if step.action == "move":
vx = step.params.get("vx", 0.0)
vy = step.params.get("vy", 0.0)
vyaw = step.params.get("vyaw", 0.0)
cmd = MoveCommand(vx=vx, vy=vy, vyaw=vyaw, duration=step.duration + 0.5)
self._ctrl.set_move_command(cmd)
elif step.action == "action":
name = step.params.get("name", "")
self._ctrl.execute_action(name)
elif step.action == "wait":
# Just wait — duration handled by caller
self._ctrl.clear_api_command()
else:
logger.warning("Unknown sequence action: %s", step.action)
# ---------------------------------------------------------------------------
# RobotController — the core
# ---------------------------------------------------------------------------
class RobotController:
"""
Central robot controller managing serial I/O, safety, and command mixing.
Lifecycle: start() → control loop runs → stop()
"""
def __init__(self, config: AppConfig):
self.config = config
self.event_log = EventLog(log_to_file=True)
self.serial = SerialManager(config, self.event_log)
self.safety = SafetyManager(config, self.event_log)
self.sequence_runner = SequenceRunner(self)
self.running = False
self.start_time = time.time()
# State
self.controller_state = ControllerState()
self.controller_connected = False
self.current_mode = RobotMode.IDLE
self.speed_mode: str = "walk" # walk, run (internal speed scaling)
# API command state
self._api_vx: float = 0.0
self._api_vy: float = 0.0
self._api_vyaw: float = 0.0
self._api_cmd_expires: float = 0.0
self._api_active: bool = False
# Button hold queue: list of (buttons, expire_time)
self._button_holds: list[tuple[int, float]] = []
self._action_hold_seconds: float = 0.35 # how long to hold buttons
# Control loop
self._control_task: Optional[asyncio.Task] = None
self._reconnect_task: Optional[asyncio.Task] = None
# WebSocket subscribers
self._ws_clients: set[WebSocket] = set()
async def start(self):
self.running = True
self.start_time = time.time()
# Open serial ports
self.serial.open_receiver()
self.serial.open_robot()
# Start loops
self._control_task = asyncio.create_task(self._control_loop())
self._reconnect_task = asyncio.create_task(self._reconnect_loop())
self.event_log.record(
EventType.SERVER_START, {"simulation": self.config.simulation}
)
logger.info("Robot controller started (simulation=%s)", self.config.simulation)
async def stop(self):
self.running = False
self.sequence_runner.cancel()
for task in (self._control_task, self._reconnect_task):
if task:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
self.serial.close()
self.event_log.record(EventType.SERVER_STOP, {})
self.event_log.close()
logger.info("Robot controller stopped")
# -- Control loop ---------------------------------------------------
async def _control_loop(self):
interval = 1.0 / self.config.control.command_rate_hz
while self.running:
try:
self._tick()
await asyncio.sleep(interval)
except asyncio.CancelledError:
break
except Exception as e:
logger.error("Control loop error: %s", e, exc_info=True)
await asyncio.sleep(0.1)
def _tick(self):
"""Single control loop iteration."""
# 1. Read controller input
pkt = self.serial.read_controller_packet()
if pkt:
self.controller_state = pkt
if not self.controller_connected:
self.controller_connected = True
self.event_log.record(EventType.CONTROLLER_CONNECT, {})
logger.info("Controller connected")
# 2. Determine target velocity
target_vx, target_vy, target_vyaw = self._compute_target()
# 3. Safety: clamp, ramp, watchdog
vx, vy, vyaw = self.safety.clamp(target_vx, target_vy, target_vyaw)
if self._api_active:
vx, vy, vyaw = self.safety.ramp(vx, vy, vyaw)
else:
self.safety.reset()
if not self.safety.check_watchdog() and self._api_active:
vx = vy = vyaw = 0.0
self._api_active = False
self.safety.reset()
# 4. Build final controller state to send
final = ControllerState()
final.ly = vx / self.config.safety.max_vx if self.config.safety.max_vx else 0
final.lx = -vy / self.config.safety.max_vy if self.config.safety.max_vy else 0
final.rx = (
-vyaw / self.config.safety.max_vyaw if self.config.safety.max_vyaw else 0
)
# 4b. Apply any active button holds
now = time.time()
active_buttons = 0
self._button_holds = [(b, t) for b, t in self._button_holds if t > now]
for buttons, _ in self._button_holds:
active_buttons |= buttons
final.buttons = active_buttons
# 5. Update mode tracking
self._update_mode()
# 6. Send to robot
self.serial.send_to_robot(final)
def _compute_target(self) -> tuple[float, float, float]:
"""Compute target velocity from API or controller."""
now = time.time()
# API command active?
if now < self._api_cmd_expires:
self._api_active = True
return self._api_vx, self._api_vy, self._api_vyaw
self._api_active = False
# Passthrough from physical controller
if self.config.control.passthrough_enabled and self.controller_connected:
return (
self.controller_state.ly * self.config.safety.max_vx,
-self.controller_state.lx * self.config.safety.max_vy,
-self.controller_state.rx * self.config.safety.max_vyaw,
)
return 0.0, 0.0, 0.0
# -- Command entrypoints -------------------------------------------
def _update_mode(self):
"""Derive current_mode from robot state."""
# If button holds include emergency stop, we're in damping
now = time.time()
active_buttons = 0
for buttons, t in self._button_holds:
if t > now:
active_buttons |= buttons
estop = ControllerButtons.START | ControllerButtons.SELECT
if active_buttons & estop == estop:
self.current_mode = RobotMode.DAMPING
return
# Check if moving
v = (
abs(self.safety._current_vx)
+ abs(self.safety._current_vy)
+ abs(self.safety._current_vyaw)
)
if v > 0.02:
self.current_mode = (
RobotMode.RUNNING if self.speed_mode == "run" else RobotMode.WALKING
)
elif self._api_active or self.controller_connected:
self.current_mode = RobotMode.STAND
else:
self.current_mode = RobotMode.IDLE
def set_move_command(self, cmd: MoveCommand):
self._api_vx = cmd.vx
self._api_vy = cmd.vy
self._api_vyaw = cmd.vyaw
duration = (
cmd.duration if cmd.duration else self.config.control.api_command_timeout
)
self._api_cmd_expires = time.time() + duration
self.safety.feed_command()
self.event_log.record(
EventType.MOVE_CMD,
{"vx": cmd.vx, "vy": cmd.vy, "vyaw": cmd.vyaw, "duration": duration},
source="api",
)
def clear_api_command(self):
self._api_vx = 0.0
self._api_vy = 0.0
self._api_vyaw = 0.0
self._api_cmd_expires = 0.0
self._api_active = False
self.safety.reset()
def execute_action(self, action_name: str) -> bool:
if action_name not in ACTION_MAP:
return False
buttons = ACTION_MAP[action_name]
# Queue button hold — the control loop will include these buttons
# in every packet until the hold expires (~350ms)
expire = time.time() + self._action_hold_seconds
self._button_holds.append((buttons, expire))
self.safety.feed_command()
self.event_log.record(
EventType.ACTION_CMD,
{
"action": action_name,
"buttons": f"0x{buttons:04X}",
"hold_ms": int(self._action_hold_seconds * 1000),
},
source="api",
)
logger.info(
"Action: %s (buttons=0x%04X, hold=%dms)",
action_name,
buttons,
int(self._action_hold_seconds * 1000),
)
return True
def set_speed_mode(self, mode: str) -> bool:
"""Switch between walk and run speed modes."""
if mode not in ("walk", "run"):
return False
if mode == self.speed_mode:
return True
self.speed_mode = mode
# Run mode is typically activated with a D-pad combo
# Using UP for run, DOWN for walk as common convention
if mode == "run":
expire = time.time() + self._action_hold_seconds
self._button_holds.append(
(ControllerButtons.L2 | ControllerButtons.UP, expire)
)
else:
expire = time.time() + self._action_hold_seconds
self._button_holds.append(
(ControllerButtons.L2 | ControllerButtons.DOWN, expire)
)
self.event_log.record(
EventType.MODE_CHANGE,
{"speed_mode": mode},
source="api",
)
logger.info("Speed mode: %s", mode)
return True
def emergency_stop(self):
self.clear_api_command()
self.sequence_runner.cancel()
self.execute_action("emergency_stop")
self.event_log.record(EventType.EMERGENCY_STOP, {}, source="api")
logger.warning("EMERGENCY STOP triggered")
def get_status(self) -> RobotStatus:
return RobotStatus(
mode=self.current_mode,
speed_mode=self.speed_mode,
battery_percent=100, # TODO: read from robot telemetry
controller_connected=self.controller_connected,
serial_connected=self.serial.receiver_connected or self.config.simulation,
api_control_active=self._api_active,
current_velocity={
"vx": round(self.safety._current_vx, 3),
"vy": round(self.safety._current_vy, 3),
"vyaw": round(self.safety._current_vyaw, 3),
},
target_velocity={
"vx": round(self._api_vx, 3),
"vy": round(self._api_vy, 3),
"vyaw": round(self._api_vyaw, 3),
},
uptime_seconds=round(time.time() - self.start_time, 1),
active_sequence=self.sequence_runner.active,
safety={
"watchdog_ok": not self.safety.watchdog_tripped,
"ramping": self.safety.is_ramping,
},
)
# -- WebSocket broadcasting ----------------------------------------
def add_ws_client(self, ws: WebSocket):
self._ws_clients.add(ws)
def remove_ws_client(self, ws: WebSocket):
self._ws_clients.discard(ws)
async def broadcast_state(self):
"""Periodically broadcast state to all WebSocket clients."""
while self.running:
if self._ws_clients:
status = self.get_status()
data = status.model_dump()
dead: list[WebSocket] = []
for ws in self._ws_clients:
try:
await ws.send_json(data)
except Exception:
dead.append(ws)
for ws in dead:
self._ws_clients.discard(ws)
await asyncio.sleep(0.1) # 10 Hz broadcast
# -- Reconnect loop ------------------------------------------------
async def _reconnect_loop(self):
"""Periodically try to reconnect lost serial ports."""
while self.running:
try:
self.serial.try_reconnect()
await asyncio.sleep(5.0)
except asyncio.CancelledError:
break
except Exception:
await asyncio.sleep(5.0)
# ---------------------------------------------------------------------------
# Global instance
# ---------------------------------------------------------------------------
robot_controller: Optional[RobotController] = None
_ws_broadcast_task: Optional[asyncio.Task] = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global robot_controller, _ws_broadcast_task
config = load_config()
robot_controller = RobotController(config)
await robot_controller.start()
_ws_broadcast_task = asyncio.create_task(robot_controller.broadcast_state())
yield
if _ws_broadcast_task:
_ws_broadcast_task.cancel()
await robot_controller.stop()
# ---------------------------------------------------------------------------
# FastAPI app
# ---------------------------------------------------------------------------
app = FastAPI(
title="Unitree G1 Robot API",
description=(
"REST + WebSocket API for controlling the Unitree G1 humanoid robot.\n\n"
"## Features\n"
"- Velocity movement commands with safety ramping\n"
"- Predefined actions (documented state transitions)\n"
"- Command sequencing / macros\n"
"- Real-time WebSocket telemetry\n"
"- Structured event logging\n"
),
version="0.3.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _ctrl() -> RobotController:
if not robot_controller:
raise HTTPException(503, "Controller not initialized")
return robot_controller
# ---------------------------------------------------------------------------
# REST endpoints
# ---------------------------------------------------------------------------
@app.get("/", tags=["System"])
async def root():
return {
"name": "Unitree G1 Robot API",
"version": "0.3.0",
"docs": "/docs",
"dashboard": "/dashboard",
"status": "running",
}
@app.get("/dashboard", response_class=HTMLResponse, tags=["System"])
async def dashboard():
"""Serve the web control dashboard."""
html_path = Path(__file__).parent / "dashboard.html"
return HTMLResponse(html_path.read_text())
# -- Status -----------------------------------------------------------------
@app.get("/api/v1/status", response_model=RobotStatus, tags=["Status"])
async def get_status():
"""Full robot status including serial, safety, gait, and active sequence."""
return _ctrl().get_status()
@app.get("/api/v1/actions", tags=["Status"])
async def list_actions():
"""List all available predefined actions."""
return {
"actions": list(ACTION_MAP.keys()),
"description": "Use POST /api/v1/action/{name} to execute",
}
# -- Movement ---------------------------------------------------------------
@app.post("/api/v1/move", response_model=ActionResponse, tags=["Movement"])
async def move(cmd: MoveCommand):
"""
Send a velocity command.
The robot will move at the specified velocity until:
- **duration** expires (if set)
- A new move/stop command is received
- The watchdog times out (default 2s)
Velocities are automatically clamped and ramped for safety.
"""
_ctrl().set_move_command(cmd)
return ActionResponse(
success=True,
message=f"Moving: vx={cmd.vx}, vy={cmd.vy}, vyaw={cmd.vyaw}",
action="move",
)