mcunode 发表于 2017-4-22 17:29:25

nodemcu的网页穿透,网页控制LED实例


项目地址:https://github.com/IoTServ/NodeMcu-Proxy
先看下效果吧!分别点击那4个按钮,看nodemcu的反应

然后是nodemcu的控制效果,以打印数据代替


好了,上我的代码,自行改1,2,3行为自己的,我的id定为4567,2,3行为我家的路由器用户名密码
id = '4567'-自己设置自己的id替换4567
ssid = 'wifi名'
ssidpwd = 'wifi密码'
wifi.setmode(wifi.STATION)
wifi.sta.config(ssid,ssidpwd)    --set your ap info !!!!!!
wifi.sta.autoconnect(1)
led1 = 3
led2 = 4
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
function startServer()
conn=net.createConnection(net.TCP, 0)
conn:on("connection", function(conn, c)
conn:send(id)
tmr.alarm(2, 30000, 1, function()
      conn:send(' ')
end)
end)
conn:on("receive", function(conn, pl)
                local _, _, method, path, vars = string.find(pl, "(+) (.+)?(.+) HTTP");
                local buf = "";
                local _GET = {}
      if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET = v
            end
      end
      buf = buf.."<h1> ESP8266 Web Server</h1>";
      buf = buf.."<p>GPIO0 <a href=\"?pin=ON1\"><button>ON</button></a> <a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
      buf = buf.."<p>GPIO2 <a href=\"?pin=ON2\"><button>ON</button></a> <a href=\"?pin=OFF2\"><button>OFF</button></a></p>"..'<h3>Raw Data To MCU:</h3><br>'..pl;
      local _on,_off = "",""
      if(_GET.pin == "ON1")then
            gpio.write(led1, gpio.HIGH);
                        print('on led1')
      elseif(_GET.pin == "OFF1")then
            gpio.write(led1, gpio.LOW);
                        print('off led1')
      elseif(_GET.pin == "ON2")then
            gpio.write(led2, gpio.HIGH);
                        print('on led2')
      elseif(_GET.pin == "OFF2")then
            gpio.write(led2, gpio.LOW);
                        print('off led2')
      end
                conn:send(buf);
      collectgarbage(); end)
conn:connect(8001,"www.mcunode.com")
end
tmr.alarm(1, 1000, 1, function()
   if wifi.sta.getip()==nil then
                print("Connect AP, Waiting...")
   else
                tmr.stop(1)
                startServer()
      
   end
end)

如果id为4567(我自己设的id),访问页面地址为:http://www.mcunode.com/proxy/4567/index.html

其中4567可替换为自定义id,index.html可换为任意字符串,不影响连接(但必须有一个字符串),mcu可以获取此参数,建议为模拟文件名,至此,你就可以从公网随意访问nodemcu页面啦!(测试阶段,当前只支持Get方法通过url参数传递参数)
其实只要按照这个标准改都可以,心跳为一个空格,里面也有,反正几天都不会掉,现在已经测设了十几天没掉
页: [1]
查看完整版本: nodemcu的网页穿透,网页控制LED实例