Sha*_*med 5 python bluetooth pybluez
我有一个使用 Rasbian OS 启动的 Raspberry pi 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")
Run Code Online (Sandbox Code Playgroud)
我已经有一个工作 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')
Run Code Online (Sandbox Code Playgroud)
这是因为蓝牙需要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
Run Code Online (Sandbox Code Playgroud)
它似乎在该 server_sock.accept() 函数处循环。
谁能给出解决方案吗?
我也面临同样的问题。问题出在 pi 的运行功率上。USB 端口通常仅提供500 mA, 5 V. 为了获得最佳性能, Raspberry pi 需要大约 100V 的电压源4.75 to 5.25V和 100V 范围内的电流700 to 1000 mA。Raspberry Pi 需要多少电流 (mA) 取决于您连接的设备。尝试更换电源,通过 1000 mA 5v 适配器获取电源。让我知道它是否有效。