扫描设备

创建一个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. 【VMware VCF】管理 VCF 环境中组件的密码策略。

    使用 SDDC Manager 中的"密码管理"功能可以统一管理 VCF 环境中组件的用户密码,比如更新(Update).轮换(Rotate)以及修复(Remediate)组件的密 ...

  2. PDFsharp 1.50

    PDFsharp 1.50 Preview Information - PDFsharp & MigraDoc PDFShapr 1.50 修复与改进 支持 Object Streams - ...

  3. Alpine介绍与apk的基本使用

    前言 Alpine是一个面向安全的轻量级的Linux发行版,相比与CentOS,ubuntu体积小很多,大约只有5M左右,由于体积小的原因,在很多场景下都会使用它来按需制作一些轻量级镜像,虽然体积小但 ...

  4. Qt编写的视频播放综合应用示例(qmedia/ffmpeg/vlc/mpv/海康sdk等)

    一.功能特点 1.1 基础功能 支持各种音频视频文件格式,比如mp3.wav.mp4.asf.rm.rmvb.mkv等. 支持本地摄像头设备,可指定分辨率.帧率. 支持各种视频流格式,比如rtp.rt ...

  5. Qt编写地图综合应用55-海量点位标注

    一.前言 海量点位标注的出现,是为了解决普通设备点超过几百个性能极速降低的问题,普通的marker标注由于采用的是对象的形式存在于地图中,数量越多,占用内存特别大,超过1000个点性能极其糟糕,哪怕是 ...

  6. Qt5离线安装包无法下载问题解决办法

    1.前言 Qt5离线安装包目前在国内已经被墙了,无法下载,只能下载在线安装包: 直接访问会显示Download from your IP address is not allowed: 本文就提出两种 ...

  7. [转]ubuntu20.04使用dev-sidecar找不到安装证书

    火狐.chrome等浏览器不走系统证书,火狐.谷歌浏览器必须在浏览器上安装证书 然后死活找不到证书,搜索了整个目录也没有. 原来是我的显示隐藏文件没打开.打开目录的"显示隐藏文件" ...

  8. Spring基础 01 | Ioc

    Maven项目的创建 项目所在路径 - 项目一 - 创建Module - 添加Webapp(Project Structure) - 项目二 Spring简介 分层全栈(各层解决方案)轻量级框架,以I ...

  9. canal源码分析简介-3

    5.0 store模块  2018-10-08 23:14:58  8,328 7 1 store模块简介 store模块用于binlog事件的存储 ,目前开源的版本中仅实现了Memory内存模式.官 ...

  10. selenium学习-常用方法

    id_#当前元素的ID  tag_name#获取元素标签名的属性  text#获取该元素的文本.  click()#单击(点击)元素  submit()#提交表单  clear()#清除一个文本输入元 ...