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.nuvo.internal.handler;
15 import static org.eclipse.jetty.http.HttpMethod.GET;
16 import static org.eclipse.jetty.http.HttpStatus.OK_200;
17 import static org.openhab.binding.nuvo.internal.NuvoBindingConstants.*;
19 import java.io.StringReader;
20 import java.math.BigDecimal;
21 import java.text.SimpleDateFormat;
22 import java.util.ArrayList;
23 import java.util.Base64;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.TreeMap;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.ScheduledFuture;
34 import java.util.concurrent.TimeUnit;
35 import java.util.concurrent.TimeoutException;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import java.util.stream.Collectors;
39 import java.util.stream.IntStream;
41 import javax.measure.Unit;
42 import javax.measure.quantity.Time;
43 import javax.xml.bind.JAXBContext;
44 import javax.xml.bind.JAXBException;
45 import javax.xml.bind.Unmarshaller;
46 import javax.xml.stream.XMLStreamException;
47 import javax.xml.stream.XMLStreamReader;
49 import org.eclipse.jdt.annotation.NonNullByDefault;
50 import org.eclipse.jdt.annotation.Nullable;
51 import org.eclipse.jetty.client.HttpClient;
52 import org.eclipse.jetty.client.api.ContentResponse;
53 import org.openhab.binding.nuvo.internal.NuvoException;
54 import org.openhab.binding.nuvo.internal.NuvoStateDescriptionOptionProvider;
55 import org.openhab.binding.nuvo.internal.NuvoThingActions;
56 import org.openhab.binding.nuvo.internal.communication.NuvoCommand;
57 import org.openhab.binding.nuvo.internal.communication.NuvoConnector;
58 import org.openhab.binding.nuvo.internal.communication.NuvoDefaultConnector;
59 import org.openhab.binding.nuvo.internal.communication.NuvoEnum;
60 import org.openhab.binding.nuvo.internal.communication.NuvoImageResizer;
61 import org.openhab.binding.nuvo.internal.communication.NuvoIpConnector;
62 import org.openhab.binding.nuvo.internal.communication.NuvoMessageEvent;
63 import org.openhab.binding.nuvo.internal.communication.NuvoMessageEventListener;
64 import org.openhab.binding.nuvo.internal.communication.NuvoSerialConnector;
65 import org.openhab.binding.nuvo.internal.communication.NuvoStatusCodes;
66 import org.openhab.binding.nuvo.internal.configuration.NuvoThingConfiguration;
67 import org.openhab.binding.nuvo.internal.dto.JAXBUtils;
68 import org.openhab.binding.nuvo.internal.dto.NuvoMenu;
69 import org.openhab.binding.nuvo.internal.dto.NuvoMenu.Source.TopMenu;
70 import org.openhab.core.io.transport.serial.SerialPortManager;
71 import org.openhab.core.library.types.DecimalType;
72 import org.openhab.core.library.types.NextPreviousType;
73 import org.openhab.core.library.types.OnOffType;
74 import org.openhab.core.library.types.OpenClosedType;
75 import org.openhab.core.library.types.PercentType;
76 import org.openhab.core.library.types.PlayPauseType;
77 import org.openhab.core.library.types.QuantityType;
78 import org.openhab.core.library.types.RawType;
79 import org.openhab.core.library.types.StringType;
80 import org.openhab.core.library.unit.Units;
81 import org.openhab.core.thing.Channel;
82 import org.openhab.core.thing.ChannelUID;
83 import org.openhab.core.thing.Thing;
84 import org.openhab.core.thing.ThingStatus;
85 import org.openhab.core.thing.ThingStatusDetail;
86 import org.openhab.core.thing.binding.BaseThingHandler;
87 import org.openhab.core.thing.binding.ThingHandlerService;
88 import org.openhab.core.types.Command;
89 import org.openhab.core.types.State;
90 import org.openhab.core.types.StateOption;
91 import org.openhab.core.types.UnDefType;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
96 * The {@link NuvoHandler} is responsible for handling commands, which are sent to one of the channels.
98 * Based on the Rotel binding by Laurent Garnier
100 * @author Michael Lobstein - Initial contribution
103 public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventListener {
104 private static final long RECON_POLLING_INTERVAL_SEC = 60;
105 private static final long POLLING_INTERVAL_SEC = 30;
106 private static final long CLOCK_SYNC_INTERVAL_SEC = 3600;
107 private static final long INITIAL_POLLING_DELAY_SEC = 30;
108 private static final long INITIAL_CLOCK_SYNC_DELAY_SEC = 10;
109 private static final long PING_TIMEOUT_SEC = 60;
110 // spec says wait 50ms, min is 100
111 private static final long SLEEP_BETWEEN_CMD_MS = 100;
112 private static final Unit<Time> API_SECOND_UNIT = Units.SECOND;
114 private static final String ZONE = "ZONE";
115 private static final String SOURCE = "SOURCE";
116 private static final String CHANNEL_DELIMIT = "#";
117 private static final String UNDEF = "UNDEF";
118 private static final String GC_STR = "NV-I8G";
120 private static final int MAX_ZONES = 20;
121 private static final int MAX_SRC = 6;
122 private static final int MAX_FAV = 12;
123 private static final int MIN_VOLUME = 0;
124 private static final int MAX_VOLUME = 79;
125 private static final int MIN_EQ = -18;
126 private static final int MAX_EQ = 18;
128 private static final int MPS4_PORT = 5006;
130 private static final byte[] NO_ART = { 0 };
132 private static final Pattern ZONE_PATTERN = Pattern
133 .compile("^ON,SRC(\\d{1}),(MUTE|VOL\\d{1,2}),DND([0-1]),LOCK([0-1])$");
134 private static final Pattern DISP_PATTERN = Pattern.compile("^DISPLINE(\\d{1}),\"(.*)\"$");
135 private static final Pattern DISP_INFO_PATTERN = Pattern
136 .compile("^DISPINFO,DUR(\\d{1,6}),POS(\\d{1,6}),STATUS(\\d{1,2})$");
137 private static final Pattern ZONE_CFG_EQ_PATTERN = Pattern.compile("^BASS(.*),TREB(.*),BAL(.*),LOUDCMP([0-1])$");
138 private static final Pattern ZONE_CFG_PATTERN = Pattern.compile(
139 "^ENABLE1,NAME\"(.*)\",SLAVETO(.*),GROUP([0-4]),SOURCES(.*),XSRC(.*),IR(.*),DND(.*),LOCKED(.*),SLAVEEQ(.*)$");
141 private final Logger logger = LoggerFactory.getLogger(NuvoHandler.class);
142 private final NuvoStateDescriptionOptionProvider stateDescriptionProvider;
143 private final SerialPortManager serialPortManager;
144 private final HttpClient httpClient;
146 private @Nullable ScheduledFuture<?> reconnectJob;
147 private @Nullable ScheduledFuture<?> pollingJob;
148 private @Nullable ScheduledFuture<?> clockSyncJob;
149 private @Nullable ScheduledFuture<?> pingJob;
151 private NuvoConnector connector = new NuvoDefaultConnector();
152 private long lastEventReceived = System.currentTimeMillis();
153 private int numZones = 1;
154 private String versionString = BLANK;
155 private boolean isGConcerto = false;
156 private Object sequenceLock = new Object();
158 private boolean isAnyOhNuvoNet = false;
159 private NuvoMenu nuvoMenus = new NuvoMenu();
160 private HashMap<String, Set<String>> nuvoGroupMap = new HashMap<String, Set<String>>();
161 private HashMap<String, Integer> nuvoNetSrcMap = new HashMap<String, Integer>();
162 private HashMap<String, String> favPrefixMap = new HashMap<String, String>();
163 private HashMap<String, String[]> favoriteMap = new HashMap<String, String[]>();
165 private HashMap<String, byte[]> albumArtMap = new HashMap<String, byte[]>();
166 private HashMap<String, Integer> albumArtIds = new HashMap<String, Integer>();
167 private HashMap<String, String> dispInfoCache = new HashMap<String, String>();
169 Set<Integer> activeZones = new HashSet<>(1);
171 // A tree map that maps the source ids to source labels
172 TreeMap<String, String> sourceLabels = new TreeMap<String, String>();
174 // Indicates if there is a need to poll status because of a disconnection used for MPS4 systems
175 boolean pollStatusNeeded = true;
176 boolean isMps4 = false;
181 public NuvoHandler(Thing thing, NuvoStateDescriptionOptionProvider stateDescriptionProvider,
182 SerialPortManager serialPortManager, HttpClient httpClient) {
184 this.stateDescriptionProvider = stateDescriptionProvider;
185 this.serialPortManager = serialPortManager;
186 this.httpClient = httpClient;
190 public void initialize() {
191 final String uid = this.getThing().getUID().getAsString();
192 NuvoThingConfiguration config = getConfigAs(NuvoThingConfiguration.class);
193 final String serialPort = config.serialPort;
194 final String host = config.host;
195 final Integer port = config.port;
196 final Integer numZones = config.numZones;
198 // Check configuration settings
199 String configError = null;
200 if ((serialPort == null || serialPort.isEmpty()) && (host == null || host.isEmpty())) {
201 configError = "undefined serialPort and host configuration settings; please set one of them";
202 } else if (serialPort != null && (host == null || host.isEmpty())) {
203 if (serialPort.toLowerCase().startsWith("rfc2217")) {
204 configError = "use host and port configuration settings for a serial over IP connection";
208 configError = "undefined port configuration setting";
209 } else if (port <= 0) {
210 configError = "invalid port configuration setting";
214 if (configError != null) {
215 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError);
219 if (serialPort != null && !serialPort.isEmpty()) {
220 connector = new NuvoSerialConnector(serialPortManager, serialPort, uid);
221 } else if (host != null && port != null) {
222 connector = new NuvoIpConnector(host, port, uid);
223 this.isMps4 = (port.intValue() == MPS4_PORT);
225 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
226 "Either Serial port or Host & Port must be specifed");
230 nuvoNetSrcMap.put("1", config.nuvoNetSrc1);
231 nuvoNetSrcMap.put("2", config.nuvoNetSrc2);
232 nuvoNetSrcMap.put("3", config.nuvoNetSrc3);
233 nuvoNetSrcMap.put("4", config.nuvoNetSrc4);
234 nuvoNetSrcMap.put("5", config.nuvoNetSrc5);
235 nuvoNetSrcMap.put("6", config.nuvoNetSrc6);
237 nuvoGroupMap.put("1", new HashSet<String>());
238 nuvoGroupMap.put("2", new HashSet<String>());
239 nuvoGroupMap.put("3", new HashSet<String>());
240 nuvoGroupMap.put("4", new HashSet<String>());
243 logger.debug("Port set to {} configuring binding for MPS4 compatability", MPS4_PORT);
245 this.isAnyOhNuvoNet = (config.nuvoNetSrc1 == 2 || config.nuvoNetSrc2 == 2 || config.nuvoNetSrc3 == 2
246 || config.nuvoNetSrc4 == 2 || config.nuvoNetSrc5 == 2 || config.nuvoNetSrc6 == 2);
248 if (this.isAnyOhNuvoNet) {
249 logger.debug("At least one source is configured as an openHAB NuvoNet source");
250 connector.setAnyOhNuvoNet(true);
251 loadMenuConfiguration(config);
254 !config.favoritesSrc1.isEmpty() ? config.favoritesSrc1.split(COMMA) : new String[0]);
256 !config.favoritesSrc2.isEmpty() ? config.favoritesSrc2.split(COMMA) : new String[0]);
258 !config.favoritesSrc3.isEmpty() ? config.favoritesSrc3.split(COMMA) : new String[0]);
260 !config.favoritesSrc4.isEmpty() ? config.favoritesSrc4.split(COMMA) : new String[0]);
262 !config.favoritesSrc5.isEmpty() ? config.favoritesSrc5.split(COMMA) : new String[0]);
264 !config.favoritesSrc6.isEmpty() ? config.favoritesSrc6.split(COMMA) : new String[0]);
266 favPrefixMap.put("1", config.favPrefix1);
267 favPrefixMap.put("2", config.favPrefix2);
268 favPrefixMap.put("3", config.favPrefix3);
269 favPrefixMap.put("4", config.favPrefix4);
270 favPrefixMap.put("5", config.favPrefix5);
271 favPrefixMap.put("6", config.favPrefix6);
273 albumArtIds.put("S1", 0);
274 albumArtIds.put("S2", 0);
275 albumArtIds.put("S3", 0);
276 albumArtIds.put("S4", 0);
277 albumArtIds.put("S5", 0);
278 albumArtIds.put("S6", 0);
280 albumArtMap.put("S1", NO_ART);
281 albumArtMap.put("S2", NO_ART);
282 albumArtMap.put("S3", NO_ART);
283 albumArtMap.put("S4", NO_ART);
284 albumArtMap.put("S5", NO_ART);
285 albumArtMap.put("S6", NO_ART);
289 if (numZones != null) {
290 this.numZones = numZones;
293 activeZones = IntStream.range((1), (this.numZones + 1)).boxed().collect(Collectors.toSet());
295 // remove the channels for the zones we are not using
296 if (this.numZones < MAX_ZONES) {
297 List<Channel> channels = new ArrayList<>(this.getThing().getChannels());
299 List<Integer> zonesToRemove = IntStream.range((this.numZones + 1), (MAX_ZONES + 1)).boxed()
300 .collect(Collectors.toList());
302 zonesToRemove.forEach(zone -> channels.removeIf(c -> (c.getUID().getId().contains("zone" + zone))));
303 updateThing(editThing().withChannels(channels).build());
306 // Build a list of State options for the global favorites using user config values (if supplied)
307 String[] favoritesArr = !config.favoriteLabels.isEmpty() ? config.favoriteLabels.split(COMMA) : new String[0];
308 List<StateOption> favoriteLabelsStateOptions = new ArrayList<>();
309 for (int i = 0; i < 12; i++) {
310 if (favoritesArr.length > i) {
311 favoriteLabelsStateOptions.add(new StateOption(String.valueOf(i + 1), favoritesArr[i]));
312 } else if (favoritesArr.length == 0) {
313 favoriteLabelsStateOptions.add(new StateOption(String.valueOf(i + 1), "Favorite " + (i + 1)));
317 // Put the global favorites labels on all active zones
318 activeZones.forEach(zoneNum -> {
319 stateDescriptionProvider.setStateOptions(
320 new ChannelUID(getThing().getUID(),
321 ZONE.toLowerCase() + zoneNum + CHANNEL_DELIMIT + CHANNEL_TYPE_FAVORITE),
322 favoriteLabelsStateOptions);
325 if (config.clockSync) {
326 scheduleClockSyncJob();
329 scheduleReconnectJob();
330 schedulePollingJob();
331 schedulePingTimeoutJob();
332 updateStatus(ThingStatus.UNKNOWN);
336 public void dispose() {
337 if (this.isAnyOhNuvoNet) {
339 // disable NuvoNet for each source that was configured as an openHAB NuvoNet source
340 nuvoNetSrcMap.forEach((srcNum, val) -> {
343 connector.sendCommand(SRC_KEY + srcNum + "DISPINFOTWO0,0,0,0,0,0,0");
344 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
345 connector.sendCommand(
346 SRC_KEY + srcNum + "DISPLINES0,0,0,\"Source Unavailable\",\"\",\"\",\"\"");
347 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
348 connector.sendCommand("SCFG" + srcNum + "NUVONET0");
349 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
350 } catch (NuvoException | InterruptedException e) {
351 logger.debug("Error sending command to disable NuvoNet source: {}", srcNum);
356 // need '1' flag for sources configured as an MPS4 NuvoNet source, but disable openHAB NuvoNet sources
357 connector.sendCommand("SNUMBERS" + (nuvoNetSrcMap.get("1") == 1 ? ONE : ZERO) + COMMA
358 + (nuvoNetSrcMap.get("2") == 1 ? ONE : ZERO) + COMMA
359 + (nuvoNetSrcMap.get("3") == 1 ? ONE : ZERO) + COMMA
360 + (nuvoNetSrcMap.get("4") == 1 ? ONE : ZERO) + COMMA
361 + (nuvoNetSrcMap.get("5") == 1 ? ONE : ZERO) + COMMA
362 + (nuvoNetSrcMap.get("6") == 1 ? ONE : ZERO));
363 } catch (NuvoException e) {
364 logger.debug("Error sending SNUMBERS command to disable NuvoNet sources");
368 cancelReconnectJob();
370 cancelClockSyncJob();
371 cancelPingTimeoutJob();
377 public Collection<Class<? extends ThingHandlerService>> getServices() {
378 return Collections.singletonList(NuvoThingActions.class);
381 public void handleRawCommand(@Nullable String command) {
382 synchronized (sequenceLock) {
384 connector.sendCommand(command);
385 } catch (NuvoException e) {
386 logger.warn("Nuvo Command: {} failed", command);
392 * Handle a command from the UI
394 * @param channelUID the channel sending the command
395 * @param command the command received
399 public void handleCommand(ChannelUID channelUID, Command command) {
400 String channel = channelUID.getId();
401 String[] channelSplit = channel.split(CHANNEL_DELIMIT);
402 NuvoEnum target = NuvoEnum.valueOf(channelSplit[0].toUpperCase());
404 String channelType = channelSplit[1];
406 if (getThing().getStatus() != ThingStatus.ONLINE) {
407 logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel);
411 synchronized (sequenceLock) {
412 if (!connector.isConnected()) {
413 logger.warn("Command {} from channel {} is ignored: connection not established", command, channel);
418 switch (channelType) {
419 case CHANNEL_TYPE_POWER:
420 if (command instanceof OnOffType) {
421 connector.sendCommand(target, command == OnOffType.ON ? NuvoCommand.ON : NuvoCommand.OFF);
424 case CHANNEL_TYPE_SOURCE:
425 if (command instanceof DecimalType) {
426 int value = ((DecimalType) command).intValue();
427 if (value >= 1 && value <= MAX_SRC) {
428 logger.debug("Got source command {} zone {}", value, target);
429 connector.sendCommand(target, NuvoCommand.SOURCE, String.valueOf(value));
433 case CHANNEL_TYPE_FAVORITE:
434 if (command instanceof DecimalType) {
435 int value = ((DecimalType) command).intValue();
436 if (value >= 1 && value <= MAX_FAV) {
437 logger.debug("Got favorite command {} zone {}", value, target);
438 connector.sendCommand(target, NuvoCommand.FAVORITE, String.valueOf(value));
442 case CHANNEL_TYPE_VOLUME:
443 if (command instanceof PercentType) {
444 int value = (MAX_VOLUME
446 ((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME))
448 logger.debug("Got volume command {} zone {}", value, target);
449 connector.sendCommand(target, NuvoCommand.VOLUME, String.valueOf(value));
452 case CHANNEL_TYPE_MUTE:
453 if (command instanceof OnOffType) {
454 connector.sendCommand(target,
455 command == OnOffType.ON ? NuvoCommand.MUTE_ON : NuvoCommand.MUTE_OFF);
458 case CHANNEL_TYPE_TREBLE:
459 if (command instanceof DecimalType) {
460 int value = ((DecimalType) command).intValue();
461 if (value >= MIN_EQ && value <= MAX_EQ) {
462 // device can only accept even values
463 if (value % 2 == 1) {
466 logger.debug("Got treble command {} zone {}", value, target);
467 connector.sendCfgCommand(target, NuvoCommand.TREBLE, String.valueOf(value));
471 case CHANNEL_TYPE_BASS:
472 if (command instanceof DecimalType) {
473 int value = ((DecimalType) command).intValue();
474 if (value >= MIN_EQ && value <= MAX_EQ) {
475 if (value % 2 == 1) {
478 logger.debug("Got bass command {} zone {}", value, target);
479 connector.sendCfgCommand(target, NuvoCommand.BASS, String.valueOf(value));
483 case CHANNEL_TYPE_BALANCE:
484 if (command instanceof DecimalType) {
485 int value = ((DecimalType) command).intValue();
486 if (value >= MIN_EQ && value <= MAX_EQ) {
487 if (value % 2 == 1) {
490 logger.debug("Got balance command {} zone {}", value, target);
491 connector.sendCfgCommand(target, NuvoCommand.BALANCE,
492 NuvoStatusCodes.getBalanceFromInt(value));
496 case CHANNEL_TYPE_LOUDNESS:
497 if (command instanceof OnOffType) {
498 connector.sendCfgCommand(target, NuvoCommand.LOUDNESS,
499 command == OnOffType.ON ? ONE : ZERO);
502 case CHANNEL_TYPE_CONTROL:
503 handleControlCommand(target, command);
505 case CHANNEL_TYPE_DND:
506 if (command instanceof OnOffType) {
507 connector.sendCommand(target,
508 command == OnOffType.ON ? NuvoCommand.DND_ON : NuvoCommand.DND_OFF);
511 case CHANNEL_TYPE_PARTY:
512 if (command instanceof OnOffType) {
513 connector.sendCommand(target,
514 command == OnOffType.ON ? NuvoCommand.PARTY_ON : NuvoCommand.PARTY_OFF);
517 case CHANNEL_DISPLAY_LINE1:
518 if (command instanceof StringType) {
519 connector.sendCommand(target, NuvoCommand.DISPLINE1, "\"" + command + "\"");
522 case CHANNEL_DISPLAY_LINE2:
523 if (command instanceof StringType) {
524 connector.sendCommand(target, NuvoCommand.DISPLINE2, "\"" + command + "\"");
527 case CHANNEL_DISPLAY_LINE3:
528 if (command instanceof StringType) {
529 connector.sendCommand(target, NuvoCommand.DISPLINE3, "\"" + command + "\"");
532 case CHANNEL_DISPLAY_LINE4:
533 if (command instanceof StringType) {
534 connector.sendCommand(target, NuvoCommand.DISPLINE4, "\"" + command + "\"");
537 case CHANNEL_TYPE_ALLOFF:
538 if (command instanceof OnOffType) {
539 connector.sendCommand(NuvoCommand.ALLOFF);
542 case CHANNEL_TYPE_ALLMUTE:
543 if (command instanceof OnOffType) {
544 connector.sendCommand(
545 command == OnOffType.ON ? NuvoCommand.ALLMUTE_ON : NuvoCommand.ALLMUTE_OFF);
548 case CHANNEL_TYPE_PAGE:
549 if (command instanceof OnOffType) {
550 connector.sendCommand(command == OnOffType.ON ? NuvoCommand.PAGE_ON : NuvoCommand.PAGE_OFF);
553 case CHANNEL_TYPE_SENDCMD:
554 if (command instanceof StringType) {
555 String commandStr = command.toString();
556 if (commandStr.contains(DISP_INFO_TWO)) {
557 String sourceKey = commandStr.split(DISP_INFO_TWO)[0];
558 dispInfoCache.put(sourceKey, commandStr);
560 // if 'albumartid' is present, substitute it with the albumArtId hex string
561 connector.sendCommand(commandStr.replace(ALBUM_ART_ID,
562 (OFFSET_ZERO + Integer.toHexString(albumArtIds.get(sourceKey)))));
564 connector.sendCommand(commandStr);
568 case CHANNEL_ART_URL:
569 if (command instanceof StringType) {
570 String url = command.toString();
571 if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
573 ContentResponse contentResponse = httpClient.newRequest(url).method(GET)
574 .timeout(10, TimeUnit.SECONDS).send();
575 int httpStatus = contentResponse.getStatus();
576 if (httpStatus == OK_200) {
577 albumArtMap.put(target.getId(),
578 NuvoImageResizer.resizeImage(contentResponse.getContent(), 80, 80));
580 updateChannelState(target, CHANNEL_ALBUM_ART, BLANK,
581 contentResponse.getContent());
583 albumArtMap.put(target.getId(), NO_ART);
584 albumArtIds.put(target.getId(), 0);
585 updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
588 } catch (InterruptedException | TimeoutException | ExecutionException e) {
589 albumArtMap.put(target.getId(), NO_ART);
590 albumArtIds.put(target.getId(), 0);
591 updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
594 albumArtIds.put(target.getId(), Math.abs(url.hashCode()));
596 // re-send the cached DISPINFOTWO message, substituting in the new albumArtId
597 if (dispInfoCache.get(target.getId()) != null) {
598 connector.sendCommand(dispInfoCache.get(target.getId()).replace(ALBUM_ART_ID,
599 (OFFSET_ZERO + Integer.toHexString(albumArtIds.get(target.getId())))));
602 albumArtMap.put(target.getId(), NO_ART);
603 albumArtIds.put(target.getId(), 0);
604 updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
608 } catch (NuvoException e) {
609 logger.warn("Command {} from channel {} failed: {}", command, channel, e.getMessage());
610 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Sending command failed");
612 scheduleReconnectJob();
618 * Open the connection with the Nuvo device
620 * @return true if the connection is opened successfully or false if not
622 private synchronized boolean openConnection() {
623 connector.addEventListener(this);
626 } catch (NuvoException e) {
627 logger.debug("openConnection() failed: {}", e.getMessage());
629 logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected");
630 return connector.isConnected();
634 * Close the connection with the Nuvo device
636 private synchronized void closeConnection() {
637 if (connector.isConnected()) {
639 connector.removeEventListener(this);
640 pollStatusNeeded = true;
641 logger.debug("closeConnection(): disconnected");
646 * Handle an event received from the Nuvo device
648 * @param event the event to process
651 public void onNewMessageEvent(NuvoMessageEvent evt) {
652 logger.debug("onNewMessageEvent: zone {}, source {}, value {}", evt.getZone(), evt.getSrc(), evt.getValue());
653 lastEventReceived = System.currentTimeMillis();
655 String type = evt.getType();
656 String zoneId = evt.getZone();
657 String srcId = evt.getSrc();
658 String updateData = evt.getValue().trim();
659 if (this.getThing().getStatus() != ThingStatus.ONLINE) {
660 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, this.versionString);
665 this.versionString = updateData;
666 // Determine if we are a Grand Concerto or not
667 if (this.versionString.contains(GC_STR)) {
668 logger.debug("Grand Concerto detected");
669 this.isGConcerto = true;
670 connector.setEssentia(false);
672 logger.debug("Grand Concerto not detected");
676 logger.debug("Restart message received; re-sending initialization messages");
677 enableNuvonet(false);
680 logger.debug("Ping message received- rescheduling ping timeout");
681 schedulePingTimeoutJob();
682 // Return here because receiving a ping does not indicate that one can poll
685 activeZones.forEach(zoneNum -> {
686 updateChannelState(NuvoEnum.valueOf(ZONE + zoneNum), CHANNEL_TYPE_POWER, OFF);
690 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_ALLMUTE, ONE.equals(updateData) ? ON : OFF);
691 activeZones.forEach(zoneNum -> {
692 updateChannelState(NuvoEnum.valueOf(ZONE + zoneNum), CHANNEL_TYPE_MUTE,
693 ONE.equals(updateData) ? ON : OFF);
697 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_PAGE, ONE.equals(updateData) ? ON : OFF);
699 case TYPE_SOURCE_UPDATE:
700 logger.debug("Source update: Source: {} - Value: {}", srcId, updateData);
701 NuvoEnum targetSource = NuvoEnum.valueOf(SOURCE + srcId);
703 if (updateData.contains(DISPLINE)) {
704 // example: DISPLINE2,"Play My Song (Featuring Dee Ajayi)"
705 Matcher matcher = DISP_PATTERN.matcher(updateData);
706 if (matcher.find()) {
707 updateChannelState(targetSource, CHANNEL_DISPLAY_LINE + matcher.group(1), matcher.group(2));
709 logger.debug("no match on message: {}", updateData);
711 } else if (updateData.contains(DISPINFO)) {
712 // example: DISPINFO,DUR0,POS70,STATUS2 (DUR and POS are expressed in tenths of a second)
713 // 6 places(tenths of a second)-> max 999,999 /10/60/60/24 = 1.15 days
714 Matcher matcher = DISP_INFO_PATTERN.matcher(updateData);
715 if (matcher.find()) {
716 updateChannelState(targetSource, CHANNEL_TRACK_LENGTH, matcher.group(1));
717 updateChannelState(targetSource, CHANNEL_TRACK_POSITION, matcher.group(2));
718 updateChannelState(targetSource, CHANNEL_PLAY_MODE, matcher.group(3));
720 logger.debug("no match on message: {}", updateData);
722 } else if (updateData.contains(NAME_QUOTE)) {
723 // example: NAME"Ipod"
724 String name = updateData.split("\"")[1];
725 sourceLabels.put(srcId, name);
728 case TYPE_ZONE_UPDATE:
729 logger.debug("Zone update: Zone: {} - Value: {}", zoneId, updateData);
731 // or: ON,SRC3,VOL63,DND0,LOCK0
732 // or: ON,SRC3,MUTE,DND0,LOCK0
734 NuvoEnum targetZone = NuvoEnum.valueOf(ZONE + zoneId);
736 if (OFF.equals(updateData)) {
737 updateChannelState(targetZone, CHANNEL_TYPE_POWER, OFF);
738 updateChannelState(targetZone, CHANNEL_TYPE_SOURCE, UNDEF);
740 Matcher matcher = ZONE_PATTERN.matcher(updateData);
741 if (matcher.find()) {
742 updateChannelState(targetZone, CHANNEL_TYPE_POWER, ON);
743 updateChannelState(targetZone, CHANNEL_TYPE_SOURCE, matcher.group(1));
745 // check if this zone is in a group, if so update the other group member's selected source
746 nuvoGroupMap.forEach((groupId, groupZones) -> {
747 if (groupZones.contains(zoneId)) {
748 groupZones.forEach(z -> {
749 if (!zoneId.equals(z)) {
750 updateChannelState(NuvoEnum.valueOf(ZONE + z), CHANNEL_TYPE_SOURCE,
757 if (MUTE.equals(matcher.group(2))) {
758 updateChannelState(targetZone, CHANNEL_TYPE_MUTE, ON);
760 updateChannelState(targetZone, CHANNEL_TYPE_MUTE, NuvoCommand.OFF.getValue());
761 updateChannelState(targetZone, CHANNEL_TYPE_VOLUME, matcher.group(2).replace(VOL, BLANK));
764 updateChannelState(targetZone, CHANNEL_TYPE_DND, ONE.equals(matcher.group(3)) ? ON : OFF);
765 updateChannelState(targetZone, CHANNEL_TYPE_LOCK, ONE.equals(matcher.group(4)) ? ON : OFF);
767 logger.debug("no match on message: {}", updateData);
771 case TYPE_ZONE_SOURCE_BUTTON:
772 logger.debug("Source Button pressed: Source: {} - Button: {}", srcId, updateData);
773 updateChannelState(NuvoEnum.valueOf(SOURCE + srcId), CHANNEL_BUTTON_PRESS, updateData);
774 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_BUTTONPRESS, zoneId + COMMA + updateData);
777 String buttonAction = NuvoStatusCodes.BUTTON_CODE.get(updateData);
779 if (buttonAction != null) {
780 logger.debug("NuvoNet Source Button pressed: Source: {} - Button: {}", srcId, buttonAction);
781 updateChannelState(NuvoEnum.valueOf(SOURCE + srcId), CHANNEL_BUTTON_PRESS, buttonAction);
782 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_BUTTONPRESS, zoneId + COMMA + buttonAction);
784 logger.debug("NuvoNet Source Button pressed: Source: {} - Unknown button code: {}", srcId,
786 updateChannelState(NuvoEnum.valueOf(SOURCE + srcId), CHANNEL_BUTTON_PRESS, updateData);
787 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_BUTTONPRESS, zoneId + COMMA + updateData);
790 case TYPE_NN_MENU_ITEM_SELECTED:
791 // ignore this update unless openHAB is handling this source
792 if (nuvoNetSrcMap.get(srcId).equals(2)) {
793 String sourceZone = SRC_KEY + srcId + ZONE_KEY + zoneId;
794 String[] updateDataSplit = updateData.split(COMMA);
795 String menuId = updateDataSplit[0];
796 int menuItemIdx = Integer.parseInt(updateDataSplit[1]) - 1;
798 boolean exitMenu = false;
799 if ("0xFFFFFFFF".equals(menuId)) {
800 TopMenu topMenuItem = nuvoMenus.getSource().get(Integer.parseInt(srcId) - 1).getTopMenu()
802 logger.debug("Top Menu item selected: Source: {} - Menu Item: {}", srcId,
803 topMenuItem.getText());
804 updateChannelState(NuvoEnum.valueOf(SOURCE + srcId), CHANNEL_BUTTON_PRESS,
805 topMenuItem.getText());
806 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_BUTTONPRESS,
807 zoneId + COMMA + topMenuItem.getText());
809 List<String> subMenuItems = topMenuItem.getItems();
811 if (subMenuItems.isEmpty()) {
814 // send submenu (maximum of 20 items)
815 int subMenuSize = subMenuItems.size() < 20 ? subMenuItems.size() : 20;
817 connector.sendCommand(sourceZone + "MENU" + (menuItemIdx + 11) + ",0,0," + subMenuSize
818 + ",0,0," + subMenuSize + ",\"" + topMenuItem.getText() + "\"");
819 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
821 for (int i = 0; i < subMenuSize; i++) {
822 connector.sendCommand(
823 sourceZone + "MENUITEM" + (i + 1) + ",0,0,\"" + subMenuItems.get(i) + "\"");
825 } catch (NuvoException | InterruptedException e) {
826 logger.debug("Error sending sub menu to {}", sourceZone);
830 // a sub menu item was selected
831 TopMenu topMenuItem = nuvoMenus.getSource().get(Integer.parseInt(srcId) - 1).getTopMenu()
832 .get(Integer.decode(menuId) - 11);
833 String subMenuItem = topMenuItem.getItems().get(menuItemIdx);
835 logger.debug("Sub Menu item selected: Source: {} - Menu Item: {}", srcId,
836 topMenuItem.getText() + "|" + subMenuItem);
837 updateChannelState(NuvoEnum.valueOf(SOURCE + srcId), CHANNEL_BUTTON_PRESS,
838 topMenuItem.getText() + "|" + subMenuItem);
839 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_BUTTONPRESS,
840 zoneId + COMMA + topMenuItem.getText() + "|" + subMenuItem);
846 // tell the zone to exit the menu
847 connector.sendCommand(sourceZone + "MENU0,0,0,0,0,0,0,\"\"");
848 } catch (NuvoException e) {
849 logger.debug("Error sending exit menu command to {}", sourceZone);
854 case TYPE_NN_MENUREQ:
855 // ignore this update unless openHAB is handling this source
856 if (nuvoNetSrcMap.get(srcId).equals(2)) {
857 logger.debug("Menu Request: Source: {} - Value: {}", srcId, updateData);
858 String sourceZone = SRC_KEY + srcId + ZONE_KEY + zoneId;
859 // For now we only support one level deep menus. If second field is '1', indicates go back to main
861 String[] menuDataSplit = updateData.split(COMMA);
862 if (menuDataSplit.length > 2 && ONE.equals(menuDataSplit[1])) {
864 connector.sendCommand(sourceZone + "MENU0xFFFFFFFF,0,0,0,0,0,0,\"\"");
865 } catch (NuvoException e) {
866 logger.debug("Error sending main menu command to {}", sourceZone);
871 case TYPE_ZONE_CONFIG:
872 logger.debug("Zone Configuration: Zone: {} - Value: {}", zoneId, updateData);
873 // example: BASS1,TREB-2,BALR2,LOUDCMP1
874 Matcher matcher = ZONE_CFG_EQ_PATTERN.matcher(updateData);
875 if (matcher.find()) {
876 updateChannelState(NuvoEnum.valueOf(ZONE + zoneId), CHANNEL_TYPE_BASS, matcher.group(1));
877 updateChannelState(NuvoEnum.valueOf(ZONE + zoneId), CHANNEL_TYPE_TREBLE, matcher.group(2));
878 updateChannelState(NuvoEnum.valueOf(ZONE + zoneId), CHANNEL_TYPE_BALANCE,
879 NuvoStatusCodes.getBalanceFromStr(matcher.group(3)));
880 updateChannelState(NuvoEnum.valueOf(ZONE + zoneId), CHANNEL_TYPE_LOUDNESS,
881 ONE.equals(matcher.group(4)) ? ON : OFF);
883 matcher = ZONE_CFG_PATTERN.matcher(updateData);
884 // example: ENABLE1,NAME"Great Room",SLAVETO0,GROUP1,SOURCES63,XSRC0,IR1,DND0,LOCKED0,SLAVEEQ0
885 if (matcher.find()) {
886 // TODO: utilize other info such as zone name, available sources bitmask, etc.
888 // if this zone is a member of a group (1-4), add the zone's id to the appropriate group map
889 if (!ZERO.equals(matcher.group(3))) {
890 nuvoGroupMap.get(matcher.group(3)).add(zoneId);
893 logger.debug("no match on message: {}", updateData);
897 case TYPE_NN_ALBUM_ART_REQ:
898 // ignore this update unless openHAB is handling this source
899 if (nuvoNetSrcMap.get(srcId).equals(2)) {
900 logger.debug("Album Art Request for Source: {} - Data: {}", srcId, updateData);
901 // 0x620FD879,80,80,2,0x00C0C0C0,0,0,0,0,1
902 String[] albumArtReq = updateData.split(COMMA);
903 albumArtIds.put(SRC_KEY + srcId, Integer.decode(albumArtReq[0]));
906 if (albumArtMap.get(SRC_KEY + srcId).length > 1) {
907 connector.sendCommand(
908 SRC_KEY + srcId + ALBUM_ART_AVAILABLE + albumArtIds.get(SRC_KEY + srcId) + COMMA
909 + albumArtMap.get(SRC_KEY + srcId).length);
911 connector.sendCommand(SRC_KEY + srcId + ALBUM_ART_AVAILABLE + ZERO_COMMA);
913 } catch (NuvoException e) {
914 logger.debug("Error sending ALBUMARTAVAILABLE command for source: {}", srcId);
918 case TYPE_NN_ALBUM_ART_FRAG_REQ:
919 // ignore this update unless openHAB is handling this source
920 if (nuvoNetSrcMap.get(srcId).equals(2)) {
921 logger.debug("Album Art Fragment Request for Source: {} - Data: {}", srcId, updateData);
922 // 0x620FD879,0,750 (id, requested offset from start of image, byte length requested)
923 String[] albumArtFragReq = updateData.split(COMMA);
924 int requestedId = Integer.decode(albumArtFragReq[0]);
925 int offset = Integer.parseInt(albumArtFragReq[1]);
926 int length = Integer.parseInt(albumArtFragReq[2]);
928 if (requestedId == albumArtIds.get(SRC_KEY + srcId)) {
929 byte[] chunk = new byte[length];
930 byte[] albumArtBytes = albumArtMap.get(SRC_KEY + srcId);
932 if (albumArtBytes != null) {
933 System.arraycopy(albumArtBytes, offset, chunk, 0, length);
934 final String frag = Base64.getEncoder().encodeToString(chunk);
936 connector.sendCommand(SRC_KEY + srcId + ALBUM_ART_FRAG + requestedId + COMMA + offset
937 + COMMA + frag.length() + COMMA + frag);
938 } catch (NuvoException e) {
939 logger.debug("Error sending ALBUMARTFRAG command for source: {}, artId: {}", srcId,
946 case TYPE_NN_FAVORITE_REQ:
947 // ignore this update unless openHAB is handling this source
948 if (nuvoNetSrcMap.get(srcId).equals(2)) {
949 logger.debug("Favorite request for source: {} - favoriteId: {}", srcId, updateData);
951 int playlistIdx = Integer.parseInt(updateData, 16) - 1000;
952 updateChannelState(NuvoEnum.valueOf(SOURCE + srcId), CHANNEL_BUTTON_PRESS,
953 "PLAY_MUSIC_PRESET:" + favoriteMap.get(srcId)[playlistIdx]);
954 } catch (NumberFormatException nfe) {
955 logger.debug("Unable to parse favoriteId: {}", updateData);
960 logger.debug("onNewMessageEvent: unhandled event type {}", type);
961 // Return here because receiving an unknown message does not indicate that one can poll
965 if (isMps4 && pollStatusNeeded) {
970 private void loadMenuConfiguration(NuvoThingConfiguration config) {
971 StringBuilder menuXml = new StringBuilder("<menu>");
973 if (!config.menuXmlSrc1.isEmpty()) {
974 menuXml.append("<source>" + config.menuXmlSrc1 + "</source>");
976 menuXml.append("<source/>");
978 if (!config.menuXmlSrc2.isEmpty()) {
979 menuXml.append("<source>" + config.menuXmlSrc2 + "</source>");
981 menuXml.append("<source/>");
983 if (!config.menuXmlSrc3.isEmpty()) {
984 menuXml.append("<source>" + config.menuXmlSrc3 + "</source>");
986 menuXml.append("<source/>");
988 if (!config.menuXmlSrc4.isEmpty()) {
989 menuXml.append("<source>" + config.menuXmlSrc4 + "</source>");
991 menuXml.append("<source/>");
993 if (!config.menuXmlSrc5.isEmpty()) {
994 menuXml.append("<source>" + config.menuXmlSrc5 + "</source>");
996 menuXml.append("<source/>");
998 if (!config.menuXmlSrc6.isEmpty()) {
999 menuXml.append("<source>" + config.menuXmlSrc6 + "</source>");
1001 menuXml.append("<source/>");
1003 menuXml.append("</menu>");
1006 JAXBContext ctx = JAXBUtils.JAXBCONTEXT_NUVO_MENU;
1008 Unmarshaller unmarshaller = ctx.createUnmarshaller();
1009 if (unmarshaller != null) {
1010 XMLStreamReader xsr = JAXBUtils.XMLINPUTFACTORY
1011 .createXMLStreamReader(new StringReader(menuXml.toString()));
1012 NuvoMenu menu = (NuvoMenu) unmarshaller.unmarshal(xsr);
1019 logger.debug("No JAXBContext available to parse Nuvo Menu XML");
1020 } catch (JAXBException | XMLStreamException e) {
1021 logger.warn("Error processing Nuvo Menu XML: {}", e.getLocalizedMessage());
1025 private void enableNuvonet(boolean showReady) {
1026 if (!this.isAnyOhNuvoNet) {
1030 // enable NuvoNet for each source configured as an openHAB NuvoNet source
1031 nuvoNetSrcMap.forEach((srcNum, val) -> {
1034 connector.sendCommand("SCFG" + srcNum + "NUVONET1");
1035 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1036 } catch (NuvoException | InterruptedException e) {
1037 logger.debug("Error sending SCFG command for source: {}", srcNum);
1043 // set '1' flag for each source configured as an MPS4 NuvoNet source or openHAB NuvoNet source
1044 connector.sendCommand("SNUMBERS" + (nuvoNetSrcMap.get("1") > 0 ? ONE : ZERO) + COMMA
1045 + (nuvoNetSrcMap.get("2") > 0 ? ONE : ZERO) + COMMA + (nuvoNetSrcMap.get("3") > 0 ? ONE : ZERO)
1046 + COMMA + (nuvoNetSrcMap.get("4") > 0 ? ONE : ZERO) + COMMA
1047 + (nuvoNetSrcMap.get("5") > 0 ? ONE : ZERO) + COMMA + (nuvoNetSrcMap.get("6") > 0 ? ONE : ZERO));
1048 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1049 } catch (NuvoException | InterruptedException e) {
1050 logger.debug("Error sending SNUMBERS command");
1053 // go though each source and if is openHAB NuvoNet then configure menu, favorites, etc.
1054 nuvoNetSrcMap.forEach((srcNum, val) -> {
1057 List<TopMenu> topMenuItems = nuvoMenus.getSource().get(Integer.parseInt(srcNum) - 1).getTopMenu();
1059 if (!topMenuItems.isEmpty()) {
1060 connector.sendCommand(
1061 SRC_KEY + srcNum + "MENU," + (topMenuItems.size() < 10 ? topMenuItems.size() : 10));
1062 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1064 for (int i = 0; i < (topMenuItems.size() < 10 ? topMenuItems.size() : 10); i++) {
1065 connector.sendCommand(SRC_KEY + srcNum + "MENUITEM" + (i + 1) + ","
1066 + (topMenuItems.get(i).getItems().isEmpty() ? ZERO : ONE) + ",0,\""
1067 + topMenuItems.get(i).getText() + "\"");
1068 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1072 String[] favorites = favoriteMap.get(srcNum);
1073 if (favorites != null) {
1074 connector.sendCommand(SRC_KEY + srcNum + "FAVORITES"
1075 + (favorites.length < 20 ? favorites.length : 20) + COMMA
1076 + ("1".equals(srcNum) ? ONE : ZERO) + COMMA + ("2".equals(srcNum) ? ONE : ZERO) + COMMA
1077 + ("3".equals(srcNum) ? ONE : ZERO) + COMMA + ("4".equals(srcNum) ? ONE : ZERO) + COMMA
1078 + ("5".equals(srcNum) ? ONE : ZERO) + COMMA + ("6".equals(srcNum) ? ONE : ZERO));
1079 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1081 for (int i = 0; i < (favorites.length < 20 ? favorites.length : 20); i++) {
1082 connector.sendCommand(SRC_KEY + srcNum + "FAVORITESITEM" + (i + 1000) + ",0,0,\""
1083 + favPrefixMap.get(srcNum) + favorites[i] + "\"");
1084 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1089 connector.sendCommand(SRC_KEY + srcNum + "DISPINFOTWO0,0,0,0,0,0,0");
1090 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1091 connector.sendCommand(SRC_KEY + srcNum + "DISPLINES0,0,0,\"Ready\",\"\",\"\",\"\"");
1092 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1095 } catch (NuvoException | InterruptedException e) {
1096 logger.debug("Error configuring NuvoNet for source: {}", srcNum);
1103 * Schedule the reconnection job
1105 private void scheduleReconnectJob() {
1106 logger.debug("Schedule reconnect job");
1107 cancelReconnectJob();
1108 reconnectJob = scheduler.scheduleWithFixedDelay(() -> {
1109 if (!connector.isConnected()) {
1110 logger.debug("Trying to reconnect...");
1112 if (openConnection()) {
1113 logger.debug("Reconnected");
1114 // Polling status will disconnect from MPS4 on reconnect
1118 enableNuvonet(true);
1120 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Reconnection failed");
1124 }, 1, RECON_POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
1128 * If a ping is not received within ping interval the connection is closed and a reconnect job is scheduled
1130 private void schedulePingTimeoutJob() {
1132 logger.debug("Schedule Ping Timeout job");
1133 cancelPingTimeoutJob();
1134 pingJob = scheduler.schedule(() -> {
1136 scheduleReconnectJob();
1137 }, PING_TIMEOUT_SEC, TimeUnit.SECONDS);
1139 logger.debug("Ping Timeout job not valid for serial connections");
1144 * Cancel the ping timeout job
1146 private void cancelPingTimeoutJob() {
1147 ScheduledFuture<?> pingJob = this.pingJob;
1148 if (pingJob != null) {
1149 pingJob.cancel(true);
1150 this.pingJob = null;
1154 private void pollStatus() {
1155 pollStatusNeeded = false;
1156 scheduler.submit(() -> {
1157 synchronized (sequenceLock) {
1159 connector.sendCommand(NuvoCommand.GET_CONTROLLER_VERSION);
1161 NuvoEnum.VALID_SOURCES.forEach(source -> {
1163 connector.sendQuery(NuvoEnum.valueOf(source), NuvoCommand.NAME);
1164 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1165 connector.sendQuery(NuvoEnum.valueOf(source), NuvoCommand.DISPINFO);
1166 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1167 connector.sendQuery(NuvoEnum.valueOf(source), NuvoCommand.DISPLINE);
1168 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1169 } catch (NuvoException | InterruptedException e) {
1170 logger.debug("Error Querying Source data: {}", e.getMessage());
1174 // Query all active zones to get their current status and eq configuration
1175 activeZones.forEach(zoneNum -> {
1177 connector.sendQuery(NuvoEnum.valueOf(ZONE + zoneNum), NuvoCommand.STATUS);
1178 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1179 connector.sendCfgCommand(NuvoEnum.valueOf(ZONE + zoneNum), NuvoCommand.STATUS_QUERY, BLANK);
1180 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1181 connector.sendCfgCommand(NuvoEnum.valueOf(ZONE + zoneNum), NuvoCommand.EQ_QUERY, BLANK);
1182 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1183 } catch (NuvoException | InterruptedException e) {
1184 logger.debug("Error Querying Zone data: {}", e.getMessage());
1188 List<StateOption> sourceStateOptions = new ArrayList<>();
1189 sourceLabels.keySet().forEach(key -> {
1190 sourceStateOptions.add(new StateOption(key, sourceLabels.get(key)));
1193 // Put the source labels on all active zones
1194 activeZones.forEach(zoneNum -> {
1195 stateDescriptionProvider.setStateOptions(
1196 new ChannelUID(getThing().getUID(),
1197 ZONE.toLowerCase() + zoneNum + CHANNEL_DELIMIT + CHANNEL_TYPE_SOURCE),
1198 sourceStateOptions);
1200 } catch (NuvoException e) {
1201 logger.debug("Error polling status from Nuvo: {}", e.getMessage());
1208 * Cancel the reconnection job
1210 private void cancelReconnectJob() {
1211 ScheduledFuture<?> reconnectJob = this.reconnectJob;
1212 if (reconnectJob != null) {
1213 reconnectJob.cancel(true);
1214 this.reconnectJob = null;
1219 * Schedule the polling job
1221 private void schedulePollingJob() {
1225 logger.debug("MPS4 doesn't support polling");
1228 logger.debug("Schedule polling job");
1231 // when the Nuvo amp is off, this will keep the connection (esp Serial over IP) alive and detect if the
1232 // connection goes down
1233 pollingJob = scheduler.scheduleWithFixedDelay(() -> {
1234 if (connector.isConnected()) {
1235 logger.debug("Polling the component for updated status...");
1237 synchronized (sequenceLock) {
1239 connector.sendCommand(NuvoCommand.GET_CONTROLLER_VERSION);
1240 } catch (NuvoException e) {
1241 logger.debug("Polling error: {}", e.getMessage());
1244 // if the last event received was more than 1.25 intervals ago,
1245 // the component is not responding even though the connection is still good
1246 if ((System.currentTimeMillis() - lastEventReceived) > (POLLING_INTERVAL_SEC * 1.25 * 1000)) {
1247 logger.debug("Component not responding to status requests");
1248 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
1249 "Component not responding to status requests");
1251 scheduleReconnectJob();
1255 }, INITIAL_POLLING_DELAY_SEC, POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
1259 * Cancel the polling job
1261 private void cancelPollingJob() {
1262 ScheduledFuture<?> pollingJob = this.pollingJob;
1263 if (pollingJob != null) {
1264 pollingJob.cancel(true);
1265 this.pollingJob = null;
1270 * Schedule the clock sync job
1272 private void scheduleClockSyncJob() {
1273 logger.debug("Schedule clock sync job");
1274 cancelClockSyncJob();
1275 clockSyncJob = scheduler.scheduleWithFixedDelay(() -> {
1276 if (this.isGConcerto) {
1278 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy,MM,dd,HH,mm");
1279 connector.sendCommand(NuvoCommand.CFGTIME.getValue() + dateFormat.format(new Date()));
1280 } catch (NuvoException e) {
1281 logger.debug("Error syncing clock: {}", e.getMessage());
1284 this.cancelClockSyncJob();
1286 }, INITIAL_CLOCK_SYNC_DELAY_SEC, CLOCK_SYNC_INTERVAL_SEC, TimeUnit.SECONDS);
1290 * Cancel the clock sync job
1292 private void cancelClockSyncJob() {
1293 ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
1294 if (clockSyncJob != null) {
1295 clockSyncJob.cancel(true);
1296 this.clockSyncJob = null;
1301 * Update the state of a channel (original method signature)
1303 * @param target the channel group
1304 * @param channelType the channel group item
1305 * @param value the value to be updated
1307 private void updateChannelState(NuvoEnum target, String channelType, String value) {
1308 updateChannelState(target, channelType, value, NO_ART);
1312 * Update the state of a channel (overloaded method to handle album_art channel)
1314 * @param target the channel group
1315 * @param channelType the channel group item
1316 * @param value the value to be updated
1317 * @param bytes the byte[] to load into the Image channel
1319 private void updateChannelState(NuvoEnum target, String channelType, String value, byte[] bytes) {
1320 String channel = target.name().toLowerCase() + CHANNEL_DELIMIT + channelType;
1322 if (!isLinked(channel)) {
1326 State state = UnDefType.UNDEF;
1328 if (UNDEF.equals(value)) {
1329 updateState(channel, state);
1333 switch (channelType) {
1334 case CHANNEL_TYPE_POWER:
1335 case CHANNEL_TYPE_MUTE:
1336 case CHANNEL_TYPE_DND:
1337 case CHANNEL_TYPE_PARTY:
1338 case CHANNEL_TYPE_ALLMUTE:
1339 case CHANNEL_TYPE_PAGE:
1340 case CHANNEL_TYPE_LOUDNESS:
1341 state = ON.equals(value) ? OnOffType.ON : OnOffType.OFF;
1343 case CHANNEL_TYPE_LOCK:
1344 state = ON.equals(value) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
1346 case CHANNEL_TYPE_SOURCE:
1347 case CHANNEL_TYPE_TREBLE:
1348 case CHANNEL_TYPE_BASS:
1349 case CHANNEL_TYPE_BALANCE:
1350 state = new DecimalType(value);
1352 case CHANNEL_TYPE_VOLUME:
1353 int volume = Integer.parseInt(value);
1354 long volumePct = Math
1355 .round((double) (MAX_VOLUME - volume) / (double) (MAX_VOLUME - MIN_VOLUME) * 100.0);
1356 state = new PercentType(BigDecimal.valueOf(volumePct));
1358 case CHANNEL_TYPE_BUTTONPRESS:
1359 case CHANNEL_DISPLAY_LINE1:
1360 case CHANNEL_DISPLAY_LINE2:
1361 case CHANNEL_DISPLAY_LINE3:
1362 case CHANNEL_DISPLAY_LINE4:
1363 case CHANNEL_BUTTON_PRESS:
1364 state = new StringType(value);
1366 case CHANNEL_PLAY_MODE:
1367 state = new StringType(NuvoStatusCodes.PLAY_MODE.get(value));
1369 case CHANNEL_TRACK_LENGTH:
1370 case CHANNEL_TRACK_POSITION:
1371 state = new QuantityType<Time>(Integer.parseInt(value) / 10, NuvoHandler.API_SECOND_UNIT);
1373 case CHANNEL_ALBUM_ART:
1374 state = new RawType(bytes, RawType.DEFAULT_MIME_TYPE);
1379 updateState(channel, state);
1383 * Handle a button press from a UI Player item
1385 * @param target the nuvo zone to receive the command
1386 * @param command the button press command to send to the zone
1388 private void handleControlCommand(NuvoEnum target, Command command) throws NuvoException {
1389 if (command instanceof PlayPauseType) {
1390 connector.sendCommand(target, NuvoCommand.PLAYPAUSE);
1391 } else if (command instanceof NextPreviousType) {
1392 if (command == NextPreviousType.NEXT) {
1393 connector.sendCommand(target, NuvoCommand.NEXT);
1394 } else if (command == NextPreviousType.PREVIOUS) {
1395 connector.sendCommand(target, NuvoCommand.PREV);
1398 logger.warn("Unknown control command: {}", command);