forked from hap-java/HAP-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBooleanCharacteristic.java
More file actions
82 lines (73 loc) · 2.5 KB
/
BooleanCharacteristic.java
File metadata and controls
82 lines (73 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package io.github.hapjava.characteristics.impl.base;
import io.github.hapjava.characteristics.ExceptionalConsumer;
import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.json.JsonNumber;
import javax.json.JsonValue;
import javax.json.JsonValue.ValueType;
/**
* Characteristic that exposes a Boolean value.
*
* @author Andy Lintner
*/
public abstract class BooleanCharacteristic extends BaseCharacteristic<Boolean> {
private final Optional<Supplier<CompletableFuture<Boolean>>> getter;
private final Optional<ExceptionalConsumer<Boolean>> setter;
/**
* Default constructor
*
* @param type a string containing a UUID that indicates the type of characteristic. Apple defines
* a set of these, however implementors can create their own as well.
* @param description a description of the characteristic to be passed to the consuming device.
* @param getter getter to retrieve the value
* @param setter setter to set value
* @param subscriber subscriber to subscribe to changes
* @param unsubscriber unsubscriber to unsubscribe from chnages
*/
public BooleanCharacteristic(
String type,
String description,
Optional<Supplier<CompletableFuture<Boolean>>> getter,
Optional<ExceptionalConsumer<Boolean>> setter,
Optional<Consumer<HomekitCharacteristicChangeCallback>> subscriber,
Optional<Runnable> unsubscriber) {
super(
type,
"bool",
description,
getter.isPresent(),
setter.isPresent(),
subscriber,
unsubscriber);
this.getter = getter;
this.setter = setter;
}
/** {@inheritDoc} */
@Override
protected Boolean convert(JsonValue jsonValue) {
if (jsonValue.getValueType().equals(ValueType.NUMBER)) {
return ((JsonNumber) jsonValue).intValue() > 0;
}
return jsonValue.equals(JsonValue.TRUE);
}
@Override
public CompletableFuture<Boolean> getValue() {
return getter.isPresent() ? getter.map(booleanGetter -> booleanGetter.get()).get() : null;
}
@Override
public void setValue(Boolean value) throws Exception {
setValue(value, null);
}
@Override
public void setValue(Boolean value, String username) throws Exception {
if (setter.isPresent()) setter.get().accept(value, username);
}
/** {@inheritDoc} */
@Override
public Boolean getDefault() {
return false;
}
}