Module mpd_state -> mqtt
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mpd_monitor.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import config
  2. import logging
  3. import paho.mqtt.client as paho
  4. import report
  5. import subprocess
  6. import time
  7. try:
  8. from config import APP_NAME as ROOT_LOGGER_NAME
  9. except ImportError:
  10. ROOT_LOGGER_NAME = 'root'
  11. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('librespot')
  12. class mpc(object):
  13. PLAYING_TXT = 'playing'
  14. def __init__(self, state_callback, title_callback):
  15. logger.info("Starting MPD monitor...")
  16. self.__state_callback__ = state_callback
  17. self.__title_callback__ = title_callback
  18. self.__state__ = None
  19. self.__title__ = None
  20. self.set_state(False)
  21. self.set_title("")
  22. def run(self):
  23. while True:
  24. output = subprocess.check_output(["mpc", "status"])
  25. out_txt = output.decode('UTF-8')
  26. self.set_state(self.PLAYING_TXT in out_txt)
  27. if self.__state__:
  28. self.set_title(out_txt.split("\n")[0])
  29. else:
  30. self.set_title("")
  31. time.sleep(.2)
  32. def set_state(self, target_state):
  33. if self.__state__ != target_state:
  34. self.__state__ = target_state
  35. logger.info('MPD state changed to %s', self.__state__)
  36. self.__state_callback__(self.__state__)
  37. def set_title(self, title):
  38. if self.__title__ != title:
  39. logger.info('MPD is playing "%s"', title)
  40. self.__title_callback__(title)
  41. self.__title__ = title
  42. def send_state_msg_mqtt(state):
  43. client= paho.Client("mpd")
  44. client.username_pw_set(config.MQTT_USER, config.MQTT_PASS)
  45. client.connect(config.MQTT_SERVER, 1883)
  46. topic = config.MQTT_TOPIC + "/state"
  47. logger.info("Sending MPD status information to mqtt %s = %s", topic, str(state))
  48. client.publish(topic, "true" if state else "false")
  49. def send_title_msg_mqtt(title):
  50. client= paho.Client("mpd")
  51. client.username_pw_set(config.MQTT_USER, config.MQTT_PASS)
  52. client.connect(config.MQTT_SERVER, 1883)
  53. topic = config.MQTT_TOPIC + "/title"
  54. logger.info("Sending MPD title information to mqtt %s = \"%s\"", topic, title)
  55. client.publish(topic, title)
  56. if __name__ == '__main__':
  57. report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  58. mpd = mpc(send_state_msg_mqtt, send_title_msg_mqtt)
  59. mpd.run()
  60. import paho.mqtt.client as paho