Использование Pybluez для подключения к уже подключенному устройству Bluetooth?
Я пишу программу на Python, которая включает использование устройства Bluetooth. Прямо сейчас я могу подключиться к устройству Bluetooth из программы Python, но каждый раз, когда я завершаю работу с программой Python, мне приходится переводить мой пакет устройств в режим сопряжения (потянув переключиться), а затем снова соединиться с ним. Я надеялся, что вы сможете показать какой-нибудь метод, с помощью которого я мог бы автоматически подключаться к сопряженному устройству, вместо того, чтобы переводить его в режим сопряжения и подключать снова при каждом запуске программы python.
Это код моего модуля Bluetooth 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 ответ
Привет, я не уверен, что это решит вашу проблему, однако это может указать вам правильное направление. Ниже приведен код, который автоматически подключается к целевому устройству Bluetooth, как только запускается программа python. Это делается путем жесткого кодирования адреса устройства Bluetooth.
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)