Skip to content

Commit 3aa1e1a

Browse files
author
Eugen
committed
Add Adaptive Lighting for lightbulbs
Adds AdaptiveLightingController, which receives the color temperature curve from a HomeKit controller and applies it through a handler. Supporting changes: writes with response ("r": true) answered with 207, instance ids stored on characteristics, TLV8 characteristic values.
1 parent a162ea5 commit 3aa1e1a

17 files changed

Lines changed: 1021 additions & 2 deletions

‎CHANGES.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# HAP-Java 2.0.10
2+
* Add Adaptive Lighting for lightbulbs (`AdaptiveLightingController`), with support for TLV8 characteristics and writes with response
23
* Add constructors with custom min/max to the window covering tilt angle characteristics [#162](https://github.com/hap-java/HAP-Java/issues/162)
34
* Add optional Mute characteristic to Doorbell service
45
* Fix leak of mDNS instances and shutdown hooks when stopping `HomekitRoot`
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package io.github.hapjava.characteristics;
2+
3+
import javax.json.JsonObjectBuilder;
4+
import javax.json.JsonValue;
5+
6+
/** A characteristic that answers a write with a value when the client requests it. */
7+
public interface WriteResponseCharacteristic extends Characteristic {
8+
9+
/**
10+
* Invoked by the remote client with a write that requests a response ("r": true).
11+
*
12+
* @param jsonValue the JSON serialized value to set.
13+
* @param username the authenticated username making the request
14+
* @param response the JsonObjectBuilder to add the "value" attribute of the response to.
15+
* @throws Exception if the value cannot be set.
16+
*/
17+
void setValueWithResponse(JsonValue jsonValue, String username, JsonObjectBuilder response)
18+
throws Exception;
19+
}

‎src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ public abstract class BaseCharacteristic<T> implements Characteristic, Eventable
3434
private final boolean isWritable;
3535
private final Optional<Consumer<HomekitCharacteristicChangeCallback>> subscriber;
3636
private final Optional<Runnable> unsubscriber;
37+
private volatile int instanceId;
3738

3839
/**
3940
* Default constructor
@@ -76,6 +77,20 @@ public String getType() {
7677
return type;
7778
}
7879

80+
/** @return the instance id assigned when the accessory was registered, 0 before. */
81+
public int getInstanceId() {
82+
return instanceId;
83+
}
84+
85+
/**
86+
* Called by the server when it assigns instance ids to the accessory's characteristics.
87+
*
88+
* @param instanceId the instance id
89+
*/
90+
public void setInstanceId(int instanceId) {
91+
this.instanceId = instanceId;
92+
}
93+
7994
@Override
8095
/** {@inheritDoc} */
8196
public final CompletableFuture<JsonObject> toJson(int iid) {

‎src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,14 @@ protected CompletableFuture<JsonObjectBuilder> makeBuilder(int iid) {
117117
});
118118
}
119119

