树莓派开发 —— 使用蓝牙配置wifi(2):使用bluez开启服务

分类: 树莓派

2019-04-02

|

632

|

评论:0

分享:

bluez是linux官方蓝牙协议栈,它实现了RFCOMM,L2CAP等协议,下面给出一个python的样例。
(这里假设你已经参照上一篇进行了service文件的修改)

安装

apt-get install pi-bluetooth bluez bluez-firmware blueman libbluetooth-dev

pip install pybluez

开启rfcomm服务

from bluetooth import *

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service( server_sock, "SampleServer",
                   service_id = uuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ], 
                    )
                   
print("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: 
            break
        
        # data转换成字符串
        data = str(data, encoding="utf-8")
        print("received [%s]" % data)
        
        # handler(data)
        client_sock.send(data)
except:
    pass
finally:

    client_sock.close()
    server_sock.close()
    print("all done")

现在你可以用手机的蓝牙串口软件发数据到树莓派了



标签: 树莓派 蓝牙
本文共 0 个回复

发表评论 (对文章评论)

captcha