ezgo 0.0.2__py3-none-any.whl → 0.0.4__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.
ezgo/go2.py ADDED
@@ -0,0 +1,795 @@
1
+ import time
2
+ import threading
3
+ import numpy as np
4
+ import cv2
5
+ import netifaces
6
+ import subprocess
7
+ from unitree_sdk2py.core.channel import ChannelSubscriber, ChannelFactoryInitialize
8
+ from unitree_sdk2py.go2.sport.sport_client import SportClient
9
+ from unitree_sdk2py.go2.video.video_client import VideoClient
10
+ from unitree_sdk2py.idl.unitree_go.msg.dds_ import SportModeState_
11
+
12
+
13
+ error_code = {
14
+ 100: "灵动",
15
+ 1001: "阻尼",
16
+ 1002: "站立锁定",
17
+ 1004: "蹲下",
18
+ 2006: "蹲下",
19
+ 1006: "打招呼/伸懒腰/舞蹈/拜年/比心/开心",
20
+ 1007: "坐下",
21
+ 1008: "前跳",
22
+ 1009: "扑人",
23
+ 1013: "平衡站立",
24
+ 1015: "常规行走",
25
+ 1016: "常规跑步",
26
+ 1017: "常规续航",
27
+ 1091: "摆姿势",
28
+ 2004: "翻身", # ???
29
+ 2007: "闪避",
30
+ 2008: "并腿跑",
31
+ 2009: "跳跃跑",
32
+ 2010: "经典",
33
+ 2011: "倒立",
34
+ 2012: "前空翻",
35
+ 2013: "后空翻",
36
+ 2014: "左空翻",
37
+ 2016: "交叉步",
38
+ 2017: "直立",
39
+ 2019: "牵引",
40
+ }
41
+
42
+
43
+ class Go2:
44
+ """
45
+ 宇树Go2 运动控制封装类
46
+ 适用于:Unitree SDK2 Python接口
47
+ """
48
+ def __init__(self, interface=None, timeout=20.0):
49
+ """
50
+ 初始化控制器
51
+ :param interface: 网卡接口名称
52
+ :param timeout: 超时时间(秒)
53
+ """
54
+ self.interface = interface
55
+ self.timeout = timeout
56
+ self.sport_client = None
57
+ self.video_client = None
58
+ self.cap = None
59
+ self.error_code = 0 # 状态码
60
+
61
+ # 移动控制相关变量
62
+ self._moving = False
63
+ self._move_params = (0, 0, 0)
64
+ self._move_thread = None
65
+
66
+ # 摄像头对象
67
+ self.camera = None
68
+
69
+ # 声光控制对象
70
+ self._vui = None
71
+
72
+ if self.interface is None:
73
+ self.get_interface()
74
+
75
+ # 清理标志
76
+ self._initialized = False
77
+
78
+ def get_interface(self):
79
+ """获取当前接口"""
80
+
81
+ interfaces = netifaces.interfaces()
82
+ for iface in interfaces:
83
+ if iface.startswith("en"):
84
+ self.interface = iface
85
+ break
86
+
87
+ def check_go2_connection(self):
88
+ """检查机器狗IP连通性"""
89
+ try:
90
+ # 使用sudo ping检查机器狗IP (192.168.123.161是Go2的默认IP)
91
+ result = subprocess.run(['sudo', 'ping', '-c', '1', '-W', '2', '192.168.123.161'],
92
+ capture_output=True, text=True, timeout=5)
93
+ return result.returncode == 0
94
+ except subprocess.TimeoutExpired:
95
+ print("ping超时")
96
+ return False
97
+ except Exception as e:
98
+ print(f"检查连接时出错: {e}")
99
+ return False
100
+
101
+
102
+
103
+
104
+ def init(self):
105
+ """初始化与Go2的连接"""
106
+
107
+ # 检查机器狗IP连通性
108
+ if not self.check_go2_connection():
109
+ print("无法连接到机器狗,请检查网络连接")
110
+ return False
111
+
112
+ ChannelFactoryInitialize(0, self.interface)
113
+
114
+ # 启动状态订阅
115
+ self.sub_state(self.callback)
116
+
117
+ # 初始化运动控制客户端
118
+ self.sport_client = SportClient()
119
+ self.sport_client.SetTimeout(self.timeout)
120
+ self.sport_client.Init()
121
+
122
+ # 注意:视频流不再自动初始化,按需开启
123
+ # self.cap = self.open_video() # 移除自动初始化
124
+
125
+ self._initialized = True
126
+ return True
127
+
128
+
129
+ def open_video(self, width: int = 480, height: int = 320):
130
+ """打开视频流"""
131
+ gstreamer_str = (
132
+ f"udpsrc address=230.1.1.1 port=1720 multicast-iface={self.interface} "
133
+ "! application/x-rtp, media=video, encoding-name=H264 "
134
+ "! rtph264depay ! h264parse "
135
+ "! avdec_h264 " # 解码H.264
136
+ "! videoscale " # 添加缩放元素,用于调整分辨率
137
+ f"! video/x-raw,width={width},height={height} " # 目标分辨率
138
+ "! videoconvert ! video/x-raw, format=BGR " # 转换为OpenCV支持的BGR格式
139
+ "! appsink drop=1"
140
+ )
141
+ cap = cv2.VideoCapture(gstreamer_str, cv2.CAP_GSTREAMER)
142
+ if not cap.isOpened():
143
+ print("视频流打开失败")
144
+ print(f"使用的网络接口: {self.interface}")
145
+ print("GStreamer字符串:", gstreamer_str)
146
+ return None
147
+ print("视频流打开成功")
148
+ return cap
149
+
150
+ def read_image(self):
151
+ """从视频流获取一帧图像"""
152
+ if self.cap is None:
153
+ print("视频流未打开,请先调用 open_video()")
154
+ return None
155
+
156
+ ret, frame = self.cap.read()
157
+ if not ret:
158
+ print("读取图像失败")
159
+ return None
160
+ return frame
161
+
162
+
163
+ def sub_state(self, callback, queue_size: int = 5):
164
+ subscriber = ChannelSubscriber("rt/sportmodestate", SportModeState_)
165
+ subscriber.Init(callback, queue_size)
166
+
167
+ def callback(self, msg):
168
+ self.error_code = msg.error_code
169
+
170
+
171
+ # def read_image(self):
172
+ # """从视频流获取一帧图像"""
173
+ # code, data = self.video_client.GetImageSample()
174
+ # if code != 0 or data is None:
175
+ # print("获取图像样本失败,错误码:", code)
176
+ # return None
177
+ # image_data = np.frombuffer(bytes(data), dtype=np.uint8)
178
+ # image = cv2.imdecode(image_data, cv2.IMREAD_COLOR)
179
+ # return image
180
+
181
+ def Damp(self):
182
+ """进入阻尼状态。"""
183
+ self._call(self.sport_client.Damp)
184
+
185
+ def BalanceStand(self):
186
+ """解除锁定。"""
187
+ self._call(self.sport_client.BalanceStand)
188
+
189
+ def StopMove(self):
190
+ """
191
+ 停止机器狗的所有移动动作,并重置相关状态。
192
+
193
+ 该方法会:
194
+ 1. 停止任何正在执行的移动线程
195
+ 2. 调用底层SDK的停止方法
196
+ 3. 重置移动状态标志
197
+
198
+ 注意:
199
+ - 该方法会阻塞等待移动线程结束,最多等待1秒
200
+ - 调用后所有运动指令将被重置为默认状态
201
+ """
202
+ print("停止移动")
203
+ # 停止持续移动线程
204
+ self._moving = False
205
+ if (hasattr(self, '_move_thread') and
206
+ self._move_thread is not None and
207
+ self._move_thread.is_alive()):
208
+ self._move_thread.join(timeout=1.0)
209
+ self._move_thread = None
210
+
211
+ # 调用SDK的停止方法
212
+ self._call(self.sport_client.StopMove)
213
+
214
+ def _call(self, func, *args, **kwargs):
215
+ """在线程中调用运动控制函数"""
216
+ def fun_thread():
217
+ ret = func(*args, **kwargs)
218
+ print(f"{func.__name__} 执行结果:", ret)
219
+
220
+ t = threading.Thread(target=fun_thread)
221
+ t.start()
222
+ t.join() # 等待线程完成
223
+
224
+
225
+
226
+ def StandUp(self):
227
+ """
228
+ 关节锁定,站高。
229
+ 执行后状态: 1002:站立锁定
230
+ """
231
+ # 执行前判断状态
232
+ if self.error_code in [1002]: # 1002 :站立锁定
233
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
234
+ return
235
+ if self.error_code not in [100, 1001, 1007, 1013]: # 100 :灵动, 1001 :阻尼, 1013 :平衡站立
236
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
237
+ return
238
+ self._call(self.sport_client.StandUp)
239
+
240
+
241
+
242
+ def StandDown(self):
243
+ """
244
+ 关节锁定,站低。
245
+ 执行后状态: 1001:阻尼
246
+ """
247
+ # 执行前判断状态
248
+ if self.error_code in [1001, 1004, 2006]: # 1001:阻尼 1004 :蹲下 2006 :蹲下
249
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
250
+ return
251
+ if self.error_code not in [100, 1002, 1013]: # 100 :灵动, 1001 :阻尼, 1013 :平衡站立
252
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
253
+ return
254
+
255
+ # 执行指令
256
+ self._call(self.sport_client.StandDown)
257
+
258
+ def RecoveryStand(self):
259
+ """ 恢复站立。"""
260
+ self._call(self.sport_client.RecoveryStand)
261
+
262
+ def Euler(self, roll, pitch, yaw):
263
+ """站立和行走时的姿态。"""
264
+ pass
265
+
266
+ def Move(self, vx, vy, vyaw):
267
+ """移动。"""
268
+ # 检查状态是否允许移动
269
+ if self.error_code not in [100, 1002, 1013]: # 100:灵动, 1002:站立锁定, 1013:平衡站立
270
+ print(f"当前状态不允许移动: {self.error_code} - {error_code.get(self.error_code, '未知状态')}")
271
+ return False
272
+
273
+ # 限制速度范围
274
+ vx = max(-1.0, min(1.0, vx)) # 前后速度限制在-1到1之间
275
+ vy = max(-1.0, min(1.0, vy)) # 左右速度限制在-1到1之间
276
+ vyaw = max(-2.0, min(2.0, vyaw)) # 转动速度限制在-2到2之间
277
+
278
+ def move_thread():
279
+ ret = self.sport_client.Move(vx, vy, vyaw)
280
+ success = ret == 0
281
+ print(f"Move 执行结果: {ret}, 成功: {success}")
282
+ return success
283
+
284
+ t = threading.Thread(target=move_thread)
285
+ t.start()
286
+ t.join()
287
+ return True
288
+
289
+ def MoveForDuration(self, vx, vy, vyaw, duration):
290
+ """
291
+ 持续移动指定时间
292
+
293
+ Args:
294
+ vx (float): 前后速度 (-1.0 到 1.0)
295
+ vy (float): 左右速度 (-1.0 到 1.0)
296
+ vyaw (float): 转动速度 (-2.0 到 2.0)
297
+ duration (float): 移动时间(秒)
298
+
299
+ Returns:
300
+ bool: 是否成功执行
301
+ """
302
+ print(f"开始移动: vx={vx}, vy={vy}, vyaw={vyaw}, 持续时间={duration}秒")
303
+ start_time = time.time()
304
+
305
+ try:
306
+ while time.time() - start_time < duration:
307
+ if not self.Move(vx, vy, vyaw):
308
+ return False
309
+ time.sleep(0.1) # 每100ms调用一次
310
+
311
+ print("移动完成")
312
+ return True
313
+
314
+ except KeyboardInterrupt:
315
+ print("移动被用户中断")
316
+ return False
317
+
318
+ def Forward(self, speed=0.3, duration=2.0):
319
+ """向前移动"""
320
+ return self.MoveForDuration(speed, 0, 0, duration)
321
+
322
+ def Backward(self, speed=0.3, duration=2.0):
323
+ """向后移动"""
324
+ return self.MoveForDuration(-speed, 0, 0, duration)
325
+
326
+ def Left(self, speed=0.3, duration=2.0):
327
+ """向左移动"""
328
+ return self.MoveForDuration(0, speed, 0, duration)
329
+
330
+ def Right(self, speed=0.3, duration=2.0):
331
+ """向右移动"""
332
+ return self.MoveForDuration(0, -speed, 0, duration)
333
+
334
+ def TurnLeft(self, speed=0.5, duration=2.0):
335
+ """左转"""
336
+ return self.MoveForDuration(0, 0, speed, duration)
337
+
338
+ def TurnRight(self, speed=0.5, duration=2.0):
339
+ """右转"""
340
+ return self.MoveForDuration(0, 0, -speed, duration)
341
+
342
+ def StartMove(self, vx, vy, vyaw):
343
+ """
344
+ 开始持续移动,需要调用StopMove来停止
345
+
346
+ Args:
347
+ vx (float): 前后速度 (-1.0 到 1.0)
348
+ vy (float): 左右速度 (-1.0 到 1.0)
349
+ vyaw (float): 转动速度 (-2.0 到 2.0)
350
+
351
+ Returns:
352
+ bool: 是否成功开始移动
353
+ """
354
+ print(f"开始持续移动: vx={vx}, vy={vy}, vyaw={vyaw}")
355
+
356
+ # 先检查是否可以移动
357
+ if not self.Move(vx, vy, vyaw):
358
+ print("无法开始持续移动:当前状态不允许移动")
359
+ return False
360
+
361
+ self._moving = True
362
+ self._move_params = (vx, vy, vyaw)
363
+
364
+ def continuous_move():
365
+ while self._moving:
366
+ if not self.Move(vx, vy, vyaw):
367
+ print("持续移动失败,停止移动")
368
+ break
369
+ time.sleep(0.1)
370
+
371
+ self._move_thread = threading.Thread(target=continuous_move)
372
+ self._move_thread.daemon = True # 设置为守护线程
373
+ self._move_thread.start()
374
+ return True
375
+
376
+ def StartForward(self, speed=0.3):
377
+ """开始向前移动"""
378
+ return self.StartMove(speed, 0, 0)
379
+
380
+ def StartBackward(self, speed=0.3):
381
+ """开始向后移动"""
382
+ return self.StartMove(-speed, 0, 0)
383
+
384
+ def StartLeft(self, speed=0.3):
385
+ """开始向左移动"""
386
+ return self.StartMove(0, speed, 0)
387
+
388
+ def StartRight(self, speed=0.3):
389
+ """开始向右移动"""
390
+ return self.StartMove(0, -speed, 0)
391
+
392
+ def StartTurnLeft(self, speed=0.5):
393
+ """开始左转"""
394
+ return self.StartMove(0, 0, speed)
395
+
396
+ def StartTurnRight(self, speed=0.5):
397
+ """开始右转"""
398
+ return self.StartMove(0, 0, -speed)
399
+
400
+ def Sit(self):
401
+ """
402
+ 坐下。
403
+ 执行后状态: 1007: 坐下
404
+ """
405
+ # 执行前判断状态
406
+ if self.error_code in [1007]: # 1007 : 坐下
407
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
408
+ return
409
+ if self.error_code not in [100, 1002, 1013]: # 100 :灵动, 1001 :阻尼, 1013 :平衡站立
410
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
411
+ return
412
+
413
+ # 执行指令
414
+ self._call(self.sport_client.Sit)
415
+
416
+ def RiseSit(self):
417
+ """
418
+ 站起(相对于坐下)。
419
+ 执行后状态:
420
+ """
421
+ # 执行前判断状态
422
+ if self.error_code in [1007]: # 1002 :站立锁定
423
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
424
+ return
425
+ if self.error_code not in [100, 1007, 1013]: # 100 :灵动, 1007 : 坐下, 1013 :平衡站立
426
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
427
+ return
428
+
429
+ # 执行指令
430
+ self._call(self.sport_client.RiseSit)
431
+
432
+
433
+
434
+ def SpeedLevel(self, level: int):
435
+ """设置速度档位。"""
436
+ pass
437
+
438
+ def Hello(self):
439
+ """
440
+ 打招呼
441
+ 执行后状态: 1013:平衡站立
442
+ """
443
+ # 执行前判断状态
444
+ if self.error_code in [1006]: # 1006 :打招呼/伸懒腰/舞蹈/拜年/比心/开心
445
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
446
+ return
447
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
448
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
449
+ return
450
+
451
+ # 执行指令
452
+ self._call(self.sport_client.Hello)
453
+
454
+ def Stretch(self):
455
+ """
456
+ 伸懒腰。
457
+ 执行后状态: 1013:平衡站立
458
+ """
459
+ # 执行前判断状态
460
+ if self.error_code in [1006]: # 1006 :打招呼/伸懒腰/舞蹈/拜年/比心/开心
461
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
462
+ return
463
+ if self.error_code not in [100, 1002, 1013]: # 站立且空闲状态
464
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
465
+ return
466
+
467
+ # 执行指令
468
+ self._call(self.sport_client.Stretch)
469
+
470
+
471
+
472
+ def Content(self):
473
+ """
474
+ 开心。
475
+ 执行后状态: 1013:平衡站立
476
+ """
477
+ # 执行前判断状态
478
+ if self.error_code in [1006]: # 1006 :打招呼/伸懒腰/舞蹈/拜年/比心/开心
479
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
480
+ return
481
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
482
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
483
+ return
484
+
485
+ # 执行指令
486
+ self._call(self.sport_client.Content)
487
+
488
+
489
+ def Heart(self):
490
+ """
491
+ 比心。
492
+ 执行后状态: 1013:平衡站立
493
+ """
494
+ # 执行前判断状态
495
+ if self.error_code in [1006]: # 1006 :打招呼/伸懒腰/舞蹈/拜年/比心/开心
496
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
497
+ return
498
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
499
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
500
+ return
501
+
502
+ # 执行指令
503
+ self._call(self.sport_client.Heart)
504
+
505
+
506
+ def Pose(self, flag):
507
+ """摆姿势。"""
508
+ pass
509
+
510
+ def Scrape(self):
511
+ """
512
+ 拜年作揖。
513
+ 执行后状态: 1013:平衡站立
514
+ """
515
+ # 执行前判断状态
516
+ if self.error_code in [1006]: # 1006 :打招呼/伸懒腰/舞蹈/拜年/比心/开心
517
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
518
+ return
519
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
520
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
521
+ return
522
+
523
+ # 执行指令
524
+ self._call(self.sport_client.Scrape)
525
+
526
+
527
+
528
+ def FrontJump(self):
529
+ """
530
+ 前跳。
531
+ 执行后状态: 1013: 平衡站立
532
+ """
533
+ # 执行前判断状态
534
+ if self.error_code in [1008]: # 1008 : 前跳
535
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
536
+ return
537
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
538
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
539
+ return
540
+
541
+ # 执行指令
542
+ self._call(self.sport_client.FrontJump)
543
+
544
+
545
+
546
+ def FrontPounce(self):
547
+ """
548
+ 向前扑人。
549
+ 执行后状态: 1013: 平衡站立
550
+ """
551
+ # 执行前判断状态
552
+ if self.error_code in [1009]: # 1009 : 扑人
553
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
554
+ return
555
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
556
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
557
+ return
558
+
559
+ # 执行指令
560
+ self._call(self.sport_client.FrontPounce)
561
+
562
+
563
+ def Dance1(self):
564
+ """
565
+ 舞蹈段落1。
566
+ 执行后状态: 1013: 平衡站立
567
+ """
568
+ # 执行前判断状态
569
+ if self.error_code in [1006]: # 1006 :打招呼/伸懒腰/舞蹈/拜年/比心/开心
570
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
571
+ return
572
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
573
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
574
+ return
575
+
576
+ # 执行指令
577
+ self._call(self.sport_client.Dance1)
578
+
579
+ def Dance2(self):
580
+ """
581
+ 舞蹈段落2。
582
+ 执行后状态: 1013: 平衡站立
583
+ """
584
+ # 执行前判断状态
585
+ if self.error_code in [1006]: # 1006 :打招呼/伸懒腰/舞蹈/拜年/比心/开心
586
+ print("当前状态:", self.error_code, error_code[self.error_code], "无需执行")
587
+ return
588
+ if self.error_code not in [100, 1002, 1013]: # 空闲状态
589
+ print("繁忙中,当前状态:", self.error_code, error_code[self.error_code])
590
+ return
591
+
592
+ # 执行指令
593
+ self._call(self.sport_client.Dance2)
594
+
595
+ def HandStand(self, flag: int):
596
+ """倒立行走。"""
597
+ pass
598
+
599
+ def LeftFlip(self):
600
+ """左空翻。"""
601
+ pass
602
+
603
+ def BackFlip(self):
604
+ """后空翻。"""
605
+ pass
606
+
607
+ def FreeWalk(self, flag: int):
608
+ """ 灵动模式(默认步态)。"""
609
+ pass
610
+
611
+ def FreeBound(self, flag: int):
612
+ """ 并腿跑模式。"""
613
+ pass
614
+
615
+ def FreeJump(self, flag: int):
616
+ """ 跳跃模式。"""
617
+ pass
618
+
619
+ def FreeAvoid(self, flag: int):
620
+ """ 闪避模式。"""
621
+ pass
622
+
623
+ def WalkUpright(self, flag: int):
624
+ """ 后腿直立模式。"""
625
+ pass
626
+
627
+ def CrossStep(self, flag: int):
628
+ """ 交叉步模式。"""
629
+ pass
630
+
631
+ def AutoRecoverSet(self, flag: int):
632
+ """ 设置自动翻身是否生效。"""
633
+ pass
634
+
635
+ def AutoRecoverGet(self):
636
+ """ 查询自动翻身是否生效。"""
637
+ pass
638
+
639
+ def ClassicWalk(self, flag: int):
640
+ """ 经典步态。"""
641
+ pass
642
+
643
+ def TrotRun(self):
644
+ """ 进入常规跑步模式 """
645
+ pass
646
+
647
+ def StaticWalk(self):
648
+ """ 进入常规行走模式"""
649
+ pass
650
+
651
+ def EconomicGait(self):
652
+ """ 进入常规续航模式 """
653
+ pass
654
+
655
+ def SwitchAvoidMode(self):
656
+ """ 闪避模式下,关闭摇杆未推时前方障碍物的闪避以及后方的障碍物躲避"""
657
+ pass
658
+
659
+ def get_camera(self):
660
+ """
661
+ 获取摄像头对象(按需初始化)
662
+
663
+ Returns:
664
+ Go2Camera: 摄像头控制对象
665
+ """
666
+ if self.camera is None:
667
+ # 直接导入go2_camera模块
668
+ from .go2_camera import Go2Camera
669
+ self.camera = Go2Camera(self.interface, self.timeout)
670
+ # 注意:这里不自动初始化,让用户按需调用
671
+ return self.camera
672
+
673
+ def get_vui(self):
674
+ """
675
+ 获取声光控制对象(按需初始化)
676
+
677
+ Returns:
678
+ Go2VUI: 声光控制对象
679
+ """
680
+ if not hasattr(self, '_vui') or self._vui is None:
681
+ # 直接导入go2_vui模块
682
+ from .go2_vui import Go2VUI
683
+ self._vui = Go2VUI(self.interface)
684
+ # 注意:这里不自动初始化,让用户按需调用
685
+ return self._vui
686
+
687
+ def capture_image(self, save_path=None):
688
+ """
689
+ 便利方法:获取一张图片(按需初始化摄像头)
690
+
691
+ Args:
692
+ save_path (str): 保存路径
693
+
694
+ Returns:
695
+ numpy.ndarray: 图像数据
696
+ """
697
+ camera = self.get_camera()
698
+ if not camera.init(self.interface):
699
+ print("摄像头初始化失败")
700
+ return None
701
+ return camera.capture_image(save_path)
702
+
703
+ def start_video_stream(self, width=480, height=320):
704
+ """
705
+ 便利方法:开始视频流(按需初始化摄像头)
706
+
707
+ Args:
708
+ width (int): 视频宽度
709
+ height (int): 视频高度
710
+
711
+ Returns:
712
+ bool: 是否成功
713
+ """
714
+ camera = self.get_camera()
715
+ if not camera.init(self.interface):
716
+ print("摄像头初始化失败")
717
+ return False
718
+ return camera.start_stream(width, height)
719
+
720
+ def get_video_frame(self):
721
+ """
722
+ 便利方法:获取最新视频帧
723
+
724
+ Returns:
725
+ numpy.ndarray: 图像数据
726
+ """
727
+ if self.camera is None:
728
+ print("视频流未启动,请先调用 start_video_stream()")
729
+ return None
730
+ return self.camera.get_latest_frame()
731
+
732
+ def stop_video_stream(self):
733
+ """便利方法:停止视频流"""
734
+ if self.camera:
735
+ self.camera.stop_stream()
736
+
737
+ def cleanup(self):
738
+ """清理资源,停止所有连接和线程"""
739
+ if not self._initialized:
740
+ return
741
+
742
+ print("正在清理Go2资源...")
743
+
744
+ # 停止移动线程
745
+ self._moving = False
746
+ if (hasattr(self, '_move_thread') and
747
+ self._move_thread is not None and
748
+ self._move_thread.is_alive()):
749
+ self._move_thread.join(timeout=1.0)
750
+ self._move_thread = None
751
+
752
+ # 清理摄像头资源
753
+ if self.camera is not None:
754
+ try:
755
+ self.camera.cleanup()
756
+ self.camera = None
757
+ except:
758
+ pass
759
+
760
+ # 释放视频流
761
+ if self.cap is not None:
762
+ try:
763
+ self.cap.release()
764
+ self.cap = None
765
+ except:
766
+ pass
767
+
768
+ # 清理DDS连接
769
+ try:
770
+ from unitree_sdk2py.core.channel import ChannelFactoryRelease
771
+ ChannelFactoryRelease()
772
+ except:
773
+ pass
774
+
775
+ self._initialized = False
776
+ print("Go2资源清理完成")
777
+
778
+ def __del__(self):
779
+ """析构函数,自动清理资源"""
780
+ try:
781
+ self.cleanup()
782
+ except:
783
+ pass
784
+
785
+
786
+
787
+
788
+ # -------------------- 测试 --------------------
789
+ if __name__ == "__main__":
790
+ interface = "enx00e0986113a6" # 替换为你的Go2网卡接口名称
791
+
792
+ go2 = Go2(interface=interface)
793
+
794
+ go2.stand_down()
795
+ go2.stand_up()