From 1f048f3e8eed3b9aac70dc10394dce0cdf2be98f Mon Sep 17 00:00:00 2001 From: kaliko Date: Mon, 7 Dec 2009 21:05:15 +0000 Subject: [PATCH] * add new goodies fadeio.py (sleep command) * add lib directory with common utilities --- config.py | 18 +++++-- fadio.py | 133 ++++++++++++++++++++++++++++++++++++++++++++++++ jingle.py | 72 +++++--------------------- lib/__init__.py | 0 lib/mpdutils.py | 107 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 268 insertions(+), 62 deletions(-) create mode 100755 fadio.py create mode 100644 lib/__init__.py create mode 100644 lib/mpdutils.py diff --git a/config.py b/config.py index 1a900c0..2bc8579 100644 --- a/config.py +++ b/config.py @@ -1,12 +1,20 @@ # -*- coding: utf-8 -*- +# This config is python script ## SETTINGS # ## MPD -# set PASSWORD to "False" if not use -HOST = 'localhost' -PORT = '6600' -PASSWORD = False +# +# The default are localhost:6600 / no password +# +# To set different MPD host/port/password please use environment variables. +# +# You may set MPD_HOST/MPD_PORT in your shell rc file +# or +# You can launch the script with leading environment variables: +# $> MPD_HOST=pass@my_mpd_host script.py +# +# More details in mpc manual (cf. man 1 mpc), section ENVIRONMENT ## Set JINGLE_TAG here. # @@ -22,6 +30,8 @@ PASSWORD = False # 'artist' : 'Steve Albini' # } #JINGLE_TAG = {'comment': 'jingle'} +#TODO: remove following to release +JINGLE_TAG = {'artist': 'Magma'} # VIM MODLINE # vim: ai ts=4 sw=4 sts=4 expandtab diff --git a/fadio.py b/fadio.py new file mode 100755 index 0000000..1053e40 --- /dev/null +++ b/fadio.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2009 Efrim {{{ +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# }}} + +""" +DOC: + heavily borrowed from perl script mpdtoys and converted to python. + mpdtoys © 2007 Joey Hess + http://kitenet.net/~joey/code/mpdtoys +""" + +import sys + +from time import sleep + +from lib.mpdutils import mconnect + +USAGE = """Usage: + +fadio.py [time [min|max]] + + * time in seconds + * min|max in percentag + +- not palying: fade in from 0% to max over time + default 10 minutes / 50% +- if playing: fade out from current volume to min over time + default 10 minutes / 1/10 of current vol + +Manual or any external volume change will abort the script. +""" + + +class Sleep(object): + """ + """ + + def __init__(self): + """""" + self.tempo = int(10) + self.volum = None + self._consume_sopt() + self.cli = mconnect() + self._run() + self.cli.disconnect() + + def _consume_sopt(self): + """ + """ + options = sys.argv + if len(sys.argv) >1 and sys.argv[1] in ['-h', '--help']: + print USAGE + sys.exit(1) + try: + self.tempo = int(options.pop(1)) + self.volum = int(options.pop(1)) + except IndexError: + pass + except ValueError, err: + print 'Error: wrong option passed: %s' % err + print USAGE + sys.exit(1) + + def _run(self): + """""" + self.mpd_state = str(self.cli.status().get('state')) + self.mpd_vol = int(self.cli.status().get('volume')) + if self.mpd_state == 'play': + if not self.volum: + self.volum = self.mpd_vol / 10 + if self.volum > self.mpd_vol: + print 'Error: specified min volume (%d%%) > to current volume (%d%%)' % (self.volum, self.mpd_vol) + sys.exit(1) + print 'fading down from %d%% to %d%% over %smin' % (self.mpd_vol, + self.volum, self.tempo) + self.fade() + self.cli.stop() + if self.mpd_state in ['stop', 'pause']: + if not self.volum: + self.volum = int(50) + print 'fading up from 0%% to %d%% over %smin' % (self.volum, + self.tempo) + self.cli.setvol(0) + self.mpd_vol = 0 + self.cli.play() + self.fade() + sleep(1) + + def fade(self): + span = float(self.volum - self.mpd_vol) + step = span / float(60 * self.tempo) + print step + vol = self.mpd_vol + while 42: + if int(vol) != int(self.cli.status().get('volume')): + print 'Warning: external volume change, aborting!' + break + vol += step + print step, int(vol) + self.cli.setvol(int(vol)) + if abs(vol - self.volum) < 1: + self.cli.setvol(self.volum) + break + sleep(1) + + +# Script starts here +if __name__ == '__main__': + options = [14, 11] + #main(options) + try: + Sleep() + except KeyboardInterrupt: + print 'exit' + +# VIM MODLINE +# vim: ai ts=4 sw=4 sts=4 expandtab diff --git a/jingle.py b/jingle.py index b0614b0..3d25dd6 100755 --- a/jingle.py +++ b/jingle.py @@ -18,7 +18,7 @@ # # }}} -""" +DOC = """ DOC: The script randomly pick up a song to queue from the library. @@ -65,7 +65,7 @@ BUGS: MPD bugs: http://musicpd.org/mantis/view.php?id=498 """ -__version__ = u'0.2' +__version__ = u'0.3' __author__ = u'$Author: kaliko $' __date__ = u'$LastChangedDate: 2009-11-17 19:23:34 +0100 (mar. 17 nov. 2009) $'[18:28] @@ -74,47 +74,21 @@ __date__ = u'$LastChangedDate: 2009-11-17 19:23:34 +0100 (mar. 17 nov. 2009) $'[ import sys from random import choice -from socket import error as SocketError try: - from mpd import (MPDClient, CommandError) + from mpd import (CommandError) except ImportError, err: print 'ERROR: "%s"\n\nPlease install python-mpd module.\n' % err sys.exit(1) try: - from config import (HOST, PORT, PASSWORD, JINGLE_TAG) + from config import JINGLE_TAG except ImportError, err: - print 'ERROR: missing settings in config.py: %s' % err + print 'ERROR: "%s"\n' % err + print '\tPlease set JINGLE_TAG in config.py' sys.exit(1) -#}}} - - -## Formating connection id (do not change this) -CON_ID = {'host': HOST, 'port': PORT} - -## Some functions#{{{ - - -def mpdConnect(client, con_id):#{{{ - """ - Simple wrapper to connect MPD. - """ - try: - client.connect(**con_id) - except SocketError: - return False - return True#}}} - -def mpdAuth(client, secret):#{{{ - """ - Authenticate - """ - try: - client.password(secret) - except CommandError: - return False - return True#}}} +from lib.mpdutils import (mconnect) +#}}} def search(tags):#{{{ @@ -125,29 +99,10 @@ def search(tags):#{{{ for k, v in tags.iteritems(): search_str.extend([str(k), str(v)]) return search_str#}}} -###}}} def main(): - ## MPD object instance - client = MPDClient() - if mpdConnect(client, CON_ID): - #print 'Got connected!' - True - else: - print 'ERROR: fail to connect MPD server.' - sys.exit(1) - - ## Auth if password is set non False - if PASSWORD: - if mpdAuth(client, PASSWORD): - #print 'Pass auth!' - True - else: - print 'ERROR: fail trying to pass auth. Check password?' - client.disconnect() - sys.exit(1) - + client = mconnect() ## List tracks matching JINGLE_TAG and randomly chose one. try: trk = choice(client.search(*search(JINGLE_TAG))) @@ -155,21 +110,22 @@ def main(): print 'Wrong search command, check JINGLE_TAG settings: %s' % err sys.exit(1) except IndexError, err: - print 'Search for "%s" returned nothing: %s' % (' '.join(search(JINGLE_TAG)), - err) + print ('Search for "%s" returned nothing: %s' % + (' '.join(search(JINGLE_TAG)), err)) sys.exit(1) ## Uncomment to print out file added to playlist #print 'add "%s"' % trk.get('file') client.add(trk.get('file', None)) - client.disconnect() - sys.exit(0) # Script starts here if __name__ == "__main__": + if len(sys.argv) > 1: + print DOC + sys.exit(0) main() # VIM MODLINE diff --git a/lib/__init__.py b/lib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lib/mpdutils.py b/lib/mpdutils.py new file mode 100644 index 0000000..a64d239 --- /dev/null +++ b/lib/mpdutils.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2009 Efrim {{{ +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# }}} + +import sys + +from os import environ +from socket import error as SocketError + +try: + from mpd import (MPDClient, CommandError) +except ImportError, err: + print 'ERROR: "%s"\n\nPlease install python-mpd module.\n' % err + sys.exit(1) + + +def get_mpd_environ():#{{{ + """ + Retrieve MPD env. var. + """ + con_id = dict({'host': 'localhost', + 'port': int(6600)}) + passwd = None + mpd_host_env = environ.get('MPD_HOST') + if mpd_host_env: + # If password is set: + # mpd_host_env = ['pass', 'host'] because MPD_HOST=pass@host + mpd_host_env = mpd_host_env.split('@') + mpd_host_env.reverse() + con_id.update({'host': mpd_host_env[0]}) + if len(mpd_host_env) > 1: + print 'passwd set in MPD_HOST' + passwd = mpd_host_env[1] + + con_id.update({'port': int(environ.get('MPD_PORT', con_id.get('port')))}) + return (con_id, passwd)#}}} + + +def mpdConnect(client, con_id):#{{{ + """ + Simple wrapper to connect MPD. + """ + try: + client.connect(**con_id) + except SocketError: + return False + return True#}}} + + +def mpdAuth(client, secret):#{{{ + """ + Authenticate + """ + try: + client.password(secret) + except CommandError: + return False + return True#}}} + + +def mconnect(): + """""" + ## get connection id + con_id, passwd = get_mpd_environ() + ## MPD object instance + client = MPDClient() + if mpdConnect(client, con_id): + #print 'Got connected!' + True + else: + print 'ERROR: fail to connect MPD server.' + sys.exit(1) + + ## Auth if password is set non False + if passwd: + if mpdAuth(client, passwd): + #print 'Pass auth!' + True + else: + print 'ERROR: fail trying to pass auth. Check password?' + client.disconnect() + sys.exit(1) + return client + +# Script starts here +if __name__ == '__main__': + cli = mconnect() + cli.disconnect() + +# VIM MODLINE +# vim: ai ts=4 sw=4 sts=4 expandtab + -- 2.39.2