Ejemplo n.º 1
0
    def run(self):

        # Wait for window to initialise
        # Can be removed after refactoring
        # time.sleep(1)

        self._client = mpd.MPDClient()
        self._client.timeout = 10
        self._client.idletimeout = None

        self._state = 'stop'
        self._card = None
        self._info = None
        self._file = None

        while (True):
            try:
                self._client.connect(self._host, self._port)

                while (True):
                    self.update()
                    time.sleep(1)
            except Exception as e:
                print e
                time.sleep(5)
Ejemplo n.º 2
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the MPD platform."""
    daemon = config.get('server', None)
    port = config.get('port', 6600)
    location = config.get('location', 'MPD')
    password = config.get('password', None)

    import mpd

    # pylint: disable=no-member
    try:
        mpd_client = mpd.MPDClient()
        mpd_client.connect(daemon, port)

        if password is not None:
            mpd_client.password(password)

        mpd_client.close()
        mpd_client.disconnect()
    except socket.error:
        _LOGGER.error("Unable to connect to MPD. "
                      "Please check your settings")

        return False
    except mpd.CommandError as error:

        if "incorrect password" in str(error):
            _LOGGER.error("MPD reported incorrect password. "
                          "Please check your password.")

            return False
        else:
            raise

    add_devices([MpdDevice(daemon, port, location, password)])
Ejemplo n.º 3
0
def MPD(stream):
    try:
        client = mpd.MPDClient()
        client.connect(stream["host"], stream["port"])
        yield client
    finally:
        client.close()
Ejemplo n.º 4
0
Archivo: common.py Proyecto: tomef/vim
	def player_mpd(self, pl, host='localhost', port=6600):
		try:
			import mpd
		except ImportError:
			now_playing = run_cmd(pl, ['mpc', 'current', '-f', '%album%\n%artist%\n%title%\n%time%', '-h', str(host), '-p', str(port)])
			if not now_playing:
				return
			now_playing = now_playing.split('\n')
			return {
				'album': now_playing[0],
				'artist': now_playing[1],
				'title': now_playing[2],
				'total': now_playing[3],
			}
		else:
			client = mpd.MPDClient()
			client.connect(host, port)
			now_playing = client.currentsong()
			if not now_playing:
				return
			status = client.status()
			client.close()
			client.disconnect()
			return {
				'state': status.get('state'),
				'state_symbol': self.STATE_SYMBOLS.get(status.get('state')),
				'album': now_playing.get('album'),
				'artist': now_playing.get('artist'),
				'title': now_playing.get('title'),
				'elapsed': self._convert_seconds(now_playing.get('elapsed', 0)),
				'total': self._convert_seconds(now_playing.get('time', 0)),
			}
Ejemplo n.º 5
0
 def __init__(self,
              host='localhost',
              port=6600,
              password=False,
              fmt_playing="%a - %t [%v%%]",
              fmt_stopped="Stopped [%v%%]",
              msg_nc='Mpd off',
              do_color_progress=True,
              **config):
     """
         - host: host to connect to
         - port: port to connect to
         - password: password to use
         - fmt_playing, fmt_stopped: format strings to display when playing/paused and when stopped, respectively
         - msg_nc: which message to show when we're not connected
         - do_color_progress: whether to indicate progress in song by altering message color
         - width: A fixed width, or bar.CALCULATED to calculate the width
         automatically (which is recommended).
     """
     super(Mpd, self).__init__(msg_nc, **config)
     self.host = host
     self.port = port
     self.password = password
     self.fmt_playing, self.fmt_stopped = fmt_playing, fmt_stopped
     self.msg_nc = msg_nc
     self.do_color_progress = do_color_progress
     self.inc = 2
     self.add_defaults(Mpd.defaults)
     self.client = mpd.MPDClient()
     self.connected = False
     self.stop = False
Ejemplo n.º 6
0
    def connect(self):

        # Try up to 10 times to connect to MPD
        self.connection_failed = 0
        self.dataclient = None

        logging.debug(u"Connecting to MPD service on {0}:{1}".format(
            self.server, self.port))

        while True:
            if self.connection_failed >= 10:
                logging.debug(u"Could not connect to MPD")
                break
            try:
                # Connection to MPD
                client = mpd.MPDClient(use_unicode=True)
                client.connect(self.server, self.port)

                self.dataclient = client
                break
            except:
                self.dataclient = None
                self.connection_failed += 1
                time.sleep(1)
        if self.dataclient is None:
            raise mpd.ConnectionError(u"Could not connect to MPD")
        else:
            logging.debug(u"Connected to MPD")
Ejemplo n.º 7
0
def update_mpd_db(songs, add_to_playlist):
    # songs: list of music files or just a string (file path)
    if not config["mpd"].getboolean("use_mpd"):
        return
    print("Updating mpd database")
    timeout_counter = 0
    mpd_client = mpd.MPDClient(use_unicode=True)
    try:
        mpd_client.connect(config["mpd"]["host"], config["mpd"].getint("port"))
    except ConnectionRefusedError as e:
        print("ERROR connecting to MPD ({}:{}): {}".format(
            config["mpd"]["host"], config["mpd"]["port"], e))
        return
    mpd_client.update()
    if add_to_playlist:
        songs = [songs] if type(songs) != list else songs
        songs = make_song_paths_relative_to_mpd_root(songs)
        while len(mpd_client.search("file", songs[0])) == 0:
            # c.update() does not block so wait for it
            if timeout_counter == 10:
                print(
                    "Tried it {} times. Give up now.".format(timeout_counter))
                return
            print("'{}' not found in the music db. Let's wait for it".format(
                songs[0]))
            timeout_counter += 1
            time.sleep(2)
        for song in songs:
            try:
                mpd_client.add(song)
                print("Added to mpd playlist: '{}'".format(song))
            except mpd.base.CommandError as mpd_error:
                print("ERROR adding '{}' to playlist: {}".format(
                    song, mpd_error))
Ejemplo n.º 8
0
    def connect(self):

        print("connecting to mopidy")
        self.client = mpd.MPDClient(use_unicode=True)
        self.client.connect("localhost", 6600)
        print("finished connecting to mopidy")
        print(client.mpd_version)
Ejemplo n.º 9
0
 def __init__(self, host='localhost', port='6600', password=None, *args, **kwargs):
     super(MPDClient, self).__init__(*args, **kwargs)
     self._client = mpd.MPDClient()
     self._connected = False
     self.host = host
     self.port = port
     self.password = password
Ejemplo n.º 10
0
def profile(request):
    client = mpd.MPDClient()
    client.timeout = 10
    client.idletimeout = None
    client.connect(Grooplayer.settings.MPD_SERVER,
                   Grooplayer.settings.MPD_PORT)

    if request.method == 'POST':
        form = TrackForm(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            instance = form.save(commit=True)
            client.update()
            return HttpResponseRedirect('/profile/')
    else:
        form = TrackForm(user=request.user)

    status = client.status()
    journal = Action.objects.all().order_by("-date")
    tracks = Track.objects.filter(user=request.user)
    return {
        "status": status,
        "journal": journal,
        "tracks": tracks,
        "form": form
    }
Ejemplo n.º 11
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the MPD platform. """

    daemon = config.get('server', None)
    port = config.get('port', 6600)
    location = config.get('location', 'MPD')

    global mpd  # pylint: disable=invalid-name
    if mpd is None:
        import mpd as mpd_
        mpd = mpd_

    # pylint: disable=no-member
    try:
        mpd_client = mpd.MPDClient()
        mpd_client.connect(daemon, port)
        mpd_client.close()
        mpd_client.disconnect()
    except socket.error:
        _LOGGER.error(
            "Unable to connect to MPD. "
            "Please check your settings")

        return False

    add_devices([MpdDevice(daemon, port, location)])
