Check item and set to default

Today my question is: How to validate an item in a rule and if the item or its state is not valid set it to a default value? I searched the forum, but did not find a solution. As far as i understand the lifcycle of an item is as follows:

1.) The item is not existing, so i cloud check if it ist null
2.) If the item in not equal null it is existant and the state is NULL
3.) If there is something wrong the bindig cloud set the state of the item to UNDEF
4.) In any other case the state of an item reflects the state like ON or a number or something else

Based on this a general rule to validate could be like this:

    val myItemDefaultValue = 12
    var Number myItemValue

    if (myItem === null) {
        Thread::sleep(200) // Wait 200ms for the system
    }
    if ((myItem.state == NULL) || (myItem.state == UNDEF)) {
        myItem.sendCommand(myItemDefaultValue)
    } else {
        myItemValue = myItem.state as DecimalType
    }

At the end we have a valid value to work within a rule. Maybe there is another way to do this. Maybe a general lamdba.

any suggestions?

The life cycle isn’t quite as you describe.

If the Item doesn’t exist and you try to access it by name you will get a “no such method” or “no such symbol” error. You can’t rely on the Item being null.

If you did something like:

if(NonExistingItem != null)

First if all it probably won’t parse the .rules file at all and fail on a syntax error. In the situation where the Item will be there but just isn’t there yet (i.e. rules start running before Items are fully loaded) then it will fail with something like “No such method equals on object null” it something like that.

I know of no way to test if an Item exists in Rules short of going to the REST API. The Rules are set up where if you made it past loading the .rules file then you are not referring to Items that don’t exist. If you were you would have failed at the point if loading the file.

1 Like