ESP8266用网页控制电灯(micropython)第二版

增加电褥子定时, 电褥子分档  。可以用手机autojs编写脚本,发送网路命令,增加多段定时,多段温度  。附上autojs代码。

import machine
import utime
import dht
d = dht.DHT22(machine.Pin(12))
from machine import Pin
import time,ntptime,uio
from machine import Timer

ntptime.NTP_DELTA = 3155644800
ntptime.host = 'ntp1.aliyun.com'
dd=[18,31,8,1]
try:
   ddd=uio.open("dingshishijian.txt", mode='r')
   dd=ddd.readline().split(",")
   ddd.close()
except:
   print("dingshishijian wenjianmeiyou")


dingshishijian=[int(dd[0]),int(dd[1]),int(dd[2]),int(dd[3])]


print(0)
tim = Timer(-1)
jiaoshichenggong=0
def set_ntptime(a):
   try:
      ntptime.settime()
      if time.localtime()[0]>2020:
         global jiaoshichenggong
         jiaoshichenggong=1
         print("jiaoshichenggong")
      else:
         print("jiaoshicuo2")
   except:
      print("jiaoshicuo")
      
   finally:
      global jiaoshichenggong
      if jiaoshichenggong==0:
         tim.init(period=5000,mode=Timer.ONE_SHOT,callback=set_ntptime)

set_ntptime(1)

dianruzi_dangwei=0
siduan=0
siduanjishu=0
def dingshi(a):
  global dianruzi_dangwei
  global jiaoshichenggong
  global siduan
  global siduanjishu
  if siduanjishu==0:
     siduanjishu=4
     siduan=dianruzi_dangwei     
  if siduan<=0:
          dianruziguan()         
  else:
          dianruzikai()         
  siduanjishu=siduanjishu-1
  siduan=siduan-1          

  if jiaoshichenggong==1:       
    t=time.localtime()    
    if t[3]==dingshishijian[0] and  t[4]==dingshishijian[1]:
       dianruzi_dangwei=4
    if t[3]==dingshishijian[2] and  t[4]==dingshishijian[3]:
       dianruzi_dangwei=0
    if t[3]==1 and  t[4]==0:
       jiaoshichenggong=0
       set_ntptime(1)
timer = Timer(-1)
timer.init(period=30000,callback=dingshi)

def dianruzikai():
   p2.on()
def dianruziguan():
   p2.off()


p0 = Pin(5, Pin.OUT)
p1 = Pin(4, Pin.OUT)
p2 = Pin(14, Pin.OUT)

#loc2="""
#<script >
#location.href="http://192.168.123.253"
#</script >
#</html>

#"""