Ejemplo n.º 12
0
def main(args):
    client = mpd.MPDClient()
    client.timeout = 10
    client.idletimeout = None
    client.connect(args.host, args.port)
    if args.password:
        client.password(args.password)
    if args.options == 'current':
        enqueue_current(client)
    elif args.options == 'search':
        enqueue_date(client, args.search_date)
    elif args.options == 'random':
        cache_file = get_cache_file()
        cache = load_cache(cache_file)
        albums: List[str] = client.list("album")
        percent = get_cache_size(len(albums))
        for n in range(args.number_off_albums):
            album_name = queue_random_album(client, cache)
            if not album_name:
                break
            cache.append(album_name)
            cache = enforce_cache_size(percent, cache)
        save_cache(cache_file, cache)
    client.close()
    client.disconnect()
Ejemplo n.º 13
0
def main():
    c = mpd.MPDClient()
    host = os.environ.get('MPD_HOST', 'localhost')
    port = os.environ.get('MPD_PORT', '6600')
    pw = None
    if "@" in host:
        pw, host = host.split("@")
    c.connect(host, port)
    if pw is not None:
        c.password(pw)
    print("<html>")
    print(
        "<head><meta charset=\"utf-8\"/><link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\"><style>body{background:#eee}table{margin:5em auto; max-width:56em; background: white;}</style></head>"
    )
    print("<body>")
    print("<div class=\"table-responsive\">")
    print("<table id=\"music\" class=\"table table-bordered\">")
    print("<thead>")
    print(
        "<tr><th>Artist</th><th>Year</th><th>Album</th><th>Rating</th></tr></thead><tbody>"
    )
    for artist in sorted(get_artists(c)):
        albums = sorted(query(c, 'date', 'album', albumartist=artist))
        print('<tr class=\"newartist\"><td rowspan="{0}">{1}</td>'.format(
            len(albums), artist))
        for i, (date, album) in enumerate(albums):
            rating = get_rating(c, artist, date, album)
            # templating libraries ftw
            print("<td>{}</td>".format(date))
            print("<td>{}</td>".format(album))
            print("<td><font color=\"red\">{}</td>".format(rating))
            print("</tr>")
    print("</table></div>")
