manager.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. """
  2. WiFi management via NetworkManager (nmcli).
  3. Handles scanning, connecting, and managing WiFi connections.
  4. Supports both Docker (via nsenter) and direct (venv) execution.
  5. """
  6. import subprocess
  7. import os
  8. import logging
  9. import asyncio
  10. import socket
  11. logger = logging.getLogger(__name__)
  12. MODE_FILE = "/tmp/dw-wifi-mode"
  13. def is_docker() -> bool:
  14. """Check if running inside a Docker container."""
  15. return os.path.exists("/.dockerenv") or os.getenv("DOCKER_CONTAINER") == "1"
  16. def run_host_command(*args: str, timeout: int = 30) -> subprocess.CompletedProcess:
  17. """Run a command on the host, handling Docker vs venv.
  18. In Docker: uses nsenter to execute in the host's namespaces.
  19. In venv: executes directly.
  20. """
  21. if is_docker():
  22. cmd = ["nsenter", "-t", "1", "-m", "-u", "-i", "-n", "-p", "--"] + list(args)
  23. else:
  24. cmd = list(args)
  25. logger.debug(f"Running host command: {' '.join(cmd)}")
  26. result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
  27. if result.returncode != 0 and result.stderr:
  28. logger.debug(f"Command stderr: {result.stderr.strip()}")
  29. return result
  30. def run_nmcli(*args: str, timeout: int = 30) -> str:
  31. """Run nmcli on the host and return stdout."""
  32. result = run_host_command("nmcli", *args, timeout=timeout)
  33. return result.stdout
  34. def get_wifi_mode() -> str:
  35. """Get the current WiFi mode from the mode file."""
  36. try:
  37. if is_docker():
  38. result = run_host_command("cat", MODE_FILE)
  39. return result.stdout.strip() or "unknown"
  40. else:
  41. with open(MODE_FILE, "r") as f:
  42. return f.read().strip() or "unknown"
  43. except (FileNotFoundError, subprocess.TimeoutExpired):
  44. return "unknown"
  45. def get_current_ssid() -> str:
  46. """Get the SSID of the currently connected WiFi network."""
  47. try:
  48. output = run_nmcli("-t", "-f", "GENERAL.CONNECTION", "dev", "show", "wlan0")
  49. for line in output.strip().splitlines():
  50. if "GENERAL.CONNECTION" in line:
  51. ssid = line.split(":", 1)[1] if ":" in line else ""
  52. if ssid and ssid != "--" and ssid != "DuneWeaver-Hotspot":
  53. return ssid
  54. except (subprocess.TimeoutExpired, Exception) as e:
  55. logger.debug(f"Error getting SSID: {e}")
  56. return ""
  57. def get_current_ip() -> str:
  58. """Get the current IP address of the wlan0 interface."""
  59. try:
  60. output = run_nmcli("-t", "-f", "IP4.ADDRESS", "dev", "show", "wlan0")
  61. for line in output.strip().splitlines():
  62. if "IP4.ADDRESS" in line:
  63. addr = line.split(":", 1)[1] if ":" in line else ""
  64. if addr:
  65. return addr.split("/")[0]
  66. except (subprocess.TimeoutExpired, Exception) as e:
  67. logger.debug(f"Error getting IP: {e}")
  68. return ""
  69. def get_hostname() -> str:
  70. """Get the system hostname."""
  71. try:
  72. return socket.gethostname()
  73. except Exception:
  74. return "duneweaver"
  75. def get_wifi_status() -> dict:
  76. """Get comprehensive WiFi status."""
  77. mode = get_wifi_mode()
  78. ssid = get_current_ssid()
  79. ip = get_current_ip()
  80. hostname = get_hostname()
  81. return {
  82. "mode": mode,
  83. "ssid": ssid,
  84. "ip": ip,
  85. "hostname": hostname,
  86. }
  87. def scan_networks() -> list[dict]:
  88. """Scan for available WiFi networks."""
  89. try:
  90. # Trigger rescan
  91. run_nmcli("dev", "wifi", "rescan", "ifname", "wlan0")
  92. except Exception:
  93. pass
  94. # Brief wait for scan results
  95. import time
  96. time.sleep(2)
  97. try:
  98. output = run_nmcli("-t", "-f", "SSID,SIGNAL,SECURITY,ACTIVE", "dev", "wifi", "list", "ifname", "wlan0")
  99. except subprocess.TimeoutExpired:
  100. logger.error("WiFi scan timed out")
  101. return []
  102. # Get saved connections for cross-reference
  103. saved = get_saved_connections()
  104. saved_ssids = {c["ssid"] for c in saved}
  105. networks = []
  106. seen_ssids = set()
  107. for line in output.strip().splitlines():
  108. if not line.strip():
  109. continue
  110. # nmcli -t uses : as delimiter, but SSID can contain colons
  111. # Format: SSID:SIGNAL:SECURITY:ACTIVE
  112. # Parse from the right since SSID is the only field that can contain ':'
  113. parts = line.rsplit(":", 3)
  114. if len(parts) < 4:
  115. continue
  116. ssid = parts[0].strip()
  117. if not ssid or ssid in seen_ssids:
  118. continue
  119. seen_ssids.add(ssid)
  120. try:
  121. signal = int(parts[1])
  122. except (ValueError, IndexError):
  123. signal = 0
  124. security = parts[2] if len(parts) > 2 else ""
  125. active = parts[3].strip().lower() == "yes" if len(parts) > 3 else False
  126. networks.append({
  127. "ssid": ssid,
  128. "signal": signal,
  129. "security": security if security and security != "--" else "Open",
  130. "saved": ssid in saved_ssids,
  131. "active": active,
  132. })
  133. # Sort by signal strength (strongest first)
  134. networks.sort(key=lambda n: n["signal"], reverse=True)
  135. return networks
  136. def get_saved_connections() -> list[dict]:
  137. """Get list of saved WiFi connections."""
  138. try:
  139. output = run_nmcli("-t", "-f", "NAME,TYPE", "con", "show")
  140. except subprocess.TimeoutExpired:
  141. return []
  142. connections = []
  143. for line in output.strip().splitlines():
  144. if "wireless" not in line:
  145. continue
  146. name = line.split(":")[0]
  147. if name == "DuneWeaver-Hotspot":
  148. continue
  149. # Get the SSID for this connection
  150. try:
  151. detail = run_nmcli("-t", "-f", "802-11-wireless.ssid", "con", "show", name)
  152. ssid = ""
  153. for detail_line in detail.strip().splitlines():
  154. if "802-11-wireless.ssid" in detail_line:
  155. ssid = detail_line.split(":", 1)[1] if ":" in detail_line else name
  156. break
  157. if not ssid:
  158. ssid = name
  159. except Exception:
  160. ssid = name
  161. connections.append({
  162. "name": name,
  163. "ssid": ssid,
  164. })
  165. return connections
  166. async def connect_to_network(ssid: str, password: str) -> dict:
  167. """Connect to a WiFi network and schedule reboot.
  168. Uses explicit connection profile creation (nmcli con add) instead of
  169. 'nmcli dev wifi connect' because the latter fails on Pi Trixie with
  170. 'key-mgmt: property is missing' for WPA networks.
  171. """
  172. try:
  173. # Delete any stale connection profile for this SSID
  174. run_host_command("nmcli", "con", "delete", ssid, timeout=10)
  175. # Create connection profile with explicit security settings
  176. if password:
  177. result = run_host_command(
  178. "nmcli", "con", "add",
  179. "type", "wifi",
  180. "ifname", "wlan0",
  181. "con-name", ssid,
  182. "ssid", ssid,
  183. "wifi-sec.key-mgmt", "wpa-psk",
  184. "wifi-sec.psk", password,
  185. timeout=15,
  186. )
  187. else:
  188. result = run_host_command(
  189. "nmcli", "con", "add",
  190. "type", "wifi",
  191. "ifname", "wlan0",
  192. "con-name", ssid,
  193. "ssid", ssid,
  194. timeout=15,
  195. )
  196. if result.returncode != 0:
  197. error_msg = result.stderr.strip() or "Failed to create connection"
  198. logger.error(f"WiFi connection add failed: {error_msg}")
  199. return {"success": False, "message": error_msg}
  200. # Activate the connection
  201. result = run_host_command(
  202. "nmcli", "con", "up", ssid,
  203. timeout=30,
  204. )
  205. if result.returncode != 0:
  206. error_msg = result.stderr.strip() or "Failed to connect"
  207. logger.error(f"WiFi connect failed: {error_msg}")
  208. # Clean up the failed connection profile
  209. run_host_command("nmcli", "con", "delete", ssid, timeout=10)
  210. return {"success": False, "message": error_msg}
  211. logger.info(f"WiFi connection to '{ssid}' successful, scheduling reboot...")
  212. # Schedule reboot so the response can be sent first
  213. asyncio.get_event_loop().call_later(3, _schedule_reboot)
  214. return {
  215. "success": True,
  216. "message": f"Connected to '{ssid}'. Rebooting in 3 seconds...",
  217. }
  218. except subprocess.TimeoutExpired:
  219. return {"success": False, "message": "Connection timed out"}
  220. except Exception as e:
  221. logger.error(f"WiFi connect error: {e}")
  222. return {"success": False, "message": str(e)}
  223. def _schedule_reboot():
  224. """Trigger a system reboot."""
  225. try:
  226. logger.info("Rebooting system for WiFi mode change...")
  227. run_host_command("reboot")
  228. except Exception as e:
  229. logger.error(f"Reboot failed: {e}")
  230. def forget_network(ssid: str) -> dict:
  231. """Delete a saved WiFi connection by SSID."""
  232. saved = get_saved_connections()
  233. con_name = None
  234. for con in saved:
  235. if con["ssid"] == ssid:
  236. con_name = con["name"]
  237. break
  238. if not con_name:
  239. return {"success": False, "message": f"No saved connection found for '{ssid}'"}
  240. try:
  241. result = run_host_command("nmcli", "con", "delete", con_name, timeout=15)
  242. if result.returncode == 0:
  243. logger.info(f"Forgot WiFi network '{ssid}' (connection: {con_name})")
  244. return {"success": True, "message": f"Forgot '{ssid}'"}
  245. else:
  246. error_msg = result.stderr.strip() or "Failed to delete connection"
  247. return {"success": False, "message": error_msg}
  248. except Exception as e:
  249. return {"success": False, "message": str(e)}