123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- import config
- import logging
- import mqtt
- import report
- import socket
- import subprocess
- import time
- import spotipy
- from spotipy.oauth2 import SpotifyClientCredentials
- import config
- import json
-
-
- try:
- from config import APP_NAME as ROOT_LOGGER_NAME
- except ImportError:
- ROOT_LOGGER_NAME = 'root'
- logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
-
-
- mc = mqtt.mqtt_client(config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS)
-
- class librespot(object):
- ON_CMD = ['play', ]
- OFF_CMD = ['pause', 'stop', ]
-
- def __init__(self, state_callback, title_callback):
- logger.info("Starting Librespot...")
- self.__state_callback__ = state_callback
- self.__title_callback__ = title_callback
- self.__start_process__()
- self.__state__ = None
- self.__preload_state__ = False
- self.__title__ = None
- self.__title_preload__ = None
- self.__title_published__ = None
- self.set_state(False)
- self.set_title("")
-
- def __start_process__(self):
- self.__process__ = subprocess.Popen(["librespot", "-v", "--name", config.DEVICE_NAME],
- shell=False,
- # We pipe the output to an internal pipe
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
-
- def run(self):
- while True:
- output = self.__process__.stdout.readline()
- # Polling returns None when the program is still running, return_code otherwise
- return_code = self.__process__.poll()
- if return_code is not None:
- #self.__process__.close()
- # Program ended, get exit/return code
- #raise RuntimeError
- logger.exception(("Command '{}' finished with exit code {}".format(command, return_code)))
- # If the output is not empty, feed it to the function, strip the newline first
- self.__start_process__()
- output = None
- elif output:
- out_txt = output.decode('utf-8').strip('\n').strip()
- out_txt = out_txt[out_txt.find(']') + 2:]
- #logger.debug("librespot output: %s", out_txt)
- if out_txt.lower().startswith("loading"):
- logger.debug("librespot: %s", out_txt)
- title = out_txt[out_txt.index("<") + 1:out_txt.index(">")]
- if self.__preload_state__:
- self.__title_preload__ = title
- logger.info("Upcomming Title %s identified", title)
- else:
- self.__title__ = title
- logger.info("Current Title %s identified", title)
- if "command=" in out_txt:
- command = out_txt[out_txt.find('command=') + 8:].strip().lower()
- logger.debug("librespot command: %s", command)
- if command.startswith("preload"):
- self.__preload_state__ = True
- if command.startswith("load"):
- self.set_state(command.split(',')[2].strip() == 'true')
- #
- self.__preload_state__ = False
- if self.__title_preload__ is not None:
- self.__title__ = self.__title_preload__
- self.__title_preload__ = None
- #
- elif command in self.ON_CMD:
- self.set_state(True)
- elif command in self.OFF_CMD:
- self.set_state(False)
- if self.__state__:
- self.set_title(self.__title__)
- else:
- self.set_title("")
-
- def set_state(self, target_state):
- if target_state != self.__state__:
- self.__state__ = target_state
- logger.info("spotify state changed to %s", self.__state__)
- self.__state_callback__(self.__state__)
-
- def set_title(self, title):
- if self.__title_published__ != title:
- self.__title_published__= title
- logger.info("spotify title changed to \"%s\"", title)
- self.__title_callback__(title)
-
-
- def send_state_msg_mqtt(state):
- topic = config.MQTT_TOPIC + "/state"
- logger.info("Sending Spotify 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 Spotify status 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)
-
- ls = librespot(send_state_msg_mqtt, send_title_msg_mqtt)
- ls.run()
-
|