PyQt5之QtBluetooth模块:低功耗蓝牙BLE通信
最近使用PyQt5开发PC端工具,正巧手上有一个富芮坤的低功耗蓝牙,于是想在PC端试试与之通信,不过发现使用PyQt5开发低功耗蓝牙的教程很少,本人参考Qt教程和官方文档,开发过程以此文记录。
参考文档:PyQt5模块安装路径下QtBluetooth.py、Qt C++蓝牙类介绍、Qt 低功耗蓝牙扫描示例
低功耗蓝牙通信大体分为以下几个过程:
1. 扫描蓝牙
def scan_for_devices(self):
self.agent = QtBt.QBluetoothDeviceDiscoveryAgent()
self.agent.setLowEnergyDiscoveryTimeout(5000)
self.agent.deviceDiscovered.connect(self.show_info)
self.agent.error.connect(self.agent_error)
self.agent.finished.connect(self.agent_finished)
self.timer = QtCore.QTimer(self.agent)
self.timer.start(5)
self.timer.timeout.connect(self.display_status)
self.agent.start()
def show_info(self, info: QtBt.QBluetoothDeviceInfo):
if int(info.coreConfigurations()) == 1:
print('Device discovered')
print(f'Name: {
info.name()}')
print(f'Addr: {
info.address().toString()}')
print(f'ServUUID: {
info.serviceUuids()}')
def agent_error(self, e):
error = ["NoError", "InputOutputError", "PoweredOffError", "InvalidBluetoothAdapterError", "UnknownError"]
if e < 4:
print(error[e])
else:
print(error[4])
def agent_finished(self):
print('Agent finished')
for dev in self.agent.discoveredDevices():
print(f'设备名称: {
dev.name()} 设备地址: {
dev.address()}')
def display_status(self):
print(self.agent.isActive(), self.agent.discoveredDevices())
self.timer.stop()
上面代码可以看到首先要创建蓝牙设备扫描代理QBluetoothServiceDiscoveryAgent,并设置超时时间,然后依次是绑定设备搜索回调函数serviceDiscovered,这个函数返回搜索到蓝牙设备信息;绑定错误信息回调函数error;绑定搜索完成回调函数finished;最终搜索完成后(通过定时器结束搜索),在discoveredDevices中保存了本次搜索的所有蓝牙设备信息。
2. 连接蓝牙
3. 获取服务
def agent_finished(self):
print('Agent finished')
for dev in self.agent.discoveredDevices():
# 通过蓝牙name连接 或者 通过蓝牙地址连接dev.address()
if self.dev_name[0] == dev.name() or self.dev_name[1] == dev.name():
print(f'连接设备: {
dev.name()}')
print(f'coreConfigurations: {
int(dev.coreConfigurations())}')
self.controller = QtBt.QLowEnergyController.createCentral(dev)
self.controller.connected.connect(self.connect_Notify)
self.controller.error.connect(self.controller_error)
self.controller.disconnected.connect(self.disconnect_Notify)
self.controller.serviceDiscovered.connect(self.addService)
self.controller.discoveryFinished.connect(self.dis_Finished)
self.controller.connectToDevice()
break
def connect_Notify(self, *args, **kwargs):
print(f'连接通知')
print(f'args: {
args}')
print(f'kwargs: {
kwargs}')
self.serviceUUID = list()
self.controller.discoverServices()
def controller_error(self, e):
error = ["NoError", "UnknownError", "UnknownRemoteDeviceError", "NetworkError", "InvalidBluetoothAdapterError",
"ConnectionError"]
if e < 6:
print(error[e])
else:
print("UnknownError")
def