Equivalent of C# enum in Hubitat Groovy

Hi folks!

I'm a newbie in Groovy (and in HE, as a matter of facts) and I'm developing my first Hubitat app/driver and I'm facing some unexpected difficulties ...

Forgive me if I'm wrong, but so far I've learned that some statements available in Groovy are not available in HE Groovy, e.g., the enum statement. I don't like to use literals anywhere in my codings, so, the absence of the enum statement is bugging me.

This is what I would use in C#:

enum lockStates
{
Uncalibrated = 0,
Locked = 1,
Unlocking = 2,
Unlocked = 3,
Locking = 4,
Unlatched = 5,
Unlatched = 6,
Unlatching = 7,
MotorBlocked = 254,
Undefined = 255
}

I've searched a lot and I could not find an alternative/substitute. Any suggestion??

Thanks in advance!

Are you just trying to match numeric keys to their string/"friendly name" values? If so, you could try something like this towards the top of your script (after any imports--one more of which you'll have to include as below--but before metadata is the usual spot):

import groovy.transform.Field

@Field static Map myMap = [0: 'Uncalibrated', 1:'Locked', 2:'Unlocking']

You could then do something like:

def myString = 'Unlocking'
def theNumber = myMap.find { it.value == myString }

to go back to 2 (here theNumber) or, of course, something like myMap[2] to get 'Unlocking'. I'm not sure what your actual use is for this, but maybe this would work?

3 Likes

That’s what I’d do, too.

Here’s a slick cheat-sheet for interacting with maps in groovy:

https://www.tutorialspoint.com/groovy/groovy_maps.htm

1 Like

@bertabcd1234, this will do!

import groovy.transform.Field

@Field static Map myMap = [0: 'Uncalibrated', 1:'Locked', 2:'Unlocking']

Additionally, it solved my problem of using it throughout my code. I've tested it using the "state" variable, but it was no good, since it was shown on the UI - not and info that is relevant for the user, no? NTKB always !

Thanks!

1 Like

@adamkempenich, thanks for the tip !

2 Likes