You can download this code by clicking the button below.
This code is now available for download.
This function is used to connect to a Bluetooth device. It first scans for nearby Bluetooth devices, then finds the target device by name, and finally connects to the device.
Technology Stack : PyBluez, BluetoothSocket, discover_devices, connect
Code Type : The type of code
Code Difficulty : Advanced
def connect_to_bluetooth_device(device_name, address):
"""
Connect to a Bluetooth device given its name and address.
"""
import bluetooth
import random
# Scan for nearby devices
nearby_devices = bluetooth.discover_devices(lookup_names=True)
print(f"Found {len(nearby_devices)} devices.")
# Find the device by name
device = None
for bdaddr, name in nearby_devices:
if name == device_name:
device = (bdaddr, name)
break
if device is None:
print(f"Device with name {device_name} not found.")
return
# Connect to the device
print(f"Connecting to {device[1]}...")
port = random.choice([1, 2, 3, 4, 5])
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((device[0], port))
print(f"Connected to {device[1]} on port {port}.")
return sock