Browse Source

初步实现网页JS显示,待完善架构《Python 设计模式》

mrh 3 năm trước cách đây
mục cha
commit
bf9d0a135b

+ 1 - 0
.gitignore

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

+ 66 - 5
.other-files/readme-heat.md

@@ -56,13 +56,52 @@ routeHandlers 这是web网页的路由表
 
 > 参考《web全栈开发:从入门到实践》9.5 从服务器获取数据给前端
 
-TODO
+**访问 index.html**
+
+注意:在esp32中不能使用 '\\'作为文件路径,应该使用 '/',否则地址识别不出来
+
+文件路径:/MicroWebSrv/web_file/index.html
+
+设置 webPath='MicroWebSrv/web_files'
+
+启动服务器
+
+```Python
+    web_srv.ip = my_wifi.get_wifi_addr()
+    web_srv.web_path = '/MicroWebSrv/web_files'
+    web_srv.start_server()
+```
+
+以上设置,浏览器输入 ip 地址,即可进入index界面
+
+想要index自动加载js、CSS文件,直接在 index 源路径写上相对于文件夹 web_files 的js文件路径:
+
+```
+<!-- / 表示根目录 -->
+<!-- MicroWebSrv\web_files\js\heat.js 填写相对路径: -->
+<script type="text/javascript" src="/js/heat.js"> </script>
+<img id="heat-sw" src='img/switch_off.png' alt="on/off">
+```
+
+
 
 在 index 页面中,windows.onload 获取开发板状态,如 开关、温度、时间
 
 
 
-# 开发板
+## 常见问题
+
+**microWebSrv 开启线程堆栈超出:**
+
+开启线程服务器前,可先设置线程堆栈大小
+
+![image-20220905190339190](F:\Engineer\Engineer_sync\my-document\.Typora-img\readme-heat\image-20220905190339190.png)
+
+
+
+# 硬件
+
+## 开发板
 
 参考:
 
@@ -72,7 +111,7 @@ https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/hw-reference/esp3
 
 
 
