wifi.setmode(wifi.STATION)
cfg =
{
ip="192.168.1.67",
netmask="255.255.255.224",
gateway="192.168.1.65"
}
wifi.sta.setip(cfg)
wifi.sta.config("SSID","password")
wifi.sta.connect()
count = 0
state = 0
gpio.mode(5,gpio.INT,gpio.PULLUP)
function last ()
cant = count*0.0114
conn:send("last run="..cant.."")
conn:send("state= off")
conn:close()
state = 0
count = 0
end
function counter()
if state == 0 then
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload) print(payload) end)
conn:connect(80,'192.168.1.70')
conn:send("state= on ")
delay = 0
state = 1
count = 1
else
count = count + 1
tmr.delay(3000000)
end
tmr.alarm( 1,25000,0,function() last() end )
end
gpio.trig(5, "down",counter)
Don't use tmr.delay as this will kill your TCP stack
Beware of relay bounce -- just posted another post on this.
TCP events are async and in general if you do 2 in one callback that your code will barf. Use the socket:on() events to sequence your TCP I/O. I need to put a better worked example in my FAQ because I keep having to explain this.
This is the new code:
delay = 0
state = 0
gpio.mode(5,gpio.INT,gpio.PULLUP)
function client()
conn=net.createConnection(net.TCP, 0)
conn:connect(80,'192.168.1.70')
conn:send("state= "..state..", last run= "..cant.."")
end
function today ()
cant = count*0.0114
state = 0
client()
count = 0
end
function counter()
if state == 0 then
cant = 0
state = 1
count = 1
client()
else
x = tmr.now()
if x > delay then
delay = tmr.now()+3000000
count = count + 1
print(count)
end
end
tmr.alarm( 1,25000,0,function() today() end )
end
gpio.trig(5, "down",counter)