]> git.basschouten.com Git - openhab-addons.git/blob
5889f770d35af2b459329268943565506e64bd20
[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.tr064.internal;
14
15 import static org.openhab.binding.tr064.internal.Tr064BindingConstants.THING_TYPE_FRITZBOX;
16 import static org.openhab.binding.tr064.internal.Tr064BindingConstants.THING_TYPE_GENERIC;
17
18 import java.net.URI;
19 import java.net.URISyntaxException;
20 import java.util.*;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.stream.Collectors;
24 import java.util.stream.Stream;
25
26 import javax.xml.soap.SOAPException;
27 import javax.xml.soap.SOAPMessage;
28
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;
57
58 /**
59  * The {@link Tr064RootHandler} is responsible for handling commands, which are
60  * sent to one of the channels and update channel values
61  *
62  * @author Jan N. Klug - Initial contribution
63  */
64 @NonNullByDefault
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",
69             "NewModelName");
70
71     private final Logger logger = LoggerFactory.getLogger(Tr064RootHandler.class);
72     private final HttpClient httpClient;
73
74     private Tr064RootConfiguration config = new Tr064RootConfiguration();
75     private String deviceType = "";
76
77     private @Nullable SCPDUtil scpdUtil;
78     private SOAPConnector soapConnector;
79     private String endpointBaseURL = "http://fritz.box:49000";
80
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();
85
86     private @Nullable ScheduledFuture<?> connectFuture;
87     private @Nullable ScheduledFuture<?> pollFuture;
88     private @Nullable ScheduledFuture<?> phonebookFuture;
89
90     Tr064RootHandler(Bridge bridge, HttpClient httpClient) {
91         super(bridge);
92         this.httpClient = httpClient;
93         soapConnector = new SOAPConnector(httpClient, endpointBaseURL);
94     }
95
96     @Override
97     public void handleCommand(ChannelUID channelUID, Command command) {
98         Tr064ChannelConfig channelConfig = channels.get(channelUID);
99         if (channelConfig == null) {
100             logger.trace("Channel {} not supported.", channelUID);
101             return;
102         }
103
104         if (command instanceof RefreshType) {
105             SOAPConnector soapConnector = this.soapConnector;
106             State state = stateCache.putIfAbsentAndGet(channelUID,
107                     () -> soapConnector.getChannelStateFromDevice(channelConfig, channels, stateCache));
108             if (state != null) {
109                 updateState(channelUID, state);
110             }
111             return;
112         }
113
114         if (channelConfig.getChannelTypeDescription().getSetAction() == null) {
115             logger.debug("Discarding command {} to {}, read-only channel", command, channelUID);
116             return;
117         }
118         scheduler.execute(() -> soapConnector.sendChannelCommandToDevice(channelConfig, command));
119     }
120
121     @Override
122     public void initialize() {
123         config = getConfigAs(Tr064RootConfiguration.class);
124         if (!config.isValid()) {
125             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
126                     "At least one mandatory configuration field is empty");
127             return;
128         }
129
130         endpointBaseURL = "http://" + config.host + ":49000";
131         updateStatus(ThingStatus.UNKNOWN);
132
133         connectFuture = scheduler.scheduleWithFixedDelay(this::internalInitialize, 0, RETRY_INTERVAL, TimeUnit.SECONDS);
134     }
135
136     /**
137      * internal thing initializer (sets SCPDUtil and connects to remote device)
138      */
139     private void internalInitialize() {
140         try {
141             scpdUtil = new SCPDUtil(httpClient, endpointBaseURL);
142         } catch (SCPDException e) {
143             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
144                     "could not get device definitions from " + config.host);
145             return;
146         }
147
148         if (establishSecureConnectionAndUpdateProperties()) {
149             removeConnectScheduler();
150
151             // connection successful, check channels
152             ThingBuilder thingBuilder = editThing();
153             thingBuilder.withoutChannels(thing.getChannels());
154             final SCPDUtil scpdUtil = this.scpdUtil;
155             if (scpdUtil != null) {
156                 Util.checkAvailableChannels(thing, thingBuilder, scpdUtil, "", deviceType, channels);
157                 updateThing(thingBuilder.build());
158             }
159
160             installPolling();
161             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
162         }
163     }
164
165     private void removeConnectScheduler() {
166         final ScheduledFuture<?> connectFuture = this.connectFuture;
167         if (connectFuture != null) {
168             connectFuture.cancel(true);
169             this.connectFuture = null;
170         }
171     }
172
173     @Override
174     public void dispose() {
175         removeConnectScheduler();
176         uninstallPolling();
177         stateCache.clear();
178
179         super.dispose();
180     }
181
182     /**
183      * poll remote device for channel values
184      */
185     private void poll() {
186         channels.forEach((channelUID, channelConfig) -> {
187             if (isLinked(channelUID)) {
188                 State state = stateCache.putIfAbsentAndGet(channelUID,
189                         () -> soapConnector.getChannelStateFromDevice(channelConfig, channels, stateCache));
190                 if (state != null) {
191                     updateState(channelUID, state);
192                 }
193             }
194         });
195     }
196
197     /**
198      * establish the connection - get secure port (if avallable), install authentication, get device properties
199      *
200      * @return true if successful
201      */
202     private boolean establishSecureConnectionAndUpdateProperties() {
203         final SCPDUtil scpdUtil = this.scpdUtil;
204         if (scpdUtil != null) {
205             try {
206                 SCPDDeviceType device = scpdUtil.getDevice("")
207                         .orElseThrow(() -> new SCPDException("Root device not found"));
208                 SCPDServiceType deviceService = device.getServiceList().stream()
209                         .filter(service -> service.getServiceId().equals("urn:DeviceInfo-com:serviceId:DeviceInfo1"))
210                         .findFirst().orElseThrow(() -> new SCPDException(
211                                 "service 'urn:DeviceInfo-com:serviceId:DeviceInfo1' not found"));
212
213                 this.deviceType = device.getDeviceType();
214
215                 // try to get security (https) port
216                 SOAPMessage soapResponse = soapConnector.doSOAPRequest(deviceService, "GetSecurityPort",
217                         Collections.emptyMap());
218                 if (!soapResponse.getSOAPBody().hasFault()) {
219                     SOAPValueConverter soapValueConverter = new SOAPValueConverter(httpClient);
220                     soapValueConverter.getStateFromSOAPValue(soapResponse, "NewSecurityPort", null)
221                             .ifPresentOrElse(port -> {
222                                 endpointBaseURL = "https://" + config.host + ":" + port.toString();
223                                 soapConnector = new SOAPConnector(httpClient, endpointBaseURL);
224                                 logger.debug("endpointBaseURL is now '{}'", endpointBaseURL);
225                             }, () -> logger.warn("Could not determine secure port, disabling https"));
226                 } else {
227                     logger.warn("Could not determine secure port, disabling https");
228                 }
229
230                 // clear auth cache and force re-auth
231                 httpClient.getAuthenticationStore().clearAuthenticationResults();
232                 AuthenticationStore auth = httpClient.getAuthenticationStore();
233                 auth.addAuthentication(new DigestAuthentication(new URI(endpointBaseURL), Authentication.ANY_REALM,
234                         config.user, config.password));
235
236                 // check & update properties
237                 SCPDActionType getInfoAction = scpdUtil.getService(deviceService.getServiceId())
238                         .orElseThrow(() -> new SCPDException(
239                                 "Could not get service definition for 'urn:DeviceInfo-com:serviceId:DeviceInfo1'"))
240                         .getActionList().stream().filter(action -> action.getName().equals("GetInfo")).findFirst()
241                         .orElseThrow(() -> new SCPDException("Action 'GetInfo' not found"));
242                 SOAPMessage soapResponse1 = soapConnector.doSOAPRequest(deviceService, getInfoAction.getName(),
243                         Collections.emptyMap());
244                 SOAPValueConverter soapValueConverter = new SOAPValueConverter(httpClient);
245                 Map<String, String> properties = editProperties();
246                 PROPERTY_ARGUMENTS.forEach(argumentName -> getInfoAction.getArgumentList().stream()
247                         .filter(argument -> argument.getName().equals(argumentName)).findFirst()
248                         .ifPresent(argument -> soapValueConverter
249                                 .getStateFromSOAPValue(soapResponse1, argumentName, null).ifPresent(value -> properties
250                                         .put(argument.getRelatedStateVariable(), value.toString()))));
251                 properties.put("deviceType", device.getDeviceType());
252                 updateProperties(properties);
253
254                 return true;
255             } catch (SCPDException | SOAPException | Tr064CommunicationException | URISyntaxException e) {
256                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
257                 return false;
258             }
259         }
260         return false;
261     }
262
263     /**
264      * get all sub devices of this root device (used for discovery)
265      *
266      * @return the list
267      */
268     public List<SCPDDeviceType> getAllSubDevices() {
269         final SCPDUtil scpdUtil = this.scpdUtil;
270         return (scpdUtil == null) ? Collections.emptyList() : scpdUtil.getAllSubDevices();
271     }
272
273     /**
274      * get the SOAP connector (used by sub devices for communication with the remote device)
275      *
276      * @return the SOAP connector
277      */
278     public SOAPConnector getSOAPConnector() {
279         return soapConnector;
280     }
281
282     /**
283      * get the SCPD processing utility
284      *
285      * @return the SCPD utility (or null if not available)
286      */
287     public @Nullable SCPDUtil getSCPDUtil() {
288         return scpdUtil;
289     }
290
291     /**
292      * uninstall the polling
293      */
294     private void uninstallPolling() {
295         final ScheduledFuture<?> pollFuture = this.pollFuture;
296         if (pollFuture != null) {
297             pollFuture.cancel(true);
298             this.pollFuture = null;
299         }
300         final ScheduledFuture<?> phonebookFuture = this.phonebookFuture;
301         if (phonebookFuture != null) {
302             phonebookFuture.cancel(true);
303             this.phonebookFuture = null;
304         }
305     }
306
307     /**
308      * install the polling
309      */
310     private void installPolling() {
311         uninstallPolling();
312         pollFuture = scheduler.scheduleWithFixedDelay(this::poll, 0, config.refresh, TimeUnit.SECONDS);
313         if (config.phonebookInterval > 0) {
314             phonebookFuture = scheduler.scheduleWithFixedDelay(this::retrievePhonebooks, 0, config.phonebookInterval,
315                     TimeUnit.SECONDS);
316         }
317     }
318
319     @SuppressWarnings("unchecked")
320     private Collection<Phonebook> processPhonebookList(SOAPMessage soapMessagePhonebookList,
321             SCPDServiceType scpdService) {
322         SOAPValueConverter soapValueConverter = new SOAPValueConverter(httpClient);
323         return (Collection<Phonebook>) soapValueConverter
324                 .getStateFromSOAPValue(soapMessagePhonebookList, "NewPhonebookList", null)
325                 .map(phonebookList -> Arrays.stream(phonebookList.toString().split(","))).orElse(Stream.empty())
326                 .map(index -> {
327                     try {
328                         SOAPMessage soapMessageURL = soapConnector.doSOAPRequest(scpdService, "GetPhonebook",
329                                 Map.of("NewPhonebookID", index));
330                         return soapValueConverter.getStateFromSOAPValue(soapMessageURL, "NewPhonebookURL", null)
331                                 .map(url -> (Phonebook) new Tr064PhonebookImpl(httpClient, url.toString()));
332                     } catch (Tr064CommunicationException e) {
333                         logger.warn("Failed to get phonebook with index {}:", index, e);
334                     }
335                     return Optional.empty();
336                 }).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
337     }
338
339     private void retrievePhonebooks() {
340         String serviceId = "urn:X_AVM-DE_OnTel-com:serviceId:X_AVM-DE_OnTel1";
341         SCPDUtil scpdUtil = this.scpdUtil;
342         if (scpdUtil == null) {
343             logger.warn("Cannot find SCPDUtil. This is most likely a programming error.");
344             return;
345         }
346         Optional<SCPDServiceType> scpdService = scpdUtil.getDevice("").flatMap(deviceType -> deviceType.getServiceList()
347                 .stream().filter(service -> service.getServiceId().equals(serviceId)).findFirst());
348
349         phonebooks = scpdService.map(service -> {
350             try {
351                 return processPhonebookList(
352                         soapConnector.doSOAPRequest(service, "GetPhonebookList", Collections.emptyMap()), service);
353             } catch (Tr064CommunicationException e) {
354                 return Collections.<Phonebook> emptyList();
355             }
356         }).orElse(Collections.emptyList());
357
358         if (phonebooks.isEmpty()) {
359             logger.warn("Could not get phonebooks for thing {}", thing.getUID());
360         }
361     }
362
363     @Override
364     public Optional<Phonebook> getPhonebookByName(String name) {
365         return phonebooks.stream().filter(p -> name.equals(p.getName())).findAny();
366     }
367
368     @Override
369     public Collection<Phonebook> getPhonebooks() {
370         return phonebooks;
371     }
372
373     @Override
374     public ThingUID getUID() {
375         return thing.getUID();
376     }
377
378     @Override
379     public String getFriendlyName() {
380         String friendlyName = thing.getLabel();
381         return friendlyName != null ? friendlyName : getUID().getId();
382     }
383
384     @Override
385     public Collection<Class<? extends ThingHandlerService>> getServices() {
386         return Set.of(Tr064DiscoveryService.class);
387     }
388 }