|
| 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 | +} |
0 commit comments