I have been trying out the blinking light lua code that seems to be popular on the forums:
------ SET THESE VARIABLES to match needs of your system ----- Secs = 1 ---->> Secs: Number of seconds between "Blinks" OffSecs = 1 Device = 8 ---->> Device: Device# of Outlet or Light to "BLINK" ------------------------------------------------------------------- Call ='urn:upnp-org:serviceId:SwitchPower1';Do ='SetTarget';Nil =""function BlinkOn()
luup.call_action(Call,Do,{newTargetValue=1},Device) -->BlinksOn
if (Run == 1) then
luup.call_timer(“BlinkOff”,1,Secs,Nil,Nil)
end
endfunction BlinkOff()
luup.call_action(Call,Do,{newTargetValue=0},Device) -->BlinksOff
if (Run == 1) then
luup.call_timer(“BlinkOn”,1,OffSecs,Nil,Nil)
end
endif (Run == 1) then
Run = 0
else
Run = 1
luup.call_timer(“BlinkOn”,1,OffSecs,Nil,1)
end
I have rewritten it and ended up like this:
------ SET THESE VARIABLES to match needs of your system ----- Secs = 1 ---->> Secs: Number of seconds between "Blinks" OffSecs = 1 Device = 8 ---->> Device: Device# of Outlet or Light to "BLINK" ------------------------------------------------------------------- Call ='urn:upnp-org:serviceId:SwitchPower1';Do ='SetTarget';Nil =""function TurnOn()
luup.call_action(‘urn:upnp-org:serviceId:SwitchPower1’,‘SetTarget’,{newTargetValue=1},Device)
return 0
endfunction TurnOff()
luup.call_action(‘urn:upnp-org:serviceId:SwitchPower1’,‘SetTarget’,{newTargetValue=0},Device)
return 0
endfunction BlinkOnce()
if BlinkRun == 1 then
TurnOn()
posix.sleep(Secs)
TurnOff()
posix.sleep(OffSecs)
end
return 0
endfunction Blinking()
while BlinkRun==1 do
BlinkOnce()
end
return 0
endrequire(“posix”)
if (BlinkRun == 1) then
BlinkRun = 0else
BlinkRun = 1
luup.call_timer(“Blinking”,1,1,Nil,Nil)
end
return 0
Now the latter code is tidier to my mind but still more convoluted than I’d like, it has ended up like that in a desperate attempt to make it work in a scene. The light blinks nicely, but when I attempt to run the scene again, it doesn’t immediately stop. The recursive code stops immediately. I don’t really understand the Vera / luup architecture. The documentation for the call_timer function (and call_delay) implies that a new worker thread is created to handle the function.
This means that the recursive code will be spinning up threads like a good’un doesn’t it? (Which is one reason I’m keen to find an alternative structure). When I ran top with the recursive version I could see a slight upward trend in memory used but I have no idea of the GC mechanisms in the lua engine so that might not be an issue. I don’t really know even whether the call_timer thread calls the BlinkOn and BlinkOff functions or creates a new thread and dies. I’m also assuming that all non-local variables have global scope and visibility across the lua engine, otherwise none of this would work, am I correct?
Apols for the rambling nature of this but I hope that somebody will be able to answer clarify things for me. Thanks for reading.