fix comment
This commit is contained in:
48
src/app.py
48
src/app.py
@@ -1,47 +1,49 @@
|
|||||||
# ESP8266天气站主程序
|
# ESP8266天气站主程序
|
||||||
# 首先尝试连接已保存的WiFi,失败则启动CaptivePortal进行配置
|
# 首先尝试连接已保存的WiFi,失败则启动CaptivePortal进行配置
|
||||||
|
|
||||||
import gc, time, sys, machine
|
import gc
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import machine
|
||||||
|
|
||||||
# 使用全局的WiFiManager实例
|
# 使用全局的WiFiManager实例
|
||||||
from wifi_manager import wifi_manager
|
from wifi_manager import wifi_manager
|
||||||
|
|
||||||
|
print("Trying to connect to saved WiFi network...")
|
||||||
|
|
||||||
print("尝试连接已保存的WiFi网络...")
|
|
||||||
|
|
||||||
if wifi_manager.connect():
|
if wifi_manager.connect():
|
||||||
# 连接成功
|
# 连接成功
|
||||||
ip = wifi_manager.get_ip()
|
ip = wifi_manager.get_ip()
|
||||||
print(f"WiFi连接成功,IP地址: {ip}")
|
print(f"WiFi connected successfully, IP address: {ip}")
|
||||||
|
|
||||||
# 在这里可以添加主应用程序代码
|
# 在这里可以添加主应用程序代码
|
||||||
# 例如:启动天气数据获取和显示
|
# 例如:启动天气数据获取和显示
|
||||||
print("启动主应用程序...")
|
print("Starting main application...")
|
||||||
|
|
||||||
# 示例:保持连接
|
# 示例:保持连接
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
# 检查连接状态
|
# 检查连接状态
|
||||||
if not wifi_manager.is_connected():
|
if not wifi_manager.is_connected():
|
||||||
print("WiFi连接断开")
|
print("WiFi connection lost")
|
||||||
break
|
break
|
||||||
|
|
||||||
# 每3秒报告一次状态
|
# 每3秒报告一次状态
|
||||||
time.sleep(3)
|
time.sleep(3)
|
||||||
gc.collect()
|
gc.collect()
|
||||||
print(f"正常运行中,IP: {ip}, 可用内存: {gc.mem_free()} bytes")
|
print(f"Running normally, IP: {ip}, Free memory: {gc.mem_free()} bytes")
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("用户中断")
|
print("User interrupted")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
wifi_manager.disconnect()
|
wifi_manager.disconnect()
|
||||||
print("应用程序结束")
|
print("Application ended")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# 连接失败,启动CaptivePortal进行WiFi配置
|
# 连接失败,启动CaptivePortal进行WiFi配置
|
||||||
print("无法连接到WiFi,启动CaptivePortal进行配置")
|
print("Failed to connect to WiFi, starting CaptivePortal for configuration")
|
||||||
|
|
||||||
from captive_portal import CaptivePortal
|
from captive_portal import CaptivePortal
|
||||||
|
|
||||||
@@ -52,41 +54,41 @@ else:
|
|||||||
if portal.start():
|
if portal.start():
|
||||||
# clear
|
# clear
|
||||||
del portal
|
del portal
|
||||||
sys.modules.pop('CaptivePortal', None)
|
sys.modules.pop("CaptivePortal", None)
|
||||||
sys.modules.pop('captive_dns', None)
|
sys.modules.pop("captive_dns", None)
|
||||||
sys.modules.pop('captive_http', None)
|
sys.modules.pop("captive_http", None)
|
||||||
sys.modules.pop('server_base', None)
|
sys.modules.pop("server_base", None)
|
||||||
gc.collect()
|
gc.collect()
|
||||||
# CaptivePortal成功配置并连接
|
# CaptivePortal成功配置并连接
|
||||||
print("WiFi配置成功并已连接")
|
print("WiFi configured successfully and connected")
|
||||||
|
|
||||||
# 在这里可以添加主应用程序代码
|
# 在这里可以添加主应用程序代码
|
||||||
print("启动主应用程序...")
|
print("Starting main application...")
|
||||||
|
|
||||||
# 示例:保持连接
|
# 示例:保持连接
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
# 检查连接状态
|
# 检查连接状态
|
||||||
if not wifi_manager.is_connected():
|
if not wifi_manager.is_connected():
|
||||||
print("WiFi连接断开")
|
print("WiFi connection lost")
|
||||||
break
|
break
|
||||||
|
|
||||||
# 每3秒报告一次状态
|
# 每3秒报告一次状态
|
||||||
time.sleep(3)
|
time.sleep(3)
|
||||||
gc.collect()
|
gc.collect()
|
||||||
print(f"正常运行中,可用内存: {gc.mem_free()} bytes")
|
print(f"Running normally, Free memory: {gc.mem_free()} bytes")
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("用户中断")
|
print("User interrupted")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
wifi_manager.disconnect()
|
wifi_manager.disconnect()
|
||||||
print("应用程序结束")
|
print("Application ended")
|
||||||
else:
|
else:
|
||||||
print("CaptivePortal未能成功建立连接")
|
print("CaptivePortal failed to establish connection")
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("用户中断")
|
print("User interrupted")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
time.sleep(3)
|
time.sleep(3)
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ class HTTPServer(BaseServer):
|
|||||||
self.sock.listen(2)
|
self.sock.listen(2)
|
||||||
self.sock.setblocking(False)
|
self.sock.setblocking(False)
|
||||||
|
|
||||||
#@micropython.native
|
# @micropython.native
|
||||||
def handle(self, sock, event, others):
|
def handle(self, sock, event, others):
|
||||||
if sock is self.sock:
|
if sock is self.sock:
|
||||||
# client connecting on port 80, so spawn off a new
|
# client connecting on port 80, so spawn off a new
|
||||||
@@ -125,9 +125,9 @@ class HTTPServer(BaseServer):
|
|||||||
config.set("password", password)
|
config.set("password", password)
|
||||||
config.set("city", city)
|
config.set("city", city)
|
||||||
if config.write():
|
if config.write():
|
||||||
print("配置保存成功")
|
print("Configuration saved successfully")
|
||||||
else:
|
else:
|
||||||
print("配置保存失败,数据无效")
|
print("Failed to save configuration, invalid data")
|
||||||
|
|
||||||
# 重定向local_ip
|
# 重定向local_ip
|
||||||
headers = (
|
headers = (
|
||||||
@@ -148,7 +148,7 @@ class HTTPServer(BaseServer):
|
|||||||
|
|
||||||
json_data = ujson.dumps({"networks": networks})
|
json_data = ujson.dumps({"networks": networks})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"扫描网络时出错: {e}")
|
print(f"Error scanning networks: {e}")
|
||||||
json_data = ujson.dumps({"networks": []})
|
json_data = ujson.dumps({"networks": []})
|
||||||
|
|
||||||
headers = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nAccess-Control-Allow-Origin: *\r\n"
|
headers = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nAccess-Control-Allow-Origin: *\r\n"
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ class CaptivePortal:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
# WiFi Connection failed but keep credentials for future retries
|
# WiFi Connection failed but keep credentials for future retries
|
||||||
print("连接失败但保留配置,可以稍后重试")
|
print("Connection failed but keeping configuration for retry")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ class Config:
|
|||||||
|
|
||||||
with open(self.CONFIG_FILE, "w") as f:
|
with open(self.CONFIG_FILE, "w") as f:
|
||||||
ujson.dump(save_data, f)
|
ujson.dump(save_data, f)
|
||||||
print(f"写入配置到 {self.CONFIG_FILE}")
|
print(f"Writing configuration to {self.CONFIG_FILE}")
|
||||||
# 写入后重新加载配置
|
# 写入后重新加载配置
|
||||||
return self.load()
|
return self.load()
|
||||||
return False
|
return False
|
||||||
@@ -45,11 +45,11 @@ class Config:
|
|||||||
loaded_data = ujson.load(f)
|
loaded_data = ujson.load(f)
|
||||||
|
|
||||||
self.config_data.update(loaded_data)
|
self.config_data.update(loaded_data)
|
||||||
print(f"从 {self.CONFIG_FILE} 加载配置")
|
print(f"Loading configuration from {self.CONFIG_FILE}")
|
||||||
|
|
||||||
# 如果核心配置不完整,可能需要清除文件
|
# 如果核心配置不完整,可能需要清除文件
|
||||||
if not self.is_valid():
|
if not self.is_valid():
|
||||||
print("配置不完整,清除配置文件")
|
print("Configuration incomplete, clearing config file")
|
||||||
self.remove()
|
self.remove()
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ class WiFiManager:
|
|||||||
self._interface_initialized = True
|
self._interface_initialized = True
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"激活WiFi接口失败: {e}")
|
print(f"Failed to activate WiFi interface: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _safe_connect_check(self):
|
def _safe_connect_check(self):
|
||||||
@@ -52,17 +52,17 @@ class WiFiManager:
|
|||||||
"""尝试连接到WiFi"""
|
"""尝试连接到WiFi"""
|
||||||
# 加载配置
|
# 加载配置
|
||||||
if not self.config.load().is_valid():
|
if not self.config.load().is_valid():
|
||||||
print("没有有效的WiFi配置")
|
print("No valid WiFi configuration")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
ssid = self.config.get("ssid")
|
ssid = self.config.get("ssid")
|
||||||
password = self.config.get("password")
|
password = self.config.get("password")
|
||||||
|
|
||||||
if not ssid or not password:
|
if not ssid or not password:
|
||||||
print("SSID或密码为空")
|
print("SSID or password is empty")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
print(f"正在尝试连接到SSID: {ssid}")
|
print(f"Trying to connect to SSID: {ssid}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 确保接口处于活动状态
|
# 确保接口处于活动状态
|
||||||
@@ -83,24 +83,24 @@ class WiFiManager:
|
|||||||
if self._safe_connect_check():
|
if self._safe_connect_check():
|
||||||
ip = self.get_ip()
|
ip = self.get_ip()
|
||||||
if ip:
|
if ip:
|
||||||
print(f"连接成功! IP: {ip}")
|
print(f"Connected successfully! IP: {ip}")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
print(f"连接尝试 {attempts}/{self.MAX_CONN_ATTEMPTS}...")
|
print(f"Connection attempt {attempts}/{self.MAX_CONN_ATTEMPTS}...")
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
attempts += 1
|
attempts += 1
|
||||||
|
|
||||||
# 连接失败
|
# 连接失败
|
||||||
print(f"连接失败: {ssid}")
|
print(f"Connection failed: {ssid}")
|
||||||
self.clear_config()
|
self.clear_config()
|
||||||
try:
|
try:
|
||||||
print(f"WLAN状态: {self.sta_if.status()}")
|
print(f"WLAN status: {self.sta_if.status()}")
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
return False
|
return False
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"连接过程中发生错误: {e}")
|
print(f"Error occurred during connection: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def disconnect(self):
|
def disconnect(self):
|
||||||
@@ -109,9 +109,9 @@ class WiFiManager:
|
|||||||
if self._safe_connect_check():
|
if self._safe_connect_check():
|
||||||
self.sta_if.disconnect()
|
self.sta_if.disconnect()
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
print("已断开WiFi连接")
|
print("WiFi connection disconnected")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"断开连接时出错: {e}")
|
print(f"Error disconnecting: {e}")
|
||||||
|
|
||||||
def scan_networks(self):
|
def scan_networks(self):
|
||||||
"""扫描可用的WiFi网络"""
|
"""扫描可用的WiFi网络"""
|
||||||
@@ -140,24 +140,24 @@ class WiFiManager:
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"扫描WiFi网络时出错: {e}")
|
print(f"Error scanning WiFi networks: {e}")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def reset(self):
|
def reset(self):
|
||||||
"""重置WiFi配置"""
|
"""重置WiFi配置"""
|
||||||
try:
|
try:
|
||||||
self.config.remove()
|
self.config.remove()
|
||||||
print("WiFi配置已重置")
|
print("WiFi configuration has been reset")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"重置配置时出错: {e}")
|
print(f"Error resetting configuration: {e}")
|
||||||
|
|
||||||
def clear_config(self):
|
def clear_config(self):
|
||||||
"""清除WiFi配置(可选操作)"""
|
"""清除WiFi配置(可选操作)"""
|
||||||
try:
|
try:
|
||||||
self.config.set("ssid", None)
|
self.config.set("ssid", None)
|
||||||
print("WiFi配置已临时清空")
|
print("WiFi configuration temporarily cleared")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"清除配置时出错: {e}")
|
print(f"Error clearing configuration: {e}")
|
||||||
|
|
||||||
|
|
||||||
# 全局WiFi管理器实例
|
# 全局WiFi管理器实例
|
||||||
|
|||||||
Reference in New Issue
Block a user