]> git.basschouten.com Git - openhab-addons.git/blob
498a147ee7b091eff6cacbd225998fc8280fdf3c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.hdpowerview.internal.handler;
14
15 import static org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants.*;
16
17 import java.util.concurrent.ScheduledFuture;
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.hdpowerview.internal.HDPowerViewWebTargets;
23 import org.openhab.binding.hdpowerview.internal.api.Color;
24 import org.openhab.binding.hdpowerview.internal.api.Firmware;
25 import org.openhab.binding.hdpowerview.internal.api.responses.RepeaterData;
26 import org.openhab.binding.hdpowerview.internal.config.HDPowerViewRepeaterConfiguration;
27 import org.openhab.binding.hdpowerview.internal.exceptions.HubException;
28 import org.openhab.binding.hdpowerview.internal.exceptions.HubInvalidResponseException;
29 import org.openhab.binding.hdpowerview.internal.exceptions.HubMaintenanceException;
30 import org.openhab.core.library.types.HSBType;
31 import org.openhab.core.library.types.OnOffType;
32 import org.openhab.core.library.types.PercentType;
33 import org.openhab.core.library.types.StringType;
34 import org.openhab.core.thing.Bridge;
35 import org.openhab.core.thing.ChannelUID;
36 import org.openhab.core.thing.Thing;
37 import org.openhab.core.thing.ThingStatus;
38 import org.openhab.core.thing.ThingStatusDetail;
39 import org.openhab.core.types.Command;
40 import org.openhab.core.types.UnDefType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Handles commands for an HD PowerView Repeater
46  *
47  * @author Jacob Laursen - Initial contribution
48  */
49 @NonNullByDefault
50 public class HDPowerViewRepeaterHandler extends AbstractHubbedThingHandler {
51
52     private final Logger logger = LoggerFactory.getLogger(HDPowerViewRepeaterHandler.class);
53
54     private static final int REFRESH_INTERVAL_MINUTES = 5;
55     private static final int IDENTITY_PERIOD_SECONDS = 3;
56     private static final String COMMAND_IDENTIFY = "IDENTIFY";
57
58     private @Nullable ScheduledFuture<?> refreshStatusFuture = null;
59     private @Nullable ScheduledFuture<?> resetIdentifyStateFuture = null;
60     private int repeaterId;
61
62     public HDPowerViewRepeaterHandler(Thing thing) {
63         super(thing);
64     }
65
66     @Override
67     public void initialize() {
68         repeaterId = getConfigAs(HDPowerViewRepeaterConfiguration.class).id;
69         logger.debug("Initializing repeater handler for repeater {}", repeaterId);
70         Bridge bridge = getBridge();
71         if (bridge == null) {
72             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
73                     "@text/offline.conf-error.invalid-bridge-handler");
74             return;
75         }
76
77         updateStatus(ThingStatus.UNKNOWN);
78
79         scheduleRefreshJob();
80     }
81
82     @Override
83     public void dispose() {
84         logger.debug("Disposing repeater handler for repeater {}", repeaterId);
85         cancelRefreshJob();
86         cancelResetIdentifyStateJob();
87     }
88
89     @Override
90     public void handleCommand(ChannelUID channelUID, Command command) {
91         HDPowerViewHubHandler bridge = getBridgeHandler();
92         if (bridge == null) {
93             logger.warn("Missing bridge handler");
94             return;
95         }
96         HDPowerViewWebTargets webTargets = bridge.getWebTargets();
97         if (webTargets == null) {
98             logger.warn("Web targets not initialized");
99             return;
100         }
101
102         try {
103             RepeaterData repeaterData;
104
105             switch (channelUID.getId()) {
106                 case CHANNEL_REPEATER_COLOR:
107                     if (command instanceof HSBType) {
108                         Color currentColor = webTargets.getRepeater(repeaterId).color;
109                         if (currentColor != null) {
110                             HSBType hsbCommand = (HSBType) command;
111                             var color = new Color(currentColor.brightness, hsbCommand);
112                             repeaterData = webTargets.setRepeaterColor(repeaterId, color);
113                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
114                         }
115                     } else if (command instanceof OnOffType) {
116                         Color currentColor = webTargets.getRepeater(repeaterId).color;
117                         if (currentColor != null) {
118                             var color = command == OnOffType.ON
119                                     ? new Color(currentColor.brightness, java.awt.Color.WHITE)
120                                     : new Color(currentColor.brightness, java.awt.Color.BLACK);
121                             repeaterData = webTargets.setRepeaterColor(repeaterId, color);
122                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
123                         }
124                     }
125                     break;
126                 case CHANNEL_REPEATER_BRIGHTNESS:
127                     if (command instanceof PercentType) {
128                         Color currentColor = webTargets.getRepeater(repeaterId).color;
129                         if (currentColor != null) {
130                             PercentType brightness = (PercentType) command;
131                             var color = new Color(brightness.intValue(), currentColor.red, currentColor.green,
132                                     currentColor.blue);
133                             repeaterData = webTargets.setRepeaterColor(repeaterId, color);
134                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
135                         }
136                     }
137                     break;
138                 case CHANNEL_REPEATER_IDENTIFY:
139                     if (command instanceof StringType) {
140                         if (COMMAND_IDENTIFY.equals(((StringType) command).toString())) {
141                             repeaterData = webTargets.identifyRepeater(repeaterId);
142                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
143                             cancelResetIdentifyStateJob();
144                             resetIdentifyStateFuture = scheduler.schedule(() -> {
145                                 updateState(CHANNEL_REPEATER_IDENTIFY, UnDefType.UNDEF);
146                             }, IDENTITY_PERIOD_SECONDS, TimeUnit.SECONDS);
147                         } else {
148                             logger.warn("Unsupported command: {}. Supported commands are: " + COMMAND_IDENTIFY,
149                                     command);
150                         }
151                     }
152                     break;
153                 case CHANNEL_REPEATER_BLINKING_ENABLED:
154                     repeaterData = webTargets.enableRepeaterBlinking(repeaterId, OnOffType.ON == command);
155                     scheduler.submit(() -> updatePropertyAndStates(repeaterData));
156                     break;
157             }
158         } catch (HubInvalidResponseException e) {
159             Throwable cause = e.getCause();
160             if (cause == null) {
161                 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
162             } else {
163                 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
164             }
165         } catch (HubMaintenanceException e) {
166             // exceptions are logged in HDPowerViewWebTargets
167         } catch (HubException e) {
168             logger.warn("Unexpected error: {}", e.getMessage());
169         }
170     }
171
172     private void cancelResetIdentifyStateJob() {
173         ScheduledFuture<?> scheduledJob = resetIdentifyStateFuture;
174         if (scheduledJob != null) {
175             scheduledJob.cancel(true);
176         }
177         resetIdentifyStateFuture = null;
178     }
179
180     private void scheduleRefreshJob() {
181         cancelRefreshJob();
182         logger.debug("Scheduling poll for repeater {} now, then every {} minutes", repeaterId,
183                 REFRESH_INTERVAL_MINUTES);
184         this.refreshStatusFuture = scheduler.scheduleWithFixedDelay(this::poll, 0, REFRESH_INTERVAL_MINUTES,
185                 TimeUnit.MINUTES);
186     }
187
188     private void cancelRefreshJob() {
189         ScheduledFuture<?> future = this.refreshStatusFuture;
190         if (future != null) {
191             future.cancel(false);
192         }
193         this.refreshStatusFuture = null;
194     }
195
196     private synchronized void poll() {
197         HDPowerViewHubHandler bridge = getBridgeHandler();
198         if (bridge == null) {
199             logger.warn("Missing bridge handler");
200             return;
201         }
202         HDPowerViewWebTargets webTargets = bridge.getWebTargets();
203         if (webTargets == null) {
204             logger.warn("Web targets not initialized");
205             return;
206         }
207         try {
208             logger.debug("Polling for status information");
209
210             RepeaterData repeaterData = webTargets.getRepeater(repeaterId);
211             updatePropertyAndStates(repeaterData);
212
213         } catch (HubInvalidResponseException e) {
214             Throwable cause = e.getCause();
215             if (cause == null) {
216                 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
217             } else {
218                 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
219             }
220         } catch (HubMaintenanceException e) {
221             // exceptions are logged in HDPowerViewWebTargets
222         } catch (HubException e) {
223             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage());
224         }
225     }
226
227     private void updatePropertyAndStates(RepeaterData repeaterData) {
228         updateStatus(ThingStatus.ONLINE);
229
230         Firmware firmware = repeaterData.firmware;
231         if (firmware != null) {
232             logger.debug("Repeater firmware version received: {}", firmware.toString());
233             updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, firmware.toString());
234         } else {
235             logger.warn("Repeater firmware version missing in response");
236         }
237
238         Color color = repeaterData.color;
239         if (color != null) {
240             logger.debug("Repeater color data received: {}", color.toString());
241             updateState(CHANNEL_REPEATER_COLOR, HSBType.fromRGB(color.red, color.green, color.red));
242             updateState(CHANNEL_REPEATER_BRIGHTNESS, new PercentType(color.brightness));
243         }
244
245         updateState(CHANNEL_REPEATER_BLINKING_ENABLED, repeaterData.blinkEnabled ? OnOffType.ON : OnOffType.OFF);
246     }
247 }