Ejemplo n.º 14
0
def main(bot, args):
    '''Управление MPD. Команды:
shuffle, sh — включает режим рандомного проигрывания и пускает следующий трек.
*  sh off — отключает рандом, что даёт возможность набивать треки в очередь.
*  sh on — только включает рандом
*  sh st — сообщает статус рандома
play, p <number> — запускает проигрывание трека номер <number> (0 — маунт first, 1 — маунт second, далее рандомные треки)
list, ls, l [first] [last] — показывает список треков с [first] по [last]
search, se, s <query> — находит треки и выводит их с соответствующими номерами 
mounts, mi, m — показывает состояние диджейских маунтов
tag, t <name> — установить название текущего трека в <name>
v <song and artist name> — ищет вконтактике и добавляет указанную песню
d <number> — удаляет трек номер <number> (первые три защищены)
dbk <words> — удаляет треки по ключевому слову(ам)
next, n <number> — перемещает трек номер <number> в самый конец плейлиста
g <words> — группирует треки по ключевому слову(ам) в конце плейлиста
wtf — показывает текущий трек и заменяет теги на ключевые слова
seek, sk [HH:][MM:]SS — перемотать на HH часов, MM минут, SS секунд
'''
    global globalbot
    globalbot = bot

    client = mpd.MPDClient()
    try:
        client.connect(**bot.settings["mpd_addr"])
    except socket.error, msg:
        return "ошибка соединения: " + msg
