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.soap;
15 import static org.openhab.binding.tr064.internal.util.Util.getSOAPElement;
17 import java.lang.reflect.InvocationTargetException;
18 import java.lang.reflect.Method;
19 import java.math.BigDecimal;
20 import java.util.List;
21 import java.util.Optional;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.TimeoutException;
25 import java.util.stream.Collectors;
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.ContentResponse;
33 import org.openhab.binding.tr064.internal.config.Tr064ChannelConfig;
34 import org.openhab.binding.tr064.internal.dto.additions.Call;
35 import org.openhab.binding.tr064.internal.dto.additions.Root;
36 import org.openhab.binding.tr064.internal.util.Util;
37 import org.openhab.core.library.types.DecimalType;
38 import org.openhab.core.library.types.OnOffType;
39 import org.openhab.core.library.types.QuantityType;
40 import org.openhab.core.library.types.StringType;
41 import org.openhab.core.types.Command;
42 import org.openhab.core.types.State;
43 import org.openhab.core.types.UnDefType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 import com.google.gson.Gson;
48 import com.google.gson.GsonBuilder;
51 * The {@link SOAPValueConverter} converts SOAP values and openHAB states
53 * @author Jan N. Klug - Initial contribution
56 public class SOAPValueConverter {
57 private static final int REQUEST_TIMEOUT = 5000; // in ms
58 private final Logger logger = LoggerFactory.getLogger(SOAPValueConverter.class);
59 private final HttpClient httpClient;
61 public SOAPValueConverter(HttpClient httpClient) {
62 this.httpClient = httpClient;
66 * convert an openHAB command to a SOAP value
68 * @param command the command to be converted
69 * @param dataType the datatype to send
70 * @param unit if available, the unit of the converted value
71 * @return a string optional containing the converted value
73 public Optional<String> getSOAPValueFromCommand(Command command, String dataType, String unit) {
74 if (dataType.isEmpty()) {
75 // we don't have data to send
76 return Optional.of("");
78 if (command instanceof QuantityType) {
79 QuantityType<?> value = (unit.isEmpty()) ? ((QuantityType<?>) command)
80 : ((QuantityType<?>) command).toUnit(unit);
82 logger.warn("Could not convert {} to unit {}", command, unit);
83 return Optional.empty();
87 return Optional.of(String.valueOf(value.shortValue()));
90 return Optional.of(String.valueOf(value.intValue()));
93 } else if (command instanceof DecimalType) {
94 BigDecimal value = ((DecimalType) command).toBigDecimal();
97 return Optional.of(String.valueOf(value.shortValue()));
100 return Optional.of(String.valueOf(value.intValue()));
103 } else if (command instanceof StringType) {
104 if (dataType.equals("string")) {
105 return Optional.of(command.toString());
107 } else if (command instanceof OnOffType) {
108 if (dataType.equals("boolean")) {
109 return Optional.of(OnOffType.ON.equals(command) ? "1" : "0");
112 return Optional.empty();
116 * convert the value from a SOAP message to an openHAB value
118 * @param soapMessage the inbound SOAP message
119 * @param element the element that needs to be extracted
120 * @param channelConfig the channel config containing additional information (if null a data-type "string" and
121 * missing unit is assumed)
122 * @return an Optional of State containing the converted value
124 public Optional<State> getStateFromSOAPValue(SOAPMessage soapMessage, String element,
125 @Nullable Tr064ChannelConfig channelConfig) {
126 String dataType = channelConfig != null ? channelConfig.getDataType() : "string";
127 String unit = channelConfig != null ? channelConfig.getChannelTypeDescription().getItem().getUnit() : "";
129 return getSOAPElement(soapMessage, element).map(rawValue -> {
130 // map rawValue to State
133 return rawValue.equals("0") ? OnOffType.OFF : OnOffType.ON;
135 return new StringType(rawValue);
139 if (!unit.isEmpty()) {
140 return new QuantityType<>(rawValue + " " + unit);
142 return new DecimalType(rawValue);
148 // check if we need post processing
149 if (channelConfig == null
150 || channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor() == null) {
153 String postProcessor = channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor();
155 Method method = SOAPValueConverter.class.getDeclaredMethod(postProcessor, State.class,
156 Tr064ChannelConfig.class);
157 Object o = method.invoke(this, state, channelConfig);
158 if (o instanceof State) {
161 } catch (NoSuchMethodException | IllegalAccessException e) {
162 logger.warn("Postprocessor {} not found, this most likely is a programming error", postProcessor, e);
163 } catch (InvocationTargetException e) {
164 Throwable cause = e.getCause();
165 logger.info("Postprocessor {} failed: {}", postProcessor,
166 cause != null ? cause.getMessage() : e.getMessage());
169 }).or(Optional::empty);
173 * post processor for answering machine new messages channel
175 * @param state the message list URL
176 * @param channelConfig channel config of the TAM new message channel
177 * @return the number of new messages
178 * @throws PostProcessingException if the message list could not be retrieved
180 @SuppressWarnings("unused")
181 private State processTamListURL(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
183 ContentResponse response = httpClient.newRequest(state.toString()).timeout(1000, TimeUnit.MILLISECONDS)
185 String responseContent = response.getContentAsString();
186 int messageCount = responseContent.split("<New>1</New>").length - 1;
188 return new DecimalType(messageCount);
189 } catch (InterruptedException | TimeoutException | ExecutionException e) {
190 throw new PostProcessingException("Failed to get TAM list from URL " + state.toString(), e);
195 * post processor for missed calls
197 * @param state the call list URL
198 * @param channelConfig channel config of the missed call channel (contains day number)
199 * @return the number of missed calls
200 * @throws PostProcessingException if call list could not be retrieved
202 @SuppressWarnings("unused")
203 private State processMissedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
204 return processCallList(state, channelConfig.getParameter(), CallListType.MISSED_COUNT);
208 * post processor for inbound calls
210 * @param state the call list URL
211 * @param channelConfig channel config of the inbound call channel (contains day number)
212 * @return the number of inbound calls
213 * @throws PostProcessingException if call list could not be retrieved
215 @SuppressWarnings("unused")
216 private State processInboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
217 return processCallList(state, channelConfig.getParameter(), CallListType.INBOUND_COUNT);
221 * post processor for rejected calls
223 * @param state the call list URL
224 * @param channelConfig channel config of the rejected call channel (contains day number)
225 * @return the number of rejected calls
226 * @throws PostProcessingException if call list could not be retrieved
228 @SuppressWarnings("unused")
229 private State processRejectedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
230 return processCallList(state, channelConfig.getParameter(), CallListType.REJECTED_COUNT);
234 * post processor for outbound calls
236 * @param state the call list URL
237 * @param channelConfig channel config of the outbound call channel (contains day number)
238 * @return the number of outbound calls
239 * @throws PostProcessingException if call list could not be retrieved
241 @SuppressWarnings("unused")
242 private State processOutboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
243 return processCallList(state, channelConfig.getParameter(), CallListType.OUTBOUND_COUNT);
247 * post processor for JSON call list
249 * @param state the call list URL
250 * @param channelConfig channel config of the call list channel (contains day number)
251 * @return caller list in JSON format
252 * @throws PostProcessingException if call list could not be retrieved
254 @SuppressWarnings("unused")
255 private State processCallListJSON(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
256 return processCallList(state, channelConfig.getParameter(), CallListType.JSON_LIST);
260 * internal helper for call list post processors
262 * @param state the call list URL
263 * @param days number of days to get
264 * @param type type of call (2=missed 1=inbound 4=rejected 3=outbund)
265 * @return the quantity of calls of the given type within the given number of days
266 * @throws PostProcessingException if the call list could not be retrieved
268 private State processCallList(State state, @Nullable String days, CallListType type)
269 throws PostProcessingException {
270 Root callListRoot = Util.getAndUnmarshalXML(httpClient, state.toString() + "&days=" + days, Root.class);
271 if (callListRoot == null) {
272 throw new PostProcessingException("Failed to get call list from URL " + state.toString());
274 List<Call> calls = callListRoot.getCall();
280 long callCount = calls.stream().filter(call -> type.typeString().equals(call.getType())).count();
281 return new DecimalType(callCount);
283 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").serializeNulls().create();
284 List<CallListEntry> callListEntries = calls.stream().map(CallListEntry::new)
285 .collect(Collectors.toList());
286 return new StringType(gson.toJson(callListEntries));
288 return UnDefType.UNDEF;