Created
June 28, 2012 10:05
-
-
Save Elwell/3010411 to your computer and use it in GitHub Desktop.
SomaFM -> MQTT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# script to parse out the metadata from soma fm and send to mqtt | |
xmlurl = 'http://api.somafm.com/channels.xml' | |
mqtt_broker = 'nowplaying.elwell.org.uk' | |
import mosquitto | |
import collections | |
import time | |
import signal | |
from lxml import etree | |
# Connect to broker | |
mqttc = mosquitto.Mosquitto('pubclient_PUBNAME') | |
mqttc.username_pw_set("USERNAME","PASSWORD") | |
mqttc.connect(mqtt_broker, 1883, 60, True) | |
metadata = collections.defaultdict(dict) | |
# Handle ctrl-c gracefully and unpublish | |
def handler(signum, frame): | |
print "Caught SIG, cleaning up" | |
for chan in metadata.keys(): | |
for key in metadata[chan].keys(): | |
print chan, key | |
mqttc.publish("somafm/%s/%s" % (chan,key), '', retain=True) | |
exit() | |
signal.signal(signal.SIGINT, handler) | |
while True: | |
tree = etree.parse(xmlurl) | |
interesting = ('title','description','image','twitter','listeners','dj') | |
for chan in tree.getiterator('channel'): | |
for thing in interesting: | |
for key in chan.iterchildren(tag=thing): | |
#print "somafm/%s/%s %s" % (chan.attrib['id'], key.tag, key.text) | |
try: | |
if metadata[chan.attrib['id']][key.tag] != key.text: | |
metadata[chan.attrib['id']][key.tag] = key.text | |
print "UPDATE somafm/%s/%s %s" % (chan.attrib['id'], key.tag, key.text) | |
# Since this is a dynamic value, remove retention | |
mqttc.publish("somafm/%s/%s" % (chan.attrib['id'], key.tag), '', retain=True) | |
mqttc.publish("somafm/%s/%s" % (chan.attrib['id'], key.tag), key.text, retain=False) | |
except KeyError: | |
metadata[chan.attrib['id']][key.tag] = key.text | |
print "ADDED somafm/%s/%s %s" % (chan.attrib['id'], key.tag, key.text) | |
mqttc.publish("somafm/%s/%s" % (chan.attrib['id'], key.tag), key.text, retain=True) | |
time.sleep(60) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment