[SOLVED] No scope for variable?

Hi i want to make an rule for protecting rollershutter to not to be in motion too long. I read many topics and i cant understand something. I am makeing same i as found but nothing works.

firstly i tried this:

    rule "rollershutter1 safety"
when
    Item rollershutter1 changed to 1 or Item rollershutter1 changed to 2
then
    rollerTimer1 = createTimer(now.plusSeconds(20), [
      rollershutter1.sendCommand(0)
    ])
    if(rollershutter1 changed to 0){
      rollerTimer1.cancel
    }
end

but i got error:

[WARN ] [del.core.internal.ModelRepositoryImpl] - Configuration model 'rollershuttersafety.rules' has 
errors, therefore ignoring it: [8,12]: no viable alternative at input 'rollershutter1'
[8,39]: mismatched input ')' expecting 'end'

Then after many tries i make something like that

var rollerTimer1
rule "rollershutter1 safety"
when
    Item rollershutter1 changed to 1 or Item rollershutter1 changed to 2
then 
      logInfo("rs1", "nowy timer")
      rollerTimer1 = createTimer(now.plusSeconds(20), [
         rollershutter1.sendCommand(0) 
      ])
end

rule "rollerTimer1 cancel"
when
    Item rollershutter1 changed to 0
then
    if(rollerTimer1 !== null){
      rollerTimer1.cancel()
      rollerTimer1 = null
    }
end

and i got:

[ERROR] [untime.internal.engine.RuleEngineImpl] - Rule 'rollerTimer1 cancel': 'cancel' is not a 
member of 'null'; line 17, column 7, length 21

Is it mean may variable rollerTimer1 does not exist in rule ‘rollerTimer1 cancel’ ?

Haw can I make it works?

Try declaring rollerTimer1 at the beginning of the file, like this:

var Timer rollerTimer1=null

Thank you very much! It works.

Do you know why that part:

if(rollershutter1 changed to 0){
  rollerTimer1.cancel
}

generate that error?:

[WARN ] [del.core.internal.ModelRepositoryImpl] - Configuration model 'rollershuttersafety.rules' has 
errors, therefore ignoring it: [8,12]: no viable alternative at input 'rollershutter1'
[8,39]: mismatched input ')' expecting 'end'

Because it’s wrong. If you want to use this kind of condition, you should use the trigger part of the rule or you should use persistence service with the previousState method, like this:

if(rollerShutter1.previousState.state!=0&&rollerShutter1.state==0) {
//do something
}

But be aware that depending on the persistence service, the changing might not be recorded quickly enough for the rule to evaluate the condition above. Thus said, it would be much easier and more reliable to use the “changed to” statement in the trigger part of the rule.

Oh ok i get it now :). Thanks again :slight_smile: