]> git.basschouten.com Git - openhab-addons.git/blob
f653d23836608e658cc462c74abb983973ebdf3d
[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.soap;
14
15 import static org.openhab.binding.tr064.internal.util.Util.getSOAPElement;
16
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;
26
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.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;
46
47 import com.google.gson.Gson;
48 import com.google.gson.GsonBuilder;
49
50 /**
51  * The {@link SOAPValueConverter} converts SOAP values and openHAB states
52  *
53  * @author Jan N. Klug - Initial contribution
54  */
55 @NonNullByDefault
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;
60
61     public SOAPValueConverter(HttpClient httpClient) {
62         this.httpClient = httpClient;
63     }
64
65     /**
66      * convert an openHAB command to a SOAP value
67      *
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
72      */
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("");
77         }
78         if (command instanceof QuantityType) {
79             QuantityType<?> value = (unit.isEmpty()) ? ((QuantityType<?>) command)
80                     : ((QuantityType<?>) command).toUnit(unit);
81             if (value == null) {
82                 logger.warn("Could not convert {} to unit {}", command, unit);
83                 return Optional.empty();
84             }
85             switch (dataType) {
86                 case "ui2":
87                     return Optional.of(String.valueOf(value.shortValue()));
88                 case "ui4":
89                     return Optional.of(String.valueOf(value.intValue()));
90                 default:
91             }
92         } else if (command instanceof DecimalType) {
93             BigDecimal value = ((DecimalType) command).toBigDecimal();
94             switch (dataType) {
95                 case "ui2":
96                     return Optional.of(String.valueOf(value.shortValue()));
97                 case "ui4":
98                     return Optional.of(String.valueOf(value.intValue()));
99                 default:
100             }
101         } else if (command instanceof StringType) {
102             if (dataType.equals("string")) {
103                 return Optional.of(command.toString());
104             }
105         } else if (command instanceof OnOffType) {
106             if (dataType.equals("boolean")) {
107                 return Optional.of(OnOffType.ON.equals(command) ? "1" : "0");
108             }
109         }
110         return Optional.empty();
111     }
112
113     /**
114      * convert the value from a SOAP message to an openHAB value
115      *
116      * @param soapMessage the inbound SOAP message
117      * @param element the element that needs to be extracted
118      * @param channelConfig the channel config containing additional information (if null a data-type "string" and
119      *            missing unit is assumed)
120      * @return an Optional of State containing the converted value
121      */
122     public Optional<State> getStateFromSOAPValue(SOAPMessage soapMessage, String element,
123             @Nullable Tr064ChannelConfig channelConfig) {
124         String dataType = channelConfig != null ? channelConfig.getDataType() : "string";
125         String unit = channelConfig != null ? channelConfig.getChannelTypeDescription().getItem().getUnit() : "";
126
127         return getSOAPElement(soapMessage, element).map(rawValue -> {
128             // map rawValue to State
129             switch (dataType) {
130                 case "boolean":
131                     return rawValue.equals("0") ? OnOffType.OFF : OnOffType.ON;
132                 case "string":
133                     return new StringType(rawValue);
134                 case "ui2":
135                 case "ui4":
136                     if (!unit.isEmpty()) {
137                         return new QuantityType<>(rawValue + " " + unit);
138                     } else {
139                         return new DecimalType(rawValue);
140                     }
141                 default:
142                     return null;
143             }
144         }).map(state -> {
145             // check if we need post processing
146             if (channelConfig == null
147                     || channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor() == null) {
148                 return state;
149             }
150             String postProcessor = channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor();
151             try {
152                 Method method = SOAPValueConverter.class.getDeclaredMethod(postProcessor, State.class,
153                         Tr064ChannelConfig.class);
154                 Object o = method.invoke(this, state, channelConfig);
155                 if (o instanceof State) {
156                     return (State) o;
157                 }
158             } catch (NoSuchMethodException | IllegalAccessException e) {
159                 logger.warn("Postprocessor {} not found, this most likely is a programming error", postProcessor, e);
160             } catch (InvocationTargetException e) {
161                 Throwable cause = e.getCause();
162                 logger.info("Postprocessor {} failed: {}", postProcessor,
163                         cause != null ? cause.getMessage() : e.getMessage());
164             }
165             return null;
166         }).or(Optional::empty);
167     }
168
169     /**
170      * post processor for answering machine new messages channel
171      *
172      * @param state the message list URL
173      * @param channelConfig channel config of the TAM new message channel
174      * @return the number of new messages
175      * @throws PostProcessingException if the message list could not be retrieved
176      */
177     @SuppressWarnings("unused")
178     private State processTamListURL(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
179         try {
180             ContentResponse response = httpClient.newRequest(state.toString()).timeout(1000, TimeUnit.MILLISECONDS)
181                     .send();
182             String responseContent = response.getContentAsString();
183             int messageCount = responseContent.split("<New>1</New>").length - 1;
184
185             return new DecimalType(messageCount);
186         } catch (InterruptedException | TimeoutException | ExecutionException e) {
187             throw new PostProcessingException("Failed to get TAM list from URL " + state.toString(), e);
188         }
189     }
190
191     /**
192      * post processor for missed calls
193      *
194      * @param state the call list URL
195      * @param channelConfig channel config of the missed call channel (contains day number)
196      * @return the number of missed calls
197      * @throws PostProcessingException if call list could not be retrieved
198      */
199     @SuppressWarnings("unused")
200     private State processMissedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
201         return processCallList(state, channelConfig.getParameter(), CallListType.MISSED_COUNT);
202     }
203
204     /**
205      * post processor for inbound calls
206      *
207      * @param state the call list URL
208      * @param channelConfig channel config of the inbound call channel (contains day number)
209      * @return the number of inbound calls
210      * @throws PostProcessingException if call list could not be retrieved
211      */
212     @SuppressWarnings("unused")
213     private State processInboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
214         return processCallList(state, channelConfig.getParameter(), CallListType.INBOUND_COUNT);
215     }
216
217     /**
218      * post processor for rejected calls
219      *
220      * @param state the call list URL
221      * @param channelConfig channel config of the rejected call channel (contains day number)
222      * @return the number of rejected calls
223      * @throws PostProcessingException if call list could not be retrieved
224      */
225     @SuppressWarnings("unused")
226     private State processRejectedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
227         return processCallList(state, channelConfig.getParameter(), CallListType.REJECTED_COUNT);
228     }
229
230     /**
231      * post processor for outbound calls
232      *
233      * @param state the call list URL
234      * @param channelConfig channel config of the outbound call channel (contains day number)
235      * @return the number of outbound calls
236      * @throws PostProcessingException if call list could not be retrieved
237      */
238     @SuppressWarnings("unused")
239     private State processOutboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
240         return processCallList(state, channelConfig.getParameter(), CallListType.OUTBOUND_COUNT);
241     }
242
243     /**
244      * post processor for JSON call list
245      *
246      * @param state the call list URL
247      * @param channelConfig channel config of the call list channel (contains day number)
248      * @return caller list in JSON format
249      * @throws PostProcessingException if call list could not be retrieved
250      */
251     @SuppressWarnings("unused")
252     private State processCallListJSON(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
253         return processCallList(state, channelConfig.getParameter(), CallListType.JSON_LIST);
254     }
255
256     /**
257      * internal helper for call list post processors
258      *
259      * @param state the call list URL
260      * @param days number of days to get
261      * @param type type of call (2=missed 1=inbound 4=rejected 3=outbund)
262      * @return the quantity of calls of the given type within the given number of days
263      * @throws PostProcessingException if the call list could not be retrieved
264      */
265     private State processCallList(State state, @Nullable String days, CallListType type)
266             throws PostProcessingException {
267         Root callListRoot = Util.getAndUnmarshalXML(httpClient, state.toString() + "&days=" + days, Root.class);
268         if (callListRoot == null) {
269             throw new PostProcessingException("Failed to get call list from URL " + state.toString());
270         }
271         List<Call> calls = callListRoot.getCall();
272         switch (type) {
273             case INBOUND_COUNT:
274             case MISSED_COUNT:
275             case OUTBOUND_COUNT:
276             case REJECTED_COUNT:
277                 long callCount = calls.stream().filter(call -> type.typeString().equals(call.getType())).count();
278                 return new DecimalType(callCount);
279             case JSON_LIST:
280                 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").serializeNulls().create();
281                 List<CallListEntry> callListEntries = calls.stream().map(CallListEntry::new)
282                         .collect(Collectors.toList());
283                 return new StringType(gson.toJson(callListEntries));
284         }
285         return UnDefType.UNDEF;
286     }
287 }