首先,确保BLE设备已正确连接并启动。然后,尝试使用以下代码示例中的流程来发送字节:
import time
from bluepy.btle import Peripheral, UUID, DefaultDelegate
#连接BLE设备
device = Peripheral("XX:XX:XX:XX:XX:XX", "public")
#指定服务和特征UUID
service_uuid = UUID("xxxxxxx")
chara_uuid = UUID("xxxxxxx")
#获取服务和特征对象
service = device.getServiceByUUID(service_uuid)
chara = service.getCharacteristic(chara_uuid)
#定义回调函数
class MyDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
print(data)
#使设备进入通知模式
device.setDelegate(MyDelegate())
temp_handle = 19 #不同的设备有不同的句柄值
device.writeCharacteristic(temp_handle, bytes("01", "utf-8"), withResponse=True)
#发送字节
chara.write(bytes("your message", "utf-8"))
#等待响应
while True:
if device.waitForNotifications(1.0):
continue
device.disconnect()
在代码中,我们首先连接到BLE设备,指定服务和特征UUID,并获取服务和特征对象。然后,我们定义了一个回调函数来处理从设备发送的通知。我们使BLE设备进入通知模式,并发送字节到特征中。最后,我们等待BLE设备对发送的字节作出响应。