扫描设备

创建一个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. CVE-2023-0461 漏洞分析与利用

    PS: 文章首发于补天社区 漏洞分析 tcp_set_ulp里面会分配和设置 icsk->icsk_ulp_data,其类型为 tls_context tcp_setsockopt do_tcp ...

  2. 部署docker-registry +ui , 使用ansible部署docker实例

    #部署docker-registry +ui , 使用ansible部署docker实例 docker registry 配置域名证书, 用户密码认证, 轻量UI shell部署docker-regi ...

  3. iOS app 自动化测试 - 环境搭建

    1. 基本前提 安装好了 mac 上自动化测试的基本环境 如果没有,可以参考这一个: 2. iOS appium python自动化测试环境搭建 2.1 真机环境 2.1.1 前提:安装了 appiu ...

  4. docker-安装Oracle11g

    获取镜像 在线   docker pull oracleinanutshell/oracle-xe-11g 离线 tar包下载:链接: https://pan.baidu.com/s/1bRp6mSq ...

  5. V3Det&Bigdetection下载记录

    V3Det dataset https://opendatalab.com/V3Det BigDetection

  6. .net core 3.x 发布单文件

    .翻译自:https://github.com/dotnet/designs/blob/master/accepted/2020/single-file/staging.md NET Core 3.0 ...

  7. 前端实现 HTML 网页转 PDF 并导出🤓

    有个新需求,当点击[下载]按钮时,直接将当前 html页面下载为 PDF.通过 html2canvas + jsPDF 可实现PDF单页下载,甚至是多页下载,记录分享一下~ 最后有源码,可自取 htm ...

  8. NET Core3.1 Cors 添加跨域支持

    在 Startup 里加: services.AddCors(options => options.AddPolicy( DefaultCors, p => p.SetIsOriginAl ...

  9. web应用分页-copy

    1. 场景描述 目前大部分的应用程序中都会用到分页功能,以便减少前端浏览器及后台服务器的压力,以及其他方面的考虑. (1)分页从概念上可分为逻辑分页和物理分页,逻辑分页主要是通过应用程序(前端或者后端 ...

  10. JVM虚拟机---常用JVM配置参数

    常用JVM配置参数 常用JVM配置参数主要有:Trace跟踪参数.堆的分配参数.栈的分配参数. 一.Trace跟踪参数 跟踪参数用于跟踪监控JVM,对于开发人员来讲用于JVM调优以及故障排查的. 1. ...