扫描设备

创建一个ScanDelegate

1 class ScanDelegate(DefaultDelegate):
2 def __init__(self):
3 DefaultDelegate.__init__(self)
4
5 def handleDiscovery(self, dev, isNewDev, isNewData):
6 if isNewDev:
7 print("Discovered device", dev.addr)
8 elif isNewData:
9 print("Received new data from", dev.addr)

扫描设备并打印

 1 scanner = Scanner().withDelegate(ScanDelegate())
2 devices = scanner.scan(10.0)
3 creyond_devices = []
4 for dev in devices:
5 print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
6 for (adtype, desc, value) in dev.getScanData():
7 if value == "CreYond":
8 creyond_devices.append(dev)
9 print(" %s = %s" % (desc, value))
10
11 print(creyond_devices)

获取Services与Characteristics

通过Peripheral来获取Services

1 c_device = creyond_devices[0]
2 p_device = Peripheral(c_device)
3 p_device.withDelegate(NotifyDelegate(p_device))
4 services = p_device.getServices()
5
6 # displays all services
7 for service in services:
8 print(service)

通过UUID获取指定Service  

1 service_uuid = UUID("00000010-3354-4d64-6e6f-XXXXXXX3534a")
2 c_service = p_device.getServiceByUUID(service_uuid)
3 print(c_service)

获取Service下的Characteristics

1 characteristics = c_service.getCharacteristics()
2 # displays all characteristics
3 for char in characteristics:
4 print(char)

订阅与通知

创建一个NotifyDelegate

1 class NotifyDelegate(DefaultDelegate):
2 # Constructor (run once on startup)
3 def __init__(self, params):
4 DefaultDelegate.__init__(self)
5
6 # func is caled on notifications
7 def handleNotification(self, cHandle, data):
8 print("Notification from Handle: 0x" + format(cHandle,'02X') )
9 print(hexlify(data))

在创建Peripheral时,指定

1 p_device.withDelegate(NotifyDelegate(p_device))

查找descriptor,并设定其值为1.设定值时注意大小端 bytes([1, 0])。注意,直接写characteristic是错误的,一定要找到characteristic下的UUID为0x2902的descriptor。部分蓝牙设备的UUID可能不规范,通过UUID查找可能存在重复,建议getDescriptors筛选好对应范围。

1 hEcg=notify_char.getHandle()
2 for descriptor in p_device.getDescriptors(hEcg,c_service.hndEnd):
3 if (descriptor.uuid==0x2902):
4 print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
5 hEcgCCC=descriptor.handle
6
7 p_device.writeCharacteristic(hEcgCCC,bytes([1, 0]))

等待显示:

1 while True:
2 if p_device.waitForNotifications(1.0):
3 # handleNotification() was called
4 continue
5
6 print("Waiting... Waited more than one sec for notification")

完整代码:

 1 # %%
2 from bluepy.btle import Scanner, DefaultDelegate,UUID, Peripheral
3 from binascii import hexlify
4 import struct
5 # %%
6 class ScanDelegate(DefaultDelegate):
7 def __init__(self):
8 DefaultDelegate.__init__(self)
9
10 def handleDiscovery(self, dev, isNewDev, isNewData):
11 if isNewDev:
12 print("Discovered device", dev.addr)
13 elif isNewData:
14 print("Received new data from", dev.addr)
15
16
17 class NotifyDelegate(DefaultDelegate):
18 # Constructor (run once on startup)
19 def __init__(self, params):
20 DefaultDelegate.__init__(self)
21
22 # func is caled on notifications
23 def handleNotification(self, cHandle, data):
24 print("Notification from Handle: 0x" + format(cHandle,'02X') )
25 print(hexlify(data))
26
27
28 # %%
29 scanner = Scanner().withDelegate(ScanDelegate())
30 devices = scanner.scan(10.0)
31 creyond_devices = []
32 for dev in devices:
33 print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
34 for (adtype, desc, value) in dev.getScanData():
35 if value == "CreYond":
36 creyond_devices.append(dev)
37 print(" %s = %s" % (desc, value))
38
39 print(creyond_devices)
40 # %% get services
41 # the first device name CreYond
42 c_device = creyond_devices[0]
43 p_device = Peripheral(c_device)
44 p_device.withDelegate(NotifyDelegate(p_device))
45 services = p_device.getServices()
46
47 # displays all services
48 for service in services:
49 print(service)
50 # %% get specified service
51 service_uuid = UUID("00000010-3354-4d64-6e6f-xxxxxxxxx534a")
52 c_service = p_device.getServiceByUUID(service_uuid)
53 print(c_service)
54
55 # %%
56 characteristics = c_service.getCharacteristics()
57 # displays all characteristics
58 for char in characteristics:
59 print(char)
60 # %%
61 notify_char = characteristics[0]
62
63 #%%
64 hEcg=notify_char.getHandle()
65 for descriptor in p_device.getDescriptors(hEcg,c_service.hndEnd):
66 if (descriptor.uuid==0x2902):
67 print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle,"02X")}')
68 hEcgCCC=descriptor.handle
69
70 p_device.writeCharacteristic(hEcgCCC,bytes([1, 0]))
71
72 #%%
73 tmp_data=p_device.readCharacteristic(0x11)
74 print(tmp_data)
75 # %%
76 while True:
77 if p_device.waitForNotifications(1.0):
78 # handleNotification() was called
79 continue
80
81 print("Waiting... Waited more than one sec for notification")
82
83 # %%
84 p_device.disconnect()
85
86 # %%

参考链接:

【Bluetooth LE】Bluez中Bluetoothctl指令详解(连接iPhone为例)

bluepy官方Demo

RPi Bluetooth LE

github demo

Python3环境,树莓派使用bluepy与BLE设备通信的更多相关文章

  1. Android BLE开发——Android手机与BLE终端通信初识

    蓝牙BLE官方Demo下载地址:   http://download.csdn.net/detail/lqw770737185/8116019参考博客地址:    http://www.eoeandr ...

  2. 玩转BLE(2)_使用bluepy扫描BLE的广播数据

    1. 前言 在linux平台下,bluez是一个很不错的软件,提供了很多基于命令行的测试工具,如hciconfig.hcitool.hcidump.bluetoothctl等.利用这些工具,我们可以方 ...

  3. 让BLE设备的名称包含MAC地址

    对于研发和测试BLE来说,经常看到同名的设备,是极为不方便的,一大堆设备同时上电会让同事不知道哪一个设备才是自己真正想操作的目标.再说一下小米手环,家中有三支小米手环,打开设备搜索全是“MI”,都不知 ...

  4. 杂记:解决Android扫描BLE设备名称不刷新问题

    背景 个人开发过一种BLE设备有这样一种需求:当设备处于状态A时,广播设备名称A:处于状态B时,广播设备名称B. 问题 我们发现,当Android在进行Ble扫描的时候,扫描回调函数onScanRes ...

  5. Python3环境搭建

    Python3环境搭建   Windows系统下安装Python3 Python3 下载 Python3 最新源码,二进制文档,新闻资讯等可以在 Python 的官网查看到: Python 官网:ht ...

  6. 【Python学习】Python3 环境搭建

    参考地址:http://www.runoob.com/python3/python3-install.html Python3 环境搭建 本章节我们将向大家介绍如何在本地搭建 Python3 开发环境 ...

  7. 蓝牙BLE设备断线回连分析

    在 文章中分析了Hogp的连接的流程 ,这里分析一下回连的流程. 在使用ble设备的过程中,我们发现当设备和主机配对之后,如果没有解除配对,那么即便设备和主机断开,那么也是可以重新连接而不需要重新走配 ...

  8. 蓝牙BLE设备主机重启回连流程分析

    如果一个BLE设备已经与蓝牙中心设备连接上,那么当中心设备的断电重启,其依然会和配对过的BLE设备连接上,而不需要重新走配对的流程,这个过程叫做回连. 这篇文章就分析一下当中心设备断电重启之后,其与B ...

  9. centos7.4上安装python3环境的坑

    前言:为了将爬虫项目布置到服务器上,才有了今天这一下午的坑,必须记录 不要动现有的python2环境!不要动现有的python2环境!不要动现有的python2环境! 解压 tar -xvf Pyth ...

  10. 1. Python3 环境搭建

    Python3 环境搭建 开门见山,其他关于Python发展史.语言类型.优缺点等等 可以自己去百度百度,这里就不多说了.其实基本想要学这门语言的时候,你已经了解差不多了!!! Python的运行环境 ...

