]> git.basschouten.com Git - openhab-addons.git/blob
1da33f9189b4dda4fd17c0bc493b025e8131d101
[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.yamahareceiver.internal.handler;
14
15 import static org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.*;
16 import static org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.Inputs.*;
17
18 import java.io.IOException;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.openhab.binding.yamahareceiver.internal.ChannelsTypeProviderAvailableInputs;
29 import org.openhab.binding.yamahareceiver.internal.ChannelsTypeProviderPreset;
30 import org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.Feature;
31 import org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.Zone;
32 import org.openhab.binding.yamahareceiver.internal.config.YamahaZoneConfig;
33 import org.openhab.binding.yamahareceiver.internal.protocol.AbstractConnection;
34 import org.openhab.binding.yamahareceiver.internal.protocol.IStateUpdatable;
35 import org.openhab.binding.yamahareceiver.internal.protocol.InputWithNavigationControl;
36 import org.openhab.binding.yamahareceiver.internal.protocol.InputWithPlayControl;
37 import org.openhab.binding.yamahareceiver.internal.protocol.InputWithPresetControl;
38 import org.openhab.binding.yamahareceiver.internal.protocol.InputWithTunerBandControl;
39 import org.openhab.binding.yamahareceiver.internal.protocol.ProtocolFactory;
40 import org.openhab.binding.yamahareceiver.internal.protocol.ReceivedMessageParseException;
41 import org.openhab.binding.yamahareceiver.internal.protocol.ZoneAvailableInputs;
42 import org.openhab.binding.yamahareceiver.internal.protocol.ZoneControl;
43 import org.openhab.binding.yamahareceiver.internal.protocol.xml.InputWithNavigationControlXML;
44 import org.openhab.binding.yamahareceiver.internal.protocol.xml.InputWithPlayControlXML;
45 import org.openhab.binding.yamahareceiver.internal.protocol.xml.ZoneControlXML;
46 import org.openhab.binding.yamahareceiver.internal.state.AvailableInputState;
47 import org.openhab.binding.yamahareceiver.internal.state.AvailableInputStateListener;
48 import org.openhab.binding.yamahareceiver.internal.state.DabBandState;
49 import org.openhab.binding.yamahareceiver.internal.state.DabBandStateListener;
50 import org.openhab.binding.yamahareceiver.internal.state.DeviceInformationState;
51 import org.openhab.binding.yamahareceiver.internal.state.NavigationControlState;
52 import org.openhab.binding.yamahareceiver.internal.state.NavigationControlStateListener;
53 import org.openhab.binding.yamahareceiver.internal.state.PlayInfoState;
54 import org.openhab.binding.yamahareceiver.internal.state.PlayInfoStateListener;
55 import org.openhab.binding.yamahareceiver.internal.state.PresetInfoState;
56 import org.openhab.binding.yamahareceiver.internal.state.PresetInfoStateListener;
57 import org.openhab.binding.yamahareceiver.internal.state.ZoneControlState;
58 import org.openhab.binding.yamahareceiver.internal.state.ZoneControlStateListener;
59 import org.openhab.core.config.core.Configuration;
60 import org.openhab.core.library.types.DecimalType;
61 import org.openhab.core.library.types.IncreaseDecreaseType;
62 import org.openhab.core.library.types.NextPreviousType;
63 import org.openhab.core.library.types.OnOffType;
64 import org.openhab.core.library.types.PercentType;
65 import org.openhab.core.library.types.PlayPauseType;
66 import org.openhab.core.library.types.StringType;
67 import org.openhab.core.library.types.UpDownType;
68 import org.openhab.core.thing.Bridge;
69 import org.openhab.core.thing.Channel;
70 import org.openhab.core.thing.ChannelUID;
71 import org.openhab.core.thing.Thing;
72 import org.openhab.core.thing.ThingStatus;
73 import org.openhab.core.thing.ThingStatusDetail;
74 import org.openhab.core.thing.ThingStatusInfo;
75 import org.openhab.core.thing.binding.BaseThingHandler;
76 import org.openhab.core.thing.binding.ThingHandlerService;
77 import org.openhab.core.thing.binding.builder.ChannelBuilder;
78 import org.openhab.core.types.Command;
79 import org.openhab.core.types.RefreshType;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82
83 /**
84  * The {@link YamahaZoneThingHandler} is managing one zone of an Yamaha AVR.
85  * It has a state consisting of the zone, the current input ID, {@link ZoneControlState}
86  * and some more state objects and uses the zone control protocol
87  * class {@link ZoneControlXML}, {@link InputWithPlayControlXML} and {@link InputWithNavigationControlXML}
88  * for communication.
89  *
90  * @author David Graeff <david.graeff@web.de>
91  * @author Tomasz Maruszak - [yamaha] Tuner band selection and preset feature for dual band models (RX-S601D), added
92  *         config object
93  */
94 public class YamahaZoneThingHandler extends BaseThingHandler
95         implements ZoneControlStateListener, NavigationControlStateListener, PlayInfoStateListener,
96         AvailableInputStateListener, PresetInfoStateListener, DabBandStateListener {
97
98     private final Logger logger = LoggerFactory.getLogger(YamahaZoneThingHandler.class);
99
100     private YamahaZoneConfig zoneConfig;
101
102     /// ChannelType providers
103     public @NonNullByDefault({}) ChannelsTypeProviderPreset channelsTypeProviderPreset;
104     public @NonNullByDefault({}) ChannelsTypeProviderAvailableInputs channelsTypeProviderAvailableInputs;
105
106     /// State
107     protected ZoneControlState zoneState = new ZoneControlState();
108     protected PresetInfoState presetInfoState = new PresetInfoState();
109     protected DabBandState dabBandState = new DabBandState();
110     protected PlayInfoState playInfoState = new PlayInfoState();
111     protected NavigationControlState navigationInfoState = new NavigationControlState();
112
113     /// Control
114     protected ZoneControl zoneControl;
115     protected InputWithPlayControl inputWithPlayControl;
116     protected InputWithNavigationControl inputWithNavigationControl;
117     protected ZoneAvailableInputs zoneAvailableInputs;
118     protected InputWithPresetControl inputWithPresetControl;
119     protected InputWithTunerBandControl inputWithDabBandControl;
120
121     public YamahaZoneThingHandler(Thing thing) {
122         super(thing);
123     }
124
125     @Override
126     public Collection<Class<? extends ThingHandlerService>> getServices() {
127         return Collections
128                 .unmodifiableList(Stream.of(ChannelsTypeProviderAvailableInputs.class, ChannelsTypeProviderPreset.class)
129                         .collect(Collectors.toList()));
130     }
131
132     /**
133      * Sets the {@link DeviceInformationState} for the handler.
134      */
135     public DeviceInformationState getDeviceInformationState() {
136         return getBridgeHandler().getDeviceInformationState();
137     }
138
139     @Override
140     public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
141         validateConfigurationParameters(configurationParameters);
142
143         Configuration configuration = editConfiguration();
144         for (Entry<String, Object> configurationParameter : configurationParameters.entrySet()) {
145             configuration.put(configurationParameter.getKey(), configurationParameter.getValue());
146         }
147
148         updateConfiguration(configuration);
149
150         zoneConfig = configuration.as(YamahaZoneConfig.class);
151         logger.trace("Updating configuration of {} with zone '{}'", getThing().getLabel(), zoneConfig.getZoneValue());
152     }
153
154     /**
155      * We handle updates of this thing ourself.
156      */
157     @Override
158     public void thingUpdated(Thing thing) {
159         this.thing = thing;
160     }
161
162     /**
163      * Calls createCommunicationObject if the host name is configured correctly.
164      */
165     @Override
166     public void initialize() {
167         // Determine the zone of this thing
168
169         zoneConfig = getConfigAs(YamahaZoneConfig.class);
170         logger.trace("Initialize {} with zone '{}'", getThing().getLabel(), zoneConfig.getZoneValue());
171
172         Bridge bridge = getBridge();
173         initializeThing(bridge != null ? bridge.getStatus() : null);
174     }
175
176     protected YamahaBridgeHandler getBridgeHandler() {
177         Bridge bridge = getBridge();
178         if (bridge == null) {
179             return null;
180         }
181         return (YamahaBridgeHandler) bridge.getHandler();
182     }
183
184     protected ProtocolFactory getProtocolFactory() {
185         return getBridgeHandler().getProtocolFactory();
186     }
187
188     protected AbstractConnection getConnection() {
189         return getBridgeHandler().getConnection();
190     }
191
192     @Override
193     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
194         initializeThing(bridgeStatusInfo.getStatus());
195     }
196
197     private void initializeThing(ThingStatus bridgeStatus) {
198         YamahaBridgeHandler bridgeHandler = getBridgeHandler();
199         if (bridgeHandler != null && bridgeStatus != null) {
200             if (bridgeStatus == ThingStatus.ONLINE) {
201                 if (zoneConfig == null || zoneConfig.getZone() == null) {
202                     String msg = String.format(
203                             "Zone not set or invalid zone name used: '%s'. It needs to be on of: '%s'",
204                             zoneConfig.getZoneValue(), Arrays.toString(Zone.values()));
205                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg);
206                     logger.info("{}", msg);
207                 } else {
208                     if (zoneControl == null) {
209                         YamahaBridgeHandler brHandler = getBridgeHandler();
210
211                         zoneControl = getProtocolFactory().ZoneControl(getConnection(), zoneConfig, this,
212                                 brHandler::getInputConverter, getDeviceInformationState());
213                         zoneAvailableInputs = getProtocolFactory().ZoneAvailableInputs(getConnection(), zoneConfig,
214                                 this, brHandler::getInputConverter, getDeviceInformationState());
215
216                         updateZoneInformation();
217                     }
218
219                     updateStatus(ThingStatus.ONLINE);
220                 }
221             } else {
222                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
223                 zoneControl = null;
224                 zoneAvailableInputs = null;
225             }
226         } else {
227             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
228         }
229     }
230
231     /**
232      * Return true if the zone is set, and zoneControl and zoneAvailableInputs objects have been created.
233      */
234     boolean isCorrectlyInitialized() {
235         return zoneConfig != null && zoneConfig.getZone() != null && zoneAvailableInputs != null && zoneControl != null;
236     }
237
238     /**
239      * Request new zone and available input information
240      */
241     void updateZoneInformation() {
242         updateAsyncMakeOfflineIfFail(zoneAvailableInputs);
243         updateAsyncMakeOfflineIfFail(zoneControl);
244
245         if (inputWithPlayControl != null) {
246             updateAsyncMakeOfflineIfFail(inputWithPlayControl);
247         }
248
249         if (inputWithNavigationControl != null) {
250             updateAsyncMakeOfflineIfFail(inputWithNavigationControl);
251         }
252
253         if (inputWithPresetControl != null) {
254             updateAsyncMakeOfflineIfFail(inputWithPresetControl);
255         }
256
257         if (inputWithDabBandControl != null) {
258             updateAsyncMakeOfflineIfFail(inputWithDabBandControl);
259         }
260     }
261
262     @Override
263     public void handleCommand(ChannelUID channelUID, Command command) {
264         if (zoneControl == null) {
265             return;
266         }
267
268         String id = channelUID.getIdWithoutGroup();
269
270         try {
271             if (command instanceof RefreshType) {
272                 refreshFromState(channelUID);
273                 return;
274             }
275
276             switch (id) {
277                 case CHANNEL_POWER:
278                     zoneControl.setPower(((OnOffType) command) == OnOffType.ON);
279                     break;
280                 case CHANNEL_INPUT:
281                     zoneControl.setInput(((StringType) command).toString());
282                     break;
283                 case CHANNEL_SURROUND:
284                     zoneControl.setSurroundProgram(((StringType) command).toString());
285                     break;
286                 case CHANNEL_VOLUME_DB:
287                     zoneControl.setVolumeDB(((DecimalType) command).floatValue());
288                     break;
289                 case CHANNEL_VOLUME:
290                     if (command instanceof DecimalType) {
291                         zoneControl.setVolume(((DecimalType) command).floatValue());
292                     } else if (command instanceof IncreaseDecreaseType) {
293                         zoneControl.setVolumeRelative(zoneState,
294                                 (((IncreaseDecreaseType) command) == IncreaseDecreaseType.INCREASE ? 1 : -1)
295                                         * zoneConfig.getVolumeRelativeChangeFactor());
296                     }
297                     break;
298                 case CHANNEL_MUTE:
299                     zoneControl.setMute(((OnOffType) command) == OnOffType.ON);
300                     break;
301                 case CHANNEL_SCENE:
302                     zoneControl.setScene(((StringType) command).toString());
303                     break;
304                 case CHANNEL_DIALOGUE_LEVEL:
305                     zoneControl.setDialogueLevel(((DecimalType) command).intValue());
306                     break;
307
308                 case CHANNEL_NAVIGATION_MENU:
309                     if (inputWithNavigationControl == null) {
310                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
311                         return;
312                     }
313
314                     String path = ((StringType) command).toFullString();
315                     inputWithNavigationControl.selectItemFullPath(path);
316                     break;
317
318                 case CHANNEL_NAVIGATION_UPDOWN:
319                     if (inputWithNavigationControl == null) {
320                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
321                         return;
322                     }
323                     if (((UpDownType) command) == UpDownType.UP) {
324                         inputWithNavigationControl.goUp();
325                     } else {
326                         inputWithNavigationControl.goDown();
327                     }
328                     break;
329
330                 case CHANNEL_NAVIGATION_LEFTRIGHT:
331                     if (inputWithNavigationControl == null) {
332                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
333                         return;
334                     }
335                     if (((UpDownType) command) == UpDownType.UP) {
336                         inputWithNavigationControl.goLeft();
337                     } else {
338                         inputWithNavigationControl.goRight();
339                     }
340                     break;
341
342                 case CHANNEL_NAVIGATION_SELECT:
343                     if (inputWithNavigationControl == null) {
344                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
345                         return;
346                     }
347                     inputWithNavigationControl.selectCurrentItem();
348                     break;
349
350                 case CHANNEL_NAVIGATION_BACK:
351                     if (inputWithNavigationControl == null) {
352                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
353                         return;
354                     }
355                     inputWithNavigationControl.goBack();
356                     break;
357
358                 case CHANNEL_NAVIGATION_BACKTOROOT:
359                     if (inputWithNavigationControl == null) {
360                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
361                         return;
362                     }
363                     inputWithNavigationControl.goToRoot();
364                     break;
365
366                 case CHANNEL_PLAYBACK_PRESET:
367                     if (inputWithPresetControl == null) {
368                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
369                         return;
370                     }
371
372                     if (command instanceof DecimalType) {
373                         inputWithPresetControl.selectItemByPresetNumber(((DecimalType) command).intValue());
374                     } else if (command instanceof StringType) {
375                         try {
376                             int v = Integer.valueOf(((StringType) command).toString());
377                             inputWithPresetControl.selectItemByPresetNumber(v);
378                         } catch (NumberFormatException e) {
379                             logger.warn("Provide a number for {}", id);
380                         }
381                     }
382                     break;
383
384                 case CHANNEL_TUNER_BAND:
385                     if (inputWithDabBandControl == null) {
386                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
387                         return;
388                     }
389
390                     if (command instanceof StringType) {
391                         inputWithDabBandControl.selectBandByName(command.toString());
392                     } else {
393                         logger.warn("Provide a string for {}", id);
394                     }
395                     break;
396
397                 case CHANNEL_PLAYBACK:
398                     if (inputWithPlayControl == null) {
399                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
400                         return;
401                     }
402
403                     if (command instanceof PlayPauseType) {
404                         PlayPauseType t = ((PlayPauseType) command);
405                         switch (t) {
406                             case PAUSE:
407                                 inputWithPlayControl.pause();
408                                 break;
409                             case PLAY:
410                                 inputWithPlayControl.play();
411                                 break;
412                         }
413                     } else if (command instanceof NextPreviousType) {
414                         NextPreviousType t = ((NextPreviousType) command);
415                         switch (t) {
416                             case NEXT:
417                                 inputWithPlayControl.nextTrack();
418                                 break;
419                             case PREVIOUS:
420                                 inputWithPlayControl.previousTrack();
421                                 break;
422                         }
423                     } else if (command instanceof DecimalType) {
424                         int v = ((DecimalType) command).intValue();
425                         if (v < 0) {
426                             inputWithPlayControl.skipREV();
427                         } else if (v > 0) {
428                             inputWithPlayControl.skipFF();
429                         }
430                     } else if (command instanceof StringType) {
431                         String v = ((StringType) command).toFullString();
432                         switch (v) {
433                             case "Play":
434                                 inputWithPlayControl.play();
435                                 break;
436                             case "Pause":
437                                 inputWithPlayControl.pause();
438                                 break;
439                             case "Stop":
440                                 inputWithPlayControl.stop();
441                                 break;
442                             case "Rewind":
443                                 inputWithPlayControl.skipREV();
444                                 break;
445                             case "FastForward":
446                                 inputWithPlayControl.skipFF();
447                                 break;
448                             case "Next":
449                                 inputWithPlayControl.nextTrack();
450                                 break;
451                             case "Previous":
452                                 inputWithPlayControl.previousTrack();
453                                 break;
454                         }
455                     }
456                     break;
457                 default:
458                     logger.warn("Channel {} not supported!", id);
459             }
460         } catch (IOException e) {
461             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
462         } catch (ReceivedMessageParseException e) {
463             // Some AVRs send unexpected responses. We log parser exceptions therefore.
464             logger.debug("Parse error!", e);
465         }
466     }
467
468     /**
469      * Called by handleCommand() if a RefreshType command was received. It will update
470      * the given channel with the correct state.
471      *
472      * @param channelUID The channel
473      */
474     private void refreshFromState(ChannelUID channelUID) {
475         String id = channelUID.getId();
476
477         if (id.equals(grpZone(CHANNEL_POWER))) {
478             updateState(channelUID, zoneState.power ? OnOffType.ON : OnOffType.OFF);
479
480         } else if (id.equals(grpZone(CHANNEL_VOLUME_DB))) {
481             updateState(channelUID, new DecimalType(zoneState.volumeDB));
482         } else if (id.equals(grpZone(CHANNEL_VOLUME))) {
483             updateState(channelUID, new PercentType((int) zoneConfig.getVolumePercentage(zoneState.volumeDB)));
484         } else if (id.equals(grpZone(CHANNEL_MUTE))) {
485             updateState(channelUID, zoneState.mute ? OnOffType.ON : OnOffType.OFF);
486         } else if (id.equals(grpZone(CHANNEL_INPUT))) {
487             updateState(channelUID, new StringType(zoneState.inputID));
488         } else if (id.equals(grpZone(CHANNEL_SURROUND))) {
489             updateState(channelUID, new StringType(zoneState.surroundProgram));
490         } else if (id.equals(grpZone(CHANNEL_SCENE))) {
491             // no state updates available
492         } else if (id.equals(grpZone(CHANNEL_DIALOGUE_LEVEL))) {
493             updateState(channelUID, new DecimalType(zoneState.dialogueLevel));
494
495         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK))) {
496             updateState(channelUID, new StringType(playInfoState.playbackMode));
497         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_STATION))) {
498             updateState(channelUID, new StringType(playInfoState.station));
499         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_ARTIST))) {
500             updateState(channelUID, new StringType(playInfoState.artist));
501         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_ALBUM))) {
502             updateState(channelUID, new StringType(playInfoState.album));
503         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_SONG))) {
504             updateState(channelUID, new StringType(playInfoState.song));
505         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_SONG_IMAGE_URL))) {
506             updateState(channelUID, new StringType(playInfoState.songImageUrl));
507         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_PRESET))) {
508             updateState(channelUID, new DecimalType(presetInfoState.presetChannel));
509         } else if (id.equals(grpPlayback(CHANNEL_TUNER_BAND))) {
510             updateState(channelUID, new StringType(dabBandState.band));
511
512         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_MENU))) {
513             updateState(channelUID, new StringType(navigationInfoState.getCurrentItemName()));
514         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_LEVEL))) {
515             updateState(channelUID, new DecimalType(navigationInfoState.menuLayer));
516         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_CURRENT_ITEM))) {
517             updateState(channelUID, new DecimalType(navigationInfoState.currentLine));
518         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_TOTAL_ITEMS))) {
519             updateState(channelUID, new DecimalType(navigationInfoState.maxLine));
520         } else {
521             logger.warn("Channel {} not implemented!", id);
522         }
523     }
524
525     @Override
526     public void zoneStateChanged(ZoneControlState msg) {
527         boolean inputChanged = !msg.inputID.equals(zoneState.inputID);
528         zoneState = msg;
529
530         updateStatus(ThingStatus.ONLINE);
531
532         updateState(grpZone(CHANNEL_POWER), zoneState.power ? OnOffType.ON : OnOffType.OFF);
533         updateState(grpZone(CHANNEL_INPUT), new StringType(zoneState.inputID));
534         updateState(grpZone(CHANNEL_SURROUND), new StringType(zoneState.surroundProgram));
535         updateState(grpZone(CHANNEL_VOLUME_DB), new DecimalType(zoneState.volumeDB));
536         updateState(grpZone(CHANNEL_VOLUME), new PercentType((int) zoneConfig.getVolumePercentage(zoneState.volumeDB)));
537         updateState(grpZone(CHANNEL_MUTE), zoneState.mute ? OnOffType.ON : OnOffType.OFF);
538         updateState(grpZone(CHANNEL_DIALOGUE_LEVEL), new DecimalType(zoneState.dialogueLevel));
539
540         // If the input changed
541         if (inputChanged) {
542             inputChanged();
543         }
544     }
545
546     /**
547      * Called by {@link #zoneStateChanged(ZoneControlState)} if the input has changed.
548      * Will request updates from {@see InputWithNavigationControl} and {@see InputWithPlayControl}.
549      */
550     private void inputChanged() {
551         logger.debug("Input changed to {}", zoneState.inputID);
552
553         if (!isInputSupported(zoneState.inputID)) {
554             // for now just emit a warning in logs
555             logger.warn("Input {} is not supported on your AVR model", zoneState.inputID);
556         }
557
558         inputChangedCheckForNavigationControl();
559         // Note: the DAB band needs to be initialized before preset and playback
560         inputChangedCheckForDabBand();
561         inputChangedCheckForPlaybackControl();
562         inputChangedCheckForPresetControl();
563     }
564
565     /**
566      * Checks if the specified input is supported given the detected device feature information.
567      *
568      * @param inputID - the input name
569      * @return true when input is supported
570      */
571     private boolean isInputSupported(String inputID) {
572         switch (inputID) {
573             case INPUT_SPOTIFY:
574                 return getDeviceInformationState().features.contains(Feature.SPOTIFY);
575
576             case INPUT_TUNER:
577                 return getDeviceInformationState().features.contains(Feature.TUNER)
578                         || getDeviceInformationState().features.contains(Feature.DAB);
579
580             // Note: add more inputs here in the future
581         }
582         return true;
583     }
584
585     private void inputChangedCheckForNavigationControl() {
586         boolean includeInputWithNavigationControl = false;
587
588         for (String channelName : CHANNELS_NAVIGATION) {
589             if (isLinked(grpNav(channelName))) {
590                 includeInputWithNavigationControl = true;
591                 break;
592             }
593         }
594
595         if (includeInputWithNavigationControl) {
596             includeInputWithNavigationControl = InputWithNavigationControl.SUPPORTED_INPUTS.contains(zoneState.inputID);
597             if (!includeInputWithNavigationControl) {
598                 logger.debug("Navigation control not supported by {}", zoneState.inputID);
599             }
600         }
601
602         logger.trace("Navigation control requested by channel");
603
604         if (!includeInputWithNavigationControl) {
605             inputWithNavigationControl = null;
606             navigationInfoState.invalidate();
607             navigationUpdated(navigationInfoState);
608             return;
609         }
610
611         inputWithNavigationControl = getProtocolFactory().InputWithNavigationControl(getConnection(),
612                 navigationInfoState, zoneState.inputID, this, getDeviceInformationState());
613
614         updateAsyncMakeOfflineIfFail(inputWithNavigationControl);
615     }
616
617     private void inputChangedCheckForPlaybackControl() {
618         boolean includeInputWithPlaybackControl = false;
619
620         for (String channelName : CHANNELS_PLAYBACK) {
621             if (isLinked(grpPlayback(channelName))) {
622                 includeInputWithPlaybackControl = true;
623                 break;
624             }
625         }
626
627         logger.trace("Playback control requested by channel");
628
629         if (includeInputWithPlaybackControl) {
630             includeInputWithPlaybackControl = InputWithPlayControl.SUPPORTED_INPUTS.contains(zoneState.inputID);
631             if (!includeInputWithPlaybackControl) {
632                 logger.debug("Playback control not supported by {}", zoneState.inputID);
633             }
634         }
635
636         if (!includeInputWithPlaybackControl) {
637             inputWithPlayControl = null;
638             playInfoState.invalidate();
639             playInfoUpdated(playInfoState);
640             return;
641         }
642
643         /**
644          * The {@link inputChangedCheckForDabBand} needs to be called first before this method, in case the AVR Supports
645          * DAB
646          */
647         if (inputWithDabBandControl != null) {
648             // When input is Tuner DAB there is no playback control
649             inputWithPlayControl = null;
650         } else {
651             inputWithPlayControl = getProtocolFactory().InputWithPlayControl(getConnection(), zoneState.inputID, this,
652                     getBridgeHandler().getConfiguration(), getDeviceInformationState());
653
654             updateAsyncMakeOfflineIfFail(inputWithPlayControl);
655         }
656     }
657
658     private void inputChangedCheckForPresetControl() {
659         boolean includeInput = isLinked(grpPlayback(CHANNEL_PLAYBACK_PRESET));
660
661         logger.trace("Preset control requested by channel");
662
663         if (includeInput) {
664             includeInput = InputWithPresetControl.SUPPORTED_INPUTS.contains(zoneState.inputID);
665             if (!includeInput) {
666                 logger.debug("Preset control not supported by {}", zoneState.inputID);
667             }
668         }
669
670         if (!includeInput) {
671             inputWithPresetControl = null;
672             presetInfoState.invalidate();
673             presetInfoUpdated(presetInfoState);
674             return;
675         }
676
677         /**
678          * The {@link inputChangedCheckForDabBand} needs to be called first before this method, in case the AVR Supports
679          * DAB
680          */
681         if (inputWithDabBandControl != null) {
682             // When the input is Tuner DAB the control also provides preset functionality
683             inputWithPresetControl = (InputWithPresetControl) inputWithDabBandControl;
684             // Note: No need to update state - it will be already called for DabBand control (see
685             // inputChangedCheckForDabBand)
686         } else {
687             inputWithPresetControl = getProtocolFactory().InputWithPresetControl(getConnection(), zoneState.inputID,
688                     this, getDeviceInformationState());
689
690             updateAsyncMakeOfflineIfFail(inputWithPresetControl);
691         }
692     }
693
694     private void inputChangedCheckForDabBand() {
695         boolean includeInput = isLinked(grpPlayback(CHANNEL_TUNER_BAND));
696
697         logger.trace("Band control requested by channel");
698
699         if (includeInput) {
700             // Check if TUNER input is DAB - dual bands radio tuner
701             includeInput = InputWithTunerBandControl.SUPPORTED_INPUTS.contains(zoneState.inputID)
702                     && getDeviceInformationState().features.contains(Feature.DAB);
703             if (!includeInput) {
704                 logger.debug("Band control not supported by {}", zoneState.inputID);
705             }
706         }
707
708         if (!includeInput) {
709             inputWithDabBandControl = null;
710             dabBandState.invalidate();
711             dabBandUpdated(dabBandState);
712             return;
713         }
714
715         logger.debug("InputWithTunerBandControl created for {}", zoneState.inputID);
716         inputWithDabBandControl = getProtocolFactory().InputWithDabBandControl(zoneState.inputID, getConnection(), this,
717                 this, this, getDeviceInformationState());
718
719         updateAsyncMakeOfflineIfFail(inputWithDabBandControl);
720     }
721
722     protected void updateAsyncMakeOfflineIfFail(IStateUpdatable stateUpdatable) {
723         scheduler.submit(() -> {
724             try {
725                 stateUpdatable.update();
726             } catch (IOException e) {
727                 logger.debug("State update error. Changing thing to offline", e);
728                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
729             } catch (ReceivedMessageParseException e) {
730                 updateProperty(PROPERTY_LAST_PARSE_ERROR, e.getMessage());
731                 // Some AVRs send unexpected responses. We log parser exceptions therefore.
732                 logger.debug("Parse error!", e);
733             }
734         });
735     }
736
737     /**
738      * Once this thing is set up and the AVR is connected, the available inputs for this zone are requested.
739      * The thing is updated with a new CHANNEL_AVAILABLE_INPUT which lists the available inputs for the current zone..
740      */
741     @Override
742     public void availableInputsChanged(AvailableInputState msg) {
743         // Update channel type provider with a list of available inputs
744         channelsTypeProviderAvailableInputs.changeAvailableInputs(msg.availableInputs);
745
746         // Remove the old channel and add the new channel. The channel will be requested from the
747         // yamahaChannelTypeProvider.
748         ChannelUID inputChannelUID = new ChannelUID(thing.getUID(), CHANNEL_GROUP_ZONE, CHANNEL_INPUT);
749         Channel channel = ChannelBuilder.create(inputChannelUID, "String")
750                 .withType(channelsTypeProviderAvailableInputs.getChannelTypeUID()).build();
751         updateThing(editThing().withoutChannel(inputChannelUID).withChannel(channel).build());
752     }
753
754     private String grpPlayback(String channelIDWithoutGroup) {
755         return new ChannelUID(thing.getUID(), CHANNEL_GROUP_PLAYBACK, channelIDWithoutGroup).getId();
756     }
757
758     private String grpNav(String channelIDWithoutGroup) {
759         return new ChannelUID(thing.getUID(), CHANNEL_GROUP_NAVIGATION, channelIDWithoutGroup).getId();
760     }
761
762     private String grpZone(String channelIDWithoutGroup) {
763         return new ChannelUID(thing.getUID(), CHANNEL_GROUP_ZONE, channelIDWithoutGroup).getId();
764     }
765
766     @Override
767     public void playInfoUpdated(PlayInfoState msg) {
768         playInfoState = msg;
769
770         updateState(grpPlayback(CHANNEL_PLAYBACK), new StringType(msg.playbackMode));
771         updateState(grpPlayback(CHANNEL_PLAYBACK_STATION), new StringType(msg.station));
772         updateState(grpPlayback(CHANNEL_PLAYBACK_ARTIST), new StringType(msg.artist));
773         updateState(grpPlayback(CHANNEL_PLAYBACK_ALBUM), new StringType(msg.album));
774         updateState(grpPlayback(CHANNEL_PLAYBACK_SONG), new StringType(msg.song));
775         updateState(grpPlayback(CHANNEL_PLAYBACK_SONG_IMAGE_URL), new StringType(msg.songImageUrl));
776     }
777
778     @Override
779     public void presetInfoUpdated(PresetInfoState msg) {
780         presetInfoState = msg;
781
782         if (msg.presetChannelNamesChanged) {
783             msg.presetChannelNamesChanged = false;
784
785             channelsTypeProviderPreset.changePresetNames(msg.presetChannelNames);
786
787             // Remove the old channel and add the new channel. The channel will be requested from the
788             // channelsTypeProviderPreset.
789             ChannelUID inputChannelUID = new ChannelUID(thing.getUID(), CHANNEL_GROUP_PLAYBACK,
790                     CHANNEL_PLAYBACK_PRESET);
791             Channel channel = ChannelBuilder.create(inputChannelUID, "Number")
792                     .withType(channelsTypeProviderPreset.getChannelTypeUID()).build();
793             updateThing(editThing().withoutChannel(inputChannelUID).withChannel(channel).build());
794         }
795
796         updateState(grpPlayback(CHANNEL_PLAYBACK_PRESET), new DecimalType(msg.presetChannel));
797     }
798
799     @Override
800     public void dabBandUpdated(DabBandState msg) {
801         dabBandState = msg;
802         updateState(grpPlayback(CHANNEL_TUNER_BAND), new StringType(msg.band));
803     }
804
805     @Override
806     public void navigationUpdated(NavigationControlState msg) {
807         navigationInfoState = msg;
808         updateState(grpNav(CHANNEL_NAVIGATION_MENU), new StringType(msg.menuName));
809         updateState(grpNav(CHANNEL_NAVIGATION_LEVEL), new DecimalType(msg.menuLayer));
810         updateState(grpNav(CHANNEL_NAVIGATION_CURRENT_ITEM), new DecimalType(msg.currentLine));
811         updateState(grpNav(CHANNEL_NAVIGATION_TOTAL_ITEMS), new DecimalType(msg.maxLine));
812     }
813
814     @Override
815     public void navigationError(String msg) {
816         updateProperty(PROPERTY_MENU_ERROR, msg);
817         logger.warn("Navigation error: {}", msg);
818     }
819 }