OH2 rule/script not running anymore under OH3

Hello,

I recently updated to OH3 and the rule below stopped working. I updated it to the form shown here now but it seems I am still missing something. The purpose of the rule is to check if the Smart Plug still measures power consumption and if not after 10 Minutes to trigger certain actions.

My I kindly ask for your guidance how I can update this rule to work in OH3?

triggers:
  - id: "1"
    configuration:
      itemName: Verbrauch_Kodi
      previousState: ""
    type: core.ItemStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/vnd.openhab.dsl.rule
      script: >
        if(Verbrauch_Kodi.state < 2){ 
            if (timerKodiabschalten===null) {  
        	        timerKodiabschalten = createTimer(now.plusMinutes (10), [ |
                    if(Verbrauch_Kodi.state < 2){     
        	            Kodi_Energiezufuhr.sendCommand(OFF)
                    Lebensbaum_Licht.sendCommand(OFF)
                    KrakeImWohnzimmer_Helligkeit.sendCommand(0)
                    }
                    timerKodiabschalten = null
                ])}
        }

        if(Verbrauch_Kodi.state >= 2){
            timerKodiabschalten?.cancel
            timerKodiabschalten = null   		// cancel timer if power consumption raises
        }
    type: script.ScriptAction

ps: I there a guide on how to change OH2 rules to OH3 rules?

First of all, this rule as originally written in OH 2 probably would have worked in OH 3 unchanged. While there are some breaking changes mostly having to do with date times, .rules files from OH 2 are OH 3 rules.

But you are looking to convert a .rules file defined rule to a UI defined rule. There is one major difference between rules defined in a .rules file and those defined in the UI. In a .rules file, you have a place outside the rule to define variables. That’s where you define variables that you want to share between rules or want to preserve from one run of the rule to the next.

In the UI, there is no outside the rule. So every time that rule runs, it’s going to complain that timerKodiabschaklten doesn’t exist, because it doesn’t. But even if it did, it would always be null because it get recreated every time the rule runs.

So your options are:

  • keep the rule in a .rules file as you had it before
  • use a different language in the UI to implement this

Blockly, a graphical rules language now supported by OH 3 supports saving variables that survive from one run of the rule to the next. JSScripting (a separate installable add-on) even supports sharing variables between different rules through a cache. Note that for both of these though you will need to be running the just release 3.2 or later.

Thank you for your comprehensive answer which clarified a big misunderstanding for me regarding the outside of a rule.

I opted for the simple solution: keep the rule in a .rules file.