html= """<html><head>
<meta  http-equiv="Content-Type"  content="text/html; charset=utf-8" />
<meta name="viewport"content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes"/>
<style>
input[type="button"]{margin:10px;width:40px;height:40px;border-radius: 10px;}
</style>
</head>

<script >
    function dianji(val)
    {
        var request = new XMLHttpRequest();

        
        request.open('GET', "?mcu_do="+val,true);
        if (val=='wen'){
         {   request.onload = function() {  huixian.innerHTML= this.response;    }
    }
        }
        else{
        request.onload = function() {
        if( this.response[0]==1)deng1.style.color="red";else deng1.style.color="black"
        if( this.response[1]==1)deng2.style.color="red";else deng2.style.color="black" 
        if( this.response[2]>0){deng4.style.color="red";
        deng4.innerText= "电褥子:"+(5-this.response[2])+"档"}
        else deng4.style.color="black" 
        }

        }
        request.send();
    }

    function dianji2(val){
location.href="http://192.168.123.254/?mcu_do="+val
}

function xiugaidingshi(){
var request = new XMLHttpRequest();
request.open('GET',"?mcu_do=xgd"+(shi.value-0+100)+(fen.value-0+100)+(shi2.value-0+100)+(fen2.value-0+100),true)
request.onload = function(){chenggong.innerHTML="<p>成功</p>"}
request.send();
}


function shuaxin()
{
dianji("shx")
var request = new XMLHttpRequest();        
request.open('GET', "?mcu_do=dqd",true);
request.onload = function(){
aa=this.response.split("#")
shijianxianshi.innerText=aa[1]
a=aa[0].split(",")
shi.value=a[0]
fen.value=a[1]
shi2.value=a[2]
fen2.value=a[3]
}
request.send();
}
shuaxin()    
</script>
<body  style="text-align:center">
    <h1 id=deng1 style="color:black">屋里电灯</h1>
    <input  type="button" οnclick="dianji('1on');" value="开" /><span  style="margin:20 40px;"></span>
    <input  type="button" οnclick="dianji('1of');" value="关" />
        <h1 id=deng2 style="color:black" >院里电灯</h1>
    <input  type="button" οnclick="dianji('2on');" value="开" /><span  style="margin:20 40px;"></span>
    <input  type="button" οnclick="dianji('2of');" value="关" />
    <h1 id=deng4 style="color:black" >电褥子</h1>
    <input  type="button" οnclick="dianji('1da');" value="一档" />
    <input  type="button" οnclick="dianji('2da');" value="二档" />
    <input  type="button" οnclick="dianji('3da');" value="三档" />
    <input  type="button" οnclick="dianji('4da');" value="四档" /><br><br>
    <input  type="button" οnclick="dianji('0da');" value="关" />    
    
    <br><br><div id="shijianxianshi"></div>
    <br>开<input type="number"  style="width:60px"  value="0" id="shi" />时<input type="number"  style="width:60px"  value="0" id="fen"  />分

<br><br>关<input type="number"  style="width:60px"  value="0" id="shi2" />时<input type="number"  style="width:60px"  value="0" id="fen2"  />分
<br><br><input type="button"  style="width:80px"  οnclick="xiugaidingshi()" value="修改定时"/>
<br><div id="chenggong"></div><br>
<input  type="button" οnclick="dianji('wen');" value="温湿度" style="width:60px" />
    <br>    
    <p id="huixian"></p>
</body>
</html>

"""


header="""HTTP/1.1 200 OK
Content-Type:text/html
Content-Length:"""

header404="""
HTTP/1.1 404 Not Found

"""

import socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
addr2 = socket.getaddrinfo('192.168.123.254',80)[0][-1]
s = socket.socket()

s.bind(addr)
s.listen(0)
print('listening on', addr)


def fasong(socket,stri):
   s=stri.encode()
   socket.write(header)
   socket.write(str(len(s)))
   socket.write("\n\n")
   socket.write(s)  

def sss():
          global dianruzi_dangwei
          sendhtm=str(p1.value())+str(p0.value())+str(dianruzi_dangwei)
          fasong(cl,sendhtm)
          #cl.send(header.format(len(sendhtm),sendhtm))
          cl.close()

