Linux(RaspberryPi)上通过Python进行蓝牙BLE通信

使用python的第三方库bluepy可以很方便的在linux主机如树莓派上进行蓝牙通信。

  • bluepy的安装
sudo apt-get install python-pip libglib2.0-dev
sudo pip install bluepy

源码安装如下:

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

官方示例代码

import btle

class MyDelegate(btle.DefaultDelegate):
    def __init__(self, params):
        btle.DefaultDelegate.__init__(self)
        # ... initialise here

    def handleNotification(self, cHandle, data):
        # ... perhaps check cHandle
        # ... process 'data'


# Initialisation  -------

p = btle.Peripheral( address )
p.setDelegate( MyDelegate(params) )

# Setup to turn notifications on, e.g.
#   svc = p.getServiceByUUID( service_uuid )
#   ch = svc.getCharacteristics( char_uuid )[0]
#   ch.write( setup_data )

# Main loop --------

while True:
    if p.waitForNotifications(1.0):
        # handleNotification() was called
        continue

    print "Waiting..."
    # Perhaps do something else here

这是自己写的一个和arduino(arduino bluno)上的BLE通讯的代码,先遍历输出目标的服务(server)信息
在与目标通讯。
在arduino上只是接收到’B’字符后开始发送数据

from bluepy import btle
from bluepy.btle import DefaultDelegate
import time

class NotifyDelegate(DefaultDelegate):
    def __init__(self):
            DefaultDelegate.__init__(self)
    def handleNotification(self,cHandle,data):
        print("notify from "+str(cHandle)+str(data)+"\n")

dev=btle.Peripheral("50:65:83:94:28:02").withDelegate(NotifyDelegate())

time.sleep(0.5)

for ser in dev.getServices():
    print(str(ser))
    for chara in ser.getCharacteristics():
        print(str(chara))
        print("Handle is "+str(chara.getHandle()))
        print("properties is "+chara.propertiesToString())
        if(chara.supportsRead()):
            print(type(chara.read()))
            print(chara.read())
    print("\n")



dev.writeCharacteristic(37,b'A',withResponse=True)
dev.waitForNotifications(1)
dev.writeCharacteristic(37,b'b',withResponse=True)
dev.waitForNotifications(1)
dev.writeCharacteristic(37,b'A',withResponse=True)
dev.waitForNotifications(1)
dev.writeCharacteristic(37,b'b',withResponse=True)

i=0
dev.writeCharacteristic(37,b'B',withResponse=False)
while(True):
    if(dev.waitForNotifications(1)):
        i=i+1
        if(i>1000):
            break
        continue
    print("Waiting...")
time.sleep(0.5)

dev.disconnect()

Linux(RaspberryPi)上通过Python进行蓝牙BLE通信_第1张图片

你可能感兴趣的:(python,linux,bluepy,Linux)