From 6be16ed101309f2d05d9652a5e8df19ca8d59045 Mon Sep 17 00:00:00 2001 From: Josef Zweck <24647999+zweckj@users.noreply.github.com> Date: Fri, 8 Nov 2024 10:05:16 +0100 Subject: [PATCH] add method to get correct device --- pyacaia_async/exceptions.py | 5 +++++ pyacaia_async/helpers.py | 35 +++++++++++++++++++++++++++++++++-- setup.py | 2 +- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/pyacaia_async/exceptions.py b/pyacaia_async/exceptions.py index b7382f6..541b333 100644 --- a/pyacaia_async/exceptions.py +++ b/pyacaia_async/exceptions.py @@ -1,4 +1,5 @@ """Exceptions for pyacaia_async.""" + from bleak.exc import BleakDeviceNotFoundError, BleakError @@ -12,3 +13,7 @@ class AcaiaDeviceNotFound(BleakDeviceNotFoundError): class AcaiaError(BleakError): """Exception for general bleak errors.""" + + +class AcaiaUnknownDevice(Exception): + """Exception for unknown devices.""" diff --git a/pyacaia_async/helpers.py b/pyacaia_async/helpers.py index a74e77c..7ae468f 100644 --- a/pyacaia_async/helpers.py +++ b/pyacaia_async/helpers.py @@ -1,9 +1,18 @@ """Helper functions, taken from pyacaia.""" + import logging -from bleak import BleakScanner +from bleak import BleakScanner, BLEDevice, BleakClient +from bleak.exc import BleakDeviceNotFoundError, BleakError -from .const import HEADER1, HEADER2, SCALE_START_NAMES +from .const import ( + HEADER1, + HEADER2, + SCALE_START_NAMES, + OLD_STYLE_CHAR_ID, + DEFAULT_CHAR_ID, +) +from .exceptions import AcaiaDeviceNotFound, AcaiaError, AcaiaUnknownDevice _LOOGER = logging.getLogger(__name__) @@ -32,6 +41,28 @@ async def scan(scanner: BleakScanner, timeout) -> list: return addresses +async def is_new_scale(address_or_ble_device: str | BLEDevice) -> bool: + """Check if the scale is a new style scale.""" + async with BleakClient(address_or_ble_device) as client: + try: + await client.connect() + services = await client.get_services() + except BleakDeviceNotFoundError as ex: + raise AcaiaDeviceNotFound("Device not found") from ex + except (BleakError, Exception) as ex: + raise AcaiaError from ex + + characteristics = [] + for char in services.characteristics.values(): + characteristics.append(char.uuid) + + if OLD_STYLE_CHAR_ID in characteristics: + return False + if DEFAULT_CHAR_ID in characteristics: + return True + raise AcaiaUnknownDevice + + def encode(msg_type: int, payload: bytearray | list[int]) -> bytearray: """Encode a message to the scale.""" byte_msg = bytearray(5 + len(payload)) diff --git a/setup.py b/setup.py index 1bcce0b..ebe2610 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="pyacaia_async", - version="0.1.0", + version="0.1.1", description="An async implementation of PyAcaia", long_description=readme, long_description_content_type="text/markdown",