]> git.basschouten.com Git - openhab-addons.git/blob
383b9aaf56d44d8df51aae9221a5401fe460385d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.dmx.internal.handler;
14
15 import static org.openhab.binding.dmx.internal.DmxBindingConstants.*;
16
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.Set;
20 import java.util.stream.IntStream;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.openhab.binding.dmx.internal.DmxBindingConstants.ListenerType;
24 import org.openhab.binding.dmx.internal.DmxBridgeHandler;
25 import org.openhab.binding.dmx.internal.DmxThingHandler;
26 import org.openhab.binding.dmx.internal.Util;
27 import org.openhab.binding.dmx.internal.ValueSet;
28 import org.openhab.binding.dmx.internal.action.FadeAction;
29 import org.openhab.binding.dmx.internal.config.TunableWhiteThingHandlerConfiguration;
30 import org.openhab.binding.dmx.internal.multiverse.BaseDmxChannel;
31 import org.openhab.binding.dmx.internal.multiverse.DmxChannel;
32 import org.openhab.core.library.types.DecimalType;
33 import org.openhab.core.library.types.IncreaseDecreaseType;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.library.types.PercentType;
36 import org.openhab.core.thing.Bridge;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.ThingTypeUID;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * The {@link TunableWhiteThingHandler} is responsible for handling commands, which are
49  * sent to the dimmer.
50  *
51  * @author Jan N. Klug - Initial contribution
52  */
53 @NonNullByDefault
54 public class TunableWhiteThingHandler extends DmxThingHandler {
55     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_TUNABLEWHITE);
56
57     private final Logger logger = LoggerFactory.getLogger(TunableWhiteThingHandler.class);
58
59     private final List<DmxChannel> channels = new ArrayList<>();
60
61     private final List<Integer> currentValues = new ArrayList<>();
62     private PercentType currentBrightness = PercentType.ZERO;
63     private PercentType currentColorTemperature = new PercentType(50);
64
65     private ValueSet turnOnValue = new ValueSet(0, -1, DmxChannel.MAX_VALUE);
66     private ValueSet turnOffValue = new ValueSet(0, -1, DmxChannel.MIN_VALUE);
67
68     private int fadeTime = 0, dimTime = 0;
69
70     private boolean dynamicTurnOnValue = false;
71     private boolean isDimming = false;
72
73     public TunableWhiteThingHandler(Thing dimmerThing) {
74         super(dimmerThing);
75     }
76
77     @Override
78     public void handleCommand(ChannelUID channelUID, Command command) {
79         logger.trace("received command {} in channel {}", command, channelUID);
80         ValueSet targetValueSet = new ValueSet(fadeTime, -1);
81         switch (channelUID.getId()) {
82             case CHANNEL_BRIGHTNESS: {
83                 if (command instanceof PercentType || command instanceof DecimalType) {
84                     PercentType brightness = (command instanceof PercentType percentCommand) ? percentCommand
85                             : Util.toPercentValue(((DecimalType) command).intValue());
86                     logger.trace("adding fade to channels in thing {}", this.thing.getUID());
87                     targetValueSet.addValue(Util.toDmxValue(
88                             Util.toDmxValue(brightness) * (100 - currentColorTemperature.intValue()) / 100));
89                     targetValueSet.addValue(
90                             Util.toDmxValue(Util.toDmxValue(brightness) * currentColorTemperature.intValue() / 100));
91                 } else if (command instanceof OnOffType onOffCommand) {
92                     logger.trace("adding {} fade to channels in thing {}", command, this.thing.getUID());
93                     if (onOffCommand == OnOffType.ON) {
94                         targetValueSet = turnOnValue;
95                     } else {
96                         if (dynamicTurnOnValue) {
97                             turnOnValue.clear();
98                             for (DmxChannel channel : channels) {
99                                 turnOnValue.addValue(channel.getValue());
100                             }
101                             logger.trace("stored channel values fort next turn-on");
102                         }
103                         targetValueSet = turnOffValue;
104                     }
105                 } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
106                     if (isDimming && increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
107                         logger.trace("stopping fade in thing {}", this.thing.getUID());
108                         channels.forEach(DmxChannel::clearAction);
109                         isDimming = false;
110                         return;
111                     } else {
112                         logger.trace("starting {} fade in thing {}", command, this.thing.getUID());
113                         targetValueSet = increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE) ? turnOnValue
114                                 : turnOffValue;
115                         targetValueSet.setFadeTime(dimTime);
116                         isDimming = true;
117                     }
118                 } else if (command instanceof RefreshType) {
119                     logger.trace("sending update on refresh to channel {}:brightness", this.thing.getUID());
120                     currentValues.set(0, channels.get(0).getValue());
121                     currentValues.set(1, channels.get(1).getValue());
122                     updateCurrentBrightnessAndTemperature();
123                     updateState(channelUID, currentBrightness);
124                     return;
125                 } else {
126                     logger.debug("command {} not supported in channel {}:brightness", command.getClass(),
127                             this.thing.getUID());
128                     return;
129                 }
130                 break;
131             }
132             case CHANNEL_BRIGHTNESS_CW:
133                 if (command instanceof RefreshType) {
134                     logger.trace("sending update on refresh to channel {}:brightness_cw", this.thing.getUID());
135                     currentValues.set(0, channels.get(0).getValue());
136                     updateState(channelUID, Util.toPercentValue(currentValues.get(0)));
137                     return;
138                 } else {
139                     logger.debug("command {} not supported in channel {}:brightness_cw", command.getClass(),
140                             this.thing.getUID());
141                     return;
142                 }
143             case CHANNEL_BRIGHTNESS_WW:
144                 if (command instanceof RefreshType) {
145                     logger.trace("sending update on refresh to channel {}:brightness_ww", this.thing.getUID());
146                     currentValues.set(1, channels.get(1).getValue());
147                     updateState(channelUID, Util.toPercentValue(currentValues.get(1)));
148                     return;
149                 } else {
150                     logger.debug("command {} not supported in channel {}:brightness_ww", command.getClass(),
151                             this.thing.getUID());
152                     return;
153                 }
154             case CHANNEL_COLOR_TEMPERATURE: {
155                 if (command instanceof PercentType colorTemperature) {
156                     targetValueSet.addValue(Util.toDmxValue(
157                             Util.toDmxValue(currentBrightness) * (100 - colorTemperature.intValue()) / 100));
158                     targetValueSet.addValue(
159                             Util.toDmxValue(Util.toDmxValue(currentBrightness) * colorTemperature.intValue() / 100));
160                 } else if (command instanceof RefreshType) {
161                     logger.trace("sending update on refresh to channel {}:color_temperature", this.thing.getUID());
162                     currentValues.set(0, channels.get(0).getValue());
163                     currentValues.set(1, channels.get(1).getValue());
164                     updateCurrentBrightnessAndTemperature();
165                     updateState(channelUID, currentColorTemperature);
166                     return;
167                 } else {
168                     logger.debug("command {} not supported in channel {}:color_temperature", command.getClass(),
169                             this.thing.getUID());
170                     return;
171                 }
172                 break;
173             }
174             default:
175                 logger.debug("channel {} not supported in thing {}", channelUID.getId(), this.thing.getUID());
176                 return;
177         }
178         final ValueSet valueSet = targetValueSet;
179         IntStream.range(0, channels.size()).forEach(i -> {
180             channels.get(i).setChannelAction(new FadeAction(valueSet.getFadeTime(), channels.get(i).getValue(),
181                     valueSet.getValue(i), valueSet.getHoldTime()));
182         });
183     }
184
185     @Override
186     public void initialize() {
187         Bridge bridge = getBridge();
188         DmxBridgeHandler bridgeHandler;
189         if (bridge == null) {
190             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "no bridge assigned");
191             dmxHandlerStatus = ThingStatusDetail.CONFIGURATION_ERROR;
192             return;
193         } else {
194             bridgeHandler = (DmxBridgeHandler) bridge.getHandler();
195             if (bridgeHandler == null) {
196                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "no bridge handler available");
197                 dmxHandlerStatus = ThingStatusDetail.CONFIGURATION_ERROR;
198                 return;
199             }
200         }
201
202         TunableWhiteThingHandlerConfiguration configuration = getConfig()
203                 .as(TunableWhiteThingHandlerConfiguration.class);
204         if (configuration.dmxid.isEmpty()) {
205             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
206                     "DMX channel configuration missing");
207             dmxHandlerStatus = ThingStatusDetail.CONFIGURATION_ERROR;
208             return;
209         }
210         try {
211             List<BaseDmxChannel> configChannels = BaseDmxChannel.fromString(configuration.dmxid,
212                     bridgeHandler.getUniverseId());
213             logger.trace("found {} channels in {}", configChannels.size(), this.thing.getUID());
214             for (BaseDmxChannel channel : configChannels) {
215                 channels.add(bridgeHandler.getDmxChannel(channel, this.thing));
216             }
217         } catch (IllegalArgumentException e) {
218             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
219             dmxHandlerStatus = ThingStatusDetail.CONFIGURATION_ERROR;
220             return;
221         }
222
223         currentValues.add(DmxChannel.MIN_VALUE);
224         currentValues.add(DmxChannel.MIN_VALUE);
225
226         fadeTime = configuration.fadetime;
227         logger.trace("setting fadeTime to {} ms in {}", fadeTime, this.thing.getUID());
228
229         dimTime = configuration.dimtime;
230         logger.trace("setting dimTime to {} ms in {}", fadeTime, this.thing.getUID());
231
232         String turnOnValueString = fadeTime + ":" + configuration.turnonvalue + ":-1";
233         ValueSet turnOnValue = ValueSet.fromString(turnOnValueString);
234         if (turnOnValue.size() % 2 == 0) {
235             this.turnOnValue = turnOnValue;
236             logger.trace("set turnonvalue to {} in {}", turnOnValue, this.thing.getUID());
237         } else {
238             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "turn-on value malformed");
239             dmxHandlerStatus = ThingStatusDetail.CONFIGURATION_ERROR;
240             return;
241         }
242         this.turnOnValue.setFadeTime(fadeTime);
243
244         dynamicTurnOnValue = configuration.dynamicturnonvalue;
245
246         String turnOffValueString = fadeTime + ":" + configuration.turnoffvalue + ":-1";
247         ValueSet turnOffValue = ValueSet.fromString(turnOffValueString);
248         if (turnOffValue.size() % 2 == 0) {
249             this.turnOffValue = turnOffValue;
250             logger.trace("set turnoffvalue to {} in {}", turnOffValue, this.thing.getUID());
251         } else {
252             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "turn-off value malformed");
253             dmxHandlerStatus = ThingStatusDetail.CONFIGURATION_ERROR;
254             return;
255         }
256
257         this.turnOffValue.setFadeTime(fadeTime);
258
259         // register feedback listeners
260         channels.get(0).addListener(new ChannelUID(this.thing.getUID(), CHANNEL_BRIGHTNESS_CW), this,
261                 ListenerType.VALUE);
262         channels.get(1).addListener(new ChannelUID(this.thing.getUID(), CHANNEL_BRIGHTNESS_WW), this,
263                 ListenerType.VALUE);
264
265         if (bridge.getStatus().equals(ThingStatus.ONLINE)) {
266             updateStatus(ThingStatus.ONLINE);
267             dmxHandlerStatus = ThingStatusDetail.NONE;
268         } else {
269             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
270         }
271     }
272
273     @Override
274     public void dispose() {
275         if (!channels.isEmpty()) {
276             channels.get(0).removeListener(new ChannelUID(this.thing.getUID(), CHANNEL_BRIGHTNESS_CW));
277             channels.get(1).removeListener(new ChannelUID(this.thing.getUID(), CHANNEL_BRIGHTNESS_WW));
278         }
279         Bridge bridge = getBridge();
280         if (bridge != null) {
281             DmxBridgeHandler bridgeHandler = (DmxBridgeHandler) bridge.getHandler();
282             if (bridgeHandler != null) {
283                 bridgeHandler.unregisterDmxChannels(this.thing);
284                 logger.debug("removing {} channels from {}", channels.size(), this.thing.getUID());
285             }
286         }
287         channels.clear();
288         currentValues.clear();
289     }
290
291     @Override
292     public void updateChannelValue(ChannelUID channelUID, int value) {
293         updateState(channelUID, Util.toPercentValue(value));
294         switch (channelUID.getId()) {
295             case CHANNEL_BRIGHTNESS_CW:
296                 currentValues.set(0, value);
297                 break;
298             case CHANNEL_BRIGHTNESS_WW:
299                 currentValues.set(1, value);
300                 break;
301             default:
302                 logger.debug("don't know how to handle {} in tunable white type", channelUID.getId());
303                 return;
304         }
305
306         updateCurrentBrightnessAndTemperature();
307         updateState(new ChannelUID(this.thing.getUID(), CHANNEL_BRIGHTNESS), currentBrightness);
308         updateState(new ChannelUID(this.thing.getUID(), CHANNEL_COLOR_TEMPERATURE), currentColorTemperature);
309         logger.trace("received update {} for channel {}, resulting in b={}, ct={}", value, channelUID,
310                 currentBrightness, currentColorTemperature);
311     }
312
313     private void updateCurrentBrightnessAndTemperature() {
314         currentBrightness = Util.toPercentValue(Util.toDmxValue(currentValues.get(0) + currentValues.get(1)));
315         if (!PercentType.ZERO.equals(currentBrightness)) {
316             currentColorTemperature = new PercentType(
317                     100 * currentValues.get(1) / (currentValues.get(0) + currentValues.get(1)));
318         }
319     }
320 }