2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.openwebnet.internal.handler;
15 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.*;
18 import java.util.concurrent.TimeUnit;
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;
45 * The {@link OpenWebNetLightingHandler} is responsible for handling
46 * commands/messages for a Lighting OpenWebNet device.
47 * It extends the abstract {@link OpenWebNetThingHandler}.
49 * @author Massimo Valla - Initial contribution
52 public class OpenWebNetLightingHandler extends OpenWebNetThingHandler {
54 private final Logger logger = LoggerFactory.getLogger(OpenWebNetLightingHandler.class);
56 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = OpenWebNetBindingConstants.LIGHTING_SUPPORTED_THING_TYPES;
58 // interval to interpret ON as response to requestStatus
59 private static final int BRIGHTNESS_STATUS_REQUEST_INTERVAL_MSEC = 250;
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;
65 private static final int UNKNOWN_STATE = 1000;
67 private long lastBrightnessChangeSentTS = 0; // timestamp when last brightness change was sent to the device
69 private long lastStatusRequestSentTS = 0; // timestamp when last status request was sent to the device
71 private static long lastAllDevicesRefreshTS = 0; // ts when last all device refresh was sent for this handler
73 private int brightness = UNKNOWN_STATE; // current brightness percent value for this device
75 private int brightnessBeforeOff = UNKNOWN_STATE; // latest brightness before device was set to off
77 public OpenWebNetLightingHandler(Thing thing) {
82 protected void requestChannelState(ChannelUID channel) {
83 super.requestChannelState(channel);
84 if (deviceWhere != null) {
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());
96 protected long getRefreshAllLastTS() {
97 return lastAllDevicesRefreshTS;
101 protected void refreshDevice(boolean refreshAll) {
103 logger.debug("--- refreshDevice() : refreshing GENERAL... ({})", thing.getUID());
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());
111 logger.debug("--- refreshDevice() : refreshing SINGLE... ({})", thing.getUID());
112 ThingTypeUID thingType = thing.getThingTypeUID();
113 if (THING_TYPE_ZB_ON_OFF_SWITCH_2UNITS.equals(thingType)) {
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
119 requestChannelState(new ChannelUID(thing.getUID(), CHANNEL_SWITCH_02));
121 requestChannelState(new ChannelUID(thing.getUID(), CHANNEL_SWITCH_01));
126 protected void handleChannelCommand(ChannelUID channel, Command command) {
127 switch (channel.getId()) {
128 case CHANNEL_BRIGHTNESS:
129 handleBrightnessCommand(command);
132 case CHANNEL_SWITCH_01:
133 case CHANNEL_SWITCH_02:
134 handleSwitchCommand(channel, command);
137 logger.warn("Unsupported ChannelUID {}", channel);
143 * Handles Lighting switch command for a channel
145 * @param channel the channel
146 * @param command the command
148 private void handleSwitchCommand(ChannelUID channel, Command command) {
149 logger.debug("handleSwitchCommand() (command={} - channel={})", command, channel);
150 if (command instanceof OnOffType) {
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())));
157 } catch (OWNException e) {
158 logger.warn("Exception while processing command {}: {}", command, e.getMessage());
161 logger.warn("Unsupported command: {}", command);
166 * Handles Lighting brightness command (xx%, INCREASE, DECREASE, ON, OFF)
168 * @param command the command
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);
178 dimLightTo(brightness - 10, command);
180 } else if (command instanceof OnOffType) {
181 if (OnOffType.ON.equals(command)) {
182 dimLightTo(brightnessBeforeOff, command);
184 dimLightTo(0, command);
187 logger.warn("Cannot handle command {} for thing {}", command, getThing().getUID());
192 * Helper method to dim light to given percent
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%
200 } else if (newBrightness <= 0) {
202 brightnessBeforeOff = brightness;
203 logger.debug(" DIM saved bri before sending bri=0 command to device");
204 } else if (newBrightness > 100) {
207 What newBrightnessWhat = Lighting.percentToWhat(newBrightness);
208 logger.debug(" DIM newBrightness={} newBrightnessWhat={}", newBrightness, newBrightnessWhat);
210 What brightnessWhat = null;
211 if (brightness != UNKNOWN_STATE) {
212 brightnessWhat = Lighting.percentToWhat(brightness);
214 if (brightnessWhat == null || !newBrightnessWhat.value().equals(brightnessWhat.value())) {
215 logger.debug(" DIM brightnessWhat {} --> {} WHAT level change needed", brightnessWhat,
217 Where w = deviceWhere;
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());
227 logger.debug(" DIM brightnessWhat {} --> {} NO WHAT level change needed", brightnessWhat,
230 brightness = newBrightness;
231 updateState(CHANNEL_BRIGHTNESS, new PercentType(brightness));
232 logger.debug(" DIM---END bri={} briBeforeOff={}", brightness, brightnessBeforeOff);
236 protected String ownIdPrefix() {
237 return Who.LIGHTING.value().toString();
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);
248 updateOnOffState((Lighting) msg);
253 * Updates brightness based on OWN Lighting message received
255 * @param msg the Lighting message received
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" : ""));
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);
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);
282 // otherwise we interpret this ON event as the requestStatus response event with
284 // so we proceed to call updateBrightnessState()
285 logger.debug(" $BRI 'ON' is the requestStatus response level");
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) {
295 newBrightness = msg.parseDimmerLevel100();
296 } catch (FrameException fe) {
297 logger.warn("updateBrightness() Wrong value for dimmerLevel100 in message: {}", msg);
300 logger.debug(" $BRI DIMMER_LEVEL_100 newBrightness={}", newBrightness);
301 updateState(CHANNEL_BRIGHTNESS, new PercentType(newBrightness));
302 if (newBrightness == 0) {
303 brightnessBeforeOff = brightness;
305 brightness = newBrightness;
307 logger.warn("updateBrightness() Cannot handle message {} for thing {}", msg, getThing().getUID());
312 logger.debug(" $BRI---END updateBrightness({}) || bri={} briBeforeOff={}", msg, brightness,
313 brightnessBeforeOff);
317 * Updates light brightness state based on an OWN Lighting message
319 * @param msg the Lighting message received
321 private void updateBrightnessState(Lighting msg) {
322 What w = msg.getWhat();
324 if (Lighting.WhatLighting.ON.equals(w)) {
325 w = Lighting.WhatLighting.DIMMER_LEVEL_2; // levels start at 2
327 int newBrightnessWhat = w.value();
328 int brightnessWhat = UNKNOWN_STATE;
329 if (brightness != UNKNOWN_STATE) {
330 brightnessWhat = Lighting.percentToWhat(brightness).value();
332 logger.debug(" $BRI brightnessWhat {} --> {}", brightnessWhat, newBrightnessWhat);
333 if (brightnessWhat != newBrightnessWhat) {
334 int newBrightness = Lighting.levelToPercent(newBrightnessWhat);
335 updateState(CHANNEL_BRIGHTNESS, new PercentType(newBrightness));
337 brightnessBeforeOff = brightness;
339 brightness = newBrightness;
340 logger.debug(" $BRI brightness CHANGED to {}", brightness);
342 logger.debug(" $BRI no change");
348 * Updates light on/off state based on an OWN Lighting event message received
350 * @param msg the Lighting message received
352 private void updateOnOffState(Lighting msg) {
353 OpenWebNetBridgeHandler brH = bridgeHandler;
355 if (msg.isOn() || msg.isOff()) {
357 if (brH.isBusGateway()) {
358 channelId = CHANNEL_SWITCH;
360 WhereZigBee w = (WhereZigBee) (msg.getWhere());
361 if (WhereZigBee.UNIT_02.equals(w.getUnit())) {
362 channelId = CHANNEL_SWITCH_02;
364 channelId = CHANNEL_SWITCH_01;
367 updateState(channelId, OnOffType.from(msg.isOn()));
369 logger.debug("updateOnOffState() Ignoring unsupported WHAT for thing {}. Frame={}", getThing().getUID(),
370 msg.getFrameValue());
377 protected Where buildBusWhere(String wStr) throws IllegalArgumentException {
378 return new WhereLightAutom(wStr);
382 * Returns a WHERE address string based on channelId string
384 * @param channelId the channelId string
387 private String toWhere(String channelId) {
388 Where w = deviceWhere;
390 OpenWebNetBridgeHandler brH = bridgeHandler;
392 if (brH.isBusGateway()) {
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);