1. 程式人生 > >「python」bluepy 一款python封裝的BLE利器!

「python」bluepy 一款python封裝的BLE利器!

1、bluepy 簡介

bluepy是github上一個很好的藍芽開源專案,其地址在 LINK-1 , 其主要功能是用python實現linux上BLE的介面。

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版本:The code is tested on Python 2.7 and 3.4 ; it should also work on 3.3.

2、安裝

直接原始碼安裝,python3加持:

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登入:

➜ 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 [email protected]
[email protected]'s password: 1234

3、看文件,玩DEMO

bluepy的文件地址 LINK-2

在bluepy中新建一個examples資料夾,用來存放接下來我們的測試DEMO:

3.1 scan devices demo

這裡第一個DEMO是BLE裝置掃描,這裡用到了Scanner物件,該物件可以用來搜尋BLE裝置的廣播包資料。在大多數情況下該物件將會掃描出周圍所有可連線裝置。

下面是我改造為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的回撥函式,我們可以在其回撥函式中實時獲取並列印。當超時後會返回一個裝置列表;

執行效果如下:

「python」bluepy 一款python封裝的BLE利器!

 

注:注意用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 會返回所連線裝置的服務;

執行效果如下:

「python」bluepy 一款python封裝的BLE利器!

 

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

執行效果如下:

「python」bluepy 一款python封裝的BLE利器!

 

3.4 get device name

直接上程式碼:

進群:960410445  即可獲取數十套PDF!

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

執行效果如下:

「python」bluepy 一款python封裝的BLE利器!

 

小結

bluepy是非常棒的一款藍芽BLE工具,掌握它會為你節省比較多的時間~