Bleak是一个用于蓝牙通信的跨平台库,它提供了一个简单的接口来连接到蓝牙设备,发现服务,读取和写入特征,监听通知等。
以下是使用Bleak进行蓝牙通信的一些基本示例:
- 扫描蓝牙设备:
import asyncio
from bleak import discover
async def main():
devices = await discover()
for device in devices:
print(f"Device {device.address} - {device.name}")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
- 连接到蓝牙设备并读取特征:
import asyncio
from bleak import BleakClient
async def main():
# 假设设备的MAC地址是'XX:XX:XX:XX:XX:XX'
async with BleakClient("XX:XX:XX:XX:XX:XX") as client:
# 假设特征的UUID是'00002A19-0000-1000-8000-00805F9B34FB'
result = await client.read_gatt_char("00002A19-0000-1000-8000-00805F9B34FB")
print(result)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
- 连接到蓝牙设备并写入特征:
import asyncio
from bleak import BleakClient
async def main():
# 假设设备的MAC地址是'XX:XX:XX:XX:XX:XX'
async with BleakClient("XX:XX:XX:XX:XX:XX") as client:
# 假设特征的UUID是'00002A19-0000-1000-8000-00805F9B34FB'
await client.write_gatt_char("00002A19-0000-1000-8000-00805F9B34FB", bytearray([0x01]))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
- 连接到蓝牙设备并监听特征通知:
import asyncio
from bleak import BleakClient
async def handle_notifications(sender, data):
print(f"Notification received: {data}")
async def main():
# 假设设备的MAC地址是'XX:XX:XX:XX:XX:XX'
async with BleakClient("XX:XX:XX:XX:XX:XX") as client:
# 假设特征的UUID是'00002A19-0000-1000-8000-00805F9B34FB'
await client.start_notify("00002A19-0000-1000-8000-00805F9B34FB", handle_notifications)
await asyncio.sleep(10.0) # 监听一段时间
await client.stop_notify("00002A19-0000-1000-8000-00805F9B34FB")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
以上代码都是使用async/await语法,这是在Python中编写异步代码的推荐方式。这些例子都是基于假设的设备MAC地址和特征UUID,您需要根据实际的蓝牙设备进行相应的替换。