]> git.basschouten.com Git - openhab-addons.git/blob
d5516e09361136e56fdbc7998950fc58f09a5d3b
[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.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.config.HDPowerViewRepeaterConfiguration;
24 import org.openhab.binding.hdpowerview.internal.dto.Color;
25 import org.openhab.binding.hdpowerview.internal.dto.Firmware;
26 import org.openhab.binding.hdpowerview.internal.dto.responses.RepeaterData;
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         try {
98             RepeaterData repeaterData;
99
100             switch (channelUID.getId()) {
101                 case CHANNEL_REPEATER_COLOR:
102                     if (command instanceof HSBType) {
103                         Color currentColor = webTargets.getRepeater(repeaterId).color;
104                         if (currentColor != null) {
105                             HSBType hsbCommand = (HSBType) command;
106                             var color = new Color(currentColor.brightness, hsbCommand);
107                             repeaterData = webTargets.setRepeaterColor(repeaterId, color);
108                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
109                         }
110                     } else if (command instanceof OnOffType) {
111                         Color currentColor = webTargets.getRepeater(repeaterId).color;
112                         if (currentColor != null) {
113                             var color = command == OnOffType.ON
114                                     ? new Color(currentColor.brightness, java.awt.Color.WHITE)
115                                     : new Color(currentColor.brightness, java.awt.Color.BLACK);
116                             repeaterData = webTargets.setRepeaterColor(repeaterId, color);
117                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
118                         }
119                     }
120                     break;
121                 case CHANNEL_REPEATER_BRIGHTNESS:
122                     if (command instanceof PercentType) {
123                         Color currentColor = webTargets.getRepeater(repeaterId).color;
124                         if (currentColor != null) {
125                             PercentType brightness = (PercentType) command;
126                             var color = new Color(brightness.intValue(), currentColor.red, currentColor.green,
127                                     currentColor.blue);
128                             repeaterData = webTargets.setRepeaterColor(repeaterId, color);
129                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
130                         }
131                     }
132                     break;
133                 case CHANNEL_REPEATER_IDENTIFY:
134                     if (command instanceof StringType) {
135                         if (COMMAND_IDENTIFY.equals(((StringType) command).toString())) {
136                             repeaterData = webTargets.identifyRepeater(repeaterId);
137                             scheduler.submit(() -> updatePropertyAndStates(repeaterData));
138                             cancelResetIdentifyStateJob();
139                             resetIdentifyStateFuture = scheduler.schedule(() -> {
140                                 updateState(CHANNEL_REPEATER_IDENTIFY, UnDefType.UNDEF);
141                             }, IDENTITY_PERIOD_SECONDS, TimeUnit.SECONDS);
142                         } else {
143                             logger.warn("Unsupported command: {}. Supported commands are: " + COMMAND_IDENTIFY,
144                                     command);
145                         }
146                     }
147                     break;
148                 case CHANNEL_REPEATER_BLINKING_ENABLED:
149                     repeaterData = webTargets.enableRepeaterBlinking(repeaterId, OnOffType.ON == command);
150                     scheduler.submit(() -> updatePropertyAndStates(repeaterData));
151                     break;
152             }
153         } catch (HubInvalidResponseException e) {
154             Throwable cause = e.getCause();
155             if (cause == null) {
156                 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
157             } else {
158                 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
159             }
160         } catch (HubMaintenanceException e) {
161             // exceptions are logged in HDPowerViewWebTargets
162         } catch (HubException e) {
163             logger.warn("Unexpected error: {}", e.getMessage());
164         }
165     }
166
167     private void cancelResetIdentifyStateJob() {
168         ScheduledFuture<?> scheduledJob = resetIdentifyStateFuture;
169         if (scheduledJob != null) {
170             scheduledJob.cancel(true);
171         }
172         resetIdentifyStateFuture = null;
173     }
174
175     private void scheduleRefreshJob() {
176         cancelRefreshJob();
177         logger.debug("Scheduling poll for repeater {} now, then every {} minutes", repeaterId,
178                 REFRESH_INTERVAL_MINUTES);
179         this.refreshStatusFuture = scheduler.scheduleWithFixedDelay(this::poll, 0, REFRESH_INTERVAL_MINUTES,
180                 TimeUnit.MINUTES);
181     }
182
183     private void cancelRefreshJob() {
184         ScheduledFuture<?> future = this.refreshStatusFuture;
185         if (future != null) {
186             future.cancel(false);
187         }
188         this.refreshStatusFuture = null;
189     }
190
191     private synchronized void poll() {
192         HDPowerViewHubHandler bridge = getBridgeHandler();
193         if (bridge == null) {
194             logger.warn("Missing bridge handler");
195             return;
196         }
197         HDPowerViewWebTargets webTargets = bridge.getWebTargets();
198         try {
199             logger.debug("Polling for status information");
200
201             RepeaterData repeaterData = webTargets.getRepeater(repeaterId);
202             updatePropertyAndStates(repeaterData);
203
204         } catch (HubInvalidResponseException e) {
205             Throwable cause = e.getCause();
206             if (cause == null) {
207                 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
208             } else {
209                 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
210             }
211         } catch (HubMaintenanceException e) {
212             // exceptions are logged in HDPowerViewWebTargets
213         } catch (HubException e) {
214             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage());
215         }
216     }
217
218     private void updatePropertyAndStates(RepeaterData repeaterData) {
219         updateStatus(ThingStatus.ONLINE);
220
221         Firmware firmware = repeaterData.firmware;
222         if (firmware != null) {
223             logger.debug("Repeater firmware version received: {}", firmware.toString());
224             updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, firmware.toString());
225         } else {
226             logger.warn("Repeater firmware version missing in response");
227         }
228
229         Color color = repeaterData.color;
230         if (color != null) {
231             logger.debug("Repeater color data received: {}", color.toString());
232             updateState(CHANNEL_REPEATER_COLOR, HSBType.fromRGB(color.red, color.green, color.red));
233             updateState(CHANNEL_REPEATER_BRIGHTNESS, new PercentType(color.brightness));
234         }
235
236         updateState(CHANNEL_REPEATER_BLINKING_ENABLED, repeaterData.blinkEnabled ? OnOffType.ON : OnOffType.OFF);
237     }
238 }