Пример #1
0
 def volume_down(self, location):
     for speaker in location:
         if speaker not in self.ips:
             self.ips = self.music_repository.get_ip(speaker)
         print("Lowering Volume on Speaker with IP Address: " + self.ips[speaker])
         sonos = SoCo(self.ips[speaker])
         sonos.set_relative_volume(-1)
Пример #2
0
	def now_playing(self):
		my_zone = SoCo('192.168.86.225')
		
		status = my_zone.get_current_transport_info()
		
		track = my_zone.get_current_track_info()
		
		artist = ''
		title = ''
		if(track['artist'] == '' and track['title'] == ''):
			return "Stopped - Playlist Empty"
		elif (track['artist'] == '' and track['title'] != ''):
			title = track['title']
			parts = title.split('|')
			for part in parts:
				if(part[:7] == 'ARTIST '):
					artist = part[7:]
				elif(part[:6] == 'TITLE '):
					title = part[6:]
		else:
			artist = track['artist']
			title = track['title']
			
		state = "Now Playing: "
		if(status['current_transport_state'] == 'STOPPED'):
			state = "Up Next"
			
		return state + artist + ' - ' + title
Пример #3
0
def main():
    speakers = [speaker.ip_address for speaker in SoCo.discover()]

    if not speakers:
        print("no speakers found, exiting.")
        return

    soco = SoCo(speakers[0])

    # get a plugin by name (eg from a config file)
    myplugin = SoCoPlugin.from_name("soco.plugins.example.ExamplePlugin", soco,
                                    "some user")

    # do something with your plugin
    print("Testing", myplugin.name)
    myplugin.music_plugin_play()

    time.sleep(5)

    # create a plugin by normal instantiation
    from soco.plugins.example import ExamplePlugin

    # create a new plugin, pass the soco instance to it
    myplugin = ExamplePlugin(soco, "a user")

    print("Testing", myplugin.name)

    # do something with your plugin
    myplugin.music_plugin_stop()
Пример #4
0
class Sonos(AbstractJob):

    def __init__(self, conf):
        self.interval = conf['interval']
        self.sonos = SoCo(conf['ip'])

    def get(self):
        zone_name = self.sonos.get_speaker_info()['zone_name']
        np = self.sonos.get_current_track_info()

        current_track = np if np['playlist_position'] != '0' else None
        queue = self.sonos.get_queue(int(np['playlist_position']), 1)
        next_item = queue.pop() if len(queue) > 0 else None
        next_track = {}
        if next_item is not None:
            next_track = {
                'artist': next_item.creator,
                'title': next_item.title,
                'album': next_item.album
            }

        state = self.sonos.get_current_transport_info()[
            'current_transport_state']

        return {
            'room': zone_name,
            'state': state,
            'current': current_track,
            'next': next_track
        }
Пример #5
0
        def play_sonos(junk):
            logging.info('play button pressed')

            self.force_refresh = True
            self.nav_array[int(right(junk.label, 1)) - 1] = BoxButton(
                'pause',
                2,
                is_sprite=True,
                theme=nav_theme,
                on_press=pause_sonos,
                user_data=None)
            #self.nav_grid = urwid.GridFlow(self.nav_array,cell_width=50,h_sep=0,v_sep=0,align='center')
            self.dead_alarm = self.loop.set_alarm_in(.01, self.refresh)
            #commented out for testing at hotel
            play_room = (str(pod_dict['Rooms']['Living']))
            try:
                sonos = SoCo(play_room)
                look_at_queue = sonos.get_queue()

                if len(look_at_queue) > 0:
                    sonos.group.coordinator.play()
                #else:
                #    print("the queue is empty")
            except:
                #this doesn't work for some reason. try just looking for stop states.
                logging.warning("Exception caught. Not expecting trace",
                                exc_info=False,
                                stack_info=False)
                print("the queue is empty")
Пример #6
0
def add_to_group(spkr_ip, coord_ip):
    my_soco = SoCo(spkr_ip)
    ans = []
    if my_soco is not None:
        my_soco.join(SoCo(coord_ip))

    return ans
Пример #7
0
def play_uri(ip, uri, meta):
    my_soco = SoCo(ip)
    ans = []
    if my_soco is not None:
        my_soco.play_uri(uri, meta)

    return ans
Пример #8
0
def play_fav(title, uri, meta, ip):
    my_soco = SoCo(ip)
    ans = []
    if my_soco is not None:
        my_soco.play_uri(uri, meta, title)

    return ans
