2 * Copyright (c) 2010-2023 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.soap;
15 import static org.openhab.binding.tr064.internal.util.Util.getSOAPElement;
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;
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;
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;
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;
64 * The {@link SOAPConnector} provides communication with a remote SOAP device
66 * @author Jan N. Klug - Initial contribution
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;
76 private final ExpiringCacheMap<SOAPRequest, SOAPMessage> soapMessageCache = new ExpiringCacheMap<>(
77 Duration.ofMillis(2000));
79 public SOAPConnector(HttpClient httpClient, String endpointBaseURL) {
80 this.httpClient = httpClient;
81 this.endpointBaseURL = endpointBaseURL;
82 this.soapValueConverter = new SOAPValueConverter(httpClient);
86 * prepare a SOAP request for an action request to a service
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
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/");
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 -> {
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(),
114 MimeHeaders headers = soapMessage.getMimeHeaders();
115 headers.addHeader("SOAPAction", soapRequest.service.getServiceType() + "#" + soapRequest.soapAction);
116 soapMessage.saveChanges();
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));
133 * execute a SOAP request with cache
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
139 public SOAPMessage doSOAPRequest(SOAPRequest soapRequest) throws Tr064CommunicationException {
141 SOAPMessage soapMessage = Objects.requireNonNull(soapMessageCache.putIfAbsentAndGet(soapRequest, () -> {
143 SOAPMessage newValue = doSOAPRequestUncached(soapRequest);
144 logger.trace("Storing in cache: {}", newValue);
146 } catch (Tr064CommunicationException e) {
148 throw new IllegalArgumentException(e);
151 logger.trace("Returning from cache: {}", soapMessage);
153 } catch (IllegalArgumentException e) {
154 Throwable cause = e.getCause();
155 if (cause instanceof Tr064CommunicationException) {
156 throw (Tr064CommunicationException) cause;
164 * execute a SOAP request without cache
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
170 public synchronized SOAPMessage doSOAPRequestUncached(SOAPRequest soapRequest) throws Tr064CommunicationException {
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())));
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();
185 try (final ByteArrayInputStream is = new ByteArrayInputStream(response.getContent())) {
186 logger.trace("Received response: {}", response.getContentAsString());
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);
198 } catch (IOException | SOAPException | InterruptedException | TimeoutException | ExecutionException e) {
199 throw new Tr064CommunicationException(e);
204 * send a command to the remote device
206 * @param channelConfig the channel config containing all information
207 * @param command the command to send
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());
217 Map<String, String> arguments = new HashMap<>();
218 if (channelTypeDescription.getSetAction().getArgument() != null) {
219 arguments.put(channelTypeDescription.getSetAction().getArgument(), value);
221 String parameter = channelConfig.getParameter();
222 if (parameter != null) {
224 channelConfig.getChannelTypeDescription().getGetAction().getParameter().getName(),
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());
233 }, () -> logger.warn("Could not convert {} to SOAP value", command));
237 * get a value from the remote device - updates state cache for all possible channels
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
244 public State getChannelStateFromDevice(final Tr064ChannelConfig channelConfig,
245 Map<ChannelUID, Tr064ChannelConfig> channelConfigMap, ExpiringCacheMap<ChannelUID, State> stateCache) {
247 final SCPDActionType getAction = channelConfig.getGetAction();
248 if (getAction == null) {
249 // channel has no get action, return a default
250 switch (channelConfig.getDataType()) {
252 return OnOffType.OFF;
254 return StringType.EMPTY;
256 return UnDefType.UNDEF;
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);
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())
275 .equals(map.getValue().getChannelTypeDescription().getGetAction().getArgument()))
276 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
280 channelConfig1) -> soapValueConverter
281 .getStateFromSOAPValue(soapResponse,
282 channelConfig1.getChannelTypeDescription().getGetAction()
285 .ifPresent(state -> stateCache.putValue(channelUID, state)));
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()) {
294 // NoSuchEntryInArray usually is an unknown entry in the MAC list
295 logger.debug("Failed to get {}: {}", channelConfig, e.getMessage());
296 return UnDefType.UNDEF;
300 // all other cases are an error
301 logger.warn("Failed to get {}: {}", channelConfig, e.getMessage());
302 return UnDefType.UNDEF;