扫描设备

创建一个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. 攻防世界:web习题之disabled_button

    攻防世界:web习题之disabled_button 题目内容 https://adworld.xctf.org.cn/challenges/list 打开网页会发现有一个无法点击的按钮 思路 查看该 ...

  2. 修改QScrollArea背景色透明,且不影响子控件,在Edit Style Sheet中修改

    在QScrollArea或者父控件中设置: QScrollArea{ background-color:transparent; } 在scrollAreaWidgetContents控件或者父控件中 ...

  3. 【Vue】vite+vue3 如何实现点击进入详情页/文章页

    如上图,点击标题可以进入详情页,关键代码截图如下: 然后去配置路由 那么组件如何从地址中接收参数呢

  4. 【uni-app】【01】底部导航栏与页面切换

    1.(配置文件在哪)uni-app 路由控制是在 pages.json文件中的. 2.(基本配置项有哪些)初学的时候主要有三个配置项,①pages ② globalStyle ③ tabbar [!T ...

  5. 龙哥量化:通达信的macd改进优化方法及选股公式源码

    有很多同学是看macd的数值,遇到股价比较低的,macd数值变成0.00,就看不明白了, 优化: 第一步,给股价乘100,所有的哦 源码: DIF:EMA(CLOSE*100,12)-EMA(CLOS ...

  6. Qt开源作品3-串口调试助手

    一.前言 这个作品很多年前就做了,经过了长达七八年的完善,当然也不是全身心的投入完善,也就是根据实际项目的需求不断完善的,尤其是模拟设备回复数据的功能,这个在很多用Qt做上位机开发非常实用,毕竟很多软 ...

  7. WebClient 用法小结

    进来的项目中要实现能够在windows service中调用指定项目的链接页面.由于访问页面时候使用的是ie浏览器或其他浏览器,所以想起用webclient类. 如果只想从特定的URI请求文件,则使用 ...

  8. Qml 中实现水印工具

    [写在前面] 在 Qt 的 Quick 模块中,QQuickPaintedItem 是一个非常有用的类,它允许我们在 Qml 中自定义绘制逻辑. 我们可以通过这种方式实现水印工具,包括在文本.图片或整 ...

  9. IM跨平台技术学习(四):蘑菇街基于Electron开发IM客户端的技术实践

    本文由蘑菇街前端技术团队分享,原题"Electron 从零到一",有修订和改动. 1.引言 本系列文章的前面几篇主要是从Electron技术本身进行了讨论(包括:第1篇初步了解El ...

  10. kubernetes系列(八) - 控制器的资源清单定义

    1. ReplicaSet 1.1 ReplicaSet资源清单 1.2 selector 2. Deployment 2.1 Deployment资源清单 2.2 其他相关操作 2.2.1 应用ya ...