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.