]> git.basschouten.com Git - openhab-addons.git/blob
7869b78778185544738353c0ad7cc8bb3b25929e
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.nuvo.internal.handler;
14
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.*;
18
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;
30 import java.util.Set;
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;
40
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;
48
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;
94
95 /**
96  * The {@link NuvoHandler} is responsible for handling commands, which are sent to one of the channels.
97  *
98  * Based on the Rotel binding by Laurent Garnier
99  *
100  * @author Michael Lobstein - Initial contribution
101  */
102 @NonNullByDefault
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;
113
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";
119
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;
127
128     private static final int MPS4_PORT = 5006;
129
130     private static final byte[] NO_ART = { 0 };
131
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])$");
138
139     private final Logger logger = LoggerFactory.getLogger(NuvoHandler.class);
140     private final NuvoStateDescriptionOptionProvider stateDescriptionProvider;
141     private final SerialPortManager serialPortManager;
142     private final HttpClient httpClient;
143
144     private @Nullable ScheduledFuture<?> reconnectJob;
145     private @Nullable ScheduledFuture<?> pollingJob;
146     private @Nullable ScheduledFuture<?> clockSyncJob;
147     private @Nullable ScheduledFuture<?> pingJob;
148
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();
155
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[]>();
161
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>();
165
166     Set<Integer> activeZones = new HashSet<>(1);
167
168     // A tree map that maps the source ids to source labels
169     TreeMap<String, String> sourceLabels = new TreeMap<String, String>();
170
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;
174
175     /**
176      * Constructor
177      */
178     public NuvoHandler(Thing thing, NuvoStateDescriptionOptionProvider stateDescriptionProvider,
179             SerialPortManager serialPortManager, HttpClient httpClient) {
180         super(thing);
181         this.stateDescriptionProvider = stateDescriptionProvider;
182         this.serialPortManager = serialPortManager;
183         this.httpClient = httpClient;
184     }
185
186     @Override
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;
194
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";
202             }
203         } else {
204             if (port == null) {
205                 configError = "undefined port configuration setting";
206             } else if (port <= 0) {
207                 configError = "invalid port configuration setting";
208             }
209         }
210
211         if (configError != null) {
212             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError);
213             return;
214         }
215
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);
221         } else {
222             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
223                     "Either Serial port or Host & Port must be specifed");
224             return;
225         }
226
227         if (this.isMps4) {
228             logger.debug("Port set to {} configuring binding for MPS4 compatability", MPS4_PORT);
229
230             this.isAnyOhNuvoNet = (config.nuvoNetSrc1 == 2 || config.nuvoNetSrc2 == 2 || config.nuvoNetSrc3 == 2
231                     || config.nuvoNetSrc4 == 2 || config.nuvoNetSrc5 == 2 || config.nuvoNetSrc6 == 2);
232
233             if (this.isAnyOhNuvoNet) {
234                 logger.debug("At least one source is configured as an openHAB NuvoNet source");
235                 loadMenuConfiguration(config);
236
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);
243
244                 favoriteMap.put("1",
245                         !config.favoritesSrc1.isEmpty() ? config.favoritesSrc1.split(COMMA) : new String[0]);
246                 favoriteMap.put("2",
247                         !config.favoritesSrc2.isEmpty() ? config.favoritesSrc2.split(COMMA) : new String[0]);
248                 favoriteMap.put("3",
249                         !config.favoritesSrc3.isEmpty() ? config.favoritesSrc3.split(COMMA) : new String[0]);
250                 favoriteMap.put("4",
251                         !config.favoritesSrc4.isEmpty() ? config.favoritesSrc4.split(COMMA) : new String[0]);
252                 favoriteMap.put("5",
253                         !config.favoritesSrc5.isEmpty() ? config.favoritesSrc5.split(COMMA) : new String[0]);
254                 favoriteMap.put("6",
255                         !config.favoritesSrc6.isEmpty() ? config.favoritesSrc6.split(COMMA) : new String[0]);
256
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);
263
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);
270
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);
277             }
278         }
279
280         if (numZones != null) {
281             this.numZones = numZones;
282         }
283
284         activeZones = IntStream.range((1), (this.numZones + 1)).boxed().collect(Collectors.toSet());
285
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());
289
290             List<Integer> zonesToRemove = IntStream.range((this.numZones + 1), (MAX_ZONES + 1)).boxed()
291                     .collect(Collectors.toList());
292
293             zonesToRemove.forEach(zone -> channels.removeIf(c -> (c.getUID().getId().contains("zone" + zone))));
294             updateThing(editThing().withChannels(channels).build());
295         }
296
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)));
305             }
306         }
307
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);
314         });
315
316         if (config.clockSync) {
317             scheduleClockSyncJob();
318         }
319
320         scheduleReconnectJob();
321         schedulePollingJob();
322         schedulePingTimeoutJob();
323         updateStatus(ThingStatus.UNKNOWN);
324     }
325
326     @Override
327     public void dispose() {
328         if (this.isAnyOhNuvoNet) {
329             try {
330                 // disable NuvoNet for each source that was configured as an openHAB NuvoNet source
331                 nuvoNetSrcMap.forEach((srcNum, val) -> {
332                     if (val == 2) {
333                         try {
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);
343                         }
344                     }
345                 });
346
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");
356             }
357         }
358
359         cancelReconnectJob();
360         cancelPollingJob();
361         cancelClockSyncJob();
362         cancelPingTimeoutJob();
363         closeConnection();
364         super.dispose();
365     }
366
367     @Override
368     public Collection<Class<? extends ThingHandlerService>> getServices() {
369         return Collections.singletonList(NuvoThingActions.class);
370     }
371
372     public void handleRawCommand(@Nullable String command) {
373         synchronized (sequenceLock) {
374             try {
375                 connector.sendCommand(command);
376             } catch (NuvoException e) {
377                 logger.warn("Nuvo Command: {} failed", command);
378             }
379         }
380     }
381
382     /**
383      * Handle a command from the UI
384      *
385      * @param channelUID the channel sending the command
386      * @param command the command received
387      *
388      */
389     @Override
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());
394
395         String channelType = channelSplit[1];
396
397         if (getThing().getStatus() != ThingStatus.ONLINE) {
398             logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel);
399             return;
400         }
401
402         synchronized (sequenceLock) {
403             if (!connector.isConnected()) {
404                 logger.warn("Command {} from channel {} is ignored: connection not established", command, channel);
405                 return;
406             }
407
408             try {
409                 switch (channelType) {
410                     case CHANNEL_TYPE_POWER:
411                         if (command instanceof OnOffType) {
412                             connector.sendCommand(target, command == OnOffType.ON ? NuvoCommand.ON : NuvoCommand.OFF);
413                         }
414                         break;
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));
421                             }
422                         }
423                         break;
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));
430                             }
431                         }
432                         break;
433                     case CHANNEL_TYPE_VOLUME:
434                         if (command instanceof PercentType) {
435                             int value = (MAX_VOLUME
436                                     - (int) Math.round(
437                                             ((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME))
438                                     + MIN_VOLUME);
439                             logger.debug("Got volume command {} zone {}", value, target);
440                             connector.sendCommand(target, NuvoCommand.VOLUME, String.valueOf(value));
441                         }
442                         break;
443                     case CHANNEL_TYPE_MUTE:
444                         if (command instanceof OnOffType) {
445                             connector.sendCommand(target,
446                                     command == OnOffType.ON ? NuvoCommand.MUTE_ON : NuvoCommand.MUTE_OFF);
447                         }
448                         break;
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) {
455                                     value++;
456                                 }
457                                 logger.debug("Got treble command {} zone {}", value, target);
458                                 connector.sendCfgCommand(target, NuvoCommand.TREBLE, String.valueOf(value));
459                             }
460                         }
461                         break;
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) {
467                                     value++;
468                                 }
469                                 logger.debug("Got bass command {} zone {}", value, target);
470                                 connector.sendCfgCommand(target, NuvoCommand.BASS, String.valueOf(value));
471                             }
472                         }
473                         break;
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) {
479                                     value++;
480                                 }
481                                 logger.debug("Got balance command {} zone {}", value, target);
482                                 connector.sendCfgCommand(target, NuvoCommand.BALANCE,
483                                         NuvoStatusCodes.getBalanceFromInt(value));
484                             }
485                         }
486                         break;
487                     case CHANNEL_TYPE_LOUDNESS:
488                         if (command instanceof OnOffType) {
489                             connector.sendCfgCommand(target, NuvoCommand.LOUDNESS,
490                                     command == OnOffType.ON ? ONE : ZERO);
491                         }
492                         break;
493                     case CHANNEL_TYPE_CONTROL:
494                         handleControlCommand(target, command);
495                         break;
496                     case CHANNEL_TYPE_DND:
497                         if (command instanceof OnOffType) {
498                             connector.sendCommand(target,
499                                     command == OnOffType.ON ? NuvoCommand.DND_ON : NuvoCommand.DND_OFF);
500                         }
501                         break;
502                     case CHANNEL_TYPE_PARTY:
503                         if (command instanceof OnOffType) {
504                             connector.sendCommand(target,
505                                     command == OnOffType.ON ? NuvoCommand.PARTY_ON : NuvoCommand.PARTY_OFF);
506                         }
507                         break;
508                     case CHANNEL_DISPLAY_LINE1:
509                         if (command instanceof StringType) {
510                             connector.sendCommand(target, NuvoCommand.DISPLINE1, "\"" + command + "\"");
511                         }
512                         break;
513                     case CHANNEL_DISPLAY_LINE2:
514                         if (command instanceof StringType) {
515                             connector.sendCommand(target, NuvoCommand.DISPLINE2, "\"" + command + "\"");
516                         }
517                         break;
518                     case CHANNEL_DISPLAY_LINE3:
519                         if (command instanceof StringType) {
520                             connector.sendCommand(target, NuvoCommand.DISPLINE3, "\"" + command + "\"");
521                         }
522                         break;
523                     case CHANNEL_DISPLAY_LINE4:
524                         if (command instanceof StringType) {
525                             connector.sendCommand(target, NuvoCommand.DISPLINE4, "\"" + command + "\"");
526                         }
527                         break;
528                     case CHANNEL_TYPE_ALLOFF:
529                         if (command instanceof OnOffType) {
530                             connector.sendCommand(NuvoCommand.ALLOFF);
531                         }
532                         break;
533                     case CHANNEL_TYPE_ALLMUTE:
534                         if (command instanceof OnOffType) {
535                             connector.sendCommand(
536                                     command == OnOffType.ON ? NuvoCommand.ALLMUTE_ON : NuvoCommand.ALLMUTE_OFF);
537                         }
538                         break;
539                     case CHANNEL_TYPE_PAGE:
540                         if (command instanceof OnOffType) {
541                             connector.sendCommand(command == OnOffType.ON ? NuvoCommand.PAGE_ON : NuvoCommand.PAGE_OFF);
542                         }
543                         break;
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);
550
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)))));
554                             } else {
555                                 connector.sendCommand(commandStr);
556                             }
557                         }
558                         break;
559                     case CHANNEL_ART_URL:
560                         if (command instanceof StringType) {
561                             String url = command.toString();
562                             if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
563                                 try {
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));
570
571                                         updateChannelState(target, CHANNEL_ALBUM_ART, BLANK,
572                                                 contentResponse.getContent());
573                                     } else {
574                                         albumArtMap.put(target.getId(), NO_ART);
575                                         albumArtIds.put(target.getId(), 0);
576                                         updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
577                                         return;
578                                     }
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);
583                                     return;
584                                 }
585                                 albumArtIds.put(target.getId(), Math.abs(url.hashCode()));
586
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())))));
591                                 }
592                             } else {
593                                 albumArtMap.put(target.getId(), NO_ART);
594                                 albumArtIds.put(target.getId(), 0);
595                                 updateChannelState(target, CHANNEL_ALBUM_ART, UNDEF);
596                             }
597                         }
598                 }
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");
602                 closeConnection();
603                 scheduleReconnectJob();
604             }
605         }
606     }
607
608     /**
609      * Open the connection with the Nuvo device
610      *
611      * @return true if the connection is opened successfully or false if not
612      */
613     private synchronized boolean openConnection() {
614         connector.addEventListener(this);
615         try {
616             connector.open();
617         } catch (NuvoException e) {
618             logger.debug("openConnection() failed: {}", e.getMessage());
619         }
620         logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected");
621         return connector.isConnected();
622     }
623
624     /**
625      * Close the connection with the Nuvo device
626      */
627     private synchronized void closeConnection() {
628         if (connector.isConnected()) {
629             connector.close();
630             connector.removeEventListener(this);
631             pollStatusNeeded = true;
632             logger.debug("closeConnection(): disconnected");
633         }
634     }
635
636     /**
637      * Handle an event received from the Nuvo device
638      *
639      * @param event the event to process
640      */
641     @Override
642     public void onNewMessageEvent(NuvoMessageEvent evt) {
643         logger.debug("onNewMessageEvent: key {} = {}", evt.getKey(), evt.getValue());
644         lastEventReceived = System.currentTimeMillis();
645
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);
651         }
652
653         switch (type) {
654             case TYPE_VERSION:
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);
661                 } else {
662                     logger.debug("Grand Concerto not detected");
663                 }
664                 break;
665             case TYPE_RESTART:
666                 logger.debug("Restart message received; re-sending initialization messages");
667                 enableNuvonet(false);
668                 return;
669             case TYPE_PING:
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
673                 return;
674             case TYPE_ALLOFF:
675                 activeZones.forEach(zoneNum -> {
676                     updateChannelState(NuvoEnum.valueOf(ZONE + zoneNum), CHANNEL_TYPE_POWER, OFF);
677                 });
678                 break;
679             case TYPE_ALLMUTE:
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);
684                 });
685                 break;
686             case TYPE_PAGE:
687                 updateChannelState(NuvoEnum.SYSTEM, CHANNEL_TYPE_PAGE, ONE.equals(updateData) ? ON : OFF);
688                 break;
689             case TYPE_SOURCE_UPDATE:
690                 logger.debug("Source update: Source: {} - Value: {}", key, updateData);
691                 NuvoEnum targetSource = NuvoEnum.valueOf(SOURCE + key);
692
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));
698                     } else {
699                         logger.debug("no match on message: {}", updateData);
700                     }
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));
709                     } else {
710                         logger.debug("no match on message: {}", updateData);
711                     }
712                 } else if (updateData.contains(NAME_QUOTE)) {
713                     // example: NAME"Ipod"
714                     String name = updateData.split("\"")[1];
715                     sourceLabels.put(key, name);
716                 }
717                 break;
718             case TYPE_ZONE_UPDATE:
719                 logger.debug("Zone update: Zone: {} - Value: {}", key, updateData);
720                 // example : OFF
721                 // or: ON,SRC3,VOL63,DND0,LOCK0
722                 // or: ON,SRC3,MUTE,DND0,LOCK0
723
724                 NuvoEnum targetZone = NuvoEnum.valueOf(ZONE + key);
725
726                 if (OFF.equals(updateData)) {
727                     updateChannelState(targetZone, CHANNEL_TYPE_POWER, OFF);
728                     updateChannelState(targetZone, CHANNEL_TYPE_SOURCE, UNDEF);
729                 } else {
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));
734
735                         if (MUTE.equals(matcher.group(2))) {
736                             updateChannelState(targetZone, CHANNEL_TYPE_MUTE, ON);
737                         } else {
738                             updateChannelState(targetZone, CHANNEL_TYPE_MUTE, NuvoCommand.OFF.getValue());
739                             updateChannelState(targetZone, CHANNEL_TYPE_VOLUME, matcher.group(2).replace(VOL, BLANK));
740                         }
741
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);
744                     } else {
745                         logger.debug("no match on message: {}", updateData);
746                     }
747                 }
748                 break;
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);
752                 break;
753             case TYPE_ZONE_BUTTON2:
754                 String buttonAction = NuvoStatusCodes.BUTTON_CODE.get(updateData);
755
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);
759                 } else {
760                     logger.debug("Zone NuvoNet Button pressed: Source: {} - Unknown button code: {}", key, updateData);
761                     updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS, updateData);
762                 }
763                 break;
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;
769
770                 boolean exitMenu = false;
771                 if ("0xFFFFFFFF".equals(menuId)) {
772                     TopMenu topMenuItem = nuvoMenus.getSource().get(Integer.parseInt(key) - 1).getTopMenu()
773                             .get(menuItemIdx);
774                     logger.debug("Top Menu item selected: Source: {} - Menu Item: {}", key, topMenuItem.getText());
775                     updateChannelState(NuvoEnum.valueOf(SOURCE + key), CHANNEL_BUTTON_PRESS, topMenuItem.getText());
776
777                     List<String> subMenuItems = topMenuItem.getItems();
778
779                     if (subMenuItems.isEmpty()) {
780                         exitMenu = true;
781                     } else {
782                         // send submenu (maximum of 20 items)
783                         int subMenuSize = subMenuItems.size() < 20 ? subMenuItems.size() : 20;
784                         try {
785                             connector.sendCommand(zoneSource + "MENU" + (menuItemIdx + 11) + ",0,0," + subMenuSize
786                                     + ",0,0," + subMenuSize + ",\"" + topMenuItem.getText() + "\"");
787                             Thread.sleep(SLEEP_BETWEEN_CMD_MS);
788
789                             for (int i = 0; i < subMenuSize; i++) {
790                                 connector.sendCommand(
791                                         zoneSource + "MENUITEM" + (i + 1) + ",0,0,\"" + subMenuItems.get(i) + "\"");
792                             }
793                         } catch (NuvoException | InterruptedException e) {
794                             logger.debug("Error sending sub menu for {}", zoneSource);
795                         }
796                     }
797                 } else {
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);
802
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);
807                     exitMenu = true;
808                 }
809
810                 if (exitMenu) {
811                     try {
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);
816                     }
817                 }
818                 break;
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])) {
824                     try {
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]);
828                     }
829                 }
830
831                 break;
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);
843                 } else {
844                     logger.debug("no match on message: {}", updateData);
845                 }
846                 break;
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]));
852
853                 try {
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);
857                     } else {
858                         connector.sendCommand(SRC_KEY + key + ALBUM_ART_AVAILABLE + ZERO_COMMA);
859                     }
860                 } catch (NuvoException e) {
861                     logger.debug("Error sending ALBUMARTAVAILABLE command for source: {}", key);
862                 }
863                 break;
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]);
871
872                 if (requestedId == albumArtIds.get(SRC_KEY + key)) {
873                     byte[] chunk = new byte[length];
874                     byte[] albumArtBytes = albumArtMap.get(SRC_KEY + key);
875
876                     if (albumArtBytes != null) {
877                         System.arraycopy(albumArtBytes, offset, chunk, 0, length);
878                         final String frag = Base64.getEncoder().encodeToString(chunk);
879                         try {
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,
884                                     requestedId);
885                         }
886                     }
887                 }
888                 break;
889             case TYPE_FAVORITE_REQ:
890                 logger.debug("Favorite request for source: {} - favoriteId: {}", key, updateData);
891                 try {
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);
897                 }
898                 break;
899             default:
900                 logger.debug("onNewMessageEvent: unhandled key {}", key);
901                 // Return here because receiving an unknown message does not indicate that one can poll
902                 return;
903         }
904
905         if (isMps4 && pollStatusNeeded) {
906             pollStatus();
907         }
908     }
909
910     private void loadMenuConfiguration(NuvoThingConfiguration config) {
911         StringBuilder menuXml = new StringBuilder("<menu>");
912
913         if (!config.menuXmlSrc1.isEmpty()) {
914             menuXml.append("<source>" + config.menuXmlSrc1 + "</source>");
915         } else {
916             menuXml.append("<source/>");
917         }
918         if (!config.menuXmlSrc2.isEmpty()) {
919             menuXml.append("<source>" + config.menuXmlSrc2 + "</source>");
920         } else {
921             menuXml.append("<source/>");
922         }
923         if (!config.menuXmlSrc3.isEmpty()) {
924             menuXml.append("<source>" + config.menuXmlSrc3 + "</source>");
925         } else {
926             menuXml.append("<source/>");
927         }
928         if (!config.menuXmlSrc4.isEmpty()) {
929             menuXml.append("<source>" + config.menuXmlSrc4 + "</source>");
930         } else {
931             menuXml.append("<source/>");
932         }
933         if (!config.menuXmlSrc5.isEmpty()) {
934             menuXml.append("<source>" + config.menuXmlSrc5 + "</source>");
935         } else {
936             menuXml.append("<source/>");
937         }
938         if (!config.menuXmlSrc6.isEmpty()) {
939             menuXml.append("<source>" + config.menuXmlSrc6 + "</source>");
940         } else {
941             menuXml.append("<source/>");
942         }
943         menuXml.append("</menu>");
944
945         try {
946             JAXBContext ctx = JAXBUtils.JAXBCONTEXT_NUVO_MENU;
947             if (ctx != null) {
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);
953                     if (menu != null) {
954                         nuvoMenus = menu;
955                         return;
956                     }
957                 }
958             }
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());
962         }
963     }
964
965     private void enableNuvonet(boolean showReady) {
966         if (!this.isAnyOhNuvoNet) {
967             return;
968         }
969
970         // enable NuvoNet for each source configured as an openHAB NuvoNet source
971         nuvoNetSrcMap.forEach((srcNum, val) -> {
972             if (val == 2) {
973                 try {
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);
978                 }
979             }
980         });
981
982         try {
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");
991         }
992
993         // go though each source and if is openHAB NuvoNet then configure menu, favorites, etc.
994         nuvoNetSrcMap.forEach((srcNum, val) -> {
995             if (val == 2) {
996                 try {
997                     List<TopMenu> topMenuItems = nuvoMenus.getSource().get(Integer.parseInt(srcNum) - 1).getTopMenu();
998
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);
1003
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);
1009                         }
1010                     }
1011
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);
1020
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);
1025                         }
1026                     }
1027
1028                     if (showReady) {
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);
1033                     }
1034
1035                 } catch (NuvoException | InterruptedException e) {
1036                     logger.debug("Error configuring NuvoNet for source: {}", srcNum);
1037                 }
1038             }
1039         });
1040     }
1041
1042     /**
1043      * Schedule the reconnection job
1044      */
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...");
1051                 closeConnection();
1052                 if (openConnection()) {
1053                     logger.debug("Reconnected");
1054                     // Polling status will disconnect from MPS4 on reconnect
1055                     if (!isMps4) {
1056                         pollStatus();
1057                     }
1058                     enableNuvonet(true);
1059                 } else {
1060                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Reconnection failed");
1061                     closeConnection();
1062                 }
1063             }
1064         }, 1, RECON_POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
1065     }
1066
1067     /**
1068      * If a ping is not received within ping interval the connection is closed and a reconnect job is scheduled
1069      */
1070     private void schedulePingTimeoutJob() {
1071         if (isMps4) {
1072             logger.debug("Schedule Ping Timeout job");
1073             cancelPingTimeoutJob();
1074             pingJob = scheduler.schedule(() -> {
1075                 closeConnection();
1076                 scheduleReconnectJob();
1077             }, PING_TIMEOUT_SEC, TimeUnit.SECONDS);
1078         } else {
1079             logger.debug("Ping Timeout job not valid for serial connections");
1080         }
1081     }
1082
1083     /**
1084      * Cancel the ping timeout job
1085      */
1086     private void cancelPingTimeoutJob() {
1087         ScheduledFuture<?> pingJob = this.pingJob;
1088         if (pingJob != null) {
1089             pingJob.cancel(true);
1090             this.pingJob = null;
1091         }
1092     }
1093
1094     private void pollStatus() {
1095         pollStatusNeeded = false;
1096         scheduler.submit(() -> {
1097             synchronized (sequenceLock) {
1098                 try {
1099                     connector.sendCommand(NuvoCommand.GET_CONTROLLER_VERSION);
1100
1101                     NuvoEnum.VALID_SOURCES.forEach(source -> {
1102                         try {
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());
1111                         }
1112                     });
1113
1114                     // Query all active zones to get their current status and eq configuration
1115                     activeZones.forEach(zoneNum -> {
1116                         try {
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());
1123                         }
1124                     });
1125
1126                     List<StateOption> sourceStateOptions = new ArrayList<>();
1127                     sourceLabels.keySet().forEach(key -> {
1128                         sourceStateOptions.add(new StateOption(key, sourceLabels.get(key)));
1129                     });
1130
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);
1137                     });
1138                 } catch (NuvoException e) {
1139                     logger.debug("Error polling status from Nuvo: {}", e.getMessage());
1140                 }
1141             }
1142         });
1143     }
1144
1145     /**
1146      * Cancel the reconnection job
1147      */
1148     private void cancelReconnectJob() {
1149         ScheduledFuture<?> reconnectJob = this.reconnectJob;
1150         if (reconnectJob != null) {
1151             reconnectJob.cancel(true);
1152             this.reconnectJob = null;
1153         }
1154     }
1155
1156     /**
1157      * Schedule the polling job
1158      */
1159     private void schedulePollingJob() {
1160         cancelPollingJob();
1161
1162         if (isMps4) {
1163             logger.debug("MPS4 doesn't support polling");
1164             return;
1165         } else {
1166             logger.debug("Schedule polling job");
1167         }
1168
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...");
1174
1175                 synchronized (sequenceLock) {
1176                     try {
1177                         connector.sendCommand(NuvoCommand.GET_CONTROLLER_VERSION);
1178                     } catch (NuvoException e) {
1179                         logger.debug("Polling error: {}", e.getMessage());
1180                     }
1181
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");
1188                         closeConnection();
1189                         scheduleReconnectJob();
1190                     }
1191                 }
1192             }
1193         }, INITIAL_POLLING_DELAY_SEC, POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
1194     }
1195
1196     /**
1197      * Cancel the polling job
1198      */
1199     private void cancelPollingJob() {
1200         ScheduledFuture<?> pollingJob = this.pollingJob;
1201         if (pollingJob != null) {
1202             pollingJob.cancel(true);
1203             this.pollingJob = null;
1204         }
1205     }
1206
1207     /**
1208      * Schedule the clock sync job
1209      */
1210     private void scheduleClockSyncJob() {
1211         logger.debug("Schedule clock sync job");
1212         cancelClockSyncJob();
1213         clockSyncJob = scheduler.scheduleWithFixedDelay(() -> {
1214             if (this.isGConcerto) {
1215                 try {
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());
1220                 }
1221             } else {
1222                 this.cancelClockSyncJob();
1223             }
1224         }, INITIAL_CLOCK_SYNC_DELAY_SEC, CLOCK_SYNC_INTERVAL_SEC, TimeUnit.SECONDS);
1225     }
1226
1227     /**
1228      * Cancel the clock sync job
1229      */
1230     private void cancelClockSyncJob() {
1231         ScheduledFuture<?> clockSyncJob = this.clockSyncJob;
1232         if (clockSyncJob != null) {
1233             clockSyncJob.cancel(true);
1234             this.clockSyncJob = null;
1235         }
1236     }
1237
1238     /**
1239      * Update the state of a channel (original method signature)
1240      *
1241      * @param target the channel group
1242      * @param channelType the channel group item
1243      * @param value the value to be updated
1244      */
1245     private void updateChannelState(NuvoEnum target, String channelType, String value) {
1246         updateChannelState(target, channelType, value, NO_ART);
1247     }
1248
1249     /**
1250      * Update the state of a channel (overloaded method to handle album_art channel)
1251      *
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
1256      */
1257     private void updateChannelState(NuvoEnum target, String channelType, String value, byte[] bytes) {
1258         String channel = target.name().toLowerCase() + CHANNEL_DELIMIT + channelType;
1259
1260         if (!isLinked(channel)) {
1261             return;
1262         }
1263
1264         State state = UnDefType.UNDEF;
1265
1266         if (UNDEF.equals(value)) {
1267             updateState(channel, state);
1268             return;
1269         }
1270
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;
1280                 break;
1281             case CHANNEL_TYPE_LOCK:
1282                 state = ON.equals(value) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
1283                 break;
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);
1289                 break;
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));
1295                 break;
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);
1302                 break;
1303             case CHANNEL_PLAY_MODE:
1304                 state = new StringType(NuvoStatusCodes.PLAY_MODE.get(value));
1305                 break;
1306             case CHANNEL_TRACK_LENGTH:
1307             case CHANNEL_TRACK_POSITION:
1308                 state = new QuantityType<Time>(Integer.parseInt(value) / 10, NuvoHandler.API_SECOND_UNIT);
1309                 break;
1310             case CHANNEL_ALBUM_ART:
1311                 state = new RawType(bytes, RawType.DEFAULT_MIME_TYPE);
1312                 break;
1313             default:
1314                 break;
1315         }
1316         updateState(channel, state);
1317     }
1318
1319     /**
1320      * Handle a button press from a UI Player item
1321      *
1322      * @param target the nuvo zone to receive the command
1323      * @param command the button press command to send to the zone
1324      */
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);
1333             }
1334         } else {
1335             logger.warn("Unknown control command: {}", command);
1336         }
1337     }
1338 }