/** * Bluetooth Mode Controller * Uses the new unified Bluetooth API at /api/bluetooth/ */ const BluetoothMode = (function() { 'use strict'; // State let isScanning = false; let eventSource = null; let devices = new Map(); let baselineSet = false; let baselineCount = 0; // DOM elements (cached) let startBtn, stopBtn, messageContainer, deviceContainer; let adapterSelect, scanModeSelect, transportSelect, durationInput, minRssiInput; let baselineStatusEl, capabilityStatusEl; // Stats tracking let deviceStats = { strong: 0, medium: 0, weak: 0, trackers: [] }; // Zone counts for proximity display let zoneCounts = { veryClose: 0, close: 0, nearby: 0, far: 0 }; // New visualization components let radarInitialized = false; let radarPaused = false; // Device list filter let currentDeviceFilter = 'all'; /** * Initialize the Bluetooth mode */ function init() { console.log('[BT] Initializing BluetoothMode'); // Cache DOM elements startBtn = document.getElementById('startBtBtn'); stopBtn = document.getElementById('stopBtBtn'); messageContainer = document.getElementById('btMessageContainer'); deviceContainer = document.getElementById('btDeviceListContent'); adapterSelect = document.getElementById('btAdapterSelect'); scanModeSelect = document.getElementById('btScanMode'); transportSelect = document.getElementById('btTransport'); durationInput = document.getElementById('btScanDuration'); minRssiInput = document.getElementById('btMinRssi'); baselineStatusEl = document.getElementById('btBaselineStatus'); capabilityStatusEl = document.getElementById('btCapabilityStatus'); // Check capabilities on load checkCapabilities(); // Check scan status (in case page was reloaded during scan) checkScanStatus(); // Initialize proximity visualization initProximityRadar(); // Initialize legacy heatmap (zone counts) initHeatmap(); // Initialize device list filters initDeviceFilters(); // Set initial panel states updateVisualizationPanels(); } /** * Initialize device list filter buttons */ function initDeviceFilters() { const filterContainer = document.getElementById('btDeviceFilters'); if (!filterContainer) return; filterContainer.addEventListener('click', (e) => { const btn = e.target.closest('.bt-filter-btn'); if (!btn) return; const filter = btn.dataset.filter; if (!filter) return; // Update active state filterContainer.querySelectorAll('.bt-filter-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); // Apply filter currentDeviceFilter = filter; applyDeviceFilter(); }); } /** * Apply current filter to device list */ function applyDeviceFilter() { if (!deviceContainer) return; const cards = deviceContainer.querySelectorAll('[data-bt-device-id]'); cards.forEach(card => { const isNew = card.dataset.isNew === 'true'; const hasName = card.dataset.hasName === 'true'; const rssi = parseInt(card.dataset.rssi) || -100; let visible = true; switch (currentDeviceFilter) { case 'new': visible = isNew; break; case 'named': visible = hasName; break; case 'strong': visible = rssi >= -70; break; case 'all': default: visible = true; } card.style.display = visible ? '' : 'none'; }); // Update visible count updateFilteredCount(); } /** * Update the device count display based on visible devices */ function updateFilteredCount() { const countEl = document.getElementById('btDeviceListCount'); if (!countEl || !deviceContainer) return; if (currentDeviceFilter === 'all') { countEl.textContent = devices.size; } else { const visible = deviceContainer.querySelectorAll('[data-bt-device-id]:not([style*="display: none"])').length; countEl.textContent = visible + '/' + devices.size; } } /** * Initialize the new proximity radar component */ function initProximityRadar() { const radarContainer = document.getElementById('btProximityRadar'); if (!radarContainer) return; if (typeof ProximityRadar !== 'undefined') { ProximityRadar.init('btProximityRadar', { onDeviceClick: (deviceKey) => { // Find device by key and show modal const device = Array.from(devices.values()).find(d => d.device_key === deviceKey); if (device) { selectDevice(device.device_id); } } }); radarInitialized = true; // Setup radar controls setupRadarControls(); } } /** * Setup radar control button handlers */ function setupRadarControls() { // Filter buttons document.querySelectorAll('#btRadarControls button[data-filter]').forEach(btn => { btn.addEventListener('click', () => { const filter = btn.getAttribute('data-filter'); if (typeof ProximityRadar !== 'undefined') { ProximityRadar.setFilter(filter); // Update button states document.querySelectorAll('#btRadarControls button[data-filter]').forEach(b => { b.classList.remove('active'); }); if (ProximityRadar.getFilter() === filter) { btn.classList.add('active'); } } }); }); // Pause button const pauseBtn = document.getElementById('btRadarPauseBtn'); if (pauseBtn) { pauseBtn.addEventListener('click', () => { radarPaused = !radarPaused; if (typeof ProximityRadar !== 'undefined') { ProximityRadar.setPaused(radarPaused); } pauseBtn.textContent = radarPaused ? 'Resume' : 'Pause'; pauseBtn.classList.toggle('active', radarPaused); }); } } /** * Update the proximity radar with current devices */ function updateRadar() { if (!radarInitialized || typeof ProximityRadar === 'undefined') return; // Convert devices map to array for radar const deviceList = Array.from(devices.values()).map(d => ({ device_key: d.device_key || d.device_id, device_id: d.device_id, name: d.name, address: d.address, rssi_current: d.rssi_current, rssi_ema: d.rssi_ema, estimated_distance_m: d.estimated_distance_m, proximity_band: d.proximity_band || 'unknown', distance_confidence: d.distance_confidence || 0.5, is_new: d.is_new || !d.in_baseline, is_randomized_mac: d.is_randomized_mac, in_baseline: d.in_baseline, heuristic_flags: d.heuristic_flags || [], age_seconds: d.age_seconds || 0, })); ProximityRadar.updateDevices(deviceList); // Update zone counts from radar const counts = ProximityRadar.getZoneCounts(); updateProximityZoneCounts(counts); } /** * Update proximity zone counts display (new system) */ function updateProximityZoneCounts(counts) { const immediateEl = document.getElementById('btZoneImmediate'); const nearEl = document.getElementById('btZoneNear'); const farEl = document.getElementById('btZoneFar'); if (immediateEl) immediateEl.textContent = counts.immediate || 0; if (nearEl) nearEl.textContent = counts.near || 0; if (farEl) farEl.textContent = counts.far || 0; } /** * Initialize proximity zones display */ function initHeatmap() { updateProximityZones(); } /** * Update proximity zone counts (simple HTML, no canvas) */ function updateProximityZones() { zoneCounts = { veryClose: 0, close: 0, nearby: 0, far: 0 }; devices.forEach(device => { const rssi = device.rssi_current; if (rssi == null) return; if (rssi >= -40) zoneCounts.veryClose++; else if (rssi >= -55) zoneCounts.close++; else if (rssi >= -70) zoneCounts.nearby++; else zoneCounts.far++; }); // Update DOM elements const veryCloseEl = document.getElementById('btZoneVeryClose'); const closeEl = document.getElementById('btZoneClose'); const nearbyEl = document.getElementById('btZoneNearby'); const farEl = document.getElementById('btZoneFar'); if (veryCloseEl) veryCloseEl.textContent = zoneCounts.veryClose; if (closeEl) closeEl.textContent = zoneCounts.close; if (nearbyEl) nearbyEl.textContent = zoneCounts.nearby; if (farEl) farEl.textContent = zoneCounts.far; } // Currently selected device let selectedDeviceId = null; /** * Show device detail panel */ function showDeviceDetail(deviceId) { const device = devices.get(deviceId); if (!device) return; selectedDeviceId = deviceId; const placeholder = document.getElementById('btDetailPlaceholder'); const content = document.getElementById('btDetailContent'); if (!placeholder || !content) return; const rssi = device.rssi_current; const rssiColor = getRssiColor(rssi); const flags = device.heuristic_flags || []; const protocol = device.protocol || 'ble'; // Update panel elements document.getElementById('btDetailName').textContent = device.name || formatDeviceId(device.address); document.getElementById('btDetailAddress').textContent = device.address; // RSSI const rssiEl = document.getElementById('btDetailRssi'); rssiEl.textContent = rssi != null ? rssi : '--'; rssiEl.style.color = rssiColor; // Badges const badgesEl = document.getElementById('btDetailBadges'); let badgesHtml = `${protocol.toUpperCase()}`; badgesHtml += `${device.in_baseline ? '✓ KNOWN' : '● NEW'}`; flags.forEach(f => { badgesHtml += `${f.replace(/_/g, ' ').toUpperCase()}`; }); badgesEl.innerHTML = badgesHtml; // Stats grid document.getElementById('btDetailMfr').textContent = device.manufacturer_name || '--'; document.getElementById('btDetailMfrId').textContent = device.manufacturer_id != null ? '0x' + device.manufacturer_id.toString(16).toUpperCase().padStart(4, '0') : '--'; document.getElementById('btDetailAddrType').textContent = device.address_type || '--'; document.getElementById('btDetailSeen').textContent = (device.seen_count || 0) + '×'; document.getElementById('btDetailRange').textContent = device.range_band || '--'; // Min/Max combined const minMax = []; if (device.rssi_min != null) minMax.push(device.rssi_min); if (device.rssi_max != null) minMax.push(device.rssi_max); document.getElementById('btDetailRssiRange').textContent = minMax.length === 2 ? minMax[0] + '/' + minMax[1] : '--'; document.getElementById('btDetailFirstSeen').textContent = device.first_seen ? new Date(device.first_seen).toLocaleTimeString() : '--'; document.getElementById('btDetailLastSeen').textContent = device.last_seen ? new Date(device.last_seen).toLocaleTimeString() : '--'; // Services const servicesContainer = document.getElementById('btDetailServices'); const servicesList = document.getElementById('btDetailServicesList'); if (device.service_uuids && device.service_uuids.length > 0) { servicesContainer.style.display = 'block'; servicesList.textContent = device.service_uuids.join(', '); } else { servicesContainer.style.display = 'none'; } // Show content, hide placeholder placeholder.style.display = 'none'; content.style.display = 'block'; // Highlight selected device in list highlightSelectedDevice(deviceId); } /** * Clear device selection */ function clearSelection() { selectedDeviceId = null; const placeholder = document.getElementById('btDetailPlaceholder'); const content = document.getElementById('btDetailContent'); if (placeholder) placeholder.style.display = 'flex'; if (content) content.style.display = 'none'; // Remove highlight from device list if (deviceContainer) { deviceContainer.querySelectorAll('.bt-device-row.selected').forEach(el => { el.classList.remove('selected'); }); } } /** * Highlight selected device in the list */ function highlightSelectedDevice(deviceId) { if (!deviceContainer) return; // Remove existing highlights deviceContainer.querySelectorAll('.bt-device-row.selected').forEach(el => { el.classList.remove('selected'); }); // Add highlight to selected device const escapedId = CSS.escape(deviceId); const card = deviceContainer.querySelector(`[data-bt-device-id="${escapedId}"]`); if (card) { card.classList.add('selected'); } } /** * Copy selected device address to clipboard */ function copyAddress() { if (!selectedDeviceId) return; const device = devices.get(selectedDeviceId); if (!device) return; navigator.clipboard.writeText(device.address).then(() => { const btn = document.querySelector('.bt-detail-btn'); if (btn) { const originalText = btn.textContent; btn.textContent = 'Copied!'; btn.style.background = '#22c55e'; setTimeout(() => { btn.textContent = originalText; btn.style.background = ''; }, 1500); } }); } /** * Select a device - opens modal with details */ function selectDevice(deviceId) { showDeviceDetail(deviceId); } /** * Format device ID for display (when no name available) */ function formatDeviceId(address) { if (!address) return 'Unknown Device'; const parts = address.split(':'); if (parts.length === 6) { return parts[0] + ':' + parts[1] + ':...:' + parts[4] + ':' + parts[5]; } return address; } /** * Check system capabilities */ async function checkCapabilities() { try { const response = await fetch('/api/bluetooth/capabilities'); const data = await response.json(); if (!data.available) { showCapabilityWarning(['Bluetooth not available on this system']); return; } if (adapterSelect && data.adapters && data.adapters.length > 0) { adapterSelect.innerHTML = data.adapters.map(a => { const status = a.powered ? 'UP' : 'DOWN'; return ``; }).join(''); } else if (adapterSelect) { adapterSelect.innerHTML = ''; } if (data.issues && data.issues.length > 0) { showCapabilityWarning(data.issues); } else { hideCapabilityWarning(); } if (scanModeSelect && data.preferred_backend) { const option = scanModeSelect.querySelector(`option[value="${data.preferred_backend}"]`); if (option) option.selected = true; } } catch (err) { console.error('Failed to check capabilities:', err); showCapabilityWarning(['Failed to check Bluetooth capabilities']); } } function showCapabilityWarning(issues) { if (!capabilityStatusEl) return; capabilityStatusEl.style.display = 'block'; capabilityStatusEl.innerHTML = `