使用Pybluez连接已经配对的蓝牙设备?

时间:2018-01-30 01:48:45

标签: python bluetooth pybluez

我正在编写一个涉及使用蓝牙设备的python程序。现在我可以从python程序连接到蓝牙设备但是每次我退出python程序时我必须将我的设备包带到配对模式(通过拉动开关),然后再次与它配对。 我希望你能展示出我可以自动连接到配对设备的方法,而不是每次运行python程序时都将它带到配对模式并重新连接。

这是我的蓝牙python模块的代码:

import bluetooth
from bluetooth.btcommon import BluetoothError
import time

class DeviceConnector:

TARGET_NAME = "Device name"
TARGET_ADDRESS = None
SOCKET = None

def __init__(self):
    pass

def getConnectionInstance(self):
    self.deviceDiscovery()
    if(DeviceConnector.TARGET_ADDRESS is not None):
        print('Device found!')
        self.connect_bluetooth_addr()
        return DeviceConnector.SOCKET
    else:
        print('Could not find target bluetooth device nearby')

def deviceDiscovery(self):
    try:
        nearby_devices = bluetooth.discover_devices(lookup_names = True, duration=5)
        while nearby_devices.__len__() == 0 and tries < 3:
            nearby_devices = bluetooth.discover_devices(lookup_names = True, duration=5)
            tries += 1
            time.sleep (200.0 / 1000.0)
            print ('couldnt connect! trying again...')
        for bdaddr, name in nearby_devices:
            if bdaddr and name == DeviceConnector.TARGET_NAME:
                DeviceConnector.TARGET_ADDRESS = bdaddr
                DeviceConnector.TARGET_NAME = name
    except BluetoothError as e:
        print ('bluetooth is off')

def connect_bluetooth_addr(self):
    for i in range(1,5):
        time.sleep(1)
        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        try:
            sock.connect((DeviceConnector.TARGET_ADDRESS, 1))
            sock.setblocking(False)
            DeviceConnector.SOCKET = sock
            return
        except BluetoothError as e:
            print('Could not connect to the device')
    return None

谢谢:)

1 个答案:

答案 0 :(得分:0)

嗨,我不确定这是否能解决您的问题,但是这可能会为您指明正确的方向。下面是python程序一执行就会自动连接到目标蓝牙设备的代码。这是通过对蓝牙设备的地址进行硬编码来实现的

import bluetooth


target_name = "enter your Bluetooth device name"
target_address = None

nearby_devices = bluetooth.discover_devices()

for bdaddr in nearby_devices:
    if target_name == bluetooth.lookup_name( bdaddr ):
        target_address = bdaddr
        break

if target_address is not None:
    print("found target bluetooth device with address ", target_address)
else:
    print("could not find target bluetooth device nearby")


bd_addr = target_address
print(bd_addr)

port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)