def test_envvar(self): os.environ.pop('MPD_HOST', None) os.environ.pop('MPD_PORT', None) client = musicpd.MPDClient() self.assertEqual(client.host, 'localhost') self.assertEqual(client.port, '6600') os.environ['MPD_HOST'] = '*****@*****.**' client = musicpd.MPDClient() self.assertEqual(client.pwd, 'pa55w04d') self.assertEqual(client.host, 'example.org') self.assertEqual(client.port, '6600') os.environ.pop('MPD_HOST', None) os.environ['MPD_PORT'] = '6666' client = musicpd.MPDClient() self.assertEqual(client.pwd, None) self.assertEqual(client.host, 'localhost') self.assertEqual(client.port, '6666') # Test unix socket fallback os.environ.pop('MPD_HOST', None) os.environ.pop('MPD_PORT', None) os.environ.pop('XDG_RUNTIME_DIR', None) with mock.patch('os.path.exists', return_value=True): client = musicpd.MPDClient() self.assertEqual(client.host, '/run/mpd/socket') os.environ.pop('MPD_HOST', None) os.environ.pop('MPD_PORT', None) os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/' with mock.patch('os.path.exists', return_value=True): client = musicpd.MPDClient() self.assertEqual(client.host, '/run/user/1000/mpd/socket')
def __init__(self): self.targetVolume = 90 self.currentVolume = 65 self.maxIncrement = 2 self.volumeInterval = 2 # interval in [sec] self.playList = [] self.client = musicpd.MPDClient() self.update()
def __init__(self, loop): self.client = musicpd.MPDClient() self.loop = loop self.connected = False self.radiostations = [] self.playlists = [] self.nowplaying = {} self.status = "" self.loadedplaylist = "" self._connectionlost()
def main(): config_path = sys.argv[1] config = load_config(config_path) rfid = Reader(config["general"]["rfid_device"].strip('"')) spotify_controller = SpotifyController(config["general"]["spotify_device"]) mpd_controller = musicpd.MPDClient() mpd_controller.connect(config["general"]["mpd_host"].strip('"')) while True: tag = rfid.readCard() logging.info("read tag %s", tag) config = load_config(config_path) max_retries = config.getint("general", "retry") retry_count = 0 should_try = True while should_try: if retry_count > 0: logging.warning("tentative %d", retry_count) try: if tag == config["controls"]["stop"].strip('"'): logging.info("stopping spotify") spotify_controller.stop() logging.info("stopping mpd") mpd_controller.stop() elif tag in config["spotify"]: uri = config["spotify"][tag] mpd_controller.stop() spotify_controller.play_or_next(uri) elif tag in config["mpd"]: spotify_controller.stop() uri = config["mpd"][tag].strip('"') logging.info("playing %s", uri) mpd_controller.clear() mpd_controller.load(uri) mpd_controller.play() else: logging.info("unknown tag %s", tag) should_try = False except Exception as e: logging.error("error %s", e) try: mpd_controller.disconnect() except: # Was already disconnected, do nothing pass retry_count += 1 if retry_count >= max_retries: logging.error("too many retries, exiting") sys.exit(1)
def main(): global poll_interval, accel_factor, volume_step, pin_a, pin_b, print_debug, db, db_cursor, mpd_cli # Parse input args (if any) if len(sys.argv) > 1: if sys.argv[1] == "--version" or sys.argv[1] == "-v": print("rotenc.py version " + program_version) sys.exit(0) if len(sys.argv) >= 6: poll_interval = int(sys.argv[1]) accel_factor = int(sys.argv[2]) volume_step = int(sys.argv[3]) pin_a = int(sys.argv[4]) pin_b = int(sys.argv[5]) if len(sys.argv) == 7: print_debug = int(sys.argv[6]) if print_debug: print(sys.argv, len(sys.argv)) # Setup GPIO GPIO.setmode(GPIO.BCM) # SoC pin numbering GPIO.setwarnings(True) GPIO.setup(pin_a, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(pin_b, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect( pin_a, GPIO.BOTH, callback=encoder_isr) # NOTE: bouncetime= is not specified GPIO.add_event_detect(pin_b, GPIO.BOTH, callback=encoder_isr) # Setup sqlite db = sqlite3.connect('/var/local/www/db/moode-sqlite3.db') db.row_factory = sqlite3.Row db.text_factory = str db_cursor = db.cursor() # Setup MPD client mpd_cli = musicpd.MPDClient() #mpd_cli.connect() # Detect encoder changes poll_interval = poll_interval / 1000 poll_encoder()
def setUp(self): self.socket_patch = mock.patch('musicpd.socket') self.socket_mock = self.socket_patch.start() self.socket_mock.getaddrinfo.return_value = [range(5)] self.socket_mock.socket.side_effect = ( lambda *a, **kw: # Create a new socket.socket() mock with default attributes, # each time we are calling it back (otherwise, it keeps set # attributes across calls). # That's probably what we want, since reconnecting is like # reinitializing the entire connection, and so, the mock. mock.MagicMock(name='socket.socket')) self.client = musicpd.MPDClient() self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT) self.client._sock.reset_mock() self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
def main(): music = musicpd.MPDClient() music.connect('localhost', 6600) music.replay_gain_mode('track') music.volume(100) music.update() music.disconnect() while True: try: code = get_command() except OverflowError: # because alarm fired continue music.connect('localhost', 6600) try: if code == 'STOP': print('STOP') music.clear() elif code == '8686': call('/sbin/poweroff') elif code == '-': print('previous') music.previous() elif code == '+': print('next') music.next() else: music.clear() music.load(code + '.m3u') music.consume(0) music.repeat(0) if code == '999': music.random(1) else: music.random(0) music.play() signal.alarm(MAXPLAYTIME) print('Now playing: ' + code) except Exception as e: print('got an error: ' + str(e)) music.disconnect()
def main(): logging.basicConfig(level=logging.DEBUG) # MPD setup mpd = musicpd.MPDClient() mpd.connect('localhost', 6600) atexit.register(cleanup(mpd)) # Backend Player player = BackendPlayer(mpd) # Tk root = tk.Tk() root.config(cursor="none") root.attributes('-zoomed', True) root.geometry('{}x{}'.format(320, 240)) app = PiraTK(root, player) app.toggle_fullscreen() # Begin playing player.init() root.mainloop()
def __init__(self): self.client = musicpd.MPDClient() #stores current playlist name self.currentPlaylistName = "None"
def sleep_handler(signum, frame): music = musicpd.MPDClient() music.connect('localhost', 6600) music.clear() print('going to sleep') music.disconnect()
def _connect(self): self._client = musicpd.MPDClient() self._client.connect(host=str(self.basepath), port=0)
from urllib.request import urlopen from waitress import serve from colorthief import ColorThief if sys.version_info < (3, 0): from urllib2 import urlopen else: from urllib.request import urlopen # initialization app = Flask(__name__) #Flask CORS(app, resources=r'/api/*', allow_headers=['Content-Type', 'Access-Control-Allow-Origin']) #Cross Origin for JSON #logging.getLogger('flask_cors').level = logging.DEBUG #Debug with CORS client = musicpd.MPDClient() #mpd client desired_volume = 50 #volume at start = 50 info = [] # functions def startup_func(): global desired_volume, client, info program = 'C:/mpd/mpd.exe' #make sure your path is correct args = 'C:/mpd/mpd.conf' #make sure your path is correct try: client.connect() except: Popen([program, args], creationflags=CREATE_NEW_CONSOLE ) #CREATE_NEW_CONSOLE MAY ONLY WORK IN WINDOWS client.connect()
def main(): parser = argparse.ArgumentParser() parser.add_argument('--host', '-s', type=str, default='localhost', \ help='Specify the host mpd is running on') parser.add_argument('--port', '-p', type=int, default=6600, \ help='Specify the port mpd is running on') parser.add_argument('--play_symbol', type=str, default="f144", \ help='Symbol-code for playing music') parser.add_argument('--pause_symbol', type=str, default="f28b", \ help='Symbol-code for paused music') parser.add_argument('--stop_symbol', type=str, default="f28d", \ help='Symbol-code for stopped music') parser.add_argument('--refresh-time', '-r', type=float, default=0.5, \ help='Interval for when to check data in seconds (float)') parser.add_argument('--text-refresh-rate', '-R', type=float, default=1, \ help='Interval for text rotation:' \ 'index will be increased by x for every r') parser.add_argument('--string-length', '-l', type=int, default=45, \ help='Total length of printed string') parser.add_argument('--pango', '-m', action='store_true', \ help='Enables printing with pango markup. ' \ ' Required for some unicode symbols.') parser.add_argument('--unicode-font', type=str, \ default='Font Awesome 5 Free Solid', \ help='Font for drawing unicode symbols') parser.add_argument('--regular-font', type=str, \ default='DejaVu Sans Mono', \ help='Font for regular text') parser.add_argument('--no-artist', action='store_true', \ help='Disable showing the artist') parser.add_argument('--no-title', action='store_true', \ help='Disable showing the title') args = parser.parse_args() try: client = musicpd.MPDClient() client.connect(args.host, args.port) index = 0.0 while True: if args.pango: play, pause, stop = pango_unicode(args) else: play, pause, stop = python_unicode(args) data = get_info(client) state = data[0]['state'] if state == 'play': title_str, time_str, index = generate_title_string(data, args, index) title_string = '%s%s%s' % (play, title_str, time_str) elif state == 'pause': title_str, time_str, index = generate_title_string(data, args, index) title_string = '%s%s%s' % (pause, title_str, time_str) else: title_string = '%s %s' % (stop, generate_title_string(None, args)) print(title_string) sys.stdout.flush() time.sleep(args.refresh_time) finally: client.close() client.disconnect()
def main(): client = musicpd.MPDClient() client.timeout = 300 client.idletimeout = 300 client.connect('::1', 6600) option = rofi_options(client) index = rofi_index(client) current_dir = '' status = 1 # select row place Thread(target=check, daemon=True, args=(client, )).start() while 1: option.gen_options() rofi = subprocess.Popen(option.options, stdout=subprocess.PIPE, stdin=subprocess.PIPE) index.gen_index(current_dir) select = index.prefix + index.indexes tmp = rofi.communicate(select.encode())[0].decode().rstrip() status = 1 if not tmp: break if tmp == ' Go Back': if '/' in current_dir: current_dir = current_dir[:current_dir.rfind('/')] else: current_dir = '' elif tmp == ' Add all': client.add(current_dir) if '/' in current_dir: current_dir = current_dir[:current_dir.rfind('/')] else: current_dir = '' # Go to Playlist mode elif tmp == ' Playlist mode': playlist = rofi_playlist(client) status = 3 while 1: if playlist.playlist: status = 1 option.gen_options() option.options[8] = f'[Playlist mode]{playlist.playlist}' rofi = subprocess.Popen(option.options, stdout=subprocess.PIPE, stdin=subprocess.PIPE) playlist.gen_index() select = playlist.prefix + playlist.indexes tmp = rofi.communicate(select.encode())[0].decode().rstrip() status = 3 if not tmp: sys.exit() else: if tmp == ' Go Back to Main menu': status = 1 break if tmp == ' Clear Playlist': client.clear() elif tmp == ' Go Back': playlist.playlist = '' elif tmp == ' Add this playlist': client.load(playlist.playlist) playlist.playlist = '' status = 0 elif '' in tmp: playlist.playlist = tmp.split()[-1] else: pass elif tmp == ' Play': if not client.playlistinfo(): pass else: client.play() elif tmp == ' Pause': client.pause() elif tmp == ' Next': client.next() elif '' in tmp: # TODO: add functions status = 2 else: status = 2 if current_dir: current_dir += '/' + tmp[4:] else: current_dir = tmp[4:]
def __init__(self, *args, **kwargs): super(Mpd, self).__init__(*args, **kwargs) self.client = musicpd.MPDClient() self.client.connect(self.config['ip'], self.config['port'])
def main(): disp.set_backlight(True) filename = '/var/local/www/currentsong.txt' c = 0 p = 0 k = 0 ol = 0 ss = 0 x1 = 20 x2 = 20 x3 = 20 title_top = 105 volume_top = 184 time_top = 222 act_mpd = isServiceActive('mpd') SHADE = displayConf['shadow'] if act_mpd == True: while True: client = musicpd.MPDClient() # create client object try: client.connect() # use MPD_HOST/MPD_PORT except: pass else: moode_meta = getMoodeMetadata(filename) mpd_current = client.currentsong() mpd_status = client.status() cover = get_cover(moode_meta) mn = 50 if OVERLAY == 3: img.paste( cover.resize((WIDTH, HEIGHT), Image.LANCZOS).convert('RGB')) else: img.paste( cover.resize((WIDTH, HEIGHT), Image.LANCZOS).filter( ImageFilter.GaussianBlur).convert('RGB')) if 'state' in mpd_status: if (mpd_status['state'] == 'stop') and (BLANK != 0): if ss < BLANK: ss = ss + 1 else: disp.set_backlight(False) else: ss = 0 disp.set_backlight(True) im_stat = ImageStat.Stat(cover) im_mean = im_stat.mean mn = mean(im_mean) #txt_col = (255-int(im_mean[0]), 255-int(im_mean[1]), 255-int(im_mean[2])) txt_col = (255, 255, 255) str_col = (15, 15, 15) bar_col = (255, 255, 255, 255) dark = False if mn > 175: txt_col = (55, 55, 55) str_col = (200, 200, 200) dark = True bar_col = (100, 100, 100, 225) if mn < 80: txt_col = (200, 200, 200) str_col = (55, 55, 55) if (moode_meta['source'] == 'library') or (moode_meta['source'] == 'radio'): if (OVERLAY > 0) and (OVERLAY < 3): if 'state' in mpd_status: if OVERLAY == 2: if mpd_status['state'] != 'play': if dark is False: img.paste(pause_icons, (0, 0), pause_icons) else: img.paste(pause_icons_dark, (0, 0), pause_icons_dark) else: if dark is False: img.paste(play_icons, (0, 0), play_icons) else: img.paste(play_icons_dark, (0, 0), play_icons_dark) elif OVERLAY == 1: if dark is False: img.paste(vol_icons, (0, 0), vol_icons) else: img.paste(vol_icons_dark, (0, 0), vol_icons_dark) else: img.paste(play_icons, (0, 0), play_icons) if 'volume' in mpd_status: vol = int(mpd_status['volume']) vol_x = int((vol / 100) * (WIDTH - 33)) draw.rectangle( (5, volume_top, WIDTH - 34, volume_top + 8), (255, 255, 255, 145)) draw.rectangle( (5, volume_top, vol_x, volume_top + 8), bar_col) if OVERLAY < 3: if TIMEBAR == 1: if 'elapsed' in mpd_status: el_time = int(float(mpd_status['elapsed'])) if 'duration' in mpd_status: du_time = int(float( mpd_status['duration'])) dur_x = int( (el_time / du_time) * (WIDTH - 10)) draw.rectangle((5, time_top, WIDTH - 5, time_top + 12), (255, 255, 255, 145)) draw.rectangle( (5, time_top, dur_x, time_top + 12), bar_col) top = 7 if 'artist' in moode_meta: w1, y1 = draw.textsize(moode_meta['artist'], font_m) x1 = x1 - 20 if x1 < (WIDTH - w1 - 20): x1 = 0 if w1 <= WIDTH: x1 = (WIDTH - w1) // 2 if SHADE != 0: draw.text((x1 + SHADE, top + SHADE), moode_meta['artist'], font=font_m, fill=str_col) draw.text((x1, top), moode_meta['artist'], font=font_m, fill=txt_col) top = 35 if 'album' in moode_meta: w2, y2 = draw.textsize(moode_meta['album'], font_s) x2 = x2 - 20 if x2 < (WIDTH - w2 - 20): x2 = 0 if w2 <= WIDTH: x2 = (WIDTH - w2) // 2 if SHADE != 0: draw.text((x2 + SHADE, top + SHADE), moode_meta['album'], font=font_s, fill=str_col) draw.text((x2, top), moode_meta['album'], font=font_s, fill=txt_col) if 'title' in moode_meta: w3, y3 = draw.textsize(moode_meta['title'], font_l) x3 = x3 - 20 if x3 < (WIDTH - w3 - 20): x3 = 0 if w3 <= WIDTH: x3 = (WIDTH - w3) // 2 if SHADE != 0: draw.text((x3 + SHADE, title_top + SHADE), moode_meta['title'], font=font_l, fill=str_col) draw.text((x3, title_top), moode_meta['title'], font=font_l, fill=txt_col) else: if 'file' in moode_meta: txt = moode_meta['file'].replace(' ', '\n') w3, h3 = draw.multiline_textsize(txt, font_l, spacing=6) x3 = (WIDTH - w3) // 2 y3 = (HEIGHT - h3) // 2 if SHADE != 0: draw.text((x3 + SHADE, y3 + SHADE), txt, font=font_l, fill=str_col) draw.text((x3, y3), txt, font=font_l, fill=txt_col, spacing=6, align="center") disp.display(img) if c == 0: im7 = img.save(script_path + '/dump.jpg') c += 1 time.sleep(1) ol += 1 client.disconnect() else: draw.rectangle((0, 0, 240, 240), fill=(0, 0, 0)) txt = 'MPD not Active!\nEnsure MPD is running\nThen restart script' mlw, mlh = draw.multiline_textsize(txt, font=font_m, spacing=4) draw.multiline_text(((WIDTH - mlw) // 2, 20), txt, fill=(255, 255, 255), font=font_m, spacing=4, align="center") disp.display(img)
def run(args): cli = musicpd.MPDClient() cli.connect() uri = cli.currentsong().get('file') try: likes = cli.sticker_get('song', uri, 'likes') likes_offset = len('likes=') likes = int(likes[likes_offset:]) except musicpd.CommandError: likes = 0 try: dislikes = cli.sticker_get('song', uri, 'dislikes') dislikes_offset = len('dislikes=') dislikes = int(dislikes[dislikes_offset:]) except musicpd.CommandError: dislikes = 0 if args.verbose: try: wrating = cli.sticker_get('song', uri, 'wrating') wrating_offset = len('wrating=') wrating = wrating[wrating_offset:] except musicpd.CommandError: print("No rating yet") wrating = 0 print('Likes before update =', likes) print('Dislikes before update =', dislikes) print('Rating before update =', wrating) if args.like: likes += 1 elif args.dislike: dislikes += 1 elif args.unlike: likes = max(0, likes - 1) elif args.undislike: dislikes = max(0, dislikes - 1) wrating = wilson_lower_bound(likes, dislikes) likes = str(likes) dislikes = str(dislikes) wrating = '{0:.10f}'.format(wrating) if args.like or args.dislike or args.unlike or args.undislike: cli.sticker_set('song', uri, 'likes', likes) cli.sticker_set('song', uri, 'dislikes', dislikes) cli.sticker_set('song', uri, 'wrating', wrating) if args.notify: import notify2 timeout = 1000 notify2.init("Rating notifier") notify_text = "" if args.like: notify_text = "Liked!\n" elif args.dislike: notify_text = "Disliked!\n" elif args.unlike: notify_text = "Unliked!\n" elif args.undislike: notify_text = "Undisiked!\n" else: notify_text = "Checking!\n" timeout = 2000 notify_text += "L: " + str(likes) + "\n" notify_text += "D: " + str(dislikes) + "\n" notify_text += "R: " + str(wrating) + "\n" n = notify2.Notification( notify_text, "Rating", icon="notification-message-im" # Icon name ) n.set_timeout(timeout) n.show() if args.verbose: print('Likes after update =', likes) print('Dislikes after update =', dislikes) print('Rating after update =', wrating) cli.disconnect()
action="append", default=[]) parser.add_argument( "-b", "--before", help="How many played songs leave in the playlist (default: 10)", type=int, default=10) parser.add_argument("-a", "--ahead", help="How many songs plan ahead (default: 10)", type=int, default=10) args = parser.parse_args() client = musicpd.MPDClient() currentlists = {} # { 'playlist', 'last-modified', 'weight' } currentsongs = [] # [ (id, name) ] playedsongs = [] # [ id ] if not len(args.playlist): args.playlist.append('Auto') def msg(*msg): if not args.quiet: print(*msg) def parsePlaylist(name):