# -*- 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.
#
# '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
--- /dev/null
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2009 Efrim <efrim@azylum.org> {{{
+#
+# 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 <http://www.gnu.org/licenses/>.
+#
+# }}}
+
+"""
+DOC:
+ heavily borrowed from perl script mpdtoys and converted to python.
+ mpdtoys © 2007 Joey Hess <joey@kitenet.net>
+ 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
#\r
# }}}\r
\r
-"""\r
+DOC = """\r
DOC:\r
\r
The script randomly pick up a song to queue from the library.\r
MPD bugs: http://musicpd.org/mantis/view.php?id=498\r
"""\r
\r
-__version__ = u'0.2'\r
+__version__ = u'0.3'\r
__author__ = u'$Author: kaliko $'\r
__date__ = u'$LastChangedDate: 2009-11-17 19:23:34 +0100 (mar. 17 nov. 2009) $'[18:28]\r
\r
import sys\r
\r
from random import choice\r
-from socket import error as SocketError\r
try:\r
- from mpd import (MPDClient, CommandError)\r
+ from mpd import (CommandError)\r
except ImportError, err:\r
print 'ERROR: "%s"\n\nPlease install python-mpd module.\n' % err\r
sys.exit(1)\r
\r
try:\r
- from config import (HOST, PORT, PASSWORD, JINGLE_TAG)\r
+ from config import JINGLE_TAG\r
except ImportError, err:\r
- print 'ERROR: missing settings in config.py: %s' % err\r
+ print 'ERROR: "%s"\n' % err\r
+ print '\tPlease set JINGLE_TAG in config.py'\r
sys.exit(1)\r
-#}}}\r
-\r
-\r
-## Formating connection id (do not change this)\r
-CON_ID = {'host': HOST, 'port': PORT}\r
-\r
-## Some functions#{{{\r
-\r
-\r
-def mpdConnect(client, con_id):#{{{\r
- """\r
- Simple wrapper to connect MPD.\r
- """\r
- try:\r
- client.connect(**con_id)\r
- except SocketError:\r
- return False\r
- return True#}}}\r
\r
-\r
-def mpdAuth(client, secret):#{{{\r
- """\r
- Authenticate\r
- """\r
- try:\r
- client.password(secret)\r
- except CommandError:\r
- return False\r
- return True#}}}\r
+from lib.mpdutils import (mconnect)\r
+#}}}\r
\r
\r
def search(tags):#{{{\r
for k, v in tags.iteritems():\r
search_str.extend([str(k), str(v)])\r
return search_str#}}}\r
-###}}}\r
\r
\r
def main():\r
- ## MPD object instance\r
- client = MPDClient()\r
- if mpdConnect(client, CON_ID):\r
- #print 'Got connected!'\r
- True\r
- else:\r
- print 'ERROR: fail to connect MPD server.'\r
- sys.exit(1)\r
-\r
- ## Auth if password is set non False\r
- if PASSWORD:\r
- if mpdAuth(client, PASSWORD):\r
- #print 'Pass auth!'\r
- True\r
- else:\r
- print 'ERROR: fail trying to pass auth. Check password?'\r
- client.disconnect()\r
- sys.exit(1)\r
-\r
+ client = mconnect()\r
## List tracks matching JINGLE_TAG and randomly chose one.\r
try:\r
trk = choice(client.search(*search(JINGLE_TAG)))\r
print 'Wrong search command, check JINGLE_TAG settings: %s' % err\r
sys.exit(1)\r
except IndexError, err:\r
- print 'Search for "%s" returned nothing: %s' % (' '.join(search(JINGLE_TAG)),\r
- err)\r
+ print ('Search for "%s" returned nothing: %s' %\r
+ (' '.join(search(JINGLE_TAG)), err))\r
sys.exit(1)\r
\r
## Uncomment to print out file added to playlist\r
#print 'add "%s"' % trk.get('file')\r
\r
client.add(trk.get('file', None))\r
-\r
client.disconnect()\r
-\r
sys.exit(0)\r
\r
# Script starts here\r
if __name__ == "__main__":\r
+ if len(sys.argv) > 1:\r
+ print DOC\r
+ sys.exit(0)\r
main()\r
\r
# VIM MODLINE\r
--- /dev/null
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2009 Efrim <efrim@azylum.org> {{{
+#
+# 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 <http://www.gnu.org/licenses/>.
+#
+# }}}
+
+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
+