From 3ba98a8f82a31fb804fee641da118879af556e50 Mon Sep 17 00:00:00 2001 From: yhql Date: Fri, 3 Mar 2023 10:34:32 +0100 Subject: [PATCH] Add BLE support with 'bleak' --- README.md | 2 +- ledgerwallet/client.py | 4 +++- ledgerwallet/transport/__init__.py | 2 +- ledgerwallet/transport/ble.py | 5 +++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1329849..6bd309f 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ $ ledgerctl -v run Bitcoin => e0d8000007426974636f696e <= 9000 ``` + ### Using BLE BLE scanning is disabled by default. It can be activated by setting an environment variable named `LEDGER_USE_BLE`. @@ -159,4 +160,3 @@ And executed with: ```console pre-commit run --all-files ``` - diff --git a/ledgerwallet/client.py b/ledgerwallet/client.py index c8b6317..09fd810 100644 --- a/ledgerwallet/client.py +++ b/ledgerwallet/client.py @@ -164,6 +164,7 @@ class NoLedgerDeviceException(Exception): class LedgerClient(object): def __init__(self, device=None, cla=0xE0, private_key=None): + self.device = None if device is None: devices = enumerate_devices() if len(devices) == 0: @@ -184,7 +185,8 @@ def __del__(self): self.close() def close(self): - self.device.close() + if self.device is not None: + self.device.close() def raw_exchange(self, data: bytes) -> bytes: LOG.debug("=> " + data.hex()) diff --git a/ledgerwallet/transport/__init__.py b/ledgerwallet/transport/__init__.py index 4ea567b..e339bb8 100644 --- a/ledgerwallet/transport/__init__.py +++ b/ledgerwallet/transport/__init__.py @@ -1,7 +1,7 @@ from contextlib import contextmanager -from .device import Device from .ble import BleDevice +from .device import Device from .hid import HidDevice from .tcp import TcpDevice diff --git a/ledgerwallet/transport/ble.py b/ledgerwallet/transport/ble.py index df27aa2..1ce661e 100644 --- a/ledgerwallet/transport/ble.py +++ b/ledgerwallet/transport/ble.py @@ -1,8 +1,9 @@ import asyncio import os +from typing import List + from bleak import BleakClient, BleakScanner from bleak.exc import BleakError -from typing import List HANDLE_CHAR_ENABLE_NOTIF = 13 HANDLE_CHAR_WRITE = 16 @@ -13,7 +14,7 @@ async def ble_discover(): - devices = await BleakScanner.discover(timeout=1.) + devices = await BleakScanner.discover(timeout=1.0) return devices