3-51单片机WIFI学习(开发板8266底层源码介绍)

2018-04-18 16:24:12 浏览数 (1)

上一篇链接  http://www.cnblogs.com/yangfengwu/p/8743502.html

直接上源码:注意源码有两部分,第一部分是一开始的时候写在模块内部的,另一部分是存在手机内部的,方便后期更新功能

看第一部分的源码

亲们可以直接把下面的第一部分(注意只下载第一部分就行)的程序下载到8266里面就可以用自己的APP实现远程控制

怎么下载看我以前的文章,LUA开发的

代码语言:javascript复制
--[[
GPIO0--3
GPIO1--10
GPIO2--4
GPIO3--9
GPIO4--2
GPIO5--1
GPIO9--11
GPIO10--12
GPIO12--6
GPIO13--7
GPIO14--5
GPIO15--8
GPIO16--0
0--GPIO16   1--GPIO5   2--GPIO4   3--GPIO0   4--GPIO2
5--GPIO14   6--GPIO12  7--GPIO13  8--GPIO15  9--GPIO3    
10--GPIO1   11--GPIO9  12--GPIO10
]]

RelayPin=2;


splitStart = 1
splitIdex=0;
splitTable={}
function split(s, delim)
    if type(delim) ~= "string" or string.len(delim) <= 0 then
        return
    end
    splitStart = 1
    splitTable = {}
    while true do
        splitIdex = string.find (s, delim, splitStart, true) -- plain find
        if not splitIdex then
          break
        end
        table.insert (splitTable, string.sub (s, splitStart, splitIdex - 1))
        splitStart = splitIdex   string.len (delim)
    end
    table.insert (splitTable, string.sub (s, splitStart))
    
    return splitTable
end


wifi.setmode(wifi.STATION)

local updataFlage = 0

YouInitData1 = "NULL";
YouInitData2 = "NULL";
YouInitData3 = "NULL";
YouInitData4 = "NULL";


MyInitData1 = "";
MyInitData2 = "";
MyInitData3 = "";
MyInitData4 = "";

NodeMcuTimeInSecond = 0;
NodeMcuTimeInUSecond = 0;
NodeMcuTimeInrate = 0;
NodeMcuYear = 0;
NodeMcuMonth = 0;
NodeMcuDay= 0;
NodeMcuHour= 0;
NodeMcuMinute= 0;
NodeMcuSecond= 0;
NodeMcuWeekday= 0;
NodeMcuRtctime={};
NodeMcuTimer={};
NodeMcuTimerList={};
NodeMcuDataString="nil"
NodeMcuTimeString="nil";
NodeMcuWeekdayString="nil";

mqttConnectedFlage = 0;
NodeMcuRequestTime=0

sntpAddress="nil";

updataCnt = 0;
linkcnt=0;
printtimeCnt=0;
TCPReadDataOverTime = 0;

tmr.softwd(60)--watchdog 60S

clientid = wifi.sta.getmac()
SubscribeTopic = "yang/sw/"..clientid
PublishTopic = "feng/sw/"..clientid


if  file.open("InitData.lua", "r") then
    local MyInitData = file.read();
    local DataList = split(MyInitData, ';');
    if  DataList[1] == "MyData" then
        MyInitData1 = DataList[2]
        MyInitData2 = DataList[3]
        MyInitData3 = DataList[4]
        MyInitData4 = DataList[5]
    end
else
    print("no InitData")  
end


print("Topic = switch/"..clientid)
print("MyInitData1 = "..MyInitData1)
print("MyInitData2 = "..MyInitData2)
print("MyInitData3 = "..MyInitData3)
print("MyInitData4 = "..MyInitData4)


--[[Connect the phone to the ap]]
apcfg={}
apcfg.ssid="qqqqqq"
apcfg.pwd="11223344"
wifi.sta.config(apcfg)
wifi.sta.connect()
--wifi.sta.autoconnect(1)


--[[The connection serve phone]]
connectIP="192.168.1.102"
ClientConnectedFlage = 0

ReceiveData = "";
ReceiveDataCopy = "";
UpdataDataCopy="";
ReceiveDataCnt = 0;
ReceiveDataCntCopy = 0;

