diff --git a/ap.py b/ap.py index a301967..ca24a2a 100644 --- a/ap.py +++ b/ap.py @@ -2986,17 +2986,25 @@ def stop_hostapd(iface=None): subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True) def ensure_nm_manages_wifi(iface=None): - """Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT).""" + """Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT) et attend qu'elle soit prête.""" iface = iface or INTERFACE if not iface: return + was_unmanaged = (command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) or '').startswith('10') stop_hostapd(iface) + if was_unmanaged: + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) + subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True) + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True) + time.sleep(0.2) subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True) - for _ in range(25): + for _ in range(35): st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) - if st and not st.startswith('10'): # 10 = unmanaged + if st and not st.startswith('10') and not st.startswith('20'): # 10=unmanaged, 20=unavailable break time.sleep(0.2) + if was_unmanaged: + time.sleep(0.3) def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=None): """Démarre le point d'accès Wi-Fi en mode pont directement via hostapd (bridge=br0) sans que NetworkManager ne touche au pont hôte.""" @@ -3422,13 +3430,59 @@ def clients(): ipmac[nmac] = nip output = []; dump = command('iw','dev',INTERFACE,'station','dump'); blocked_macs = blocked_set() + # Sur Raspberry Pi (brcmfmac), hostapd_cli all_sta peut fournir signal= même quand iw station dump omet signal: + hostapd_signals = {} + if is_hostapd_running(): + h_out = command('hostapd_cli', '-p', '/run/hostapd', '-i', INTERFACE, 'all_sta') + if h_out: + cur_mac = None + for hline in h_out.splitlines(): + hline = hline.strip() + if re.fullmatch(r'[0-9a-fA-F:]{17}', hline): + cur_mac = hline.upper() + elif cur_mac and hline.startswith('signal='): + try: + sv = int(hline.split('=', 1)[1].strip()) + if -120 <= sv < 0: + hostapd_signals[cur_mac] = sv + except ValueError: + pass + + def _extract_signal_dbm(blk, sta_mac): + # 1. « signal: -XX dBm » puis « signal avg: -XX dBm » (utilisé par brcmfmac sur Raspberry Pi) + for pat in (r'^\s*signal:\s*(-?\d+)', r'^\s*signal\s+avg:\s*(-?\d+)'): + mm = re.search(pat, blk, re.I | re.M) + if mm: + try: + val = int(mm.group(1)) + if -120 <= val < 0: + return val + except ValueError: + pass + # 2. Repli hostapd_cli all_sta (mode Pont) + if sta_mac in hostapd_signals: + return hostapd_signals[sta_mac] + # 3. Repli « iw dev station get » (force une lecture fraîche du firmware brcmfmac) + g_out = command('iw', 'dev', INTERFACE, 'station', 'get', sta_mac.lower()) + if g_out: + for pat in (r'^\s*signal:\s*(-?\d+)', r'^\s*signal\s+avg:\s*(-?\d+)'): + mm = re.search(pat, g_out, re.I | re.M) + if mm: + try: + val = int(mm.group(1)) + if -120 <= val < 0: + return val + except ValueError: + pass + return None + for m in re.finditer(r'^Station ([0-9a-f:]{17})(.*?)(?=^Station |\Z)', dump, re.I|re.M|re.S): mac = m.group(1).upper(); detail = m.group(2) # CORRECTION : « iw station dump » liste aussi les appareils qui n'ont jamais fini l'authentification # (authorized: no, 0 octet échangé). Ce ne sont pas des clients connectés. am = re.search(r'^\s*authorized:\s*(\w+)', detail, re.I|re.M) if am and am.group(1).lower() != 'yes' and mac not in blocked_macs: continue - sm = re.search(r'^\s*signal:\s*(-?\d+)', detail, re.I|re.M) + sig_dbm = _extract_signal_dbm(detail, mac) rx_m = re.search(r'^\s*rx bytes:\s*(\d+)', detail, re.I|re.M) tx_m = re.search(r'^\s*tx bytes:\s*(\d+)', detail, re.I|re.M) raw_rx = int(rx_m.group(1)) if rx_m else 0 @@ -3537,7 +3591,7 @@ def clients(): 'ip': ip, 'mac': mac, 'device_type': custom_types.get(mac) or guess_device_type(name, mac), - 'signal_dbm': int(sm.group(1)) if sm else None, + 'signal_dbm': sig_dbm, 'blocked': blocked, 'connected': not blocked, 'download_speed': round(tx_rate), @@ -4751,6 +4805,9 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal name = target_name # Persister l'intégralité de la configuration Wi-Fi en BDD SQLite pour survie au redémarrage du conteneur + prev_mode = (get_pref('mode', 'ap') or 'ap').lower() + if prev_mode != mode: + station_live_ips.clear() set_pref('ap_ssid', ssid) set_pref('ap_password', password) set_pref('ap_security', sec) @@ -8446,6 +8503,33 @@ class Handler(BaseHTTPRequestHandler): except OSError: pass invalidate_status_cache() log({'start':'démarrage','stop':'arrêt','restart':'redémarrage'}.get(action,'action'), 'Point d’accès Wi-Fi', ip=request_ip(self), mac='AP'); self.send_json({'ok':True}); return + if self.path == '/api/ap/mode': + target_mode = str(data.get('mode', '')).strip().lower() + if target_mode not in ('ap', 'bridge'): + raise ValueError("Mode invalide (attendu 'ap' ou 'bridge')") + cur_st = status(force_refresh=True) + ssid = (get_pref('ap_ssid', '') or cur_st.get('ssid') or '').strip() + password = get_pref('ap_password', '') or cur_st.get('password') or '' + sec = (get_pref('ap_security', '') or cur_st.get('security') or 'wpa2').lower() + auto_raw = get_pref('ap_autoconnect', None) + autoconnect = (str(auto_raw).lower() in ('1', 'true', 'yes', 'oui')) if auto_raw is not None else bool(cur_st.get('autoconnect', True)) + b_name = str(data.get('bridge_name', '')).strip() or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) + b_eth = str(data.get('bridge_eth', '')).strip() or get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', '')) + if not ssid or ssid == 'SSID inconnu' or not password: + raise RuntimeError('Configuration Wi-Fi incomplète en BDD : veuillez vérifier vos réglages Wi-Fi') + was_active = bool(cur_st.get('active')) + station_live_ips.clear() + configure_ap({ + 'ssid': ssid, + 'password': password, + 'security': sec, + 'mode': target_mode, + 'autoconnect': autoconnect, + 'bridge_name': b_name, + 'bridge_eth': b_eth + }, initial=False, caller_ip=request_ip(self), start_now=was_active) + new_st = status(force_refresh=True) + self.send_json({'ok': True, 'mode': target_mode, 'status': new_st}); return if self.path == '/api/setup': self.send_json({'ok':True,'message':'Configuration enregistrée','connection':configure_ap(data,True,caller_ip=request_ip(self))}); return if self.path == '/api/settings': self.send_json({'ok':True,'message':'Réglages enregistrés','connection':configure_ap(data,caller_ip=request_ip(self))}); return if self.path == '/api/settings/proxy': diff --git a/index.html b/index.html index 0a16b0a..b8b93dc 100644 --- a/index.html +++ b/index.html @@ -4633,7 +4633,12 @@
État de l’AP
Chargement
-
—
+
+
—
+ +
Clients connectés
@@ -9992,11 +9997,13 @@ ${vpnBadgeTopo} } function esc(s) { return String(s).replace(/([\\;,:])/g, '\\$1') } function signalQuality(dbm) { - if (dbm === null || dbm === undefined) return '—'; - if (dbm >= -50) return `${t('signal_excellent', 'Excellent')}`; - if (dbm >= -60) return `${t('signal_good', 'Bon')}`; - if (dbm >= -70) return `${t('signal_fair', 'Moyen')}`; - return `${t('signal_weak', 'Faible')}`; + if (dbm === null || dbm === undefined || Number.isNaN(Number(dbm))) return '—'; + const val = Math.round(Number(dbm)); + const dbmTag = ` (${val} dBm)`; + if (val >= -50) return `${t('signal_excellent', 'Excellent')}${dbmTag}`; + if (val >= -60) return `${t('signal_good', 'Bon')}${dbmTag}`; + if (val >= -70) return `${t('signal_fair', 'Moyen')}${dbmTag}`; + return `${t('signal_weak', 'Faible')}${dbmTag}`; } function cleanQrBox(box) { @@ -10149,6 +10156,37 @@ ${vpnBadgeTopo} }); } + let _switchingMode = false; + async function quickSwitchMode(targetMode) { + if (_switchingMode) return; + const isBridge = status && status.mode === 'bridge'; + const nextMode = targetMode || (isBridge ? 'ap' : 'bridge'); + const btn = $('quickSwitchModeBtn'); + _switchingMode = true; + if (btn) { + btn.disabled = true; + btn.textContent = '⏳ ' + t('mode_switching', 'Bascule…'); + } + return runAction(async () => { + try { + const response = await apiFetch('/api/ap/mode', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mode: nextMode }) + }); + const data = await response.json(); + if (!response.ok) throw Error(data.error || 'Échec du changement de mode'); + await load(); + } catch (e) { + alert(tErr(e.message)); + } finally { + _switchingMode = false; + if (btn) btn.disabled = false; + render(); + } + }); + } + function render() { updateApButtons(); $('clientCount').textContent = status.max_clients > 0 ? `${clients.length} / ${status.max_clients}` : clients.length; @@ -10165,6 +10203,16 @@ ${vpnBadgeTopo} $('networkModeBadge').style.background = ''; $('networkModeBadge').style.color = ''; } + if ($('quickSwitchModeBtn')) { + const qbtn = $('quickSwitchModeBtn'); + qbtn.style.display = status.configured ? 'inline-flex' : 'none'; + if (!_switchingMode) { + qbtn.textContent = isBridge ? '⇄ ' + t('btn_switch_to_ap', 'Mode AP') : '⇄ ' + t('btn_switch_to_bridge', 'Mode Pont'); + qbtn.title = isBridge + ? t('tip_switch_to_ap', 'Basculer instantanément en Mode AP (Routeur/NAT)') + : t('tip_switch_to_bridge', 'Basculer instantanément en Mode Pont (DHCP Box)'); + } + } if ($('settingsModeAp') && $('settingsModeBridge')) { if (isBridge) $('settingsModeBridge').checked = true; else $('settingsModeAp').checked = true; if ($('settingsBridgeBlock')) $('settingsBridgeBlock').style.display = isBridge ? 'block' : 'none'; diff --git a/lang/en-gb.js b/lang/en-gb.js index 390a16d..8c244a1 100644 --- a/lang/en-gb.js +++ b/lang/en-gb.js @@ -1155,4 +1155,9 @@ window.I18N['en-gb'] = { "adv_pcap_err_clear": "Error clearing packets", "adv_pcap_filter_icmp": "ICMP (Ping)", "adv_pcap_filter_tls": "TLS / HTTPS", + "btn_switch_to_ap": "AP Mode", + "btn_switch_to_bridge": "Bridge Mode", + "tip_switch_to_ap": "Switch instantly to AP Mode (Router/NAT)", + "tip_switch_to_bridge": "Switch instantly to Bridge Mode (Router DHCP)", + "mode_switching": "Switching…", }; diff --git a/lang/en-us.js b/lang/en-us.js index 096ed65..77d597f 100644 --- a/lang/en-us.js +++ b/lang/en-us.js @@ -1155,4 +1155,9 @@ window.I18N['en-us'] = { "adv_pcap_err_clear": "Error clearing packets", "adv_pcap_filter_icmp": "ICMP (Ping)", "adv_pcap_filter_tls": "TLS / HTTPS", + "btn_switch_to_ap": "AP Mode", + "btn_switch_to_bridge": "Bridge Mode", + "tip_switch_to_ap": "Switch instantly to AP Mode (Router/NAT)", + "tip_switch_to_bridge": "Switch instantly to Bridge Mode (Router DHCP)", + "mode_switching": "Switching…", }; diff --git a/lang/fr.js b/lang/fr.js index bb5c037..6e378bd 100644 --- a/lang/fr.js +++ b/lang/fr.js @@ -1155,4 +1155,9 @@ window.I18N['fr'] = { "adv_pcap_err_clear": "Erreur effacement", "adv_pcap_filter_icmp": "ICMP (Ping)", "adv_pcap_filter_tls": "TLS / HTTPS", + "btn_switch_to_ap": "Mode AP", + "btn_switch_to_bridge": "Mode Pont", + "tip_switch_to_ap": "Basculer instantanément en Mode AP (Routeur/NAT)", + "tip_switch_to_bridge": "Basculer instantanément en Mode Pont (DHCP Box)", + "mode_switching": "Bascule…", };