diff --git a/ap.py b/ap.py
index bffb84a..25f12d2 100644
--- a/ap.py
+++ b/ap.py
@@ -15,7 +15,34 @@ for p in ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin',
if p not in os.environ.get('PATH', '').split(':'):
os.environ['PATH'] = p + ':' + os.environ.get('PATH', '')
-INTERFACE = os.environ.get('AP_INTERFACE', 'wls16b1')
+def detect_wifi_interface():
+ env_iface = (os.environ.get('AP_INTERFACE') or '').strip()
+ if env_iface and os.path.exists(f'/sys/class/net/{env_iface}'):
+ return env_iface
+ try:
+ if os.path.exists('/sys/class/net'):
+ for d in os.listdir('/sys/class/net'):
+ p = os.path.join('/sys/class/net', d)
+ if os.path.isdir(os.path.join(p, 'wireless')) or os.path.isdir(os.path.join(p, 'phy80211')):
+ return d
+ except Exception: pass
+ try:
+ out = subprocess.check_output(['iw', 'dev'], text=True, stderr=subprocess.DEVNULL)
+ for line in out.splitlines():
+ parts = line.strip().split()
+ if len(parts) >= 2 and parts[0] == 'Interface':
+ return parts[1]
+ except Exception: pass
+ try:
+ out = subprocess.check_output(['nmcli', '-t', '-g', 'DEVICE,TYPE', 'device'], text=True, stderr=subprocess.DEVNULL)
+ for line in out.splitlines():
+ if ':wifi' in line or ':802-11-wireless' in line:
+ d = line.split(':')[0].strip()
+ if d: return d
+ except Exception: pass
+ return env_iface or 'wlan0'
+
+INTERFACE = detect_wifi_interface()
SOCKET_PATH = os.environ.get('AP_SOCKET', '/run/ap-api.sock')
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_FILE = os.environ.get('AP_DB_FILE', os.path.join(BASE_DIR, 'ap-dashboard.sqlite3'))
@@ -4008,34 +4035,29 @@ def stop_hostapd(iface=None):
def ensure_nm_manages_wifi(iface=None, force=False):
"""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 get_wifi_interface()
if not iface:
return
- # Si le périphérique est déjà sous le contrôle de NetworkManager (pas de hostapd actif, non asservi à un pont et état >= 30)
- # il est contre-productif de faire un reset physique (down/up) qui déconnecterait l'interface.
is_master = os.path.exists(f'/sys/class/net/{iface}/master')
hostapd_act = is_hostapd_running()
current_st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=2)
+ # Si le périphérique est déjà sous le contrôle de NetworkManager (pas de hostapd actif, non asservi à un pont et état != 10 unmanaged)
+ # il ne faut JAMAIS faire de reset physique (down/up) qui déconnecterait l'interface.
if not force and not is_master and not hostapd_act:
- if current_st and not current_st.startswith('10') and not current_st.startswith('20'):
+ if current_st and not current_st.startswith('10'):
return
stop_hostapd(iface)
- # S'assurer que wpa_supplicant est actif (indispensable pour que NM puisse initialiser la radio Wi-Fi)
ensure_wpa_supplicant_running()
- subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True, timeout=3)
- subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True, timeout=3)
- subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True, timeout=3)
- subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True, timeout=3)
- subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True, timeout=3)
- subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True, timeout=3)
- subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True, timeout=5)
- subprocess.run(['nmcli', 'radio', 'wifi', 'on'], capture_output=True, timeout=5)
- for _ in range(35):
- st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=2)
- if st and not st.startswith('10') and not st.startswith('20'): # 10=unmanaged, 20=unavailable
+ subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True, timeout=2)
+ subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True, timeout=2)
+ subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True, timeout=2)
+ subprocess.run(['nmcli', 'radio', 'wifi', 'on'], capture_output=True, timeout=2)
+ for _ in range(5):
+ st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=1)
+ if st and not st.startswith('10'):
break
- time.sleep(0.2)
+ time.sleep(0.1)
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."""
@@ -6609,7 +6631,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(get_effective_ap_channel(AP_BAND, force_rescan=is_auto_channel())),
+ '802-11-wireless.channel', str(get_effective_ap_channel(AP_BAND, force_rescan=False)),
'connection.autoconnect', 'yes' if autoconnect else 'no'
]
if proto: modify_args += ['802-11-wireless-security.proto', proto]
@@ -6624,8 +6646,10 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
ensure_dnsmasq_dns()
save_connection(name)
if start_now:
- r = subprocess.run(['nmcli', '--wait', '20', 'connection', 'up', name], text=True, capture_output=True, timeout=25)
- if r.returncode:
+ r = subprocess.run(['nmcli', 'connection', 'up', name, 'ifname', INTERFACE], text=True, capture_output=True, timeout=12)
+ if r.returncode != 0:
+ r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True, timeout=10)
+ if r.returncode != 0:
raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès')
disable_wifi_powersave(INTERFACE)
setup_ap_nat(INTERFACE)
@@ -6741,16 +6765,19 @@ def restore_ap_from_db(force_start=False):
save_connection(target_name)
if should_start:
teardown_bridge(b_name, b_eth)
- ensure_nm_manages_wifi(INTERFACE)
- state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', INTERFACE)
+ wifi_if = get_wifi_interface()
+ ensure_nm_manages_wifi(wifi_if)
+ state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', wifi_if, timeout=2)
if not state.startswith('100'):
print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode=ap)...", flush=True)
- r = subprocess.run(['nmcli', '--wait', '15', 'connection', 'up', target_name], capture_output=True, text=True, timeout=20)
+ r = subprocess.run(['nmcli', 'connection', 'up', target_name, 'ifname', wifi_if], capture_output=True, text=True, timeout=12)
+ if r.returncode != 0:
+ r = subprocess.run(['nmcli', 'connection', 'up', target_name], capture_output=True, text=True, timeout=10)
if r.returncode != 0:
print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True)
return False
- disable_wifi_powersave(INTERFACE)
- setup_ap_nat(INTERFACE)
+ disable_wifi_powersave(wifi_if)
+ setup_ap_nat(wifi_if)
mark_ap_started()
else:
print(f"[ap-api] Profil Wi-Fi '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True)
@@ -7292,28 +7319,8 @@ def parse_packet(raw, ts):
def get_wifi_interface():
global INTERFACE
- env_iface = os.environ.get('AP_INTERFACE', '').strip()
- if env_iface and os.path.exists(f'/sys/class/net/{env_iface}'):
- INTERFACE = env_iface
- return env_iface
- if INTERFACE and os.path.exists(f'/sys/class/net/{INTERFACE}'):
- return INTERFACE
- try:
- for d in os.listdir('/sys/class/net'):
- p = os.path.join('/sys/class/net', d)
- if os.path.isdir(os.path.join(p, 'wireless')) or os.path.isdir(os.path.join(p, 'phy80211')):
- INTERFACE = d
- return d
- except Exception: pass
- try:
- out = subprocess.check_output(['iw', 'dev'], text=True, stderr=subprocess.DEVNULL)
- for line in out.splitlines():
- parts = line.strip().split()
- if len(parts) >= 2 and parts[0] == 'Interface':
- INTERFACE = parts[1]
- return parts[1]
- except Exception: pass
- return INTERFACE or 'wls16b1'
+ INTERFACE = detect_wifi_interface()
+ return INTERFACE
def start_capture(target_iface=None):
global capture_running, capture_thread, capture_pcap_bytes, capture_iface_used, capture_started_at
@@ -13023,6 +13030,7 @@ class Handler(BaseHTTPRequestHandler):
if is_bridge_mode():
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
+ wifi_if = get_wifi_interface()
if action in ('start', 'restart'):
db_ssid = (get_pref('ap_ssid', '') or '').strip()
db_pass = get_pref('ap_password', '') or ''
@@ -13030,38 +13038,48 @@ class Handler(BaseHTTPRequestHandler):
if not db_ssid or not db_pass:
raise RuntimeError('Paramètres Wi-Fi manquants en BDD : veuillez ré-enregistrer les réglages Wi-Fi')
if action == 'restart':
- stop_hostapd(INTERFACE)
+ stop_hostapd(wifi_if)
time.sleep(0.3)
setup_bridge(b_name, b_eth)
- start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE)
+ start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=wifi_if)
mark_ap_started()
elif action == 'stop':
- stop_hostapd(INTERFACE)
- teardown_bridge_dns_redirection(b_name, INTERFACE)
+ stop_hostapd(wifi_if)
+ teardown_bridge_dns_redirection(b_name, wifi_if)
try: os.remove(UPTIME_FILE)
except OSError: pass
else:
+ wifi_if = get_wifi_interface()
if action in ('start', 'restart'):
- ensure_nm_manages_wifi(INTERFACE)
- nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True, timeout=5).returncode == 0)
- if not nm_exists and get_pref('ap_ssid', ''):
+ if not name:
+ name = connection_name()
+ if not name and get_pref('ap_ssid', ''):
+ name = 'AP-' + get_pref('ap_ssid', '').strip()
+ if not name:
+ raise ValueError('Aucune connexion AP configurée')
+
+ ensure_nm_manages_wifi(wifi_if)
+ if action == 'restart':
+ subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=5)
+ time.sleep(0.3)
+
+ # Tentative d'activation directe rapide
+ r = subprocess.run(['nmcli', 'connection', 'up', name, 'ifname', wifi_if], capture_output=True, text=True, timeout=12)
+ if r.returncode != 0:
+ # Deuxième tentative sans ifname explicite
+ r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True, timeout=10)
+
+ if r.returncode != 0:
+ print(f"[ap-control] Échec activation directe '{name}' ({r.stderr.strip()}), restauration via BDD...", flush=True)
if not restore_ap_from_db(force_start=True):
- raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD')
- else:
- if action == 'restart':
- subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=10)
- time.sleep(0.5)
- r = subprocess.run(['nmcli', '--wait', '15', 'connection', 'up', name], capture_output=True, text=True, timeout=20)
- if r.returncode:
- print(f"[ap-control] Échec activation '{name}' ({r.stderr.strip()}), tentative de restauration BDD...", flush=True)
- if not restore_ap_from_db(force_start=True):
- raise RuntimeError(r.stderr.strip() or "Échec de l'activation du point d'accès Wi-Fi")
- disable_wifi_powersave(INTERFACE)
- setup_ap_nat(INTERFACE)
+ raise RuntimeError(r.stderr.strip() or "Échec de l'activation du point d'accès Wi-Fi")
+
+ disable_wifi_powersave(wifi_if)
+ setup_ap_nat(wifi_if)
mark_ap_started()
elif action == 'stop':
if name:
- r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=10)
+ r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=5)
if r.returncode and 'not an active connection' not in r.stderr.lower():
raise RuntimeError(r.stderr.strip())
teardown_ap_nat()
diff --git a/index.html b/index.html
index a75bcc9..962cc56 100644
--- a/index.html
+++ b/index.html
@@ -9688,10 +9688,15 @@ ${vpnBadgeTopo}
rstBtn.innerHTML = `⚙️ ${escapeHtml(t('btn_restarting', 'Redémarrage…'))}`;
}
try {
- const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 35000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
+ const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 60000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Action refusée');
- await new Promise(resolve => setTimeout(resolve, 800));
- await load();
+ for (let attempt = 0; attempt < 6; attempt++) {
+ await new Promise(resolve => setTimeout(resolve, 600));
+ await load();
+ if (action === 'start' && status && status.active) break;
+ if (action === 'stop' && status && !status.active) break;
+ if (action === 'restart' && status && status.active) break;
+ }
} catch (e) {
alert(tErr(e.message));
} finally {