function InitTimer0function()
    if  ClientConnectedFlage == 0 then
        Client = net.createConnection(net.TCP, 0) 
        --Client:connect(8888,connectIP)
        Client:connect(8888,gateway)
        
        Client:on("receive", function(Client, data) 
            ReceiveData = ReceiveData..data;
            ReceiveDataCnt = ReceiveDataCnt   1;
        end)
        Client:on("connection", function(sck, c) 
            ClientConnectedFlage = 1
            TcpConnect = Client
            print("Link OK")
            tmr.stop(0)
            Client:on("disconnection", function(sck, c) 
                ClientConnectedFlage = 0
                TcpConnect = nil
                tmr.start(0)
            end)
        end)
        
        if  ClientConnectedFlage == 0 then
            print("Link Error")
            updataCnt = 0;
            updataFlage = 0;
            linkcnt = linkcnt 1
            if  linkcnt >= 6 then
                linkcnt = 0
                if  TcpConnect ~= nil then
                    TcpConnect:close()
                end
                tmr.stop(0)
                tmr.stop(1)
                dofile("updata.lua");
            end
        end
    end
end
tmr.alarm(0, 1000, 1, InitTimer0function)



function disposedata(data)
    local DataList = split(data, ';');
    if  DataList[1] == "MyData" then
        if  file.open("InitData.lua", "w ") then
            file.write(data)--MyInitData
            file.close()
 
            MyInitData1 = DataList[2]
            MyInitData2 = DataList[3]
            MyInitData3 = DataList[4]
            MyInitData4 = DataList[5]
            
            print("MyInitData1 = "..DataList[2])
            print("MyInitData2 = "..DataList[3])
            print("MyInitData3 = "..DataList[4])
            print("MyInitData4 = "..DataList[5])
          
            if  TcpConnect ~= nil then
                TcpConnect:send(data);
            end
            
            print("write InitData success")     
        end
    elseif  DataList[1] == "YouData" then    
            if  TcpConnect ~= nil then
                TcpConnect:send("YouData;"..clientid..";"..SubscribeTopic..";"..PublishTopic..";"..YouInitData1..";"..
                                YouInitData2..";"..YouInitData3..";"..YouInitData4);
            end
            print("Send YouData success")   
    elseif  DataList[1] == "UpdataData" then  
            updataFlage = 1; 
            if  TcpConnect ~= nil then
                TcpConnect:send("WaitUpdataData0;");
            end     
            print("WaitUpdataData......")
            file.open("updata.lua", "w ")
    end
    ReceiveDataCopy = "";
end



function InitTimer1function()
   if  ReceiveDataCnt ~=0 then
       if   ReceiveDataCnt == ReceiveDataCntCopy then
            TCPReadDataOverTime = 0;
            
            ReceiveDataCopy = ReceiveData;
            ReceiveData = "";
            ReceiveDataCnt = 0;
            ReceiveDataCntCopy = 0;
            
            if  updataFlage == 0 then
                disposedata(ReceiveDataCopy);
            else
                if  ReceiveDataCopy ~= "UpdataDataSuccess" then
                    file.write(ReceiveDataCopy)
                    updataCnt = updataCnt   1
                    if  TcpConnect ~= nil then
                        TcpConnect:send("WaitUpdataData"..updataCnt..";");
                    end  
                    print("start down...")  
                else
                    if  TcpConnect ~= nil then
                        TcpConnect:send("UpdataDataSuccess");
                        TcpConnect:close()
                    end
                    file.close() 
                    updataFlage = 0  
                    print("UpdataDataSuccess")  
                    
                    tmr.stop(0)
                    tmr.stop(1)
                    --dofile("main.lua");
                    node.compile("updata.lua")
                    dofile("updata.lua");
                    --dofile("main.lc"); 
                end
                ReceiveDataCopy = "";
            end
       else
            ReceiveDataCntCopy = ReceiveDataCnt      
       end
   end
end
tmr.alarm(1, 400, 1, InitTimer1function)

