当多个用户尝试连接到我的NodeMCU时出现问题



我正在使用Lua和NodeMCU板进行一个小项目,但我对这两个主题都是新手,我遇到了一些麻烦。

我在设备上连接了一个按钮,我想做的基本上是手动身份验证。在用户连接到nodeMCU上的服务器后,他将收到一个控制页面,他必须在其中按下按钮,刷新页面并查看我在设备上加载的网页。

我现在遇到的问题是,在一个用户按下按钮后,每个连接到服务器的新用户都会完全跳过第一阶段,直接连接到网页。

我一直在尝试一些解决方案,但没有一个真正奏效。我想在一个用户按下按钮后初始化一个字符串,它可以作为某种会话令牌,但我不知道这是否真的可行。有什么更简单的解决方案吗?

这是我到目前为止的代码:

auth.loa

srv=net.createServer(net.TCP)
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.."<html><body>"
buf = buf.."<h1> Control Web Server</h1>";
buf=buf.."<p> Press the button attached to the device and click below</p>"
buf=buf.."<p><button onclick="history.go(0)">ADVANCE</button></p>"
buf = buf.."</form></body></html>"
local _on,_off = "",""
gpio.mode(1 ,gpio.INPUT,gpio.PULLUP)
function debounce (func)
local last = 0
local delay = 200000
return function (...)
local now = tmr.now()
if now - last < delay then return end
last = now
return func(...)
end
end
function onChange()  
if gpio.read(1) == 0 then
assert(loadfile("server.lua"))
tmr.delay(500000)
end
end

gpio.trig(1,"down", debounce(onChange))
client:send(buf);
client:close();
collectgarbage();
end)
end)

server.loa

srv:listen(80,function(conn)
conn:on("receive", function(client,payload)
tgtfile = string.sub(payload,string.find(payload,"GET /")
+5,string.find(payload,"HTTP/")-2)
if tgtfile == "" then tgtfile = "index.htm" end  
local f = file.open(tgtfile,"r")
if f ~= nil then
client:send(file.read())
file.close()
else
client:send("<html>"..tgtfile.." not found - 404 error.<BR><a href='index.htm'/<%= @a %>>Home</a><BR>")
end
client:close();
collectgarbage();
f = nil
tgtfile = nil
end)
end)

我认为问题是在onChange函数中加载的server.lua中的srv:listen()也在端口80上。auth.lua中的srv:listen()不再被调用,因为它们都在端口80上,所以较新的listen()取而代之。

您必须以某种方式编写代码,使所有代码都在同一个srv:listen()函数中,并将有关客户端的信息(他们的IP、cookie或其他东西)存储在数组中。

最新更新