Saturday, October 16, 2010

Automating a gingerbread house with an Arduino

It's been well known in my area that I really get into the holiday spirit come the holiday season. Outside, I've been slowly working my way up to being the Griswold on the block. As part of every holiday season, my family and I get together to build a gingerbread house. Recently I've been tinkering with an Arduino which is a single-board micro-controller that can be used to prototype circuits or build small projects and I started thinking, why should I build a gingerbread house just like anyone else. Why not instead trick it out a little with some lights and automation. At the very minumum, I wanted at least 12 LED's for lighting, an automated door and an automated figure that would come out after the door is opened. I've started prototyping an automated gingerbread house in a combination of cardboard and wood and an Arduino Duemillenove. The first challenge was to build a light harness containing 12 leds that can be individually controlled with very I/O lines. This is achieved through a technique known as Charlieplexing.  Charlieplexing allows for n pins to drive n2-n segments or LED's.  A great tutorial for creating Charliepexed circuits can be found on UsiMonkey's blog. I created and LED harness with 12 LED's on one end an a 4 pin header connector on the other end. I individually labeled every line on both ends and each of the four header connector lines with a Brother p-touch labeler. I did this in case I to assist in diagnosing any connection problems in the future. I neatly wrapped the lies with black electrical tape to form a trunk. At the end with the LED's, I left about eight inches unwrapped so I have some flexibility in the placement of the LED's.


For the automated figure and door, I choose to go with the HS-322HD because it was relatively inexpensive and provided enough torque to suit my needs. I initially connected a small nylon control horn I got from an on-line hobby shop to a cardboard door with hot glue to test the door mechanism and found that when the door stuck a little, the torque from the servo ripped the control horn right off of the cardboard door. Well, that wasn't going to do. If the torque was too much for the cardboard, it would certainly bee too much for a door made of gingerbread. The solution I came up with was to build a small wooden sub-frame from luan. I attached several small nylon hinges onto the wood frame and the small wooden door. This proved to be strong enough to handle the torque from the servo. The idea here is to hot glue this sub-frame to the front inside wall and to hot glue the gingerbread door onto the wooden door so that the wooden door serves as a durable backing to the gingerbread.



The following is a video of the mock gingerbread house I set up:





Ok so we finally got around to assembling and wiring the gingerbread house yesterday.  We decided to go with a castle. The reason for this is because the wood sub-frame I built for the door was too large for a "normal" sized gingerbread house.  The photo you see below is the wiring in the main house on the second level of the castle. I used hot glue to glue each led in place. The cable wrapped in black electrical tape is the wire trunk for the 12 LEDs. Eight of the LEDs are in the main house and the remaining four were placed in the tower next to the house. The blue cable is the wiring for the LCD display on front of the main house. Both wiring trunks go down to the first level where they connect to the Arduino.  



The following is a photo of the first level. Here you can see the two servos, one on the left and one on the right. In the center lies the Arduino.




The following are some photos of the finished house:





Below is a video of the gingerbread house in action:





Although it is a little hard to see, the LCD panel in the front says Merry Christmas in English, Spanish and French.

Saturday, August 21, 2010

Building Flexible Query Api's with Hamcrest and Guava

If you've ever had to build an api for custom querying of data then you've probably had to address the issue of how to handle queries for ever changing criteria. We've all seen different varieties of approaches. One approach I've seen recently that I find particularly interesting is using a combination of Hamcrest matchers and the Google commons library (now Guava) to create an api where custom queries can be accepted without having to customize the api.

We'll start by creating a simple class to hold information about People.
import org.apache.commons.lang.builder.ToStringBuilder;

final class Person{
private final String firstName,lastName;
private final int age;
private final double salary;

Person(final String firstName, final String lastName, final int age, final double salary) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.salary = salary;
}
public String firstName() {return firstName;}
public String lastName() {return lastName;}
public int age() {return age;}
public double salary() {return salary;}

@Override
public String toString() { return ToStringBuilder.reflectionToString(this);}
}

Nothing special here. One thing to note is the implementation of equals uses ToStringBuilder from the Apache Commons api. This is a great little utility for building a string representation of an object. Be careful how you use it however because it does so by reflection so performance may suffer.

Next, lets build a class to hold a cache of data on people containing a method to query for those people.
package org.foo;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.hamcrest.Matcher;
import java.util.*;