gpio.mode(4,gpio.OUTPUT)--输出模式  
tmr.alarm(2, 500, 1, function()
    if  mqttConnectedFlage==1 then
        gpio.write(4,1-gpio.read(4))
        if  NodeMcuRequestTime == 0 then
            sntp.sync(sntpAddress,
            function()
                print("sync succeeded:"..sntpAddress)
                NodeMcuRequestTime = 1;
            end,
            function(index)
                print("failed : "..index)
            end)
        end
    end
    
    NodeMcurRtctime = rtctime.epoch2cal(rtctime.get() 28800)
    NodeMcuTimer = string.format("d;d;d;d;d;d;d", 
                        NodeMcurRtctime["year"], 
                        NodeMcurRtctime["mon"], 
                        NodeMcurRtctime["day"], 
                        NodeMcurRtctime["hour"] 8, 
                        NodeMcurRtctime["min"], 
                        NodeMcurRtctime["sec"],
                        NodeMcurRtctime["wday"])
               
    NodeMcuTimerList = split(NodeMcuTimer, ';');
    NodeMcuYear = tonumber(NodeMcuTimerList[1]);
    NodeMcuMonth = tonumber(NodeMcuTimerList[2]);
    NodeMcuDay = tonumber(NodeMcuTimerList[3]);
    NodeMcuHour = tonumber(NodeMcuTimerList[4]);
    NodeMcuMinute = tonumber(NodeMcuTimerList[5]);
    NodeMcuSecond = tonumber(NodeMcuTimerList[6]);
    NodeMcuWeekday = tonumber(NodeMcuTimerList[7]); 
    NodeMcuHour = NodeMcuHour - 8;   
    NodeMcuDataString=NodeMcuYear.."/"..NodeMcuMonth.."/"..NodeMcuDay;   
    NodeMcuTimeString=NodeMcuHour..":"..NodeMcuMinute..":"..NodeMcuSecond;   
    NodeMcuWeekdayString = NodeMcuWeekday.."";

    NodeMcuTimeInSecond,NodeMcuTimeInUSecond,NodeMcuTimeInrate= rtctime.get()
    
    if  NodeMcuHour == 2 and NodeMcuMinute == 2 and NodeMcuSecond == 2 then
        NodeMcuRequestTime = 0;
    end
    printtimeCnt = printtimeCnt  1;
    if printtimeCnt >20 then
       printtimeCnt = 0;
       print("Year="..NodeMcuYear..";Month="..NodeMcuMonth..";Day="..NodeMcuDay..";Hour="..
            NodeMcuHour..";Minute="..NodeMcuMinute..";Second="..NodeMcuSecond..";Weekday="..
            NodeMcuWeekdayString..";TimeInSecond="..NodeMcuTimeInSecond)
    end

    if  TcpConnect ~= nil then
        TCPReadDataOverTime = TCPReadDataOverTime  1;
        if TCPReadDataOverTime > 20 then
           TCPReadDataOverTime = 0;
           TcpConnect:close()
           dofile("updata.lua");
        end
    end
    
    
    tmr.softwd(60);
end)


printip = 0
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
    printip = 0
end)


wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
   if printip == 0 then
      ip,netmask,gateway = wifi.sta.getip()
      print(ip)
   end
   printip = 1
end)

 说一下源码

关于SNTP获取网络时间的问题,用阿里的博客写的

https://yq.aliyun.com/articles/511601?spm=a2c4e.11155435.0.0.15873312ZAcLKJ

直接把源码一贴,不好讲了,因为涉及的多...所以还是看后期自己一点一点的写源码吧

现在贴上第二部分源码,也就是存在手机上的,手机上就是这样存的,前面一点是接收用户配置的MQTT和WIFI的一些信息,所以做成这样子了

n是换行  " 的意思就是"  是因为特殊的字符在手机APP源码上要这样写

还有 "&#037  其实就是 "%   也是因为特殊字符的问题

