import asyncio
from bleak import BleakScanner

async def main():
    print("Searching for nearby BLE devices for 10 seconds...")
    devices_dict = await BleakScanner.discover(timeout=10.0, return_adv=True)
    
    print("\n--- Detected BLE Devices ---")
    print(f"{'MAC/Bluetooth Address':<24} | {'Device Name':<30} | {'RSSI (dBm)'}")
    print("-" * 70)
    
    # devices_dict is { address: (device, advertisement_data) }
    # So item[1] is (device, advertisement_data), and item[1][1] is advertisement_data
    sorted_devices = sorted(devices_dict.items(), key=lambda item: item[1][1].rssi, reverse=True)
    
    for address, (device, adv) in sorted_devices:
        name = device.name if device.name else "Unknown Device"
        print(f"{device.address:<24} | {name:<30} | {adv.rssi}")

if __name__ == "__main__":
    asyncio.run(main())
