mpc.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import print_function
  2. from gevent import monkey
  3. monkey.patch_all(subprocess=True)
  4. import logging
  5. logging.basicConfig(level=logging.INFO,
  6. format='%(asctime)s %(message)s',
  7. datefmt='%H:%M:%S')
  8. from subprocess import check_output
  9. import gevent
  10. from gevent.queue import Queue
  11. from gevent.wsgi import WSGIServer
  12. from eventutils import ParentedLet, CeleryTask, Timer
  13. from task import create as create_continous
  14. import rpc
  15. class MpcWatcher(ParentedLet):
  16. def __init__(self, queue):
  17. ParentedLet.__init__(self, queue)
  18. def do_business(self):
  19. while True:
  20. status = check_output(['mpc', 'idle']).decode('utf-8').strip()
  21. yield ('mpc', status)
  22. class Player(gevent.Greenlet):
  23. def __init__(self):
  24. gevent.Greenlet.__init__(self)
  25. self.min_playlist_length = 10
  26. self.q = Queue()
  27. def check_playlist(self):
  28. out = check_output(['mpc', 'playlist']).decode('utf-8').strip()
  29. songs = out.split('\n')
  30. if(len(songs) >= self.min_playlist_length):
  31. return
  32. logging.info('need to add new songs')
  33. CeleryTask(create_continous, self.q).start()
  34. CeleryTask(create_continous, self.q).start()
  35. def _run(self):
  36. MpcWatcher(self.q).start()
  37. Timer(6000, self.q).start()
  38. http_server = WSGIServer(('', 5000), rpc.create_app(self.q))
  39. http_server.start()
  40. while True:
  41. value = self.q.get()
  42. # emitter = value['emitter']
  43. kind = value['kind']
  44. args = value['args']
  45. if kind == 'timer':
  46. logging.info('CLOCK')
  47. if kind == 'timer' or (kind == 'mpc' and args[0] == 'playlist'):
  48. gevent.Greenlet.spawn(self.check_playlist)
  49. elif kind == 'celery':
  50. logging.info("celery: %s" % str(args))
  51. else:
  52. logging.warning("Unknown message: %s" % str(value))
  53. logging.info(str(value))
  54. if __name__ == '__main__':
  55. p = Player()
  56. p.start()
  57. gevent.wait()