代码语言:javascript复制
<string name="initupdata0">
        configwifissid = "%1$s";n
        configwifipwd= "%2$s";n
        MqttUserString = "%3$s";n
        MqttPwdString = "%4$s";n
        MqttIPString = "%5$s";n
        MqttPort = %6$d;n
        
        if configwifipwd == "nil" thenn
           configwifipwd = niln
        endn
        
        globalSendData ="nil"; n
        globalSendData1="nil";n
        globalSendData2="nil";n
        
        
        MemoryRelayState = "3";
        
        regulartime={};n
        regularoption={};n
        regularrepetition={};n
        DisposeOnceTime="nil";n
        
        RegularTimeLabel=0;n
        RegularTimeData="0";n
        RegularOptionLabel=0;n
        RegularOptionData="0";n
        RegularRepetitionLabel=0;n
        RegularRepetitionData="0";n
        RegularCustom={}n
        RegularCustomLabel=0;n
        RegularCustomData="0";n
        
        DelayData={};n
        DelayTime={};n
        DelayOption={};n
        DelayUnixTime={};n
        DelayunixTime=0;n
        DelayIndex=0;n
        
        DelayTimeLabel=0;n
        DelayTimeData="0";n
        DelayTimeDataNumber=0;n
        
        
        RelayNowState=0n
        RelayNowStateCopy=0n
        
        UsartReceiveData="";
        UsartReceiveDataCnt=0;
        UsartReceiveDataCntCopy=0;
        
        for i=0,7 don
            if  file.open("regular="..i..".lua", "r") thenn
                local list = split(file.read(), ";")n
                for _, s in ipairs(list) don
                    local mlist = split(s, "=")n
                    if  string.find(mlist[1],"time") thenn
                        regulartime[i] = mlist[2];print(regulartime[i])n
                    elseif  string.find(mlist[1],"option") then n
                        regularoption[i] = mlist[2];print(regularoption[i])n
                    elseif  string.find(mlist[1],"repetition") then n
                        regularrepetition[i] = mlist[2];print(regularrepetition[i])n
                    endn
                endn
                file.close() n
            endn
            if  file.open("delay="..i..".lua", "r") thenn
                local list = split(file.read(), ";")n
                for _, s in ipairs(list) don
                   local mlist = split(s, "=")n
                   if  string.find(mlist[1],"data") thenn
                       DelayData[i] = mlist[2];print(DelayData[i])n
                   elseif  string.find(mlist[1],"time") thenn
                       DelayTime[i] = mlist[2];print(DelayTime[i])n
                   elseif  string.find(mlist[1],"option") then n
                        DelayOption[i] = mlist[2];print(DelayOption[i])  n    
                   elseif  string.find(mlist[1],"unixTime") then n
                        DelayUnixTime[i] = mlist[2];print(DelayUnixTime[i])  n  
                   end     n
                endn
                file.close() n
            endn
            
        endn
        
        
        if  file.open("initpower.lua","r") thenn
            
        endn
        
        </string>
        
    <string name="initupdata0_0" formatted="false">
        if  file.open("switch=1.lua", "r") thenn
            if  file.read() == "relay=1" thenn
                gpio.write(RelayPin,1)n
                gpio.mode(RelayPin,gpio.OUTPUT)n
                RelayNowState=1n
                RelayNowStateCopy=1n
                print("relay=1")n
            endn
            if  file.read() == "relay=0" thenn
                gpio.write(RelayPin,0)n
                gpio.mode(RelayPin,gpio.OUTPUT)n
                RelayNowState=0n
                RelayNowStateCopy=0n
                print("relay=0")n
            endn
            file.close() n
        elsen
            print("open RelayState.lua faild")  n
        endn
           
        apcfg={}n
        apcfg.ssid=configwifissidn
        apcfg.pwd=configwifipwdn
        wifi.sta.config(apcfg)n
        --wifi.sta.connect()n
        wifi.sta.autoconnect(1)n
        
        Mymqtt = mqtt.Client(clientid, 120,MqttUserString, MqttPwdString);n
        
        tmr.alarm(3, 1000, 1, function()n
            Mymqtt:connect(MqttIPString, MqttPort, 0,ConnectSuccess,ConnectFailed)n
        end)n
        
        function ConnectSuccess(client)n
             client:subscribe(SubscribeTopic, 0, subscribeSuccess)n
             print("connected")n
             mqttClient = client;n
             tmr.stop(3);n
             if sntpAddress == "nil"  then n
                sntpAddress="ntp2.aliyun.com"; n
             end n
             mqttConnectedFlage = 1;n
        endn
        function ConnectFailed(client,reason)n
           mqttConnectedFlage = 0;n
           print("failed reason: " .. reason)n
           tmr.start(3)n
        endn
        function subscribeSuccess(client)n
            print("subscribe success") n
        endn
        </string>
        
       <string name="initupdata0_1" formatted="false">
            Mymqtt:on("message", function(client, topic, data) n
        local list = split(data, ";")n
        ControlRelayFlage = -1;n
        uart.write(0,data)n
        if  string.find(list[1],"regular") ~= nil thenn
            if  file.open(list[1]..".lua", "w ") thenn
                file.write(data)n
                file.close() n
                for _, s in ipairs(list) don
                    local mlist = split(s, "=")n
                    local aa = string.match(mlist[1],"&#037;d"); n
                    if  string.find(mlist[1],"time") thenn
                        regulartime[tonumber(aa)] = mlist[2];n
                    elseif  string.find(mlist[1],"option") then n
                        regularoption[tonumber(aa)] = mlist[2];n
                    elseif  string.find(mlist[1],"repetition") then n
                        regularrepetition[tonumber(aa)] = mlist[2];n
                    endn
                endn
                globalSendData1 = datan
            end  
        elseif string.find(list[1],"delay") ~= nil thenn
            if  file.open(list[1]..".lua", "w ") thenn
                file.write(data)n
                file.close() n
                for _, s in ipairs(list) don
                   local mlist = split(s, "=")n
                   local aa = string.match(mlist[1],"&#037;d");n
                   if  string.find(mlist[1],"data") thenn
                       DelayIndex = tonumber(aa);n
                       DelayData[tonumber(aa)] = mlist[2];n
                   elseif  string.find(mlist[1],"time") thenn
                       DelayTime[tonumber(aa)] = mlist[2];n
                   elseif  string.find(mlist[1],"option") then n
                        DelayOption[tonumber(aa)] = mlist[2]; n     
                   elseif  string.find(mlist[1],"unixTime") then n
                        DelayUnixTime[tonumber(aa)] = mlist[2];n    
                        DelayunixTime = tonumber(mlist[2]);n
                   end n    
                endn
                if  DelayunixTime &#060; NodeMcuTimeInSecond and DelayunixTime ~= 0 and DelayunixTime ~= 1 thenn
                    globalSendData1 = "delayerror="..DelayIndex..";data"..DelayIndex.."="..n
                    NodeMcuDataString..";".."time"..DelayIndex.."="..NodeMcuTimeStringn
                elsen
                    globalSendData1 = data;n
                endn
                DelayunixTime=0; n
                
            end
        elseif string.find(list[1],"switch") ~= nil then n
            if  file.open(list[1]..".lua", "w ") then n
                file.write(list[2]) n
                file.close() n
                for _, s in ipairs(list) do n
                    if  string.find(s,"relay=0") ~= nil then n
                        gpio.write(RelayPin,0) n
                        gpio.mode(RelayPin,gpio.OUTPUT) n
                        globalSendData1 = data n
                    endn
                    if  string.find(s,"relay=1") ~= nil then n
                        gpio.write(RelayPin,1) n
                        gpio.mode(RelayPin,gpio.OUTPUT) n
                        globalSendData1 = data n
                    endn
                endn
            end  n
        elseif string.find(list[1],"initpower") ~= nil thenn
            if  file.open(list[1]..".lua", "w ") thenn
                file.write(list[2])n
                file.close() n
                globalSendData1 = datan
            end    n
        elseif string.find(list[1],"SWStatus") ~= nil then n
               globalSendData1 = "switch=1;relay="..RelayNowState n   
        end n
    end)    n 
        
         </string>
         
       <string name="initupdata0_2" formatted="false">

