2 * Copyright (c) 2010-2023 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.squeezebox.internal.handler;
15 import static org.openhab.binding.squeezebox.internal.SqueezeBoxBindingConstants.*;
18 import java.net.URISyntaxException;
19 import java.time.Duration;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.List;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.openhab.binding.squeezebox.internal.SqueezeBoxStateDescriptionOptionsProvider;
31 import org.openhab.binding.squeezebox.internal.config.SqueezeBoxPlayerConfig;
32 import org.openhab.binding.squeezebox.internal.model.Favorite;
33 import org.openhab.binding.squeezebox.internal.utils.SqueezeBoxTimeoutException;
34 import org.openhab.core.cache.ExpiringCacheMap;
35 import org.openhab.core.io.net.http.HttpUtil;
36 import org.openhab.core.library.types.DecimalType;
37 import org.openhab.core.library.types.IncreaseDecreaseType;
38 import org.openhab.core.library.types.NextPreviousType;
39 import org.openhab.core.library.types.OnOffType;
40 import org.openhab.core.library.types.PercentType;
41 import org.openhab.core.library.types.PlayPauseType;
42 import org.openhab.core.library.types.RawType;
43 import org.openhab.core.library.types.RewindFastforwardType;
44 import org.openhab.core.library.types.StringType;
45 import org.openhab.core.thing.ChannelUID;
46 import org.openhab.core.thing.Thing;
47 import org.openhab.core.thing.ThingStatus;
48 import org.openhab.core.thing.ThingStatusDetail;
49 import org.openhab.core.thing.ThingStatusInfo;
50 import org.openhab.core.thing.ThingTypeUID;
51 import org.openhab.core.thing.binding.BaseThingHandler;
52 import org.openhab.core.types.Command;
53 import org.openhab.core.types.RefreshType;
54 import org.openhab.core.types.State;
55 import org.openhab.core.types.StateOption;
56 import org.openhab.core.types.UnDefType;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 * The {@link SqueezeBoxPlayerHandler} is responsible for handling states, which
62 * are sent to/from channels.
64 * @author Dan Cunningham - Initial contribution
65 * @author Mark Hilbush - Improved handling of player status, prevent REFRESH from causing exception
66 * @author Mark Hilbush - Implement AudioSink and notifications
67 * @author Mark Hilbush - Added duration channel
68 * @author Patrik Gfeller - Timeout for TTS messages increased from 30 to 90s.
69 * @author Mark Hilbush - Get favorites from server and play favorite
70 * @author Mark Hilbush - Convert sound notification volume from channel to config parameter
71 * @author Mark Hilbush - Add like/unlike functionality
73 public class SqueezeBoxPlayerHandler extends BaseThingHandler implements SqueezeBoxPlayerEventListener {
74 private final Logger logger = LoggerFactory.getLogger(SqueezeBoxPlayerHandler.class);
76 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
77 .singleton(SQUEEZEBOXPLAYER_THING_TYPE);
80 * We need to remember some states to change offsets in volume, time index,
83 protected Map<String, State> stateMap = Collections.synchronizedMap(new HashMap<>());
86 * Keeps current track time
88 private ScheduledFuture<?> timeCounterJob;
91 * Local reference to our bridge
93 private SqueezeBoxServerHandler squeezeBoxServerHandler;
96 * Our mac address, needed everywhere
101 * The server sends us the current time on play/pause/stop events, we
102 * increment it locally from there on
104 private int currentTime = 0;
107 * Our we playing something right now or not, need to keep current track
110 private boolean playing;
113 * Separate volume level for notifications
115 private Integer notificationSoundVolume = null;
117 private String callbackUrl;
119 private SqueezeBoxStateDescriptionOptionsProvider stateDescriptionProvider;
121 private static final ExpiringCacheMap<String, RawType> IMAGE_CACHE = new ExpiringCacheMap<>(
122 TimeUnit.MINUTES.toMillis(15)); // 15min
124 private String likeCommand;
125 private String unlikeCommand;
126 private boolean connected = false;
129 * Creates SqueezeBox Player Handler
132 * @param stateDescriptionProvider
134 public SqueezeBoxPlayerHandler(@NonNull Thing thing, String callbackUrl,
135 SqueezeBoxStateDescriptionOptionsProvider stateDescriptionProvider) {
137 this.callbackUrl = callbackUrl;
138 this.stateDescriptionProvider = stateDescriptionProvider;
142 public void initialize() {
143 mac = getConfig().as(SqueezeBoxPlayerConfig.class).mac;
146 logger.debug("player thing {} initialized with mac {}", getThing().getUID(), mac);
147 if (squeezeBoxServerHandler != null) {
148 // ensure we get an up-to-date connection state
149 squeezeBoxServerHandler.requestPlayers();
154 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
158 private void updateThingStatus() {
159 Thing bridge = getBridge();
160 if (bridge != null) {
161 squeezeBoxServerHandler = (SqueezeBoxServerHandler) bridge.getHandler();
162 ThingStatus bridgeStatus = bridge.getStatus();
164 if (bridgeStatus == ThingStatus.OFFLINE) {
165 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
166 } else if (!this.connected) {
167 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
168 } else if (bridgeStatus == ThingStatus.ONLINE && getThing().getStatus() != ThingStatus.ONLINE) {
169 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
172 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Bridge not found");
177 public void dispose() {
178 // stop our duration counter
179 if (timeCounterJob != null && !timeCounterJob.isCancelled()) {
180 timeCounterJob.cancel(true);
181 timeCounterJob = null;
184 if (squeezeBoxServerHandler != null) {
185 squeezeBoxServerHandler.removePlayerCache(mac);
187 logger.debug("player thing {} disposed for mac {}", getThing().getUID(), mac);
192 public void handleCommand(ChannelUID channelUID, Command command) {
193 if (squeezeBoxServerHandler == null) {
194 logger.debug("Player {} has no server configured, ignoring command: {}", getThing().getUID(), command);
197 // Some of the code below is not designed to handle REFRESH, only reply to channels where cached values exist
198 if (command == RefreshType.REFRESH) {
199 String channelID = channelUID.getId();
200 State newState = stateMap.get(channelID);
201 if (newState != null) {
202 updateState(channelID, newState);
207 switch (channelUID.getIdWithoutGroup()) {
209 if (command.equals(OnOffType.ON)) {
210 squeezeBoxServerHandler.powerOn(mac);
212 squeezeBoxServerHandler.powerOff(mac);
216 if (command.equals(OnOffType.ON)) {
217 squeezeBoxServerHandler.mute(mac);
219 squeezeBoxServerHandler.unMute(mac);
223 if (command.equals(OnOffType.ON)) {
224 squeezeBoxServerHandler.stop(mac);
225 } else if (command.equals(OnOffType.OFF)) {
226 squeezeBoxServerHandler.play(mac);
229 case CHANNEL_PLAY_PAUSE:
230 if (command.equals(OnOffType.ON)) {
231 squeezeBoxServerHandler.play(mac);
232 } else if (command.equals(OnOffType.OFF)) {
233 squeezeBoxServerHandler.pause(mac);
237 if (command.equals(OnOffType.ON)) {
238 squeezeBoxServerHandler.prev(mac);
242 if (command.equals(OnOffType.ON)) {
243 squeezeBoxServerHandler.next(mac);
247 if (command instanceof PercentType) {
248 squeezeBoxServerHandler.setVolume(mac, ((PercentType) command).intValue());
249 } else if (command.equals(IncreaseDecreaseType.INCREASE)) {
250 squeezeBoxServerHandler.volumeUp(mac, currentVolume());
251 } else if (command.equals(IncreaseDecreaseType.DECREASE)) {
252 squeezeBoxServerHandler.volumeDown(mac, currentVolume());
253 } else if (command.equals(OnOffType.OFF)) {
254 squeezeBoxServerHandler.mute(mac);
255 } else if (command.equals(OnOffType.ON)) {
256 squeezeBoxServerHandler.unMute(mac);
259 case CHANNEL_CONTROL:
260 if (command instanceof PlayPauseType) {
261 if (command.equals(PlayPauseType.PLAY)) {
262 squeezeBoxServerHandler.play(mac);
263 } else if (command.equals(PlayPauseType.PAUSE)) {
264 squeezeBoxServerHandler.pause(mac);
267 if (command instanceof NextPreviousType) {
268 if (command.equals(NextPreviousType.NEXT)) {
269 squeezeBoxServerHandler.next(mac);
270 } else if (command.equals(NextPreviousType.PREVIOUS)) {
271 squeezeBoxServerHandler.prev(mac);
274 if (command instanceof RewindFastforwardType) {
275 if (command.equals(RewindFastforwardType.REWIND)) {
276 squeezeBoxServerHandler.setPlayingTime(mac, currentPlayingTime() - 5);
277 } else if (command.equals(RewindFastforwardType.FASTFORWARD)) {
278 squeezeBoxServerHandler.setPlayingTime(mac, currentPlayingTime() + 5);
283 squeezeBoxServerHandler.playUrl(mac, command.toString());
286 if (command.toString().isBlank()) {
287 squeezeBoxServerHandler.unSyncPlayer(mac);
289 squeezeBoxServerHandler.syncPlayer(mac, command.toString());
293 if (command.equals(OnOffType.ON)) {
294 squeezeBoxServerHandler.unSyncPlayer(mac);
297 case CHANNEL_PLAYLIST_INDEX:
298 squeezeBoxServerHandler.playPlaylistItem(mac, ((DecimalType) command).intValue());
300 case CHANNEL_CURRENT_PLAYING_TIME:
301 squeezeBoxServerHandler.setPlayingTime(mac, ((DecimalType) command).intValue());
303 case CHANNEL_CURRENT_PLAYLIST_SHUFFLE:
304 squeezeBoxServerHandler.setShuffleMode(mac, ((DecimalType) command).intValue());
306 case CHANNEL_CURRENT_PLAYLIST_REPEAT:
307 squeezeBoxServerHandler.setRepeatMode(mac, ((DecimalType) command).intValue());
309 case CHANNEL_FAVORITES_PLAY:
310 squeezeBoxServerHandler.playFavorite(mac, command.toString());
313 if (command.equals(OnOffType.ON)) {
314 squeezeBoxServerHandler.rate(mac, likeCommand);
315 } else if (command.equals(OnOffType.OFF)) {
316 squeezeBoxServerHandler.rate(mac, unlikeCommand);
320 if (command instanceof DecimalType) {
321 Duration sleepDuration = Duration.ofMinutes(((DecimalType) command).longValue());
322 if (sleepDuration.isNegative() || sleepDuration.compareTo(Duration.ofDays(1)) > 0) {
323 logger.debug("Sleep timer of {} minutes must be >= 0 and <= 1 day", sleepDuration.toMinutes());
326 squeezeBoxServerHandler.sleep(mac, sleepDuration);
335 public void playerAdded(SqueezeBoxPlayer player) {
336 // Player properties are saved in SqueezeBoxPlayerDiscoveryParticipant
340 public void powerChangeEvent(String mac, boolean power) {
341 updateChannel(mac, CHANNEL_POWER, power ? OnOffType.ON : OnOffType.OFF);
342 if (!power && isMe(mac)) {
348 public synchronized void modeChangeEvent(String mac, String mode) {
349 updateChannel(mac, CHANNEL_CONTROL, "play".equals(mode) ? PlayPauseType.PLAY : PlayPauseType.PAUSE);
350 updateChannel(mac, CHANNEL_PLAY_PAUSE, "play".equals(mode) ? OnOffType.ON : OnOffType.OFF);
351 updateChannel(mac, CHANNEL_STOP, "stop".equals(mode) ? OnOffType.ON : OnOffType.OFF);
353 playing = "play".equalsIgnoreCase(mode);
358 public void sourceChangeEvent(String mac, String source) {
359 updateChannel(mac, CHANNEL_SOURCE, StringType.valueOf(source));
363 public void absoluteVolumeChangeEvent(String mac, int volume) {
364 int newVolume = volume;
365 newVolume = Math.min(100, newVolume);
366 newVolume = Math.max(0, newVolume);
367 updateChannel(mac, CHANNEL_VOLUME, new PercentType(newVolume));
371 public void relativeVolumeChangeEvent(String mac, int volumeChange) {
372 int newVolume = currentVolume() + volumeChange;
373 newVolume = Math.min(100, newVolume);
374 newVolume = Math.max(0, newVolume);
375 updateChannel(mac, CHANNEL_VOLUME, new PercentType(newVolume));
378 logger.trace("Volume changed [{}] for player {}. New volume: {}", volumeChange, mac, newVolume);
383 public void muteChangeEvent(String mac, boolean mute) {
384 updateChannel(mac, CHANNEL_MUTE, mute ? OnOffType.ON : OnOffType.OFF);
388 public void currentPlaylistIndexEvent(String mac, int index) {
389 updateChannel(mac, CHANNEL_PLAYLIST_INDEX, new DecimalType(index));
393 public void currentPlayingTimeEvent(String mac, int time) {
394 updateChannel(mac, CHANNEL_CURRENT_PLAYING_TIME, new DecimalType(time));
401 public void durationEvent(String mac, int duration) {
402 if (getThing().getChannel(CHANNEL_DURATION) == null) {
403 logger.debug("Channel 'duration' does not exist. Delete and readd player thing to pick up channel.");
406 updateChannel(mac, CHANNEL_DURATION, new DecimalType(duration));
410 public void numberPlaylistTracksEvent(String mac, int track) {
411 updateChannel(mac, CHANNEL_NUMBER_PLAYLIST_TRACKS, new DecimalType(track));
415 public void currentPlaylistShuffleEvent(String mac, int shuffle) {
416 updateChannel(mac, CHANNEL_CURRENT_PLAYLIST_SHUFFLE, new DecimalType(shuffle));
420 public void currentPlaylistRepeatEvent(String mac, int repeat) {
421 updateChannel(mac, CHANNEL_CURRENT_PLAYLIST_REPEAT, new DecimalType(repeat));
425 public void titleChangeEvent(String mac, String title) {
426 updateChannel(mac, CHANNEL_TITLE, new StringType(title));
430 public void albumChangeEvent(String mac, String album) {
431 updateChannel(mac, CHANNEL_ALBUM, new StringType(album));
435 public void artistChangeEvent(String mac, String artist) {
436 updateChannel(mac, CHANNEL_ARTIST, new StringType(artist));
440 public void coverArtChangeEvent(String mac, String coverArtUrl) {
441 updateChannel(mac, CHANNEL_COVERART_DATA, createImage(downloadImage(mac, coverArtUrl)));
445 * Download and cache the image data from an URL.
447 * @param url The URL of the image to be downloaded.
448 * @return A RawType object containing the image, null if the content type could not be found or the content type is
451 private RawType downloadImage(String mac, String url) {
452 // Only get the image if this is my PlayerHandler instance
454 if (url != null && !url.isEmpty()) {
455 String sanitizedUrl = sanitizeUrl(url);
456 RawType image = IMAGE_CACHE.putIfAbsentAndGet(url, () -> {
457 logger.debug("Trying to download the content of URL {}", sanitizedUrl);
459 return HttpUtil.downloadImage(url);
460 } catch (IllegalArgumentException e) {
461 logger.debug("IllegalArgumentException when downloading image from {}", sanitizedUrl, e);
466 logger.debug("Failed to download the content of URL {}", sanitizedUrl);
477 * Replaces the password in the URL, if present
479 private String sanitizeUrl(String url) {
480 String sanitizedUrl = url;
482 URI uri = new URI(url);
483 String userInfo = uri.getUserInfo();
484 if (userInfo != null) {
485 String[] userInfoParts = userInfo.split(":");
486 if (userInfoParts.length == 2) {
487 sanitizedUrl = url.replace(userInfoParts[1], "**********");
490 } catch (URISyntaxException e) {
491 // Just return what was passed in
497 * Wrap the given RawType and return it as {@link State} or return {@link UnDefType#UNDEF} if the RawType is null.
499 private State createImage(RawType image) {
501 return UnDefType.UNDEF;
508 public void yearChangeEvent(String mac, String year) {
509 updateChannel(mac, CHANNEL_YEAR, new StringType(year));
513 public void genreChangeEvent(String mac, String genre) {
514 updateChannel(mac, CHANNEL_GENRE, new StringType(genre));
518 public void remoteTitleChangeEvent(String mac, String title) {
519 updateChannel(mac, CHANNEL_REMOTE_TITLE, new StringType(title));
523 public void irCodeChangeEvent(String mac, String ircode) {
525 postCommand(CHANNEL_IRCODE, new StringType(ircode));
530 public void buttonsChangeEvent(String mac, String likeCommand, String unlikeCommand) {
532 this.likeCommand = likeCommand;
533 this.unlikeCommand = unlikeCommand;
534 logger.trace("Player {} got a button change event: like='{}' unlike='{}'", mac, likeCommand, unlikeCommand);
539 public void connectedStateChangeEvent(String mac, boolean connected) {
541 this.connected = connected;
547 public void updateFavoritesListEvent(List<Favorite> favorites) {
548 logger.trace("Player {} updating favorites list with {} favorites", mac, favorites.size());
549 List<StateOption> options = new ArrayList<>();
550 for (Favorite favorite : favorites) {
551 options.add(new StateOption(favorite.shortId, favorite.name));
553 stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_FAVORITES_PLAY), options);
557 * Update a channel if the mac matches our own
563 private void updateChannel(String mac, String channelID, State state) {
565 State prevState = stateMap.put(channelID, state);
566 if (prevState == null || !prevState.equals(state)) {
567 logger.trace("Updating channel {} for thing {} with mac {} to state {}", channelID, getThing().getUID(),
569 updateState(channelID, state);
575 * Helper methods to get the current state of the player
579 int currentVolume() {
580 return cachedStateAsInt(CHANNEL_VOLUME);
583 int currentPlayingTime() {
584 return cachedStateAsInt(CHANNEL_CURRENT_PLAYING_TIME);
587 int currentNumberPlaylistTracks() {
588 return cachedStateAsInt(CHANNEL_NUMBER_PLAYLIST_TRACKS);
591 int currentPlaylistIndex() {
592 return cachedStateAsInt(CHANNEL_PLAYLIST_INDEX);
595 boolean currentPower() {
596 return cachedStateAsBoolean(CHANNEL_POWER, OnOffType.ON);
599 boolean currentStop() {
600 return cachedStateAsBoolean(CHANNEL_STOP, OnOffType.ON);
603 boolean currentControl() {
604 return cachedStateAsBoolean(CHANNEL_CONTROL, PlayPauseType.PLAY);
607 boolean currentMute() {
608 return cachedStateAsBoolean(CHANNEL_MUTE, OnOffType.ON);
611 int currentShuffle() {
612 return cachedStateAsInt(CHANNEL_CURRENT_PLAYLIST_SHUFFLE);
615 int currentRepeat() {
616 return cachedStateAsInt(CHANNEL_CURRENT_PLAYLIST_REPEAT);
619 private boolean cachedStateAsBoolean(String key, @NonNull State activeState) {
620 return activeState.equals(stateMap.get(key));
623 private int cachedStateAsInt(String key) {
624 State state = stateMap.get(key);
625 return state instanceof DecimalType ? ((DecimalType) state).intValue() : 0;
629 * Ticks away when in a play state to keep current track time
631 private void timeCounter() {
632 timeCounterJob = scheduler.scheduleWithFixedDelay(() -> {
634 updateChannel(mac, CHANNEL_CURRENT_PLAYING_TIME, new DecimalType(currentTime++));
636 }, 0, 1, TimeUnit.SECONDS);
639 private boolean isMe(String mac) {
640 return mac.equals(this.mac);
644 * Returns our server handler if set
648 public SqueezeBoxServerHandler getSqueezeBoxServerHandler() {
649 return this.squeezeBoxServerHandler;
653 * Returns the MAC address for this player
657 public String getMac() {
662 * Give the notification player access to the notification timeout
664 public int getNotificationTimeout() {
665 return getConfigAs(SqueezeBoxPlayerConfig.class).notificationTimeout;
669 * Used by the AudioSink to get the volume level that should be used for the notification.
670 * Priority for determining volume is:
671 * - volume is provided in the say/playSound actions
672 * - volume is contained in the player thing's configuration
673 * - current player volume setting
675 public PercentType getNotificationSoundVolume() {
676 // Get the notification sound volume from this player thing's configuration
677 Integer configNotificationSoundVolume = getConfigAs(SqueezeBoxPlayerConfig.class).notificationVolume;
679 // Determine which volume to use
680 Integer currentNotificationSoundVolume;
681 if (notificationSoundVolume != null) {
682 currentNotificationSoundVolume = notificationSoundVolume;
683 } else if (configNotificationSoundVolume != null) {
684 currentNotificationSoundVolume = configNotificationSoundVolume;
686 currentNotificationSoundVolume = Integer.valueOf(currentVolume());
688 return new PercentType(currentNotificationSoundVolume.intValue());
692 * Used by the AudioSink to set the volume level that should be used to play the notification
694 public void setNotificationSoundVolume(PercentType newNotificationSoundVolume) {
695 if (newNotificationSoundVolume != null) {
696 notificationSoundVolume = Integer.valueOf(newNotificationSoundVolume.intValue());
701 * Play the notification.
703 public void playNotificationSoundURI(StringType uri) {
704 logger.debug("Play notification sound on player {} at URI {}", mac, uri);
706 try (SqueezeBoxNotificationPlayer notificationPlayer = new SqueezeBoxNotificationPlayer(this,
707 squeezeBoxServerHandler, uri)) {
708 notificationPlayer.play();
709 } catch (InterruptedException e) {
710 logger.warn("Notification playback was interrupted", e);
711 } catch (SqueezeBoxTimeoutException e) {
712 logger.debug("SqueezeBoxTimeoutException during notification: {}", e.getMessage());
714 notificationSoundVolume = null;
719 * Return the IP and port of the OH2 web server
721 public String getHostAndPort() {