Sfoglia il codice sorgente

```
feat(python/mcu_test): 添加随机延时和异步任务处理功能

- 引入random模块用于生成随机延时
- 移除废弃的asyncio事件循环代码
- 将固定延时改为随机延时(1-10秒)
- 添加数据接收中断检测和错误提示
- 实现异步并发执行run和print_all方法
- 添加调试信息打印功能
- 优化程序退出处理机制
```

rambo 1 settimana fa
parent
commit
3c3e546a0b
1 ha cambiato i file con 23 aggiunte e 7 eliminazioni
  1. 23 7
      python/mcu_test.py

+ 23 - 7
python/mcu_test.py

@@ -5,6 +5,7 @@ import serial.tools.list_ports
 # from mcu.base_mode.base import *
 from mcu.SerialIns import SerialIns
 import asyncio
+import random
 
 class Main():
     def __init__(self):
@@ -40,15 +41,12 @@ class Main():
         return False
 
     def run(self):
-        # loop = asyncio.get_event_loop()
-        loop = asyncio.get_event_loop()
-        listen_task = loop.run_in_executor(None, self.print_all())
-        asyncio.gather(listen_task)
         n = 0
         value = 0
         while True:
             value += 1
-            time.sleep(0.05)
+            random_int = random.randint(1, 10)
+            time.sleep(random_int)
             n += 1
             send_data = []
             send_data.extend([0x01, 0x07, 0x01, 0x00, value, 0x05, 0x78, 0x01, 0x90, 0x00, 0x64, 0x00, 0x01, 0x00])
@@ -83,9 +81,11 @@ class Main():
         except:
             return None
     def print_all(self):
+        print("开始打印数据")
         while 1:
             time.sleep(0.01)
             r_data = self.serial_ins.read_cmd()
+            print("接收数据:{}".format(r_data))
             if r_data:
                 r_data = r_data[1:]
                 _r_data = self.serial_ins.change_hex_to_int(r_data)
@@ -97,9 +97,25 @@ class Main():
                 if value == 1 or value == self.last_value + 1:
                     self.last_value = value
                 else:
+                    print("数据接收有中断")
                     raise "数据接收有中断"
-
+            else:
+                # print("数据未获取到")
+                pass
 
 if __name__ == '__main__':
     main =  Main()
-    main.run()
+    async def run_tasks():
+        loop = asyncio.get_event_loop()
+        
+        # 创建任务
+        task1 = loop.run_in_executor(None, main.run)
+        task2 = loop.run_in_executor(None, main.print_all)
+        
+        # 等待两个任务(它们会无限运行,除非发生异常)
+        await asyncio.gather(task1, task2)
+    
+    try:
+        asyncio.run(run_tasks())
+    except KeyboardInterrupt:
+        print("程序被用户中断")