使用Python和bleak库通知蓝牙GATT设备,但结果不稳定

朱三Chu

我尝试使用Python控制某些BLE GATT设备。我发现Bleak(https://bleak.readthedocs.io/en/latest/)这个库可以与GATT设备通信。

当我使用它时,大多数时候它确实运行良好。

但是,一旦我尝试与BLE GATT医疗设备进行通信,我发现我无法始终使用此设备进行通知。

这是我的代码,我对Bleak的github示例进行了一些更改:( https://github.com/hbldh/bleak/blob/develop/examples/enable_notifications.py

import asyncio
import logging

from bleak import discover
from bleak import BleakClient

devices_dict = {}
devices_list = []
receive_data = []

#To discover BLE devices nearby 
async def scan():
    dev = await discover()
    for i in range(0,len(dev)):
        #Print the devices discovered
        print("[" + str(i) + "]" + dev[i].address,dev[i].name,dev[i].metadata["uuids"])
        #Put devices information into list
        devices_dict[dev[i].address] = []
        devices_dict[dev[i].address].append(dev[i].name)
        devices_dict[dev[i].address].append(dev[i].metadata["uuids"])
        devices_list.append(dev[i].address)

#An easy notify function, just print the recieve data
def notification_handler(sender, data):
    print(', '.join('{:02x}'.format(x) for x in data))

async def run(address, debug=False):
    log = logging.getLogger(__name__)
    if debug:
        import sys

        log.setLevel(logging.DEBUG)
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(logging.DEBUG)
        log.addHandler(h)

    async with BleakClient(address) as client:
        x = await client.is_connected()
        log.info("Connected: {0}".format(x))

        for service in client.services:
            log.info("[Service] {0}: {1}".format(service.uuid, service.description))
            for char in service.characteristics:
                if "read" in char.properties:
                    try:
                        value = bytes(await client.read_gatt_char(char.uuid))
                    except Exception as e:
                        value = str(e).encode()
                else:
                    value = None
                log.info(
                    "\t[Characteristic] {0}: (Handle: {1}) ({2}) | Name: {3}, Value: {4} ".format(
                        char.uuid,
                        char.handle,
                        ",".join(char.properties),
                        char.description,
                        value,
                    )
                )
                for descriptor in char.descriptors:
                    value = await client.read_gatt_descriptor(descriptor.handle)
                    log.info(
                        "\t\t[Descriptor] {0}: (Handle: {1}) | Value: {2} ".format(
                            descriptor.uuid, descriptor.handle, bytes(value)
                        )
                    )

                #Characteristic uuid
                CHARACTERISTIC_UUID = "put your characteristic uuid"

                await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
                await asyncio.sleep(5.0)
                await client.stop_notify(CHARACTERISTIC_UUID)

if __name__ == "__main__":
    print("Scanning for peripherals...")

    #Build an event loop
    loop = asyncio.get_event_loop()
    #Run the discover event
    loop.run_until_complete(scan())

    #let user chose the device
    index = input('please select device from 0 to ' + str(len(devices_list)) + ":")
    index = int(index)
    address = devices_list[index]
    print("Address is " + address)

    #Run notify event
    loop = asyncio.get_event_loop()
    loop.set_debug(True)
    loop.run_until_complete(run(address, True))

在大多数情况下,此代码可以很好地用作此图像

但是有时候(大约25%的比率),这个问题就发生了:

[0]08:6B:D7:12:F1:33 Nonin3150_502892837['uuid']
[1]1D:BD:4A:69:8B:AB Unknown []
[2]73:15:CD:47:AF:08 Unknown []
[3]40:4E:36:5B:8D:1B HTC BS 1BBDB9 ['uuid']
[4]6B:FB:E5:DD:7F:4E Unknown []
[5]69:A7:87:23:5C:7C Unknown []
please select device from 0 to 6:0
Address is 08:6B:D7:12:F1:33
Traceback (most recent call last):
  File "D:/Bletest/nonin_test.py", line 91, in <module>
    loop.run_until_complete(run(address, True))
  File "C:\Users\rizal\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 579, in run_until_complete
    return future.result()
  File "D:/Bletest/nonin_test.py", line 36, in run
    async with BleakClient(address) as client:
  File "C:\Users\rizal\AppData\Local\Programs\Python\Python37\lib\site-packages\bleak\backends\client.py", line 60, in __aenter__
    await self.connect()
  File "C:\Users\rizal\AppData\Local\Programs\Python\Python37\lib\site-packages\bleak\backends\dotnet\client.py", line 154, in connect
    "Device with address {0} was not found.".format(self.address)
bleak.exc.BleakError: Device with address 08:6B:D7:12:F1:33 was not found.

Process finished with exit code 1

我不知道为什么程序可以发现此设备,但无法通知它。

这是我的代码问题,还是可能是由该设备的程序流程引起的?

地狱

我确实有同样的问题。但是,我认为这与Windows中BLE的实现有关。在Windows界面中扫描设备时,有时可以看到设备的外观和消失情况。设备广告间隔可能很长。

但是,可以通过将其包装在try catch部分中来进行修复。

这样的事情可能对您有用。

    async def connect_to_device(self):
        while True:
            if self.connection_enabled:
                try:
                    await self.client.connect()
                    self.connected = await self.client.is_connected()
                    if self.connected:
                        print("Connected to Device")
                        self.client.set_disconnected_callback(self.on_disconnect)
                        await self.client.start_notify(
                            self.notify_characteristic, self.notify_callback,
                        )
                        while True:
                            if not self.connected:
                                break
                            await asyncio.sleep(1.0)
                    else:
                        print(f"Failed to connect to Device")
                except Exception as e:
                    print(e)
            else:
                await asyncio.sleep(1.0)

您只需要将此任务添加到循环中

asyncio.ensure_future(self.connect_to_device(), loop)

定义客户

self.client = BleakClient(self.connected_device.address, loop=loop)

并启用连接

self.connection_enabled = true

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

每晚使用“使用不稳定的库功能'集合'”

来自分类Dev

是否建议使用“不稳定”的angularjs库?

来自分类Dev

scikit KernelPCA结果不稳定

来自分类Dev

OpenCV拼接结果的尺寸不稳定

来自分类Dev

Javascript:复制数组的结果不稳定

来自分类Dev

使用 sublime 运行 python:dtype 输出不稳定

来自分类Dev

蓝牙Broadcom 43142工作期间不稳定连接和其他错误

来自分类Dev

关于不稳定和同步

来自分类Dev

UserDefaults 和 If/else 不稳定行为

来自分类Dev

Rust稳定的标准库是否使用不稳定的功能?

来自分类常见问题

Android 4.3蓝牙低功耗不稳定

来自分类Dev

使用AudioQueue播放不稳定的音频

来自分类Dev

使用AudioQueue播放不稳定的音频

来自分类Dev

对int不稳定?

来自分类Dev

通过不稳定的网络同步本地数据库和远程应用程序

来自分类Dev

网站页脚在我的移动设备上不稳定

来自分类Dev

动画 SVG 在移动设备上的帧率不稳定

来自分类Dev

如何判断我在使用Debian稳定还是不稳定?

来自分类Dev

iOS Forward Geocoding返回不稳定的稀疏结果

来自分类Dev

Hadoop Terasort不稳定的基准测试结果

来自分类Dev

宏功能的有害(或不稳定)结果

来自分类Dev

GROUP BY的MAX日期字段-结果不稳定

来自分类Dev

iOS Forward Geocoding返回不稳定的稀疏结果

来自分类Dev

回声以BASH中不稳定的顺序输出结果

来自分类Dev

GraphicsScene 中的轴承公式计算产生不稳定的结果

来自分类Dev

使用create-react-app和Skaffold kubernetes的行为不稳定且缓慢

来自分类Dev

如何删除sid(不稳定)存储库

来自分类Dev

使用 Pandas 使用(略微)不稳定时区的 Python 日期时间的字符串格式

来自分类Dev

在C / Python程序中使用无符号长整型时的行为不稳定

Related 相关文章

  1. 1

    每晚使用“使用不稳定的库功能'集合'”

  2. 2

    是否建议使用“不稳定”的angularjs库?

  3. 3

    scikit KernelPCA结果不稳定

  4. 4

    OpenCV拼接结果的尺寸不稳定

  5. 5

    Javascript:复制数组的结果不稳定

  6. 6

    使用 sublime 运行 python:dtype 输出不稳定

  7. 7

    蓝牙Broadcom 43142工作期间不稳定连接和其他错误

  8. 8

    关于不稳定和同步

  9. 9

    UserDefaults 和 If/else 不稳定行为

  10. 10

    Rust稳定的标准库是否使用不稳定的功能?

  11. 11

    Android 4.3蓝牙低功耗不稳定

  12. 12

    使用AudioQueue播放不稳定的音频

  13. 13

    使用AudioQueue播放不稳定的音频

  14. 14

    对int不稳定?

  15. 15

    通过不稳定的网络同步本地数据库和远程应用程序

  16. 16

    网站页脚在我的移动设备上不稳定

  17. 17

    动画 SVG 在移动设备上的帧率不稳定

  18. 18

    如何判断我在使用Debian稳定还是不稳定?

  19. 19

    iOS Forward Geocoding返回不稳定的稀疏结果

  20. 20

    Hadoop Terasort不稳定的基准测试结果

  21. 21

    宏功能的有害(或不稳定)结果

  22. 22

    GROUP BY的MAX日期字段-结果不稳定

  23. 23

    iOS Forward Geocoding返回不稳定的稀疏结果

  24. 24

    回声以BASH中不稳定的顺序输出结果

  25. 25

    GraphicsScene 中的轴承公式计算产生不稳定的结果

  26. 26

    使用create-react-app和Skaffold kubernetes的行为不稳定且缓慢

  27. 27

    如何删除sid(不稳定)存储库

  28. 28

    使用 Pandas 使用(略微)不稳定时区的 Python 日期时间的字符串格式

  29. 29

    在C / Python程序中使用无符号长整型时的行为不稳定

热门标签

归档