5 Commits
Author SHA1 Message Date
linyimin f0df9ad915 fix: 重连时间设置更小 2026-07-31 14:09:11 +08:00
linyimin 3fcd38f417 fix: 4g通讯 2026-07-31 13:59:48 +08:00
linyimin abbf30d7c0 pref: wifi连接成功重新登录 2026-06-25 12:17:58 +08:00
linyimin 5cf752bb3f fix: maixcam wifi连接 2026-06-25 12:02:39 +08:00
linyimin 6d8de56bfa fix: maixcam wifi连接 2026-06-25 11:02:19 +08:00
6 changed files with 89 additions and 40 deletions
+1 -3
View File
@@ -1,6 +1,6 @@
id: t11 id: t11
name: t11 name: t11
version: 2.15.16 version: 2.15.18
author: t11 author: t11
icon: '' icon: ''
desc: t11 desc: t11
@@ -18,8 +18,6 @@ files:
- laser_manager.py - laser_manager.py
- logger_manager.py - logger_manager.py
- main.py - main.py
- model_270139.cvimodel
- model_270139.mud
- network.py - network.py
- ota_curl.sh - ota_curl.sh
- ota_manager.py - ota_manager.py
+7 -6
View File
@@ -76,10 +76,11 @@ class ATClient:
""" """
expect_b = expect.encode() if isinstance(expect, str) else expect expect_b = expect.encode() if isinstance(expect, str) else expect
with self._cmd_lock: with self._cmd_lock:
# 初始化等待 with self._q_lock:
self._waiting = True # 初始化等待
self._expect = expect_b self._waiting = True
self._resp = b"" self._expect = expect_b
self._resp = b""
# 发送 # 发送
if cmd: if cmd:
@@ -300,8 +301,8 @@ class ATClient:
if len(self._rx) > 512 * 1024: if len(self._rx) > 512 * 1024:
self._rx = self._rx[-256 * 1024:] self._rx = self._rx[-256 * 1024:]
else: else:
if len(self._rx) > 16384: if len(self._rx) > 32768:
self._rx = self._rx[-4096:] self._rx = self._rx[-16384:]
+1 -1
View File
@@ -24,7 +24,7 @@ TRIANGLE_DETECT_SCALE = 0.4
# SERVER_IP = "stcp.shelingxingqiu.com" # SERVER_IP = "stcp.shelingxingqiu.com"
SERVER_IP = "www.shelingxingqiu.com" SERVER_IP = "www.shelingxingqiu.com"
SERVER_PORT = 50005 SERVER_PORT = 50005
HEARTBEAT_INTERVAL = 15 # 心跳间隔(秒) HEARTBEAT_INTERVAL = 5 # 心跳间隔(秒)
# WiFi 质量评估(开机先尝试 WiFi;质量差且 4G 可用则切到 4G,本次上电直至关机锁定 4G) # WiFi 质量评估(开机先尝试 WiFi;质量差且 4G 可用则切到 4G,本次上电直至关机锁定 4G)
WIFI_QUALITY_RTT_SAMPLES = 3 # 到业务服务器 TCP 建连耗时采样次数,取中位数 WIFI_QUALITY_RTT_SAMPLES = 3 # 到业务服务器 TCP 建连耗时采样次数,取中位数
+76 -28
View File
@@ -474,10 +474,10 @@ class NetworkManager:
def select_network(self, prefer_wifi=None): def select_network(self, prefer_wifi=None):
""" """
自动选择网络(WiFi优先) 自动选择网络(WiFi优先)
Args: Args:
prefer_wifi: 是否优先使用WiFiNone表示使用默认策略) prefer_wifi: 是否优先使用WiFiNone表示使用默认策略)
Returns: Returns:
"wifi""4g" 或 None(无可用网络) "wifi""4g" 或 None(无可用网络)
""" """
@@ -624,16 +624,21 @@ class NetworkManager:
password = inner_data.get("password") password = inner_data.get("password")
ota_res_url = inner_data.get("url") ota_res_url = inner_data.get("url")
try: try:
ip, err = self.connect_wifi(ssid, password, persist=False, timeout_s=15, verify_host=None, verify_port=None) for _f in ("/etc/wpa_supplicant.conf", "/boot/wpa_supplicant.conf", "/boot/wifi.ssid", "/boot/wifi.pass"):
if err: try:
raise RuntimeError(err) os.remove(_f)
except OSError:
pass
w = network.wifi.Wifi()
e = w.connect(ssid, password, wait=True, timeout=15)
err.check_raise(e, "connect wifi failed")
if self.logger: if self.logger:
self.logger.info(f"[ota] Connect success, got ip{ip}") self.logger.info(f"[ota] Connect success, got ip{w.get_ip()}")
self.safe_enqueue( self.safe_enqueue(
{ {
"cmd": 300, "cmd": 300,
"result": "ota start...", "result": "ota start...",
"wifi": ip, "wifi": w.get_ip(),
}, },
2, 2,
) )
@@ -643,7 +648,7 @@ class NetworkManager:
{ {
"cmd": 300, "cmd": 300,
"result": "success", "result": "success",
"wifi": ip, "wifi": w.get_ip(),
}, },
2, 2,
) )
@@ -665,19 +670,29 @@ class NetworkManager:
ssid = inner_data.get("ssid") ssid = inner_data.get("ssid")
password = inner_data.get("password") password = inner_data.get("password")
try: try:
ip, err = self.connect_wifi(ssid, password, persist=False, timeout_s=15, verify_host=None, verify_port=None) for _f in ("/etc/wpa_supplicant.conf", "/boot/wpa_supplicant.conf", "/boot/wifi.ssid", "/boot/wifi.pass"):
if err: try:
raise RuntimeError(err) os.remove(_f)
except OSError:
pass
w = network.wifi.Wifi()
e = w.connect(ssid, password, wait=True, timeout=15)
err.check_raise(e, "connect wifi failed")
if self.logger: if self.logger:
self.logger.info(f"[conn wifi] Connect success, got ip{ip}") self.logger.info(f"[ota] Connect success, got ip{w.get_ip()}")
self.safe_enqueue( self.safe_enqueue(
{ {
"cmd": 600, "cmd": 600,
"result": "success", "result": "success",
"wifi": ip, "wifi": w.get_ip(),
}, },
2, 2,
) )
self._session_force_4g = False
self.disconnect_server()
self._tcp_connected = False
self._network_type = None
self.logger.info("[conn wifi] WiFi已连接,等待主循环重新登录")
except Exception as e: except Exception as e:
self.logger.error(f"cmd600 失败: {e}") self.logger.error(f"cmd600 失败: {e}")
self.safe_enqueue( self.safe_enqueue(
@@ -697,7 +712,7 @@ class NetworkManager:
def connect_server(self): def connect_server(self):
""" """
连接到服务器(自动选择WiFi或4G) 连接到服务器(自动选择WiFi或4G)
Returns: Returns:
bool: 是否连接成功 bool: 是否连接成功
""" """
@@ -706,7 +721,7 @@ class NetworkManager:
if self._network_type == "wifi": if self._network_type == "wifi":
return self._check_wifi_connection() return self._check_wifi_connection()
elif self._network_type == "4g": elif self._network_type == "4g":
return True # 4G连接状态由AT命令维护 return self._check_4g_connection()
return False return False
# 自动选择网络 # 自动选择网络
@@ -723,6 +738,37 @@ class NetworkManager:
return self._connect_tcp_via_4g() return self._connect_tcp_via_4g()
return False return False
def _check_4g_connection(self):
"""检查4G TCP连接是否仍然有效(通过查询PDP地址验证网络附着状态)"""
try:
atc = hardware_manager.at_client
if atc is None:
return False
if not self._uart4g_lock.acquire(timeout=3000):
# 获取锁超时说明有其他操作在进行,视为连接仍有效
return True
try:
r = atc.send("AT+CGPADDR=1", "OK", 3000)
m = re.search(r'\+CGPADDR:\s*1,"([^"]+)"', r)
ip = m.group(1) if m else ""
if ip and ip != "0.0.0.0":
return True
# 无IP或IP无效,尝试重新激活PDP
self.logger.warning("[4G-TCP] PDP地址无效,尝试重新激活")
atc.send("AT+MIPCALL=1,1", "OK", 15000)
r2 = atc.send("AT+CGPADDR=1", "OK", 3000)
m2 = re.search(r'\+CGPADDR:\s*1,"([^"]+)"', r2)
ip2 = m2.group(1) if m2 else ""
if ip2 and ip2 != "0.0.0.0":
return True
self.logger.error("[4G-TCP] 重新激活PDP仍无有效IP,连接已断开")
return False
finally:
self._uart4g_lock.release()
except Exception as e:
self.logger.warning(f"[4G-TCP] 连接检查异常: {e}")
return True # 异常时不误判断线
def _wrap_wifi_tls(self, plain_sock, hostname): def _wrap_wifi_tls(self, plain_sock, hostname):
""" """
在已建立的 TCP socket 上做 TLSWiFi 走主机 ssl 库;4G 仍用模组 AT+SSL)。 在已建立的 TCP socket 上做 TLSWiFi 走主机 ssl 库;4G 仍用模组 AT+SSL)。
@@ -973,11 +1019,11 @@ class NetworkManager:
def tcp_send_raw(self, data: bytes, max_retries=2) -> bool: def tcp_send_raw(self, data: bytes, max_retries=2) -> bool:
""" """
统一的TCP发送接口(自动选择WiFi或4G) 统一的TCP发送接口(自动选择WiFi或4G)
Args: Args:
data: 要发送的数据 data: 要发送的数据
max_retries: 最大重试次数 max_retries: 最大重试次数
Returns: Returns:
bool: 是否发送成功 bool: 是否发送成功
""" """
@@ -1070,6 +1116,8 @@ class NetworkManager:
total += n total += n
hardware_manager.uart4g.write(b"\x1A") hardware_manager.uart4g.write(b"\x1A")
with hardware_manager.at_client._q_lock:
hardware_manager.at_client._rx = b""
r = hardware_manager.at_client.send("", "OK", 8000) r = hardware_manager.at_client.send("", "OK", 8000)
if ("SEND OK" in r) or ("OK" in r) or ("+MIPSEND" in r): if ("SEND OK" in r) or ("OK" in r) or ("+MIPSEND" in r):
return True return True
@@ -1148,10 +1196,10 @@ class NetworkManager:
def receive_tcp_data_via_wifi(self, timeout_ms=100): def receive_tcp_data_via_wifi(self, timeout_ms=100):
""" """
通过WiFi接收TCP数据 通过WiFi接收TCP数据
Args: Args:
timeout_ms: 超时时间(毫秒) timeout_ms: 超时时间(毫秒)
Returns: Returns:
bytes: 接收到的数据,如果没有数据则返回 b"" bytes: 接收到的数据,如果没有数据则返回 b""
""" """
@@ -1189,7 +1237,7 @@ class NetworkManager:
def _upload_log_file(self, upload_url, wifi_ssid=None, wifi_password=None, include_rotated=True, max_files=None, def _upload_log_file(self, upload_url, wifi_ssid=None, wifi_password=None, include_rotated=True, max_files=None,
archive_format="tgz"): archive_format="tgz"):
"""上传日志文件到指定URL """上传日志文件到指定URL
Args: Args:
upload_url: 上传目标URL,例如 "https://example.com/upload/" upload_url: 上传目标URL,例如 "https://example.com/upload/"
wifi_ssid: WiFi SSID(可选,如果未连接WiFi则尝试连接) wifi_ssid: WiFi SSID(可选,如果未连接WiFi则尝试连接)
@@ -1197,7 +1245,7 @@ class NetworkManager:
include_rotated: 是否包含轮转日志(app.log.1 等) include_rotated: 是否包含轮转日志(app.log.1 等)
max_files: 最多打包多少个日志文件(包含 app.log 本身),None=按 backupCount 自动推断 max_files: 最多打包多少个日志文件(包含 app.log 本身),None=按 backupCount 自动推断
archive_format: 打包格式:tgz 或 zip archive_format: 打包格式:tgz 或 zip
Note: Note:
该功能仅在 WiFi 连接时可用,4G 网络暂不支持文件上传 该功能仅在 WiFi 连接时可用,4G 网络暂不支持文件上传
""" """
@@ -1784,7 +1832,7 @@ class NetworkManager:
continue continue
if not self.connect_server(): if not self.connect_server():
time.sleep_ms(5000) time.sleep_ms(1000)
continue continue
# 发送登录包 # 发送登录包
@@ -1805,7 +1853,7 @@ class NetworkManager:
self.disconnect_server() self.disconnect_server()
except: except:
pass pass
time.sleep_ms(2000) time.sleep_ms(500)
continue continue
self.logger.info("➡️ 登录包已发送,等待确认...") self.logger.info("➡️ 登录包已发送,等待确认...")
@@ -2148,7 +2196,7 @@ class NetworkManager:
self.logger.info(f"password: {password}") self.logger.info(f"password: {password}")
ota_manager._start_update_thread() ota_manager._start_update_thread()
self._spawn_cmd_thread(ota_manager.handle_wifi_and_update, self._spawn_cmd_thread(ota_manager.handle_wifi_and_update,
(ssid, password, ota_url)) (ssid, password, ota_url))
elif inner_cmd == 6: elif inner_cmd == 6:
try: try:
ip = os.popen( ip = os.popen(
@@ -2294,8 +2342,8 @@ class NetworkManager:
pass pass
break break
else: else:
# 不立即断开,让下一轮心跳再试;同时缩短一点等待,提升恢复速度 # 不立即断开,让下一轮心跳再试
time.sleep_ms(200) time.sleep_ms(50)
continue continue
else: else:
send_hartbeat_fail_count = 0 send_hartbeat_fail_count = 0
@@ -2325,8 +2373,8 @@ class NetworkManager:
self._send_event.clear() self._send_event.clear()
self._tcp_connected = False self._tcp_connected = False
self.logger.error("连接异常,2秒后重连...") self.logger.error("连接异常,50ms后重连...")
time.sleep_ms(200) time.sleep_ms(50)
except Exception as e: except Exception as e:
# TCP主循环的顶层异常捕获,防止线程静默退出 # TCP主循环的顶层异常捕获,防止线程静默退出
+3 -1
View File
@@ -26,4 +26,6 @@
# 2.15.13 优化算法 # 2.15.13 优化算法
# 2.15.14 优化算法 # 2.15.14 优化算法
# 2.15.15 优化wifi连接 # 2.15.15 优化wifi连接
# 2.15.16 修复wifi连接问题 # 2.15.16 修复wifi连接问题
# 2.15.17 修复wifi连接问题
# 2.15.18 wifi连接成功重新登录
+1 -1
View File
@@ -4,6 +4,6 @@
应用版本号 应用版本号
每次 OTA 更新时,只需要更新这个文件中的版本号 每次 OTA 更新时,只需要更新这个文件中的版本号
""" """
VERSION = '2.15.16' VERSION = '2.15.18'