final class PeopleCache {
private static final PeopleCache instance = new PeopleCache();
private final erson> people = buildCache();

private PeopleCache() {}

public static PeopleCache instance() {return instance;}

public Iterable<Person> queryForPeople(Matcher<Person> matcher){
return (matcher == null
? people : Iterables.filter(people, new PredicateWrapper<Person>(matcher)));
}

private List<Person> buildCache() {
final List<Person> people = new ArrayList<Person>();
people.add(new Person("John", "Smith", 45, 150000));
people.add(new Person("Bob", "Smith", 35, 75000));
people.add(new Person("Bob", "Gordon", 37, 80000));
people.add(new Person("Tom", "Barry", 54, 100000));
return people;
}
}
Note that the queryForPeople method takes one argument, a matcher. The Matcher is a Hamcrest interface that provides methods to match an object and to describe a condition where a match has failed. Also note the use of the Iterables.filter method. This if from Google's Guava library. It is a method that takes an Iterable and and an Predicate. The Predicate is also from the Guava library and like the Matcher interface, it provides methods for checking equality on objects. Custom implementations of the Predicate interface work well but the real magic lies in adapting the rich set of Hamcrest matchers to the Predicate interface so that those matchers can be used in the filtering.

So, lets create the magic now. The following is a wrapper that adapts Matchers to a Predicate.
class PredicateWrapper<Person> implements Predicate<Person>{
private final Matcher<Person> matcher;
PredicateWrapper(final Matcher<Person> matcher) { this.matcher = matcher; }
public boolean apply(final Person input) { return matcher.matches(input); }
}
Now that we have an adapter for the matchers, we can create some custom matchers.
package org.foo;
import org.hamcrest.*;
import static org.hamcrest.CoreMatchers.allOf;
final class PeopleMatchers{
private PeopleMatchers(){}

public static Matcher<Person> hasLastName(final String lastName) {
return new TypeSafeMatcher<Person>() {

@Override
public boolean matchesSafely(final Person toMatch) {
return lastName.equalsIgnoreCase(toMatch.lastName());
}

@Override
public void describeTo(final Description desc) {
desc.appendText("last name is ").appendValue(lastName);
}
};
}

public static Matcher<Person> isOlderThan(final Integer age) {
return new TypeSafeMatcher<Person>() {
@Override
public boolean matchesSafely(final Person toMatch) {
return toMatch.age() > age;
}

@Override
public void describeTo(final Description desc) {
desc.appendText("age is than ").appendValue(age);
}
};
}
}
Ok, So now that we have some matchers, we can call build a query by initializing a matcher and passing it to the query method. If you were to print out the result of executing the following:
PeopleCache.instance().queryForPeople(PeopleMatchers.hasLastName("Smith"))
You would see something like the following in the output:
org.foo.Person@482923[firstName=John,lastName=Smith,age=45,salary=150000.0]
org.foo.Person@c832d2[firstName=Bob,lastName=Smith,age=35,salary=75000.0]

If you were to print out the result of executing the following:
PeopleCache.instance().queryForPeople(PeopleMatchers.isOlderThan(35)))

You would see something like the following in the output:
org.foo.Person@482923[firstName=John,lastName=Smith,age=45,salary=150000.0]
org.foo.Person@d19bc8[firstName=Bob,lastName=Gordon,age=37,salary=80000.0]
org.foo.Person@14a8cd1[firstName=Tom,lastName=Barry,age=54,salary=100000.0]

Ok, so thats kind of cool but most real life queries require more than one condition. This can easily be accomodated by using the Hamcrest allOf matcher
which takes an array of matchers as an argument. Lets add a new matcher into the PeopleMatchers class and try it out. The following is a matcher that matches for a salary being greater than the given argument.

public static Matcher<Person> salaryGreaterThan(final double salary)
{
return new TypeSafeMatcher<Person>() {
@Override
public boolean matchesSafely(final Person toMatch) { return toMatch.salary() > salary; }

@Override
public void describeTo(final Description desc) { desc.appendText("salary is").appendValue(salary); }
};
}

So now, if you were to to print out the results of calling the query :
PeopleCache.instance().queryForPeople(
allOf(PeopleMatchers.isOlderThan(35), PeopleMatchers.salaryGreaterThan(80000))))

