fix wifi 2 pkg issue
This commit is contained in:
76
wifi.py
76
wifi.py
@@ -116,6 +116,20 @@ class WiFiManager:
|
||||
|
||||
# ==================== WiFi 连接方法 ====================
|
||||
|
||||
def is_sta_associated(self):
|
||||
"""
|
||||
是否作为 STA 已关联到上游 AP(用于与 AP 模式区分:AP 模式下 wlan0 可能有 IP 但 iw link 为 Not connected)。
|
||||
"""
|
||||
try:
|
||||
out = os.popen("iw dev wlan0 link 2>/dev/null").read()
|
||||
if not out.strip():
|
||||
return False
|
||||
if "Not connected" in out:
|
||||
return False
|
||||
return "Connected to" in out
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def is_wifi_connected(self):
|
||||
"""检查WiFi是否已连接"""
|
||||
# 优先用 MaixPy network(如果可用)
|
||||
@@ -271,7 +285,67 @@ class WiFiManager:
|
||||
self._wifi_ip = None
|
||||
self.logger.error(f"[WIFI] 连接/验证失败,已回滚: {e}")
|
||||
return None, str(e)
|
||||
|
||||
|
||||
def persist_sta_credentials(self, ssid: str, password: str, restart_service: bool = True):
|
||||
"""
|
||||
仅写入 STA 凭证(/etc/wpa_supplicant.conf + /boot/wifi.ssid|pass),
|
||||
可选是否立即 /etc/init.d/S30wifi restart。
|
||||
不做可达性验证。用于热点配网页提交后切换到连接指定路由器。
|
||||
password 为空时按开放网络(key_mgmt=NONE)写入。
|
||||
Returns:
|
||||
(ok: bool, err_msg: str)
|
||||
"""
|
||||
ssid = (ssid or "").strip()
|
||||
password = (password or "").strip()
|
||||
if not ssid:
|
||||
return False, "SSID 为空"
|
||||
|
||||
conf_path = "/etc/wpa_supplicant.conf"
|
||||
ssid_file = "/boot/wifi.ssid"
|
||||
pass_file = "/boot/wifi.pass"
|
||||
|
||||
def _write_text(path: str, content: str):
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
|
||||
try:
|
||||
if password:
|
||||
net_conf = os.popen(f'wpa_passphrase "{ssid}" "{password}"').read()
|
||||
if "network={" not in net_conf:
|
||||
return False, "wpa_passphrase 失败"
|
||||
else:
|
||||
esc = ssid.replace("\\", "\\\\").replace('"', '\\"')
|
||||
net_conf = (
|
||||
"network={\n"
|
||||
f' ssid="{esc}"\n'
|
||||
" key_mgmt=NONE\n"
|
||||
"}\n"
|
||||
)
|
||||
_write_text(
|
||||
conf_path,
|
||||
"ctrl_interface=/var/run/wpa_supplicant\n"
|
||||
"update_config=1\n\n"
|
||||
+ net_conf,
|
||||
)
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
try:
|
||||
_write_text(ssid_file, ssid)
|
||||
_write_text(pass_file, password)
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
if restart_service:
|
||||
try:
|
||||
os.system("/etc/init.d/S30wifi restart")
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
self.logger.info(f"[WIFI] persist_sta_credentials: 已写入并重启 S30wifi, ssid={ssid!r}")
|
||||
else:
|
||||
self.logger.info(f"[WIFI] persist_sta_credentials: 已写入凭证(未重启 S30wifi), ssid={ssid!r}")
|
||||
return True, ""
|
||||
|
||||
def disconnect_wifi(self):
|
||||
"""断开WiFi连接并清理资源"""
|
||||
if self._wifi_socket:
|
||||
|
||||
Reference in New Issue
Block a user