qt5.py
25.6 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
from PyQt5.QtCore import pyqtSlot, QObject, QTimer, pyqtSignal, QMutex, QMutexLocker, QThread, QEvent
from PyQt5.QtBluetooth import (QBluetoothDeviceDiscoveryAgent, QLowEnergyController,
QBluetoothUuid, QLowEnergyService, QLowEnergyCharacteristic,
QLowEnergyDescriptor, QBluetoothDeviceInfo, QBluetoothServiceDiscoveryAgent,
QBluetoothSocket, QBluetoothServiceInfo)
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QVBoxLayout, QWidget, QPushButton, QHBoxLayout
from PyQt5.QtWebSockets import QWebSocketServer, QWebSocket
from PyQt5.QtNetwork import QHostAddress
class BluetoothDeviceScanner(QObject):
deviceDiscovered = pyqtSignal(QBluetoothDeviceInfo)
scanFinished = pyqtSignal()
deviceConnected = pyqtSignal(QLowEnergyController)
def __init__(self, parent=None, target_uuid="00001523-1212-efde-1523-785feabcd123"):
super().__init__(parent)
self.target_uuid = target_uuid
self.discovery_agent = QBluetoothDeviceDiscoveryAgent(self)
# 配置扫描参数 - 低功耗设备需要更长的扫描时间
self.discovery_agent.setLowEnergyDiscoveryTimeout(10000) # 10秒的扫描时间
# 配置扫描方式,包括低功耗设备和经典蓝牙设备
self.discovery_agent.setInquiryType(QBluetoothDeviceDiscoveryAgent.GeneralUnlimitedInquiry)
# 连接信号
self.discovery_agent.deviceDiscovered.connect(self.on_device_discovered)
self.discovery_agent.finished.connect(self.on_scan_finished)
self.discovery_agent.error.connect(self.on_error)
self.controllers = {} # Store controllers by device address
self.target_device = None
self.discovered_devices = {} # 存储所有发现的设备,避免重复处理
# 添加自动重试机制
self.scan_retry_count = 0
self.max_scan_retries = 2 # 最多重试2次,加上第一次共3次
self.connection_retry_count = 0
self.max_connection_retries = 2
# 创建计时器用于延迟重试
self.retry_timer = QTimer(self)
self.retry_timer.setSingleShot(True)
self.retry_timer.timeout.connect(self.retry_scan)
# 记录已经尝试过连接的设备
self.connection_attempts = set()
def start_scan(self):
"""开始扫描蓝牙设备"""
print("开始蓝牙设备扫描...")
self.scan_retry_count = 0
self.discovered_devices.clear()
self.connection_attempts.clear()
self.target_device = None
# 设置更广泛的设备类型过滤
self.discovery_agent.start()
def stop_scan(self):
"""停止设备扫描"""
self.discovery_agent.stop()
self.retry_timer.stop()
print("蓝牙设备扫描已停止")
def retry_scan(self):
"""重试扫描,用于当扫描失败或未找到目标设备时"""
if self.scan_retry_count < self.max_scan_retries and not self.target_device:
self.scan_retry_count += 1
print(f"重试扫描 ({self.scan_retry_count}/{self.max_scan_retries})...")
self.discovery_agent.start()
@pyqtSlot(QBluetoothDeviceInfo)
def on_device_discovered(self, device_info):
"""当发现蓝牙设备时调用"""
device_name = device_info.name() or "未命名设备"
device_address = device_info.address().toString()
# 如果已经处理过这个设备,则直接返回,除非是我们感兴趣的目标设备
if device_address in self.discovered_devices and "LPF2" not in device_name:
return
# 存储设备信息
self.discovered_devices[device_address] = device_info
# 分析设备类型
device_type = "未知"
# 获取主要和次要设备类别
major_class = device_info.majorDeviceClass()
minor_class = device_info.minorDeviceClass()
print(f"调试信息 - 主类别: {major_class}, 次类别: {minor_class}")
# 识别设备类别
if (major_class == QBluetoothDeviceInfo.MiscellaneousDevice or major_class == 0) and "LPF2" in device_name:
device_type = "LEGO智能集线器"
elif major_class == QBluetoothDeviceInfo.ToyDevice:
if minor_class == 0x01:
device_type = "玩具机器人"
elif minor_class == 0x02:
device_type = "玩具车辆"
else:
device_type = "玩具"
elif major_class == QBluetoothDeviceInfo.ComputerDevice:
device_type = "电脑"
elif major_class == QBluetoothDeviceInfo.PhoneDevice:
device_type = "手机"
elif major_class == QBluetoothDeviceInfo.AudioVideoDevice:
device_type = "音频/视频设备"
elif major_class == QBluetoothDeviceInfo.NetworkDevice:
device_type = "网络设备"
elif major_class == QBluetoothDeviceInfo.PeripheralDevice:
if minor_class & 0x04: # 键盘
device_type = "键盘"
elif minor_class & 0x08: # 鼠标
device_type = "鼠标"
elif minor_class & 0x10: # 组合键盘/鼠标
device_type = "键盘/鼠标组合"
elif minor_class & 0x40: # 游戏杆
device_type = "游戏杆"
elif minor_class & 0x80: # 游戏手柄
device_type = "游戏手柄"
else:
device_type = "外围设备"
elif major_class == QBluetoothDeviceInfo.ImagingDevice:
device_type = "成像设备"
elif major_class == QBluetoothDeviceInfo.WearableDevice:
device_type = "可穿戴设备"
elif major_class == QBluetoothDeviceInfo.HealthDevice:
device_type = "健康设备"
# 基于设备名称的额外分类
if device_type == "未知":
if "lego" in device_name.lower() or "lpf2" in device_name.lower():
device_type = "LEGO智能集线器"
elif "hub" in device_name.lower():
device_type = "智能集线器"
elif "watch" in device_name.lower():
device_type = "智能手表"
elif "speaker" in device_name.lower() or "headphone" in device_name.lower() or "airpod" in device_name.lower():
device_type = "音频设备"
elif "fitness" in device_name.lower() or "band" in device_name.lower():
device_type = "健身追踪器"
print(f"发现设备: {device_name} ({device_address}) - 类型: {device_type}")
# 获取额外的设备信息
rssi = device_info.rssi()
if rssi != 0:
print(f"信号强度 (RSSI): {rssi} dBm")
# 检查制造商特定数据
manufacturer_data = device_info.manufacturerData()
if manufacturer_data:
print(f"制造商数据可用: {len(manufacturer_data)} 字节")
for manufacturer_id, data in manufacturer_data.items():
# 将QByteArray转换为十六进制字符串
data_bytes = bytes(data)
hex_string = data_bytes.hex() if hasattr(data_bytes, 'hex') else ' '.join([f'{b:02x}' for b in data_bytes])
print(f"制造商ID: {manufacturer_id:04x}, 数据: {hex_string}")
# 获取服务UUID(如果可用)
service_uuids = device_info.serviceUuids()
if service_uuids:
print(f"服务UUID数量: {len(service_uuids)}")
for uuid_obj in service_uuids:
if isinstance(uuid_obj, QBluetoothUuid):
uuid_str = uuid_obj.toString()
print(f" - {uuid_str}")
# 连接决策逻辑 - 优先级从高到低
should_connect = False
connection_reason = ""
# 优先级1: 检查设备是否有与目标UUID匹配的服务
if service_uuids:
for uuid_obj in service_uuids:
if isinstance(uuid_obj, QBluetoothUuid):
uuid_str = uuid_obj.toString().lower()
if uuid_str == self.target_uuid.lower():
should_connect = True
connection_reason = "匹配服务UUID"
break
# 优先级2: 特别处理LEGO设备 - 通常只是基于名称
if not should_connect and "LPF2" in device_name:
should_connect = True
connection_reason = "LEGO智能集线器"
# 优先级3: 设备地址或名称包含目标UUID前缀
if not should_connect and self.target_uuid:
if (self.target_uuid[:8].lower() in device_address.lower() or
(device_name and self.target_uuid[:8].lower() in device_name.lower())):
should_connect = True
connection_reason = "UUID前缀匹配名称/地址"
# 优先级4: 如果信号强度很好,并且是玩具类型设备
if not should_connect and rssi > -60 and (device_type.startswith("玩具") or device_type.startswith("LEGO")):
should_connect = True
connection_reason = "强信号玩具设备"
# 如果决定连接,并且之前没有尝试过
if should_connect and device_address not in self.connection_attempts:
print(f"尝试连接设备: {device_name} (原因: {connection_reason})")
self.connection_attempts.add(device_address) # 标记为已尝试
self.target_device = device_info
self.connect_to_device(device_info)
# 找到了可能的目标,停止扫描
if "LPF2" in device_name:
self.discovery_agent.stop()
self.deviceDiscovered.emit(device_info)
@pyqtSlot()
def on_scan_finished(self):
"""当设备扫描完成时调用"""
print("蓝牙扫描完成")
# 如果我们还没有找到目标设备,但又发现了一些设备,则选择一个尝试连接
if not self.target_device and self.discovered_devices:
print("没有通过UUID找到目标设备,尝试连接发现的设备...")
# 首先尝试连接任何包含"LPF2"的设备
for addr, device_info in self.discovered_devices.items():
if "LPF2" in device_info.name() and addr not in self.connection_attempts:
print(f"尝试连接: {device_info.name()} (LEGO设备)")
self.connection_attempts.add(addr)
self.target_device = device_info
self.connect_to_device(device_info)
break
# 如果还没有目标设备,尝试基于信号强度来选择设备
if not self.target_device:
# 按信号强度排序设备
devices_by_signal = sorted(
[(addr, info) for addr, info in self.discovered_devices.items() if addr not in self.connection_attempts],
key=lambda x: x[1].rssi(), reverse=True # 最强信号优先
)
if devices_by_signal:
addr, device_info = devices_by_signal[0]
print(f"尝试连接: {device_info.name()} (最强信号设备)")
self.connection_attempts.add(addr)
self.target_device = device_info
self.connect_to_device(device_info)
# 如果仍未找到设备,考虑重试扫描
if not self.target_device and self.scan_retry_count < self.max_scan_retries:
print(f"没有找到合适的设备,将在2秒后重试扫描... (已尝试 {self.scan_retry_count+1}/{self.max_scan_retries+1})")
self.retry_timer.start(2000) # 2秒后重试
else:
if not self.target_device:
print("经过多次尝试后仍未找到目标设备。")
self.scanFinished.emit()
@pyqtSlot(QBluetoothDeviceDiscoveryAgent.Error)
def on_error(self, error):
"""处理发现错误"""
error_str = "未知错误"
if error == QBluetoothDeviceDiscoveryAgent.PoweredOffError:
error_str = "蓝牙已关闭"
elif error == QBluetoothDeviceDiscoveryAgent.InputOutputError:
error_str = "蓝牙I/O错误"
elif error == QBluetoothDeviceDiscoveryAgent.InvalidBluetoothAdapterError:
error_str = "无效的蓝牙适配器"
elif error == QBluetoothDeviceDiscoveryAgent.UnsupportedPlatformError:
error_str = "不支持的平台"
elif error == QBluetoothDeviceDiscoveryAgent.UnsupportedDiscoveryMethod:
error_str = "不支持的发现方法"
elif error == QBluetoothDeviceDiscoveryAgent.ResourceError:
error_str = "资源错误"
print(f"蓝牙发现错误: {error_str}")
# 如果遇到错误,也考虑重试
if self.scan_retry_count < self.max_scan_retries:
print(f"因错误将在3秒后重试扫描...")
self.retry_timer.start(3000) # 3秒后重试
def connect_to_device(self, device_info):
"""连接到指定设备"""
print(f"正在连接 {device_info.name()}...")
# 创建设备控制器
controller = QLowEnergyController.createCentral(device_info)
device_address = device_info.address().toString()
self.controllers[device_address] = controller
# 连接控制器信号
controller.connected.connect(self.on_device_connected)
controller.disconnected.connect(self.on_device_disconnected)
controller.error.connect(self.on_controller_error)
controller.serviceDiscovered.connect(self.on_service_discovered)
controller.discoveryFinished.connect(self.on_service_discovery_finished)
# 连接超时计时器
connection_timer = QTimer(self)
connection_timer.setSingleShot(True)
connection_timer.timeout.connect(lambda: self.on_connection_timeout(device_address, connection_timer))
connection_timer.start(5000) # 5秒连接超时
# 存储计时器以便稍后引用
controller.property_connection_timer = connection_timer
# 连接到设备
controller.connectToDevice()
def on_connection_timeout(self, device_address, timer):
"""处理连接超时"""
if device_address in self.controllers:
controller = self.controllers[device_address]
# 在PyQt5中,QLowEnergyController没有isConnected()方法
# 改用state()方法检查连接状态
if controller.state() != QLowEnergyController.ConnectedState:
print(f"连接到 {controller.remoteName()} 超时")
# 删除连接尝试记录,以便后续可以再次尝试
if device_address in self.connection_attempts:
self.connection_attempts.remove(device_address)
# 设置为null,这样我们可以尝试其他设备
if self.target_device and self.target_device.address().toString() == device_address:
self.target_device = None
# 重新开始扫描,如果我们已经尝试了最大重试次数
if not self.discovery_agent.isActive() and self.scan_retry_count < self.max_scan_retries:
print("将重新开始扫描...")
self.retry_timer.start(1000) # 1秒后重试
@pyqtSlot()
def on_device_connected(self):
"""当连接到设备时调用"""
controller = self.sender()
print(f"已连接到 {controller.remoteName()}")
self.deviceConnected.emit(controller)
# 停止连接超时计时器
if hasattr(controller, 'property_connection_timer'):
controller.property_connection_timer.stop()
# 发现服务
controller.discoverServices()
@pyqtSlot()
def on_device_disconnected(self):
"""当从设备断开连接时调用"""
controller = self.sender()
device_address = ""
# 找到这个控制器的地址
for addr, ctrl in self.controllers.items():
if ctrl == controller:
device_address = addr
break
print(f"从 {controller.remoteName()} 断开连接")
# 如果这是我们当前的目标设备,清除它,以便我们可以尝试另一个
if self.target_device and self.target_device.address().toString() == device_address:
self.target_device = None
# 如果当前没有在扫描,并且我们还有剩余的重试次数,则重新开始扫描
if not self.discovery_agent.isActive() and self.scan_retry_count < self.max_scan_retries:
print("设备断开连接,将重新开始扫描...")
self.retry_timer.start(1000) # 1秒后重试
@pyqtSlot(QLowEnergyController.Error)
def on_controller_error(self, error):
"""处理控制器错误"""
controller = self.sender()
device_address = ""
# 找到这个控制器的地址
for addr, ctrl in self.controllers.items():
if ctrl == controller:
device_address = addr
break
error_str = "未知错误"
if error == QLowEnergyController.UnknownError:
error_str = "未知错误"
elif error == QLowEnergyController.RemoteHostClosedError:
error_str = "远程主机关闭了连接"
elif error == QLowEnergyController.ConnectionError:
error_str = "连接错误"
print(f"控制器错误 ({controller.remoteName()}): {error_str}")
# 如果是我们当前的目标设备,清除它并尝试另一个
if self.target_device and self.target_device.address().toString() == device_address:
# 从尝试列表中移除,以便后续可以重新尝试
if device_address in self.connection_attempts:
self.connection_attempts.remove(device_address)
self.target_device = None
# 如果当前没有在扫描,并且我们还有剩余的重试次数,则重新开始扫描
if not self.discovery_agent.isActive() and self.scan_retry_count < self.max_scan_retries:
print("因控制器错误将重新开始扫描...")
self.retry_timer.start(1000) # 1秒后重试
@pyqtSlot(QBluetoothUuid)
def on_service_discovered(self, uuid):
"""当在连接的设备上发现服务时调用"""
controller = self.sender()
print(f"在 {controller.remoteName()} 上发现服务: {uuid.toString()}")
@pyqtSlot()
def on_service_discovery_finished(self):
"""当服务发现完成时调用"""
controller = self.sender()
print(f"{controller.remoteName()} 的服务发现完成")
# 处理发现的服务
services_found = False
for service_uuid in controller.services():
service = controller.createServiceObject(service_uuid)
if service:
services_found = True
print(f"处理服务: {service_uuid.toString()}")
service.stateChanged.connect(self.on_service_state_changed)
service.characteristicChanged.connect(
lambda characteristic, value, service=service:
self.on_characteristic_changed(characteristic, value)
)
service.discoverDetails()
if not services_found:
print("未发现服务,可能需要特定的连接协议")
@pyqtSlot(QLowEnergyService.ServiceState)
def on_service_state_changed(self, state):
"""当服务状态改变时调用"""
service = self.sender()
if state == QLowEnergyService.ServiceDiscovered:
print(f"服务详情已发现: {service.serviceUuid().toString()}")
# 处理特性
for characteristic in service.characteristics():
print(f"发现特性: {characteristic.uuid().toString()}")
print(f" - 特性属性: {characteristic.properties()}")
# 如果这是一个可读特性,尝试读取它
if characteristic.properties() & QLowEnergyCharacteristic.Read:
print(f" - 读取特性值...")
service.readCharacteristic(characteristic)
# 如果这是一个可通知特性,尝试开启通知
if characteristic.properties() & QLowEnergyCharacteristic.Notify:
print(f" - 启用通知...")
try:
# PyQt5的QLowEnergyService没有descriptors()方法
# 我们可以直接尝试获取CCCD描述符
# 或者尝试直接写入特征来启用通知
descriptor = characteristic.descriptor(QBluetoothUuid(QBluetoothUuid.ClientCharacteristicConfiguration))
if descriptor.isValid():
print(f" - 找到客户端特性配置描述符")
service.writeDescriptor(descriptor, b"\x01\x00") # 启用通知
else:
print(f" - 未找到有效的客户端特性配置描述符")
# 某些实现可能支持以下方法
if hasattr(service, 'setNotifyValue'):
print(f" - 尝试使用setNotifyValue方法")
service.setNotifyValue(characteristic, True)
except Exception as e:
print(f" - 启用通知时出错: {e}")
print(f" - 将尝试特殊处理LEGO设备...")
# LEGO设备特殊处理 - 这是一种常见的方法
try:
if "LPF2" in service.controller().remoteName():
print(f" - 检测到LEGO设备,尝试特殊处理")
# 有些LEGO设备需要写入一个特定值到特性以启用通知
if characteristic.properties() & QLowEnergyCharacteristic.Write:
print(f" - 尝试写入特性来启用通知")
service.writeCharacteristic(characteristic, b"\x01\x00")
except Exception as e2:
print(f" - LEGO设备特殊处理失败: {e2}")
def on_characteristic_changed(self, characteristic, value):
"""当特性值改变时调用"""
try:
# 将QByteArray转换为十六进制字符串
if hasattr(value, 'data'): # 它是一个QByteArray
data_bytes = bytes(value)
hex_string = data_bytes.hex() if hasattr(data_bytes, 'hex') else ' '.join([f'{b:02x}' for b in data_bytes])
else: # 它可能已经是bytes
hex_string = value.hex() if hasattr(value, 'hex') else ' '.join([f'{b:02x}' for b in value])
print(f"特性 {characteristic.uuid().toString()} 值改变: {hex_string}")
# 解析数据 (示例)
print(f"数据解析: {' '.join([f'{b:02x}' for b in data_bytes])}")
except Exception as e:
print(f"处理特性变化时出错: {e}")
def main():
"""运行蓝牙扫描器的主函数"""
import sys
app = QApplication(sys.argv)
# 创建带有目标UUID的扫描器
scanner = BluetoothDeviceScanner(target_uuid="00001523-1212-efde-1523-785feabcd123")
# 创建简单的UI
window = QMainWindow()
window.setWindowTitle("蓝牙扫描器")
window.resize(700, 500)
central_widget = QWidget()
layout = QVBoxLayout(central_widget)
# 添加文本编辑框
text_edit = QTextEdit()
text_edit.setReadOnly(True)
layout.addWidget(text_edit)
# 添加按钮布局
button_layout = QHBoxLayout()
# 开始扫描按钮
start_scan_button = QPushButton("开始扫描")
start_scan_button.clicked.connect(scanner.start_scan)
button_layout.addWidget(start_scan_button)
# 停止扫描按钮
stop_scan_button = QPushButton("停止扫描")
stop_scan_button.clicked.connect(scanner.stop_scan)
button_layout.addWidget(stop_scan_button)
# 清除按钮
clear_button = QPushButton("清除日志")
clear_button.clicked.connect(text_edit.clear)
button_layout.addWidget(clear_button)
layout.addLayout(button_layout)
window.setCentralWidget(central_widget)
window.show()
# 重定向print语句到文本编辑框
import sys
original_stdout = sys.stdout
class TextEditRedirector:
def __init__(self, text_edit):
self.text_edit = text_edit
def write(self, text):
self.text_edit.append(text)
original_stdout.write(text)
def flush(self):
pass
sys.stdout = TextEditRedirector(text_edit)
# 自动开始第一次扫描
scanner.start_scan()
return app.exec_()
if __name__ == "__main__":
main()