nodeMCU典型代码

nodeMCU官方文档:https://nodemcu.readthedocs.io/en/master/en/modules/wifi/

1.发送UPD到服务器

wifi.setmode(wifi.STATION)
wifi.sta.config("enjoy2018","enjoy12345")
print(wifi.sta.getip())

cu=net.createConnection(net.UDP)
cu:on("receive",function(cu,c) print(c) end)
cu:connect(5683,"192.168.3.105")
cu:send("hello")

2.作为TCP服务器监听消息

wifi.setmode(wifi.STATION)
wifi.sta.config("enjoy2018","enjoy12345")
print(wifi.sta.getip())

sv = net.createServer(net.TCP, 30)

function receiver(sck, data)
  print(data)
  --sck:close()
end

if sv then
  sv:listen(80, function(conn)
    conn:on("receive", receiver)
    conn:send("hello world")
  end)
end

3.网页远程控制LED

wifi.setmode(wifi.STATION)
wifi.sta.config("ENJOY","enjoy2014enjoy")
print(wifi.sta.getip())
led2 = 4
gpio.mode(led2, gpio.OUTPUT)
gpio.write(led2, gpio.LOW);

srv=net.createServer(net.TCP, 30)
srv:listen(80,function(conn)
    conn:on("receive", function(client,request)
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        
        local _GET = {}
        
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET[k] = v
            end
        end
        
        buf = buf.."<h1> ESP8266 Web Server</h1>";
        buf = buf.."<p>GPIO2 <a href=\"?pin=ON2\">OFF</a> <a href=\"?pin=OFF2\">ON</a></p>";

    --下面两句这种方式使用chrome浏览器正常,但使用其他浏览器无法控制,各个浏览器解析不一样导致

    --上面两句在各个浏览器中可以正常控制
buf = buf.."<p>GPIO2 <a href=\"?pin=ON2\"><button>OFF</button></a> <a href=\"?pin=OFF2\"><button>ON</button></a></p>";  
        local _on,_off = "",""
        
        --if (vars ~= nil)then
        if(_GET.pin == "ON2")then
              gpio.write(led2, gpio.HIGH);
        elseif(_GET.pin == "OFF2")then
              gpio.write(led2, gpio.LOW);
        end
        --print("_GET.pin=".._GET.pin)
        --end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)

4.Udp服务器远程控制LED

--连接wifi
wifi.setmode(wifi.STATION)
wifi.sta.config("ENJOY","enjoy2014enjoy")
print(wifi.sta.getip())

--先关闭LED
led2 = 4;
gpio.mode(led2, gpio.OUTPUT)
gpio.write(led2, gpio.LOW);

--与UPD服务器通信
cu=net.createConnection(net.UDP)

function receiver(cu,c)
    if(c=="ON" or c=="on" )
    then
        gpio.write(led2, gpio.LOW);
        cu:send("turn led on")
    else
        gpio.write(led2, gpio.HIGH);
        cu:send("turn led off")
    end    
        print("udp recerve:",c) 
end

cu:on("receive",receiver)
cu:connect(5683,"192.168.1.117")
cu:send("hello")

--监控针脚数据
tmr.alarm(0, 1000, tmr.ALARM_AUTO, function()
    if (gpio.read(led2) == 0)     
    then
        cu:send("led status : on")
    else
        cu:send("led status : off")
    end
end
)

4.远程设置TCP服务器IP及端口

nodeMCU有双重身份,既是TCP server(用于初始连接),以是TCP client

(1)连接nodeMCU上Tcp Server服务

(2)通过TCP server发送要连接的服务器IP及端口

(3)创见TCP client客户端

wifi.setmode(wifi.STATION)  
wifi.sta.config("ENJOY","enjoy2014enjoy")  
print(wifi.sta.getip())  

print(wifi.sta.getip())

--字符串分割
function stringsplit(input, delimiter)
    input = tostring(input)
    delimiter = tostring(delimiter)
    if (delimiter=='') then return false end
    local pos,arr = 0, {}
    for st,sp in function() return string.find(input, delimiter, pos, true) end do
        table.insert(arr, string.sub(input, pos, st - 1))
        pos = sp + 1
    end
    table.insert(arr, string.sub(input, pos))
    return arr
end

--创建TCP客户端
function creatTcpClient(ip, port)
    clt = net.createConnection(net.TCP, 0)
    clt:on("receive", function(sck, c) 
        print(c) 
        sck:send("reveived")
    end)
    clt:on("connection", function(sck, c)
     -- print(c)
      sck:send("server connected")
    end)

    clt:connect(port, ip)
end


--作为服务器收到消息后设备TCP客户端要连接的IP
function receiveClientMsg(sck, data)  
  print(data)
  
  local str = data --"192.168.1.117:60" 
  local str_Arr =stringsplit(str,":")
  print(str_Arr[1])
  print(str_Arr[2])

  sck:send(data)
  creatTcpClient(str_Arr[1], str_Arr[2])
  sck:close()
end  


sv = net.createServer(net.TCP, 30)  
if sv then  
  sv:listen(80, function(conn)  
    conn:on("receive", receiveClientMsg)  
    conn:send("hello client")  
  end)  
end  

猜你喜欢

转载自blog.csdn.net/zouxin_88/article/details/80024206