Video icon 64
Learn to code with practical video courses from Tuts+. Start your free trial today.
Advertisement

How to Add a Web UI to the RGB LCD Tweet Box

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →
Final product image
What You'll Be Creating

This tutorial extends the previous tutorial, How to build a Tweet controlled RGB LCD, by adding web page control. With this you can change the configuration of the Tweetbox on the fly from your laptop, tablet or phone. 

You'll learn useful techniques in this tutorial so that you can add web page control to your own Raspberry Pi projects. 

Setup

  1. First complete the previous tutorial How to build a Tweet controlled RGB LCD
  2. Install Tornado:

sudo pip install tornado

All the code for this project is available here:

https://github.com/jerbly/tutorials/tree/master/tweetbox

Stage 1: Basic Form

To recap, by the end of the previous tutorial you had a Raspberry Pi with RGB LCD connected to Twitter receiving public tweets matching a filter. The RGB backlight would change colour depending on other matching words in the tweet. To configure the filter and colour map you had to change the code and restart the program.

In this first stage I'll add a web server to the program. Then you can go to a web page and update the configuration live. I'll be using Tornado, there are lots of different web frameworks for Python and I've used many of them over the years but this is now my go-to framework. It ticks a lot of boxes for a lot of different projects.

Take a look at the Hello world example on the Tornado page so you can see how to set up a handler and start a tornado server thread. I'll be using this exact same principle here.

I'll take the tweetbox.py code from the previous tutorial and add the web framework in. To start with I'll just have a simple form allowing us to change what I'm tracking on Twitter. First, add some imports to the top of the script:

import tornado.ioloop
import tornado.web

Next I need two handlers: one to show the HTML form and a second to receive the form submission:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("templates/form1.html")

class ConfigHandler(tornado.web.RequestHandler):
    def post(self):
        config_track = self.get_argument("config_track")
        restart(config_track)
        self.write("Now tracking %s" % config_track)

application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/config", ConfigHandler),
])

Note that MainHandler uses get and ConfigHandler uses post, the HTML form uses the post method to submit the form data back to the web server. To serve the form the MainHandler simply calls the render function to have a template rendered and sent to the browser. More about this in a moment.

When the form data comes back ConfigHandler extracts one argument, config_track. This is sent to a restart function to change the settings with tweepy before returning a simple string showing what is being tracked.

Create the template by adding a directory called templates to the source directory and create the form1.html file there:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Raspberry Pi Tweetbox</title>
  </head>

  <body>
    <form id="config_form" action="config" method="post">
      <input id="config_track" name="config_track" type="text">
      <button type="submit">Submit</button>
    </form>
  </body>
</html>

This is a very simple form with a text input box and a submit button. It’s all that’s needed at this stage. Next create the restart function:

def restart(track_text):
    stream.disconnect()
    time.sleep(5) #Allow time for the thread to disconnect...
    stream.filter(track=[track_text], async=True)

This disconnects the Twitter stream and then reconnects it with the new filter, track_text, which is whatever was submitted from the form. An important change here, from the previous tutorial, is that the Twitter stream thread runs in asynchronous mode, async=True. This runs the stream connection in a background thread so that the web server runs as the main thread.

Add a couple of lines to the end to start the stream in asynchronous mode and to then start the web server:

stream.filter(track=['jeremy'], async=True)
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

This starts the web server listening on port 8888. Point a web browser at http://{your-raspi-ipaddress}:8888/ and you will see the form:

Tweetbox webpage form
Tweetbox webpage form

Enter something else to track like raspberry and click submit. After five seconds it will switch to tracking these tweets instead.

Stage 2: Colour Map and Saving Configuration

In this stage I'll add the colour map to the configuration so you can set the words that trigger the RGB backlight to change. Since there are seven settings I don't really want to re-enter these every time I run the application so I'll save these to a file.

The program uses pickle to save and load the configuration file, plus there's an initial file exists check so add these imports to the top:

import pickle
from genericpath import exists

The DisplayLoop class is already responsible for managing the backlight_map so I'll extend this so it takes care of what I'm currently tracking, track_text. Read and Write config methods are also added here:

