I don’t think this is in the docs yet (I’ll open an issue shortly) and this is a little-known feature, or at least it was unknown to me until recently when I was exploring the source code for another reason.
We all know (or should know) that certain Items can receive commands of multiple types but internally store their state using only one of those types.
For example, a ColorItem can receive OnOffType, IncreaseDecreaseType, DecimalType, or HSBType in a sendCommand or postUpdate but it internally stores its state as an HSBType. So when you call
MyColorItem.state it returns an HSBType.
That can be annoying because it isn’t always clear how to tell when that light is ON from the HSBType. Will it always be
0,0,0 or can we only guarantee that the last number (Brightness) will be 0 when the light is OFF?
We are in luck. The developers thought ahead on this and have provided a
getStateAs method. You pass the class name of the Type you want the Item to return. So if you wanted a ColorItem’s state as an OnOffType to see if it is ON you can:
if(MyColorItem.getStateAs(OnOffType) == ON)
I’ll admit, I have not run the full gambit of tests to fully explore the full combination of potential behaviors on this method. For example, what happens if I called
MyDimmer.getStateAs(DecimalType)? I’m not sure why you would want to do that but while you cannot send a StringType to a MyColorItem, it should be possible and simple to get any Item’s state as a StringType.
I also don’t know what error gets generated when you try to getStateAs an incompatible type. If anyone has time to play, please respond with your results.