Skip to content

Commit dc64fe1

Browse files
authored
refactor: do same as previous test earlier (#326)
1 parent b9b43f4 commit dc64fe1

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

src/bthome_ble/parser.py

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,19 @@ def get_mic(service_data: bytes) -> bytes:
108108
return service_data[-4:]
109109

110110

111+
def find_bthome_uuid(service_info: BluetoothServiceInfoBleak) -> UuidType | None:
112+
"""Searches for the first bthome UUID."""
113+
# Iterates over a dictionary, and one device should use only
114+
# one of the 3 valid UUIDs. So there is as most one successful
115+
# iteration cycle and we can break afterwards safely.
116+
for uuid in service_info.service_data.keys():
117+
try:
118+
return UuidType(uuid)
119+
except ValueError:
120+
continue
121+
return None
122+
123+
111124
def get_encryption_scheme(uuid_type: UuidType, service_data: bytes) -> EncryptionScheme:
112125
"""
113126
Returns the encryption schema using the UUID for V1 and the
@@ -310,13 +323,15 @@ def supported(self, data: BluetoothServiceInfoBleak) -> bool:
310323
def _start_update(self, service_info: BluetoothServiceInfoBleak) -> None:
311324
"""Update from BLE advertisement data."""
312325
_LOGGER.debug("Parsing BTHome BLE advertisement data: %s", service_info)
313-
for uuid, service_data in service_info.service_data.items():
314-
if self._parse_bthome(uuid, service_info, service_data):
315-
self.last_service_info = service_info
316-
# Iterates over a dictionary, and one device should use only
317-
# one of the 3 valid UUIDs. So there is as most one successful
318-
# iteration cycle and we can break afterwards safely.
319-
break
326+
uuid_type = find_bthome_uuid(service_info)
327+
if uuid_type is None:
328+
return None
329+
service_data = service_info.service_data.get(uuid_type.value)
330+
self._set_encryption_scheme(uuid_type, service_data)
331+
if self._is_same_as_last(service_info):
332+
return None
333+
if self._parse_bthome(uuid_type, service_info, service_data):
334+
self.last_service_info = service_info
320335
return None
321336

322337
def _set_encryption_scheme(self, uuid: UuidType, service_data: bytes) -> None:
@@ -482,19 +497,11 @@ def _is_same_as_last(self, service_info: BluetoothServiceInfoBleak) -> bool:
482497

483498
def _parse_bthome(
484499
self,
485-
uuid: str,
500+
uuid_type: UuidType,
486501
service_info: BluetoothServiceInfoBleak,
487502
service_data: bytes,
488503
) -> bool:
489504
"""Parser for BTHome sensors"""
490-
try:
491-
uuid_type = UuidType(uuid)
492-
except ValueError:
493-
return False
494-
495-
self._set_encryption_scheme(uuid_type, service_data)
496-
if self._is_same_as_last(service_info):
497-
return True
498505
self._set_downgrade_detected(service_info)
499506
if self.downgrade_detected:
500507
return False

0 commit comments

Comments
 (0)