class DisplayLoop(StreamListener):
    PICKLE_FILE = '/home/pi/py/tweetbox.pkl'
    
    def __init__(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.backlight(self.lcd.RED)
        self.lcd.clear()
        self.track_text = 'jeremy'
        self.backlight_map = {'red':self.lcd.RED,
                              'green':self.lcd.GREEN,
                              'blue':self.lcd.BLUE,
                              'yellow':self.lcd.YELLOW,
                              'teal':self.lcd.TEAL,
                              'violet':self.lcd.VIOLET}
        self.msglist = []
        self.pos = 0
        self.tweet = 'Nothing yet'

    def write_config(self):
        data = {"track_text":self.track_text,
                "backlight_map":self.backlight_map}
        output = open(self.PICKLE_FILE, 'wb')
        pickle.dump(data, output)
        output.close()
        
    def read_config(self):
        if exists(self.PICKLE_FILE):
            pkl_file = open(self.PICKLE_FILE, 'rb')
            data = pickle.load(pkl_file)
            pkl_file.close()
            self.track_text = data["track_text"]
            self.backlight_map = data["backlight_map"]
        

Change the request handlers to take care of the colours. Also below you'll see that when I render the main page I'm passing in the current configuration. This means I can fill the configuration form with the current settings when it's requested.

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        inverted_map = {v:k for k, v in display_loop_instance.backlight_map.items()}
        self.render("templates/form3.html", 
                    config_track=display_loop_instance.track_text,
                    config_red=inverted_map[Adafruit_CharLCDPlate.RED], 
                    config_green=inverted_map[Adafruit_CharLCDPlate.GREEN],
                    config_blue=inverted_map[Adafruit_CharLCDPlate.BLUE],
                    config_yellow=inverted_map[Adafruit_CharLCDPlate.YELLOW],
                    config_teal=inverted_map[Adafruit_CharLCDPlate.TEAL],
                    config_violet=inverted_map[Adafruit_CharLCDPlate.VIOLET])

class ConfigHandler(tornado.web.RequestHandler):
    def post(self):
        config_track = self.get_argument("config_track")
        colour_map = {self.get_argument("config_red"):Adafruit_CharLCDPlate.RED,
                      self.get_argument("config_green"):Adafruit_CharLCDPlate.GREEN,
                      self.get_argument("config_blue"):Adafruit_CharLCDPlate.BLUE,
                      self.get_argument("config_yellow"):Adafruit_CharLCDPlate.YELLOW,
                      self.get_argument("config_teal"):Adafruit_CharLCDPlate.TEAL,
                      self.get_argument("config_violet"):Adafruit_CharLCDPlate.VIOLET 
                      }
        set_config(config_track, colour_map)
        self.write("Now tracking %s" % config_track)

One technique to note here is how I invert the colour map. When processing it I want the map to be word > colour but when configuring it in the form I want colour > word. A Python dictionary comprehension can be used to invert the map in a single statement: {v:k for k, v in display_loop_instance.backlight_map.items()}

A new HTML form is required to support the colour settings. Also I need to populate the form input boxes with the current settings by making use of Tornado's template system. This is very basic, I'm just taking the values passed in to the render function and pulling them out here in the template for example {{ config_track }}.

<!DOCTYPE html>
<html lang="en">
    <head>
		<title>Raspberry Pi Tweetbox</title>
	</head>

	<body>
		<form id="config_form" action="config" method="post">
			<label for="config_track">Track:</label>
			<input id="config_track" name="config_track" type="text" value="{{ config_track }}">
			<br/>
			<label for="config_red">Red:</label>
			<input id="config_red" name="config_red" type="text" value="{{ config_red }}">
			<br/>
			<label for="config_green">Green:</label>
			<input id="config_green" name="config_green" type="text" value="{{ config_green }}">
			<br/>
			<label for="config_blue">Blue:</label>
			<input id="config_blue" name="config_blue" type="text" value="{{ config_blue }}">
			<br/>
			<label for="config_yellow">Yellow:</label>
			<input id="config_yellow" name="config_yellow" type="text" value="{{ config_yellow }}">
			<br/>
			<label for="config_teal">Teal:</label>
			<input id="config_teal" name="config_teal" type="text" value="{{ config_teal }}">
			<br/>
			<label for="config_violet">Violet:</label>
			<input id="config_violet" name="config_violet" type="text" value="{{ config_violet }}">
			<br/>
			<button type="submit">Submit</button>
		</form>
	</body>
</html>

Now that I can save and load the configuration, the former restart routine needs to be a little more sophisticated:

def set_config(track_text, colour_map):
    display_loop_instance.set_text("Updating configuration")
    stream.disconnect()
    display_loop_instance.track_text = track_text
    display_loop_instance.backlight_map = colour_map
    display_loop_instance.write_config()
    time.sleep(5) #Allow time for the thread to disconnect...
    stream.filter(track=[display_loop_instance.track_text], async=True)
    display_loop_instance.set_text("Updated configuration")
    

Since it's more than a restart it's name is now set_config. It's here where I now call write_config to save the changes to file.

All that's left is a couple of changes to read in the configuration at startup:

display_loop_instance = DisplayLoop()
display_loop_instance.read_config()

And to start the stream from this setting rather than  'jeremy':

stream = Stream(auth, display_loop_instance)
stream.filter(track=[display_loop_instance.track_text], async=True)

Start the program, point a web browser at http://{your-raspi-ipaddress}:8888/ and you will see the form:

Web form
Web form

Stage 3: Finishing Touches

There are a few things that aren't very slick about this program:

  • Delay while updating the configuration
  • The Now tracking... response after submitting the form
  • Ugly form styling

The delay while the configuration is changing is due to the asynchronous nature of the program. There is a thread managing the Twitter stream, a thread scrolling the display and the main thread running the web server. 

When I want to change the settings on the stream I need to disconnect it and then reconnect with the new options. Unfortunately there's no event from tweepy to tell me when I have successfully disconnected and so up until now I have just delayed for five seconds between disconnect and reconnect. 

To remove this delay what I'll do is start a new connection while the old one is disconnecting so I don't have to wait. Of course this means that at one point there may be two streams receiving tweets. This would be confusing on the display since you would see the old tracking and the new tracking combined. 

Therefore, just prior to disconnecting I'll connect the old stream to a listener which does nothing with the incoming tweets. Here is the definition of the NullListener and the changes to the set_config routine:

class NullListener(StreamListener):
    def on_data(self, data):
        pass
        
def set_config(track_text, colour_map):
    print "restarting"
    display_loop_instance.set_text("Updating configuration")
    #Kill the old stream asynchronously
    global stream    
    stream.listener = NullListener()
    stream.disconnect()
    
    display_loop_instance.track_text = track_text
    display_loop_instance.backlight_map = colour_map
    display_loop_instance.write_config()

    #Make a new stream
    stream = Stream(auth, display_loop_instance)    
    stream.filter(track=[display_loop_instance.track_text], async=True)
    display_loop_instance.set_text("Updated configuration")

Regarding the Now tracking… response, the current version of the form is submitted to the ConfigHandler which changes the settings and returns this ugly response. Really what I want is for the form to re-appear with the new settings in place. 

I can achieve this by redirecting the user back to the / URL. Also, there's really no need for the ConfigHandler anyway, I can define the get and post methods on the MainHandler and simply submit the form there instead:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        inverted_map = {v:k for k, v in display_loop_instance.backlight_map.items()}
        self.render("templates/form4.html", 
                    config_track=display_loop_instance.track_text,
                    config_red=inverted_map[Adafruit_CharLCDPlate.RED], 
                    config_green=inverted_map[Adafruit_CharLCDPlate.GREEN],
                    config_blue=inverted_map[Adafruit_CharLCDPlate.BLUE],
                    config_yellow=inverted_map[Adafruit_CharLCDPlate.YELLOW],
                    config_teal=inverted_map[Adafruit_CharLCDPlate.TEAL],
                    config_violet=inverted_map[Adafruit_CharLCDPlate.VIOLET])

    def post(self):
        config_track = self.get_argument("config_track")
        colour_map = {self.get_argument("config_red"):Adafruit_CharLCDPlate.RED,
                      self.get_argument("config_green"):Adafruit_CharLCDPlate.GREEN,
                      self.get_argument("config_blue"):Adafruit_CharLCDPlate.BLUE,
                      self.get_argument("config_yellow"):Adafruit_CharLCDPlate.YELLOW,
                      self.get_argument("config_teal"):Adafruit_CharLCDPlate.TEAL,
                      self.get_argument("config_violet"):Adafruit_CharLCDPlate.VIOLET 
                      }
        set_config(config_track, colour_map)
        #Use a redirect to avoid problems with refreshes in the browser from a form post
        self.redirect("/")

application = tornado.web.Application([
    (r"/", MainHandler),
])

Finally, styling. Making this look really beautiful could be a whole new tutorial in itself, but a really good start is to introduce a framework to take care of a lot of the styling for you. 

I’m  Bootstrap for styling and JQuery for scripting. Both of these are available on CDNs so you don't need to download anything, just include them in the head section of the page:

<head>
	<title>Raspberry Pi Tweetbox</title>

	<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
	<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
	
	<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
	<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
	<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>	
		
	<meta name="viewport" content="width=device-width, initial-scale=1">	
</head>

To make the form look better we'll use Bootstrap's Horizontal Form style:

<form id="config_form" action="/" method="post" class="form-horizontal" role="form">
    		<div class="form-group">
		<label for="config_track" class="col-sm-1 control-label">Track:</label>
		<div class="col-sm-2">
			<input id="config_track" name="config_track" type="text" value="{{ config_track }}" class="form-control">
		</div>
	</div>
	<div class="form-group">
		<label for="config_red" class="col-sm-1 control-label">Red:</label>
		<div class="col-sm-2">
			<input id="config_red" name="config_red" type="text" value="{{ config_red }}" class="form-control">
		</div>
	</div>
	<div class="form-group">
		<label for="config_green" class="col-sm-1 control-label">Green:</label>
		<div class="col-sm-2">
			<input id="config_green" name="config_green" type="text" value="{{ config_green }}" class="form-control">
		</div>
	</div>
	<div class="form-group">
		<label for="config_blue" class="col-sm-1 control-label">Blue:</label>
		<div class="col-sm-2">
			<input id="config_blue" name="config_blue" type="text" value="{{ config_blue }}" class="form-control">
		</div>
	</div>
	<div class="form-group">
		<label for="config_yellow" class="col-sm-1 control-label">Yellow:</label>
		<div class="col-sm-2">
			<input id="config_yellow" name="config_yellow" type="text" value="{{ config_yellow }}" class="form-control">
		</div>
	</div>
	<div class="form-group">
		<label for="config_teal" class="col-sm-1 control-label">Teal:</label>
		<div class="col-sm-2">
			<input id="config_teal" name="config_teal" type="text" value="{{ config_teal }}" class="form-control">
		</div>	
	</div>
	<div class="form-group">
		<label for="config_violet" class="col-sm-1 control-label">Violet:</label>
		<div class="col-sm-2">
			<input id="config_violet" name="config_violet" type="text" value="{{ config_violet }}" class="form-control">
		</div>	
	</div>
	<div class="form-group">
		<div class="col-sm-offset-1 col-sm-1">
    				<button type="submit" class="btn btn-default">Submit</button>
  			</div>
	</div>
</form>

Finally to put a bit of polish on the UI we'll indicate to the user that the Raspberry Pi is updating when they click the submit button. This involves a little bit of Javascript to capture the form submission event, change the button text to Updating... and disable the button:

<script>
$("form").submit(function(event) {
    $("form button").html("Updating...").prop("disabled", true);
});
</script>

And here's the finished web UI:

The finished web form
The finished web form

Conclusion

This tutorial has expanded on the previous one to add a web UI to the RGB LCD Tweet Box. You can now control what you're following on the screen and the backlight colours you want from your phone, tablet or desktop machine.

Advertisement