poller.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # -*- coding: utf-8 -*-
  2. #
  3. from mpd import MPDClient, MPDError, CommandError
  4. import sys
  5. import os
  6. class PollerError(Exception):
  7. """Fatal error in poller."""
  8. class MPDPoller(object):
  9. _host="/tmp/mpd/socket"
  10. #_host = "localhost"
  11. _port="6600"
  12. _client= None
  13. def __init__(self, host, port="6600"):
  14. self._host = host
  15. self._port = port
  16. self._client = MPDClient(use_unicode=True)
  17. self._client.timeout = 60*60*1000
  18. def connect(self):
  19. try:
  20. self._client.connect(self._host, self._port)
  21. # Catch socket errors
  22. except IOError as err:
  23. errno, strerror = err
  24. raise PollerError("Could not connect to '%s': %s" %
  25. (self._host, strerror))
  26. # Catch all other possible errors
  27. except MPDError as e:
  28. raise PollerError("Could not connect to '%s': %s" %
  29. (self._host, e))
  30. def disconnect(self):
  31. # Try to tell MPD to close the connection first
  32. try:
  33. self._client.close()
  34. # If that fails, ignore it and disconnect
  35. except (MPDError, IOError):
  36. pass
  37. try:
  38. self._client.disconnect()
  39. # Disconnecting failed, setup a new client object instead
  40. # This should never happen. If it does, something is seriously broken,
  41. # and the client object shouldn't be trusted to be re-used.
  42. except (MPDError, IOError):
  43. self._client = MPDClient(use_unicode=True)
  44. self._client.timeout = 60*60*1000
  45. def general(self,func,*args):
  46. ret = None
  47. try:
  48. ret = func( *args )
  49. except CommandError:
  50. return False
  51. except (MPDError, IOError):
  52. print("first error")
  53. self.disconnect()
  54. try:
  55. self.connect()
  56. except PollerError as e:
  57. raise PollerError("Reconnecting failed: %s" % e)
  58. try:
  59. ret = func(*args)
  60. except (MPDError, IOError) as e:
  61. raise PollerError("Couldn't retrieve current song: %s" % e)
  62. return ret
  63. def ping(self):
  64. return self.general(self._client.ping)
  65. def poll(self):
  66. song = self.general( self._client.status )
  67. """
  68. while playing:
  69. {u'songid': u'4', u'playlistlength': u'4', u'playlist': u'7', u'repeat': u'0', u'consume': u'0', u'mixrampdb': u'0.000000', u'random': u'0', u'state': u'play', u'elapsed': u'148.758', u'volume': u'100', u'single': u'0', u'time': u'149:436', u'duration': u'435.670', u'song': u'3', u'audio': u'44100:24:2', u'bitrate': u'192'}
  70. """
  71. # print(song)
  72. return song
  73. def stop(self):
  74. self.general(self._client.stop)
  75. def addfile(self,url):
  76. self.general(self._client.add, url)
  77. def delete(self,posid):
  78. self.general(self._client.delete,posid)
  79. def play(self,posid):
  80. song = self.poll()
  81. if "song" in song:
  82. if int(song["song"]) != posid:
  83. self.general(self._client.play,posid)
  84. else:
  85. if "state" in song:
  86. if song["state"] == "play":
  87. self.general(self._client.pause)
  88. elif song["state"] == "pause":
  89. self.general(self._client.pause)
  90. elif song["state"] == "stop":
  91. self.general(self._client.play,posid)
  92. else:
  93. self.general(self._client.play,posid)
  94. self.general(self._client.setvol,100)
  95. return posid
  96. def playlist(self):
  97. lst = self.general(self._client.playlistinfo)
  98. return lst
  99. for i in lst:
  100. if "title" in i:
  101. print( i["title"] )
  102. elif "file" in i:
  103. print( os.path.basename( i["file"] ) )
  104. def listfiles(self,path):
  105. files = self.general(self._client.lsinfo,path)
  106. return files
  107. for i in sorted(files):
  108. if "directory" in i:
  109. print( "D %s" % i["directory"] )
  110. elif "file" in i:
  111. print(i["file"])
  112. def rootfiles(self):
  113. files = self.general(self._client.lsinfo, "/")
  114. return files
  115. for i in sorted(files):
  116. if "directory" in i:
  117. print( "D %s" % i["directory"] )
  118. elif "file" in i:
  119. print(i["file"])
  120. def main():
  121. from time import sleep
  122. poller = MPDPoller()
  123. poller.connect()
  124. while True:
  125. print("poll:")
  126. print( poller.poll() )
  127. """
  128. print("playlist:")
  129. print(poller.playlist())
  130. print("rootfiles:")
  131. poller.rootfiles()
  132. """
  133. sleep(120)
  134. if __name__ == "__main__":
  135. import sys
  136. try:
  137. main()
  138. except PollerError as e:
  139. print("Fatal poller error: %s" % e)
  140. sys.exit(1)
  141. except Exception as e:
  142. print("Unexpected exception: %s" % e)
  143. sys.exit(1)
  144. except:
  145. sys.exit(0)