-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathracecam_network_manager.py
More file actions
62 lines (54 loc) · 2.39 KB
/
racecam_network_manager.py
File metadata and controls
62 lines (54 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
import subprocess
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - NetworkManager - %(message)s')
def run_cmd(cmd):
"""Runs a command, logging errors but not stopping the script."""
try:
result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
logging.error(f"Command '{cmd}' failed: {e.stderr.strip()}")
return ""
def is_wifi_connected():
"""
Checks if there is an active Wi-Fi connection on the wlan0 interface.
A more reliable check is to see if an active connection profile exists on the device.
"""
try:
# We use subprocess.run directly to check the return code, which is cleaner.
# A return code of 0 from grep means a match was found.
subprocess.run("nmcli -t -f DEVICE connection show --active | grep -q '^wlan0$'", shell=True, check=True)
logging.info("Active Wi-Fi connection found on wlan0.")
return True
except subprocess.CalledProcessError:
# This error means grep returned a non-zero code (no match found).
logging.info("No active Wi-Fi connection found on wlan0.")
return False
def set_ap_mode(enable=True):
"""Enables or disables the Wi-Fi Access Point mode."""
if enable:
logging.info("No Wi-Fi connection. Enabling Access Point (AP) mode.")
# Stop NetworkManager from managing wlan0 so hostapd can use it.
run_cmd("sudo nmcli device set wlan0 managed no")
run_cmd("sudo systemctl start hostapd.service")
run_cmd("sudo systemctl start dnsmasq.service")
else:
logging.info("Wi-Fi connection detected. Disabling Access Point (AP) mode.")
run_cmd("sudo systemctl stop hostapd.service")
run_cmd("sudo systemctl stop dnsmasq.service")
# Give control of wlan0 back to NetworkManager.
run_cmd("sudo nmcli device set wlan0 managed yes")
def main():
"""Main logic to check network status and switch modes."""
logging.info("Starting network mode check...")
# Give NetworkManager a moment to establish a connection at boot.
time.sleep(15)
if is_wifi_connected():
set_ap_mode(enable=False)
else:
set_ap_mode(enable=True)
logging.info("Network mode check complete.")
if __name__ == "__main__":
main()