Bockly: Doing math with units?

If do some basic math with the blockly rule above.

Set current_P_Sum to curennt_P1 + current_P2 + current_P3

2022-09-02 15:19:59.577 [INFO ] [penhab.rule.wallbox_charging_current] - 2300 W2300 W2300 W
2022-09-02 15:19:59.578 [INFO ] [penhab.rule.wallbox_charging_current] - 6900

The unit “watt” gets lost.
And “magically” the unit of “e_Wallbox_CurrentP_Sum” changes from Watts to kW, because kW is set as Diyplay Unit for the item.

If It jumps into the else Path, everything works as assumed: watts is passed along as unit and the display unit is kW.

Is there a way to attach the unit as it is possible in “normal” rules?
Like mentioned here: Working with Number:Temperature Items in rules

Unfortunately I don’t have power channels that when created with number:power will result into a number with the unit, so I went forward and created an example with temperatures like so

The temperature items are defined as follows

The sumTempItemC is defined as

When I run the following rule

the result is as follows

[org.openhab.rule.temperatureSumRule ] - 12.78 °C12.59 °C
[org.openhab.rule.temperatureSumRule ] - 25.369999999999997
[org.openhab.rule.temperatureSumRule ] - 25.369999999999997 °C

which, to me, looks good in terms of temperatures.

The unit “watt” gets lost.

This is because the way javascript handles values with postfixes when doing math like adding numbers - it just strips them away when adding them (which honestly is kind of neat as you don’ t have to strip the unit first). Of course JavaScript has no clue about units at all.

If It jumps into the else Path, everything works as assumed:

In this case not addition is done in Javascript but the string containing the unit is just passed forwared

As you know W(att) and KW(att) are a tricky thing because strictly spoken >K< is not a unit but a magnitude (* 1000) and I doubt that this is taken into account when displaying the item.

As far as I know the display unit is just a label that is put behind the value.

In General:

  • When doing Math with units the unit prefixes get stripped of and the values are pure numbers
  • Unit Prefixes are powers of 10th which are not taken into account in formulas.

Final note:@rlkoshak has mentioned quite a bit related to that topic as well for example here: Extending Blockly with new openHAB commands - #344 by rlkoshak