Archive for the ‘code’ Category

CurrentCostuino

Wednesday, November 19th, 2008

With homecamp fast approaching I spent some time last weekend reviving some CurrentCost hacking I started in the summer.

One of the downsides of the data connection on the CurrentCost is the need for an always-on computer in order to capture the data. In practice, the existence of low powered machines like the MPC-L, or slug, make this a pretty inconsequential downside. That said, it was enough motivation to see what I could do with an Arduino and Ethernet Shield.

I have previously mentioned that part of the setup used to graph the power data online was to publish the data to a broker-in-the-sky using MQTT. To achieve this with an arduino it was clear that I needed one thing in particular - an arduino that is capable of connecting and publishing to an MQTT server.

With my ethernet shield in hand, I set about implementing enough of the MQTT spec to support basic publishing and subscribing. With that working, I looked into getting the arduino and CurrentCost talking. Thanks to Alexis, this was very straightforward, although I did rework the parsing of the data to take advantage of its somewhat-fixed length format.

Here’s the sketch I ended up with:

#include <Ethernet.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 172, 16, 0, 50 };
byte server[] = { 172, 16, 0, 103 };

PubSubClient client(server, 1883,0);

#define rx 6
#define tx 7

SoftwareSerial softSerial =  SoftwareSerial(rx, tx);

void setup()  {
  pinMode(rx, INPUT);
  pinMode(tx, OUTPUT);
  softSerial.begin(9650);
  Ethernet.begin(mac, ip);
  delay(500);
}

void connect() {
  while(!client.connect("nolcc")) {
    delay(10000);
  }
  delay(200);
}

int offset = -1;
void loop() {
  if (!client.connected()) {
    connect();
    offset = -1;
  }
  client.loop();

  // scan the data for <msg>
  while(offset == -1) {
    char c = ' ';
    while (c!='<') {
      c = softSerial.read();
    }
    if (softSerial.read()=='m' &&
        softSerial.read()=='s' &&
        softSerial.read()=='g' &&
        softSerial.read()=='>') {
      offset = 5;
    }
  }

  // skip to the current value
  while(offset < 156) {
    offset++;
    softSerial.read();
  }
  char current[5];
  int value = 0;
  for (int i=0;i<5;i++) {
    current[i] = softSerial.read();
  }
  offset += 5;

  // skip to the temperature value
  while(offset < 243) {
    offset++;
    softSerial.read();
  }
  char temp[5];
  for (int i=0;i<4;i++) {
    temp[i] = softSerial.read();
  }
  offset += 4;

  client.publish("current",(uint8_t*)current,5);
  client.publish("temp",(uint8_t*)temp,4);

  // scan for </msg>
  while(offset != -1) {
    char c = ' ';
    while (c!='<') {
      c = softSerial.read();
    }
    if (softSerial.read()=='/' &&
        softSerial.read()=='m' &&
        softSerial.read()=='s' &&
        softSerial.read()=='g' &&
        softSerial.read()=='>') {
      offset = -1;
    }
  }
}

It publishes each power reading to a topic called ‘current’ and each temperature reading to a topic called ‘temp’. This isn’t quite the right configuration for the existing broker setup, but it wouldn’t take much to modify it appropriately.

You’ll note this sketch isn’t much use without the library that does the MQTT bit. Luckily, I have been given permission to release the library to the world. I should stress at this point, in case it wasn’t obvious from the fact I am releasing this code on my personal site, that my employer has nothing to do with it.

You’ll find the Client for MQTT library here.

If you want an MQTT server to play with, go buy Lotus Expeditor to get your hands on a microbroker <gratuitous-plug />, or check out the links on mqtt.org for the Really Small Message Broker.

Google Treasure Hunt

Monday, May 19th, 2008

Earlier today, I spotted a tweet from @thomasj about the Google Treasure Hunt. This was followed later in the day by a series of tweets from @graham_alton (warning: spoiler in tweets!) that picqued enough interest that I decided to have a go.

