]> git.basschouten.com Git - openhab-addons.git/blob
48b36bb78d488ed8b0f29ddccc9ee36848f3e2d4
[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.lang.reflect.InvocationTargetException;
18 import java.lang.reflect.Method;
19 import java.math.BigDecimal;
20 import java.util.Arrays;
21 import java.util.List;
22 import java.util.Optional;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
26 import java.util.stream.Collectors;
27
28 import javax.xml.soap.SOAPMessage;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.eclipse.jetty.client.api.ContentResponse;
34 import org.openhab.binding.tr064.internal.config.Tr064ChannelConfig;
35 import org.openhab.binding.tr064.internal.dto.additions.Call;
36 import org.openhab.binding.tr064.internal.dto.additions.Root;
37 import org.openhab.binding.tr064.internal.util.Util;
38 import org.openhab.core.library.types.DecimalType;
39 import org.openhab.core.library.types.OnOffType;
40 import org.openhab.core.library.types.QuantityType;
41 import org.openhab.core.library.types.StringType;
42 import org.openhab.core.library.unit.Units;
43 import org.openhab.core.types.Command;
44 import org.openhab.core.types.State;
45 import org.openhab.core.types.UnDefType;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import com.google.gson.Gson;
50 import com.google.gson.GsonBuilder;
51
52 /**
53  * The {@link SOAPValueConverter} converts SOAP values and openHAB states
54  *
55  * @author Jan N. Klug - Initial contribution
56  */
57 @NonNullByDefault
58 public class SOAPValueConverter {
59     private final Logger logger = LoggerFactory.getLogger(SOAPValueConverter.class);
60     private final HttpClient httpClient;
61     private final int timeout;
62
63     public SOAPValueConverter(HttpClient httpClient, int timeout) {
64         this.httpClient = httpClient;
65         this.timeout = timeout;
66     }
67
68     /**
69      * convert an openHAB command to a SOAP value
70      *
71      * @param command the command to be converted
72      * @param dataType the datatype to send
73      * @param unit if available, the unit of the converted value
74      * @return a string optional containing the converted value
75      */
76     public Optional<String> getSOAPValueFromCommand(Command command, String dataType, String unit) {
77         if (dataType.isEmpty()) {
78             // we don't have data to send
79             return Optional.of("");
80         }
81         if (command instanceof QuantityType quantityCommand) {
82             QuantityType<?> value = (unit.isEmpty()) ? quantityCommand : quantityCommand.toUnit(unit);
83             if (value == null) {
84                 logger.warn("Could not convert {} to unit {}", command, unit);
85                 return Optional.empty();
86             }
87             switch (dataType) {
88                 case "ui1", "ui2" -> {
89                     return Optional.of(String.valueOf(value.shortValue()));
90                 }
91                 case "i4", "ui4" -> {
92                     return Optional.of(String.valueOf(value.intValue()));
93                 }
94                 default -> {
95                 }
96             }
97         } else if (command instanceof DecimalType decimalCommand) {
98             BigDecimal value = decimalCommand.toBigDecimal();
99             switch (dataType) {
100                 case "ui1", "ui2" -> {
101                     return Optional.of(String.valueOf(value.shortValue()));
102                 }
103                 case "i4", "ui4" -> {
104                     return Optional.of(String.valueOf(value.intValue()));
105                 }
106                 default -> {
107                 }
108             }
109         } else if (command instanceof StringType) {
110             if ("string".equals(dataType)) {
111                 return Optional.of(command.toString());
112             }
113         } else if (command instanceof OnOffType) {
114             if ("boolean".equals(dataType)) {
115                 return Optional.of(OnOffType.ON.equals(command) ? "1" : "0");
116             }
117         }
118         return Optional.empty();
119     }
120
121     /**
122      * convert the value from a SOAP message to an openHAB value
123      *
124      * @param soapMessage the inbound SOAP message
125      * @param element the element that needs to be extracted
126      * @param channelConfig the channel config containing additional information (if null a data-type "string" and
127      *            missing unit is assumed)
128      * @return an Optional of State containing the converted value
129      */
130     public Optional<State> getStateFromSOAPValue(SOAPMessage soapMessage, String element,
131             @Nullable Tr064ChannelConfig channelConfig) {
132         String dataType = channelConfig != null ? channelConfig.getDataType() : "string";
133         String unit = channelConfig != null ? channelConfig.getChannelTypeDescription().getItem().getUnit() : "";
134         BigDecimal factor = channelConfig != null ? channelConfig.getChannelTypeDescription().getItem().getFactor()
135                 : null;
136
137         return getSOAPElement(soapMessage, element).map(rawValue -> {
138             // map rawValue to State
139             switch (dataType) {
140                 case "boolean" -> {
141                     return "0".equals(rawValue) ? OnOffType.OFF : OnOffType.ON;
142                 }
143                 case "string" -> {
144                     return new StringType(rawValue);
145                 }
146                 case "ui1", "ui2", "i4", "ui4" -> {
147                     BigDecimal decimalValue = new BigDecimal(rawValue);
148                     if (factor != null) {
149                         decimalValue = decimalValue.multiply(factor);
150                     }
151                     if (!unit.isEmpty()) {
152                         return new QuantityType<>(decimalValue + " " + unit);
153                     } else {
154                         return new DecimalType(decimalValue);
155                     }
156                 }
157                 default -> {
158                     return null;
159                 }
160             }
161         }).map(state -> {
162             // check if we need post-processing
163             if (channelConfig == null
164                     || channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor() == null) {
165                 return state;
166             }
167             String postProcessor = channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor();
168             try {
169                 Method method = SOAPValueConverter.class.getDeclaredMethod(postProcessor, State.class,
170                         Tr064ChannelConfig.class);
171                 Object o = method.invoke(this, state, channelConfig);
172                 if (o instanceof State stateInstance) {
173                     return stateInstance;
174                 }
175             } catch (NoSuchMethodException | IllegalAccessException e) {
176                 logger.warn("Postprocessor {} not found, this most likely is a programming error", postProcessor, e);
177             } catch (InvocationTargetException e) {
178                 Throwable cause = e.getCause();
179                 logger.info("Postprocessor {} failed: {}", postProcessor,
180                         cause != null ? cause.getMessage() : e.getMessage());
181             }
182             return null;
183         }).or(Optional::empty);
184     }
185
186     /**
187      * post processor for current bitrate
188      */
189     @SuppressWarnings("unused")
190     private State processCurrentBitrate(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
191         Double bps = Arrays.stream(state.toString().split(",")).mapToDouble(s -> {
192             try {
193                 return Double.parseDouble(s);
194             } catch (NumberFormatException e) {
195                 return 0.0;
196             }
197         }).limit(3).average().orElse(Double.NaN);
198
199         if (bps.equals(Double.NaN)) {
200             return UnDefType.UNDEF;
201         } else {
202             return new QuantityType<>(bps * 8.0 / 1024.0, Units.KILOBIT_PER_SECOND);
203         }
204     }
205
206     /**
207      * post processor to map mac device signal strength to system.signal-strength 0-4
208      *
209      * @param state with signalStrength
210      * @param channelConfig channel config of the mac signal strength
211      * @return the mapped system.signal-strength in range 0-4
212      */
213     @SuppressWarnings("unused")
214     private State processMacSignalStrength(State state, Tr064ChannelConfig channelConfig) {
215         State mappedSignalStrength = UnDefType.UNDEF;
216         DecimalType currentStateValue = state.as(DecimalType.class);
217
218         if (currentStateValue != null) {
219             if (currentStateValue.intValue() > 80) {
220                 mappedSignalStrength = new DecimalType(4);
221             } else if (currentStateValue.intValue() > 60) {
222                 mappedSignalStrength = new DecimalType(3);
223             } else if (currentStateValue.intValue() > 40) {
224                 mappedSignalStrength = new DecimalType(2);
225             } else if (currentStateValue.intValue() > 20) {
226                 mappedSignalStrength = new DecimalType(1);
227             } else {
228                 mappedSignalStrength = new DecimalType(0);
229             }
230         }
231
232         return mappedSignalStrength;
233     }
234
235     /**
236      * post processor for answering machine new messages channel
237      *
238      * @param state the message list URL
239      * @param channelConfig channel config of the TAM new message channel
240      * @return the number of new messages
241      * @throws PostProcessingException if the message list could not be retrieved
242      */
243     @SuppressWarnings("unused")
244     private State processTamListURL(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
245         try {
246             ContentResponse response = httpClient.newRequest(state.toString()).timeout(timeout, TimeUnit.SECONDS)
247                     .send();
248             String responseContent = response.getContentAsString();
249             int messageCount = responseContent.split("<New>1</New>").length - 1;
250
251             return new DecimalType(messageCount);
252         } catch (InterruptedException | TimeoutException | ExecutionException e) {
253             throw new PostProcessingException("Failed to get TAM list from URL " + state, e);
254         }
255     }
256
257     /**
258      * post processor for missed calls
259      *
260      * @param state the call list URL
261      * @param channelConfig channel config of the missed call channel (contains day number)
262      * @return the number of missed calls
263      * @throws PostProcessingException if call list could not be retrieved
264      */
265     @SuppressWarnings("unused")
266     private State processMissedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
267         return processCallList(state, channelConfig.getParameter(), CallListType.MISSED_COUNT);
268     }
269
270     /**
271      * post processor for inbound calls
272      *
273      * @param state the call list URL
274      * @param channelConfig channel config of the inbound call channel (contains day number)
275      * @return the number of inbound calls
276      * @throws PostProcessingException if call list could not be retrieved
277      */
278     @SuppressWarnings("unused")
279     private State processInboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
280         return processCallList(state, channelConfig.getParameter(), CallListType.INBOUND_COUNT);
281     }
282
283     /**
284      * post processor for rejected calls
285      *
286      * @param state the call list URL
287      * @param channelConfig channel config of the rejected call channel (contains day number)
288      * @return the number of rejected calls
289      * @throws PostProcessingException if call list could not be retrieved
290      */
291     @SuppressWarnings("unused")
292     private State processRejectedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
293         return processCallList(state, channelConfig.getParameter(), CallListType.REJECTED_COUNT);
294     }
295
296     /**
297      * post processor for outbound calls
298      *
299      * @param state the call list URL
300      * @param channelConfig channel config of the outbound call channel (contains day number)
301      * @return the number of outbound calls
302      * @throws PostProcessingException if call list could not be retrieved
303      */
304     @SuppressWarnings("unused")
305     private State processOutboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
306         return processCallList(state, channelConfig.getParameter(), CallListType.OUTBOUND_COUNT);
307     }
308
309     /**
310      * post processor for JSON call list
311      *
312      * @param state the call list URL
313      * @param channelConfig channel config of the call list channel (contains day number)
314      * @return caller list in JSON format
315      * @throws PostProcessingException if call list could not be retrieved
316      */
317     @SuppressWarnings("unused")
318     private State processCallListJSON(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
319         return processCallList(state, channelConfig.getParameter(), CallListType.JSON_LIST);
320     }
321
322     /**
323      * internal helper for call list post processors
324      *
325      * @param state the call list URL
326      * @param days number of days to get
327      * @param type type of call (2=missed 1=inbound 4=rejected 3=outbund)
328      * @return the quantity of calls of the given type within the given number of days
329      * @throws PostProcessingException if the call list could not be retrieved
330      */
331     private State processCallList(State state, @Nullable String days, CallListType type)
332             throws PostProcessingException {
333         Root callListRoot = Util.getAndUnmarshalXML(httpClient, state + "&days=" + days, Root.class, timeout);
334         if (callListRoot == null) {
335             throw new PostProcessingException("Failed to get call list from URL " + state);
336         }
337         List<Call> calls = callListRoot.getCall();
338         switch (type) {
339             case INBOUND_COUNT, MISSED_COUNT, OUTBOUND_COUNT, REJECTED_COUNT -> {
340                 long callCount = calls.stream().filter(call -> type.typeString().equals(call.getType())).count();
341                 return new DecimalType(callCount);
342             }
343             case JSON_LIST -> {
344                 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").serializeNulls().create();
345                 List<CallListEntry> callListEntries = calls.stream().map(CallListEntry::new)
346                         .collect(Collectors.toList());
347                 return new StringType(gson.toJson(callListEntries));
348             }
349         }
350         return UnDefType.UNDEF;
351     }
352 }