diff --git a/ap.py b/ap.py index 21d7856..1a355f6 100644 --- a/ap.py +++ b/ap.py @@ -40,10 +40,255 @@ if not os.path.exists(DB_FILE) and os.path.exists(OLD_DB_FILE): shutil.copy2(OLD_DB_FILE, DB_FILE) except Exception: pass -# Radio : 2,4 GHz canal 6 par défaut (le plus compatible en mode point d'accès). Modifiable via docker-compose. +# Exécution de commandes système +def command(*args, timeout=5): + try: return subprocess.check_output(args, text=True, stderr=subprocess.DEVNULL, timeout=timeout).strip() + except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError): return '' + +# Radio : 2,4 GHz ou 5 GHz. AP_BAND = os.environ.get('AP_BAND', 'bg') if os.environ.get('AP_BAND', 'bg') in ('bg', 'a') else 'bg' -try: AP_CHANNEL = int(os.environ.get('AP_CHANNEL', '6')) -except ValueError: AP_CHANNEL = 6 +AP_CHANNEL_CONFIGURED = os.environ.get('AP_CHANNEL', '').strip() + +_auto_channel_cache = { + 'channel': None, + 'band': None, + 'time': 0, + 'details': {} +} +_auto_channel_lock = threading.Lock() + +def is_auto_channel(): + """Vérifie si AP_CHANNEL n'est pas renseigné ou est configuré sur 'auto' / '0'.""" + raw = os.environ.get('AP_CHANNEL') + if raw is None: + return True + s = str(raw).strip().lower() + return s in ('', 'auto', '0', 'none', 'null') + +def scan_neighboring_wifi_networks(iface=None): + """ + Scanne les réseaux Wi-Fi voisins pour mesurer l'encombrement par canal. + Utilise nmcli dev wifi list (avec rescan), iw dev scan, ou iw dev scan dump. + Retourne une liste de dicts : [{'channel': int, 'freq': int, 'signal_dbm': float, 'ssid': str}] + """ + iface = iface or INTERFACE + networks = [] + seen_keys = set() + + # 1. Tentative via nmcli (géré par NetworkManager) + try: + nm_out = command('nmcli', '-t', '-f', 'CHAN,SIGNAL,FREQ,SSID', 'dev', 'wifi', 'list', '--rescan', 'yes') + if not nm_out: + nm_out = command('nmcli', '-t', '-f', 'CHAN,SIGNAL,FREQ,SSID', 'dev', 'wifi', 'list') + if nm_out: + for line in nm_out.splitlines(): + line = line.strip() + if not line or ':' not in line: + continue + parts = line.split(':') + if len(parts) >= 3: + try: + chan_str = parts[0].strip() + sig_str = parts[1].strip() + freq_str = parts[2].strip().replace('MHz', '').strip() + ssid_str = ':'.join(parts[3:]).strip() if len(parts) > 3 else '' + if not chan_str.isdigit(): + continue + chan = int(chan_str) + sig_pct = int(sig_str) if sig_str.isdigit() else 50 + sig_dbm = -100.0 + (sig_pct / 2.0) + freq = int(freq_str) if freq_str.isdigit() else (2407 + chan * 5 if chan <= 14 else 5000 + chan * 5) + key = (chan, freq, round(sig_dbm, 0), ssid_str) + if key not in seen_keys: + seen_keys.add(key) + networks.append({'channel': chan, 'freq': freq, 'signal_dbm': sig_dbm, 'ssid': ssid_str}) + except Exception: + pass + except Exception as e: + print(f"[ap-wifi] [Auto-Channel] Scan nmcli indisponible : {e}", flush=True) + + # 2. Si nmcli n'a rien retourné (ex: carte hors NM à cet instant), tenter iw + if not networks and iface: + try: + iw_out = command('iw', 'dev', iface, 'scan') + if not iw_out: + iw_out = command('iw', 'dev', iface, 'scan', 'dump') + if iw_out: + curr_net = {} + for line in iw_out.splitlines(): + line = line.strip() + if line.startswith('BSS '): + if curr_net.get('channel') is not None: + key = (curr_net.get('channel'), curr_net.get('freq', 0), round(curr_net.get('signal_dbm', -70), 0), curr_net.get('ssid', '')) + if key not in seen_keys: + seen_keys.add(key) + networks.append(dict(curr_net)) + curr_net = {'channel': None, 'freq': 0, 'signal_dbm': -70.0, 'ssid': ''} + elif line.startswith('freq:'): + parts = line.split() + if len(parts) >= 2 and parts[1].isdigit(): + f = int(parts[1]) + curr_net['freq'] = f + if curr_net.get('channel') is None: + if 2412 <= f <= 2484: + curr_net['channel'] = 14 if f == 2484 else (f - 2407) // 5 + elif 5000 <= f <= 5900: + curr_net['channel'] = (f - 5000) // 5 + elif line.startswith('signal:'): + m_sig = re.search(r'([-0-9\.]+)\s*dBm', line) + if m_sig: + curr_net['signal_dbm'] = float(m_sig.group(1)) + elif 'primary channel:' in line or 'DS Parameter set: channel' in line: + m_ch = re.search(r'channel\s*(\d+)', line) + if m_ch: + curr_net['channel'] = int(m_ch.group(1)) + elif line.startswith('SSID:'): + curr_net['ssid'] = line.replace('SSID:', '').strip() + if curr_net.get('channel') is not None: + key = (curr_net.get('channel'), curr_net.get('freq', 0), round(curr_net.get('signal_dbm', -70), 0), curr_net.get('ssid', '')) + if key not in seen_keys: + seen_keys.add(key) + networks.append(dict(curr_net)) + except Exception as e: + print(f"[ap-wifi] [Auto-Channel] Scan iw indisponible : {e}", flush=True) + + return networks + +def calculate_best_channel(networks, band='bg'): + """ + Analyse les réseaux scannés et calcule le canal optimal (le moins encombré et le plus rapide). + Pour 2.4 GHz ('bg') : + - Évalue les canaux non recouvrants standard : 1, 6, 11 (et 13 pour l'Europe/France). + - Calcule l'encombrement en tenant compte du débordement spectral adjacent (|c - c_voisin| <= 4). + - Privilégie le canal ayant le score de collision le plus bas pour garantir le meilleur débit Wi-Fi. + Pour 5 GHz ('a') : + - Évalue les canaux U-NII-1 (36, 40, 44, 48) sans radar DFS, permettant des largeurs 40/80 MHz immédiates. + """ + band = (band or 'bg').lower().strip() + is_5g = (band == 'a') + + if is_5g: + candidates = [36, 40, 44, 48] + relevant_nets = [n for n in networks if n.get('freq', 0) > 4000 or n.get('channel', 0) >= 36] + else: + candidates = [1, 6, 11, 13] + relevant_nets = [n for n in networks if n.get('freq', 0) < 4000 and n.get('channel', 0) <= 14] + + scores = {} + net_counts = {} + + for cand in candidates: + score = 0.0 + count = 0 + for net in relevant_nets: + c_net = net.get('channel') + if c_net is None: + continue + sig_dbm = net.get('signal_dbm', -75.0) + + if sig_dbm >= -55: + weight = 100.0 + elif sig_dbm >= -67: + weight = 50.0 + elif sig_dbm >= -75: + weight = 25.0 + elif sig_dbm >= -85: + weight = 10.0 + else: + weight = 3.0 + + if is_5g: + if c_net == cand: + score += weight * 1.5 + count += 1 + elif abs(c_net - cand) <= 12: + score += weight * 0.3 + count += 1 + else: + diff = abs(c_net - cand) + if diff == 0: + score += weight * 1.5 + count += 1 + elif diff == 1: + score += weight * 0.85 + count += 1 + elif diff == 2: + score += weight * 0.60 + count += 1 + elif diff == 3: + score += weight * 0.35 + count += 1 + elif diff == 4: + score += weight * 0.15 + count += 1 + + scores[cand] = score + net_counts[cand] = count + + tie_breaker_order = [36, 44, 40, 48] if is_5g else [6, 1, 11, 13] + + def sort_key(ch): + pref_idx = tie_breaker_order.index(ch) if ch in tie_breaker_order else 99 + return (scores.get(ch, 0.0), pref_idx) + + best_channel = min(candidates, key=sort_key) + return best_channel, scores, net_counts + +def detect_best_wifi_channel(band=None, iface=None, force_rescan=False): + """ + Détecte automatiquement le meilleur canal Wi-Fi (le moins encombré et le plus rapide). + Met en cache le résultat pendant 30 minutes sauf si force_rescan=True. + """ + band = (band or AP_BAND or 'bg').lower().strip() + iface = iface or INTERFACE + now = time.time() + + with _auto_channel_lock: + if not force_rescan and _auto_channel_cache['channel'] is not None and (now - _auto_channel_cache['time'] < 1800) and (_auto_channel_cache['band'] == band): + return _auto_channel_cache['channel'] + + print(f"[ap-wifi] [Auto-Channel] Analyse de l'environnement radio Wi-Fi sur {iface} (bande {band})...", flush=True) + networks = scan_neighboring_wifi_networks(iface=iface) + best_chan, scores, counts = calculate_best_channel(networks, band=band) + + scores_repr = ', '.join([f"Ch.{ch}: score={scores.get(ch, 0):.0f} ({counts.get(ch, 0)} AP)" for ch in sorted(scores.keys())]) + print(f"[ap-wifi] [Auto-Channel] {len(networks)} réseau(x) détecté(s). Encombrement : [{scores_repr}] -> Canal {best_chan} sélectionné (le plus rapide & disponible)", flush=True) + + with _auto_channel_lock: + _auto_channel_cache['channel'] = best_chan + _auto_channel_cache['band'] = band + _auto_channel_cache['time'] = now + _auto_channel_cache['details'] = { + 'best_channel': best_chan, + 'band': band, + 'scores': scores, + 'counts': counts, + 'total_networks': len(networks), + 'scanned_at': time.strftime('%Y-%m-%d %H:%M:%S') + } + + return best_chan + +def get_effective_ap_channel(band=None, force_rescan=False): + """ + Retourne le canal effectif à utiliser pour le point d'accès : + - Canal fixe si AP_CHANNEL est renseigné dans docker-compose (ex. '6', '11', '36') + - Canal automatique scanné (le moins utilisé et plus rapide) si AP_CHANNEL n'est pas renseigné ou est 'auto' + """ + if is_auto_channel(): + return detect_best_wifi_channel(band=band or AP_BAND, force_rescan=force_rescan) + try: + val = int(os.environ.get('AP_CHANNEL', '6').strip()) + return val if val > 0 else 6 + except (TypeError, ValueError): + return 6 + +# Initialisation du canal par défaut +if not is_auto_channel(): + try: AP_CHANNEL = int(AP_CHANNEL_CONFIGURED) + except ValueError: AP_CHANNEL = 6 +else: + AP_CHANNEL = get_effective_ap_channel(AP_BAND) APP_VERSION = 'V5.5' SERVER_BOOT_TIME = time.time() @@ -1476,14 +1721,15 @@ def apply_radio_defaults(): if is_bridge_mode(): return name = connection_name() if not name: return + eff_channel = get_effective_ap_channel(AP_BAND) band = command('nmcli','-t','-g','802-11-wireless.band','connection','show',name) chan = command('nmcli','-t','-g','802-11-wireless.channel','connection','show',name) key = command('nmcli','-t','-g','802-11-wireless-security.key-mgmt','connection','show',name) - if band == AP_BAND and chan == str(AP_CHANNEL): return - args = ['nmcli','connection','modify',name,'802-11-wireless.band',AP_BAND,'802-11-wireless.channel',str(AP_CHANNEL)] + if band == AP_BAND and chan == str(eff_channel): return + args = ['nmcli','connection','modify',name,'802-11-wireless.band',AP_BAND,'802-11-wireless.channel',str(eff_channel)] if key in ('wpa-psk','sae'): args += ['802-11-wireless-security.pairwise','ccmp','802-11-wireless-security.group','ccmp'] r = subprocess.run(args, text=True, capture_output=True) - print(f"[ap-api] Radio {name} : bande={AP_BAND} canal={AP_CHANNEL} -> {'OK' if not r.returncode else r.stderr.strip()}", flush=True) + print(f"[ap-api] Radio {name} : bande={AP_BAND} canal={eff_channel}{' (auto)' if is_auto_channel() else ''} -> {'OK' if not r.returncode else r.stderr.strip()}", flush=True) if not r.returncode and command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE).startswith('100'): subprocess.run(['nmcli','connection','up',name], text=True, capture_output=True) @@ -3082,7 +3328,7 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No band = (AP_BAND or 'bg').strip().lower() hw_mode = 'a' if band == 'a' else 'g' - channel = str(AP_CHANNEL or '6').strip() + channel = str(get_effective_ap_channel(band)).strip() sec_norm = (sec or 'wpa2').lower() def _build_conf(enable_ht=True): @@ -3745,7 +3991,8 @@ def status(force_refresh=False): except OSError: pass b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', '')) - res = {'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME,'update':check_gitea_update(force_refresh=False)} + eff_chan = get_effective_ap_channel(AP_BAND) + res = {'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME,'channel':eff_chan,'channel_auto':is_auto_channel(),'band':AP_BAND,'update':check_gitea_update(force_refresh=False)} with _status_cache_lock: _status_cache['time'] = now _status_cache['data'] = res @@ -4685,7 +4932,9 @@ def get_wifi_channel_freq(interface): ch = (f - 2407) // 5 if f < 2500 else (f - 5000) // 5 return {'channel': ch, 'freq_mhz': f} except Exception: pass - return {'channel': 6, 'freq_mhz': 2437} + eff_ch = get_effective_ap_channel(AP_BAND) + eff_fr = 5000 + eff_ch * 5 if AP_BAND == 'a' else (2484 if eff_ch == 14 else 2407 + eff_ch * 5) + return {'channel': eff_ch, 'freq_mhz': eff_fr} def get_dns_servers(): env_dns = os.environ.get('AP_DNS', '').strip() @@ -4804,7 +5053,8 @@ def compute_topology_internal(active_items=None, active_status=None): 'cidr': ap_net.get('cidr') or '24', 'mode': 'NAT (Routeur Wi-Fi)' if st.get('mode') == 'nat' else 'Pont réseau (Bridge)', 'mode_key': 'nat' if st.get('mode') == 'nat' else 'bridge', - 'channel': wifi_radio.get('channel') or 6, + 'channel': wifi_radio.get('channel') or get_effective_ap_channel(AP_BAND), + 'channel_auto': is_auto_channel(), 'frequency_mhz': wifi_radio.get('freq_mhz') or 2437, 'band': '5 GHz' if (wifi_radio.get('freq_mhz') or 0) > 4000 else '2.4 GHz', 'uptime_seconds': st.get('uptime_seconds', 0), @@ -5310,7 +5560,7 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal 'ipv4.method', 'shared', 'ipv6.method', 'ignore', '802-11-wireless.band', AP_BAND, - '802-11-wireless.channel', str(AP_CHANNEL), + '802-11-wireless.channel', str(get_effective_ap_channel(AP_BAND, force_rescan=is_auto_channel())), 'connection.autoconnect', 'yes' if autoconnect else 'no' ] if proto: modify_args += ['802-11-wireless-security.proto', proto] @@ -10458,6 +10708,21 @@ class Handler(BaseHTTPRequestHandler): elif path_only == '/api/logs': self.send_json(logs()) elif path_only == '/api/stats': self.send_json(stats()) elif path_only == '/api/network/topology': self.send_json(network_topology()) + elif path_only == '/api/wifi/channel': + parsed = urllib.parse.urlparse(self.path) + q = urllib.parse.parse_qs(parsed.query) + force = 'force' in q or 'rescan' in q + eff_chan = get_effective_ap_channel(AP_BAND, force_rescan=force) + with _auto_channel_lock: + details = dict(_auto_channel_cache.get('details') or {}) + self.send_json({ + 'ok': True, + 'channel': eff_chan, + 'is_auto': is_auto_channel(), + 'band': AP_BAND, + 'configured_channel': os.environ.get('AP_CHANNEL', ''), + 'details': details + }) elif path_only == '/api/vpn/profiles': self.send_json({'profiles': list_vpn_profiles()}) elif path_only == '/api/vpn/clients': diff --git a/docker-compose.yml b/docker-compose.yml index d4efdc5..fe33d06 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,7 +17,10 @@ services: # Radio du point d'accès. FR = France. Bande "bg" = 2,4 GHz (canal 1 à 13), "a" = 5 GHz. AP_COUNTRY: "FR" AP_BAND: "bg" - AP_CHANNEL: "6" + # Canal Wi-Fi : laisser vide ("") ou omettre pour détecter automatiquement le canal + # le moins encombré et le plus rapide (analyse intelligente du spectre radio). + # Ou spécifier un numéro fixe (ex: "6", "11", "36"). + AP_CHANNEL: "" # En mode Pont (sélectionné dans l'interface web) : nom de l'interface Ethernet reliée à la box (laisser vide = détection auto) AP_BRIDGE_ETH: "" # En mode Pont : nom de l'interface pont (par défaut "br0") diff --git a/index.html b/index.html index c08583e..c4a38c6 100644 --- a/index.html +++ b/index.html @@ -7806,7 +7806,8 @@ } const apBadge = $('topoStatusAp'); if (apBadge && data.ap) { - apBadge.textContent = `AP : ${data.ap.interface} (${data.ap.band} • Ch.${data.ap.channel})`; + const autoTag = data.ap.channel_auto ? ' • ⚡ Auto' : ''; + apBadge.textContent = `AP : ${data.ap.interface} (${data.ap.band} • Ch.${data.ap.channel}${autoTag})`; } const countBadge = $('topoClientsCount'); if (countBadge) { @@ -7898,7 +7899,8 @@ ${vpnBadgeHtml} } const apIpEl = $('topoApIp'); const apIpDisp = (data.ap.ip === 'IP Pont LAN' || String(data.ap.ip).includes('Pont')) ? t('topo_ip_bridge_lan', 'IP Pont LAN') : data.ap.ip; - if (apIpEl) apIpEl.textContent = `${apIpDisp}/${data.ap.cidr || '24'} • ${t('topo_channel', 'Canal')} ${data.ap.channel} (${data.ap.band})`; + const autoTag = data.ap.channel_auto ? ' • ⚡ Auto' : ''; + if (apIpEl) apIpEl.textContent = `${apIpDisp}/${data.ap.cidr || '24'} • ${t('topo_channel', 'Canal')} ${data.ap.channel} (${data.ap.band}${autoTag})`; const apMetaEl = $('topoApMeta'); let apModeText = data.ap.mode || ''; if (data.ap.mode_key === 'bridge' || apModeText.includes('Bridge') || apModeText.includes('Pont')) { @@ -8732,7 +8734,8 @@ ${vpnBadgeTopo} ctx.fillStyle = mutedColor; ctx.font = '13px ' + fontMono; - const apIpStr = (data.ap && data.ap.ip) ? `${data.ap.ip}/${data.ap.cidr || '24'} • Canal ${data.ap.channel} (${data.ap.band})` : '10.42.0.1/24 • Canal 6'; + const autoTagCanvas = (data.ap && data.ap.channel_auto) ? ' • ⚡ Auto' : ''; + const apIpStr = (data.ap && data.ap.ip) ? `${data.ap.ip}/${data.ap.cidr || '24'} • Canal ${data.ap.channel} (${data.ap.band}${autoTagCanvas})` : '10.42.0.1/24 • Canal 6'; ctx.fillText(apIpStr, apX + 60, apY + 50); ctx.font = '11px ' + fontFamily; const apMetaStr = `${(data.ap && data.ap.security) || 'WPA2'} • ${(data.ap && data.ap.mode) || 'NAT'} • ↓ ${data.total_download_str || '0 o/s'} • ↑ ${data.total_upload_str || '0 o/s'}`; @@ -8935,7 +8938,7 @@ ${vpnBadgeTopo}
${t('topo_modal_ssid', 'NOM DU SSID')}
${ap.ssid || 'AP Wi-Fi'}
${t('topo_modal_local_ip', 'IP LOCALE AP')}
${apIpVal}/${ap.cidr || '24'}
${t('topo_modal_wifi_iface', 'INTERFACE SANS FIL')}
${ap.interface || 'wlan0'}
-
${t('topo_modal_radio_channel', 'RADIO & CANAL')}
${t('topo_channel', 'Canal')} ${ap.channel || 6} (${ap.band || '2.4 GHz'})
+
${t('topo_modal_radio_channel', 'RADIO & CANAL')}
${t('topo_channel', 'Canal')} ${ap.channel || 6} (${ap.band || '2.4 GHz'})${ap.channel_auto ? ' ⚡ Auto' : ''}
${t('topo_modal_net_mode', 'MODE RÉSEAU')}
${apModeVal}
${t('topo_modal_security', 'SÉCURITÉ')}
${ap.security || 'WPA2'}
${t('topo_modal_connected_devs', 'APPAREILS CONNECTÉS')}
${data.total_clients_count || 0} / ${ap.max_clients || 30}
diff --git a/version.json b/version.json index 8e83a3e..37684c5 100644 --- a/version.json +++ b/version.json @@ -1,5 +1,5 @@ { "version": "V5.5", - "commit": "5bfc833675337dc692f3b4d1b51bcccdc1445872", - "build_date": "2026-11-21T23:43:40Z" + "commit": "ab03ed72111bda56a5227294bc4ba724cf628a14", + "build_date": "2026-11-22T00:11:41Z" } \ No newline at end of file