Procházet zdrojové kódy

MQTT auth and improvements implemented

master
Dirk Alders před 2 roky
rodič
revize
8a4e7f4f37
6 změnil soubory, kde provedl 110 přidání a 0 odebrání
  1. 5
    0
      .gitignore
  2. 3
    0
      .gitmodules
  3. 24
    0
      config_example/config.py
  4. 1
    0
      report
  5. 1
    0
      requirements.txt
  6. 76
    0
      spotify.py

+ 5
- 0
.gitignore Zobrazit soubor

@@ -1,3 +1,8 @@
1
+# ---> spotify
2
+#
3
+config.py
4
+*.err
5
+
1 6
 # ---> Python
2 7
 # Byte-compiled / optimized / DLL files
3 8
 __pycache__/

+ 3
- 0
.gitmodules Zobrazit soubor

@@ -0,0 +1,3 @@
1
+[submodule "report"]
2
+	path = report
3
+	url = https://git.mount-mockery.de/pylib/report.git

+ 24
- 0
config_example/config.py Zobrazit soubor

@@ -0,0 +1,24 @@
1
+#!/usr/bin/env python
2
+# -*- coding: UTF-8 -*-
3
+import os
4
+import report
5
+
6
+MQTT_USER = "user"
7
+MQTT_PASS = "pass"
8
+MQTT_SERVER = "localhost"
9
+MQTT_TOPIC = "hifi/spotify"
10
+
11
+DEVICE_NAME = "Multimedia"
12
+
13
+#
14
+# Logging
15
+#
16
+__BASEPATH__ = os.path.abspath(os.path.dirname(__file__))
17
+APP_NAME = "spotify"
18
+LOGTARGET = 'logfile'   # possible choices are: 'logfile' or 'stdout'
19
+LOGLVL = 'DEBUG'
20
+
21
+LOGHOST = 'cutelog'
22
+LOGPORT = 19996
23
+
24
+formatter = report.LONG_FMT

+ 1
- 0
report

@@ -0,0 +1 @@
1
+Subproject commit 21bac82e0c459ebf6d34783c9249526a657a6bbd

+ 1
- 0
requirements.txt Zobrazit soubor

@@ -0,0 +1 @@
1
+paho-mqtt

+ 76
- 0
spotify.py Zobrazit soubor

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

Načítá se…
Zrušit
Uložit