while True:
  try:
    cl, addr = s.accept()
    print('client connected from :', addr)
    #cl_file = cl.makefile('rwb', 0)
    cl.settimeout(3)
    lll= b''
    lll=cl.readline()+cl.readline()  
    while True:       
            line = cl.readline()        
            #lll=lll+line
            #print( lll)
            if not line or line == b'\r\n':
                break
    llll=lll.decode("utf-8")
    #print(llll)
    l=llll.find("mcu_do=",0,20)
    if  not l==-1:
        cmd=(llll[l+7:l+10])         
        if cmd=="wen":
            try:
                d.measure()
            ddd=str(d.temperature()) 
            except OSError:
                fasong(cl,"错")
                cl.close()
            else:
                response =ddd + " " + str(d.humidity())
                fasong(cl,response)
                cl.close()
            continue
        elif cmd=="1of":
            print("of")
            p1.off()
            sss()
        elif cmd=="1on":
            print("on")
            p1.on()
            sss()
        elif cmd=="2of":
            print("2of")
            p0.off()
            sss()
        elif cmd=="2on":
            print("2on")
            p0.on()
            sss()
        elif cmd=="1da":
            print("1da")
            dianruzi_dangwei=4
            sss()
        elif cmd=="2da":
            print("2da")
            dianruzi_dangwei=3
            sss()
        elif cmd=="3da":
            print("3da")
            dianruzi_dangwei=2
            sss()
        elif cmd=="4da":
            print("4da")
            dianruzi_dangwei=1
            sss()
        elif cmd=="0da":
            print("0da")
            dianruzi_dangwei=0
            sss()
        elif cmd=="shx":
            print("shx")
            sss()
        elif cmd=="xof":
            print("3of")
            s2.connect(addr2)
            sss="GET /?mcu_do=1of  http/1.1\r\n"
            s2.send(sss.encode('utf-8'))
            sss="HOST:192.168.123.253\r\n"
            s2.send(sss.encode('utf-8'))    
            s2.close()
            cl.close()
        elif cmd=="xon":
            print("3on")
            s2 = socket.socket()
            s2.connect(addr2)
            sss="GET /?mcu_do=2on  http/1.1\r\n"
            s2.send(sss.encode('utf-8'))
            sss="HOST:192.168.123.253\r\n\r\n"
            s2.send(sss.encode('utf-8'))    
            
            cl.send(s2.recv(100))
            s2.close()
            cl.close()
        
        elif cmd=="rst":
            machine.reset()

        
        elif cmd=="xgd":
          dingshishijian[0]=int(llll[l+10:l+13])-100
          dingshishijian[1]=int(llll[l+13:l+16])-100
          dingshishijian[2]=int(llll[l+16:l+19])-100
          print(7)
          dingshishijian[3]=int(llll[l+19:l+22])-100
          print(8)
          dddx=uio.open("dingshishijian.txt", mode='w')
          dddx.write(str(dingshishijian[0])+","+str(dingshishijian[1])+","+str(dingshishijian[2])+","+str(dingshishijian[3]))
          dddx.close()
          cl.send("ok")
          cl.close()

        elif cmd=="dqd":
          jj=str(dingshishijian[0])+","+str(dingshishijian[1])+","+str(dingshishijian[2])+","+str(dingshishijian[3])+"#"+"{:0>2d}年{:0>2d}月{:0>2d}日 {:0>2d}:{:0>2d}:{:0>2d} ".format(*time.localtime())
          fasong(cl,jj)
          cl.close()

          
    else:
      l=llll.lower().find("favicon")
      if not l==-1:
         print("favicon")
         cl.write(header404)
         cl.close()
      else:
         print("5")
         fasong(cl,html)         
         #cl.write(header.format(len(html),html))         
         cl.close()
  except  Exception as e:
        cl.close()
        print( "cuowu",e)
    
 

--------------------------------------分割线-----------------------------------------------------

autojs代码:

var url = "192.168.123.253?mcu_do=2da";
var res = http.get(url);
if(res.statusCode == 200){
    toast(res.body);
}else{
    toast("请求失败:" + res.statusMessage);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
2022 / 01/ 30: 新esptool 刷micropython固件指令不是 esptool.py cmd... 而是 esptool cmd... 即可;另外rshell 在 >= python 3.10 的时候出错解决方法可以查看:  已于2022年发布的: 第二章:修复rshell在python3.10出错 免费内容: https://edu.csdn.net/course/detail/29666 micropython语法和python3一样,编写起来非常方便。如果你快速入门单片机玩物联网而且像轻松实现各种功能,那绝力推荐使用micropython。方便易懂易学。 同时如果你懂C语音,也可以用C写好函数并编译进micropython固件里然后进入micropython调用(非必须)。 能通过WIFI联网(2.1章),也能通过sim卡使用2G/3G/4G/5G联网(4.5章)。 为实现语音控制,本教程会教大家使用tensorflow利用神经网络训练自己的语音模型并应用。为实现通过网页控制,本教程会教大家linux(debian10 nginx->uwsgi->python3->postgresql)网站前后台入门。为记录单片机传输过来的数据, 本教程会教大家入门数据库。  本教程会通过通俗易懂的比喻来讲解各种原理与思路,并手把手编写程序来实现各项功能。 本教程micropython本是 2019年6月发布的1.11; 更多内容请看视频列表。  学习这门课程之前你需要至少掌握: 1: python3基础(变量, 循环, 函数, 常用库, 常用方法)。 本视频使用到的零件与淘宝上大致价格:     1: 超声波传感器(3)     2: MAX9814麦克风放大模块(8)     3: DHT22(15)     4: LED(0.1)     5: 8路5V低电平触发继电器(12)     6: HX1838红外接收模块(2)     7:红外发射管(0.1),HX1838红外接收板(1)     other: 电表, 排线, 面包板(2)*2,ESP32(28)  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值