tmr.alarm(4, 10, 1, function() n 
    if  mqttClient ~= nil and mqttConnectedFlage == 1 then n 
        RelayNowState = gpio.read(RelayPin) n 
        if  RelayNowState ~= RelayNowStateCopy then n 
            RelayNowStateCopy = RelayNowState n 
            globalSendData1 = "switch=1;relay="..RelayNowState n 
        end n 
    
        if  globalSendData1~="nil" then n 
            globalSendData=globalSendData1; n 
            globalSendData1="nil" n 
        elseif globalSendData2 ~="nil" then n 
            globalSendData=globalSendData2; n 
            globalSendData2="nil" n 
        else n 
            globalSendData="nil";     n 
        end n 
        if  globalSendData ~= "nil" then n 
            mqttClient:publish(PublishTopic,globalSendData, 0, 0, function(client)  n 
            end) n 
        end n 
    end       n 
    
    if UsartReceiveDataCnt ~= 0 then  n 
       if UsartReceiveDataCntCopy == UsartReceiveDataCnt then  n 
          UsartReceiveDataCnt=0;  n 
          UsartReceiveDataCntCopy = 0;  n 
          globalSendData2 = UsartReceiveData;  n 
          UsartReceiveData="";  n 
       else  n 
          UsartReceiveDataCntCopy = UsartReceiveDataCnt;  n 
       end  n 
    end  n 
end) n 

uart.setup(0, 115200, 8, uart.PARITY_NONE, uart.STOPBITS_1)
uart.on("data",0,function(data) 
    UsartReceiveData = UsartReceiveData..data;
    UsartReceiveDataCnt = UsartReceiveDataCnt   1;
end, 0)

tmr.alarm(0, 500, 1, function()  n 
    for  RegularTimeLabel, RegularTimeData in pairs (regulartime)  do n 
         if  RegularTimeData == NodeMcuTimeString  and DisposeOnceTime ~= NodeMcuTimeString then n 
             DisposeOnceTime = NodeMcuTimeString; n 
             if regularrepetition[RegularTimeLabel] ==  "everyday" then n 
                print("everyday") n 
                DisposeData(RegularTimeLabel); n 
             elseif  regularrepetition[RegularTimeLabel] ==  "work" then  n 
                if  NodeMcuWeekdayString=="2" or NodeMcuWeekdayString=="3" or NodeMcuWeekdayString=="4" or NodeMcuWeekdayString=="5" or NodeMcuWeekdayString=="6" then
                    print("work") n 
                    DisposeData(RegularTimeLabel); n 
                 end n 
             else n 
                 RegularCustom={} n 
                 RegularCustom = split(regularrepetition[RegularTimeLabel], ",");    n 
                 for RegularCustomLabel, RegularCustomData in ipairs (RegularCustom)  do n 
                     if RegularCustomData == NodeMcuWeekdayString then n 
                        print("custom") n 
                        DisposeData(RegularTimeLabel); n 
                     end n 
                 end  n 
             end n 
         else n 
            negationOnceTime="nil";    n  
         end n 
    end n 
    
    for  DelayTimeLabel, DelayTimeData in pairs (DelayUnixTime)  do n 
         --DelayTimeDataNumber = tonumber(DelayTimeData); n 
         if DelayTimeData == NodeMcuTimeInSecond.."" then n 
            if  DelayOption[DelayTimeLabel] == "on" then n 
                gpio.write(RelayPin,1) n 
                gpio.mode(RelayPin,gpio.OUTPUT) n 
                print("on") n 
             elseif  DelayOption[DelayTimeLabel] == "off" then n 
                gpio.write(RelayPin,0) n 
                gpio.mode(RelayPin,gpio.OUTPUT)  n 
                print("off") n 
             elseif  DelayOption[DelayTimeLabel] == "negation" then n 
                gpio.write(RelayPin,1-gpio.read(RelayPin)) n 
                gpio.mode(RelayPin,gpio.OUTPUT)     n 
                print("negation") n 
             end n 
         end n 
    end n 
end) n 


function DisposeData(label) n 
   if  regularoption[label] == "on" then n 
       gpio.write(RelayPin,1) n 
       gpio.mode(RelayPin,gpio.OUTPUT) n 
       print("on") n 
   elseif  regularoption[label] == "off" then n 
       gpio.write(RelayPin,0) n 
       gpio.mode(RelayPin,gpio.OUTPUT)  n 
       print("off") n 
   elseif  regularoption[label] == "negation" then n 
       gpio.write(RelayPin,1-gpio.read(RelayPin)) n 
       gpio.mode(RelayPin,gpio.OUTPUT)     n 
       print("negation") n 
   end n 
   print("pin="..gpio.read(RelayPin))  n   
end n 

           
           </string>

上面的不方便看,给大家一个直接可以下载用的

前面是路由器的和MQTT的信息,屏蔽了

代码语言:javascript复制
--configwifissid = "";
--configwifipwd="";
--MqttUserString = "";
--MqttPwdString = "";
--MqttIPString = "";
--MqttPort = ;

if configwifipwd == "nil" then
   configwifipwd = nil
end



globalSendData ="nil"; 
globalSendData1="nil";
globalSendData2="nil";


MemoryRelayState = "3";

regulartime={};
regularoption={};
regularrepetition={};
DisposeOnceTime="";

RegularTimeLabel=0;
RegularTimeData="";
RegularOptionLabel=0;
RegularOptionData="";
RegularRepetitionLabel=0;
RegularRepetitionData="";
RegularCustom={}
RegularCustomLabel=0;
RegularCustomData="";

DelayData={};
DelayTime={};
DelayOption={};
DelayUnixTime={};
DelayunixTime=0;
DelayIndex=0;

DelayTimeLabel=0;
DelayTimeData="";
DelayTimeDataNumber=0;


RelayNowState=0
RelayNowStateCopy=0

UsartReceiveData="";
UsartReceiveDataCnt=0;
UsartReceiveDataCntCopy=0;


for i=0,7 do
    if  file.open("regular="..i..".lua", "r") then
        local list = split(file.read(), ';')
        for _, s in ipairs(list) do
            local mlist = split(s, '=')
            if  string.find(mlist[1],"time") then
                regulartime[i] = mlist[2];print(regulartime[i])
            elseif  string.find(mlist[1],"option") then 
                regularoption[i] = mlist[2];print(regularoption[i])
            elseif  string.find(mlist[1],"repetition") then 
                regularrepetition[i] = mlist[2];print(regularrepetition[i])
            end
        end
        file.close() 
    end
    if  file.open("delay="..i..".lua", "r") then
        local list = split(file.read(), ';')
        for _, s in ipairs(list) do
           local mlist = split(s, '=')
           if  string.find(mlist[1],"data") then
               DelayData[i] = mlist[2];print(DelayData[i])
           elseif  string.find(mlist[1],"time") then
               DelayTime[i] = mlist[2];print(DelayTime[i])
           elseif  string.find(mlist[1],"option") then 
                DelayOption[i] = mlist[2];print(DelayOption[i])      
           elseif  string.find(mlist[1],"unixTime") then 
                DelayUnixTime[i] = mlist[2];print(DelayUnixTime[i])    
           end     
        end
        file.close() 
    end
    
end


if  file.open("initpower.lua","r") then
    
end


