Преглед изворни кода

Title playing identification added

master
Dirk Alders пре 2 година
родитељ
комит
d8096b0f31
3 измењених фајлова са 57 додато и 7 уклоњено
  1. 2
    2
      config_example/config.py
  2. 2
    0
      requirements.txt
  3. 53
    5
      spotify.py

+ 2
- 2
config_example/config.py Прегледај датотеку

@@ -15,10 +15,10 @@ DEVICE_NAME = "Multimedia"
15 15
 #
16 16
 __BASEPATH__ = os.path.abspath(os.path.dirname(__file__))
17 17
 APP_NAME = "spotify"
18
-LOGTARGET = 'logfile'   # possible choices are: 'logfile' or 'stdout'
18
+LOGTARGET = 'stdout'   # possible choices are: 'logfile' or 'stdout'
19 19
 LOGLVL = 'DEBUG'
20 20
 
21 21
 LOGHOST = 'cutelog'
22 22
 LOGPORT = 19996
23 23
 
24
-formatter = report.LONG_FMT
24
+formatter = report.SHORT_FMT

+ 2
- 0
requirements.txt Прегледај датотеку

@@ -1 +1,3 @@
1 1
 paho-mqtt
2
+spotipy
3
+

+ 53
- 5
spotify.py Прегледај датотеку

@@ -4,6 +4,10 @@ import paho.mqtt.client as paho
4 4
 import report
5 5
 import subprocess
6 6
 import time
7
+import spotipy
8
+from spotipy.oauth2 import SpotifyClientCredentials
9
+import config
10
+import json
7 11
 
8 12
 
9 13
 try:
@@ -17,15 +21,19 @@ class librespot(object):
17 21
     ON_CMD = ['play', ]
18 22
     OFF_CMD = ['pause', 'stop', ]
19 23
 
20
-    def __init__(self, state_callback):
24
+    def __init__(self, state_callback, title_callback):
21 25
         logger.info("Starting Librespot...")
22 26
         self.__state_callback__ = state_callback
27
+        self.__title_callback__ = title_callback
23 28
         self.__process__ = subprocess.Popen(["librespot", "-v", "--name", config.DEVICE_NAME],
24 29
                                shell=False,
25 30
                                # We pipe the output to an internal pipe
26 31
                                stderr=subprocess.PIPE)
27 32
         self.__state__ = None
33
+        self.__title__ = None
34
+        self.__spot_id__ = None
28 35
         self.set_state(False)
36
+        self.set_title("")
29 37
 
30 38
     def run(self):
31 39
         while True:
@@ -42,6 +50,14 @@ class librespot(object):
42 50
                 out_txt = output.decode('utf-8').strip('\n').strip()
43 51
                 out_txt = out_txt[out_txt.find(']') + 2:]
44 52
                 logger.debug("librespot output: %s", out_txt)
53
+                # TODO: Parse for "librespot output: Loading <Here Ever After> with Spotify URI <spotify:track:0zckHMfaB6vT5o23ZVBLHJ>"
54
+                if out_txt.lower().startswith("loading"):
55
+                    self.__spot_id__ = out_txt.split("<")[2][:-1]
56
+                    logger.info("Track-ID %s identified", self.__spot_id__)
57
+                    if self.__state__:
58
+                        self.set_title(self.get_title_by_id())
59
+                    else:
60
+                        self.set_title("")
45 61
                 if "command=" in out_txt:
46 62
                     command = out_txt[out_txt.find('command=') + 8:].strip().lower()
47 63
                     logger.debug("librespot command: %s", command)
@@ -52,6 +68,21 @@ class librespot(object):
52 68
                         self.set_state(True)
53 69
                     if command in self.OFF_CMD:
54 70
                         self.set_state(False)
71
+                    if self.__state__:
72
+                        self.set_title(self.get_title_by_id())
73
+                    else:
74
+                        self.set_title("")
75
+
76
+    def get_title_by_id(self):
77
+        if self.__spot_id__ is None:
78
+            return ""
79
+        else:
80
+            sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=config.SPOTIFY_CLIENT_ID,client_secret=config.SPOTIFY_CLIENT_SECRET))
81
+            try:
82
+                track = sp.track(self.__spot_id__)
83
+            except Exception:
84
+                return None
85
+            return track["artists"][0]["name"] + " - " + track["name"]
55 86
 
56 87
     def set_state(self, target_state):
57 88
         if target_state != self.__state__:
@@ -59,18 +90,35 @@ class librespot(object):
59 90
             logger.info("spotify state changed to %s", self.__state__)
60 91
             self.__state_callback__(self.__state__)
61 92
 
93
+    def set_title(self, title):
94
+        if title != self.__title__:
95
+            self.__title__ = title
96
+            logger.info("spotify title changed to \"%s\"", self.__title__)
97
+            self.__title_callback__(self.__title__)
98
+            
99
+
100
+def send_state_msg_mqtt(state):
101
+    client= paho.Client("spotify")
102
+    client.username_pw_set(config.MQTT_USER, config.MQTT_PASS)
103
+    client.connect(config.MQTT_SERVER, 1883)
104
+    topic = config.MQTT_TOPIC + "/state"
105
+    logger.info("Sending Spotify status information to mqtt %s = %s", topic, str(state))
106
+    client.publish(topic, "true" if state else "false")
62 107
 
63
-def send_msg_mqtt(state):
108
+def send_title_msg_mqtt(title):
64 109
     client= paho.Client("spotify")
65 110
     client.username_pw_set(config.MQTT_USER, config.MQTT_PASS)
66 111
     client.connect(config.MQTT_SERVER, 1883)
67
-    logger.info("Sending Spotify status information to mqtt %s = %s", config.MQTT_TOPIC, str(state))
68
-    client.publish(config.MQTT_TOPIC, "true" if state else "false")
112
+    topic = config.MQTT_TOPIC + "/title"
113
+    logger.info("Sending Spotify status information to mqtt %s = %s", topic, title)
114
+    client.publish(topic, title)
69 115
 
70 116
 
71 117
 
72 118
 if __name__ == '__main__': 
73 119
     report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
74 120
     
75
-    ls = librespot(send_msg_mqtt)
121
+    ls = librespot(send_state_msg_mqtt, send_title_msg_mqtt)
76 122
     ls.run()
123
+
124
+

Loading…
Откажи
Сачувај