]> git.basschouten.com Git - openhab-addons.git/blob
f43745c1dab0e96af6a9dba536d071623d601a8c
[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.denonmarantz.internal.connector.http;
14
15 import java.beans.Introspector;
16 import java.io.ByteArrayInputStream;
17 import java.io.IOException;
18 import java.io.StringWriter;
19 import java.io.UnsupportedEncodingException;
20 import java.net.URLEncoder;
21 import java.nio.charset.Charset;
22 import java.nio.charset.StandardCharsets;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26
27 import javax.xml.bind.JAXBContext;
28 import javax.xml.bind.JAXBException;
29 import javax.xml.bind.Marshaller;
30 import javax.xml.bind.UnmarshalException;
31 import javax.xml.stream.XMLInputFactory;
32 import javax.xml.stream.XMLStreamException;
33 import javax.xml.stream.XMLStreamReader;
34 import javax.xml.stream.util.StreamReaderDelegate;
35
36 import org.apache.commons.io.IOUtils;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.eclipse.jetty.client.HttpClient;
39 import org.eclipse.jetty.client.api.Response;
40 import org.eclipse.jetty.client.api.Result;
41 import org.openhab.binding.denonmarantz.internal.DenonMarantzState;
42 import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration;
43 import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnector;
44 import org.openhab.binding.denonmarantz.internal.xml.entities.Deviceinfo;
45 import org.openhab.binding.denonmarantz.internal.xml.entities.Main;
46 import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatus;
47 import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatusLite;
48 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandRequest;
49 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandResponse;
50 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandRx;
51 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandTx;
52 import org.openhab.core.io.net.http.HttpUtil;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * This class makes the connection to the receiver and manages it.
58  * It is also responsible for sending commands to the receiver.
59  * *
60  *
61  * @author Jeroen Idserda - Initial Contribution (1.x Binding)
62  * @author Jan-Willem Veldhuis - Refactored for 2.x
63  */
64 public class DenonMarantzHttpConnector extends DenonMarantzConnector {
65
66     private Logger logger = LoggerFactory.getLogger(DenonMarantzHttpConnector.class);
67
68     private static final int REQUEST_TIMEOUT_MS = 5000; // 5 seconds
69
70     // Main URL for the receiver
71     private static final String URL_MAIN = "formMainZone_MainZoneXml.xml";
72
73     // Main Zone Status URL
74     private static final String URL_ZONE_MAIN = "formMainZone_MainZoneXmlStatus.xml";
75
76     // Secondary zone lite status URL (contains less info)
77     private static final String URL_ZONE_SECONDARY_LITE = "formZone%d_Zone%dXmlStatusLite.xml";
78
79     // Device info URL
80     private static final String URL_DEVICE_INFO = "Deviceinfo.xml";
81
82     // URL to send app commands to
83     private static final String URL_APP_COMMAND = "AppCommand.xml";
84
85     private static final String CONTENT_TYPE_XML = "application/xml";
86
87     private final String cmdUrl;
88
89     private final String statusUrl;
90
91     private final HttpClient httpClient;
92
93     private ScheduledFuture<?> pollingJob;
94
95     public DenonMarantzHttpConnector(DenonMarantzConfiguration config, DenonMarantzState state,
96             ScheduledExecutorService scheduler, HttpClient httpClient) {
97         this.config = config;
98         this.scheduler = scheduler;
99         this.state = state;
100         this.cmdUrl = String.format("http://%s:%d/goform/formiPhoneAppDirect.xml?", config.getHost(),
101                 config.getHttpPort());
102         this.statusUrl = String.format("http://%s:%d/goform/", config.getHost(), config.getHttpPort());
103         this.httpClient = httpClient;
104     }
105
106     public DenonMarantzState getState() {
107         return state;
108     }
109
110     /**
111      * Set up the connection to the receiver by starting to poll the HTTP API.
112      */
113     @Override
114     public void connect() {
115         if (!isPolling()) {
116             logger.debug("HTTP polling started.");
117             try {
118                 setConfigProperties();
119             } catch (IOException e) {
120                 logger.debug("IO error while retrieving document:", e);
121                 state.connectionError("IO error while connecting to AVR: " + e.getMessage());
122                 return;
123             }
124
125             pollingJob = scheduler.scheduleWithFixedDelay(() -> {
126                 try {
127                     refreshHttpProperties();
128                 } catch (IOException e) {
129                     logger.debug("IO error while retrieving document", e);
130                     state.connectionError("IO error while connecting to AVR: " + e.getMessage());
131                     stopPolling();
132                 } catch (RuntimeException e) {
133                     /**
134                      * We need to catch this RuntimeException, as otherwise the polling stops.
135                      * Log as error as it could be a user configuration error.
136                      */
137                     StringBuilder sb = new StringBuilder();
138                     for (StackTraceElement s : e.getStackTrace()) {
139                         sb.append(s.toString()).append("\n");
140                     }
141                     logger.error("Error while polling Http: \"{}\". Stacktrace: \n{}", e.getMessage(), sb.toString());
142                 }
143             }, 0, config.httpPollingInterval, TimeUnit.SECONDS);
144         }
145     }
146
147     private boolean isPolling() {
148         return pollingJob != null && !pollingJob.isCancelled();
149     }
150
151     private void stopPolling() {
152         if (isPolling()) {
153             pollingJob.cancel(true);
154             logger.debug("HTTP polling stopped.");
155         }
156     }
157
158     /**
159      * Shutdown the http client
160      */
161     @Override
162     public void dispose() {
163         logger.debug("disposing connector");
164
165         stopPolling();
166     }
167
168     @Override
169     protected void internalSendCommand(String command) {
170         logger.debug("Sending command '{}'", command);
171         if (command == null || command.isBlank()) {
172             logger.warn("Trying to send empty command");
173             return;
174         }
175
176         try {
177             String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName());
178             logger.trace("Calling url {}", url);
179
180             httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() {
181                 @Override
182                 public void onComplete(Result result) {
183                     if (result.getResponse().getStatus() != 200) {
184                         logger.warn("Error {} while sending command", result.getResponse().getReason());
185                     }
186                 }
187             });
188
189         } catch (UnsupportedEncodingException e) {
190             logger.warn("Error sending command", e);
191         }
192     }
193
194     private void updateMain() throws IOException {
195         String url = statusUrl + URL_MAIN;
196         logger.trace("Refreshing URL: {}", url);
197
198         Main statusMain = getDocument(url, Main.class);
199         if (statusMain != null) {
200             state.setPower(statusMain.getPower().getValue());
201         }
202     }
203
204     private void updateMainZone() throws IOException {
205         String url = statusUrl + URL_ZONE_MAIN;
206         logger.trace("Refreshing URL: {}", url);
207
208         ZoneStatus mainZone = getDocument(url, ZoneStatus.class);
209         if (mainZone != null) {
210             state.setInput(mainZone.getInputFuncSelect().getValue());
211             state.setMainVolume(mainZone.getMasterVolume().getValue());
212             state.setMainZonePower(mainZone.getPower().getValue());
213             state.setMute(mainZone.getMute().getValue());
214
215             if (config.inputOptions == null) {
216                 config.inputOptions = mainZone.getInputFuncList();
217             }
218
219             if (mainZone.getSurrMode() == null) {
220                 logger.debug("Unable to get the SURROUND_MODE. MainZone update may not be correct.");
221             } else {
222                 state.setSurroundProgram(mainZone.getSurrMode().getValue());
223             }
224         }
225     }
226
227     private void updateSecondaryZones() throws IOException {
228         for (int i = 2; i <= config.getZoneCount(); i++) {
229             String url = String.format("%s" + URL_ZONE_SECONDARY_LITE, statusUrl, i, i);
230             logger.trace("Refreshing URL: {}", url);
231             ZoneStatusLite zoneSecondary = getDocument(url, ZoneStatusLite.class);
232             if (zoneSecondary != null) {
233                 switch (i) {
234                     // maximum 2 secondary zones are supported
235                     case 2:
236                         state.setZone2Power(zoneSecondary.getPower().getValue());
237                         state.setZone2Volume(zoneSecondary.getMasterVolume().getValue());
238                         state.setZone2Mute(zoneSecondary.getMute().getValue());
239                         state.setZone2Input(zoneSecondary.getInputFuncSelect().getValue());
240                         break;
241                     case 3:
242                         state.setZone3Power(zoneSecondary.getPower().getValue());
243                         state.setZone3Volume(zoneSecondary.getMasterVolume().getValue());
244                         state.setZone3Mute(zoneSecondary.getMute().getValue());
245                         state.setZone3Input(zoneSecondary.getInputFuncSelect().getValue());
246                         break;
247                     case 4:
248                         state.setZone4Power(zoneSecondary.getPower().getValue());
249                         state.setZone4Volume(zoneSecondary.getMasterVolume().getValue());
250                         state.setZone4Mute(zoneSecondary.getMute().getValue());
251                         state.setZone4Input(zoneSecondary.getInputFuncSelect().getValue());
252                         break;
253                 }
254             }
255         }
256     }
257
258     private void updateDisplayInfo() throws IOException {
259         String url = statusUrl + URL_APP_COMMAND;
260         logger.trace("Refreshing URL: {}", url);
261
262         AppCommandRequest request = AppCommandRequest.of(CommandTx.CMD_NET_STATUS);
263         AppCommandResponse response = postDocument(url, AppCommandResponse.class, request);
264
265         if (response != null) {
266             CommandRx titleInfo = response.getCommands().get(0);
267             state.setNowPlayingArtist(titleInfo.getText("artist"));
268             state.setNowPlayingAlbum(titleInfo.getText("album"));
269             state.setNowPlayingTrack(titleInfo.getText("track"));
270         }
271     }
272
273     private boolean setConfigProperties() throws IOException {
274         String url = statusUrl + URL_DEVICE_INFO;
275         logger.debug("Refreshing URL: {}", url);
276
277         Deviceinfo deviceinfo = getDocument(url, Deviceinfo.class);
278         if (deviceinfo != null) {
279             config.setZoneCount(deviceinfo.getDeviceZones());
280         }
281
282         /**
283          * The maximum volume is received from the telnet connection in the
284          * form of the MVMAX property. It is not always received reliable however,
285          * so we're using a default for now.
286          */
287         config.setMainVolumeMax(DenonMarantzConfiguration.MAX_VOLUME);
288
289         // if deviceinfo is null, something went wrong (and is logged in getDocument catch blocks)
290         return (deviceinfo != null);
291     }
292
293     private void refreshHttpProperties() throws IOException {
294         logger.trace("Refreshing Denon status");
295
296         updateMain();
297         updateMainZone();
298         updateSecondaryZones();
299         updateDisplayInfo();
300     }
301
302     @Nullable
303     private <T> T getDocument(String uri, Class<T> response) throws IOException {
304         try {
305             String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS);
306             logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result);
307
308             if (result != null && !result.isBlank()) {
309                 JAXBContext jc = JAXBContext.newInstance(response);
310                 XMLInputFactory xif = XMLInputFactory.newInstance();
311                 xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
312                 xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
313                 XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(result));
314                 xsr = new PropertyRenamerDelegate(xsr);
315
316                 @SuppressWarnings("unchecked")
317                 T obj = (T) jc.createUnmarshaller().unmarshal(xsr);
318
319                 return obj;
320             }
321         } catch (UnmarshalException e) {
322             logger.debug("Failed to unmarshal xml document: {}", e.getMessage());
323         } catch (JAXBException e) {
324             logger.debug("Unexpected error occurred during unmarshalling of document: {}", e.getMessage());
325         } catch (XMLStreamException e) {
326             logger.debug("Communication error: {}", e.getMessage());
327         }
328
329         return null;
330     }
331
332     @Nullable
333     private <T, S> T postDocument(String uri, Class<T> response, S request) throws IOException {
334         try {
335             JAXBContext jaxbContext = JAXBContext.newInstance(request.getClass());
336             Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
337             StringWriter sw = new StringWriter();
338             jaxbMarshaller.marshal(request, sw);
339
340             ByteArrayInputStream inputStream = new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8));
341             String result = HttpUtil.executeUrl("POST", uri, inputStream, CONTENT_TYPE_XML, REQUEST_TIMEOUT_MS);
342
343             if (result != null && !result.isBlank()) {
344                 JAXBContext jcResponse = JAXBContext.newInstance(response);
345
346                 @SuppressWarnings("unchecked")
347                 T obj = (T) jcResponse.createUnmarshaller().unmarshal(IOUtils.toInputStream(result));
348
349                 return obj;
350             }
351         } catch (JAXBException e) {
352             logger.debug("Encoding error in post", e);
353         }
354
355         return null;
356     }
357
358     private static class PropertyRenamerDelegate extends StreamReaderDelegate {
359
360         public PropertyRenamerDelegate(XMLStreamReader xsr) {
361             super(xsr);
362         }
363
364         @Override
365         public String getAttributeLocalName(int index) {
366             return Introspector.decapitalize(super.getAttributeLocalName(index));
367         }
368
369         @Override
370         public String getLocalName() {
371             return Introspector.decapitalize(super.getLocalName());
372         }
373     }
374 }