APmanageur Wi-Fi V1.0

This commit is contained in:
yoannmultigaming committed 2026-11-18 01:54:10 +01:00
1 parent 82cc8f7920
commit 810d086426
5 files changed
+158 -11

No files matched your search

+89 -5
View File
@@ -2986,17 +2986,25 @@ def stop_hostapd(iface=None):
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
def ensure_nm_manages_wifi(iface=None): 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 iface = iface or INTERFACE
if not iface: if not iface:
return return
was_unmanaged = (command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) or '').startswith('10')
stop_hostapd(iface) 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) 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) 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 break
time.sleep(0.2) time.sleep(0.2)
if was_unmanaged:
time.sleep(0.3)
def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=None): 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.""" """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 ipmac[nmac] = nip
output = []; dump = command('iw','dev',INTERFACE,'station','dump'); blocked_macs = blocked_set() 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 <iface> station get <mac> » (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): 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) mac = m.group(1).upper(); detail = m.group(2)
# CORRECTION : « iw station dump » liste aussi les appareils qui n'ont jamais fini l'authentification # 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. # (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) 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 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) 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) 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 raw_rx = int(rx_m.group(1)) if rx_m else 0
@@ -3537,7 +3591,7 @@ def clients():
'ip': ip, 'ip': ip,
'mac': mac, 'mac': mac,
'device_type': custom_types.get(mac) or guess_device_type(name, 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, 'blocked': blocked,
'connected': not blocked, 'connected': not blocked,
'download_speed': round(tx_rate), '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 name = target_name
# Persister l'intégralité de la configuration Wi-Fi en BDD SQLite pour survie au redémarrage du conteneur # 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_ssid', ssid)
set_pref('ap_password', password) set_pref('ap_password', password)
set_pref('ap_security', sec) set_pref('ap_security', sec)
@@ -8446,6 +8503,33 @@ class Handler(BaseHTTPRequestHandler):
except OSError: pass except OSError: pass
invalidate_status_cache() 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 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/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': 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': if self.path == '/api/settings/proxy':
+54 -6
View File
@@ -4633,7 +4633,12 @@
<div class="card"> <div class="card">
<div class="label" data-i18n="dash_state_title">État de l’AP</div> <div class="label" data-i18n="dash_state_title">État de l’AP</div>
<div id="state" class="metric status"><i class="dot"></i> Chargement</div> <div id="state" class="metric status"><i class="dot"></i> Chargement</div>
<div id="networkModeBadge" class="pill" style="margin-top:8px;width:fit-content;max-width:100%">—</div> <div style="display:flex;align-items:center;gap:6px;margin-top:8px;flex-wrap:wrap">
<div id="networkModeBadge" class="pill" style="width:fit-content;max-width:100%">—</div>
<button id="quickSwitchModeBtn" type="button" class="secondary" onclick="quickSwitchMode()"
style="padding:3px 9px;font-size:11px;border-radius:999px;line-height:1.3;display:none"
title="Basculer instantanément entre Mode AP et Mode Pont">⇄</button>
</div>
</div> </div>
<div class="card"> <div class="card">
<div class="label" data-i18n="dash_clients_title">Clients connectés</div> <div class="label" data-i18n="dash_clients_title">Clients connectés</div>
@@ -9992,11 +9997,13 @@ ${vpnBadgeTopo}
} }
function esc(s) { return String(s).replace(/([\\;,:])/g, '\\$1') } function esc(s) { return String(s).replace(/([\\;,:])/g, '\\$1') }
function signalQuality(dbm) { function signalQuality(dbm) {
if (dbm === null || dbm === undefined) return '<span class="signal">—</span>'; if (dbm === null || dbm === undefined || Number.isNaN(Number(dbm))) return '<span class="signal">—</span>';
if (dbm >= -50) return `<span class="signal signal-excellent">${t('signal_excellent', 'Excellent')}</span>`; const val = Math.round(Number(dbm));
if (dbm >= -60) return `<span class="signal signal-bon">${t('signal_good', 'Bon')}</span>`; const dbmTag = ` <small style="opacity:.78;font-weight:500">(${val} dBm)</small>`;
if (dbm >= -70) return `<span class="signal signal-moyen">${t('signal_fair', 'Moyen')}</span>`; if (val >= -50) return `<span class="signal signal-excellent" title="${val} dBm">${t('signal_excellent', 'Excellent')}${dbmTag}</span>`;
return `<span class="signal signal-faible">${t('signal_weak', 'Faible')}</span>`; if (val >= -60) return `<span class="signal signal-bon" title="${val} dBm">${t('signal_good', 'Bon')}${dbmTag}</span>`;
if (val >= -70) return `<span class="signal signal-moyen" title="${val} dBm">${t('signal_fair', 'Moyen')}${dbmTag}</span>`;
return `<span class="signal signal-faible" title="${val} dBm">${t('signal_weak', 'Faible')}${dbmTag}</span>`;
} }
function cleanQrBox(box) { 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() { function render() {
updateApButtons(); updateApButtons();
$('clientCount').textContent = status.max_clients > 0 ? `${clients.length} / ${status.max_clients}` : clients.length; $('clientCount').textContent = status.max_clients > 0 ? `${clients.length} / ${status.max_clients}` : clients.length;
@@ -10165,6 +10203,16 @@ ${vpnBadgeTopo}
$('networkModeBadge').style.background = ''; $('networkModeBadge').style.background = '';
$('networkModeBadge').style.color = ''; $('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 ($('settingsModeAp') && $('settingsModeBridge')) {
if (isBridge) $('settingsModeBridge').checked = true; else $('settingsModeAp').checked = true; if (isBridge) $('settingsModeBridge').checked = true; else $('settingsModeAp').checked = true;
if ($('settingsBridgeBlock')) $('settingsBridgeBlock').style.display = isBridge ? 'block' : 'none'; if ($('settingsBridgeBlock')) $('settingsBridgeBlock').style.display = isBridge ? 'block' : 'none';
+5
View File
@@ -1155,4 +1155,9 @@ window.I18N['en-gb'] = {
"adv_pcap_err_clear": "Error clearing packets", "adv_pcap_err_clear": "Error clearing packets",
"adv_pcap_filter_icmp": "ICMP (Ping)", "adv_pcap_filter_icmp": "ICMP (Ping)",
"adv_pcap_filter_tls": "TLS / HTTPS", "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…",
}; };
+5
View File
@@ -1155,4 +1155,9 @@ window.I18N['en-us'] = {
"adv_pcap_err_clear": "Error clearing packets", "adv_pcap_err_clear": "Error clearing packets",
"adv_pcap_filter_icmp": "ICMP (Ping)", "adv_pcap_filter_icmp": "ICMP (Ping)",
"adv_pcap_filter_tls": "TLS / HTTPS", "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…",
}; };
+5
View File
@@ -1155,4 +1155,9 @@ window.I18N['fr'] = {
"adv_pcap_err_clear": "Erreur effacement", "adv_pcap_err_clear": "Erreur effacement",
"adv_pcap_filter_icmp": "ICMP (Ping)", "adv_pcap_filter_icmp": "ICMP (Ping)",
"adv_pcap_filter_tls": "TLS / HTTPS", "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…",
}; };