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