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.eclipse.jdt.annotation.Nullable;
37 import org.eclipse.jetty.client.HttpClient;
38 import org.eclipse.jetty.client.api.Response;
39 import org.eclipse.jetty.client.api.Result;
40 import org.openhab.binding.denonmarantz.internal.DenonMarantzState;
41 import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration;
42 import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnector;
43 import org.openhab.binding.denonmarantz.internal.xml.entities.Deviceinfo;
44 import org.openhab.binding.denonmarantz.internal.xml.entities.Main;
45 import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatus;
46 import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatusLite;
47 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandRequest;
48 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandResponse;
49 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandRx;
50 import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandTx;
51 import org.openhab.core.io.net.http.HttpUtil;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * This class makes the connection to the receiver and manages it.
57 * It is also responsible for sending commands to the receiver.
60 * @author Jeroen Idserda - Initial Contribution (1.x Binding)
61 * @author Jan-Willem Veldhuis - Refactored for 2.x
63 public class DenonMarantzHttpConnector extends DenonMarantzConnector {
65 private Logger logger = LoggerFactory.getLogger(DenonMarantzHttpConnector.class);
67 private static final int REQUEST_TIMEOUT_MS = 5000; // 5 seconds
69 // Main URL for the receiver
70 private static final String URL_MAIN = "formMainZone_MainZoneXml.xml";
72 // Main Zone Status URL
73 private static final String URL_ZONE_MAIN = "formMainZone_MainZoneXmlStatus.xml";
75 // Secondary zone lite status URL (contains less info)
76 private static final String URL_ZONE_SECONDARY_LITE = "formZone%d_Zone%dXmlStatusLite.xml";
79 private static final String URL_DEVICE_INFO = "Deviceinfo.xml";
81 // URL to send app commands to
82 private static final String URL_APP_COMMAND = "AppCommand.xml";
84 private static final String CONTENT_TYPE_XML = "application/xml";
86 private final String cmdUrl;
88 private final String statusUrl;
90 private final HttpClient httpClient;
92 private ScheduledFuture<?> pollingJob;
94 public DenonMarantzHttpConnector(DenonMarantzConfiguration config, DenonMarantzState state,
95 ScheduledExecutorService scheduler, HttpClient httpClient) {
97 this.scheduler = scheduler;
99 this.cmdUrl = String.format("http://%s:%d/goform/formiPhoneAppDirect.xml?", config.getHost(),
100 config.getHttpPort());
101 this.statusUrl = String.format("http://%s:%d/goform/", config.getHost(), config.getHttpPort());
102 this.httpClient = httpClient;
105 public DenonMarantzState getState() {
110 * Set up the connection to the receiver by starting to poll the HTTP API.
113 public void connect() {
115 logger.debug("HTTP polling started.");
117 setConfigProperties();
118 } catch (IOException e) {
119 logger.debug("IO error while retrieving document:", e);
120 state.connectionError("IO error while connecting to AVR: " + e.getMessage());
124 pollingJob = scheduler.scheduleWithFixedDelay(() -> {
126 refreshHttpProperties();
127 } catch (IOException e) {
128 logger.debug("IO error while retrieving document", e);
129 state.connectionError("IO error while connecting to AVR: " + e.getMessage());
131 } catch (RuntimeException e) {
133 * We need to catch this RuntimeException, as otherwise the polling stops.
134 * Log as error as it could be a user configuration error.
136 StringBuilder sb = new StringBuilder();
137 for (StackTraceElement s : e.getStackTrace()) {
138 sb.append(s.toString()).append("\n");
140 logger.error("Error while polling Http: \"{}\". Stacktrace: \n{}", e.getMessage(), sb.toString());
142 }, 0, config.httpPollingInterval, TimeUnit.SECONDS);
146 private boolean isPolling() {
147 return pollingJob != null && !pollingJob.isCancelled();
150 private void stopPolling() {
152 pollingJob.cancel(true);
153 logger.debug("HTTP polling stopped.");
158 * Shutdown the http client
161 public void dispose() {
162 logger.debug("disposing connector");
168 protected void internalSendCommand(String command) {
169 logger.debug("Sending command '{}'", command);
170 if (command == null || command.isBlank()) {
171 logger.warn("Trying to send empty command");
176 String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName());
177 logger.trace("Calling url {}", url);
179 httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() {
181 public void onComplete(Result result) {
182 if (result.getResponse().getStatus() != 200) {
183 logger.warn("Error {} while sending command", result.getResponse().getReason());
188 } catch (UnsupportedEncodingException e) {
189 logger.warn("Error sending command", e);
193 private void updateMain() throws IOException {
194 String url = statusUrl + URL_MAIN;
195 logger.trace("Refreshing URL: {}", url);
197 Main statusMain = getDocument(url, Main.class);
198 if (statusMain != null) {
199 state.setPower(statusMain.getPower().getValue());
203 private void updateMainZone() throws IOException {
204 String url = statusUrl + URL_ZONE_MAIN;
205 logger.trace("Refreshing URL: {}", url);
207 ZoneStatus mainZone = getDocument(url, ZoneStatus.class);
208 if (mainZone != null) {
209 state.setInput(mainZone.getInputFuncSelect().getValue());
210 state.setMainVolume(mainZone.getMasterVolume().getValue());
211 state.setMainZonePower(mainZone.getPower().getValue());
212 state.setMute(mainZone.getMute().getValue());
214 if (config.inputOptions == null) {
215 config.inputOptions = mainZone.getInputFuncList();
218 if (mainZone.getSurrMode() == null) {
219 logger.debug("Unable to get the SURROUND_MODE. MainZone update may not be correct.");
221 state.setSurroundProgram(mainZone.getSurrMode().getValue());
226 private void updateSecondaryZones() throws IOException {
227 for (int i = 2; i <= config.getZoneCount(); i++) {
228 String url = String.format("%s" + URL_ZONE_SECONDARY_LITE, statusUrl, i, i);
229 logger.trace("Refreshing URL: {}", url);
230 ZoneStatusLite zoneSecondary = getDocument(url, ZoneStatusLite.class);
231 if (zoneSecondary != null) {
233 // maximum 2 secondary zones are supported
235 state.setZone2Power(zoneSecondary.getPower().getValue());
236 state.setZone2Volume(zoneSecondary.getMasterVolume().getValue());
237 state.setZone2Mute(zoneSecondary.getMute().getValue());
238 state.setZone2Input(zoneSecondary.getInputFuncSelect().getValue());
241 state.setZone3Power(zoneSecondary.getPower().getValue());
242 state.setZone3Volume(zoneSecondary.getMasterVolume().getValue());
243 state.setZone3Mute(zoneSecondary.getMute().getValue());
244 state.setZone3Input(zoneSecondary.getInputFuncSelect().getValue());
247 state.setZone4Power(zoneSecondary.getPower().getValue());
248 state.setZone4Volume(zoneSecondary.getMasterVolume().getValue());
249 state.setZone4Mute(zoneSecondary.getMute().getValue());
250 state.setZone4Input(zoneSecondary.getInputFuncSelect().getValue());
257 private void updateDisplayInfo() throws IOException {
258 String url = statusUrl + URL_APP_COMMAND;
259 logger.trace("Refreshing URL: {}", url);
261 AppCommandRequest request = AppCommandRequest.of(CommandTx.CMD_NET_STATUS);
262 AppCommandResponse response = postDocument(url, AppCommandResponse.class, request);
264 if (response != null) {
265 CommandRx titleInfo = response.getCommands().get(0);
266 state.setNowPlayingArtist(titleInfo.getText("artist"));
267 state.setNowPlayingAlbum(titleInfo.getText("album"));
268 state.setNowPlayingTrack(titleInfo.getText("track"));
272 private boolean setConfigProperties() throws IOException {
273 String url = statusUrl + URL_DEVICE_INFO;
274 logger.debug("Refreshing URL: {}", url);
276 Deviceinfo deviceinfo = getDocument(url, Deviceinfo.class);
277 if (deviceinfo != null) {
278 config.setZoneCount(deviceinfo.getDeviceZones());
282 * The maximum volume is received from the telnet connection in the
283 * form of the MVMAX property. It is not always received reliable however,
284 * so we're using a default for now.
286 config.setMainVolumeMax(DenonMarantzConfiguration.MAX_VOLUME);
288 // if deviceinfo is null, something went wrong (and is logged in getDocument catch blocks)
289 return (deviceinfo != null);
292 private void refreshHttpProperties() throws IOException {
293 logger.trace("Refreshing Denon status");
297 updateSecondaryZones();
302 private <T> T getDocument(String uri, Class<T> response) throws IOException {
304 String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS);
305 logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result);
307 if (result != null && !result.isBlank()) {
308 JAXBContext jc = JAXBContext.newInstance(response);
309 XMLInputFactory xif = XMLInputFactory.newInstance();
310 xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
311 xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
312 XMLStreamReader xsr = xif
313 .createXMLStreamReader(new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8)));
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()
348 .unmarshal(new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8)));
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());