2 * Copyright (c) 2010-2021 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.denonmarantz.internal.connector.http;
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;
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;
36 import org.apache.commons.io.IOUtils;
37 import org.apache.commons.lang.StringUtils;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.eclipse.jetty.client.HttpClient;
40 import org.eclipse.jetty.client.api.Response;
41 import org.eclipse.jetty.client.api.Result;
42 import org.openhab.binding.denonmarantz.internal.DenonMarantzState;
43 import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration;
44 import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnector;
45 import org.openhab.binding.denonmarantz.internal.xml.entities.Deviceinfo;
46 import org.openhab.binding.denonmarantz.internal.xml.entities.Main;
47 import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatus;
48 import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatusLite;
49 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandRequest;
50 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandResponse;
51 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandRx;
52 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandTx;
53 import org.openhab.core.io.net.http.HttpUtil;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * This class makes the connection to the receiver and manages it.
59 * It is also responsible for sending commands to the receiver.
62 * @author Jeroen Idserda - Initial Contribution (1.x Binding)
63 * @author Jan-Willem Veldhuis - Refactored for 2.x
65 public class DenonMarantzHttpConnector extends DenonMarantzConnector {
67 private Logger logger = LoggerFactory.getLogger(DenonMarantzHttpConnector.class);
69 private static final int REQUEST_TIMEOUT_MS = 5000; // 5 seconds
71 // Main URL for the receiver
72 private static final String URL_MAIN = "formMainZone_MainZoneXml.xml";
74 // Main Zone Status URL
75 private static final String URL_ZONE_MAIN = "formMainZone_MainZoneXmlStatus.xml";
77 // Secondary zone lite status URL (contains less info)
78 private static final String URL_ZONE_SECONDARY_LITE = "formZone%d_Zone%dXmlStatusLite.xml";
81 private static final String URL_DEVICE_INFO = "Deviceinfo.xml";
83 // URL to send app commands to
84 private static final String URL_APP_COMMAND = "AppCommand.xml";
86 private static final String CONTENT_TYPE_XML = "application/xml";
88 private final String cmdUrl;
90 private final String statusUrl;
92 private final HttpClient httpClient;
94 private ScheduledFuture<?> pollingJob;
96 public DenonMarantzHttpConnector(DenonMarantzConfiguration config, DenonMarantzState state,
97 ScheduledExecutorService scheduler, HttpClient httpClient) {
99 this.scheduler = scheduler;
101 this.cmdUrl = String.format("http://%s:%d/goform/formiPhoneAppDirect.xml?", config.getHost(),
102 config.getHttpPort());
103 this.statusUrl = String.format("http://%s:%d/goform/", config.getHost(), config.getHttpPort());
104 this.httpClient = httpClient;
107 public DenonMarantzState getState() {
112 * Set up the connection to the receiver by starting to poll the HTTP API.
115 public void connect() {
117 logger.debug("HTTP polling started.");
119 setConfigProperties();
120 } catch (IOException e) {
121 logger.debug("IO error while retrieving document:", e);
122 state.connectionError("IO error while connecting to AVR: " + e.getMessage());
126 pollingJob = scheduler.scheduleWithFixedDelay(() -> {
128 refreshHttpProperties();
129 } catch (IOException e) {
130 logger.debug("IO error while retrieving document", e);
131 state.connectionError("IO error while connecting to AVR: " + e.getMessage());
133 } catch (RuntimeException e) {
135 * We need to catch this RuntimeException, as otherwise the polling stops.
136 * Log as error as it could be a user configuration error.
138 StringBuilder sb = new StringBuilder();
139 for (StackTraceElement s : e.getStackTrace()) {
140 sb.append(s.toString()).append("\n");
142 logger.error("Error while polling Http: \"{}\". Stacktrace: \n{}", e.getMessage(), sb.toString());
144 }, 0, config.httpPollingInterval, TimeUnit.SECONDS);
148 private boolean isPolling() {
149 return pollingJob != null && !pollingJob.isCancelled();
152 private void stopPolling() {
154 pollingJob.cancel(true);
155 logger.debug("HTTP polling stopped.");
160 * Shutdown the http client
163 public void dispose() {
164 logger.debug("disposing connector");
170 protected void internalSendCommand(String command) {
171 logger.debug("Sending command '{}'", command);
172 if (StringUtils.isBlank(command)) {
173 logger.warn("Trying to send empty command");
178 String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName());
179 logger.trace("Calling url {}", url);
181 httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() {
183 public void onComplete(Result result) {
184 if (result.getResponse().getStatus() != 200) {
185 logger.warn("Error {} while sending command", result.getResponse().getReason());
190 } catch (UnsupportedEncodingException e) {
191 logger.warn("Error sending command", e);
195 private void updateMain() throws IOException {
196 String url = statusUrl + URL_MAIN;
197 logger.trace("Refreshing URL: {}", url);
199 Main statusMain = getDocument(url, Main.class);
200 if (statusMain != null) {
201 state.setPower(statusMain.getPower().getValue());
205 private void updateMainZone() throws IOException {
206 String url = statusUrl + URL_ZONE_MAIN;
207 logger.trace("Refreshing URL: {}", url);
209 ZoneStatus mainZone = getDocument(url, ZoneStatus.class);
210 if (mainZone != null) {
211 state.setInput(mainZone.getInputFuncSelect().getValue());
212 state.setMainVolume(mainZone.getMasterVolume().getValue());
213 state.setMainZonePower(mainZone.getPower().getValue());
214 state.setMute(mainZone.getMute().getValue());
216 if (config.inputOptions == null) {
217 config.inputOptions = mainZone.getInputFuncList();
220 if (mainZone.getSurrMode() == null) {
221 logger.debug("Unable to get the SURROUND_MODE. MainZone update may not be correct.");
223 state.setSurroundProgram(mainZone.getSurrMode().getValue());
228 private void updateSecondaryZones() throws IOException {
229 for (int i = 2; i <= config.getZoneCount(); i++) {
230 String url = String.format("%s" + URL_ZONE_SECONDARY_LITE, statusUrl, i, i);
231 logger.trace("Refreshing URL: {}", url);
232 ZoneStatusLite zoneSecondary = getDocument(url, ZoneStatusLite.class);
233 if (zoneSecondary != null) {
235 // maximum 2 secondary zones are supported
237 state.setZone2Power(zoneSecondary.getPower().getValue());
238 state.setZone2Volume(zoneSecondary.getMasterVolume().getValue());
239 state.setZone2Mute(zoneSecondary.getMute().getValue());
240 state.setZone2Input(zoneSecondary.getInputFuncSelect().getValue());
243 state.setZone3Power(zoneSecondary.getPower().getValue());
244 state.setZone3Volume(zoneSecondary.getMasterVolume().getValue());
245 state.setZone3Mute(zoneSecondary.getMute().getValue());
246 state.setZone3Input(zoneSecondary.getInputFuncSelect().getValue());
249 state.setZone4Power(zoneSecondary.getPower().getValue());
250 state.setZone4Volume(zoneSecondary.getMasterVolume().getValue());
251 state.setZone4Mute(zoneSecondary.getMute().getValue());
252 state.setZone4Input(zoneSecondary.getInputFuncSelect().getValue());
259 private void updateDisplayInfo() throws IOException {
260 String url = statusUrl + URL_APP_COMMAND;
261 logger.trace("Refreshing URL: {}", url);
263 AppCommandRequest request = AppCommandRequest.of(CommandTx.CMD_NET_STATUS);
264 AppCommandResponse response = postDocument(url, AppCommandResponse.class, request);
266 if (response != null) {
267 CommandRx titleInfo = response.getCommands().get(0);
268 state.setNowPlayingArtist(titleInfo.getText("artist"));
269 state.setNowPlayingAlbum(titleInfo.getText("album"));
270 state.setNowPlayingTrack(titleInfo.getText("track"));
274 private boolean setConfigProperties() throws IOException {
275 String url = statusUrl + URL_DEVICE_INFO;
276 logger.debug("Refreshing URL: {}", url);
278 Deviceinfo deviceinfo = getDocument(url, Deviceinfo.class);
279 if (deviceinfo != null) {
280 config.setZoneCount(deviceinfo.getDeviceZones());
284 * The maximum volume is received from the telnet connection in the
285 * form of the MVMAX property. It is not always received reliable however,
286 * so we're using a default for now.
288 config.setMainVolumeMax(DenonMarantzConfiguration.MAX_VOLUME);
290 // if deviceinfo is null, something went wrong (and is logged in getDocument catch blocks)
291 return (deviceinfo != null);
294 private void refreshHttpProperties() throws IOException {
295 logger.trace("Refreshing Denon status");
299 updateSecondaryZones();
304 private <T> T getDocument(String uri, Class<T> response) throws IOException {
306 String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS);
307 logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result);
309 if (StringUtils.isNotBlank(result)) {
310 JAXBContext jc = JAXBContext.newInstance(response);
311 XMLInputFactory xif = XMLInputFactory.newInstance();
312 xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
313 xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
314 XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(result));
315 xsr = new PropertyRenamerDelegate(xsr);
317 @SuppressWarnings("unchecked")
318 T obj = (T) jc.createUnmarshaller().unmarshal(xsr);
322 } catch (UnmarshalException e) {
323 logger.debug("Failed to unmarshal xml document: {}", e.getMessage());
324 } catch (JAXBException e) {
325 logger.debug("Unexpected error occurred during unmarshalling of document: {}", e.getMessage());
326 } catch (XMLStreamException e) {
327 logger.debug("Communication error: {}", e.getMessage());
334 private <T, S> T postDocument(String uri, Class<T> response, S request) throws IOException {
336 JAXBContext jaxbContext = JAXBContext.newInstance(request.getClass());
337 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
338 StringWriter sw = new StringWriter();
339 jaxbMarshaller.marshal(request, sw);
341 ByteArrayInputStream inputStream = new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8));
342 String result = HttpUtil.executeUrl("POST", uri, inputStream, CONTENT_TYPE_XML, REQUEST_TIMEOUT_MS);
344 if (StringUtils.isNotBlank(result)) {
345 JAXBContext jcResponse = JAXBContext.newInstance(response);
347 @SuppressWarnings("unchecked")
348 T obj = (T) jcResponse.createUnmarshaller().unmarshal(IOUtils.toInputStream(result));
352 } catch (JAXBException e) {
353 logger.debug("Encoding error in post", e);
359 private static class PropertyRenamerDelegate extends StreamReaderDelegate {
361 public PropertyRenamerDelegate(XMLStreamReader xsr) {
366 public String getAttributeLocalName(int index) {
367 return Introspector.decapitalize(super.getAttributeLocalName(index));
371 public String getLocalName() {
372 return Introspector.decapitalize(super.getLocalName());