Created
March 8, 2012 12:59
-
-
Save xintron/2000892 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
# -*- coding: utf-8 -*- | |
import logging | |
from mpd import MPDClient, CommandError | |
from tornado.httpserver import HTTPServer | |
from tornado.ioloop import IOLoop | |
from tornado.web import Application | |
from tornado.websocket import WebSocketHandler | |
class MPDHandler(WebSocketHandler): | |
def open(self): | |
self._cmd = { | |
'password': lambda x: self.mpd.password(x), | |
'stats' : lambda: self.mpd.stats(), | |
'status': lambda: self.mpd.status(), | |
'play': lambda x=None: self.mpd.play(x) if x else self.mpd.play(), | |
'pause': lambda x=None: self.mpd.pause(x) if x else self.mpd.pause(), | |
'stop': lambda: self.mpd.stop(), | |
'playlistinfo': lambda x=None: self.mpd.playlistinfo(x) if x else self.mpd.playlistinfo() | |
} | |
logging.info('New connection from: {}'.format(self.request.remote_ip)) | |
logging.debug('Connection websocket-key: {}'.format(self.request.headers['Sec-Websocket-Key'])) | |
self.mpd = MPDClient() | |
self.mpd.connect('localhost', 6600) | |
def on_message(self, msg): | |
logging.info('New message: {}; from: {}'.format(msg, self.request.remote_ip)) | |
msg.strip() | |
if ' ' in msg: | |
cmd, args = msg.split(' ') | |
else: | |
cmd = msg | |
args = None | |
if cmd in self._cmd: | |
try: | |
logging.info('Sending MPD-command: {}, args: {}'.format(cmd, args)) | |
if args: | |
resp = self._cmd[cmd](args) | |
else: | |
resp = self._cmd[cmd]() | |
logging.debug('Command response: {}'.format(resp)) | |
if not resp: | |
self.write_message('OK') | |
else: | |
self.write_message(resp) | |
except CommandError: | |
self.write_message('Error') | |
else: | |
self.write_message('Command not found') | |
def on_close(self): | |
logging.info('Connection closed') | |
self.mpd.disconnect() | |
def getmpd(self): | |
return self.mpd | |
if __name__ == '__main__': | |
logging.getLogger().setLevel(logging.DEBUG) | |
logging.info('Starting application') | |
application = Application([(r'/', MPDHandler)]) | |
http_server = HTTPServer(application) | |
http_server.listen(8080) | |
IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment