Module spotify_state -> mqtt
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

spotify.py 2.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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('main')
  12. class librespot(object):
  13. ON_CMD = ['play', ]
  14. OFF_CMD = ['pause', 'stop', ]
  15. def __init__(self, state_callback):
  16. logger.info("Starting Librespot...")
  17. self.__state_callback__ = state_callback
  18. self.__process__ = subprocess.Popen(["librespot", "-v", "--name", config.DEVICE_NAME],
  19. shell=False,
  20. # We pipe the output to an internal pipe
  21. stderr=subprocess.PIPE)
  22. self.__state__ = None
  23. self.set_state(False)
  24. def run(self):
  25. while True:
  26. output = self.__process__.stderr.readline()
  27. # Polling returns None when the program is still running, return_code otherwise
  28. return_code = self.__process__.poll()
  29. if return_code is not None:
  30. self.__process__.close()
  31. # Program ended, get exit/return code
  32. raise RuntimeError("Command '{}' finished with exit code {}".format(command, return_code))
  33. # If the output is not empty, feed it to the function, strip the newline first
  34. if output:
  35. out_txt = output.decode('utf-8').strip('\n').strip()
  36. out_txt = out_txt[out_txt.find(']') + 2:]
  37. logger.debug("librespot output: %s", out_txt)
  38. if "command=" in out_txt:
  39. command = out_txt[out_txt.find('command=') + 8:].strip().lower()
  40. logger.debug("librespot command: %s", command)
  41. if command.startswith("load"):
  42. self.set_state(command.split(',')[2].strip() == 'true')
  43. #
  44. if command in self.ON_CMD:
  45. self.set_state(True)
  46. if command in self.OFF_CMD:
  47. self.set_state(False)
  48. def set_state(self, target_state):
  49. if target_state != self.__state__:
  50. self.__state__ = target_state
  51. logger.info("spotify state changed to %s", self.__state__)
  52. self.__state_callback__(self.__state__)
  53. def send_msg_mqtt(state):
  54. client= paho.Client("spotify")
  55. client.username_pw_set(config.MQTT_USER, config.MQTT_PASS)
  56. client.connect(config.MQTT_SERVER, 1883)
  57. logger.info("Sending Spotify status information to mqtt %s = %s", config.MQTT_TOPIC, str(state))
  58. client.publish(config.MQTT_TOPIC, "true" if state else "false")
  59. if __name__ == '__main__':
  60. report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  61. ls = librespot(send_msg_mqtt)
  62. ls.run()