Просмотр исходного кода

fix(nextion): make screen refresh async and protect shared state

wenhongquan 4 месяцев назад
Родитель
Сommit
5e8c23c507
1 измененных файлов с 89 добавлено и 47 удалено
  1. 89 47
      backend/app.py

+ 89 - 47
backend/app.py

@@ -2,6 +2,7 @@ from flask import Flask, jsonify, request, abort
 from flask_cors import CORS
 from flask_socketio import SocketIO, emit
 import threading
+import queue
 import time
 import json
 import os
@@ -102,6 +103,9 @@ address_config = AddressConfigProtocol(serial_client)
 # Nextion 串口屏实例
 screen_display = NextionDisplay()
 screen_current_panel_index = 0
+screen_lock = threading.Lock()
+screen_refresh_queue = queue.Queue()
+screen_refresh_thread = None
 
 # 初始化 DHT11 传感器(后续在 __main__ 中设置回调并启动)
 dht11_sensor = None
@@ -175,54 +179,74 @@ def _port_status_to_pic(port_state_entry):
     return 3  # CONNECTED
 
 
+def _screen_refresh_worker():
+    """在后台线程中异步刷新 Nextion 屏幕。"""
+    while True:
+        try:
+            item = screen_refresh_queue.get()
+            if item is None:
+                break
+            panel_id = item[0]
+            refresh_screen_panel(panel_id)
+        except Exception as e:
+            logger.error(f"屏幕刷新工作线程异常: {e}")
+        finally:
+            try:
+                screen_refresh_queue.task_done()
+            except Exception:
+                pass
+
+
 def refresh_screen_panel(panel_id):
     """将指定 panel 的数据下发到 Nextion 屏幕。"""
     global screen_current_panel_index
-    panels = get_sorted_panels()
-    if not panels:
-        return False, '没有可用的 panel'
-    panel_ids = [p[0] for p in panels]
-    if panel_id not in panel_ids:
-        return False, f'panel 不存在: {panel_id}'
-    if not screen_display.get_status().get('connected'):
-        return False, '屏幕串口未连接'
-
-    ps = port_state.get(panel_id, {})
-    now = time.time()
-    online_count = sum(1 for pid in panel_ids if device_last_seen.get(pid, 0) > now - 60)
-    idx = panel_ids.index(panel_id)
-    screen_current_panel_index = idx
+    with screen_lock:
+        panels = get_sorted_panels()
+        if not panels:
+            return False, '没有可用的 panel'
+        panel_ids = [p[0] for p in panels]
+        if panel_id not in panel_ids:
+            return False, f'panel 不存在: {panel_id}'
+        if not screen_display.get_status().get('connected'):
+            return False, '屏幕串口未连接'
+
+        ps = port_state.get(panel_id, {})
+        now = time.time()
+        online_count = sum(1 for pid in panel_ids if device_last_seen.get(pid, 0) > now - 60)
+        idx = panel_ids.index(panel_id)
+        screen_current_panel_index = idx
 
-    mqtt_st = mqtt_client.get_status()
-    mqtt_connected = mqtt_st.get('connected', False) if isinstance(mqtt_st, dict) else bool(mqtt_st)
+        mqtt_st = mqtt_client.get_status()
+        mqtt_connected = mqtt_st.get('connected', False) if isinstance(mqtt_st, dict) else bool(mqtt_st)
 
-    delay_ms = NEXTION_CMD_DELAY_MS
+        delay_ms = NEXTION_CMD_DELAY_MS
 
-    screen_display.send_cmd(f't2.txt="{NEXTION_PANEL_NAME_PREFIX}{idx + 1}"', delay_ms=delay_ms)
-    screen_display.send_cmd(f't1.txt="{panel_id}"', delay_ms=delay_ms)
-    screen_display.send_cmd(f't4.txt="{dtu_config.get("firmware_version", "v1.0.0")}"', delay_ms=delay_ms)
+        screen_display.send_cmd(f't2.txt="{NEXTION_PANEL_NAME_PREFIX}{idx + 1}"', delay_ms=delay_ms)
+        screen_display.send_cmd(f't1.txt="{panel_id}"', delay_ms=delay_ms)
+        screen_display.send_cmd(f't4.txt="{dtu_config.get("firmware_version", "v1.0.0")}"', delay_ms=delay_ms)
 
-    mqtt_str = '已连接' if mqtt_connected else '未连接'
-    screen_display.send_cmd(f'g0.txt="MQTT:{mqtt_str} 当前终端数:{online_count}"', delay_ms=delay_ms)
-    screen_display.send_cmd(f'g0.pco={0 if mqtt_connected else 63488}', delay_ms=delay_ms)
+        mqtt_str = '已连接' if mqtt_connected else '未连接'
+        screen_display.send_cmd(f'g0.txt="MQTT:{mqtt_str} 当前终端数:{online_count}"', delay_ms=delay_ms)
+        screen_display.send_cmd(f'g0.pco={0 if mqtt_connected else 63488}', delay_ms=delay_ms)
 
-    for port_id in range(1, 25):
-        pic = _port_status_to_pic(ps.get(port_id, {}))
-        screen_display.send_cmd(f'p{port_id - 1}.pic={pic}', delay_ms=delay_ms)
+        for port_id in range(1, 25):
+            pic = _port_status_to_pic(ps.get(port_id, {}))
+            screen_display.send_cmd(f'p{port_id - 1}.pic={pic}', delay_ms=delay_ms)
 