In summary, the challenge is to state how many unqiue paths there are across an arbitrarily sized chessboard from the top-left corner to the bottom-right corner, but only moving down or right at each step. Graham has written up his solution, along with the original question on his blog.

He has gone straight for the proper solution using a simple formula… and some perl to handle the fact the numbers involved are beyond most desk calculators.

I decided to go for a bit more of a brute force approach… and some python to handle the fact I haven’t touched perl in a while.

Here’s my solution:

#!/usr/bin/python
# the dimensions of the board
w=54
h=30
lr = [1]*w
for y in range(1,h):
   lc = 1
      for x in range(1,w):
         lc = lc + lr[x]
         lr[x] = lc
print lc

The secret here is that for any given square on the board, the number of unique paths is equal to the sum of the number of unique paths from the squares immediately to the right and below.

Here’s an attempt to express it slightly more formally:

f(x,y) = f(x+1,y)+f(x,y+1)

where f(w,y) = f(x,h) = 1

The next question of the treasure hunt is due any minute now…

for(laziness in javascript)

Wednesday, October 18th, 2006

This post is mostly a note-to-self.

Compare the following pieces of javascript:

var list = ['a','b','c'];
for(x in list) {
   alert(x);
}
var list = ['a','b','c'];
for(var x in list) {
   alert(x);
}
 

Either works in Firefox. Only the one on the right works in IE. Hint: the difference is in bold.

The IE behaviour encourages you to define your variables and not get lazy. Given that I develop under Firefox and don’t test under IE until late in the day, remembering this one will be a huge time-saver.

Overflowing Quirks

Monday, October 16th, 2006

Much has been written about the inconsistencies of CSS within the various browsers. A great resource for learning about them is the QuirksMode website. Despite having read a lot of that site, I spent far too much time today trying to debug one.

Its worth mentioning upfront that this is with Firefox 1.5.0.7 on my laptop. Since writing up this post, I have found that Firefox 1.0.x on my desktop does not behave as described here. I’m not sure which is infact ‘correct’.

For a website I’m developing in work, I have a drag-and-drop interface that allows the user to arrange objects represented as <div> elements onscreen. If the user cancels the drag, the <div> is animated returning to its original position. For reasons that are not important, the <div> can return to one of two containing <div> elements. This all works well, apart from the fact that for one of the containers, an object that is returning to it consistently ends up 1 pixel out of position.

I initially assumed this was to do with the Box model issues, but the css for the two containers have identical border declarations. A bit of further digging and I found the only difference was the overflow style - and funnily enough, thats exactly where the problem lies.

To demonstrate, below are two identical <div> elements that contain a child <div> which has position: relative and is offset by 5px on both top: and left:. The sole difference between them is the first has overflow: hidden, and the second overflow: visible. Each of the inner <div>s are armed with the following piece of javascript:

onclick="
   var a=this.parentNode;
   this.innerHTML = 'dx:'+(this.offsetLeft-a.offsetLeft)+
                    ' dy:'+(this.offsetTop-a.offsetTop);
"

When you click on them, the offset between the child and its parent is shown. Remember that the css is identical for these examples in all but overflow.

click me
click me

As you can see, assuming you have clicked away and your are running the right level of the right browser, the offsets are different and its all thanks to the overflow. I have not fully investigated the various fixes for CSS issues such as Strict mode, but I was fortunately able to code a workaround using javascript that dynamically alters the overflow style depending on whether the user is dragging. I admit its not the cleanest solution.

Ruby Cubes

Wednesday, October 4th, 2006
Ruby Cube Pieces
The 6 Pieces

At a recent get-together with friends, I found myself playing with a wooden puzzle consisting of 6 pieces that were claimed to be able to come together to form a solid cube.

Lucy, the puzzle’s owner, said she had owned it for years and never successfully solved it. Not to be detered, I spent the whole evening failing to get anywhere with it.

