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.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;
28 import javax.xml.soap.SOAPMessage;
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;
49 import com.google.gson.Gson;
50 import com.google.gson.GsonBuilder;
53 * The {@link SOAPValueConverter} converts SOAP values and openHAB states
55 * @author Jan N. Klug - Initial contribution
58 public class SOAPValueConverter {
59 private final Logger logger = LoggerFactory.getLogger(SOAPValueConverter.class);
60 private final HttpClient httpClient;
61 private final int timeout;
63 public SOAPValueConverter(HttpClient httpClient, int timeout) {
64 this.httpClient = httpClient;
65 this.timeout = timeout;
69 * convert an openHAB command to a SOAP value
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
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("");
81 if (command instanceof QuantityType quantityCommand) {
82 QuantityType<?> value = (unit.isEmpty()) ? quantityCommand : quantityCommand.toUnit(unit);
84 logger.warn("Could not convert {} to unit {}", command, unit);
85 return Optional.empty();
88 case "ui1", "ui2" -> {
89 return Optional.of(String.valueOf(value.shortValue()));
92 return Optional.of(String.valueOf(value.intValue()));
97 } else if (command instanceof DecimalType decimalCommand) {
98 BigDecimal value = decimalCommand.toBigDecimal();
100 case "ui1", "ui2" -> {
101 return Optional.of(String.valueOf(value.shortValue()));
103 case "i4", "ui4" -> {
104 return Optional.of(String.valueOf(value.intValue()));
109 } else if (command instanceof StringType) {
110 if ("string".equals(dataType)) {
111 return Optional.of(command.toString());
113 } else if (command instanceof OnOffType) {
114 if ("boolean".equals(dataType)) {
115 return Optional.of(OnOffType.ON.equals(command) ? "1" : "0");
118 return Optional.empty();
122 * convert the value from a SOAP message to an openHAB value
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
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()
137 return getSOAPElement(soapMessage, element).map(rawValue -> {
138 // map rawValue to State
141 return OnOffType.from(!"0".equals(rawValue));
144 return new StringType(rawValue);
146 case "ui1", "ui2", "i4", "ui4" -> {
147 BigDecimal decimalValue = new BigDecimal(rawValue);
148 if (factor != null) {
149 decimalValue = decimalValue.multiply(factor);
151 if (!unit.isEmpty()) {
152 return new QuantityType<>(decimalValue + " " + unit);
154 return new DecimalType(decimalValue);
162 // check if we need post-processing
163 if (channelConfig == null
164 || channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor() == null) {
167 String postProcessor = channelConfig.getChannelTypeDescription().getGetAction().getPostProcessor();
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;
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());
183 }).or(Optional::empty);
187 * post processor for current bitrate
189 @SuppressWarnings("unused")
190 private State processCurrentBitrate(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
191 Double bps = Arrays.stream(state.toString().split(",")).mapToDouble(s -> {
193 return Double.parseDouble(s);
194 } catch (NumberFormatException e) {
197 }).limit(3).average().orElse(Double.NaN);
199 if (bps.equals(Double.NaN)) {
200 return UnDefType.UNDEF;
202 return new QuantityType<>(bps * 8.0 / 1024.0, Units.KILOBIT_PER_SECOND);
207 * post processor to map mac device signal strength to system.signal-strength 0-4
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
213 @SuppressWarnings("unused")
214 private State processMacSignalStrength(State state, Tr064ChannelConfig channelConfig) {
215 State mappedSignalStrength = UnDefType.UNDEF;
216 DecimalType currentStateValue = state.as(DecimalType.class);
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);
228 mappedSignalStrength = new DecimalType(0);
232 return mappedSignalStrength;
236 * post processor for answering machine new messages channel
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
243 @SuppressWarnings("unused")
244 private State processTamListURL(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
246 ContentResponse response = httpClient.newRequest(state.toString()).timeout(timeout, TimeUnit.SECONDS)
248 String responseContent = response.getContentAsString();
249 int messageCount = responseContent.split("<New>1</New>").length - 1;
251 return new DecimalType(messageCount);
252 } catch (InterruptedException | TimeoutException | ExecutionException e) {
253 throw new PostProcessingException("Failed to get TAM list from URL " + state, e);
258 * post processor for missed calls
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
265 @SuppressWarnings("unused")
266 private State processMissedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
267 return processCallList(state, channelConfig.getParameter(), CallListType.MISSED_COUNT);
271 * post processor for inbound calls
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
278 @SuppressWarnings("unused")
279 private State processInboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
280 return processCallList(state, channelConfig.getParameter(), CallListType.INBOUND_COUNT);
284 * post processor for rejected calls
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
291 @SuppressWarnings("unused")
292 private State processRejectedCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
293 return processCallList(state, channelConfig.getParameter(), CallListType.REJECTED_COUNT);
297 * post processor for outbound calls
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
304 @SuppressWarnings("unused")
305 private State processOutboundCalls(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
306 return processCallList(state, channelConfig.getParameter(), CallListType.OUTBOUND_COUNT);
310 * post processor for JSON call list
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
317 @SuppressWarnings("unused")
318 private State processCallListJSON(State state, Tr064ChannelConfig channelConfig) throws PostProcessingException {
319 return processCallList(state, channelConfig.getParameter(), CallListType.JSON_LIST);
323 * internal helper for call list post processors
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
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);
337 List<Call> calls = callListRoot.getCall();
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);
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));
350 return UnDefType.UNDEF;