Browse Source

稳定加热40°,待完善网页

mrh 3 years ago
parent
commit
a4be5d3f7f

+ 1 - 0
.gitignore

@@ -1,2 +1,3 @@
 .mpyproject.json
 .vscode/
+MicroWebSrv/__pycache__

+ 0 - 0
oled.py → .other-files/driver/oled.py


+ 0 - 0
driver/ssd1306.py → .other-files/driver/ssd1306.py


+ 0 - 0
driver/temp_sensor.py → .other-files/driver/temp_sensor.py


+ 0 - 0
MicroWebSrv/microWebSocket.py → .other-files/microWebSocket.py


+ 0 - 0
MicroWebSrv/microWebTemplate.py → .other-files/microWebTemplate.py


+ 51 - 2
readme-heat.md → .other-files/readme-heat.md

@@ -62,11 +62,31 @@ TODO
 
 
 
-# ADC
+# 开发板
+
+参考:
+
+https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/hw-reference/esp32/get-started-devkitc.html
+
+![img](F:\Engineer\Engineer_sync\my-document\.Typora-img\readme-heat\esp32-devkitC-v4-pinout.png)
+
+
+
+## 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)
+
+![img](https://img-blog.csdnimg.cn/20210717100659835.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTY1MjQ0NA==,size_16,color_FFFFFF,t_70)
+
+
+
+
+
+## ADC
 
 MicroPython 参考:http://docs.micropython.org/en/latest/esp32/quickref.html#adc-analog-to-digital-conversion
 
-## 基准电压
+### 基准电压
 
 ADC的基准电压是1.8V,因此接3.3V分压光敏电阻,很难达到1.8V以下
 
@@ -120,3 +140,32 @@ R_ntc: 14       Vntc:1.92 V
 ...
 ```
 
+## NTC
+
+R = 10K,Rntc=7.67K
+
+万用表:31℃
+
+ADC:27000
+
+Vntc 1.465V
+
+### 计算温度
+
+参考
+
+[(159条消息) 热敏电阻的计算公式_メイ的博客-CSDN博客]([(159条消息) 热敏电阻温度计算 公式 程序_yangyang_1024的博客-CSDN博客_热敏电阻计算公式](https://blog.csdn.net/yangyang_1024/article/details/80563522?spm=1001.2101.3001.6650.17&utm_medium=distribute.pc_relevant.none-task-blog-2~default~ESLANDING~default-17-80563522-blog-86743840.pc_relevant_multi_platform_whitelistv4eslandingctr&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~ESLANDING~default-17-80563522-blog-86743840.pc_relevant_multi_platform_whitelistv4eslandingctr&utm_relevant_index=24))
+
+[NTC数据文档](extension://bfdogplmndidlpjfhoijckpakkdjkkil/pdf/viewer.html?file=file%3A%2F%2F%2FF%3A%2FEngineer%2FEngineer_sync%2Fone-chip-computer%2Fmicropython%2F5P-heat%2Fother-files%2F%25E7%2583%25AD%25E6%2595%258F%25E7%2594%25B5%25E9%2598%25BB%25E8%25A1%25A8.pdf)
+
+
+
+Rt = R *EXP(B*(1/T1-1/T2))
+
+R=1000
+
+T=273.15+25
+
+
+
+34 + 13*2

+ 3 - 0
.other-files/run-rshell.bat

@@ -0,0 +1,3 @@
+@echo off
+cd ..
+call F:\Engineer\Engineer_sync\one-chip-computer\micropython\env-python-3.8.10-embed-amd64\run-cmd-here.bat

+ 5 - 0
.other-files/run-rshell.ps1

@@ -0,0 +1,5 @@
+$ENV_PATH="F:\Engineer\Engineer_sync\one-chip-computer\micropython\env-python-3.8.10-embed-amd64"
+$Env:path=";$ENV_PATH;$ENV_PATH\Scripts;"+$Env:Path  
+Python -V
+pip -V
+cd $PSScriptRoot\..

+ 9 - 0
test.py → .other-files/test.py

@@ -1,3 +1,12 @@
+import micropython
+print(micropython.mem_info())
+
+# 垃圾回收
+import gc
+gc.collect()
+print(gc.mem_info())
+gc.threshold(gc.mem_free())
+
 
 
 # 线程

BIN
.other-files/热敏电阻表.pdf


BIN
MicroWebSrv/__pycache__/microWebSocket.cpython-310.pyc


BIN
MicroWebSrv/__pycache__/microWebSrv.cpython-310.pyc


BIN
MicroWebSrv/__pycache__/microWebTemplate.cpython-310.pyc


+ 15 - 0
MicroWebSrv/upload_dat.py

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

+ 32 - 35
MicroWebSrv/main.py → MicroWebSrv/urls.py

@@ -1,35 +1,37 @@
-
-from microWebSrv import MicroWebSrv
+import gc
+from MicroWebSrv.microWebSrv import MicroWebSrv
 
 # ----------------------------------------------------------------------------
-
-@MicroWebSrv.route('/test')
-def _httpHandlerTestGet(httpClient, httpResponse) :
-	content = """\
-	<!DOCTYPE html>
-	<html lang=en>
-        <head>
-        	<meta charset="UTF-8" />
-            <title>TEST GET</title>
-        </head>
-        <body>
-            <h1>TEST GET</h1>
-            Client IP address = %s
-            <br />
-			<form action="/test" method="post" accept-charset="ISO-8859-1">
-				First name: <input type="text" name="firstname"><br />
-				Last name: <input type="text" name="lastname"><br />
-				<input type="submit" value="Submit">
-			</form>
-        </body>
-    </html>
-	""" % httpClient.GetIPAddr()
+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('/status')
+def _httpHandlerStatusGet(httpClient, httpResponse) :
+	content = upload.get_status()
+	print('board status:\n', content)
 	httpResponse.WriteResponseOk( headers		 = None,
 								  contentType	 = "text/html",
 								  contentCharset = "UTF-8",
 								  content 		 = content )
 
 
+@MicroWebSrv.route('/test')
+def _httpHandlerTestGet(httpClient, httpResponse) :
+	httpResponse.WriteResponseFile(
+		filepath= r'MicroWebSrv\web_files\test.html',
+		contentType	 = "text/html",
+		headers		 = None)
+	print('handle')
+	# print('GetRequestHeaders:',httpClient.GetRequestHeaders())
+	# print('ReadRequestContent: ',httpClient.ReadRequestContent(size=None))
+	# print('ReadRequestContentAsJSON:', httpClient.ReadRequestContentAsJSON())
+
 @MicroWebSrv.route('/test', 'POST')
 def _httpHandlerTestPost(httpClient, httpResponse) :
 	formData  = httpClient.ReadRequestPostedFormData()
@@ -106,16 +108,11 @@ def _closedCallback(webSocket) :
 	print("WS CLOSED")
 
 # ----------------------------------------------------------------------------
+routeHandlers = [
+	( "/",	"GET",	_httpHandlerRootGet ),
+	( "/status",	"GET",	_httpHandlerStatusGet ),
+	( "/test",	"GET",	_httpHandlerTestGet ),
+	( "/test",	"POST",	_httpHandlerTestPost )
+]
 
-#routeHandlers = [
-#	( "/test",	"GET",	_httpHandlerTestGet ),
-#	( "/test",	"POST",	_httpHandlerTestPost )
-#]
 
-srv = MicroWebSrv(webPath='www/')
-srv.MaxWebSocketRecvLen     = 256
-srv.WebSocketThreaded		= False
-srv.AcceptWebSocketCallback = _acceptWebSocketCallback
-srv.Start()
-
-# ----------------------------------------------------------------------------

+ 30 - 0
MicroWebSrv/web_files/heat.js

@@ -0,0 +1,30 @@
+
+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;
+};

+ 3 - 19
MicroWebSrv/web_files/index.html

@@ -9,25 +9,9 @@
         <title>恒温加热</title>
         
     </head>
+    <script type="text/javascript" src="heat.js"> </script>
     <script>
-        window.onload = function() {
-                var oBtn = document.getElementById("li-sw");
-                var oPic = document.getElementById("heat-sw");
-                var flag = false;
-                oBtn.onclick = function() {
-                if (flag) {
-                    oPic.src = "switch_on.png";
-                    flag = false;
-                } else {
-                    oPic.src = "switch_off.png";
-                    flag = true;
-                }
-                };
-            }
-        
-            var url = window.location.href
-            document.write("当前页面地址:" + url)
-            var request = new XMLHttpRequest();
+
             
     </script>
 <body>
@@ -42,7 +26,7 @@
             铁丝温度:26 ℃
         </li>
         <li id="li-sw">
-            <img id="heat-sw" src="switch_off.png" alt="on/off">
+            <img id="heat-sw" alt="on/off">
         </li>
     </ul>
 </body>

+ 0 - 144
MicroWebSrv/web_server.py

@@ -1,144 +0,0 @@
-from microWebSrv import MicroWebSrv
-# ----------------------------------------------------------------------------
-@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('/test')
-def _httpHandlerTestGet(httpClient, httpResponse) :
-	httpResponse.WriteResponseFile(
-		filepath= r'MicroWebSrv\web_files\test.html',
-		contentType	 = "text/html",
-		headers		 = None)
-	print('handle')
-	# print('GetRequestHeaders:',httpClient.GetRequestHeaders())
-	# print('ReadRequestContent: ',httpClient.ReadRequestContent(size=None))
-	# print('ReadRequestContentAsJSON:', httpClient.ReadRequestContentAsJSON())
-
-@MicroWebSrv.route('/test', 'POST')
-def _httpHandlerTestPost(httpClient, httpResponse) :
-	formData  = httpClient.ReadRequestPostedFormData()
-	firstname = formData["firstname"]
-	lastname  = formData["lastname"]
-	content   = """\
-	<!DOCTYPE html>
-	<html lang=en>
-		<head>
-			<meta charset="UTF-8" />
-            <title>TEST POST</title>
-        </head>
-        <body>
-            <h1>TEST POST</h1>
-            Firstname = %s<br />
-            Lastname = %s<br />
-        </body>
-    </html>
-	""" % ( MicroWebSrv.HTMLEscape(firstname),
-		    MicroWebSrv.HTMLEscape(lastname) )
-	httpResponse.WriteResponseOk( headers		 = None,
-								  contentType	 = "text/html",
-								  contentCharset = "UTF-8",
-								  content 		 = content )
-
-
-@MicroWebSrv.route('/edit/<index>')             # <IP>/edit/123           ->   args['index']=123
-@MicroWebSrv.route('/edit/<index>/abc/<foo>')   # <IP>/edit/123/abc/bar   ->   args['index']=123  args['foo']='bar'
-@MicroWebSrv.route('/edit')                     # <IP>/edit               ->   args={}
-def _httpHandlerEditWithArgs(httpClient, httpResponse, args={}) :
-	content = """\
-	<!DOCTYPE html>
-	<html lang=en>
-        <head>
-        	<meta charset="UTF-8" />
-            <title>TEST EDIT</title>
-        </head>
-        <body>
-	"""
-	content += "<h1>EDIT item with {} variable arguments</h1>"\
-		.format(len(args))
-	
-	if 'index' in args :
-		content += "<p>index = {}</p>".format(args['index'])
-	
-	if 'foo' in args :
-		content += "<p>foo = {}</p>".format(args['foo'])
-	
-	content += """
-        </body>
-    </html>
-	"""
-	httpResponse.WriteResponseOk( headers		 = None,
-								  contentType	 = "text/html",
-								  contentCharset = "UTF-8",
-								  content 		 = content )
-
-# ----------------------------------------------------------------------------
-
-def _acceptWebSocketCallback(webSocket, httpClient) :
-	print("WS ACCEPT")
-	webSocket.RecvTextCallback   = _recvTextCallback
-	webSocket.RecvBinaryCallback = _recvBinaryCallback
-	webSocket.ClosedCallback 	 = _closedCallback
-
-def _recvTextCallback(webSocket, msg) :
-	print("WS RECV TEXT : %s" % msg)
-	webSocket.SendText("Reply for %s" % msg)
-
-def _recvBinaryCallback(webSocket, data) :
-	print("WS RECV DATA : %s" % data)
-
-def _closedCallback(webSocket) :
-	print("WS CLOSED")
-
-# ----------------------------------------------------------------------------
-
-routeHandlers = [
-	( "/",	"GET",	_httpHandlerRootGet ),
-	( "/test",	"GET",	_httpHandlerTestGet ),
-	( "/test",	"POST",	_httpHandlerTestPost )
-]
-'''
-` 实例化web服务器对象
-` bindIP='192.168.31.123' 必填。在WiFi已经连接路由器的情况下,填写esp32的ip地址
-` 这个脚本同时支持 Python3.10 代码,测试时填上电脑本机IP地址即可
-` routeHandlers 这是web网页的路由表
-  - 当浏览器访问 192.168.31.123/test 时,会调用 _httpHandlerTestGet 函数
-  - 当浏览器点击 summit 时,
-    - 如 _httpHandlerTestGet 函数中 content 的 html 内容 method="post" 所显示的那样:<form action="/test" method="post" accept-charset="ISO-8859-1">
-    - 该语句会以 POST 方式请求服务器
-	- 再经过 routeHandlers 路由到 _httpHandlerTestPost 回调函数,输出函数内 content 的结果返回给浏览器
-` 浏览器直接输入: 192.168.43.67 会出现 index.html 页面(前提是 webPath='MicroWebSrv/www/' 路径设置正常)
-  - index.html 文件在哪路由?
-    - 在 MicroWebSrv\microWebSrv.py 文件中,初始化提到:_indexPages,函数 _physPathFromURLPath 调用相关页面
-	- 理论上这是作者源文件里面的东西,我们可以不用管它,也无法从外部修改,直接使用 WriteResponseFile 函数返回网页文件即可
-	- `httpResponse.WriteResponseFile(filepath= '/my-html.html',contentType	 = "text/html",headers		 = None)`
-'''
-def main():
-	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.MaxWebSocketRecvLen     = 256
-	srv.WebSocketThreaded		= True
-	srv.AcceptWebSocketCallback = _acceptWebSocketCallback
-	srv.SetNotFoundPageUrl("https://www.baidu.com/")
-	srv.Start(threaded=True)
-	print("start:", ip_addr)
-
-	if sys.platform == 'win32':
-		while True:
-			pass
-if __name__ == '__main__':
-	main()
-
-# ----------------------------------------------------------------------------

BIN
MicroWebSrv/www/favicon.ico


+ 0 - 28
MicroWebSrv/www/index.html

@@ -1,28 +0,0 @@
-<!DOCTYPE html>
-
-<html lang=fr>
-
-	<head>
-		<meta charset="UTF-8" />
-		<title>Page de test MicroWebSrv</title>
-		<link rel="stylesheet" href="style.css" />
-	</head>
-
-	<body>
-		<h1>Page de test MicroWebSrv</h1>
-		<h2>Hello !</h2>
-		<p>
-			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget ligula quis libero mollis dapibus. Suspendisse potenti. Nullam facilisis neque et sem. Proin placerat adipiscing urna. Aenean sollicitudin. Mauris lorem erat, fringilla quis, sagittis a, varius sed, nunc. Pellentesque ligula. Nullam egestas eleifend turpis. Vivamus ac sapien. Sed venenatis, ligula ut scelerisque vehicula, erat tellus euismod ipsum, eget faucibus tortor arcu et lectus. Vivamus vel purus. Fusce dignissim tortor quis diam elementum fermentum. Mauris eleifend lorem vel arcu. Vivamus tempus faucibus lectus. Curabitur volutpat ornare mi. Curabitur ac libero. Sed eu elit ac metus egestas iaculis.
-		</p>
-		<br />
-		<hr />
-		<br />
-		<div style="text-align: center">
-			<img src="pdf.png" />
-			<p>
-				Afficher « <a href="test.pdf">un fichier PDF</a> »
-			</p>
-		</div>
-	</body>
-
-</html>

BIN
MicroWebSrv/www/pdf.png


+ 0 - 36
MicroWebSrv/www/style.css

@@ -1,36 +0,0 @@
-html, body {
- margin: 0;
- padding: 0;
- }
-body {
- background-color: white; 
- font-family: Verdana, sans-serif; 
- font-size: 100%;
- }
-h1 {
- font-size: 200%; 
- color: navy; 
- text-align: center;
- }
-h2 {
- font-size: 150%; 
- color: red; 
- padding-left: 15px;
- }
-p,ul,li,td {
- color: black; 
- }
-a:link {
- color: green;
- text-decoration: underline;
- }
-a:visited {
- color: gray;
- }
-a:hover {
- color: red;
- text-decoration: none;
-}
-a:active, a:focus {
- color: red;
-}

BIN
MicroWebSrv/www/test.pdf


+ 0 - 34
MicroWebSrv/www/test.pyhtml

@@ -1,34 +0,0 @@
-<html>
-	<head>
-		<title>TEST</title>
-	</head>
-	<body>
-		<h1>BEGIN</h1>
-		{{ py }}
-			def _testFunction(x) :
-				return "IN TEST FUNCTION %s" % x
-		{{ end }}
-		<div style="background-color: black; color: white;">
-			{{ for toto in range(3) }}
-				This is an HTML test...<br />
-				TOTO = {{ toto + 1 }} !<br />
-				{{ for toto2 in range(3) }}
-					TOTO2 = {{ _testFunction(toto2) }}
-				{{ end }}
-				Ok good.<br />
-			{{ end }}
-		</div>
-		{{ _testFunction(100) }}<br />
-		<br />
-		{{ if 2+5 < 3 }}
-			IN IF (1)
-		{{ elif 10+15 != 25 }}
-			IN ELIF (2)
-		{{ elif 10+15 == 25 }}
-			IN ELIF (3)
-		{{ else }}
-			IN ELSE (4)
-		{{ end }}
-		<h1>JC :')</h1>
-	</body>
-</html>

+ 0 - 78
MicroWebSrv/www/wstest.html

@@ -1,78 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-
-    <head>
-        <meta charset="utf-8" />
-        <title>MicroWebSocket Test</title>
-    </head>
-
-    <script language="javascript">
-
-        var output;
-
-        function init()
-        {
-            output = document.getElementById("output");
-            testWebSocket();
-        }
-
-        function testWebSocket()
-        {
-            var wsUri           = "ws://" + window.location.hostname;
-            writeToScreen("Connection to " + wsUri + "...")
-            websocket           = new WebSocket(wsUri);
-            websocket.onopen    = function(evt) { onOpen    (evt) };
-            websocket.onclose   = function(evt) { onClose   (evt) };
-            websocket.onmessage = function(evt) { onMessage (evt) };
-            websocket.onerror   = function(evt) { onError   (evt) };
-        }
-
-        function onOpen(evt)
-        {
-            writeToScreen("<strong>-- CONNECTED --</strong>");
-            SendMsg("Hello world :)");
-            SendMsg("This is a WebSocket test");
-            SendMsg("(with a text frame encoded in UTF-8)");
-            setTimeout( function() { websocket.close() }, 500 )
-        }
-
-        function onClose(evt)
-        {
-            writeToScreen("<strong>-- DISCONNECTED --</strong>");
-        }
-
-        function onMessage(evt)
-        {
-            writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
-        }
-
-        function onError(evt)
-        {
-            writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
-        }
-
-        function SendMsg(msg)
-        {
-            writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
-            websocket.send(msg);
-        }
-
-        function writeToScreen(s)
-        {
-            var pre = document.createElement("p");
-            pre.style.wordWrap = "break-word";
-            pre.innerHTML = s;
-            output.appendChild(pre);
-        }
-
-        window.addEventListener("load", init, false);
-
-    </script>
-
-    <body>
-      <h2>MicroWebSocket Test :</h2>
-      <div id="output"></div>
-    </body>
-
-</html>

+ 107 - 19
heat.py

@@ -1,20 +1,108 @@
 # PWM
-from machine import Pin,PWM
-mos = PWM(Pin(15))
-FREQ = 10000
-heat_ohm = 15.111
-MAX_POWER = 12 #功率
-MAX_VOL = pow(MAX_POWER*heat_ohm, 1/2) #电压
-MAX_CURRENT = MAX_POWER/MAX_VOL #0.4A
-
-mos.freq(10000)
-def duty_percent(pwn_pin, percent):
-    if percent > 1:
-        percent == 1
-    elif percent < 0:
-        percent = 0
-    set_value = round(percent * 255)
-    print(percent)
-    print(set_value)
-    # pwn_pin.duty(set_value)
-duty_percent(mos, 0.3)
+import math
+import time
+from cmath import log
+import micropython
+import gc
+import uasyncio
+from machine import Pin,PWM,ADC
+from web_server import WebSrv
+from MicroWebSrv.upload_dat import upload
+
+class Ntc():
+    def __init__(self, pin) -> None:
+        self.ntc = ADC(Pin(pin), atten=ADC.ATTN_11DB)
+        self.VCC = 3344
+    def get_temperature(self):
+        val_uv = self.ntc.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
+        # print("Rt:", Rt)
+        # print("voltage:", val_uv)
+        # print("T1:", T1.real)
+        return T1.real
+
+    
+
+
+class HeatPower():
+    _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.sw_pin = PWM(Pin(15))
+        self.sw_pin.freq(1000)
+        # 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
+
+    def duty_percent(self, percent):
+        if percent > 1:
+            percent == 1
+        elif percent < 0:
+            percent = 0
+        self.duty = percent
+        set_value = round(self.duty * 1024)
+        print(self.duty)
+        print(set_value)
+        self.sw_pin.duty(set_value)
+    
+
+    def get_sw_status(self):
+        if self.duty > 0:
+            return True
+        else:
+            return False
+    
+    def get_sw_percent(self):
+        return self.duty
+
+    def off(self):
+        self.heat_status = 0
+        self.duty_percent(0)
+        print("heat off")
+    
+    def on(self):
+        # TODO
+        ""
+        self.duty_percent(0.7)
+        self.heat_status = 1
+        print("heat on")
+
+def sensor(heat):
+    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()) 
+        # 主动垃圾回收是个好习惯,如果没有经常开辟内存,可不用
+        gc.collect()
+        # print("collect mem_info():", micropython.mem_info()) 
+        time.sleep_ms(800)
+
+if __name__ == '__main__':
+    heat_power = HeatPower()
+    srv = WebSrv()
+    sensor(heat_power)

+ 0 - 28
local_test.py

@@ -1,28 +0,0 @@
-class Micro:
-    _index_page = 'html'
-    def __init__(self) -> None:
-        print('ok')
-    def url(self):
-        print(self._index_page)
-
-mi = Micro()
-mi.url()
-
-'''
-FREQ = 10000
-heat_ohm = 15.111
-MAX_POWER = 12 #功率
-MAX_VOL = pow(MAX_POWER*heat_ohm, 1/2) #电压
-MAX_CURRENT = MAX_POWER/MAX_VOL #0.4A
-print("%.2f" % MAX_VOL)
-def duty_percent(pwn_pin, percent):
-    if percent > 1:
-        percent == 1
-    elif percent < 0:
-        percent = 0
-    set_value = round(percent * 255)
-    print(percent)
-    print(set_value)
-
-duty_percent(1, 0.05)
-'''

+ 5 - 5
mywifi.py

@@ -5,13 +5,13 @@ SSID = "Xiaomi_eng"
 PASSWORD = "88888888"
 
 class MyWifi():
-    # _instance = None
+    _instance = None
     # _first_init = True
 
-    # def __new__(cls, *args, **kwargs):
-    #     if cls._instance is None:
-    #         cls._instance = super().__new__(cls)
-    #     return cls._instance   # 返回的是内存地址
+    def __new__(cls, *args, **kwargs):
+        if cls._instance is None:
+            cls._instance = super().__new__(cls)
+        return cls._instance   # 返回的是内存地址
 
     # WiFi 不能被初始化两次,否则会发生内部错误
     # 注意,在重复导入模块时,已经被算作初始化了,如果另一个模块又导入了这个类,很容易重复实例化一个新的WiFi对象

+ 47 - 0
web_server.py

@@ -0,0 +1,47 @@
+
+from MicroWebSrv.microWebSrv import MicroWebSrv
+from MicroWebSrv.urls import routeHandlers,_acceptWebSocketCallback
+
+'''
+` 实例化web服务器对象
+` bindIP='192.168.31.123' 必填。在WiFi已经连接路由器的情况下,填写esp32的ip地址
+` 这个脚本同时支持 Python3.10 代码,测试时填上电脑本机IP地址即可
+` routeHandlers 这是web网页的路由表
+  - 当浏览器访问 192.168.31.123/test 时,会调用 _httpHandlerTestGet 函数
+  - 当浏览器点击 summit 时,
+    - 如 _httpHandlerTestGet 函数中 content 的 html 内容 method="post" 所显示的那样:<form action="/test" method="post" accept-charset="ISO-8859-1">
+    - 该语句会以 POST 方式请求服务器
+	- 再经过 routeHandlers 路由到 _httpHandlerTestPost 回调函数,输出函数内 content 的结果返回给浏览器
+` 浏览器直接输入: 192.168.43.67 会出现 index.html 页面(前提是 webPath='MicroWebSrv/www/' 路径设置正常)
+  - index.html 文件在哪路由?
+    - 在 MicroWebSrv\microWebSrv.py 文件中,初始化提到:_indexPages,函数 _physPathFromURLPath 调用相关页面
+	- 理论上这是作者源文件里面的东西,我们可以不用管它,也无法从外部修改,直接使用 WriteResponseFile 函数返回网页文件即可
+	- `httpResponse.WriteResponseFile(filepath= '/my-html.html',contentType	 = "text/html",headers		 = None)`
+'''
+class WebSrv():
+    _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
+if __name__ == '__main__':
+	WebSrv()
+
+# ----------------------------------------------------------------------------