MCPcopy Create free account
hub / github.com/PierreGode/Ragnar / detect_wifi_interface

Function detect_wifi_interface

shared.py:49–94  ·  view source on GitHub ↗

Detect the primary WiFi interface dynamically. If *configured* is an explicit interface name (not 'auto'), return it as-is. Otherwise auto-detect via nmcli, then sysfs, falling back to 'wlan0'. Results are cached for 60 seconds to avoid repeated subprocess calls.

(configured='auto')

Source from the content-addressed store, hash-verified

47_detected_wifi_interface_time = 0
48
49def detect_wifi_interface(configured='auto'):
50 """Detect the primary WiFi interface dynamically.
51
52 If *configured* is an explicit interface name (not 'auto'), return it as-is.
53 Otherwise auto-detect via nmcli, then sysfs, falling back to 'wlan0'.
54 Results are cached for 60 seconds to avoid repeated subprocess calls.
55 """
56 global _detected_wifi_interface, _detected_wifi_interface_time
57
58 if configured and configured != 'auto':
59 return configured
60
61 now = time.time()
62 if _detected_wifi_interface and (now - _detected_wifi_interface_time) < 60:
63 return _detected_wifi_interface
64
65 # Method 1: nmcli — first managed wifi device
66 try:
67 result = subprocess.run(
68 ['nmcli', '-t', '-f', 'DEVICE,TYPE', 'device'],
69 capture_output=True, text=True, timeout=5
70 )
71 if result.returncode == 0:
72 for line in result.stdout.strip().split('\n'):
73 parts = line.split(':')
74 if len(parts) >= 2 and parts[1] == 'wifi':
75 _detected_wifi_interface = parts[0]
76 _detected_wifi_interface_time = now
77 return _detected_wifi_interface
78 except Exception:
79 pass
80
81 # Method 2: sysfs — pick first interface that has wireless/ directory
82 try:
83 for name in sorted(os.listdir('/sys/class/net')):
84 if os.path.isdir(f'/sys/class/net/{name}/wireless'):
85 _detected_wifi_interface = name
86 _detected_wifi_interface_time = now
87 return _detected_wifi_interface
88 except Exception:
89 pass
90
91 # Fallback
92 _detected_wifi_interface = 'wlan0'
93 _detected_wifi_interface_time = now
94 return _detected_wifi_interface
95
96try:
97 from PIL import Image, ImageFont

Callers 7

scan_wifiMethod · 0.90
gather_wifi_interfacesFunction · 0.90
_default_ifaceMethod · 0.90
__init__Method · 0.90
_get_wifi_ifaceFunction · 0.90
__init__Method · 0.90

Calls 1

runMethod · 0.45

Tested by

no test coverage detected