[python] bluepy 一款python封裝的BLE利器


一、bluepy 簡介

bluepy 是github上一個很好的藍牙開源項目,其地址在 LINK-1, 其主要功能是用python實現linux上BLE的接口。html

This is a project to provide an API to allow access to Bluetooth Low Energy devices from Python. At present it runs on Linux only; I've mostly developed it using a Raspberry Pi, but it will also run on x86 Debian Linux.python

支持python版本:The code is tested on Python 2.7 and 3.4; it should also work on 3.3.linux

 

二、安裝

直接源碼安裝,python3加持:git

sudo apt-get install git build-essential libglib2.0-dev
git clone https://github.com/IanHarvey/bluepy.git
cd bluepy
python3 setup.py build
sudo python3 setup.py install

注:不要用python2,這輩子都不會用python2!
注:進行到這一步忽然驚醒個人臺式機無藍牙,遂開啓個人無屏幕樹莓派,用命令找其ip,並用ssh登陸:github

➜  Downloads  sudo nmap -sS -p 22 192.168.31.0/24 | grep -B 5 -A 0 "Pi"
Nmap scan report for 192.168.31.51
Host is up (0.19s latency).

PORT   STATE SERVICE
22/tcp open  ssh
MAC Address: B8:27:EB:71:33:AE (Raspberry Pi Foundation)

➜  Downloads  ssh pi@192.168.31.51
pi@192.168.31.51's password: 1234

 

三、看文檔,玩DEMO

bluepy 的文檔地址 LINK-2
在bluepy中新建一個examples文件夾,用來存放接下來咱們的測試DEMO:ssh

3.1 scan devices demotcp

這裏第一個DEMO是BLE設備掃描,這裏用到了Scanner對象,該對象能夠用來搜索BLE設備的廣播包數據。在大多數狀況下該對象將會掃描出周圍全部可鏈接設備。ide

下面是我改造爲python3的代碼:函數

➜  examples git:(master) ✗ cat scan.py 
#!/usr/bin/env python
# coding=utf-8

from bluepy.btle import Scanner, DefaultDelegate

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print("Discovered device", dev.addr)
        elif isNewData:
            print("Received new data from", dev.addr)

scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(10.0)

for dev in devices:
    print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
    for (adtype, desc, value) in dev.getScanData():
        print("  %s = %s" % (desc, value))
  • 其中Scanner([index=0])用於產生並初始化一個新的scanner對象,index 用來指名哪個藍牙設備就會被用(默認0表示使用/dev/hci0)。掃描知道調用start或scan函數以後纔會開始;工具

  • 其中withDelegate(delegate)存儲對委託對象的引用,委託對象在接收來自設備的廣播時接收回調。有關詳細信息,請參閱DefaultDelegate的文檔;

  • 其中scan([timeout = 10])開始掃描並帶有超時,在此掃描期間掃描到的設備會觸發Delegate的回調函數,咱們能夠在其回調函數中實時獲取並打印。當超時後會返回一個設備列表;

執行效果以下:

注:注意用sudo運行,更詳細的接口見 LINK-3

 
3.2 get services

bluepy 的DEMO有點少,我又找了個專是DEMO的github項目:LINK-5

將其中的getServices.py改造下:

➜  examples git:(master) ✗ cat get_setvices.py 
import sys
from bluepy.btle import UUID, Peripheral

if len(sys.argv) != 2:
  print("Fatal, must pass device address:", sys.argv[0], "<device address="">")
  quit()

p = Peripheral(sys.argv[1],"public")

services=p.getServices()

#displays all services
for service in services:
   print(service)
  • 其中Peripheral(sys.argv[1],"public")是用mac地址建立一個鏈接,因爲咱們上一步用scan搜索到的mac地址爲public類型,所以這裏第二個參數爲"public",更詳細的介紹見 LINK-6

  • 其中getServices會返回所鏈接設備的服務;

執行效果以下:

 
3.3 get characteristics

同3.2獲取characteristic的代碼以下:

➜  examples git:(master) ✗ cat get_characteristics.py 
import sys
from bluepy.btle import UUID, Peripheral

if len(sys.argv) != 2:
  print("Fatal, must pass device address:", sys.argv[0], "<device address="">")
  quit()

p = Peripheral(sys.argv[1],"public")

chList = p.getCharacteristics()
print("Handle   UUID                                Properties")
print("-------------------------------------------------------")                     
for ch in chList:
   print("  0x"+ format(ch.getHandle(),'02X')  +"   "+str(ch.uuid) +" " + ch.propertiesToString())

執行效果以下:

 
3.4 get device name

直接上代碼:

➜  examples git:(master) ✗ cat get_device_name.py 
import sys
from bluepy.btle import UUID, Peripheral
 
dev_name_uuid = UUID(0x2A00)
 
if len(sys.argv) != 2:
  print("Fatal, must pass device address:", sys.argv[0], "<device address="">")
  quit()
 
p = Peripheral(sys.argv[1],"public")
 
try:
    ch = p.getCharacteristics(uuid=dev_name_uuid)[0]
    if (ch.supportsRead()):
            print(ch.read())
 
finally:
    p.disconnect()

運行效果以下:

 

小結

bluepy 是很是棒的一款藍牙BLE工具,掌握它會爲你節省比較多的時間~


: 完~
: 你們以爲不錯,能夠點推薦給更多人~


[1]. bluepy GITHUB 連接地址
[2]. bluepy 的文檔地址
[3]. Scanner Demo 地址
[4]. python3和python2的print的區別
[5]. bluepy examples using nRF51822 width mbed
[6]. The Peripheral class


@beautifulzzzz
智能硬件、物聯網,熱愛技術,關注產品
博客:http://blog.beautifulzzzz.com
園友交流羣:414948975
相關文章
相關標籤/搜索