前言
这两天在搞树莓派蓝牙通信,发现里面的坑还真不少,在次记录一下,以备查询
安装 pybluez
我用的python3,现在差不多没人用Python2了吧…
首先需要安装 libbluetooth-dev
sudo apt-get install libbluetooth-dev
然后安装 pybluez
sudo pip3 install pybluez
使用
可以先看看官方的示例程序 点我跳转
我使用了 rfcomm-server.py 这个程序,遇到以下错误
1. no such file or directory
解决办法:修改文件
sudo nano /lib/systemd/system/bluetooth.service
找到如下一行
ExecStart=/usr/lib/bluetooth/bluetoothd
在末尾添加 -E -C
ExecStart=/usr/lib/bluetooth/bluetoothd -E -C
如果没有这一行,需要自行添加,写在上面那条语句下面即可
ExecStartPost=/usr/bin/sdptool add SP
Ctrl+o 保存 Ctrl+x 退出
2. no advertisable device
这是由于蓝牙不可见导致
解决办法:在原程序上增加两句,使蓝牙可发现
#!/usr/bin/env python3
"""PyBluez simple example rfcomm-server.py
Simple demonstration of a server application that uses RFCOMM sockets.
Author: Albert Huang <albert@csail.mit.edu>
$Id: rfcomm-server.py 518 2007-08-10 07:20:07Z albert $
"""
import bluetooth
import os
import sys
#增加以下两句 修改蓝牙可见
os.system("bluetoothctl power on")
os.system("bluetoothctl discoverable on")
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
server_sock.bind(("", bluetooth.PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
bluetooth.advertise_service(server_sock, "SampleServer", service_id=uuid,
service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
profiles=[bluetooth.SERIAL_PORT_PROFILE],
# protocols=[bluetooth.OBEX_UUID]
)
print("Waiting for connection on RFCOMM channel", port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from", client_info)
try:
while True:
data = client_sock.recv(1024)
if not data:
break
print("Received", data)
except OSError:
pass
print("Disconnected.")
client_sock.close()
server_sock.close()
print("All done.")
3.Permission denied
解决办法:修改文件权限
sudo chmod 777 /var/run/sdp
参考链接
- https://bbs.archlinux.org/viewtopic.php?id=201672
- https://blog.csdn.net/qq21497936/article/details/110940484