Skip to content

Instantly share code, notes, and snippets.

@YtvwlD
Last active August 18, 2017 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YtvwlD/41e65fa2afee1f71363e23ad14975954 to your computer and use it in GitHub Desktop.
Save YtvwlD/41e65fa2afee1f71363e23ad14975954 to your computer and use it in GitHub Desktop.
mpd2mqtt
# https://docs.docker.com/get-started/part2/#define-a-container-with-a-dockerfile
# Use an official Python runtime as a parent image
FROM python:3-alpine
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt
# Run app.py when the container launches
CMD ["./mpd2mqtt.py"]
#!/usr/bin/env python3
# DEBUG
import os
DEBUG = "DEBUG" in os.environ
print("Debugging: {} {}".format(DEBUG, "(You might want to set DEBUG.)" if not DEBUG else ""))
# connect to Sentry (pip3 install raven)
if not DEBUG:
if "SENTRY_DSN" in os.environ:
import raven
raven = raven.Client(os.environ["SENTRY_DSN"])
print("Connected to Sentry.")
else:
raven = None
print("Didn't connect to Sentry. You might want to set SENTRY_DSN.")
else:
raven = None
print("Didn't connect to Sentry because DEBUG is set.")
def handle_status(playing):
title = playing.get("title")
artist = playing.get("artist")
album = playing.get("album")
if not artist and not album and title:
if " - " in title:
artist = title.split(" - ")[0]
title = title.split(" - ")[1]
if DEBUG:
print("------------------------")
print("Currently playing: {}".format(playing))
print("Title: {}".format(title))
print("Artist: {}".format(artist))
print("Album: {}".format(album))
mqtt.publish("music/title", title)
mqtt.publish("music/artist", artist)
mqtt.publish("music/album", album)
mqtt.publish("music/source", "mpd")
def quit():
print("Exiting...")
mqtt.loop_stop(force=False)
mpd.close()
mpd.disconnect()
try:
# connect to mpd (apt install python3-mpd)
from mpd import MPDClient
mpd = MPDClient()
mpd.idletimeout = None
mpd.connect("mpd", 6600)
print("Connected to mpd: version {}".format(mpd.mpd_version))
# connect to mqtt (pip3 install paho-mqtt)
import paho.mqtt.client
mqtt = paho.mqtt.client.Client()
mqtt.connect("mqttserver")
mqtt.loop_start()
print("Connected to mqtt.")
# SIGTERM
import signal
signal.signal(signal.SIGTERM, quit)
try:
while True:
playing = mpd.currentsong()
handle_status(playing)
mpd.idle()
except KeyboardInterrupt:
quit()
except Exception as exc:
if raven:
raven.captureException()
raise
python-mpd2==0.5.5
paho-mqtt==1.3.0
raven==6.1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment