Custom enumeration in rules

Hi,

I have several virtual items that have “custom” states mapped to numbers and wonder if there is a smart way to define custom state enumeration and use them in the code of the rules to improve readability.

For example, I have one item that stores the actual state or the house mode: 1=Presence, 2=Away, 3=Night.
In the code, currently I write:

if(my_item.state == 1){ //Presence
}

And I would like to have something like:

if(my_item.state == MODE_PRESENCE){
}

I could do this by declaring the whole list of constants. But to get them available from in all .rules files, I need to declare them in all files where they are used.
Is there an alternative to handle this in a smart way?

Thank you

I’d use a String Item in the first place and do away with the 1, 2, 3 and use “Presence”, “Away”, and “Night” in the first place. There is no reason to have to use a Number for this and if you use a String there is no need to do the mapping.

Then your comparison is self documenting:

if(my_item.state == "Presence")

You can use a .map file and the transform Action.
presence.map

1 = Presence
2 = Away
3 = Night
...
if(transform("MAP", "presence.map", myItem.state.toString) == "Presence")

I moved progressively from HomeSeer to Eventghost and then to openHAB: that is probably why I did not think about changing the type of items but that is the simpler way.

The transform() might slow down execution but has the advantage of lower refactoring of the code.

THank you!

Welcome to OH! :slight_smile:

Stuff like this isn’t going to have a noticeable impact on execution time. But I don’t really see how it saves refactoring over using a String. If you add a new state you only have to change code that cares about that new state, which you would have to do anyway with the transform.