项目地址:
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, "([A-Z]+) (.+)?(.+) HTTP");
- local buf = "";
- local _GET = {}
- if (vars ~= nil)then
- for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
- _GET[k] = v
- end
- end
- buf = buf.."
ESP8266 Web Server
";
- buf = buf.."
GPIO0
";
- buf = buf.."
GPIO2
"..'Raw Data To MCU:
'..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参数传递参数)