andypiper
5/9/2013 - 5:16 PM

Read BBC Radio livetext from MQTT and display on LCDsysinfo (http://coldtearselectronics.wikispaces.com/USB+LCD+-+LCD+System+info)

Read BBC Radio livetext from MQTT and display on LCDsysinfo (http://coldtearselectronics.wikispaces.com/USB+LCD+-+LCD+System+info)

#!/usr/bin/python

from pylcdsysinfo import BackgroundColours, TextColours, TextAlignment, TextLines, LCDSysInfo
import mosquitto
import textwrap
import sys
from time import sleep

def on_message(mosq, obj, msg):
    lines = textwrap.wrap(msg.payload, width=20)
    for n, s in enumerate(lines):
        d.display_text_on_line(int(n)+2, s, False, TextAlignment.CENTRE, TextColours.CYAN)

def on_connect(mosq, obj, msg):
    d.display_text_on_line(6, "Connected", False, TextAlignment.CENTRE, TextColours.GREEN)

def on_disconnect():
    d.display_text_on_line(6, "Disconnected", False, TextAlignment.CENTRE, TextColours.RED)

d = LCDSysInfo()
d.clear_lines(TextLines.ALL, BackgroundColours.BLACK)

mqttc = mosquitto.Mosquitto()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect

mqttc.connect("test.mosquitto.org", 1883, 60)
mqttc.subscribe("bbc/livetext/radio2", 0)

rc = 0
while rc == 0:
  try:
    rc = mqttc.loop()
  except KeyboardInterrupt:
    mqttc.unsubscribe("bbc/livetext/radio2")
    mqttc.disconnect()
    on_disconnect()
    print "Bye!"
    sleep(1)
    d.clear_lines(TextLines.ALL, BackgroundColours.BLACK)
    sys.exit()