UoM how best to perform mathematical comparison's

I am struggled with UoM, I am looking at doing some maths to values that are different QuantityTypes Dimensionless, Temperature are the two main ones.

When the measurement values are provided as plain Numbers then I have no issues with performing maths on these values. Now as my device types around the house expands I am finding I may have sensors that are supported by different bindings some that present the values as plain numbers and some that use UoM.

I am looking for two things I think, one an easy way to distinguish programmatically in a rule that a value is not a plain number and secondly to then do the comparison for a UoM value with thresholds that are held as DecimalType.

I have read a few threads on UoM and non of them quite match what I am trying to achieve.



if(MyItem.state instanceof QuantityType)

Though be aware that will be false if the Item’s state is NULL or UNDEF too.

Usually you will already know that a given item has uom or not though so it should be rare to have such tests inn rules.

Why not store the threasholds with the same units?

First you have to make sure that the undefined units of your thteashold matches the default units of your item. The item might hold degrees f but because of your regional settingds log and present as degrees c. If that all checks out, then you just need to convert the QuantityType to a primitive.

if((MyItem.state as QuantityType).floatValue > MyThreasholdItem.state)

if you have a constant value, you can specify the units in a comparison with |unit. For example, 50|%% for a Dimensionless percent 50 or 10|km for 10 kilometees.

Thanks @rlkoshak I will try some of the suggestions out, for the time being I have avoided the binding using UoM and used node red to get the data and pass it through to OH. I see this as a short term workaround at present, while I learn better how to deal with UoM…

Two reasons:

  1. I do not know how to simple perform maths on UoM elements.
  2. I have multiple bindings that pass through tmp and humidity readings and so far only one with a couple uses the UoM. So easy to convert the least number of elements to meet the existing majority.



It’s easier to answer specifics but:

var sum = MyTempItem.state + 5 |°C
var sub = MyTempItem.state - 5 |°F // Note, it's the same MyTempItem, the conversion is done for you

if(MyTempItem.state > 25 |°C)

var sumItems = MyTempItem.state + MyOtherTempItem.state

These are all Rules DSL. MyTempItem and MyOtherTempItem are both the same units (Number:Temperature). To do math with Items of different units you must strip off the units.

1 Like