Пример #9
0
        def play_sonos(junk):
            logging.info('pause button pressed, start playing')
            self.force_refresh = True
            self.nav_array[1] = BoxButton('pause',
                                          2,
                                          is_sprite=True,
                                          on_press=play_sonos,
                                          user_data=None)
            #self.nav_grid = urwid.GridFlow(self.nav_array,cell_width=50,h_sep=0,v_sep=0,align='center')
            self.dead_alarm = self.loop.set_alarm_in(.01, self.refresh)
            #commented out for testing at hotel
            play_room = (str(pod_dict['Rooms']['Living']))
            self.poor_man_refresh()
            try:
                sonos = SoCo(play_room)
                look_at_queue = sonos.get_queue()

                if len(look_at_queue) > 0:
                    sonos.group.coordinator.play()
                else:
                    print("the queue is empty")
            except soco.exceptions.SoCoUPnPException as e:
                logging.warning("Exception caught. Not expecting trace",
                                exc_info=False,
                                stack_info=False)
                print("the queue is empty")
Пример #10
0
def get_zone(zone_name):
    device = SoCo('192.168.1.253')
    return device
    cache_name = "{}_last_known_ip.txt".format(zone_name)
    if devices:
        for device in devices:
            if device.player_name == zone_name:
                # Save the well known IP of the device for future cache
                # When discover() fails need to fallback to this solution
                #try:
                f = open(cache_name, "w+")
                f.write(device.ip_address)
                f.close()
                return device
    # Device not found, try be known IP
    try:
        if os.path.isfile(cache_name) and os.access(cache_name, os.R_OK):
            f = open(cache_name, "r")
            ip_address = f.readline()
            f.close()
            print("Using cached IP:{} for zone:".format(ip_address, zone_name))
            device = SoCo(ip_address)
            return device
        else:
            print("No cached record for zone")
    except:
        return None
Пример #11
0
def remove_from_group(spkr_ip):
    my_soco = SoCo(spkr_ip)
    ans = []
    if my_soco is not None:
        my_soco.unjoin()

    return ans
Пример #12
0
def set_volume(ip, vol):
    my_soco = SoCo(ip)
    ans = []
    if my_soco is not None:
        my_soco.play_uri(vol)

    return ans
Пример #13
0
    def get(self, request, format=None):
        params = request.query_params
        sound_id = params["sound_id"]
        speaker_id = params["speaker_id"]

        if sound_id is None and speaker_id is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        elif sound_id is None or speaker_id is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        speaker = Sonos.objects.filter(pk=speaker_id)
        if not speaker:
            raise NotFound(detail=_("No Sonos with this id"))

        sound = Sound.objects.filter(pk=sound_id)
        if not sound:
            raise NotFound(detail=_("No sound with this id"))

        sonos = SoCo(speaker[0].ip_address)
        uri = 'http://' + get_ip_address() + ':8000/static/data/' + sound[
            0].author.name_text + '/sounds/' + sound[0].file_name_text
        sonos.play_uri(uri, start=True)

        sound[0].play_count_integer += 1
        sound[0].save()

        data = {"meta": {"code": status.HTTP_200_OK}}

        return Response(data, status=status.HTTP_200_OK)
Пример #14
0
def get_sonos_favorites(request):  # pragma: no cover,
    nuimo_app_config_path = request.registry.settings['nuimo_app_config_path']
    mac_address = request.matchdict['mac_address'].replace('-', ':')
    component_id = request.matchdict['component_id']

    with open(nuimo_app_config_path, 'r') as f:
        config = yaml.load(f)

    try:
        nuimo = config['nuimos'][mac_address]
    except (KeyError, TypeError):
        return HTTPNotFound("No Nuimo with such ID")

    components = nuimo['components']

    try:
        component = next(c for c in components if c['id'] == component_id)
    except StopIteration:
        raise HTTPNotFound("No Component with such ID")

    if component['type'] != 'sonos':
        return HTTPNotFound("No Sonos Component with such ID")

    sonos_controller = SoCo(component['ip_address'])
    try:
        favorites = sonos_controller.get_sonos_favorites()
    except SoCoException:
        return HTTPNotFound("Sonos Device not reachable")

    if favorites['returned'] < 3:
        return HTTPNotFound("less than Three Favorites on Sonos")

    return {'favorites': favorites}
