2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.sonos.internal.handler;
15 import static org.openhab.binding.sonos.internal.SonosBindingConstants.*;
17 import java.io.IOException;
18 import java.net.MalformedURLException;
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;
31 import java.util.TimeZone;
32 import java.util.concurrent.ScheduledFuture;
33 import java.util.concurrent.TimeUnit;
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;
79 * The {@link ZonePlayerHandler} is responsible for handling commands, which are
80 * sent to one of the channels.
82 * @author Karel Goderis - Initial contribution
85 public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOParticipant {
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";
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";
103 private static final String LINEINCONNECTED = "LineInConnected";
104 private static final String TOSLINEINCONNECTED = "TOSLinkConnected";
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";
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;
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";
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";
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";
152 private static final int SOCKET_TIMEOUT = 5000;
154 private static final int TUNEIN_DEFAULT_SERVICE_TYPE = 65031;
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;
165 private final Logger logger = LoggerFactory.getLogger(ZonePlayerHandler.class);
167 private final ThingRegistry localThingRegistry;
168 private final UpnpIOService service;
169 private final @Nullable String opmlUrl;
170 private final SonosStateDescriptionOptionProvider stateDescriptionProvider;
172 private ZonePlayerConfiguration configuration = new ZonePlayerConfiguration();
175 * Intrinsic lock used to synchronize the execution of notification sounds
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();
182 private final Map<String, String> stateMap = Collections.synchronizedMap(new HashMap<>());
184 private @Nullable ScheduledFuture<?> pollingJob;
185 private @Nullable SonosZonePlayerState savedState;
187 private Map<String, Boolean> subscriptionState = new HashMap<>();
190 * Thing handler instance of the coordinator speaker used for control delegation
192 private @Nullable ZonePlayerHandler coordinatorHandler;
194 private @Nullable List<SonosMusicService> musicServices;
196 private enum LineInType {
202 public ZonePlayerHandler(ThingRegistry thingRegistry, Thing thing, UpnpIOService upnpIOService,
203 @Nullable String opmlUrl, SonosStateDescriptionOptionProvider stateDescriptionProvider) {
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;
213 public void dispose() {
214 logger.debug("Handler disposed for thing {}", getThing().getUID());
216 ScheduledFuture<?> job = this.pollingJob;
220 this.pollingJob = null;
222 removeSubscription();
223 service.unregisterParticipant(this);
227 public void initialize() {
228 logger.debug("initializing handler for thing {}", getThing().getUID());
230 if (migrateThingType()) {
231 // we change the type, so we might need a different handler -> let's finish
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);
241 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
242 "@text/offline.conf-error-missing-udn");
243 logger.debug("Cannot initalize the zoneplayer. UDN not set.");
247 private void poll() {
248 synchronized (jobLock) {
249 if (pollingJob == null) {
253 logger.debug("Polling job");
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<>();
267 // Check if the Sonos zone can be joined
268 // If not, set the thing state to OFFLINE and do nothing else
270 if (getThing().getStatus() != ThingStatus.ONLINE) {
276 if (isLinked(ZONENAME)) {
277 updateCurrentZoneName();
282 // Action GetRemainingSleepTimerDuration is failing for a group slave member (error code 500)
283 if (isLinked(SLEEPTIMER) && isCoordinator()) {
284 updateSleepTimerDuration();
286 } catch (Exception e) {
287 logger.debug("Exception during poll: {}", e.getMessage(), e);
293 public void handleCommand(ChannelUID channelUID, Command command) {
294 if (command == RefreshType.REFRESH) {
295 updateChannel(channelUID.getId());
297 switch (channelUID.getId()) {
304 case NOTIFICATIONSOUND:
305 scheduleNotificationSound(command);
308 stopPlaying(command);
311 setVolumeForGroup(command);
320 setLoudness(command);
323 setSubwoofer(command);
326 setSubwooferGain(command);
329 setSurround(command);
331 case SURROUNDMUSICMODE:
332 setSurroundMusicMode(command);
334 case SURROUNDMUSICLEVEL:
335 setSurroundMusicLevel(command);
337 case SURROUNDTVLEVEL:
338 setSurroundTvLevel(command);
344 removeMember(command);
347 becomeStandAlonePlayer();
350 publicAddress(LineInType.ANY);
352 case PUBLICANALOGADDRESS:
353 publicAddress(LineInType.ANALOG);
355 case PUBLICDIGITALADDRESS:
356 publicAddress(LineInType.DIGITAL);
361 case TUNEINSTATIONID:
362 playTuneinStation(command);
365 playFavorite(command);
371 snoozeAlarm(command);
374 saveAllPlayerState();
377 restoreAllPlayerState();
386 playPlayList(command);
405 if (command instanceof PlayPauseType) {
406 if (command == PlayPauseType.PLAY) {
407 getCoordinatorHandler().play();
408 } else if (command == PlayPauseType.PAUSE) {
409 getCoordinatorHandler().pause();
412 if (command instanceof NextPreviousType) {
413 if (command == NextPreviousType.NEXT) {
414 getCoordinatorHandler().next();
415 } else if (command == NextPreviousType.PREVIOUS) {
416 getCoordinatorHandler().previous();
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());
425 setSleepTimer(command);
434 setNightMode(command);
436 case SPEECHENHANCEMENT:
437 setSpeechEnhancement(command);
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();
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) {
468 public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
469 if (variable == null || value == null || service == null) {
473 if (getThing().getStatus() == ThingStatus.ONLINE) {
474 logger.trace("Received pair '{}':'{}' (service '{}') for thing '{}'",
475 new Object[] { variable, value, service, this.getThing().getUID() });
477 String oldValue = this.stateMap.get(variable);
478 if (shouldIgnoreVariableUpdate(variable, value, oldValue)) {
482 this.stateMap.put(variable, value);
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);
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);
501 updateMediaInformation();
502 if (parsedValues.get("TransportState") != null) {
503 onValueReceived("TransportState", parsedValues.get("TransportState"), service);
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);
514 List<StateOption> options = new ArrayList<>();
516 // update the appropriate channel
518 case "TransportState":
519 updateChannel(STATE);
520 updateChannel(CONTROL);
522 dispatchOnAllGroupMembers(variable, value, service);
524 case "CurrentPlayMode":
525 updateChannel(SHUFFLE);
526 updateChannel(REPEAT);
527 dispatchOnAllGroupMembers(variable, value, service);
529 case "CurrentLEDState":
533 updateState(ZONENAME, new StringType(value));
535 case "CurrentZoneName":
536 updateChannel(ZONENAME);
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);
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);
554 case "LocalGroupUUID":
555 updateChannel(ZONEGROUPID);
557 case "GroupCoordinatorIsLocal":
558 updateChannel(LOCALCOORDINATOR);
561 updateChannel(VOLUME);
570 updateChannel(TREBLE);
572 case "LoudnessMaster":
573 updateChannel(LOUDNESS);
577 updateChannel(TREBLE);
578 updateChannel(LOUDNESS);
581 updateChannel(SUBWOOFER);
584 updateChannel(SUBWOOFERGAIN);
586 case "SurroundEnabled":
587 updateChannel(SURROUND);
590 updateChannel(SURROUNDMUSICMODE);
592 case "SurroundLevel":
593 updateChannel(SURROUNDTVLEVEL);
595 case "MusicSurroundLevel":
596 updateChannel(SURROUNDMUSICLEVEL);
599 updateChannel(NIGHTMODE);
602 updateChannel(SPEECHENHANCEMENT);
604 case LINEINCONNECTED:
605 if (SonosBindingConstants.WITH_LINEIN_THING_TYPES_UIDS.contains(getThing().getThingTypeUID())) {
606 updateChannel(LINEIN);
608 if (SonosBindingConstants.WITH_ANALOG_LINEIN_THING_TYPES_UIDS
609 .contains(getThing().getThingTypeUID())) {
610 updateChannel(ANALOGLINEIN);
613 case TOSLINEINCONNECTED:
614 if (SonosBindingConstants.WITH_LINEIN_THING_TYPES_UIDS.contains(getThing().getThingTypeUID())) {
615 updateChannel(LINEIN);
617 if (SonosBindingConstants.WITH_DIGITAL_LINEIN_THING_TYPES_UIDS
618 .contains(getThing().getThingTypeUID())) {
619 updateChannel(DIGITALLINEIN);
623 updateChannel(ALARMRUNNING);
624 updateRunningAlarmProperties();
626 case "RunningAlarmProperties":
627 updateChannel(ALARMPROPERTIES);
629 case "CurrentURIFormatted":
630 updateChannel(CURRENTTRACK);
633 updateChannel(CURRENTTITLE);
635 case "CurrentArtist":
636 updateChannel(CURRENTARTIST);
639 updateChannel(CURRENTALBUM);
642 updateChannel(CURRENTTRANSPORTURI);
644 case "CurrentTrackURI":
645 updateChannel(CURRENTTRACKURI);
647 case "CurrentAlbumArtURI":
648 updateChannel(CURRENTALBUMARTURL);
650 case "CurrentSleepTimerGeneration":
651 if (value.equals("0")) {
652 updateState(SLEEPTIMER, new DecimalType(0));
655 case "SleepTimerGeneration":
656 if (value.equals("0")) {
657 updateState(SLEEPTIMER, new DecimalType(0));
659 updateSleepTimerDuration();
662 case "RemainingSleepTimerDuration":
663 updateState(SLEEPTIMER, new DecimalType(sleepStrTimeToSeconds(value)));
665 case "CurrentTuneInStationId":
666 updateChannel(TUNEINSTATIONID);
668 case "SavedQueuesUpdateID": // service ContentDirectoy
669 for (SonosEntry entry : getPlayLists()) {
670 options.add(new StateOption(entry.getTitle(), entry.getTitle()));
672 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), PLAYLIST), options);
674 case "FavoritesUpdateID": // service ContentDirectoy
675 for (SonosEntry entry : getFavorites()) {
676 options.add(new StateOption(entry.getTitle(), entry.getTitle()));
678 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), FAVORITE), options);
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()));
689 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), RADIO), options);
698 private void dispatchOnAllGroupMembers(String variable, String value, String service) {
699 if (isCoordinator()) {
700 for (String member : getOtherZoneGroupMembers()) {
702 ZonePlayerHandler memberHandler = getHandlerByName(member);
703 if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) {
704 memberHandler.onValueReceived(variable, value, service);
706 } catch (IllegalStateException e) {
707 logger.debug("Cannot update channel for group member ({})", e.getMessage());
713 private @Nullable String getAlbumArtUrl() {
715 String albumArtURI = stateMap.get("CurrentAlbumArtURI");
716 if (albumArtURI != null) {
717 if (albumArtURI.startsWith("http")) {
719 } else if (albumArtURI.startsWith("/")) {
721 URL serviceDescrUrl = service.getDescriptorURL(this);
722 if (serviceDescrUrl != null) {
723 url = new URL(serviceDescrUrl.getProtocol(), serviceDescrUrl.getHost(),
724 serviceDescrUrl.getPort(), albumArtURI).toExternalForm();
726 } catch (MalformedURLException e) {
727 logger.debug("Failed to build a valid album art URL from {}: {}", albumArtURI, e.getMessage());
734 protected void updateChannel(String channelId) {
735 if (!isLinked(channelId)) {
741 State newState = UnDefType.UNDEF;
745 value = getTransportState();
747 newState = new StringType(value);
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;
761 value = getTransportState();
763 newState = OnOffType.from(STATE_STOPPED.equals(value));
767 if (getPlayMode() != null) {
768 newState = OnOffType.from(isShuffleActive());
772 if (getPlayMode() != null) {
773 newState = new StringType(getRepeatMode());
779 newState = OnOffType.from(value);
783 value = getCurrentZoneName();
785 newState = new StringType(value);
789 value = getZoneGroupID();
791 newState = new StringType(value);
795 newState = new StringType(getCoordinator());
797 case LOCALCOORDINATOR:
798 if (getGroupCoordinatorIsLocal() != null) {
799 newState = OnOffType.from(isGroupCoordinator());
805 newState = new PercentType(value);
810 if (value != null && !isOutputLevelFixed()) {
811 newState = new DecimalType(value);
816 if (value != null && !isOutputLevelFixed()) {
817 newState = new DecimalType(value);
821 value = getLoudness();
822 if (value != null && !isOutputLevelFixed()) {
823 newState = OnOffType.from(value);
829 newState = OnOffType.from(value);
833 value = getSubwooferEnabled();
835 newState = OnOffType.from(value);
839 value = getSubwooferGain();
841 newState = new DecimalType(value);
845 value = getSurroundEnabled();
847 newState = OnOffType.from(value);
850 case SURROUNDMUSICMODE:
851 value = getSurroundMusicMode();
853 newState = new StringType(value);
856 case SURROUNDMUSICLEVEL:
857 value = getSurroundMusicLevel();
859 newState = new DecimalType(value);
862 case SURROUNDTVLEVEL:
863 value = getSurroundTvLevel();
865 newState = new DecimalType(value);
869 value = getNightMode();
871 newState = OnOffType.from(value);
874 case SPEECHENHANCEMENT:
875 value = getDialogLevel();
877 newState = OnOffType.from(value);
881 if (getAnalogLineInConnected() != null) {
882 newState = OnOffType.from(isAnalogLineInConnected());
883 } else if (getOpticalLineInConnected() != null) {
884 newState = OnOffType.from(isOpticalLineInConnected());
888 if (getAnalogLineInConnected() != null) {
889 newState = OnOffType.from(isAnalogLineInConnected());
893 if (getOpticalLineInConnected() != null) {
894 newState = OnOffType.from(isOpticalLineInConnected());
898 if (getAlarmRunning() != null) {
899 newState = OnOffType.from(isAlarmRunning());
902 case ALARMPROPERTIES:
903 value = getRunningAlarmProperties();
905 newState = new StringType(value);
909 value = stateMap.get("CurrentURIFormatted");
911 newState = new StringType(value);
915 value = getCurrentTitle();
917 newState = new StringType(value);
921 value = getCurrentArtist();
923 newState = new StringType(value);
927 value = getCurrentAlbum();
929 newState = new StringType(value);
932 case CURRENTALBUMART:
934 updateAlbumArtChannel(false);
936 case CURRENTALBUMARTURL:
937 url = getAlbumArtUrl();
939 newState = new StringType(url);
942 case CURRENTTRANSPORTURI:
943 value = getCurrentURI();
945 newState = new StringType(value);
948 case CURRENTTRACKURI:
949 value = stateMap.get("CurrentTrackURI");
951 newState = new StringType(value);
954 case TUNEINSTATIONID:
955 value = stateMap.get("CurrentTuneInStationId");
957 newState = new StringType(value);
964 if (newState != null) {
965 updateState(channelId, newState);
969 private void updateAlbumArtChannel(boolean allGroup) {
970 String url = getAlbumArtUrl();
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);
978 updateChannel(CURRENTALBUMART, UnDefType.UNDEF, allGroup);
982 private void updateChannel(String channeldD, State state, boolean allGroup) {
984 for (String member : getZoneGroupMembers()) {
986 ZonePlayerHandler memberHandler = getHandlerByName(member);
987 if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())
988 && memberHandler.isLinked(channeldD)) {
989 memberHandler.updateState(channeldD, state);
991 } catch (IllegalStateException e) {
992 logger.debug("Cannot update channel for group member ({})", e.getMessage());
995 } else if (ThingStatus.ONLINE.equals(getThing().getStatus()) && isLinked(channeldD)) {
996 updateState(channeldD, state);
1001 * CurrentURI will not change, but will trigger change of CurrentURIFormated
1002 * CurrentTrackMetaData will not change, but will trigger change of Title, Artist, Album
1004 private boolean shouldIgnoreVariableUpdate(String variable, String value, @Nullable String oldValue) {
1005 return !hasValueChanged(value, oldValue) && !isQueueEvent(variable);
1008 private boolean hasValueChanged(@Nullable String value, @Nullable String oldValue) {
1009 return oldValue != null ? !oldValue.equals(value) : value != null;
1013 * Similar to the AVTransport eventing, the Queue events its state variables
1014 * as sub values within a synthesized LastChange state variable.
1016 private boolean isQueueEvent(String variable) {
1017 return "LastChange".equals(variable);
1020 private void updateGroupCoordinator() {
1022 coordinatorHandler = getHandlerByName(getCoordinator());
1023 } catch (IllegalStateException e) {
1024 logger.debug("Cannot update the group coordinator ({})", e.getMessage());
1025 coordinatorHandler = null;
1029 private boolean isUpnpDeviceRegistered() {
1030 return service.isRegistered(this);
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);
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);
1061 subscriptionState = new HashMap<>();
1066 public void onServiceSubscribed(@Nullable String service, boolean succeeded) {
1067 if (service == null) {
1070 synchronized (upnpLock) {
1071 logger.debug("{}: Subscription to service {} {}", getUDN(), service, succeeded ? "succeeded" : "failed");
1072 subscriptionState.put(service, succeeded);
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);
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<>();
1094 } else if (!ThingStatus.ONLINE.equals(getThing().getStatus())) {
1095 logger.debug("Sonos player {} has been found in local network", getUDN());
1096 updateStatus(ThingStatus.ONLINE);
1100 protected void updateCurrentZoneName() {
1101 executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_GET_ZONE_ATTRIBUTES, null);
1104 protected void updateLed() {
1105 executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_GET_LED_STATE, null);
1108 protected void updateTime() {
1109 executeAction(SERVICE_ALARM_CLOCK, "GetTimeNow", null);
1112 protected void updatePosition() {
1113 executeAction(SERVICE_AV_TRANSPORT, ACTION_GET_POSITION_INFO, null);
1116 protected void updateRunningAlarmProperties() {
1117 Map<String, String> result = service.invokeAction(this, SERVICE_AV_TRANSPORT,
1118 ACTION_GET_RUNNING_ALARM_PROPERTIES, null);
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;
1126 newStringValue = "No running alarm";
1128 result.put("RunningAlarmProperties", newStringValue);
1130 result.forEach((variable, value) -> {
1131 this.onValueReceived(variable, value, SERVICE_AV_TRANSPORT);
1135 protected boolean updateZoneInfo() {
1136 Map<String, String> result = executeAction(SERVICE_DEVICE_PROPERTIES, ACTION_GET_ZONE_INFO, null);
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);
1143 value = stateMap.get("DisplaySoftwareVersion");
1144 if (value != null && !value.isEmpty()) {
1145 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, value);
1147 value = stateMap.get("SerialNumber");
1148 if (value != null && !value.isEmpty()) {
1149 properties.put(Thing.PROPERTY_SERIAL_NUMBER, value);
1151 value = stateMap.get("MACAddress");
1152 if (value != null && !value.isEmpty()) {
1153 properties.put(MAC_ADDRESS, value);
1155 value = stateMap.get("IPAddress");
1156 if (value != null && !value.isEmpty()) {
1157 properties.put(IP_ADDRESS, value);
1159 updateProperties(properties);
1161 return !result.isEmpty();
1164 public String getCoordinator() {
1165 for (SonosZoneGroup zg : getZoneGroups()) {
1166 if (zg.getMembers().contains(getUDN())) {
1167 return zg.getCoordinator();
1173 public boolean isCoordinator() {
1174 return getUDN().equals(getCoordinator());
1177 protected void updateMediaInformation() {
1178 String currentURI = getCurrentURI();
1179 SonosMetaData currentTrack = getTrackMetadata();
1180 SonosMetaData currentUriMetaData = getCurrentURIMetadata();
1182 String artist = null;
1183 String album = null;
1184 String title = null;
1185 String resultString = null;
1186 String stationID = null;
1187 boolean needsUpdating = false;
1189 // if currentURI == null, we do nothing
1190 if (currentURI != null) {
1191 if (currentURI.isEmpty()) {
1193 needsUpdating = true;
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
1201 else if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)) {
1202 // Radio stream (tune-in)
1203 boolean opmlUrlSucceeded = false;
1204 stationID = extractStationId(currentURI);
1205 String url = opmlUrl;
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);
1212 String response = null;
1214 response = HttpUtil.executeUrl("GET", url, SOCKET_TIMEOUT);
1215 } catch (IOException e) {
1216 logger.debug("Request to device failed", e);
1219 if (response != null) {
1220 List<String> fields = SonosXMLParser.getRadioTimeFromXML(response);
1222 if (!fields.isEmpty()) {
1223 opmlUrlSucceeded = true;
1226 for (String field : fields) {
1227 if (resultString.isEmpty()) {
1228 // radio name should be first field
1231 resultString += " - ";
1233 resultString += field;
1236 needsUpdating = true;
1241 if (!opmlUrlSucceeded) {
1242 if (currentUriMetaData != null) {
1243 title = currentUriMetaData.getTitle();
1244 if (currentTrack == null || currentTrack.getStreamContent().isEmpty()) {
1245 resultString = title;
1247 resultString = title + " - " + currentTrack.getStreamContent();
1249 needsUpdating = true;
1254 else if (isPlayingLineIn(currentURI)) {
1255 if (currentTrack != null) {
1256 title = currentTrack.getTitle();
1257 resultString = title;
1258 needsUpdating = true;
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;
1276 String albumArtURI = (currentTrack != null && !currentTrack.getAlbumArtUri().isEmpty())
1277 ? currentTrack.getAlbumArtUri()
1280 ZonePlayerHandler handlerForImageUpdate = null;
1281 for (String member : getZoneGroupMembers()) {
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;
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);
1303 } catch (IllegalStateException e) {
1304 logger.debug("Cannot update media data for group member ({})", e.getMessage());
1307 if (needsUpdating && handlerForImageUpdate != null) {
1308 handlerForImageUpdate.updateAlbumArtChannel(true);
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", "&");
1322 private @Nullable String substringBetween(String str, String open, String close) {
1323 String result = null;
1324 int idx1 = str.indexOf(open);
1326 idx1 += open.length();
1327 int idx2 = str.indexOf(close, idx1);
1329 result = str.substring(idx1, idx2);
1335 public @Nullable String getGroupCoordinatorIsLocal() {
1336 return stateMap.get("GroupCoordinatorIsLocal");
1339 public boolean isGroupCoordinator() {
1340 return "true".equals(getGroupCoordinatorIsLocal());
1344 public String getUDN() {
1345 String udn = configuration.udn;
1346 return udn != null && !udn.isEmpty() ? udn : "undefined";
1349 public @Nullable String getCurrentURI() {
1350 return stateMap.get("CurrentURI");
1353 public @Nullable String getCurrentURIMetadataAsString() {
1354 return stateMap.get("CurrentURIMetaData");
1357 public @Nullable SonosMetaData getCurrentURIMetadata() {
1358 String metaData = getCurrentURIMetadataAsString();
1359 return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1362 public @Nullable SonosMetaData getTrackMetadata() {
1363 String metaData = stateMap.get("CurrentTrackMetaData");
1364 return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1367 public @Nullable SonosMetaData getEnqueuedTransportURIMetaData() {
1368 String metaData = stateMap.get("EnqueuedTransportURIMetaData");
1369 return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1372 public @Nullable String getMACAddress() {
1373 String mac = stateMap.get("MACAddress");
1374 if (mac == null || mac.isEmpty()) {
1377 return stateMap.get("MACAddress");
1380 public @Nullable String getRefreshedPosition() {
1382 return stateMap.get("RelTime");
1385 public long getRefreshedCurrenTrackNr() {
1387 String value = stateMap.get("Track");
1388 if (value != null) {
1389 return Long.valueOf(value);
1395 public @Nullable String getVolume() {
1396 return stateMap.get("VolumeMaster");
1399 public boolean isOutputLevelFixed() {
1400 return "1".equals(stateMap.get("OutputFixed"));
1403 public @Nullable String getBass() {
1404 return stateMap.get("Bass");
1407 public @Nullable String getTreble() {
1408 return stateMap.get("Treble");
1411 public @Nullable String getLoudness() {
1412 return stateMap.get("LoudnessMaster");
1415 public @Nullable String getSurroundEnabled() {
1416 return stateMap.get("SurroundEnabled");
1419 public @Nullable String getSurroundMusicMode() {
1420 return stateMap.get("SurroundMode");
1423 public @Nullable String getSurroundTvLevel() {
1424 return stateMap.get("SurroundLevel");
1427 public @Nullable String getSurroundMusicLevel() {
1428 return stateMap.get("MusicSurroundLevel");
1431 public @Nullable String getSubwooferEnabled() {
1432 return stateMap.get("SubEnabled");
1435 public @Nullable String getSubwooferGain() {
1436 return stateMap.get("SubGain");
1439 public @Nullable String getTransportState() {
1440 return stateMap.get("TransportState");
1443 public @Nullable String getCurrentTitle() {
1444 return stateMap.get("CurrentTitle");
1447 public @Nullable String getCurrentArtist() {
1448 return stateMap.get("CurrentArtist");
1451 public @Nullable String getCurrentAlbum() {
1452 return stateMap.get("CurrentAlbum");
1455 public List<SonosEntry> getArtists(String filter) {
1456 return getEntries("A:", filter);
1459 public List<SonosEntry> getArtists() {
1460 return getEntries("A:", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1463 public List<SonosEntry> getAlbums(String filter) {
1464 return getEntries("A:ALBUM", filter);
1467 public List<SonosEntry> getAlbums() {
1468 return getEntries("A:ALBUM", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1471 public List<SonosEntry> getTracks(String filter) {
1472 return getEntries("A:TRACKS", filter);
1475 public List<SonosEntry> getTracks() {
1476 return getEntries("A:TRACKS", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1479 public List<SonosEntry> getQueue(String filter) {
1480 return getEntries("Q:0", filter);
1483 public List<SonosEntry> getQueue() {
1484 return getEntries("Q:0", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1487 public long getQueueSize() {
1488 return getNbEntries("Q:0");
1491 public List<SonosEntry> getPlayLists(String filter) {
1492 return getEntries("SQ:", filter);
1495 public List<SonosEntry> getPlayLists() {
1496 return getEntries("SQ:", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1499 public List<SonosEntry> getFavoriteRadios(String filter) {
1500 return getEntries("R:0/0", filter);
1503 public List<SonosEntry> getFavoriteRadios() {
1504 return getEntries("R:0/0", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1508 * Searches for entries in the 'favorites' list on a sonos account
1512 public List<SonosEntry> getFavorites() {
1513 return getEntries("FV:2", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1516 protected List<SonosEntry> getEntries(String type, String filter) {
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", "");
1527 Map<String, String> result = service.invokeAction(this, SERVICE_CONTENT_DIRECTORY, "Browse", inputs);
1529 String initialResult = result.get("Result");
1530 if (initialResult == null) {
1531 return Collections.emptyList();
1534 long totalMatches = getResultEntry(result, "TotalMatches", type, filter);
1535 long initialNumberReturned = getResultEntry(result, "NumberReturned", type, filter);
1537 List<SonosEntry> resultList = SonosXMLParser.getEntriesFromString(initialResult);
1538 startAt = startAt + initialNumberReturned;
1540 while (startAt < totalMatches) {
1541 inputs.put("StartingIndex", Long.toString(startAt));
1542 result = service.invokeAction(this, SERVICE_CONTENT_DIRECTORY, "Browse", inputs);
1544 // Execute this action synchronously
1545 String nextResult = result.get("Result");
1546 if (nextResult == null) {
1550 long numberReturned = getResultEntry(result, "NumberReturned", type, filter);
1552 resultList.addAll(SonosXMLParser.getEntriesFromString(nextResult));
1554 startAt = startAt + numberReturned;
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", "");
1569 Map<String, String> result = service.invokeAction(this, SERVICE_CONTENT_DIRECTORY, "Browse", inputs);
1571 return getResultEntry(result, "TotalMatches", type, "dc:title");
1575 * Handles value searching in a SONOS result map (called by {@link #getEntries(String, String)})
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
1582 * @return 0 as long or the value corresponding to the requiredKey if found
1584 private Long getResultEntry(Map<String, String> resultInput, String requestedKey, String entriesType,
1585 String entriesFilter) {
1588 if (resultInput.isEmpty()) {
1593 String resultString = resultInput.get(requestedKey);
1594 if (resultString == null) {
1595 throw new NumberFormatException("Requested key is null.");
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);
1607 * Save the state (track, position etc) of the Sonos Zone player.
1609 * @return true if no error occurred.
1611 protected void saveState() {
1612 synchronized (stateLock) {
1613 savedState = new SonosZonePlayerState();
1614 String currentURI = getCurrentURI();
1616 savedState.transportState = getTransportState();
1617 savedState.volume = getVolume();
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);
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();
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(),
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());
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();
1668 saveQueue(TITLE_PREFIX + getUDN(), existingList);
1670 // get all the playlists and a ref to our
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(),
1683 savedState.entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + getUDN() + "#0");
1687 savedState.relTime = getRefreshedPosition();
1689 savedState.entry = null;
1695 * Restore the state (track, position etc) of the Sonos Zone player.
1697 * @return true if no error occurred.
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));
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);
1719 setCurrentURI(entry);
1720 setPosition(state.relTime);
1724 String transportState = state.transportState;
1725 if (transportState != null) {
1726 if (transportState.equals(STATE_PLAYING)) {
1728 } else if (transportState.equals(STATE_STOPPED)) {
1730 } else if (transportState.equals(STATE_PAUSED_PLAYBACK)) {
1739 public void saveQueue(String name, String queueID) {
1740 executeAction(SERVICE_AV_TRANSPORT, ACTION_SAVE_QUEUE, Map.of("Title", name, "ObjectID", queueID));
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) {
1756 } else if (command == OnOffType.OFF) {
1758 } else if (command instanceof DecimalType) {
1759 newValue = String.valueOf(((DecimalType) command).intValue());
1763 executeAction(SERVICE_RENDERING_CONTROL, ACTION_SET_VOLUME,
1764 Map.of("Channel", "Master", "DesiredVolume", newValue));
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.
1773 public void setVolumeForGroup(Command command) {
1774 if (isAdHocGroup() || isStandalonePlayer()) {
1778 getCoordinatorHandler().setVolume(command);
1779 } catch (IllegalStateException e) {
1780 logger.debug("Cannot set group volume ({})", e.getMessage());
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));
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));
1805 private @Nullable String getNewNumericValue(Command command, @Nullable String currentValue, int minValue,
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());
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));
1833 * Checks if the player receiving the command is part of a group that
1834 * consists of randomly added players or contains bonded players
1838 private boolean isAdHocGroup() {
1839 SonosZoneGroup currentZoneGroup = getCurrentZoneGroup();
1840 if (currentZoneGroup != null) {
1841 List<String> zoneGroupMemberNames = currentZoneGroup.getMemberZoneNames();
1843 for (String zoneName : zoneGroupMemberNames) {
1844 if (!zoneName.equals(zoneGroupMemberNames.get(0))) {
1845 // At least one "ZoneName" differs so we have an AdHoc group
1854 * Checks if the player receiving the command is a standalone player
1858 private boolean isStandalonePlayer() {
1859 SonosZoneGroup zoneGroup = getCurrentZoneGroup();
1860 return zoneGroup == null || zoneGroup.getMembers().size() == 1;
1863 private Collection<SonosZoneGroup> getZoneGroups() {
1864 String zoneGroupState = stateMap.get("ZoneGroupState");
1865 return zoneGroupState == null ? Collections.emptyList() : SonosXMLParser.getZoneGroupFromXML(zoneGroupState);
1869 * Returns the current zone group
1870 * (of which the player receiving the command is part)
1872 * @return {@link SonosZoneGroup}
1874 private @Nullable SonosZoneGroup getCurrentZoneGroup() {
1875 for (SonosZoneGroup zoneGroup : getZoneGroups()) {
1876 if (zoneGroup.getMembers().contains(getUDN())) {
1880 logger.debug("Could not fetch Sonos group state information");
1885 * Sets the volume level for a notification sound
1887 * @param notificationSoundVolume
1889 public void setNotificationSoundVolume(@Nullable PercentType notificationSoundVolume) {
1890 if (notificationSoundVolume != null) {
1891 setVolumeForGroup(notificationSoundVolume);
1896 * Gets the volume level for a notification sound
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;
1905 return new PercentType(notificationSoundVolume);
1908 public void addURIToQueue(String URI, String meta, long desiredFirstTrack, boolean enqueueAsNext) {
1909 Map<String, String> inputs = new HashMap<>();
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());
1921 executeAction(SERVICE_AV_TRANSPORT, ACTION_ADD_URI_TO_QUEUE, inputs);
1924 public void setCurrentURI(SonosEntry newEntry) {
1925 setCurrentURI(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry));
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));
1936 public void setPosition(@Nullable String relTime) {
1937 seek("REL_TIME", relTime);
1940 public void setPositionTrack(long tracknr) {
1941 seek("TRACK_NR", Long.toString(tracknr));
1944 public void setPositionTrack(String tracknr) {
1945 seek("TRACK_NR", tracknr);
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));
1954 public void play() {
1955 executeAction(SERVICE_AV_TRANSPORT, ACTION_PLAY, Map.of("Speed", "1"));
1958 public void stop() {
1959 executeAction(SERVICE_AV_TRANSPORT, ACTION_STOP, null);
1962 public void pause() {
1963 executeAction(SERVICE_AV_TRANSPORT, ACTION_PAUSE, null);
1966 public void setShuffle(Command command) {
1967 if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
1969 ZonePlayerHandler coordinator = getCoordinatorHandler();
1971 if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
1972 || command.equals(OpenClosedType.OPEN)) {
1973 switch (coordinator.getRepeatMode()) {
1975 coordinator.updatePlayMode("SHUFFLE");
1978 coordinator.updatePlayMode("SHUFFLE_REPEAT_ONE");
1981 coordinator.updatePlayMode("SHUFFLE_NOREPEAT");
1984 } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
1985 || command.equals(OpenClosedType.CLOSED)) {
1986 switch (coordinator.getRepeatMode()) {
1988 coordinator.updatePlayMode("REPEAT_ALL");
1991 coordinator.updatePlayMode("REPEAT_ONE");
1994 coordinator.updatePlayMode("NORMAL");
1998 } catch (IllegalStateException e) {
1999 logger.debug("Cannot handle shuffle command ({})", e.getMessage());
2004 public void setRepeat(Command command) {
2005 if (command instanceof StringType) {
2007 ZonePlayerHandler coordinator = getCoordinatorHandler();
2009 switch (command.toString()) {
2011 coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE" : "REPEAT_ALL");
2014 coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_REPEAT_ONE" : "REPEAT_ONE");
2017 coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_NOREPEAT" : "NORMAL");
2020 logger.debug("{}: unexpected repeat command; accepted values are ALL, ONE and OFF",
2021 command.toString());
2024 } catch (IllegalStateException e) {
2025 logger.debug("Cannot handle repeat command ({})", e.getMessage());
2030 public void setSubwoofer(Command command) {
2031 setEqualizerBooleanSetting(command, "SubEnabled");
2034 public void setSubwooferGain(Command command) {
2035 setEqualizerNumericSetting(command, "SubGain", getSubwooferGain(), MIN_SUBWOOFER_GAIN, MAX_SUBWOOFER_GAIN);
2038 public void setSurround(Command command) {
2039 setEqualizerBooleanSetting(command, "SurroundEnabled");
2042 public void setSurroundMusicMode(Command command) {
2043 if (command instanceof StringType) {
2044 setEQ("SurroundMode", command.toString());
2048 public void setSurroundMusicLevel(Command command) {
2049 setEqualizerNumericSetting(command, "MusicSurroundLevel", getSurroundMusicLevel(), MIN_SURROUND_LEVEL,
2050 MAX_SURROUND_LEVEL);
2053 public void setSurroundTvLevel(Command command) {
2054 setEqualizerNumericSetting(command, "SurroundLevel", getSurroundTvLevel(), MIN_SURROUND_LEVEL,
2055 MAX_SURROUND_LEVEL);
2058 public void setNightMode(Command command) {
2059 setEqualizerBooleanSetting(command, "NightMode");
2062 public void setSpeechEnhancement(Command command) {
2063 setEqualizerBooleanSetting(command, "DialogLevel");
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");
2073 private void setEqualizerNumericSetting(Command command, String eqType, @Nullable String currentValue, int minValue,
2075 String newValue = getNewNumericValue(command, currentValue, minValue, maxValue);
2076 if (newValue != null) {
2077 setEQ(eqType, newValue);
2081 private void setEQ(String eqType, String value) {
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());
2090 public @Nullable String getNightMode() {
2091 return stateMap.get("NightMode");
2094 public @Nullable String getDialogLevel() {
2095 return stateMap.get("DialogLevel");
2098 public @Nullable String getPlayMode() {
2099 return stateMap.get("CurrentPlayMode");
2102 public Boolean isShuffleActive() {
2103 String playMode = getPlayMode();
2104 return (playMode != null && playMode.startsWith("SHUFFLE"));
2107 public String getRepeatMode() {
2108 String mode = "OFF";
2109 String playMode = getPlayMode();
2110 if (playMode != null) {
2117 case "SHUFFLE_REPEAT_ONE":
2121 case "SHUFFLE_NOREPEAT":
2130 protected void updatePlayMode(String playMode) {
2131 executeAction(SERVICE_AV_TRANSPORT, ACTION_SET_PLAY_MODE, Map.of("InstanceID", "0", "NewPlayMode", playMode));
2135 * Clear all scheduled music from the current queue.
2138 public void removeAllTracksFromQueue() {
2139 executeAction(SERVICE_AV_TRANSPORT, ACTION_REMOVE_ALL_TRACKS_FROM_QUEUE, Map.of("InstanceID", "0"));
2143 * Play music from the line-in of the given Player referenced by the given UDN or name
2145 * @param udn or name
2147 public void playLineIn(Command command) {
2148 if (command instanceof StringType) {
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);
2159 ZonePlayerHandler coordinatorHandler = getCoordinatorHandler();
2160 ZonePlayerHandler remoteHandler = getHandlerByName(remotePlayerName);
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();
2169 if (lineInType != LineInType.DIGITAL && remoteHandler.isAnalogLineInConnected()) {
2170 coordinatorHandler.setCurrentURI(ANALOG_LINE_IN_URI + remoteHandler.getUDN(), "");
2172 coordinatorHandler.setCurrentURI(OPTICAL_LINE_IN_URI + remoteHandler.getUDN() + SPDIF, "");
2175 // take the system off mute
2176 coordinatorHandler.setMute(OnOffType.OFF);
2179 coordinatorHandler.play();
2181 logger.debug("Line-in of {} is not connected", remoteHandler.getUDN());
2183 } catch (IllegalStateException e) {
2184 logger.debug("Cannot play line-in ({})", e.getMessage());
2189 private ZonePlayerHandler getCoordinatorHandler() throws IllegalStateException {
2190 ZonePlayerHandler handler = coordinatorHandler;
2191 if (handler != null) {
2195 handler = getHandlerByName(getCoordinator());
2196 coordinatorHandler = handler;
2198 } catch (IllegalStateException e) {
2199 throw new IllegalStateException("Missing group coordinator " + getCoordinator());
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
2207 * @return a list of Strings containing the UDNs of other group members
2209 protected List<String> getZoneGroupMembers() {
2210 List<String> result = new ArrayList<>();
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());
2221 // If the group topology was not yet received, return at least the current Sonos zone
2222 result.add(getUDN());
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
2231 * @return a list of Strings containing the UDNs of other group members
2233 protected List<String> getOtherZoneGroupMembers() {
2234 List<String> zoneGroupMembers = getZoneGroupMembers();
2235 zoneGroupMembers.remove(getUDN());
2236 return zoneGroupMembers;
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;
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;
2258 throw new IllegalStateException("Could not find handler for " + remotePlayerName);
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));
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);
2276 public void updateAlarm(SonosAlarm alarm) {
2277 Map<String, String> inputs = new HashMap<>();
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");
2292 inputs.put("IncludeLinkedZones", "0");
2295 if (alarm.getEnabled()) {
2296 inputs.put("Enabled", "1");
2298 inputs.put("Enabled", "0");
2300 } catch (NumberFormatException ex) {
2301 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
2304 executeAction(SERVICE_ALARM_CLOCK, "UpdateAlarm", inputs);
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)) {
2311 } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
2312 || command.equals(OpenClosedType.CLOSED)) {
2318 public void setAlarm(boolean alarmSwitch) {
2319 List<SonosAlarm> sonosAlarms = getCurrentAlarmList();
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"));
2326 String currentLocalTime = getTime();
2327 Date currentDateTime = null;
2329 currentDateTime = fmt.parse(currentLocalTime);
2330 } catch (ParseException e) {
2331 logger.debug("An exception occurred while formatting a date", e);
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();
2341 SonosAlarm firstAlarm = null;
2343 for (SonosAlarm anAlarm : sonosAlarms) {
2344 SimpleDateFormat durationFormat = new SimpleDateFormat("HH:mm:ss");
2345 durationFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
2348 durationDate = durationFormat.parse(anAlarm.getDuration());
2349 } catch (ParseException e) {
2350 logger.debug("An exception occurred while parsing a date : '{}'", e.getMessage());
2354 long duration = durationDate.getTime();
2356 if (duration < shortestDuration && anAlarm.getRoomUUID().equals(getUDN())) {
2357 shortestDuration = duration;
2358 firstAlarm = anAlarm;
2363 if (firstAlarm != null) {
2365 firstAlarm.setEnabled(true);
2367 firstAlarm.setEnabled(false);
2370 updateAlarm(firstAlarm);
2375 public @Nullable String getTime() {
2377 return stateMap.get("CurrentLocalTime");
2380 public @Nullable String getAlarmRunning() {
2381 return stateMap.get("AlarmRunning");
2384 public boolean isAlarmRunning() {
2385 return "1".equals(getAlarmRunning());
2388 public void snoozeAlarm(Command command) {
2389 if (isAlarmRunning() && command instanceof DecimalType) {
2390 int minutes = ((DecimalType) command).intValue();
2392 Map<String, String> inputs = new HashMap<>();
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"));
2402 inputs.put("Duration", pFormatter.format(snoozePeriod.getTime()));
2403 } catch (NumberFormatException ex) {
2404 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
2407 executeAction(SERVICE_AV_TRANSPORT, ACTION_SNOOZE_ALARM, inputs);
2409 logger.debug("There is no alarm running on {}", getUDN());
2413 public @Nullable String getAnalogLineInConnected() {
2414 return stateMap.get(LINEINCONNECTED);
2417 public boolean isAnalogLineInConnected() {
2418 return "true".equals(getAnalogLineInConnected());
2421 public @Nullable String getOpticalLineInConnected() {
2422 return stateMap.get(TOSLINEINCONNECTED);
2425 public boolean isOpticalLineInConnected() {
2426 return "true".equals(getOpticalLineInConnected());
2429 public void becomeStandAlonePlayer() {
2430 executeAction(SERVICE_AV_TRANSPORT, ACTION_BECOME_COORDINATOR_OF_STANDALONE_GROUP, null);
2433 public void addMember(Command command) {
2434 if (command instanceof StringType) {
2435 SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", GROUP_URI + getUDN());
2437 getHandlerByName(command.toString()).setCurrentURI(entry);
2438 } catch (IllegalStateException e) {
2439 logger.debug("Cannot add group member ({})", e.getMessage());
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();
2451 // add all other players to this new group
2452 for (SonosZoneGroup group : getZoneGroups()) {
2453 for (String player : group.getMembers()) {
2455 ZonePlayerHandler somePlayer = getHandlerByName(player);
2456 if (somePlayer != this) {
2457 somePlayer.becomeStandAlonePlayer();
2459 addMember(StringType.valueOf(somePlayer.getUDN()));
2461 } catch (IllegalStateException e) {
2462 logger.debug("Cannot add to group ({})", e.getMessage());
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);
2474 coordinator.setCurrentURI(entry);
2478 } catch (IllegalStateException e) {
2479 logger.debug("Cannot handle command ({})", e.getMessage());
2483 logger.debug("Line-in of {} is not connected", getUDN());
2489 * Play a given url to music in one of the music libraries.
2492 * in the format of //host/folder/filename.mp3
2494 public void playURI(Command command) {
2495 if (command instanceof StringType) {
2497 String url = command.toString();
2499 ZonePlayerHandler coordinator = getCoordinatorHandler();
2501 // stop whatever is currently playing
2503 coordinator.waitForNotTransportState(STATE_PLAYING);
2505 // clear any tracks which are pending in the queue
2506 coordinator.removeAllTracksFromQueue();
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;
2514 coordinator.addURIToQueue(url, "", 0, true);
2516 // set the current playlist to our new queue
2517 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2519 // take the system off mute
2520 coordinator.setMute(OnOffType.OFF);
2524 } catch (IllegalStateException e) {
2525 logger.debug("Cannot play URI ({})", e.getMessage());
2530 private void scheduleNotificationSound(final Command command) {
2531 scheduler.submit(() -> {
2532 synchronized (notificationLock) {
2533 playNotificationSoundURI(command);
2539 * Play a given notification sound
2541 * @param url in the format of //host/folder/filename.mp3
2543 public void playNotificationSoundURI(Command notificationURL) {
2544 if (notificationURL instanceof StringType) {
2546 ZonePlayerHandler coordinator = getCoordinatorHandler();
2548 String currentURI = coordinator.getCurrentURI();
2549 logger.debug("playNotificationSoundURI: currentURI {} metadata {}", currentURI,
2550 coordinator.getCurrentURIMetadataAsString());
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);
2562 synchronized (notificationLock) {
2563 notificationLock.notify();
2565 } catch (IllegalStateException e) {
2566 logger.debug("Cannot play sound ({})", e.getMessage());
2571 private boolean isPlaylistEmpty(ZonePlayerHandler coordinator) {
2572 return coordinator.getQueueSize() == 0;
2575 private boolean isPlayingQueue(@Nullable String currentURI) {
2576 return currentURI != null && currentURI.contains(QUEUE_URI);
2579 private boolean isPlayingStream(@Nullable String currentURI) {
2580 return currentURI != null && currentURI.contains(STREAM_URI);
2583 private boolean isPlayingRadio(@Nullable String currentURI) {
2584 return currentURI != null && currentURI.contains(RADIO_URI);
2587 private boolean isPlayingRadioStartedByAmazonEcho(@Nullable String currentURI) {
2588 return currentURI != null && currentURI.contains(RADIO_MP3_URI) && currentURI.contains(OPML_TUNE);
2591 private boolean isPlayingLineIn(@Nullable String currentURI) {
2592 return currentURI != null && (isPlayingAnalogLineIn(currentURI) || isPlayingOpticalLineIn(currentURI));
2595 private boolean isPlayingAnalogLineIn(@Nullable String currentURI) {
2596 return currentURI != null && currentURI.contains(ANALOG_LINE_IN_URI);
2599 private boolean isPlayingOpticalLineIn(@Nullable String currentURI) {
2600 return currentURI != null && currentURI.startsWith(OPTICAL_LINE_IN_URI) && currentURI.endsWith(SPDIF);
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
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)
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();
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);
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
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)
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();
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);
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
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)
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);
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);
2675 * Handle the execution of the notification sound by sequentially executing the required steps.
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)
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) {
2685 coordinator.waitForNotTransportState(STATE_PLAYING);
2686 applyNotificationSoundVolume();
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) {
2694 coordinator.waitForNotTransportState(STATE_PLAYING);
2695 applyNotificationSoundVolume();
2698 coordinator.waitForFinishedNotification();
2699 if (originalVolume != null) {
2700 setVolumeForGroup(DecimalType.valueOf(originalVolume));
2702 coordinator.removeRangeOfTracksFromQueue(new StringType(Long.toString(notificationPosition) + ",1"));
2705 private void restoreLastTransportState(ZonePlayerHandler coordinator, @Nullable String nextAction) {
2706 if (nextAction != null) {
2707 switch (nextAction) {
2710 coordinator.waitForTransportState(STATE_PLAYING);
2712 case STATE_PAUSED_PLAYBACK:
2713 coordinator.pause();
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
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)
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));
2739 * Applies the notification sound volume level to the group (if not null)
2741 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2743 private void applyNotificationSoundVolume() {
2744 setNotificationSoundVolume(getNotificationSoundVolume());
2747 private void waitForFinishedNotification() {
2748 waitForTransportState(STATE_PLAYING);
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) {
2756 String currentTitle = getCurrentTitle();
2757 if ((notificationTitle == null && currentTitle != null)
2758 || (notificationTitle != null && !notificationTitle.equals(currentTitle))
2759 || !STATE_PLAYING.equals(getTransportState())) {
2762 } catch (InterruptedException e) {
2763 logger.debug("InterruptedException during playing a notification sound");
2768 private void waitForTransportState(String state) {
2769 if (getTransportState() != null) {
2770 long start = System.currentTimeMillis();
2771 while (!state.equals(getTransportState())) {
2774 if (System.currentTimeMillis() - start > (long) configuration.notificationTimeout * 1000) {
2777 } catch (InterruptedException e) {
2778 logger.debug("InterruptedException during playing a notification sound");
2784 private void waitForNotTransportState(String state) {
2785 if (getTransportState() != null) {
2786 long start = System.currentTimeMillis();
2787 while (state.equals(getTransportState())) {
2790 if (System.currentTimeMillis() - start > (long) configuration.notificationTimeout * 1000) {
2793 } catch (InterruptedException e) {
2794 logger.debug("InterruptedException during playing a notification sound");
2801 * Removes a range of tracks from the queue.
2802 * (<x,y> will remove y songs started by the song number x)
2804 * @param command - must be in the format <startIndex, numberOfSongs>
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));
2817 public void clearQueue() {
2819 ZonePlayerHandler coordinator = getCoordinatorHandler();
2821 coordinator.removeAllTracksFromQueue();
2822 } catch (IllegalStateException e) {
2823 logger.debug("Cannot clear queue ({})", e.getMessage());
2827 public void playQueue() {
2829 ZonePlayerHandler coordinator = getCoordinatorHandler();
2831 // set the current playlist to our new queue
2832 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2834 // take the system off mute
2835 coordinator.setMute(OnOffType.OFF);
2839 } catch (IllegalStateException e) {
2840 logger.debug("Cannot play queue ({})", e.getMessage());
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);
2853 public void removeMember(Command command) {
2854 if (command instanceof StringType) {
2856 ZonePlayerHandler oldmemberHandler = getHandlerByName(command.toString());
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());
2868 public void previous() {
2869 executeAction(SERVICE_AV_TRANSPORT, ACTION_PREVIOUS, null);
2872 public void next() {
2873 executeAction(SERVICE_AV_TRANSPORT, ACTION_NEXT, null);
2876 public void stopPlaying(Command command) {
2877 if (command instanceof OnOffType) {
2879 getCoordinatorHandler().stop();
2880 } catch (IllegalStateException e) {
2881 logger.debug("Cannot handle stop command ({})", e.getMessage(), e);
2886 public void playRadio(Command command) {
2887 if (command instanceof StringType) {
2888 String station = command.toString();
2889 List<SonosEntry> stations = getFavoriteRadios();
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;
2900 // set the URI of the group coordinator
2901 if (theEntry != null) {
2903 ZonePlayerHandler coordinator = getCoordinatorHandler();
2904 coordinator.setCurrentURI(theEntry);
2906 } catch (IllegalStateException e) {
2907 logger.debug("Cannot play radio ({})", e.getMessage());
2910 logger.debug("Radio station '{}' not found", station);
2915 public void playTuneinStation(Command command) {
2916 if (command instanceof StringType) {
2917 String stationId = command.toString();
2918 List<SonosMusicService> allServices = getAvailableMusicServices();
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;
2931 // set the URI of the group coordinator
2932 if (tuneinService != null) {
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);
2943 } catch (IllegalStateException e) {
2944 logger.debug("Cannot play TuneIn station {} ({})", stationId, e.getMessage());
2947 logger.debug("TuneIn service not found");
2952 private @Nullable List<SonosMusicService> getAvailableMusicServices() {
2953 if (musicServices == null) {
2954 Map<String, String> result = service.invokeAction(this, "MusicServices", "ListAvailableServices", null);
2956 String serviceList = result.get("AvailableServiceDescriptorList");
2957 if (serviceList != null) {
2958 List<SonosMusicService> services = SonosXMLParser.getMusicServicesFromXML(serviceList);
2959 musicServices = services;
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
2967 servicesTypes = serviceTypeList.split(",");
2971 for (SonosMusicService service : services) {
2972 if (!service.getName().equals("TuneIn")) {
2973 // Add the service type integer value from "AvailableServiceTypeList" to each service
2975 if (idx < servicesTypes.length) {
2977 Integer serviceType = Integer.parseInt(servicesTypes[idx]);
2978 service.setType(serviceType);
2979 } catch (NumberFormatException e) {
2984 service.setType(TUNEIN_DEFAULT_SERVICE_TYPE);
2986 logger.debug("Service name {} => id {} type {}", service.getName(), service.getId(),
2991 return musicServices;
2995 * This will attempt to match the station string with a entry in the
2996 * favorites list, this supports both single entries and playlists
2998 * @param favorite to match
2999 * @return true if a match was found and played.
3001 public void playFavorite(Command command) {
3002 if (command instanceof StringType) {
3003 String favorite = command.toString();
3004 List<SonosEntry> favorites = getFavorites();
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)) {
3015 // set the URI of the group coordinator
3016 if (theEntry != null) {
3018 ZonePlayerHandler coordinator = getCoordinatorHandler();
3021 * If this is a playlist we need to treat it as such
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);
3031 coordinator.setCurrentURI(theEntry);
3034 } catch (IllegalStateException e) {
3035 logger.debug("Cannot paly favorite ({})", e.getMessage());
3038 logger.debug("Favorite '{}' not found", favorite);
3043 public void playTrack(Command command) {
3044 if (command instanceof DecimalType) {
3046 ZonePlayerHandler coordinator = getCoordinatorHandler();
3048 String trackNumber = String.valueOf(((DecimalType) command).intValue());
3050 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
3052 // seek the track - warning, we do not check if the tracknumber falls in the boundary of the queue
3053 coordinator.setPositionTrack(trackNumber);
3055 // take the system off mute
3056 coordinator.setMute(OnOffType.OFF);
3060 } catch (IllegalStateException e) {
3061 logger.debug("Cannot play track ({})", e.getMessage());
3066 public void playPlayList(Command command) {
3067 if (command instanceof StringType) {
3068 String playlist = command.toString();
3069 List<SonosEntry> playlists = getPlayLists();
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;
3080 // set the URI of the group coordinator
3081 if (theEntry != null) {
3083 ZonePlayerHandler coordinator = getCoordinatorHandler();
3085 coordinator.addURIToQueue(theEntry);
3087 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
3089 String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued");
3090 coordinator.seek("TRACK_NR", firstTrackNumberEnqueued);
3093 } catch (IllegalStateException e) {
3094 logger.debug("Cannot play playlist ({})", e.getMessage());
3097 logger.debug("Playlist '{}' not found", playlist);
3102 public void addURIToQueue(SonosEntry newEntry) {
3103 addURIToQueue(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry), 1, true);
3106 public @Nullable String getZoneName() {
3107 return stateMap.get("ZoneName");
3110 public @Nullable String getZoneGroupID() {
3111 return stateMap.get("LocalGroupUUID");
3114 public @Nullable String getRunningAlarmProperties() {
3115 return stateMap.get("RunningAlarmProperties");
3118 public @Nullable String getRefreshedRunningAlarmProperties() {
3119 updateRunningAlarmProperties();
3120 return getRunningAlarmProperties();
3123 public @Nullable String getMute() {
3124 return stateMap.get("MuteMaster");
3127 public @Nullable String getLed() {
3128 return stateMap.get("CurrentLEDState");
3131 public @Nullable String getCurrentZoneName() {
3132 return stateMap.get("CurrentZoneName");
3135 public @Nullable String getRefreshedCurrentZoneName() {
3136 updateCurrentZoneName();
3137 return getCurrentZoneName();
3141 public void onStatusChanged(boolean 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);
3149 logger.info("UPnP device {} is absent (thing {})", getUDN(), getThing().getUID());
3150 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR);
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);
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);
3175 private boolean isSupportedModel(String modelName) {
3176 for (ThingTypeUID thingTypeUID : SUPPORTED_KNOWN_THING_TYPES_UIDS) {
3177 if (thingTypeUID.getId().equalsIgnoreCase(modelName)) {
3184 private void updateSonosThingType(String newThingTypeID) {
3185 changeThingType(new ThingTypeUID(SonosBindingConstants.BINDING_ID, newThingTypeID), getConfig());
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
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())));
3200 protected void updateSleepTimerDuration() {
3201 executeAction(SERVICE_AV_TRANSPORT, ACTION_GET_REMAINING_SLEEP_TIMER_DURATION, null);
3204 private String sleepSecondsToTimeStr(long sleepSeconds) {
3205 if (sleepSeconds == 0) {
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);
3216 logger.debug("Sonos SleepTimer: Invalid sleep time set. sleep time must be >=0 and < 68400s (24h)");
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;