Prechádzať zdrojové kódy

使用协程方式运行整个程序

mrh 3 rokov pred
rodič
commit
fe288d121d
8 zmenil súbory, kde vykonal 47 pridanie a 133 odobranie
  1. 1 1
      .gitignore
  2. 6 0
      .other-files/readme-heat.md
  3. 20 21
      heat.py
  4. 13 10
      main.py
  5. 0 91
      my_timer.py
  6. 0 1
      mywifi.py
  7. 5 6
      web_server.py
  8. 2 3
      work_led.py

+ 1 - 1
.gitignore

@@ -1,4 +1,4 @@
 .mpyproject.json
 .vscode/
 .other-files
-MicroWebSrv/__pycache__
+MicroWebSrv/__pycache__

+ 6 - 0
.other-files/readme-heat.md

@@ -85,6 +85,12 @@ routeHandlers 这是web网页的路由表
 
 
 
+## JS传送数据回开发板进行控制
+
+进行到这里,程序已经变得复杂起来,有必要优化程序架构。参考:[Python设计模式(第2版)-Chetan Giridhar 吉里德尔-微信读书 (qq.com)](https://weread.qq.com/web/reader/e5c328107159b28fe5c8d02)9.4 现实世界的 MVC模式
+
+
+
 在 index 页面中,windows.onload 获取开发板状态,如 开关、温度、时间
 
 

+ 20 - 21
heat.py

@@ -6,9 +6,8 @@ import micropython
 import gc
 import uasyncio
 from machine import Pin,PWM,ADC
-from web_server import WebSrv
+# from web_server import WebSrv
 from MicroWebSrv.upload_dat import upload
-from my_timer import MyTimer as Timer
 
 def average(series, new_value):
     series.append(new_value)
@@ -25,11 +24,8 @@ class Ntc():
         self.VCC = 3344
         self.temp = 0
         self.temp_list = []
-        self.tim = Timer(-1)
-        self.tim.init(period=200, mode=Timer.PERIODIC,
-                      callback=self.cal_temperature)
 
-    def cal_temperature(self, tim):
+    def cal_temperature(self):
         val_uv = self.adc.read_uv()/1000
         Rt = val_uv / ((self.VCC - val_uv)/10000)
         T1 = 1/(log(Rt/10000)/3950 + 1/(273.15+25)) - 273.15
@@ -58,9 +54,9 @@ class HeatPower():
         self.sw_pin.freq(1000)
         # self.sw_pin.duty(180)
         self.duty = 0.0
-        self.duty_percent(0.7)
         self.status = 0
         self.dat = {'status':0, 'pwr_percent':0}
+        self.duty_percent(0.7)
 
     def duty_percent(self, percent):
         if percent > 1:
@@ -104,40 +100,43 @@ class HeatPower():
             self.ajust_duty(step)
             print('wt:', wt, "step:", step)
         else:
-            step = (40-ct)/100
+            step = (42-ct)/100
             print('ct:', ct, "step:", step)
             self.ajust_duty(step)
 
+wire_ntc = Ntc(34)
+center_ntc = Ntc(36)
+async def cal_ntc():
+    while True:
+        wire_ntc.cal_temperature()
+        center_ntc.cal_temperature()
+        await uasyncio.sleep_ms(200)
 
-def sensor():
-    wire_ntc = Ntc(34)
-    center_ntc = Ntc(36)
+async def sensor():
+    uasyncio.create_task(cal_ntc())
     heat = HeatPower()
-    def heat_status_print():
-        # nonlocal wire_ntc,center_ntc,heat
+    heat.on()
+    while True:
         wire_temp = wire_ntc.get_temperature()
-        # center_temp = 0
         center_temp = center_ntc.get_temperature()
         print("wire_temp:", wire_temp, "\tcenter_temp:", center_temp, '\tduty:', heat.duty)
         heat.ajust_power(wire_temp, center_temp)
-        # heat.ajust_duty(1)
         upload.set_data('heat', heat.dat)
         upload.set_data('ntc', {"wire_temp": wire_temp, 'center_temp':center_temp})
         # 主动垃圾回收是个好习惯,如果没有经常开辟内存,可不用
         gc.collect()
+        await uasyncio.sleep_ms(1000)
 
-    tim = Timer()
-    tim.init(1, 1200, heat_status_print)
         
-    
+
 def test():
-    wire_ntc = Ntc(34,2)
-    center_ntc = Ntc(36,3)
+    wire_ntc = Ntc(34)
+    center_ntc = Ntc(36)
     print("class Ntc:", wire_ntc, center_ntc)
     print("class adc:", wire_ntc.adc, center_ntc.adc)
     print("tim:", wire_ntc.tim, center_ntc.tim)
 
 
 if __name__ == '__main__':
-    sensor()
+    uasyncio.run(sensor())
     # test()

+ 13 - 10
main.py

@@ -1,9 +1,9 @@
 import time
 import uasyncio
 #from mywifi import my_wifi
-from work_led import WorckLed
-import heat
-
+from work_led import work_led_blink
+from heat import sensor
+from web_server import start_server
 class Device():
     _instance = None
     # 单例模式:WiFi实例化只能有一次,实例化多个 mywifi 对象将始终返回同一个-
@@ -14,16 +14,19 @@ class Device():
 
     def __init__(self) -> None:
         print("device init")
-        self.wled= WorckLed(2)
+        # self.wled= WorckLed(2)
 
 
-def main(): 
-    wled= WorckLed(2)
-    
-    heat_power = heat.HeatPower()
-    heat.sensor(heat_power)
-    
+async def main(): 
+    uasyncio.create_task(work_led_blink())
+    uasyncio.create_task(sensor())
+    uasyncio.create_task(start_server())
+    loop = uasyncio.get_event_loop()
+    loop.run_forever()
 
 if __name__ == '__main__':
+    print('run')
+    uasyncio.run(main())
+    print('stop')
     # main()
     pass

+ 0 - 91
my_timer.py

@@ -1,91 +0,0 @@
-import time
-import sys
-from machine import Timer
-# import traceback
-
-class TimerV():
-    _instance = None
-
-    def __new__(cls, *args, **kwargs):
-        if cls._instance is None:
-            cls._instance = super().__new__(cls)
-        return cls._instance   # 返回的是内存地址
-    def __init__(self, id=3) -> None:
-        self._id = id
-        self._tim = Timer(id)
-        self._task_info = {}
-        self._tim.init(period=1, mode=Timer.PERIODIC,callback=self.dispacth)
-        
-    def create_task(self, dict):
-        self._task_info.update(dict)
-        # print("update:", dict)
-
-    def dispacth(self, tim):
-        try:
-            for task_id in list(self._task_info.keys()):
-                task = self._task_info.get(task_id)
-                task['cnt'] += 1
-                if task['cnt'] >= task['period']:
-                    if task['mode'] == 0:
-                        self._task_info.pop(task_id)
-                    else:
-                        task['cnt'] = 0
-                    task['callback'](task['my_timer'])
-        except Exception as e:
-            # print(traceback.format_exception(... *sys.exc_info()))
-            sys.print_exception(e)
-            # print("error: {}:{}".format(__file__, sys._getframe().f_lineno))
-            print("\ntimer %s deinit" % self._id)
-            self._tim.deinit()
-    def stop_task(self, id):
-        if id in self._task_info:
-            # print('stop task:', id)
-            self._task_info.pop(id)
-
-TIMERV = TimerV(3)
-
-class MyTimer():
-    ONE_SHOT = 0  # type: int
-    PERIODIC = 1  # type: int
-
-    def __init__(self, *args):
-        self._task_info = None
-        self._id = None
-
-    def init(self, mode=PERIODIC, period=-1, callback=None):
-        if self._id is not None:
-            self.deinit()
-        self._task_info = {"mode" : mode, "period" : period, "callback" : callback, 'cnt':0, 'my_timer':self}
-        self._id = id(callback)
-        TIMERV.create_task({self._id:self._task_info})
-
-    def deinit(self) -> None:
-        TIMERV.stop_task(self._id)
-
-
-if __name__ == '__main__':
-    class Cal():
-        def __init__(self) -> None:
-            self.c = 9
-
-        def cal(self, tim):
-            self.c += 1
-            tim.init(0, self.c, self.cal)
-        def cal2(self, tim):
-            print('cal2')
-            pass
-    time_start = time.time_ns()  # 记录开始时间
-    c = Cal()
-    print("---- tim ---- ")
-    tim = MyTimer()
-    tim.init(0, 9, c.cal)
-    tim.init(0, 9, c.cal)
-    print("---- tim2 ---- ")
-    tim2 = MyTimer()
-    tim2.init(1, 100, c.cal2)
-    time.sleep_ms(1000)
-    tim.deinit()
-    # tim2.deinit()
-    time_end = time.time_ns()  # 记录结束时间
-    time_sum = time_end - time_start  # 计算的时间差为程序的执行时间,单位为秒/s
-    print("running time:", time_sum / 1000)

+ 0 - 1
mywifi.py

@@ -1,5 +1,4 @@
 import network
-from my_timer import MyTimer as Timer
 # from machine import Timer
 SSID = "Xiaomi_eng"
 # SSID = "Mi11_eng"

+ 5 - 6
web_server.py

@@ -1,7 +1,10 @@
-
+from    _thread     import stack_size
+import uasyncio
+import gc
+import micropython
+from mywifi import wifi_do_work, my_wifi
 from MicroWebSrv.microWebSrv import MicroWebSrv
 from MicroWebSrv.urls import routeHandlers,_acceptWebSocketCallback
-from    _thread     import start_new_thread,stack_size
 
 '''
 ` 实例化web服务器对象
@@ -48,10 +51,6 @@ class MyWebSrv():
         self.srv.Start(threaded=True)
         print("start:", self.ip)
 
-import micropython
-import gc
-import uasyncio
-from mywifi import wifi_do_work, my_wifi
 
 web_srv = MyWebSrv()
 

+ 2 - 3
work_led.py

@@ -1,7 +1,6 @@
 from machine import Pin, PWM
 import time
 from machine import Timer
-from my_timer import MyTimer
 
 class WorckLed:
     def __init__(self, pin_num) -> None:
@@ -21,12 +20,12 @@ class WorckLed:
             self.tim.init(1, 1200, self.blink)
             self.off()
         else:
-            self.tim.init(1, 10, self.blink)
+            self.tim.init(1, 5, self.blink)
             self.on()
 
 # 协程的方式
 import uasyncio
-async def work_led_blink(led=WorckLed(2), on_t=10, off_t=1200):
+async def work_led_blink(led=Pin(2, Pin.OUT), on_t=10, off_t=1200):
     while True:
         led.value(1)
         await uasyncio.sleep_ms(on_t)