Пример #15
0
def play_local_file(speaker: SoCo, pathname: str, end_on_pause: bool = False) -> bool:

    if not path.exists(pathname):
        error_report("File '{}' not found".format(pathname))
        return False

    directory, filename = path.split(pathname)

    if not is_supported_type(filename):
        error_report(
            "Unsupported file type; must be one of: {}".format(SUPPORTED_TYPES)
        )
        return False

    # Make filename compatible with URL naming
    url_filename = urllib.parse.quote(filename)

    server_ip = get_server_ip(speaker)
    if not server_ip:
        error_report("Can't determine an IP address for web server")
        return False
    logging.info("Using server IP address: {}".format(server_ip))

    # Start the webserver (runs in a daemon thread)
    speaker_ips = []
    for zone in speaker.all_zones:
        speaker_ips.append(zone.ip_address)
    httpd = http_server(server_ip, directory, url_filename, speaker_ips)
    if not httpd:
        error_report("Cannot create HTTP server")
        return False

    # This ensures that other running invocations of 'play_file'
    # receive their stop events, and terminate.
    logging.info("Stopping speaker '{}'".format(speaker.player_name))
    speaker.stop()

    # Assemble the URI
    uri = "http://" + server_ip + ":" + str(httpd.server_port) + "/" + url_filename
    logging.info("Playing file '{}' from directory '{}'".format(filename, directory))
    logging.info("Playback URI: {}".format(uri))

    logging.info("Send URI to '{}' for playback".format(speaker.player_name))
    speaker.play_uri(uri)

    logging.info("Setting flag to stop playback on CTRL-C")
    set_speaker_playing_local_file(speaker)

    logging.info("Waiting 1s for playback to start")
    time.sleep(1.0)
    logging.info("Waiting for playback to stop")
    wait_until_stopped(speaker, uri, end_on_pause)
    logging.info("Playback stopped ... terminating web server")
    httpd.shutdown()
    logging.info("Web server terminated")

    set_speaker_playing_local_file(None)

    return True
Пример #16
0
 def stopPlaying(self):
     
     for speakerIp in self.sonos.get_speaker_ips():
         sonosSpeaker = SoCo(speakerIp)
         all_info = sonosSpeaker.get_speaker_info()
         for item in all_info:
             logging.info("Stopping for speaker %s: %s" % (item, all_info[item]))
         sonos.stop()
         LCDScreen.updateStatus("Sonos" , "Music Stopped" )
Пример #17
0
	def GET(self):
		web.header('Access-Control-Allow-Origin', '*')
                web.header('Access-Control-Allow-Credentials', 'true')

		data = web.input(uri="no", player="no")
		sonos = SoCo('192.168.1.105')
                sonos.play_uri(data.uri)
		track = sonos.get_current_track_info()
                return track['title'] + " - " + data.player
Пример #18
0
	def GET(self, ipadress):
		web.header('Content-Type', 'application/json')
		web.header('Access-Control-Allow-Origin', '*')
		web.header('Access-Control-Allow-Credentials', 'true')

		sonos = SoCo(ipadress)
		track = sonos.get_current_track_info()

		return json.dumps(track)
Пример #19
0
 def volume_down(self):
     for ip in self._ZONE_IPS:
         device = SoCo(ip)
         vol = int(device.volume())
         if vol > 0:
             device.volume(vol-1)
             return True
         elif vol == 100:
             return True
Пример #20
0
 def volume_down(self):
     for ip in self._ZONE_IPS:
         device = SoCo(ip)
         vol = int(device.volume())
         if vol > 0:
             device.volume(vol - 1)
             return True
         elif vol == 100:
             return True
Пример #21
0
 def play(self):
     self.logger.info('Playing zones...')
     for ip in self._ZONE_IPS:
         device = SoCo(ip)
         self.logger.debug('Playing zone at %s', ip)
         if not device.play():
             self.logger.error('Unable to play zone at %s', ip)
             return False
     self.logger.info('All zones playing.')
     return True
Пример #22
0
 def pause(self):
     self.logger.info('Pausing zones...')
     for ip in self._ZONE_IPS:
         device = SoCo(ip)
         self.logger.debug('Pausing zone at %s', ip)
         if not device.pause():
             self.logger.error('Unable to pause zone at %s', ip)
             return False
     self.logger.info('All zones paused.')
     return True
Пример #23
0
 def listAll(self):
 
     for speakerIp in self.sonos.get_speaker_ips():
         logging.info("********* %s ***********" % str(speakerIp))
         sonosSpeaker = SoCo(speakerIp)
         all_info = sonosSpeaker.get_speaker_info()
         for item in all_info:
             logging.info("    %s: %s" % (item, all_info[item]))
         logging.info('co-ordinator = ' + str(sonosSpeaker.get_group_coordinator(all_info['zone_name'], True)))
         logging.info("****************************" )
Пример #24
0
def refresh_speaker_info():
    sd = SonosDiscovery()
    possible_matches = sd.get_speaker_ips()
    speaker_info = {}
    for ip in possible_matches:
        s = SoCo(ip)
        try:
            speaker_info[ip] = s.get_speaker_info()
        except Exception, e:
            speaker_info[ip] = {}
Пример #25
0
    def play(self):
        self.logger.info('Playing zones...')
        for ip in self._ZONE_IPS:
            device = SoCo(ip)
	    self.logger.debug('Playing zone at %s', ip)
	    if not device.play():
                self.logger.error('Unable to play zone at %s', ip)
		return False
	self.logger.info('All zones playing.')
        return True
Пример #26
0
    def pause(self):
        self.logger.info('Pausing zones...')
        for ip in self._ZONE_IPS:
            device = SoCo(ip)
            self.logger.debug('Pausing zone at %s', ip)
	    if not device.pause():
                self.logger.error('Unable to pause zone at %s', ip)
		return False
	self.logger.info('All zones paused.')
        return True
Пример #27
0
    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()
Пример #28
0
 def play_it_ran():
     flip_back(index_id)
     logging.info('random threading')
     play_room = (str(pod_dict['Rooms']['Living']))
     url = 'http://0.0.0.0:5005/preset/all_rooms/'
     r = requests.get(url)
     data = requests.get('http://0.0.0.0:5000/random/' +
                         str(pod_id) + "/").json()
     time.sleep(1)
     sonos = SoCo(play_room)
     sonos.play_uri(data['location'])
Пример #29
0
 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()
Пример #30
0
def main():

    with closing(MySQLdb.connect(
            login.DB_HOST, login.DB_USER,
            login.DB_PASSWORD, login.DB_DATABASE)) as connection:
        with closing(connection.cursor()) as cursor:
            cursor.execute('SELECT ip FROM sonos WHERE id="1"')
            ip = cursor.fetchone()[0]

    sonos = SoCo(ip)
    sonos.start_library_update()
Пример #31
0
    def sonos_pause(self):
        """Afspeellijst, <pause> button, afspelen pauzeren.
        """
        
        # pagina laden voor als antwoord terug aan de server
        h = queuebeheer_temp.sonos_pause()
                
        ## sonos, afspelen pauzeren
        sonos = SoCo(COORDINATOR)
        sonos.pause()

        return h
Пример #32
0
    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
Пример #33
0
    def sonos_play(self):
        """Afspeellijst, <play> button, afspelen of doorgaan na een pauze.
        """
        
        # pagina laden voor als antwoord terug aan de server
        h = queuebeheer_temp.sonos_play()
                
        ## sonos, afspelen
        sonos = SoCo(COORDINATOR)
        sonos.play()

        return h
Пример #34
0
def play_recent(pod_address):
    url = 'http://localhost:5005/preset/all_rooms'
    r = requests.get(url)

    with open('/usr/local/bin/sonos-rooms.json', 'r') as f:
        d = json.load(f)
        play_room = (d['Master'])

    d = feedparser.parse(pod_address)
    most_recent = d.entries[0].enclosures[0].href
    sonos = SoCo(play_room)
    sonos.play_uri(most_recent)
Пример #35
0
 def connect(self, address):
     try:
         self.connected_device = SoCo(address)
         self.connected_device.player_name
         print_green('Connection active')
     except ConnectionRefusedError:
         self.connected_device = None
         print_red(
             'Connection Failed: connection refused to {}'.format(address))
     except OSError:
         self.connected_device = None
         print_red('Connection Failed: device {} not found'.format(address))
