]> git.basschouten.com Git - openhab-addons.git/blob
f335fc4cfcdaba6ad6dd453ae34e840125249846
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.sonos.internal.handler;
14
15 import static org.openhab.binding.sonos.internal.SonosBindingConstants.*;
16
17 import java.io.IOException;
18 import java.net.MalformedURLException;
19 import java.net.URL;
20 import java.text.ParseException;
21 import java.text.SimpleDateFormat;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Calendar;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Date;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.TimeZone;
32 import java.util.concurrent.ScheduledFuture;
33 import java.util.concurrent.TimeUnit;
34
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.openhab.binding.sonos.internal.SonosAlarm;
38 import org.openhab.binding.sonos.internal.SonosBindingConstants;
39 import org.openhab.binding.sonos.internal.SonosEntry;
40 import org.openhab.binding.sonos.internal.SonosMetaData;
41 import org.openhab.binding.sonos.internal.SonosMusicService;
42 import org.openhab.binding.sonos.internal.SonosResourceMetaData;
43 import org.openhab.binding.sonos.internal.SonosStateDescriptionOptionProvider;
44 import org.openhab.binding.sonos.internal.SonosXMLParser;
45 import org.openhab.binding.sonos.internal.SonosZoneGroup;
46 import org.openhab.binding.sonos.internal.SonosZonePlayerState;
47 import org.openhab.binding.sonos.internal.config.ZonePlayerConfiguration;
48 import org.openhab.core.io.net.http.HttpUtil;
49 import org.openhab.core.io.transport.upnp.UpnpIOParticipant;
50 import org.openhab.core.io.transport.upnp.UpnpIOService;
51 import org.openhab.core.library.types.DecimalType;
52 import org.openhab.core.library.types.IncreaseDecreaseType;
53 import org.openhab.core.library.types.NextPreviousType;
54 import org.openhab.core.library.types.OnOffType;
55 import org.openhab.core.library.types.OpenClosedType;
56 import org.openhab.core.library.types.PercentType;
57 import org.openhab.core.library.types.PlayPauseType;
58 import org.openhab.core.library.types.RawType;
59 import org.openhab.core.library.types.StringType;
60 import org.openhab.core.library.types.UpDownType;
61 import org.openhab.core.thing.ChannelUID;
62 import org.openhab.core.thing.Thing;
63 import org.openhab.core.thing.ThingRegistry;
64 import org.openhab.core.thing.ThingStatus;
65 import org.openhab.core.thing.ThingStatusDetail;
66 import org.openhab.core.thing.ThingTypeUID;
67 import org.openhab.core.thing.ThingUID;
68 import org.openhab.core.thing.binding.BaseThingHandler;
69 import org.openhab.core.thing.binding.ThingHandler;
70 import org.openhab.core.types.Command;
71 import org.openhab.core.types.RefreshType;
72 import org.openhab.core.types.State;
73 import org.openhab.core.types.StateOption;
74 import org.openhab.core.types.UnDefType;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 /**
79  * The {@link ZonePlayerHandler} is responsible for handling commands, which are
80  * sent to one of the channels.
81  *
82  * @author Karel Goderis - Initial contribution
83  */
84 @NonNullByDefault
85 public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOParticipant {
86
87     private static final String ANALOG_LINE_IN_URI = "x-rincon-stream:";
88     private static final String OPTICAL_LINE_IN_URI = "x-sonos-htastream:";
89     private static final String QUEUE_URI = "x-rincon-queue:";
90     private static final String GROUP_URI = "x-rincon:";
91     private static final String STREAM_URI = "x-sonosapi-stream:";
92     private static final String RADIO_URI = "x-sonosapi-radio:";
93     private static final String RADIO_MP3_URI = "x-rincon-mp3radio:";
94     private static final String OPML_TUNE = "http://opml.radiotime.com/Tune.ashx";
95     private static final String FILE_URI = "x-file-cifs:";
96     private static final String SPDIF = ":spdif";
97     private static final String TUNEIN_URI = "x-sonosapi-stream:s%s?sid=%s&flags=32";
98
99     private static final String STATE_PLAYING = "PLAYING";
100     private static final String STATE_PAUSED_PLAYBACK = "PAUSED_PLAYBACK";
101     private static final String STATE_STOPPED = "STOPPED";
102
103     private static final String LINEINCONNECTED = "LineInConnected";
104     private static final String TOSLINEINCONNECTED = "TOSLinkConnected";
105
106     private static final String SERVICE_DEVICE_PROPERTIES = "DeviceProperties";
107     private static final String SERVICE_AV_TRANSPORT = "AVTransport";
108     private static final String SERVICE_RENDERING_CONTROL = "RenderingControl";
109     private static final String SERVICE_ZONE_GROUP_TOPOLOGY = "ZoneGroupTopology";
110     private static final String SERVICE_GROUP_MANAGEMENT = "GroupManagement";
111     private static final String SERVICE_AUDIO_IN = "AudioIn";
112     private static final String SERVICE_HT_CONTROL = "HTControl";
113     private static final String SERVICE_CONTENT_DIRECTORY = "ContentDirectory";
114     private static final String SERVICE_ALARM_CLOCK = "AlarmClock";
115
116     private static final Collection<String> SERVICE_SUBSCRIPTIONS = Arrays.asList(SERVICE_DEVICE_PROPERTIES,
117             SERVICE_AV_TRANSPORT, SERVICE_ZONE_GROUP_TOPOLOGY, SERVICE_GROUP_MANAGEMENT, SERVICE_RENDERING_CONTROL,
118             SERVICE_AUDIO_IN, SERVICE_HT_CONTROL, SERVICE_CONTENT_DIRECTORY);
119     protected static final int SUBSCRIPTION_DURATION = 1800;
120
121     private static final String ACTION_GET_ZONE_ATTRIBUTES = "GetZoneAttributes";
122     private static final String ACTION_GET_ZONE_INFO = "GetZoneInfo";
123     private static final String ACTION_GET_LED_STATE = "GetLEDState";
124     private static final String ACTION_SET_LED_STATE = "SetLEDState";
125
126     private static final String ACTION_GET_POSITION_INFO = "GetPositionInfo";
127     private static final String ACTION_SET_AV_TRANSPORT_URI = "SetAVTransportURI";
128     private static final String ACTION_SEEK = "Seek";
129     private static final String ACTION_PLAY = "Play";
130     private static final String ACTION_STOP = "Stop";
131     private static final String ACTION_PAUSE = "Pause";
132     private static final String ACTION_PREVIOUS = "Previous";
133     private static final String ACTION_NEXT = "Next";
134     private static final String ACTION_ADD_URI_TO_QUEUE = "AddURIToQueue";
135     private static final String ACTION_REMOVE_TRACK_RANGE_FROM_QUEUE = "RemoveTrackRangeFromQueue";
136     private static final String ACTION_REMOVE_ALL_TRACKS_FROM_QUEUE = "RemoveAllTracksFromQueue";
137     private static final String ACTION_SAVE_QUEUE = "SaveQueue";
138     private static final String ACTION_SET_PLAY_MODE = "SetPlayMode";
139     private static final String ACTION_BECOME_COORDINATOR_OF_STANDALONE_GROUP = "BecomeCoordinatorOfStandaloneGroup";
140     private static final String ACTION_GET_RUNNING_ALARM_PROPERTIES = "GetRunningAlarmProperties";
141     private static final String ACTION_SNOOZE_ALARM = "SnoozeAlarm";
142     private static final String ACTION_GET_REMAINING_SLEEP_TIMER_DURATION = "GetRemainingSleepTimerDuration";
143     private static final String ACTION_CONFIGURE_SLEEP_TIMER = "ConfigureSleepTimer";
144
145     private static final String ACTION_SET_VOLUME = "SetVolume";
146     private static final String ACTION_SET_MUTE = "SetMute";
147     private static final String ACTION_SET_BASS = "SetBass";
148     private static final String ACTION_SET_TREBLE = "SetTreble";
149     private static final String ACTION_SET_LOUDNESS = "SetLoudness";
150     private static final String ACTION_SET_EQ = "SetEQ";
151
152     private static final int SOCKET_TIMEOUT = 5000;
153
154     private static final int TUNEIN_DEFAULT_SERVICE_TYPE = 65031;
155
156     private static final int MIN_BASS = -10;
157     private static final int MAX_BASS = 10;
158     private static final int MIN_TREBLE = -10;
159     private static final int MAX_TREBLE = 10;
160     private static final int MIN_SUBWOOFER_GAIN = -15;
161     private static final int MAX_SUBWOOFER_GAIN = 15;
162     private static final int MIN_SURROUND_LEVEL = -15;
163     private static final int MAX_SURROUND_LEVEL = 15;
164
165     private final Logger logger = LoggerFactory.getLogger(ZonePlayerHandler.class);
166
167     private final ThingRegistry localThingRegistry;
168     private final UpnpIOService service;
169     private final @Nullable String opmlUrl;
170     private final SonosStateDescriptionOptionProvider stateDescriptionProvider;
171
172     private ZonePlayerConfiguration configuration = new ZonePlayerConfiguration();
173
174     /**
175      * Intrinsic lock used to synchronize the execution of notification sounds
176      */
177     private final Object notificationLock = new Object();
178     private final Object upnpLock = new Object();
179     private final Object stateLock = new Object();
180     private final Object jobLock = new Object();
181
182     private final Map<String, String> stateMap = Collections.synchronizedMap(new HashMap<>());
183
184     private @Nullable ScheduledFuture<?> pollingJob;
185     private @Nullable SonosZonePlayerState savedState;
186
187     private Map<String, Boolean> subscriptionState = new HashMap<>();
188
189     /**
190      * Thing handler instance of the coordinator speaker used for control delegation
191      */
192     private @Nullable ZonePlayerHandler coordinatorHandler;
193
194     private @Nullable List<SonosMusicService> musicServices;
195
196     private enum LineInType {
197         ANALOG,
198         DIGITAL,
199         ANY
200     }
201
202     public ZonePlayerHandler(ThingRegistry thingRegistry, Thing thing, UpnpIOService upnpIOService,
203             @Nullable String opmlUrl, SonosStateDescriptionOptionProvider stateDescriptionProvider) {
204         super(thing);
205         this.localThingRegistry = thingRegistry;
206         this.opmlUrl = opmlUrl;
207         logger.debug("Creating a ZonePlayerHandler for thing '{}'", getThing().getUID());
208         this.service = upnpIOService;
209         this.stateDescriptionProvider = stateDescriptionProvider;
210     }
211
212     @Override
213     public void dispose() {
214         logger.debug("Handler disposed for thing {}", getThing().getUID());
215
216         ScheduledFuture<?> job = this.pollingJob;
217         if (job != null) {
218             job.cancel(true);
219         }
220         this.pollingJob = null;
221
222         removeSubscription();
223         service.unregisterParticipant(this);
224     }
225
226     @Override
227     public void initialize() {
228         logger.debug("initializing handler for thing {}", getThing().getUID());
229
230         if (migrateThingType()) {
231             // we change the type, so we might need a different handler -> let's finish
232             return;
233         }
234
235         configuration = getConfigAs(ZonePlayerConfiguration.class);
236         String udn = configuration.udn;
237         if (udn != null && !udn.isEmpty()) {
238             service.registerParticipant(this);
239             pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, configuration.refresh, TimeUnit.SECONDS);
240         } else {
241             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
242                     "@text/offline.conf-error-missing-udn");
243             logger.debug("Cannot initalize the zoneplayer. UDN not set.");
244         }
245     }
246
247     private void poll() {
248         synchronized (jobLock) {
249             if (pollingJob == null) {
250                 return;
251             }
252             try {
253                 logger.debug("Polling job");
254
255                 // First check if the Sonos zone is set in the UPnP service registry
256                 // If not, set the thing state to OFFLINE and wait for the next poll
257                 if (!isUpnpDeviceRegistered()) {
258                     logger.debug("UPnP device {} not yet registered", getUDN());
259                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
260                             "@text/offline.upnp-device-not-registered [\"" + getUDN() + "\"]");
261                     synchronized (upnpLock) {
262                         subscriptionState = new HashMap<>();
263                     }
264                     return;
265                 }
266
267                 // Check if the Sonos zone can be joined
268                 // If not, set the thing state to OFFLINE and do nothing else
269                 updatePlayerState();
270                 if (getThing().getStatus() != ThingStatus.ONLINE) {
271                     return;
272                 }
273
274                 addSubscription();
275
276                 if (isLinked(ZONENAME)) {
277                     updateCurrentZoneName();
278                 }
279                 if (isLinked(LED)) {
280                     updateLed();
281                 }
282                 // Action GetRemainingSleepTimerDuration is failing for a group slave member (error code 500)
283                 if (isLinked(SLEEPTIMER) && isCoordinator()) {
284                     updateSleepTimerDuration();
285                 }
286             } catch (Exception e) {
287                 logger.debug("Exception during poll: {}", e.getMessage(), e);
288             }
289         }
290     }
291
292     @Override
293     public void handleCommand(ChannelUID channelUID, Command command) {
294         if (command == RefreshType.REFRESH) {
295             updateChannel(channelUID.getId());
296         } else {
297             switch (channelUID.getId()) {
298                 case LED:
299                     setLed(command);
300                     break;
301                 case MUTE:
302                     setMute(command);
303                     break;
304                 case NOTIFICATIONSOUND:
305                     scheduleNotificationSound(command);
306                     break;
307                 case STOP:
308                     stopPlaying(command);
309                     break;
310                 case VOLUME:
311                     setVolumeForGroup(command);
312                     break;
313                 case BASS:
314                     setBass(command);
315                     break;
316                 case TREBLE:
317                     setTreble(command);
318                     break;
319                 case LOUDNESS:
320                     setLoudness(command);
321                     break;
322                 case SUBWOOFER:
323                     setSubwoofer(command);
324                     break;
325                 case SUBWOOFERGAIN:
326                     setSubwooferGain(command);
327                     break;
328                 case SURROUND:
329                     setSurround(command);
330                     break;
331                 case SURROUNDMUSICMODE:
332                     setSurroundMusicMode(command);
333                     break;
334                 case SURROUNDMUSICLEVEL:
335                     setSurroundMusicLevel(command);
336                     break;
337                 case SURROUNDTVLEVEL:
338                     setSurroundTvLevel(command);
339                     break;
340                 case ADD:
341                     addMember(command);
342                     break;
343                 case REMOVE:
344                     removeMember(command);
345                     break;
346                 case STANDALONE:
347                     becomeStandAlonePlayer();
348                     break;
349                 case PUBLICADDRESS:
350                     publicAddress(LineInType.ANY);
351                     break;
352                 case PUBLICANALOGADDRESS:
353                     publicAddress(LineInType.ANALOG);
354                     break;
355                 case PUBLICDIGITALADDRESS:
356                     publicAddress(LineInType.DIGITAL);
357                     break;
358                 case RADIO:
359                     playRadio(command);
360                     break;
361                 case TUNEINSTATIONID:
362                     playTuneinStation(command);
363                     break;
364                 case FAVORITE:
365                     playFavorite(command);
366                     break;
367                 case ALARM:
368                     setAlarm(command);
369                     break;
370                 case SNOOZE:
371                     snoozeAlarm(command);
372                     break;
373                 case SAVEALL:
374                     saveAllPlayerState();
375                     break;
376                 case RESTOREALL:
377                     restoreAllPlayerState();
378                     break;
379                 case SAVE:
380                     saveState();
381                     break;
382                 case RESTORE:
383                     restoreState();
384                     break;
385                 case PLAYLIST:
386                     playPlayList(command);
387                     break;
388                 case CLEARQUEUE:
389                     clearQueue();
390                     break;
391                 case PLAYQUEUE:
392                     playQueue();
393                     break;
394                 case PLAYTRACK:
395                     playTrack(command);
396                     break;
397                 case PLAYURI:
398                     playURI(command);
399                     break;
400                 case PLAYLINEIN:
401                     playLineIn(command);
402                     break;
403                 case CONTROL:
404                     try {
405                         if (command instanceof PlayPauseType) {
406                             if (command == PlayPauseType.PLAY) {
407                                 getCoordinatorHandler().play();
408                             } else if (command == PlayPauseType.PAUSE) {
409                                 getCoordinatorHandler().pause();
410                             }
411                         }
412                         if (command instanceof NextPreviousType) {
413                             if (command == NextPreviousType.NEXT) {
414                                 getCoordinatorHandler().next();
415                             } else if (command == NextPreviousType.PREVIOUS) {
416                                 getCoordinatorHandler().previous();
417                             }
418                         }
419                         // Rewind and Fast Forward are currently not implemented by the binding
420                     } catch (IllegalStateException e) {
421                         logger.debug("Cannot handle control command ({})", e.getMessage());
422                     }
423                     break;
424                 case SLEEPTIMER:
425                     setSleepTimer(command);
426                     break;
427                 case SHUFFLE:
428                     setShuffle(command);
429                     break;
430                 case REPEAT:
431                     setRepeat(command);
432                     break;
433                 case NIGHTMODE:
434                     setNightMode(command);
435                     break;
436                 case SPEECHENHANCEMENT:
437                     setSpeechEnhancement(command);
438                     break;
439                 default:
440                     break;
441             }
442         }
443     }
444
445     private void restoreAllPlayerState() {
446         for (Thing aThing : localThingRegistry.getAll()) {
447             if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) {
448                 ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler();
449                 if (handler != null) {
450                     handler.restoreState();
451                 }
452             }
453         }
454     }
455
456     private void saveAllPlayerState() {
457         for (Thing aThing : localThingRegistry.getAll()) {
458             if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) {
459                 ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler();
460                 if (handler != null) {
461                     handler.saveState();
462                 }
463             }
464         }
465     }
466
467     @Override
468     public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
469         if (variable == null || value == null || service == null) {
470             return;
471         }
472
473         if (getThing().getStatus() == ThingStatus.ONLINE) {
474             logger.trace("Received pair '{}':'{}' (service '{}') for thing '{}'",
475                     new Object[] { variable, value, service, this.getThing().getUID() });
476
477             String oldValue = this.stateMap.get(variable);
478             if (shouldIgnoreVariableUpdate(variable, value, oldValue)) {
479                 return;
480             }
481
482             this.stateMap.put(variable, value);
483
484             // pre-process some variables, eg XML processing
485             if (service.equals(SERVICE_AV_TRANSPORT) && variable.equals("LastChange")) {
486                 Map<String, String> parsedValues = SonosXMLParser.getAVTransportFromXML(value);
487                 parsedValues.forEach((variable1, value1) -> {
488                     // Update the transport state after the update of the media information
489                     // to not break the notification mechanism
490                     if (!variable1.equals("TransportState")) {
491                         onValueReceived(variable1, value1, service);
492                     }
493                     // Translate AVTransportURI/AVTransportURIMetaData to CurrentURI/CurrentURIMetaData
494                     // for a compatibility with the result of the action GetMediaInfo
495                     if (variable1.equals("AVTransportURI")) {
496                         onValueReceived("CurrentURI", value1, service);
497                     } else if (variable1.equals("AVTransportURIMetaData")) {
498                         onValueReceived("CurrentURIMetaData", value1, service);
499                     }
500                 });
501                 updateMediaInformation();
502                 if (parsedValues.get("TransportState") != null) {
503                     onValueReceived("TransportState", parsedValues.get("TransportState"), service);
504                 }
505             }
506
507             if (service.equals(SERVICE_RENDERING_CONTROL) && variable.equals("LastChange")) {
508                 Map<String, String> parsedValues = SonosXMLParser.getRenderingControlFromXML(value);
509                 parsedValues.forEach((variable1, value1) -> {
510                     onValueReceived(variable1, value1, service);
511                 });
512             }
513
514             List<StateOption> options = new ArrayList<>();
515
516             // update the appropriate channel
517             switch (variable) {
518                 case "TransportState":
519                     updateChannel(STATE);
520                     updateChannel(CONTROL);
521                     updateChannel(STOP);
522                     dispatchOnAllGroupMembers(variable, value, service);
523                     break;
524                 case "CurrentPlayMode":
525                     updateChannel(SHUFFLE);
526                     updateChannel(REPEAT);
527                     dispatchOnAllGroupMembers(variable, value, service);
528                     break;
529                 case "CurrentLEDState":
530                     updateChannel(LED);
531                     break;
532                 case "ZoneName":
533                     updateState(ZONENAME, new StringType(value));
534                     break;
535                 case "CurrentZoneName":
536                     updateChannel(ZONENAME);
537                     break;
538                 case "ZoneGroupState":
539                     updateChannel(COORDINATOR);
540                     // Update coordinator after a change is made to the grouping of Sonos players
541                     updateGroupCoordinator();
542                     updateMediaInformation();
543                     // Update state and control channels for the group members with the coordinator values
544                     String transportState = getTransportState();
545                     if (transportState != null) {
546                         dispatchOnAllGroupMembers("TransportState", transportState, SERVICE_AV_TRANSPORT);
547                     }
548                     // Update shuffle and repeat channels for the group members with the coordinator values
549                     String playMode = getPlayMode();
550                     if (playMode != null) {
551                         dispatchOnAllGroupMembers("CurrentPlayMode", playMode, SERVICE_AV_TRANSPORT);
552                     }
553                     break;
554                 case "LocalGroupUUID":
555                     updateChannel(ZONEGROUPID);
556                     break;
557                 case "GroupCoordinatorIsLocal":
558                     updateChannel(LOCALCOORDINATOR);
559                     break;
560                 case "VolumeMaster":
561                     updateChannel(VOLUME);
562                     break;
563                 case "MuteMaster":
564                     updateChannel(MUTE);
565                     break;
566                 case "Bass":
567                     updateChannel(BASS);
568                     break;
569                 case "Treble":
570                     updateChannel(TREBLE);
571                     break;
572                 case "LoudnessMaster":
573                     updateChannel(LOUDNESS);
574                     break;
575                 case "OutputFixed":
576                     updateChannel(BASS);
577                     updateChannel(TREBLE);
578                     updateChannel(LOUDNESS);
579                     break;
580                 case "SubEnabled":
581                     updateChannel(SUBWOOFER);
582                     break;
583                 case "SubGain":
584                     updateChannel(SUBWOOFERGAIN);
585                     break;
586                 case "SurroundEnabled":
587                     updateChannel(SURROUND);
588                     break;
589                 case "SurroundMode":
590                     updateChannel(SURROUNDMUSICMODE);
591                     break;
592                 case "SurroundLevel":
593                     updateChannel(SURROUNDTVLEVEL);
594                     break;
595                 case "MusicSurroundLevel":
596                     updateChannel(SURROUNDMUSICLEVEL);
597                     break;
598                 case "NightMode":
599                     updateChannel(NIGHTMODE);
600                     break;
601                 case "DialogLevel":
602                     updateChannel(SPEECHENHANCEMENT);
603                     break;
604                 case LINEINCONNECTED:
605                     if (SonosBindingConstants.WITH_LINEIN_THING_TYPES_UIDS.contains(getThing().getThingTypeUID())) {
606                         updateChannel(LINEIN);
607                     }
608                     if (SonosBindingConstants.WITH_ANALOG_LINEIN_THING_TYPES_UIDS
609                             .contains(getThing().getThingTypeUID())) {
610                         updateChannel(ANALOGLINEIN);
611                     }
612                     break;
613                 case TOSLINEINCONNECTED:
614                     if (SonosBindingConstants.WITH_LINEIN_THING_TYPES_UIDS.contains(getThing().getThingTypeUID())) {
615                         updateChannel(LINEIN);
616                     }
617                     if (SonosBindingConstants.WITH_DIGITAL_LINEIN_THING_TYPES_UIDS
618                             .contains(getThing().getThingTypeUID())) {
619                         updateChannel(DIGITALLINEIN);
620                     }
621                     break;
622                 case "AlarmRunning":
623                     updateChannel(ALARMRUNNING);
624                     updateRunningAlarmProperties();
625                     break;
626                 case "RunningAlarmProperties":
627                     updateChannel(ALARMPROPERTIES);
628                     break;
629                 case "CurrentURIFormatted":
630                     updateChannel(CURRENTTRACK);
631                     break;
632                 case "CurrentTitle":
633                     updateChannel(CURRENTTITLE);
634                     break;
635                 case "CurrentArtist":
636                     updateChannel(CURRENTARTIST);
637                     break;
638                 case "CurrentAlbum":
639                     updateChannel(CURRENTALBUM);
640                     break;
641                 case "CurrentURI":
642                     updateChannel(CURRENTTRANSPORTURI);
643                     break;
644                 case "CurrentTrackURI":
645                     updateChannel(CURRENTTRACKURI);
646                     break;
647                 case "CurrentAlbumArtURI":
648                     updateChannel(CURRENTALBUMARTURL);
649                     break;
650                 case "CurrentSleepTimerGeneration":
651                     if (value.equals("0")) {
652                         updateState(SLEEPTIMER, new DecimalType(0));
653                     }
654                     break;
655                 case "SleepTimerGeneration":
656                     if (value.equals("0")) {
657                         updateState(SLEEPTIMER, new DecimalType(0));
658                     } else {
659                         updateSleepTimerDuration();
660                     }
661                     break;
662                 case "RemainingSleepTimerDuration":
663                     updateState(SLEEPTIMER, new DecimalType(sleepStrTimeToSeconds(value)));
664                     break;
665                 case "CurrentTuneInStationId":
666                     updateChannel(TUNEINSTATIONID);
667                     break;
668                 case "SavedQueuesUpdateID": // service ContentDirectoy
669                     for (SonosEntry entry : getPlayLists()) {
670                         options.add(new StateOption(entry.getTitle(), entry.getTitle()));
671                     }
672                     stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), PLAYLIST), options);
673                     break;
674                 case "FavoritesUpdateID": // service ContentDirectoy
675                     for (SonosEntry entry : getFavorites()) {
676                         options.add(new StateOption(entry.getTitle(), entry.getTitle()));
677                     }
678                     stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), FAVORITE), options);
679                     break;
680                 // For favorite radios, we should have checked the state variable named RadioFavoritesUpdateID
681                 // Due to a bug in the data type definition of this state variable, it is not set.
682                 // As a workaround, we check the state variable named ContainerUpdateIDs.
683                 case "ContainerUpdateIDs": // service ContentDirectoy
684                     if (value.startsWith("R:0,") || stateDescriptionProvider
685                             .getStateOptions(new ChannelUID(getThing().getUID(), RADIO)) == null) {
686                         for (SonosEntry entry : getFavoriteRadios()) {
687                             options.add(new StateOption(entry.getTitle(), entry.getTitle()));
688                         }
689                         stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), RADIO), options);
690                     }
691                     break;
692                 default:
693                     break;
694             }
695         }
696     }
697
698     private void dispatchOnAllGroupMembers(String variable, String value, String service) {
699         if (isCoordinator()) {
700             for (String member : getOtherZoneGroupMembers()) {
701                 try {
702                     ZonePlayerHandler memberHandler = getHandlerByName(member);
703                     if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) {
704                         memberHandler.onValueReceived(variable, value, service);
705                     }
706                 } catch (IllegalStateException e) {
707                     logger.debug("Cannot update channel for group member ({})", e.getMessage());
708                 }
709             }
710         }
711     }
712
713     private @Nullable String getAlbumArtUrl() {
714         String url = null;
715         String albumArtURI = stateMap.get("CurrentAlbumArtURI");
716         if (albumArtURI != null) {
717             if (albumArtURI.startsWith("http")) {
718                 url = albumArtURI;
719             } else if (albumArtURI.startsWith("/")) {
720                 try {
721                     URL serviceDescrUrl = service.getDescriptorURL(this);
722                     if (serviceDescrUrl != null) {
723                         url = new URL(serviceDescrUrl.getProtocol(), serviceDescrUrl.getHost(),
724                                 serviceDescrUrl.getPort(), albumArtURI).toExternalForm();
725                     }
726                 } catch (MalformedURLException e) {
727                     logger.debug("Failed to build a valid album art URL from {}: {}", albumArtURI, e.getMessage());
728                 }
729             }
730         }
731         return url;
732     }
733
734     protected void updateChannel(String channelId) {
735         if (!isLinked(channelId)) {
736             return;
737         }
738
739         String url;
740
741         State newState = UnDefType.UNDEF;
742         String value;
743         switch (channelId) {
744             case STATE:
745                 value = getTransportState();
746                 if (value != null) {
747                     newState = new StringType(value);
748                 }
749                 break;
750             case CONTROL:
751                 value = getTransportState();
752                 if (STATE_PLAYING.equals(value)) {
753                     newState = PlayPauseType.PLAY;
754                 } else if (STATE_STOPPED.equals(value)) {
755                     newState = PlayPauseType.PAUSE;
756                 } else if (STATE_PAUSED_PLAYBACK.equals(value)) {
757                     newState = PlayPauseType.PAUSE;
758                 }
759                 break;
760             case STOP:
761                 value = getTransportState();
762                 if (value != null) {
763                     newState = OnOffType.from(STATE_STOPPED.equals(value));
764                 }
765                 break;
766             case SHUFFLE:
767                 if (getPlayMode() != null) {
768                     newState = OnOffType.from(isShuffleActive());
769                 }
770                 break;
771             case REPEAT:
772                 if (getPlayMode() != null) {
773                     newState = new StringType(getRepeatMode());
774                 }
775                 break;
776             case LED:
777                 value = getLed();
778                 if (value != null) {
779                     newState = OnOffType.from(value);
780                 }
781                 break;
782             case ZONENAME:
783                 value = getCurrentZoneName();
784                 if (value != null) {
785                     newState = new StringType(value);
786                 }
787                 break;
788             case ZONEGROUPID:
789                 value = getZoneGroupID();
790                 if (value != null) {
791                     newState = new StringType(value);
792                 }
793                 break;
794             case COORDINATOR:
795                 newState = new StringType(getCoordinator());
796                 break;
797             case LOCALCOORDINATOR:
798                 if (getGroupCoordinatorIsLocal() != null) {
799                     newState = OnOffType.from(isGroupCoordinator());
800                 }
801                 break;
802             case VOLUME:
803                 value = getVolume();
804                 if (value != null) {
805                     newState = new PercentType(value);
806                 }
807                 break;
808             case BASS:
809                 value = getBass();
810                 if (value != null && !isOutputLevelFixed()) {
811                     newState = new DecimalType(value);
812                 }
813                 break;
814             case TREBLE:
815                 value = getTreble();
816                 if (value != null && !isOutputLevelFixed()) {
817                     newState = new DecimalType(value);
818                 }
819                 break;
820             case LOUDNESS:
821                 value = getLoudness();
822                 if (value != null && !isOutputLevelFixed()) {
823                     newState = OnOffType.from(value);
824                 }
825                 break;
826             case MUTE:
827                 value = getMute();
828                 if (value != null) {
829                     newState = OnOffType.from(value);
830                 }
831                 break;
832             case SUBWOOFER:
833                 value = getSubwooferEnabled();
834                 if (value != null) {
835                     newState = OnOffType.from(value);
836                 }
837                 break;
838             case SUBWOOFERGAIN:
839                 value = getSubwooferGain();
840                 if (value != null) {
841                     newState = new DecimalType(value);
842                 }
843                 break;
844             case SURROUND:
845                 value = getSurroundEnabled();
846                 if (value != null) {
847                     newState = OnOffType.from(value);
848                 }
849                 break;
850             case SURROUNDMUSICMODE:
851                 value = getSurroundMusicMode();
852                 if (value != null) {
853                     newState = new StringType(value);
854                 }
855                 break;
856             case SURROUNDMUSICLEVEL:
857                 value = getSurroundMusicLevel();
858                 if (value != null) {
859                     newState = new DecimalType(value);
860                 }
861                 break;
862             case SURROUNDTVLEVEL:
863                 value = getSurroundTvLevel();
864                 if (value != null) {
865                     newState = new DecimalType(value);
866                 }
867                 break;
868             case NIGHTMODE:
869                 value = getNightMode();
870                 if (value != null) {
871                     newState = OnOffType.from(value);
872                 }
873                 break;
874             case SPEECHENHANCEMENT:
875                 value = getDialogLevel();
876                 if (value != null) {
877                     newState = OnOffType.from(value);
878                 }
879                 break;
880             case LINEIN:
881                 if (getAnalogLineInConnected() != null) {
882                     newState = OnOffType.from(isAnalogLineInConnected());
883                 } else if (getOpticalLineInConnected() != null) {
884                     newState = OnOffType.from(isOpticalLineInConnected());
885                 }
886                 break;
887             case ANALOGLINEIN:
888                 if (getAnalogLineInConnected() != null) {
889                     newState = OnOffType.from(isAnalogLineInConnected());
890                 }
891                 break;
892             case DIGITALLINEIN:
893                 if (getOpticalLineInConnected() != null) {
894                     newState = OnOffType.from(isOpticalLineInConnected());
895                 }
896                 break;
897             case ALARMRUNNING:
898                 if (getAlarmRunning() != null) {
899                     newState = OnOffType.from(isAlarmRunning());
900                 }
901                 break;
902             case ALARMPROPERTIES:
903                 value = getRunningAlarmProperties();
904                 if (value != null) {
905                     newState = new StringType(value);
906                 }
907                 break;
908             case CURRENTTRACK:
909                 value = stateMap.get("CurrentURIFormatted");
910                 if (value != null) {
911                     newState = new StringType(value);
912                 }
913                 break;
914             case CURRENTTITLE:
915                 value = getCurrentTitle();
916                 if (value != null) {
917                     newState = new StringType(value);
918                 }
919                 break;
920             case CURRENTARTIST:
921                 value = getCurrentArtist();
922                 if (value != null) {
923                     newState = new StringType(value);
924                 }
925                 break;
926             case CURRENTALBUM:
927                 value = getCurrentAlbum();
928                 if (value != null) {
929                     newState = new StringType(value);
930                 }
931                 break;
932             case CURRENTALBUMART:
933                 newState = null;
934                 updateAlbumArtChannel(false);
935                 break;
936             case CURRENTALBUMARTURL:
937                 url = getAlbumArtUrl();
938                 if (url != null) {
939                     newState = new StringType(url);
940                 }
941                 break;
942             case CURRENTTRANSPORTURI:
943                 value = getCurrentURI();
944                 if (value != null) {
945                     newState = new StringType(value);
946                 }
947                 break;
948             case CURRENTTRACKURI:
949                 value = stateMap.get("CurrentTrackURI");
950                 if (value != null) {
951                     newState = new StringType(value);
952                 }
953                 break;
954             case TUNEINSTATIONID:
955                 value = stateMap.get("CurrentTuneInStationId");
956                 if (value != null) {
957                     newState = new StringType(value);
958                 }
959                 break;
960             default:
961                 newState = null;
962                 break;
963         }
964         if (newState != null) {
965             updateState(channelId, newState);
966         }
967     }
968
969     private void updateAlbumArtChannel(boolean allGroup) {
970         String url = getAlbumArtUrl();
971         if (url != null) {
972             // We download the cover art in a different thread to not delay the other operations
973             scheduler.submit(() -> {
974                 RawType image = HttpUtil.downloadImage(url, true, 500000);
975                 updateChannel(CURRENTALBUMART, image != null ? image : UnDefType.UNDEF, allGroup);
976             });
977         } else {
978             updateChannel(CURRENTALBUMART, UnDefType.UNDEF, allGroup);
979         }
980     }
981
982     private void updateChannel(String channeldD, State state, boolean allGroup) {
983         if (allGroup) {
984             for (String member : getZoneGroupMembers()) {
985                 try {
986                     ZonePlayerHandler memberHandler = getHandlerByName(member);
987                     if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())
988                             && memberHandler.isLinked(channeldD)) {
989                         memberHandler.updateState(channeldD, state);
990                     }
991                 } catch (IllegalStateException e) {
992                     logger.debug("Cannot update channel for group member ({})", e.getMessage());
993                 }
994             }
995         } else if (ThingStatus.ONLINE.equals(getThing().getStatus()) && isLinked(channeldD)) {
996             updateState(channeldD, state);
997         }
998     }
999
1000     /**
1001      * CurrentURI will not change, but will trigger change of CurrentURIFormated
1002      * CurrentTrackMetaData will not change, but will trigger change of Title, Artist, Album
1003      */
1004     private boolean shouldIgnoreVariableUpdate(String variable, String value, @Nullable String oldValue) {
1005         return !hasValueChanged(value, oldValue) && !isQueueEvent(variable);
1006     }
1007
1008     private boolean hasValueChanged(@Nullable String value, @Nullable String oldValue) {
1009         return oldValue != null ? !oldValue.equals(value) : value != null;
1010     }
1011
1012     /**
1013      * Similar to the AVTransport eventing, the Queue events its state variables
1014      * as sub values within a synthesized LastChange state variable.
1015      */
1016     private boolean isQueueEvent(String variable) {
1017         return "LastChange".equals(variable);
1018     }
1019
1020     private void updateGroupCoordinator() {
1021         try {
1022             coordinatorHandler = getHandlerByName(getCoordinator());
1023         } catch (IllegalStateException e) {
1024             logger.debug("Cannot update the group coordinator ({})", e.getMessage());
1025             coordinatorHandler = null;
1026         }
1027     }
1028
1029     private boolean isUpnpDeviceRegistered() {
1030         return service.isRegistered(this);
1031     }
1032
1033     private void addSubscription() {
1034         synchronized (upnpLock) {
1035             // Set up GENA Subscriptions
1036             if (service.isRegistered(this)) {
1037                 for (String subscription : SERVICE_SUBSCRIPTIONS) {
1038                     Boolean state = subscriptionState.get(subscription);
1039                     if (state == null || !state) {
1040                         logger.debug("{}: Subscribing to service {}...", getUDN(), subscription);
1041                         service.addSubscription(this, subscription, SUBSCRIPTION_DURATION);
1042                         subscriptionState.put(subscription, true);
1043                     }
1044                 }
1045             }
1046         }
1047     }
1048
1049     private void removeSubscription() {
1050         synchronized (upnpLock) {
1051             // Set up GENA Subscriptions
1052             if (service.isRegistered(this)) {
1053                 for (String subscription : SERVICE_SUBSCRIPTIONS) {
1054                     Boolean state = subscriptionState.get(subscription);
1055                     if (state != null && state) {
1056                         logger.debug("{}: Unsubscribing from service {}...", getUDN(), subscription);
1057                         service.removeSubscription(this, subscription);
1058                     }
1059                 }
1060             }
1061             subscriptionState = new HashMap<>();
1062         }
1063     }
1064
1065     @Override
1066     public void onServiceSubscribed(@Nullable String service, boolean succeeded) {
1067         if (service == null) {
1068             return;
1069         }
1070         synchronized (upnpLock) {
1071             logger.debug("{}: Subscription to service {} {}", getUDN(), service, succeeded ? "succeeded" : "failed");
1072             subscriptionState.put(service, succeeded);
1073         }
1074     }
1075
1076     private Map<String, String> executeAction(String serviceId, String actionId, @Nullable Map<String, String> inputs) {
1077         Map<String, String> result = service.invokeAction(this, serviceId, actionId, inputs);
1078         result.forEach((variable, value) -> {
1079             this.onValueReceived(variable, value, serviceId);
1080         });
1081         return result;
1082     }
1083
1084     private void updatePlayerState() {
1085         if (!updateZoneInfo()) {
1086             if (!ThingStatus.OFFLINE.equals(getThing().getStatus())) {
1087                 logger.debug("Sonos player {} is not available in local network", getUDN());
1088                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
1089                         "@text/offline.not-available-on-network [\"" + getUDN() + "\"]");
1090                 synchronized (upnpLock) {
1091                     subscriptionState = new HashMap<>();
1092                 }
1093             }
1094         } else if (!ThingStatus.ONLINE.equals(getThing().getStatus())) {
1095             logger.debug("Sonos player {} has been found in local network", getUDN());
1096             updateStatus(ThingStatus.ONLINE);
1097         }
1098     }
1099
1100     protected void updateCurrentZoneName() {
1101         executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_GET_ZONE_ATTRIBUTES, null);
1102     }
1103
1104     protected void updateLed() {
1105         executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_GET_LED_STATE, null);
1106     }
1107
1108     protected void updateTime() {
1109         executeAction(SERVICE_ALARM_CLOCK, "GetTimeNow", null);
1110     }
1111
1112     protected void updatePosition() {
1113         executeAction(SERVICE_AV_TRANSPORT, ACTION_GET_POSITION_INFO, null);
1114     }
1115
1116     protected void updateRunningAlarmProperties() {
1117         Map<String, String> result = service.invokeAction(this, SERVICE_AV_TRANSPORT,
1118                 ACTION_GET_RUNNING_ALARM_PROPERTIES, null);
1119
1120         String alarmID = result.get("AlarmID");
1121         String loggedStartTime = result.get("LoggedStartTime");
1122         String newStringValue = null;
1123         if (alarmID != null && loggedStartTime != null) {
1124             newStringValue = alarmID + " - " + loggedStartTime;
1125         } else {
1126             newStringValue = "No running alarm";
1127         }
1128         result.put("RunningAlarmProperties", newStringValue);
1129
1130         result.forEach((variable, value) -> {
1131             this.onValueReceived(variable, value, SERVICE_AV_TRANSPORT);
1132         });
1133     }
1134
1135     protected boolean updateZoneInfo() {
1136         Map<String, String> result = executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_GET_ZONE_INFO, null);
1137
1138         Map<String, String> properties = editProperties();
1139         String value = stateMap.get("HardwareVersion");
1140         if (value != null && !value.isEmpty()) {
1141             properties.put(Thing.PROPERTY_HARDWARE_VERSION, value);
1142         }
1143         value = stateMap.get("DisplaySoftwareVersion");
1144         if (value != null && !value.isEmpty()) {
1145             properties.put(Thing.PROPERTY_FIRMWARE_VERSION, value);
1146         }
1147         value = stateMap.get("SerialNumber");
1148         if (value != null && !value.isEmpty()) {
1149             properties.put(Thing.PROPERTY_SERIAL_NUMBER, value);
1150         }
1151         value = stateMap.get("MACAddress");
1152         if (value != null && !value.isEmpty()) {
1153             properties.put(MAC_ADDRESS, value);
1154         }
1155         value = stateMap.get("IPAddress");
1156         if (value != null && !value.isEmpty()) {
1157             properties.put(IP_ADDRESS, value);
1158         }
1159         updateProperties(properties);
1160
1161         return !result.isEmpty();
1162     }
1163
1164     public String getCoordinator() {
1165         for (SonosZoneGroup zg : getZoneGroups()) {
1166             if (zg.getMembers().contains(getUDN())) {
1167                 return zg.getCoordinator();
1168             }
1169         }
1170         return getUDN();
1171     }
1172
1173     public boolean isCoordinator() {
1174         return getUDN().equals(getCoordinator());
1175     }
1176
1177     protected void updateMediaInformation() {
1178         String currentURI = getCurrentURI();
1179         SonosMetaData currentTrack = getTrackMetadata();
1180         SonosMetaData currentUriMetaData = getCurrentURIMetadata();
1181
1182         String artist = null;
1183         String album = null;
1184         String title = null;
1185         String resultString = null;
1186         String stationID = null;
1187         boolean needsUpdating = false;
1188
1189         // if currentURI == null, we do nothing
1190         if (currentURI != null) {
1191             if (currentURI.isEmpty()) {
1192                 // Reset data
1193                 needsUpdating = true;
1194             }
1195
1196             // if (currentURI.contains(GROUP_URI)) we do nothing, because
1197             // The Sonos is a slave member of a group
1198             // The media information will be updated by the coordinator
1199             // Notification of group change occurs later, so we just check the URI
1200
1201             else if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)) {
1202                 // Radio stream (tune-in)
1203                 boolean opmlUrlSucceeded = false;
1204                 stationID = extractStationId(currentURI);
1205                 String url = opmlUrl;
1206                 if (url != null) {
1207                     String mac = getMACAddress();
1208                     if (stationID != null && !stationID.isEmpty() && mac != null && !mac.isEmpty()) {
1209                         url = url.replace("%id", stationID);
1210                         url = url.replace("%serial", mac);
1211
1212                         String response = null;
1213                         try {
1214                             response = HttpUtil.executeUrl("GET", url, SOCKET_TIMEOUT);
1215                         } catch (IOException e) {
1216                             logger.debug("Request to device failed", e);
1217                         }
1218
1219                         if (response != null) {
1220                             List<String> fields = SonosXMLParser.getRadioTimeFromXML(response);
1221
1222                             if (!fields.isEmpty()) {
1223                                 opmlUrlSucceeded = true;
1224
1225                                 resultString = "";
1226                                 for (String field : fields) {
1227                                     if (resultString.isEmpty()) {
1228                                         // radio name should be first field
1229                                         title = field;
1230                                     } else {
1231                                         resultString += " - ";
1232                                     }
1233                                     resultString += field;
1234                                 }
1235
1236                                 needsUpdating = true;
1237                             }
1238                         }
1239                     }
1240                 }
1241                 if (!opmlUrlSucceeded) {
1242                     if (currentUriMetaData != null) {
1243                         title = currentUriMetaData.getTitle();
1244                         if (currentTrack == null || currentTrack.getStreamContent().isEmpty()) {
1245                             resultString = title;
1246                         } else {
1247                             resultString = title + " - " + currentTrack.getStreamContent();
1248                         }
1249                         needsUpdating = true;
1250                     }
1251                 }
1252             }
1253
1254             else if (isPlayingLineIn(currentURI)) {
1255                 if (currentTrack != null) {
1256                     title = currentTrack.getTitle();
1257                     resultString = title;
1258                     needsUpdating = true;
1259                 }
1260             }
1261
1262             else if (isPlayingRadio(currentURI)
1263                     || (!currentURI.contains("x-rincon-mp3") && !currentURI.contains("x-sonosapi"))) {
1264                 // isPlayingRadio(currentURI) is true for Google Play Music radio or Apple Music radio
1265                 if (currentTrack != null) {
1266                     artist = !currentTrack.getAlbumArtist().isEmpty() ? currentTrack.getAlbumArtist()
1267                             : currentTrack.getCreator();
1268                     album = currentTrack.getAlbum();
1269                     title = currentTrack.getTitle();
1270                     resultString = artist + " - " + album + " - " + title;
1271                     needsUpdating = true;
1272                 }
1273             }
1274         }
1275
1276         String albumArtURI = (currentTrack != null && !currentTrack.getAlbumArtUri().isEmpty())
1277                 ? currentTrack.getAlbumArtUri()
1278                 : "";
1279
1280         ZonePlayerHandler handlerForImageUpdate = null;
1281         for (String member : getZoneGroupMembers()) {
1282             try {
1283                 ZonePlayerHandler memberHandler = getHandlerByName(member);
1284                 if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) {
1285                     if (memberHandler.isLinked(CURRENTALBUMART)
1286                             && hasValueChanged(albumArtURI, memberHandler.stateMap.get("CurrentAlbumArtURI"))) {
1287                         handlerForImageUpdate = memberHandler;
1288                     }
1289                     memberHandler.onValueReceived("CurrentTuneInStationId", (stationID != null) ? stationID : "",
1290                             SERVICE_AV_TRANSPORT);
1291                     if (needsUpdating) {
1292                         memberHandler.onValueReceived("CurrentArtist", (artist != null) ? artist : "",
1293                                 SERVICE_AV_TRANSPORT);
1294                         memberHandler.onValueReceived("CurrentAlbum", (album != null) ? album : "",
1295                                 SERVICE_AV_TRANSPORT);
1296                         memberHandler.onValueReceived("CurrentTitle", (title != null) ? title : "",
1297                                 SERVICE_AV_TRANSPORT);
1298                         memberHandler.onValueReceived("CurrentURIFormatted", (resultString != null) ? resultString : "",
1299                                 SERVICE_AV_TRANSPORT);
1300                         memberHandler.onValueReceived("CurrentAlbumArtURI", albumArtURI, SERVICE_AV_TRANSPORT);
1301                     }
1302                 }
1303             } catch (IllegalStateException e) {
1304                 logger.debug("Cannot update media data for group member ({})", e.getMessage());
1305             }
1306         }
1307         if (needsUpdating && handlerForImageUpdate != null) {
1308             handlerForImageUpdate.updateAlbumArtChannel(true);
1309         }
1310     }
1311
1312     private @Nullable String extractStationId(String uri) {
1313         String stationID = null;
1314         if (isPlayingStream(uri)) {
1315             stationID = substringBetween(uri, ":s", "?sid");
1316         } else if (isPlayingRadioStartedByAmazonEcho(uri)) {
1317             stationID = substringBetween(uri, "sid=s", "&");
1318         }
1319         return stationID;
1320     }
1321
1322     private @Nullable String substringBetween(String str, String open, String close) {
1323         String result = null;
1324         int idx1 = str.indexOf(open);
1325         if (idx1 >= 0) {
1326             idx1 += open.length();
1327             int idx2 = str.indexOf(close, idx1);
1328             if (idx2 >= 0) {
1329                 result = str.substring(idx1, idx2);
1330             }
1331         }
1332         return result;
1333     }
1334
1335     public @Nullable String getGroupCoordinatorIsLocal() {
1336         return stateMap.get("GroupCoordinatorIsLocal");
1337     }
1338
1339     public boolean isGroupCoordinator() {
1340         return "true".equals(getGroupCoordinatorIsLocal());
1341     }
1342
1343     @Override
1344     public String getUDN() {
1345         String udn = configuration.udn;
1346         return udn != null && !udn.isEmpty() ? udn : "undefined";
1347     }
1348
1349     public @Nullable String getCurrentURI() {
1350         return stateMap.get("CurrentURI");
1351     }
1352
1353     public @Nullable String getCurrentURIMetadataAsString() {
1354         return stateMap.get("CurrentURIMetaData");
1355     }
1356
1357     public @Nullable SonosMetaData getCurrentURIMetadata() {
1358         String metaData = getCurrentURIMetadataAsString();
1359         return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1360     }
1361
1362     public @Nullable SonosMetaData getTrackMetadata() {
1363         String metaData = stateMap.get("CurrentTrackMetaData");
1364         return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1365     }
1366
1367     public @Nullable SonosMetaData getEnqueuedTransportURIMetaData() {
1368         String metaData = stateMap.get("EnqueuedTransportURIMetaData");
1369         return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1370     }
1371
1372     public @Nullable String getMACAddress() {
1373         String mac = stateMap.get("MACAddress");
1374         if (mac == null || mac.isEmpty()) {
1375             updateZoneInfo();
1376         }
1377         return stateMap.get("MACAddress");
1378     }
1379
1380     public @Nullable String getRefreshedPosition() {
1381         updatePosition();
1382         return stateMap.get("RelTime");
1383     }
1384
1385     public long getRefreshedCurrenTrackNr() {
1386         updatePosition();
1387         String value = stateMap.get("Track");
1388         if (value != null) {
1389             return Long.valueOf(value);
1390         } else {
1391             return -1;
1392         }
1393     }
1394
1395     public @Nullable String getVolume() {
1396         return stateMap.get("VolumeMaster");
1397     }
1398
1399     public boolean isOutputLevelFixed() {
1400         return "1".equals(stateMap.get("OutputFixed"));
1401     }
1402
1403     public @Nullable String getBass() {
1404         return stateMap.get("Bass");
1405     }
1406
1407     public @Nullable String getTreble() {
1408         return stateMap.get("Treble");
1409     }
1410
1411     public @Nullable String getLoudness() {
1412         return stateMap.get("LoudnessMaster");
1413     }
1414
1415     public @Nullable String getSurroundEnabled() {
1416         return stateMap.get("SurroundEnabled");
1417     }
1418
1419     public @Nullable String getSurroundMusicMode() {
1420         return stateMap.get("SurroundMode");
1421     }
1422
1423     public @Nullable String getSurroundTvLevel() {
1424         return stateMap.get("SurroundLevel");
1425     }
1426
1427     public @Nullable String getSurroundMusicLevel() {
1428         return stateMap.get("MusicSurroundLevel");
1429     }
1430
1431     public @Nullable String getSubwooferEnabled() {
1432         return stateMap.get("SubEnabled");
1433     }
1434
1435     public @Nullable String getSubwooferGain() {
1436         return stateMap.get("SubGain");
1437     }
1438
1439     public @Nullable String getTransportState() {
1440         return stateMap.get("TransportState");
1441     }
1442
1443     public @Nullable String getCurrentTitle() {
1444         return stateMap.get("CurrentTitle");
1445     }
1446
1447     public @Nullable String getCurrentArtist() {
1448         return stateMap.get("CurrentArtist");
1449     }
1450
1451     public @Nullable String getCurrentAlbum() {
1452         return stateMap.get("CurrentAlbum");
1453     }
1454
1455     public List<SonosEntry> getArtists(String filter) {
1456         return getEntries("A:", filter);
1457     }
1458
1459     public List<SonosEntry> getArtists() {
1460         return getEntries("A:", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1461     }
1462
1463     public List<SonosEntry> getAlbums(String filter) {
1464         return getEntries("A:ALBUM", filter);
1465     }
1466
1467     public List<SonosEntry> getAlbums() {
1468         return getEntries("A:ALBUM", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1469     }
1470
1471     public List<SonosEntry> getTracks(String filter) {
1472         return getEntries("A:TRACKS", filter);
1473     }
1474
1475     public List<SonosEntry> getTracks() {
1476         return getEntries("A:TRACKS", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1477     }
1478
1479     public List<SonosEntry> getQueue(String filter) {
1480         return getEntries("Q:0", filter);
1481     }
1482
1483     public List<SonosEntry> getQueue() {
1484         return getEntries("Q:0", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1485     }
1486
1487     public long getQueueSize() {
1488         return getNbEntries("Q:0");
1489     }
1490
1491     public List<SonosEntry> getPlayLists(String filter) {
1492         return getEntries("SQ:", filter);
1493     }
1494
1495     public List<SonosEntry> getPlayLists() {
1496         return getEntries("SQ:", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1497     }
1498
1499     public List<SonosEntry> getFavoriteRadios(String filter) {
1500         return getEntries("R:0/0", filter);
1501     }
1502
1503     public List<SonosEntry> getFavoriteRadios() {
1504         return getEntries("R:0/0", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1505     }
1506
1507     /**
1508      * Searches for entries in the 'favorites' list on a sonos account
1509      *
1510      * @return
1511      */
1512     public List<SonosEntry> getFavorites() {
1513         return getEntries("FV:2", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1514     }
1515
1516     protected List<SonosEntry> getEntries(String type, String filter) {
1517         long startAt = 0;
1518
1519         Map<String, String> inputs = new HashMap<>();
1520         inputs.put("ObjectID", type);
1521         inputs.put("BrowseFlag", "BrowseDirectChildren");
1522         inputs.put("Filter", filter);
1523         inputs.put("StartingIndex", Long.toString(startAt));
1524         inputs.put("RequestedCount", Integer.toString(200));
1525         inputs.put("SortCriteria", "");
1526
1527         Map<String, String> result = service.invokeAction(this, SERVICE_CONTENT_DIRECTORY, "Browse", inputs);
1528
1529         String initialResult = result.get("Result");
1530         if (initialResult == null) {
1531             return Collections.emptyList();
1532         }
1533
1534         long totalMatches = getResultEntry(result, "TotalMatches", type, filter);
1535         long initialNumberReturned = getResultEntry(result, "NumberReturned", type, filter);
1536
1537         List<SonosEntry> resultList = SonosXMLParser.getEntriesFromString(initialResult);
1538         startAt = startAt + initialNumberReturned;
1539
1540         while (startAt < totalMatches) {
1541             inputs.put("StartingIndex", Long.toString(startAt));
1542             result = service.invokeAction(this, SERVICE_CONTENT_DIRECTORY, "Browse", inputs);
1543
1544             // Execute this action synchronously
1545             String nextResult = result.get("Result");
1546             if (nextResult == null) {
1547                 break;
1548             }
1549
1550             long numberReturned = getResultEntry(result, "NumberReturned", type, filter);
1551
1552             resultList.addAll(SonosXMLParser.getEntriesFromString(nextResult));
1553
1554             startAt = startAt + numberReturned;
1555         }
1556
1557         return resultList;
1558     }
1559
1560     protected long getNbEntries(String type) {
1561         Map<String, String> inputs = new HashMap<>();
1562         inputs.put("ObjectID", type);
1563         inputs.put("BrowseFlag", "BrowseDirectChildren");
1564         inputs.put("Filter", "dc:title");
1565         inputs.put("StartingIndex", "0");
1566         inputs.put("RequestedCount", "1");
1567         inputs.put("SortCriteria", "");
1568
1569         Map<String, String> result = service.invokeAction(this, SERVICE_CONTENT_DIRECTORY, "Browse", inputs);
1570
1571         return getResultEntry(result, "TotalMatches", type, "dc:title");
1572     }
1573
1574     /**
1575      * Handles value searching in a SONOS result map (called by {@link #getEntries(String, String)})
1576      *
1577      * @param resultInput - the map to be examined for the requestedKey
1578      * @param requestedKey - the key to be sought in the resultInput map
1579      * @param entriesType - the 'type' argument of {@link #getEntries(String, String)} method used for logging
1580      * @param entriesFilter - the 'filter' argument of {@link #getEntries(String, String)} method used for logging
1581      *
1582      * @return 0 as long or the value corresponding to the requiredKey if found
1583      */
1584     private Long getResultEntry(Map<String, String> resultInput, String requestedKey, String entriesType,
1585             String entriesFilter) {
1586         long result = 0;
1587
1588         if (resultInput.isEmpty()) {
1589             return result;
1590         }
1591
1592         try {
1593             String resultString = resultInput.get(requestedKey);
1594             if (resultString == null) {
1595                 throw new NumberFormatException("Requested key is null.");
1596             }
1597             result = Long.valueOf(resultString);
1598         } catch (NumberFormatException ex) {
1599             logger.debug("Could not fetch {} result for type: {} and filter: {}. Using default value '0': {}",
1600                     requestedKey, entriesType, entriesFilter, ex.getMessage(), ex);
1601         }
1602
1603         return result;
1604     }
1605
1606     /**
1607      * Save the state (track, position etc) of the Sonos Zone player.
1608      *
1609      * @return true if no error occurred.
1610      */
1611     protected void saveState() {
1612         synchronized (stateLock) {
1613             savedState = new SonosZonePlayerState();
1614             String currentURI = getCurrentURI();
1615
1616             savedState.transportState = getTransportState();
1617             savedState.volume = getVolume();
1618
1619             if (currentURI != null) {
1620                 if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)
1621                         || isPlayingRadio(currentURI)) {
1622                     // we are streaming music, like tune-in radio or Google Play Music radio
1623                     SonosMetaData track = getTrackMetadata();
1624                     SonosMetaData current = getCurrentURIMetadata();
1625                     if (track != null && current != null) {
1626                         savedState.entry = new SonosEntry("", current.getTitle(), "", "", track.getAlbumArtUri(), "",
1627                                 current.getUpnpClass(), currentURI);
1628                     }
1629                 } else if (currentURI.contains(GROUP_URI)) {
1630                     // we are a slave to some coordinator
1631                     savedState.entry = new SonosEntry("", "", "", "", "", "", "", currentURI);
1632                 } else if (isPlayingLineIn(currentURI)) {
1633                     // we are streaming from the Line In connection
1634                     savedState.entry = new SonosEntry("", "", "", "", "", "", "", currentURI);
1635                 } else if (isPlayingQueue(currentURI)) {
1636                     // we are playing something that sits in the queue
1637                     SonosMetaData queued = getEnqueuedTransportURIMetaData();
1638                     if (queued != null) {
1639                         savedState.track = getRefreshedCurrenTrackNr();
1640
1641                         if (queued.getUpnpClass().contains("object.container.playlistContainer")) {
1642                             // we are playing a real 'saved' playlist
1643                             List<SonosEntry> playLists = getPlayLists();
1644                             for (SonosEntry someList : playLists) {
1645                                 if (someList.getTitle().equals(queued.getTitle())) {
1646                                     savedState.entry = new SonosEntry(someList.getId(), someList.getTitle(),
1647                                             someList.getParentId(), "", "", "", someList.getUpnpClass(),
1648                                             someList.getRes());
1649                                     break;
1650                                 }
1651                             }
1652                         } else if (queued.getUpnpClass().contains("object.container")) {
1653                             // we are playing some other sort of
1654                             // 'container' - we will save that to a
1655                             // playlist for our convenience
1656                             logger.debug("Save State for a container of type {}", queued.getUpnpClass());
1657
1658                             // save the playlist
1659                             String existingList = "";
1660                             List<SonosEntry> playLists = getPlayLists();
1661                             for (SonosEntry someList : playLists) {
1662                                 if (someList.getTitle().equals(TITLE_PREFIX + getUDN())) {
1663                                     existingList = someList.getId();
1664                                     break;
1665                                 }
1666                             }
1667
1668                             saveQueue(TITLE_PREFIX + getUDN(), existingList);
1669
1670                             // get all the playlists and a ref to our
1671                             // saved list
1672                             playLists = getPlayLists();
1673                             for (SonosEntry someList : playLists) {
1674                                 if (someList.getTitle().equals(TITLE_PREFIX + getUDN())) {
1675                                     savedState.entry = new SonosEntry(someList.getId(), someList.getTitle(),
1676                                             someList.getParentId(), "", "", "", someList.getUpnpClass(),
1677                                             someList.getRes());
1678                                     break;
1679                                 }
1680                             }
1681                         }
1682                     } else {
1683                         savedState.entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + getUDN() + "#0");
1684                     }
1685                 }
1686
1687                 savedState.relTime = getRefreshedPosition();
1688             } else {
1689                 savedState.entry = null;
1690             }
1691         }
1692     }
1693
1694     /**
1695      * Restore the state (track, position etc) of the Sonos Zone player.
1696      *
1697      * @return true if no error occurred.
1698      */
1699     protected void restoreState() {
1700         synchronized (stateLock) {
1701             SonosZonePlayerState state = savedState;
1702             if (state != null) {
1703                 // put settings back
1704                 String volume = state.volume;
1705                 if (volume != null) {
1706                     setVolume(DecimalType.valueOf(volume));
1707                 }
1708
1709                 if (isCoordinator()) {
1710                     SonosEntry entry = state.entry;
1711                     if (entry != null) {
1712                         // check if we have a playlist to deal with
1713                         if (entry.getUpnpClass().contains("object.container.playlistContainer")) {
1714                             addURIToQueue(entry.getRes(), SonosXMLParser.compileMetadataString(entry), 0, true);
1715                             entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + getUDN() + "#0");
1716                             setCurrentURI(entry);
1717                             setPositionTrack(state.track);
1718                         } else {
1719                             setCurrentURI(entry);
1720                             setPosition(state.relTime);
1721                         }
1722                     }
1723
1724                     String transportState = state.transportState;
1725                     if (transportState != null) {
1726                         if (transportState.equals(STATE_PLAYING)) {
1727                             play();
1728                         } else if (transportState.equals(STATE_STOPPED)) {
1729                             stop();
1730                         } else if (transportState.equals(STATE_PAUSED_PLAYBACK)) {
1731                             pause();
1732                         }
1733                     }
1734                 }
1735             }
1736         }
1737     }
1738
1739     public void saveQueue(String name, String queueID) {
1740         executeAction(SERVICE_AV_TRANSPORT, ACTION_SAVE_QUEUE, Map.of("Title", name, "ObjectID", queueID));
1741     }
1742
1743     public void setVolume(Command command) {
1744         if (command instanceof OnOffType || command instanceof IncreaseDecreaseType || command instanceof DecimalType
1745                 || command instanceof PercentType) {
1746             String newValue = null;
1747             String currentVolume = getVolume();
1748             if (command == IncreaseDecreaseType.INCREASE && currentVolume != null) {
1749                 int i = Integer.valueOf(currentVolume);
1750                 newValue = String.valueOf(Math.min(100, i + 1));
1751             } else if (command == IncreaseDecreaseType.DECREASE && currentVolume != null) {
1752                 int i = Integer.valueOf(currentVolume);
1753                 newValue = String.valueOf(Math.max(0, i - 1));
1754             } else if (command == OnOffType.ON) {
1755                 newValue = "100";
1756             } else if (command == OnOffType.OFF) {
1757                 newValue = "0";
1758             } else if (command instanceof DecimalType) {
1759                 newValue = String.valueOf(((DecimalType) command).intValue());
1760             } else {
1761                 return;
1762             }
1763             executeAction(SERVICE_RENDERING_CONTROL, ACTION_SET_VOLUME,
1764                     Map.of("Channel", "Master", "DesiredVolume", newValue));
1765         }
1766     }
1767
1768     /**
1769      * Set the VOLUME command specific to the current grouping according to the Sonos behaviour.
1770      * AdHoc groups handles the volume specifically for each player.
1771      * Bonded groups delegate the volume to the coordinator which applies the same level to all group members.
1772      */
1773     public void setVolumeForGroup(Command command) {
1774         if (isAdHocGroup() || isStandalonePlayer()) {
1775             setVolume(command);
1776         } else {
1777             try {
1778                 getCoordinatorHandler().setVolume(command);
1779             } catch (IllegalStateException e) {
1780                 logger.debug("Cannot set group volume ({})", e.getMessage());
1781             }
1782         }
1783     }
1784
1785     public void setBass(Command command) {
1786         if (!isOutputLevelFixed()) {
1787             String newValue = getNewNumericValue(command, getBass(), MIN_BASS, MAX_BASS);
1788             if (newValue != null) {
1789                 executeAction(SERVICE_RENDERING_CONTROL, ACTION_SET_BASS,
1790                         Map.of("InstanceID", "0", "DesiredBass", newValue));
1791             }
1792         }
1793     }
1794
1795     public void setTreble(Command command) {
1796         if (!isOutputLevelFixed()) {
1797             String newValue = getNewNumericValue(command, getTreble(), MIN_TREBLE, MAX_TREBLE);
1798             if (newValue != null) {
1799                 executeAction(SERVICE_RENDERING_CONTROL, ACTION_SET_TREBLE,
1800                         Map.of("InstanceID", "0", "DesiredTreble", newValue));
1801             }
1802         }
1803     }
1804
1805     private @Nullable String getNewNumericValue(Command command, @Nullable String currentValue, int minValue,
1806             int maxValue) {
1807         String newValue = null;
1808         if (command instanceof IncreaseDecreaseType || command instanceof DecimalType) {
1809             if (command == IncreaseDecreaseType.INCREASE && currentValue != null) {
1810                 int i = Integer.valueOf(currentValue);
1811                 newValue = String.valueOf(Math.min(maxValue, i + 1));
1812             } else if (command == IncreaseDecreaseType.DECREASE && currentValue != null) {
1813                 int i = Integer.valueOf(currentValue);
1814                 newValue = String.valueOf(Math.max(minValue, i - 1));
1815             } else if (command instanceof DecimalType) {
1816                 newValue = String.valueOf(((DecimalType) command).intValue());
1817             }
1818         }
1819         return newValue;
1820     }
1821
1822     public void setLoudness(Command command) {
1823         if (!isOutputLevelFixed() && (command instanceof OnOffType || command instanceof OpenClosedType
1824                 || command instanceof UpDownType)) {
1825             String value = (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
1826                     || command.equals(OpenClosedType.OPEN)) ? "True" : "False";
1827             executeAction(SERVICE_RENDERING_CONTROL, ACTION_SET_LOUDNESS,
1828                     Map.of("InstanceID", "0", "Channel", "Master", "DesiredLoudness", value));
1829         }
1830     }
1831
1832     /**
1833      * Checks if the player receiving the command is part of a group that
1834      * consists of randomly added players or contains bonded players
1835      *
1836      * @return boolean
1837      */
1838     private boolean isAdHocGroup() {
1839         SonosZoneGroup currentZoneGroup = getCurrentZoneGroup();
1840         if (currentZoneGroup != null) {
1841             List<String> zoneGroupMemberNames = currentZoneGroup.getMemberZoneNames();
1842
1843             for (String zoneName : zoneGroupMemberNames) {
1844                 if (!zoneName.equals(zoneGroupMemberNames.get(0))) {
1845                     // At least one "ZoneName" differs so we have an AdHoc group
1846                     return true;
1847                 }
1848             }
1849         }
1850         return false;
1851     }
1852
1853     /**
1854      * Checks if the player receiving the command is a standalone player
1855      *
1856      * @return boolean
1857      */
1858     private boolean isStandalonePlayer() {
1859         SonosZoneGroup zoneGroup = getCurrentZoneGroup();
1860         return zoneGroup == null || zoneGroup.getMembers().size() == 1;
1861     }
1862
1863     private Collection<SonosZoneGroup> getZoneGroups() {
1864         String zoneGroupState = stateMap.get("ZoneGroupState");
1865         return zoneGroupState == null ? Collections.emptyList() : SonosXMLParser.getZoneGroupFromXML(zoneGroupState);
1866     }
1867
1868     /**
1869      * Returns the current zone group
1870      * (of which the player receiving the command is part)
1871      *
1872      * @return {@link SonosZoneGroup}
1873      */
1874     private @Nullable SonosZoneGroup getCurrentZoneGroup() {
1875         for (SonosZoneGroup zoneGroup : getZoneGroups()) {
1876             if (zoneGroup.getMembers().contains(getUDN())) {
1877                 return zoneGroup;
1878             }
1879         }
1880         logger.debug("Could not fetch Sonos group state information");
1881         return null;
1882     }
1883
1884     /**
1885      * Sets the volume level for a notification sound
1886      *
1887      * @param notificationSoundVolume
1888      */
1889     public void setNotificationSoundVolume(@Nullable PercentType notificationSoundVolume) {
1890         if (notificationSoundVolume != null) {
1891             setVolumeForGroup(notificationSoundVolume);
1892         }
1893     }
1894
1895     /**
1896      * Gets the volume level for a notification sound
1897      */
1898     public @Nullable PercentType getNotificationSoundVolume() {
1899         Integer notificationSoundVolume = getConfigAs(ZonePlayerConfiguration.class).notificationVolume;
1900         if (notificationSoundVolume == null) {
1901             // if no value is set we use the current volume instead
1902             String volume = getVolume();
1903             return volume != null ? new PercentType(volume) : null;
1904         }
1905         return new PercentType(notificationSoundVolume);
1906     }
1907
1908     public void addURIToQueue(String URI, String meta, long desiredFirstTrack, boolean enqueueAsNext) {
1909         Map<String, String> inputs = new HashMap<>();
1910
1911         try {
1912             inputs.put("InstanceID", "0");
1913             inputs.put("EnqueuedURI", URI);
1914             inputs.put("EnqueuedURIMetaData", meta);
1915             inputs.put("DesiredFirstTrackNumberEnqueued", Long.toString(desiredFirstTrack));
1916             inputs.put("EnqueueAsNext", Boolean.toString(enqueueAsNext));
1917         } catch (NumberFormatException ex) {
1918             logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
1919         }
1920
1921         executeAction(SERVICE_AV_TRANSPORT, ACTION_ADD_URI_TO_QUEUE, inputs);
1922     }
1923
1924     public void setCurrentURI(SonosEntry newEntry) {
1925         setCurrentURI(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry));
1926     }
1927
1928     public void setCurrentURI(@Nullable String URI, @Nullable String URIMetaData) {
1929         if (URI != null && URIMetaData != null) {
1930             logger.debug("setCurrentURI URI {} URIMetaData {}", URI, URIMetaData);
1931             executeAction(SERVICE_AV_TRANSPORT, ACTION_SET_AV_TRANSPORT_URI,
1932                     Map.of("InstanceID", "0", "CurrentURI", URI, "CurrentURIMetaData", URIMetaData));
1933         }
1934     }
1935
1936     public void setPosition(@Nullable String relTime) {
1937         seek("REL_TIME", relTime);
1938     }
1939
1940     public void setPositionTrack(long tracknr) {
1941         seek("TRACK_NR", Long.toString(tracknr));
1942     }
1943
1944     public void setPositionTrack(String tracknr) {
1945         seek("TRACK_NR", tracknr);
1946     }
1947
1948     protected void seek(String unit, @Nullable String target) {
1949         if (target != null) {
1950             executeAction(SERVICE_AV_TRANSPORT, ACTION_SEEK, Map.of("InstanceID", "0", "Unit", unit, "Target", target));
1951         }
1952     }
1953
1954     public void play() {
1955         executeAction(SERVICE_AV_TRANSPORT, ACTION_PLAY, Map.of("Speed", "1"));
1956     }
1957
1958     public void stop() {
1959         executeAction(SERVICE_AV_TRANSPORT, ACTION_STOP, null);
1960     }
1961
1962     public void pause() {
1963         executeAction(SERVICE_AV_TRANSPORT, ACTION_PAUSE, null);
1964     }
1965
1966     public void setShuffle(Command command) {
1967         if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
1968             try {
1969                 ZonePlayerHandler coordinator = getCoordinatorHandler();
1970
1971                 if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
1972                         || command.equals(OpenClosedType.OPEN)) {
1973                     switch (coordinator.getRepeatMode()) {
1974                         case "ALL":
1975                             coordinator.updatePlayMode("SHUFFLE");
1976                             break;
1977                         case "ONE":
1978                             coordinator.updatePlayMode("SHUFFLE_REPEAT_ONE");
1979                             break;
1980                         case "OFF":
1981                             coordinator.updatePlayMode("SHUFFLE_NOREPEAT");
1982                             break;
1983                     }
1984                 } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
1985                         || command.equals(OpenClosedType.CLOSED)) {
1986                     switch (coordinator.getRepeatMode()) {
1987                         case "ALL":
1988                             coordinator.updatePlayMode("REPEAT_ALL");
1989                             break;
1990                         case "ONE":
1991                             coordinator.updatePlayMode("REPEAT_ONE");
1992                             break;
1993                         case "OFF":
1994                             coordinator.updatePlayMode("NORMAL");
1995                             break;
1996                     }
1997                 }
1998             } catch (IllegalStateException e) {
1999                 logger.debug("Cannot handle shuffle command ({})", e.getMessage());
2000             }
2001         }
2002     }
2003
2004     public void setRepeat(Command command) {
2005         if (command instanceof StringType) {
2006             try {
2007                 ZonePlayerHandler coordinator = getCoordinatorHandler();
2008
2009                 switch (command.toString()) {
2010                     case "ALL":
2011                         coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE" : "REPEAT_ALL");
2012                         break;
2013                     case "ONE":
2014                         coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_REPEAT_ONE" : "REPEAT_ONE");
2015                         break;
2016                     case "OFF":
2017                         coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_NOREPEAT" : "NORMAL");
2018                         break;
2019                     default:
2020                         logger.debug("{}: unexpected repeat command; accepted values are ALL, ONE and OFF",
2021                                 command.toString());
2022                         break;
2023                 }
2024             } catch (IllegalStateException e) {
2025                 logger.debug("Cannot handle repeat command ({})", e.getMessage());
2026             }
2027         }
2028     }
2029
2030     public void setSubwoofer(Command command) {
2031         setEqualizerBooleanSetting(command, "SubEnable");
2032     }
2033
2034     public void setSubwooferGain(Command command) {
2035         setEqualizerNumericSetting(command, "SubGain", getSubwooferGain(), MIN_SUBWOOFER_GAIN, MAX_SUBWOOFER_GAIN);
2036     }
2037
2038     public void setSurround(Command command) {
2039         setEqualizerBooleanSetting(command, "SurroundEnable");
2040     }
2041
2042     public void setSurroundMusicMode(Command command) {
2043         if (command instanceof StringType) {
2044             setEQ("SurroundMode", command.toString());
2045         }
2046     }
2047
2048     public void setSurroundMusicLevel(Command command) {
2049         setEqualizerNumericSetting(command, "MusicSurroundLevel", getSurroundMusicLevel(), MIN_SURROUND_LEVEL,
2050                 MAX_SURROUND_LEVEL);
2051     }
2052
2053     public void setSurroundTvLevel(Command command) {
2054         setEqualizerNumericSetting(command, "SurroundLevel", getSurroundTvLevel(), MIN_SURROUND_LEVEL,
2055                 MAX_SURROUND_LEVEL);
2056     }
2057
2058     public void setNightMode(Command command) {
2059         setEqualizerBooleanSetting(command, "NightMode");
2060     }
2061
2062     public void setSpeechEnhancement(Command command) {
2063         setEqualizerBooleanSetting(command, "DialogLevel");
2064     }
2065
2066     private void setEqualizerBooleanSetting(Command command, String eqType) {
2067         if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
2068             setEQ(eqType, (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
2069                     || command.equals(OpenClosedType.OPEN)) ? "1" : "0");
2070         }
2071     }
2072
2073     private void setEqualizerNumericSetting(Command command, String eqType, @Nullable String currentValue, int minValue,
2074             int maxValue) {
2075         String newValue = getNewNumericValue(command, currentValue, minValue, maxValue);
2076         if (newValue != null) {
2077             setEQ(eqType, newValue);
2078         }
2079     }
2080
2081     private void setEQ(String eqType, String value) {
2082         try {
2083             executeAction(SERVICE_RENDERING_CONTROL, ACTION_SET_EQ,
2084                     Map.of("InstanceID", "0", "EQType", eqType, "DesiredValue", value));
2085         } catch (IllegalStateException e) {
2086             logger.debug("Cannot handle {} command ({})", eqType, e.getMessage());
2087         }
2088     }
2089
2090     public @Nullable String getNightMode() {
2091         return stateMap.get("NightMode");
2092     }
2093
2094     public @Nullable String getDialogLevel() {
2095         return stateMap.get("DialogLevel");
2096     }
2097
2098     public @Nullable String getPlayMode() {
2099         return stateMap.get("CurrentPlayMode");
2100     }
2101
2102     public Boolean isShuffleActive() {
2103         String playMode = getPlayMode();
2104         return (playMode != null && playMode.startsWith("SHUFFLE"));
2105     }
2106
2107     public String getRepeatMode() {
2108         String mode = "OFF";
2109         String playMode = getPlayMode();
2110         if (playMode != null) {
2111             switch (playMode) {
2112                 case "REPEAT_ALL":
2113                 case "SHUFFLE":
2114                     mode = "ALL";
2115                     break;
2116                 case "REPEAT_ONE":
2117                 case "SHUFFLE_REPEAT_ONE":
2118                     mode = "ONE";
2119                     break;
2120                 case "NORMAL":
2121                 case "SHUFFLE_NOREPEAT":
2122                 default:
2123                     mode = "OFF";
2124                     break;
2125             }
2126         }
2127         return mode;
2128     }
2129
2130     protected void updatePlayMode(String playMode) {
2131         executeAction(SERVICE_AV_TRANSPORT, ACTION_SET_PLAY_MODE, Map.of("InstanceID", "0", "NewPlayMode", playMode));
2132     }
2133
2134     /**
2135      * Clear all scheduled music from the current queue.
2136      *
2137      */
2138     public void removeAllTracksFromQueue() {
2139         executeAction(SERVICE_AV_TRANSPORT, ACTION_REMOVE_ALL_TRACKS_FROM_QUEUE, Map.of("InstanceID", "0"));
2140     }
2141
2142     /**
2143      * Play music from the line-in of the given Player referenced by the given UDN or name
2144      *
2145      * @param udn or name
2146      */
2147     public void playLineIn(Command command) {
2148         if (command instanceof StringType) {
2149             try {
2150                 LineInType lineInType = LineInType.ANY;
2151                 String remotePlayerName = command.toString();
2152                 if (remotePlayerName.toUpperCase().startsWith("ANALOG,")) {
2153                     lineInType = LineInType.ANALOG;
2154                     remotePlayerName = remotePlayerName.substring(7);
2155                 } else if (remotePlayerName.toUpperCase().startsWith("DIGITAL,")) {
2156                     lineInType = LineInType.DIGITAL;
2157                     remotePlayerName = remotePlayerName.substring(8);
2158                 }
2159                 ZonePlayerHandler coordinatorHandler = getCoordinatorHandler();
2160                 ZonePlayerHandler remoteHandler = getHandlerByName(remotePlayerName);
2161
2162                 // check if player has a line-in connected
2163                 if ((lineInType != LineInType.DIGITAL && remoteHandler.isAnalogLineInConnected())
2164                         || (lineInType != LineInType.ANALOG && remoteHandler.isOpticalLineInConnected())) {
2165                     // stop whatever is currently playing
2166                     coordinatorHandler.stop();
2167
2168                     // set the URI
2169                     if (lineInType != LineInType.DIGITAL && remoteHandler.isAnalogLineInConnected()) {
2170                         coordinatorHandler.setCurrentURI(ANALOG_LINE_IN_URI + remoteHandler.getUDN(), "");
2171                     } else {
2172                         coordinatorHandler.setCurrentURI(OPTICAL_LINE_IN_URI + remoteHandler.getUDN() + SPDIF, "");
2173                     }
2174
2175                     // take the system off mute
2176                     coordinatorHandler.setMute(OnOffType.OFF);
2177
2178                     // start jammin'
2179                     coordinatorHandler.play();
2180                 } else {
2181                     logger.debug("Line-in of {} is not connected", remoteHandler.getUDN());
2182                 }
2183             } catch (IllegalStateException e) {
2184                 logger.debug("Cannot play line-in ({})", e.getMessage());
2185             }
2186         }
2187     }
2188
2189     private ZonePlayerHandler getCoordinatorHandler() throws IllegalStateException {
2190         ZonePlayerHandler handler = coordinatorHandler;
2191         if (handler != null) {
2192             return handler;
2193         }
2194         try {
2195             handler = getHandlerByName(getCoordinator());
2196             coordinatorHandler = handler;
2197             return handler;
2198         } catch (IllegalStateException e) {
2199             throw new IllegalStateException("Missing group coordinator " + getCoordinator());
2200         }
2201     }
2202
2203     /**
2204      * Returns a list of all zone group members this particular player is member of
2205      * Or empty list if the players is not assigned to any group
2206      *
2207      * @return a list of Strings containing the UDNs of other group members
2208      */
2209     protected List<String> getZoneGroupMembers() {
2210         List<String> result = new ArrayList<>();
2211
2212         Collection<SonosZoneGroup> zoneGroups = getZoneGroups();
2213         if (!zoneGroups.isEmpty()) {
2214             for (SonosZoneGroup zg : zoneGroups) {
2215                 if (zg.getMembers().contains(getUDN())) {
2216                     result.addAll(zg.getMembers());
2217                     break;
2218                 }
2219             }
2220         } else {
2221             // If the group topology was not yet received, return at least the current Sonos zone
2222             result.add(getUDN());
2223         }
2224         return result;
2225     }
2226
2227     /**
2228      * Returns a list of other zone group members this particular player is member of
2229      * Or empty list if the players is not assigned to any group
2230      *
2231      * @return a list of Strings containing the UDNs of other group members
2232      */
2233     protected List<String> getOtherZoneGroupMembers() {
2234         List<String> zoneGroupMembers = getZoneGroupMembers();
2235         zoneGroupMembers.remove(getUDN());
2236         return zoneGroupMembers;
2237     }
2238
2239     protected ZonePlayerHandler getHandlerByName(String remotePlayerName) throws IllegalStateException {
2240         for (ThingTypeUID supportedThingType : SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS) {
2241             Thing thing = localThingRegistry.get(new ThingUID(supportedThingType, remotePlayerName));
2242             if (thing != null) {
2243                 ThingHandler handler = thing.getHandler();
2244                 if (handler instanceof ZonePlayerHandler) {
2245                     return (ZonePlayerHandler) handler;
2246                 }
2247             }
2248         }
2249         for (Thing aThing : localThingRegistry.getAll()) {
2250             if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())
2251                     && aThing.getConfiguration().get(ZonePlayerConfiguration.UDN).equals(remotePlayerName)) {
2252                 ThingHandler handler = aThing.getHandler();
2253                 if (handler instanceof ZonePlayerHandler) {
2254                     return (ZonePlayerHandler) handler;
2255                 }
2256             }
2257         }
2258         throw new IllegalStateException("Could not find handler for " + remotePlayerName);
2259     }
2260
2261     public void setMute(Command command) {
2262         if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
2263             String value = (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
2264                     || command.equals(OpenClosedType.OPEN)) ? "True" : "False";
2265             executeAction(SERVICE_RENDERING_CONTROL, ACTION_SET_MUTE,
2266                     Map.of("Channel", "Master", "DesiredMute", value));
2267         }
2268     }
2269
2270     public List<SonosAlarm> getCurrentAlarmList() {
2271         Map<String, String> result = executeAction(SERVICE_ALARM_CLOCK, "ListAlarms", null);
2272         String alarmList = result.get("CurrentAlarmList");
2273         return alarmList == null ? Collections.emptyList() : SonosXMLParser.getAlarmsFromStringResult(alarmList);
2274     }
2275
2276     public void updateAlarm(SonosAlarm alarm) {
2277         Map<String, String> inputs = new HashMap<>();
2278
2279         try {
2280             inputs.put("ID", Integer.toString(alarm.getId()));
2281             inputs.put("StartLocalTime", alarm.getStartTime());
2282             inputs.put("Duration", alarm.getDuration());
2283             inputs.put("Recurrence", alarm.getRecurrence());
2284             inputs.put("RoomUUID", alarm.getRoomUUID());
2285             inputs.put("ProgramURI", alarm.getProgramURI());
2286             inputs.put("ProgramMetaData", alarm.getProgramMetaData());
2287             inputs.put("PlayMode", alarm.getPlayMode());
2288             inputs.put("Volume", Integer.toString(alarm.getVolume()));
2289             if (alarm.getIncludeLinkedZones()) {
2290                 inputs.put("IncludeLinkedZones", "1");
2291             } else {
2292                 inputs.put("IncludeLinkedZones", "0");
2293             }
2294
2295             if (alarm.getEnabled()) {
2296                 inputs.put("Enabled", "1");
2297             } else {
2298                 inputs.put("Enabled", "0");
2299             }
2300         } catch (NumberFormatException ex) {
2301             logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
2302         }
2303
2304         executeAction(SERVICE_ALARM_CLOCK, "UpdateAlarm", inputs);
2305     }
2306
2307     public void setAlarm(Command command) {
2308         if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
2309             if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) {
2310                 setAlarm(true);
2311             } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
2312                     || command.equals(OpenClosedType.CLOSED)) {
2313                 setAlarm(false);
2314             }
2315         }
2316     }
2317
2318     public void setAlarm(boolean alarmSwitch) {
2319         List<SonosAlarm> sonosAlarms = getCurrentAlarmList();
2320
2321         // find the nearest alarm - take the current time from the Sonos system,
2322         // not the system where we are running
2323         SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2324         fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
2325
2326         String currentLocalTime = getTime();
2327         Date currentDateTime = null;
2328         try {
2329             currentDateTime = fmt.parse(currentLocalTime);
2330         } catch (ParseException e) {
2331             logger.debug("An exception occurred while formatting a date", e);
2332         }
2333
2334         if (currentDateTime != null) {
2335             Calendar currentDateTimeCalendar = Calendar.getInstance();
2336             currentDateTimeCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
2337             currentDateTimeCalendar.setTime(currentDateTime);
2338             currentDateTimeCalendar.add(Calendar.DAY_OF_YEAR, 10);
2339             long shortestDuration = currentDateTimeCalendar.getTimeInMillis() - currentDateTime.getTime();
2340
2341             SonosAlarm firstAlarm = null;
2342
2343             for (SonosAlarm anAlarm : sonosAlarms) {
2344                 SimpleDateFormat durationFormat = new SimpleDateFormat("HH:mm:ss");
2345                 durationFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
2346                 Date durationDate;
2347                 try {
2348                     durationDate = durationFormat.parse(anAlarm.getDuration());
2349                 } catch (ParseException e) {
2350                     logger.debug("An exception occurred while parsing a date : '{}'", e.getMessage());
2351                     continue;
2352                 }
2353
2354                 long duration = durationDate.getTime();
2355
2356                 if (duration < shortestDuration && anAlarm.getRoomUUID().equals(getUDN())) {
2357                     shortestDuration = duration;
2358                     firstAlarm = anAlarm;
2359                 }
2360             }
2361
2362             // Set the Alarm
2363             if (firstAlarm != null) {
2364                 if (alarmSwitch) {
2365                     firstAlarm.setEnabled(true);
2366                 } else {
2367                     firstAlarm.setEnabled(false);
2368                 }
2369
2370                 updateAlarm(firstAlarm);
2371             }
2372         }
2373     }
2374
2375     public @Nullable String getTime() {
2376         updateTime();
2377         return stateMap.get("CurrentLocalTime");
2378     }
2379
2380     public @Nullable String getAlarmRunning() {
2381         return stateMap.get("AlarmRunning");
2382     }
2383
2384     public boolean isAlarmRunning() {
2385         return "1".equals(getAlarmRunning());
2386     }
2387
2388     public void snoozeAlarm(Command command) {
2389         if (isAlarmRunning() && command instanceof DecimalType) {
2390             int minutes = ((DecimalType) command).intValue();
2391
2392             Map<String, String> inputs = new HashMap<>();
2393
2394             Calendar snoozePeriod = Calendar.getInstance();
2395             snoozePeriod.setTimeZone(TimeZone.getTimeZone("GMT"));
2396             snoozePeriod.setTimeInMillis(0);
2397             snoozePeriod.add(Calendar.MINUTE, minutes);
2398             SimpleDateFormat pFormatter = new SimpleDateFormat("HH:mm:ss");
2399             pFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
2400
2401             try {
2402                 inputs.put("Duration", pFormatter.format(snoozePeriod.getTime()));
2403             } catch (NumberFormatException ex) {
2404                 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
2405             }
2406
2407             executeAction(SERVICE_AV_TRANSPORT, ACTION_SNOOZE_ALARM, inputs);
2408         } else {
2409             logger.debug("There is no alarm running on {}", getUDN());
2410         }
2411     }
2412
2413     public @Nullable String getAnalogLineInConnected() {
2414         return stateMap.get(LINEINCONNECTED);
2415     }
2416
2417     public boolean isAnalogLineInConnected() {
2418         return "true".equals(getAnalogLineInConnected());
2419     }
2420
2421     public @Nullable String getOpticalLineInConnected() {
2422         return stateMap.get(TOSLINEINCONNECTED);
2423     }
2424
2425     public boolean isOpticalLineInConnected() {
2426         return "true".equals(getOpticalLineInConnected());
2427     }
2428
2429     public void becomeStandAlonePlayer() {
2430         executeAction(SERVICE_AV_TRANSPORT, ACTION_BECOME_COORDINATOR_OF_STANDALONE_GROUP, null);
2431     }
2432
2433     public void addMember(Command command) {
2434         if (command instanceof StringType) {
2435             SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", GROUP_URI + getUDN());
2436             try {
2437                 getHandlerByName(command.toString()).setCurrentURI(entry);
2438             } catch (IllegalStateException e) {
2439                 logger.debug("Cannot add group member ({})", e.getMessage());
2440             }
2441         }
2442     }
2443
2444     public boolean publicAddress(LineInType lineInType) {
2445         // check if sourcePlayer has a line-in connected
2446         if ((lineInType != LineInType.DIGITAL && isAnalogLineInConnected())
2447                 || (lineInType != LineInType.ANALOG && isOpticalLineInConnected())) {
2448             // first remove this player from its own group if any
2449             becomeStandAlonePlayer();
2450
2451             // add all other players to this new group
2452             for (SonosZoneGroup group : getZoneGroups()) {
2453                 for (String player : group.getMembers()) {
2454                     try {
2455                         ZonePlayerHandler somePlayer = getHandlerByName(player);
2456                         if (somePlayer != this) {
2457                             somePlayer.becomeStandAlonePlayer();
2458                             somePlayer.stop();
2459                             addMember(StringType.valueOf(somePlayer.getUDN()));
2460                         }
2461                     } catch (IllegalStateException e) {
2462                         logger.debug("Cannot add to group ({})", e.getMessage());
2463                     }
2464                 }
2465             }
2466
2467             try {
2468                 ZonePlayerHandler coordinator = getCoordinatorHandler();
2469                 // set the URI of the group to the line-in
2470                 SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", ANALOG_LINE_IN_URI + getUDN());
2471                 if (lineInType != LineInType.ANALOG && isOpticalLineInConnected()) {
2472                     entry = new SonosEntry("", "", "", "", "", "", "", OPTICAL_LINE_IN_URI + getUDN() + SPDIF);
2473                 }
2474                 coordinator.setCurrentURI(entry);
2475                 coordinator.play();
2476
2477                 return true;
2478             } catch (IllegalStateException e) {
2479                 logger.debug("Cannot handle command ({})", e.getMessage());
2480                 return false;
2481             }
2482         } else {
2483             logger.debug("Line-in of {} is not connected", getUDN());
2484             return false;
2485         }
2486     }
2487
2488     /**
2489      * Play a given url to music in one of the music libraries.
2490      *
2491      * @param url
2492      *            in the format of //host/folder/filename.mp3
2493      */
2494     public void playURI(Command command) {
2495         if (command instanceof StringType) {
2496             try {
2497                 String url = command.toString();
2498
2499                 ZonePlayerHandler coordinator = getCoordinatorHandler();
2500
2501                 // stop whatever is currently playing
2502                 coordinator.stop();
2503                 coordinator.waitForNotTransportState(STATE_PLAYING);
2504
2505                 // clear any tracks which are pending in the queue
2506                 coordinator.removeAllTracksFromQueue();
2507
2508                 // add the new track we want to play to the queue
2509                 // The url will be prefixed with x-file-cifs if it is NOT a http URL
2510                 if (!url.startsWith("x-") && (!url.startsWith("http"))) {
2511                     // default to file based url
2512                     url = FILE_URI + url;
2513                 }
2514                 coordinator.addURIToQueue(url, "", 0, true);
2515
2516                 // set the current playlist to our new queue
2517                 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2518
2519                 // take the system off mute
2520                 coordinator.setMute(OnOffType.OFF);
2521
2522                 // start jammin'
2523                 coordinator.play();
2524             } catch (IllegalStateException e) {
2525                 logger.debug("Cannot play URI ({})", e.getMessage());
2526             }
2527         }
2528     }
2529
2530     private void scheduleNotificationSound(final Command command) {
2531         scheduler.submit(() -> {
2532             synchronized (notificationLock) {
2533                 playNotificationSoundURI(command);
2534             }
2535         });
2536     }
2537
2538     /**
2539      * Play a given notification sound
2540      *
2541      * @param url in the format of //host/folder/filename.mp3
2542      */
2543     public void playNotificationSoundURI(Command notificationURL) {
2544         if (notificationURL instanceof StringType) {
2545             try {
2546                 ZonePlayerHandler coordinator = getCoordinatorHandler();
2547
2548                 String currentURI = coordinator.getCurrentURI();
2549                 logger.debug("playNotificationSoundURI: currentURI {} metadata {}", currentURI,
2550                         coordinator.getCurrentURIMetadataAsString());
2551
2552                 if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)
2553                         || isPlayingRadio(currentURI)) {
2554                     handleRadioStream(currentURI, notificationURL, coordinator);
2555                 } else if (isPlayingLineIn(currentURI)) {
2556                     handleLineIn(currentURI, notificationURL, coordinator);
2557                 } else if (isPlayingQueue(currentURI)) {
2558                     handleSharedQueue(currentURI, notificationURL, coordinator);
2559                 } else if (isPlaylistEmpty(coordinator)) {
2560                     handleEmptyQueue(notificationURL, coordinator);
2561                 }
2562                 synchronized (notificationLock) {
2563                     notificationLock.notify();
2564                 }
2565             } catch (IllegalStateException e) {
2566                 logger.debug("Cannot play sound ({})", e.getMessage());
2567             }
2568         }
2569     }
2570
2571     private boolean isPlaylistEmpty(ZonePlayerHandler coordinator) {
2572         return coordinator.getQueueSize() == 0;
2573     }
2574
2575     private boolean isPlayingQueue(@Nullable String currentURI) {
2576         return currentURI != null && currentURI.contains(QUEUE_URI);
2577     }
2578
2579     private boolean isPlayingStream(@Nullable String currentURI) {
2580         return currentURI != null && currentURI.contains(STREAM_URI);
2581     }
2582
2583     private boolean isPlayingRadio(@Nullable String currentURI) {
2584         return currentURI != null && currentURI.contains(RADIO_URI);
2585     }
2586
2587     private boolean isPlayingRadioStartedByAmazonEcho(@Nullable String currentURI) {
2588         return currentURI != null && currentURI.contains(RADIO_MP3_URI) && currentURI.contains(OPML_TUNE);
2589     }
2590
2591     private boolean isPlayingLineIn(@Nullable String currentURI) {
2592         return currentURI != null && (isPlayingAnalogLineIn(currentURI) || isPlayingOpticalLineIn(currentURI));
2593     }
2594
2595     private boolean isPlayingAnalogLineIn(@Nullable String currentURI) {
2596         return currentURI != null && currentURI.contains(ANALOG_LINE_IN_URI);
2597     }
2598
2599     private boolean isPlayingOpticalLineIn(@Nullable String currentURI) {
2600         return currentURI != null && currentURI.startsWith(OPTICAL_LINE_IN_URI) && currentURI.endsWith(SPDIF);
2601     }
2602
2603     /**
2604      * Does a chain of predefined actions when a Notification sound is played by
2605      * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2606      * radio streaming is currently loaded
2607      *
2608      * @param currentStreamURI - the currently loaded stream's URI
2609      * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2610      * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2611      */
2612     private void handleRadioStream(@Nullable String currentStreamURI, Command notificationURL,
2613             ZonePlayerHandler coordinator) {
2614         String nextAction = coordinator.getTransportState();
2615         SonosMetaData track = coordinator.getTrackMetadata();
2616         SonosMetaData currentUriMetaData = coordinator.getCurrentURIMetadata();
2617
2618         handleNotificationSound(notificationURL, coordinator);
2619         if (currentStreamURI != null && track != null && currentUriMetaData != null) {
2620             coordinator.setCurrentURI(new SonosEntry("", currentUriMetaData.getTitle(), "", "", track.getAlbumArtUri(),
2621                     "", currentUriMetaData.getUpnpClass(), currentStreamURI));
2622             restoreLastTransportState(coordinator, nextAction);
2623         }
2624     }
2625
2626     /**
2627      * Does a chain of predefined actions when a Notification sound is played by
2628      * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2629      * line in is currently loaded
2630      *
2631      * @param currentLineInURI - the currently loaded line-in URI
2632      * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2633      * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2634      */
2635     private void handleLineIn(@Nullable String currentLineInURI, Command notificationURL,
2636             ZonePlayerHandler coordinator) {
2637         logger.debug("Handling notification while sound from line-in was being played");
2638         String nextAction = coordinator.getTransportState();
2639
2640         handleNotificationSound(notificationURL, coordinator);
2641         if (currentLineInURI != null) {
2642             logger.debug("Restoring sound from line-in using {}", currentLineInURI);
2643             coordinator.setCurrentURI(currentLineInURI, "");
2644             restoreLastTransportState(coordinator, nextAction);
2645         }
2646     }
2647
2648     /**
2649      * Does a chain of predefined actions when a Notification sound is played by
2650      * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2651      * shared queue is currently loaded
2652      *
2653      * @param currentQueueURI - the currently loaded queue URI
2654      * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2655      * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2656      */
2657     private void handleSharedQueue(@Nullable String currentQueueURI, Command notificationURL,
2658             ZonePlayerHandler coordinator) {
2659         String nextAction = coordinator.getTransportState();
2660         String trackPosition = coordinator.getRefreshedPosition();
2661         long currentTrackNumber = coordinator.getRefreshedCurrenTrackNr();
2662         logger.debug("handleSharedQueue: currentQueueURI {} trackPosition {} currentTrackNumber {}", currentQueueURI,
2663                 trackPosition, currentTrackNumber);
2664
2665         handleNotificationSound(notificationURL, coordinator);
2666         String queueUri = QUEUE_URI + coordinator.getUDN() + "#0";
2667         if (queueUri.equals(currentQueueURI)) {
2668             coordinator.setPositionTrack(currentTrackNumber);
2669             coordinator.setPosition(trackPosition);
2670             restoreLastTransportState(coordinator, nextAction);
2671         }
2672     }
2673
2674     /**
2675      * Handle the execution of the notification sound by sequentially executing the required steps.
2676      *
2677      * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2678      * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2679      */
2680     private void handleNotificationSound(Command notificationURL, ZonePlayerHandler coordinator) {
2681         boolean sourceStoppable = !isPlayingOpticalLineIn(coordinator.getCurrentURI());
2682         String originalVolume = (isAdHocGroup() || isStandalonePlayer()) ? getVolume() : coordinator.getVolume();
2683         if (sourceStoppable) {
2684             coordinator.stop();
2685             coordinator.waitForNotTransportState(STATE_PLAYING);
2686             applyNotificationSoundVolume();
2687         }
2688         long notificationPosition = coordinator.getQueueSize() + 1;
2689         coordinator.addURIToQueue(notificationURL.toString(), "", notificationPosition, false);
2690         coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2691         coordinator.setPositionTrack(notificationPosition);
2692         if (!sourceStoppable) {
2693             coordinator.stop();
2694             coordinator.waitForNotTransportState(STATE_PLAYING);
2695             applyNotificationSoundVolume();
2696         }
2697         coordinator.play();
2698         coordinator.waitForFinishedNotification();
2699         if (originalVolume != null) {
2700             setVolumeForGroup(DecimalType.valueOf(originalVolume));
2701         }
2702         coordinator.removeRangeOfTracksFromQueue(new StringType(Long.toString(notificationPosition) + ",1"));
2703     }
2704
2705     private void restoreLastTransportState(ZonePlayerHandler coordinator, @Nullable String nextAction) {
2706         if (nextAction != null) {
2707             switch (nextAction) {
2708                 case STATE_PLAYING:
2709                     coordinator.play();
2710                     coordinator.waitForTransportState(STATE_PLAYING);
2711                     break;
2712                 case STATE_PAUSED_PLAYBACK:
2713                     coordinator.pause();
2714                     break;
2715             }
2716         }
2717     }
2718
2719     /**
2720      * Does a chain of predefined actions when a Notification sound is played by
2721      * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2722      * empty queue is currently loaded
2723      *
2724      * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2725      * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2726      */
2727     private void handleEmptyQueue(Command notificationURL, ZonePlayerHandler coordinator) {
2728         String originalVolume = coordinator.getVolume();
2729         coordinator.applyNotificationSoundVolume();
2730         coordinator.playURI(notificationURL);
2731         coordinator.waitForFinishedNotification();
2732         coordinator.removeAllTracksFromQueue();
2733         if (originalVolume != null) {
2734             coordinator.setVolume(DecimalType.valueOf(originalVolume));
2735         }
2736     }
2737
2738     /**
2739      * Applies the notification sound volume level to the group (if not null)
2740      *
2741      * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2742      */
2743     private void applyNotificationSoundVolume() {
2744         setNotificationSoundVolume(getNotificationSoundVolume());
2745     }
2746
2747     private void waitForFinishedNotification() {
2748         waitForTransportState(STATE_PLAYING);
2749
2750         // check Sonos state events to determine the end of the notification sound
2751         String notificationTitle = getCurrentTitle();
2752         long playstart = System.currentTimeMillis();
2753         while (System.currentTimeMillis() - playstart < (long) configuration.notificationTimeout * 1000) {
2754             try {
2755                 Thread.sleep(50);
2756                 String currentTitle = getCurrentTitle();
2757                 if ((notificationTitle == null && currentTitle != null)
2758                         || (notificationTitle != null && !notificationTitle.equals(currentTitle))
2759                         || !STATE_PLAYING.equals(getTransportState())) {
2760                     break;
2761                 }
2762             } catch (InterruptedException e) {
2763                 logger.debug("InterruptedException during playing a notification sound");
2764             }
2765         }
2766     }
2767
2768     private void waitForTransportState(String state) {
2769         if (getTransportState() != null) {
2770             long start = System.currentTimeMillis();
2771             while (!state.equals(getTransportState())) {
2772                 try {
2773                     Thread.sleep(50);
2774                     if (System.currentTimeMillis() - start > (long) configuration.notificationTimeout * 1000) {
2775                         break;
2776                     }
2777                 } catch (InterruptedException e) {
2778                     logger.debug("InterruptedException during playing a notification sound");
2779                 }
2780             }
2781         }
2782     }
2783
2784     private void waitForNotTransportState(String state) {
2785         if (getTransportState() != null) {
2786             long start = System.currentTimeMillis();
2787             while (state.equals(getTransportState())) {
2788                 try {
2789                     Thread.sleep(50);
2790                     if (System.currentTimeMillis() - start > (long) configuration.notificationTimeout * 1000) {
2791                         break;
2792                     }
2793                 } catch (InterruptedException e) {
2794                     logger.debug("InterruptedException during playing a notification sound");
2795                 }
2796             }
2797         }
2798     }
2799
2800     /**
2801      * Removes a range of tracks from the queue.
2802      * (<x,y> will remove y songs started by the song number x)
2803      *
2804      * @param command - must be in the format <startIndex, numberOfSongs>
2805      */
2806     public void removeRangeOfTracksFromQueue(Command command) {
2807         if (command instanceof StringType) {
2808             String[] rangeInputSplit = command.toString().split(",");
2809             // If range input is incorrect, remove the first song by default
2810             String startIndex = rangeInputSplit[0] != null ? rangeInputSplit[0] : "1";
2811             String numberOfTracks = rangeInputSplit[1] != null ? rangeInputSplit[1] : "1";
2812             executeAction(SERVICE_AV_TRANSPORT, ACTION_REMOVE_TRACK_RANGE_FROM_QUEUE,
2813                     Map.of("InstanceID", "0", "StartingIndex", startIndex, "NumberOfTracks", numberOfTracks));
2814         }
2815     }
2816
2817     public void clearQueue() {
2818         try {
2819             ZonePlayerHandler coordinator = getCoordinatorHandler();
2820
2821             coordinator.removeAllTracksFromQueue();
2822         } catch (IllegalStateException e) {
2823             logger.debug("Cannot clear queue ({})", e.getMessage());
2824         }
2825     }
2826
2827     public void playQueue() {
2828         try {
2829             ZonePlayerHandler coordinator = getCoordinatorHandler();
2830
2831             // set the current playlist to our new queue
2832             coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2833
2834             // take the system off mute
2835             coordinator.setMute(OnOffType.OFF);
2836
2837             // start jammin'
2838             coordinator.play();
2839         } catch (IllegalStateException e) {
2840             logger.debug("Cannot play queue ({})", e.getMessage());
2841         }
2842     }
2843
2844     public void setLed(Command command) {
2845         if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
2846             String value = (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
2847                     || command.equals(OpenClosedType.OPEN)) ? "On" : "Off";
2848             executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_SET_LED_STATE, Map.of("DesiredLEDState", value));
2849             executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_GET_LED_STATE, null);
2850         }
2851     }
2852
2853     public void removeMember(Command command) {
2854         if (command instanceof StringType) {
2855             try {
2856                 ZonePlayerHandler oldmemberHandler = getHandlerByName(command.toString());
2857
2858                 oldmemberHandler.becomeStandAlonePlayer();
2859                 SonosEntry entry = new SonosEntry("", "", "", "", "", "", "",
2860                         QUEUE_URI + oldmemberHandler.getUDN() + "#0");
2861                 oldmemberHandler.setCurrentURI(entry);
2862             } catch (IllegalStateException e) {
2863                 logger.debug("Cannot remove group member ({})", e.getMessage());
2864             }
2865         }
2866     }
2867
2868     public void previous() {
2869         executeAction(SERVICE_AV_TRANSPORT, ACTION_PREVIOUS, null);
2870     }
2871
2872     public void next() {
2873         executeAction(SERVICE_AV_TRANSPORT, ACTION_NEXT, null);
2874     }
2875
2876     public void stopPlaying(Command command) {
2877         if (command instanceof OnOffType) {
2878             try {
2879                 getCoordinatorHandler().stop();
2880             } catch (IllegalStateException e) {
2881                 logger.debug("Cannot handle stop command ({})", e.getMessage(), e);
2882             }
2883         }
2884     }
2885
2886     public void playRadio(Command command) {
2887         if (command instanceof StringType) {
2888             String station = command.toString();
2889             List<SonosEntry> stations = getFavoriteRadios();
2890
2891             SonosEntry theEntry = null;
2892             // search for the appropriate radio based on its name (title)
2893             for (SonosEntry someStation : stations) {
2894                 if (someStation.getTitle().equals(station)) {
2895                     theEntry = someStation;
2896                     break;
2897                 }
2898             }
2899
2900             // set the URI of the group coordinator
2901             if (theEntry != null) {
2902                 try {
2903                     ZonePlayerHandler coordinator = getCoordinatorHandler();
2904                     coordinator.setCurrentURI(theEntry);
2905                     coordinator.play();
2906                 } catch (IllegalStateException e) {
2907                     logger.debug("Cannot play radio ({})", e.getMessage());
2908                 }
2909             } else {
2910                 logger.debug("Radio station '{}' not found", station);
2911             }
2912         }
2913     }
2914
2915     public void playTuneinStation(Command command) {
2916         if (command instanceof StringType) {
2917             String stationId = command.toString();
2918             List<SonosMusicService> allServices = getAvailableMusicServices();
2919
2920             SonosMusicService tuneinService = null;
2921             // search for the TuneIn music service based on its name
2922             if (allServices != null) {
2923                 for (SonosMusicService service : allServices) {
2924                     if (service.getName().equals("TuneIn")) {
2925                         tuneinService = service;
2926                         break;
2927                     }
2928                 }
2929             }
2930
2931             // set the URI of the group coordinator
2932             if (tuneinService != null) {
2933                 try {
2934                     ZonePlayerHandler coordinator = getCoordinatorHandler();
2935                     SonosEntry entry = new SonosEntry("", "TuneIn station", "", "", "", "",
2936                             "object.item.audioItem.audioBroadcast",
2937                             String.format(TUNEIN_URI, stationId, tuneinService.getId()));
2938                     Integer tuneinServiceType = tuneinService.getType();
2939                     int serviceTypeNum = tuneinServiceType == null ? TUNEIN_DEFAULT_SERVICE_TYPE : tuneinServiceType;
2940                     entry.setDesc("SA_RINCON" + Integer.toString(serviceTypeNum) + "_");
2941                     coordinator.setCurrentURI(entry);
2942                     coordinator.play();
2943                 } catch (IllegalStateException e) {
2944                     logger.debug("Cannot play TuneIn station {} ({})", stationId, e.getMessage());
2945                 }
2946             } else {
2947                 logger.debug("TuneIn service not found");
2948             }
2949         }
2950     }
2951
2952     private @Nullable List<SonosMusicService> getAvailableMusicServices() {
2953         if (musicServices == null) {
2954             Map<String, String> result = service.invokeAction(this, "MusicServices", "ListAvailableServices", null);
2955
2956             String serviceList = result.get("AvailableServiceDescriptorList");
2957             if (serviceList != null) {
2958                 List<SonosMusicService> services = SonosXMLParser.getMusicServicesFromXML(serviceList);
2959                 musicServices = services;
2960
2961                 String[] servicesTypes = new String[0];
2962                 String serviceTypeList = result.get("AvailableServiceTypeList");
2963                 if (serviceTypeList != null) {
2964                     // It is a comma separated list of service types (integers) in the same order as the services
2965                     // declaration in "AvailableServiceDescriptorList" except that there is no service type for the
2966                     // TuneIn service
2967                     servicesTypes = serviceTypeList.split(",");
2968                 }
2969
2970                 int idx = 0;
2971                 for (SonosMusicService service : services) {
2972                     if (!service.getName().equals("TuneIn")) {
2973                         // Add the service type integer value from "AvailableServiceTypeList" to each service
2974                         // except TuneIn
2975                         if (idx < servicesTypes.length) {
2976                             try {
2977                                 Integer serviceType = Integer.parseInt(servicesTypes[idx]);
2978                                 service.setType(serviceType);
2979                             } catch (NumberFormatException e) {
2980                             }
2981                             idx++;
2982                         }
2983                     } else {
2984                         service.setType(TUNEIN_DEFAULT_SERVICE_TYPE);
2985                     }
2986                     logger.debug("Service name {} => id {} type {}", service.getName(), service.getId(),
2987                             service.getType());
2988                 }
2989             }
2990         }
2991         return musicServices;
2992     }
2993
2994     /**
2995      * This will attempt to match the station string with a entry in the
2996      * favorites list, this supports both single entries and playlists
2997      *
2998      * @param favorite to match
2999      * @return true if a match was found and played.
3000      */
3001     public void playFavorite(Command command) {
3002         if (command instanceof StringType) {
3003             String favorite = command.toString();
3004             List<SonosEntry> favorites = getFavorites();
3005
3006             SonosEntry theEntry = null;
3007             // search for the appropriate favorite based on its name (title)
3008             for (SonosEntry entry : favorites) {
3009                 if (entry.getTitle().equals(favorite)) {
3010                     theEntry = entry;
3011                     break;
3012                 }
3013             }
3014
3015             // set the URI of the group coordinator
3016             if (theEntry != null) {
3017                 try {
3018                     ZonePlayerHandler coordinator = getCoordinatorHandler();
3019
3020                     /**
3021                      * If this is a playlist we need to treat it as such
3022                      */
3023                     SonosResourceMetaData resourceMetaData = theEntry.getResourceMetaData();
3024                     if (resourceMetaData != null && resourceMetaData.getUpnpClass().startsWith("object.container")) {
3025                         coordinator.removeAllTracksFromQueue();
3026                         coordinator.addURIToQueue(theEntry);
3027                         coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
3028                         String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued");
3029                         coordinator.seek("TRACK_NR", firstTrackNumberEnqueued);
3030                     } else {
3031                         coordinator.setCurrentURI(theEntry);
3032                     }
3033                     coordinator.play();
3034                 } catch (IllegalStateException e) {
3035                     logger.debug("Cannot paly favorite ({})", e.getMessage());
3036                 }
3037             } else {
3038                 logger.debug("Favorite '{}' not found", favorite);
3039             }
3040         }
3041     }
3042
3043     public void playTrack(Command command) {
3044         if (command instanceof DecimalType) {
3045             try {
3046                 ZonePlayerHandler coordinator = getCoordinatorHandler();
3047
3048                 String trackNumber = String.valueOf(((DecimalType) command).intValue());
3049
3050                 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
3051
3052                 // seek the track - warning, we do not check if the tracknumber falls in the boundary of the queue
3053                 coordinator.setPositionTrack(trackNumber);
3054
3055                 // take the system off mute
3056                 coordinator.setMute(OnOffType.OFF);
3057
3058                 // start jammin'
3059                 coordinator.play();
3060             } catch (IllegalStateException e) {
3061                 logger.debug("Cannot play track ({})", e.getMessage());
3062             }
3063         }
3064     }
3065
3066     public void playPlayList(Command command) {
3067         if (command instanceof StringType) {
3068             String playlist = command.toString();
3069             List<SonosEntry> playlists = getPlayLists();
3070
3071             SonosEntry theEntry = null;
3072             // search for the appropriate play list based on its name (title)
3073             for (SonosEntry somePlaylist : playlists) {
3074                 if (somePlaylist.getTitle().equals(playlist)) {
3075                     theEntry = somePlaylist;
3076                     break;
3077                 }
3078             }
3079
3080             // set the URI of the group coordinator
3081             if (theEntry != null) {
3082                 try {
3083                     ZonePlayerHandler coordinator = getCoordinatorHandler();
3084
3085                     coordinator.addURIToQueue(theEntry);
3086
3087                     coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
3088
3089                     String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued");
3090                     coordinator.seek("TRACK_NR", firstTrackNumberEnqueued);
3091
3092                     coordinator.play();
3093                 } catch (IllegalStateException e) {
3094                     logger.debug("Cannot play playlist ({})", e.getMessage());
3095                 }
3096             } else {
3097                 logger.debug("Playlist '{}' not found", playlist);
3098             }
3099         }
3100     }
3101
3102     public void addURIToQueue(SonosEntry newEntry) {
3103         addURIToQueue(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry), 1, true);
3104     }
3105
3106     public @Nullable String getZoneName() {
3107         return stateMap.get("ZoneName");
3108     }
3109
3110     public @Nullable String getZoneGroupID() {
3111         return stateMap.get("LocalGroupUUID");
3112     }
3113
3114     public @Nullable String getRunningAlarmProperties() {
3115         return stateMap.get("RunningAlarmProperties");
3116     }
3117
3118     public @Nullable String getRefreshedRunningAlarmProperties() {
3119         updateRunningAlarmProperties();
3120         return getRunningAlarmProperties();
3121     }
3122
3123     public @Nullable String getMute() {
3124         return stateMap.get("MuteMaster");
3125     }
3126
3127     public @Nullable String getLed() {
3128         return stateMap.get("CurrentLEDState");
3129     }
3130
3131     public @Nullable String getCurrentZoneName() {
3132         return stateMap.get("CurrentZoneName");
3133     }
3134
3135     public @Nullable String getRefreshedCurrentZoneName() {
3136         updateCurrentZoneName();
3137         return getCurrentZoneName();
3138     }
3139
3140     @Override
3141     public void onStatusChanged(boolean status) {
3142         if (status) {
3143             logger.info("UPnP device {} is present (thing {})", getUDN(), getThing().getUID());
3144             if (getThing().getStatus() != ThingStatus.ONLINE) {
3145                 updateStatus(ThingStatus.ONLINE);
3146                 scheduler.execute(this::poll);
3147             }
3148         } else {
3149             logger.info("UPnP device {} is absent (thing {})", getUDN(), getThing().getUID());
3150             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR);
3151         }
3152     }
3153
3154     private @Nullable String getModelNameFromDescriptor() {
3155         URL descriptor = service.getDescriptorURL(this);
3156         if (descriptor != null) {
3157             String sonosModelDescription = SonosXMLParser.parseModelDescription(descriptor);
3158             return sonosModelDescription == null ? null : SonosXMLParser.extractModelName(sonosModelDescription);
3159         } else {
3160             return null;
3161         }
3162     }
3163
3164     private boolean migrateThingType() {
3165         if (getThing().getThingTypeUID().equals(ZONEPLAYER_THING_TYPE_UID)) {
3166             String modelName = getModelNameFromDescriptor();
3167             if (modelName != null && isSupportedModel(modelName)) {
3168                 updateSonosThingType(modelName);
3169                 return true;
3170             }
3171         }
3172         return false;
3173     }
3174
3175     private boolean isSupportedModel(String modelName) {
3176         for (ThingTypeUID thingTypeUID : SUPPORTED_KNOWN_THING_TYPES_UIDS) {
3177             if (thingTypeUID.getId().equalsIgnoreCase(modelName)) {
3178                 return true;
3179             }
3180         }
3181         return false;
3182     }
3183
3184     private void updateSonosThingType(String newThingTypeID) {
3185         changeThingType(new ThingTypeUID(SonosBindingConstants.BINDING_ID, newThingTypeID), getConfig());
3186     }
3187
3188     /*
3189      * Set the sleeptimer duration
3190      * Use String command of format "HH:MM:SS" to set the timer to the desired duration
3191      * Use empty String "" to switch the sleep timer off
3192      */
3193     public void setSleepTimer(Command command) {
3194         if (command instanceof DecimalType) {
3195             this.service.invokeAction(this, SERVICE_AV_TRANSPORT, ACTION_CONFIGURE_SLEEP_TIMER, Map.of("InstanceID",
3196                     "0", "NewSleepTimerDuration", sleepSecondsToTimeStr(((DecimalType) command).longValue())));
3197         }
3198     }
3199
3200     protected void updateSleepTimerDuration() {
3201         executeAction(SERVICE_AV_TRANSPORT, ACTION_GET_REMAINING_SLEEP_TIMER_DURATION, null);
3202     }
3203
3204     private String sleepSecondsToTimeStr(long sleepSeconds) {
3205         if (sleepSeconds == 0) {
3206             return "";
3207         } else if (sleepSeconds < 68400) {
3208             long remainingSeconds = sleepSeconds;
3209             long hours = TimeUnit.SECONDS.toHours(remainingSeconds);
3210             remainingSeconds -= TimeUnit.HOURS.toSeconds(hours);
3211             long minutes = TimeUnit.SECONDS.toMinutes(remainingSeconds);
3212             remainingSeconds -= TimeUnit.MINUTES.toSeconds(minutes);
3213             long seconds = TimeUnit.SECONDS.toSeconds(remainingSeconds);
3214             return String.format("%02d:%02d:%02d", hours, minutes, seconds);
3215         } else {
3216             logger.debug("Sonos SleepTimer: Invalid sleep time set. sleep time must be >=0 and < 68400s (24h)");
3217             return "ERR";
3218         }
3219     }
3220
3221     private long sleepStrTimeToSeconds(String sleepTime) {
3222         String[] units = sleepTime.split(":");
3223         int hours = Integer.parseInt(units[0]);
3224         int minutes = Integer.parseInt(units[1]);
3225         int seconds = Integer.parseInt(units[2]);
3226         return 3600 * hours + 60 * minutes + seconds;
3227     }
3228 }