-## esp32 引脚图
+### esp32 引脚图
 
 ![img](https://img-blog.csdnimg.cn/20210717100620172.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTY1MjQ0NA==,size_16,color_FFFFFF,t_70)
 
@@ -82,11 +121,11 @@ https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/hw-reference/esp3
 
 
 
-## ADC
+### ADC
 
 MicroPython 参考:http://docs.micropython.org/en/latest/esp32/quickref.html#adc-analog-to-digital-conversion
 
-### 基准电压
+#### 基准电压
 
 ADC的基准电压是1.8V,因此接3.3V分压光敏电阻,很难达到1.8V以下
 
@@ -169,3 +208,25 @@ T=273.15+25
 
 
 34 + 13*2
+
+
+
+## 发热电阻
+
+45℃, 24欧姆
+
+55摄氏度 23欧姆
+
+功率 = 12*12 / 24 = 6W
+
+
+
+### 升降压模块
+
+17 * 17 / 24 = 12W
+
+25 * 25 / 24 = 26W, 电流 = 25/24 = 1A
+
+
+
+20V最大功率输出时,电流0.834,铁丝维持在92℃左右,中心温度42.5

+ 2 - 1
.other-files/run-rshell.ps1

@@ -2,4 +2,5 @@ $ENV_PATH="F:\Engineer\Engineer_sync\one-chip-computer\micropython\env-python-3.
 $Env:path=";$ENV_PATH;$ENV_PATH\Scripts;"+$Env:Path  
 Python -V
 pip -V
-cd $PSScriptRoot\..
+cd $PSScriptRoot\..
+rshell -p COM4

+ 2 - 3
.other-files/test.py

@@ -1,10 +1,9 @@
-import micropython
-print(micropython.mem_info())
 
 # 垃圾回收
+import micropython
 import gc
 gc.collect()
-print(gc.mem_info())
+print(micropython.mem_info())
 gc.threshold(gc.mem_free())
 
 

+ 2 - 2
MicroWebSrv/upload_dat.py

@@ -1,13 +1,13 @@
 import json
 class Upload():
     def __init__(self) -> None:
-        self.dat = {'heat_status':0, 'wire_temp': 0, 'center_temp':0, "run_time":0}
+        self.dat = {}
     
     def set_data(self, key, value):
         if key in self.dat:
             self.dat[key] = value
         else:
-            self.datx.update({key:value})
+            self.dat.update({key:value})
     
     def get_status(self):
         return json.dumps(self.dat)

+ 51 - 9
MicroWebSrv/urls.py

@@ -1,15 +1,54 @@
-import gc
 from MicroWebSrv.microWebSrv import MicroWebSrv
 
 # ----------------------------------------------------------------------------
 from MicroWebSrv.upload_dat import upload
-@MicroWebSrv.route('/')
-def _httpHandlerRootGet(httpClient, httpResponse) :
-	print('get root')
-	httpResponse.WriteResponseFile(
-		filepath= r'MicroWebSrv\web_files\index.html',
-		contentType	 = "text/html",
-		headers		 = None)
+# @MicroWebSrv.route('/')
+# def _httpHandlerRootGet(httpClient, httpResponse) :
+# 	print('root:')
+# 	httpResponse.WriteResponseFile(
+# 		filepath= r'/MicroWebSrv/web_files/index.html',
+# 		contentType	 = "text/html",
+# 		headers		 = None)
+
+# @MicroWebSrv.route('/js/<index>')
+# @MicroWebSrv.route('/js')
+# def _httpHandlerJsGet(httpClient, httpResponse, args={}) :
+# 	print("httpClient.GetServer():", httpClient.GetServer())
+# 	print("httpClient.GetAddr():", httpClient.GetAddr())
+# 	print("httpClient.GetIPAddr():", httpClient.GetIPAddr())
+# 	print("httpClient.GetPort():", httpClient.GetPort())
+# 	print("httpClient.GetRequestMethod():", httpClient.GetRequestMethod())
+# 	print("httpClient.GetRequestTotalPath():", httpClient.GetRequestTotalPath())
+# 	print("httpClient.GetRequestPath():", httpClient.GetRequestPath())
+# 	print("httpClient.GetRequestQueryString():", httpClient.GetRequestQueryString())
+# 	print("httpClient.GetRequestQueryParams():", httpClient.GetRequestQueryParams())
+# 	print("httpClient.GetRequestHeaders():", httpClient.GetRequestHeaders())
+# 	print("httpClient.GetRequestContentType():", httpClient.GetRequestContentType())
+# 	print("httpClient.GetRequestContentLength():", httpClient.GetRequestContentLength())
+# 	print("httpClient.ReadRequestContent(size=None):", httpClient.ReadRequestContent(size=None))
+# 	print("httpClient.ReadRequestPostedFormData():", httpClient.ReadRequestPostedFormData())
+# 	print("httpClient.ReadRequestContentAsJSON():", httpClient.ReadRequestContentAsJSON())	
+# 	print('args:', args)
+# 	httpResponse.WriteResponseFile(
+# 		filepath= r'/MicroWebSrv/web_files/js/heat.js',
+# 		contentType	 = "application/javascript",
+# 		headers		 = None)
+
+# @MicroWebSrv.route('/css/<index>')
+# def _httpHandlerCssGet(httpClient, httpResponse, args={}) :
+# 	print('args:', args)
+# 	httpResponse.WriteResponseFile(
+# 		filepath= r'/MicroWebSrv/web_files/js/heat.js',
+# 		contentType	 = "application/javascript",
+# 		headers		 = None)
+
+# @MicroWebSrv.route('/img/<index>')
+# def _httpHandlerImgGet(httpClient, httpResponse, args={}) :
+# 	print('args:', args)
+# 	httpResponse.WriteResponseFile(
+# 		filepath= r'/MicroWebSrv/web_files/js/heat.js',
+# 		contentType	 = "application/javascript",
+# 		headers		 = None)
 
 @MicroWebSrv.route('/status')
 def _httpHandlerStatusGet(httpClient, httpResponse) :
@@ -109,7 +148,10 @@ def _closedCallback(webSocket) :
 
 # ----------------------------------------------------------------------------
 routeHandlers = [
-	( "/",	"GET",	_httpHandlerRootGet ),
+	# ( "/",	"GET",	_httpHandlerRootGet ),
+	# ( "/js",	"GET",	_httpHandlerJsGet ),
+	# ( "/css/<index>",	"GET",	_httpHandlerCssGet ),
+	# ( "/img",	"GET",	_httpHandlerImgGet ),
 	( "/status",	"GET",	_httpHandlerStatusGet ),
 	( "/test",	"GET",	_httpHandlerTestGet ),
 	( "/test",	"POST",	_httpHandlerTestPost )

+ 0 - 0
MicroWebSrv/web_files/heat.css → MicroWebSrv/web_files/css/heat.css


+ 0 - 0
MicroWebSrv/web_files/normalize.css → MicroWebSrv/web_files/css/normalize.css


+ 0 - 30
MicroWebSrv/web_files/heat.js

@@ -1,30 +0,0 @@
-
-var oSw_btn
-
-var flag = true;
-function set_switch(oBtn){
-if (flag) {
-    oSw_btn.src = "switch_on.png";
-    flag = false;
-} else {
-    oSw_btn.src = "switch_off.png";
-    flag = true;
-}
-}
-// op_switch()
-// oBtn.onclick = op_switch;
-
-var url = window.location.href
-document.write("当前页面地址:" + url)
-var request = new XMLHttpRequest();
-function f() {
-    document.write('This is java script')
-}
-// window.onload = f
-f();
-
-window.onload = function() {
-    oSw_btn = document.getElementById("li-sw");
-    // oSw_btn = document.getElementById("heat-sw");
-    oBtn.onclick = op_switch;
-};

+ 0 - 0
MicroWebSrv/web_files/switch_off.png → MicroWebSrv/web_files/img/switch_off.png


+ 0 - 0
MicroWebSrv/web_files/switch_on.png → MicroWebSrv/web_files/img/switch_on.png


+ 7 - 10
MicroWebSrv/web_files/index.html

@@ -4,16 +4,12 @@
         <meta charset="UTF-8" />
         <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
         <meta http-equiv="X-UA-Compatible" content="IE=edge">
-        <link rel="stylesheet" href="normalize.css">
-        <link rel="stylesheet" href="heat.css">
+        <link rel="stylesheet" href="/css/normalize.css">
+        <link rel="stylesheet" href="/css/heat.css">
         <title>恒温加热</title>
-        
+        <!--  -->
     </head>
-    <script type="text/javascript" src="heat.js"> </script>
-    <script>
-
-            
-    </script>
+    <script type="text/javascript" src="/js/heat.js"> </script>
 <body>
     <ul>
         <li class="time">
@@ -25,8 +21,9 @@
         <li class="temperature">
             铁丝温度:26 ℃
         </li>
-        <li id="li-sw">
-            <img id="heat-sw" alt="on/off">
+        <li id="lisw">
+            <!-- <img id="heat-sw" src='img/switch_off.png' alt="on/off"> -->
+            <img id="heatsw" alt="on/off">
         </li>
     </ul>
 </body>

+ 47 - 0
MicroWebSrv/web_files/js/heat.js

@@ -0,0 +1,47 @@
+
+var oSw_btn
+
+function show_heat_img(oHeatsw, status){
+if (status) {
+    oHeatsw.src = "img/switch_off.png";
+} else {
+    oHeatsw.src = "img/switch_on.png";
+}
+}
+function set_heat_switch(oHeatsw, status){
+    
+    if (oHeatsw.src.match('on')) {
+        oHeatsw.src = "img/switch_off.png";
+    } else {
+        oHeatsw.src = "img/switch_on.png";
+    }
+}
+
+var url = window.location.href
+console.log("当前页面地址:" + url)
+function get_status(root_url, oHeatsw){
+    console.log("get_status :" + url)
+    var url_staus = root_url + 'status';
+    var request = new XMLHttpRequest();
+    request.open('GET', url_staus);
+    // 等待获取成功 onreadystatechange
+    request.onreadystatechange = function(){
+        if (request.readyState == 4 && request.status == 200){
+            var res_status = JSON.parse(request.responseText)
+            show_heat_img(oHeatsw, res_status['heat']['status']);
+        }
+    }
+    request.send(null)
+}
+
+
+function my_function() {
+    // window.alert('onload1');
+    oLisw = document.getElementById("lisw");
+    oHeatsw = document.getElementById("heatsw");
+    get_status(url, oHeatsw)
+    oHeatsw.onclick = function() {
+    };
+};
+window.onload = my_function
+

+ 84 - 49
heat.py

@@ -8,20 +8,40 @@ import uasyncio
 from machine import Pin,PWM,ADC
 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)
+    if len(series) > 8:
+        series.pop(0)
+    total = sum(series)
+    # print(series)
+    return total/len(series)
+
 
 class Ntc():
     def __init__(self, pin) -> None:
-        self.ntc = ADC(Pin(pin), atten=ADC.ATTN_11DB)
+        self.adc = ADC(Pin(pin), atten=ADC.ATTN_11DB)
         self.VCC = 3344
-    def get_temperature(self):
-        val_uv = self.ntc.read_uv()/1000
+        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):
+        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 + 0.5
+        T1 = 1/(log(Rt/10000)/3950 + 1/(273.15+25)) - 273.15
+        # 0.5 是误差。T1是复数,T1.real是取它的实部
+        temp = T1.real + 0.5
+        self.temp = average(self.temp_list, temp)
         # print("Rt:", Rt)
         # print("voltage:", val_uv)
         # print("T1:", T1.real)