Continuing not be detered, I decided to do the honorable geek thing and write a computer program to solve it.

Herewith how I approached the problem and got started with ruby. (more…)

Overlapping Text

Wednesday, September 6th, 2006

The parent hosting site for knolleary is BlogsDollocks - a hosting service that I have a hand in.

Last night I spent some time reworking the BD homepage so that it includes a selection of blog entries from the hosted sites. This was easily achieved using the same mechanism as I used for the del.icio.us links in the sidebar.

One of the existing design features of the page that Kyb put together was the BD text at the top of the page. On my laptop, running Ubuntu Dapper with Firefox 1.5.0.5, it looks like this:

BlogsDollocks Logo on Laptop

I was never quite sure about this overlapping design, but it wasn’t until this morning that I looked at the site with my desktop machine, running Debian with Firefox 1.0.4 that I saw it rendered like this:

BlogsDollocks Logo

This does lead me to wonder which is the correct rendering of the text.

The html for the logo is simply:

<div class="title">
   <h1>Blogs Dollocks</h1>
   <h2>every blog has his day</h2>
</div>

and the css is:

div.title {
        font-size: 28pt;
        width: 6em;
        margin: auto;
}
h1 {
        font-family: perpetua, serif;
        font-weight: normal;
        font-size: 28pt;
        text-align: center;
        line-height: 0px;
        padding-top: 20px;
}

h2 {
        font-style: italic;
        font-weight: normal;
        font-size: 7pt;
        text-align: right;
        line-height: 0px;
}

It seems that the width property of div.title is what is being handled differently. It all comes down to the magical em unit of measurement.

The differing versions of firefox is a complete red herring. The key is the different resolutions the two machines run at - the laptop at a lowly 1024×768 and the desktop at 1600×1200.

If I set the width to a more rigid value of 200px then the text is rendered more consistently between the two browsers - in this case with the words overlapping as 200px is not sufficient for the text to be layed out fully at its default font size. However this doesn’t work with zooming the page (Ctrl++/Ctrl+- on firefox).

Having conferred with Kyb, the desired rendering is the properly spaced out version. As such, I have changed to css to:

div.title {
        font-size: 8em;
        width: 3em;
        margin-left: 200px;
}

This keeps the text looking sane at both resolutions, and gracefully handles enlarging the text.

Note I have also moved away from margin: auto so that the title stays in position as the screen size changes.

Right-Handed Bullets

Friday, September 1st, 2006

In the endless process of refining the aesthetics of the site, I would like to have the list items in the sidebar have their bullets on the right-hand side of the item text rather than the default left.

A quick google reveals the direction CSS property which almost does the necessary. Given a simple list like this:

<ul>
   <li>A</li>
   <li>B</li>
   <li>C</li>
</ul>
  • A
  • B
  • C

setting the direction property to rtl - ie right-to-left - generates this:

<ul style="direction:rtl;">
   <li>A</li>
   <li>B</li>
   <li>C</li>
</ul>
  • A
  • B
  • C

On the face of it, this is ideal. But if you have a punctuation character in there, such as the post counts against the catergory links, you hit a problem:

<ul style="direction:rtl;">
   <li>A(1)</li>
   <li>B+</li>
   <li>C?</li>
</ul>
  • A(1)
  • B+
  • C?

This is a direct result of how right-to-left text works in CSS. There are a couple of possible work-arounds:

  • Set the list-style to none and set the background image of the element to include a bullet point on the right-hand side.
  • Apply direction: rtl; to the <li> elements and have a <span> element with its direction set to ltr surrounding the content in order to pull it back into place.

The first option feels dirty and I would rather not go near it.
The second option seems easier if it wasn’t for the way Wordpress generates the list of categories. The function call to wp_list_cats() doesn’t allow for custom HTML in the output, so it isn’t possible to add the <span> element. I could write my own version of the function that did what I wanted - but that seems overkill.

For now I will live with the left-hand bullets - any other suggestions for moving the bullet over are welcome.