【发布时间】:2016-04-23 12:08:34
【问题描述】:
我正在尝试构建一个简单的蓝牙客户端/服务器,其中我的 Raspberry Pi 是服务器,我的笔记本电脑是客户端。
这是服务器代码(在我的 Raspberry Pi 上运行):
#!/usr/bin/python
# -*- coding: utf-8
import wifi, bluetooth
uuid="1e0ca4ea-299d-4335-93eb-27fcfe7fa848"
print "Setting up Bluetooth socket"
try:
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.bind(("", 0))
sock.listen(1)
except IOError as e:
print str(e)
print "Registering service"
try:
bluetooth.advertise_service(sock, "MyService", uuid)
while True:
print "Waiting for connection..."
client_sock,address = sock.accept()
print "Accepted connection from {0}".format(address)
data = client_sock.recv(1024)
print "Received data: {0}".format(data)
print "Closing client socket."
client_sock.close()
except IOError as e:
print str(e)
这似乎有效,脚本运行并以Waiting for connection... 阻塞。
然后,我的客户端代码:
#!/usr/bin/python
# -*- coding: utf-8
import bluetooth, time
mac = "00:15:83:E5:E2:46"
uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848"
service = []
retry = 1
while len(service) == 0:
print "Looking for service on {0}, try {1}".format(mac, retry)
service = bluetooth.find_service(address=mac, uuid=uuid)
retry = retry + 1
time.sleep(1)
if len(service) == 1:
service = service[0]
print "Service found. Name={0}".format(service["name"])
print "Connecting to service."
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
try:
sock.connect((mac, service["port"]))
print "Connected to service on {0} on port {1}".format(mac, service["port"])
except bluetooth.btcommon.BluetoothError as e:
print "Connection failed: {0}".format(e)
elif len(service) == 0:
print "No service found on mac {0}.".format(mac)
else:
print "{0} services found for mac/uuid, ignored.".format(len(service))
也可以,直到我尝试 connect() 到 Raspberry Pi。我收到以下错误:
Connecting to service.
Connection failed: (111, 'Connection refused')
我尝试将笔记本电脑连接到 Raspberry Pi(它找到它并说它已“连接”)并在线搜索更多信息,但找不到任何东西。
【问题讨论】:
标签: python bluetooth raspberry-pi