-    logger.info(f"屏幕已刷新: {panel_id} (终端{idx + 1})")
-    return True, '屏幕已刷新'
+        logger.info(f"屏幕已刷新: {panel_id} (终端{idx + 1})")
+        return True, '屏幕已刷新'
 
 
 def switch_screen_panel(direction):
     """切换当前显示的 panel。"""
-    panels = get_sorted_panels()
-    if not panels:
-        return False, '没有可用的 panel'
     global screen_current_panel_index
-    screen_current_panel_index = (screen_current_panel_index + direction) % len(panels)
-    panel_id = panels[screen_current_panel_index][0]
-    logger.info(f'屏幕切换: 终端{screen_current_panel_index + 1} -> {panel_id}')
+    with screen_lock:
+        panels = get_sorted_panels()
+        if not panels:
+            return False, '没有可用的 panel'
+        screen_current_panel_index = (screen_current_panel_index + direction) % len(panels)
+        panel_id = panels[screen_current_panel_index][0]
+        logger.info(f'屏幕切换: 终端{screen_current_panel_index + 1} -> {panel_id}')
     return refresh_screen_panel(panel_id)
 
 
@@ -431,7 +455,10 @@ def mqtt_status_handler(status):
             panels = get_sorted_panels()
             if panels and screen_display.get_status().get('connected'):
                 try:
-                    refresh_screen_panel(panels[screen_current_panel_index][0])
+                    with screen_lock:
+                        current_idx = screen_current_panel_index
+                    if 0 <= current_idx < len(panels):
+                        screen_refresh_queue.put((panels[current_idx][0],))
                 except Exception as e:
                     logger.error(f"MQTT 状态变化刷新屏幕失败: {e}")
     except Exception as e:
@@ -2154,10 +2181,13 @@ def health_check():
 @app.route('/api/screen/status', methods=['GET'])
 def get_screen_status():
     """获取 Nextion 屏幕状态。"""
-    panels = get_sorted_panels()
-    current_panel_id = None
-    if panels and 0 <= screen_current_panel_index < len(panels):
-        current_panel_id = panels[screen_current_panel_index][0]
+    with screen_lock:
+        panels = get_sorted_panels()
+        current_index = screen_current_panel_index
+        current_panel_id = None
+        if panels and 0 <= current_index < len(panels):
+            current_panel_id = panels[current_index][0]
+        panel_count = len(panels)
     status = screen_display.get_status()
     return jsonify({
         'success': True,
@@ -2165,9 +2195,9 @@ def get_screen_status():
             'connected': status.get('connected', False),
             'port': status.get('port'),
             'baudrate': status.get('baudrate'),
-            'current_panel_index': screen_current_panel_index,
+            'current_panel_index': current_index,
             'current_panel_id': current_panel_id,
-            'panel_count': len(panels)
+            'panel_count': panel_count
         }
     })
 
@@ -2175,10 +2205,13 @@ def get_screen_status():
 @app.route('/api/screen/refresh', methods=['POST'])
 def refresh_screen():
     """手动刷新当前 panel 到屏幕。"""
-    panels = get_sorted_panels()
-    if not panels:
-        return jsonify({'success': False, 'message': '没有可用的 panel'}), 400
-    panel_id = panels[screen_current_panel_index][0]
+    with screen_lock:
+        panels = get_sorted_panels()
+        if not panels:
+            return jsonify({'success': False, 'message': '没有可用的 panel'}), 400
+        if not (0 <= screen_current_panel_index < len(panels)):
+            return jsonify({'success': False, 'message': '当前 panel 索引无效'}), 400
+        panel_id = panels[screen_current_panel_index][0]
     success, message = refresh_screen_panel(panel_id)
     if success:
         return jsonify({'success': True, 'message': message})
@@ -3672,9 +3705,13 @@ if __name__ == '__main__':
                             dtu_publish_panel_status(panel_id, addr, panel_ports)
                             # 如果该 panel 是当前显示的 panel,刷新屏幕
                             panels = get_sorted_panels()
-                            if panels and panels[screen_current_panel_index][0] == panel_id:
+                            trigger_panel_id = None
+                            with screen_lock:
+                                if panels and 0 <= screen_current_panel_index < len(panels) and panels[screen_current_panel_index][0] == panel_id:
+                                    trigger_panel_id = panel_id
+                            if trigger_panel_id:
                                 try:
-                                    refresh_screen_panel(panel_id)
+                                    screen_refresh_queue.put((trigger_panel_id,))
                                 except Exception as e:
                                     logger.error(f"刷新屏幕失败: {e}")
                         else:
@@ -3711,6 +3748,11 @@ if __name__ == '__main__':
             except Exception as e:
                 logger.error(f"Nextion 屏幕初始化异常: {e}")
 
+        # 启动 Nextion 屏幕异步刷新工作线程
+        screen_refresh_thread = threading.Thread(target=_screen_refresh_worker, daemon=True)
+        screen_refresh_thread.start()
+        logger.info("启动 Nextion 屏幕异步刷新线程")
+
         # 启动服务
         socketio.run(
             app,