Пример #36
0
def tune():
    station = request.args.get('station')
    target = request.args.get('target')
    sonos = SoCo(target)
    sonos.pause()
    if station == 'eldoradio':
        sonos.play_uri('x-rincon-mp3radio://sender.eldoradio.de:8000/high')
    elif station == 'xfm':
        sonos.play_uri('x-rincon-mp3radio://live64.917xfm.de')
    elif station == 'wdr5':
        sonos.play_uri('x-rincon-mp3radio://wdr-5.akacast.akamaistream.net/7/41/119439/v1/gnl.akacast.akamaistream.net/wdr-5')
    return 'Ok'
Пример #37
0
    def sonos_previous(self):
        """Afspeellijst, <Previous> button, gaat naar vorige nummer, in de afspeellijst.
        """
        
        # pagina laden voor als antwoord terug aan de server
        h = queuebeheer_temp.sonos_previous()
                
        ##
        sonos = SoCo(COORDINATOR)
        sonos.previous()

        return h
Пример #38
0
def playTheme(data, cur, themes, sonosPlayer):
    if data['hw'] in themes.keys() and getLastAction(data, cur) == 'remove':
        from soco import SoCo
        sonos = SoCo(sonosPlayer)
        if sonos.get_current_transport_info() == 'PLAYING':
            return '';
        sonos.unjoin();
        sonos.play_uri(themes[data['hw']])
        sonos.volume = 20;
        if sonos.get_current_transport_info() == 'PLAYING':
            return '';    
        sonos.play()
        syslog.syslog('Playing theme for: ' + data['hw'])
Пример #39
0
    def sonos_play_from_queue(self):
        """sonos_play_from_queue, speelt queue af
        """
        
        # pagina laden voor als antwoord terug aan de server
        h = queuebeheer_temp.sonos_play_from_queue()

        # queue afspelen als deze niet leeg is
        sonos = SoCo(COORDINATOR)
        if len(sonos.get_queue()) > 0:
            sonos.play_from_queue(0)

        return h
Пример #40
0
    def connect(self):
        ips = []
        while (len(ips) == 0):
            print "No Sonos found"
            sonos_devices = SonosDiscovery()
            ips = sonos_devices.get_speaker_ips()

        print "Found {0} device(s)".format(len(ips))

        for ip in ips:
            self._device = SoCo(ip)
            zone_name = self._device.get_speaker_info()['zone_name']
            print "IP of {0} is {1}".format(zone_name, ip)
Пример #41
0
        def play_spot(junk, location):
            time.sleep(5)
            play_room = (str(pod_dict['Rooms']['Living']))

            sonos = SoCo(play_room)
            uri = location['location']
            sonos.clear_queue()
            sonos.add_uri_to_queue(uri=uri)
            sonos.play_from_queue(index=0)
            sonos.play_mode = "SHUFFLE_NOREPEAT"
Пример #42
0
def bttn_stop():
    # connect to the Sonos
    sonos = SoCo(SONOS_IP)

    # connect to Philips Hue Bridge
    hue = Bridge(ip=HUE_IP,
                 username=HUE_USERNAME)

    # stop the Sonos and reset to sensible defaults

    queue = sonos.get_queue()
    sonos.clear_queue()
    sonos.volume = STOP_VOLUME
    sonos.play_mode = 'NORMAL'
    sonos.stop()

    # set the lights back to a sensible default

    command = {
        'transitiontime': (STOP_DIMMER_SECONDS * 10),
        'on': True,
        'bri': STOP_DIMMER_BRIGHTNESS
    }

    hue.set_light(STOP_LIGHTS, command)

    return jsonify(status="success")
