| 1 |
"""Parser for BLE advertisements in BTHome format. |
| 2 |
|
| 3 |
This file is shamelessly copied from the following repository: |
| 4 |
https://github.com/Ernst79/bleparser/blob/ac8757ad64f1fc17674dcd22111e547cdf2f205b/package/bleparser/ha_ble.py |
| 5 |
|
| 6 |
BTHome was originally developed as HA BLE for ble_monitor and has been renamed |
| 7 |
to BTHome for the Home Assistant Bluetooth integration. |
| 8 |
|
| 9 |
MIT License applies. |
| 10 |
""" |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import logging |
| 15 |
import struct |
| 16 |
from datetime import UTC, datetime |
| 17 |
from enum import Enum |
| 18 |
from typing import Any |
| 19 |
|
| 20 |
from bluetooth_data_tools import short_address |
| 21 |
from bluetooth_sensor_state_data import BluetoothData |
| 22 |
from cryptography.exceptions import InvalidTag |
| 23 |
from cryptography.hazmat.primitives.ciphers.aead import AESCCM |
| 24 |
from habluetooth import BluetoothServiceInfoBleak |
| 25 |
from sensor_state_data.description import ( |
| 26 |
BaseBinarySensorDescription, |
| 27 |
BaseSensorDescription, |
| 28 |
) |
| 29 |
|
| 30 |
from .const import MEAS_TYPES |
| 31 |
from .event import BUTTON_EVENTS, COMMAND_EVENTS, DIMMER_EVENTS, EventDeviceKeys |
| 32 |
|
| 33 |
_LOGGER = logging.getLogger(__name__) |
| 34 |
|
| 35 |
|
| 36 |
class EncryptionScheme(Enum): |
| 37 |
|
| 38 |
NONE = "none" |
| 39 |
|
| 40 |
|
| 41 |
BTHOME_BINDKEY = "bthome_bindkey" |
| 42 |
|
| 43 |
|
| 44 |
class UuidType(Enum): |
| 45 |
V1_NON_ENCRYPTED = "0000181c-0000-1000-8000-00805f9b34fb" |
| 46 |
V1_ENCRYPTED = "0000181e-0000-1000-8000-00805f9b34fb" |
| 47 |
V2 = "0000fcd2-0000-1000-8000-00805f9b34fb" |
| 48 |
|
| 49 |
|
| 50 |
class BTHomeVersion(Enum): |
| 51 |
INVALID = 0 |
| 52 |
V1 = 1 |
| 53 |
V2 = 2 |
| 54 |
|
| 55 |
|
| 56 |
def to_mac(addr: bytes) -> str: |
| 57 |
"""Return formatted MAC address.""" |
| 58 |
return ":".join(f"{i:02X}" for i in addr) |
| 59 |
|
| 60 |
|
| 61 |
def find_bthome_uuid(service_info: BluetoothServiceInfoBleak) -> UuidType | None: |
| 62 |
"""Searches for the first bthome UUID.""" |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
for uuid in service_info.service_data.keys(): |
| 67 |
try: |
| 68 |
return UuidType(uuid) |
| 69 |
except ValueError: |
| 70 |
continue |
| 71 |
return None |
| 72 |
|
| 73 |
|
| 74 |
def parse_uint(data_obj: bytes, factor: float = 1.0) -> float: |
| 75 |
"""Convert bytes (as unsigned integer) and factor to float.""" |
| 76 |
decimal_places = -int(f"{factor:e}".split("e")[-1]) |
| 77 |
return round( |
| 78 |
int.from_bytes(data_obj, "little", signed=False) * factor, decimal_places |
| 79 |
) |
| 80 |
|
| 81 |
|
| 82 |
def parse_int(data_obj: bytes, factor: float = 1.0) -> float: |
| 83 |
"""Convert bytes (as signed integer) and factor to float.""" |
| 84 |
decimal_places = -int(f"{factor:e}".split("e")[-1]) |
| 85 |
return round( |
| 86 |
int.from_bytes(data_obj, "little", signed=True) * factor, decimal_places |
| 87 |
) |
| 88 |
|
| 89 |
|
| 90 |
def parse_float(data_obj: bytes, factor: float = 1.0) -> float | None: |
| 91 |
"""Convert bytes (as float) and factor to float.""" |
| 92 |
decimal_places = -int(f"{factor:e}".split("e")[-1]) |
| 93 |
if len(data_obj) == 2: |
| 94 |
[val] = struct.unpack("<e", data_obj) |
| 95 |
elif len(data_obj) == 4: |
| 96 |
[val] = struct.unpack("<f", data_obj) |
| 97 |
elif len(data_obj) == 8: |
| 98 |
[val] = struct.unpack("<d", data_obj) |
| 99 |
else: |
| 100 |
_LOGGER.error("only 2, 4 or 8 byte long floats are supported in BTHome BLE") |
| 101 |
return None |
| 102 |
return round(val * factor, decimal_places) |
| 103 |
|
| 104 |
|
| 105 |
def parse_raw(data_obj: bytes) -> str | None: |
| 106 |
"""Convert bytes to raw hex string.""" |
| 107 |
return data_obj.hex() |
| 108 |
|
| 109 |
|
| 110 |
def parse_string(data_obj: bytes) -> str | None: |
| 111 |
"""Convert bytes to string.""" |
| 112 |
try: |
| 113 |
return data_obj.decode("UTF-8") |
| 114 |
except UnicodeDecodeError: |
| 115 |
_LOGGER.error( |
| 116 |
"BTHome data contains bytes that can't be decoded to a string (use UTF-8 encoding)" |
| 117 |
) |
| 118 |
return None |
| 119 |
|
| 120 |
|
| 121 |
def parse_timestamp(data_obj: bytes) -> datetime | None: |
| 122 |
"""Convert bytes to a datetime object.""" |
| 123 |
try: |
| 124 |
value = datetime.fromtimestamp( |
| 125 |
int.from_bytes(data_obj, "little", signed=False), tz=UTC |
| 126 |
) |
| 127 |
except ValueError: |
| 128 |
_LOGGER.error( |
| 129 |
"BTHome data contains bytes that can't be decoded to a datetime object" |
| 130 |
) |
| 131 |
return None |
| 132 |
return value |
| 133 |
|
| 134 |
|
| 135 |
def parse_event_type(event_device: str, data_obj: int) -> str | None: |
| 136 |
"""Convert bytes to event type.""" |
| 137 |
if event_device == "dimmer": |
| 138 |
event_type = DIMMER_EVENTS.get(data_obj) |
| 139 |
elif event_device == "button": |
| 140 |
event_type = BUTTON_EVENTS.get(data_obj) |
| 141 |
elif event_device == "command": |
| 142 |
event_type = COMMAND_EVENTS.get(data_obj) |
| 143 |
else: |
| 144 |
event_type = None |
| 145 |
return event_type |
| 146 |
|
| 147 |
|
| 148 |
def parse_event_properties( |
| 149 |
event_device: str, data_obj: bytes |
| 150 |
) -> dict[str, str | int | float | None] | None: |
| 151 |
"""Convert bytes to event properties.""" |
| 152 |
if event_device == "dimmer": |
| 153 |
|
| 154 |
|
| 155 |
return {"steps": int.from_bytes(data_obj, "little", signed=False)} |
| 156 |
elif event_device == "command": |
| 157 |
|
| 158 |
return {"args": data_obj.hex()} |
| 159 |
else: |
| 160 |
return None |
| 161 |
|
| 162 |
|
| 163 |
class BTHomeData: |
| 164 |
def __init__( |
| 165 |
self, |
| 166 |
service_info: BluetoothServiceInfoBleak, |
| 167 |
): |
| 168 |
uuid_type = find_bthome_uuid(service_info) |
| 169 |
if uuid_type is None: |
| 170 |
raise ValueError |
| 171 |
self.uuid_type = uuid_type |
| 172 |
self.service_info = service_info |
| 173 |
|
| 174 |
def get_address(self) -> str: |
| 175 |
"""Returns the mac address.""" |
| 176 |
return self.service_info.address |
| 177 |
|
| 178 |
def get_time(self) -> float: |
| 179 |
"""Returns the time stamp.""" |
| 180 |
return self.service_info.time |
| 181 |
|
| 182 |
def _get_service_data(self) -> bytes: |
| 183 |
"""Returns the bthome service data.""" |
| 184 |
return self.service_info.service_data.get(self.uuid_type.value) |
| 185 |
|
| 186 |
def _get_adv_info(self) -> int: |
| 187 |
"""Extracts the advertisement info.""" |
| 188 |
return self._get_service_data()[0] |
| 189 |
|
| 190 |
def _is_encrypted(self) -> bool: |
| 191 |
"""Checks if the encryption flag is set.""" |
| 192 |
return bool(self._get_adv_info() & (1 << 0)) |
| 193 |
|
| 194 |
def _is_mac_included(self) -> bool: |
| 195 |
"""Checks if the MAC is included flag is set.""" |
| 196 |
|
| 197 |
return bool(self._get_adv_info() & (1 << 1)) |
| 198 |
|
| 199 |
def _is_sleepy_device(self) -> bool: |
| 200 |
"""Checks if device has sleepy flag set.""" |
| 201 |
|
| 202 |
return bool(self._get_adv_info() & (1 << 2)) |
| 203 |
|
| 204 |
def _get_version(self) -> int: |
| 205 |
"""Extracts the version from the advertisement info.""" |
| 206 |
return (self._get_adv_info() >> 5) & 7 |
| 207 |
|
| 208 |
def _get_mac(self) -> str: |
| 209 |
"""Extracts the MAC.""" |
| 210 |
bthome_mac_reversed = self._get_service_data()[1:7] |
| 211 |
return to_mac(bthome_mac_reversed[::-1]) |
| 212 |
|
| 213 |
def _get_payload(self) -> bytes: |
| 214 |
"""Extracts the payload (removes MAC and advertisement info).""" |
| 215 |
if self._is_mac_included(): |
| 216 |
return self._get_service_data()[7:] |
| 217 |
return self._get_service_data()[1:] |
| 218 |
|
| 219 |
def get_counter(self) -> bytes: |
| 220 |
"""Extracts the encryption counter bytes.""" |
| 221 |
return self._get_service_data()[-8:-4] |
| 222 |
|
| 223 |
def get_mic(self) -> bytes: |
| 224 |
"""Extracts the encryption mic.""" |
| 225 |
return self._get_service_data()[-4:] |
| 226 |
|
| 227 |
def get_encryption_scheme(self) -> EncryptionScheme: |
| 228 |
""" |
| 229 |
Returns the encryption schema using the UUID for V1 and the |
| 230 |
advertisement info flag for V2. |
| 231 |
""" |
| 232 |
match self.uuid_type: |
| 233 |
case UuidType.V1_NON_ENCRYPTED: |
| 234 |
return EncryptionScheme.NONE |
| 235 |
case UuidType.V1_ENCRYPTED: |
| 236 |
return EncryptionScheme.BTHOME_BINDKEY |
| 237 |
case UuidType.V2: |
| 238 |
if self._is_encrypted(): |
| 239 |
return EncryptionScheme.BTHOME_BINDKEY |
| 240 |
return EncryptionScheme.NONE |
| 241 |
|
| 242 |
def get_bthome_version(self) -> BTHomeVersion: |
| 243 |
""" |
| 244 |
Returns the bhtome version based on UUID for V1 and version bits from |
| 245 |
advertisement info for V2 |
| 246 |
""" |
| 247 |
match self.uuid_type: |
| 248 |
case UuidType.V1_NON_ENCRYPTED | UuidType.V1_ENCRYPTED: |
| 249 |
return BTHomeVersion.V1 |
| 250 |
case UuidType.V2: |
| 251 |
sw_version = self._get_version() |
| 252 |
if sw_version != 2: |
| 253 |
identifier = short_address(self.service_info.address) |
| 254 |
_LOGGER.error( |
| 255 |
"%s: Sensor is set to use BTHome version %s, which is not existing. " |
| 256 |
"Please modify the version in the first byte of the service data", |
| 257 |
identifier, |
| 258 |
sw_version, |
| 259 |
) |
| 260 |
return BTHomeVersion.INVALID |
| 261 |
return BTHomeVersion.V2 |
| 262 |
|
| 263 |
def get_name(self) -> str: |
| 264 |
"""Returns the name of the device.""" |
| 265 |
name = self.service_info.name |
| 266 |
|
| 267 |
if name == self.get_address(): |
| 268 |
name = "BTHome sensor" |
| 269 |
|
| 270 |
|
| 271 |
atc_identifier = ( |
| 272 |
self.get_address().replace("-", "").replace(":", "")[-6:].upper() |
| 273 |
) |
| 274 |
if name[-6:] == atc_identifier: |
| 275 |
name = name[:-6].rstrip(" _") |
| 276 |
return name |
| 277 |
|
| 278 |
def is_sleepy_device(self) -> bool: |
| 279 |
"""Return True if the device is sleepy, False otherwise.""" |
| 280 |
match self.get_bthome_version(): |
| 281 |
case BTHomeVersion.V1: |
| 282 |
return False |
| 283 |
case BTHomeVersion.V2: |
| 284 |
return self._is_sleepy_device() |
| 285 |
case _: |
| 286 |
raise ValueError |
| 287 |
|
| 288 |
def get_nounce_uuid(self) -> bytes: |
| 289 |
"""Returns the UUID for the nounce.""" |
| 290 |
match self.get_bthome_version(): |
| 291 |
case BTHomeVersion.V1: |
| 292 |
return b"\x1e\x18" |
| 293 |
case BTHomeVersion.V2: |
| 294 |
adv_info = self._get_adv_info() |
| 295 |
return b"\xd2\xfc" + bytes([adv_info]) |
| 296 |
case _: |
| 297 |
raise ValueError |
| 298 |
|
| 299 |
def get_mac_readable(self) -> str: |
| 300 |
"""Returns the mac address. If included in payload returns that one.""" |
| 301 |
match self.get_bthome_version(): |
| 302 |
case BTHomeVersion.V1: |
| 303 |
return self.get_address() |
| 304 |
case BTHomeVersion.V2: |
| 305 |
if self._is_mac_included(): |
| 306 |
return self._get_mac() |
| 307 |
return self.get_address() |
| 308 |
case _: |
| 309 |
raise ValueError |
| 310 |
|
| 311 |
def get_associated_data(self) -> bytes | None: |
| 312 |
"""Defines associated data for decryption depending on bthome version.""" |
| 313 |
match self.get_bthome_version(): |
| 314 |
case BTHomeVersion.V1: |
| 315 |
return b"\x11" |
| 316 |
case BTHomeVersion.V2: |
| 317 |
return None |
| 318 |
case _: |
| 319 |
raise ValueError |
| 320 |
|
| 321 |
def get_payload(self) -> bytes: |
| 322 |
"""Returns the payload.""" |
| 323 |
match self.get_bthome_version(): |
| 324 |
case BTHomeVersion.V1: |
| 325 |
return self._get_service_data() |
| 326 |
case BTHomeVersion.V2: |
| 327 |
return self._get_payload() |
| 328 |
case _: |
| 329 |
raise ValueError |
| 330 |
|
| 331 |
def get_encrypted_payload(self) -> bytes: |
| 332 |
"""Removes the last 8 bytes (mic and encryption counter) from payload.""" |
| 333 |
return self.get_payload()[:-8] |
| 334 |
|
| 335 |
def get_nonce(self) -> bytes: |
| 336 |
"""Creates the nounce for decryption.""" |
| 337 |
counter = self.get_counter() |
| 338 |
mac_readable = self.get_mac_readable() |
| 339 |
bthome_mac = bytes.fromhex(mac_readable.replace(":", "")) |
| 340 |
uuid = self.get_nounce_uuid() |
| 341 |
|
| 342 |
return b"".join([bthome_mac, uuid, counter]) |
| 343 |
|
| 344 |
def get_minimum_payload_length(self) -> int: |
| 345 |
"""Returns the minimum payload length.""" |
| 346 |
match self.get_bthome_version(): |
| 347 |
case BTHomeVersion.V1: |
| 348 |
return 4 |
| 349 |
case BTHomeVersion.V2: |
| 350 |
return 2 |
| 351 |
case _: |
| 352 |
raise ValueError |
| 353 |
|
| 354 |
|
| 355 |
class BTHomeBluetoothDeviceData(BluetoothData): |
| 356 |
"""Data for BTHome Bluetooth devices.""" |
| 357 |
|
| 358 |
def __init__(self, bindkey: bytes | None = None) -> None: |
| 359 |
super().__init__() |
| 360 |
self.set_bindkey(bindkey) |
| 361 |
|
| 362 |
|
| 363 |
self.unhandled: dict[str, Any] = {} |
| 364 |
|
| 365 |
|
| 366 |
self.encryption_scheme = EncryptionScheme.NONE |
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
self.encryption_counter = 0.0 |
| 372 |
|
| 373 |
|
| 374 |
self.packet_id: float | None = None |
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
self.bindkey_verified = False |
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
self.decryption_failed = True |
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
self.pending = True |
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
self.last_service_info: BluetoothServiceInfoBleak | None = None |
| 394 |
|
| 395 |
|
| 396 |
self.sleepy_device = False |
| 397 |
|
| 398 |
|
| 399 |
self.bthome_version: BTHomeVersion = BTHomeVersion.INVALID |
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
self.device_type_id: int | None = None |
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
self.downgrade_detected = False |
| 409 |
|
| 410 |
def set_bindkey(self, bindkey: bytes | None) -> None: |
| 411 |
"""Set the bindkey.""" |
| 412 |
self.bindkey = bindkey |
| 413 |
if bindkey: |
| 414 |
self.cipher: AESCCM | None = AESCCM(bindkey, tag_length=4) |
| 415 |
else: |
| 416 |
self.cipher = None |
| 417 |
|
| 418 |
def reset_encryption_counter(self) -> None: |
| 419 |
"""Reset the tracked encryption counter. |
| 420 |
|
| 421 |
Use this when the device's AES-CCM counter is known to have restarted |
| 422 |
from an arbitrary value (e.g. after a battery replacement on a device |
| 423 |
that seeds the counter with a random initial value). Resets the |
| 424 |
tracked counter so the next advertisement is accepted regardless of |
| 425 |
its counter value; replay protection resumes from there. |
| 426 |
""" |
| 427 |
self.encryption_counter = 0.0 |
| 428 |
|
| 429 |
def supported(self, data: BluetoothServiceInfoBleak) -> bool: |
| 430 |
if not super().supported(data): |
| 431 |
return False |
| 432 |
return True |
| 433 |
|
| 434 |
def _start_update(self, service_info: BluetoothServiceInfoBleak) -> None: |
| 435 |
"""Update from BLE advertisement data.""" |
| 436 |
_LOGGER.debug("Parsing BTHome BLE advertisement data: %s", service_info) |
| 437 |
try: |
| 438 |
bthome_data = BTHomeData(service_info) |
| 439 |
except ValueError: |
| 440 |
return None |
| 441 |
|
| 442 |
self.encryption_scheme = bthome_data.get_encryption_scheme() |
| 443 |
if self._is_same_as_last(service_info): |
| 444 |
return None |
| 445 |
if self._parse_bthome(bthome_data): |
| 446 |
self.last_service_info = service_info |
| 447 |
return None |
| 448 |
|
| 449 |
def _set_downgrade_detected(self, bthome_data: BTHomeData) -> None: |
| 450 |
"""Sets the downgrade_detected flag if bindkey is set and encryption scheme not NONE.""" |
| 451 |
if self.bindkey and self.encryption_scheme == EncryptionScheme.NONE: |
| 452 |
identifier = short_address(bthome_data.get_address()) |
| 453 |
_LOGGER.warning( |
| 454 |
"Received plaintext adv from %s while bindkey is known, ignoring!", |
| 455 |
identifier, |
| 456 |
) |
| 457 |
self.downgrade_detected = True |
| 458 |
return |
| 459 |
|
| 460 |
|
| 461 |
self.downgrade_detected = False |
| 462 |
|
| 463 |
def _set_bthome_version( |
| 464 |
self, |
| 465 |
bthome_data: BTHomeData, |
| 466 |
) -> None: |
| 467 |
"""Sets the bthome_version field and device's software version.""" |
| 468 |
self.bthome_version = bthome_data.get_bthome_version() |
| 469 |
|
| 470 |
|
| 471 |
match self.encryption_scheme: |
| 472 |
case EncryptionScheme.NONE: |
| 473 |
self.set_device_sw_version(f"BTHome BLE v{self.bthome_version.value}") |
| 474 |
case EncryptionScheme.BTHOME_BINDKEY: |
| 475 |
self.set_device_sw_version( |
| 476 |
f"BTHome BLE v{self.bthome_version.value} (encrypted)" |
| 477 |
) |
| 478 |
|
| 479 |
def _set_manufacture_name_type_and_title(self, bthome_data: BTHomeData) -> None: |
| 480 |
"""Sets device type, manufacturer, name and title based on name and mac address.""" |
| 481 |
|
| 482 |
identifier = short_address(bthome_data.get_address()) |
| 483 |
name = bthome_data.get_name() |
| 484 |
if name.startswith(("ATC", "LYWSD03MMC")): |
| 485 |
manufacturer = "Xiaomi" |
| 486 |
device_type = "Temperature/Humidity sensor" |
| 487 |
elif name.startswith("prst"): |
| 488 |
manufacturer = "b-parasite" |
| 489 |
name = "b-parasite" |
| 490 |
device_type = "Plant sensor" |
| 491 |
elif name == "SBBT-002C": |
| 492 |
manufacturer = "Shelly" |
| 493 |
name = "Shelly BLU Button1" |
| 494 |
device_type = "BLU Button1" |
| 495 |
elif name == "SBBT-102C": |
| 496 |
manufacturer = "Shelly" |
| 497 |
name = "Shelly BLU Button1 ZB" |
| 498 |
device_type = "BLU Button1 ZB" |
| 499 |
elif name == "SBDW-002C": |
| 500 |
manufacturer = "Shelly" |
| 501 |
name = "Shelly BLU Door/Window" |
| 502 |
device_type = "BLU Door/Window" |
| 503 |
elif name == "SBMO-003Z": |
| 504 |
manufacturer = "Shelly" |
| 505 |
name = "Shelly BLU Motion" |
| 506 |
device_type = "BLU Motion" |
| 507 |
elif name == "SBHT-003C": |
| 508 |
manufacturer = "Shelly" |
| 509 |
name = "Shelly BLU H&T" |
| 510 |
device_type = "BLU H&T" |
| 511 |
elif name == "SBHT-203C": |
| 512 |
manufacturer = "Shelly" |
| 513 |
name = "Shelly BLU H&T ZB" |
| 514 |
device_type = "BLU H&T ZB" |
| 515 |
elif name == "SBHT-103C": |
| 516 |
manufacturer = "Shelly" |
| 517 |
name = "Shelly BLU H&T Display ZB" |
| 518 |
device_type = "BLU H&T Display ZB" |
| 519 |
elif name == "SBBT-004CEU": |
| 520 |
manufacturer = "Shelly" |
| 521 |
name = "Shelly BLU Wall Switch 4" |
| 522 |
device_type = "BLU Wall Switch 4" |
| 523 |
elif name == "SBBT-004CUS": |
| 524 |
manufacturer = "Shelly" |
| 525 |
name = "Shelly BLU RC Button 4" |
| 526 |
device_type = "BLU RC Button 4" |
| 527 |
elif name == "SBTR-001AEU": |
| 528 |
manufacturer = "Shelly" |
| 529 |
name = "Shelly BLU TRV" |
| 530 |
device_type = "BLU TRV" |
| 531 |
else: |
| 532 |
manufacturer = None |
| 533 |
device_type = "BTHome sensor" |
| 534 |
if manufacturer: |
| 535 |
self.set_device_manufacturer(manufacturer) |
| 536 |
|
| 537 |
self.set_device_name(f"{name} {identifier}") |
| 538 |
self.set_title(f"{name} {identifier}") |
| 539 |
self.set_device_type(device_type) |
| 540 |
|
| 541 |
def _get_decrypted_payload( |
| 542 |
self, |
| 543 |
bthome_data: BTHomeData, |
| 544 |
) -> bytes | None: |
| 545 |
"""Returns the payload. Decrypts the payload if needed.""" |
| 546 |
match self.encryption_scheme: |
| 547 |
case EncryptionScheme.NONE: |
| 548 |
return bthome_data.get_payload() |
| 549 |
case EncryptionScheme.BTHOME_BINDKEY: |
| 550 |
try: |
| 551 |
return self._decrypt_bthome(bthome_data) |
| 552 |
except (ValueError, TypeError): |
| 553 |
return None |
| 554 |
|
| 555 |
def _is_same_as_last(self, service_info: BluetoothServiceInfoBleak) -> bool: |
| 556 |
""" |
| 557 |
Checks if the advertisement is encrypted and exactly the same as the previous |
| 558 |
advertisement. |
| 559 |
""" |
| 560 |
if ( |
| 561 |
self.last_service_info |
| 562 |
and self.encryption_scheme == EncryptionScheme.BTHOME_BINDKEY |
| 563 |
and service_info.time - self.last_service_info.time > 4 |
| 564 |
and service_info.service_data == self.last_service_info.service_data |
| 565 |
and self.bindkey_verified is True |
| 566 |
): |
| 567 |
_LOGGER.debug( |
| 568 |
"%s: The encrypted service data is the same as the previous service data. " |
| 569 |
"Skipping this BLE advertisement.", |
| 570 |
self.title, |
| 571 |
) |
| 572 |
return True |
| 573 |
return False |
| 574 |
|
| 575 |
def _parse_bthome( |
| 576 |
self, |
| 577 |
bthome_data: BTHomeData, |
| 578 |
) -> bool: |
| 579 |
"""Parser for BTHome sensors""" |
| 580 |
self._set_downgrade_detected(bthome_data) |
| 581 |
if self.downgrade_detected: |
| 582 |
return False |
| 583 |
if bthome_data.get_bthome_version() == BTHomeVersion.INVALID: |
| 584 |
return False |
| 585 |
self._set_bthome_version(bthome_data) |
| 586 |
self.sleepy_device = bthome_data.is_sleepy_device() |
| 587 |
self._set_manufacture_name_type_and_title(bthome_data) |
| 588 |
|
| 589 |
payload = self._get_decrypted_payload(bthome_data) |
| 590 |
if payload is None: |
| 591 |
return True |
| 592 |
return self._parse_payload(payload, bthome_data.get_time()) |
| 593 |
|
| 594 |
def _skip_old_or_duplicated_advertisement( |
| 595 |
self, new_packet_id: float, adv_time: float |
| 596 |
) -> bool: |
| 597 |
""" |
| 598 |
Detect duplicated or older packets |
| 599 |
|
| 600 |
Devices may send duplicated advertisements or advertisements order can change |
| 601 |
when passing through a proxy. If more than 4 seconds pass since the last |
| 602 |
advertisement assume it is a new packet even if it has the same packet id. |
| 603 |
Packet id rollover at 255 to 0, validate that the difference between last packet id |
| 604 |
and new packet id is less than 64. This assumes device is not sending more than 16 |
| 605 |
advertisements per second. |
| 606 |
""" |
| 607 |
last_packet_id = self.packet_id |
| 608 |
|
| 609 |
|
| 610 |
if last_packet_id is None or self.last_service_info is None: |
| 611 |
_LOGGER.debug( |
| 612 |
"%s: First packet, not filtering packet_id %i", |
| 613 |
self.title, |
| 614 |
new_packet_id, |
| 615 |
) |
| 616 |
return False |
| 617 |
|
| 618 |
|
| 619 |
if adv_time - self.last_service_info.time > 4: |
| 620 |
_LOGGER.debug( |
| 621 |
"%s: Not filtering packet_id, more than 4 seconds since last packet. " |
| 622 |
"New time: %i, Old time: %i", |
| 623 |
self.title, |
| 624 |
adv_time, |
| 625 |
self.last_service_info.time, |
| 626 |
) |
| 627 |
return False |
| 628 |
|
| 629 |
|
| 630 |
if (new_packet_id > last_packet_id and new_packet_id - last_packet_id < 64) or ( |
| 631 |
new_packet_id < last_packet_id and new_packet_id + 256 - last_packet_id < 64 |
| 632 |
): |
| 633 |
return False |
| 634 |
|
| 635 |
|
| 636 |
_LOGGER.debug( |
| 637 |
"%s: New packet_id %i indicates an older packet (previous packet_id %i). " |
| 638 |
"BLE advertisement will be skipped", |
| 639 |
self.title, |
| 640 |
new_packet_id, |
| 641 |
last_packet_id, |
| 642 |
) |
| 643 |
return True |
| 644 |
|
| 645 |
def _parse_payload(self, payload: bytes, adv_time: float) -> bool: |
| 646 |
payload_length = len(payload) |
| 647 |
next_obj_start = 0 |
| 648 |
prev_obj_meas_type = 0 |
| 649 |
result = False |
| 650 |
measurements: list[dict[str, Any]] = [] |
| 651 |
postfix_dict: dict[str, int] = {} |
| 652 |
obj_data_format: str | int |
| 653 |
|
| 654 |
|
| 655 |
while payload_length >= next_obj_start + 1: |
| 656 |
obj_start = next_obj_start |
| 657 |
|
| 658 |
match self.bthome_version: |
| 659 |
case BTHomeVersion.V1: |
| 660 |
if payload_length < obj_start + 2: |
| 661 |
_LOGGER.debug( |
| 662 |
"%s: Truncated V1 payload, missing measurement type byte: %s", |
| 663 |
self.title, |
| 664 |
payload.hex(), |
| 665 |
) |
| 666 |
break |
| 667 |
obj_meas_type = payload[obj_start + 1] |
| 668 |
obj_control_byte = payload[obj_start] |
| 669 |
obj_data_length = (obj_control_byte >> 0) & 31 |
| 670 |
obj_data_format = (obj_control_byte >> 5) & 7 |
| 671 |
obj_data_start = obj_start + 2 |
| 672 |
next_obj_start = obj_start + obj_data_length + 1 |
| 673 |
case BTHomeVersion.V2: |
| 674 |
obj_meas_type = payload[obj_start] |
| 675 |
if prev_obj_meas_type > obj_meas_type: |
| 676 |
_LOGGER.warning( |
| 677 |
"%s: BTHome device is not sending object ids in numerical order " |
| 678 |
"(from low to high object id). This can cause issues with your BTHome " |
| 679 |
"receiver, payload: %s", |
| 680 |
self.title, |
| 681 |
payload.hex(), |
| 682 |
) |
| 683 |
if obj_meas_type not in MEAS_TYPES: |
| 684 |
_LOGGER.debug( |
| 685 |
"%s: Invalid Object ID found in payload: %s", |
| 686 |
self.title, |
| 687 |
payload.hex(), |
| 688 |
) |
| 689 |
break |
| 690 |
prev_obj_meas_type = obj_meas_type |
| 691 |
obj_data_format = MEAS_TYPES[obj_meas_type].data_format |
| 692 |
|
| 693 |
if obj_data_format in ["raw", "string", "command"]: |
| 694 |
if payload_length < obj_start + 2: |
| 695 |
_LOGGER.debug( |
| 696 |
"%s: Truncated payload, missing length byte for " |
| 697 |
"%s object: %s", |
| 698 |
self.title, |
| 699 |
obj_data_format, |
| 700 |
payload.hex(), |
| 701 |
) |
| 702 |
break |
| 703 |
if obj_data_format == "command": |
| 704 |
|
| 705 |
args_length = payload[obj_start + 1] & 0x1F |
| 706 |
|
| 707 |
obj_data_length = 1 + args_length |
| 708 |
else: |
| 709 |
obj_data_length = payload[obj_start + 1] |
| 710 |
obj_data_start = obj_start + 2 |
| 711 |
else: |
| 712 |
obj_data_length = MEAS_TYPES[obj_meas_type].data_length |
| 713 |
obj_data_start = obj_start + 1 |
| 714 |
next_obj_start = obj_data_start + obj_data_length |
| 715 |
case _: |
| 716 |
raise ValueError |
| 717 |
|
| 718 |
if obj_data_length == 0: |
| 719 |
_LOGGER.debug( |
| 720 |
"%s: Invalid payload data length found with length 0, payload: %s", |
| 721 |
self.title, |
| 722 |
payload.hex(), |
| 723 |
) |
| 724 |
continue |
| 725 |
|
| 726 |
if payload_length < next_obj_start: |
| 727 |
_LOGGER.debug( |
| 728 |
"%s: Invalid payload data length, payload: %s", |
| 729 |
self.title, |
| 730 |
payload.hex(), |
| 731 |
) |
| 732 |
break |
| 733 |
|
| 734 |
|
| 735 |
if obj_meas_type == 0: |
| 736 |
new_packet_id = parse_uint(payload[obj_data_start:next_obj_start]) |
| 737 |
if self._skip_old_or_duplicated_advertisement(new_packet_id, adv_time): |
| 738 |
break |
| 739 |
self.packet_id = new_packet_id |
| 740 |
|
| 741 |
measurements.append( |
| 742 |
{ |
| 743 |
"data format": obj_data_format, |
| 744 |
"data length": obj_data_length, |
| 745 |
"measurement type": obj_meas_type, |
| 746 |
"measurement data": payload[obj_data_start:next_obj_start], |
| 747 |
"device id": None, |
| 748 |
} |
| 749 |
) |
| 750 |
|
| 751 |
|
| 752 |
seen_meas_formats = set() |
| 753 |
dup_meas_formats = set() |
| 754 |
for meas in measurements: |
| 755 |
if meas["measurement type"] in MEAS_TYPES: |
| 756 |
meas_format = MEAS_TYPES[meas["measurement type"]].meas_format |
| 757 |
if meas_format is None: |
| 758 |
|
| 759 |
|
| 760 |
continue |
| 761 |
if meas_format in seen_meas_formats: |
| 762 |
dup_meas_formats.add(meas_format) |
| 763 |
else: |
| 764 |
seen_meas_formats.add(meas_format) |
| 765 |
|
| 766 |
|
| 767 |
for meas in measurements: |
| 768 |
if meas["measurement type"] not in MEAS_TYPES: |
| 769 |
_LOGGER.debug( |
| 770 |
"%s: UNKNOWN measurement type %s in BTHome BLE payload! Adv: %s", |
| 771 |
self.title, |
| 772 |
meas["measurement type"], |
| 773 |
payload.hex(), |
| 774 |
) |
| 775 |
continue |
| 776 |
|
| 777 |
meas_type = MEAS_TYPES[meas["measurement type"]] |
| 778 |
meas_format = meas_type.meas_format |
| 779 |
meas_factor = meas_type.factor |
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
if meas["data format"] == "device_type_id": |
| 784 |
self.device_type_id = int(parse_uint(meas["measurement data"])) |
| 785 |
result = True |
| 786 |
continue |
| 787 |
if meas["data format"] == "firmware_version_4": |
| 788 |
fw = meas["measurement data"] |
| 789 |
|
| 790 |
|
| 791 |
self.set_device_sw_version(f"{fw[3]}.{fw[2]}.{fw[1]}.{fw[0]}") |
| 792 |
result = True |
| 793 |
continue |
| 794 |
if meas["data format"] == "firmware_version_3": |
| 795 |
fw = meas["measurement data"] |
| 796 |
|
| 797 |
self.set_device_sw_version(f"{fw[2]}.{fw[1]}.{fw[0]}") |
| 798 |
result = True |
| 799 |
continue |
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
assert meas_format is not None |
| 804 |
|
| 805 |
if meas_type.meas_format in dup_meas_formats: |
| 806 |
|
| 807 |
postfix_counter = postfix_dict.get(meas_format, 0) + 1 |
| 808 |
postfix_dict[meas_format] = postfix_counter |
| 809 |
postfix = f"_{postfix_counter}" |
| 810 |
else: |
| 811 |
postfix = "" |
| 812 |
|
| 813 |
value: None | str | int | float | datetime |
| 814 |
if meas["data format"] == 0 or meas["data format"] == "unsigned_integer": |
| 815 |
value = parse_uint(meas["measurement data"], meas_factor) |
| 816 |
elif meas["data format"] == 1 or meas["data format"] == "signed_integer": |
| 817 |
value = parse_int(meas["measurement data"], meas_factor) |
| 818 |
elif meas["data format"] == 2 or meas["data format"] == "float": |
| 819 |
value = parse_float(meas["measurement data"], meas_factor) |
| 820 |
elif meas["data format"] == 3 or meas["data format"] == "string": |
| 821 |
value = parse_string(meas["measurement data"]) |
| 822 |
elif meas["data format"] == 4 or meas["data format"] == "raw": |
| 823 |
value = parse_raw(meas["measurement data"]) |
| 824 |
elif meas["data format"] == 5 or meas["data format"] == "timestamp": |
| 825 |
value = parse_timestamp(meas["measurement data"]) |
| 826 |
elif meas["data format"] == "command": |
| 827 |
value = meas["measurement data"].hex() |
| 828 |
else: |
| 829 |
_LOGGER.error( |
| 830 |
"%s: UNKNOWN dataobject in BTHome BLE payload! Adv: %s", |
| 831 |
self.title, |
| 832 |
payload.hex(), |
| 833 |
) |
| 834 |
continue |
| 835 |
|
| 836 |
if value is not None: |
| 837 |
if ( |
| 838 |
isinstance(meas_format, BaseSensorDescription) |
| 839 |
and meas_format.device_class |
| 840 |
): |
| 841 |
self.update_sensor( |
| 842 |
key=f"{str(meas_format.device_class)}{postfix}", |
| 843 |
native_unit_of_measurement=meas_format.native_unit_of_measurement, |
| 844 |
native_value=value, |
| 845 |
device_class=meas_format.device_class, |
| 846 |
) |
| 847 |
elif ( |
| 848 |
isinstance(meas_format, BaseBinarySensorDescription) |
| 849 |
and meas_format.device_class |
| 850 |
): |
| 851 |
self.update_binary_sensor( |
| 852 |
key=f"{str(meas_format.device_class)}{postfix}", |
| 853 |
device_class=meas_format.device_class, |
| 854 |
native_value=bool(value), |
| 855 |
) |
| 856 |
elif isinstance(meas_format, EventDeviceKeys): |
| 857 |
event_type = parse_event_type( |
| 858 |
event_device=meas_format, |
| 859 |
data_obj=meas["measurement data"][0], |
| 860 |
) |
| 861 |
event_properties = parse_event_properties( |
| 862 |
event_device=meas_format, |
| 863 |
data_obj=meas["measurement data"][1:], |
| 864 |
) |
| 865 |
if event_type: |
| 866 |
self.fire_event( |
| 867 |
key=f"{str(meas_format)}{postfix}", |
| 868 |
event_type=event_type, |
| 869 |
event_properties=event_properties, |
| 870 |
) |
| 871 |
result = True |
| 872 |
else: |
| 873 |
_LOGGER.debug( |
| 874 |
"%s: UNKNOWN dataobject in BTHome BLE payload! Adv: %s", |
| 875 |
self.title, |
| 876 |
payload.hex(), |
| 877 |
) |
| 878 |
|
| 879 |
if not result: |
| 880 |
return False |
| 881 |
|
| 882 |
return True |
| 883 |
|
| 884 |
def _check_bind_key(self) -> None: |
| 885 |
"""Raises a ValueError, if no bindkey is set or bindkey is too short""" |
| 886 |
if not self.bindkey: |
| 887 |
self.bindkey_verified = False |
| 888 |
_LOGGER.debug("%s: Encryption key not set and adv is encrypted", self.title) |
| 889 |
raise ValueError |
| 890 |
if not self.bindkey or len(self.bindkey) != 16: |
| 891 |
self.bindkey_verified = False |
| 892 |
_LOGGER.error( |
| 893 |
"%s: Encryption key should be 16 bytes (32 characters) long", self.title |
| 894 |
) |
| 895 |
raise ValueError |
| 896 |
|
| 897 |
def _check_encryption_counter(self, new_encryption_counter: float) -> None: |
| 898 |
"""Raises a ValueError on decreasing encryption counter to avoid replay attacks.""" |
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
last_encryption_counter = self.encryption_counter |
| 905 |
if ( |
| 906 |
new_encryption_counter < last_encryption_counter |
| 907 |
and self.bindkey_verified is True |
| 908 |
and new_encryption_counter >= 100 |
| 909 |
): |
| 910 |
_LOGGER.warning( |
| 911 |
"%s: The new encryption counter (%i) is smaller than the previous value (%i). " |
| 912 |
"The data might be compromised. BLE advertisement will be skipped.", |
| 913 |
self.title, |
| 914 |
new_encryption_counter, |
| 915 |
last_encryption_counter, |
| 916 |
) |
| 917 |
raise ValueError |
| 918 |
|
| 919 |
def _check_minimum_length(self, bthome_data: BTHomeData, payload: bytes) -> None: |
| 920 |
"""Raises a value error, if payload length is to short.""" |
| 921 |
if len(payload) < bthome_data.get_minimum_payload_length(): |
| 922 |
_LOGGER.debug( |
| 923 |
"%s: Invalid data length (for decryption), adv: %s", |
| 924 |
self.title, |
| 925 |
payload.hex(), |
| 926 |
) |
| 927 |
raise ValueError |
| 928 |
|
| 929 |
def _handle_decryption_error( |
| 930 |
self, |
| 931 |
error: InvalidTag, |
| 932 |
encrypted_payload: bytes, |
| 933 |
nonce: bytes, |
| 934 |
mic: bytes, |
| 935 |
) -> None: |
| 936 |
"""Handles a decryption InvalidTag error.""" |
| 937 |
if self.decryption_failed is True: |
| 938 |
|
| 939 |
self.bindkey_verified = False |
| 940 |
else: |
| 941 |
self.decryption_failed = True |
| 942 |
_LOGGER.warning("%s: Decryption failed: %s", self.title, error) |
| 943 |
_LOGGER.debug("%s: nonce: %s", self.title, nonce.hex()) |
| 944 |
_LOGGER.debug("%s: mic: %s", self.title, mic.hex()) |
| 945 |
_LOGGER.debug("%s: encrypted_payload: %s", self.title, encrypted_payload.hex()) |
| 946 |
raise ValueError |
| 947 |
|
| 948 |
def _check_empty_decrypted_payload( |
| 949 |
self, |
| 950 |
decrypted_payload: bytes | None, |
| 951 |
bthome_data: BTHomeData, |
| 952 |
) -> None: |
| 953 |
"""Raises an ValueError if decrypted values is empty.""" |
| 954 |
if decrypted_payload is None: |
| 955 |
self.bindkey_verified = False |
| 956 |
_LOGGER.error( |
| 957 |
"%s: Decryption failed for %s, decrypted payload is None", |
| 958 |
self.title, |
| 959 |
bthome_data.get_mac_readable(), |
| 960 |
) |
| 961 |
raise ValueError |
| 962 |
|
| 963 |
def _decrypt_bthome( |
| 964 |
self, |
| 965 |
bthome_data: BTHomeData, |
| 966 |
) -> bytes: |
| 967 |
"""Decrypt encrypted BTHome BLE advertisements""" |
| 968 |
self._check_bind_key() |
| 969 |
|
| 970 |
new_encryption_counter = parse_uint(bthome_data.get_counter()) |
| 971 |
self._check_encryption_counter(new_encryption_counter) |
| 972 |
|
| 973 |
encrypted_payload = bthome_data.get_encrypted_payload() |
| 974 |
self._check_minimum_length(bthome_data, encrypted_payload) |
| 975 |
|
| 976 |
mic = bthome_data.get_mic() |
| 977 |
nonce = bthome_data.get_nonce() |
| 978 |
associated_data = bthome_data.get_associated_data() |
| 979 |
|
| 980 |
|
| 981 |
try: |
| 982 |
assert self.cipher is not None |
| 983 |
decrypted_payload = self.cipher.decrypt( |
| 984 |
nonce, encrypted_payload + mic, associated_data |
| 985 |
) |
| 986 |
except InvalidTag as error: |
| 987 |
self._handle_decryption_error(error, encrypted_payload, nonce, mic) |
| 988 |
self._check_empty_decrypted_payload(decrypted_payload, bthome_data) |
| 989 |
|
| 990 |
self.decryption_failed = False |
| 991 |
self.bindkey_verified = True |
| 992 |
self.encryption_counter = new_encryption_counter |
| 993 |
|
| 994 |
return decrypted_payload |