]> git.basschouten.com Git - openhab-addons.git/blob
6c799375f5cf84d96e4e0b370823e3e553c6e9ed
[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.unifi.internal.handler;
14
15 import static org.openhab.core.thing.ThingStatus.OFFLINE;
16 import static org.openhab.core.thing.ThingStatus.ONLINE;
17 import static org.openhab.core.thing.ThingStatus.UNKNOWN;
18 import static org.openhab.core.thing.ThingStatusDetail.COMMUNICATION_ERROR;
19 import static org.openhab.core.thing.ThingStatusDetail.CONFIGURATION_ERROR;
20
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.eclipse.jetty.client.HttpClient;
29 import org.openhab.binding.unifi.internal.UniFiControllerThingConfig;
30 import org.openhab.binding.unifi.internal.api.UniFiCommunicationException;
31 import org.openhab.binding.unifi.internal.api.UniFiController;
32 import org.openhab.binding.unifi.internal.api.UniFiException;
33 import org.openhab.binding.unifi.internal.api.UniFiInvalidCredentialsException;
34 import org.openhab.binding.unifi.internal.api.UniFiInvalidHostException;
35 import org.openhab.binding.unifi.internal.api.UniFiSSLException;
36 import org.openhab.core.thing.Bridge;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.ThingStatus;
39 import org.openhab.core.thing.ThingStatusDetail;
40 import org.openhab.core.thing.ThingStatusInfo;
41 import org.openhab.core.thing.binding.BaseBridgeHandler;
42 import org.openhab.core.thing.binding.ThingHandlerService;
43 import org.openhab.core.thing.binding.builder.ThingStatusInfoBuilder;
44 import org.openhab.core.types.Command;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * The {@link UniFiControllerThingHandler} is responsible for handling commands and status
50  * updates for the UniFi Controller.
51  *
52  * @author Matthew Bowman - Initial contribution
53  */
54 @NonNullByDefault
55 public class UniFiControllerThingHandler extends BaseBridgeHandler {
56
57     private static final String STATUS_DESCRIPTION_COMMUNICATION_ERROR = "@text/error.bridge.offline.communication_error";
58     private static final String STATUS_DESCRIPTION_SSL_ERROR = "@text/error.bridge.offline.ssl_error";
59     private static final String STATUS_DESCRIPTION_INVALID_CREDENTIALS = "@text/error.bridge.offline.invalid_credentials";
60     private static final String STATUS_DESCRIPTION_INVALID_HOSTNAME = "@text/error.bridge.offline.invalid_hostname";
61
62     private final Logger logger = LoggerFactory.getLogger(UniFiControllerThingHandler.class);
63
64     private UniFiControllerThingConfig config = new UniFiControllerThingConfig();
65
66     private @Nullable volatile UniFiController controller; /* mgb: volatile because accessed from multiple threads */
67
68     private @Nullable ScheduledFuture<?> refreshJob;
69
70     private final HttpClient httpClient;
71
72     public UniFiControllerThingHandler(final Bridge bridge, final HttpClient httpClient) {
73         super(bridge);
74         this.httpClient = httpClient;
75     }
76
77     // Public API
78
79     @Override
80     public Collection<Class<? extends ThingHandlerService>> getServices() {
81         return List.of(UniFiThingDiscoveryService.class);
82     }
83
84     @Override
85     public void initialize() {
86         config = getConfigAs(UniFiControllerThingConfig.class);
87         logger.debug("Initializing the UniFi Controller Handler with config = {}", config);
88         final UniFiController uc = new UniFiController(httpClient, config.getHost(), config.getPort(),
89                 config.getUsername(), config.getPassword(), config.isUniFiOS());
90
91         controller = uc;
92         updateStatus(UNKNOWN);
93         scheduler.schedule(() -> start(uc), 10, TimeUnit.MILLISECONDS);
94     }
95
96     @Override
97     protected void updateStatus(final ThingStatus status, final ThingStatusDetail statusDetail,
98             @Nullable final String description) {
99         // mgb: update the status only if it's changed
100         final ThingStatusInfo statusInfo = ThingStatusInfoBuilder.create(status, statusDetail)
101                 .withDescription(description).build();
102         if (!statusInfo.equals(getThing().getStatusInfo())) {
103             super.updateStatus(status, statusDetail, description);
104         }
105     }
106
107     @Override
108     public void dispose() {
109         cancelRefreshJob();
110         if (controller != null) {
111             try {
112                 controller.stop();
113             } catch (final UniFiException e) {
114                 // mgb: nop as we're in dispose
115             }
116             controller = null;
117         }
118     }
119
120     @Override
121     public void handleCommand(final ChannelUID channelUID, final Command command) {
122         // nop - read-only binding
123         logger.warn("Ignoring command = {} for channel = {} - the UniFi binding is read-only!", command, channelUID);
124     }
125
126     public @Nullable UniFiController getController() {
127         return controller;
128     }
129
130     // Private API
131
132     private void start(final UniFiController uc) {
133         boolean startRefresh = false;
134         try {
135             uc.start();
136             startRefresh = true;
137         } catch (final UniFiCommunicationException e) {
138             updateStatus(OFFLINE, COMMUNICATION_ERROR, STATUS_DESCRIPTION_COMMUNICATION_ERROR);
139             startRefresh = true;
140         } catch (final UniFiInvalidHostException e) {
141             updateStatus(OFFLINE, CONFIGURATION_ERROR, STATUS_DESCRIPTION_INVALID_HOSTNAME);
142         } catch (final UniFiSSLException e) {
143             updateStatus(OFFLINE, CONFIGURATION_ERROR, STATUS_DESCRIPTION_SSL_ERROR);
144         } catch (final UniFiInvalidCredentialsException e) {
145             updateStatus(OFFLINE, CONFIGURATION_ERROR, STATUS_DESCRIPTION_INVALID_CREDENTIALS);
146         } catch (final UniFiException e) {
147             logger.debug("Unknown error while configuring the UniFi Controller", e);
148             updateStatus(OFFLINE, CONFIGURATION_ERROR, e.getMessage());
149         }
150         if (startRefresh) {
151             logger.debug("Scheduling refresh job every {}s", config.getRefresh());
152             refreshJob = scheduler.scheduleWithFixedDelay(this::run, 0, config.getRefresh(), TimeUnit.SECONDS);
153         }
154     }
155
156     private void cancelRefreshJob() {
157         synchronized (this) {
158             final ScheduledFuture<?> rj = refreshJob;
159
160             if (rj != null) {
161                 logger.debug("Cancelling refresh job");
162                 rj.cancel(true);
163                 refreshJob = null;
164             }
165         }
166     }
167
168     private void run() {
169         try {
170             logger.trace("Executing refresh job");
171             refresh();
172             updateStatus(ONLINE);
173         } catch (final UniFiCommunicationException e) {
174             updateStatus(OFFLINE, COMMUNICATION_ERROR, STATUS_DESCRIPTION_COMMUNICATION_ERROR);
175         } catch (final UniFiInvalidCredentialsException e) {
176             updateStatus(OFFLINE, CONFIGURATION_ERROR, STATUS_DESCRIPTION_INVALID_CREDENTIALS);
177         } catch (final RuntimeException | UniFiException e) {
178             logger.debug("Unhandled exception while refreshing the UniFi Controller {}", getThing().getUID(), e);
179             updateStatus(OFFLINE, COMMUNICATION_ERROR, e.getMessage());
180         }
181     }
182
183     private void refresh() throws UniFiException {
184         final UniFiController uc = controller;
185
186         if (uc != null) {
187             logger.debug("Refreshing the UniFi Controller {}", getThing().getUID());
188             uc.refresh();
189             // mgb: then refresh all the client things
190             getThing().getThings().forEach((thing) -> {
191                 if (thing.getHandler() instanceof UniFiBaseThingHandler) {
192                     ((UniFiBaseThingHandler) thing.getHandler()).refresh();
193                 }
194             });
195         }
196     }
197 }