扫描设备

创建一个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. 前后端数据传递之form-data

    前情 最近在项目开发中,跟服务端连调发现接口一直报错,服务端一直提示是数据没有传,而通过浏览器控制台发现数据是有传的. 坑 服务通过postman自测是OK的.经过和服务端一起定位发现服务端只接收以f ...

  2. GraphQL Part VII: 实现数据变更

    我们已经可以使用各种方式来获取数据了.但是如何修改服务器端的数据呢?包括数据插入,修补,删除或者更新等等.GraphQL 的 mutation 就是负责这部分的. 在我们继续之前,我想对项目做一点调整 ...

  3. Anaconda功能、优点、安装步骤(安装视频)

    目录 介绍 功能(包和环境的管理器) 优点(省时省心) 下载地址 安装教程 要点 conda 的常见命令 查询完整帮助文件 管理conda和anaconda 管理环境 包管理 其他 ​ 介绍 Anac ...

  4. 【Python】【Jupyter】Jupyter 的简单使用 与 Python的基本输出输入

    上课无聊写着玩的,不必当真. Jupyter 的简单使用 与 Python的基本输出输入 目录 Jupyter 的简单使用 与 Python的基本输出输入 数据准备 输出 输入 一些练习 print( ...

  5. arch 音频处显示没有输入或输出设备

    我的设备是 Dell G15 5511, 属于比较新的设备, 查看了 Fourm 与 wiki 后使用 1 yay -S sof-firmware   安装框架之后重启即可使用.

  6. Docker封装Java环境镜像(Alpine+OpenJDK)

    在给Java程序封装镜像时,使用的基础镜像动辄上百M,还需要每次部署的时候挂载时区等问题,不如自己封装一个镜像,供之后使用. 这里使用Alpine Linux(3.9) 安装OpenJDK 1.8及部 ...

  7. 转载 Netty tls验证

    https://blog.csdn.net/luo15242208310/article/details/108215019 目录Java ssl单向TLSServer端Client端双向TLSser ...

  8. Qt/C++开发经验小技巧286-290

    国内站点:https://gitee.com/feiyangqingyun 国际站点:https://github.com/feiyangqingyun 很多时候项目越写越大,然后就可能遇到,明明之前 ...

  9. SQL Server 递归+向上统计

    前几天有个需求需要基于分类数据向上统计总数,一开始第一个想法是通过程序来计算,后再思考能不能通过SQL脚本直接来计算 基础数据 Id ParentId Category Num 1 0 分类1 0 2 ...

  10. Solution -「COCI 2009-2010」「洛谷 P8076」RESTORAN

    \(\mathscr{Description}\)   Link.   给定一个含 \(n\) 个点 \(m\) 条边的简单图, 求一种边二染色方案, 使得所有 \(\deg\ge2\) 的结点都邻接 ...