Cannot update Timer in lambda

  • Platform information:
    • Hardware: RP4 8Gb
    • OS: Bullseye
    • openHAB version: 3.2.0.M5

I am trying to create a script that uses a Timer to turn lights off if no motion has been detected for a fixed time. I created the following rule using the UI

configuration: {}
triggers:
  - id: "1"
    configuration:
      itemName: DenMotionSensor
      state: OK
      previousState: ""
    type: core.ItemStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      considerConditions: true
      ruleUIDs:
        - f627c72323
    type: core.RunRuleAction

which call this script:

val String logName = "den.rules"
val Integer timeoutSeconds = 3  //Time to leave lights on after motion no longer detected
var Timer occupancyTimer = null  //Tracks time until lights are to be turned OFF
  
if(occupancyTimer === null || occupancyTimer.hasTerminated()) {
  occupancyTimer = createTimer(
      now.plusSeconds(timeoutSeconds), 
      [|
          sendCommand(DenLights, OFF)
          occupancyTimer = null
          logInfo(logName, 
              "Motion stopped: timer expired, lights off")
      ]
  )
  logInfo(logName, "Motion stopped: timer started")
}
else {
    occupancyTimer.reschedule(now.plusSeconds(timeoutSeconds))
    logInfo(logName, "Motion stopped: timer rescheduled")
}

I get the following error: ā€œCannot refer to the non-final variable occupancyTimer inside a lambda expression; line 10, column 400, length 14.ā€ The script ran in OH2.5. I canā€™t identify the problem and donā€™t know how to correct it. Any suggestions will be appreciated.
As an aside, note that the error message refers to ā€œcolumn 400.ā€

Thatā€™s not going to work in GUI entered DSL scripts. If you need to use ā€˜globalsā€™, use file based rules (where there is somewhere ā€œoutsideā€ of the rule to create ā€˜globalsā€™)

1 Like

Just want to add a note that the JSScripting add-on has a cache feature that gives one a place to store data outside the rule and share data, like timers, between scripts and rules.

To get it out great itā€™s only available in the JSScripting add-on but there are currently plans to eventually move the feature to core so itā€™s available in all languages including Rules DSL.

Good things are coming down the way.

Thanks for the comments and help.
Does ā€œuse file based rulesā€ mean to create and access rules like was done in OH2.5?
Iā€™ll look at the JSScripting to learn how to use it.

Yes.

Itā€™s probably too soon. Maybe in a couple weeks.