Controlling the WIFI370

20140503-155503.jpg

As part of a home automation system, we purchased the RGB LED Wifi controller. It is quite a cool device that can be connected to your own WiFi network and it comes with its own App, to control the LEDs, but we wanted to control it using a different device and so set about reverse engineering the device.

The app controls the WiFi controller by sending TCP packets.  It sends them to the IP of the controller and to port 5577.  We captured the data that the app sent to the controller and are sharing it here in case anyone finds it useful.

Colour Ring Mode

This is the simplest mode and simply sets the colour of the LEDs to the sent RGB colour.  The command consists of five bytes: a header, a three byte colour code and a footer byte:

0x56 - header
  RR - RED value
  GG - GREEN value
  BB - BLUE value
0xaa - footer

e.g.: 56 00 ff 00 aa -> sets the LEDs to GREEN

Music Mode

This is a setting in which the app changes the colour of the LEDs in time to a song that is playing. It seems to behave in a similar manner to the colour ring mode but with different header and footer bytes:

0x78 - header
  RR - RED value
  GG - GREEN value
  BB - BLUE value
0xee - footer

e.g.: 78 ff 00 00 ee -> sets the LEDs to RED

Preset Modes

The controller has a number of preset modes that you can set it to and it will then automatically cycle the lights through a preset sequence. This is a nice feature as it means that you only have to tell it to start the sequence and don’t have to continually send packet data to the controller.

The command consists of four bytes, a header byte, a mode byte, a speed byte and a footer byte:

0xbb - header
  MM - Mode (0x25 - 0x38)
  SS - Speed Byte (0x01 - 0x1f)
0x44 - footer
Mode Description Mode Byte
Seven Colour Cross Fade 0x25
Red Gradual Change 0x26
Green Gradual Change 0x27
Blue Gradual Change 0x28
Yellow Gradual Change 0x29
Cyan Gradual Change 0x2a
Purple Gradual Change 0x2b
White Gradual Change 0x2c
Red, Green Cross fade 0x2d
Red, Blue Cross fade 0x2e
Green, Blue Cross fade 0x2f
Seven Colour Strobe Flash 0x30
Red Strobe Flash 0x31
Green Strobe Flash 0x32
Blue Strobe Flash 0x33
Yellow Strobe Flash 0x34
Cyan Strobe Flash 0x35
Purple Strobe Flash 0x36
White Strobe Flash 0x37
Seven Colour Jumping Change 0x38

Some examples of using the commands:

bb 25 1f 44 -> Seven colour cross fade, speed = 1
bb 2c 15 44 -> White gradual change, speed = 11
bb 35 01 44 -> Cyan Strobe flash, speed = 31

Control Commands

It is possible to pause the running sequence or turn off the LEDs completely.  The controller seems to supply a number of commands to control this.  They are all three bytes:

0xcc - header
  CC - control byte
0x33 - footer

We’re not entirely sure how these work, but the table below gives the value for the command and what we think they do:

Byte Description
0x20 Run ON – Starts playing the set sequence (predefined or custom). Always seems to restart from the beginning
0x21 Run OFF – Seems to pause the LEDs on the current value that they have
0x23 Open ON – Allows the LEDs to turn on
0x24 Open OFF – Turns the LEDs off

Custom Colour Modes

If the above predefined modes do not suffice, then it is possible to upload your own sequence to the device.  This mode allows you to upload a sequence of up to 16 colours, a speed and a change mode to the controller.  You only need to load this once, and once it has been sent, the controller will cycle through the colours without further intervention.

This command consists of 53 bytes: one header byte, 16 three byte RGB colour values, three modes bytes and a footer:

0x99       - header
  RR GG BB - 16 three byte colour values or 0x01 0x02 0x03
  SS       - a speed byte (see above for details of setting this)
  MM       - a mode byte (see table below for details of this byte)
0xff       - a reserved byte (always ff)
0x66       - footer

16 three byte colours must be supplied. If fewer than 16 colours are used, then a value of 0x01 0x02 0x03 is supplied to indicate that the value is not used.

The mode is show in the table below:

Value Mode Description
0x3a Gradual Fade to the colour
0x3b Jump Switch immediately to the colour
0x3c Strobe Flash the colour briefly

Some examples of using this command as follows:

To jump between RED and GREEN with a speed of 10:
99   ff 00 00   00 ff 00   (01 02 03)x14   16 3b ff   66

To Strobe between BLUE, GREEN and RED, speed 1:
99   00 00 ff   00 ff 00   ff 00 00   (01 02 03)x13   1f 3c ff   66

Note that it might be necessary to ensure that the controller has turned run and open on (see above for details).

Combining Multiple Commands into one TCP packet

We didn’t throughly test this, but the WiFi Controller seemed quite happy when we concatenated multiple commands into one TCP packet instead of sending two. i.e. to set the colour mode and turn OPEN on, sending the following packet should suffice:

56 ff 00 ff aa cc 23 33

Unhiding ads when searching with google

The ads that google place at the top of search result are quite difficult to separate from the main content because they have chosen to place them in a div that is practically the same colour as the main search results. As amazing as google is at predicting what I want, I rarely find that the ads that they place are relevent to what I am searching for and as a result I like to have an easy way of distinguishing them so that I can start at the top of the main results.

If you use Firefox, it is possible to setup a custom theme to change the colour of the ads so that they are distinguishable from the main result. To do this, you need to edit your userContent.css to set a custom rule for the div in question.

To do this, create (or edit) the following file C:\Documents and Settings\\Mozilla\Firefox\Profiles\.default\chrome and add the following section:

@-moz-document domain(google.co.uk) {
#tads { background-color: #eeeeee !important; }

Obviously change the google domain if you use google from another country and feel free to use a different colour if you want.

Credit must go to: http://coreygilmore.com/blog/2008/10/23/per-site-custom-css-in-firefox/ for details of this feature. This site is worth a read if you want to do this from a Mac.

Starting a Django Project

Django has fast become my web development weapon of choice.  Quick to develop, lots of functionality for free and of course allows me to code in python.  Everytime I create a project I find myself trawling through previous project to find those little snippets that make my life a lot easier.  For posterity, I am hoping to capture those steps in one place so that the next time I create a project it is much easier.

Virtualenv

Virtualenv creates a virtual python environment which allows you to isolate the libraries you install for each project.  I find it handy when developing for a machine where I am not the root user as it allows me to install a large number of packages without having write access to the library path.  The other major advantage is when you start a new project which uses a later version of django, it makes handling multiple django installs easy.  It is kind of a chicken and egg problem because we need a virtual env to install django, but we really want the env inside our django project.  I solve this by creating the environment, using this to create the project and then creating a bash script to activate the environment.

The other nice thing about virtualenv is that you can either install it or just download the file.  The overall process looks something like this:

# Setup virtualenv
$ cd projects

# Create directory for your virtual envs
$ mkdir venvs
$ cd venvs

# Install virtual env
$ wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py

# Create virtual env
$ python virtualenv.py <PROJECT_NAME>

# Activate virtual env
$ source <PROJECT_NAME>/bin/activate

# Install django
$ pip install django

The rest of this document assumes that you will have the virtual environment activated for all python commands.

Creating the Django Project

Now that we are in our virtual environment with django installed, we can create the project as we normally would.

(VENV)$ django-admin.py startproject <project_name>
(VENV)$ cd <project_name> python ./manage.py startapp <app_name>

Nothing exciting there.

Setting up Git

Version control is just a good idea. But first, let’s create a .gitignore file.

*.pyc              # ignore all compiled python files
local_settings.py  # Don't commit the local settings file (see later)
db.sq3             # Ignore the sqllite database

Once that has been created in your project directory, do the following

(VENV)$ git init
(VENV)$ git add .
(VENV)$ git commit -m 'Initial commit'

Edit settings.py

Django insists on using absolute paths for all of its config which is not very helpful if you are sharing users. I therefore add the following macros at the top of my settings.py file:

import os, django
DJANGO_ROOT = os.path.dirname(os.path.realpath(__django.__file__))
SITE_ROOT   = os.path.dirname(os.path.realpath(__file__))

DATABASE_NAME = os.path.join(SITE_ROOT, 'db.sq3')

TEMPLATE_DIRS = (
  os.path.join(SITE_ROOT, 'templates'),
)

DJANGO_ROOT now contains the location of the folder where django is installed. Most likely /usr/… or in your virtual environment. SITE_ROOT contains the location of the main site folder. You can see how these variables are used to set relative paths.

I also change the TIME_ZONE to ‘Europe/London’.

Finally at the end of settings.py I add the following lines. These allow me to easily override settings for each install. This means I generally set the settings.py up for development, using a sqllite backend which means that you can clone the repository and use the runserver command without any fancy setup. For production, the local_settings.py file overrides this and uses production values. It also is a good place for database passwords as these won’t get pushed to the repository.

try:
  from local_settings import *
except ImportError:
  pass

My local_settings.py looks like this:

DEBUG = False
TEMPLATE_DEBUG = False

ADMINS = (('<name>', '<email>'),)

DATABASES = (<database settings>)

SECRET_KEY = "Shh don't tell anyone"

Install South

Django comes with a great database abstraction layer, but it doesn’t handle migrations out of the box. Enter south. Whilst it seems like overkill now, you will be very happy later when you decide to add a column to your table and south just handles it.

Install south using pip. Make sure that you are running from the virtual environment.

(VENV)$ pip install South

The tutorial provides a good starting point for using south.

Model / View Creation

I find that I generally have to add the same imports at the top of most of my models / views and I generally have to look up what they are, so I am including them here:

# models.py

from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.conf import settings
from django.db.models.signals import post_delete
import django.dispatch
from django.utils import timezone
from django import forms
# views.py

from <app>.models import *
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse_lazy, reverse
from django.template import RequestContext, Context, loader
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.conf import settings
from django.utils import timezone
import datetime, json

The following is a quickstart guide for setting up the admin.

# admin.py

from django.contrib import admin
from <app> import *

class BlahAdmin(admin.ModelAdmin):
  list_display = ['', '']
  list_filter = ['', '']
  search_fileds = ['', '']
  ordering = ['', '']

admin.site.register(Blah, BlahAdmin)

Base Template

The following can be used as a base template:

<!DOCTYPE html>
<html>
<head>
  <!-- title block -->
  <title>{% block title %}Title{% endblock %}</title>

  <!-- website icons -->
  <link rel="icon" href="{{ STATIC_URL }}img/favicon.ico" type="image/x-icon" />
  <link rel="shortcut icon" href="{{ STATIC_URL }}img/favicon.ico" type="image/x-icon" />

  <!-- Styles and scripts required for each page -->
  <link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" type="text/css" />
  <script src="{{ STATIC_URL }}js/script.js" type="text/javascript"></script>

  <!-- A block so that a page can add stuff to the page header -->
  {% block extraheader %}
  {% endblock %}
</head>
<body>
  <div id="content">
    <!-- A block for navigation header -->
    {% block navbar %}
    {% endblock %}

    <!-- The main page content goes here -->
    {% block content %}
    {% endblock %}
  </div>
</body>
</html>

Setting up a scripts directory

It is worthwhile setting up a scripts directory for commonly used operations. It may be possible to eclipse this use fabric which will be explained later on, but doing this will save quite some time.

Create a script to enable the virtual evironment

# scripts/activate_venv.sh

source </bin/activate

Create a script for any jobs that you might want to add to a cron job.

# scripts/CRON.daily

# make sure we have the venv
activate_venv.sh

# run some commands
python manage.py <some command>

This can also be repeated for a cron weekly or other type of script.

I quite often have background daemon to process stuff so I found the following script would create a screen session for me, run a webserver and then start any background jobs.

# start.sh
# Loads an environment contained in an ENV.start file

ENV=$1

if [ -z "$ENV" ]
then
    echo "Environment not specified"
    exit 1
fi

FILE="scripts/$ENV.start"

if [ ! -f "$FILE" ]
then
    echo "Environment $ENV not known"
    exit 1					
fi

# start up a named screen session
screen -dmS "$ENV"
sleep 1

# apply the commands in $FILE to the screen session
screen -r "$ENV" -X source "$FILE"

The commands in the screen session look something like this:

# scripts/DEFAULT.start
# Starts the webserver and one background job

select 0
title "Server"
exec python manage.py runserver 0.0.0.0:8000

# command for production
#exec python manage.py runfcgi method=threaded host=127.0.0.1 port=8070 daemonize=false

# start the background job
screen
select 1
title "Background job"
exec python manage.py <command>

The following file is used to kill the named screen session.

# scripts/stop.sh

ENV=$1

if [ -z "$ENV" ]
then
    echo "Environment not specified"
    exit 1
fi

FILE="scripts/$ENV.start"

if [ ! -f "$FILE" ]
then
    echo "$ENV not known"
    exit 1
fi

# kill the session
screen -X -S "$ENV" quit || exit 0

Now I can create as many environment files as I require (typically one for local debug and one for production) and call them as follows:

# Start the webserver
(VENV)$ scripts/start.sh DEFAULT

# Stop the webserver
(VENV)$ scripts/stop.sh DEFAULT

Note that you must have the virtual environment activated for the django admin commands to work properly.

Beanstalk

I typically find that my web applications involve a web frontend that puts data in a database and a background daemon that processes the data. Initially, in my worker thread, I would poll on the database with a 10 or so second sleep between polls, but this is not very elegant. I now use beanstalk which means I don’t have to poll.

worker_signal = django.dispatch.Signal(providing_args=[])
worker_signal.send(sender=model instance)

from django.dispatch import receiver
@receiver(worker_signal)
def do_some_work(sender, **kwargs):
  pass

Fabric

At first glance fabric seems far too simple to be useful, but that is what gives it its power, the fact that it is really simple. To install it, from the virtual environment use:

(VENV)$ pip install fabric

I’m still new to fabric and haven’t yet worked out the best way to fit it into my projects. At the moment I use it to drive the scripts in my scripts folder and use it to push changes from my development version to my remotely installed version. This is the fab command that I use to do that:

def releaseversion(tag):
  local('git push origin %s' % tag)
  with cd('path to dir'):
    run('./scripts/stop.sh PRODUCTION')
    run('git pull --tags origin master')
    run('git checkout %s' % tag)
    # include commands here to syncdb / manage south migrations
    # and do anything else when new stuff is installed
    run('./scripts/start.sh PRODUCTION')

This means that now when I am happy with my development testing on my dev site, I can run the following set of commands and have the remote site(s) automatically update. This makes pushing changes to remote sites easy.

(VENV)$ git tag -a tag_name -m 'Blah'
(VENV)$ fab releaseversion:tag_name

I’ll update this section as I get a better handle on fabric. For now, read the documentation here.

One or Two Beers from Belgium

20120410-204954.jpg

Pauwel Kwak and Tripel Karmeliet

In continuing with drinking beers from the country of sporting events that we follow, we were obliged to knock back some beers from Belgium whilst watching Paris-Roubaix.

The first thing to note about the beers that we tried is that they are not shy when it comes to ABV.  All the following beers were at least nine percent which really does the trick.

In all, five beers were drunk.  Three golden ones: Duvel, Tripel Karmeliet and Urthel Hop-It and two dark ones: Urthel Samarath and Pauwal Kwak all of which were very enjoyable in their own unique way.

Although all of the beers had very different tastes,one thing they do have in common is their strength.  It is very subtle, but they all have a slight taste of alcohol.  Not a lot, but just enough to make you sit up and take notice.  Just enough to remind you that that these are beers to be taken seriously, beers that should be sipped and appreciated; not just downed.  I am very much looking forward to the next Belgium beer tasting.

Urthel Hop-It

Urthel Samarath

Duvel

Australian Beer for an Australian Race

In an attempt to revive the 1001 beers attempt, we will be trying to to drink one (or more) beers from the country that is hosting the grand prix in that weekend.  The 2012 season started in Albert Park.  The beer of choice was Little Creatures’s Pale Ale – a delicious, fruity beer.  We also obtained, but did not get around to drinking Boag’s Premium Lager which is from Tasmania.

Some locations will be more challenging than others e.g. Malaysia and Bahrain and in this case we will have to open the selection up to neighbouring countries.

Update: We have now had the Boag’s Premium Lager.  A very tasty beer that I can imagine would be very refreshing on a hot summer’s day, standing in front of a braai / BBQ.

Heston’s Exploding Chocolate Gateau

I’ve been following Heston’s recent cooking series: “How to cook like Heston”.  So far I have found it to contain many useful tidbits.  His episode on chocolate inspired me to make his chocolate gateau.  You can see the full recipe here.

Unfortunately I was unable to find the popping candy for the base, but the result was still amazing and the passion fruit did indeed work very well with the chocolate.  My final result is shown below:

You may be able to see that I didn’t bother with spraying the cake with a chocolate finish.  As awesome as it would have been, it seemed a little excessive.

Some other photos of the making of the cake are shown below:

Combining the passion fruit pulp with the cream

Melting the dark and milk chocolate

Mixing the molten chocolate with the cream

Spreading a thin layer of the ganache on the base that is frozen. This stops the mixture seeping into the base.

 

 

NSLookup

This is mainly a note to myself as everytime I try and find this command, the search terms required for google seem to get more and more difficult to remember.

In order to turn a local IP address into a hostname, you can use the following command:

$ nslookup <ip address>

Brightly Coloured Lichen

Image

Water on Rock

Having finally uploaded one of my own photos for the header of my blog, I thought I’d make a mention of it with another one of my photos.  Both photos were taken in Zimbabwe.  The blog header was taken near Cecil John Rhodes’ grave in the Matopas.  The Matopas consists of large rock forms covered in striking lichen.  It was an overcast  day which allowed the lichen to contrast beautifully against the rock and the windswept grass adds movement and drama to the photo.

You forget just how brightly coloured the lichen can be as can be better seen in the photo attached to this post.  You can see just how vibrant the orange is against the rock.  This photo was unplanned; some ice from the cooler box melted whilst I was waiting for a sunset shot.  The glistening of the water caught my eye and resulted in the above shot.

Beer Dispensing Equipment

Image

I was in a bar recently which has taps plumbed in on the table where you sat so you could pour your own drinks.  An experience I really enjoyed – it certainly made getting drinks easier.  Although you did have to keep on remembering which account to set before pouring your drink.  I imagine that this gets more difficult as the evening wears on…

As cool as having beer piped to each table was, the bar had made the effort to put the beer dispensing equipment on display for their patrons to see as they visited the facilities.  What a brilliant idea!