首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Windows中从CPython列出连接的BLE设备

在Windows中从CPython列出连接的BLE设备
EN

Stack Overflow用户
提问于 2022-03-21 12:45:35
回答 1查看 178关注 0票数 0

我正在将运行在Linux上的Python代码移植到Windows,并且需要实现两个特定于平台的简单功能(通过Linux下的bluetoothctl调用来处理):

  1. 列出所有当前连接的BLE设备
    • 例如list_connected()[('F9:18:AF:E7:9D:40','HeadPhones'),('aa:93:88:1e:03','SmartWatch')]

  2. 连接设备的力分离
    • 例如disconnect('F9:18:AF:E7:9D:40',timeout=2)

多亏了凄凉,BLE的其余功能已经跨平台了。

我只有很少的Windows经验,尤其是最近的API。我环顾四周,发现WinRT (Windows )是UWP (Universal )的一部分,可以通过pythonnetwinrt包从CPython获得;这是实现的正确方法吗?

谢谢你的暗示。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-28 14:27:54

下面是列出和断开设备的代码的主要部分(完整的代码通过电子邮件发送到OP )。我没有包含异常处理和从异步到同步的包装,因为这是Python特有的,对其他人可能不那么重要。

代码语言:javascript
复制
import winrt.windows.foundation as wf
import winrt.windows.devices.bluetooth as bt
import winrt.windows.devices.enumeration as denum

import asyncio # to support async / await because winrt doesn't have sync versions of BLE functions

# the naming in the Python wrapper looks a bit messy, underscores mixed up with PascalCase
# another caveat is that we have to call the specific override with the second argument `[]`
# otherwise Python winrt wrapper gets confused with multiple versions of find_all_async
dev_infos = await denum.DeviceInformation.find_all_async(bt.BluetoothLEDevice.get_device_selector(), [])

id_name_pairs = []
    
for dev_info in dev_infos:
    # getting the device itself to access it's "connected" status
    le_device = await bt.BluetoothLEDevice.from_id_async(dev_info.id);
    
    if le_device is None: # enumerator sometimes has stale devices; this can also happen when you unplug BLE dongle
        continue
        
    # in status context, Microsoft calls it "CONNECTED", but later, when disconnecting, it needs "unpair"
    # and there is no any "disconnect" function. Microsoft is messy in this regard
    if le_device.connection_status == bt.BluetoothConnectionStatus.CONNECTED:
        id_name_pairs.append((le_device.device_id, le_device.name));

重要- Microsoft通过其完整的ID而不是BLE地址来标识BLE设备。如果我们想以后能够断开设备的连接,我们必须知道ID。如果我们不将ID存储在任何地方并按地址断开连接,我们将不得不再次运行枚举并按地址查找ID。

要从设备ID中轻松提取BLE地址:

代码语言:javascript
复制
addressed_devices = list(map(lambda dev: (dev[0][-17:], dev[1]), id_name_pairs))

若要通过已知ID断开设备,请执行以下操作:

代码语言:javascript
复制
le_device = await bt.BluetoothLEDevice.from_id_async(dev_id)
await le_device.device_information.pairing.unpair_async()

要求: Windows 10,2018年10月更新或更高版本,Python for Windows,版本3.7或更高版本,pip,版本19或更高版本。

使用pip install winrt获取Python包装器库。

总之,乍一看,一个看似微不足道的任务,由于.NET / Python命名和覆盖的差异,以及微软的配对/连接实现,造成了一些令人费解的问题;它很容易与传统的蓝牙BR/EDR混为一谈,而这些API不适用于BLE配对信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71557849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档