Using variables and timers in rule

Hey guys,

after some problems with my old openHAB installation, I installed openHAB 3.2 and set it up from scratch.

I also tried to use the new rule engine with blockly - but I have a problem with a timer. The rule ist triggered if a member of my window group changed to any status. I want to receive a notification if a window is open more than x minutes (second timer with additional x minutes). Because of debugging the rule I set it up to 15 seconds :wink:

If I open any window in this group, the timer starts and I receive both notifications. But if I close the window before the first or second timer is over, I see that the timer is not running (log info in the else-condition).

This is my blockly rule:

And the result in javascript:

var minutesFirstTimer, minutesSecondTimer, actualState, triggeredItem, timer1, timer2;

var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);

var scriptExecution = Java.type('org.openhab.core.model.script.actions.ScriptExecution');

var zdt = Java.type('java.time.ZonedDateTime');

if (typeof this.timers === 'undefined') {
  this.timers = [];
}


minutesFirstTimer = 15;
minutesSecondTimer = 15;
actualState = event.itemState;
triggeredItem = event.itemName;
if (actualState == 'OPEN') {
  logger.info('Erster Timer gestartet.');
  timer1 = String(triggeredItem) + '_FirstTimer';
  if (typeof this.timers[timer1] === 'undefined' || this.timers[timer1].hasTerminated()) {
    this.timers[timer1] = scriptExecution.createTimer(zdt.now().plusSeconds(minutesFirstTimer), function () {
      if (itemRegistry.getItem(triggeredItem).getState() == 'OPEN') {
        events.sendCommand('NotificationAtHome', (['Das folgende Fenster ist länger als ',minutesFirstTimer,' Minuten offen: <br><b>* ',itemRegistry.getItem(triggeredItem).getLabel(),' </b>'].join('')));
        logger.info('Zweiter Timer gestartet.');
        timer2 = String(triggeredItem) + '_SecondTimer';
        if (typeof this.timers[timer2] === 'undefined' || this.timers[timer2].hasTerminated()) {
          this.timers[timer2] = scriptExecution.createTimer(zdt.now().plusSeconds(minutesSecondTimer), function () {
            if (itemRegistry.getItem(triggeredItem).getState() == 'OPEN') {
              events.sendCommand('NotificationAtHome', (['Das folgende Fenster ist länger als ',minutesFirstTimer + minutesSecondTimer,' Minuten offen: <br><b>* ',itemRegistry.getItem(triggeredItem).getLabel(),' </b><br><i>Hinweis:</i> Das war die letzte Benachrichtigung!'].join('')));
            } else {
              if (typeof this.timers[timer1] !== 'undefined') {
                this.timers[timer1].cancel();
                this.timers[timer1] = undefined;
              }
            }
            })
        }
      } else {
        if (typeof this.timers[timer1] !== 'undefined') {
          this.timers[timer1].cancel();
          this.timers[timer1] = undefined;
        }
      }
      })
  }
} else if (actualState == 'CLOSED') {
  if (typeof this.timers[timer1] !== 'undefined' && this.timers[timer1].isRunning()) {
    logger.info('Erster Timer abgebrochen.');
    if (typeof this.timers[triggeredItem] !== 'undefined') {
      this.timers[triggeredItem].cancel();
      this.timers[triggeredItem] = undefined;
    }
  } else {
    logger.info('Erster Timer läuft nicht');
  }
  if (typeof this.timers[timer2] !== 'undefined' && this.timers[timer2].isRunning()) {
    logger.info('Zweiter Timer abgebrochen.');
    if (typeof this.timers[triggeredItem] !== 'undefined') {
      this.timers[triggeredItem].cancel();
      this.timers[triggeredItem] = undefined;
    }
  } else {
    logger.info('Zweiter Timer läuft nicht');
  }
} else {
  logger.error(('Unerwarteter Status: ' + String(actualState)));
}

I’m a little bit confused :confused:

Please post your log and tell what you expect to happen.

Based on your script the timers will cancel if you close a window, therefore it should be expected that the timer is not running.

Hi,
this is the log:

2022-02-13 10:13:02.526 [INFO ] [openhab.event.ItemStateChangedEvent ] - Item 'SensorBuroFensterlinks_StateContact' changed from CLOSED to OPEN
==> /var/log/openhab/openhab.log <==
2022-02-13 10:13:02.527 [INFO ] [org.openhab.rule.393e24dd8c         ] - Erster Timer gestartet.
==> /var/log/openhab/events.log <==
2022-02-13 10:13:09.657 [INFO ] [openhab.event.ItemStateChangedEvent ] - Item 'SensorBuroFensterlinks_StateContact' changed from OPEN to CLOSED
==> /var/log/openhab/openhab.log <==
2022-02-13 10:13:09.659 [INFO ] [org.openhab.rule.393e24dd8c         ] - Erster Timer läuft nicht
2022-02-13 10:13:09.659 [INFO ] [org.openhab.rule.393e24dd8c         ] - Zweiter Timer läuft nicht

I expected, that the timer was running (and canceled), when the rule was triggered after I close the window.

A timer running means it is currently executing the code inside its timer block. This event will usually only last a few milliseconds, and you’d be (un)lucky to catch it when your rule retriggers.

A timer active means that the timer is currently counting down.

You may want to check whether your timer is active, rather than running.

Check the draft reference here.

(I also first thought that running meant that the timer was counting down - “the timer is running” in common parlance would usually suggest the same. I would have preferred executing and running instead of the current running and active respectively, but there’s history here!)

1 Like

Thank you :slight_smile:

Now it is working as expected :+1: