From 3aa1e1ac4acd0cbaf032ce8c35587539cda0dee5 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 15 Nov 2026 17:41:18 +0100 Subject: [PATCH] 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. --- CHANGES.md | 1 + .../WriteResponseCharacteristic.java | 19 ++ .../impl/base/BaseCharacteristic.java | 15 ++ .../impl/base/IntegerCharacteristic.java | 8 + .../lightbulb/AdaptiveLightingController.java | 227 ++++++++++++++++++ .../lightbulb/AdaptiveLightingHandler.java | 20 ++ .../characteristics/impl/lightbulb/Tlv8.java | 89 +++++++ .../impl/lightbulb/Tlv8Characteristic.java | 70 ++++++ .../impl/lightbulb/Transition.java | 108 +++++++++ .../hapjava/server/impl/HomekitRegistry.java | 4 + .../impl/json/CharacteristicsController.java | 25 +- .../impl/json/HapJsonMultiStatusResponse.java | 13 + .../AdaptiveLightingControllerTest.java | 177 ++++++++++++++ .../impl/lightbulb/Tlv8Test.java | 42 ++++ .../impl/lightbulb/TransitionTest.java | 83 +++++++ .../server/impl/HomekitRegistryTest.java | 35 +++ .../json/CharacteristicsControllerTest.java | 87 +++++++ 17 files changed, 1021 insertions(+), 2 deletions(-) create mode 100644 src/main/java/io/github/hapjava/characteristics/WriteResponseCharacteristic.java create mode 100644 src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingController.java create mode 100644 src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingHandler.java create mode 100644 src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8.java create mode 100644 src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Characteristic.java create mode 100644 src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Transition.java create mode 100644 src/main/java/io/github/hapjava/server/impl/json/HapJsonMultiStatusResponse.java create mode 100644 src/test/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingControllerTest.java create mode 100644 src/test/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Test.java create mode 100644 src/test/java/io/github/hapjava/characteristics/impl/lightbulb/TransitionTest.java create mode 100644 src/test/java/io/github/hapjava/server/impl/HomekitRegistryTest.java create mode 100644 src/test/java/io/github/hapjava/server/impl/json/CharacteristicsControllerTest.java diff --git a/CHANGES.md b/CHANGES.md index ab4bb1202..dd7ab35aa 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,5 @@ # HAP-Java 2.0.10 +* Add Adaptive Lighting for lightbulbs (`AdaptiveLightingController`), with support for TLV8 characteristics and writes with response * Add constructors with custom min/max to the window covering tilt angle characteristics [#162](https://github.com/hap-java/HAP-Java/issues/162) * Add optional Mute characteristic to Doorbell service * Fix leak of mDNS instances and shutdown hooks when stopping `HomekitRoot` diff --git a/src/main/java/io/github/hapjava/characteristics/WriteResponseCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/WriteResponseCharacteristic.java new file mode 100644 index 000000000..1fa6759d2 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/WriteResponseCharacteristic.java @@ -0,0 +1,19 @@ +package io.github.hapjava.characteristics; + +import javax.json.JsonObjectBuilder; +import javax.json.JsonValue; + +/** A characteristic that answers a write with a value when the client requests it. */ +public interface WriteResponseCharacteristic extends Characteristic { + + /** + * Invoked by the remote client with a write that requests a response ("r": true). + * + * @param jsonValue the JSON serialized value to set. + * @param username the authenticated username making the request + * @param response the JsonObjectBuilder to add the "value" attribute of the response to. + * @throws Exception if the value cannot be set. + */ + void setValueWithResponse(JsonValue jsonValue, String username, JsonObjectBuilder response) + throws Exception; +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java index 0808883bb..8e46a5fe2 100644 --- a/src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/BaseCharacteristic.java @@ -34,6 +34,7 @@ public abstract class BaseCharacteristic implements Characteristic, Eventable private final boolean isWritable; private final Optional> subscriber; private final Optional unsubscriber; + private volatile int instanceId; /** * Default constructor @@ -76,6 +77,20 @@ public String getType() { return type; } + /** @return the instance id assigned when the accessory was registered, 0 before. */ + public int getInstanceId() { + return instanceId; + } + + /** + * Called by the server when it assigns instance ids to the accessory's characteristics. + * + * @param instanceId the instance id + */ + public void setInstanceId(int instanceId) { + this.instanceId = instanceId; + } + @Override /** {@inheritDoc} */ public final CompletableFuture toJson(int iid) { diff --git a/src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java index 6b6cd2982..d722b115b 100644 --- a/src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java +++ b/src/main/java/io/github/hapjava/characteristics/impl/base/IntegerCharacteristic.java @@ -117,6 +117,14 @@ protected CompletableFuture makeBuilder(int iid) { }); } + public int getMinValue() { + return minValue; + } + + public int getMaxValue() { + return maxValue; + } + @Override public CompletableFuture getValue() { return getter.map(integerGetter -> integerGetter.get()).orElse(null); diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingController.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingController.java new file mode 100644 index 000000000..91f9f8b66 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingController.java @@ -0,0 +1,227 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.impl.base.BaseCharacteristic; +import io.github.hapjava.characteristics.impl.base.IntegerCharacteristic; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Adaptive Lighting for a lightbulb with brightness and color temperature. A HomeKit controller + * sends a color temperature curve, which is applied in the interval the controller asks for and + * adjusted to the current brightness. + * + *

