2 * Copyright (c) 2010-2020 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 Collection<String> SERVICE_SUBSCRIPTIONS = Arrays.asList("DeviceProperties", "AVTransport",
107 "ZoneGroupTopology", "GroupManagement", "RenderingControl", "AudioIn", "HTControl", "ContentDirectory");
108 protected static final int SUBSCRIPTION_DURATION = 1800;
110 private static final int SOCKET_TIMEOUT = 5000;
112 private static final int TUNEIN_DEFAULT_SERVICE_TYPE = 65031;
114 private final Logger logger = LoggerFactory.getLogger(ZonePlayerHandler.class);
116 private final ThingRegistry localThingRegistry;
117 private final UpnpIOService service;
118 private final @Nullable String opmlUrl;
119 private final SonosStateDescriptionOptionProvider stateDescriptionProvider;
121 private ZonePlayerConfiguration configuration = new ZonePlayerConfiguration();
124 * Intrinsic lock used to synchronize the execution of notification sounds
126 private final Object notificationLock = new Object();
127 private final Object upnpLock = new Object();
128 private final Object stateLock = new Object();
129 private final Object jobLock = new Object();
131 private final Map<String, @Nullable String> stateMap = Collections.synchronizedMap(new HashMap<>());
133 private @Nullable ScheduledFuture<?> pollingJob;
134 private @Nullable SonosZonePlayerState savedState;
136 private Map<String, @Nullable Boolean> subscriptionState = new HashMap<>();
139 * Thing handler instance of the coordinator speaker used for control delegation
141 private @Nullable ZonePlayerHandler coordinatorHandler;
143 private @Nullable List<SonosMusicService> musicServices;
145 private enum LineInType {
151 public ZonePlayerHandler(ThingRegistry thingRegistry, Thing thing, UpnpIOService upnpIOService,
152 @Nullable String opmlUrl, SonosStateDescriptionOptionProvider stateDescriptionProvider) {
154 this.localThingRegistry = thingRegistry;
155 this.opmlUrl = opmlUrl;
156 logger.debug("Creating a ZonePlayerHandler for thing '{}'", getThing().getUID());
157 this.service = upnpIOService;
158 this.stateDescriptionProvider = stateDescriptionProvider;
162 public void dispose() {
163 logger.debug("Handler disposed for thing {}", getThing().getUID());
165 ScheduledFuture<?> job = this.pollingJob;
169 this.pollingJob = null;
171 removeSubscription();
172 service.unregisterParticipant(this);
176 public void initialize() {
177 logger.debug("initializing handler for thing {}", getThing().getUID());
179 if (migrateThingType()) {
180 // we change the type, so we might need a different handler -> let's finish
184 configuration = getConfigAs(ZonePlayerConfiguration.class);
185 String udn = configuration.udn;
186 if (udn != null && !udn.isEmpty()) {
187 service.registerParticipant(this);
188 pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, configuration.refresh, TimeUnit.SECONDS);
190 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
191 "@text/offline.conf-error-missing-udn");
192 logger.debug("Cannot initalize the zoneplayer. UDN not set.");
196 private void poll() {
197 synchronized (jobLock) {
198 if (pollingJob == null) {
202 logger.debug("Polling job");
204 // First check if the Sonos zone is set in the UPnP service registry
205 // If not, set the thing state to OFFLINE and wait for the next poll
206 if (!isUpnpDeviceRegistered()) {
207 logger.debug("UPnP device {} not yet registered", getUDN());
208 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
209 "@text/offline.upnp-device-not-registered [\"" + getUDN() + "\"]");
210 synchronized (upnpLock) {
211 subscriptionState = new HashMap<>();
216 // Check if the Sonos zone can be joined
217 // If not, set the thing state to OFFLINE and do nothing else
219 if (getThing().getStatus() != ThingStatus.ONLINE) {
225 if (isLinked(ZONENAME)) {
226 updateCurrentZoneName();
231 // Action GetRemainingSleepTimerDuration is failing for a group slave member (error code 500)
232 if (isLinked(SLEEPTIMER) && isCoordinator()) {
233 updateSleepTimerDuration();
235 } catch (Exception e) {
236 logger.debug("Exception during poll: {}", e.getMessage(), e);
242 public void handleCommand(ChannelUID channelUID, Command command) {
243 if (command == RefreshType.REFRESH) {
244 updateChannel(channelUID.getId());
246 switch (channelUID.getId()) {
253 case NOTIFICATIONSOUND:
254 scheduleNotificationSound(command);
257 stopPlaying(command);
260 setVolumeForGroup(command);
266 removeMember(command);
269 becomeStandAlonePlayer();
272 publicAddress(LineInType.ANY);
274 case PUBLICANALOGADDRESS:
275 publicAddress(LineInType.ANALOG);
277 case PUBLICDIGITALADDRESS:
278 publicAddress(LineInType.DIGITAL);
283 case TUNEINSTATIONID:
284 playTuneinStation(command);
287 playFavorite(command);
293 snoozeAlarm(command);
296 saveAllPlayerState();
299 restoreAllPlayerState();
308 playPlayList(command);
327 if (command instanceof PlayPauseType) {
328 if (command == PlayPauseType.PLAY) {
329 getCoordinatorHandler().play();
330 } else if (command == PlayPauseType.PAUSE) {
331 getCoordinatorHandler().pause();
334 if (command instanceof NextPreviousType) {
335 if (command == NextPreviousType.NEXT) {
336 getCoordinatorHandler().next();
337 } else if (command == NextPreviousType.PREVIOUS) {
338 getCoordinatorHandler().previous();
341 // Rewind and Fast Forward are currently not implemented by the binding
342 } catch (IllegalStateException e) {
343 logger.debug("Cannot handle control command ({})", e.getMessage());
347 setSleepTimer(command);
356 setNightMode(command);
358 case SPEECHENHANCEMENT:
359 setSpeechEnhancement(command);
367 private void restoreAllPlayerState() {
368 for (Thing aThing : localThingRegistry.getAll()) {
369 if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) {
370 ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler();
371 if (handler != null) {
372 handler.restoreState();
378 private void saveAllPlayerState() {
379 for (Thing aThing : localThingRegistry.getAll()) {
380 if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) {
381 ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler();
382 if (handler != null) {
390 public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
391 if (variable == null || value == null || service == null) {
395 if (getThing().getStatus() == ThingStatus.ONLINE) {
396 logger.trace("Received pair '{}':'{}' (service '{}') for thing '{}'",
397 new Object[] { variable, value, service, this.getThing().getUID() });
399 String oldValue = this.stateMap.get(variable);
400 if (shouldIgnoreVariableUpdate(variable, value, oldValue)) {
404 this.stateMap.put(variable, value);
406 // pre-process some variables, eg XML processing
407 if (service.equals("AVTransport") && variable.equals("LastChange")) {
408 Map<String, @Nullable String> parsedValues = SonosXMLParser.getAVTransportFromXML(value);
409 for (String parsedValue : parsedValues.keySet()) {
410 // Update the transport state after the update of the media information
411 // to not break the notification mechanism
412 if (!parsedValue.equals("TransportState")) {
413 onValueReceived(parsedValue, parsedValues.get(parsedValue), "AVTransport");
415 // Translate AVTransportURI/AVTransportURIMetaData to CurrentURI/CurrentURIMetaData
416 // for a compatibility with the result of the action GetMediaInfo
417 if (parsedValue.equals("AVTransportURI")) {
418 onValueReceived("CurrentURI", parsedValues.get(parsedValue), service);
419 } else if (parsedValue.equals("AVTransportURIMetaData")) {
420 onValueReceived("CurrentURIMetaData", parsedValues.get(parsedValue), service);
423 updateMediaInformation();
424 if (parsedValues.get("TransportState") != null) {
425 onValueReceived("TransportState", parsedValues.get("TransportState"), "AVTransport");
429 if (service.equals("RenderingControl") && variable.equals("LastChange")) {
430 Map<String, @Nullable String> parsedValues = SonosXMLParser.getRenderingControlFromXML(value);
431 for (String parsedValue : parsedValues.keySet()) {
432 onValueReceived(parsedValue, parsedValues.get(parsedValue), "RenderingControl");
436 List<StateOption> options = new ArrayList<>();
438 // update the appropriate channel
440 case "TransportState":
441 updateChannel(STATE);
442 updateChannel(CONTROL);
444 dispatchOnAllGroupMembers(variable, value, service);
446 case "CurrentPlayMode":
447 updateChannel(SHUFFLE);
448 updateChannel(REPEAT);
449 dispatchOnAllGroupMembers(variable, value, service);
451 case "CurrentLEDState":
455 updateState(ZONENAME, new StringType(value));
457 case "CurrentZoneName":
458 updateChannel(ZONENAME);
460 case "ZoneGroupState":
461 updateChannel(COORDINATOR);
462 // Update coordinator after a change is made to the grouping of Sonos players
463 updateGroupCoordinator();
464 updateMediaInformation();
465 // Update state and control channels for the group members with the coordinator values
466 String transportState = getTransportState();
467 if (transportState != null) {
468 dispatchOnAllGroupMembers("TransportState", transportState, "AVTransport");
470 // Update shuffle and repeat channels for the group members with the coordinator values
471 String playMode = getPlayMode();
472 if (playMode != null) {
473 dispatchOnAllGroupMembers("CurrentPlayMode", playMode, "AVTransport");
476 case "LocalGroupUUID":
477 updateChannel(ZONEGROUPID);
479 case "GroupCoordinatorIsLocal":
480 updateChannel(LOCALCOORDINATOR);
483 updateChannel(VOLUME);
489 updateChannel(NIGHTMODE);
492 updateChannel(SPEECHENHANCEMENT);
494 case LINEINCONNECTED:
495 if (SonosBindingConstants.WITH_LINEIN_THING_TYPES_UIDS.contains(getThing().getThingTypeUID())) {
496 updateChannel(LINEIN);
498 if (SonosBindingConstants.WITH_ANALOG_LINEIN_THING_TYPES_UIDS
499 .contains(getThing().getThingTypeUID())) {
500 updateChannel(ANALOGLINEIN);
503 case TOSLINEINCONNECTED:
504 if (SonosBindingConstants.WITH_LINEIN_THING_TYPES_UIDS.contains(getThing().getThingTypeUID())) {
505 updateChannel(LINEIN);
507 if (SonosBindingConstants.WITH_DIGITAL_LINEIN_THING_TYPES_UIDS
508 .contains(getThing().getThingTypeUID())) {
509 updateChannel(DIGITALLINEIN);
513 updateChannel(ALARMRUNNING);
514 updateRunningAlarmProperties();
516 case "RunningAlarmProperties":
517 updateChannel(ALARMPROPERTIES);
519 case "CurrentURIFormatted":
520 updateChannel(CURRENTTRACK);
523 updateChannel(CURRENTTITLE);
525 case "CurrentArtist":
526 updateChannel(CURRENTARTIST);
529 updateChannel(CURRENTALBUM);
532 updateChannel(CURRENTTRANSPORTURI);
534 case "CurrentTrackURI":
535 updateChannel(CURRENTTRACKURI);
537 case "CurrentAlbumArtURI":
538 updateChannel(CURRENTALBUMARTURL);
540 case "CurrentSleepTimerGeneration":
541 if (value.equals("0")) {
542 updateState(SLEEPTIMER, new DecimalType(0));
545 case "SleepTimerGeneration":
546 if (value.equals("0")) {
547 updateState(SLEEPTIMER, new DecimalType(0));
549 updateSleepTimerDuration();
552 case "RemainingSleepTimerDuration":
553 updateState(SLEEPTIMER, new DecimalType(sleepStrTimeToSeconds(value)));
555 case "CurrentTuneInStationId":
556 updateChannel(TUNEINSTATIONID);
558 case "SavedQueuesUpdateID": // service ContentDirectoy
559 for (SonosEntry entry : getPlayLists()) {
560 options.add(new StateOption(entry.getTitle(), entry.getTitle()));
562 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), PLAYLIST), options);
564 case "FavoritesUpdateID": // service ContentDirectoy
565 for (SonosEntry entry : getFavorites()) {
566 options.add(new StateOption(entry.getTitle(), entry.getTitle()));
568 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), FAVORITE), options);
570 // For favorite radios, we should have checked the state variable named RadioFavoritesUpdateID
571 // Due to a bug in the data type definition of this state variable, it is not set.
572 // As a workaround, we check the state variable named ContainerUpdateIDs.
573 case "ContainerUpdateIDs": // service ContentDirectoy
574 if (value.startsWith("R:0,") || stateDescriptionProvider
575 .getStateOptions(new ChannelUID(getThing().getUID(), RADIO)) == null) {
576 for (SonosEntry entry : getFavoriteRadios()) {
577 options.add(new StateOption(entry.getTitle(), entry.getTitle()));
579 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), RADIO), options);
588 private void dispatchOnAllGroupMembers(String variable, String value, String service) {
589 if (isCoordinator()) {
590 for (String member : getOtherZoneGroupMembers()) {
592 ZonePlayerHandler memberHandler = getHandlerByName(member);
593 if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) {
594 memberHandler.onValueReceived(variable, value, service);
596 } catch (IllegalStateException e) {
597 logger.debug("Cannot update channel for group member ({})", e.getMessage());
603 private @Nullable String getAlbumArtUrl() {
605 String albumArtURI = stateMap.get("CurrentAlbumArtURI");
606 if (albumArtURI != null) {
607 if (albumArtURI.startsWith("http")) {
609 } else if (albumArtURI.startsWith("/")) {
611 URL serviceDescrUrl = service.getDescriptorURL(this);
612 if (serviceDescrUrl != null) {
613 url = new URL(serviceDescrUrl.getProtocol(), serviceDescrUrl.getHost(),
614 serviceDescrUrl.getPort(), albumArtURI).toExternalForm();
616 } catch (MalformedURLException e) {
617 logger.debug("Failed to build a valid album art URL from {}: {}", albumArtURI, e.getMessage());
624 protected void updateChannel(String channelId) {
625 if (!isLinked(channelId)) {
631 State newState = UnDefType.UNDEF;
635 value = getTransportState();
637 newState = new StringType(value);
641 value = getTransportState();
642 if (STATE_PLAYING.equals(value)) {
643 newState = PlayPauseType.PLAY;
644 } else if (STATE_STOPPED.equals(value)) {
645 newState = PlayPauseType.PAUSE;
646 } else if (STATE_PAUSED_PLAYBACK.equals(value)) {
647 newState = PlayPauseType.PAUSE;
651 value = getTransportState();
653 newState = STATE_STOPPED.equals(value) ? OnOffType.ON : OnOffType.OFF;
657 if (getPlayMode() != null) {
658 newState = isShuffleActive() ? OnOffType.ON : OnOffType.OFF;
662 if (getPlayMode() != null) {
663 newState = new StringType(getRepeatMode());
667 if (getLed() != null) {
668 newState = isLedOn() ? OnOffType.ON : OnOffType.OFF;
672 value = getCurrentZoneName();
674 newState = new StringType(value);
678 value = getZoneGroupID();
680 newState = new StringType(value);
684 newState = new StringType(getCoordinator());
686 case LOCALCOORDINATOR:
687 if (getGroupCoordinatorIsLocal() != null) {
688 newState = isGroupCoordinator() ? OnOffType.ON : OnOffType.OFF;
694 newState = new PercentType(value);
700 newState = isMuted() ? OnOffType.ON : OnOffType.OFF;
704 value = getNightMode();
706 newState = isNightModeOn() ? OnOffType.ON : OnOffType.OFF;
709 case SPEECHENHANCEMENT:
710 value = getDialogLevel();
712 newState = isSpeechEnhanced() ? OnOffType.ON : OnOffType.OFF;
716 if (getAnalogLineInConnected() != null) {
717 newState = isAnalogLineInConnected() ? OnOffType.ON : OnOffType.OFF;
718 } else if (getOpticalLineInConnected() != null) {
719 newState = isOpticalLineInConnected() ? OnOffType.ON : OnOffType.OFF;
723 if (getAnalogLineInConnected() != null) {
724 newState = isAnalogLineInConnected() ? OnOffType.ON : OnOffType.OFF;
728 if (getOpticalLineInConnected() != null) {
729 newState = isOpticalLineInConnected() ? OnOffType.ON : OnOffType.OFF;
733 if (getAlarmRunning() != null) {
734 newState = isAlarmRunning() ? OnOffType.ON : OnOffType.OFF;
737 case ALARMPROPERTIES:
738 value = getRunningAlarmProperties();
740 newState = new StringType(value);
744 value = stateMap.get("CurrentURIFormatted");
746 newState = new StringType(value);
750 value = getCurrentTitle();
752 newState = new StringType(value);
756 value = getCurrentArtist();
758 newState = new StringType(value);
762 value = getCurrentAlbum();
764 newState = new StringType(value);
767 case CURRENTALBUMART:
769 updateAlbumArtChannel(false);
771 case CURRENTALBUMARTURL:
772 url = getAlbumArtUrl();
774 newState = new StringType(url);
777 case CURRENTTRANSPORTURI:
778 value = getCurrentURI();
780 newState = new StringType(value);
783 case CURRENTTRACKURI:
784 value = stateMap.get("CurrentTrackURI");
786 newState = new StringType(value);
789 case TUNEINSTATIONID:
790 value = stateMap.get("CurrentTuneInStationId");
792 newState = new StringType(value);
799 if (newState != null) {
800 updateState(channelId, newState);
804 private void updateAlbumArtChannel(boolean allGroup) {
805 String url = getAlbumArtUrl();
807 // We download the cover art in a different thread to not delay the other operations
808 scheduler.submit(() -> {
809 RawType image = HttpUtil.downloadImage(url, true, 500000);
810 updateChannel(CURRENTALBUMART, image != null ? image : UnDefType.UNDEF, allGroup);
813 updateChannel(CURRENTALBUMART, UnDefType.UNDEF, allGroup);
817 private void updateChannel(String channeldD, State state, boolean allGroup) {
819 for (String member : getZoneGroupMembers()) {
821 ZonePlayerHandler memberHandler = getHandlerByName(member);
822 if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())
823 && memberHandler.isLinked(channeldD)) {
824 memberHandler.updateState(channeldD, state);
826 } catch (IllegalStateException e) {
827 logger.debug("Cannot update channel for group member ({})", e.getMessage());
830 } else if (ThingStatus.ONLINE.equals(getThing().getStatus()) && isLinked(channeldD)) {
831 updateState(channeldD, state);
836 * CurrentURI will not change, but will trigger change of CurrentURIFormated
837 * CurrentTrackMetaData will not change, but will trigger change of Title, Artist, Album
839 private boolean shouldIgnoreVariableUpdate(String variable, String value, @Nullable String oldValue) {
840 return !hasValueChanged(value, oldValue) && !isQueueEvent(variable);
843 private boolean hasValueChanged(@Nullable String value, @Nullable String oldValue) {
844 return oldValue != null ? !oldValue.equals(value) : value != null;
848 * Similar to the AVTransport eventing, the Queue events its state variables
849 * as sub values within a synthesized LastChange state variable.
851 private boolean isQueueEvent(String variable) {
852 return "LastChange".equals(variable);
855 private void updateGroupCoordinator() {
857 coordinatorHandler = getHandlerByName(getCoordinator());
858 } catch (IllegalStateException e) {
859 logger.debug("Cannot update the group coordinator ({})", e.getMessage());
860 coordinatorHandler = null;
864 private boolean isUpnpDeviceRegistered() {
865 return service.isRegistered(this);
868 private void addSubscription() {
869 synchronized (upnpLock) {
870 // Set up GENA Subscriptions
871 if (service.isRegistered(this)) {
872 for (String subscription : SERVICE_SUBSCRIPTIONS) {
873 Boolean state = subscriptionState.get(subscription);
874 if (state == null || !state) {
875 logger.debug("{}: Subscribing to service {}...", getUDN(), subscription);
876 service.addSubscription(this, subscription, SUBSCRIPTION_DURATION);
877 subscriptionState.put(subscription, true);
884 private void removeSubscription() {
885 synchronized (upnpLock) {
886 // Set up GENA Subscriptions
887 if (service.isRegistered(this)) {
888 for (String subscription : SERVICE_SUBSCRIPTIONS) {
889 Boolean state = subscriptionState.get(subscription);
890 if (state != null && state) {
891 logger.debug("{}: Unsubscribing from service {}...", getUDN(), subscription);
892 service.removeSubscription(this, subscription);
896 subscriptionState = new HashMap<>();
901 public void onServiceSubscribed(@Nullable String service, boolean succeeded) {
902 if (service == null) {
905 synchronized (upnpLock) {
906 logger.debug("{}: Subscription to service {} {}", getUDN(), service, succeeded ? "succeeded" : "failed");
907 subscriptionState.put(service, succeeded);
911 private void updatePlayerState() {
912 if (!updateZoneInfo()) {
913 if (!ThingStatus.OFFLINE.equals(getThing().getStatus())) {
914 logger.debug("Sonos player {} is not available in local network", getUDN());
915 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
916 "@text/offline.not-available-on-network [\"" + getUDN() + "\"]");
917 synchronized (upnpLock) {
918 subscriptionState = new HashMap<>();
921 } else if (!ThingStatus.ONLINE.equals(getThing().getStatus())) {
922 logger.debug("Sonos player {} has been found in local network", getUDN());
923 updateStatus(ThingStatus.ONLINE);
927 protected void updateCurrentZoneName() {
928 Map<String, String> result = service.invokeAction(this, "DeviceProperties", "GetZoneAttributes", null);
930 for (String variable : result.keySet()) {
931 this.onValueReceived(variable, result.get(variable), "DeviceProperties");
935 protected void updateLed() {
936 Map<String, String> result = service.invokeAction(this, "DeviceProperties", "GetLEDState", null);
938 for (String variable : result.keySet()) {
939 this.onValueReceived(variable, result.get(variable), "DeviceProperties");
943 protected void updateTime() {
944 Map<String, String> result = service.invokeAction(this, "AlarmClock", "GetTimeNow", null);
946 for (String variable : result.keySet()) {
947 this.onValueReceived(variable, result.get(variable), "AlarmClock");
951 protected void updatePosition() {
952 Map<String, String> result = service.invokeAction(this, "AVTransport", "GetPositionInfo", null);
954 for (String variable : result.keySet()) {
955 this.onValueReceived(variable, result.get(variable), "AVTransport");
959 protected void updateRunningAlarmProperties() {
960 Map<String, @Nullable String> result = service.invokeAction(this, "AVTransport", "GetRunningAlarmProperties",
963 String alarmID = result.get("AlarmID");
964 String loggedStartTime = result.get("LoggedStartTime");
965 String newStringValue = null;
966 if (alarmID != null && loggedStartTime != null) {
967 newStringValue = alarmID + " - " + loggedStartTime;
969 newStringValue = "No running alarm";
971 result.put("RunningAlarmProperties", newStringValue);
973 for (String variable : result.keySet()) {
974 this.onValueReceived(variable, result.get(variable), "AVTransport");
978 protected boolean updateZoneInfo() {
979 Map<String, String> result = service.invokeAction(this, "DeviceProperties", "GetZoneInfo", null);
980 for (String variable : result.keySet()) {
981 this.onValueReceived(variable, result.get(variable), "DeviceProperties");
984 Map<String, String> properties = editProperties();
985 String value = stateMap.get("HardwareVersion");
986 if (value != null && !value.isEmpty()) {
987 properties.put(Thing.PROPERTY_HARDWARE_VERSION, value);
989 value = stateMap.get("DisplaySoftwareVersion");
990 if (value != null && !value.isEmpty()) {
991 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, value);
993 value = stateMap.get("SerialNumber");
994 if (value != null && !value.isEmpty()) {
995 properties.put(Thing.PROPERTY_SERIAL_NUMBER, value);
997 value = stateMap.get("MACAddress");
998 if (value != null && !value.isEmpty()) {
999 properties.put(MAC_ADDRESS, value);
1001 value = stateMap.get("IPAddress");
1002 if (value != null && !value.isEmpty()) {
1003 properties.put(IP_ADDRESS, value);
1005 updateProperties(properties);
1007 return !result.isEmpty();
1010 public String getCoordinator() {
1011 for (SonosZoneGroup zg : getZoneGroups()) {
1012 if (zg.getMembers().contains(getUDN())) {
1013 return zg.getCoordinator();
1019 public boolean isCoordinator() {
1020 return getUDN().equals(getCoordinator());
1023 protected void updateMediaInformation() {
1024 String currentURI = getCurrentURI();
1025 SonosMetaData currentTrack = getTrackMetadata();
1026 SonosMetaData currentUriMetaData = getCurrentURIMetadata();
1028 String artist = null;
1029 String album = null;
1030 String title = null;
1031 String resultString = null;
1032 String stationID = null;
1033 boolean needsUpdating = false;
1035 // if currentURI == null, we do nothing
1036 if (currentURI != null) {
1037 if (currentURI.isEmpty()) {
1039 needsUpdating = true;
1042 // if (currentURI.contains(GROUP_URI)) we do nothing, because
1043 // The Sonos is a slave member of a group
1044 // The media information will be updated by the coordinator
1045 // Notification of group change occurs later, so we just check the URI
1047 else if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)) {
1048 // Radio stream (tune-in)
1049 boolean opmlUrlSucceeded = false;
1050 stationID = extractStationId(currentURI);
1051 String url = opmlUrl;
1053 String mac = getMACAddress();
1054 if (stationID != null && !stationID.isEmpty() && mac != null && !mac.isEmpty()) {
1055 url = url.replace("%id", stationID);
1056 url = url.replace("%serial", mac);
1058 String response = null;
1060 response = HttpUtil.executeUrl("GET", url, SOCKET_TIMEOUT);
1061 } catch (IOException e) {
1062 logger.debug("Request to device failed", e);
1065 if (response != null) {
1066 List<String> fields = SonosXMLParser.getRadioTimeFromXML(response);
1068 if (!fields.isEmpty()) {
1069 opmlUrlSucceeded = true;
1072 for (String field : fields) {
1073 if (resultString.isEmpty()) {
1074 // radio name should be first field
1077 resultString += " - ";
1079 resultString += field;
1082 needsUpdating = true;
1087 if (!opmlUrlSucceeded) {
1088 if (currentUriMetaData != null) {
1089 title = currentUriMetaData.getTitle();
1090 if (currentTrack == null || currentTrack.getStreamContent().isEmpty()) {
1091 resultString = title;
1093 resultString = title + " - " + currentTrack.getStreamContent();
1095 needsUpdating = true;
1100 else if (isPlayingLineIn(currentURI)) {
1101 if (currentTrack != null) {
1102 title = currentTrack.getTitle();
1103 resultString = title;
1104 needsUpdating = true;
1108 else if (isPlayingRadio(currentURI)
1109 || (!currentURI.contains("x-rincon-mp3") && !currentURI.contains("x-sonosapi"))) {
1110 // isPlayingRadio(currentURI) is true for Google Play Music radio or Apple Music radio
1111 if (currentTrack != null) {
1112 artist = !currentTrack.getAlbumArtist().isEmpty() ? currentTrack.getAlbumArtist()
1113 : currentTrack.getCreator();
1114 album = currentTrack.getAlbum();
1115 title = currentTrack.getTitle();
1116 resultString = artist + " - " + album + " - " + title;
1117 needsUpdating = true;
1122 String albumArtURI = (currentTrack != null && !currentTrack.getAlbumArtUri().isEmpty())
1123 ? currentTrack.getAlbumArtUri()
1126 ZonePlayerHandler handlerForImageUpdate = null;
1127 for (String member : getZoneGroupMembers()) {
1129 ZonePlayerHandler memberHandler = getHandlerByName(member);
1130 if (ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) {
1131 if (memberHandler.isLinked(CURRENTALBUMART)
1132 && hasValueChanged(albumArtURI, memberHandler.stateMap.get("CurrentAlbumArtURI"))) {
1133 handlerForImageUpdate = memberHandler;
1135 memberHandler.onValueReceived("CurrentTuneInStationId", (stationID != null) ? stationID : "",
1137 if (needsUpdating) {
1138 memberHandler.onValueReceived("CurrentArtist", (artist != null) ? artist : "", "AVTransport");
1139 memberHandler.onValueReceived("CurrentAlbum", (album != null) ? album : "", "AVTransport");
1140 memberHandler.onValueReceived("CurrentTitle", (title != null) ? title : "", "AVTransport");
1141 memberHandler.onValueReceived("CurrentURIFormatted", (resultString != null) ? resultString : "",
1143 memberHandler.onValueReceived("CurrentAlbumArtURI", albumArtURI, "AVTransport");
1146 } catch (IllegalStateException e) {
1147 logger.debug("Cannot update media data for group member ({})", e.getMessage());
1150 if (needsUpdating && handlerForImageUpdate != null) {
1151 handlerForImageUpdate.updateAlbumArtChannel(true);
1155 private @Nullable String extractStationId(String uri) {
1156 String stationID = null;
1157 if (isPlayingStream(uri)) {
1158 stationID = substringBetween(uri, ":s", "?sid");
1159 } else if (isPlayingRadioStartedByAmazonEcho(uri)) {
1160 stationID = substringBetween(uri, "sid=s", "&");
1165 private @Nullable String substringBetween(String str, String open, String close) {
1166 String result = null;
1167 int idx1 = str.indexOf(open);
1169 idx1 += open.length();
1170 int idx2 = str.indexOf(close, idx1);
1172 result = str.substring(idx1, idx2);
1178 public @Nullable String getGroupCoordinatorIsLocal() {
1179 return stateMap.get("GroupCoordinatorIsLocal");
1182 public boolean isGroupCoordinator() {
1183 return "true".equals(getGroupCoordinatorIsLocal());
1187 public String getUDN() {
1188 String udn = configuration.udn;
1189 return udn != null && !udn.isEmpty() ? udn : "undefined";
1192 public @Nullable String getCurrentURI() {
1193 return stateMap.get("CurrentURI");
1196 public @Nullable String getCurrentURIMetadataAsString() {
1197 return stateMap.get("CurrentURIMetaData");
1200 public @Nullable SonosMetaData getCurrentURIMetadata() {
1201 String metaData = getCurrentURIMetadataAsString();
1202 return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1205 public @Nullable SonosMetaData getTrackMetadata() {
1206 String metaData = stateMap.get("CurrentTrackMetaData");
1207 return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1210 public @Nullable SonosMetaData getEnqueuedTransportURIMetaData() {
1211 String metaData = stateMap.get("EnqueuedTransportURIMetaData");
1212 return metaData != null && !metaData.isEmpty() ? SonosXMLParser.getMetaDataFromXML(metaData) : null;
1215 public @Nullable String getMACAddress() {
1216 String mac = stateMap.get("MACAddress");
1217 if (mac == null || mac.isEmpty()) {
1220 return stateMap.get("MACAddress");
1223 public @Nullable String getRefreshedPosition() {
1225 return stateMap.get("RelTime");
1228 public long getRefreshedCurrenTrackNr() {
1230 String value = stateMap.get("Track");
1231 if (value != null) {
1232 return Long.valueOf(value);
1238 public @Nullable String getVolume() {
1239 return stateMap.get("VolumeMaster");
1242 public @Nullable String getTransportState() {
1243 return stateMap.get("TransportState");
1246 public @Nullable String getCurrentTitle() {
1247 return stateMap.get("CurrentTitle");
1250 public @Nullable String getCurrentArtist() {
1251 return stateMap.get("CurrentArtist");
1254 public @Nullable String getCurrentAlbum() {
1255 return stateMap.get("CurrentAlbum");
1258 public List<SonosEntry> getArtists(String filter) {
1259 return getEntries("A:", filter);
1262 public List<SonosEntry> getArtists() {
1263 return getEntries("A:", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1266 public List<SonosEntry> getAlbums(String filter) {
1267 return getEntries("A:ALBUM", filter);
1270 public List<SonosEntry> getAlbums() {
1271 return getEntries("A:ALBUM", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1274 public List<SonosEntry> getTracks(String filter) {
1275 return getEntries("A:TRACKS", filter);
1278 public List<SonosEntry> getTracks() {
1279 return getEntries("A:TRACKS", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1282 public List<SonosEntry> getQueue(String filter) {
1283 return getEntries("Q:0", filter);
1286 public List<SonosEntry> getQueue() {
1287 return getEntries("Q:0", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1290 public long getQueueSize() {
1291 return getNbEntries("Q:0");
1294 public List<SonosEntry> getPlayLists(String filter) {
1295 return getEntries("SQ:", filter);
1298 public List<SonosEntry> getPlayLists() {
1299 return getEntries("SQ:", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1302 public List<SonosEntry> getFavoriteRadios(String filter) {
1303 return getEntries("R:0/0", filter);
1306 public List<SonosEntry> getFavoriteRadios() {
1307 return getEntries("R:0/0", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1311 * Searches for entries in the 'favorites' list on a sonos account
1315 public List<SonosEntry> getFavorites() {
1316 return getEntries("FV:2", "dc:title,res,dc:creator,upnp:artist,upnp:album");
1319 protected List<SonosEntry> getEntries(String type, String filter) {
1322 Map<String, String> inputs = new HashMap<>();
1323 inputs.put("ObjectID", type);
1324 inputs.put("BrowseFlag", "BrowseDirectChildren");
1325 inputs.put("Filter", filter);
1326 inputs.put("StartingIndex", Long.toString(startAt));
1327 inputs.put("RequestedCount", Integer.toString(200));
1328 inputs.put("SortCriteria", "");
1330 Map<String, @Nullable String> result = service.invokeAction(this, "ContentDirectory", "Browse", inputs);
1332 String initialResult = result.get("Result");
1333 if (initialResult == null) {
1334 return Collections.emptyList();
1337 long totalMatches = getResultEntry(result, "TotalMatches", type, filter);
1338 long initialNumberReturned = getResultEntry(result, "NumberReturned", type, filter);
1340 List<SonosEntry> resultList = SonosXMLParser.getEntriesFromString(initialResult);
1341 startAt = startAt + initialNumberReturned;
1343 while (startAt < totalMatches) {
1344 inputs.put("StartingIndex", Long.toString(startAt));
1345 result = service.invokeAction(this, "ContentDirectory", "Browse", inputs);
1347 // Execute this action synchronously
1348 String nextResult = result.get("Result");
1349 if (nextResult == null) {
1353 long numberReturned = getResultEntry(result, "NumberReturned", type, filter);
1355 resultList.addAll(SonosXMLParser.getEntriesFromString(nextResult));
1357 startAt = startAt + numberReturned;
1363 protected long getNbEntries(String type) {
1364 Map<String, String> inputs = new HashMap<>();
1365 inputs.put("ObjectID", type);
1366 inputs.put("BrowseFlag", "BrowseDirectChildren");
1367 inputs.put("Filter", "dc:title");
1368 inputs.put("StartingIndex", "0");
1369 inputs.put("RequestedCount", "1");
1370 inputs.put("SortCriteria", "");
1372 Map<String, @Nullable String> result = service.invokeAction(this, "ContentDirectory", "Browse", inputs);
1374 return getResultEntry(result, "TotalMatches", type, "dc:title");
1378 * Handles value searching in a SONOS result map (called by {@link #getEntries(String, String)})
1380 * @param resultInput - the map to be examined for the requestedKey
1381 * @param requestedKey - the key to be sought in the resultInput map
1382 * @param entriesType - the 'type' argument of {@link #getEntries(String, String)} method used for logging
1383 * @param entriesFilter - the 'filter' argument of {@link #getEntries(String, String)} method used for logging
1385 * @return 0 as long or the value corresponding to the requiredKey if found
1387 private Long getResultEntry(Map<String, @Nullable String> resultInput, String requestedKey, String entriesType,
1388 String entriesFilter) {
1391 if (resultInput.isEmpty()) {
1396 result = Long.valueOf(resultInput.get(requestedKey));
1397 } catch (NumberFormatException ex) {
1398 logger.debug("Could not fetch {} result for type: {} and filter: {}. Using default value '0': {}",
1399 requestedKey, entriesType, entriesFilter, ex.getMessage(), ex);
1406 * Save the state (track, position etc) of the Sonos Zone player.
1408 * @return true if no error occurred.
1410 protected void saveState() {
1411 synchronized (stateLock) {
1412 savedState = new SonosZonePlayerState();
1413 String currentURI = getCurrentURI();
1415 savedState.transportState = getTransportState();
1416 savedState.volume = getVolume();
1418 if (currentURI != null) {
1419 if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)
1420 || isPlayingRadio(currentURI)) {
1421 // we are streaming music, like tune-in radio or Google Play Music radio
1422 SonosMetaData track = getTrackMetadata();
1423 SonosMetaData current = getCurrentURIMetadata();
1424 if (track != null && current != null) {
1425 savedState.entry = new SonosEntry("", current.getTitle(), "", "", track.getAlbumArtUri(), "",
1426 current.getUpnpClass(), currentURI);
1428 } else if (currentURI.contains(GROUP_URI)) {
1429 // we are a slave to some coordinator
1430 savedState.entry = new SonosEntry("", "", "", "", "", "", "", currentURI);
1431 } else if (isPlayingLineIn(currentURI)) {
1432 // we are streaming from the Line In connection
1433 savedState.entry = new SonosEntry("", "", "", "", "", "", "", currentURI);
1434 } else if (isPlayingQueue(currentURI)) {
1435 // we are playing something that sits in the queue
1436 SonosMetaData queued = getEnqueuedTransportURIMetaData();
1437 if (queued != null) {
1438 savedState.track = getRefreshedCurrenTrackNr();
1440 if (queued.getUpnpClass().contains("object.container.playlistContainer")) {
1441 // we are playing a real 'saved' playlist
1442 List<SonosEntry> playLists = getPlayLists();
1443 for (SonosEntry someList : playLists) {
1444 if (someList.getTitle().equals(queued.getTitle())) {
1445 savedState.entry = new SonosEntry(someList.getId(), someList.getTitle(),
1446 someList.getParentId(), "", "", "", someList.getUpnpClass(),
1451 } else if (queued.getUpnpClass().contains("object.container")) {
1452 // we are playing some other sort of
1453 // 'container' - we will save that to a
1454 // playlist for our convenience
1455 logger.debug("Save State for a container of type {}", queued.getUpnpClass());
1457 // save the playlist
1458 String existingList = "";
1459 List<SonosEntry> playLists = getPlayLists();
1460 for (SonosEntry someList : playLists) {
1461 if (someList.getTitle().equals(ESH_PREFIX + getUDN())) {
1462 existingList = someList.getId();
1467 saveQueue(ESH_PREFIX + getUDN(), existingList);
1469 // get all the playlists and a ref to our
1471 playLists = getPlayLists();
1472 for (SonosEntry someList : playLists) {
1473 if (someList.getTitle().equals(ESH_PREFIX + getUDN())) {
1474 savedState.entry = new SonosEntry(someList.getId(), someList.getTitle(),
1475 someList.getParentId(), "", "", "", someList.getUpnpClass(),
1482 savedState.entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + getUDN() + "#0");
1486 savedState.relTime = getRefreshedPosition();
1488 savedState.entry = null;
1494 * Restore the state (track, position etc) of the Sonos Zone player.
1496 * @return true if no error occurred.
1498 protected void restoreState() {
1499 synchronized (stateLock) {
1500 SonosZonePlayerState state = savedState;
1501 if (state != null) {
1502 // put settings back
1503 String volume = state.volume;
1504 if (volume != null) {
1505 setVolume(DecimalType.valueOf(volume));
1508 if (isCoordinator()) {
1509 SonosEntry entry = state.entry;
1510 if (entry != null) {
1511 // check if we have a playlist to deal with
1512 if (entry.getUpnpClass().contains("object.container.playlistContainer")) {
1513 addURIToQueue(entry.getRes(), SonosXMLParser.compileMetadataString(entry), 0, true);
1514 entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + getUDN() + "#0");
1515 setCurrentURI(entry);
1516 setPositionTrack(state.track);
1518 setCurrentURI(entry);
1519 setPosition(state.relTime);
1523 String transportState = state.transportState;
1524 if (transportState != null) {
1525 if (transportState.equals(STATE_PLAYING)) {
1527 } else if (transportState.equals(STATE_STOPPED)) {
1529 } else if (transportState.equals(STATE_PAUSED_PLAYBACK)) {
1538 public void saveQueue(String name, String queueID) {
1539 Map<String, String> inputs = new HashMap<>();
1540 inputs.put("Title", name);
1541 inputs.put("ObjectID", queueID);
1543 Map<String, String> result = service.invokeAction(this, "AVTransport", "SaveQueue", inputs);
1545 for (String variable : result.keySet()) {
1546 this.onValueReceived(variable, result.get(variable), "AVTransport");
1550 public void setVolume(Command command) {
1551 if (command instanceof OnOffType || command instanceof IncreaseDecreaseType || command instanceof DecimalType
1552 || command instanceof PercentType) {
1553 Map<String, String> inputs = new HashMap<>();
1555 String newValue = null;
1556 String currentVolume = getVolume();
1557 if (command == IncreaseDecreaseType.INCREASE && currentVolume != null) {
1558 int i = Integer.valueOf(currentVolume);
1559 newValue = String.valueOf(Math.min(100, i + 1));
1560 } else if (command == IncreaseDecreaseType.DECREASE && currentVolume != null) {
1561 int i = Integer.valueOf(currentVolume);
1562 newValue = String.valueOf(Math.max(0, i - 1));
1563 } else if (command == OnOffType.ON) {
1565 } else if (command == OnOffType.OFF) {
1567 } else if (command instanceof DecimalType) {
1568 newValue = String.valueOf(((DecimalType) command).intValue());
1572 inputs.put("Channel", "Master");
1573 inputs.put("DesiredVolume", newValue);
1575 Map<String, String> result = service.invokeAction(this, "RenderingControl", "SetVolume", inputs);
1577 for (String variable : result.keySet()) {
1578 this.onValueReceived(variable, result.get(variable), "RenderingControl");
1584 * Set the VOLUME command specific to the current grouping according to the Sonos behaviour.
1585 * AdHoc groups handles the volume specifically for each player.
1586 * Bonded groups delegate the volume to the coordinator which applies the same level to all group members.
1588 public void setVolumeForGroup(Command command) {
1589 if (isAdHocGroup() || isStandalonePlayer()) {
1593 getCoordinatorHandler().setVolume(command);
1594 } catch (IllegalStateException e) {
1595 logger.debug("Cannot set group volume ({})", e.getMessage());
1601 * Checks if the player receiving the command is part of a group that
1602 * consists of randomly added players or contains bonded players
1606 private boolean isAdHocGroup() {
1607 SonosZoneGroup currentZoneGroup = getCurrentZoneGroup();
1608 if (currentZoneGroup != null) {
1609 List<String> zoneGroupMemberNames = currentZoneGroup.getMemberZoneNames();
1611 for (String zoneName : zoneGroupMemberNames) {
1612 if (!zoneName.equals(zoneGroupMemberNames.get(0))) {
1613 // At least one "ZoneName" differs so we have an AdHoc group
1622 * Checks if the player receiving the command is a standalone player
1626 private boolean isStandalonePlayer() {
1627 SonosZoneGroup zoneGroup = getCurrentZoneGroup();
1628 return zoneGroup == null || zoneGroup.getMembers().size() == 1;
1631 private Collection<SonosZoneGroup> getZoneGroups() {
1632 String zoneGroupState = stateMap.get("ZoneGroupState");
1633 return zoneGroupState == null ? Collections.emptyList() : SonosXMLParser.getZoneGroupFromXML(zoneGroupState);
1637 * Returns the current zone group
1638 * (of which the player receiving the command is part)
1640 * @return {@link SonosZoneGroup}
1642 private @Nullable SonosZoneGroup getCurrentZoneGroup() {
1643 for (SonosZoneGroup zoneGroup : getZoneGroups()) {
1644 if (zoneGroup.getMembers().contains(getUDN())) {
1648 logger.debug("Could not fetch Sonos group state information");
1653 * Sets the volume level for a notification sound
1655 * @param notificationSoundVolume
1657 public void setNotificationSoundVolume(@Nullable PercentType notificationSoundVolume) {
1658 if (notificationSoundVolume != null) {
1659 setVolumeForGroup(notificationSoundVolume);
1664 * Gets the volume level for a notification sound
1666 public @Nullable PercentType getNotificationSoundVolume() {
1667 Integer notificationSoundVolume = getConfigAs(ZonePlayerConfiguration.class).notificationVolume;
1668 if (notificationSoundVolume == null) {
1669 // if no value is set we use the current volume instead
1670 String volume = getVolume();
1671 return volume != null ? new PercentType(volume) : null;
1673 return new PercentType(notificationSoundVolume);
1676 public void addURIToQueue(String URI, String meta, long desiredFirstTrack, boolean enqueueAsNext) {
1677 Map<String, String> inputs = new HashMap<>();
1680 inputs.put("InstanceID", "0");
1681 inputs.put("EnqueuedURI", URI);
1682 inputs.put("EnqueuedURIMetaData", meta);
1683 inputs.put("DesiredFirstTrackNumberEnqueued", Long.toString(desiredFirstTrack));
1684 inputs.put("EnqueueAsNext", Boolean.toString(enqueueAsNext));
1685 } catch (NumberFormatException ex) {
1686 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
1689 Map<String, String> result = service.invokeAction(this, "AVTransport", "AddURIToQueue", inputs);
1691 for (String variable : result.keySet()) {
1692 this.onValueReceived(variable, result.get(variable), "AVTransport");
1696 public void setCurrentURI(SonosEntry newEntry) {
1697 setCurrentURI(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry));
1700 public void setCurrentURI(@Nullable String URI, @Nullable String URIMetaData) {
1701 if (URI != null && URIMetaData != null) {
1702 logger.debug("setCurrentURI URI {} URIMetaData {}", URI, URIMetaData);
1703 Map<String, String> inputs = new HashMap<>();
1706 inputs.put("InstanceID", "0");
1707 inputs.put("CurrentURI", URI);
1708 inputs.put("CurrentURIMetaData", URIMetaData);
1709 } catch (NumberFormatException ex) {
1710 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
1713 Map<String, String> result = service.invokeAction(this, "AVTransport", "SetAVTransportURI", inputs);
1715 for (String variable : result.keySet()) {
1716 this.onValueReceived(variable, result.get(variable), "AVTransport");
1721 public void setPosition(@Nullable String relTime) {
1722 seek("REL_TIME", relTime);
1725 public void setPositionTrack(long tracknr) {
1726 seek("TRACK_NR", Long.toString(tracknr));
1729 public void setPositionTrack(String tracknr) {
1730 seek("TRACK_NR", tracknr);
1733 protected void seek(String unit, @Nullable String target) {
1734 if (target != null) {
1735 Map<String, String> inputs = new HashMap<>();
1738 inputs.put("InstanceID", "0");
1739 inputs.put("Unit", unit);
1740 inputs.put("Target", target);
1741 } catch (NumberFormatException ex) {
1742 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
1745 Map<String, String> result = service.invokeAction(this, "AVTransport", "Seek", inputs);
1747 for (String variable : result.keySet()) {
1748 this.onValueReceived(variable, result.get(variable), "AVTransport");
1753 public void play() {
1754 Map<String, String> inputs = new HashMap<>();
1755 inputs.put("Speed", "1");
1757 Map<String, String> result = service.invokeAction(this, "AVTransport", "Play", inputs);
1759 for (String variable : result.keySet()) {
1760 this.onValueReceived(variable, result.get(variable), "AVTransport");
1764 public void stop() {
1765 Map<String, String> result = service.invokeAction(this, "AVTransport", "Stop", null);
1767 for (String variable : result.keySet()) {
1768 this.onValueReceived(variable, result.get(variable), "AVTransport");
1772 public void pause() {
1773 Map<String, String> result = service.invokeAction(this, "AVTransport", "Pause", null);
1775 for (String variable : result.keySet()) {
1776 this.onValueReceived(variable, result.get(variable), "AVTransport");
1780 public void setShuffle(Command command) {
1781 if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
1783 ZonePlayerHandler coordinator = getCoordinatorHandler();
1785 if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
1786 || command.equals(OpenClosedType.OPEN)) {
1787 switch (coordinator.getRepeatMode()) {
1789 coordinator.updatePlayMode("SHUFFLE");
1792 coordinator.updatePlayMode("SHUFFLE_REPEAT_ONE");
1795 coordinator.updatePlayMode("SHUFFLE_NOREPEAT");
1798 } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
1799 || command.equals(OpenClosedType.CLOSED)) {
1800 switch (coordinator.getRepeatMode()) {
1802 coordinator.updatePlayMode("REPEAT_ALL");
1805 coordinator.updatePlayMode("REPEAT_ONE");
1808 coordinator.updatePlayMode("NORMAL");
1812 } catch (IllegalStateException e) {
1813 logger.debug("Cannot handle shuffle command ({})", e.getMessage());
1818 public void setRepeat(Command command) {
1819 if (command instanceof StringType) {
1821 ZonePlayerHandler coordinator = getCoordinatorHandler();
1823 switch (command.toString()) {
1825 coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE" : "REPEAT_ALL");
1828 coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_REPEAT_ONE" : "REPEAT_ONE");
1831 coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_NOREPEAT" : "NORMAL");
1834 logger.debug("{}: unexpected repeat command; accepted values are ALL, ONE and OFF",
1835 command.toString());
1838 } catch (IllegalStateException e) {
1839 logger.debug("Cannot handle repeat command ({})", e.getMessage());
1844 public void setNightMode(Command command) {
1845 if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
1846 setEQ("NightMode", (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
1847 || command.equals(OpenClosedType.OPEN)) ? "1" : "0");
1851 public void setSpeechEnhancement(Command command) {
1852 if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
1853 setEQ("DialogLevel", (command.equals(OnOffType.ON) || command.equals(UpDownType.UP)
1854 || command.equals(OpenClosedType.OPEN)) ? "1" : "0");
1858 private void setEQ(String eqType, String value) {
1860 Map<String, String> inputs = new HashMap<>();
1861 inputs.put("InstanceID", "0");
1862 inputs.put("EQType", eqType);
1863 inputs.put("DesiredValue", value);
1864 Map<String, String> result = service.invokeAction(this, "RenderingControl", "SetEQ", inputs);
1866 for (String variable : result.keySet()) {
1867 this.onValueReceived(variable, result.get(variable), "RenderingControl");
1869 } catch (IllegalStateException e) {
1870 logger.debug("Cannot handle {} command ({})", eqType, e.getMessage());
1874 public @Nullable String getNightMode() {
1875 return stateMap.get("NightMode");
1878 public boolean isNightModeOn() {
1879 return "1".equals(getNightMode());
1882 public @Nullable String getDialogLevel() {
1883 return stateMap.get("DialogLevel");
1886 public boolean isSpeechEnhanced() {
1887 return "1".equals(getDialogLevel());
1890 public @Nullable String getPlayMode() {
1891 return stateMap.get("CurrentPlayMode");
1894 public Boolean isShuffleActive() {
1895 String playMode = getPlayMode();
1896 return (playMode != null && playMode.startsWith("SHUFFLE"));
1899 public String getRepeatMode() {
1900 String mode = "OFF";
1901 String playMode = getPlayMode();
1902 if (playMode != null) {
1909 case "SHUFFLE_REPEAT_ONE":
1913 case "SHUFFLE_NOREPEAT":
1922 protected void updatePlayMode(String playMode) {
1923 Map<String, String> inputs = new HashMap<>();
1924 inputs.put("InstanceID", "0");
1925 inputs.put("NewPlayMode", playMode);
1927 Map<String, String> result = service.invokeAction(this, "AVTransport", "SetPlayMode", inputs);
1929 for (String variable : result.keySet()) {
1930 this.onValueReceived(variable, result.get(variable), "AVTransport");
1935 * Clear all scheduled music from the current queue.
1938 public void removeAllTracksFromQueue() {
1939 Map<String, String> inputs = new HashMap<>();
1940 inputs.put("InstanceID", "0");
1942 Map<String, String> result = service.invokeAction(this, "AVTransport", "RemoveAllTracksFromQueue", inputs);
1944 for (String variable : result.keySet()) {
1945 this.onValueReceived(variable, result.get(variable), "AVTransport");
1950 * Play music from the line-in of the given Player referenced by the given UDN or name
1952 * @param udn or name
1954 public void playLineIn(Command command) {
1955 if (command instanceof StringType) {
1957 LineInType lineInType = LineInType.ANY;
1958 String remotePlayerName = command.toString();
1959 if (remotePlayerName.toUpperCase().startsWith("ANALOG,")) {
1960 lineInType = LineInType.ANALOG;
1961 remotePlayerName = remotePlayerName.substring(7);
1962 } else if (remotePlayerName.toUpperCase().startsWith("DIGITAL,")) {
1963 lineInType = LineInType.DIGITAL;
1964 remotePlayerName = remotePlayerName.substring(8);
1966 ZonePlayerHandler coordinatorHandler = getCoordinatorHandler();
1967 ZonePlayerHandler remoteHandler = getHandlerByName(remotePlayerName);
1969 // check if player has a line-in connected
1970 if ((lineInType != LineInType.DIGITAL && remoteHandler.isAnalogLineInConnected())
1971 || (lineInType != LineInType.ANALOG && remoteHandler.isOpticalLineInConnected())) {
1972 // stop whatever is currently playing
1973 coordinatorHandler.stop();
1976 if (lineInType != LineInType.DIGITAL && remoteHandler.isAnalogLineInConnected()) {
1977 coordinatorHandler.setCurrentURI(ANALOG_LINE_IN_URI + remoteHandler.getUDN(), "");
1979 coordinatorHandler.setCurrentURI(OPTICAL_LINE_IN_URI + remoteHandler.getUDN() + SPDIF, "");
1982 // take the system off mute
1983 coordinatorHandler.setMute(OnOffType.OFF);
1986 coordinatorHandler.play();
1988 logger.debug("Line-in of {} is not connected", remoteHandler.getUDN());
1990 } catch (IllegalStateException e) {
1991 logger.debug("Cannot play line-in ({})", e.getMessage());
1996 private ZonePlayerHandler getCoordinatorHandler() throws IllegalStateException {
1997 ZonePlayerHandler handler = coordinatorHandler;
1998 if (handler != null) {
2002 handler = getHandlerByName(getCoordinator());
2003 coordinatorHandler = handler;
2005 } catch (IllegalStateException e) {
2006 throw new IllegalStateException("Missing group coordinator " + getCoordinator());
2011 * Returns a list of all zone group members this particular player is member of
2012 * Or empty list if the players is not assigned to any group
2014 * @return a list of Strings containing the UDNs of other group members
2016 protected List<String> getZoneGroupMembers() {
2017 List<String> result = new ArrayList<>();
2019 Collection<SonosZoneGroup> zoneGroups = getZoneGroups();
2020 if (!zoneGroups.isEmpty()) {
2021 for (SonosZoneGroup zg : zoneGroups) {
2022 if (zg.getMembers().contains(getUDN())) {
2023 result.addAll(zg.getMembers());
2028 // If the group topology was not yet received, return at least the current Sonos zone
2029 result.add(getUDN());
2035 * Returns a list of other zone group members this particular player is member of
2036 * Or empty list if the players is not assigned to any group
2038 * @return a list of Strings containing the UDNs of other group members
2040 protected List<String> getOtherZoneGroupMembers() {
2041 List<String> zoneGroupMembers = getZoneGroupMembers();
2042 zoneGroupMembers.remove(getUDN());
2043 return zoneGroupMembers;
2046 protected ZonePlayerHandler getHandlerByName(String remotePlayerName) throws IllegalStateException {
2047 for (ThingTypeUID supportedThingType : SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS) {
2048 Thing thing = localThingRegistry.get(new ThingUID(supportedThingType, remotePlayerName));
2049 if (thing != null) {
2050 ThingHandler handler = thing.getHandler();
2051 if (handler instanceof ZonePlayerHandler) {
2052 return (ZonePlayerHandler) handler;
2056 for (Thing aThing : localThingRegistry.getAll()) {
2057 if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())
2058 && aThing.getConfiguration().get(ZonePlayerConfiguration.UDN).equals(remotePlayerName)) {
2059 ThingHandler handler = aThing.getHandler();
2060 if (handler instanceof ZonePlayerHandler) {
2061 return (ZonePlayerHandler) handler;
2065 throw new IllegalStateException("Could not find handler for " + remotePlayerName);
2068 public void setMute(Command command) {
2069 if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
2070 Map<String, String> inputs = new HashMap<>();
2071 inputs.put("Channel", "Master");
2073 if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) {
2074 inputs.put("DesiredMute", "True");
2075 } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
2076 || command.equals(OpenClosedType.CLOSED)) {
2077 inputs.put("DesiredMute", "False");
2080 Map<String, String> result = service.invokeAction(this, "RenderingControl", "SetMute", inputs);
2082 for (String variable : result.keySet()) {
2083 this.onValueReceived(variable, result.get(variable), "RenderingControl");
2088 public List<SonosAlarm> getCurrentAlarmList() {
2089 Map<String, @Nullable String> result = service.invokeAction(this, "AlarmClock", "ListAlarms", null);
2091 for (String variable : result.keySet()) {
2092 this.onValueReceived(variable, result.get(variable), "AlarmClock");
2095 String alarmList = result.get("CurrentAlarmList");
2096 return alarmList == null ? Collections.emptyList() : SonosXMLParser.getAlarmsFromStringResult(alarmList);
2099 public void updateAlarm(SonosAlarm alarm) {
2100 Map<String, String> inputs = new HashMap<>();
2103 inputs.put("ID", Integer.toString(alarm.getId()));
2104 inputs.put("StartLocalTime", alarm.getStartTime());
2105 inputs.put("Duration", alarm.getDuration());
2106 inputs.put("Recurrence", alarm.getRecurrence());
2107 inputs.put("RoomUUID", alarm.getRoomUUID());
2108 inputs.put("ProgramURI", alarm.getProgramURI());
2109 inputs.put("ProgramMetaData", alarm.getProgramMetaData());
2110 inputs.put("PlayMode", alarm.getPlayMode());
2111 inputs.put("Volume", Integer.toString(alarm.getVolume()));
2112 if (alarm.getIncludeLinkedZones()) {
2113 inputs.put("IncludeLinkedZones", "1");
2115 inputs.put("IncludeLinkedZones", "0");
2118 if (alarm.getEnabled()) {
2119 inputs.put("Enabled", "1");
2121 inputs.put("Enabled", "0");
2123 } catch (NumberFormatException ex) {
2124 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
2127 Map<String, String> result = service.invokeAction(this, "AlarmClock", "UpdateAlarm", inputs);
2129 for (String variable : result.keySet()) {
2130 this.onValueReceived(variable, result.get(variable), "AlarmClock");
2134 public void setAlarm(Command command) {
2135 if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
2136 if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) {
2138 } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
2139 || command.equals(OpenClosedType.CLOSED)) {
2145 public void setAlarm(boolean alarmSwitch) {
2146 List<SonosAlarm> sonosAlarms = getCurrentAlarmList();
2148 // find the nearest alarm - take the current time from the Sonos system,
2149 // not the system where we are running
2150 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2151 fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
2153 String currentLocalTime = getTime();
2154 Date currentDateTime = null;
2156 currentDateTime = fmt.parse(currentLocalTime);
2157 } catch (ParseException e) {
2158 logger.debug("An exception occurred while formatting a date", e);
2161 if (currentDateTime != null) {
2162 Calendar currentDateTimeCalendar = Calendar.getInstance();
2163 currentDateTimeCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
2164 currentDateTimeCalendar.setTime(currentDateTime);
2165 currentDateTimeCalendar.add(Calendar.DAY_OF_YEAR, 10);
2166 long shortestDuration = currentDateTimeCalendar.getTimeInMillis() - currentDateTime.getTime();
2168 SonosAlarm firstAlarm = null;
2170 for (SonosAlarm anAlarm : sonosAlarms) {
2171 SimpleDateFormat durationFormat = new SimpleDateFormat("HH:mm:ss");
2172 durationFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
2175 durationDate = durationFormat.parse(anAlarm.getDuration());
2176 } catch (ParseException e) {
2177 logger.debug("An exception occurred while parsing a date : '{}'", e.getMessage());
2181 long duration = durationDate.getTime();
2183 if (duration < shortestDuration && anAlarm.getRoomUUID().equals(getUDN())) {
2184 shortestDuration = duration;
2185 firstAlarm = anAlarm;
2190 if (firstAlarm != null) {
2192 firstAlarm.setEnabled(true);
2194 firstAlarm.setEnabled(false);
2197 updateAlarm(firstAlarm);
2202 public @Nullable String getTime() {
2204 return stateMap.get("CurrentLocalTime");
2207 public @Nullable String getAlarmRunning() {
2208 return stateMap.get("AlarmRunning");
2211 public boolean isAlarmRunning() {
2212 return "1".equals(getAlarmRunning());
2215 public void snoozeAlarm(Command command) {
2216 if (isAlarmRunning() && command instanceof DecimalType) {
2217 int minutes = ((DecimalType) command).intValue();
2219 Map<String, String> inputs = new HashMap<>();
2221 Calendar snoozePeriod = Calendar.getInstance();
2222 snoozePeriod.setTimeZone(TimeZone.getTimeZone("GMT"));
2223 snoozePeriod.setTimeInMillis(0);
2224 snoozePeriod.add(Calendar.MINUTE, minutes);
2225 SimpleDateFormat pFormatter = new SimpleDateFormat("HH:mm:ss");
2226 pFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
2229 inputs.put("Duration", pFormatter.format(snoozePeriod.getTime()));
2230 } catch (NumberFormatException ex) {
2231 logger.debug("Action Invalid Value Format Exception {}", ex.getMessage());
2234 Map<String, String> result = service.invokeAction(this, "AVTransport", "SnoozeAlarm", inputs);
2236 for (String variable : result.keySet()) {
2237 this.onValueReceived(variable, result.get(variable), "AVTransport");
2240 logger.debug("There is no alarm running on {}", getUDN());
2244 public @Nullable String getAnalogLineInConnected() {
2245 return stateMap.get(LINEINCONNECTED);
2248 public boolean isAnalogLineInConnected() {
2249 return "true".equals(getAnalogLineInConnected());
2252 public @Nullable String getOpticalLineInConnected() {
2253 return stateMap.get(TOSLINEINCONNECTED);
2256 public boolean isOpticalLineInConnected() {
2257 return "true".equals(getOpticalLineInConnected());
2260 public void becomeStandAlonePlayer() {
2261 Map<String, String> result = service.invokeAction(this, "AVTransport", "BecomeCoordinatorOfStandaloneGroup",
2264 for (String variable : result.keySet()) {
2265 this.onValueReceived(variable, result.get(variable), "AVTransport");
2269 public void addMember(Command command) {
2270 if (command instanceof StringType) {
2271 SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", GROUP_URI + getUDN());
2273 getHandlerByName(command.toString()).setCurrentURI(entry);
2274 } catch (IllegalStateException e) {
2275 logger.debug("Cannot add group member ({})", e.getMessage());
2280 public boolean publicAddress(LineInType lineInType) {
2281 // check if sourcePlayer has a line-in connected
2282 if ((lineInType != LineInType.DIGITAL && isAnalogLineInConnected())
2283 || (lineInType != LineInType.ANALOG && isOpticalLineInConnected())) {
2284 // first remove this player from its own group if any
2285 becomeStandAlonePlayer();
2287 // add all other players to this new group
2288 for (SonosZoneGroup group : getZoneGroups()) {
2289 for (String player : group.getMembers()) {
2291 ZonePlayerHandler somePlayer = getHandlerByName(player);
2292 if (somePlayer != this) {
2293 somePlayer.becomeStandAlonePlayer();
2295 addMember(StringType.valueOf(somePlayer.getUDN()));
2297 } catch (IllegalStateException e) {
2298 logger.debug("Cannot add to group ({})", e.getMessage());
2304 ZonePlayerHandler coordinator = getCoordinatorHandler();
2305 // set the URI of the group to the line-in
2306 SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", ANALOG_LINE_IN_URI + getUDN());
2307 if (lineInType != LineInType.ANALOG && isOpticalLineInConnected()) {
2308 entry = new SonosEntry("", "", "", "", "", "", "", OPTICAL_LINE_IN_URI + getUDN() + SPDIF);
2310 coordinator.setCurrentURI(entry);
2314 } catch (IllegalStateException e) {
2315 logger.debug("Cannot handle command ({})", e.getMessage());
2319 logger.debug("Line-in of {} is not connected", getUDN());
2325 * Play a given url to music in one of the music libraries.
2328 * in the format of //host/folder/filename.mp3
2330 public void playURI(Command command) {
2331 if (command instanceof StringType) {
2333 String url = command.toString();
2335 ZonePlayerHandler coordinator = getCoordinatorHandler();
2337 // stop whatever is currently playing
2339 coordinator.waitForNotTransportState(STATE_PLAYING);
2341 // clear any tracks which are pending in the queue
2342 coordinator.removeAllTracksFromQueue();
2344 // add the new track we want to play to the queue
2345 // The url will be prefixed with x-file-cifs if it is NOT a http URL
2346 if (!url.startsWith("x-") && (!url.startsWith("http"))) {
2347 // default to file based url
2348 url = FILE_URI + url;
2350 coordinator.addURIToQueue(url, "", 0, true);
2352 // set the current playlist to our new queue
2353 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2355 // take the system off mute
2356 coordinator.setMute(OnOffType.OFF);
2360 } catch (IllegalStateException e) {
2361 logger.debug("Cannot play URI ({})", e.getMessage());
2366 private void scheduleNotificationSound(final Command command) {
2367 scheduler.submit(() -> {
2368 synchronized (notificationLock) {
2369 playNotificationSoundURI(command);
2375 * Play a given notification sound
2377 * @param url in the format of //host/folder/filename.mp3
2379 public void playNotificationSoundURI(Command notificationURL) {
2380 if (notificationURL instanceof StringType) {
2382 ZonePlayerHandler coordinator = getCoordinatorHandler();
2384 String currentURI = coordinator.getCurrentURI();
2385 logger.debug("playNotificationSoundURI: currentURI {} metadata {}", currentURI,
2386 coordinator.getCurrentURIMetadataAsString());
2388 if (isPlayingStream(currentURI) || isPlayingRadioStartedByAmazonEcho(currentURI)
2389 || isPlayingRadio(currentURI)) {
2390 handleRadioStream(currentURI, notificationURL, coordinator);
2391 } else if (isPlayingLineIn(currentURI)) {
2392 handleLineIn(currentURI, notificationURL, coordinator);
2393 } else if (isPlayingQueue(currentURI)) {
2394 handleSharedQueue(currentURI, notificationURL, coordinator);
2395 } else if (isPlaylistEmpty(coordinator)) {
2396 handleEmptyQueue(notificationURL, coordinator);
2398 synchronized (notificationLock) {
2399 notificationLock.notify();
2401 } catch (IllegalStateException e) {
2402 logger.debug("Cannot play sound ({})", e.getMessage());
2407 private boolean isPlaylistEmpty(ZonePlayerHandler coordinator) {
2408 return coordinator.getQueueSize() == 0;
2411 private boolean isPlayingQueue(@Nullable String currentURI) {
2412 return currentURI != null && currentURI.contains(QUEUE_URI);
2415 private boolean isPlayingStream(@Nullable String currentURI) {
2416 return currentURI != null && currentURI.contains(STREAM_URI);
2419 private boolean isPlayingRadio(@Nullable String currentURI) {
2420 return currentURI != null && currentURI.contains(RADIO_URI);
2423 private boolean isPlayingRadioStartedByAmazonEcho(@Nullable String currentURI) {
2424 return currentURI != null && currentURI.contains(RADIO_MP3_URI) && currentURI.contains(OPML_TUNE);
2427 private boolean isPlayingLineIn(@Nullable String currentURI) {
2428 return currentURI != null && (isPlayingAnalogLineIn(currentURI) || isPlayingOpticalLineIn(currentURI));
2431 private boolean isPlayingAnalogLineIn(@Nullable String currentURI) {
2432 return currentURI != null && currentURI.contains(ANALOG_LINE_IN_URI);
2435 private boolean isPlayingOpticalLineIn(@Nullable String currentURI) {
2436 return currentURI != null && currentURI.startsWith(OPTICAL_LINE_IN_URI) && currentURI.endsWith(SPDIF);
2440 * Does a chain of predefined actions when a Notification sound is played by
2441 * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2442 * radio streaming is currently loaded
2444 * @param currentStreamURI - the currently loaded stream's URI
2445 * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2446 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2448 private void handleRadioStream(@Nullable String currentStreamURI, Command notificationURL,
2449 ZonePlayerHandler coordinator) {
2450 String nextAction = coordinator.getTransportState();
2451 SonosMetaData track = coordinator.getTrackMetadata();
2452 SonosMetaData currentUriMetaData = coordinator.getCurrentURIMetadata();
2454 handleNotificationSound(notificationURL, coordinator);
2455 if (currentStreamURI != null && track != null && currentUriMetaData != null) {
2456 coordinator.setCurrentURI(new SonosEntry("", currentUriMetaData.getTitle(), "", "", track.getAlbumArtUri(),
2457 "", currentUriMetaData.getUpnpClass(), currentStreamURI));
2458 restoreLastTransportState(coordinator, nextAction);
2463 * Does a chain of predefined actions when a Notification sound is played by
2464 * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2465 * line in is currently loaded
2467 * @param currentLineInURI - the currently loaded line-in URI
2468 * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2469 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2471 private void handleLineIn(@Nullable String currentLineInURI, Command notificationURL,
2472 ZonePlayerHandler coordinator) {
2473 logger.debug("Handling notification while sound from line-in was being played");
2474 String nextAction = coordinator.getTransportState();
2476 handleNotificationSound(notificationURL, coordinator);
2477 if (currentLineInURI != null) {
2478 logger.debug("Restoring sound from line-in using {}", currentLineInURI);
2479 coordinator.setCurrentURI(currentLineInURI, "");
2480 restoreLastTransportState(coordinator, nextAction);
2485 * Does a chain of predefined actions when a Notification sound is played by
2486 * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2487 * shared queue is currently loaded
2489 * @param currentQueueURI - the currently loaded queue URI
2490 * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2491 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2493 private void handleSharedQueue(@Nullable String currentQueueURI, Command notificationURL,
2494 ZonePlayerHandler coordinator) {
2495 String nextAction = coordinator.getTransportState();
2496 String trackPosition = coordinator.getRefreshedPosition();
2497 long currentTrackNumber = coordinator.getRefreshedCurrenTrackNr();
2498 logger.debug("handleSharedQueue: currentQueueURI {} trackPosition {} currentTrackNumber {}", currentQueueURI,
2499 trackPosition, currentTrackNumber);
2501 handleNotificationSound(notificationURL, coordinator);
2502 String queueUri = QUEUE_URI + coordinator.getUDN() + "#0";
2503 if (queueUri.equals(currentQueueURI)) {
2504 coordinator.setPositionTrack(currentTrackNumber);
2505 coordinator.setPosition(trackPosition);
2506 restoreLastTransportState(coordinator, nextAction);
2511 * Handle the execution of the notification sound by sequentially executing the required steps.
2513 * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2514 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2516 private void handleNotificationSound(Command notificationURL, ZonePlayerHandler coordinator) {
2517 boolean sourceStoppable = !isPlayingOpticalLineIn(coordinator.getCurrentURI());
2518 String originalVolume = (isAdHocGroup() || isStandalonePlayer()) ? getVolume() : coordinator.getVolume();
2519 if (sourceStoppable) {
2521 coordinator.waitForNotTransportState(STATE_PLAYING);
2522 applyNotificationSoundVolume();
2524 long notificationPosition = coordinator.getQueueSize() + 1;
2525 coordinator.addURIToQueue(notificationURL.toString(), "", notificationPosition, false);
2526 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2527 coordinator.setPositionTrack(notificationPosition);
2528 if (!sourceStoppable) {
2530 coordinator.waitForNotTransportState(STATE_PLAYING);
2531 applyNotificationSoundVolume();
2534 coordinator.waitForFinishedNotification();
2535 if (originalVolume != null) {
2536 setVolumeForGroup(DecimalType.valueOf(originalVolume));
2538 coordinator.removeRangeOfTracksFromQueue(new StringType(Long.toString(notificationPosition) + ",1"));
2541 private void restoreLastTransportState(ZonePlayerHandler coordinator, @Nullable String nextAction) {
2542 if (nextAction != null) {
2543 switch (nextAction) {
2546 coordinator.waitForTransportState(STATE_PLAYING);
2548 case STATE_PAUSED_PLAYBACK:
2549 coordinator.pause();
2556 * Does a chain of predefined actions when a Notification sound is played by
2557 * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case
2558 * empty queue is currently loaded
2560 * @param notificationURL - the notification url in the format of //host/folder/filename.mp3
2561 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2563 private void handleEmptyQueue(Command notificationURL, ZonePlayerHandler coordinator) {
2564 String originalVolume = coordinator.getVolume();
2565 coordinator.applyNotificationSoundVolume();
2566 coordinator.playURI(notificationURL);
2567 coordinator.waitForFinishedNotification();
2568 coordinator.removeAllTracksFromQueue();
2569 if (originalVolume != null) {
2570 coordinator.setVolume(DecimalType.valueOf(originalVolume));
2575 * Applies the notification sound volume level to the group (if not null)
2577 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s)
2579 private void applyNotificationSoundVolume() {
2580 setNotificationSoundVolume(getNotificationSoundVolume());
2583 private void waitForFinishedNotification() {
2584 waitForTransportState(STATE_PLAYING);
2586 // check Sonos state events to determine the end of the notification sound
2587 String notificationTitle = getCurrentTitle();
2588 long playstart = System.currentTimeMillis();
2589 while (System.currentTimeMillis() - playstart < (long) configuration.notificationTimeout * 1000) {
2592 String currentTitle = getCurrentTitle();
2593 if ((notificationTitle == null && currentTitle != null)
2594 || (notificationTitle != null && !notificationTitle.equals(currentTitle))
2595 || !STATE_PLAYING.equals(getTransportState())) {
2598 } catch (InterruptedException e) {
2599 logger.debug("InterruptedException during playing a notification sound");
2604 private void waitForTransportState(String state) {
2605 if (getTransportState() != null) {
2606 long start = System.currentTimeMillis();
2607 while (!state.equals(getTransportState())) {
2610 if (System.currentTimeMillis() - start > (long) configuration.notificationTimeout * 1000) {
2613 } catch (InterruptedException e) {
2614 logger.debug("InterruptedException during playing a notification sound");
2620 private void waitForNotTransportState(String state) {
2621 if (getTransportState() != null) {
2622 long start = System.currentTimeMillis();
2623 while (state.equals(getTransportState())) {
2626 if (System.currentTimeMillis() - start > (long) configuration.notificationTimeout * 1000) {
2629 } catch (InterruptedException e) {
2630 logger.debug("InterruptedException during playing a notification sound");
2637 * Removes a range of tracks from the queue.
2638 * (<x,y> will remove y songs started by the song number x)
2640 * @param command - must be in the format <startIndex, numberOfSongs>
2642 public void removeRangeOfTracksFromQueue(Command command) {
2643 if (command instanceof StringType) {
2644 Map<String, String> inputs = new HashMap<>();
2645 String[] rangeInputSplit = command.toString().split(",");
2647 // If range input is incorrect, remove the first song by default
2648 String startIndex = rangeInputSplit[0] != null ? rangeInputSplit[0] : "1";
2649 String numberOfTracks = rangeInputSplit[1] != null ? rangeInputSplit[1] : "1";
2651 inputs.put("InstanceID", "0");
2652 inputs.put("StartingIndex", startIndex);
2653 inputs.put("NumberOfTracks", numberOfTracks);
2655 Map<String, String> result = service.invokeAction(this, "AVTransport", "RemoveTrackRangeFromQueue", inputs);
2657 for (String variable : result.keySet()) {
2658 this.onValueReceived(variable, result.get(variable), "AVTransport");
2663 public void clearQueue() {
2665 ZonePlayerHandler coordinator = getCoordinatorHandler();
2667 coordinator.removeAllTracksFromQueue();
2668 } catch (IllegalStateException e) {
2669 logger.debug("Cannot clear queue ({})", e.getMessage());
2673 public void playQueue() {
2675 ZonePlayerHandler coordinator = getCoordinatorHandler();
2677 // set the current playlist to our new queue
2678 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2680 // take the system off mute
2681 coordinator.setMute(OnOffType.OFF);
2685 } catch (IllegalStateException e) {
2686 logger.debug("Cannot play queue ({})", e.getMessage());
2690 public void setLed(Command command) {
2691 if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) {
2692 Map<String, String> inputs = new HashMap<>();
2694 if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) {
2695 inputs.put("DesiredLEDState", "On");
2696 } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN)
2697 || command.equals(OpenClosedType.CLOSED)) {
2698 inputs.put("DesiredLEDState", "Off");
2701 Map<String, String> result = service.invokeAction(this, "DeviceProperties", "SetLEDState", inputs);
2702 Map<String, String> result2 = service.invokeAction(this, "DeviceProperties", "GetLEDState", null);
2704 result.putAll(result2);
2706 for (String variable : result.keySet()) {
2707 this.onValueReceived(variable, result.get(variable), "DeviceProperties");
2712 public void removeMember(Command command) {
2713 if (command instanceof StringType) {
2715 ZonePlayerHandler oldmemberHandler = getHandlerByName(command.toString());
2717 oldmemberHandler.becomeStandAlonePlayer();
2718 SonosEntry entry = new SonosEntry("", "", "", "", "", "", "",
2719 QUEUE_URI + oldmemberHandler.getUDN() + "#0");
2720 oldmemberHandler.setCurrentURI(entry);
2721 } catch (IllegalStateException e) {
2722 logger.debug("Cannot remove group member ({})", e.getMessage());
2727 public void previous() {
2728 Map<String, String> result = service.invokeAction(this, "AVTransport", "Previous", null);
2730 for (String variable : result.keySet()) {
2731 this.onValueReceived(variable, result.get(variable), "AVTransport");
2735 public void next() {
2736 Map<String, String> result = service.invokeAction(this, "AVTransport", "Next", null);
2738 for (String variable : result.keySet()) {
2739 this.onValueReceived(variable, result.get(variable), "AVTransport");
2743 public void stopPlaying(Command command) {
2744 if (command instanceof OnOffType) {
2746 getCoordinatorHandler().stop();
2747 } catch (IllegalStateException e) {
2748 logger.debug("Cannot handle stop command ({})", e.getMessage(), e);
2753 public void playRadio(Command command) {
2754 if (command instanceof StringType) {
2755 String station = command.toString();
2756 List<SonosEntry> stations = getFavoriteRadios();
2758 SonosEntry theEntry = null;
2759 // search for the appropriate radio based on its name (title)
2760 for (SonosEntry someStation : stations) {
2761 if (someStation.getTitle().equals(station)) {
2762 theEntry = someStation;
2767 // set the URI of the group coordinator
2768 if (theEntry != null) {
2770 ZonePlayerHandler coordinator = getCoordinatorHandler();
2771 coordinator.setCurrentURI(theEntry);
2773 } catch (IllegalStateException e) {
2774 logger.debug("Cannot play radio ({})", e.getMessage());
2777 logger.debug("Radio station '{}' not found", station);
2782 public void playTuneinStation(Command command) {
2783 if (command instanceof StringType) {
2784 String stationId = command.toString();
2785 List<SonosMusicService> allServices = getAvailableMusicServices();
2787 SonosMusicService tuneinService = null;
2788 // search for the TuneIn music service based on its name
2789 if (allServices != null) {
2790 for (SonosMusicService service : allServices) {
2791 if (service.getName().equals("TuneIn")) {
2792 tuneinService = service;
2798 // set the URI of the group coordinator
2799 if (tuneinService != null) {
2801 ZonePlayerHandler coordinator = getCoordinatorHandler();
2802 SonosEntry entry = new SonosEntry("", "TuneIn station", "", "", "", "",
2803 "object.item.audioItem.audioBroadcast",
2804 String.format(TUNEIN_URI, stationId, tuneinService.getId()));
2805 Integer tuneinServiceType = tuneinService.getType();
2806 int serviceTypeNum = tuneinServiceType == null ? TUNEIN_DEFAULT_SERVICE_TYPE : tuneinServiceType;
2807 entry.setDesc("SA_RINCON" + Integer.toString(serviceTypeNum) + "_");
2808 coordinator.setCurrentURI(entry);
2810 } catch (IllegalStateException e) {
2811 logger.debug("Cannot play TuneIn station {} ({})", stationId, e.getMessage());
2814 logger.debug("TuneIn service not found");
2819 private @Nullable List<SonosMusicService> getAvailableMusicServices() {
2820 if (musicServices == null) {
2821 Map<String, @Nullable String> result = service.invokeAction(this, "MusicServices", "ListAvailableServices",
2824 String serviceList = result.get("AvailableServiceDescriptorList");
2825 if (serviceList != null) {
2826 List<SonosMusicService> services = SonosXMLParser.getMusicServicesFromXML(serviceList);
2827 musicServices = services;
2829 String[] servicesTypes = new String[0];
2830 String serviceTypeList = result.get("AvailableServiceTypeList");
2831 if (serviceTypeList != null) {
2832 // It is a comma separated list of service types (integers) in the same order as the services
2833 // declaration in "AvailableServiceDescriptorList" except that there is no service type for the
2835 servicesTypes = serviceTypeList.split(",");
2839 for (SonosMusicService service : services) {
2840 if (!service.getName().equals("TuneIn")) {
2841 // Add the service type integer value from "AvailableServiceTypeList" to each service
2843 if (idx < servicesTypes.length) {
2845 Integer serviceType = Integer.parseInt(servicesTypes[idx]);
2846 service.setType(serviceType);
2847 } catch (NumberFormatException e) {
2852 service.setType(TUNEIN_DEFAULT_SERVICE_TYPE);
2854 logger.debug("Service name {} => id {} type {}", service.getName(), service.getId(),
2859 return musicServices;
2863 * This will attempt to match the station string with a entry in the
2864 * favorites list, this supports both single entries and playlists
2866 * @param favorite to match
2867 * @return true if a match was found and played.
2869 public void playFavorite(Command command) {
2870 if (command instanceof StringType) {
2871 String favorite = command.toString();
2872 List<SonosEntry> favorites = getFavorites();
2874 SonosEntry theEntry = null;
2875 // search for the appropriate favorite based on its name (title)
2876 for (SonosEntry entry : favorites) {
2877 if (entry.getTitle().equals(favorite)) {
2883 // set the URI of the group coordinator
2884 if (theEntry != null) {
2886 ZonePlayerHandler coordinator = getCoordinatorHandler();
2889 * If this is a playlist we need to treat it as such
2891 SonosResourceMetaData resourceMetaData = theEntry.getResourceMetaData();
2892 if (resourceMetaData != null && resourceMetaData.getUpnpClass().startsWith("object.container")) {
2893 coordinator.removeAllTracksFromQueue();
2894 coordinator.addURIToQueue(theEntry);
2895 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2896 String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued");
2897 coordinator.seek("TRACK_NR", firstTrackNumberEnqueued);
2899 coordinator.setCurrentURI(theEntry);
2902 } catch (IllegalStateException e) {
2903 logger.debug("Cannot paly favorite ({})", e.getMessage());
2906 logger.debug("Favorite '{}' not found", favorite);
2911 public void playTrack(Command command) {
2912 if (command instanceof DecimalType) {
2914 ZonePlayerHandler coordinator = getCoordinatorHandler();
2916 String trackNumber = String.valueOf(((DecimalType) command).intValue());
2918 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2920 // seek the track - warning, we do not check if the tracknumber falls in the boundary of the queue
2921 coordinator.setPositionTrack(trackNumber);
2923 // take the system off mute
2924 coordinator.setMute(OnOffType.OFF);
2928 } catch (IllegalStateException e) {
2929 logger.debug("Cannot play track ({})", e.getMessage());
2934 public void playPlayList(Command command) {
2935 if (command instanceof StringType) {
2936 String playlist = command.toString();
2937 List<SonosEntry> playlists = getPlayLists();
2939 SonosEntry theEntry = null;
2940 // search for the appropriate play list based on its name (title)
2941 for (SonosEntry somePlaylist : playlists) {
2942 if (somePlaylist.getTitle().equals(playlist)) {
2943 theEntry = somePlaylist;
2948 // set the URI of the group coordinator
2949 if (theEntry != null) {
2951 ZonePlayerHandler coordinator = getCoordinatorHandler();
2953 coordinator.addURIToQueue(theEntry);
2955 coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
2957 String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued");
2958 coordinator.seek("TRACK_NR", firstTrackNumberEnqueued);
2961 } catch (IllegalStateException e) {
2962 logger.debug("Cannot play playlist ({})", e.getMessage());
2965 logger.debug("Playlist '{}' not found", playlist);
2970 public void addURIToQueue(SonosEntry newEntry) {
2971 addURIToQueue(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry), 1, true);
2974 public @Nullable String getZoneName() {
2975 return stateMap.get("ZoneName");
2978 public @Nullable String getZoneGroupID() {
2979 return stateMap.get("LocalGroupUUID");
2982 public @Nullable String getRunningAlarmProperties() {
2983 return stateMap.get("RunningAlarmProperties");
2986 public @Nullable String getRefreshedRunningAlarmProperties() {
2987 updateRunningAlarmProperties();
2988 return getRunningAlarmProperties();
2991 public @Nullable String getMute() {
2992 return stateMap.get("MuteMaster");
2995 public boolean isMuted() {
2996 return "1".equals(getMute());
2999 public @Nullable String getLed() {
3000 return stateMap.get("CurrentLEDState");
3003 public boolean isLedOn() {
3004 return "On".equals(getLed());
3007 public @Nullable String getCurrentZoneName() {
3008 return stateMap.get("CurrentZoneName");
3011 public @Nullable String getRefreshedCurrentZoneName() {
3012 updateCurrentZoneName();
3013 return getCurrentZoneName();
3017 public void onStatusChanged(boolean status) {
3019 logger.info("UPnP device {} is present (thing {})", getUDN(), getThing().getUID());
3020 if (getThing().getStatus() != ThingStatus.ONLINE) {
3021 updateStatus(ThingStatus.ONLINE);
3022 scheduler.execute(this::poll);
3025 logger.info("UPnP device {} is absent (thing {})", getUDN(), getThing().getUID());
3026 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR);
3030 private @Nullable String getModelNameFromDescriptor() {
3031 URL descriptor = service.getDescriptorURL(this);
3032 if (descriptor != null) {
3033 String sonosModelDescription = SonosXMLParser.parseModelDescription(descriptor);
3034 return sonosModelDescription == null ? null : SonosXMLParser.extractModelName(sonosModelDescription);
3040 private boolean migrateThingType() {
3041 if (getThing().getThingTypeUID().equals(ZONEPLAYER_THING_TYPE_UID)) {
3042 String modelName = getModelNameFromDescriptor();
3043 if (modelName != null && isSupportedModel(modelName)) {
3044 updateSonosThingType(modelName);
3051 private boolean isSupportedModel(String modelName) {
3052 for (ThingTypeUID thingTypeUID : SUPPORTED_KNOWN_THING_TYPES_UIDS) {
3053 if (thingTypeUID.getId().equalsIgnoreCase(modelName)) {
3060 private void updateSonosThingType(String newThingTypeID) {
3061 changeThingType(new ThingTypeUID(SonosBindingConstants.BINDING_ID, newThingTypeID), getConfig());
3065 * Set the sleeptimer duration
3066 * Use String command of format "HH:MM:SS" to set the timer to the desired duration
3067 * Use empty String "" to switch the sleep timer off
3069 public void setSleepTimer(Command command) {
3070 if (command instanceof DecimalType) {
3071 Map<String, String> inputs = new HashMap<>();
3072 inputs.put("InstanceID", "0");
3073 inputs.put("NewSleepTimerDuration", sleepSecondsToTimeStr(((DecimalType) command).longValue()));
3075 this.service.invokeAction(this, "AVTransport", "ConfigureSleepTimer", inputs);
3079 protected void updateSleepTimerDuration() {
3080 Map<String, String> result = service.invokeAction(this, "AVTransport", "GetRemainingSleepTimerDuration", null);
3081 for (String variable : result.keySet()) {
3082 this.onValueReceived(variable, result.get(variable), "AVTransport");
3086 private String sleepSecondsToTimeStr(long sleepSeconds) {
3087 if (sleepSeconds == 0) {
3089 } else if (sleepSeconds < 68400) {
3090 long remainingSeconds = sleepSeconds;
3091 long hours = TimeUnit.SECONDS.toHours(remainingSeconds);
3092 remainingSeconds -= TimeUnit.HOURS.toSeconds(hours);
3093 long minutes = TimeUnit.SECONDS.toMinutes(remainingSeconds);
3094 remainingSeconds -= TimeUnit.MINUTES.toSeconds(minutes);
3095 long seconds = TimeUnit.SECONDS.toSeconds(remainingSeconds);
3096 return String.format("%02d:%02d:%02d", hours, minutes, seconds);
3098 logger.debug("Sonos SleepTimer: Invalid sleep time set. sleep time must be >=0 and < 68400s (24h)");
3103 private long sleepStrTimeToSeconds(String sleepTime) {
3104 String[] units = sleepTime.split(":");
3105 int hours = Integer.parseInt(units[0]);
3106 int minutes = Integer.parseInt(units[1]);
3107 int seconds = Integer.parseInt(units[2]);
3108 return 3600 * hours + 60 * minutes + seconds;