]> git.basschouten.com Git - openhab-addons.git/blob
f2a3e37d6d7f475aca5c72f149ee14d3b525fcae
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.bsblan.internal.handler;
14
15 import static org.openhab.binding.bsblan.internal.BsbLanBindingConstants.*;
16
17 import java.util.HashSet;
18 import java.util.Set;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21 import java.util.stream.*;
22
23 import org.apache.commons.lang.StringUtils;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.bsblan.internal.api.BsbLanApiCaller;
27 import org.openhab.binding.bsblan.internal.api.dto.BsbLanApiParameterQueryResponseDTO;
28 import org.openhab.binding.bsblan.internal.configuration.BsbLanBridgeConfiguration;
29 import org.openhab.core.thing.Bridge;
30 import org.openhab.core.thing.ChannelUID;
31 import org.openhab.core.thing.ThingStatus;
32 import org.openhab.core.thing.ThingStatusDetail;
33 import org.openhab.core.thing.binding.BaseBridgeHandler;
34 import org.openhab.core.types.Command;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * Bridge for BSB-LAN devices.
40  *
41  * @author Peter Schraffl - Initial contribution
42  */
43 @NonNullByDefault
44 public class BsbLanBridgeHandler extends BaseBridgeHandler {
45
46     private final Logger logger = LoggerFactory.getLogger(BsbLanBridgeHandler.class);
47     private final Set<BsbLanBaseThingHandler> things = new HashSet<>();
48     private BsbLanBridgeConfiguration bridgeConfig = new BsbLanBridgeConfiguration();
49     private @Nullable ScheduledFuture<?> refreshJob;
50     private @Nullable ScheduledFuture<?> debouncedInit;
51     private @Nullable BsbLanApiParameterQueryResponseDTO cachedParameterQueryResponse;
52
53     public BsbLanBridgeHandler(Bridge bridge) {
54         super(bridge);
55     }
56
57     @Override
58     public void handleCommand(ChannelUID channelUID, Command command) {
59     }
60
61     public void registerThing(final BsbLanBaseThingHandler parameter) {
62         this.things.add(parameter);
63
64         // To avoid having to wait up to refreshInterval seconds until values are updated
65         // for the added thing, we trigger a debounced refresh to shorten the delay.
66         // Alternatively the thing itself could make an additional REST call
67         // on initialization but this would flood the device when lots of parameters are setup.
68
69         // use a local variable to avoid the build warning "Potential null pointer access"
70         ScheduledFuture<?> localDebouncedInit = debouncedInit;
71         if (localDebouncedInit == null || localDebouncedInit.isCancelled() || localDebouncedInit.isDone()) {
72             debouncedInit = scheduler.schedule(this::doRefresh, 2, TimeUnit.SECONDS);
73         }
74     }
75
76     @Override
77     public void initialize() {
78         bridgeConfig = getConfigAs(BsbLanBridgeConfiguration.class);
79
80         // validate 'host' configuration
81         if (StringUtils.isBlank(bridgeConfig.host)) {
82             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
83                     "Parameter 'host' is mandatory and must be configured");
84             return;
85         }
86
87         // validate 'refreshInterval' configuration
88         if (bridgeConfig.refreshInterval != null && bridgeConfig.refreshInterval < MIN_REFRESH_INTERVAL) {
89             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
90                     String.format("Parameter 'refreshInterval' must be at least %d seconds", MIN_REFRESH_INTERVAL));
91             return;
92         }
93
94         if (bridgeConfig.port == null) {
95             bridgeConfig.port = DEFAULT_API_PORT;
96         }
97
98         // all checks succeeded, start refreshing
99         startAutomaticRefresh(bridgeConfig);
100     }
101
102     @Override
103     public void dispose() {
104         // use a local variable to avoid the build warning "Potential null pointer access"
105         ScheduledFuture<?> localRefreshJob = refreshJob;
106         if (localRefreshJob != null) {
107             localRefreshJob.cancel(true);
108         }
109         // use a local variable to avoid the build warning "Potential null pointer access"
110         ScheduledFuture<?> localDebouncedInit = debouncedInit;
111         if (localDebouncedInit != null) {
112             localDebouncedInit.cancel(true);
113         }
114         things.clear();
115     }
116
117     public @Nullable BsbLanApiParameterQueryResponseDTO getCachedParameterQueryResponse() {
118         return cachedParameterQueryResponse;
119     }
120
121     public BsbLanBridgeConfiguration getBridgeConfiguration() {
122         return bridgeConfig;
123     }
124
125     private void doRefresh() {
126         logger.trace("Refreshing parameter values");
127
128         BsbLanApiCaller apiCaller = new BsbLanApiCaller(bridgeConfig);
129
130         // refresh all parameters
131         Set<Integer> parameterIds = things.stream().filter(thing -> thing instanceof BsbLanParameterHandler)
132                 .map(thing -> (BsbLanParameterHandler) thing).map(thing -> thing.getParameterId())
133                 .collect(Collectors.toSet());
134
135         cachedParameterQueryResponse = apiCaller.queryParameters(parameterIds);
136
137         // InetAddress.isReachable(...) check returned false on RPi although the device is reachable (worked on
138         // Windows).
139         // Therefore we check status depending on the response.
140         if (cachedParameterQueryResponse == null) {
141             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
142                     "Did not receive a response from BSB-LAN device. Check your configuration and if device is online.");
143             // continue processing, so things can go to OFFLINE too
144         } else {
145             // response received, tread device as reachable, refresh state now
146             updateStatus(ThingStatus.ONLINE);
147         }
148
149         for (BsbLanBaseThingHandler parameter : things) {
150             parameter.refresh(bridgeConfig);
151         }
152     }
153
154     /**
155      * Start the job refreshing the data
156      */
157     private void startAutomaticRefresh(BsbLanBridgeConfiguration config) {
158         // use a local variable to avoid the build warning "Potential null pointer access"
159         ScheduledFuture<?> localRefreshJob = refreshJob;
160         if (localRefreshJob == null || localRefreshJob.isCancelled()) {
161             int interval = (config.refreshInterval != null) ? config.refreshInterval.intValue()
162                     : DEFAULT_REFRESH_INTERVAL;
163             refreshJob = scheduler.scheduleWithFixedDelay(this::doRefresh, 0, interval, TimeUnit.SECONDS);
164         }
165     }
166 }