Пример #43
0
class Sonos:
	def __init__(self, ip):
		self.sonos = SoCo(ip)
		self.sonos.volume = 60

	def playJason(self):
		self.sonos.play_uri("x-sonos-spotify:spotify%3atrack%3a6g6A7qNhTfUgOSH7ROOxTD?sid=12&flags=32")
		time.sleep(1)
		self.sonos.pause()

	def randomKatyPerrySong(self):
		darkHorse = 'x-sonos-spotify:spotify%3atrack%3a5jrdCoLpJSvHHorevXBATy?sid=12&flags=32'
		firework = 'x-sonos-spotify:spotify%3atrack%3a4lCv7b86sLynZbXhfScfm2?sid=12&flags=32'
		roar = 'x-sonos-spotify:spotify%3atrack%3a3XSczvk4MRteOw4Yx3lqMU?sid=12&flags=32'
		birthday = 'x-sonos-spotify:spotify%3atrack%3a2xLOMHjkOK8nzxJ4r6yOKR?sid=12&flags=32'
		californiaGurls = 'x-sonos-spotify:spotify%3atrack%3a6tS3XVuOyu10897O3ae7bi?sid=12&flags=32'
		teenageDream = 'x-sonos-spotify:spotify%3atrack%3a55qBw1900pZKfXJ6Q9A2Lc?sid=12&flags=32'
		lastFridayNight	= 'x-sonos-spotify:spotify%3atrack%3a455AfCsOhhLPRc68sE01D8?sid=12&flags=32'
		peacock = 'x-sonos-spotify:spotify%3atrack%3a3y3Hucw52QpjtHUeOKTkaO?sid=12&flags=32'
		et = 'x-sonos-spotify:spotify%3atrack%3a4kkeuVl6gF3RMqE4Nn5W3E?sid=12&flags=32'

		songs = [darkHorse, firework, roar, birthday, californiaGurls, teenageDream, lastFridayNight, peacock, et]
		chosen_song = random.choice(songs)
		return chosen_song

	def playKatyPerry(self):
		self.playJason()
		self.sonos.play_uri(self.randomKatyPerrySong())
		# set Katy Perry duration here (in seconds)
		time.sleep(10)
		self.sonos.pause()
Пример #44
0
def bttn_stop():
    # connect to the Sonos
    sonos = SoCo(SONOS_IP)

    # connect to Philips Hue Bridge
    hue = Bridge(ip=HUE_IP,
                 username=HUE_USERNAME)

    # stop the Sonos and reset to sensible defaults

    queue = sonos.get_queue()
    sonos.clear_queue()
    sonos.volume = 45
    sonos.play_mode = 'NORMAL'
    sonos.stop()

    # set the lights back to approximately 80% over 3 seconds

    command = {
        'transitiontime': 30,
        'on': True,
        'bri': 203
    }

    hue.set_light(1, command)

    return jsonify(status="success")
Пример #45
0
    def __init__(self):
	self.logger = logging.getLogger(__name__)
	self.logger.setLevel(logging.DEBUG)
	fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        fmt = logging.Formatter(fmt)

	# Configuring logging to file
	# Currently logs everything DEBUG and above 	
	logfile = logging.FileHandler('clock.log')
	logfile.setLevel(logging.DEBUG)
	logfile.setFormatter(fmt)
	self.logger.addHandler(logfile)

	# Configuring logging to stdout
	# Currently logs everything INFO and above:w
	stderr_handle = logging.StreamHandler()
        stderr_handle.setLevel(logging.INFO)
	stderr_handle.setFormatter(fmt)
	self.logger.addHandler(stderr_handle)
       
        self.logger.info('Starting log...')
 
	# Time variables
	self._then = ''
        
        # Player variables        
        self._ZONE_IPS = []

	self.logger.info('Searching for zones...')
        disc = SonosDiscovery()

        self.household = {}

        self.logger.info('Building household tree...')
	for ip in disc.get_speaker_ips():
            device = SoCo(ip)
            try:
                zone = device.get_speaker_info()['zone_name']
                if zone != None:
	            if self.household.has_key(zone):
                        self.household[zone].append(ip)
                    else:
                        self.household[zone] = []
                        self.household[zone].append(ip)
            except ValueError:
                msg = 'Zone with no name at '+ip+', possibly a bridge'
		self.logger.error(msg)
                continue
Пример #46
0
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        fmt = logging.Formatter(fmt)

        # Configuring logging to file
        # Currently logs everything DEBUG and above
        logfile = logging.FileHandler('clock.log')
        logfile.setLevel(logging.DEBUG)
        logfile.setFormatter(fmt)
        self.logger.addHandler(logfile)

        # Configuring logging to stdout
        # Currently logs everything INFO and above:w
        stderr_handle = logging.StreamHandler()
        stderr_handle.setLevel(logging.INFO)
        stderr_handle.setFormatter(fmt)
        self.logger.addHandler(stderr_handle)

        self.logger.info('Starting log...')

        # Time variables
        self._then = ''

        # Player variables
        self._ZONE_IPS = []

        self.logger.info('Searching for zones...')
        disc = SonosDiscovery()

        self.household = {}

        self.logger.info('Building household tree...')
        for ip in disc.get_speaker_ips():
            device = SoCo(ip)
            try:
                zone = device.get_speaker_info()['zone_name']
                if zone != None:
                    if self.household.has_key(zone):
                        self.household[zone].append(ip)
                    else:
                        self.household[zone] = []
                        self.household[zone].append(ip)
            except ValueError:
                msg = 'Zone with no name at ' + ip + ', possibly a bridge'
                self.logger.error(msg)
                continue
