Pybluez在不同设备上的不稳定行为-Python

时间:2018-09-02 16:32:28

标签: python server bluetooth raspberry-pi pybluez

我有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('什么都没找到')

如果在2-3次成功连接后错误开始发生,我需要重新启动Raspberry pi才能再次连接。

感谢您的帮助

0 个答案:

没有答案