|
1 | 1 | from __future__ import annotations |
| 2 | +import asyncio |
2 | 3 | from typing import TYPE_CHECKING |
3 | 4 | from bleak import BleakClient |
4 | 5 | from bleak.backends.device import BLEDevice |
@@ -73,18 +74,26 @@ def createBluetooth(self, vin: str, key: ec.EllipticCurvePrivateKey | None = Non |
73 | 74 | self[vin] = vehicle |
74 | 75 | return vehicle |
75 | 76 |
|
76 | | - async def query_device_name(self, device: BLEDevice, max_attempts=3) -> str: |
| 77 | + async def query_display_name(self, device: BLEDevice, max_attempts=5) -> str | None: |
77 | 78 | """Queries the name of a bluetooth vehicle.""" |
78 | | - async with await establish_connection( |
| 79 | + client = await establish_connection( |
79 | 80 | BleakClient, |
80 | 81 | device, |
81 | 82 | device.name or "Unknown", |
82 | 83 | max_attempts=max_attempts |
83 | | - ) as client: |
| 84 | + ) |
| 85 | + name: str | None = None |
| 86 | + for i in range(max_attempts): |
84 | 87 | try: |
85 | 88 | # Standard GATT Device Name characteristic (0x2A00) |
86 | | - device_name = await client.read_gatt_char(NAME_UUID) |
87 | | - return device_name.decode('utf-8').replace("🔑 ","") |
| 89 | + device_name = (await client.read_gatt_char(NAME_UUID)).decode('utf-8') |
| 90 | + if device_name.startswith("🔑 "): |
| 91 | + name = device_name.replace("🔑 ","") |
| 92 | + break |
| 93 | + await asyncio.sleep(1) |
| 94 | + LOGGER.debug(f"Attempt {i+1} to query display name failed, {device_name}") |
88 | 95 | except Exception as e: |
89 | 96 | LOGGER.error(f"Failed to read device name: {e}") |
90 | | - return None |
| 97 | + |
| 98 | + await client.disconnect() |
| 99 | + return name |
0 commit comments