First, I've found this website lovely and informative, esp as a newbie delving into the ESP8266. Thanks for all your contributions!
I have a project where i would like to get live sensor data. I also need a RESTful response to control the output of a few GPIO ports. I have the webserver working, but it doesn't refresh the sensor data on the page. I have looked at several examples, but I do not have enough understanding of how to refresh the output on the page, as i've tried adding the tmr.alarm, changed how the connection closes, etc, so here is my code and i'd love it if someone could point out what i should do.
wifi.setmode(wifi.STATION)
wifi.sta.config("----","-----")
print(wifi.sta.getip())
led = 1;
light = 0;
showlight="XX"
bimb=1
gpio.mode(led, gpio.OUTPUT)
function ReadADC()
light = adc.read(0)
showlight=(light)
print("light: "..showlight.."%")
end
ReadADC()
tmr.alarm(1,6000, 1, function() ReadADC() bimb=bimb+1 if bimb==50 then bimb=0 wifi.sta.connect() print("Reconnect")end end)
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.."<h1> ESP8266 Web Server</h1>";
buf = buf.."<p>LED <a href=\"?pin=ON1\"><button>ON</button></a> <a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
buf = buf..'<p>ADC <input style=\"text-align: center\"type=\"text\"size=4 name=\"j\"value=\"'..showlight..'\"> % of relative light<br><br></p>';
local _on,_off = "",""
if(_GET.pin == "ON1")then
gpio.write(led, gpio.HIGH);
elseif(_GET.pin == "OFF1")then
gpio.write(led, gpio.LOW);
end
if(light > 100)then
buf = buf.."<p>Light is ON</p>";
elseif(light < 100)then
buf = buf.."<p>Light is OFF</p>";
end
client:send(buf);
client:on("sent",function(conn) conn:close() end)
collectgarbage();
end)
end)
Thanks!