Ejemplo n.º 15
0
def main():
    # Main program block

    # Initialise display
    lcd_init()
    ## Connect to mpd client ###
    client = mpd.MPDClient()
    client.connect("localhost", 6600)

    ## Get current song info ###
    curSongInfo = client.currentsong()
    songTitle = curSongInfo['file']

    # Send some right justified text
    lcd_byte(LCD_LINE_1, LCD_CMD)
    lcd_string("Now Playing: ", 1)
    str_pad = " " * 16
    songTitle = str_pad + songTitle
    for i in range(0, len(songTitle)):
        lcd_byte(LCD_LINE_2, LCD_CMD)
        lcd_text = songTitle[i:(i + 15)]
        lcd_string(lcd_text, 1)
        time.sleep(0.4)
    lcd_byte(LCD_LINE_2, LCD_CMD)
    lcd_string(str_pad, 1)
Ejemplo n.º 16
0
    def __init__(self):
        super(Controller, self).__init__()
        self.daemon = True
        self.exit_event = threading.Event()
        #self.plugins = plugins.load_all()
        self.buttons = buttons.ButtonReader(config.BUTTONS_EVDEV_FILE)
        self.buttons.register(self.buttons_callback)
        self.buttons.start()
        self.queue = Queue.Queue()
        self.queue_do = Queue.Queue()

        dummy_parameter = "dummy_parameter"
        self.sensors = sensors.SensorReader(dummy_parameter)
        self.sensors.register(self.sensors_callback)
        self.sensors.start()
        self.queue_sensors = Queue.Queue()

        self.folder_index = -1
        self.folders = config.MUSIC_FOLDERS
        self.mpd = mpd.MPDClient()
        self.mpd.connect('127.0.0.1', 6600)
        self.led = leds.LED(config.LED_NAME)
        self.updater = updater.Updater()
        self.justBooted()
        self.saved_song = 0
        self.saved_time = 0
Ejemplo n.º 17
0
def get_mpd_client():
    mpd_client = mpd.MPDClient()
    mpd_client.connect(MPD_HOST, MPD_PORT)
    if MPD_PASSWORD:
        mpd_client.password(MPD_PASSWORD)

    return mpd_client
Ejemplo n.º 18
0
    def __init__(self, log):
        self._log = log

        self.music_directory = (
            mpd_config['music_directory'].as_str())

        self.client = mpd.MPDClient(use_unicode=True)