Пример #47
0
def get_zone(zone_name):
    import re
    devices = discover()
    cache_name = "{}_ip.txt".format(zone_name)
    if devices:
        for device in devices:
            if device.player_name == zone_name:
                # Save the well known IP of the device for future cache
                # When discover() fails need to fallback to this solution
                #try:
                f = open(cache_name, "w+")
                f.write(device.ip_address)
                f.close()
                return device
    if not devices or len(devices) == 0:
        print("WARNING: No devices found through discover.")
    # Device not found, try be known IP
    try:
        if os.path.isfile(cache_name) and os.access(cache_name, os.R_OK):
            f = open(cache_name, "r")
            line = f.readline()
            ip_address = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
                                   line).group()
            f.close()
            print("Using cached IP:{} for zone:{}".format(
                ip_address, zone_name))
            device = SoCo(ip_address)
            return device
        else:
            print("No cached record for zone")
    except:
        print("Exception reading cached record")
        return None
Пример #48
0
def main():
    sd = SonosDiscovery()
    speakers = sd.get_speaker_ips()

    if not speakers:
        print 'no speakers found, exiting.'
        return

    soco = SoCo(speakers[0])

    # get a plugin by name (eg from a config file)
    myplugin = SoCoPlugin.from_name('soco.plugins.example.ExamplePlugin', soco,
                                    'some user')

    # do something with your plugin
    print 'Testing', myplugin.name
    myplugin.music_plugin_play()

    time.sleep(5)

    # create a plugin by normal instantiation
    from soco.plugins.example import ExamplePlugin

    # create a new plugin, pass the soco instance to it
    myplugin = ExamplePlugin(soco, 'a user')

    print 'Testing', myplugin.name

    # do something with your plugin
    myplugin.music_plugin_stop()
Пример #49
0
	def GET(self):

		web.header('Content-Type', 'application/json')
		web.header('Access-Control-Allow-Origin', '*')
                web.header('Access-Control-Allow-Credentials', 'true')
		

		data = web.input(player="blank")
		sonos = SoCo(data.player)
		
		track = sonos.get_current_track_info()
		
		

		
		return json.dumps(track)
Пример #50
0
def main():
    speakers = [speaker.ip_address for speaker in SoCo.discover()]

    if not speakers:
        print 'no speakers found, exiting.'
        return

    soco = SoCo(speakers[0])

    # get a plugin by name (eg from a config file)
    myplugin = SoCoPlugin.from_name('soco.plugins.example.ExamplePlugin',
                                    soco, 'some user')

    # do something with your plugin
    print 'Testing', myplugin.name
    myplugin.music_plugin_play()


    time.sleep(5)

    # create a plugin by normal instantiation
    from soco.plugins.example import ExamplePlugin

    # create a new plugin, pass the soco instance to it
    myplugin = ExamplePlugin(soco, 'a user')

    print 'Testing', myplugin.name

    # do something with your plugin
    myplugin.music_plugin_stop()
def decir2(texto):
    track = sonos.get_current_track_info()
    playlistPos = int(track['playlist_position'])-1
    trackPos = track['position']
    trackURI = track['uri']

    # This information allows us to resume services like Pandora
    mediaInfo = sonos.avTransport.GetMediaInfo([('InstanceID', 0)])
    mediaURI = mediaInfo['CurrentURI']
    mediaMeta = mediaInfo['CurrentURIMetaData']

    ok, file_name =  text2mp3(texto, PATH, LANGUAGE, False)
    if ok:
        zp = SoCo(ip_sonos)
        print('x-file-cifs:%s' % '//homeserver/sonidos/speech.mp3')
        zp.play_uri('x-file-cifs:%s' % '//homeserver/sonidos/speech.mp3')
Пример #52
0
    def volume_down(self):
	self.logger.info('Lowering volume...')
        for ip in self._ZONE_IPS:
            device = SoCo(ip)
            vol = int(device.volume())
            if vol > 0:
		self.logger.debug('Setting volume to %d', vol-1)
                if not device.volume(vol-1):
                    self.logger.error('Could not set volume at %s.', ip)
                    return False
		else:
		    self.logger.error('Lowered volume.')
		    return True
            elif vol == 100:
		self.logger.info('Volume at min, could not lower.')
                return True
