openhab/openhab-core

ECMAScript: Quantity can't be multiplied with negative value

Closed this issue · 2 comments

Since updating from 4.0.3 to 4.1.1 I can't multiply a Quantity with -1 anymore in ECMAScript. Before updating to 4.0.3 it worked as expected.

Expected Behavior

When multiplying a Quantity with -1, the result should be the original Quantity negated.

const {
    Quantity
} = require("openhab")

console.info(Quantity("0.5 °C").multiply(-1))
console.info(Quantity("0.5 °C").multiply(1))

should yield

-0.5 °C
0.5 °C

Current Behavior

The above example yields

-546.80 °C
0.5 °C

Steps to Reproduce (for Bugs)

Copy above snippet into the ECMAScript scratchpad or an otherwise empty js file in the automation/js folder of OpenHAB's config directory and watch the log file.

Context

I have a rule that reacts to button presses of an NSPanel used as a thermostat. The left button should decrease the setpoint by 0.5 °C. So I multipy the constant step of 0.5 °C by -1 for the left and by 1 for the right button.

Workaround

An additional constant Quantity("-0.5 °C") can be added to the current setpoint and yields the correct value.

Your Environment

  • Version used: OpenHAB 4.1.1 - official stable
  • Hardware: Raspberry Pi 5
  • OS: Raspbian Bookworm
  • OpenHAB JS Library: 4.8.1 in node_modules, but "Cache library injection" enabled
  • Node 20.11.1, NPM 10.2.4

See #3792

This is a change in behaviour introduced by the above PR on purpose. This only impacts temperatures. If you read the summary of the PR, it explains why it has changed in this way. It is by design. When multiplying, temperatures are considered from the absolute 0 K base.

If you want to work with Quantities in this case, use 0.5 K as factor for the multiplication.

This will give you the correct offset:

const {
    Quantity
} = require("openhab")

console.info(Quantity("0.5 K").multiply(-1))
console.info(Quantity("0.5 K").multiply(1))

Alternatively, in the rule where you increase/decrease, this will also work:

if (increase) {
    newTemp = oldTemp + Quantity("0.5 °C")
} else {
    newTemp = oldTemp - Quanity("0.5 °C")
}

After stepping through the code I understand what is happening and why.

Is there a reason why the negate function isn't available in ECMAScript Quantity type?

EDIT: Using 0.5 K as setpoint step works of course and makes total sense.