Ejemplo n.º 19
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the MPD platform."""
    daemon = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    location = config.get(CONF_LOCATION)
    password = config.get(CONF_PASSWORD)

    import mpd

    # pylint: disable=no-member
    try:
        mpd_client = mpd.MPDClient()
        mpd_client.connect(daemon, port)

        if password is not None:
            mpd_client.password(password)

        mpd_client.close()
        mpd_client.disconnect()
    except socket.error:
        _LOGGER.error("Unable to connect to MPD")
        return False
    except mpd.CommandError as error:

        if "incorrect password" in str(error):
            _LOGGER.error("MPD reported incorrect password")
            return False
        else:
            raise

    add_devices([MpdDevice(daemon, port, location, password)])
Ejemplo n.º 20
0
 def __init__(self, **config):
     super(Mpd, self).__init__('MPD Widget', **config)
     self.add_defaults(Mpd.defaults)
     self.inc = 2
     self.client = mpd.MPDClient()
     self.connected = None
     self.stop = False
Ejemplo n.º 21
0
    def __init__(self):
        self.mpd_client = mpd.MPDClient()
        self.host = 'localhost'
        self.port = 6600
        self.update_interval = 1000  # Interval between mpc status update calls (milliseconds)
        self.volume = 0  # Playback volume
        self.playlist_current = []  # Current playlist song title
        self.repeat = False  #
        self.random = False
        self.single = False
        self.consume = False
        self.updating_library = False
        self.__radio_mode = False
        self.now_playing = MPDNowPlaying()
        self.events = deque([])  # Queue of mpd events
        # Database search results
        self.searching_artist = ""  # Search path user goes through
        self.searching_album = ""
        self.list_albums = []
        self.list_artists = []
        self.list_songs = []
        self.list_query_results = []

        self.__music_directory = ""
        self.__now_playing = None  # Dictionary containing currently playing song info
        self.__now_playing_changed = False
        self.__player_control = ''  # Indicates whether mpd is playing, pausing or has stopped playing music
        self.__muted = False  # Indicates whether muted
        self.__playlist_current_playing_index = 0
        self.__last_update_time = 0  # For checking last update time (milliseconds)
        self.__status = None  # mps's current status output
Ejemplo n.º 22
0
 def __init__(self, config, media=None):
     # 播放器相同字段
     self.config = config
     self._media = media
     self._muted = False
     self.media_position = 0
     self.media_duration = 0
     self.media_position_updated_at = datetime.datetime.now()
     self.state = 'idle'
     self.is_tts = False
     self.is_on = True
     # 不同字段
     self._status = None
     self._muted_volume = 0
     self._is_connected = False
     try:
         import mpd
         self._client = mpd.MPDClient()
         self._client.timeout = 30
         self._client.idletimeout = None
         self._connect()
         self.is_support = True
         # 定时更新
         self.timer = threading.Timer(1, self.update)
         self.timer.start()
     except Exception as e:
         print(e)
         self.is_support = False
Ejemplo n.º 23
0
    def publishReceived(self, mosq, obj, msg):
        match = re.match(r'mpd/(\w+)/control', msg.topic)

        if match and match.group(1) in CHANNEL_TO_SERVER:

            command = msg.payload.decode('utf-8')

            if not command in ALLOWED_COMMANDS:
                logging.info('command not allowed: {}'.format(command))

            else:
                logging.debug('mpd command: {}'.format(command))

                try:
                    server, port, mqtt_prefix = CHANNEL_TO_SERVER[match.group(
                        1)]
                    c = mpd.MPDClient()
                    c.timeout = 10
                    c.idletimeout = None
                    c.connect(server, port)
                    ALLOWED_COMMANDS[command](c)
                    c.close()
                    c.disconnect()

                except:
                    logging.error(
                        'error while sending mpd command ({server}:{port} {command})'
                        .format(server=server, port=port, command=command))
Ejemplo n.º 24
0
    def __init__(self, params):
        self.client = mpd.MPDClient()

        self._dbus = dbus
        self._params = params
        self._dbus_service = None

        self._can_single = False
        self._can_idle = False

        self._errors = 0
        self._poll_id = None
        self._watch_id = None
        self._idling = False

        self._status = {
            'state': None,
            'volume': None,
            'random': None,
            'repeat': None,
        }
        self._metadata = {}
        self._temp_song_url = None
        self._temp_cover = None
        self._position = 0
        self._time = 0

        self._bus = dbus.SessionBus()
        if self._params['mmkeys']:
            self.setup_mediakeys()
Ejemplo n.º 25
0
 def __init__(self, registrar):
   super(Music, self).__init__(registrar)
   settings = ConfigParser.SafeConfigParser()
   settings.read(utils.get_plugin_settings_paths(__name__))
   hostname = "localhost"
   port = 6600
   try:
     hostname = settings.get("MPD", "hostname")
     port = settings.get("MPD", "port")
   except ConfigParser.NoSectionError:
     raise plugin.PluginLoadError("'MPD' section in config does not exist.")
   except ConfigParser.NoOptionError as err:
     if err.section == "hostname":
       logger.log("MPD hostname not in settings. "
                   "Using default of '{0}'".format(hostname))
     elif err.section == "port":
       logger.log("MPD port not in settings. "
                   "Using default of '{0}'".format(port))
   except TypeError:
     logger.log("Error loading settings for MPD. Using host and port "
                 "{0}:{1}.".format(hostname, port))
   self.client = mpd.MPDClient()
   self.client.connect(hostname, port)
   self.version = tuple(int(i) for i in self.client.mpd_version.split('.'))
   
   registrar.register_service("play", self.play,
     {"target": []}, namespace=__name__)
   registrar.register_service("listen", self.play,
     {"target": ["listen to"]}, namespace=__name__)
   registrar.register_service("pause", self.pause, {}, namespace=__name__)
   registrar.register_service("stop", self.stop, {}, namespace=__name__)
   registrar.register_service("song", self.song, {
     "next": ["next"],
     "previous": ["previous"],
   }, namespace=__name__)
Ejemplo n.º 26
0
 def MPDInitialize(self):
     global rpi
     rpi = mpd.MPDClient()
     rpi.connect('10.184.2.31', 6600)
     time.sleep(2)
     print('Correct')
     print(rpi.playlist())
Ejemplo n.º 27
0
    def __init__(self, main_window):
        self.enabled = len(main_window) > 1
        if not self.enabled:
            return

        self.main_window = main_window
        self.client = mpd.MPDClient()
        self.connected = False
        self.mpd_status = None

        self.status_label = QtWidgets.QLabel()
        self.status_label.setProperty('class', 'icon')
        self.status_label.setStyleSheet('QWidget { margin-right: -8px }')
        self.song_label = QtWidgets.QLabel()
        self.random_label = QtWidgets.QLabel()
        self.random_label.setProperty('class', 'icon')
        self.random_label.setText('\U0001F500')

        for w in [self.status_label, self.song_label, self.random_label]:
            main_window[len(main_window) -
                        1].right_widget.layout().addWidget(w)

        self.status_label.mouseReleaseEvent = self.play_pause_clicked
        self.song_label.mouseReleaseEvent = self.play_pause_clicked
        self.random_label.mouseReleaseEvent = self.random_clicked
        self.status_label.wheelEvent = self.prev_or_next_track
        self.song_label.wheelEvent = self.prev_or_next_track
Ejemplo n.º 28
0
def control(request):
    if request.method == "POST":
        if request.POST["action"] is not None:
            action =  request.POST["action"]
            carma = None
            client = None
            if request.user.is_authenticated():
                profile = user_profile(request.user)
                carma = profile.carma
                client = mpd.MPDClient()
                client.timeout = 10
                client.idletimeout = None
                client.connect(Grooplayer.settings.MPD_SERVER,Grooplayer.settings.MPD_PORT)
            if action and carma is not None:
                if request.user.is_authenticated():
                    if action == "play" and carma > 0:
                        client.play()
                        profile.take(2)
                        log(request.user, 'нажал на кнопку "Воспроизведение"')
                    elif action == "stop" and carma > 0:
                        client.stop()
                        profile.take(2)
                        log(request.user, 'нажал на кнопку "Стоп"')
                    elif action == "pause" and carma > 0:
                        client.pause()
                        profile.take(2)
                        log(request.user, 'нажал на кнопку "Пауза"')

    return HttpResponse(status=200)
Ejemplo n.º 29
0
 def connection(self):
     # prepare client
     client = mpd.MPDClient()
     client.timeout = None
     client.idletimeout = None
     try:
         client.connect(self._server, self._port)
         if self._password is not None and self._password != '':
             client.password(self._password)
         yield client
     except (mpd.ConnectionError, socket.error) as e:
         if isinstance(e, socket.error):
             message = "%s (Errno: %d)" % (e.strerror, e.errno)
         else:
             message = e.message
         self._logger.warning(
             'Connection error while trying to access server %s:%d: %s',
             self._server, self._port, message)
         raise RuntimeError('Connection failed')
     finally:
         try:
             client.close()
         except Exception:
             pass
         try:
             client.disconnect()
         except Exception:
             pass
Ejemplo n.º 30
0
def get_filenames(mpd_playlist, mpd_connection, mp3_root):
    client = mpd.MPDClient()
    client.connect(*mpd_connection)
    return [
        os.path.join(mp3_root, filename)
        for filename in client.listplaylist(mpd_playlist)
    ]