---------------
-- connect as station to a Wifi Access Point
-- Use as : connecttoap("yourSSID","yourpassword")
connecttoap = function (ssid,pw)
print(wifi.sta.getip())
wifi.setmode(wifi.STATION)
wifi.sta.config(ssid,pw)
print("Connected to ",ssid," as ",wifi.sta.getip())
end
---------------
-- install a webserver
-- Use as : httpserver()
httpserver = function ()
srv=net.createServer(net.TCP) srv:listen(80,function(conn)
conn:on("receive",function(conn,payload) print(payload)
conn:send("HTTP/1.1 200 OK\n\n")
conn:send("
")
conn:send("Served from GWR's ESP8266
")
conn:send("NODE.CHIPID : " .. node.chipid() .. "
")
conn:send("NODE.HEAP : " .. node.heap() .. "
")
conn:send("GPIO0 : " .. gpio.read(8) .. "
")
conn:send("GPIO1 : " .. gpio.read(9) .. "
")
conn:send("ADC0 : " .. adc.read(0) .. "
")
conn:send("")
conn:on("sent",function(conn) conn:close() end)
end)
end)
print("httpserver installed. Browse to " .. wifi.sta.getip())
end
---------------
-- function httpget(ip,page)
-- A simple http client
-- Usage : httpget("192.168.0.20","index.html")
function httpget(ip,page)
sk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(80,ip)
sk:send("GET /" .. page .. " HTTP/1.1\r\nHost: ip" .. "\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
-- sk:on("sent",function(sk) sk:close() end)
end
---------------
function iot()
-- internet of things basiscs. Send ADC every #secs and Send GPIO at level change
-- usage : iot()
-- set GPIO0 to Interrupt mode and define interrupt procedure
gpio.mode(8,gpio.INT)
gpio0_tlow=15000
gpio0_thigh=50
gpio.trig(8, "both", function() print("GPIO0:" .. gpio.read(0)) httpget("192.168.0.11",node.chipid() .. ",gpio0," .. gpio.read(8) .. "," .. gpio0_tlow .. "," .. gpio0_thigh) end )
-- set GPIO1 to Interrupt mode and define interrupt procedure
gpio.mode(9,gpio.INT)
gpio1_tlow=10000
gpio1_thigh=50
gpio.trig(9, "both", function() print("GPIO1:" .. gpio.read(1)) httpget("192.168.0.11",node.chipid() .. ",gpio1," .. gpio.read(9)) end )
gpio.trig(9, "both", function() print("GPIO1:" .. gpio.read(1)) httpget("192.168.0.11",node.chipid() .. ",gpio1," .. gpio.read(9) .. "," .. gpio1_tlow .. "," .. gpio1_thigh) end )
-- send ADC to webserver every 5 seconds
tmr.alarm(5000, 1, function() adc0=adc.read(0) print("ADC(0):" .. adc0) httpget("192.168.0.11",node.chipid() .. ",adc0," .. adc0) end )
end
---------------
httpserver()
iot()