Преглед на файлове

大体完成,但是手机页面无法加载JS

mrh преди 3 години
родител
ревизия
7c1982814c

+ 17 - 14
MicroWebSrv/web_files/css/heat.css → MicroWebSrv/view/css/heat.css

@@ -7,14 +7,11 @@ body{
     /* 最大页面不超过 */
     max-width: 640px;
     margin: 0 auto;
-    font-size: 14px;
-    line-height: 1.5;
+    font-size: 20px;
+    line-height: 2;
     color: #000;
 }
 
-.time{
-    height: 45px;
-}
 
 ul{
     margin: 0;
@@ -26,27 +23,33 @@ ul li h1{
     color: #9e8201;
 
 }
+ul li.blank{
+    border: #020202;
+    margin: 50% 10%;
+}
+
 /* 后代元素选择器
 语法: 祖先 后代 后代
 */
-.app ul li{
-    /* 靠左浮动,这样他们才可以并排一行 */
+/* .app ul li{
+    // 靠左浮动,这样他们才可以并排一行
     float: left;
     height: 45px;
     background-color: #333333;
-    /* 文本居中 */
+    // 文本居中 
     text-align: center;
     line-height: 45px;
-}
+} */
+
 /* 伪类选择器,根据相同类型元素选择
     :first-of-type 同类型第一个子元素
     :nth-of-type(n) 同类型第n个子元素
     :nth-last-of-type(n) 同类型倒数第n个子元素
  */
