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.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;
57 * This class makes the connection to the receiver and manages it.
58 * It is also responsible for sending commands to the receiver.
61 * @author Jeroen Idserda - Initial Contribution (1.x Binding)
62 * @author Jan-Willem Veldhuis - Refactored for 2.x
64 public class DenonMarantzHttpConnector extends DenonMarantzConnector {
66 private Logger logger = LoggerFactory.getLogger(DenonMarantzHttpConnector.class);
68 private static final int REQUEST_TIMEOUT_MS = 5000; // 5 seconds
70 // Main URL for the receiver
71 private static final String URL_MAIN = "formMainZone_MainZoneXml.xml";
73 // Main Zone Status URL
74 private static final String URL_ZONE_MAIN = "formMainZone_MainZoneXmlStatus.xml";
76 // Secondary zone lite status URL (contains less info)
77 private static final String URL_ZONE_SECONDARY_LITE = "formZone%d_Zone%dXmlStatusLite.xml";
80 private static final String URL_DEVICE_INFO = "Deviceinfo.xml";
82 // URL to send app commands to
83 private static final String URL_APP_COMMAND = "AppCommand.xml";
85 private static final String CONTENT_TYPE_XML = "application/xml";
87 private final String cmdUrl;
89 private final String statusUrl;
91 private final HttpClient httpClient;
93 private ScheduledFuture<?> pollingJob;
95 public DenonMarantzHttpConnector(DenonMarantzConfiguration config, DenonMarantzState state,
96 ScheduledExecutorService scheduler, HttpClient httpClient) {
98 this.scheduler = scheduler;
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;
106 public DenonMarantzState getState() {
111 * Set up the connection to the receiver by starting to poll the HTTP API.
114 public void connect() {
116 logger.debug("HTTP polling started.");
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());
125 pollingJob = scheduler.scheduleWithFixedDelay(() -> {
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());
132 } catch (RuntimeException e) {
134 * We need to catch this RuntimeException, as otherwise the polling stops.
135 * Log as error as it could be a user configuration error.
137 StringBuilder sb = new StringBuilder();
138 for (StackTraceElement s : e.getStackTrace()) {
139 sb.append(s.toString()).append("\n");
141 logger.error("Error while polling Http: \"{}\". Stacktrace: \n{}", e.getMessage(), sb.toString());
143 }, 0, config.httpPollingInterval, TimeUnit.SECONDS);
147 private boolean isPolling() {
148 return pollingJob != null && !pollingJob.isCancelled();
151 private void stopPolling() {
153 pollingJob.cancel(true);
154 logger.debug("HTTP polling stopped.");
159 * Shutdown the http client
162 public void dispose() {
163 logger.debug("disposing connector");
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");
177 String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName());
178 logger.trace("Calling url {}", url);
180 httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() {
182 public void onComplete(Result result) {
183 if (result.getResponse().getStatus() != 200) {
184 logger.warn("Error {} while sending command", result.getResponse().getReason());
189 } catch (UnsupportedEncodingException e) {
190 logger.warn("Error sending command", e);
194 private void updateMain() throws IOException {
195 String url = statusUrl + URL_MAIN;
196 logger.trace("Refreshing URL: {}", url);
198 Main statusMain = getDocument(url, Main.class);
199 if (statusMain != null) {
200 state.setPower(statusMain.getPower().getValue());
204 private void updateMainZone() throws IOException {
205 String url = statusUrl + URL_ZONE_MAIN;
206 logger.trace("Refreshing URL: {}", url);
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());
215 if (config.inputOptions == null) {
216 config.inputOptions = mainZone.getInputFuncList();
219 if (mainZone.getSurrMode() == null) {
220 logger.debug("Unable to get the SURROUND_MODE. MainZone update may not be correct.");
222 state.setSurroundProgram(mainZone.getSurrMode().getValue());
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) {
234 // maximum 2 secondary zones are supported
236 state.setZone2Power(zoneSecondary.getPower().getValue());
237 state.setZone2Volume(zoneSecondary.getMasterVolume().getValue());
238 state.setZone2Mute(zoneSecondary.getMute().getValue());
239 state.setZone2Input(zoneSecondary.getInputFuncSelect().getValue());
242 state.setZone3Power(zoneSecondary.getPower().getValue());
243 state.setZone3Volume(zoneSecondary.getMasterVolume().getValue());
244 state.setZone3Mute(zoneSecondary.getMute().getValue());
245 state.setZone3Input(zoneSecondary.getInputFuncSelect().getValue());
248 state.setZone4Power(zoneSecondary.getPower().getValue());
249 state.setZone4Volume(zoneSecondary.getMasterVolume().getValue());
250 state.setZone4Mute(zoneSecondary.getMute().getValue());
251 state.setZone4Input(zoneSecondary.getInputFuncSelect().getValue());
258 private void updateDisplayInfo() throws IOException {
259 String url = statusUrl + URL_APP_COMMAND;
260 logger.trace("Refreshing URL: {}", url);
262 AppCommandRequest request = AppCommandRequest.of(CommandTx.CMD_NET_STATUS);
263 AppCommandResponse response = postDocument(url, AppCommandResponse.class, request);
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"));
273 private boolean setConfigProperties() throws IOException {
274 String url = statusUrl + URL_DEVICE_INFO;
275 logger.debug("Refreshing URL: {}", url);
277 Deviceinfo deviceinfo = getDocument(url, Deviceinfo.class);
278 if (deviceinfo != null) {
279 config.setZoneCount(deviceinfo.getDeviceZones());
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.
287 config.setMainVolumeMax(DenonMarantzConfiguration.MAX_VOLUME);
289 // if deviceinfo is null, something went wrong (and is logged in getDocument catch blocks)
290 return (deviceinfo != null);
293 private void refreshHttpProperties() throws IOException {
294 logger.trace("Refreshing Denon status");
298 updateSecondaryZones();
303 private <T> T getDocument(String uri, Class<T> response) throws IOException {
305 String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS);
306 logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result);
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);
316 @SuppressWarnings("unchecked")
317 T obj = (T) jc.createUnmarshaller().unmarshal(xsr);
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());
333 private <T, S> T postDocument(String uri, Class<T> response, S request) throws IOException {
335 JAXBContext jaxbContext = JAXBContext.newInstance(request.getClass());
336 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
337 StringWriter sw = new StringWriter();
338 jaxbMarshaller.marshal(request, sw);
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);
343 if (result != null && !result.isBlank()) {
344 JAXBContext jcResponse = JAXBContext.newInstance(response);
346 @SuppressWarnings("unchecked")
347 T obj = (T) jcResponse.createUnmarshaller().unmarshal(IOUtils.toInputStream(result));
351 } catch (JAXBException e) {
352 logger.debug("Encoding error in post", e);
358 private static class PropertyRenamerDelegate extends StreamReaderDelegate {
360 public PropertyRenamerDelegate(XMLStreamReader xsr) {
365 public String getAttributeLocalName(int index) {
366 return Introspector.decapitalize(super.getAttributeLocalName(index));
370 public String getLocalName() {
371 return Introspector.decapitalize(super.getLocalName());