1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import asyncio from bleak import BleakScanner, BleakClient from tabulate import tabulate # RSSI de referencia y constante de propagación RSSI_REFERENCE = -59 PROPAGATION_CONSTANT = 2 def calculate_distance(rssi, reference=RSSI_REFERENCE, n=PROPAGATION_CONSTANT): return 10 ** ((reference - rssi) / (10 * n)) async def scan_for_devices(): print("Escaneando dispositivos BLE...") devices = await BleakScanner.discover() return devices async def get_device_details(device): try: async with BleakClient(device) as client: print(f"Conectado a {device.address}") # Mostrar servicios y características for service in client.services: print(f"\nServicio: {service.uuid} - {service.description}") for characteristic in service.characteristics: try: value = await client.read_gatt_char(characteristic.uuid) print(f" Característica: {characteristic.uuid} - {characteristic.description}") print(f" Valor: {value}") print(f" Propiedades: {characteristic.properties}") print(f" Handle: {characteristic.handle}") except Exception as e: print(f" Error al leer la característica {characteristic.uuid}: {e}") except asyncio.exceptions.TimeoutError: print(f"Error: Tiempo de conexión excedido con {device.address}") except Exception as e: print(f"Error: No se pudo conectar a {device.address}: {e}") async def main(): # Escanear dispositivos devices = await scan_for_devices() if not devices: print("No se encontraron dispositivos BLE.") return # Crear una lista de dispositivos con sus distancias calculadas device_distances = [] for device in devices: rssi = device.rssi local_name = device.name if device.name else "Unknown" distance = calculate_distance(rssi) device_distances.append((local_name, device.address, rssi, distance)) # Ordenar los dispositivos por distancia device_distances.sort(key=lambda x: x[3]) # Crear una tabla con los dispositivos y distancias headers = ["Nombre", "Dirección", "RSSI (dBm)", "Distancia Estimada (metros)"] table = tabulate(device_distances, headers=headers, tablefmt="grid") print("\nDispositivos encontrados:") print(table) # Opcional: Obtener detalles del dispositivo más cercano if device_distances: closest_device_address = device_distances[0][1] closest_device = next(dev for dev in devices if dev.address == closest_device_address) await get_device_details(closest_device) # Ejecutar el escaneo y obtener detalles asyncio.run(main()) |