]> git.basschouten.com Git - openhab-addons.git/blob
b5ae4c76ab1f67c0e41973312ab23abdfd7bae69
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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 a 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 - Initial contribution
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 decimalCommand) {
291                         zoneControl.setVolume(decimalCommand.floatValue());
292                     } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
293                         zoneControl.setVolumeRelative(zoneState,
294                                 (increaseDecreaseCommand == 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_HDMI1OUT:
309                     zoneControl.setHDMI1Out(((OnOffType) command) == OnOffType.ON);
310                     break;
311
312                 case CHANNEL_HDMI2OUT:
313                     zoneControl.setHDMI2Out(((OnOffType) command) == OnOffType.ON);
314                     break;
315
316                 case CHANNEL_NAVIGATION_MENU:
317                     if (inputWithNavigationControl == null) {
318                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
319                         return;
320                     }
321
322                     String path = ((StringType) command).toFullString();
323                     inputWithNavigationControl.selectItemFullPath(path);
324                     break;
325
326                 case CHANNEL_NAVIGATION_UPDOWN:
327                     if (inputWithNavigationControl == null) {
328                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
329                         return;
330                     }
331                     if (((UpDownType) command) == UpDownType.UP) {
332                         inputWithNavigationControl.goUp();
333                     } else {
334                         inputWithNavigationControl.goDown();
335                     }
336                     break;
337
338                 case CHANNEL_NAVIGATION_LEFTRIGHT:
339                     if (inputWithNavigationControl == null) {
340                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
341                         return;
342                     }
343                     if (((UpDownType) command) == UpDownType.UP) {
344                         inputWithNavigationControl.goLeft();
345                     } else {
346                         inputWithNavigationControl.goRight();
347                     }
348                     break;
349
350                 case CHANNEL_NAVIGATION_SELECT:
351                     if (inputWithNavigationControl == null) {
352                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
353                         return;
354                     }
355                     inputWithNavigationControl.selectCurrentItem();
356                     break;
357
358                 case CHANNEL_NAVIGATION_BACK:
359                     if (inputWithNavigationControl == null) {
360                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
361                         return;
362                     }
363                     inputWithNavigationControl.goBack();
364                     break;
365
366                 case CHANNEL_NAVIGATION_BACKTOROOT:
367                     if (inputWithNavigationControl == null) {
368                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
369                         return;
370                     }
371                     inputWithNavigationControl.goToRoot();
372                     break;
373
374                 case CHANNEL_PLAYBACK_PRESET:
375                     if (inputWithPresetControl == null) {
376                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
377                         return;
378                     }
379
380                     if (command instanceof DecimalType decimalCommand) {
381                         inputWithPresetControl.selectItemByPresetNumber(decimalCommand.intValue());
382                     } else if (command instanceof StringType stringCommand) {
383                         try {
384                             int v = Integer.valueOf(stringCommand.toString());
385                             inputWithPresetControl.selectItemByPresetNumber(v);
386                         } catch (NumberFormatException e) {
387                             logger.warn("Provide a number for {}", id);
388                         }
389                     }
390                     break;
391
392                 case CHANNEL_TUNER_BAND:
393                     if (inputWithDabBandControl == null) {
394                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
395                         return;
396                     }
397
398                     if (command instanceof StringType) {
399                         inputWithDabBandControl.selectBandByName(command.toString());
400                     } else {
401                         logger.warn("Provide a string for {}", id);
402                     }
403                     break;
404
405                 case CHANNEL_PLAYBACK:
406                     if (inputWithPlayControl == null) {
407                         logger.warn("Channel {} not working with {} input!", id, zoneState.inputID);
408                         return;
409                     }
410
411                     if (command instanceof PlayPauseType t) {
412                         switch (t) {
413                             case PAUSE:
414                                 inputWithPlayControl.pause();
415                                 break;
416                             case PLAY:
417                                 inputWithPlayControl.play();
418                                 break;
419                         }
420                     } else if (command instanceof NextPreviousType t) {
421                         switch (t) {
422                             case NEXT:
423                                 inputWithPlayControl.nextTrack();
424                                 break;
425                             case PREVIOUS:
426                                 inputWithPlayControl.previousTrack();
427                                 break;
428                         }
429                     } else if (command instanceof DecimalType decimalCommand) {
430                         int v = decimalCommand.intValue();
431                         if (v < 0) {
432                             inputWithPlayControl.skipREV();
433                         } else if (v > 0) {
434                             inputWithPlayControl.skipFF();
435                         }
436                     } else if (command instanceof StringType stringCommand) {
437                         String v = stringCommand.toFullString();
438                         switch (v) {
439                             case "Play":
440                                 inputWithPlayControl.play();
441                                 break;
442                             case "Pause":
443                                 inputWithPlayControl.pause();
444                                 break;
445                             case "Stop":
446                                 inputWithPlayControl.stop();
447                                 break;
448                             case "Rewind":
449                                 inputWithPlayControl.skipREV();
450                                 break;
451                             case "FastForward":
452                                 inputWithPlayControl.skipFF();
453                                 break;
454                             case "Next":
455                                 inputWithPlayControl.nextTrack();
456                                 break;
457                             case "Previous":
458                                 inputWithPlayControl.previousTrack();
459                                 break;
460                         }
461                     }
462                     break;
463                 default:
464                     logger.warn("Channel {} not supported!", id);
465             }
466         } catch (IOException e) {
467             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
468         } catch (ReceivedMessageParseException e) {
469             // Some AVRs send unexpected responses. We log parser exceptions therefore.
470             logger.debug("Parse error!", e);
471         }
472     }
473
474     /**
475      * Called by handleCommand() if a RefreshType command was received. It will update
476      * the given channel with the correct state.
477      *
478      * @param channelUID The channel
479      */
480     private void refreshFromState(ChannelUID channelUID) {
481         String id = channelUID.getId();
482
483         if (id.equals(grpZone(CHANNEL_POWER))) {
484             updateState(channelUID, OnOffType.from(zoneState.power));
485
486         } else if (id.equals(grpZone(CHANNEL_VOLUME_DB))) {
487             updateState(channelUID, new DecimalType(zoneState.volumeDB));
488         } else if (id.equals(grpZone(CHANNEL_VOLUME))) {
489             updateState(channelUID, new PercentType((int) zoneConfig.getVolumePercentage(zoneState.volumeDB)));
490         } else if (id.equals(grpZone(CHANNEL_MUTE))) {
491             updateState(channelUID, OnOffType.from(zoneState.mute));
492         } else if (id.equals(grpZone(CHANNEL_INPUT))) {
493             updateState(channelUID, new StringType(zoneState.inputID));
494         } else if (id.equals(grpZone(CHANNEL_SURROUND))) {
495             updateState(channelUID, new StringType(zoneState.surroundProgram));
496         } else if (id.equals(grpZone(CHANNEL_SCENE))) {
497             logger.debug("No state updates available");
498         } else if (id.equals(grpZone(CHANNEL_DIALOGUE_LEVEL))) {
499             updateState(channelUID, new DecimalType(zoneState.dialogueLevel));
500         } else if (id.equals(grpZone(CHANNEL_HDMI1OUT))) {
501             updateState(channelUID, OnOffType.from(zoneState.hdmi1Out));
502         } else if (id.equals(grpZone(CHANNEL_HDMI2OUT))) {
503             updateState(channelUID, OnOffType.from(zoneState.hdmi2Out));
504
505         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK))) {
506             updateState(channelUID, new StringType(playInfoState.playbackMode));
507         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_STATION))) {
508             updateState(channelUID, new StringType(playInfoState.station));
509         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_ARTIST))) {
510             updateState(channelUID, new StringType(playInfoState.artist));
511         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_ALBUM))) {
512             updateState(channelUID, new StringType(playInfoState.album));
513         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_SONG))) {
514             updateState(channelUID, new StringType(playInfoState.song));
515         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_SONG_IMAGE_URL))) {
516             updateState(channelUID, new StringType(playInfoState.songImageUrl));
517         } else if (id.equals(grpPlayback(CHANNEL_PLAYBACK_PRESET))) {
518             updateState(channelUID, new DecimalType(presetInfoState.presetChannel));
519         } else if (id.equals(grpPlayback(CHANNEL_TUNER_BAND))) {
520             updateState(channelUID, new StringType(dabBandState.band));
521
522         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_MENU))) {
523             updateState(channelUID, new StringType(navigationInfoState.getCurrentItemName()));
524         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_LEVEL))) {
525             updateState(channelUID, new DecimalType(navigationInfoState.menuLayer));
526         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_CURRENT_ITEM))) {
527             updateState(channelUID, new DecimalType(navigationInfoState.currentLine));
528         } else if (id.equals(grpNav(CHANNEL_NAVIGATION_TOTAL_ITEMS))) {
529             updateState(channelUID, new DecimalType(navigationInfoState.maxLine));
530         } else {
531             logger.warn("Channel {} not implemented!", id);
532         }
533     }
534
535     @Override
536     public void zoneStateChanged(ZoneControlState msg) {
537         boolean inputChanged = !msg.inputID.equals(zoneState.inputID);
538         zoneState = msg;
539
540         updateStatus(ThingStatus.ONLINE);
541
542         updateState(grpZone(CHANNEL_POWER), OnOffType.from(zoneState.power));
543         updateState(grpZone(CHANNEL_INPUT), new StringType(zoneState.inputID));
544         updateState(grpZone(CHANNEL_SURROUND), new StringType(zoneState.surroundProgram));
545         updateState(grpZone(CHANNEL_VOLUME_DB), new DecimalType(zoneState.volumeDB));
546         updateState(grpZone(CHANNEL_VOLUME), new PercentType((int) zoneConfig.getVolumePercentage(zoneState.volumeDB)));
547         updateState(grpZone(CHANNEL_MUTE), OnOffType.from(zoneState.mute));
548         updateState(grpZone(CHANNEL_DIALOGUE_LEVEL), new DecimalType(zoneState.dialogueLevel));
549         updateState(grpZone(CHANNEL_HDMI1OUT), OnOffType.from(zoneState.hdmi1Out));
550         updateState(grpZone(CHANNEL_HDMI2OUT), OnOffType.from(zoneState.hdmi2Out));
551
552         // If the input changed
553         if (inputChanged) {
554             inputChanged();
555         }
556     }
557
558     /**
559      * Called by {@link #zoneStateChanged(ZoneControlState)} if the input has changed.
560      * Will request updates from {@see InputWithNavigationControl} and {@see InputWithPlayControl}.
561      */
562     private void inputChanged() {
563         logger.debug("Input changed to {}", zoneState.inputID);
564
565         if (!isInputSupported(zoneState.inputID)) {
566             // for now just emit a warning in logs
567             logger.warn("Input {} is not supported on your AVR model", zoneState.inputID);
568         }
569
570         inputChangedCheckForNavigationControl();
571         // Note: the DAB band needs to be initialized before preset and playback
572         inputChangedCheckForDabBand();
573         inputChangedCheckForPlaybackControl();
574         inputChangedCheckForPresetControl();
575     }
576
577     /**
578      * Checks if the specified input is supported given the detected device feature information.
579      *
580      * @param inputID - the input name
581      * @return true when input is supported
582      */
583     private boolean isInputSupported(String inputID) {
584         switch (inputID) {
585             case INPUT_SPOTIFY:
586                 return getDeviceInformationState().features.contains(Feature.SPOTIFY);
587
588             case INPUT_TUNER:
589                 return getDeviceInformationState().features.contains(Feature.TUNER)
590                         || getDeviceInformationState().features.contains(Feature.DAB);
591
592             // Note: add more inputs here in the future
593         }
594         return true;
595     }
596
597     private void inputChangedCheckForNavigationControl() {
598         boolean includeInputWithNavigationControl = false;
599
600         for (String channelName : CHANNELS_NAVIGATION) {
601             if (isLinked(grpNav(channelName))) {
602                 includeInputWithNavigationControl = true;
603                 break;
604             }
605         }
606
607         if (includeInputWithNavigationControl) {
608             includeInputWithNavigationControl = InputWithNavigationControl.SUPPORTED_INPUTS.contains(zoneState.inputID);
609             if (!includeInputWithNavigationControl) {
610                 logger.debug("Navigation control not supported by {}", zoneState.inputID);
611             }
612         }
613
614         logger.trace("Navigation control requested by channel");
615
616         if (!includeInputWithNavigationControl) {
617             inputWithNavigationControl = null;
618             navigationInfoState.invalidate();
619             navigationUpdated(navigationInfoState);
620             return;
621         }
622
623         inputWithNavigationControl = getProtocolFactory().InputWithNavigationControl(getConnection(),
624                 navigationInfoState, zoneState.inputID, this, getDeviceInformationState());
625
626         updateAsyncMakeOfflineIfFail(inputWithNavigationControl);
627     }
628
629     private void inputChangedCheckForPlaybackControl() {
630         boolean includeInputWithPlaybackControl = false;
631
632         for (String channelName : CHANNELS_PLAYBACK) {
633             if (isLinked(grpPlayback(channelName))) {
634                 includeInputWithPlaybackControl = true;
635                 break;
636             }
637         }
638
639         logger.trace("Playback control requested by channel");
640
641         if (includeInputWithPlaybackControl) {
642             includeInputWithPlaybackControl = InputWithPlayControl.SUPPORTED_INPUTS.contains(zoneState.inputID);
643             if (!includeInputWithPlaybackControl) {
644                 logger.debug("Playback control not supported by {}", zoneState.inputID);
645             }
646         }
647
648         if (!includeInputWithPlaybackControl) {
649             inputWithPlayControl = null;
650             playInfoState.invalidate();
651             playInfoUpdated(playInfoState);
652             return;
653         }
654
655         /**
656          * The {@link inputChangedCheckForDabBand} needs to be called first before this method, in case the AVR Supports
657          * DAB
658          */
659         if (inputWithDabBandControl != null) {
660             // When input is Tuner DAB there is no playback control
661             inputWithPlayControl = null;
662         } else {
663             inputWithPlayControl = getProtocolFactory().InputWithPlayControl(getConnection(), zoneState.inputID, this,
664                     getBridgeHandler().getConfiguration(), getDeviceInformationState());
665
666             updateAsyncMakeOfflineIfFail(inputWithPlayControl);
667         }
668     }
669
670     private void inputChangedCheckForPresetControl() {
671         boolean includeInput = isLinked(grpPlayback(CHANNEL_PLAYBACK_PRESET));
672
673         logger.trace("Preset control requested by channel");
674
675         if (includeInput) {
676             includeInput = InputWithPresetControl.SUPPORTED_INPUTS.contains(zoneState.inputID);
677             if (!includeInput) {
678                 logger.debug("Preset control not supported by {}", zoneState.inputID);
679             }
680         }
681
682         if (!includeInput) {
683             inputWithPresetControl = null;
684             presetInfoState.invalidate();
685             presetInfoUpdated(presetInfoState);
686             return;
687         }
688
689         /**
690          * The {@link inputChangedCheckForDabBand} needs to be called first before this method, in case the AVR Supports
691          * DAB
692          */
693         if (inputWithDabBandControl != null) {
694             // When the input is Tuner DAB the control also provides preset functionality
695             inputWithPresetControl = (InputWithPresetControl) inputWithDabBandControl;
696             // Note: No need to update state - it will be already called for DabBand control (see
697             // inputChangedCheckForDabBand)
698         } else {
699             inputWithPresetControl = getProtocolFactory().InputWithPresetControl(getConnection(), zoneState.inputID,
700                     this, getDeviceInformationState());
701
702             updateAsyncMakeOfflineIfFail(inputWithPresetControl);
703         }
704     }
705
706     private void inputChangedCheckForDabBand() {
707         boolean includeInput = isLinked(grpPlayback(CHANNEL_TUNER_BAND));
708
709         logger.trace("Band control requested by channel");
710
711         if (includeInput) {
712             // Check if TUNER input is DAB - dual bands radio tuner
713             includeInput = InputWithTunerBandControl.SUPPORTED_INPUTS.contains(zoneState.inputID)
714                     && getDeviceInformationState().features.contains(Feature.DAB);
715             if (!includeInput) {
716                 logger.debug("Band control not supported by {}", zoneState.inputID);
717             }
718         }
719
720         if (!includeInput) {
721             inputWithDabBandControl = null;
722             dabBandState.invalidate();
723             dabBandUpdated(dabBandState);
724             return;
725         }
726
727         logger.debug("InputWithTunerBandControl created for {}", zoneState.inputID);
728         inputWithDabBandControl = getProtocolFactory().InputWithDabBandControl(zoneState.inputID, getConnection(), this,
729                 this, this, getDeviceInformationState());
730
731         updateAsyncMakeOfflineIfFail(inputWithDabBandControl);
732     }
733
734     protected void updateAsyncMakeOfflineIfFail(IStateUpdatable stateUpdatable) {
735         scheduler.submit(() -> {
736             try {
737                 stateUpdatable.update();
738             } catch (IOException e) {
739                 logger.debug("State update error. Changing thing to offline", e);
740                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
741             } catch (ReceivedMessageParseException e) {
742                 String message = e.getMessage();
743                 updateProperty(PROPERTY_LAST_PARSE_ERROR, message != null ? message : "");
744                 // Some AVRs send unexpected responses. We log parser exceptions therefore.
745                 logger.debug("Parse error!", e);
746             }
747         });
748     }
749
750     /**
751      * Once this thing is set up and the AVR is connected, the available inputs for this zone are requested.
752      * The thing is updated with a new CHANNEL_AVAILABLE_INPUT which lists the available inputs for the current zone..
753      */
754     @Override
755     public void availableInputsChanged(AvailableInputState msg) {
756         // Update channel type provider with a list of available inputs
757         channelsTypeProviderAvailableInputs.changeAvailableInputs(msg.availableInputs);
758
759         // Remove the old channel and add the new channel. The channel will be requested from the
760         // yamahaChannelTypeProvider.
761         ChannelUID inputChannelUID = new ChannelUID(thing.getUID(), CHANNEL_GROUP_ZONE, CHANNEL_INPUT);
762         Channel channel = ChannelBuilder.create(inputChannelUID, "String")
763                 .withType(channelsTypeProviderAvailableInputs.getChannelTypeUID()).build();
764         updateThing(editThing().withoutChannel(inputChannelUID).withChannel(channel).build());
765     }
766
767     private String grpPlayback(String channelIDWithoutGroup) {
768         return new ChannelUID(thing.getUID(), CHANNEL_GROUP_PLAYBACK, channelIDWithoutGroup).getId();
769     }
770
771     private String grpNav(String channelIDWithoutGroup) {
772         return new ChannelUID(thing.getUID(), CHANNEL_GROUP_NAVIGATION, channelIDWithoutGroup).getId();
773     }
774
775     private String grpZone(String channelIDWithoutGroup) {
776         return new ChannelUID(thing.getUID(), CHANNEL_GROUP_ZONE, channelIDWithoutGroup).getId();
777     }
778
779     @Override
780     public void playInfoUpdated(PlayInfoState msg) {
781         playInfoState = msg;
782
783         updateState(grpPlayback(CHANNEL_PLAYBACK), new StringType(msg.playbackMode));
784         updateState(grpPlayback(CHANNEL_PLAYBACK_STATION), new StringType(msg.station));
785         updateState(grpPlayback(CHANNEL_PLAYBACK_ARTIST), new StringType(msg.artist));
786         updateState(grpPlayback(CHANNEL_PLAYBACK_ALBUM), new StringType(msg.album));
787         updateState(grpPlayback(CHANNEL_PLAYBACK_SONG), new StringType(msg.song));
788         updateState(grpPlayback(CHANNEL_PLAYBACK_SONG_IMAGE_URL), new StringType(msg.songImageUrl));
789     }
790
791     @Override
792     public void presetInfoUpdated(PresetInfoState msg) {
793         presetInfoState = msg;
794
795         if (msg.presetChannelNamesChanged) {
796             msg.presetChannelNamesChanged = false;
797
798             channelsTypeProviderPreset.changePresetNames(msg.presetChannelNames);
799
800             // Remove the old channel and add the new channel. The channel will be requested from the
801             // channelsTypeProviderPreset.
802             ChannelUID inputChannelUID = new ChannelUID(thing.getUID(), CHANNEL_GROUP_PLAYBACK,
803                     CHANNEL_PLAYBACK_PRESET);
804             Channel channel = ChannelBuilder.create(inputChannelUID, "Number")
805                     .withType(channelsTypeProviderPreset.getChannelTypeUID()).build();
806             updateThing(editThing().withoutChannel(inputChannelUID).withChannel(channel).build());
807         }
808
809         updateState(grpPlayback(CHANNEL_PLAYBACK_PRESET), new DecimalType(msg.presetChannel));
810     }
811
812     @Override
813     public void dabBandUpdated(DabBandState msg) {
814         dabBandState = msg;
815         updateState(grpPlayback(CHANNEL_TUNER_BAND), new StringType(msg.band));
816     }
817
818     @Override
819     public void navigationUpdated(NavigationControlState msg) {
820         navigationInfoState = msg;
821         updateState(grpNav(CHANNEL_NAVIGATION_MENU), new StringType(msg.menuName));
822         updateState(grpNav(CHANNEL_NAVIGATION_LEVEL), new DecimalType(msg.menuLayer));
823         updateState(grpNav(CHANNEL_NAVIGATION_CURRENT_ITEM), new DecimalType(msg.currentLine));
824         updateState(grpNav(CHANNEL_NAVIGATION_TOTAL_ITEMS), new DecimalType(msg.maxLine));
825     }
826
827     @Override
828     public void navigationError(String msg) {
829         updateProperty(PROPERTY_MENU_ERROR, msg);
830         logger.warn("Navigation error: {}", msg);
831     }
832 }