trackinfo = {
        'name':
        track.get('name'),
        'artists':
        ', '.join([artist.get('name') for artist in track.get('artists')])
    }
    print('Now playing: {artists} - {name}'.format(**trackinfo))


def show_tracklist(tracklist):
    print_nice('> Current Tracklist: ', tracklist, format='tracklist')


mopidy = MopidyClient()
mopidy.bind_event('track_playback_started', print_track_info)

mopidy.tracklist.get_tl_tracks(on_result=show_tracklist)

mopidy.tracklist.add(uris=[
    'local:track:01%20Home%20Recording.m4a',
    'local:track:Zonder%20totetrekkerie.mp3'
])

mopidy.tracklist.get_tl_tracks(on_result=show_tracklist)

mopidy.playback.play()

if __name__ == '__main__':

    # Main loop
Exemplo n.º 2
0
class MopidyWSCLI(object):
    def __init__(self, debug=False):
        super(MopidyWSCLI, self).__init__()

        print('Starting Mopidy Websocket Client CLI DEMO ...')

        # Init variables
        self.state = 'stopped'
        self.uri = None
        self.save_results = False
        self.debug_flag = debug

        # Instantiate Mopidy Client
        self.mopidy = MopidyClient(ws_url='ws://localhost:6680/mopidy/ws',
                                   error_handler=self.on_server_error,
                                   connection_handler=self.on_connection,
                                   autoconnect=False,
                                   retry_max=10,
                                   retry_secs=10)

        self.mopidy.debug_client(self.debug_flag)
        self.bind_events()
        self.mopidy.connect()

    def on_connection(self, conn_state):
        if conn_state:
            # Initialize mopidy track and state
            self.state = self.mopidy.playback.get_state(timeout=5)
            tl_track = self.mopidy.playback.get_current_tl_track(timeout=15)
            self.track_playback_started(tl_track)
        else:
            self.state = 'stopped'
            self.uri = None

    def bind_events(self):
        self.mopidy.bind_event('playback_state_changed',
                               self.playback_state_changed)
        self.mopidy.bind_event('stream_title_changed',
                               self.stream_title_changed)
        self.mopidy.bind_event('options_changed', self.options_changed)
        self.mopidy.bind_event('volume_changed', self.volume_changed)
        self.mopidy.bind_event('mute_changed', self.mute_changed)
        self.mopidy.bind_event('seeked', self.seeked)
        #self.mopidy.bind_event('audio_message', audio_message)

    def gen_uris(self, input_uris=None):
        presets = {
            'bt': ['bt:stream'],
            'spotify': ['spotifyweb:yourmusic:songs'],
            'epic': ['tunein:station:s213847'],
            'flaix': ['tunein:station:s24989'],
            'tunein': ['tunein:root'],
            'uri': [self.uri],
            'none': [None],
            'test': [
                'spotify:track:4ZiMMIaoK9sSI1iQIvHSq8',
                'tunein:station:s24989',
                'podcast+http://feeds.feedburner.com/aokishouse#http://traffic.libsyn.com/steveaoki/037_AOKIS_HOUSE_-_STEVE_AOKI.mp3',
                'bt:stream',
            ],
        }

        if not input_uris:
            return [self.uri]

        output_uris = []
        for uri in input_uris:
            if uri in presets:
                output_uris += presets[uri]
            else:
                output_uris += [uri]

        return output_uris

    def prompt(self):
        symbol = {
            'playing': '|>',
            'paused': '||',
            'stopped': '[]',
            None: '--',
        }
        uri = self.uri
        prompt_line = 'Mopidy %s>> ' % (
            # '{%s}(%s)' % (symbol[self.state], uri)
            '(%s)' % (symbol[self.state])
            if self.mopidy.is_connected() else '[OFFLINE]')
        user_input = input(prompt_line)
        command_line = user_input.strip(' \t\n\r').split(' ')

        command = command_line[0].lower()
        args = command_line[1:]

        return command, args

    @staticmethod
    def command_on_off(args, getter, setter):
        if args:
            if args[0].lower() in {'on', 'yes', 'true'}:
                new_value = True
            elif args[0].lower() in {'off', 'no', 'false'}:
                new_value = False
        else:
            current_value = getter(timeout=15)
            new_value = not current_value

        setter(new_value)

    @staticmethod
    def command_numeric(args, getter, setter, callback=None, step=1, res=1):

        if args:
            arg_value = args[0]
            current_value = 0

            relative = +1 if arg_value.startswith('+') \
                else -1 if arg_value.startswith('-') \
                else 0

            if relative:
                current_value = getter(timeout=15)
                arg_value = arg_value[1:]
            else:
                relative = 1

            if unicode(arg_value).isnumeric():
                step = int(arg_value)
            elif arg_value:
                return

            new_value = current_value + step * relative * res
            new_value = max(new_value, 0)

            setter(new_value)

        else:
            # No argument, get current value
            getter(on_result=callback)

    def get_debug(self, **kwargs):
        return self.debug_flag

    def set_debug(self, value, **kwargs):
        self.debug_flag = value
        self.mopidy.debug_client(self.debug_flag)
        print('> Debugging mopidy-json-client : %s' % self.debug_flag)

    def get_save_results(self, **kwargs):
        return self.save_results

    def set_save_results(self, value, **kwargs):
        self.save_results = value
        print('> Saving Results to file : %s' % value)

    def execute_command(self, command, args=[]):
        # Exit demo program
        if (command == 'exit'):
            self.mopidy.disconnect()
            time.sleep(0.2)
            exit()

        # Connection methods
        elif (command == 'connect'):
            self.mopidy.connect()

        elif (command == 'disconnect'):
            self.mopidy.disconnect()

        # Core methods
        elif (command == 'api'):
            core_api = self.mopidy.core.describe(timeout=40)

            if args:
                filtered_api = {
                    method: desc
                    for method, desc in core_api.items()
                    if any([arg in method for arg in args])
                }
                print_nice('*** MOPIDY CORE API [%s] ***' % ', '.join(args),
                           filtered_api)
            else:
                print_nice('*** MOPIDY CORE API ***', core_api)

        elif (command == 'version'):
            mopidy_version = self.mopidy.core.get_version(timeout=5)
            client_version = self.mopidy.get_client_version()
            print_nice('Mopidy Core Version: ', mopidy_version)
            print_nice('Mopidy-JSON Client Version: ', client_version)

        elif (command == 'send'):
            if args:
                kwargs = {}
                try:
                    for arg in args[1:]:
                        words = arg.split('=')
                        key = words[0]
                        value = int(words[1]) if unicode(words[1]).isnumeric() \
                            else words[1]
                        kwargs.update({key: value})
                    if 'timeout' not in kwargs:
                        kwargs['timeout'] = 40

                    result = self.mopidy.core.send(args[0], **kwargs)
                    print_nice('Result: ', result)

                except Exception as ex:
                    print_nice('Exception: ', ex, format='error')
            else:
                print('Use %s <method> <arg1=vaue1> <arg2=value2> ...\n' %
                      command)

        elif (command == 'debug'):
            self.command_on_off(args,
                                getter=self.get_debug,
                                setter=self.set_debug)

        # Get current track and update self.uri
        elif (command == 'track'):
            tl_track = self.mopidy.playback.get_current_tl_track(timeout=10)
            self.track_playback_started(tl_track)

        elif (command == 'stream'):
            self.mopidy.playback.get_stream_title(
                on_result=self.stream_title_changed)

        elif (command == 'pos'):
            self.command_numeric(args,
                                 getter=self.mopidy.playback.get_time_position,
                                 setter=self.mopidy.playback.seek,
                                 callback=self.seeked,
                                 step=30,
                                 res=1000)

        elif (command == 'state'):
            self.state = self.mopidy.playback.get_state(timeout=5)
            print_nice('Playback State: ', self.state)

        # Playback commands
        elif (command == 'play'):
            if args:
                if unicode(args[0]).isnumeric():
                    self.mopidy.playback.play(tlid=int(args[0]))
            else:
                self.mopidy.playback.play()
        elif (command == 'pause'):
            self.mopidy.playback.pause()
        elif (command == 'stop'):
            self.mopidy.playback.stop()
        elif (command == 'resume'):
            self.mopidy.playback.resume()
        elif (command == 'next'):
            self.mopidy.playback.next()
        elif (command in ('prev', 'previous')):
            self.mopidy.playback.previous()

        # Mixer commands
        elif (command in ('vol', 'volume')):
            self.command_numeric(args,
                                 getter=self.mopidy.mixer.get_volume,
                                 setter=self.mopidy.mixer.set_volume,
                                 callback=self.volume_changed,
                                 step=10)

        elif (command == 'mute'):
            self.command_on_off(args,
                                getter=self.mopidy.mixer.get_mute,
                                setter=self.mopidy.mixer.set_mute)

        # Tracklist commands
        elif (command == 'tracklist'):
            self.mopidy.tracklist.get_tl_tracks(on_result=self.show_tracklist)

        elif (command == 'add'):
            self.mopidy.tracklist.add(uris=self.gen_uris(args))

        elif (command == 'del'):
            if args and all([unicode(arg).isnumeric() for arg in args]):
                self.mopidy.tracklist.remove(
                    criteria={'tlid': [int(i) for i in args]})

        elif (command == 'clear'):
            self.mopidy.tracklist.clear()

        elif (command == 'shuffle'):
            self.mopidy.tracklist.shuffle()

        elif (command == 'random'):
            self.command_on_off(args,
                                getter=self.mopidy.tracklist.get_random,
                                setter=self.mopidy.tracklist.set_random)
        elif (command == 'single'):
            self.command_on_off(args,
                                getter=self.mopidy.tracklist.get_single,
                                setter=self.mopidy.tracklist.set_single)
        elif (command == 'repeat'):
            self.command_on_off(args,
                                getter=self.mopidy.tracklist.get_repeat,
                                setter=self.mopidy.tracklist.set_repeat)
        elif (command == 'consume'):
            self.command_on_off(args,
                                getter=self.mopidy.tracklist.get_consume,
                                setter=self.mopidy.tracklist.set_consume)
        elif (command == 'options'):
            self.options_changed()

        elif (command == 'playlists'):
            self.mopidy.playlists.as_list(on_result=self.show_playlists)

        # 'Tune' the given URIs uris and play them
        elif (command == 'tune'):
            if args:
                self.mopidy.tracklist.clear()
                self.mopidy.tracklist.add(uris=self.gen_uris(args))
                self.mopidy.playback.play()
                self.execute_command('track')

        # History methods
        elif (command == 'history'):
            self.mopidy.history.get_history(on_result=self.show_history)

        # Library methods
        elif (command == 'browse'):
            uri = self.gen_uris(args)[0]
            result = self.mopidy.library.browse(uri=uri, timeout=30)
            print_nice('> Browsing %s :' % uri, result, format='browse')

        elif (command in ['info', 'lookup', 'detail']):
            info = self.mopidy.library.lookup(uris=self.gen_uris(args),
                                              timeout=30)
            print_nice('> Lookup on URIs: ',
                       info,
                       format='expand' if command == 'detail' else 'lookup')

        elif (command in ['image', 'images']):
            images = self.mopidy.library.get_images(uris=self.gen_uris(args),
                                                    timeout=30)
            print_nice('> Images for URIs :', images, format='images')

        elif (command == 'search'):
            if args:
                uris = []
                search_terms = []
                for arg in args:
                    if arg.startswith('#'):
                        arg = self.gen_uris(arg)
                    if ':' in arg:
                        uris.append(arg)
                    else:
                        search_terms.append(arg)
                if not uris:
                    uris = []

                self.mopidy.library.search(query={'any': search_terms},
                                           uris=uris,
                                           on_result=self.show_search_results)

        # Set current uri
        elif (command == 'uri'):
            if args:
                self.uri = self.gen_uris([' '.join(args)])[0]

            print_nice("> Current URI: ", self.uri)

        elif (command == 'save'):
            self.command_on_off(args,
                                getter=self.get_save_results,
                                setter=self.set_save_results)

        elif command != '':
            print("  Unknown command '%s'" % command)

    # Request callbacks

    def show_search_results(self, search_results):
        print_nice('> Search Results: ', search_results, format='search')
        if self.save_results:
            with open('result_search.json', 'w') as json_file:
                json.dump(search_results, json_file)

    def show_tracklist(self, tracklist):
        print_nice('> Current Tracklist: ', tracklist, format='tracklist')
        if self.save_results:
            with open('result_tracklist.json', 'w') as json_file:
                json.dump(tracklist, json_file)

    def show_playlists(self, playlists):
        print_nice('> User Playlists: ', playlists, format='browse')
        if self.save_results:
            with open('result_playlists.json', 'w') as json_file:
                json.dump(playlists, json_file)

    def show_history(self, history):
        print_nice('> History: ', history, format='history')
        if self.save_results:
            with open('result_history.json', 'w') as json_file:
                json.dump(history, json_file)

    # Server Error Handler

    def on_server_error(self, error):
        print_nice('[SERVER_ERROR] ', error, format='error')

    # Mopidy Corelistener Events

    def stream_title_changed(self, title):
        print_nice('> Stream Title: ', title)

    def volume_changed(self, volume):
        print_nice('> Current volume is ', volume, format='volume')

    def playback_state_changed(self, old_state, new_state):
        self.state = new_state
        print_nice('> Playback state changed to ', self.state)

    def mute_changed(self, mute):
        print_nice('> Mute State is ', mute, format='mute')

    def options_changed(self):
        options = {
            'random': self.mopidy.tracklist.get_random(timeout=10),
            'single': self.mopidy.tracklist.get_single(timeout=10),
            'consume': self.mopidy.tracklist.get_consume(timeout=10),
            'repeat': self.mopidy.tracklist.get_repeat(timeout=10)
        }
        print_nice('Tracklist Options:', options, format='expand')

    def track_playback_started(self, tl_track):
        track = tl_track.get('track') if tl_track else None
        self.uri = track.get('uri') if track else None
        print_nice('> Current Track: ', track, format='track')

    def seeked(self, time_position):
        print_nice('> Current Position is ',
                   time_position,
                   format='time_position')
Exemplo n.º 3
0
class MopidyListenerClient(MopidyClient):
    """A simple mopidy Client class using the JSON WS interface of mopidy"""
    def __init__(self, debug=False):
        applog.debug('Initializing MopidyClient ...')

        # Init variables
        self.state = 'stopped'
        self.uri = None
        self.save_results = False
        self.debug_flag = debug

        # Instantiate Mopidy Client
        self.mopidy = MopidyClient(
            ws_url='ws://localhost:6680/mopidy/ws',
            #event_handler=self.on_event,
            connection_handler=self.on_connection,
            autoconnect=False,
            retry_max=None,
            retry_secs=10)

        self.mopidy.debug_client(self.debug_flag)
        self.mopidy.bind_event('playback_state_changed',
                               self.playback_state_changed)
        self.mopidy.connect()

        # Instantiate Timer Objects
        self.backlight_dim_timer = None
        self.backlight_off_timer = None

        # Functions for Timer Objects
    def bl_dim(self):
        applog.info("dimming backlight... ")
        sysfile = open("/sys/class/backlight/rpi_backlight/brightness", "w")
        sysfile.write(str(20))
        sysfile.close()

    def bl_off(self):
        applog.info("turning off backlight ")
        sysfile = open("/sys/class/backlight/rpi_backlight/bl_power", "w")
        sysfile.write(str(1))
        sysfile.close()

    def bl_on(self):
        applog.info("turning on backlight ")
        sysfile = open("/sys/class/backlight/rpi_backlight/bl_power", "w")
        sysfile.write(str(0))
        sysfile.close()
        #wait some time for the previous SPI command to finish
        time.sleep(0.5)
        #applog.info ("setting max brightness")
        sysfile = open("/sys/class/backlight/rpi_backlight/brightness", "w")
        sysfile.write(str(255))
        sysfile.close()

    def playback_state_changed(self, old_state, new_state):
        self.state = new_state
        applog.info('State changed: ' + str(old_state) + ' => ' +
                    str(self.state))
        self.backlight_timer_control()

    def backlight_timer_control(self):
        #Handle backlight timers
        #try to stop existing timers before starting new timers
        applog.debug("stopping backlight timers ")

        if (self.backlight_dim_timer is not None):
            self.backlight_dim_timer.cancel()
        if (self.backlight_off_timer is not None):
            self.backlight_off_timer.cancel()
        #applog.debug ("turn on backlight")
        self.bl_on()

        if (self.state != 'playing'):
            applog.debug("starting backlight timers")
            self.backlight_dim_timer = Timer(30.0, self.bl_dim)
            self.backlight_off_timer = Timer(60.0, self.bl_off)
            self.backlight_dim_timer.start()
            self.backlight_off_timer.start()

    def on_connection(self, conn_state):
        if conn_state:
            # Initialize mopidy track and state
            self.state = self.mopidy.playback.get_state(timeout=5)
            tl_track = self.mopidy.playback.get_current_tl_track(timeout=15)
            #self.track_playback_started(tl_track)
            #applog.debug ("On Conn: Current state "+self.state)
            self.backlight_timer_control()
        else:
            self.state = 'stopped'
            self.uri = None

    def playback_play(self):
        self.mopidy.playback.play()

    def playback_pause(self):
        self.mopidy.playback.pause()

    def playback_stop(self):
        self.mopidy.playback.stop()

    def tracklist_clear(self):
        self.mopidy.tracklist.clear()

    def tracklist_tune(self, uri):
        self.mopidy.playback.stop()
        self.mopidy.tracklist.clear()
        self.mopidy.tracklist.add(at_position=1, uri=uri)
        self.mopidy.mixer.set_volume(100)
        self.mopidy.playback.play()