-        return T1.real
 
+    def get_temperature(self):
+        return self.temp
     
 
 
@@ -39,9 +59,8 @@ class HeatPower():
         # self.sw_pin.duty(180)
         self.duty = 0.0
         self.duty_percent(0.7)
-        self.center_temp = 0
-        self.wire_temp = 0
         self.status = 0
+        self.dat = {'status':0, 'pwr_percent':0}
 
     def duty_percent(self, percent):
         if percent > 1:
@@ -49,60 +68,76 @@ class HeatPower():
         elif percent < 0:
             percent = 0
         self.duty = percent
-        set_value = round(self.duty * 1024)
-        print(self.duty)
-        print(set_value)
+        set_value = round(self.duty * 1023)
+        # print(self.duty)
+        # print(set_value)
         self.sw_pin.duty(set_value)
+        self.dat['pwr_percent'] = self.duty
     
 
     def get_sw_status(self):
-        if self.duty > 0:
-            return True
-        else:
-            return False
-    
-    def get_sw_percent(self):
-        return self.duty
+        return self.dat
 
     def off(self):
-        self.heat_status = 0
+        self.dat['status'] = 0
         self.duty_percent(0)
-        print("heat off")
+        # print("heat off")
     
-    def on(self):
-        # TODO
-        ""
-        self.duty_percent(0.7)
-        self.heat_status = 1
-        print("heat on")
+    def on(self, power_percent=0.8):
+        self.dat['status'] = 1
+        self.duty_percent(power_percent)
+        # print("heat on")
+    
+    def ajust_duty(self, step=0):
+        self.duty += step
+        if self.duty > 1:
+            self.duty = 1
+        elif self.duty < 0:
+            self.duty = 0
+        self.duty_percent(self.duty)
 
-def sensor(heat):
+    def ajust_power(self, wt, ct):
+        if not self.dat['status']:
+            return
+        if wt > 88 or ct > 45:
+            step = (88-wt)/100
+            self.ajust_duty(step)
+            print('wt:', wt, "step:", step)
+        else:
+            step = (40-ct)/100
+            print('ct:', ct, "step:", step)
+            self.ajust_duty(step)
+
+
+def sensor():
     wire_ntc = Ntc(34)
     center_ntc = Ntc(36)
-    while True:
-        heat.wire_temp = wire_ntc.get_temperature()
-        heat.center_temp = center_ntc.get_temperature()
-        
-        print("wire_temp:", heat.wire_temp)
-        print( "center_temp:", heat.center_temp)
-        if heat.wire_temp > 98:
-            heat.off()
-        elif heat.wire_temp < 85:
-            if heat.center_temp > 44:
-                heat.off()
-            else:
-                if heat.center_temp < 40 and heat.status == 0:
-                    heat.on()
-        upload.set_data('heat_status', heat.status)
-        upload.set_data('wire_temp', heat.wire_temp)
-        upload.set_data('center_temp', heat.center_temp)
-        # print("mem_info():", micropython.mem_info()) 
+    heat = HeatPower()
+    def heat_status_print():
+        # nonlocal wire_ntc,center_ntc,heat
+        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()
-        # print("collect mem_info():", micropython.mem_info()) 
-        time.sleep_ms(800)
+
+    tim = Timer()
+    tim.init(1, 1200, heat_status_print)
+        
+    
+def test():
+    wire_ntc = Ntc(34,2)
+    center_ntc = Ntc(36,3)
+    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__':
-    heat_power = HeatPower()
-    srv = WebSrv()
-    sensor(heat_power)
+    sensor()
+    # test()

+ 8 - 2
main.py

@@ -1,6 +1,8 @@
 import time
+import uasyncio
 #from mywifi import my_wifi
 from work_led import WorckLed
+import heat
 
 class Device():
     _instance = None
@@ -15,9 +17,13 @@ class Device():
         self.wled= WorckLed(2)
 
 
-def main():    
+def main(): 
     wled= WorckLed(2)
     
+    heat_power = heat.HeatPower()
+    heat.sensor(heat_power)
+    
 
 if __name__ == '__main__':
-    main()
+    # main()
+    pass

+ 91 - 0
my_timer.py

@@ -0,0 +1,91 @@
+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)

+ 18 - 14
mywifi.py

@@ -1,5 +1,6 @@
 import network
-from machine import Timer
+from my_timer import MyTimer as Timer
+# from machine import Timer
 SSID = "Xiaomi_eng"
 # SSID = "Mi11_eng"
 PASSWORD = "88888888"
@@ -20,14 +21,9 @@ class MyWifi():
         self.wlan = network.WLAN(network.STA_IF)            
         self.ssid = ssid
         self.password = password
-        self.tim = Timer(0)
         self.s = {'status': 'start connect', 'count': 0, 'check_count': 3}
-        self.tim.init(period=1, mode=Timer.ONE_SHOT,callback=self.check_disconnect)
 
-
-    def check_disconnect(self, timer):
-        self.tim.init(period=1000, mode=Timer.ONE_SHOT,
-                    callback=self.check_disconnect)
+    def check_disconnect(self):
         if self.s['status'] == 'start connect':
             if not self.wlan.isconnected():
                 print("Start connect to wifi:", self.ssid)
@@ -35,8 +31,6 @@ class MyWifi():
                 self.wlan.connect(self.ssid, self.password)
                 print('connecting to network...', self.ssid)
             self.s['status'] = 'check isconnected'
-            self.tim.init(period=1, mode=Timer.ONE_SHOT,
-                        callback=self.check_disconnect)
         elif self.s['status'] == 'check isconnected':
             if self.wlan.isconnected():
                 self.s['count'] = 0
@@ -68,10 +62,20 @@ class MyWifi():
         return self.get_wifi_ifconfig()[0]
 
     def get_wifi_ifconfig(self):
-        # 等待 check_disconnect() WiFi连接成功再返回
-        while not self.s['status'] == 'recheck':
-            pass
-        # 返回: ('192.168.31.123', '255.255.255.0', '192.168.31.1', '192.168.31.1')
+        # # 等待 check_disconnect() WiFi连接成功再返回
+        # while not self.s['status'] == 'recheck':
+        #     pass
+        # # 返回: ('192.168.31.123', '255.255.255.0', '192.168.31.1', '192.168.31.1')
         return self.wlan.ifconfig()
     
-my_wifi = MyWifi()
+my_wifi = MyWifi()
+
+# 协程的方式
+import uasyncio
+async def wifi_do_work():
+    while True:
+        my_wifi.check_disconnect()
+        await uasyncio.sleep_ms(1000)
+
+if __name__ == '__main__':
+    uasyncio.run(wifi_do_work())

+ 50 - 19
web_server.py

@@ -1,6 +1,7 @@
 
 from MicroWebSrv.microWebSrv import MicroWebSrv
 from MicroWebSrv.urls import routeHandlers,_acceptWebSocketCallback
+from    _thread     import start_new_thread,stack_size
 
 '''
 ` 实例化web服务器对象
@@ -18,30 +19,60 @@ from MicroWebSrv.urls import routeHandlers,_acceptWebSocketCallback
 	- 理论上这是作者源文件里面的东西,我们可以不用管它,也无法从外部修改,直接使用 WriteResponseFile 函数返回网页文件即可
 	- `httpResponse.WriteResponseFile(filepath= '/my-html.html',contentType	 = "text/html",headers		 = None)`
 '''
-class WebSrv():
+class MyWebSrv():
     _instance = None
     def __new__(cls, *args, **kwargs):
         if cls._instance is None:
             cls._instance = super().__new__(cls)
         return cls._instance   # 返回的是内存地址
-    def __init__(self) -> None:
-        self.srv = self.start_server()
-
-    def start_server(self):
-        import sys
-        if sys.platform == 'win32':
-            ip_addr = '192.168.43.240'
-            web_path = 'MicroWebSrv\web_files'
-        else:
-            from mywifi import my_wifi
-            ip_addr = my_wifi.get_wifi_addr()
-            web_path = '/MicroWebSrv/web_files'
-        print(web_path)
-        srv = MicroWebSrv(routeHandlers=routeHandlers, bindIP=ip_addr, webPath='MicroWebSrv\web_files')
-        srv.Start(threaded=True)
-        print("start:", ip_addr)
-        return srv
+    def __init__(self, ip='', webp = '') -> None:
+        self.ip = ip
+        self.web_path = webp
+        self.srv = None
+
+    def start_server(self, threaded=True):
+        # import sys
+        # if sys.platform == 'win32':
+        #     ip_addr = '192.168.43.240'
+        #     web_path = 'MicroWebSrv\web_files'
+        # else:
+        #     from mywifi import my_wifi
+        #     while not my_wifi.wlan.isconnected():
+        #         pass
+        #     ip_addr = my_wifi.get_wifi_addr()
+        #     web_path = '/MicroWebSrv/web_files'
+        # print(self.web_path)
+        # stack_size 必须设置大小,如果不设置当访问网页程序会抛出超出堆栈的异常
+        stack_size(32768)
+        self.srv = MicroWebSrv(routeHandlers=routeHandlers, bindIP=self.ip, webPath=self.web_path)
+        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()
+
+async def start_server():
+    uasyncio.create_task(wifi_do_work())
+    while not my_wifi.wlan.isconnected():
+        await uasyncio.sleep_ms(100)
+        # print('wait to wifi connect...')
+
+    web_srv.ip = my_wifi.get_wifi_addr()
+    web_srv.web_path = '/MicroWebSrv/web_files'
+    web_srv.start_server()
+    
+    while True:
+        gc.collect()
+        # print(micropython.mem_info())
+        await uasyncio.sleep_ms(10000)
+
+
 if __name__ == '__main__':
-	WebSrv()
+	uasyncio.run(start_server())
+    # WebSrv()
 
 # ----------------------------------------------------------------------------

+ 26 - 17
work_led.py

@@ -1,29 +1,38 @@
 from machine import Pin, PWM
 import time
 from machine import Timer
+from my_timer import MyTimer
 
 class WorckLed:
     def __init__(self, pin_num) -> None:
         self.led = Pin(pin_num, Pin.OUT)
-        self.led.value(0)
+        # self.tim = MyTimer(0)
+        # self.tim.init(0, 1, self.blink)
+    def on(self):
+        self.led.value(1)
+        print('on')
 
-        self.led = PWM(Pin(pin_num))
-        self.led.freq(1000)
-        self.led_status = 0
-        self.led_blink_time = {'on': 40, 'off': 800}
-        self.tim = Timer(1)
-        self.led_on(None)
-        
-    def led_on(self, timer):
-        self.led.duty(100)
-        self.tim.init(period=self.led_blink_time['on'], mode=Timer.ONE_SHOT,
-                      callback=self.led_off)
+    def off(self):
+        self.led.value(0)
+        print('off')
 
-    def led_off(self, timer):
-        self.led.duty(0)
-        self.tim.init(period=self.led_blink_time['off'], mode=Timer.ONE_SHOT,
-                      callback=self.led_on)
+    def blink(self, tim):
+        if self.led.value():
+            self.tim.init(1, 1200, self.blink)
+            self.off()
+        else:
+            self.tim.init(1, 10, self.blink)
+            self.on()
 
+# 协程的方式
+import uasyncio
+async def work_led_blink(led=WorckLed(2), on_t=10, off_t=1200):
+    while True:
+        led.value(1)
+        await uasyncio.sleep_ms(on_t)
+        led.value(0)
+        await uasyncio.sleep_ms(off_t)
 
 if __name__ == '__main__':
-    WorckLed(2)
+    # led = WorckLed(2)
+    uasyncio.run(work_led_blink(led=Pin(2, Pin.OUT), on_t=10, off_t=1200))