Linux 端藍芽除錯工具

weixin_33782386發表於2016-07-21

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()
    

參考

相關文章