Exemplo n.º 4
0
class MediaManager(EventDispatcher):

    connected = BooleanProperty(False)

    current = ObjectProperty(TrackControl(
        refresh_method='playback.get_current_tl_track', refresh_args={}),
                             rebind=True)

    prev = ObjectProperty(TrackControl(
        refresh_method='tracklist.previous_track',
        refresh_args={'tl_track': None}),
                          rebind=True)
    next = ObjectProperty(TrackControl(refresh_method='tracklist.next_track',
                                       refresh_args={'tl_track': None}),
                          rebind=True)
    eot = ObjectProperty(TrackControl(refresh_method='tracklist.eot_track',
                                      refresh_args={'tl_track': None}),
                         rebind=True)

    state = ObjectProperty(PlaybackControl(), rebind=True)

    mixer = ObjectProperty(MixerControl(), rebind=True)
    options = ObjectProperty(OptionsControl(), rebind=True)

    queue = ObjectProperty(QueueControl(), rebind=True)

    browser = ObjectProperty(BrowserControl(), rebind=True)
    history = ObjectProperty(HistoryControl(), rebind=True)

    def __init__(self, **kwargs):
        super(MediaManager, self).__init__(**kwargs)

        self.app = App.get_running_app()
        MediaController.app = self.app

        self.mopidy = MopidyClient(
            ws_url='ws://' + self.app.MOPIDY_SERVER + '/mopidy/ws',
            version='2.0.1',
            error_handler=self.on_mopidy_error,
            connection_handler=self.on_connection,
        )
        #        self.mopidy.debug_client(True)

        self.controllers = (self.state, self.mixer, self.options, self.current,
                            self.next, self.prev, self.queue, self.browser,
                            self.history)

        self.bind_events()

    @mainthread
    def on_connection(self, connection_state, *args):
        self.connected = connection_state

        if self.connected:
            self.set_interfaces()
            self.init_player_state()
        else:
            self.reset_player_state()

        Clock.schedule_once(self.choose_window, 5)

    def choose_window(self, *args, **kwargs):
        if not self.connected:
            screen = 'system'
        elif self.state.playback_state != 'stopped':
            screen = 'playback'
        elif self.queue.tracklist:
            screen = 'tracklist'
        else:
            screen = 'browse'

        self.app.main.switch_to(screen=screen)

    def set_interfaces(self):
        # Set mopidy accesible to every MediaController subclass
        MediaController.set_server(self.mopidy)

        PlaybackControl.set_interface(self.mopidy.playback)
        MixerControl.set_interface(self.mopidy.mixer)
        OptionsControl.set_interface(self.mopidy.tracklist)
        QueueControl.set_interface(self.mopidy.tracklist)
        BrowserControl.set_interface(self.mopidy.library)
        HistoryControl.set_interface(self.mopidy.history)

    def bind_events(self, *args):
        # Clear previous events to avoid duplicity
        self.mopidy.listener.clear()

        # Mixer events
        self.mopidy.bind_event('volume_changed', self.mixer.update_volume)
        self.mopidy.bind_event('mute_changed', self.mixer.update_mute)

        # State events
        self.mopidy.bind_event('playback_state_changed',
                               self.state.set_playback_state)
        self.mopidy.bind_event('seeked', self.state.set_time_position)
        self.mopidy.bind_event('stream_title_changed',
                               self.state.set_stream_title)

        # Playback events
        self.mopidy.bind_event('track_playback_started',
                               self.track_playback_started)
        self.mopidy.bind_event('track_playback_ended',
                               self.track_playback_ended)
        self.mopidy.bind_event('track_playback_paused',
                               self.track_playback_paused_or_resumed)
        self.mopidy.bind_event('track_playback_resumed',
                               self.track_playback_paused_or_resumed)

        # Current track updates
        self.current.bind(item=self.refresh_context_info)
        self.state.bind(on_next=self.current.refresh,
                        on_prev=self.current.refresh)

        # Context update: Options and Tracklist
        self.mopidy.bind_event('options_changed', self.options.refresh)
        self.mopidy.bind_event('tracklist_changed', self.queue.refresh)
        self.mopidy.bind_event('options_changed', self.refresh_context_info)
        self.mopidy.bind_event('tracklist_changed', self.refresh_context_info)

    def init_player_state(self):
        for controller in self.controllers:
            controller.refresh()

    def reset_player_state(self):
        for controller in self.controllers:
            controller.reset()

    def on_mopidy_error(self, error):
        self.app.main.show_error(error=error)

    @triggered(3)
    def check_info_on_track_end(self, *args):
        for controller in (self.state, self.current):
            controller.refresh()

    @triggered(1)
    def refresh_context_info(self, *args):
        for trackitem in (self.next, self.prev, self.eot):
            trackitem.refresh()

    # Track playback events

    @mainthread
    def track_playback_started(self, tl_track):
        self.check_info_on_track_end.cancel()
        self.state.set_time_position(0)
        self.current.set_tl_track(tl_track)
        self.history.refresh()

    @mainthread
    def track_playback_ended(self, time_position, tl_track):
        self.state.set_time_position(0)
        self.state.set_stream_title(None)
        self.check_info_on_track_end()

    @mainthread
    def track_playback_paused_or_resumed(self, time_position, tl_track):
        self.state.set_time_position(time_position)
        self.current.set_tl_track(tl_track)

    # TODO: Move to a proper place (queue)
    # TODO: The two actions are quite the same. Join.

    def play_uris(self, uris=None, refs=None):

        if refs:
            uris = [
                RefUtils.get_uri(ref) for ref in refs
                if RefUtils.get_type(ref) == 'track'
            ]
        if not uris:
            return

        try:
            tl_index = self.mopidy.tracklist.index(timeout=5) or 0
            tltracks = self.mopidy.tracklist.add(
                uris=uris,
                at_position=tl_index + 1,  # play just before current track
                timeout=20)
            tlid_first = tltracks[0]['tlid']
            self.mopidy.playback.play(tlid=tlid_first)
            self.app.main.switch_to(screen='playback')
        except Exception:
            pass

    def add_to_tracklist(
        self,
        refs=None,
        uris=None,
        tune_id=None,
    ):
        if refs:
            uris = [
                RefUtils.get_uri(ref) for ref in refs
                if RefUtils.get_type(ref) == 'track'
            ]
        if not uris:
            return

        # Select tune_id as first and shuffle if aplicable

        if tune_id is not None:
            tune_uri = uris.pop(tune_id)
            self.mopidy.tracklist.clear()
            self.mopidy.tracklist.add(uris=[tune_uri])
            self.mopidy.playback.play()
            self.app.main.switch_to(screen='playback')
        else:
            tune_id = 0

        if self.queue.shuffle_mode:
            random.shuffle(uris)
            tune_id = 0

        self.mopidy.tracklist.add(uris=uris[tune_id:])
        if tune_id:
            self.mopidy.tracklist.add(uris=uris[:tune_id], at_position=0)
