def listen(): while self._listeningForZoneChanges: try: event = self._avTransportSubscription.events.get( timeout=0.1) # Add in track info as well event.variables[ 'track'] = self._current_zone.get_current_track_info() event.variables['tv_playing'] = int( self._current_zone.is_playing_tv) callback(event.variables) except: pass try: event = self._renderingControlSubscription.events.get( timeout=0.1) callback(event.variables) except: pass try: event = self._zoneGroupTopologySubscription.events.get( timeout=0.1) callback(event.variables) except: pass self._avTransportSubscription.unsubscribe() self._renderingControlSubscription.unsubscribe() self._zoneGroupTopologySubscription.unsubscribe() event_listener.stop()
def run(self): while not self.abortThread: #self.msleep(100) variablesone = None variablestwo = None if not self.pausethread: try: while True: self.event = self.avSubscription.events.get(timeout=0.1) except Empty: pass try: while True: self.event2 = self.renderingSubscription.events.get(timeout=0.1) except Empty: pass if self.event2 is not None or self.event is not None: if self.event is not None: print("event") variablesone = self.event.variables print("meta") print(self.event.variables['current_track_meta_data'].to_dict()) pprint(self.event.variables) if self.event2 is not None: print("event2") pprint(self.event2.variables) variablestwo = self.event2.variables self.updateValues.emit(variablesone, variablestwo) self.event = None self.event2 = None self.avSubscription.unsubscribe() self.renderingSubscription.unsubscribe() event_listener.stop()
def onShutdown(self): if self.interval: self.interval.cancel() self.deRegisterForEvents() event_listener.stop()
def start_subs(): logging.basicConfig(level=logging.ERROR) # pick a device device = soco.discover().pop() # Subscribe to ZGT events sub = device.zoneGroupTopology.subscribe() # print out the events as they arise t_end = time.time() + 60 * 2 while time.time() < t_end: try: event = sub.events.get(timeout=0.5) pp = pprint.PrettyPrinter(indent=4) pp.pprint(event.variables) except Empty: pass except KeyboardInterrupt: print("exiting KeyboardInterrupt") sub.unsubscribe() event_listener.stop() break except EOFError: print("exiting EOFError") sub.unsubscribe() event_listener.stop() break print("exiting loop") sub.unsubscribe()
def main(): parser = argparse.ArgumentParser( description='automatically turn the amplifier on for sonos.') parser.add_argument('--sonos', default='Living Room', help='sonso devices [Living Room]') parser.add_argument('--amplifier', default=None, help='amplifier to use [discover]') parser.add_argument('--input', default='AV5', help='amplifier input to use [AV4]') parser.add_argument('--volume', type=int, default=55, help='sonos volume to use [55]') args = parser.parse_args() amps = rxv.find() if args.amplifier is not None: lst = list(filter(lambda x: x.model_name == args.amplifier, amps)) if len(lst) != 1: print('Could not find amplifier %s' % args.amplifier, file=sys.stderr) os.exit(1) amp = lst[0] else: amp = amps[0] print('Amplifier is %s' % amp.model_name) devices = soco.discover() for device in devices: print("%21s @ %s" % (device.player_name, device.ip_address)) speaker = find_speakers(devices, args.sonos) if speaker is None: print('Could not find speaker %s' % args.sonso, file=sys.stderr) os.exit(1) print('Speaker is %s @ %s' % (speaker.player_name, speaker.ip_address)) bridge = Bridge(amp, speaker, args.input, args.volume) # set up the unified queue mq, threads = subscribe(devices) keep_running = True while keep_running: try: event = mq.get() handle_event(event, bridge) except queue.Empty: pass except KeyboardInterrupt: keep_running = False event_listener.stop()
def run(self): while True: if self.terminate: self.subscription.unsubscribe() event_listener.stop() break try: event = self.subscription.events.get(timeout=0.5) self.state_callback(event.transport_state) except Empty: pass
def startListening(): while True: try: event = sub.events.get(timeout=1.0) pprint(event.variables) except Empty: print("Empty") pass except KeyboardInterrupt: sub.unsubscribe() event_listener.stop() break
def main(args): x = StoppableThread("test") x.daemon = True if sonos_controller: # print out the events as they arise # sub = sonos_controller.renderingControl.subscribe() sub2 = sonos_controller.avTransport.subscribe() while True: # try: # event = sub.events.get(timeout=0.5) # pprint(event.variables) # except Empty: # pass try: event = sub2.events.get(timeout=0.5) pprint(event.variables) print(event.variables['current_track_meta_data'].title) if event.variables['current_track_uri'] == 'x-rincon:RINCON_949F3ED42D3F01400': my_text = 'TV' else: my_text = event.variables['current_track_meta_data'].title if x.is_alive(): x.stop() x = StoppableThread(my_text) x.text = my_text # if not x.is_alive(): x.start() print("running in background") except SoCoFault: print("error") pass except Empty: pass except KeyboardInterrupt: # sub.unsubscribe() sub2.unsubscribe() event_listener.stop() break else: logger.error(f'Device "${args.sonos_host}" not found!') sys.exit(1)
#pprint (event.variables) if event.current_track_duration == '0:00:00': print ('>>Playing stream (eg radio)') print ('content: {}'.format(event.current_track_meta_data.stream_content)) print ('show: {}'.format(event.current_track_meta_data.radio_show)) print ('station: {}'.format(event.enqueued_transport_uri_meta_data.title)) elif event.current_track_duration == '': print ('>>Playing from line in') print ('not handled....yet') else: print ('>>Playing from queue') print ('Artist: {}'.format(event.current_track_meta_data.creator)) print ('Album: {}'.format(event.current_track_meta_data.album)) print ('Track: {}'.format(event.current_track_meta_data.title)) print ('Playlist: {}'.format(event.enqueued_transport_uri_meta_data.title)) print ('Track uri {}'.format(event.current_track_uri)) if event.next_track_meta_data: print ('next Artist: {}'.format(event.next_track_meta_data.creator)) print ('next Album: {}'.format(event.next_track_meta_data.album)) print ('next Track: {}'.format(event.next_track_meta_data.title)) except Empty: pass except KeyboardInterrupt: sub.unsubscribe() sub2.unsubscribe() event_listener.stop() break
def say(self, message): log("Speech: Message to say is: %s" % message) # Start by checking to see if the message is valid if not self.checkIfValidMessage(message): return xbmc.executebuiltin("ActivateWindow(busydialog)") try: # Need to subscribe to transport events, this is so that we know # when a given track has finished, and so we can stop it, if # we do not stop it, then it will repeat the text for a second time sub = self.device.avTransport.subscribe() # Take a snapshot of the current sonos device state, we will want # to roll back to this when we are done log("Speech: Taking snapshot") snap = Snapshot(self.device) snap.snapshot() # Get the URI and play it trans_URI = self._get_uri(message) log("Speech: Playing URI %s" % trans_URI) self.device.play_uri(trans_URI, title=ADDON.getLocalizedString(32105)) # The maximum number of seconds that we will wait for the message to # complete playing duration = 200 while duration > 0: # Check to see if the system is shutting down if xbmc.abortRequested: break try: eventItem = sub.events.get(timeout=0.1) # Now get the details of an event if there is one there if eventItem is not None: # Check to see if there is a message saying that it is waiting # to restart the audio stream. This happens because it is # being treated like a radio stream, so Sonos things when the # end of the mp3 file playing is reached that there has been # a connection error and needs to reconnect. If left to itself # it would play the mp3 file again if hasattr(eventItem, 'restart_pending') and ( eventItem.restart_pending is not None): # About to try and restart, so stop looping and stop the # track before it starts again if eventItem.restart_pending == '1': log("Speech: Detected restart attempt") break except Empty: pass # Wait another 10th of a second for the speech to stop playing duration = duration - 1 xbmc.sleep(100) log("Speech: Stopping speech") # Stop the stream playing self.device.stop() log("Speech: Restoring snapshot") try: # We no longer want to receive messages sub.unsubscribe() except: log( "Sonos: Failed to unsubscribe: %s" % traceback.format_exc(), xbmc.LOGERROR) try: # Make sure the thread is stopped even if unsubscribe failed event_listener.stop() except: log( "Sonos: Failed to stop event listener: %s" % traceback.format_exc(), xbmc.LOGERROR) del sub # Restore the sonos device back to it's previous state snap.restore() del snap except: log("Speech: %s" % traceback.format_exc(), xbmc.LOGERROR) xbmc.executebuiltin("Dialog.Close(busydialog)") raise xbmc.executebuiltin("Dialog.Close(busydialog)")
def say(self, message): log("Speech: Message to say is: %s" % message) # Start by checking to see if the message is valid if not self.checkIfValidMessage(message): return xbmc.executebuiltin("ActivateWindow(busydialog)") try: # Need to subscribe to transport events, this is so that we know # when a given track has finished, and so we can stop it, if # we do not stop it, then it will repeat the text for a second time sub = self.device.avTransport.subscribe() # Take a snapshot of the current sonos device state, we will want # to roll back to this when we are done log("Speech: Taking snapshot") snap = Snapshot(self.device) snap.snapshot() # Get the URI and play it trans_URI = self._get_uri(message) log("Speech: Playing URI %s" % trans_URI) self.device.play_uri(trans_URI, title=__addon__.getLocalizedString(32105)) # The maximum number of seconds that we will wait for the message to # complete playing duration = 200 while duration > 0: # Check to see if the system is shutting down if xbmc.abortRequested: break try: eventItem = sub.events.get(timeout=0.1) # Now get the details of an event if there is one there if eventItem is not None: # Check to see if there is a message saying that it is waiting # to restart the audio stream. This happens because it is # being treated like a radio stream, so Sonos things when the # end of the mp3 file playing is reached that there has been # a connection error and needs to reconnect. If left to itself # it would play the mp3 file again if hasattr(eventItem, 'restart_pending') and (eventItem.restart_pending is not None): # About to try and restart, so stop looping and stop the # track before it starts again if eventItem.restart_pending == '1': log("Speech: Detected restart attempt") break except Empty: pass # Wait another 10th of a second for the speech to stop playing duration = duration - 1 xbmc.sleep(100) log("Speech: Stopping speech") # Stop the stream playing self.device.stop() log("Speech: Restoring snapshot") try: # We no longer want to receive messages sub.unsubscribe() except: log("Sonos: Failed to unsubscribe: %s" % traceback.format_exc(), xbmc.LOGERROR) try: # Make sure the thread is stopped even if unsubscribe failed event_listener.stop() except: log("Sonos: Failed to stop event listener: %s" % traceback.format_exc(), xbmc.LOGERROR) del sub # Restore the sonos device back to it's previous state snap.restore() del snap except: log("Speech: %s" % traceback.format_exc(), xbmc.LOGERROR) xbmc.executebuiltin("Dialog.Close(busydialog)") raise xbmc.executebuiltin("Dialog.Close(busydialog)")
def say(self, message): # Need to subscribe to transport events, this is so that we know # when a given track has finished, and so we can stop it, if # we do not stop it, then it will repeat the text for a second time sub = self.device.avTransport.subscribe() # fade out #prefade_volume = self.device.volume #for v in range(prefade_volume): # self.device.volume -= 1 # time.sleep(0.25) # Take a snapshot of the current sonos device state, we will want # to roll back to this when we are done snap = Snapshot(self.device) snap.snapshot() msg = cgi.escape(message) payload = { 'ie' : 'UTF-8', 'q' : message, 'tl' : 'en', 'total' : 1, 'idx' : 0, 'client' : 't', 'textlen' : len(message), 'tk' : Token().calculate_token(message)} #trans_URL = "x-rincon-mp3radio://translate.google.com/translate_tts?tl=en&q=%s" % msg trans_URL = "x-rincon-mp3radio://translate.google.com/translate_tts?" + urlencode(payload) print trans_URL #from IPython import embed #embed() self.device.play_uri(trans_URL, title="Speech") #self.device.volume = prefade_volume impatience = time.time() patience = time.time() + 20 while patience > impatience: try: event = sub.events.get(timeout=0.5) print event.variables if 'restart_pending' not in event.variables: continue restart_pending = event.variables['restart_pending'] # About to try and restart, so stop looping and stop the # track before it starts again if restart_pending == '1': break except Empty: pass # Wait another second for the speech to stop playing time.sleep(1) impatience = time.time() time.sleep(0) # Stop the stream playing self.device.stop() # Restore the sonos device back to it's previous state snap.restore() # fade back in #for v in range(prefade_volume): # self.device.volume += 1 # time.sleep(0.25) # We no longer want to receive messages sub.unsubscribe() event_listener.stop()
def __del__(self): for sub in self.eventSubs: sub.unsubscribe() event_listener.stop()
def say(self, message): # Need to subscribe to transport events, this is so that we know # when a given track has finished, and so we can stop it, if # we do not stop it, then it will repeat the text for a second time sub = self.device.avTransport.subscribe() # fade out #prefade_volume = self.device.volume #for v in range(prefade_volume): # self.device.volume -= 1 # time.sleep(0.25) # Take a snapshot of the current sonos device state, we will want # to roll back to this when we are done snap = Snapshot(self.device) snap.snapshot() msg = cgi.escape(message) payload = { 'ie': 'UTF-8', 'q': message, 'tl': 'en', 'total': 1, 'idx': 0, 'client': 't', 'textlen': len(message), 'tk': Token().calculate_token(message) } #trans_URL = "x-rincon-mp3radio://translate.google.com/translate_tts?tl=en&q=%s" % msg trans_URL = "x-rincon-mp3radio://translate.google.com/translate_tts?" + urlencode( payload) print trans_URL #from IPython import embed #embed() self.device.play_uri(trans_URL, title="Speech") #self.device.volume = prefade_volume impatience = time.time() patience = time.time() + 20 while patience > impatience: try: event = sub.events.get(timeout=0.5) print event.variables if 'restart_pending' not in event.variables: continue restart_pending = event.variables['restart_pending'] # About to try and restart, so stop looping and stop the # track before it starts again if restart_pending == '1': break except Empty: pass # Wait another second for the speech to stop playing time.sleep(1) impatience = time.time() time.sleep(0) # Stop the stream playing self.device.stop() # Restore the sonos device back to it's previous state snap.restore() # fade back in #for v in range(prefade_volume): # self.device.volume += 1 # time.sleep(0.25) # We no longer want to receive messages sub.unsubscribe() event_listener.stop()