def do(self, params): speaker = SoCo(socket.gethostbyname(params['host'])) print(speaker.groups) if 'volume' in params: speaker.volume = params['volume'] if 'clear_queue' in params: speaker.clear_queue() if 'add_playlist_id_to_queue' in params: playlist = speaker.get_sonos_playlists()[ params['add_playlist_id_to_queue']] speaker.add_uri_to_queue(playlist.resources[0].uri) if 'switch_to_tv' in params: speaker.switch_to_tv() if 'next' in params: speaker.next() elif 'previous' in params: speaker.previous() if 'play' in params: speaker.play() elif 'pause' in params: speaker.pause() if 'set_sleep_timer' in params: speaker.set_sleep_timer(params['set_sleep_timer'] * 60)
def action(player: SoCo, action: str): if action == 'play': player.play() elif action == 'stop': player.stop() elif action == 'pause': player.pause() elif action == 'next': player.next() elif action == 'previous': player.previous()
def sexy_time(): # connect to the Sonos sonos = SoCo(SONOS_IP) # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # get queue queue = sonos.get_queue() # if we: # * already have a queue # * music is playing # * we are already playing a queue that begins with "Let's Get It On" # ...then skip to the next track if len(queue) > 0 and \ sonos.get_current_transport_info()['current_transport_state'] == "PLAYING" and \ queue[0].title == SEXY_TIME_FIRST_TRACK: sonos.next() # else, intitiate a fresh Sexy Time else: # clear Sonos queue sonos.clear_queue() # turn off shuffle and repeat sonos.play_mode = 'NORMAL' # set volume sonos.volume = 45 # play Sexy Time playlist playlist = get_sonos_playlist(sonos, SEXY_TIME_PLAYLIST_NAME) if playlist: sonos.add_to_queue(playlist) sonos.play() # dim the lights (bri out of 254) over the pre-defined amount of time command = { 'transitiontime': (SEXY_TIME_DIMMER_SECONDS * 10), 'on': True, 'bri': SEXY_TIME_DIMMER_BRIGHTNESS } hue.set_light(1, command) return jsonify(status="success")
def sonos_next(self): """Afspeellijst <Next> button, gaat naar volgende nummer in afspeellijst. """ # pagina laden voor als antwoord terug aan de server h = queuebeheer_temp.sonos_next() ## sonos = SoCo(COORDINATOR) sonos.next() return h
def sonos(command, volume=-1): s = SoCo(app.config['SONOS']) try: if command == 'play': s.play() elif command == 'pause': s.pause() elif command =='volume': logging.info('Setting volume of Sonos to %d' % volume) s.volume(volume) elif command == 'next': s.next() elif command == 'previous': s.previous() return "OK" except: return "FAIL"
def arriving_home(): # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # set the lights to approximately 80% over 3 seconds command = { 'transitiontime': 30, 'on': True, 'bri': 203 } hue.set_light(1, command) # connect to the Sonos sonos = SoCo(SONOS_IP) # clear the queue sonos.clear_queue() # set volume sonos.volume = 25 # play Arriving Home playlist playlist = get_sonos_playlist(sonos, ARRIVING_HOME_PLAYLIST_NAME) print playlist if playlist: sonos.add_to_queue(playlist) # turn on shuffle, turn off repeat sonos.play_mode = 'SHUFFLE_NOREPEAT' # play sonos.play() # we're in shuffle mode, but the first track is always the same sonos.next() return jsonify(status="success")
def arriving_home(): # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # set the lights to appropriate brightness over appropriate time command = { 'transitiontime': (ARRIVING_HOME_DIMMER_SECONDS * 10), 'on': True, 'bri': ARRIVING_HOME_DIMMER_BRIGHTNESS } hue.set_light(ARRIVING_HOME_LIGHTS, command) # connect to the Sonos sonos = SoCo(SONOS_IP) # clear the queue sonos.clear_queue() # set volume sonos.volume = ARRIVING_HOME_VOLUME # play Arriving Home playlist playlist = get_sonos_playlist(sonos, ARRIVING_HOME_PLAYLIST_NAME) if playlist: sonos.add_to_queue(playlist) # turn on shuffle, turn off repeat sonos.play_mode = 'SHUFFLE_NOREPEAT' # play sonos.play() # we're in shuffle mode, but the first track is always the same sonos.next() return jsonify(status="success")
def party(): # connect to the Sonos sonos = SoCo(SONOS_IP) # get queue queue = sonos.get_queue() # if we: # * already have a queue # * music is playing # ...then skip to the next track if len(queue) > 0 and sonos.get_current_transport_info()['current_transport_state'] == "PLAYING": sonos.next() # else, intitiate a fresh Party Time else: # clear Sonos queue sonos.clear_queue() # turn on shuffle, turn off repeat sonos.play_mode = 'SHUFFLE_NOREPEAT' # set volume sonos.volume = 45 # play Party playlist playlist = get_sonos_playlist(sonos, PARTY_TIME_PLAYLIST_NAME) if playlist: sonos.add_to_queue(playlist) sonos.play() return jsonify(status="success")
elif action == 'v-5': # Decrease volume current_vol = sonos.volume new_vol = current_vol - 5 if new_vol < 0: new_vol = 0 sonos.ramp_to_volume(new_vol) elif action == 'mute': # Mute Volume sonos.volume = 0 elif action == 'next': # Next Song (might be unsupported by playback source e.g. streams) try: sonos.next() except SoCoUPnPException: print '[{"icon": "font-awesome:times-circle", "title": "Not supported for current playback source."}]' elif action == 'prev': # Previous Song (might be unsupported by playback source e.g. streams) try: sonos.previous() except SoCoUPnPException: print '[{"icon": "font-awesome:times-circle", "title": "Not supported for current playback source."}]' elif action == 'set_zone': # Used during setup to save preferred zone settings_file_path = os.path.join(os.getenv('LB_SUPPORT_PATH'), 'settings.json') settings = {'zone_ip_address': sonos_zone}
if __name__ == '__main__': if (len(sys.argv) != 3): print "Usage: sonoshell.py [speaker's IP] [cmd]" print "" print "Valid commands: play, pause, stop, next, previous, current, and partymode" sys.exit() speaker_ip = sys.argv[1] cmd = sys.argv[2].lower() sonos = SoCo(speaker_ip) if (cmd == 'partymode'): print sonos.partymode() elif (cmd == 'play'): print sonos.play() elif (cmd == 'pause'): print sonos.pause() elif (cmd == 'stop'): print sonos.stop() elif (cmd == 'next'): print sonos.next() elif (cmd == 'previous'): print sonos.previous() elif (cmd == 'current'): track = sonos.get_current_track_info() print 'Current track: ' + track['artist'] + ' - ' + track['title'] + '. From album ' + track['album'] + '. This is track number ' + track['playlist_position'] + ' in the playlist. It is ' + track['duration'] + ' minutes long.' else: print "Valid commands: play, pause, stop, next, previous, current, and partymode"
class Component(ThreadComponent): MATRIX = matrices.MUSIC_NOTE STATE_PLAYING = 'PLAYING' STATE_PAUSED = 'PAUSED_PLAYBACK' STATE_STOPPED = 'STOPPED' # how many seconds to wait after sending last command before # receiving device state change events EVENT_IDLE_INTERVAL = 2 # seconds def __init__(self, component_config): super().__init__(component_config) self.sonos_controller = SoCo(component_config['ip_address']) self.volume_range = range(0, 100) self.event_listener = event_listener # comes from global scope self.state = None self.volume = None self.nuimo = None self.last_request_time = time() self.sonos_joined_controllers = [] self.station_id_1 = component_config.get('station1', None) self.station_id_2 = component_config.get('station2', None) self.station_id_3 = component_config.get('station3', None) if not any((self.station_id_1, self.station_id_2, self.station_id_3)): try: favorites = self.sonos_controller.get_sonos_favorites( max_items=3) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) if favorites['returned'] >= 3: self.station_id_1 = favorites['favorites'][0] self.station_id_2 = favorites['favorites'][1] self.station_id_3 = favorites['favorites'][2] if len( self.sonos_controller.group.members ) > 1 and self.sonos_controller.group.coordinator.ip_address == component_config[ 'ip_address']: for sonos_controller in self.sonos_controller.group.members: if sonos_controller.ip_address != component_config[ 'ip_address'] and sonos_controller.player_name != self.sonos_controller.group.coordinator.player_name: self.sonos_joined_controllers.append( SoCo(sonos_controller.ip_address)) def run(self): self.subscribe_to_events() self.update_state() try: self.run_loop() finally: self.unsubscribe_from_events() def run_loop(self): while not self.stopped: try: event = self.av_transport_subscription.events.get(timeout=0.1) if time() - self.last_request_time > self.EVENT_IDLE_INTERVAL: logger.debug("avTransport event: %s", pformat(event.variables)) self.state = event.variables['transport_state'] except Empty: pass try: event = self.rendering_control_subscription.events.get( timeout=0.1) if time() - self.last_request_time > self.EVENT_IDLE_INTERVAL: logger.debug("renderingControl event: %s", pformat(event.variables)) self.volume = int(event.variables['volume']['Master']) except Empty: pass def subscribe_to_events(self): self.av_transport_subscription = self.sonos_controller.avTransport.subscribe( ) self.rendering_control_subscription = self.sonos_controller.renderingControl.subscribe( ) def unsubscribe_from_events(self): self.rendering_control_subscription.unsubscribe() self.av_transport_subscription.unsubscribe() def update_state(self): self.state = self.sonos_controller.get_current_transport_info( )['current_transport_state'] self.volume = self.sonos_controller.volume logger.debug("%s state: %s volume: %s", self.sonos_controller.ip_address, self.state, self.volume) def on_rotation(self, delta): if self.state is not None: try: delta = round(self.volume_range.stop * delta) self.volume = clamp_value(self.volume + delta, self.volume_range) self.sonos_controller.volume = self.volume if self.sonos_joined_controllers != []: for sonos_joined_controller in self.sonos_joined_controllers: sonos_joined_controller.volume = self.volume logger.debug("volume update delta: %s volume: %s", delta, self.volume) matrix = matrices.progress_bar(self.volume / self.volume_range.stop) self.nuimo.display_matrix(matrix, fading=True, ignore_duplicates=True) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) self.last_request_time = time() else: self.nuimo.display_matrix(matrices.ERROR) logger.debug("No Active connection with Host") def on_button_press(self): if self.state == self.STATE_PLAYING: self.pause() logger.debug("Play Paused by self.pause() on button press.") elif self.state in [self.STATE_PAUSED, self.STATE_STOPPED]: self.play() logger.debug( "Play started/resumed by self.pause() on button press.") elif self.state is None: self.nuimo.display_matrix(matrices.ERROR) logger.debug("No Active connection with Host.") logger.debug("state toggle: %s", self.state) self.last_request_time = time() def pause(self, show_matrix=True): try: self.sonos_controller.pause() self.state = self.STATE_PAUSED if show_matrix: self.nuimo.display_matrix(matrices.PAUSE) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def play(self, show_matrix=True): try: self.sonos_controller.play() self.state = self.STATE_PLAYING if show_matrix: self.nuimo.display_matrix(matrices.PLAY) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def on_swipe_right(self): try: self.sonos_controller.next() if self.state != self.STATE_PLAYING: self.play(show_matrix=False) self.nuimo.display_matrix(matrices.NEXT_SONG) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) self.last_request_time = time() def on_swipe_left(self): try: self.sonos_controller.previous() if self.state != self.STATE_PLAYING: self.play(show_matrix=False) self.nuimo.display_matrix(matrices.PREVIOUS_SONG) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) self.last_request_time = time() def on_longtouch_left(self): logger.debug("favorite left") if self.station_id_1 is not None: try: self.play_track_playlist_or_album(self.station_id_1, matrices.STATION1) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def on_longtouch_bottom(self): logger.debug("favorite bottom") if self.station_id_2 is not None: try: self.play_track_playlist_or_album(self.station_id_2, matrices.STATION2) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def on_longtouch_right(self): logger.debug("favorite right") if self.station_id_3 is not None: try: self.play_track_playlist_or_album(self.station_id_3, matrices.STATION3) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def play_track_playlist_or_album(self, src, matrix): try: if 'object.container.playlistContainer' in src[ 'meta'] or 'object.container.album.musicAlbum' in src[ 'meta']: self._replace_queue_with_playlist(src) self.sonos_controller.play_from_queue(0) else: self.sonos_controller.play_uri(uri=src['uri'], meta=src['meta'], title=src['title']) self.nuimo.display_matrix(matrix) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def _replace_queue_with_playlist(self, src): """Replace queue with playlist represented by src. Playlists can't be played directly with the self.sonos_controller.play_uri API as they are actually composed of mulitple URLs. Until soco has suppport for playing a playlist, we'll need to parse the playlist item and replace the current queue in order to play it. """ import soco import xml.etree.ElementTree as ET root = ET.fromstring(src['meta']) namespaces = { 'item': 'urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/', 'desc': 'urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/' } desc = root.find('item:item', namespaces).find('desc:desc', namespaces).text res = [ soco.data_structures.DidlResource(uri=src['uri'], protocol_info="DUMMY") ] didl = soco.data_structures.DidlItem(title="DUMMY", parent_id="DUMMY", item_id=src['uri'], desc=desc, resources=res) self.sonos_controller.stop() self.sonos_controller.clear_queue() self.sonos_controller.play_mode = 'NORMAL' self.sonos_controller.add_to_queue(didl)
class Component(ThreadComponent): MATRIX = matrices.MUSIC_NOTE STATE_PLAYING = 'PLAYING' STATE_PAUSED = 'PAUSED_PLAYBACK' STATE_STOPPED = 'STOPPED' # how many seconds to wait after sending last command before # receiving device state change events EVENT_IDLE_INTERVAL = 2 # seconds def __init__(self, component_config): super().__init__(component_config) self.sonos_controller = SoCo(component_config['ip_address']) self.volume_range = range(0, 100) self.event_listener = event_listener # comes from global scope self.state = None self.volume = None self.nuimo = None self.last_request_time = time() def run(self): self.subscribe_to_events() self.update_state() try: self.run_loop() finally: self.unsubscribe_from_events() def run_loop(self): while not self.stopped: try: event = self.av_transport_subscription.events.get(timeout=0.1) if time() - self.last_request_time > self.EVENT_IDLE_INTERVAL: logger.debug("avTransport event: %s", pformat(event.variables)) self.state = event.variables['transport_state'] except Empty: pass try: event = self.rendering_control_subscription.events.get( timeout=0.1) if time() - self.last_request_time > self.EVENT_IDLE_INTERVAL: logger.debug("renderingControl event: %s", pformat(event.variables)) self.volume = int(event.variables['volume']['Master']) except Empty: pass def subscribe_to_events(self): self.av_transport_subscription = self.sonos_controller.avTransport.subscribe( ) self.rendering_control_subscription = self.sonos_controller.renderingControl.subscribe( ) def unsubscribe_from_events(self): self.rendering_control_subscription.unsubscribe() self.av_transport_subscription.unsubscribe() def update_state(self): self.state = self.sonos_controller.get_current_transport_info( )['current_transport_state'] self.volume = self.sonos_controller.volume logger.debug("%s state: %s volume: %s", self.sonos_controller.ip_address, self.state, self.volume) def on_rotation(self, delta): try: delta = round(self.volume_range.stop * delta) self.volume = clamp_value(self.volume + delta, self.volume_range) self.sonos_controller.volume = self.volume logger.debug("volume update delta: %s volume: %s", delta, self.volume) matrix = matrices.progress_bar(self.volume / self.volume_range.stop) self.nuimo.display_matrix(matrix, fading=True, ignore_duplicates=True) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) self.last_request_time = time() def on_button_press(self): if self.state == self.STATE_PLAYING: self.pause() elif self.state in [self.STATE_PAUSED, self.STATE_STOPPED]: self.play() logger.debug("state toggle: %s", self.state) self.last_request_time = time() def pause(self, show_matrix=True): try: self.sonos_controller.pause() self.state = self.STATE_PAUSED if show_matrix: self.nuimo.display_matrix(matrices.PAUSE) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def play(self, show_matrix=True): try: self.sonos_controller.play() self.state = self.STATE_PLAYING if show_matrix: self.nuimo.display_matrix(matrices.PLAY) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) def on_swipe_right(self): try: self.sonos_controller.next() if self.state != self.STATE_PLAYING: self.play(show_matrix=False) self.nuimo.display_matrix(matrices.NEXT_SONG) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) self.last_request_time = time() def on_swipe_left(self): try: self.sonos_controller.previous() if self.state != self.STATE_PLAYING: self.play(show_matrix=False) self.nuimo.display_matrix(matrices.PREVIOUS_SONG) except SoCoException: self.nuimo.display_matrix(matrices.ERROR) self.last_request_time = time()
def skip(self): my_zone = SoCo('192.168.1.19') print('Sonos - Next track') my_zone.next()
elif action == 'v-5': # Decrease volume current_vol = sonos.volume new_vol = current_vol - 5 if new_vol < 0: new_vol = 0 sonos.ramp_to_volume(new_vol) elif action == 'mute': # Mute Volume sonos.volume = 0 elif action == 'next': # Next Song (might be unsupported by playback source e.g. streams) try: sonos.next() except SoCoUPnPException: print '[{"icon": "font-awesome:times-circle", "title": "Not supported for current playback source."}]' elif action == 'prev': # Previous Song (might be unsupported by playback source e.g. streams) try: sonos.previous() except SoCoUPnPException: print '[{"icon": "font-awesome:times-circle", "title": "Not supported for current playback source."}]' elif action == 'set_zone': # Used during setup to save preferred zone settings_file_path = os.path.join(os.getenv('LB_SUPPORT_PATH'), 'settings.json') settings = {'zone_ip_address': sonos_zone} json.dump(settings, file(settings_file_path, 'w'))