2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.tr064.internal;
15 import static org.openhab.binding.tr064.internal.Tr064BindingConstants.THING_TYPE_SUBDEVICE;
16 import static org.openhab.binding.tr064.internal.Tr064BindingConstants.THING_TYPE_SUBDEVICE_LAN;
18 import java.util.HashMap;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.tr064.internal.config.Tr064ChannelConfig;
27 import org.openhab.binding.tr064.internal.config.Tr064SubConfiguration;
28 import org.openhab.binding.tr064.internal.dto.scpd.root.SCPDDeviceType;
29 import org.openhab.binding.tr064.internal.soap.SOAPConnector;
30 import org.openhab.binding.tr064.internal.util.SCPDUtil;
31 import org.openhab.binding.tr064.internal.util.Util;
32 import org.openhab.core.cache.ExpiringCacheMap;
33 import org.openhab.core.thing.*;
34 import org.openhab.core.thing.binding.BaseThingHandler;
35 import org.openhab.core.thing.binding.builder.ThingBuilder;
36 import org.openhab.core.types.Command;
37 import org.openhab.core.types.RefreshType;
38 import org.openhab.core.types.State;
39 import org.openhab.core.types.UnDefType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * The {@link Tr064SubHandler} is responsible for handling commands, which are
45 * sent to one of the channels.
47 * @author Jan N. Klug - Initial contribution
50 public class Tr064SubHandler extends BaseThingHandler {
51 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SUBDEVICE,
52 THING_TYPE_SUBDEVICE_LAN);
53 private static final int RETRY_INTERVAL = 60;
55 private final Logger logger = LoggerFactory.getLogger(Tr064SubHandler.class);
57 private Tr064SubConfiguration config = new Tr064SubConfiguration();
59 private String deviceType = "";
60 private boolean isInitialized = false;
62 private final Map<ChannelUID, Tr064ChannelConfig> channels = new HashMap<>();
63 // caching is used to prevent excessive calls to the same action
64 private final ExpiringCacheMap<ChannelUID, State> stateCache = new ExpiringCacheMap<>(2000);
66 private @Nullable SOAPConnector soapConnector;
67 private @Nullable ScheduledFuture<?> connectFuture;
68 private @Nullable ScheduledFuture<?> pollFuture;
70 Tr064SubHandler(Thing thing) {
75 @SuppressWarnings("null")
76 public void handleCommand(ChannelUID channelUID, Command command) {
77 Tr064ChannelConfig channelConfig = channels.get(channelUID);
78 if (channelConfig == null) {
79 logger.trace("Channel {} not supported.", channelUID);
83 if (command instanceof RefreshType) {
84 State state = stateCache.putIfAbsentAndGet(channelUID, () -> soapConnector == null ? UnDefType.UNDEF
85 : soapConnector.getChannelStateFromDevice(channelConfig, channels, stateCache));
87 updateState(channelUID, state);
92 if (channelConfig.getChannelTypeDescription().getSetAction() == null) {
93 logger.debug("Discarding command {} to {}, read-only channel", command, channelUID);
96 scheduler.execute(() -> {
97 if (soapConnector == null) {
98 logger.warn("Could not send command because connector not available");
100 soapConnector.sendChannelCommandToDevice(channelConfig, command);
106 public void initialize() {
107 config = getConfigAs(Tr064SubConfiguration.class);
108 if (!config.isValid()) {
109 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
110 "One or more mandatory configuration fields are empty");
114 final Bridge bridge = getBridge();
115 if (bridge != null && bridge.getStatus().equals(ThingStatus.ONLINE)) {
116 updateStatus(ThingStatus.UNKNOWN);
117 connectFuture = scheduler.scheduleWithFixedDelay(this::internalInitialize, 0, 30, TimeUnit.SECONDS);
119 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
123 private void internalInitialize() {
124 final Bridge bridge = getBridge();
125 if (bridge == null) {
128 final Tr064RootHandler bridgeHandler = (Tr064RootHandler) bridge.getHandler();
129 if (bridgeHandler == null) {
130 logger.warn("Bridge-handler is null in thing {}", thing.getUID());
133 final SCPDUtil scpdUtil = bridgeHandler.getSCPDUtil();
134 if (scpdUtil == null) {
135 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
136 "Could not get device definitions");
140 if (checkProperties(scpdUtil)) {
141 // properties set, check channels
142 ThingBuilder thingBuilder = editThing();
143 thingBuilder.withoutChannels(thing.getChannels());
144 Util.checkAvailableChannels(thing, thingBuilder, scpdUtil, config.uuid, deviceType, channels);
145 updateThing(thingBuilder.build());
147 // remove connect scheduler
148 removeConnectScheduler();
149 soapConnector = bridgeHandler.getSOAPConnector();
151 isInitialized = true;
153 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
157 private void removeConnectScheduler() {
158 final ScheduledFuture<?> connectFuture = this.connectFuture;
159 if (connectFuture != null) {
160 connectFuture.cancel(true);
161 this.connectFuture = null;
166 public void dispose() {
167 removeConnectScheduler();
171 isInitialized = false;
177 * poll remote device for channel values
179 private void poll() {
180 SOAPConnector soapConnector = this.soapConnector;
181 channels.forEach((channelUID, channelConfig) -> {
182 if (isLinked(channelUID)) {
183 State state = stateCache.putIfAbsentAndGet(channelUID, () -> soapConnector == null ? UnDefType.UNDEF
184 : soapConnector.getChannelStateFromDevice(channelConfig, channels, stateCache));
186 updateState(channelUID, state);
193 * get device properties from remote device
195 * @param scpdUtil the SCPD util of this device
196 * @return true if successfull
198 private boolean checkProperties(SCPDUtil scpdUtil) {
200 SCPDDeviceType device = scpdUtil.getDevice(config.uuid)
201 .orElseThrow(() -> new SCPDException("Could not find device " + config.uuid));
202 String deviceType = device.getDeviceType();
203 if (deviceType == null) {
204 throw new SCPDException("deviceType can't be null ");
206 this.deviceType = deviceType;
208 Map<String, String> properties = editProperties();
209 properties.put("deviceType", deviceType);
210 updateProperties(properties);
213 } catch (SCPDException e) {
214 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
215 "Failed to update device properties: " + e.getMessage());
222 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
223 if (!bridgeStatusInfo.getStatus().equals(ThingStatus.ONLINE)) {
224 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
225 removeConnectScheduler();
228 updateStatus(ThingStatus.ONLINE);
230 updateStatus(ThingStatus.UNKNOWN);
231 connectFuture = scheduler.scheduleWithFixedDelay(this::internalInitialize, 0, RETRY_INTERVAL,
238 * uninstall update polling
240 private void uninstallPolling() {
241 final ScheduledFuture<?> pollFuture = this.pollFuture;
242 if (pollFuture != null) {
243 pollFuture.cancel(true);
244 this.pollFuture = null;
249 * install update polling
251 private void installPolling() {
253 pollFuture = scheduler.scheduleWithFixedDelay(this::poll, 0, config.refresh, TimeUnit.SECONDS);