APmanageur Wi-Fi V1.0
This commit is contained in:
1 parent
82cc8f7920
commit
810d086426
5 files changed
+158
-11
No files matched your search
@@ -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 <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):
|
||||
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':
|
||||
|
||||
Reference in new issue
Block a user