Exemplo n.º 5
0
class MediaManager(EventDispatcher):

    connected = BooleanProperty(False)

    current = ObjectProperty(
        TrackControl(refresh_method='playback.get_current_tl_track',
                     refresh_args={}),
        rebind=True)

    prev = ObjectProperty(
        TrackControl(refresh_method='tracklist.previous_track',
                     refresh_args={'tl_track': None}),
        rebind=True)
    next = ObjectProperty(
        TrackControl(refresh_method='tracklist.next_track',
                     refresh_args={'tl_track': None}),
        rebind=True)
    eot = ObjectProperty(
        TrackControl(refresh_method='tracklist.eot_track',
                     refresh_args={'tl_track': None}),
        rebind=True)

    state = ObjectProperty(PlaybackControl(), rebind=True)

    mixer = ObjectProperty(MixerControl(), rebind=True)
    options = ObjectProperty(OptionsControl(), rebind=True)

    queue = ObjectProperty(QueueControl(), rebind=True)

    browser = ObjectProperty(BrowserControl(), rebind=True)
    history = ObjectProperty(HistoryControl(), rebind=True)


    def __init__(self, **kwargs):
        super(MediaManager, self).__init__(**kwargs)

        self.app = App.get_running_app()
        MediaController.app = self.app

        self.mopidy = MopidyClient(
            ws_url='ws://' + self.app.MOPIDY_SERVER + '/mopidy/ws',
            version='2.0.1',
            error_handler=self.on_mopidy_error,
            connection_handler=self.on_connection,
        )
