This repository has been archived by the owner on Sep 21, 2020. It is now read-only.
/
SqueezeBoxPlayerHandler.java
942 lines (833 loc) · 32.8 KB
/
SqueezeBoxPlayerHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
/**
* Copyright (c) 2010-2017 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.squeezebox.handler;
import static org.openhab.binding.squeezebox.SqueezeBoxBindingConstants.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType;
import org.eclipse.smarthome.core.library.types.NextPreviousType;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.library.types.PlayPauseType;
import org.eclipse.smarthome.core.library.types.RawType;
import org.eclipse.smarthome.core.library.types.RewindFastforwardType;
import org.eclipse.smarthome.core.library.types.StringType;
import org.eclipse.smarthome.core.net.HttpServiceUtil;
import org.eclipse.smarthome.core.net.NetUtil;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.ThingStatusInfo;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.binding.BaseThingHandler;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.eclipse.smarthome.core.types.State;
import org.openhab.binding.squeezebox.SqueezeBoxBindingConstants;
import org.openhab.binding.squeezebox.config.SqueezeBoxPlayerConfig;
import org.openhab.binding.squeezebox.internal.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link SqueezeBoxPlayerHandler} is responsible for handling states, which
* are sent to/from channels.
*
* @author Dan Cunningham - Initial contribution
* @author Mark Hilbush - Improved handling of player status, prevent REFRESH from causing exception
* @author Mark Hilbush - Implement AudioSink and notifications
* @author Mark Hilbush - Added duration channel
*/
public class SqueezeBoxPlayerHandler extends BaseThingHandler implements SqueezeBoxPlayerEventListener {
private Logger logger = LoggerFactory.getLogger(SqueezeBoxPlayerHandler.class);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
.singleton(SQUEEZEBOXPLAYER_THING_TYPE);
/**
* We need to remember some states to change offsets in volume, time index,
* etc..
*/
protected Map<String, State> stateMap = Collections.synchronizedMap(new HashMap<String, State>());
/**
* Keeps current track time
*/
ScheduledFuture<?> timeCounterJob;
/**
* Local reference to our bridge
*/
private SqueezeBoxServerHandler squeezeBoxServerHandler;
/**
* Our mac address, needed everywhere
*/
private String mac;
/**
* Before we mute or recieve a mute event, store our current volume
*/
private int unmuteVolume = 0;
/**
* The server sends us the current time on play/pause/stop events, we
* increment it locally from there on
*/
private int currentTime = 0;
/**
* Our we playing something right now or not, need to keep current track
* time
*/
private boolean playing;
/**
* Separate volume level for notifications
*/
private int notificationSoundVolume = -1;
/**
* Creates SqueezeBox Player Handler
*
* @param thing
*/
public SqueezeBoxPlayerHandler(Thing thing) {
super(thing);
}
@Override
public void initialize() {
mac = getConfig().as(SqueezeBoxPlayerConfig.class).mac;
timeCounter();
updateBridgeStatus();
}
@Override
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
updateBridgeStatus();
}
private void updateBridgeStatus() {
ThingStatus bridgeStatus = getBridge().getStatus();
if (bridgeStatus == ThingStatus.ONLINE && getThing().getStatus() != ThingStatus.ONLINE) {
updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
squeezeBoxServerHandler = (SqueezeBoxServerHandler) getBridge().getHandler();
} else if (bridgeStatus == ThingStatus.OFFLINE) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
}
}
@Override
public void dispose() {
// stop our duration counter
if (timeCounterJob != null && !timeCounterJob.isCancelled()) {
timeCounterJob.cancel(true);
timeCounterJob = null;
}
if (squeezeBoxServerHandler != null) {
squeezeBoxServerHandler.removePlayerCache(mac);
}
logger.debug("player thing {} disposed.", getThing().getUID());
super.dispose();
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (squeezeBoxServerHandler == null) {
logger.info("player thing {} has no server configured, ignoring command: {}", getThing().getUID(), command);
return;
}
String mac = getConfigAs(SqueezeBoxPlayerConfig.class).mac;
// Some of the code below is not designed to handle REFRESH
if (command == RefreshType.REFRESH) {
return;
}
switch (channelUID.getIdWithoutGroup()) {
case CHANNEL_POWER:
if (command.equals(OnOffType.ON)) {
squeezeBoxServerHandler.powerOn(mac);
} else {
squeezeBoxServerHandler.powerOff(mac);
}
break;
case CHANNEL_MUTE:
if (command.equals(OnOffType.ON)) {
mute();
} else {
squeezeBoxServerHandler.unMute(mac, unmuteVolume);
}
break;
case CHANNEL_STOP:
if (command.equals(OnOffType.ON)) {
squeezeBoxServerHandler.stop(mac);
} else if (command.equals(OnOffType.OFF)) {
squeezeBoxServerHandler.play(mac);
}
break;
case CHANNEL_PLAY_PAUSE:
if (command.equals(OnOffType.ON)) {
squeezeBoxServerHandler.play(mac);
} else if (command.equals(OnOffType.OFF)) {
squeezeBoxServerHandler.pause(mac);
}
break;
case CHANNEL_PREV:
if (command.equals(OnOffType.ON)) {
squeezeBoxServerHandler.prev(mac);
}
break;
case CHANNEL_NEXT:
if (command.equals(OnOffType.ON)) {
squeezeBoxServerHandler.next(mac);
}
break;
case CHANNEL_VOLUME:
if (command instanceof PercentType) {
squeezeBoxServerHandler.setVolume(mac, ((PercentType) command).intValue());
} else if (command.equals(IncreaseDecreaseType.INCREASE)) {
squeezeBoxServerHandler.volumeUp(mac, currentVolume());
} else if (command.equals(IncreaseDecreaseType.DECREASE)) {
squeezeBoxServerHandler.volumeDown(mac, currentVolume());
} else if (command.equals(OnOffType.OFF)) {
mute();
} else if (command.equals(OnOffType.ON)) {
squeezeBoxServerHandler.unMute(mac, unmuteVolume);
}
break;
case CHANNEL_CONTROL:
if (command instanceof PlayPauseType) {
if (command.equals(PlayPauseType.PLAY)) {
squeezeBoxServerHandler.play(mac);
} else if (command.equals(PlayPauseType.PAUSE)) {
squeezeBoxServerHandler.pause(mac);
}
}
if (command instanceof NextPreviousType) {
if (command.equals(NextPreviousType.NEXT)) {
squeezeBoxServerHandler.next(mac);
} else if (command.equals(NextPreviousType.PREVIOUS)) {
squeezeBoxServerHandler.prev(mac);
}
}
if (command instanceof RewindFastforwardType) {
if (command.equals(RewindFastforwardType.REWIND)) {
squeezeBoxServerHandler.setPlayingTime(mac, currentPlayingTime() - 5);
} else if (command.equals(RewindFastforwardType.FASTFORWARD)) {
squeezeBoxServerHandler.setPlayingTime(mac, currentPlayingTime() + 5);
}
}
break;
case CHANNEL_STREAM:
squeezeBoxServerHandler.playUrl(mac, command.toString());
break;
case CHANNEL_SYNC:
if (StringUtils.isBlank(command.toString())) {
squeezeBoxServerHandler.unSyncPlayer(mac);
} else {
squeezeBoxServerHandler.syncPlayer(mac, command.toString());
}
break;
case CHANNEL_UNSYNC:
if (command.equals(OnOffType.ON)) {
squeezeBoxServerHandler.unSyncPlayer(mac);
}
break;
case CHANNEL_PLAYLIST_INDEX:
squeezeBoxServerHandler.playPlaylistItem(mac, ((DecimalType) command).intValue());
break;
case CHANNEL_CURRENT_PLAYING_TIME:
squeezeBoxServerHandler.setPlayingTime(mac, ((DecimalType) command).intValue());
break;
case CHANNEL_CURRENT_PLAYLIST_SHUFFLE:
squeezeBoxServerHandler.setShuffleMode(mac, ((DecimalType) command).intValue());
break;
case CHANNEL_CURRENT_PLAYLIST_REPEAT:
squeezeBoxServerHandler.setRepeatMode(mac, ((DecimalType) command).intValue());
break;
case CHANNEL_NOTIFICATION_SOUND_VOLUME:
setNotificationSoundVolume(((PercentType) command));
break;
default:
break;
}
}
@Override
public void playerAdded(SqueezeBoxPlayer player) {
// Player properties are saved in SqueezeBoxPlayerDiscoveryParticipant
}
@Override
public void powerChangeEvent(String mac, boolean power) {
updateChannel(mac, CHANNEL_POWER, power ? OnOffType.ON : OnOffType.OFF);
if (!power && isMe(mac)) {
playing = false;
}
}
@Override
public synchronized void modeChangeEvent(String mac, String mode) {
updateChannel(mac, CHANNEL_CONTROL, "play".equals(mode) ? PlayPauseType.PLAY : PlayPauseType.PAUSE);
updateChannel(mac, CHANNEL_STOP, mode.equals("stop") ? OnOffType.ON : OnOffType.OFF);
if (isMe(mac)) {
playing = "play".equalsIgnoreCase(mode);
}
}
@Override
public void volumeChangeEvent(String mac, int volume) {
volume = Math.min(100, volume);
volume = Math.max(0, volume);
updateChannel(mac, CHANNEL_VOLUME, new PercentType(volume));
}
@Override
public void muteChangeEvent(String mac, boolean mute) {
unmuteVolume = currentVolume();
updateChannel(mac, CHANNEL_MUTE, mute ? OnOffType.ON : OnOffType.OFF);
}
@Override
public void currentPlaylistIndexEvent(String mac, int index) {
updateChannel(mac, CHANNEL_PLAYLIST_INDEX, new DecimalType(index));
}
@Override
public void currentPlayingTimeEvent(String mac, int time) {
updateChannel(mac, CHANNEL_CURRENT_PLAYING_TIME, new DecimalType(time));
if (isMe(mac)) {
currentTime = time;
}
}
@Override
public void durationEvent(String mac, int duration) {
if (getThing().getChannel(CHANNEL_DURATION) == null) {
logger.debug("Channel 'duration' does not exist. Delete and readd player thing to pick up channel.");
return;
}
updateChannel(mac, CHANNEL_DURATION, new DecimalType(duration));
}
@Override
public void numberPlaylistTracksEvent(String mac, int track) {
updateChannel(mac, CHANNEL_NUMBER_PLAYLIST_TRACKS, new DecimalType(track));
}
@Override
public void currentPlaylistShuffleEvent(String mac, int shuffle) {
updateChannel(mac, CHANNEL_CURRENT_PLAYLIST_SHUFFLE, new DecimalType(shuffle));
}
@Override
public void currentPlaylistRepeatEvent(String mac, int repeat) {
updateChannel(mac, CHANNEL_CURRENT_PLAYLIST_REPEAT, new DecimalType(repeat));
}
@Override
public void titleChangeEvent(String mac, String title) {
updateChannel(mac, CHANNEL_TITLE, new StringType(title));
}
@Override
public void albumChangeEvent(String mac, String album) {
updateChannel(mac, CHANNEL_ALBUM, new StringType(album));
}
@Override
public void artistChangeEvent(String mac, String artist) {
updateChannel(mac, CHANNEL_ARTIST, new StringType(artist));
}
@Override
public void coverArtChangeEvent(String mac, String coverArtUrl) {
try {
byte[] data = HttpUtils.getData(coverArtUrl);
updateChannel(mac, CHANNEL_COVERART_DATA, new RawType(data));
} catch (Exception e) {
logger.debug("Could not get album art data", e);
}
}
@Override
public void yearChangeEvent(String mac, String year) {
updateChannel(mac, CHANNEL_YEAR, new StringType(year));
}
@Override
public void genreChangeEvent(String mac, String genre) {
updateChannel(mac, CHANNEL_GENRE, new StringType(genre));
}
@Override
public void remoteTitleChangeEvent(String mac, String title) {
updateChannel(mac, CHANNEL_REMOTE_TITLE, new StringType(title));
}
@Override
public void irCodeChangeEvent(String mac, String ircode) {
if (isMe(mac)) {
postCommand(CHANNEL_IRCODE, new StringType(ircode));
}
}
/**
* Update a channel if the mac matches our own
*
* @param mac
* @param channelID
* @param state
*/
private void updateChannel(String mac, String channelID, State state) {
if (isMe(mac)) {
State prevState = stateMap.put(channelID, state);
if (prevState == null || !prevState.equals(state)) {
logger.trace("Updating channel {} for thing {} with mac {} to state {}", channelID, getThing().getUID(),
mac, state);
try {
updateState(channelID, state);
} catch (Exception e) {
logger.error("Could not update channel", e);
}
}
}
}
/**
* Helper method to mute a player
*/
private void mute() {
unmuteVolume = currentVolume();
squeezeBoxServerHandler.mute(mac);
}
/**
* Helper methods to get the current state of the player
*
* @return
*/
private int currentVolume() {
if (stateMap.containsKey(CHANNEL_VOLUME)) {
return ((DecimalType) stateMap.get(CHANNEL_VOLUME)).intValue();
} else {
return 0;
}
}
private int currentPlayingTime() {
if (stateMap.containsKey(CHANNEL_CURRENT_PLAYING_TIME)) {
return ((DecimalType) stateMap.get(CHANNEL_CURRENT_PLAYING_TIME)).intValue();
} else {
return 0;
}
}
private int currentNumberPlaylistTracks() {
if (stateMap.containsKey(CHANNEL_NUMBER_PLAYLIST_TRACKS)) {
return ((DecimalType) stateMap.get(CHANNEL_NUMBER_PLAYLIST_TRACKS)).intValue();
} else {
return 0;
}
}
private int currentPlaylistIndex() {
if (stateMap.containsKey(CHANNEL_PLAYLIST_INDEX)) {
return ((DecimalType) stateMap.get(CHANNEL_PLAYLIST_INDEX)).intValue();
} else {
return 0;
}
}
private boolean currentPower() {
if (stateMap.containsKey(CHANNEL_POWER)) {
return (stateMap.get(CHANNEL_POWER).equals(OnOffType.ON) ? true : false);
} else {
return false;
}
}
private boolean currentStop() {
if (stateMap.containsKey(CHANNEL_STOP)) {
return (stateMap.get(CHANNEL_STOP).equals(OnOffType.ON) ? true : false);
} else {
return false;
}
}
private boolean currentControl() {
if (stateMap.containsKey(CHANNEL_CONTROL)) {
return (stateMap.get(CHANNEL_CONTROL).equals(PlayPauseType.PLAY) ? true : false);
} else {
return false;
}
}
private boolean currentMute() {
if (stateMap.containsKey(CHANNEL_MUTE)) {
return (stateMap.get(CHANNEL_MUTE).equals(OnOffType.ON) ? true : false);
} else {
return false;
}
}
private int currentShuffle() {
if (stateMap.containsKey(CHANNEL_CURRENT_PLAYLIST_SHUFFLE)) {
return ((DecimalType) stateMap.get(CHANNEL_CURRENT_PLAYLIST_SHUFFLE)).intValue();
} else {
return 0;
}
}
private int currentRepeat() {
if (stateMap.containsKey(CHANNEL_CURRENT_PLAYLIST_REPEAT)) {
return ((DecimalType) stateMap.get(CHANNEL_CURRENT_PLAYLIST_REPEAT)).intValue();
} else {
return 0;
}
}
/**
* Ticks away when in a play state to keep current track time
*/
private void timeCounter() {
Runnable runnable = new Runnable() {
@Override
public void run() {
if (playing) {
updateChannel(mac, CHANNEL_CURRENT_PLAYING_TIME, new DecimalType(currentTime++));
}
}
};
timeCounterJob = scheduler.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
}
private boolean isMe(String mac) {
return mac.equals(this.mac);
}
/**
* Returns our server handler if set
*
* @return
*/
public SqueezeBoxServerHandler getSqueezeBoxServerHandler() {
return this.squeezeBoxServerHandler;
}
/**
* Returns the MAC address for this player
*
* @return
*/
public String getMac() {
return this.mac;
}
/*
* The following methods were added to enable notifications using the ESH AudioSink
*/
public PercentType getNotificationSoundVolume() {
if (notificationSoundVolume == -1) {
// Initialize the value for the first time
logger.debug("Initializing notification volume to current player volume");
notificationSoundVolume = currentVolume();
if (notificationSoundVolume != 0) {
updateState(SqueezeBoxBindingConstants.CHANNEL_NOTIFICATION_SOUND_VOLUME,
new PercentType(notificationSoundVolume));
}
}
return PercentType.valueOf(String.valueOf(notificationSoundVolume));
}
public void setNotificationSoundVolume(PercentType volume) {
if (volume != null) {
logger.debug("Set notification volume to: {}", volume.toString());
notificationSoundVolume = volume.intValue();
}
}
/*
* Play the notification by 1) saving the state of the player, 2) stopping the current
* playlist item, 3) adding the notification as a new playlist item, 4) playing the
* new playlist item, and 5) restoring the player to its previous state.
*/
public void playNotificationSoundURI(StringType uri) {
logger.debug("Play notification sound on player {} at URI {}", mac, uri);
SqueezeBoxPlayerState playerState = new SqueezeBoxPlayerState();
playNotification(playerState, uri);
}
private void playNotification(SqueezeBoxPlayerState playerState, StringType uri) {
if (squeezeBoxServerHandler == null) {
logger.warn("Server handler is null in playNotification");
return;
}
logger.debug("Setting up player for notification");
if (!playerState.isPoweredOn()) {
logger.debug("Powering on the player");
squeezeBoxServerHandler.powerOn(mac);
}
if (playerState.isShuffling()) {
logger.debug("Turning off shuffle");
squeezeBoxServerHandler.setShuffleMode(mac, 0);
}
if (playerState.isRepeating()) {
logger.debug("Turning off repeat");
squeezeBoxServerHandler.setRepeatMode(mac, 0);
}
if (playerState.isPlaying()) {
squeezeBoxServerHandler.stop(mac);
}
int notificationVolume = getNotificationSoundVolume().intValue();
squeezeBoxServerHandler.setVolume(mac, notificationVolume);
waitForVolume(notificationVolume);
// Add the notification uri to the playlist, get the playlist item index, then play
logger.debug("Playing notification");
squeezeBoxServerHandler.addPlaylistItem(mac, uri.toString());
if (!waitForPlaylistUpdate()) {
// Give up since we timed out waiting for playlist to update
squeezeBoxServerHandler.setVolume(mac, playerState.getVolume());
waitForVolume(playerState.getVolume());
return;
}
int newNumberPlaylistTracks = currentNumberPlaylistTracks();
squeezeBoxServerHandler.playPlaylistItem(mac, newNumberPlaylistTracks - 1);
waitForNotification();
logger.debug("Restoring player state");
// Mute the player to prevent any noise during the transition to previous state
squeezeBoxServerHandler.setVolume(mac, 0);
waitForVolume(0);
// Remove the notification uri from the playlist
squeezeBoxServerHandler.deletePlaylistItem(mac, newNumberPlaylistTracks - 1);
waitForPlaylistUpdate();
// Resume playing save playlist item if player wasn't stopped
if (!playerState.isStopped()) {
logger.debug("Resuming last item playing");
squeezeBoxServerHandler.playPlaylistItem(mac, playerState.getPlaylistIndex());
waitForPlaylistUpdate();
// Note that setting the time doesn't work for remote streams
squeezeBoxServerHandler.setPlayingTime(mac, playerState.getPlayingTime());
}
if (playerState.isStopped()) {
logger.debug("Stopping the player");
squeezeBoxServerHandler.stop(mac);
} else if (playerState.isPlaying()) {
logger.debug("Playing the playlist item");
// Nothing to do; should already be playing due to call to playPlaylistItem above
} else {
logger.debug("Pausing the player");
// Sometimes the first couple pauses don't work (really!)
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
int count;
final int maxPauseAttempts = 4;
for (count = 0; count < maxPauseAttempts; count++) {
squeezeBoxServerHandler.pause(mac);
if (waitForPause()) {
break;
}
}
if (count == maxPauseAttempts) {
// Unable to pause, try to stop
squeezeBoxServerHandler.stop(mac);
}
}
// Now we can restore the volume and the remaining state items
squeezeBoxServerHandler.setVolume(mac, playerState.getVolume());
waitForVolume(playerState.getVolume());
if (playerState.isShuffling()) {
logger.debug("Restoring shuffle mode");
squeezeBoxServerHandler.setShuffleMode(mac, playerState.getShuffle());
}
if (playerState.isRepeating()) {
logger.debug("Restoring repeat mode");
squeezeBoxServerHandler.setRepeatMode(mac, playerState.getRepeat());
}
if (playerState.isMuted()) {
logger.debug("Re-muting the player");
squeezeBoxServerHandler.mute(mac);
}
if (!playerState.isPoweredOn()) {
logger.debug("Powering off the player");
squeezeBoxServerHandler.powerOff(mac);
}
}
/*
* Monitor the number of playlist entries. When it changes, then we know the playlist
* has been updated with the notification URL. There's probably an edge case here where
* someone is updating the playlist at the same time, but that should be rare.
*/
private boolean waitForPlaylistUpdate() {
final int timeoutMaxCount = 50;
SqueezeBoxNotificationListener listener = new SqueezeBoxNotificationListener(mac);
squeezeBoxServerHandler.registerSqueezeBoxPlayerListener(listener);
logger.trace("Waiting up to {} ms for playlist to be updated...", timeoutMaxCount * 100);
listener.resetPlaylistUpdated();
int timeoutCount = 0;
while (!listener.isPlaylistUpdated() && timeoutCount < timeoutMaxCount) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
timeoutCount++;
}
squeezeBoxServerHandler.unregisterSqueezeBoxPlayerListener(listener);
listener = null;
return checkForTimeout(timeoutCount, timeoutMaxCount, "playlist to update");
}
/*
* Monitor the status of the notification so that we know when it has finished playing
*/
private boolean waitForNotification() {
final int timeoutMaxCount = 300;
SqueezeBoxNotificationListener listener = new SqueezeBoxNotificationListener(mac);
squeezeBoxServerHandler.registerSqueezeBoxPlayerListener(listener);
logger.trace("Waiting up to {} ms for stop...", timeoutMaxCount * 100);
listener.resetStopped();
int timeoutCount = 0;
while (!listener.isStopped() && timeoutCount < timeoutMaxCount) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
timeoutCount++;
}
squeezeBoxServerHandler.unregisterSqueezeBoxPlayerListener(listener);
listener = null;
return checkForTimeout(timeoutCount, timeoutMaxCount, "stop");
}
/*
* Wait for the volume status to equal the targetVolume
*/
private boolean waitForVolume(int targetVolume) {
final int timeoutMaxCount = 40;
SqueezeBoxNotificationListener listener = new SqueezeBoxNotificationListener(mac);
squeezeBoxServerHandler.registerSqueezeBoxPlayerListener(listener);
logger.trace("Waiting up to {} ms for volume to update...", timeoutMaxCount * 100);
listener.resetVolumeUpdated();
int timeoutCount = 0;
while (!listener.isVolumeUpdated(targetVolume) && timeoutCount < timeoutMaxCount) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
timeoutCount++;
}
squeezeBoxServerHandler.unregisterSqueezeBoxPlayerListener(listener);
listener = null;
return checkForTimeout(timeoutCount, timeoutMaxCount, "volume to update");
}
/*
* Wait for the mode to reflect that the player is paused
*/
private boolean waitForPause() {
final int timeoutMaxCount = 25;
SqueezeBoxNotificationListener listener = new SqueezeBoxNotificationListener(mac);
squeezeBoxServerHandler.registerSqueezeBoxPlayerListener(listener);
logger.trace("Waiting up to {} ms for player to pause...", timeoutMaxCount * 100);
listener.resetPaused();
int timeoutCount = 0;
while (!listener.isPaused() && timeoutCount < timeoutMaxCount) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
timeoutCount++;
}
squeezeBoxServerHandler.unregisterSqueezeBoxPlayerListener(listener);
listener = null;
return checkForTimeout(timeoutCount, timeoutMaxCount, "player to pause");
}
private boolean checkForTimeout(int timeoutCount, int timeoutLimit, String message) {
if (timeoutCount >= timeoutLimit) {
logger.warn("TIMEOUT after {} waiting for {}!", timeoutCount * 100, message);
return false;
}
logger.debug("Done waiting {} ms for {}", timeoutCount * 100, message);
return true;
}
/*
* Return the IP and port of the OH2 web server (assumes the primary ipv4 interface
* is where the web server is listening)
*/
public String getHostAndPort() {
final String ipAddress = NetUtil.getLocalIpv4HostAddress();
if (ipAddress == null) {
logger.warn("No network interface could be found");
return null;
}
// Get the HTTP (non-SSL) port
final int port = HttpServiceUtil.getHttpServicePort(bundleContext);
if (port == -1) {
logger.warn("Cannot find port of the http service");
return null;
}
return new String("http://" + ipAddress + ":" + port);
}
/**
* The {@link SqueezeBoxPlayerState} is responsible for saving the state of a player.
*
* @author Mark Hilbush - Added support for AudioSink and notifications
*/
public class SqueezeBoxPlayerState {
int savedVolume;
boolean savedMute;
boolean savedPower;
boolean savedStop;
boolean savedControl;
int savedShuffle;
int savedRepeat;
int savedPlaylistIndex;
int savedNumberPlaylistTracks;
int savedPlayingTime;
public SqueezeBoxPlayerState() {
save();
}
private boolean isMuted() {
return savedMute;
}
private boolean isPoweredOn() {
return savedPower;
}
private boolean isStopped() {
return savedStop;
}
private boolean isPlaying() {
return savedControl;
}
private boolean isShuffling() {
return savedShuffle == 0 ? false : true;
}
private int getShuffle() {
return savedShuffle;
}
private boolean isRepeating() {
return savedRepeat == 0 ? false : true;
}
private int getRepeat() {
return savedRepeat;
}
private int getVolume() {
return savedVolume;
}
private int getPlaylistIndex() {
return savedPlaylistIndex;
}
private int getNumberPlaylistTracks() {
return savedNumberPlaylistTracks;
}
private int getPlayingTime() {
return savedPlayingTime;
}
private void save() {
savedVolume = currentVolume();
savedMute = currentMute();
savedPower = currentPower();
savedStop = currentStop();
savedControl = currentControl();
savedShuffle = currentShuffle();
savedRepeat = currentRepeat();
savedPlaylistIndex = currentPlaylistIndex();
savedNumberPlaylistTracks = currentNumberPlaylistTracks();
savedPlayingTime = currentPlayingTime();
logger.debug("Cur State: vol={}, mut={}, pwr={}, stp={}, ctl={}, shf={}, rpt={}, tix={}, tnm={}, tim={}",
savedVolume, muteAsString(), powerAsString(), stopAsString(), controlAsString(), shuffleAsString(),
repeatAsString(), getPlaylistIndex(), getNumberPlaylistTracks(), getPlayingTime());
}
private String muteAsString() {
return isMuted() ? "MUTED" : "NOT MUTED";
}
private String powerAsString() {
return isPoweredOn() ? "ON" : "OFF";
}
private String stopAsString() {
return isStopped() ? "STOPPED" : "NOT STOPPED";
}
private String controlAsString() {
return isPlaying() ? "PLAYING" : "PAUSED";
}
private String shuffleAsString() {
String shuffle = "OFF";
if (getShuffle() == 1) {
shuffle = "SONG";
} else if (getShuffle() == 2) {
shuffle = "ALBUM";
}
return shuffle;
}
private String repeatAsString() {
String repeat = "OFF";
if (getRepeat() == 1) {
repeat = "SONG";
} else if (getRepeat() == 2) {
repeat = "PLAYLIST";
}
return repeat;
}
}
}