From 5ba42fb745f89d82ee62466ea141aa3056e165aa Mon Sep 17 00:00:00 2001 From: trollhase Date: Thu, 24 Oct 2013 13:32:17 +0200 Subject: [PATCH] MPD Database Reader + Connection --- mpddbreader.py | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 mpddbreader.py diff --git a/mpddbreader.py b/mpddbreader.py new file mode 100644 index 0000000..c0c56ca --- /dev/null +++ b/mpddbreader.py @@ -0,0 +1,81 @@ +import socket + +class LineReader(object): + def __init__(self, source): + self.source = source + self.buffer = "" + + def read(self,bufsize=1024): + while not "\n" in self.buffer: + data = self.source.recv(bufsize) + if len(data) == 0: + return None + self.buffer += data + + pos = self.buffer.pos("\n") + line, self.buffer = self.buffer[:pos], self.buffer[pos+1:] + return line + + def clear(self): + self.buffer = "" + +class HashListCommandReader(object): + def run(self, linereader, endline="OK", errorline="ACK"): + data = {} + line = linereader.read() + while line is not None and line != endline and line != errorline: + if not ":" in line: + continue + arr = line.split(":",1) + key, value = arr[0].strip().lower(), arr[1].strip() + if key in data: + yield data + data = {} + data[key] = value + line = linereader.read() + +class MPDConnection(object): + def __init__(self, host=None): + self.socket = None + self.linereader = None + if host is not None: + self.connect(host) + + def connect(self,host): + if self.socket is not None: + return + self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) + self.socket.connect(host) + + self.linereader = LineReader(self.socket) + + #Initialize connection + line = self.linereader.read() + + if line[:7] != "OK MPD ": + self.close() + raise Exception("Not an mpd server") + + def close(self): + try: + self.socket.close() + finally: + self.socket = None + self.linereader = None + + def run(self,command,reader): + self.socket.send(str(command)+"\n") + self.linereader.clear() + return reader.run(self.linereader) + +if __name__ == '__main__': + try: + c = MPDConnection(('10.0.0.1',6600)) + for song in c.run("listallinfo",HashListCommandReader()): + artist = song['artist'] if 'artist' in song else "Unknown" + title = song['title'] if 'title' in song else "Unknown" + print "%s - %s" % (artist,song) + finally: + c.close() + print "Terminated." +