How to use bleak - 10 common examples

To help you get started, we’ve selected a few bleak examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github hbldh / bleak / tests / test_imports.py View on Github external
def test_import():
    """Test by importing the client and assert correct client by OS."""
    if platform.system() == "Linux":
        from bleak import BleakClient

        assert BleakClient.__name__ == "BleakClientBlueZDBus"
    elif platform.system() == "Windows":
        from bleak import BleakClient

        assert BleakClient.__name__ == "BleakClientDotNet"
    elif platform.system() == "Darwin":
        from bleak import BleakClient

        assert BleakClient.__name__ == "BleakClientCoreBluetooth"
github hbldh / bleak / bleak / __init__.py View on Github external
from bleak.backends.corebluetooth import (
        BleakClientCoreBluetooth as BleakClient,
        discover,
    )  # noqa
elif platform.system() == "Windows":
    # Requires Windows 10 Creators update at least, i.e. Window 10.0.16299
    _vtup = platform.win32_ver()[1].split(".")
    if int(_vtup[0]) != 10:
        raise BleakError(
            "Only Windows 10 is supported. Detected was {0}".format(
                platform.win32_ver()
            )
        )

    if (int(_vtup[1]) == 0) and (int(_vtup[2]) < 16299):
        raise BleakError(
            "Requires at least Windows 10 version 0.16299 (Fall Creators Update)."
        )

    from bleak.backends.dotnet.discovery import discover  # noqa
    from bleak.backends.dotnet.client import BleakClientDotNet as BleakClient  # noqa


def cli():
    import argparse
    from asyncio.tasks import ensure_future

    loop = asyncio.get_event_loop()

    parser = argparse.ArgumentParser(
        description="Perform Bluetooth Low Energy device scan"
    )
github hbldh / bleak / bleak / backends / bluezdbus / utils.py View on Github external
Service         org.bluez
    Interface       org.bluez.Device1
    Object path     [variable prefix]/{hci0,hci1,...}/dev_XX_XX_XX_XX_XX_XX

    Args:
        hci_device (str): Which bluetooth adapter to connect with.
        address (str): The MAC adress of the bluetooth device.

    Returns:
        String representation of device object path on format
        `/org/bluez/{hci0,hci1,...}/dev_XX_XX_XX_XX_XX_XX`.

    """
    if not validate_mac_address(address):
        raise BleakError("{0} is not a valid MAC adrdess.".format(address))

    if not validate_hci_device(hci_device):
        raise BleakError("{0} is not a valid HCI device.".format(hci_device))

    # TODO: Join using urljoin? Or pathlib?
    return "/org/bluez/{0}/dev_{1}".format(
        hci_device, "_".join(address.split(":")).upper()
    )
github hbldh / bleak / bleak / __init__.py View on Github external
from bleak.backends.bluezdbus.discovery import discover  # noqa
    from bleak.backends.bluezdbus.client import (
        BleakClientBlueZDBus as BleakClient
    )  # noqa
elif platform.system() == "Darwin":
    # TODO: Check if macOS version has Core Bluetooth, raise error otherwise.
    from bleak.backends.corebluetooth import (
        BleakClientCoreBluetooth as BleakClient,
        discover,
    )  # noqa
elif platform.system() == "Windows":
    # Requires Windows 10 Creators update at least, i.e. Window 10.0.16299
    _vtup = platform.win32_ver()[1].split(".")
    if int(_vtup[0]) != 10:
        raise BleakError(
            "Only Windows 10 is supported. Detected was {0}".format(
                platform.win32_ver()
            )
        )

    if (int(_vtup[1]) == 0) and (int(_vtup[2]) < 16299):
        raise BleakError(
            "Requires at least Windows 10 version 0.16299 (Fall Creators Update)."
        )

    from bleak.backends.dotnet.discovery import discover  # noqa
    from bleak.backends.dotnet.client import BleakClientDotNet as BleakClient  # noqa


def cli():
    import argparse
github hbldh / bleak / examples / disconnect_callback.py View on Github external
async def show_disconnect_handling(mac_addr: str, loop: asyncio.AbstractEventLoop):
    async with BleakClient(mac_addr, loop=loop) as client:
        disconnected_event = asyncio.Event()

        def disconnect_callback(client):
            print("Disconnected callback called!")
            loop.call_soon_threadsafe(disconnected_event.set)

        client.set_disconnected_callback(disconnect_callback)
        print("Sleeping until device disconnects according to BlueZ...")
        await disconnected_event.wait()
        print("Connected: {0}".format(await client.is_connected()))
        await asyncio.sleep(0.5)  # Sleep a bit longer to allow _cleanup to remove all BlueZ notifications nicely...
github hbldh / bleak / bleak / backends / dotnet / utils.py View on Github external
"""
    done = asyncio.Event()
    # Register AsyncOperationCompletedHandler callback that triggers the above asyncio.Event.
    op.Completed = AsyncOperationCompletedHandler[return_type](
        lambda x, y: loop.call_soon_threadsafe(done.set)
    )
    # Wait for callback.
    await done.wait()

    if op.Status == AsyncStatus.Completed:
        return op.GetResults()
    elif op.Status == AsyncStatus.Error:
        # Exception occurred. Wrap it in BleakDotNetTaskError
        # to make it catchable.
        raise BleakDotNetTaskError(op.ErrorCode.ToString())
    else:
        # TODO: Handle IsCancelled.
        raise BleakDotNetTaskError("IAsyncOperation Status: {0}".format(op.Status))