#        self.mopidy.debug_client(True)

        self.controllers = (
            self.state, self.mixer, self.options,
            self.current, self.next, self.prev,
            self.queue, self.browser, self.history
            )

        self.bind_events()

    @mainthread
    def on_connection(self, connection_state, *args):
        self.connected = connection_state

        if self.connected:
            self.set_interfaces()
            self.init_player_state()
        else:
            self.reset_player_state()

        Clock.schedule_once(self.choose_window, 5)

    def choose_window(self, *args, **kwargs):
        if not self.connected:
            screen = 'system'
        elif self.state.playback_state != 'stopped':
            screen = 'playback'
        elif self.queue.tracklist:
            screen = 'tracklist'
        else:
            screen = 'browse'

        self.app.main.switch_to(screen=screen)

    def set_interfaces(self):
        # Set mopidy accesible to every MediaController subclass
        MediaController.set_server(self.mopidy)

        PlaybackControl.set_interface(self.mopidy.playback)
        MixerControl.set_interface(self.mopidy.mixer)
        OptionsControl.set_interface(self.mopidy.tracklist)
        QueueControl.set_interface(self.mopidy.tracklist)
        BrowserControl.set_interface(self.mopidy.library)
        HistoryControl.set_interface(self.mopidy.history)

    def bind_events(self, *args):
        # Clear previous events to avoid duplicity
        self.mopidy.listener.clear()

        # Mixer events
        self.mopidy.bind_event('volume_changed', self.mixer.update_volume)
        self.mopidy.bind_event('mute_changed', self.mixer.update_mute)

        # State events
        self.mopidy.bind_event('playback_state_changed', self.state.set_playback_state)
        self.mopidy.bind_event('seeked', self.state.set_time_position)
        self.mopidy.bind_event('stream_title_changed', self.state.set_stream_title)

        # Playback events
        self.mopidy.bind_event('track_playback_started', self.track_playback_started)
        self.mopidy.bind_event('track_playback_ended', self.track_playback_ended)
        self.mopidy.bind_event('track_playback_paused', self.track_playback_paused_or_resumed)
        self.mopidy.bind_event('track_playback_resumed', self.track_playback_paused_or_resumed)

        # Current track updates
        self.current.bind(item=self.refresh_context_info)
        self.state.bind(on_next=self.current.refresh,
                        on_prev=self.current.refresh)

        # Context update: Options and Tracklist
        self.mopidy.bind_event('options_changed', self.options.refresh)
        self.mopidy.bind_event('tracklist_changed', self.queue.refresh)
        self.mopidy.bind_event('options_changed', self.refresh_context_info)
        self.mopidy.bind_event('tracklist_changed', self.refresh_context_info)

    def init_player_state(self):
        for controller in self.controllers:
            controller.refresh()

    def reset_player_state(self):
        for controller in self.controllers:
            controller.reset()

    def on_mopidy_error(self, error):
        self.app.main.show_error(error=error)

    @triggered(3)
    def check_info_on_track_end(self, *args):
        for controller in (self.state,
                           self.current):
            controller.refresh()

    @triggered(1)
    def refresh_context_info(self, *args):
        for trackitem in (self.next,
                          self.prev,
                          self.eot):
            trackitem.refresh()

    # Track playback events

    @mainthread
    def track_playback_started(self, tl_track):
        self.check_info_on_track_end.cancel()
        self.state.set_time_position(0)
        self.current.set_tl_track(tl_track)
        self.history.refresh()

    @mainthread
    def track_playback_ended(self, time_position, tl_track):
        self.state.set_time_position(0)
        self.state.set_stream_title(None)
        self.check_info_on_track_end()

    @mainthread
    def track_playback_paused_or_resumed(self, time_position, tl_track):
        self.state.set_time_position(time_position)
        self.current.set_tl_track(tl_track)

    # TODO: Move to a proper place (queue)
    # TODO: The two actions are quite the same. Join.

    def play_uris(self, uris=None, refs=None):

        if refs:
            uris = [RefUtils.get_uri(ref) for ref in refs
                    if RefUtils.get_type(ref) == 'track']
        if not uris:
            return

        try:
            tl_index = self.mopidy.tracklist.index(timeout=5) or 0
            tltracks = self.mopidy.tracklist.add(
                uris=uris,
                at_position=tl_index + 1,  # play just before current track
                timeout=20
            )
            tlid_first = tltracks[0]['tlid']
            self.mopidy.playback.play(tlid=tlid_first)
            self.app.main.switch_to(screen='playback')
        except Exception:
            pass

    def add_to_tracklist(self,
                         refs=None, uris=None,
                         tune_id=None,
                         ):
        if refs:
            uris = [RefUtils.get_uri(ref) for ref in refs
                    if RefUtils.get_type(ref) == 'track']
        if not uris:
            return

        # Select tune_id as first and shuffle if aplicable

        if tune_id is not None:
            tune_uri = uris.pop(tune_id)
            self.mopidy.tracklist.clear()
            self.mopidy.tracklist.add(uris=[tune_uri])
            self.mopidy.playback.play()
            self.app.main.switch_to(screen='playback')
        else:
            tune_id = 0

        if self.queue.shuffle_mode:
            random.shuffle(uris)
            tune_id = 0

        self.mopidy.tracklist.add(uris=uris[tune_id:])
        if tune_id:
            self.mopidy.tracklist.add(uris=uris[:tune_id], at_position=0)