-.app ul li:nth-child(1){
-    width: 8%;
-}
-.app ul li:nth-child(2){
+/* .app ul li:nth-child(1){
+    height: 45%;
+} */
+/* .app ul li:nth-child(2){
     width: 10%;
 }
 .app ul li:nth-child(3){
@@ -54,4 +57,4 @@ ul li h1{
 }
 .app ul li:nth-child(4){
     width: 25%;
-}
+} */

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


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


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


+ 14 - 5
MicroWebSrv/web_files/index.html → MicroWebSrv/view/index.html

@@ -4,6 +4,9 @@
         <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">
+        <META HTTP-EQUIV="pragma" CONTENT="no-cache"> 
+        <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"> 
+        <META HTTP-EQUIV="expires" CONTENT="0">
         <link rel="stylesheet" href="/css/normalize.css">
         <link rel="stylesheet" href="/css/heat.css">
         <title>恒温加热</title>
@@ -12,14 +15,20 @@
     <script type="text/javascript" src="/js/heat.js"> </script>
 <body>
     <ul>
-        <li class="time">
+        <li class="blank">
+            <p></p>
+        </li>
+        <li id="run_time">
             <h1>运行时间:00:00:00</h1>
         </li>
-        <li class="temperature">
-            中心温度:26 ℃
+        <li id="c_temp">
+            <!-- 中心温度:26 ℃ -->
+        </li>
+        <li id="r_temp">
+            <!-- 铁丝温度:26 ℃ -->
         </li>
-        <li class="temperature">
-            铁丝温度:26 ℃
+        <li id="pwr">
+            <!-- 功率百分比 -->
         </li>
         <li id="lisw">
             <!-- <img id="heat-sw" src='img/switch_off.png' alt="on/off"> -->

+ 128 - 0
MicroWebSrv/view/js/heat.js

@@ -0,0 +1,128 @@
+
+var host = window.location.href
+console.log("当前页面地址:" + host)
+
+function show_heat_img(oHeatsw, status){
+    console.log('status:', status)
+    // 必须要 == 1,否则会导致无法关闭
+    // 可能是因为status是字符串,所以 if(status) 这种方式必定为真
+    if (status == 1) {
+        oHeatsw.src = "img/switch_on.png";
+    } else {
+        oHeatsw.src = "img/switch_off.png";
+    }
+}
+
+function show_temp(oTemp, value, name){
+    oTemp.innerHTML = name + "温度:" + value.toFixed(2); + '℃';
+}
+
+function show_time(oRuntime, run_time){
+    console.log("time:", run_time)
+    oRuntime.innerHTML = '运行时间:' + PrefixInteger(parseInt(run_time/3600), 2) + ':' + PrefixInteger(parseInt(run_time/60) % 60, 2) + ':' + PrefixInteger(parseInt(run_time % 60),2)
+}
+
+function toggle_heat_switch(oHeatsw){
+    var request = new XMLHttpRequest();
+    if (oHeatsw.src.indexOf('switch_off') != -1) {
+        // false 是不采用异步方式,也就是说必须等到 request 返回,程序才执行下一步
+        request.open('GET', 'heat/on', false);
+    } else if (oHeatsw.src.indexOf('switch_on')){
+        request.open('GET', 'heat/off', false);
+    }
+
+    var heat_response
+    request.onreadystatechange = function(){
+        if (request.readyState == 4 && request.status == 200){
+            heat_response = parseInt(request.responseText);
+            if (heat_response in [0,1]){
+                show_heat_img(oHeatsw, heat_response);
+            }
+        }
+    }
+    request.send(null)
+    return heat_response
+}
+
+function get_status(url_staus){
+    var res_status = new Object;
+    var request = new XMLHttpRequest();
+    console.log("url_staus :" + url_staus)
+    request.open('GET', url_staus, false);
+    // 等待获取成功 onreadystatechange
+    request.onreadystatechange = function(){
+        if (request.readyState == 4 && request.status == 200){
+            res_status = JSON.parse(request.responseText)
+            console.log('res_status:', res_status)
+        }
+    }
+    request.send(null)
+    return res_status
+}
+
+var temp_cnt = 5
+function reflash_dat(owireTemp, ocenterTemp, oPower, board_status){
+    temp_cnt += 1
+    if (temp_cnt > 3)
+    {
+        temp_cnt = 0
+        if (board_status == null){
+            board_status = get_status(host + 'status')
+        }
+        ntc = board_status['ntc']
+        show_temp(owireTemp, ntc['wire_temp'], '铁丝')
+        show_temp(ocenterTemp, ntc['center_temp'], '中心')
+        oPower.innerHTML = '功率:' + board_status['heat']['pwr_percent'].toFixed(2) * 100 + '%'
+    }
+}
+
+function my_function() {
+    oHeatsw = document.getElementById("heatsw");
+    owireTemp = document.getElementById("r_temp");
+    ocenterTemp = document.getElementById("c_temp");
+    oRunTime = document.getElementById("run_time");
+    oPower = document.getElementById("pwr");
+    
+    var board_status
+    function show_dat(){
+        board_status = get_status(host + 'status')
+        show_heat_img(oHeatsw, board_status['heat']['status']);
+        reflash_dat(owireTemp, ocenterTemp, oPower, board_status)
+        show_time(oRunTime, board_status['time']['run_time'], 0)    
+    }
+    show_dat()
+
+    var run_time = board_status['time']['run_time']
+    var stop_reflash = 0
+    function reflash(){
+        // 不论开启或关闭加热,温度都会一直获取
+        reflash_dat(owireTemp, ocenterTemp, oPower, null)
+
+        if (stop_reflash == 0){
+            show_time(oRunTime, run_time, 1)
+            run_time += 1
+        }
+    }
+
+    oHeatsw.onclick = function() {
+        res = toggle_heat_switch(oHeatsw)
+        if (res == 0){
+            show_time(oRunTime, 0, 0)
+            stop_reflash = 1
+            console.log('stop:interval')
+        }
+        else if(res ==1){
+            stop_reflash = 0
+            cnt = 6
+            run_time = 0
+        }
+        
+    };
+    setInterval(reflash,1000)
+};
+window.onload = my_function
+
+// num传入的数字,n需要的字符长度
+function PrefixInteger(num, n) {
+    return (Array(n).join(0) + num).slice(-n);
+}

+ 0 - 0
MicroWebSrv/web_files/heat_status.html


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

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

+ 0 - 21
MicroWebSrv/web_files/test.html

@@ -1,21 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-<title>菜鸟教程(runoob.com)</title>
-</head>
-<body>
-
-<form id="frm1" action="demo-form.php">
-第一个名字: <input type="text" name="fname" value="Donald"><br>
-最后一个名字: <input type="text" name="lname" value="Duck"><br>
-<input type="submit" value="提交">
-</form>
-<p>action属性的值为:
-<script>
-document.write(document.getElementById("frm1").action);
-</script>
-</p>
-
-</body>
-</html>

+ 9 - 17
heat.py

@@ -6,8 +6,6 @@ import micropython
 import gc
 import uasyncio
 from machine import Pin,PWM,ADC
-# from web_server import WebSrv
-from MicroWebSrv.upload_dat import upload
 
 def average(series, new_value):
     series.append(new_value)
@@ -53,9 +51,8 @@ class HeatPower():
         self.sw_pin = PWM(Pin(15))
         self.sw_pin.freq(1000)
         # self.sw_pin.duty(180)
-        self.duty = 0.0
         self.status = 0
-        self.dat = {'status':0, 'pwr_percent':0}
+        self.duty = 0.0
         self.duty_percent(0.7)
 
     def duty_percent(self, percent):
@@ -68,19 +65,15 @@ class HeatPower():
         # print(self.duty)
         # print(set_value)
         self.sw_pin.duty(set_value)
-        self.dat['pwr_percent'] = self.duty
     
 
-    def get_sw_status(self):
-        return self.dat
-
     def off(self):
-        self.dat['status'] = 0
+        self.status = 0
         self.duty_percent(0)
         # print("heat off")
     
     def on(self, power_percent=0.8):
-        self.dat['status'] = 1
+        self.status = 1
         self.duty_percent(power_percent)
         # print("heat on")
     
@@ -93,19 +86,21 @@ class HeatPower():
         self.duty_percent(self.duty)
 
     def ajust_power(self, wt, ct):
-        if not self.dat['status']:
+        if not self.status:
             return
         if wt > 88 or ct > 45:
             step = (88-wt)/100
             self.ajust_duty(step)
-            print('wt:', wt, "step:", step)
+            # print('wt:', wt, "step:", step)
         else:
             step = (42-ct)/100
-            print('ct:', ct, "step:", step)
+            # print('ct:', ct, "step:", step)
             self.ajust_duty(step)
 
 wire_ntc = Ntc(34)
 center_ntc = Ntc(36)
+heat = HeatPower()
+
 async def cal_ntc():
     while True:
         wire_ntc.cal_temperature()
@@ -114,18 +109,15 @@ async def cal_ntc():
 
 async def sensor():
     uasyncio.create_task(cal_ntc())
-    heat = HeatPower()
     heat.on()
     while True:
         wire_temp = wire_ntc.get_temperature()
         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)
-        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)
+        await uasyncio.sleep_ms(3000)
 
         
 

+ 37 - 0
http_handler.py

@@ -0,0 +1,37 @@
+from MicroWebSrv.microWebSrv import MicroWebSrv
+from module import mod
+
+
+@MicroWebSrv.route('/status')
+def _httpHandlerStatusGet(httpClient, httpResponse) :
+    content = mod.get_dat()
+    print("content:", content)
+    httpResponse.WriteResponseOk( headers		 = None,
+								  contentType	 = "text/html",
+								  contentCharset = "UTF-8",
+								  content 		 = content )
+
+@MicroWebSrv.route('/heat/<index>')
+def _httpHandlerHeat(httpClient, httpResponse, args={}) :
+    content = ''
+    if 'index' in args:
+        if args['index'] == 'on':
+            mod.heat_on()
+            content = str(mod.heat.status)
+        elif args['index'] == 'off':
+            mod.heat_off()
+            content = str(mod.heat.status)
+        elif args['index'] == 'status':
+            content = str(mod.heat.status)
+    print('_httpHandlerHeat:', content)
+    httpResponse.WriteResponseOk( headers		 = None,
+								  contentType	 = "text/html",
+								  contentCharset = "UTF-8",
+								  content 		 = content )
+
+
+# ----------------------------------------------------------------------------
+routeHandlers = [
+	( "/status",	"GET",	_httpHandlerStatusGet ),
+    ( '/heat/<index>', 'GET',	_httpHandlerHeat ),
+]

+ 5 - 7
main.py

@@ -19,14 +19,12 @@ class Device():
 
 async def main(): 
     uasyncio.create_task(work_led_blink())
-    uasyncio.create_task(sensor())
+    t = uasyncio.create_task(sensor())
     uasyncio.create_task(start_server())
