1

我有 3 个设备 -> 2*PC 和 1 个 Raspberry Pi。2台PC仅用于测试。2PC = 2 台装有 Windows 10 的笔记本电脑。

在树莓派上我有蓝牙服务(Py 2.7 但如果 print() 3.5 也应该工作):

import bluetooth

try:
    server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
    server_sock.bind(("",0))
    server_sock.listen(100)
    bluetooth.advertise_service( server_sock, "MyService",
    service_classes = [ bluetooth.SERIAL_PORT_CLASS ],
    profiles = [ bluetooth.SERIAL_PORT_PROFILE ] )
    client_sock, client_info = server_sock.accept()
    print("Accepted connection from ", client_info)
    client_sock.send('Hello')
    data = client_sock.recv(1024)
    print("received [%s]" % data)
    client_sock.close()
    server_sock.close()
except:
    client_sock.close()
    server_sock.close()

在笔记本电脑上我有客户端

import sys
from bluetooth import *

try:
    service_matches = find_service(name="MyService",
    uuid = SERIAL_PORT_CLASS )
    print(service_matches)
    if len(service_matches) == 0:
        print('Found nothing')
        sys.exit(0)

    for i in service_matches:
        print(i)
    first_match = service_matches[0]
    port = first_match["port"]
    name = first_match["name"]
    host = first_match["host"]
    print "connecting to ", host
    sock=BluetoothSocket( RFCOMM )
    sock.connect((host, port))
    data = sock.recv(1024)
    sock.send("hello!!")

    print(data)
    sock.close()
except Exception as e:
    print(e)
    sock.close()

一切正常,但是,使用一台笔记本电脑,我可以重复聆听和连接之间的过程。与其他 Laptot 我能够连接 2-3 次,然后我收到此错误:

in <module>
    uuid = SERIAL_PORT_CLASS )
  File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 204, in find_service
    addresses = discover_devices (lookup_names = False)
  File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 15, in discover_devices
    devices = bt.discover_devices(duration=duration, flush_cache=flush_cache)
IOError: No more data is available.

这意味着错误发生在 pybluez 函数 find_service 内部。有趣的是,当它找不到设备时会发生这种情况。在从未触发此错误的另一台笔记本电脑上(始终连接),但没有设备总是以: print('Found nothing')

当 2-3 次成功连接后开始出现错误时,我需要重新启动 Raspberry pi 才能再次连接。

谢谢你的帮助

4

0 回答 0