Add {@link #getCharacteristics()} to the lightbulb service. Call {@link #update()} when the + * brightness changes, and {@link #disable()} when the color temperature, hue or saturation is + * changed other than through {@link AdaptiveLightingHandler#applyColorTemperature(int)}, including + * writes from HomeKit. + */ +public class AdaptiveLightingController { + + private static final Logger logger = LoggerFactory.getLogger(AdaptiveLightingController.class); + + // TLV types as named in HAP-NodeJS, which documents the protocol + private static final int SUPPORTED_TRANSITION_CONFIGURATION = 0x01; + private static final int SUPPORTED_CHARACTERISTIC_IID = 0x01; + private static final int SUPPORTED_TRANSITION_TYPE = 0x02; + private static final byte TRANSITION_TYPE_BRIGHTNESS = 0x01; + private static final byte TRANSITION_TYPE_COLOR_TEMPERATURE = 0x02; + + private static final int READ_TRANSITION = 0x01; + private static final int UPDATE_TRANSITION = 0x02; + private static final int VALUE_TRANSITION_CONFIGURATION = 0x01; + + private static final int VALUE_CONFIGURATION_STATUS = 0x01; + private static final int STATUS_CHARACTERISTIC_IID = 0x01; + private static final int STATUS_TRANSITION_PARAMETERS = 0x02; + private static final int STATUS_TIME_SINCE_START = 0x03; + + private final BrightnessCharacteristic brightness; + private final ColorTemperatureCharacteristic colorTemperature; + private final ScheduledExecutorService scheduler; + private final AdaptiveLightingHandler handler; + private final List characteristics; + private volatile HomekitCharacteristicChangeCallback activeTransitionCountCallback; + private volatile Transition transition; + private ScheduledFuture updates; + + /** + * @param brightness the brightness characteristic of the lightbulb + * @param colorTemperature the color temperature characteristic of the lightbulb + * @param scheduler runs the color temperature updates + * @param handler applies the color temperature and stores the state + * @param savedState the state last passed to {@link AdaptiveLightingHandler#saveState(byte[])}, + * or null + */ + public AdaptiveLightingController( + BrightnessCharacteristic brightness, + ColorTemperatureCharacteristic colorTemperature, + ScheduledExecutorService scheduler, + AdaptiveLightingHandler handler, + byte[] savedState) { + this.brightness = brightness; + this.colorTemperature = colorTemperature; + this.scheduler = scheduler; + this.handler = handler; + characteristics = + Arrays.asList( + new Tlv8Characteristic( + "00000144-0000-1000-8000-0026BB765291", this::supportedConfiguration, null), + new Tlv8Characteristic( + "00000143-0000-1000-8000-0026BB765291", this::transitionStatus, this::handleWrite), + new IntegerCharacteristic( + "0000024B-0000-1000-8000-0026BB765291", + "uint8", + "", + 0, + 255, + null, + Optional.of(() -> CompletableFuture.completedFuture(transition == null ? 0 : 1)), + Optional.empty(), + Optional.of(callback -> activeTransitionCountCallback = callback), + Optional.of(() -> activeTransitionCountCallback = null)) {}); + if (savedState != null) { + start(Transition.fromState(savedState)); + } + } + + /** @return the characteristics to add to the lightbulb service */ + public List getCharacteristics() { + return characteristics; + } + + /** Applies the color temperature for the current time and brightness. */ + public synchronized void update() { + if (transition == null) { + return; + } + Integer mired = + transition.colorTemperature(System.currentTimeMillis(), brightness.getValue().join()); + if (mired == null) { + disable(); + return; + } + handler.applyColorTemperature( + Math.max(colorTemperature.getMinValue(), Math.min(colorTemperature.getMaxValue(), mired))); + } + + /** Turns Adaptive Lighting off. */ + public synchronized void disable() { + if (transition == null) { + return; + } + transition = null; + updates.cancel(false); + handler.saveState(null); + notifyActiveTransitionCount(); + } + + /** Stops the color temperature updates, e.g. when the accessory is removed. */ + public synchronized void stop() { + if (updates != null) { + updates.cancel(false); + } + } + + private synchronized void start(Transition transition) { + this.transition = transition; + if (updates != null) { + updates.cancel(false); + } + updates = + scheduler.scheduleWithFixedDelay( + this::scheduledUpdate, 0, transition.updateInterval, TimeUnit.MILLISECONDS); + notifyActiveTransitionCount(); + } + + private void scheduledUpdate() { + // an exception would end the scheduled updates + try { + update(); + } catch (RuntimeException e) { + logger.warn("Could not apply Adaptive Lighting", e); + } + } + + private void notifyActiveTransitionCount() { + HomekitCharacteristicChangeCallback callback = activeTransitionCountCallback; + if (callback != null) { + callback.changed(); + } + } + + private synchronized String handleWrite(String value) { + Map> request = Tlv8.decode(Base64.getDecoder().decode(value)); + ByteArrayOutputStream response = new ByteArrayOutputStream(); + if (request.containsKey(READ_TRANSITION) && transition != null) { + Tlv8.write(response, READ_TRANSITION, transition.configuration); + } + byte[] update = Tlv8.get(request, UPDATE_TRANSITION); + if (update != null) { + byte[] configuration = Tlv8.get(Tlv8.decode(update), VALUE_TRANSITION_CONFIGURATION); + Transition newTransition = Transition.parse(configuration, System.currentTimeMillis()); + if (newTransition == null) { + disable(); + Tlv8.write(response, UPDATE_TRANSITION, new byte[0]); + } else { + start(newTransition); + handler.saveState(newTransition.toState()); + Tlv8.write(response, UPDATE_TRANSITION, status(newTransition, 0)); + } + } + return Base64.getEncoder().encodeToString(response.toByteArray()); + } + + private String transitionStatus() { + Transition current = transition; + if (current == null) { + return ""; + } + long timeSinceStart = System.currentTimeMillis() - current.startMillis; + return Base64.getEncoder().encodeToString(status(current, timeSinceStart)); + } + + private static byte[] status(Transition transition, long timeSinceStart) { + ByteArrayOutputStream status = new ByteArrayOutputStream(); + Tlv8.write(status, STATUS_CHARACTERISTIC_IID, transition.characteristicIid); + Tlv8.write(status, STATUS_TRANSITION_PARAMETERS, transition.parameters); + Tlv8.write(status, STATUS_TIME_SINCE_START, Tlv8.uint(timeSinceStart)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Tlv8.write(out, VALUE_CONFIGURATION_STATUS, status.toByteArray()); + return out.toByteArray(); + } + + private String supportedConfiguration() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Tlv8.write( + out, + SUPPORTED_TRANSITION_CONFIGURATION, + supportedTransition(brightness, TRANSITION_TYPE_BRIGHTNESS)); + // list separator + out.write(0); + out.write(0); + Tlv8.write( + out, + SUPPORTED_TRANSITION_CONFIGURATION, + supportedTransition(colorTemperature, TRANSITION_TYPE_COLOR_TEMPERATURE)); + return Base64.getEncoder().encodeToString(out.toByteArray()); + } + + private static byte[] supportedTransition(BaseCharacteristic characteristic, byte type) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Tlv8.write(out, SUPPORTED_CHARACTERISTIC_IID, Tlv8.uint(characteristic.getInstanceId())); + Tlv8.write(out, SUPPORTED_TRANSITION_TYPE, new byte[] {type}); + return out.toByteArray(); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingHandler.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingHandler.java new file mode 100644 index 000000000..1c647fe1d --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingHandler.java @@ -0,0 +1,20 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +/** Receives the color temperature and the state of an {@link AdaptiveLightingController}. */ +public interface AdaptiveLightingHandler { + + /** + * Sets the color temperature of the light. + * + * @param mired the color temperature in mired, within the range of the color temperature + * characteristic + */ + void applyColorTemperature(int mired); + + /** + * Stores the state, to be passed to the controller after a restart. + * + * @param state the state, or null when Adaptive Lighting is off + */ + void saveState(byte[] state); +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8.java new file mode 100644 index 000000000..3af8b9d6c --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8.java @@ -0,0 +1,89 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** TLV8 as used by characteristic values. */ +final class Tlv8 { + + private Tlv8() {} + + /** + * @return the values per type; a type has several values when it is a list. Values longer than + * 255 bytes, split into several items, are joined. + */ + static Map> decode(byte[] data) { + Map> result = new HashMap<>(); + int lastType = -1; + int lastLength = -1; + int i = 0; + while (i + 2 <= data.length) { + int type = data[i] & 0xFF; + int length = data[i + 1] & 0xFF; + if (i + 2 + length > data.length) { + throw new IllegalArgumentException("TLV8 item exceeds data"); + } + byte[] value = new byte[length]; + System.arraycopy(data, i + 2, value, 0, length); + i += 2 + length; + + List values = result.computeIfAbsent(type, t -> new ArrayList<>()); + if (type == lastType && lastLength == 255) { + byte[] previous = values.get(values.size() - 1); + byte[] joined = new byte[previous.length + length]; + System.arraycopy(previous, 0, joined, 0, previous.length); + System.arraycopy(value, 0, joined, previous.length, length); + values.set(values.size() - 1, joined); + } else { + values.add(value); + } + lastType = type; + lastLength = length; + } + return result; + } + + /** @return the first value of the type, or null if there is none. */ + static byte[] get(Map> tlv, int type) { + List values = tlv.get(type); + return values == null ? null : values.get(0); + } + + static void write(ByteArrayOutputStream out, int type, byte[] value) { + int offset = 0; + do { + int length = Math.min(255, value.length - offset); + out.write(type); + out.write(length); + out.write(value, offset, length); + offset += length; + } while (offset < value.length); + } + + /** @return the value as little endian unsigned integer of 1, 2, 4 or 8 bytes. */ + static byte[] uint(long value) { + int length = value <= 0xFF ? 1 : value <= 0xFFFF ? 2 : value <= 0xFFFFFFFFL ? 4 : 8; + byte[] bytes = new byte[length]; + for (int i = 0; i < length; i++) { + bytes[i] = (byte) (value >>> (8 * i)); + } + return bytes; + } + + static long readUint(byte[] bytes) { + long value = 0; + for (int i = bytes.length - 1; i >= 0; i--) { + value = (value << 8) | (bytes[i] & 0xFF); + } + return value; + } + + static float readFloat(byte[] bytes) { + return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat(); + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Characteristic.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Characteristic.java new file mode 100644 index 000000000..14df0ad07 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Characteristic.java @@ -0,0 +1,70 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import io.github.hapjava.characteristics.WriteResponseCharacteristic; +import io.github.hapjava.characteristics.impl.base.BaseCharacteristic; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.function.Supplier; +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObjectBuilder; +import javax.json.JsonString; +import javax.json.JsonValue; + +/** Characteristic with a base64 encoded TLV8 value. A write is answered with a TLV8 value. */ +class Tlv8Characteristic extends BaseCharacteristic implements WriteResponseCharacteristic { + + private final Supplier getter; + private final Function writer; + + /** + * @param getter supplies the value + * @param writer handles a write and returns the response, null for a read-only characteristic + */ + Tlv8Characteristic(String type, Supplier getter, Function writer) { + super(type, "tlv8", "", true, writer != null, Optional.empty(), Optional.empty()); + this.getter = getter; + this.writer = writer; + } + + @Override + protected CompletableFuture makeBuilder(int iid) { + if (writer == null) { + return super.makeBuilder(iid); + } + // replaces the perms to add "wr", which BaseCharacteristic does not know + JsonArrayBuilder perms = Json.createArrayBuilder().add("pr").add("pw").add("wr"); + return super.makeBuilder(iid).thenApply(builder -> builder.add("perms", perms)); + } + + @Override + protected String convert(JsonValue jsonValue) { + return ((JsonString) jsonValue).getString(); + } + + @Override + public void setValue(String value) { + if (writer != null) { + writer.apply(value); + } + } + + @Override + public void setValueWithResponse( + JsonValue jsonValue, String username, JsonObjectBuilder response) { + if (writer != null) { + response.add("value", writer.apply(convert(jsonValue))); + } + } + + @Override + public CompletableFuture getValue() { + return CompletableFuture.completedFuture(getter.get()); + } + + @Override + public String getDefault() { + return ""; + } +} diff --git a/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Transition.java b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Transition.java new file mode 100644 index 000000000..95c742e20 --- /dev/null +++ b/src/main/java/io/github/hapjava/characteristics/impl/lightbulb/Transition.java @@ -0,0 +1,108 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** Color temperature curve sent by a HomeKit controller when it enables Adaptive Lighting. */ +final class Transition { + + // TLV types as named in HAP-NodeJS, which documents the protocol + private static final int CHARACTERISTIC_IID = 0x01; + private static final int TRANSITION_PARAMETERS = 0x02; + private static final int ENABLED = 0x03; // HAP-NodeJS: UNKNOWN_3, absent when disabling + private static final int CURVE = 0x05; + private static final int UPDATE_INTERVAL = 0x06; + + private static final int CURVE_ENTRY = 0x01; + private static final int BRIGHTNESS_RANGE = 0x03; + + private static final int ADJUSTMENT_FACTOR = 0x01; + private static final int VALUE = 0x02; + private static final int TRANSITION_TIME = 0x03; + private static final int HOLD = 0x04; // HAP-NodeJS: DURATION + + private static final int MIN_BRIGHTNESS = 0x01; + private static final int MAX_BRIGHTNESS = 0x02; + + final byte[] configuration; + final long startMillis; + final byte[] characteristicIid; + final byte[] parameters; + final long updateInterval; + + private final float[] values; + private final float[] adjustmentFactors; + private final long[] transitionTimes; + // time an entry is held before the transition to the next one starts + private final long[] holds; + private final int minBrightness; + private final int maxBrightness; + + private Transition(Map> tlv, byte[] configuration, long startMillis) { + this.configuration = configuration; + this.startMillis = startMillis; + characteristicIid = Tlv8.get(tlv, CHARACTERISTIC_IID); + parameters = Tlv8.get(tlv, TRANSITION_PARAMETERS); + byte[] interval = Tlv8.get(tlv, UPDATE_INTERVAL); + updateInterval = interval == null ? 60_000 : Tlv8.readUint(interval); + + Map> curve = Tlv8.decode(Tlv8.get(tlv, CURVE)); + List entries = curve.get(CURVE_ENTRY); + values = new float[entries.size()]; + adjustmentFactors = new float[entries.size()]; + transitionTimes = new long[entries.size()]; + holds = new long[entries.size()]; + for (int i = 0; i < entries.size(); i++) { + Map> entry = Tlv8.decode(entries.get(i)); + values[i] = Tlv8.readFloat(Tlv8.get(entry, VALUE)); + adjustmentFactors[i] = Tlv8.readFloat(Tlv8.get(entry, ADJUSTMENT_FACTOR)); + transitionTimes[i] = Tlv8.readUint(Tlv8.get(entry, TRANSITION_TIME)); + byte[] hold = Tlv8.get(entry, HOLD); + if (i > 0 && hold != null) { + holds[i - 1] = Tlv8.readUint(hold); + } + } + Map> range = Tlv8.decode(Tlv8.get(curve, BRIGHTNESS_RANGE)); + minBrightness = (int) Tlv8.readUint(Tlv8.get(range, MIN_BRIGHTNESS)); + maxBrightness = (int) Tlv8.readUint(Tlv8.get(range, MAX_BRIGHTNESS)); + } + + /** @return the transition, or null if the configuration disables Adaptive Lighting. */ + static Transition parse(byte[] configuration, long startMillis) { + Map> tlv = Tlv8.decode(configuration); + return tlv.containsKey(ENABLED) ? new Transition(tlv, configuration, startMillis) : null; + } + + static Transition fromState(byte[] state) { + return parse(Arrays.copyOfRange(state, 8, state.length), ByteBuffer.wrap(state).getLong()); + } + + byte[] toState() { + return ByteBuffer.allocate(8 + configuration.length) + .putLong(startMillis) + .put(configuration) + .array(); + } + + /** @return the color temperature in mired, or null if the curve has ended. */ + Integer colorTemperature(long timeMillis, int brightness) { + long offset = timeMillis - startMillis; + long reached = 0; + for (int i = 0; i + 1 < values.length; i++) { + reached += transitionTimes[i]; + if (offset >= reached && offset <= reached + holds[i] + transitionTimes[i + 1]) { + long transitioning = offset - reached - holds[i]; + float progress = transitioning <= 0 ? 0 : (float) transitioning / transitionTimes[i + 1]; + float value = values[i] + (values[i + 1] - values[i]) * progress; + float factor = + adjustmentFactors[i] + (adjustmentFactors[i + 1] - adjustmentFactors[i]) * progress; + int adjustedBrightness = Math.max(minBrightness, Math.min(maxBrightness, brightness)); + return Math.round(value + factor * adjustedBrightness); + } + reached += holds[i]; + } + return null; + } +} diff --git a/src/main/java/io/github/hapjava/server/impl/HomekitRegistry.java b/src/main/java/io/github/hapjava/server/impl/HomekitRegistry.java index 3c70cfb9e..0a6ad918d 100644 --- a/src/main/java/io/github/hapjava/server/impl/HomekitRegistry.java +++ b/src/main/java/io/github/hapjava/server/impl/HomekitRegistry.java @@ -2,6 +2,7 @@ import io.github.hapjava.accessories.HomekitAccessory; import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.impl.base.BaseCharacteristic; import io.github.hapjava.server.impl.connections.SubscriptionManager; import io.github.hapjava.services.Service; import io.github.hapjava.services.impl.AccessoryInformationService; @@ -63,6 +64,9 @@ public synchronized void reset() { newServicesByInterfaceId.put(++iid, service); for (Characteristic characteristic : service.getCharacteristics()) { newCharacteristicsByInterfaceId.put(++iid, characteristic); + if (characteristic instanceof BaseCharacteristic) { + ((BaseCharacteristic) characteristic).setInstanceId(iid); + } } } services.put(accessory, newServicesByInterfaceId); diff --git a/src/main/java/io/github/hapjava/server/impl/json/CharacteristicsController.java b/src/main/java/io/github/hapjava/server/impl/json/CharacteristicsController.java index f5f8bb87c..b7d047e75 100644 --- a/src/main/java/io/github/hapjava/server/impl/json/CharacteristicsController.java +++ b/src/main/java/io/github/hapjava/server/impl/json/CharacteristicsController.java @@ -2,6 +2,7 @@ import io.github.hapjava.characteristics.Characteristic; import io.github.hapjava.characteristics.EventableCharacteristic; +import io.github.hapjava.characteristics.WriteResponseCharacteristic; import io.github.hapjava.server.impl.HomekitRegistry; import io.github.hapjava.server.impl.connections.SubscriptionManager; import io.github.hapjava.server.impl.http.HomekitClientConnection; @@ -68,6 +69,8 @@ public HttpResponse get(HttpRequest request) throws Exception { public HttpResponse put(HttpRequest request, HomekitClientConnection connection) throws Exception { + JsonArrayBuilder responses = Json.createArrayBuilder(); + boolean hasWriteResponse = false; subscriptions.batchUpdate(); try { try (ByteArrayInputStream bais = new ByteArrayInputStream(request.getBody())) { @@ -88,9 +91,20 @@ public HttpResponse put(HttpRequest request, HomekitClientConnection connection) return new HapJsonNoContentResponse(); } + JsonObjectBuilder response = + Json.createObjectBuilder().add("aid", aid).add("iid", iid).add("status", 0); if (jsonCharacteristic.containsKey("value")) { - characteristic.setValue(jsonCharacteristic.get("value"), connection.getUsername()); + if (jsonCharacteristic.getBoolean("r", false) + && characteristic instanceof WriteResponseCharacteristic) { + ((WriteResponseCharacteristic) characteristic) + .setValueWithResponse( + jsonCharacteristic.get("value"), connection.getUsername(), response); + hasWriteResponse = true; + } else { + characteristic.setValue(jsonCharacteristic.get("value"), connection.getUsername()); + } } + responses.add(response); if (jsonCharacteristic.containsKey("ev") && characteristic instanceof EventableCharacteristic) { if (jsonCharacteristic.getBoolean("ev")) { @@ -106,6 +120,13 @@ public HttpResponse put(HttpRequest request, HomekitClientConnection connection) } finally { subscriptions.completeUpdateBatch(); } - return new HapJsonNoContentResponse(); + if (!hasWriteResponse) { + return new HapJsonNoContentResponse(); + } + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter jsonWriter = Json.createWriter(baos)) { + jsonWriter.write(Json.createObjectBuilder().add("characteristics", responses).build()); + return new HapJsonMultiStatusResponse(baos.toByteArray()); + } } } diff --git a/src/main/java/io/github/hapjava/server/impl/json/HapJsonMultiStatusResponse.java b/src/main/java/io/github/hapjava/server/impl/json/HapJsonMultiStatusResponse.java new file mode 100644 index 000000000..890a6e473 --- /dev/null +++ b/src/main/java/io/github/hapjava/server/impl/json/HapJsonMultiStatusResponse.java @@ -0,0 +1,13 @@ +package io.github.hapjava.server.impl.json; + +class HapJsonMultiStatusResponse extends HapJsonResponse { + + public HapJsonMultiStatusResponse(byte[] body) { + super(body); + } + + @Override + public int getStatusCode() { + return 207; + } +} diff --git a/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingControllerTest.java b/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingControllerTest.java new file mode 100644 index 000000000..6e2afc639 --- /dev/null +++ b/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/AdaptiveLightingControllerTest.java @@ -0,0 +1,177 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.notNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback; +import io.github.hapjava.characteristics.WriteResponseCharacteristic; +import io.github.hapjava.characteristics.impl.base.BaseCharacteristic; +import java.io.ByteArrayOutputStream; +import java.util.Base64; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; +import javax.json.JsonString; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +public class AdaptiveLightingControllerTest { + + private final BrightnessCharacteristic brightness = + new BrightnessCharacteristic( + () -> CompletableFuture.completedFuture(50), v -> {}, c -> {}, () -> {}); + private final ColorTemperatureCharacteristic colorTemperature = + new ColorTemperatureCharacteristic( + 140, 500, () -> CompletableFuture.completedFuture(300), v -> {}, c -> {}, () -> {}); + private final ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class); + private final ScheduledFuture updates = mock(ScheduledFuture.class); + private final AdaptiveLightingHandler handler = mock(AdaptiveLightingHandler.class); + + @Before + public void setUp() { + doReturn(updates) + .when(scheduler) + .scheduleWithFixedDelay(any(), anyLong(), anyLong(), any(TimeUnit.class)); + } + + @Test + public void supportedConfigurationNamesBrightnessAndColorTemperature() { + brightness.setInstanceId(9); + colorTemperature.setInstanceId(10); + AdaptiveLightingController controller = controller(null); + + assertThat(value(controller, 0)) + .containsExactly(1, 6, 1, 1, 9, 2, 1, 1, 0, 0, 1, 6, 1, 1, 10, 2, 1, 2); + } + + @Test + public void controlPointAnswersWritesWithAResponse() { + JsonObject json = characteristic(controller(null), 1).toJson(1).join(); + + assertThat(json.getString("format")).isEqualTo("tlv8"); + assertThat(json.getJsonArray("perms").getValuesAs(JsonString.class)) + .extracting(JsonString::getString) + .containsExactly("pr", "pw", "wr"); + } + + @Test + public void enablingStartsTheUpdatesAndAnswersWithTheStatus() throws Exception { + AdaptiveLightingController controller = controller(null); + HomekitCharacteristicChangeCallback callback = mock(HomekitCharacteristicChangeCallback.class); + characteristic(controller, 2).subscribe(callback); + + byte[] response = write(controller, tlv(0x02, tlv(0x01, TransitionTest.configuration()))); + + assertThat(response).containsExactly(2, 14, 1, 12, 1, 1, 10, 2, 4, 1, 2, 3, 4, 3, 1, 0); + verify(handler).saveState(notNull()); + verify(callback).changed(); + assertThat(characteristic(controller, 2).getValue().join()).isEqualTo(1); + runUpdate(); + verify(handler).applyColorTemperature(250); + assertThat(value(controller, 1)).startsWith(1, 12, 1, 1, 10, 2, 4, 1, 2, 3, 4, 3); + } + + @Test + public void colorTemperatureIsLimitedToTheCharacteristicRange() throws Exception { + AdaptiveLightingController controller = + new AdaptiveLightingController( + brightness, + new ColorTemperatureCharacteristic( + 260, 500, () -> CompletableFuture.completedFuture(300), v -> {}, c -> {}, () -> {}), + scheduler, + handler, + null); + write(controller, tlv(0x02, tlv(0x01, TransitionTest.configuration()))); + + runUpdate(); + + verify(handler).applyColorTemperature(260); + } + + @Test + public void readingTheConfigurationReturnsTheOneReceived() throws Exception { + AdaptiveLightingController controller = controller(null); + write(controller, tlv(0x02, tlv(0x01, TransitionTest.configuration()))); + + byte[] response = write(controller, tlv(0x01, tlv(0x01, new byte[] {10}))); + + assertThat(response).isEqualTo(tlv(0x01, TransitionTest.configuration())); + } + + @Test + public void disablingStopsTheUpdates() throws Exception { + AdaptiveLightingController controller = controller(null); + write(controller, tlv(0x02, tlv(0x01, TransitionTest.configuration()))); + + byte[] response = write(controller, tlv(0x02, tlv(0x01, tlv(0x01, new byte[] {10})))); + + assertThat(response).containsExactly(2, 0); + verify(handler).saveState(isNull()); + verify(updates).cancel(false); + assertThat(characteristic(controller, 2).getValue().join()).isEqualTo(0); + assertThat(value(controller, 1)).isEmpty(); + } + + @Test + public void savedStateIsRestoredUntilTheCurveEnds() { + byte[] state = Transition.parse(TransitionTest.configuration(), 0).toState(); + AdaptiveLightingController controller = controller(state); + + assertThat(characteristic(controller, 2).getValue().join()).isEqualTo(1); + runUpdate(); + verify(handler).saveState(isNull()); + } + + private AdaptiveLightingController controller(byte[] savedState) { + colorTemperature.setInstanceId(10); + return new AdaptiveLightingController( + brightness, colorTemperature, scheduler, handler, savedState); + } + + @SuppressWarnings("unchecked") + private static > T characteristic( + AdaptiveLightingController controller, int index) { + return (T) controller.getCharacteristics().get(index); + } + + private static byte[] value(AdaptiveLightingController controller, int index) { + BaseCharacteristic characteristic = characteristic(controller, index); + return Base64.getDecoder().decode(characteristic.getValue().join()); + } + + private static byte[] write(AdaptiveLightingController controller, byte[] request) + throws Exception { + JsonArray value = + Json.createArrayBuilder().add(Base64.getEncoder().encodeToString(request)).build(); + JsonObjectBuilder response = Json.createObjectBuilder(); + WriteResponseCharacteristic control = characteristic(controller, 1); + control.setValueWithResponse(value.get(0), null, response); + return Base64.getDecoder().decode(response.build().getString("value")); + } + + private void runUpdate() { + ArgumentCaptor update = ArgumentCaptor.forClass(Runnable.class); + verify(scheduler) + .scheduleWithFixedDelay(update.capture(), eq(0L), eq(60_000L), eq(TimeUnit.MILLISECONDS)); + update.getValue().run(); + } + + private static byte[] tlv(int type, byte[] value) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Tlv8.write(out, type, value); + return out.toByteArray(); + } +} diff --git a/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Test.java b/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Test.java new file mode 100644 index 000000000..2a658651a --- /dev/null +++ b/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/Tlv8Test.java @@ -0,0 +1,42 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Map; +import org.junit.Test; + +public class Tlv8Test { + + @Test + public void longValueIsSplitAndJoined() { + byte[] value = new byte[300]; + value[299] = 7; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Tlv8.write(out, 5, value); + byte[] data = out.toByteArray(); + + assertThat(data).hasSize(304); + assertThat(data[1] & 0xFF).isEqualTo(255); + assertThat(data[258]).isEqualTo((byte) 45); + assertThat(Tlv8.decode(data).get(5)).containsExactly(value); + } + + @Test + public void separatedItemsOfOneTypeAreAList() { + Map> tlv = Tlv8.decode(new byte[] {1, 1, 10, 0, 0, 1, 1, 11, 2, 0}); + + assertThat(tlv.get(1)).containsExactly(new byte[] {10}, new byte[] {11}); + assertThat(Tlv8.get(tlv, 2)).isEmpty(); + assertThat(Tlv8.get(tlv, 3)).isNull(); + } + + @Test + public void unsignedIntegersUseTheSmallestLength() { + assertThat(Tlv8.uint(255)).containsExactly(0xFF); + assertThat(Tlv8.uint(256)).containsExactly(0x00, 0x01); + assertThat(Tlv8.uint(70_000)).containsExactly(0x70, 0x11, 0x01, 0x00); + assertThat(Tlv8.readUint(Tlv8.uint(86_400_000L))).isEqualTo(86_400_000L); + } +} diff --git a/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/TransitionTest.java b/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/TransitionTest.java new file mode 100644 index 000000000..00ecd3a2d --- /dev/null +++ b/src/test/java/io/github/hapjava/characteristics/impl/lightbulb/TransitionTest.java @@ -0,0 +1,83 @@ +package io.github.hapjava.characteristics.impl.lightbulb; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import org.junit.Test; + +public class TransitionTest { + + static final byte[] PARAMETERS = {1, 2, 3, 4}; + + /** Curve: 300 mired held for 500 ms, then 1000 ms to 400 mired; factor -1 per % brightness. */ + static byte[] configuration() { + ByteArrayOutputStream curve = new ByteArrayOutputStream(); + Tlv8.write(curve, 0x01, entry(300, 0, null)); + curve.write(0); + curve.write(0); + Tlv8.write(curve, 0x01, entry(400, 1000, 500L)); + ByteArrayOutputStream range = new ByteArrayOutputStream(); + Tlv8.write(range, 0x01, new byte[] {10, 0, 0, 0}); + Tlv8.write(range, 0x02, new byte[] {100, 0, 0, 0}); + Tlv8.write(curve, 0x03, range.toByteArray()); + + ByteArrayOutputStream configuration = new ByteArrayOutputStream(); + Tlv8.write(configuration, 0x01, new byte[] {10}); + Tlv8.write(configuration, 0x02, PARAMETERS); + Tlv8.write(configuration, 0x03, new byte[] {1}); + Tlv8.write(configuration, 0x05, curve.toByteArray()); + Tlv8.write(configuration, 0x06, Tlv8.uint(60_000)); + return configuration.toByteArray(); + } + + private static byte[] entry(float value, long transitionTime, Long hold) { + ByteArrayOutputStream entry = new ByteArrayOutputStream(); + Tlv8.write(entry, 0x01, float32(-1)); + Tlv8.write(entry, 0x02, float32(value)); + Tlv8.write(entry, 0x03, Tlv8.uint(transitionTime)); + if (hold != null) { + Tlv8.write(entry, 0x04, Tlv8.uint(hold)); + } + return entry.toByteArray(); + } + + private static byte[] float32(float value) { + return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putFloat(value).array(); + } + + @Test + public void followsTheCurveAdjustedByBrightness() { + Transition transition = Transition.parse(configuration(), 1000); + + assertThat(transition.colorTemperature(1000, 50)).isEqualTo(250); + assertThat(transition.colorTemperature(1500, 50)).isEqualTo(250); + assertThat(transition.colorTemperature(2000, 50)).isEqualTo(300); + assertThat(transition.colorTemperature(2500, 50)).isEqualTo(350); + assertThat(transition.colorTemperature(2501, 50)).isNull(); + } + + @Test + public void brightnessIsLimitedToTheRange() { + Transition transition = Transition.parse(configuration(), 0); + + assertThat(transition.colorTemperature(0, 1)).isEqualTo(290); + assertThat(transition.colorTemperature(0, 100)).isEqualTo(200); + } + + @Test + public void configurationWithoutEnabledFlagDisables() { + assertThat(Transition.parse(new byte[] {0x01, 0x01, 10}, 0)).isNull(); + } + + @Test + public void stateKeepsStartTimeAndConfiguration() { + Transition transition = Transition.fromState(Transition.parse(configuration(), 1000).toState()); + + assertThat(transition.startMillis).isEqualTo(1000); + assertThat(transition.configuration).isEqualTo(configuration()); + assertThat(transition.parameters).isEqualTo(PARAMETERS); + assertThat(transition.updateInterval).isEqualTo(60_000); + } +} diff --git a/src/test/java/io/github/hapjava/server/impl/HomekitRegistryTest.java b/src/test/java/io/github/hapjava/server/impl/HomekitRegistryTest.java new file mode 100644 index 000000000..478b0278a --- /dev/null +++ b/src/test/java/io/github/hapjava/server/impl/HomekitRegistryTest.java @@ -0,0 +1,35 @@ +package io.github.hapjava.server.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.github.hapjava.accessories.LightbulbAccessory; +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.impl.base.BaseCharacteristic; +import io.github.hapjava.server.impl.connections.SubscriptionManager; +import io.github.hapjava.services.impl.LightbulbService; +import java.util.Collections; +import java.util.Map; +import org.junit.Test; + +public class HomekitRegistryTest { + + @Test + public void characteristicsKnowTheirInstanceId() { + LightbulbAccessory accessory = mock(LightbulbAccessory.class); + when(accessory.getId()).thenReturn(2); + when(accessory.getServices()) + .thenReturn(Collections.singletonList(new LightbulbService(accessory))); + HomekitRegistry registry = new HomekitRegistry("test", mock(SubscriptionManager.class)); + registry.add(accessory); + + registry.reset(); + + Map characteristics = registry.getCharacteristics(2); + assertThat(characteristics).isNotEmpty(); + characteristics.forEach( + (iid, characteristic) -> + assertThat(((BaseCharacteristic) characteristic).getInstanceId()).isEqualTo(iid)); + } +} diff --git a/src/test/java/io/github/hapjava/server/impl/json/CharacteristicsControllerTest.java b/src/test/java/io/github/hapjava/server/impl/json/CharacteristicsControllerTest.java new file mode 100644 index 000000000..fe8df3402 --- /dev/null +++ b/src/test/java/io/github/hapjava/server/impl/json/CharacteristicsControllerTest.java @@ -0,0 +1,87 @@ +package io.github.hapjava.server.impl.json; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.github.hapjava.characteristics.Characteristic; +import io.github.hapjava.characteristics.WriteResponseCharacteristic; +import io.github.hapjava.server.impl.HomekitRegistry; +import io.github.hapjava.server.impl.connections.SubscriptionManager; +import io.github.hapjava.server.impl.http.HomekitClientConnection; +import io.github.hapjava.server.impl.http.HttpRequest; +import io.github.hapjava.server.impl.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import javax.json.JsonObjectBuilder; +import javax.json.JsonValue; +import org.junit.Before; +import org.junit.Test; + +public class CharacteristicsControllerTest { + + private final HomekitRegistry registry = mock(HomekitRegistry.class); + private final WriteResponseCharacteristic control = mock(WriteResponseCharacteristic.class); + private final Characteristic on = mock(Characteristic.class); + private final HomekitClientConnection connection = mock(HomekitClientConnection.class); + private final CharacteristicsController controller = + new CharacteristicsController(registry, mock(SubscriptionManager.class)); + + @Before + public void setUp() throws Exception { + Map characteristics = new HashMap<>(); + characteristics.put(5, control); + characteristics.put(6, on); + when(registry.getCharacteristics(1)).thenReturn(characteristics); + when(connection.getUsername()).thenReturn("user"); + doAnswer( + invocation -> { + invocation.getArgument(2).add("value", "Ag=="); + return null; + }) + .when(control) + .setValueWithResponse(any(), any(), any()); + } + + @Test + public void writeWithResponseRequestIsAnsweredWithMultiStatus() throws Exception { + HttpResponse response = + put( + "{\"characteristics\":[{\"aid\":1,\"iid\":5,\"value\":\"AQ==\",\"r\":true}," + + "{\"aid\":1,\"iid\":6,\"value\":true}]}"); + + assertThat(response.getStatusCode()).isEqualTo(207); + assertThat(body(response)) + .isEqualTo( + "{\"characteristics\":[{\"aid\":1,\"iid\":5,\"status\":0,\"value\":\"Ag==\"}," + + "{\"aid\":1,\"iid\":6,\"status\":0}]}"); + verify(on).setValue(JsonValue.TRUE, "user"); + } + + @Test + public void writeWithoutResponseRequestHasNoContent() throws Exception { + HttpResponse response = put("{\"characteristics\":[{\"aid\":1,\"iid\":5,\"value\":\"AQ==\"}]}"); + + assertThat(response.getStatusCode()).isEqualTo(204); + verify(control).setValue(any(JsonValue.class), eq("user")); + } + + private HttpResponse put(String body) throws Exception { + HttpRequest request = mock(HttpRequest.class); + when(request.getBody()).thenReturn(body.getBytes(StandardCharsets.UTF_8)); + return controller.put(request, connection); + } + + private static String body(HttpResponse response) { + ByteBuffer buffer = response.getBody(); + byte[] bytes = new byte[buffer.remaining()]; + buffer.get(bytes); + return new String(bytes, StandardCharsets.UTF_8); + } +}