2 * Copyright (c) 2010-2022 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_PATTERN = Pattern.compile("^BASS(.*),TREB(.*),BAL(.*),LOUDCMP([0-1])$");
139 private final Logger logger = LoggerFactory.getLogger(NuvoHandler.class);
140 private final NuvoStateDescriptionOptionProvider stateDescriptionProvider;
141 private final SerialPortManager serialPortManager;
142 private final HttpClient httpClient;
144 private @Nullable ScheduledFuture<?> reconnectJob;
145 private @Nullable ScheduledFuture<?> pollingJob;
146 private @Nullable ScheduledFuture<?> clockSyncJob;
147 private @Nullable ScheduledFuture<?> pingJob;
149 private NuvoConnector connector = new NuvoDefaultConnector();
150 private long lastEventReceived = System.currentTimeMillis();
151 private int numZones = 1;
152 private String versionString = BLANK;
153 private boolean isGConcerto = false;
154 private Object sequenceLock = new Object();
156 private boolean isAnyOhNuvoNet = false;
157 private NuvoMenu nuvoMenus = new NuvoMenu();
158 private HashMap<String, Integer> nuvoNetSrcMap = new HashMap<String, Integer>();
159 private HashMap<String, String> favPrefixMap = new HashMap<String, String>();
160 private HashMap<String, String[]> favoriteMap = new HashMap<String, String[]>();
162 private HashMap<String, byte[]> albumArtMap = new HashMap<String, byte[]>();
163 private HashMap<String, Integer> albumArtIds = new HashMap<String, Integer>();
164 private HashMap<String, String> dispInfoCache = new HashMap<String, String>();
166 Set<Integer> activeZones = new HashSet<>(1);
168 // A tree map that maps the source ids to source labels
169 TreeMap<String, String> sourceLabels = new TreeMap<String, String>();
171 // Indicates if there is a need to poll status because of a disconnection used for MPS4 systems
172 boolean pollStatusNeeded = true;
173 boolean isMps4 = false;
178 public NuvoHandler(Thing thing, NuvoStateDescriptionOptionProvider stateDescriptionProvider,
179 SerialPortManager serialPortManager, HttpClient httpClient) {
181 this.stateDescriptionProvider = stateDescriptionProvider;
182 this.serialPortManager = serialPortManager;
183 this.httpClient = httpClient;
187 public void initialize() {
188 final String uid = this.getThing().getUID().getAsString();
189 NuvoThingConfiguration config = getConfigAs(NuvoThingConfiguration.class);
190 final String serialPort = config.serialPort;
191 final String host = config.host;
192 final Integer port = config.port;
193 final Integer numZones = config.numZones;
195 // Check configuration settings
196 String configError = null;
197 if ((serialPort == null || serialPort.isEmpty()) && (host == null || host.isEmpty())) {
198 configError = "undefined serialPort and host configuration settings; please set one of them";
199 } else if (serialPort != null && (host == null || host.isEmpty())) {
200 if (serialPort.toLowerCase().startsWith("rfc2217")) {
201 configError = "use host and port configuration settings for a serial over IP connection";
205 configError = "undefined port configuration setting";
206 } else if (port <= 0) {
207 configError = "invalid port configuration setting";
211 if (configError != null) {
212 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError);
216 if (serialPort != null && !serialPort.isEmpty()) {
217 connector = new NuvoSerialConnector(serialPortManager, serialPort, uid);
218 } else if (port != null) {
219 connector = new NuvoIpConnector(host, port, uid);
220 this.isMps4 = (port.intValue() == MPS4_PORT);
222 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
223 "Either Serial port or Host & Port must be specifed");
228 logger.debug("Port set to {} configuring binding for MPS4 compatability", MPS4_PORT);
230 this.isAnyOhNuvoNet = (config.nuvoNetSrc1 == 2 || config.nuvoNetSrc2 == 2 || config.nuvoNetSrc3 == 2
231 || config.nuvoNetSrc4 == 2 || config.nuvoNetSrc5 == 2 || config.nuvoNetSrc6 == 2);
233 if (this.isAnyOhNuvoNet) {
234 logger.debug("At least one source is configured as an openHAB NuvoNet source");
235 loadMenuConfiguration(config);
237 nuvoNetSrcMap.put("1", config.nuvoNetSrc1);
238 nuvoNetSrcMap.put("2", config.nuvoNetSrc2);
239 nuvoNetSrcMap.put("3", config.nuvoNetSrc3);
240 nuvoNetSrcMap.put("4", config.nuvoNetSrc4);
241 nuvoNetSrcMap.put("5", config.nuvoNetSrc5);
242 nuvoNetSrcMap.put("6", config.nuvoNetSrc6);
245 !config.favoritesSrc1.isEmpty() ? config.favoritesSrc1.split(COMMA) : new String[0]);
247 !config.favoritesSrc2.isEmpty() ? config.favoritesSrc2.split(COMMA) : new String[0]);
249 !config.favoritesSrc3.isEmpty() ? config.favoritesSrc3.split(COMMA) : new String[0]);
251 !config.favoritesSrc4.isEmpty() ? config.favoritesSrc4.split(COMMA) : new String[0]);
253 !config.favoritesSrc5.isEmpty() ? config.favoritesSrc5.split(COMMA) : new String[0]);
255 !config.favoritesSrc6.isEmpty() ? config.favoritesSrc6.split(COMMA) : new String[0]);
257 favPrefixMap.put("1", config.favPrefix1);
258 favPrefixMap.put("2", config.favPrefix2);
259 favPrefixMap.put("3", config.favPrefix3);
260 favPrefixMap.put("4", config.favPrefix4);
261 favPrefixMap.put("5", config.favPrefix5);
262 favPrefixMap.put("6", config.favPrefix6);
264 albumArtIds.put("S1", 0);
265 albumArtIds.put("S2", 0);
266 albumArtIds.put("S3", 0);
267 albumArtIds.put("S4", 0);
268 albumArtIds.put("S5", 0);
269 albumArtIds.put("S6", 0);
271 albumArtMap.put("S1", NO_ART);
272 albumArtMap.put("S2", NO_ART);
273 albumArtMap.put("S3", NO_ART);
274 albumArtMap.put("S4", NO_ART);
275 albumArtMap.put("S5", NO_ART);
276 albumArtMap.put("S6", NO_ART);
280 if (numZones != null) {
281 this.numZones = numZones;
284 activeZones = IntStream.range((1), (this.numZones + 1)).boxed().collect(Collectors.toSet());
286 // remove the channels for the zones we are not using
287 if (this.numZones < MAX_ZONES) {
288 List<Channel> channels = new ArrayList<>(this.getThing().getChannels());
290 List<Integer> zonesToRemove = IntStream.range((this.numZones + 1), (MAX_ZONES + 1)).boxed()
291 .collect(Collectors.toList());
293 zonesToRemove.forEach(zone -> channels.removeIf(c -> (c.getUID().getId().contains("zone" + zone))));
294 updateThing(editThing().withChannels(channels).build());
297 // Build a list of State options for the global favorites using user config values (if supplied)
298 String[] favoritesArr = !config.favoriteLabels.isEmpty() ? config.favoriteLabels.split(COMMA) : new String[0];
299 List<StateOption> favoriteLabelsStateOptions = new ArrayList<>();
300 for (int i = 0; i < 12; i++) {
301 if (favoritesArr.length > i) {
302 favoriteLabelsStateOptions.add(new StateOption(String.valueOf(i + 1), favoritesArr[i]));
303 } else if (favoritesArr.length == 0) {
304 favoriteLabelsStateOptions.add(new StateOption(String.valueOf(i + 1), "Favorite " + (i + 1)));
308 // Put the global favorites labels on all active zones
309 activeZones.forEach(zoneNum -> {
310 stateDescriptionProvider.setStateOptions(
311 new ChannelUID(getThing().getUID(),
312 ZONE.toLowerCase() + zoneNum + CHANNEL_DELIMIT + CHANNEL_TYPE_FAVORITE),
313 favoriteLabelsStateOptions);
316 if (config.clockSync) {
317 scheduleClockSyncJob();
320 scheduleReconnectJob();
321 schedulePollingJob();
322 schedulePingTimeoutJob();
323 updateStatus(ThingStatus.UNKNOWN);
327 public void dispose() {
328 if (this.isAnyOhNuvoNet) {
330 // disable NuvoNet for each source that was configured as an openHAB NuvoNet source
331 nuvoNetSrcMap.forEach((srcNum, val) -> {
334 connector.sendCommand(SRC_KEY + srcNum + "DISPINFOTWO0,0,0,0,0,0,0");
335 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
336 connector.sendCommand(
337 SRC_KEY + srcNum + "DISPLINES0,0,0,\"Source Unavailable\",\"\",\"\",\"\"");
338 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
339 connector.sendCommand("SCFG" + srcNum + "NUVONET0");
340 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
341 } catch (NuvoException | InterruptedException e) {
342 logger.debug("Error sending command to disable NuvoNet source: {}", srcNum);
347 // need '1' flag for sources configured as an MPS4 NuvoNet source, but disable openHAB NuvoNet sources
348 connector.sendCommand("SNUMBERS" + (nuvoNetSrcMap.get("1") == 1 ? ONE : ZERO) + COMMA
349 + (nuvoNetSrcMap.get("2") == 1 ? ONE : ZERO) + COMMA
350 + (nuvoNetSrcMap.get("3") == 1 ? ONE : ZERO) + COMMA
351 + (nuvoNetSrcMap.get("4") == 1 ? ONE : ZERO) + COMMA
352 + (nuvoNetSrcMap.get("5") == 1 ? ONE : ZERO) + COMMA
353 + (nuvoNetSrcMap.get("6") == 1 ? ONE : ZERO));
354 } catch (NuvoException e) {
355 logger.debug("Error sending SNUMBERS command to disable NuvoNet sources");
359 cancelReconnectJob();
361 cancelClockSyncJob();
362 cancelPingTimeoutJob();
368 public Collection<Class<? extends ThingHandlerService>> getServices() {
369 return Collections.singletonList(NuvoThingActions.class);
372 public void handleRawCommand(@Nullable String command) {
373 synchronized (sequenceLock) {
375 connector.sendCommand(command);
376 } catch (NuvoException e) {
377 logger.warn("Nuvo Command: {} failed", command);
383 * Handle a command from the UI
385 * @param channelUID the channel sending the command
386 * @param command the command received
390 public void handleCommand(ChannelUID channelUID, Command command) {
391 String channel = channelUID.getId();
392 String[] channelSplit = channel.split(CHANNEL_DELIMIT);
393 NuvoEnum target = NuvoEnum.valueOf(channelSplit[0].toUpperCase());
395 String channelType = channelSplit[1];
397 if (getThing().getStatus() != ThingStatus.ONLINE) {
398 logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel);
402 synchronized (sequenceLock) {
403 if (!connector.isConnected()) {
404 logger.warn("Command {} from channel {} is ignored: connection not established", command, channel);
409 switch (channelType) {
410 case CHANNEL_TYPE_POWER:
411 if (command instanceof OnOffType) {
412 connector.sendCommand(target, command == OnOffType.ON ? NuvoCommand.ON : NuvoCommand.OFF);
415 case CHANNEL_TYPE_SOURCE:
416 if (command instanceof DecimalType) {
417 int value = ((DecimalType) command).intValue();
418 if (value >= 1 && value <= MAX_SRC) {
419 logger.debug("Got source command {} zone {}", value, target);
420 connector.sendCommand(target, NuvoCommand.SOURCE, String.valueOf(value));
424 case CHANNEL_TYPE_FAVORITE:
425 if (command instanceof DecimalType) {
426 int value = ((DecimalType) command).intValue();
427 if (value >= 1 && value <= MAX_FAV) {
428 logger.debug("Got favorite command {} zone {}", value, target);
429 connector.sendCommand(target, NuvoCommand.FAVORITE, String.valueOf(value));
433 case CHANNEL_TYPE_VOLUME:
434 if (command instanceof PercentType) {
435 int value = (MAX_VOLUME
437 ((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME))
439 logger.debug("Got volume command {} zone {}", value, target);
440 connector.sendCommand(target, NuvoCommand.VOLUME, String.valueOf(value));
443 case CHANNEL_TYPE_MUTE:
444 if (command instanceof OnOffType) {
445 connector.sendCommand(target,
446 command == OnOffType.ON ? NuvoCommand.MUTE_ON : NuvoCommand.MUTE_OFF);
449 case CHANNEL_TYPE_TREBLE:
450 if (command instanceof DecimalType) {
451 int value = ((DecimalType) command).intValue();
452 if (value >= MIN_EQ && value <= MAX_EQ) {
453 // device can only accept even values
454 if (value % 2 == 1) {
457 logger.debug("Got treble command {} zone {}", value, target);
458 connector.sendCfgCommand(target, NuvoCommand.TREBLE, String.valueOf(value));
462 case CHANNEL_TYPE_BASS:
463 if (command instanceof DecimalType) {
464 int value = ((DecimalType) command).intValue();
465 if (value >= MIN_EQ && value <= MAX_EQ) {
466 if (value % 2 == 1) {
469 logger.debug("Got bass command {} zone {}", value, target);
470 connector.sendCfgCommand(target, NuvoCommand.BASS, String.valueOf(value));
474 case CHANNEL_TYPE_BALANCE:
475 if (command instanceof DecimalType) {
476 int value = ((DecimalType) command).intValue();
477 if (value >= MIN_EQ && value <= MAX_EQ) {
478 if (value % 2 == 1) {
481 logger.debug("Got balance command {} zone {}", value, target);
482 connector.sendCfgCommand(target, NuvoCommand.BALANCE,
483 NuvoStatusCodes.getBalanceFromInt(value));
487 case CHANNEL_TYPE_LOUDNESS:
488 if (command instanceof OnOffType) {
489 connector.sendCfgCommand(target, NuvoCommand.LOUDNESS,
490 command == OnOffType.ON ? ONE : ZERO);
493 case CHANNEL_TYPE_CONTROL:
494 handleControlCommand(target, command);
496 case CHANNEL_TYPE_DND:
497 if (command instanceof OnOffType) {
498 connector.sendCommand(target,
499 command == OnOffType.ON ? NuvoCommand.DND_ON : NuvoCommand.DND_OFF);
502 case CHANNEL_TYPE_PARTY:
503 if (command instanceof OnOffType) {
504 connector.sendCommand(target,
505 command == OnOffType.ON ? NuvoCommand.PARTY_ON : NuvoCommand.PARTY_OFF);
508 case CHANNEL_DISPLAY_LINE1:
509 if (command instanceof StringType) {
510 connector.sendCommand(target, NuvoCommand.DISPLINE1, "\"" + command + "\"");
513 case CHANNEL_DISPLAY_LINE2:
514 if (command instanceof StringType) {
515 connector.sendCommand(target, NuvoCommand.DISPLINE2, "\"" + command + "\"");
518 case CHANNEL_DISPLAY_LINE3:
519 if (command instanceof StringType) {
520 connector.sendCommand(target, NuvoCommand.DISPLINE3, "\"" + command + "\"");
523 case CHANNEL_DISPLAY_LINE4:
524 if (command instanceof StringType) {
525 connector.sendCommand(target, NuvoCommand.DISPLINE4, "\"" + command + "\"");
528 case CHANNEL_TYPE_ALLOFF:
529 if (command instanceof OnOffType) {
530 connector.sendCommand(NuvoCommand.ALLOFF);
533 case CHANNEL_TYPE_ALLMUTE:
534 if (command instanceof OnOffType) {
535 connector.sendCommand(
536 command == OnOffType.ON ? NuvoCommand.ALLMUTE_ON : NuvoCommand.ALLMUTE_OFF);
539 case CHANNEL_TYPE_PAGE:
540 if (command instanceof OnOffType) {
541 connector.sendCommand(command == OnOffType.ON ? NuvoCommand.PAGE_ON : NuvoCommand.PAGE_OFF);
544 case CHANNEL_TYPE_SENDCMD:
545 if (command instanceof StringType) {
546 String commandStr = command.toString();
547 if (commandStr.contains(DISP_INFO_TWO)) {
548 String sourceKey = commandStr.split(DISP_INFO_TWO)[0];
549 dispInfoCache.put(sourceKey, commandStr);
551 // if 'albumartid' is present, substitute it with the albumArtId hex string
552 connector.sendCommand(commandStr.replace(ALBUM_ART_ID,
553 (OFFSET_ZERO + Integer.toHexString(albumArtIds.get(sourceKey)))));
555 connector.sendCommand(commandStr);
559 case CHANNEL_ART_URL:
560 if (command instanceof StringType) {
561 String url = command.toString();
562 if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
564 ContentResponse contentResponse = httpClient.newRequest(url).method(GET)
565 .timeout(10, TimeUnit.SECONDS).send();
566 int httpStatus = contentResponse.getStatus();
567 if (httpStatus == OK_200) {
568 albumArtMap.put(target.getId(),
569 NuvoImageResizer.resizeImage(contentResponse.getContent(), 80, 80));
571 updateChannelState(target, CHANNEL_ALBUM_ART, BLANK,
572 contentResponse.getContent());
574 albumArtMap.put(target.getId(), NO_ART);
575 albumArtIds.put(target.getId(), 0);
576 updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
579 } catch (InterruptedException | TimeoutException | ExecutionException e) {
580 albumArtMap.put(target.getId(), NO_ART);
581 albumArtIds.put(target.getId(), 0);
582 updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
585 albumArtIds.put(target.getId(), Math.abs(url.hashCode()));
587 // re-send the cached DISPINFOTWO message, substituting in the new albumArtId
588 if (dispInfoCache.get(target.getId()) != null) {
589 connector.sendCommand(dispInfoCache.get(target.getId()).replace(ALBUM_ART_ID,
590 (OFFSET_ZERO + Integer.toHexString(albumArtIds.get(target.getId())))));
593 albumArtMap.put(target.getId(), NO_ART);
594 albumArtIds.put(target.getId(), 0);
595 updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
599 } catch (NuvoException e) {
600 logger.warn("Command {} from channel {} failed: {}", command, channel, e.getMessage());
601 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Sending command failed");
603 scheduleReconnectJob();
609 * Open the connection with the Nuvo device
611 * @return true if the connection is opened successfully or false if not
613 private synchronized boolean openConnection() {
614 connector.addEventListener(this);
617 } catch (NuvoException e) {
618 logger.debug("openConnection() failed: {}", e.getMessage());
620 logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected");
621 return connector.isConnected();
625 * Close the connection with the Nuvo device
627 private synchronized void closeConnection() {
628 if (connector.isConnected()) {
630 connector.removeEventListener(this);
631 pollStatusNeeded = true;
632 logger.debug("closeConnection(): disconnected");
637 * Handle an event received from the Nuvo device
639 * @param event the event to process
642 public void onNewMessageEvent(NuvoMessageEvent evt) {
643 logger.debug("onNewMessageEvent: key {} = {}", evt.getKey(), evt.getValue());
644 lastEventReceived = System.currentTimeMillis();
646 String type = evt.getType();
647 String key = evt.getKey();
648 String updateData = evt.getValue().trim();
649 if (this.getThing().getStatus() != ThingStatus.ONLINE) {
650 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, this.versionString);
655 this.versionString = updateData;
656 // Determine if we are a Grand Concerto or not
657 if (this.versionString.contains(GC_STR)) {
658 logger.debug("Grand Concerto detected");
659 this.isGConcerto = true;
660 connector.setEssentia(false);
662 logger.debug("Grand Concerto not detected");
666 logger.debug("Restart message received; re-sending initialization messages");
667 enableNuvonet(false);
670 logger.debug("Ping message received- rescheduling ping timeout");
671 schedulePingTimeoutJob();
672 // Return here because receiving a ping does not indicate that one can poll
675 activeZones.forEach(zoneNum -> {
676 updateChannelState(NuvoEnum.valueOf(ZONE + zoneNum), CHANNEL_TYPE_POWER, OFF);
680 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_ALLMUTE, ONE.equals(updateData) ? ON : OFF);
681 activeZones.forEach(zoneNum -> {
682 updateChannelState(NuvoEnum.valueOf(ZONE + zoneNum), CHANNEL_TYPE_MUTE,
683 ONE.equals(updateData) ? ON : OFF);
687 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_PAGE, ONE.equals(updateData) ? ON : OFF);
689 case TYPE_SOURCE_UPDATE:
690 logger.debug("Source update: Source: {} - Value: {}", key, updateData);
691 NuvoEnum targetSource = NuvoEnum.valueOf(SOURCE + key);
693 if (updateData.contains(DISPLINE)) {
694 // example: DISPLINE2,"Play My Song (Featuring Dee Ajayi)"
695 Matcher matcher = DISP_PATTERN.matcher(updateData);
696 if (matcher.find()) {
697 updateChannelState(targetSource, CHANNEL_DISPLAY_LINE + matcher.group(1), matcher.group(2));
699 logger.debug("no match on message: {}", updateData);
701 } else if (updateData.contains(DISPINFO)) {
702 // example: DISPINFO,DUR0,POS70,STATUS2 (DUR and POS are expressed in tenths of a second)
703 // 6 places(tenths of a second)-> max 999,999 /10/60/60/24 = 1.15 days
704 Matcher matcher = DISP_INFO_PATTERN.matcher(updateData);
705 if (matcher.find()) {
706 updateChannelState(targetSource, CHANNEL_TRACK_LENGTH, matcher.group(1));
707 updateChannelState(targetSource, CHANNEL_TRACK_POSITION, matcher.group(2));
708 updateChannelState(targetSource, CHANNEL_PLAY_MODE, matcher.group(3));
710 logger.debug("no match on message: {}", updateData);
712 } else if (updateData.contains(NAME_QUOTE)) {
713 // example: NAME"Ipod"
714 String name = updateData.split("\"")[1];
715 sourceLabels.put(key, name);
718 case TYPE_ZONE_UPDATE:
719 logger.debug("Zone update: Zone: {} - Value: {}", key, updateData);
721 // or: ON,SRC3,VOL63,DND0,LOCK0
722 // or: ON,SRC3,MUTE,DND0,LOCK0
724 NuvoEnum targetZone = NuvoEnum.valueOf(ZONE + key);
726 if (OFF.equals(updateData)) {
727 updateChannelState(targetZone, CHANNEL_TYPE_POWER, OFF);
728 updateChannelState(targetZone, CHANNEL_TYPE_SOURCE, UNDEF);
730 Matcher matcher = ZONE_PATTERN.matcher(updateData);
731 if (matcher.find()) {
732 updateChannelState(targetZone, CHANNEL_TYPE_POWER, ON);
733 updateChannelState(targetZone, CHANNEL_TYPE_SOURCE, matcher.group(1));
735 if (MUTE.equals(matcher.group(2))) {
736 updateChannelState(targetZone, CHANNEL_TYPE_MUTE, ON);
738 updateChannelState(targetZone, CHANNEL_TYPE_MUTE, NuvoCommand.OFF.getValue());
739 updateChannelState(targetZone, CHANNEL_TYPE_VOLUME, matcher.group(2).replace(VOL, BLANK));
742 updateChannelState(targetZone, CHANNEL_TYPE_DND, ONE.equals(matcher.group(3)) ? ON : OFF);
743 updateChannelState(targetZone, CHANNEL_TYPE_LOCK, ONE.equals(matcher.group(4)) ? ON : OFF);
745 logger.debug("no match on message: {}", updateData);
749 case TYPE_ZONE_BUTTON:
750 logger.debug("Zone Button pressed: Source: {} - Button: {}", key, updateData);
751 updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS, updateData);
753 case TYPE_ZONE_BUTTON2:
754 String buttonAction = NuvoStatusCodes.BUTTON_CODE.get(updateData);
756 if (buttonAction != null) {
757 logger.debug("Zone NuvoNet Button pressed: Source: {} - Button: {}", key, buttonAction);
758 updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS, buttonAction);
760 logger.debug("Zone NuvoNet Button pressed: Source: {} - Unknown button code: {}", key, updateData);
761 updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS, updateData);
764 case TYPE_MENU_ITEM_SELECTED:
765 String[] updateDataSplit = updateData.split(COMMA);
766 String zoneSource = updateDataSplit[0];
767 String menuId = updateDataSplit[1];
768 int menuItemIdx = Integer.parseInt(updateDataSplit[2]) - 1;
770 boolean exitMenu = false;
771 if ("0xFFFFFFFF".equals(menuId)) {
772 TopMenu topMenuItem = nuvoMenus.getSource().get(Integer.parseInt(key) - 1).getTopMenu()
774 logger.debug("Top Menu item selected: Source: {} - Menu Item: {}", key, topMenuItem.getText());
775 updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS, topMenuItem.getText());
777 List<String> subMenuItems = topMenuItem.getItems();
779 if (subMenuItems.isEmpty()) {
782 // send submenu (maximum of 20 items)
783 int subMenuSize = subMenuItems.size() < 20 ? subMenuItems.size() : 20;
785 connector.sendCommand(zoneSource + "MENU" + (menuItemIdx + 11) + ",0,0," + subMenuSize
786 + ",0,0," + subMenuSize + ",\"" + topMenuItem.getText() + "\"");
787 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
789 for (int i = 0; i < subMenuSize; i++) {
790 connector.sendCommand(
791 zoneSource + "MENUITEM" + (i + 1) + ",0,0,\"" + subMenuItems.get(i) + "\"");
793 } catch (NuvoException | InterruptedException e) {
794 logger.debug("Error sending sub menu for {}", zoneSource);
798 // a sub menu item was selected
799 TopMenu topMenuItem = nuvoMenus.getSource().get(Integer.parseInt(key) - 1).getTopMenu()
800 .get(Integer.decode(menuId) - 11);
801 String subMenuItem = topMenuItem.getItems().get(menuItemIdx);
803 logger.debug("Sub Menu item selected: Source: {} - Menu Item: {}", key,
804 topMenuItem.getText() + "|" + subMenuItem);
805 updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS,
806 topMenuItem.getText() + "|" + subMenuItem);
812 // tell the zone to exit the menu
813 connector.sendCommand(zoneSource + "MENU0,0,0,0,0,0,0,\"\"");
814 } catch (NuvoException e) {
815 logger.debug("Error sending exit menu command for {}", zoneSource);
819 case TYPE_ZONE_MENUREQ:
820 logger.debug("Menu Request: Source: {} - Value: {}", key, updateData);
821 // For now we only support one level deep menus. If third field is '1', indicates go back to main menu.
822 String[] menuDataSplit = updateData.split(",");
823 if (menuDataSplit.length > 3 && ONE.equals(menuDataSplit[2])) {
825 connector.sendCommand(menuDataSplit[0] + "MENU0xFFFFFFFF,0,0,0,0,0,0,\"\"");
826 } catch (NuvoException e) {
827 logger.debug("Error sending main menu command for {}", menuDataSplit[0]);
832 case TYPE_ZONE_CONFIG:
833 logger.debug("Zone Configuration: Zone: {} - Value: {}", key, updateData);
834 // example: BASS1,TREB-2,BALR2,LOUDCMP1
835 Matcher matcher = ZONE_CFG_PATTERN.matcher(updateData);
836 if (matcher.find()) {
837 updateChannelState(NuvoEnum.valueOf(ZONE + key), CHANNEL_TYPE_BASS, matcher.group(1));
838 updateChannelState(NuvoEnum.valueOf(ZONE + key), CHANNEL_TYPE_TREBLE, matcher.group(2));
839 updateChannelState(NuvoEnum.valueOf(ZONE + key), CHANNEL_TYPE_BALANCE,
840 NuvoStatusCodes.getBalanceFromStr(matcher.group(3)));
841 updateChannelState(NuvoEnum.valueOf(ZONE + key), CHANNEL_TYPE_LOUDNESS,
842 ONE.equals(matcher.group(4)) ? ON : OFF);
844 logger.debug("no match on message: {}", updateData);
847 case TYPE_ALBUM_ART_REQ:
848 logger.debug("Album Art Request for Source: {} - Data: {}", key, updateData);
849 // 0x620FD879,80,80,2,0x00C0C0C0,0,0,0,0,1
850 String[] albumArtReq = updateData.split(COMMA);
851 albumArtIds.put(SRC_KEY + key, Integer.decode(albumArtReq[0]));
854 if (albumArtMap.get(SRC_KEY + key).length > 1) {
855 connector.sendCommand(SRC_KEY + key + ALBUM_ART_AVAILABLE + albumArtIds.get(SRC_KEY + key)
856 + COMMA + albumArtMap.get(SRC_KEY + key).length);
858 connector.sendCommand(SRC_KEY + key + ALBUM_ART_AVAILABLE + ZERO_COMMA);
860 } catch (NuvoException e) {
861 logger.debug("Error sending ALBUMARTAVAILABLE command for source: {}", key);
864 case TYPE_ALBUM_ART_FRAG_REQ:
865 logger.debug("Album Art Fragment Request for Source: {} - Data: {}", key, updateData);
866 // 0x620FD879,0,750 (id, requested offset from start of image, byte length requested)
867 String[] albumArtFragReq = updateData.split(COMMA);
868 int requestedId = Integer.decode(albumArtFragReq[0]);
869 int offset = Integer.parseInt(albumArtFragReq[1]);
870 int length = Integer.parseInt(albumArtFragReq[2]);
872 if (requestedId == albumArtIds.get(SRC_KEY + key)) {
873 byte[] chunk = new byte[length];
874 byte[] albumArtBytes = albumArtMap.get(SRC_KEY + key);
876 if (albumArtBytes != null) {
877 System.arraycopy(albumArtBytes, offset, chunk, 0, length);
878 final String frag = Base64.getEncoder().encodeToString(chunk);
880 connector.sendCommand(SRC_KEY + key + ALBUM_ART_FRAG + requestedId + COMMA + offset + COMMA
881 + frag.length() + COMMA + frag);
882 } catch (NuvoException e) {
883 logger.debug("Error sending ALBUMARTFRAG command for source: {}, artId: {}", key,
889 case TYPE_FAVORITE_REQ:
890 logger.debug("Favorite request for source: {} - favoriteId: {}", key, updateData);
892 int playlistIdx = Integer.parseInt(updateData, 16) - 1000;
893 updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS,
894 "PLAY_MUSIC_PRESET:" + favoriteMap.get(key)[playlistIdx]);
895 } catch (NumberFormatException nfe) {
896 logger.debug("Unable to parse favoriteId: {}", updateData);
900 logger.debug("onNewMessageEvent: unhandled key {}", key);
901 // Return here because receiving an unknown message does not indicate that one can poll
905 if (isMps4 && pollStatusNeeded) {
910 private void loadMenuConfiguration(NuvoThingConfiguration config) {
911 StringBuilder menuXml = new StringBuilder("<menu>");
913 if (!config.menuXmlSrc1.isEmpty()) {
914 menuXml.append("<source>" + config.menuXmlSrc1 + "</source>");
916 menuXml.append("<source/>");
918 if (!config.menuXmlSrc2.isEmpty()) {
919 menuXml.append("<source>" + config.menuXmlSrc2 + "</source>");
921 menuXml.append("<source/>");
923 if (!config.menuXmlSrc3.isEmpty()) {
924 menuXml.append("<source>" + config.menuXmlSrc3 + "</source>");
926 menuXml.append("<source/>");
928 if (!config.menuXmlSrc4.isEmpty()) {
929 menuXml.append("<source>" + config.menuXmlSrc4 + "</source>");
931 menuXml.append("<source/>");
933 if (!config.menuXmlSrc5.isEmpty()) {
934 menuXml.append("<source>" + config.menuXmlSrc5 + "</source>");
936 menuXml.append("<source/>");
938 if (!config.menuXmlSrc6.isEmpty()) {
939 menuXml.append("<source>" + config.menuXmlSrc6 + "</source>");
941 menuXml.append("<source/>");
943 menuXml.append("</menu>");
946 JAXBContext ctx = JAXBUtils.JAXBCONTEXT_NUVO_MENU;
948 Unmarshaller unmarshaller = ctx.createUnmarshaller();
949 if (unmarshaller != null) {
950 XMLStreamReader xsr = JAXBUtils.XMLINPUTFACTORY
951 .createXMLStreamReader(new StringReader(menuXml.toString()));
952 NuvoMenu menu = (NuvoMenu) unmarshaller.unmarshal(xsr);
959 logger.debug("No JAXBContext available to parse Nuvo Menu XML");
960 } catch (JAXBException | XMLStreamException e) {
961 logger.warn("Error processing Nuvo Menu XML: {}", e.getLocalizedMessage());
965 private void enableNuvonet(boolean showReady) {
966 if (!this.isAnyOhNuvoNet) {
970 // enable NuvoNet for each source configured as an openHAB NuvoNet source
971 nuvoNetSrcMap.forEach((srcNum, val) -> {
974 connector.sendCommand("SCFG" + srcNum + "NUVONET1");
975 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
976 } catch (NuvoException | InterruptedException e) {
977 logger.debug("Error sending SCFG command for source: {}", srcNum);
983 // set '1' flag for each source configured as an MPS4 NuvoNet source or openHAB NuvoNet source
984 connector.sendCommand("SNUMBERS" + (nuvoNetSrcMap.get("1") > 0 ? ONE : ZERO) + COMMA
985 + (nuvoNetSrcMap.get("2") > 0 ? ONE : ZERO) + COMMA + (nuvoNetSrcMap.get("3") > 0 ? ONE : ZERO)
986 + COMMA + (nuvoNetSrcMap.get("4") > 0 ? ONE : ZERO) + COMMA
987 + (nuvoNetSrcMap.get("5") > 0 ? ONE : ZERO) + COMMA + (nuvoNetSrcMap.get("6") > 0 ? ONE : ZERO));
988 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
989 } catch (NuvoException | InterruptedException e) {
990 logger.debug("Error sending SNUMBERS command");
993 // go though each source and if is openHAB NuvoNet then configure menu, favorites, etc.
994 nuvoNetSrcMap.forEach((srcNum, val) -> {
997 List<TopMenu> topMenuItems = nuvoMenus.getSource().get(Integer.parseInt(srcNum) - 1).getTopMenu();
999 if (!topMenuItems.isEmpty()) {
1000 connector.sendCommand(
1001 SRC_KEY + srcNum + "MENU," + (topMenuItems.size() < 10 ? topMenuItems.size() : 10));
1002 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1004 for (int i = 0; i < (topMenuItems.size() < 10 ? topMenuItems.size() : 10); i++) {
1005 connector.sendCommand(SRC_KEY + srcNum + "MENUITEM" + (i + 1) + ","
1006 + (topMenuItems.get(i).getItems().isEmpty() ? ZERO : ONE) + ",0,\""
1007 + topMenuItems.get(i).getText() + "\"");
1008 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1012 String[] favorites = favoriteMap.get(srcNum);
1013 if (favorites != null) {
1014 connector.sendCommand(SRC_KEY + srcNum + "FAVORITES"
1015 + (favorites.length < 20 ? favorites.length : 20) + COMMA
1016 + ("1".equals(srcNum) ? ONE : ZERO) + COMMA + ("2".equals(srcNum) ? ONE : ZERO) + COMMA
1017 + ("3".equals(srcNum) ? ONE : ZERO) + COMMA + ("4".equals(srcNum) ? ONE : ZERO) + COMMA
1018 + ("5".equals(srcNum) ? ONE : ZERO) + COMMA + ("6".equals(srcNum) ? ONE : ZERO));
1019 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1021 for (int i = 0; i < (favorites.length < 20 ? favorites.length : 20); i++) {
1022 connector.sendCommand(SRC_KEY + srcNum + "FAVORITESITEM" + (i + 1000) + ",0,0,\""
1023 + favPrefixMap.get(srcNum) + favorites[i] + "\"");
1024 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1029 connector.sendCommand(SRC_KEY + srcNum + "DISPINFOTWO0,0,0,0,0,0,0");
1030 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1031 connector.sendCommand(SRC_KEY + srcNum + "DISPLINES0,0,0,\"Ready\",\"\",\"\",\"\"");
1032 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1035 } catch (NuvoException | InterruptedException e) {
1036 logger.debug("Error configuring NuvoNet for source: {}", srcNum);
1043 * Schedule the reconnection job
1045 private void scheduleReconnectJob() {
1046 logger.debug("Schedule reconnect job");
1047 cancelReconnectJob();
1048 reconnectJob = scheduler.scheduleWithFixedDelay(() -> {
1049 if (!connector.isConnected()) {
1050 logger.debug("Trying to reconnect...");
1052 if (openConnection()) {
1053 logger.debug("Reconnected");
1054 // Polling status will disconnect from MPS4 on reconnect
1058 enableNuvonet(true);
1060 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Reconnection failed");
1064 }, 1, RECON_POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
1068 * If a ping is not received within ping interval the connection is closed and a reconnect job is scheduled
1070 private void schedulePingTimeoutJob() {
1072 logger.debug("Schedule Ping Timeout job");
1073 cancelPingTimeoutJob();
1074 pingJob = scheduler.schedule(() -> {
1076 scheduleReconnectJob();
1077 }, PING_TIMEOUT_SEC, TimeUnit.SECONDS);
1079 logger.debug("Ping Timeout job not valid for serial connections");
1084 * Cancel the ping timeout job
1086 private void cancelPingTimeoutJob() {
1087 ScheduledFuture<?> pingJob = this.pingJob;
1088 if (pingJob != null) {
1089 pingJob.cancel(true);
1090 this.pingJob = null;
1094 private void pollStatus() {
1095 pollStatusNeeded = false;
1096 scheduler.submit(() -> {
1097 synchronized (sequenceLock) {
1099 connector.sendCommand(NuvoCommand.GET_CONTROLLER_VERSION);
1101 NuvoEnum.VALID_SOURCES.forEach(source -> {
1103 connector.sendQuery(NuvoEnum.valueOf(source), NuvoCommand.NAME);
1104 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1105 connector.sendQuery(NuvoEnum.valueOf(source), NuvoCommand.DISPINFO);
1106 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1107 connector.sendQuery(NuvoEnum.valueOf(source), NuvoCommand.DISPLINE);
1108 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1109 } catch (NuvoException | InterruptedException e) {
1110 logger.debug("Error Querying Source data: {}", e.getMessage());
1114 // Query all active zones to get their current status and eq configuration
1115 activeZones.forEach(zoneNum -> {
1117 connector.sendQuery(NuvoEnum.valueOf(ZONE + zoneNum), NuvoCommand.STATUS);
1118 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1119 connector.sendCfgCommand(NuvoEnum.valueOf(ZONE + zoneNum), NuvoCommand.EQ_QUERY, BLANK);
1120 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
1121 } catch (NuvoException | InterruptedException e) {
1122 logger.debug("Error Querying Zone data: {}", e.getMessage());
1126 List<StateOption> sourceStateOptions = new ArrayList<>();
1127 sourceLabels.keySet().forEach(key -> {
1128 sourceStateOptions.add(new StateOption(key, sourceLabels.get(key)));
1131 // Put the source labels on all active zones
1132 activeZones.forEach(zoneNum -> {
1133 stateDescriptionProvider.setStateOptions(
1134 new ChannelUID(getThing().getUID(),
1135 ZONE.toLowerCase() + zoneNum + CHANNEL_DELIMIT + CHANNEL_TYPE_SOURCE),
1136 sourceStateOptions);
1138 } catch (NuvoException e) {
1139 logger.debug("Error polling status from Nuvo: {}", e.getMessage());
1146 * Cancel the reconnection job
1148 private void cancelReconnectJob() {
1149 ScheduledFuture<?> reconnectJob = this.reconnectJob;
1150 if (reconnectJob != null) {
1151 reconnectJob.cancel(true);
1152 this.reconnectJob = null;
1157 * Schedule the polling job
1159 private void schedulePollingJob() {
1163 logger.debug("MPS4 doesn't support polling");
1166 logger.debug("Schedule polling job");
1169 // when the Nuvo amp is off, this will keep the connection (esp Serial over IP) alive and detect if the
1170 // connection goes down
1171 pollingJob = scheduler.scheduleWithFixedDelay(() -> {
1172 if (connector.isConnected()) {
1173 logger.debug("Polling the component for updated status...");
1175 synchronized (sequenceLock) {
1177 connector.sendCommand(NuvoCommand.GET_CONTROLLER_VERSION);
1178 } catch (NuvoException e) {
1179 logger.debug("Polling error: {}", e.getMessage());
1182 // if the last event received was more than 1.25 intervals ago,
1183 // the component is not responding even though the connection is still good
1184 if ((System.currentTimeMillis() - lastEventReceived) > (POLLING_INTERVAL_SEC * 1.25 * 1000)) {
1185 logger.debug("Component not responding to status requests");
1186 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
1187 "Component not responding to status requests");
1189 scheduleReconnectJob();
1193 }, INITIAL_POLLING_DELAY_SEC, POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
1197 * Cancel the polling job
1199 private void cancelPollingJob() {
1200 ScheduledFuture<?> pollingJob = this.pollingJob;
1201 if (pollingJob != null) {
1202 pollingJob.cancel(true);
1203 this.pollingJob = null;
1208 * Schedule the clock sync job
1210 private void scheduleClockSyncJob() {
1211 logger.debug("Schedule clock sync job");
1212 cancelClockSyncJob();
1213 clockSyncJob = scheduler.scheduleWithFixedDelay(() -> {
1214 if (this.isGConcerto) {
1216 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy,MM,dd,HH,mm");
1217 connector.sendCommand(NuvoCommand.CFGTIME.getValue() + dateFormat.format(new Date()));
1218 } catch (NuvoException e) {
1219 logger.debug("Error syncing clock: {}", e.getMessage());
1222 this.cancelClockSyncJob();
1224 }, INITIAL_CLOCK_SYNC_DELAY_SEC, CLOCK_SYNC_INTERVAL_SEC, TimeUnit.SECONDS);
1228 * Cancel the clock sync job
1230 private void cancelClockSyncJob() {
1231 ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
1232 if (clockSyncJob != null) {
1233 clockSyncJob.cancel(true);
1234 this.clockSyncJob = null;
1239 * Update the state of a channel (original method signature)
1241 * @param target the channel group
1242 * @param channelType the channel group item
1243 * @param value the value to be updated
1245 private void updateChannelState(NuvoEnum target, String channelType, String value) {
1246 updateChannelState(target, channelType, value, NO_ART);
1250 * Update the state of a channel (overloaded method to handle album_art channel)
1252 * @param target the channel group
1253 * @param channelType the channel group item
1254 * @param value the value to be updated
1255 * @param bytes the byte[] to load into the Image channel
1257 private void updateChannelState(NuvoEnum target, String channelType, String value, byte[] bytes) {
1258 String channel = target.name().toLowerCase() + CHANNEL_DELIMIT + channelType;
1260 if (!isLinked(channel)) {
1264 State state = UnDefType.UNDEF;
1266 if (UNDEF.equals(value)) {
1267 updateState(channel, state);
1271 switch (channelType) {
1272 case CHANNEL_TYPE_POWER:
1273 case CHANNEL_TYPE_MUTE:
1274 case CHANNEL_TYPE_DND:
1275 case CHANNEL_TYPE_PARTY:
1276 case CHANNEL_TYPE_ALLMUTE:
1277 case CHANNEL_TYPE_PAGE:
1278 case CHANNEL_TYPE_LOUDNESS:
1279 state = ON.equals(value) ? OnOffType.ON : OnOffType.OFF;
1281 case CHANNEL_TYPE_LOCK:
1282 state = ON.equals(value) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
1284 case CHANNEL_TYPE_SOURCE:
1285 case CHANNEL_TYPE_TREBLE:
1286 case CHANNEL_TYPE_BASS:
1287 case CHANNEL_TYPE_BALANCE:
1288 state = new DecimalType(value);
1290 case CHANNEL_TYPE_VOLUME:
1291 int volume = Integer.parseInt(value);
1292 long volumePct = Math
1293 .round((double) (MAX_VOLUME - volume) / (double) (MAX_VOLUME - MIN_VOLUME) * 100.0);
1294 state = new PercentType(BigDecimal.valueOf(volumePct));
1296 case CHANNEL_DISPLAY_LINE1:
1297 case CHANNEL_DISPLAY_LINE2:
1298 case CHANNEL_DISPLAY_LINE3:
1299 case CHANNEL_DISPLAY_LINE4:
1300 case CHANNEL_BUTTON_PRESS:
1301 state = new StringType(value);
1303 case CHANNEL_PLAY_MODE:
1304 state = new StringType(NuvoStatusCodes.PLAY_MODE.get(value));
1306 case CHANNEL_TRACK_LENGTH:
1307 case CHANNEL_TRACK_POSITION:
1308 state = new QuantityType<Time>(Integer.parseInt(value) / 10, NuvoHandler.API_SECOND_UNIT);
1310 case CHANNEL_ALBUM_ART:
1311 state = new RawType(bytes, RawType.DEFAULT_MIME_TYPE);
1316 updateState(channel, state);
1320 * Handle a button press from a UI Player item
1322 * @param target the nuvo zone to receive the command
1323 * @param command the button press command to send to the zone
1325 private void handleControlCommand(NuvoEnum target, Command command) throws NuvoException {
1326 if (command instanceof PlayPauseType) {
1327 connector.sendCommand(target, NuvoCommand.PLAYPAUSE);
1328 } else if (command instanceof NextPreviousType) {
1329 if (command == NextPreviousType.NEXT) {
1330 connector.sendCommand(target, NuvoCommand.NEXT);
1331 } else if (command == NextPreviousType.PREVIOUS) {
1332 connector.sendCommand(target, NuvoCommand.PREV);
1335 logger.warn("Unknown control command: {}", command);