1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- import config
- import logging
- import mqtt
- import report
- import socket
- import subprocess
- import time
-
-
- try:
- from config import APP_NAME as ROOT_LOGGER_NAME
- except ImportError:
- ROOT_LOGGER_NAME = 'root'
- logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('librespot')
-
-
- mc = mqtt.mqtt_client(config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS)
-
- class mpc(object):
- PLAYING_TXT = 'playing'
-
- def __init__(self, state_callback, title_callback):
- logger.info("Starting MPD monitor...")
- self.__state_callback__ = state_callback
- self.__title_callback__ = title_callback
- self.__state__ = None
- self.__title__ = None
- self.set_state(False)
- self.set_title("")
-
- def run(self):
- while True:
- output = subprocess.check_output(["mpc", "status"])
- out_txt = output.decode('UTF-8')
- self.set_state(self.PLAYING_TXT in out_txt)
- if self.__state__:
- self.set_title(out_txt.split("\n")[0])
- else:
- self.set_title("")
- time.sleep(.2)
-
- def set_state(self, target_state):
- if self.__state__ != target_state:
- self.__state__ = target_state
- logger.info('MPD state changed to %s', self.__state__)
- self.__state_callback__(self.__state__)
-
- def set_title(self, title):
- if self.__title__ != title:
- logger.info('MPD is playing "%s"', title)
- self.__title_callback__(title)
- self.__title__ = title
-
-
- def send_state_msg_mqtt(state):
- topic = config.MQTT_TOPIC + "/state"
- logger.info("Sending MPD status information to mqtt %s = %s", topic, str(state))
- mc.send(topic, "true" if state else "false")
-
-
- def send_title_msg_mqtt(title):
- topic = config.MQTT_TOPIC + "/title"
- logger.info("Sending MPD title information to mqtt %s = \"%s\"", topic, title)
- mc.send(topic, title)
-
-
- if __name__ == '__main__':
- report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
-
- mpd = mpc(send_state_msg_mqtt, send_title_msg_mqtt)
- mpd.run()
|