我有一个用 Rasbian OS 启动的树莓派 B 型,并插入了一个蓝牙加密狗。从我的 PC 搜索时,我能够发现我的 pi,并且能够使用 Blueman GUI 进行配对。这是我用于配对过程的 python 程序:
from bluetooth import *
server_sock=BluetoothSocket(L2CAP)
server_sock.bind(("", 17))
with open(sys.path[0] + "/sdp_record.xml", "r") as fh:
service_record = fh.read()
self.bus = dbus.SystemBus()
self.manager = dbus.Interface(self.bus.get_object("org.bluez", "/"),"org.bluez.Manager")
adapter_path = self.manager.DefaultAdapter()
self.service = dbus.Interface(self.bus.get_object("org.bluez",adapter_path),
"org.bluez.Service")
service_handle = service.AddRecord(service_record)
print "Service record added"
server_sock.listen(1)
print("Waiting for connection on L2CAP")
try:
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
while True:
data = client_sock.recv(1024)
if len(data) == 0:
break
print("received [%s]" % data)
except IOError:
pass
except KeyboardInterrupt:
print "Stopping..."
stop_advertising(server_sock)
sys.exit()
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
我已经有一个正在工作的 SDP 记录,它正在被读取并被添加到 SDP 服务器。起初,当我发布这个问题时,我收到了这个错误:
Traceback (most recent call last):
File "pytest.py", line 4, in <module>
server_sock.bind(("", 17))
File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 140, in bind
return self._sock.bind (addrport)
_bluetooth.error: (13, 'Permission denied')
这是因为蓝牙需要root权限。我使用运行python代码sudo python code.py
并解决了这个错误。非常感谢回答的人。
现在我得到的问题是,即使在配对之后,套接字连接也没有被接受。对于配对,我在一个终端中运行代码,当它运行时waiting for connection on L2CAP
,我打开另一个控制台并使用命令将 pi 与我的计算机sudo bluez-simple-agent hci0 computers_macaddress
配对,在 pi 和计算机中输入一个 pin 后,它就会配对。但是配对后,代码还在等待连接:
Service record added
Waiting for connection on L2CAP
它似乎在那个 server_sock.accept() 函数上循环。
谁能给出解决方案?