120+
public int getMinValue() {
121+
return minValue;
122+
}
123+
124+
public int getMaxValue() {
125+
return maxValue;
126+
}
127+
120128
@Override
121129
public CompletableFuture<Integer> getValue() {
122130
return getter.map(integerGetter -> integerGetter.get()).orElse(null);
Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
package io.github.hapjava.characteristics.impl.lightbulb;
2+
3+
import io.github.hapjava.characteristics.Characteristic;
4+
import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback;
5+
import io.github.hapjava.characteristics.impl.base.BaseCharacteristic;
6+
import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic;
7+
import java.io.ByteArrayOutputStream;
8+
import java.util.Arrays;
9+
import java.util.Base64;
10+
import java.util.List;
11+
import java.util.Map;
12+
import java.util.Optional;
13+
import java.util.concurrent.CompletableFuture;
14+
import java.util.concurrent.ScheduledExecutorService;
15+
import java.util.concurrent.ScheduledFuture;
16+
import java.util.concurrent.TimeUnit;
17+
import org.slf4j.Logger;
18+
import org.slf4j.LoggerFactory;
19+
20+
/**
21+
* Adaptive Lighting for a lightbulb with brightness and color temperature. A HomeKit controller
22+
* sends a color temperature curve, which is applied in the interval the controller asks for and
23+
* adjusted to the current brightness.
24+
*
25+
* <p>Add {@link #getCharacteristics()} to the lightbulb service. Call {@link #update()} when the
26+
* brightness changes, and {@link #disable()} when the color temperature, hue or saturation is
27+
* changed other than through {@link AdaptiveLightingHandler#applyColorTemperature(int)}, including
28+
* writes from HomeKit.
29+
*/
30+
public class AdaptiveLightingController {
31+
32+
private static final Logger logger = LoggerFactory.getLogger(AdaptiveLightingController.class);
33+
34+
// TLV types as named in HAP-NodeJS, which documents the protocol
35+
private static final int SUPPORTED_TRANSITION_CONFIGURATION = 0x01;
36+
private static final int SUPPORTED_CHARACTERISTIC_IID = 0x01;
37+
private static final int SUPPORTED_TRANSITION_TYPE = 0x02;
38+
private static final byte TRANSITION_TYPE_BRIGHTNESS = 0x01;
39+
private static final byte TRANSITION_TYPE_COLOR_TEMPERATURE = 0x02;
40+
41+
private static final int READ_TRANSITION = 0x01;
42+
private static final int UPDATE_TRANSITION = 0x02;
43+
private static final int VALUE_TRANSITION_CONFIGURATION = 0x01;
44+
45+
private static final int VALUE_CONFIGURATION_STATUS = 0x01;
46+
private static final int STATUS_CHARACTERISTIC_IID = 0x01;
47+
private static final int STATUS_TRANSITION_PARAMETERS = 0x02;
48+
private static final int STATUS_TIME_SINCE_START = 0x03;
49+
50+
private final BrightnessCharacteristic brightness;
51+
private final ColorTemperatureCharacteristic colorTemperature;
52+
private final ScheduledExecutorService scheduler;
53+
private final AdaptiveLightingHandler handler;
54+
private final List<Characteristic> characteristics;
55+
private volatile HomekitCharacteristicChangeCallback activeTransitionCountCallback;
56+
private volatile Transition transition;
57+
private ScheduledFuture<?> updates;
58+
59+
/**
60+
* @param brightness the brightness characteristic of the lightbulb
61+
* @param colorTemperature the color temperature characteristic of the lightbulb
62+
* @param scheduler runs the color temperature updates
63+
* @param handler applies the color temperature and stores the state
64+
* @param savedState the state last passed to {@link AdaptiveLightingHandler#saveState(byte[])},
65+
* or null
66+
*/
67+
public AdaptiveLightingController(
68+
BrightnessCharacteristic brightness,
69+
ColorTemperatureCharacteristic colorTemperature,
70+
ScheduledExecutorService scheduler,
71+
AdaptiveLightingHandler handler,
72+
byte[] savedState) {
73+
this.brightness = brightness;
74+
this.colorTemperature = colorTemperature;
75+
this.scheduler = scheduler;
76+
this.handler = handler;
77+
characteristics =
78+
Arrays.asList(
79+
new Tlv8Characteristic(
80+
"00000144-0000-1000-8000-0026BB765291", this::supportedConfiguration, null),
81+
new Tlv8Characteristic(
82+
"00000143-0000-1000-8000-0026BB765291", this::transitionStatus, this::handleWrite),
83+
new IntegerCharacteristic(
84+
"0000024B-0000-1000-8000-0026BB765291",
85+
"uint8",
86+
"",
87+
0,
88+
255,
89+
null,
90+
Optional.of(() -> CompletableFuture.completedFuture(transition == null ? 0 : 1)),
91+
Optional.empty(),
92+
Optional.of(callback -> activeTransitionCountCallback = callback),
93+
Optional.of(() -> activeTransitionCountCallback = null)) {});
94+
if (savedState != null) {
95+
start(Transition.fromState(savedState));
96+
}
97+
}
98+
99+
/** @return the characteristics to add to the lightbulb service */
100+
public List<Characteristic> getCharacteristics() {
101+
return characteristics;
102+
}
103+
104+
/** Applies the color temperature for the current time and brightness. */
105+
public synchronized void update() {
106+
if (transition == null) {
107+
return;
108+
}
109+
Integer mired =
110+
transition.colorTemperature(System.currentTimeMillis(), brightness.getValue().join());
111+
if (mired == null) {
112+
disable();
113+
return;
114+
}
115+
handler.applyColorTemperature(
116+
Math.max(colorTemperature.getMinValue(), Math.min(colorTemperature.getMaxValue(), mired)));
117+
}
118+
119+
/** Turns Adaptive Lighting off. */
120+
public synchronized void disable() {
121+
if (transition == null) {
122+
return;
123+
}
124+
transition = null;
125+
updates.cancel(false);
126+
handler.saveState(null);
127+
notifyActiveTransitionCount();
128+
}
129+
130+
/** Stops the color temperature updates, e.g. when the accessory is removed. */
131+
public synchronized void stop() {
132+
if (updates != null) {
133+
updates.cancel(false);
134+
}
135+
}
136+
137+
private synchronized void start(Transition transition) {
138+
this.transition = transition;
139+
if (updates != null) {
140+
updates.cancel(false);
141+
}
142+
updates =
143+
scheduler.scheduleWithFixedDelay(
144+
this::scheduledUpdate, 0, transition.updateInterval, TimeUnit.MILLISECONDS);
145+
notifyActiveTransitionCount();
146+
}
147+
148+
private void scheduledUpdate() {
149+
// an exception would end the scheduled updates
150+
try {
151+
update();
152+
} catch (RuntimeException e) {
153+
logger.warn("Could not apply Adaptive Lighting", e);
154+
}
155+
}
156+
157+
private void notifyActiveTransitionCount() {
158+
HomekitCharacteristicChangeCallback callback = activeTransitionCountCallback;
159+
if (callback != null) {
160+
callback.changed();
161+
}
162+
}
163+
164+
private synchronized String handleWrite(String value) {
165+
Map<Integer, List<byte[]>> request = Tlv8.decode(Base64.getDecoder().decode(value));
166+
ByteArrayOutputStream response = new ByteArrayOutputStream();
167+
if (request.containsKey(READ_TRANSITION) && transition != null) {
168+
Tlv8.write(response, READ_TRANSITION, transition.configuration);
169+
}
170+
byte[] update = Tlv8.get(request, UPDATE_TRANSITION);
171+
if (update != null) {
172+
byte[] configuration = Tlv8.get(Tlv8.decode(update), VALUE_TRANSITION_CONFIGURATION);
173+
Transition newTransition = Transition.parse(configuration, System.currentTimeMillis());
174+
if (newTransition == null) {
175+
disable();
176+
Tlv8.write(response, UPDATE_TRANSITION, new byte[0]);
177+
} else {
178+
start(newTransition);
179+
handler.saveState(newTransition.toState());
180+
Tlv8.write(response, UPDATE_TRANSITION, status(newTransition, 0));
181+
}
182+
}
183+
return Base64.getEncoder().encodeToString(response.toByteArray());
184+
}
185+
186+
private String transitionStatus() {
187+
Transition current = transition;
188+
if (current == null) {
189+
return "";
190+
}
191+
long timeSinceStart = System.currentTimeMillis() - current.startMillis;
192+
return Base64.getEncoder().encodeToString(status(current, timeSinceStart));
193+
}
194+
195+
private static byte[] status(Transition transition, long timeSinceStart) {
196+
ByteArrayOutputStream status = new ByteArrayOutputStream();
197+
Tlv8.write(status, STATUS_CHARACTERISTIC_IID, transition.characteristicIid);
198+
Tlv8.write(status, STATUS_TRANSITION_PARAMETERS, transition.parameters);
199+
Tlv8.write(status, STATUS_TIME_SINCE_START, Tlv8.uint(timeSinceStart));
200+
ByteArrayOutputStream out = new ByteArrayOutputStream();
201+
Tlv8.write(out, VALUE_CONFIGURATION_STATUS, status.toByteArray());
202+
return out.toByteArray();
203+
}
204+
205+
private String supportedConfiguration() {
206+
ByteArrayOutputStream out = new ByteArrayOutputStream();
207+
Tlv8.write(
208+
out,
209+
SUPPORTED_TRANSITION_CONFIGURATION,
210+
supportedTransition(brightness, TRANSITION_TYPE_BRIGHTNESS));
211+
// list separator
212+
out.write(0);
213+
out.write(0);
214+
Tlv8.write(
215+
out,
216+
SUPPORTED_TRANSITION_CONFIGURATION,
217+
supportedTransition(colorTemperature, TRANSITION_TYPE_COLOR_TEMPERATURE));
218+
return Base64.getEncoder().encodeToString(out.toByteArray());
219+
}
220+
221+
private static byte[] supportedTransition(BaseCharacteristic<?> characteristic, byte type) {
222+
ByteArrayOutputStream out = new ByteArrayOutputStream();
223+
Tlv8.write(out, SUPPORTED_CHARACTERISTIC_IID, Tlv8.uint(characteristic.getInstanceId()));
224+
Tlv8.write(out, SUPPORTED_TRANSITION_TYPE, new byte[] {type});
225+
return out.toByteArray();
226+
}
227+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package io.github.hapjava.characteristics.impl.lightbulb;
2+
3+
/** Receives the color temperature and the state of an {@link AdaptiveLightingController}. */
4+
public interface AdaptiveLightingHandler {
5+
6+
/**
7+
* Sets the color temperature of the light.
8+
*
9+
* @param mired the color temperature in mired, within the range of the color temperature
10+
* characteristic
11+
*/
12+
void applyColorTemperature(int mired);
13+
14+
/**
15+
* Stores the state, to be passed to the controller after a restart.
16+
*
17+
* @param state the state, or null when Adaptive Lighting is off
18+
*/
19+
void saveState(byte[] state);
20+
}

0 commit comments

Comments
 (0)