]> git.basschouten.com Git - openhab-addons.git/blob
b781ffbdfe66616be7e409048d12f1a78699f512
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.monopriceaudio.internal.handler;
14
15 import static org.openhab.binding.monopriceaudio.internal.MonopriceAudioBindingConstants.*;
16
17 import java.math.BigDecimal;
18 import java.util.ArrayList;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27 import java.util.stream.Collectors;
28 import java.util.stream.IntStream;
29 import java.util.stream.Stream;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.monopriceaudio.internal.MonopriceAudioException;
34 import org.openhab.binding.monopriceaudio.internal.MonopriceAudioStateDescriptionOptionProvider;
35 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioCommand;
36 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioConnector;
37 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioDefaultConnector;
38 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioIpConnector;
39 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioMessageEvent;
40 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioMessageEventListener;
41 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioSerialConnector;
42 import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioZone;
43 import org.openhab.binding.monopriceaudio.internal.configuration.MonopriceAudioThingConfiguration;
44 import org.openhab.binding.monopriceaudio.internal.dto.MonopriceAudioZoneDTO;
45 import org.openhab.core.io.transport.serial.SerialPortManager;
46 import org.openhab.core.library.types.DecimalType;
47 import org.openhab.core.library.types.OnOffType;
48 import org.openhab.core.library.types.OpenClosedType;
49 import org.openhab.core.library.types.PercentType;
50 import org.openhab.core.thing.Channel;
51 import org.openhab.core.thing.ChannelUID;
52 import org.openhab.core.thing.Thing;
53 import org.openhab.core.thing.ThingStatus;
54 import org.openhab.core.thing.ThingStatusDetail;
55 import org.openhab.core.thing.binding.BaseThingHandler;
56 import org.openhab.core.types.Command;
57 import org.openhab.core.types.RefreshType;
58 import org.openhab.core.types.State;
59 import org.openhab.core.types.StateOption;
60 import org.openhab.core.types.UnDefType;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 /**
65  * The {@link MonopriceAudioHandler} is responsible for handling commands, which are sent to one of the channels.
66  *
67  * Based on the Rotel binding by Laurent Garnier
68  *
69  * @author Michael Lobstein - Initial contribution
70  */
71 @NonNullByDefault
72 public class MonopriceAudioHandler extends BaseThingHandler implements MonopriceAudioMessageEventListener {
73     private static final long RECON_POLLING_INTERVAL_SEC = 60;
74     private static final long INITIAL_POLLING_DELAY_SEC = 5;
75     private static final Pattern PATTERN = Pattern
76             .compile("^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})");
77
78     private static final String ZONE = "ZONE";
79     private static final String ALL = "all";
80     private static final String CHANNEL_DELIMIT = "#";
81     private static final String ON_STR = "01";
82     private static final String OFF_STR = "00";
83
84     private static final int ONE = 1;
85     private static final int MAX_ZONES = 18;
86     private static final int MAX_SRC = 6;
87     private static final int MIN_VOLUME = 0;
88     private static final int MAX_VOLUME = 38;
89     private static final int MIN_TONE = -7;
90     private static final int MAX_TONE = 7;
91     private static final int MIN_BALANCE = -10;
92     private static final int MAX_BALANCE = 10;
93     private static final int BALANCE_OFFSET = 10;
94     private static final int TONE_OFFSET = 7;
95
96     // build a Map with a MonopriceAudioZoneDTO for each zoneId
97     private final Map<String, MonopriceAudioZoneDTO> zoneDataMap = MonopriceAudioZone.VALID_ZONE_IDS.stream()
98             .collect(Collectors.toMap(s -> s, s -> new MonopriceAudioZoneDTO()));
99
100     private final Logger logger = LoggerFactory.getLogger(MonopriceAudioHandler.class);
101     private final MonopriceAudioStateDescriptionOptionProvider stateDescriptionProvider;
102     private final SerialPortManager serialPortManager;
103
104     private @Nullable ScheduledFuture<?> reconnectJob;
105     private @Nullable ScheduledFuture<?> pollingJob;
106
107     private MonopriceAudioConnector connector = new MonopriceAudioDefaultConnector();
108
109     private Set<String> ignoreZones = new HashSet<>();
110     private long lastPollingUpdate = System.currentTimeMillis();
111     private long pollingInterval = 0;
112     private int numZones = 0;
113     private int allVolume = 1;
114     private int initialAllVolume = 0;
115     private Object sequenceLock = new Object();
116
117     public MonopriceAudioHandler(Thing thing, MonopriceAudioStateDescriptionOptionProvider stateDescriptionProvider,
118             SerialPortManager serialPortManager) {
119         super(thing);
120         this.stateDescriptionProvider = stateDescriptionProvider;
121         this.serialPortManager = serialPortManager;
122     }
123
124     @Override
125     public void initialize() {
126         final String uid = this.getThing().getUID().getAsString();
127         MonopriceAudioThingConfiguration config = getConfigAs(MonopriceAudioThingConfiguration.class);
128         final String serialPort = config.serialPort;
129         final String host = config.host;
130         final Integer port = config.port;
131         final String ignoreZonesConfig = config.ignoreZones;
132
133         // Check configuration settings
134         String configError = null;
135         if ((serialPort == null || serialPort.isEmpty()) && (host == null || host.isEmpty())) {
136             configError = "undefined serialPort and host configuration settings; please set one of them";
137         } else if (serialPort != null && (host == null || host.isEmpty())) {
138             if (serialPort.toLowerCase().startsWith("rfc2217")) {
139                 configError = "use host and port configuration settings for a serial over IP connection";
140             }
141         } else {
142             if (port == null) {
143                 configError = "undefined port configuration setting";
144             } else if (port <= 0) {
145                 configError = "invalid port configuration setting";
146             }
147         }
148
149         if (configError != null) {
150             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError);
151             return;
152         }
153
154         if (serialPort != null) {
155             connector = new MonopriceAudioSerialConnector(serialPortManager, serialPort, uid);
156         } else if (port != null) {
157             connector = new MonopriceAudioIpConnector(host, port, uid);
158         } else {
159             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
160                     "Either Serial port or Host & Port must be specifed");
161             return;
162         }
163
164         pollingInterval = config.pollingInterval;
165         numZones = config.numZones;
166         initialAllVolume = config.initialAllVolume;
167
168         // If zones were specified to be ignored by the 'all*' commands, use the specified binding
169         // zone ids to get the controller's internal zone ids and save those to a list
170         if (ignoreZonesConfig != null) {
171             for (String zone : ignoreZonesConfig.split(",")) {
172                 try {
173                     int zoneInt = Integer.parseInt(zone);
174                     if (zoneInt >= ONE && zoneInt <= MAX_ZONES) {
175                         ignoreZones.add(ZONE + zoneInt);
176                     } else {
177                         logger.warn("Invalid ignore zone value: {}, value must be between {} and {}", zone, ONE,
178                                 MAX_ZONES);
179                     }
180                 } catch (NumberFormatException nfe) {
181                     logger.warn("Invalid ignore zone value: {}", zone);
182                 }
183             }
184         }
185
186         // Build a state option list for the source labels
187         List<StateOption> sourcesLabels = new ArrayList<>();
188         sourcesLabels.add(new StateOption("1", config.inputLabel1));
189         sourcesLabels.add(new StateOption("2", config.inputLabel2));
190         sourcesLabels.add(new StateOption("3", config.inputLabel3));
191         sourcesLabels.add(new StateOption("4", config.inputLabel4));
192         sourcesLabels.add(new StateOption("5", config.inputLabel5));
193         sourcesLabels.add(new StateOption("6", config.inputLabel6));
194
195         // Put the source labels on all active zones
196         List<Integer> activeZones = IntStream.range(1, numZones + 1).boxed().collect(Collectors.toList());
197
198         stateDescriptionProvider.setStateOptions(
199                 new ChannelUID(getThing().getUID(), ALL + CHANNEL_DELIMIT + CHANNEL_TYPE_ALLSOURCE), sourcesLabels);
200         activeZones.forEach(zoneNum -> {
201             stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(),
202                     ZONE.toLowerCase() + zoneNum + CHANNEL_DELIMIT + CHANNEL_TYPE_SOURCE), sourcesLabels);
203         });
204
205         // remove the channels for the zones we are not using
206         if (numZones < MAX_ZONES) {
207             List<Channel> channels = new ArrayList<>(this.getThing().getChannels());
208
209             List<Integer> zonesToRemove = IntStream.range(numZones + 1, MAX_ZONES + 1).boxed()
210                     .collect(Collectors.toList());
211
212             zonesToRemove.forEach(zone -> {
213                 channels.removeIf(c -> (c.getUID().getId().contains(ZONE.toLowerCase() + zone)));
214             });
215             updateThing(editThing().withChannels(channels).build());
216         }
217
218         // initialize the all volume state
219         allVolume = initialAllVolume;
220         long allVolumePct = Math
221                 .round((double) (initialAllVolume - MIN_VOLUME) / (double) (MAX_VOLUME - MIN_VOLUME) * 100.0);
222         updateState(ALL + CHANNEL_DELIMIT + CHANNEL_TYPE_ALLVOLUME, new PercentType(BigDecimal.valueOf(allVolumePct)));
223
224         scheduleReconnectJob();
225         schedulePollingJob();
226
227         updateStatus(ThingStatus.UNKNOWN);
228     }
229
230     @Override
231     public void dispose() {
232         cancelReconnectJob();
233         cancelPollingJob();
234         closeConnection();
235         ignoreZones.clear();
236     }
237
238     @Override
239     public void handleCommand(ChannelUID channelUID, Command command) {
240         String channel = channelUID.getId();
241         String[] channelSplit = channel.split(CHANNEL_DELIMIT);
242         MonopriceAudioZone zone = MonopriceAudioZone.valueOf(channelSplit[0].toUpperCase());
243         String channelType = channelSplit[1];
244
245         if (getThing().getStatus() != ThingStatus.ONLINE) {
246             logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel);
247             return;
248         }
249
250         boolean success = true;
251         synchronized (sequenceLock) {
252             if (!connector.isConnected()) {
253                 logger.debug("Command {} from channel {} is ignored: connection not established", command, channel);
254                 return;
255             }
256
257             if (command instanceof RefreshType) {
258                 updateChannelState(zone, channelType, zoneDataMap.get(zone.getZoneId()));
259                 return;
260             }
261
262             Stream<String> zoneStream = MonopriceAudioZone.VALID_ZONES.stream().limit(numZones);
263             try {
264                 switch (channelType) {
265                     case CHANNEL_TYPE_POWER:
266                         if (command instanceof OnOffType) {
267                             connector.sendCommand(zone, MonopriceAudioCommand.POWER, command == OnOffType.ON ? 1 : 0);
268                             zoneDataMap.get(zone.getZoneId()).setPower(command == OnOffType.ON ? ON_STR : OFF_STR);
269                         }
270                         break;
271                     case CHANNEL_TYPE_SOURCE:
272                         if (command instanceof DecimalType) {
273                             int value = ((DecimalType) command).intValue();
274                             if (value >= ONE && value <= MAX_SRC) {
275                                 logger.debug("Got source command {} zone {}", value, zone);
276                                 connector.sendCommand(zone, MonopriceAudioCommand.SOURCE, value);
277                                 zoneDataMap.get(zone.getZoneId()).setSource(String.format("%02d", value));
278                             }
279                         }
280                         break;
281                     case CHANNEL_TYPE_VOLUME:
282                         if (command instanceof PercentType) {
283                             int value = (int) Math
284                                     .round(((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME))
285                                     + MIN_VOLUME;
286                             logger.debug("Got volume command {} zone {}", value, zone);
287                             connector.sendCommand(zone, MonopriceAudioCommand.VOLUME, value);
288                             zoneDataMap.get(zone.getZoneId()).setVolume(value);
289                         }
290                         break;
291                     case CHANNEL_TYPE_MUTE:
292                         if (command instanceof OnOffType) {
293                             connector.sendCommand(zone, MonopriceAudioCommand.MUTE, command == OnOffType.ON ? 1 : 0);
294                             zoneDataMap.get(zone.getZoneId()).setMute(command == OnOffType.ON ? ON_STR : OFF_STR);
295                         }
296                         break;
297                     case CHANNEL_TYPE_TREBLE:
298                         if (command instanceof DecimalType) {
299                             int value = ((DecimalType) command).intValue();
300                             if (value >= MIN_TONE && value <= MAX_TONE) {
301                                 logger.debug("Got treble command {} zone {}", value, zone);
302                                 connector.sendCommand(zone, MonopriceAudioCommand.TREBLE, value + TONE_OFFSET);
303                                 zoneDataMap.get(zone.getZoneId()).setTreble(value + TONE_OFFSET);
304                             }
305                         }
306                         break;
307                     case CHANNEL_TYPE_BASS:
308                         if (command instanceof DecimalType) {
309                             int value = ((DecimalType) command).intValue();
310                             if (value >= MIN_TONE && value <= MAX_TONE) {
311                                 logger.debug("Got bass command {} zone {}", value, zone);
312                                 connector.sendCommand(zone, MonopriceAudioCommand.BASS, value + TONE_OFFSET);
313                                 zoneDataMap.get(zone.getZoneId()).setBass(value + TONE_OFFSET);
314                             }
315                         }
316                         break;
317                     case CHANNEL_TYPE_BALANCE:
318                         if (command instanceof DecimalType) {
319                             int value = ((DecimalType) command).intValue();
320                             if (value >= MIN_BALANCE && value <= MAX_BALANCE) {
321                                 logger.debug("Got balance command {} zone {}", value, zone);
322                                 connector.sendCommand(zone, MonopriceAudioCommand.BALANCE, value + BALANCE_OFFSET);
323                                 zoneDataMap.get(zone.getZoneId()).setBalance(value + BALANCE_OFFSET);
324                             }
325                         }
326                         break;
327                     case CHANNEL_TYPE_DND:
328                         if (command instanceof OnOffType) {
329                             connector.sendCommand(zone, MonopriceAudioCommand.DND, command == OnOffType.ON ? 1 : 0);
330                             zoneDataMap.get(zone.getZoneId()).setDnd(command == OnOffType.ON ? ON_STR : OFF_STR);
331                         }
332                         break;
333                     case CHANNEL_TYPE_ALLPOWER:
334                         if (command instanceof OnOffType) {
335                             zoneStream.forEach((zoneName) -> {
336                                 if (command == OnOffType.OFF || !ignoreZones.contains(zoneName)) {
337                                     try {
338                                         connector.sendCommand(MonopriceAudioZone.valueOf(zoneName),
339                                                 MonopriceAudioCommand.POWER, command == OnOffType.ON ? 1 : 0);
340                                         if (command == OnOffType.ON) {
341                                             // reset the volume of each zone to allVolume
342                                             connector.sendCommand(MonopriceAudioZone.valueOf(zoneName),
343                                                     MonopriceAudioCommand.VOLUME, allVolume);
344                                         }
345                                     } catch (MonopriceAudioException e) {
346                                         logger.warn("Error Turning All Zones On: {}", e.getMessage());
347                                     }
348                                 }
349
350                             });
351                         }
352                         break;
353                     case CHANNEL_TYPE_ALLSOURCE:
354                         if (command instanceof DecimalType) {
355                             int value = ((DecimalType) command).intValue();
356                             if (value >= ONE && value <= MAX_SRC) {
357                                 zoneStream.forEach((zoneName) -> {
358                                     if (!ignoreZones.contains(zoneName)) {
359                                         try {
360                                             connector.sendCommand(MonopriceAudioZone.valueOf(zoneName),
361                                                     MonopriceAudioCommand.SOURCE, value);
362                                         } catch (MonopriceAudioException e) {
363                                             logger.warn("Error Setting Source for  All Zones: {}", e.getMessage());
364                                         }
365                                     }
366                                 });
367                             }
368                         }
369                         break;
370                     case CHANNEL_TYPE_ALLVOLUME:
371                         if (command instanceof PercentType) {
372                             int value = (int) Math
373                                     .round(((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME))
374                                     + MIN_VOLUME;
375                             allVolume = value;
376                             zoneStream.forEach((zoneName) -> {
377                                 if (!ignoreZones.contains(zoneName)) {
378                                     try {
379                                         connector.sendCommand(MonopriceAudioZone.valueOf(zoneName),
380                                                 MonopriceAudioCommand.VOLUME, value);
381                                     } catch (MonopriceAudioException e) {
382                                         logger.warn("Error Setting Volume for All Zones: {}", e.getMessage());
383                                     }
384                                 }
385                             });
386                         }
387                         break;
388                     case CHANNEL_TYPE_ALLMUTE:
389                         if (command instanceof OnOffType) {
390                             int cmd = command == OnOffType.ON ? 1 : 0;
391                             zoneStream.forEach((zoneName) -> {
392                                 if (!ignoreZones.contains(zoneName)) {
393                                     try {
394                                         connector.sendCommand(MonopriceAudioZone.valueOf(zoneName),
395                                                 MonopriceAudioCommand.MUTE, cmd);
396                                     } catch (MonopriceAudioException e) {
397                                         logger.warn("Error Setting Mute for All Zones: {}", e.getMessage());
398                                     }
399                                 }
400                             });
401                         }
402                         break;
403                     default:
404                         success = false;
405                         logger.debug("Command {} from channel {} failed: unexpected command", command, channel);
406                         break;
407                 }
408
409                 if (success) {
410                     logger.trace("Command {} from channel {} succeeded", command, channel);
411                 }
412             } catch (MonopriceAudioException e) {
413                 logger.warn("Command {} from channel {} failed: {}", command, channel, e.getMessage());
414                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Sending command failed");
415                 closeConnection();
416                 scheduleReconnectJob();
417             }
418         }
419     }
420
421     /**
422      * Open the connection with the MonopriceAudio device
423      *
424      * @return true if the connection is opened successfully or false if not
425      */
426     private synchronized boolean openConnection() {
427         connector.addEventListener(this);
428         try {
429             connector.open();
430         } catch (MonopriceAudioException e) {
431             logger.debug("openConnection() failed: {}", e.getMessage());
432         }
433         logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected");
434         return connector.isConnected();
435     }
436
437     /**
438      * Close the connection with the MonopriceAudio device
439      */
440     private synchronized void closeConnection() {
441         if (connector.isConnected()) {
442             connector.close();
443             connector.removeEventListener(this);
444             logger.debug("closeConnection(): disconnected");
445         }
446     }
447
448     @Override
449     public void onNewMessageEvent(MonopriceAudioMessageEvent evt) {
450         String key = evt.getKey();
451         String updateData = evt.getValue().trim();
452         if (!MonopriceAudioConnector.KEY_ERROR.equals(key)) {
453             updateStatus(ThingStatus.ONLINE);
454         }
455         try {
456             switch (key) {
457                 case MonopriceAudioConnector.KEY_ERROR:
458                     logger.debug("Reading feedback message failed");
459                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Reading thread ended");
460                     closeConnection();
461                     break;
462
463                 case MonopriceAudioConnector.KEY_ZONE_UPDATE:
464                     String zoneId = updateData.substring(0, 2);
465
466                     if (MonopriceAudioZone.VALID_ZONE_IDS.contains(zoneId)) {
467                         MonopriceAudioZone targetZone = MonopriceAudioZone.fromZoneId(zoneId);
468                         processZoneUpdate(targetZone, zoneDataMap.get(zoneId), updateData);
469                     } else {
470                         logger.warn("invalid event: {} for key: {}", evt.getValue(), key);
471                     }
472                     break;
473                 default:
474                     logger.debug("onNewMessageEvent: unhandled key {}", key);
475                     break;
476             }
477         } catch (NumberFormatException e) {
478             logger.warn("Invalid value {} for key {}", updateData, key);
479         } catch (MonopriceAudioException e) {
480             logger.warn("Error processing zone update: {}", e.getMessage());
481         }
482     }
483
484     /**
485      * Schedule the reconnection job
486      */
487     private void scheduleReconnectJob() {
488         logger.debug("Schedule reconnect job");
489         cancelReconnectJob();
490         reconnectJob = scheduler.scheduleWithFixedDelay(() -> {
491             synchronized (sequenceLock) {
492                 if (!connector.isConnected()) {
493                     logger.debug("Trying to reconnect...");
494                     closeConnection();
495                     String error = null;
496
497                     if (openConnection()) {
498                         try {
499                             long prevUpdateTime = lastPollingUpdate;
500                             connector.queryZone(MonopriceAudioZone.ZONE1);
501
502                             // prevUpdateTime should have changed if a zone update was received
503                             if (lastPollingUpdate == prevUpdateTime) {
504                                 error = "Controller not responding to status requests";
505                             }
506
507                         } catch (MonopriceAudioException e) {
508                             error = "First command after connection failed";
509                             logger.warn("{}: {}", error, e.getMessage());
510                             closeConnection();
511                         }
512                     } else {
513                         error = "Reconnection failed";
514                     }
515                     if (error != null) {
516                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, error);
517                     } else {
518                         updateStatus(ThingStatus.ONLINE);
519                         lastPollingUpdate = System.currentTimeMillis();
520                     }
521                 }
522             }
523         }, 1, RECON_POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
524     }
525
526     /**
527      * Cancel the reconnection job
528      */
529     private void cancelReconnectJob() {
530         ScheduledFuture<?> reconnectJob = this.reconnectJob;
531         if (reconnectJob != null) {
532             reconnectJob.cancel(true);
533             this.reconnectJob = null;
534         }
535     }
536
537     /**
538      * Schedule the polling job
539      */
540     private void schedulePollingJob() {
541         logger.debug("Schedule polling job");
542         cancelPollingJob();
543
544         pollingJob = scheduler.scheduleWithFixedDelay(() -> {
545             synchronized (sequenceLock) {
546                 if (connector.isConnected()) {
547                     logger.debug("Polling the controller for updated status...");
548
549                     // poll each zone up to the number of zones specified in the configuration
550                     MonopriceAudioZone.VALID_ZONES.stream().limit(numZones).forEach((zoneName) -> {
551                         try {
552                             connector.queryZone(MonopriceAudioZone.valueOf(zoneName));
553                         } catch (MonopriceAudioException e) {
554                             logger.warn("Polling error: {}", e.getMessage());
555                         }
556                     });
557
558                     // if the last successful polling update was more than 2.25 intervals ago, the controller
559                     // is either switched off or not responding even though the connection is still good
560                     if ((System.currentTimeMillis() - lastPollingUpdate) > (pollingInterval * 2.25 * 1000)) {
561                         logger.warn("Controller not responding to status requests");
562                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
563                                 "Controller not responding to status requests");
564                         closeConnection();
565                         scheduleReconnectJob();
566                     }
567                 }
568             }
569         }, INITIAL_POLLING_DELAY_SEC, pollingInterval, TimeUnit.SECONDS);
570     }
571
572     /**
573      * Cancel the polling job
574      */
575     private void cancelPollingJob() {
576         ScheduledFuture<?> pollingJob = this.pollingJob;
577         if (pollingJob != null) {
578             pollingJob.cancel(true);
579             this.pollingJob = null;
580         }
581     }
582
583     /**
584      * Update the state of a channel
585      *
586      * @param channel the channel
587      */
588     private void updateChannelState(MonopriceAudioZone zone, String channelType, MonopriceAudioZoneDTO zoneData) {
589         String channel = zone.name().toLowerCase() + CHANNEL_DELIMIT + channelType;
590
591         if (!isLinked(channel)) {
592             return;
593         }
594
595         State state = UnDefType.UNDEF;
596         switch (channelType) {
597             case CHANNEL_TYPE_POWER:
598                 state = zoneData.isPowerOn() ? OnOffType.ON : OnOffType.OFF;
599                 break;
600             case CHANNEL_TYPE_SOURCE:
601                 state = new DecimalType(zoneData.getSource());
602                 break;
603             case CHANNEL_TYPE_VOLUME:
604                 long volumePct = Math.round(
605                         (double) (zoneData.getVolume() - MIN_VOLUME) / (double) (MAX_VOLUME - MIN_VOLUME) * 100.0);
606                 state = new PercentType(BigDecimal.valueOf(volumePct));
607                 break;
608             case CHANNEL_TYPE_MUTE:
609                 state = zoneData.isMuted() ? OnOffType.ON : OnOffType.OFF;
610                 break;
611             case CHANNEL_TYPE_TREBLE:
612                 state = new DecimalType(BigDecimal.valueOf(zoneData.getTreble() - TONE_OFFSET));
613                 break;
614             case CHANNEL_TYPE_BASS:
615                 state = new DecimalType(BigDecimal.valueOf(zoneData.getBass() - TONE_OFFSET));
616                 break;
617             case CHANNEL_TYPE_BALANCE:
618                 state = new DecimalType(BigDecimal.valueOf(zoneData.getBalance() - BALANCE_OFFSET));
619                 break;
620             case CHANNEL_TYPE_DND:
621                 state = zoneData.isDndOn() ? OnOffType.ON : OnOffType.OFF;
622                 break;
623             case CHANNEL_TYPE_PAGE:
624                 state = zoneData.isPageActive() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
625                 break;
626             case CHANNEL_TYPE_KEYPAD:
627                 state = zoneData.isKeypadActive() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
628                 break;
629             default:
630                 break;
631         }
632         updateState(channel, state);
633     }
634
635     private void processZoneUpdate(MonopriceAudioZone zone, MonopriceAudioZoneDTO zoneData, String newZoneData) {
636         // only process the update if something actually changed in this zone since the last time through
637         if (!newZoneData.equals(zoneData.toString())) {
638             // example status string: 1200010000130809100601, matcher pattern from above:
639             // "^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})"
640             Matcher matcher = PATTERN.matcher(newZoneData);
641             if (matcher.find()) {
642                 zoneData.setZone(matcher.group(1));
643
644                 if (!matcher.group(2).equals(zoneData.getPage())) {
645                     zoneData.setPage(matcher.group(2));
646                     updateChannelState(zone, CHANNEL_TYPE_PAGE, zoneData);
647                 }
648
649                 if (!matcher.group(3).equals(zoneData.getPower())) {
650                     zoneData.setPower(matcher.group(3));
651                     updateChannelState(zone, CHANNEL_TYPE_POWER, zoneData);
652                 }
653
654                 if (!matcher.group(4).equals(zoneData.getMute())) {
655                     zoneData.setMute(matcher.group(4));
656                     updateChannelState(zone, CHANNEL_TYPE_MUTE, zoneData);
657                 }
658
659                 if (!matcher.group(5).equals(zoneData.getDnd())) {
660                     zoneData.setDnd(matcher.group(5));
661                     updateChannelState(zone, CHANNEL_TYPE_DND, zoneData);
662                 }
663
664                 int volume = Integer.parseInt(matcher.group(6));
665                 if (volume != zoneData.getVolume()) {
666                     zoneData.setVolume(volume);
667                     updateChannelState(zone, CHANNEL_TYPE_VOLUME, zoneData);
668                 }
669
670                 int treble = Integer.parseInt(matcher.group(7));
671                 if (treble != zoneData.getTreble()) {
672                     zoneData.setTreble(treble);
673                     updateChannelState(zone, CHANNEL_TYPE_TREBLE, zoneData);
674                 }
675
676                 int bass = Integer.parseInt(matcher.group(8));
677                 if (bass != zoneData.getBass()) {
678                     zoneData.setBass(bass);
679                     updateChannelState(zone, CHANNEL_TYPE_BASS, zoneData);
680                 }
681
682                 int balance = Integer.parseInt(matcher.group(9));
683                 if (balance != zoneData.getBalance()) {
684                     zoneData.setBalance(balance);
685                     updateChannelState(zone, CHANNEL_TYPE_BALANCE, zoneData);
686                 }
687
688                 if (!matcher.group(10).equals(zoneData.getSource())) {
689                     zoneData.setSource(matcher.group(10));
690                     updateChannelState(zone, CHANNEL_TYPE_SOURCE, zoneData);
691                 }
692
693                 if (!matcher.group(11).equals(zoneData.getKeypad())) {
694                     zoneData.setKeypad(matcher.group(11));
695                     updateChannelState(zone, CHANNEL_TYPE_KEYPAD, zoneData);
696                 }
697             } else {
698                 logger.debug("Invalid zone update message: {}", newZoneData);
699             }
700
701         }
702         lastPollingUpdate = System.currentTimeMillis();
703     }
704 }