if  file.open("switch=1.lua", "r") then
    if  file.read() == "relay=1" then
        gpio.write(RelayPin,1)
        gpio.mode(RelayPin,gpio.OUTPUT)
        RelayNowState=1
        RelayNowStateCopy=1
        print("relay=1")  
    end
    if  file.read() == "relay=0" then
        gpio.write(RelayPin,0)
        gpio.mode(RelayPin,gpio.OUTPUT)
        RelayNowState=0
        RelayNowStateCopy=0
        print("relay=0")
    end
    file.close() 
else
    print("open RelayState.lua faild")  
end


apcfg={}
apcfg.ssid=configwifissid
apcfg.pwd=configwifipwd
wifi.sta.config(apcfg)
--wifi.sta.connect()
wifi.sta.autoconnect(1)

Mymqtt = mqtt.Client(clientid, 120,MqttUserString, MqttPwdString);


tmr.alarm(3, 1000, 1, function()
    Mymqtt:connect(MqttIPString, MqttPort, 0,ConnectSuccess,ConnectFailed)
end)

function ConnectSuccess(client)
     client:subscribe(SubscribeTopic, 0, subscribeSuccess)
     print("connected")
     mqttClient = client;
     tmr.stop(3);
     if sntpAddress == "nil"  then
        sntpAddress="ntp2.aliyun.com";
     end
     
     mqttConnectedFlage = 1;
end
function ConnectFailed(client,reason)
   mqttConnectedFlage = 0;
   print("failed reason: " .. reason)
   tmr.start(3)
end
function subscribeSuccess(client)
    print("subscribe success") 
end



Mymqtt:on("message", function(client, topic, data) 
    local list = split(data, ';')
    ControlRelayFlage = -1;
    uart.write(0,data)
    if  string.find(list[1],"regular") ~= nil then
        if  file.open(list[1]..".lua", "w ") then
            file.write(data)
            file.close() 
            for _, s in ipairs(list) do
                local mlist = split(s, '=')
                local aa = string.match(mlist[1],"%d"); 
                if  string.find(mlist[1],"time") then
                    regulartime[tonumber(aa)] = mlist[2];print(regulartime[tonumber(aa)])
                elseif  string.find(mlist[1],"option") then 
                    regularoption[tonumber(aa)] = mlist[2];print(regularoption[tonumber(aa)])
                elseif  string.find(mlist[1],"repetition") then 
                    regularrepetition[tonumber(aa)] = mlist[2];print(regularrepetition[tonumber(aa)])
                end
            end
            globalSendData1 = data
        end
    elseif string.find(list[1],"delay") ~= nil then
        if  file.open(list[1]..".lua", "w ") then
            file.write(data)
            file.close() 
            for _, s in ipairs(list) do
               local mlist = split(s, '=')
               local aa = string.match(mlist[1],"%d");
               if  string.find(mlist[1],"data") then
                   DelayIndex = tonumber(aa);
                   DelayData[tonumber(aa)] = mlist[2];print(DelayData[tonumber(aa)])
               elseif  string.find(mlist[1],"time") then
                   DelayTime[tonumber(aa)] = mlist[2];print(DelayTime[tonumber(aa)])
               elseif  string.find(mlist[1],"option") then 
                    DelayOption[tonumber(aa)] = mlist[2];print(DelayOption[tonumber(aa)])      
               elseif  string.find(mlist[1],"unixTime") then 
                    DelayUnixTime[tonumber(aa)] = mlist[2];print(DelayUnixTime[tonumber(aa)])    
                    DelayunixTime = tonumber(mlist[2]);
               end     
            end
            if  DelayunixTime < NodeMcuTimeInSecond and DelayunixTime ~= 0 and DelayunixTime ~= 1 then
                globalSendData1 = "delayerror="..DelayIndex..";data"..DelayIndex.."="..
                NodeMcuDataString..";".."time"..DelayIndex.."="..NodeMcuTimeString
            else
                globalSendData1 = data;
            end
            DelayunixTime=0;
            print(globalSendData1)
        end
    elseif string.find(list[1],"switch") ~= nil then
        if  file.open(list[1]..".lua", "w ") then
            file.write(list[2])
            file.close() 
            for _, s in ipairs(list) do
                if  string.find(s,"relay=0") ~= nil then
                    gpio.write(RelayPin,0)
                    gpio.mode(RelayPin,gpio.OUTPUT)
                    globalSendData1 = data
                end
                if  string.find(s,"relay=1") ~= nil then
                    gpio.write(RelayPin,1)
                    gpio.mode(RelayPin,gpio.OUTPUT)
                    globalSendData1 = data
                end
            end
        end  
    elseif string.find(list[1],"initpower") ~= nil then
        if  file.open(list[1]..".lua", "w ") then
            file.write(list[2])
            file.close() 
            globalSendData1 = data
        end 
    elseif string.find(list[1],"SWStatus") ~= nil then
           globalSendData1 = "switch=1;relay="..RelayNowState       
    end 
end)

