def __device_discovered(self, soco_device: soco.SoCo): """Handle discovered Sonos player.""" speaker_info = soco_device.get_speaker_info(True) player = Player( player_id=soco_device.uid, provider_id=PROV_ID, name=soco_device.player_name, features=PLAYER_FEATURES, config_entries=PLAYER_CONFIG_ENTRIES, device_info=DeviceInfo( model=speaker_info["model_name"], address=speaker_info["mac_address"], manufacturer=PROV_NAME, ), ) # store soco object on player player.soco = soco_device player.media_position_updated_at = 0 # handle subscriptions to events player.subscriptions = [] def subscribe(service, _callback): queue = ProcessSonosEventQueue(soco_device.uid, _callback) sub = service.subscribe(auto_renew=True, event_queue=queue) player.subscriptions.append(sub) subscribe(soco_device.avTransport, self.__player_event) subscribe(soco_device.renderingControl, self.__player_event) subscribe(soco_device.zoneGroupTopology, self.__topology_changed) self.mass.run_task(self.mass.players.add_player(player)) return player
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 }
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" )
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] = {}
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("****************************" )
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
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
def __init__(self): _LOGGER.info("Sonos Data: initializing") ### Debug variables IP = "192.168.0.85" ### Get data from the SoCo Library loadSocoData = SoCo(IP) self._SoCoData = loadSocoData self._model_name = loadSocoData.get_speaker_info()['model_name'] self._player_name = loadSocoData.player_name ### Misc self._icon = None self._state = loadSocoData.get_current_transport_info( )['current_transport_state']
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)
def __init__(self): # Time variables self._then = '' # Player variables self._ZONE_IPS = [] disc = SonosDiscovery() self.household = {} 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: continue
def callback(d): data = json.loads(d) url = data['url'] sonos_devices = SonosDiscovery() ips = sonos_devices.get_speaker_ips() master = SoCo(ips[0]) masteruid = master.get_speaker_info()['uid'] for ip in ips: if not (ip == master.speaker_ip): slave = SoCo(ip) ret = slave.join(masteruid) oldvol = master.volume master.volume = 60 master.play_uri(url) playing = True while playing: if master.get_current_transport_info()['current_transport_state'] == 'STOPPED': playing = False master.volume = oldvol for ip in ips: if not (ip == master.speaker_ip): slave = SoCo(ip) slave.unjoin()
def find_controllers(): dev = SonosDiscovery() for ip in dev.get_speaker_ips(): s = SoCo(ip) zone = s.get_speaker_info()['zone_name'] p("{}: {}".format(zone, ip))
print sonos.next() elif cmd == "song": sonos.play_uri(arg) print sonos.play() 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." elif cmd == "volume": print sonos.volume(int(arg)) elif cmd == "discover": sonos_devices = SonosDiscovery() for ip in sonos_devices.get_speaker_ips(): device = SoCo(ip) zone_name = device.get_speaker_info()["zone_name"] print "IP of %s is %s" % (zone_name, ip) else: print "Valid commands (with IP): info, play, pause, stop, next, previous, current, and partymode"
class SonosController: _device = None 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) def get_current_song(self): if self._device == None: self.connect() now_playing = self._device.get_current_track_info() return now_playing def play_pandora_station(self, code): if self._device == None: self.connect() PLAY_STATION_ACTION ='"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI"' TRANSPORT_ENDPOINT = '/MediaRenderer/AVTransport/Control' JOIN_RESPONSE = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetAVTransportURIResponse xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"></u:SetAVTransportURIResponse></s:Body></s:Envelope>' PLAY_STATION_BODY_TEMPLATE ='"<u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><CurrentURI>pndrradio:{music_service_station_id}</CurrentURI><CurrentURIMetaData></CurrentURIMetaData></u:SetAVTransportURI></s:Body></s:Envelope>' body = PLAY_STATION_BODY_TEMPLATE.format(music_service_station_id = code) response = self._device.send_command(TRANSPORT_ENDPOINT, PLAY_STATION_ACTION, body) if (response == JOIN_RESPONSE): self._device.play() return True else: return self._device.parse_error(response) def pause(self): if self._device == None: connect() try: self._device.pause() except: print "Error trying to pause music: there is probably nothing playing right now." return False return True def get_volume(self): if self._device == None: self.connect() current_volume = self._device.volume() return current_volume def set_volume(self, volume): if self._device == None: self.connect() result = self._device.volume(volume) return result
from soco import SoCo from soco import SonosDiscovery if __name__ == '__main__': sonos_devices = SonosDiscovery() for ip in sonos_devices.get_speaker_ips(): device = SoCo(ip) zone_name = device.get_speaker_info()['zone_name'] print "IP of %s is %s" % (zone_name, ip)
class SonosController: _device = None 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) def get_current_song(self): if self._device == None: self.connect() now_playing = self._device.get_current_track_info() return now_playing def play_pandora_station(self, code): if self._device == None: self.connect() PLAY_STATION_ACTION = '"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI"' TRANSPORT_ENDPOINT = '/MediaRenderer/AVTransport/Control' JOIN_RESPONSE = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetAVTransportURIResponse xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"></u:SetAVTransportURIResponse></s:Body></s:Envelope>' PLAY_STATION_BODY_TEMPLATE = '"<u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><CurrentURI>pndrradio:{music_service_station_id}</CurrentURI><CurrentURIMetaData></CurrentURIMetaData></u:SetAVTransportURI></s:Body></s:Envelope>' body = PLAY_STATION_BODY_TEMPLATE.format(music_service_station_id=code) response = self._device.send_command(TRANSPORT_ENDPOINT, PLAY_STATION_ACTION, body) if (response == JOIN_RESPONSE): self._device.play() return True else: return self._device.parse_error(response) def pause(self): if self._device == None: connect() try: self._device.pause() except: print "Error trying to pause music: there is probably nothing playing right now." return False return True def get_volume(self): if self._device == None: self.connect() current_volume = self._device.volume() return current_volume def set_volume(self, volume): if self._device == None: self.connect() result = self._device.volume(volume) return result