]> git.basschouten.com Git - openhab-addons.git/blob
515f33e46aca253c7258ab32ee167455d6d69b2a
[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.tr064.internal.soap;
14
15 import static org.openhab.binding.tr064.internal.util.Util.getSOAPElement;
16
17 import java.io.ByteArrayInputStream;
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.time.Duration;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.TimeoutException;
28 import java.util.stream.Collectors;
29
30 import javax.xml.soap.MessageFactory;
31 import javax.xml.soap.MimeHeader;
32 import javax.xml.soap.MimeHeaders;
33 import javax.xml.soap.SOAPBody;
34 import javax.xml.soap.SOAPElement;
35 import javax.xml.soap.SOAPEnvelope;
36 import javax.xml.soap.SOAPException;
37 import javax.xml.soap.SOAPMessage;
38 import javax.xml.soap.SOAPPart;
39
40 import org.eclipse.jdt.annotation.NonNullByDefault;
41 import org.eclipse.jetty.client.HttpClient;
42 import org.eclipse.jetty.client.api.ContentResponse;
43 import org.eclipse.jetty.client.api.Request;
44 import org.eclipse.jetty.client.util.BytesContentProvider;
45 import org.eclipse.jetty.http.HttpMethod;
46 import org.eclipse.jetty.http.HttpStatus;
47 import org.openhab.binding.tr064.internal.Tr064CommunicationException;
48 import org.openhab.binding.tr064.internal.config.Tr064ChannelConfig;
49 import org.openhab.binding.tr064.internal.dto.config.ActionType;
50 import org.openhab.binding.tr064.internal.dto.config.ChannelTypeDescription;
51 import org.openhab.binding.tr064.internal.dto.scpd.root.SCPDServiceType;
52 import org.openhab.binding.tr064.internal.dto.scpd.service.SCPDActionType;
53 import org.openhab.core.cache.ExpiringCacheMap;
54 import org.openhab.core.library.types.OnOffType;
55 import org.openhab.core.library.types.StringType;
56 import org.openhab.core.thing.ChannelUID;
57 import org.openhab.core.types.Command;
58 import org.openhab.core.types.State;
59 import org.openhab.core.types.UnDefType;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 /**
64  * The {@link SOAPConnector} provides communication with a remote SOAP device
65  *
66  * @author Jan N. Klug - Initial contribution
67  */
68 @NonNullByDefault
69 public class SOAPConnector {
70     private static final int SOAP_TIMEOUT = 5; // in
71     private final Logger logger = LoggerFactory.getLogger(SOAPConnector.class);
72     private final HttpClient httpClient;
73     private final String endpointBaseURL;
74     private final SOAPValueConverter soapValueConverter;
75
76     private final ExpiringCacheMap<SOAPRequest, SOAPMessage> soapMessageCache = new ExpiringCacheMap<>(
77             Duration.ofMillis(2000));
78
79     public SOAPConnector(HttpClient httpClient, String endpointBaseURL) {
80         this.httpClient = httpClient;
81         this.endpointBaseURL = endpointBaseURL;
82         this.soapValueConverter = new SOAPValueConverter(httpClient);
83     }
84
85     /**
86      * prepare a SOAP request for an action request to a service
87      *
88      * @param soapRequest the request to be generated
89      * @return a jetty Request containing the full SOAP message
90      * @throws IOException if a problem while writing the SOAP message to the Request occurs
91      * @throws SOAPException if a problem with creating the SOAP message occurs
92      */
93     private Request prepareSOAPRequest(SOAPRequest soapRequest) throws IOException, SOAPException {
94         MessageFactory messageFactory = MessageFactory.newInstance();
95         SOAPMessage soapMessage = messageFactory.createMessage();
96         SOAPPart soapPart = soapMessage.getSOAPPart();
97         SOAPEnvelope envelope = soapPart.getEnvelope();
98         envelope.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
99
100         // SOAP body
101         SOAPBody soapBody = envelope.getBody();
102         SOAPElement soapBodyElem = soapBody.addChildElement(soapRequest.soapAction, "u",
103                 soapRequest.service.getServiceType());
104         soapRequest.arguments.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(argument -> {
105             try {
106                 soapBodyElem.addChildElement(argument.getKey()).setTextContent(argument.getValue());
107             } catch (SOAPException e) {
108                 logger.warn("Could not add {}:{} to SOAP Request: {}", argument.getKey(), argument.getValue(),
109                         e.getMessage());
110             }
111         });
112
113         // SOAP headers
114         MimeHeaders headers = soapMessage.getMimeHeaders();
115         headers.addHeader("SOAPAction", soapRequest.service.getServiceType() + "#" + soapRequest.soapAction);
116         soapMessage.saveChanges();
117
118         // create Request and add headers and content
119         Request request = httpClient.newRequest(endpointBaseURL + soapRequest.service.getControlURL())
120                 .method(HttpMethod.POST);
121         ((Iterator<MimeHeader>) soapMessage.getMimeHeaders().getAllHeaders())
122                 .forEachRemaining(header -> request.header(header.getName(), header.getValue()));
123         try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
124             soapMessage.writeTo(os);
125             byte[] content = os.toByteArray();
126             request.content(new BytesContentProvider(content));
127         }
128
129         return request;
130     }
131
132     /**
133      * execute a SOAP request with cache
134      *
135      * @param soapRequest the request itself
136      * @return the SOAPMessage answer from the remote host
137      * @throws Tr064CommunicationException if an error occurs during the request
138      */
139     public SOAPMessage doSOAPRequest(SOAPRequest soapRequest) throws Tr064CommunicationException {
140         try {
141             SOAPMessage soapMessage = Objects.requireNonNull(soapMessageCache.putIfAbsentAndGet(soapRequest, () -> {
142                 try {
143                     SOAPMessage newValue = doSOAPRequestUncached(soapRequest);
144                     logger.trace("Storing in cache: {}", newValue);
145                     return newValue;
146                 } catch (Tr064CommunicationException e) {
147                     // wrap exception
148                     throw new IllegalArgumentException(e);
149                 }
150             }));
151             logger.trace("Returning from cache: {}", soapMessage);
152             return soapMessage;
153         } catch (IllegalArgumentException e) {
154             Throwable cause = e.getCause();
155             if (cause instanceof Tr064CommunicationException) {
156                 throw (Tr064CommunicationException) cause;
157             } else {
158                 throw e;
159             }
160         }
161     }
162
163     /**
164      * execute a SOAP request without cache
165      *
166      * @param soapRequest the request itself
167      * @return the SOAPMessage answer from the remote host
168      * @throws Tr064CommunicationException if an error occurs during the request
169      */
170     public synchronized SOAPMessage doSOAPRequestUncached(SOAPRequest soapRequest) throws Tr064CommunicationException {
171         try {
172             Request request = prepareSOAPRequest(soapRequest).timeout(SOAP_TIMEOUT, TimeUnit.SECONDS);
173             if (logger.isTraceEnabled()) {
174                 request.getContent().forEach(buffer -> logger.trace("Request: {}", new String(buffer.array())));
175             }
176
177             ContentResponse response = request.send();
178             if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) {
179                 // retry once if authentication expired
180                 logger.trace("Re-Auth needed.");
181                 httpClient.getAuthenticationStore().clearAuthenticationResults();
182                 request = prepareSOAPRequest(soapRequest).timeout(SOAP_TIMEOUT, TimeUnit.SECONDS);
183                 response = request.send();
184             }
185             try (final ByteArrayInputStream is = new ByteArrayInputStream(response.getContent())) {
186                 logger.trace("Received response: {}", response.getContentAsString());
187
188                 SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(null, is);
189                 if (soapMessage.getSOAPBody().hasFault()) {
190                     String soapError = getSOAPElement(soapMessage, "errorCode").orElse("unknown");
191                     String soapReason = getSOAPElement(soapMessage, "errorDescription").orElse("unknown");
192                     String error = String.format("HTTP-Response-Code %d (%s), SOAP-Fault: %s (%s)",
193                             response.getStatus(), response.getReason(), soapError, soapReason);
194                     throw new Tr064CommunicationException(error, response.getStatus(), soapError);
195                 }
196                 return soapMessage;
197             }
198         } catch (IOException | SOAPException | InterruptedException | TimeoutException | ExecutionException e) {
199             throw new Tr064CommunicationException(e);
200         }
201     }
202
203     /**
204      * send a command to the remote device
205      *
206      * @param channelConfig the channel config containing all information
207      * @param command the command to send
208      */
209     public void sendChannelCommandToDevice(Tr064ChannelConfig channelConfig, Command command) {
210         soapValueConverter.getSOAPValueFromCommand(command, channelConfig.getDataType(),
211                 channelConfig.getChannelTypeDescription().getItem().getUnit()).ifPresentOrElse(value -> {
212                     final ChannelTypeDescription channelTypeDescription = channelConfig.getChannelTypeDescription();
213                     final SCPDServiceType service = channelConfig.getService();
214                     logger.debug("Sending {} as {} to {}/{}", command, value, service.getServiceId(),
215                             channelTypeDescription.getSetAction().getName());
216                     try {
217                         Map<String, String> arguments = new HashMap<>();
218                         if (channelTypeDescription.getSetAction().getArgument() != null) {
219                             arguments.put(channelTypeDescription.getSetAction().getArgument(), value);
220                         }
221                         String parameter = channelConfig.getParameter();
222                         if (parameter != null) {
223                             arguments.put(
224                                     channelConfig.getChannelTypeDescription().getGetAction().getParameter().getName(),
225                                     parameter);
226                         }
227                         SOAPRequest soapRequest = new SOAPRequest(service,
228                                 channelTypeDescription.getSetAction().getName(), arguments);
229                         doSOAPRequestUncached(soapRequest);
230                     } catch (Tr064CommunicationException e) {
231                         logger.warn("Could not send command {}: {}", command, e.getMessage());
232                     }
233                 }, () -> logger.warn("Could not convert {} to SOAP value", command));
234     }
235
236     /**
237      * get a value from the remote device - updates state cache for all possible channels
238      *
239      * @param channelConfig the channel config containing all information
240      * @param channelConfigMap map of all channels in the device
241      * @param stateCache the ExpiringCacheMap for states of the device
242      * @return the value for the requested channel
243      */
244     public State getChannelStateFromDevice(final Tr064ChannelConfig channelConfig,
245             Map<ChannelUID, Tr064ChannelConfig> channelConfigMap, ExpiringCacheMap<ChannelUID, State> stateCache) {
246         try {
247             final SCPDActionType getAction = channelConfig.getGetAction();
248             if (getAction == null) {
249                 // channel has no get action, return a default
250                 switch (channelConfig.getDataType()) {
251                     case "boolean":
252                         return OnOffType.OFF;
253                     case "string":
254                         return StringType.EMPTY;
255                     default:
256                         return UnDefType.UNDEF;
257                 }
258             }
259
260             // get value(s) from remote device
261             Map<String, String> arguments = new HashMap<>();
262             String parameter = channelConfig.getParameter();
263             ActionType action = channelConfig.getChannelTypeDescription().getGetAction();
264             if (parameter != null && !action.getParameter().isInternalOnly()) {
265                 arguments.put(action.getParameter().getName(), parameter);
266             }
267             SOAPMessage soapResponse = doSOAPRequest(
268                     new SOAPRequest(channelConfig.getService(), getAction.getName(), arguments));
269             String argumentName = channelConfig.getChannelTypeDescription().getGetAction().getArgument();
270             // find all other channels with the same action that are already in cache, so we can update them
271             Map<ChannelUID, Tr064ChannelConfig> channelsInRequest = channelConfigMap.entrySet().stream()
272                     .filter(map -> getAction.equals(map.getValue().getGetAction())
273                             && stateCache.containsKey(map.getKey())
274                             && !argumentName
275                                     .equals(map.getValue().getChannelTypeDescription().getGetAction().getArgument()))
276                     .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
277             channelsInRequest
278                     .forEach(
279                             (channelUID,
280                                     channelConfig1) -> soapValueConverter
281                                             .getStateFromSOAPValue(soapResponse,
282                                                     channelConfig1.getChannelTypeDescription().getGetAction()
283                                                             .getArgument(),
284                                                     channelConfig1)
285                                             .ifPresent(state -> stateCache.putValue(channelUID, state)));
286
287             return soapValueConverter.getStateFromSOAPValue(soapResponse, argumentName, channelConfig)
288                     .orElseThrow(() -> new Tr064CommunicationException("failed to transform '"
289                             + channelConfig.getChannelTypeDescription().getGetAction().getArgument() + "'"));
290         } catch (Tr064CommunicationException e) {
291             if (e.getHttpError() == 500) {
292                 switch (e.getSoapError()) {
293                     case "714":
294                         // NoSuchEntryInArray usually is an unknown entry in the MAC list
295                         logger.debug("Failed to get {}: {}", channelConfig, e.getMessage());
296                         return UnDefType.UNDEF;
297                     default:
298                 }
299             }
300             // all other cases are an error
301             logger.warn("Failed to get {}: {}", channelConfig, e.getMessage());
302             return UnDefType.UNDEF;
303         }
304     }
305 }