-    loop = uasyncio.get_event_loop()
-    loop.run_forever()
+    await t
+    # loop = uasyncio.get_event_loop()
+    # loop.run_forever()
 
 if __name__ == '__main__':
-    print('run')
     uasyncio.run(main())
-    print('stop')
-    # main()
-    pass
+        

+ 35 - 0
module.py

@@ -0,0 +1,35 @@
+import json
+from heat import heat,wire_ntc,center_ntc
+from work_time import wt
+
+class Module():
+    # 用于更新用户界面,被 class controller 调用
+    # 基类,只能被上层继承和调用
+    def __init__(self) -> None:
+        self.heat = heat
+        self.center_ntc = center_ntc
+        self.wire_ntc = wire_ntc
+        self.work_time = wt
+        self.dat = {}
+    def register(self, name, obj):
+        self.obj.update({name: obj})
+    
+    def get_dat(self):
+        self.dat.update({'heat': {"status": heat.status, 'pwr_percent': heat.duty}})
+        self.dat.update({'ntc': {"wire_temp": self.wire_ntc.get_temperature(), 'center_temp':self.center_ntc.get_temperature()}})
+        if not heat.status:
+            self.work_time.init()
+        self.dat.update({'time':{'start_time': self.work_time.start_time, 'run_time': self.work_time.get_run_time(), 'now_time': self.work_time.now_time}})
+        return json.dumps(self.dat)
+
+    def heat_on(self):
+        self.heat.on()
+        wt.init()
+        # print('on')
+
+    def heat_off(self):
+        self.heat.off()
+        # print('off')
+
+mod = Module()
+# print(mod.get_dat())

+ 3 - 49
MicroWebSrv/urls.py → urls.py

@@ -1,58 +1,12 @@
 from MicroWebSrv.microWebSrv import MicroWebSrv
 
 # ----------------------------------------------------------------------------
-from MicroWebSrv.upload_dat import upload
-# @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)
+from module import mod
+
 
 @MicroWebSrv.route('/status')
 def _httpHandlerStatusGet(httpClient, httpResponse) :
-	content = upload.get_status()
+	content = mod.get_dat()
 	print('board status:\n', content)
 	httpResponse.WriteResponseOk( headers		 = None,
 								  contentType	 = "text/html",

+ 2 - 3
web_server.py

@@ -4,7 +4,7 @@ import gc
 import micropython
 from mywifi import wifi_do_work, my_wifi
 from MicroWebSrv.microWebSrv import MicroWebSrv
-from MicroWebSrv.urls import routeHandlers,_acceptWebSocketCallback
+from http_handler import routeHandlers
 
 '''
 ` 实例化web服务器对象
@@ -28,7 +28,7 @@ class MyWebSrv():
         if cls._instance is None:
             cls._instance = super().__new__(cls)
         return cls._instance   # 返回的是内存地址
-    def __init__(self, ip='', webp = '') -> None:
+    def __init__(self, ip='', webp = '/MicroWebSrv/view') -> None:
         self.ip = ip
         self.web_path = webp
         self.srv = None
@@ -61,7 +61,6 @@ async def start_server():
         # 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:

+ 35 - 0
work_time.py

@@ -0,0 +1,35 @@
+import uasyncio
+import time
+
+class WorkTime():
+    def __init__(self) -> None:
+        self.__run_time = 0
+        self.start_time = time.time()
+        self.now_time = time.time()
+    
+    def get_run_time(self):
+        self.now_time = time.time()
+        self.__run_time = self.now_time - self.start_time
+        return self.__run_time
+    
+
+    def init(self):
+        self.__run_time = 0
+        self.now_time = time.time()
+        self.start_time = time.time()
+    
+
+wt = WorkTime()
+async def work_time():
+    while True:
+        # print("wt.rtc.datetime():",wt.rtc.datetime())
+        wt.get_time()
+        print("now_time:\t", wt.now_time)
+        print('start_time:\t', wt.start_time)
+        print('localtime:\t', time.localtime(wt.run_time))
+        # print('gm:', time.gmtime(wt.start_time))
+        await uasyncio.sleep_ms(1000)
+
+if __name__ == '__main__':
+    uasyncio.run(work_time())
+