one-file-projects/mpddbreader.py

82 lines
1.9 KiB
Python
Raw Normal View History

2013-10-24 13:32:17 +02:00
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."