8b08c35f by huangyf2

蓝牙双重discover

1 parent 1fb31449
Showing 1 changed file with 35 additions and 12 deletions
......@@ -127,6 +127,7 @@ class BLEClient:
self.notification_records = defaultdict(lambda: (None, 0.0)) # 特征ID: (最后消息, 时间戳)
self._notification_callbacks = {} # 存储通知回调,用于清理
self._shutdown = False # 添加关闭标志
self._scanner = None # 当前扫描器实例
def on_disconnect(self, client):
print("BLE连接断开,关闭WebSocket")
......@@ -159,8 +160,22 @@ class BLEClient:
print(f"制造商数据: {adv_data.manufacturer_data}")
print(f"服务数据: {adv_data.service_data}")
print(f"本地名称: {adv_data.local_name}")
# 发现设备后,尝试立即停止扫描
try:
if self._scanner is not None:
# 在事件循环中停止扫描,避免阻塞回调
asyncio.create_task(self._stop_scan_early())
except Exception:
pass
return self.target_device
async def _stop_scan_early(self):
try:
if self._scanner is not None:
await self._scanner.stop()
except Exception:
pass
async def handle_client(self, websocket, path):
self.websocket = websocket
if path != "/scratch/ble":
......@@ -186,24 +201,32 @@ class BLEClient:
self.services.extend(filt.get("services", []))
self.optional_services = params.get("optionalServices", [])
scanner = BleakScanner(scanning_mode="active")
scanner.register_detection_callback(self.detection_callback)
max_retries = 3
# 双重扫描:快速扫描后若未发现,再进行扩展扫描;发现即停
phases = [("active", 3.0), ("passive", 6.0)]
found = False
for attempt in range(max_retries):
for phase_index, (scan_mode, duration) in enumerate(phases, start=1):
self.target_device = None
await scanner.start()
await asyncio.sleep(5)
await scanner.stop()
self._scanner = BleakScanner(scanning_mode=scan_mode)
self._scanner.register_detection_callback(self.detection_callback)
print(f"开始第{phase_index}阶段扫描(模式: {scan_mode}, 时长: {duration}s)...")
try:
await self._scanner.start()
# 轮询检查是否已找到,找到则提前停止
start_ts = time.time()
while time.time() - start_ts < duration and not self.target_device:
await asyncio.sleep(0.1)
finally:
try:
await self._scanner.stop()
except Exception:
pass
self._scanner = None
if self.target_device:
found = True
break
if attempt < max_retries - 1:
print(f"未找到设备,第{attempt+1}次重试...")
await asyncio.sleep(3)
else:
print(f"第{phase_index}阶段未找到设备")
if found:
device, adv_data = self.target_device
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!