Пример #53
0
    def volume_up(self):
        self.logger.info('Raising volume...')
        for ip in self._ZONE_IPS:
            device = SoCo(ip)
            vol = int(device.volume())
            if vol < 100:
		self.logger.debug('Setting volume to %d', vol+1)
                if not device.volume(vol+1):
                    self.logger.error('Could not set volume at %s.', ip)
                    return False
		else:
		    self.logger.info('Raised volume.')
		    return True
            elif vol == 100:
		self.logger.info('Volume at max, could not raise.')
                return True
Пример #54
0
def getSonos():
    settings = selfAddon.getSetting
    player_ip = settings('SONOS_PLAYER_IP')

    sonos = SoCo("%s" % player_ip)
    xbmc.log("SONOS: created soco with ip: %s" % player_ip)
    return sonos
Пример #55
0
 def volume_up(self):
     self.logger.info('Raising volume...')
     for ip in self._ZONE_IPS:
         device = SoCo(ip)
         vol = int(device.volume())
         if vol < 100:
             self.logger.debug('Setting volume to %d', vol + 1)
             if not device.volume(vol + 1):
                 self.logger.error('Could not set volume at %s.', ip)
                 return False
             else:
                 self.logger.info('Raised volume.')
                 return True
         elif vol == 100:
             self.logger.info('Volume at max, could not raise.')
             return True
Пример #56
0
 def volume_down(self):
     self.logger.info('Lowering volume...')
     for ip in self._ZONE_IPS:
         device = SoCo(ip)
         vol = int(device.volume())
         if vol > 0:
             self.logger.debug('Setting volume to %d', vol - 1)
             if not device.volume(vol - 1):
                 self.logger.error('Could not set volume at %s.', ip)
                 return False
             else:
                 self.logger.error('Lowered volume.')
                 return True
         elif vol == 100:
             self.logger.info('Volume at min, could not lower.')
             return True
Пример #57
0
    def sonos_clear_queue(self):
        """sonos_clear_queue, maak sonos afspeellijst leeg
        """
        
        # pagina laden voor als antwoord terug aan de server
        h = queuebeheer_temp.sonos_clear_queue()
                
        ## queue leegmaken als er wat in zit
        sonos = SoCo(COORDINATOR)
        # als de sonos queue niet leeg is
        if len(sonos.get_queue()) > 0:
            ## sonos queue leegmaken
            sonos.clear_queue()

            query = """
                delete from queue
            """
            self._db.dbExecute(query)

        return h
Пример #58
0
   def playStation(self, stationNameLike, onSpeakerLike): 
 
       LCDScreen.updateStatus("Pandora", "Loading music")
       stationId = self.rpandora.getIdForStation(stationNameLike)
       stationName = self.rpandora.getNameForStation(stationNameLike)
       
       LCDScreen.updateStatus("Pl: %s"  % stationName, "On %s" % onSpeakerLike )
       
       for speakerIp in self.sonos.get_speaker_ips():
           try:
               sonosSpeaker = SoCo(str(speakerIp))
               all_info = sonosSpeaker.get_speaker_info()
               if onSpeakerLike in all_info['zone_name'] :
                   logging.info("Playing on speaker %s" % str(speakerIp))
                   sonosSpeaker.play_uri("pndrradio:%s" % str(stationId), '')
                   LCDScreen.updateStatus("Pl: %s"  % stationName, "On %s" % all_info['zone_name'] )
               else:
                   logging.info('Skipping player "%s"' % all_info['zone_name'])
           except:
               logging.error('Failed calling %s' % speakerIp)
Пример #59
0
def main():
    '''
    Test stub to call the say routine.
    Command line provides the words to say in inverted commas
    If omitted then uses a default text
    '''
    #use text argument from command line if present - else use default
    if len(sys.argv) < 2:
        txt = DEFUALT_TEXT
    else:
        txt = sys.argv[1]
    
    print ('Testing using %s character string "%s"' %  (len(txt), txt) )
    ok, file_name =  text2mp3(txt, PATH, LANGUAGE, ALERT)
    
    #if TTS worked OK, use file name returned to play MP3 on Sonos
    if ok:
        zp = SoCo(IP)
        zp.play_uri('x-file-cifs:%s' % file_name)
        print 'Listen to your Sonos - check volume turned up!'