Exemplo n.º 6
0
class RunText(SampleBase):
    def __init__(self, *args, **kwargs):
        super(RunText, self).__init__(*args, **kwargs)
        self.parser.add_argument("-t", "--text", help="The text to scroll on the RGB LED panel", default="Hello world!")
        super(RunText, self).__init__()

        print('Starting Mopidy to Matrix')

        # Init variables
        self.state = 'stopped'
        self.uri = None
        self.save_results = False
        self.debug_flag = False

        # Instantiate Mopidy Client
        self.mopidy = MopidyClient(
            ws_url='ws://192.168.178.220:6680/mopidy/ws',
            autoconnect=False,
            retry_max=10,
            retry_secs=10
        )
        self.mopidy.bind_event('track_playback_started', updatetrack)
        self.mopidy.bind_event('playback_state_changed', playback_state_changed)
        self.mopidy.debug_client(self.debug_flag)
        self.mopidy.connect()
        global mopid
        mopid = self.mopidy
        
        s.start()
        t.start()
      #  time.sleep(1.55)
      ##  state = self.mopidy.playback.get_state(timeout=5)
      #  if state == "Playing":
     #       self.mopidy.playback.pause()
   #         self.mopidy.playback.resume()

     #  tl_track = mopid.playback.get_current_tl_track(timeout=15)
     #  track = tl_track.get('track') if tl_track else None
     #  if track != None:
     #      name = track.get('name')
     #      artists = ', '.join([artist.get('name') for artist in track.get('artists')])
     #      tr = "" + artists + " - " + name
     #  else:
     #      tr = ""

        #    trackinfo = {
         #       'name': track.get('name'),
        #        'artists': ', '.join([artist.get('name') for artist in track.get('artists')])
   #         }
          # tr = track.get('name')
           # print('Now playing: {artists} - {name}'.format(**trackinfo))

    def track_playback_started(self, tl_track):
        track = tl_track.get('track') if tl_track else None
        self.uri = track.get('uri') if track else None
        print_nice('> Current Track: ', track, format='track')

    def run(self):
        offscreen_canvas = self.matrix.CreateFrameCanvas()
        font = graphics.Font()
        font.LoadFont("/home/pi/rpi-rgb-led-matrix/fonts/6x13.bdf")
      #  r = random.randint(1, 255)
      #  g = random.randint(1, 255)
      #  b = random.randint(1, 255)
      #  textColor = graphics.Color(r, g, b)
        pos = offscreen_canvas.width
       # my_text = self.args.text

        while True:
            offscreen_canvas.Clear()
            global disco
            if disco == True:
                r = random.randint(1, 255)
                g = random.randint(1, 255)
                b = random.randint(1, 255)
            else:
                r = 255
                g = 255
                b = 0 

            textColor = graphics.Color(r, g, b)
            global li
            global status
           # print(status)


            if status == "music":
                global loc
                global maxlen
                

                breed = loc / maxlen * 32
                len = graphics.DrawText(offscreen_canvas, font, pos, 12, textColor, tr)
                if tr != "":
                    lenr = graphics.DrawLine(offscreen_canvas, 0, 15, breed, 15, textColor)
                pos -= 1
                if (pos + len < 0):
                    pos = offscreen_canvas.width
    
                time.sleep(0.05)
                
            elif status == "time":
                localtime   = time.localtime()
                timeString  = time.strftime("%H:%M", localtime)
                minu  = time.strftime("%M", localtime)
                if int(minu) % 5 == 0:
                    x = 0
                    y = 14
                elif int(minu) % 3 == 0:
                    x = 3
                    y = 12
                else:
                    x = 1
                    y = 15
               # print(timeString)
                leni = graphics.DrawText(offscreen_canvas, font, x, y, textColor, timeString)
            else:
                pass
            offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas)