Skip to content

Commit 17ccc5d

Browse files
committed
Enforce that value is within range
1 parent 34b6799 commit 17ccc5d

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

src/main/java/com/beowulfe/hap/characteristics/FloatCharacteristic.java

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package com.beowulfe.hap.characteristics;
22

3-
import java.util.concurrent.CompletableFuture;
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
45

56
import javax.json.JsonNumber;
67
import javax.json.JsonObjectBuilder;
78
import javax.json.JsonValue;
9+
import java.util.concurrent.CompletableFuture;
810

911
/**
1012
* A characteristic that provides a Float value type.
@@ -13,6 +15,8 @@
1315
*/
1416
public abstract class FloatCharacteristic extends BaseCharacteristic<Double> {
1517

18+
private final static Logger LOGGER = LoggerFactory.getLogger(FloatCharacteristic.class);
19+
1620
private final double minValue;
1721
private final double maxValue;
1822
private final double minStep;
@@ -45,14 +49,11 @@ public FloatCharacteristic(String type, boolean isWritable, boolean isReadable,
4549
*/
4650
@Override
4751
protected CompletableFuture<JsonObjectBuilder> makeBuilder(int iid) {
48-
return super.makeBuilder(iid).thenApply(builder -> {
49-
return builder
50-
.add("minValue", minValue)
51-
.add("maxValue", maxValue)
52-
.add("minStep", minStep)
53-
.add("unit", unit);
54-
});
55-
52+
return super.makeBuilder(iid).thenApply(builder -> builder
53+
.add("minValue", minValue)
54+
.add("maxValue", maxValue)
55+
.add("minStep", minStep)
56+
.add("unit", unit));
5657
}
5758

5859
/**
@@ -69,7 +70,23 @@ protected Double convert(JsonValue jsonValue) {
6970
@Override
7071
protected final CompletableFuture<Double> getValue() {
7172
double rounder = 1 / this.minStep;
72-
return getDoubleValue().thenApply(d -> d == null ? null : Math.round(d * rounder) / rounder);
73+
return getDoubleValue().thenApply(d -> d == null ? null : Math.round(d * rounder) / rounder)
74+
.thenApply(d -> {
75+
if (d != null) {
76+
if (d < minValue) {
77+
LOGGER.warn("Detected value out of range " + d
78+
+ ". Returning min value instead. Characteristic " + this);
79+
return minValue;
80+
}
81+
if (d > maxValue) {
82+
LOGGER.warn("Detected value out of range " + d
83+
+ ". Returning max value instead. Characteristic " + this);
84+
return maxValue;
85+
}
86+
return d;
87+
}
88+
return null;
89+
});
7390
}
7491

7592
/**

0 commit comments

Comments
 (0)