Files
iot-interphone/boot.py
2025-04-27 22:10:10 +08:00

50 lines
1.4 KiB
Python

import socket
import time
from machine import reset, Pin, Timer # 添加 Timer
import _thread
import gc
import network
import system
import shared_vars
gc.enable()
# 启动看门狗线程
_thread.start_new_thread(system.watchdog_thread, ())
# 启动接收数据的线程
_thread.start_new_thread(system.websocket_receive_thread, ())
def ws_client():
try:
# 尝试连接 WiFi
sta_if = system.connect_to_stored_wifi()
print(f"连接到 WebSocket 服务器 {shared_vars.WS_HOST}:{shared_vars.WS_PORT}...")
shared_vars.WS_SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shared_vars.WS_SOCK.connect((shared_vars.WS_HOST, shared_vars.WS_PORT))
print("连接成功")
# 进行 WebSocket 握手
system.websocket_handshake()
while True:
time.sleep(30)
system.send_text(shared_vars.WS_SOCK, '{"action":"sys.ping"}')
system.reset_watchdog() # 重置看门狗
except OSError as e:
print(f"连接异常: {str(e)}")
if 'sta_if' in locals():
sta_if.active(False)
time.sleep(5)
reset()
except Exception as e:
print(f"发生错误:", e)
shared_vars.WS_SOCK.close()
time.sleep(5)
reset()
if __name__ == "__main__":
# 运行主函数
ws_client()
else:
# 作为模块导入时的处理逻辑
pass