Bluetooth Device Discovery with Optional Filtering

  • Share this:

Code introduction


This function is used to search for nearby Bluetooth devices and can optionally search for devices with a specific name or address.


Technology Stack : PyBluez

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
from pybluez import bluetooth

def discover_devices(name=None, address=None):
    """
    Discover nearby Bluetooth devices. If a specific device name or address is provided,
    it will try to find that device only.
    """
    # Scan for devices
    nearby_devices = bluetooth.discover_devices(duration=10, lookup_names=True)
    
    # Filter devices if a specific name or address is given
    if name:
        nearby_devices = [device for device in nearby_devices if device[1] == name]
    if address:
        nearby_devices = [device for device in nearby_devices if device[0] == address]
    
    return nearby_devices                
              
Tags: