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