Closed kindmartin closed 5 years ago
Hi! Not sure if you really need such tricky logic. Cause run_once timer in this case can be replaced with time.sleep(). You see ... main goal of blynktimer is to fire different timers periodically within infinite loop. But anyway if your scipt logic really needs timers usage you can try such code:
import time
from blynktimer import Timer
blynk_timer = Timer(no_timers_err=False)
@blynk_timer.register(interval=5, run_once=True, stopped=True)
def function_1():
print(' [HERE TIMER EXECUTES SMTH]')
target_timer_id = list(blynk_timer.get_timers().keys())[0]
for i in range(1, 10000):
print(i)
print('Sleeping 1 sec ...')
time.sleep(1)
if i % 10 == 0:
blynk_timer.start(target_timer_id)
print('\n=== Timer was started ===')
while blynk_timer.timers[target_timer_id].fire_time is None or blynk_timer.timers[
target_timer_id].fire_time >= time.time():
blynk_timer.run()
print('=== Timer was stopped ===')
if i % 15 == 0:
break
print('-' * 30)
Before execution please update blynktimer.py - casue there were minor modifications related to current example. Just let me know if this example was helpful.
thanks, I will try both change the logic to just use time.sleep() and also try your code.
the original logic I was like normally timealarms c lib used there, ref https://github.com/PaulStoffregen/TimeAlarms
in particular: … If you want a timer to trigger once only, you can use the timerOnce method: Alarm.timerOnce(10, OnceOnly); // called once after 10 seconds This calls the onceOnly() function in a sketch 10 seconds after the timer is created. …
now in my python new code for air heater machine, I check every second if temp from a sensor is >= than a limit. If so I turn off the heat production, but keeping air pump for a while so extracting the residual heat on the burner/heat inter-exchange, lets say for 10 minutes after the top limit reach.
So now in my python code could be like (sorry for use global variables) where VentilacionOff10M() was aimed to turn off the air pump after ten minutes. Sorry Im not a deep skilled programmer, I hope anycase my case help others.
…..
@blynk_timer.register(interval=600,run_once=True) def VentilacionOff10M(): led_VT.off() # apago despues de 10M blynk.virtual_write(vLed_VT, 0) dprint2('Apago ventilacion')
@blynk_timer.register(interval=1) def updateBlynkServer(): global T_MIN4AA global T_MAX4AA global T_MIN4CF global T_MAX4CF global temperature global humidity global List_HT global Avg_HT global CF_SEASON global MANUAL_MODE global CF_ON global AA_ON global VT_ON
h, t = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, GPIO_DTH11PIN04, retries=3, delay_seconds=.5) if all([h, t]): List_HT.append([h,t])
Avg_HT = numpy.mean(List_HT, axis=0) # promedio de numpy para el ultima list matrix humidity = Avg_HT[0] temperature = Avg_HT[1]
if all([humidity, temperature]):
blynk.virtual_write(T_VPIN, temperature)
blynk.virtual_write(H_VPIN, humidity)
if (CF_SEASON == True and Piloto == 1 and MANUAL_MODE == False): # invierno / piloto / no modo manual
if temperature <= T_MIN4CF :
CF_ON = True
blynk.set_property(T_VPIN, 'color', T_LOW_COLOR)
led_VT.on() # si calefaccion sumo ventilador, igual deberia actucar la proteccion con el diodo desde CF a VT en la placa relays
blynk.virtual_write(vLed_VT, 255)
led_CF.on() # limite inferior alcanzado prendo calefaccion
blynk.virtual_write(vLed_CF, 255)
dprint2(' como temperature={} < limiteLow {} arranco CF'.format(temperature,T_MIN4CF))
# send notifications not each time but once a minute (6*10 sec)
if Counter.cycle % 300 == 0:
blynk.notify(T_LOW_MSG)
Counter.cycle = 0
else:
blynk.set_property(T_VPIN, 'color', T_COLOR)
if temperature >= T_MAX4CF : # limite superior alcanzado apago calefaccion
CF_ON = False
led_CF.off()
blynk.virtual_write(vLed_CF, 0)
led_VT.off() # si calefaccion sumo ventilador
blynk.virtual_write(vLed_VT, 0)
VentilacionOff10M() # continuo la ventilacion para aprovechar el calor residual en la maquina, luego de 10min apago
#
blynk.set_property(T_VPIN, 'color', T_HIGH_COLOR)
dprint2(' como temperature={} > limiteHigh {} apago CF'.format(temperature,T_MAX4CF))
if (CF_SEASON == True and Piloto == 0 ):
blynk.set_property(T_VPIN, 'color', ERR_COLOR) # show aka 'disabled' that mean we errors on data read
blynk.set_property(45, 'color', ERR_COLOR) # show aka 'disabled' that mean we errors on data read
dprint2('Piloto Apagado')
else: dprint2('[ERROR] reading DHT11 sensor data') blynk.set_property(T_VPIN, 'color', ERR_COLOR) # show aka 'disabled' that mean we errors on data read blynk.set_property(H_VPIN, 'color', ERR_COLOR)
Now I understood what you are expected to have. Please update blynktimer.py code again and try such script:
import time
from blynktimer import Timer, TimerError
blynk_timer = Timer()
@blynk_timer.register(interval=5, run_once=True)
def event():
print('[HERE GOES SOME EVENT AFTER 5 sec DELAY]')
target_timer_id = list(blynk_timer.get_timers().keys())[0]
for i in range(1, 1000):
print('[{}] - Sleeping 1 sec ...'.format(i))
time.sleep(1)
if i % 10 == 0:
print('\n=== Timer was started ===')
try:
while True:
blynk_timer.run()
except TimerError:
# disable timer stopped to be able run it next time again
blynk_timer.start(target_timer_id)
print('=== Timer was stopped ===\n')
if i % 35 == 0:
break
print('-' * 30)
Just inform me please about results
thanks now it works,M
I stil have a doubt, when I setup/define the run once timer it actually starts, so unintentionally after the timeout fire, in my case shutting down the air pump. is any way to setup /declare but not fire ?
Not sure that I understood your last question fully ... but lets try to explain. Blynktimer consists of timers manager and registered timers. Timers have two states started ( default) and stopped. If timer in started state it is still not running. Timer run cylcle and timers control performed by manager in loop (while True: blynk_timer.run()). So timer will be in running state only after first call of blynk_timer.run(). When run once timer fired - it's state will be automatically switched to stopped. Also manager can throw exception if all timers were stopped. Within exception handle procedure we can switch run once timer state from "stopped" to "started" and again later within other loop or after some condition run and control timer again ( while True: blynk_timer.run()).
Looks like all this a little bit complicated algorithm can be replaced by threads - but you see hardware unfortunately very limited in memory and CPU resources. Even simple time.sleep() often can be resources consuming. In attempt to bring more lightweight solution - blynktimer lib was developed.
Hope my explanation of script above will be helpful for you.
thanks antohaUa. your explanations was helpful. a final question how can I stop a running timer? I mean not waiting to fire but just stop or execute forcing timeout expiration.
something like blynk_timer.stop('0_VentilacionOff5M') will work?
That timer was defined like
@blynk_timer.register(interval=300,run_once=True) def VentilacionOff5M(): global MANUAL_MODE global VT_ON VT_ON = False led_VT.off() # apago despues de 5min blynk.set_property(vLed_VT, 'color', '#32CD32') blynk.virtual_write(vLed_VT, 0) # in app print(datetime.now(), 'timeout VentilacionOff5M, Apago ventilacion')
Yes blynk_timer.stop(timer_id) will work.... but just paying your attention that all timers logic controlled just by invoking blynk_timer.run() you see here you can use not only 'while True' infinite loops but some additional logic for loops also. while someCondition1 or someCondition2 : etc
Also correct place to control some events and timers is timer internal function that may contain additional conditions or extra logic. Here very easy just to bring final solution execute something or not execute after timer fired.
Anyway I have just listed possible options how to control events in your script - hope this will allow you to make your code more elegant and effective.
Good luck!
Can be closed
I was trying the examples here using for instance https://github.com/blynkkk/lib-python/blob/master/TIMERS.md
so that is ok including one time timer, but that is just issued at the start of the python script. I m looking for an example where I set if some condition got true then i need to set a timer after that moment.
I m familiar with normal C blynktimer code and setup & behavior, but still don't understand this python library.
any hint? thanks!