manager.py 10 KB

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