]> git.basschouten.com Git - openhab-addons.git/blob
be43aa5230ee6cea4b05acfdc8b55e0db31c47b8
[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.openwebnet.internal.handler;
14
15 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.*;
16
17 import java.util.Set;
18 import java.util.concurrent.TimeUnit;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants;
23 import org.openhab.core.library.types.IncreaseDecreaseType;
24 import org.openhab.core.library.types.OnOffType;
25 import org.openhab.core.library.types.PercentType;
26 import org.openhab.core.thing.ChannelUID;
27 import org.openhab.core.thing.Thing;
28 import org.openhab.core.thing.ThingStatus;
29 import org.openhab.core.thing.ThingStatusDetail;
30 import org.openhab.core.thing.ThingTypeUID;
31 import org.openhab.core.types.Command;
32 import org.openwebnet4j.communication.OWNException;
33 import org.openwebnet4j.message.BaseOpenMessage;
34 import org.openwebnet4j.message.FrameException;
35 import org.openwebnet4j.message.Lighting;
36 import org.openwebnet4j.message.What;
37 import org.openwebnet4j.message.Where;
38 import org.openwebnet4j.message.WhereLightAutom;
39 import org.openwebnet4j.message.WhereZigBee;
40 import org.openwebnet4j.message.Who;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * The {@link OpenWebNetLightingHandler} is responsible for handling
46  * commands/messages for a Lighting OpenWebNet device.
47  * It extends the abstract {@link OpenWebNetThingHandler}.
48  *
49  * @author Massimo Valla - Initial contribution
50  */
51 @NonNullByDefault
52 public class OpenWebNetLightingHandler extends OpenWebNetThingHandler {
53
54     private final Logger logger = LoggerFactory.getLogger(OpenWebNetLightingHandler.class);
55
56     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = OpenWebNetBindingConstants.LIGHTING_SUPPORTED_THING_TYPES;
57
58     // interval to interpret ON as response to requestStatus
59     private static final int BRIGHTNESS_STATUS_REQUEST_INTERVAL_MSEC = 250;
60
61     // time to wait before sending a statusRequest, to avoid repeated requests and
62     // ensure dimmer has reached its final level
63     private static final int BRIGHTNESS_STATUS_REQUEST_DELAY_MSEC = 900;
64
65     private static final int UNKNOWN_STATE = 1000;
66
67     private long lastBrightnessChangeSentTS = 0; // timestamp when last brightness change was sent to the device
68
69     private long lastStatusRequestSentTS = 0; // timestamp when last status request was sent to the device
70
71     private static long lastAllDevicesRefreshTS = 0; // ts when last all device refresh was sent for this handler
72
73     private int brightness = UNKNOWN_STATE; // current brightness percent value for this device
74
75     private int brightnessBeforeOff = UNKNOWN_STATE; // latest brightness before device was set to off
76
77     public OpenWebNetLightingHandler(Thing thing) {
78         super(thing);
79     }
80
81     @Override
82     protected void requestChannelState(ChannelUID channel) {
83         super.requestChannelState(channel);
84         if (deviceWhere != null) {
85             try {
86                 lastStatusRequestSentTS = System.currentTimeMillis();
87                 send(Lighting.requestStatus(toWhere(channel.getId())));
88             } catch (OWNException e) {
89                 logger.debug("Exception while requesting state for channel {}: {} ", channel, e.getMessage());
90                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
91             }
92         }
93     }
94
95     @Override
96     protected long getRefreshAllLastTS() {
97         return lastAllDevicesRefreshTS;
98     };
99
100     @Override
101     protected void refreshDevice(boolean refreshAll) {
102         if (refreshAll) {
103             logger.debug("--- refreshDevice() : refreshing GENERAL... ({})", thing.getUID());
104             try {
105                 send(Lighting.requestStatus(WhereLightAutom.GENERAL.value()));
106                 lastAllDevicesRefreshTS = System.currentTimeMillis();
107             } catch (OWNException e) {
108                 logger.warn("Excpetion while requesting all devices refresh: {}", e.getMessage());
109             }
110         } else {
111             logger.debug("--- refreshDevice() : refreshing SINGLE... ({})", thing.getUID());
112             ThingTypeUID thingType = thing.getThingTypeUID();
113             if (THING_TYPE_ZB_ON_OFF_SWITCH_2UNITS.equals(thingType)) {
114                 /*
115                  * Unfortunately using USB Gateway OpenWebNet both switch endpoints cannot be
116                  * requested at the same time using UNIT 00 because USB stick returns NACK,
117                  * so we need to send a request status for both endpoints
118                  */
119                 requestChannelState(new ChannelUID(thing.getUID(), CHANNEL_SWITCH_02));
120             }
121             requestChannelState(new ChannelUID(thing.getUID(), CHANNEL_SWITCH_01));
122         }
123     }
124
125     @Override
126     protected void handleChannelCommand(ChannelUID channel, Command command) {
127         switch (channel.getId()) {
128             case CHANNEL_BRIGHTNESS:
129                 handleBrightnessCommand(command);
130                 break;
131             case CHANNEL_SWITCH:
132             case CHANNEL_SWITCH_01:
133             case CHANNEL_SWITCH_02:
134                 handleSwitchCommand(channel, command);
135                 break;
136             default: {
137                 logger.warn("Unsupported ChannelUID {}", channel);
138             }
139         }
140     }
141
142     /**
143      * Handles Lighting switch command for a channel
144      *
145      * @param channel the channel
146      * @param command the command
147      */
148     private void handleSwitchCommand(ChannelUID channel, Command command) {
149         logger.debug("handleSwitchCommand() (command={} - channel={})", command, channel);
150         if (command instanceof OnOffType) {
151             try {
152                 if (OnOffType.ON.equals(command)) {
153                     send(Lighting.requestTurnOn(toWhere(channel.getId())));
154                 } else if (OnOffType.OFF.equals(command)) {
155                     send(Lighting.requestTurnOff(toWhere(channel.getId())));
156                 }
157             } catch (OWNException e) {
158                 logger.warn("Exception while processing command {}: {}", command, e.getMessage());
159             }
160         } else {
161             logger.warn("Unsupported command: {}", command);
162         }
163     }
164
165     /**
166      * Handles Lighting brightness command (xx%, INCREASE, DECREASE, ON, OFF)
167      *
168      * @param command the command
169      */
170     private void handleBrightnessCommand(Command command) {
171         logger.debug("handleBrightnessCommand() command={}", command);
172         if (command instanceof PercentType) {
173             dimLightTo(((PercentType) command).intValue(), command);
174         } else if (command instanceof IncreaseDecreaseType) {
175             if (IncreaseDecreaseType.INCREASE.equals(command)) {
176                 dimLightTo(brightness + 10, command);
177             } else { // DECREASE
178                 dimLightTo(brightness - 10, command);
179             }
180         } else if (command instanceof OnOffType) {
181             if (OnOffType.ON.equals(command)) {
182                 dimLightTo(brightnessBeforeOff, command);
183             } else { // OFF
184                 dimLightTo(0, command);
185             }
186         } else {
187             logger.warn("Cannot handle command {} for thing {}", command, getThing().getUID());
188         }
189     }
190
191     /**
192      * Helper method to dim light to given percent
193      */
194     private void dimLightTo(int percent, Command command) {
195         logger.debug("   DIM dimLightTo({}) bri={} briBeforeOff={}", percent, brightness, brightnessBeforeOff);
196         int newBrightness = percent;
197         if (newBrightness == UNKNOWN_STATE) {
198             // we do not know last brightness -> set dimmer to 100%
199             newBrightness = 100;
200         } else if (newBrightness <= 0) {
201             newBrightness = 0;
202             brightnessBeforeOff = brightness;
203             logger.debug("   DIM saved bri before sending bri=0 command to device");
204         } else if (newBrightness > 100) {
205             newBrightness = 100;
206         }
207         What newBrightnessWhat = Lighting.percentToWhat(newBrightness);
208         logger.debug("   DIM newBrightness={} newBrightnessWhat={}", newBrightness, newBrightnessWhat);
209         @Nullable
210         What brightnessWhat = null;
211         if (brightness != UNKNOWN_STATE) {
212             brightnessWhat = Lighting.percentToWhat(brightness);
213         }
214         if (brightnessWhat == null || !newBrightnessWhat.value().equals(brightnessWhat.value())) {
215             logger.debug("   DIM brightnessWhat {} --> {}  WHAT level change needed", brightnessWhat,
216                     newBrightnessWhat);
217             Where w = deviceWhere;
218             if (w != null) {
219                 try {
220                     lastBrightnessChangeSentTS = System.currentTimeMillis();
221                     send(Lighting.requestDimTo(w.value(), newBrightnessWhat));
222                 } catch (OWNException e) {
223                     logger.warn("Exception while sending dimTo request for command {}: {}", command, e.getMessage());
224                 }
225             }
226         } else {
227             logger.debug("   DIM brightnessWhat {} --> {}  NO WHAT level change needed", brightnessWhat,
228                     newBrightnessWhat);
229         }
230         brightness = newBrightness;
231         updateState(CHANNEL_BRIGHTNESS, new PercentType(brightness));
232         logger.debug("   DIM---END bri={} briBeforeOff={}", brightness, brightnessBeforeOff);
233     }
234
235     @Override
236     protected String ownIdPrefix() {
237         return Who.LIGHTING.value().toString();
238     }
239
240     @Override
241     protected void handleMessage(BaseOpenMessage msg) {
242         logger.debug("handleMessage({}) for thing: {}", msg, thing.getUID());
243         super.handleMessage(msg);
244         ThingTypeUID thingType = thing.getThingTypeUID();
245         if (THING_TYPE_ZB_DIMMER.equals(thingType) || THING_TYPE_BUS_DIMMER.equals(thingType)) {
246             updateBrightness((Lighting) msg);
247         } else {
248             updateOnOffState((Lighting) msg);
249         }
250     }
251
252     /**
253      * Updates brightness based on OWN Lighting message received
254      *
255      * @param msg the Lighting message received
256      */
257     private synchronized void updateBrightness(Lighting msg) {
258         logger.debug("  $BRI updateBrightness({})       || bri={} briBeforeOff={}", msg, brightness,
259                 brightnessBeforeOff);
260         long now = System.currentTimeMillis();
261         long delta = now - lastBrightnessChangeSentTS;
262         boolean belowThresh = delta < BRIGHTNESS_STATUS_REQUEST_DELAY_MSEC;
263         logger.debug("  $BRI delta={}ms {}", delta, (belowThresh ? "< DELAY" : ""));
264         if (belowThresh) {
265             // we just sent a command from OH, so we can ignore this message from network
266             logger.debug("  $BRI a command was sent {} < {} ms --> no action needed", delta,
267                     BRIGHTNESS_STATUS_REQUEST_DELAY_MSEC);
268         } else {
269             if (msg.isOn()) {
270                 // if we have not just sent a requestStatus, on ON event we send requestStatus
271                 // to know current level
272                 long deltaStatusReq = now - lastStatusRequestSentTS;
273                 if (deltaStatusReq > BRIGHTNESS_STATUS_REQUEST_INTERVAL_MSEC) {
274                     logger.debug("  $BRI 'ON' is new notification from network, scheduling requestStatus...");
275                     // we must wait BRIGHTNESS_STATUS_REQUEST_DELAY_MSEC to be sure dimmer has
276                     // reached its final level
277                     scheduler.schedule(() -> {
278                         requestChannelState(new ChannelUID(thing.getUID(), CHANNEL_BRIGHTNESS));
279                     }, BRIGHTNESS_STATUS_REQUEST_DELAY_MSEC, TimeUnit.MILLISECONDS);
280                     return;
281                 } else {
282                     // otherwise we interpret this ON event as the requestStatus response event with
283                     // level=1
284                     // so we proceed to call updateBrightnessState()
285                     logger.debug("  $BRI 'ON' is the requestStatus response level");
286                 }
287             }
288             logger.debug("  $BRI update from network");
289             if (msg.getWhat() != null) {
290                 updateBrightnessState(msg);
291             } else { // dimension notification
292                 if (msg.getDim() == Lighting.DimLighting.DIMMER_LEVEL_100) {
293                     int newBrightness;
294                     try {
295                         newBrightness = msg.parseDimmerLevel100();
296                     } catch (FrameException fe) {
297                         logger.warn("updateBrightness() Wrong value for dimmerLevel100 in message: {}", msg);
298                         return;
299                     }
300                     logger.debug("  $BRI DIMMER_LEVEL_100 newBrightness={}", newBrightness);
301                     updateState(CHANNEL_BRIGHTNESS, new PercentType(newBrightness));
302                     if (newBrightness == 0) {
303                         brightnessBeforeOff = brightness;
304                     }
305                     brightness = newBrightness;
306                 } else {
307                     logger.warn("updateBrightness() Cannot handle message {} for thing {}", msg, getThing().getUID());
308                     return;
309                 }
310             }
311         }
312         logger.debug("  $BRI---END updateBrightness({}) || bri={} briBeforeOff={}", msg, brightness,
313                 brightnessBeforeOff);
314     }
315
316     /**
317      * Updates light brightness state based on an OWN Lighting message
318      *
319      * @param msg the Lighting message received
320      */
321     private void updateBrightnessState(Lighting msg) {
322         What w = msg.getWhat();
323         if (w != null) {
324             if (Lighting.WhatLighting.ON.equals(w)) {
325                 w = Lighting.WhatLighting.DIMMER_LEVEL_2; // levels start at 2
326             }
327             int newBrightnessWhat = w.value();
328             int brightnessWhat = UNKNOWN_STATE;
329             if (brightness != UNKNOWN_STATE) {
330                 brightnessWhat = Lighting.percentToWhat(brightness).value();
331             }
332             logger.debug("  $BRI brightnessWhat {} --> {}", brightnessWhat, newBrightnessWhat);
333             if (brightnessWhat != newBrightnessWhat) {
334                 int newBrightness = Lighting.levelToPercent(newBrightnessWhat);
335                 updateState(CHANNEL_BRIGHTNESS, new PercentType(newBrightness));
336                 if (msg.isOff()) {
337                     brightnessBeforeOff = brightness;
338                 }
339                 brightness = newBrightness;
340                 logger.debug("  $BRI brightness CHANGED to {}", brightness);
341             } else {
342                 logger.debug("  $BRI no change");
343             }
344         }
345     }
346
347     /**
348      * Updates light on/off state based on an OWN Lighting event message received
349      *
350      * @param msg the Lighting message received
351      */
352     private void updateOnOffState(Lighting msg) {
353         OpenWebNetBridgeHandler brH = bridgeHandler;
354         if (brH != null) {
355             if (msg.isOn() || msg.isOff()) {
356                 String channelId;
357                 if (brH.isBusGateway()) {
358                     channelId = CHANNEL_SWITCH;
359                 } else {
360                     WhereZigBee w = (WhereZigBee) (msg.getWhere());
361                     if (WhereZigBee.UNIT_02.equals(w.getUnit())) {
362                         channelId = CHANNEL_SWITCH_02;
363                     } else {
364                         channelId = CHANNEL_SWITCH_01;
365                     }
366                 }
367                 updateState(channelId, OnOffType.from(msg.isOn()));
368             } else {
369                 logger.debug("updateOnOffState() Ignoring unsupported WHAT for thing {}. Frame={}", getThing().getUID(),
370                         msg.getFrameValue());
371                 return;
372             }
373         }
374     }
375
376     @Override
377     protected Where buildBusWhere(String wStr) throws IllegalArgumentException {
378         return new WhereLightAutom(wStr);
379     }
380
381     /**
382      * Returns a WHERE address string based on channelId string
383      *
384      * @param channelId the channelId string
385      **/
386     @Nullable
387     private String toWhere(String channelId) {
388         Where w = deviceWhere;
389         if (w != null) {
390             OpenWebNetBridgeHandler brH = bridgeHandler;
391             if (brH != null) {
392                 if (brH.isBusGateway()) {
393                     return w.value();
394                 } else if (channelId.equals(CHANNEL_SWITCH_02)) {
395                     return ((WhereZigBee) w).valueWithUnit(WhereZigBee.UNIT_02);
396                 } else { // CHANNEL_SWITCH_01 or other channels
397                     return ((WhereZigBee) w).valueWithUnit(WhereZigBee.UNIT_01);
398                 }
399             }
400         }
401         return null;
402     }
403 }