Linux 端蓝牙调试
@(嵌入式)[BLE]
毕业大半年一直从事Ble外设开发,发现linux上可以使用bluez进行蓝牙开发,更加便捷的是,有一个python模块对bluez接口进行封装,叫bluepy,给开发测试带来更多便捷。
获取 & 安装
开发平台 ubunt 14.04
$ sudo apt-get install git build-essential libglib2.0-dev
$ git clone https://github.com/IanHarvey/bluepy.git
$ cd bluepy
$ python setup.py build
$ python setup.py install
个人测试脚本库mybluepy, 没怎么写过python,供参考。
使用 hcitool & gatttool
安装了bluez协议栈后提供的工具,简单操作如下。
- 查看蓝牙pc的设备
hcitool dev
- 扫描ble
hcitool lescan
- 设置gatttool
gatttool -b 76:66:44:33:22:72 -I
-I : 进入交互模式
在gatttool下,
开始连接设备 : connect
输入 : help查看其他指令输入characteristics 查看特征值信息,结果大概如下
handle: 0x0022, char properties: 0x1a, char value handle: 0x0023, uuid: 0000a802-0000-1000-8000-00805f9b34fb
如上, handle 0x0023 写数据, 向0x0023+1 写 0x0100
,设置监听,写0取消监听
bluepy 脚本
模块文档
提供一个简单的例子:
#!/usr/bin/python
from __future__ import print_function
import sys
import binascii
import btle
import os
ble_conn = None
class MyDelegate(btle.DefaultDelegate):
def __init__(self, conn):
btle.DefaultDelegate.__init__(self)
self.conn = conn
def handleNotification(self, cHandle, data):
data = binascii.b2a_hex(data)
print("Notification:", str(cHandle), " data ", data)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
pass
elif isNewData:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
def ble_connect(devAddr):
global ble_conn
if not devAddr is None and ble_conn is None:
ble_conn = btle.Peripheral(devAddr, btle.ADDR_TYPE_PUBLIC)
ble_conn.setDelegate(MyDelegate(ble_conn))
print("connected")
def ble_disconnect():
global ble_conn
ble_conn = None
print("disconnected")
if __name__ == '__main__':
ble_mac == "66:55:44:33:22:11"
# scan
scanner = btle.Scanner().withDelegate(MyDelegate(None))
timeout = 10.0
devices = scanner.scan(timeout)
for dev in devices:
if dev.addr == ble_mac:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
for (adtype, desc, value) in dev.getScanData():
print (" %s(0x%x) = %s" % (desc, int(adtype), value))
break
# connect
ble_connect(ble_mac)
# write , set listen
snd_content_str = """\\x01\\x00"""
ble_conn.writeCharacteristic(handle, snd_content_str)
# wait notification
ble_conn.waitForNotifications(2.0)
# disconnect
ble_disconnect()