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_FRITZBOX;
16 import static org.openhab.binding.tr064.internal.Tr064BindingConstants.THING_TYPE_GENERIC;
19 import java.net.URISyntaxException;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.stream.Collectors;
24 import java.util.stream.Stream;
26 import javax.xml.soap.SOAPException;
27 import javax.xml.soap.SOAPMessage;
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.eclipse.jetty.client.HttpClient;
32 import org.eclipse.jetty.client.api.Authentication;
33 import org.eclipse.jetty.client.api.AuthenticationStore;
34 import org.eclipse.jetty.client.util.DigestAuthentication;
35 import org.openhab.binding.tr064.internal.config.Tr064ChannelConfig;
36 import org.openhab.binding.tr064.internal.config.Tr064RootConfiguration;
37 import org.openhab.binding.tr064.internal.dto.scpd.root.SCPDDeviceType;
38 import org.openhab.binding.tr064.internal.dto.scpd.root.SCPDServiceType;
39 import org.openhab.binding.tr064.internal.dto.scpd.service.SCPDActionType;
40 import org.openhab.binding.tr064.internal.phonebook.Phonebook;
41 import org.openhab.binding.tr064.internal.phonebook.PhonebookProvider;
42 import org.openhab.binding.tr064.internal.phonebook.Tr064PhonebookImpl;
43 import org.openhab.binding.tr064.internal.soap.SOAPConnector;
44 import org.openhab.binding.tr064.internal.soap.SOAPValueConverter;
45 import org.openhab.binding.tr064.internal.util.SCPDUtil;
46 import org.openhab.binding.tr064.internal.util.Util;
47 import org.openhab.core.cache.ExpiringCacheMap;
48 import org.openhab.core.thing.*;
49 import org.openhab.core.thing.binding.BaseBridgeHandler;
50 import org.openhab.core.thing.binding.ThingHandlerService;
51 import org.openhab.core.thing.binding.builder.ThingBuilder;
52 import org.openhab.core.types.Command;
53 import org.openhab.core.types.RefreshType;
54 import org.openhab.core.types.State;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * The {@link Tr064RootHandler} is responsible for handling commands, which are
60 * sent to one of the channels and update channel values
62 * @author Jan N. Klug - Initial contribution
65 public class Tr064RootHandler extends BaseBridgeHandler implements PhonebookProvider {
66 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_GENERIC, THING_TYPE_FRITZBOX);
67 private static final int RETRY_INTERVAL = 60;
68 private static final Set<String> PROPERTY_ARGUMENTS = Set.of("NewSerialNumber", "NewSoftwareVersion",
71 private final Logger logger = LoggerFactory.getLogger(Tr064RootHandler.class);
72 private final HttpClient httpClient;
74 private Tr064RootConfiguration config = new Tr064RootConfiguration();
75 private String deviceType = "";
77 private @Nullable SCPDUtil scpdUtil;
78 private SOAPConnector soapConnector;
79 private String endpointBaseURL = "";
81 private final Map<ChannelUID, Tr064ChannelConfig> channels = new HashMap<>();
82 // caching is used to prevent excessive calls to the same action
83 private final ExpiringCacheMap<ChannelUID, State> stateCache = new ExpiringCacheMap<>(2000);
84 private Collection<Phonebook> phonebooks = Collections.emptyList();
86 private @Nullable ScheduledFuture<?> connectFuture;
87 private @Nullable ScheduledFuture<?> pollFuture;
88 private @Nullable ScheduledFuture<?> phonebookFuture;
90 private boolean communicationEstablished = false;
92 Tr064RootHandler(Bridge bridge, HttpClient httpClient) {
94 this.httpClient = httpClient;
95 this.soapConnector = new SOAPConnector(httpClient, endpointBaseURL);
99 public void handleCommand(ChannelUID channelUID, Command command) {
100 if (!communicationEstablished) {
101 logger.debug("Tried to process command, but thing is not yet ready: {} to {}", channelUID, command);
103 Tr064ChannelConfig channelConfig = channels.get(channelUID);
104 if (channelConfig == null) {
105 logger.trace("Channel {} not supported.", channelUID);
109 if (command instanceof RefreshType) {
110 SOAPConnector soapConnector = this.soapConnector;
111 State state = stateCache.putIfAbsentAndGet(channelUID,
112 () -> soapConnector.getChannelStateFromDevice(channelConfig, channels, stateCache));
114 updateState(channelUID, state);
119 if (channelConfig.getChannelTypeDescription().getSetAction() == null) {
120 logger.debug("Discarding command {} to {}, read-only channel", command, channelUID);
123 scheduler.execute(() -> soapConnector.sendChannelCommandToDevice(channelConfig, command));
127 public void initialize() {
128 config = getConfigAs(Tr064RootConfiguration.class);
129 if (!config.isValid()) {
130 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
131 "At least one mandatory configuration field is empty");
135 endpointBaseURL = "http://" + config.host + ":49000";
136 updateStatus(ThingStatus.UNKNOWN);
138 connectFuture = scheduler.scheduleWithFixedDelay(this::internalInitialize, 0, RETRY_INTERVAL, TimeUnit.SECONDS);
142 * internal thing initializer (sets SCPDUtil and connects to remote device)
144 private void internalInitialize() {
146 scpdUtil = new SCPDUtil(httpClient, endpointBaseURL);
147 } catch (SCPDException e) {
148 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
149 "could not get device definitions from " + config.host);
153 if (establishSecureConnectionAndUpdateProperties()) {
154 removeConnectScheduler();
156 // connection successful, check channels
157 ThingBuilder thingBuilder = editThing();
158 thingBuilder.withoutChannels(thing.getChannels());
159 final SCPDUtil scpdUtil = this.scpdUtil;
160 if (scpdUtil != null) {
161 Util.checkAvailableChannels(thing, thingBuilder, scpdUtil, "", deviceType, channels);
162 updateThing(thingBuilder.build());
165 communicationEstablished = true;
167 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
171 private void removeConnectScheduler() {
172 final ScheduledFuture<?> connectFuture = this.connectFuture;
173 if (connectFuture != null) {
174 connectFuture.cancel(true);
175 this.connectFuture = null;
180 public void dispose() {
181 communicationEstablished = false;
182 removeConnectScheduler();
190 * poll remote device for channel values
192 private void poll() {
193 channels.forEach((channelUID, channelConfig) -> {
194 if (isLinked(channelUID)) {
195 State state = stateCache.putIfAbsentAndGet(channelUID,
196 () -> soapConnector.getChannelStateFromDevice(channelConfig, channels, stateCache));
198 updateState(channelUID, state);
205 * establish the connection - get secure port (if avallable), install authentication, get device properties
207 * @return true if successful
209 private boolean establishSecureConnectionAndUpdateProperties() {
210 final SCPDUtil scpdUtil = this.scpdUtil;
211 if (scpdUtil != null) {
213 SCPDDeviceType device = scpdUtil.getDevice("")
214 .orElseThrow(() -> new SCPDException("Root device not found"));
215 SCPDServiceType deviceService = device.getServiceList().stream()
216 .filter(service -> service.getServiceId().equals("urn:DeviceInfo-com:serviceId:DeviceInfo1"))
217 .findFirst().orElseThrow(() -> new SCPDException(
218 "service 'urn:DeviceInfo-com:serviceId:DeviceInfo1' not found"));
220 this.deviceType = device.getDeviceType();
222 // try to get security (https) port
223 SOAPMessage soapResponse = soapConnector.doSOAPRequest(deviceService, "GetSecurityPort",
224 Collections.emptyMap());
225 if (!soapResponse.getSOAPBody().hasFault()) {
226 SOAPValueConverter soapValueConverter = new SOAPValueConverter(httpClient);
227 soapValueConverter.getStateFromSOAPValue(soapResponse, "NewSecurityPort", null)
228 .ifPresentOrElse(port -> {
229 endpointBaseURL = "https://" + config.host + ":" + port.toString();
230 soapConnector = new SOAPConnector(httpClient, endpointBaseURL);
231 logger.debug("endpointBaseURL is now '{}'", endpointBaseURL);
232 }, () -> logger.warn("Could not determine secure port, disabling https"));
234 logger.warn("Could not determine secure port, disabling https");
237 // clear auth cache and force re-auth
238 httpClient.getAuthenticationStore().clearAuthenticationResults();
239 AuthenticationStore auth = httpClient.getAuthenticationStore();
240 auth.addAuthentication(new DigestAuthentication(new URI(endpointBaseURL), Authentication.ANY_REALM,
241 config.user, config.password));
243 // check & update properties
244 SCPDActionType getInfoAction = scpdUtil.getService(deviceService.getServiceId())
245 .orElseThrow(() -> new SCPDException(
246 "Could not get service definition for 'urn:DeviceInfo-com:serviceId:DeviceInfo1'"))
247 .getActionList().stream().filter(action -> action.getName().equals("GetInfo")).findFirst()
248 .orElseThrow(() -> new SCPDException("Action 'GetInfo' not found"));
249 SOAPMessage soapResponse1 = soapConnector.doSOAPRequest(deviceService, getInfoAction.getName(),
250 Collections.emptyMap());
251 SOAPValueConverter soapValueConverter = new SOAPValueConverter(httpClient);
252 Map<String, String> properties = editProperties();
253 PROPERTY_ARGUMENTS.forEach(argumentName -> getInfoAction.getArgumentList().stream()
254 .filter(argument -> argument.getName().equals(argumentName)).findFirst()
255 .ifPresent(argument -> soapValueConverter
256 .getStateFromSOAPValue(soapResponse1, argumentName, null).ifPresent(value -> properties
257 .put(argument.getRelatedStateVariable(), value.toString()))));
258 properties.put("deviceType", device.getDeviceType());
259 updateProperties(properties);
262 } catch (SCPDException | SOAPException | Tr064CommunicationException | URISyntaxException e) {
263 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
271 * get all sub devices of this root device (used for discovery)
275 public List<SCPDDeviceType> getAllSubDevices() {
276 final SCPDUtil scpdUtil = this.scpdUtil;
277 return (scpdUtil == null) ? Collections.emptyList() : scpdUtil.getAllSubDevices();
281 * get the SOAP connector (used by sub devices for communication with the remote device)
283 * @return the SOAP connector
285 public SOAPConnector getSOAPConnector() {
286 return soapConnector;
290 * get the SCPD processing utility
292 * @return the SCPD utility (or null if not available)
294 public @Nullable SCPDUtil getSCPDUtil() {
299 * uninstall the polling
301 private void uninstallPolling() {
302 final ScheduledFuture<?> pollFuture = this.pollFuture;
303 if (pollFuture != null) {
304 pollFuture.cancel(true);
305 this.pollFuture = null;
307 final ScheduledFuture<?> phonebookFuture = this.phonebookFuture;
308 if (phonebookFuture != null) {
309 phonebookFuture.cancel(true);
310 this.phonebookFuture = null;
315 * install the polling
317 private void installPolling() {
319 pollFuture = scheduler.scheduleWithFixedDelay(this::poll, 0, config.refresh, TimeUnit.SECONDS);
320 if (config.phonebookInterval > 0) {
321 phonebookFuture = scheduler.scheduleWithFixedDelay(this::retrievePhonebooks, 0, config.phonebookInterval,
326 @SuppressWarnings("unchecked")
327 private Collection<Phonebook> processPhonebookList(SOAPMessage soapMessagePhonebookList,
328 SCPDServiceType scpdService) {
329 SOAPValueConverter soapValueConverter = new SOAPValueConverter(httpClient);
330 return (Collection<Phonebook>) soapValueConverter
331 .getStateFromSOAPValue(soapMessagePhonebookList, "NewPhonebookList", null)
332 .map(phonebookList -> Arrays.stream(phonebookList.toString().split(","))).orElse(Stream.empty())
335 SOAPMessage soapMessageURL = soapConnector.doSOAPRequest(scpdService, "GetPhonebook",
336 Map.of("NewPhonebookID", index));
337 return soapValueConverter.getStateFromSOAPValue(soapMessageURL, "NewPhonebookURL", null)
338 .map(url -> (Phonebook) new Tr064PhonebookImpl(httpClient, url.toString()));
339 } catch (Tr064CommunicationException e) {
340 logger.warn("Failed to get phonebook with index {}:", index, e);
342 return Optional.empty();
343 }).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
346 private void retrievePhonebooks() {
347 String serviceId = "urn:X_AVM-DE_OnTel-com:serviceId:X_AVM-DE_OnTel1";
348 SCPDUtil scpdUtil = this.scpdUtil;
349 if (scpdUtil == null) {
350 logger.warn("Cannot find SCPDUtil. This is most likely a programming error.");
353 Optional<SCPDServiceType> scpdService = scpdUtil.getDevice("").flatMap(deviceType -> deviceType.getServiceList()
354 .stream().filter(service -> service.getServiceId().equals(serviceId)).findFirst());
356 phonebooks = scpdService.map(service -> {
358 return processPhonebookList(
359 soapConnector.doSOAPRequest(service, "GetPhonebookList", Collections.emptyMap()), service);
360 } catch (Tr064CommunicationException e) {
361 return Collections.<Phonebook> emptyList();
363 }).orElse(Collections.emptyList());
365 if (phonebooks.isEmpty()) {
366 logger.warn("Could not get phonebooks for thing {}", thing.getUID());
371 public Optional<Phonebook> getPhonebookByName(String name) {
372 return phonebooks.stream().filter(p -> name.equals(p.getName())).findAny();
376 public Collection<Phonebook> getPhonebooks() {
381 public ThingUID getUID() {
382 return thing.getUID();
386 public String getFriendlyName() {
387 String friendlyName = thing.getLabel();
388 return friendlyName != null ? friendlyName : getUID().getId();
392 public Collection<Class<? extends ThingHandlerService>> getServices() {
393 return Set.of(Tr064DiscoveryService.class);