随机推荐

  1. PowerShell一键下载Nuget某个包的所有版本

    一转眼好几年没有写博客了,来博客园冒个泡,最近由于工作需要,内网办公,幸运的是只需要上传一个*.nupkg一个包信息就可以在私有nuget下载到了,下面就用PowerShell编写下载脚本,需要注意的 ...

  2. WebSocket事件

    优点 双通信,减少延迟 四个主要的Web Socket API事件: ·打开 onopen 当在客户端和服务器建立连接,就会从Web Socket实例触发open事件.它被称为客户端和服务器之间的初始 ...

  3. 某开源ERP最新版SQL与RCE的审计过程

    文章首发于 https://forum.butian.net/share/134 前言 代码路径 https://gitee.com/jishenghua/JSH_ERP 软件版本 华夏ERP_v2. ...

  4. 使用TOPIAM 轻松搞定「JumpServer」单点登录

    本文将介绍 TOPIAM 与 JumpServer 集成步骤详细指南. 应用简介 JumpServer 是广受欢迎的开源堡垒机,是符合 4A 规范的专业运维安全审计系统.JumpServer 帮助企业 ...

  5. [BootstrapBlazor] Blazor 使用 Mermaid 渲染详细图表

    BootstrapBlazor 是一套基于 Bootstrap 和 Blazor 的企业级组件库,无缝整合了 Bootstrap 框架与 Blazor 技术.它提供了一整套强大的工具,使开发者能够轻松 ...

  6. Spring Security并结合JWT实现用户认证(Authentication) 和用户授权(Authorization)

    引言在Web应用开发中,安全一直是非常重要的一个方面.Spring Security基于Spring 框架,提供了一套Web应用安全性的完整解决方案. JwT (JSON Web Token) 是当前 ...

  7. Qt/C++实现帧同步播放器/硬解码GPU绘制/超低资源占用/支持8K16K/支持win/linux/mac/嵌入式/国产OS等

    一.前言 首先泼一盆冷水,在不同的电脑上实现完完全全的帧同步理论上是不可能的,市面上所有号称帧同步的播放器,同一台电脑不同拼接视频可以通过合并成一张图片来绘制实现完完全全的帧同步,不同电脑,受限于网络 ...

  8. Qt音视频开发16-mpv通用接口

    一.前言 前面几篇文章,依次讲了解码播放.录像存储.读取和控制.事件订阅等,其实这些功能的实现都离不开封装的通用的接口,最开始本人去调用一些设置的时候,发现多参数的不好实现,原来需要用mpv_node ...

  9. 即时通讯技术文集(第41期):直播技术合集(Part1) [共12篇]

    为了更好地分类阅读 52im.net 总计1000多篇精编文章,我将在每周三推送新的一期技术文集,本次是第41 期. [- 1 -] 移动端实时音视频直播技术详解(一):开篇 [链接] http:// ...

  10. 微信团队分享:来看看微信十年前的IM消息收发架构,你做到了吗

    本文由微信技术团队分享,原题"十年前的微信消息收发架构长啥样?",下文进行了排版和内容优化等. 1.引言 2023 年,微信及 WeChat 的 DAU(月活用户)达到 13.4 ...