[mqtt] set the proper unit in the state description (#13604)

So that other pieces of openhab can know what unit it's going to be,
without it having a value yet. Importantly, any necessary conversion
that need to be applied to the other portion of the state description -
min, max, and step.

See also https://github.com/openhab/openhab-core/pull/3132

Signed-off-by: Cody Cutrer <cody@cutrer.us>
This commit is contained in:
Cody Cutrer 2022-10-27 00:34:50 -06:00 committed by GitHub
parent 234d354a2e
commit 26ad08cca9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 2 deletions

View File

@ -149,6 +149,11 @@ public class NumberValue extends Value {
if (min != null) { if (min != null) {
builder = builder.withMinimum(min); builder = builder.withMinimum(min);
} }
return builder.withStep(step).withPattern("%s %unit%"); if (!unit.equals(Units.ONE)) {
builder.withPattern("%s " + unit);
} else {
builder.withPattern("%s %unit%");
}
return builder.withStep(step);
} }
} }

View File

@ -75,7 +75,7 @@ public class SensorTests extends AbstractComponentTests {
publishMessage("zigbee2mqtt/sensor/state", "20"); publishMessage("zigbee2mqtt/sensor/state", "20");
assertState(component, Sensor.SENSOR_CHANNEL_ID, new QuantityType<>(20, Units.WATT)); assertState(component, Sensor.SENSOR_CHANNEL_ID, new QuantityType<>(20, Units.WATT));
assertThat(component.getChannel(Sensor.SENSOR_CHANNEL_ID).getState().getCache().createStateDescription(true) assertThat(component.getChannel(Sensor.SENSOR_CHANNEL_ID).getState().getCache().createStateDescription(true)
.build().getPattern(), is("%s %unit%")); .build().getPattern(), is("%s W"));
waitForAssert(() -> assertState(component, Sensor.SENSOR_CHANNEL_ID, UnDefType.UNDEF), 5000, 200); waitForAssert(() -> assertState(component, Sensor.SENSOR_CHANNEL_ID, UnDefType.UNDEF), 5000, 200);