Rule Cannot reference [...] before it is defined Error


I try to creation a motion sensor rule, that when it´s dark and a motion is detected switch on a light and after 3 minutes turn it of.

I use the illuminance to ask if it´s dark (if there is a better way please tell meeee). But the sensor sends the value with the lux unit, so I have to write only the numbers in a variable. Is there a method to update the status of an sensor in the rule file?

The rule is not working switching everytime the Light and visual studio is showing the error:

Cannot reference the field 'Bewegung_Whz_Illuminance' before it is defined

Here my rule file:

var Timer tNachtlicht = null
var int Schwellwert = 5
var Number Flur_Lux = Bewegung_Whz_Illuminance.state as Number

rule "Bewegungsmelder"
  Item Bewegung_WhzLUMI_Presence changed from OFF to ON
  if(Flur_Lux < Schwellwert) {
  // Sollte der Timer bereits gesetzt sein, wird er verworfen
  if (tNachtlicht!== null) {
    tNachtlicht = null
  logDebug("Nachtlicht", "Schalte jetzt das Nachtlicht.")
  sendCommand(LED_Wohnzimmer002, "ON")
    tNachtlicht = createTimer(now.plusSeconds(180)) [|
      sendCommand(LED_Wohnzimmer002, "OFF")

I am not sure if I can help you as I am not a specialist in rules, but I have the same situation here to turn a light on if it is dark.

If the sensor sends an “ON” it should also send “OFF”.
I have here a simple rule to check illuminance and then turn the light on or not.
After the in the Thing configured time it automatically sends “OFF”.
You should check the parameters of the sensor Thing for the time between ON and OFF.

Thanks for your message. What do you mean with checking the time between ON and OFF?

You are using a global variable to store the state of this item. I think that way this variable is tried to be set when the rule is read and and that time the item isn’t known (I THINK, so I’m not sure!)

Using the item state that way will not use the current value when the rule is run, so I would suggest to define and set the variable Flur_Lux in the rule.

You can’t update a sensor, it’s representation in openHAB is a Thing. What you migth really want is to update the state of an item, however if it is linked to a channel of that thing such update will get overwritten the next time the sensor does an update report.

My sensors having parameter to set in Paper UI or Habmin.
One of them works like a timer, “OFF” is sent after a defined time e.g. 300sec.
This does the thing / sensor itself, so no need for a timer in OH rules.

Thank you I will try