manager.py 10 KB

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