
|
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
#!/usr/bin/env python3 """ Radar BLE en terminal (modo reloj) ---------------------------------- Visualiza dispositivos Bluetooth Low Energy (BLE) alrededor del usuario como si fuera un radar: tú estás en el centro y cada dispositivo se representa como un punto numerado con su distancia aproximada. Requiere: - Python 3 - bleak (pip install bleak) - Terminal con soporte curses """ import asyncio import math import time import curses from bleak import BleakScanner # --------------------------------------------------------------------- # Parámetros de medición # --------------------------------------------------------------------- # RSSI de referencia (dBm) a 1 metro (aproximado) RSSI_REFERENCE = -59 # Constante de propagación (2 ≈ interior, 3–4 ≈ entornos con más obstáculos) PROPAGATION_CONSTANT = 2 # Distancia máxima (en metros) que mapeamos al borde del radar MAX_DISTANCE_METERS = 10.0 # Tiempo de escaneo BLE por ciclo (segundos) SCAN_TIME_SECONDS = 3.0 # --------------------------------------------------------------------- # Cálculos de distancia y escaneo BLE # --------------------------------------------------------------------- def calculate_distance(rssi: int, reference: int = RSSI_REFERENCE, n: int = PROPAGATION_CONSTANT) -> float: """ Estima la distancia (en metros) a partir del RSSI usando el modelo de pérdida de trayectoria en espacio libre (versión simplificada). """ return 10 ** ((reference - rssi) / (10 * n)) async def scan_for_devices_with_rssi(scan_time: float = SCAN_TIME_SECONDS): """ Escanea durante scan_time segundos y devuelve una lista de tuplas: [(device, rssi), ...] usando un callback de detección, que en macOS suele ser más fiable. """ seen = {} # address -> (device, rssi) def detection_callback(device, advertisement_data): rssi = advertisement_data.rssi if rssi is None: return # Nos quedamos con el último RSSI visto para cada dirección seen[device.address] = (device, rssi) scanner = BleakScanner(detection_callback) await scanner.start() await asyncio.sleep(scan_time) await scanner.stop() # Devolvemos una lista ordenada por intensidad (más cerca primero) return sorted(seen.values(), key=lambda dr: dr[1], reverse=True) # --------------------------------------------------------------------- # Dibujo del radar y del panel de información # --------------------------------------------------------------------- def draw_panels(stdscr, info_width: int, height: int, width: int): """ Dibuja los marcos de los dos paneles: información (izquierda) y radar (derecha), además de la banda de título superior y la barra de estado inferior. """ # Título superior centrado title = " Radar BLE en terminal (modo reloj) " stdscr.attron(curses.color_pair(1) | curses.A_BOLD) stdscr.addstr(0, max(0, (width - len(title)) // 2), title) stdscr.attroff(curses.color_pair(1) | curses.A_BOLD) # Límites de paneles info_left = 0 info_right = info_width panel_top = 1 panel_bottom = height - 2 radar_left = info_right + 1 radar_right = width - 1 # Marco panel información for x in range(info_left, info_right + 1): stdscr.addch(panel_top, x, curses.ACS_HLINE, curses.color_pair(2)) stdscr.addch(panel_bottom, x, curses.ACS_HLINE, curses.color_pair(2)) for y in range(panel_top, panel_bottom + 1): stdscr.addch(y, info_left, curses.ACS_VLINE, curses.color_pair(2)) stdscr.addch(y, info_right, curses.ACS_VLINE, curses.color_pair(2)) stdscr.addch(panel_top, info_left, curses.ACS_ULCORNER, curses.color_pair(2)) stdscr.addch(panel_top, info_right, curses.ACS_URCORNER, curses.color_pair(2)) stdscr.addch(panel_bottom, info_left, curses.ACS_LLCORNER, curses.color_pair(2)) stdscr.addch(panel_bottom, info_right, curses.ACS_LRCORNER, curses.color_pair(2)) # Marco panel radar for x in range(radar_left, radar_right + 1): stdscr.addch(panel_top, x, curses.ACS_HLINE, curses.color_pair(2)) stdscr.addch(panel_bottom, x, curses.ACS_HLINE, curses.color_pair(2)) for y in range(panel_top, panel_bottom + 1): stdscr.addch(y, radar_left, curses.ACS_VLINE, curses.color_pair(2)) stdscr.addch(y, radar_right, curses.ACS_VLINE, curses.color_pair(2)) stdscr.addch(panel_top, radar_left, curses.ACS_ULCORNER, curses.color_pair(2)) stdscr.addch(panel_top, radar_right, curses.ACS_URCORNER, curses.color_pair(2)) stdscr.addch(panel_bottom, radar_left, curses.ACS_LLCORNER, curses.color_pair(2)) stdscr.addch(panel_bottom, radar_right, curses.ACS_LRCORNER, curses.color_pair(2)) # Barra de estado inferior status = " Teclas: q = salir | Escaneo automático cada " status += f"{SCAN_TIME_SECONDS:.0f}s | Distancias aproximadas (modelo simple RSSI) " stdscr.attron(curses.color_pair(3)) stdscr.addnstr(height - 1, 0, status, width - 1) stdscr.attroff(curses.color_pair(3)) def draw_radar(stdscr, devices_with_rssi): """ Dibuja el radar y el panel de información. Cada elemento de devices_with_rssi es una tupla (device, rssi). """ stdscr.clear() height, width = stdscr.getmaxyx() # Por estética, 1/3 para info y 2/3 para radar info_width = max(32, width // 3) # Dibujar marcos y título draw_panels(stdscr, info_width, height, width) # Área útil dentro de los paneles panel_top = 1 panel_bottom = height - 2 radar_left = info_width + 1 radar_right = width - 1 radar_width = radar_right - radar_left - 1 radar_height = panel_bottom - panel_top - 1 if radar_width < 10 or radar_height < 10: stdscr.addstr(2, 2, "Ventana demasiado pequeña para el radar.", curses.color_pair(3)) stdscr.refresh() return # Centro del radar center_x = radar_left + radar_width // 2 center_y = panel_top + 1 + radar_height // 2 max_radius = min(radar_width, radar_height) // 2 - 1 # Ejes del radar (cruz) for x in range(center_x - max_radius, center_x + max_radius + 1): if radar_left + 1 <= x < radar_right: stdscr.addch(center_y, x, '-', curses.color_pair(2)) for y in range(center_y - max_radius, center_y + max_radius + 1): if panel_top + 1 <= y < panel_bottom: stdscr.addch(y, center_x, '|', curses.color_pair(2)) # Anillos de distancia (3 círculos aproximados) for ring in (max_radius // 3, 2 * max_radius // 3, max_radius): if ring <= 0: continue for angle_deg in range(0, 360, 10): angle = math.radians(angle_deg) y = int(center_y + ring * math.sin(angle)) x = int(center_x + ring * math.cos(angle)) if (panel_top + 1 <= y < panel_bottom and radar_left + 1 <= x < radar_right): stdscr.addch(y, x, '.', curses.color_pair(2)) # Centro (tú) stdscr.addch(center_y, center_x, 'O', curses.color_pair(1) | curses.A_BOLD) # Leyenda de distancia en el panel radar (arriba a la derecha) legend = f"0m ~{MAX_DISTANCE_METERS/3:.1f}m ~{2*MAX_DISTANCE_METERS/3:.1f}m ~{MAX_DISTANCE_METERS:.1f}m" stdscr.addnstr(panel_top + 1, radar_left + 2, legend, radar_right - radar_left - 3, curses.color_pair(3)) # Panel de información: encabezados info_y = panel_top + 1 stdscr.attron(curses.color_pair(3) | curses.A_BOLD) stdscr.addstr(info_y, 2, "ID Nombre RSSI Dist(m)") stdscr.attroff(curses.color_pair(3) | curses.A_BOLD) info_y += 1 if not devices_with_rssi: stdscr.addstr(info_y + 1, 2, "No se encontraron dispositivos BLE con RSSI.", curses.color_pair(3)) stdscr.refresh() return num_devices = len(devices_with_rssi) for idx, (device, rssi) in enumerate(devices_with_rssi): distance = calculate_distance(rssi) # Normalizar distancia al radio del radar normalized = min(distance / MAX_DISTANCE_METERS, 1.0) radius = max(1, int(normalized * max_radius)) # Ángulo tipo reloj angle = 2 * math.pi * idx / num_devices y = int(center_y + radius * math.sin(angle)) x = int(center_x + radius * math.cos(angle)) # Identificador (1–9, luego 0) label = str((idx + 1) % 10) # Color según distancia if distance <= 2: color = curses.color_pair(4) | curses.A_BOLD # cerca (verde) elif distance <= 5: color = curses.color_pair(2) | curses.A_BOLD # media (amarillo) else: color = curses.color_pair(5) | curses.A_BOLD # lejos (rojo) # Dibujo del dispositivo en el radar if (panel_top + 1 <= y < panel_bottom and radar_left + 1 <= x < radar_right): stdscr.addch(y, x, label, color) # Línea de información en el panel izquierdo if info_y < panel_bottom: name = device.name or "Desconocido" line = f"{label:<3} {name[:15]:15} {rssi:4d} {distance:6.2f}" stdscr.addnstr(info_y, 2, line, info_width - 3, curses.color_pair(3)) info_y += 1 stdscr.refresh() # --------------------------------------------------------------------- # Bucle principal curses # --------------------------------------------------------------------- def main(stdscr): curses.curs_set(0) # Ocultar cursor stdscr.nodelay(1) # getch() no bloqueante # Configuración de colores curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # Título, centro curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Marcos, ejes curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK) # Texto general curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK) # Dispositivos cercanos curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK) # Dispositivos lejanos while True: key = stdscr.getch() if key == ord('q'): break try: devices_with_rssi = asyncio.run( scan_for_devices_with_rssi(SCAN_TIME_SECONDS) ) except Exception as e: stdscr.clear() msg_err = f"Error escaneando BLE: {e}" stdscr.addnstr(2, 2, msg_err, curses.COLS - 4, curses.color_pair(3)) stdscr.addstr(4, 2, "Comprueba permisos de Bluetooth y que bleak está instalado.", curses.color_pair(3)) stdscr.refresh() time.sleep(2) continue draw_radar(stdscr, devices_with_rssi) time.sleep(0.3) # ligero respiro para no saturar la terminal if __name__ == "__main__": print("Iniciando Radar BLE en terminal... pulsa 'q' para salir.") time.sleep(0.5) curses.wrapper(main) |

