ESP8266/ESP32 + MicroPython web 控制 led

180it 2022-05-30 PM 1156℃ 0条

搜到一个例子,根据当下库的版本调通,实测可用(MicroPython v1.18)

ESP连上wifi后会给出一个ip地址,再电脑端打开浏览器就可以看到下图按钮,然后可以控制LED并看到当前状态。当然,不用浏览器也是可以的,命令行测试 curl 192.168.xxx.xxx/led

e11bb50e26ce47feaa5be4d23a579e85.png

下一步就是做个MQTT

import socket, time, re
import utime
import network
import webrepl
from machine import Pin
sta_if = network.WLAN(network.STA_IF);
 
SSID = "xxxxx"
PASSWORD = "xxxxxxxxx"
 
html="""
    <html>
    <head>
      <META HTTP-EQUIV="Content-Type" CONTENT="text/html">
      <title>LED控制</title>
    </head>
    <body>
    <form>
        <span id="status" name="status">%s</span>
        <input type="button" value="转换" onclick="onSubmit()">
    </from>
    </body>
    </html>
    <script>
    function onSubmit(){
    if (window.XMLHttpRequest) {
        // 用于现代浏览器的代码,code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp = new XMLHttpRequest();
     } else {
        // 应对老版本 IE 浏览器的代码,// code for IE6, IE5
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }
    
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("status").innerHTML = xmlhttp.responseText;
        // document.getElementById("status").value = xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET", "led", true);  
    xmlhttp.send("ssss");
    }
    </script>
"""
 
def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(SSID, PASSWORD)
        
    start = utime.time()
    while not wlan.isconnected():
        utime.sleep(1)
        if utime.time()-start > 5:
            print("connect timeout!")
            break
            
    if wlan.isconnected():
        print('network config:', wlan.ifconfig())
 
do_connect()
ip = sta_if.ifconfig()[0]
 
port = 80
led = Pin(2, Pin.OUT)
webserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    #创建套接字
webserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  #设置给定套接字选项的值
#webserver.settimeout(2000)
webserver.bind((ip, port))                                       #绑定IP地址和端口号
webserver.listen(5)                                              #监听套接字
print("服务器地址:%s:%d" %(ip,port))
 
while True:
  conn, addr = webserver.accept()                                #接受一个连接,conn是一个新的socket对象
  #print("in %s" % str(addr))
  request = conn.recv(1024)                              #从套接字接收1024字节的数据
  if len(request)>0:
    request = request.decode()
    result = re.search("(.*?) (.*?) HTTP/1.1", request)
    if result:
      method = result.group(1)
      url = result.group(2)
      print(url)
      if method == "POST":
        postdata = re.search(".*?\r\n\r\n(.*)", request).group(1)
        if postdata:
          lists = postdata.split("&")
          payload = {}
          for list in lists:
            k,v = list.split("=")
            payload[k]=v
          #print(payload)
      #conn.sendall("HTTP/1.1 200 OK\nConnection: close\nServer: Esp8266\nContent-Type: text/html;charset=UTF-8\n\n")
      conn.send("HTTP/1.1 200 OK\r\n")
      conn.send("Server: Esp8266\r\n")
      conn.send("Content-Type: text/html;charset=UTF-8\r\n")
      conn.send("Connection: close\r\n")
      conn.send("\r\n")
      if url =="/":         # 接收到参数 /
        conn.sendall(html % ("灯亮" if led.value()==0 else "灯灭"))
      elif url == "/led":   # 接收到参数 led
        if method == "POST":
          status = payload.get("status")
          if status=="on":
            led.value(0)
          elif status=="off":
            led.value(1)
        else:
          led.value(not led.value())
        conn.sendall("灯亮" if led.value()==0 else "灯灭")
        #conn.send(str(led.value()))
      conn.send("\r\n")  # 发送结束
    else:
      print("not found url")
  else:
    print("no request")
  conn.close()
  #print("out %s" % str(addr))

来源:https://blog.csdn.net/jiangge12/article/details/123458367

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

ESP8266/ESP32 + MicroPython web 控制 led