--[[The Send Msg]]

tmr.alarm(4, 10, 1, function()
    if  mqttClient ~= nil and mqttConnectedFlage == 1 then
        RelayNowState = gpio.read(RelayPin)
        if  RelayNowState ~= RelayNowStateCopy then
            RelayNowStateCopy = RelayNowState
            globalSendData1 = "switch=1;relay="..RelayNowState
        end
    
        if  globalSendData1~="nil" then
            globalSendData=globalSendData1;
            globalSendData1="nil"
        elseif globalSendData2 ~="nil" then
            globalSendData=globalSendData2;
            globalSendData2="nil"
        else
            globalSendData="nil";    
        end
        if  globalSendData ~= "nil" then
            mqttClient:publish(PublishTopic,globalSendData, 0, 0, function(client) 
            end)
        end
    end 
    
    if UsartReceiveDataCnt ~= 0 then
       if UsartReceiveDataCntCopy == UsartReceiveDataCnt then
          UsartReceiveDataCnt=0;
          UsartReceiveDataCntCopy = 0;
          globalSendData2 = UsartReceiveData;
          UsartReceiveData="";
       else
          UsartReceiveDataCntCopy = UsartReceiveDataCnt;
       end
    end
end)


uart.setup(0, 115200, 8, uart.PARITY_NONE, uart.STOPBITS_1)

uart.on("data",0,function(data) 
    UsartReceiveData = UsartReceiveData..data;
    UsartReceiveDataCnt = UsartReceiveDataCnt   1;
end, 0)

tmr.alarm(0, 500, 1, function() 
    for  RegularTimeLabel, RegularTimeData in pairs (regulartime)  do
         if  RegularTimeData == NodeMcuTimeString  and DisposeOnceTime ~= NodeMcuTimeString then
             DisposeOnceTime = NodeMcuTimeString;
             if regularrepetition[RegularTimeLabel] ==  "everyday" then
                print("everyday")
                DisposeData(RegularTimeLabel);
             elseif  regularrepetition[RegularTimeLabel] ==  "work" then 
                if  NodeMcuWeekdayString=="2" or NodeMcuWeekdayString=="3" or NodeMcuWeekdayString=="4" or NodeMcuWeekdayString=="5" or NodeMcuWeekdayString=="6" then
                    print("work")
                    DisposeData(RegularTimeLabel);
                 end
             else
                 RegularCustom={}
                 RegularCustom = split(regularrepetition[RegularTimeLabel], ',');   
                 for RegularCustomLabel, RegularCustomData in ipairs (RegularCustom)  do
                     if RegularCustomData == NodeMcuWeekdayString then
                        print("custom")
                        DisposeData(RegularTimeLabel);
                     end
                 end 
             end
         else
            negationOnceTime="";    
         end
    end

    for  DelayTimeLabel, DelayTimeData in pairs (DelayUnixTime)  do
         --DelayTimeDataNumber = tonumber(DelayTimeData);
         if DelayTimeData == NodeMcuTimeInSecond.."" then
            if  DelayOption[DelayTimeLabel] == "on" then
                gpio.write(RelayPin,1)
                gpio.mode(RelayPin,gpio.OUTPUT)
                print("on")
             elseif  DelayOption[DelayTimeLabel] == "off" then
                gpio.write(RelayPin,0)
                gpio.mode(RelayPin,gpio.OUTPUT) 
                print("off")
             elseif  DelayOption[DelayTimeLabel] == "negation" then
                gpio.write(RelayPin,1-gpio.read(RelayPin))
                gpio.mode(RelayPin,gpio.OUTPUT)    
                print("negation")
             end
         end
    end
end)


function DisposeData(label)
   if  regularoption[label] == "on" then
       gpio.write(RelayPin,1)
       gpio.mode(RelayPin,gpio.OUTPUT)
       print("on")
   elseif  regularoption[label] == "off" then
       gpio.write(RelayPin,0)
       gpio.mode(RelayPin,gpio.OUTPUT) 
       print("off")
   elseif  regularoption[label] == "negation" then
       gpio.write(RelayPin,1-gpio.read(RelayPin))
       gpio.mode(RelayPin,gpio.OUTPUT)    
       print("negation")
   end
   print("pin="..gpio.read(RelayPin))   
end

后期一点一点做的时候就明白了,一下子这么多实在让人受不了..............

其实只要会基本的功能了,其余的都是看个人的发挥了

0 人点赞