github hbldh / bleak / bleak / backends / dotnet / utils.py View on Github external
# Register AsyncOperationCompletedHandler callback that triggers the above asyncio.Event.
    op.Completed = AsyncOperationCompletedHandler[return_type](
        lambda x, y: loop.call_soon_threadsafe(done.set)
    )
    # Wait for callback.
    await done.wait()

    if op.Status == AsyncStatus.Completed:
        return op.GetResults()
    elif op.Status == AsyncStatus.Error:
        # Exception occurred. Wrap it in BleakDotNetTaskError
        # to make it catchable.
        raise BleakDotNetTaskError(op.ErrorCode.ToString())
    else:
        # TODO: Handle IsCancelled.
        raise BleakDotNetTaskError("IAsyncOperation Status: {0}".format(op.Status))
github hbldh / bleak / bleak / backends / bluezdbus / discovery.py View on Github external
def _device_info(path, props):
    try:
        name = props.get("Name", props.get("Alias", path.split("/")[-1]))
        address = props.get("Address", None)
        if address is None:
            try:
                address = path[-17:].replace("_", ":")
                if not validate_mac_address(address):
                    address = None
            except Exception:
                address = None
        rssi = props.get("RSSI", "?")
        return name, address, rssi, path
    except Exception as e:
        # logger.exception(e, exc_info=True)
        return None, None, None, None
github hbldh / bleak / bleak / backends / corebluetooth / PeripheralDelegate.py View on Github external
def peripheral_didDiscoverCharacteristicsForService_error_(
        self, peripheral: CBPeripheral, service: CBService, error: NSError
    ):
        serviceUUID = service.UUID().UUIDString()
        if error is not None:
            raise BleakError(
                "Failed to discover services for service {}: {}".format(
                    serviceUUID, error
                )
            )

        logger.debug("Characteristics discovered")
        self._service_characteristic_discovered_log[serviceUUID] = True
github hbldh / bleak / bleak / backends / corebluetooth / PeripheralDelegate.py View on Github external
def peripheral_didDiscoverDescriptorsForCharacteristic_error_(
        self, peripheral: CBPeripheral, characteristic: CBCharacteristic, error: NSError
    ):
        cUUID = characteristic.UUID().UUIDString()
        if error is not None:
            raise BleakError(
                "Failed to discover descriptors for characteristic {}: {}".format(
                    cUUID, error
                )
            )

        logger.debug("Descriptor discovered {}".format(cUUID))
        self._characteristic_descriptor_log[cUUID] = True