Module mpd_state -> mqtt
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

smart_mpd.py 2.2KB

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