You would see something like the following in the output:
org.foo.Person@184ec44[firstName=John,lastName=Smith,age=45,salary=150000.0]
org.foo.Person@1630ab9[firstName=Tom,lastName=Barry,age=54,salary=100000.0]
You can see that it filtered bot for age and salary in the results.
So there you have it, a nice flexible api that can accept multiple criteria nicely without having to change the signature of the query method. One thing to keep in mind here is that the Iterables.filter method does iterate through all the elements in the given iterable so performance should be considered when dealing with large cached data or when retrieving from a database and filtering the results afterwards. Source code and sample test cases for this article can be found at github.

Monday, July 26, 2010

ScalaTest, A better way to test.

ScalaTest is a flexible testing framework that allows you to test the way you feel most comfortable testing. For example, it allows you to write tests in a functional manner or in a behavior driven manner. It allows you to write tests for both Scala and Java. It even has traits that can be pulled in to enhance your existing scala JUnit or TestNG tests if you prefer. I have been writing many of my scala tests using both TestNG and JUnit and recently introduced ScalaTest matcher traits into my existing tests. I've come to find that tests as they get more complex tend to get more difficult to read. The ScalaTest matchers go a long way in making your tests easier to read and therefore easier to maintain. This is important when practicing TDD.

Lets start with the following example using the basic JUnit assertions.

package com.foo

import org.junit.Test
import scala.collection.mutable.Map

class FooTest{
val company = Company

@Test
def addsCorrectly {
val jSmith = Person("John", "Smith", 1)
company.hire(jSmith)
assert(company.employeeCount == 1)
assert(company.employees.contains(jSmith))
}
}

object Company {
private val _employees = Map[Long, Person]()
def hire(user:Person) = _employees + (user.id -> user)
def employeeCount = _employees.size
def employees = _employees.values
}

case class Person(firstName:String, lastName:String, id:Long)

As you can see, the JUnit assertions do the job but they just don't read well. It's import to make any code, even test code, easy for anyone else to jump in and quickly understand. The easer code is to read, the easier it is to maintain.

The Hamcrest matcher library provides a variety of matchers that not only provide good functionality but make code a little nicer to read. Lets revisit the example above and rewrite the test method using the Hamcrest matcher library.


package com.foo
import org.junit.Test
import org.hamcrest.Matchers._
import org.hamcrest.MatcherAssert._

class FooTest{
val company = Company

@Test
def addsCorrectly {
val jSmith = Person("John", "Smith", 1)
company.hire(jSmith)
assertThat(company.employeeCount, is(1))
assertThat(company.employees(1), is(jSmith))
}
}

Although the Hamcrest matcher library provides a wide variety of matcher functionality, it still doesn't read as nicely as it could. Lets try this again, this time using the ScalaTest matchers.


package com.foo

import org.scalatest.matchers.ShouldMatchers
import org.scalatest.matchers._
import org.junit.Test

class FooTest extends ShouldMatchers {
val company = Company

@Test
def addsCorrectly {
val jSmith = Person("John", "Smith", 1L)
company.hire(jSmith)

company.employeeCount should be (1)
company.employees should contain value (jSmith)
}
}


There, now that reads nicely. To use the matchers you can simply add the trait to your existing class and you're ready to go. The full source for this example can be found at github.

Saturday, July 24, 2010

Scala Testing with Junit 4 and Annotations

JUnit annotations can easilty be used in Scala based tests just as they can in Java based tests.

The following is a basic scala test using the Junit annotations. For the sake of keeping the code as simple as possible we won't introduce thread safety into the example.


package com.foo
import org.junit.{Before, Test}
import org.junit.Assert.assertTrue

class BasicTest{
var bankAccount:BankAccount = _

@Before
def setup() = {bankAccount = new BankAccount(100)}

@Test
def addsCorrectly {
assertTrue(bankAccount.add(150) == 250)
}
}

class BankAccount(private var balance:Double){
def add(amt:Double):Double = { balance + amt }
}

As you can see, annotating JUnit tests in scala is pretty much the same as it is in java.
Except for some syntactical differences, handling tests that expect exceptions is also very similar to the way they are handled in java unit tests. Consider the following example:


package com.foo
import org.junit.Test
class FooTest{
@Test { val expected = classOf[ IllegalArgumentException] }
def shouldThrowException {
Foo.methodThatThrowsException
}
object Foo{
def methodThatThrowsException() = throw new IllegalArgumentException
}
}

One thing you may have noticed is that I declared a val in the annotation. Scala processes annotations in a different manner than Java. More on this can be found here.