BrickPi Lego robot takes its first steps!

A little while back I wrote a post about creating a python script to control a brickpi robot, now that I actually have the brickpi components, motors and cables and have actually tried it out, I’ve made a few improvements to that script to make it work.

Installing Raspbian

Firstly, I had to revisit the raspbian installation. With the brickpi bundle I bought from Dexter Industries, it came with a pre-installed raspbian SD card. I’m not sure what was wrong, but I wasn’t able to boot into it, there were startup errors regarding /etc/init.d. A quick Google didn’t help, so I decided to flash a new SD card with a more recent version of raspbian.

It’s important to note that the stock raspbian image won’t automatically work with the brickpi, as some modifications are required in order to control I/O for the motors. You can make these modifications yourself as there are instructions on the brickpi website, but it’s far easier to just download the pre-modified raspbian from dexter industries.

This was quite simple, on a mac you can erase and format an SD card using Disk Utility, after that, use these commands to create the SD card image:

diskutil list
diskutil unmountdisk /dev/disk1
dd if=2013.07.27_BrickPi.img of=/dev/disk1 bs=2m

diskutil list will show you the drives attached, in my case the SD card was disk1 but it may vary for you. It takes around 10 minutes to flash the SD card so go make a brew.

Configuring WiFi

Setting up wifi on the pi is pretty easy, I have a USB wifi adapter, so it was just a case of configuring a wireless interface, which can be done by adding the following to /etc/network/interfaces

sudo nano /etc/network/interfaces
add
iface wlan0 inet dhcp
wpa-ssid "NETWORK_ID_HERE"
wpa-psk "NETWORK_PASSWORD_HERE"

Then do a sudo reboot

Expanding the SD card

In order to expand the root partition and make use of the entire SD card, run the following command and follow the menus to expand SD card

sudo raspi-config

Then do a sudo reboot

Setting up the brickpi dependencies

SSH onto the pi and run the following

mkdir brickpi
cd brickpi/
git clone https://github.com/DexterInd/BrickPi_Python.git
cd BrickPi_Python
sudo apt-get install python-setuptools
sudo python setup.py install

This will clone the BrickPi python repository (which contains a load of examples), install python-setuptools and install the brickpi module, so you can import Brickpi globally in your python scripts.

Controlling the robot

After testing out the brickpi examples, it was quite clear that I’d need to modify my original python script. I needed 2 threads.

  • Thread 1 would continually update the motors every 200ms, otherwise the motors would turn briefly and then remain still.
  • Thread 2 would process incoming commands and set the motor speeds.

Other than the threading code, the script is quite easy to follow

from BrickPi import *   #import BrickPi.py file to use BrickPi operations
import threading
import socket
import select
import Queue
from threading import Thread
import sys

BrickPiSetup()  # setup the serial port for communication
BrickPi.MotorEnable[PORT_A] = 1 #Enable the Motor A
BrickPi.MotorEnable[PORT_D] = 1 #Enable the Motor D
BrickPiSetupSensors()   #Send the properties of sensors to BrickPi

running = True

#This thread is used for keeping the motor running while the main thread waits for user input
class BrickPiThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        while running:
            BrickPiUpdateValues()       # Ask BrickPi to update values for sensors/motors
            time.sleep(.2)              # sleep for 200 ms

brickPiThread = BrickPiThread(1, "BrickPiThread", 1)                #Setup and start the thread
brickPiThread.setDaemon(True)
brickPiThread.start()

class ProcessCommandThread(Thread):
    def __init__(self):
        super(ProcessCommandThread, self).__init__()
        self.running = True
        self.q = Queue.Queue()

    def add(self, data):
        self.q.put(data)

    def stop(self):
        self.running = False

    def run(self):
        q = self.q
        while self.running:
            try:
                # block for 1 second only:
                value = q.get(block=True, timeout=1)
                process(value)
            except Queue.Empty:
                sys.stdout.write('.')
                sys.stdout.flush()
        if not q.empty():
            print "Elements left in the queue:"
            while not q.empty():
                print q.get()

commandThread = ProcessCommandThread()
commandThread.start()

def process(value):
    print "Processing [{v}]".format(v=value)

    # Left side
    if value == 'L-FORWARD-Start':
        print "L-FORWARD-Start"
        BrickPi.MotorSpeed[PORT_A] = 200
    elif value == 'L-FORWARD-Stop':
        print "L-FORWARD-Stop"
        BrickPi.MotorSpeed[PORT_A] = 0
    elif value == 'L-BACK-Start':
        print "L-BACK-Start"
        BrickPi.MotorSpeed[PORT_A] = -200
    elif value == 'L-BACK-Stop':
        print "L-BACK-Stop"
        BrickPi.MotorSpeed[PORT_A] = 0
    # Right side
    if value == 'R-FORWARD-Start':
        print "R-FORWARD-Start"
        BrickPi.MotorSpeed[PORT_D] = 200
    elif value == 'R-FORWARD-Stop':
        print "R-FORWARD-Stop"
        BrickPi.MotorSpeed[PORT_D] = 0
    elif value == 'R-BACK-Start':
        print "R-BACK-Start"
        BrickPi.MotorSpeed[PORT_D] = -200
    elif value == 'R-BACK-Stop':
        print "R-BACK-Stop"
        BrickPi.MotorSpeed[PORT_D] = 0

def main():
    s = socket.socket()
    #host = socket.gethostname()
    host = "192.168.0.10"
    port = 3033
    s.bind((host, port))

    print "Server listening on port {p}...".format(p=port)

    s.listen(5)                 # Now wait for client connection.

    while True:
        try:
            client, addr = s.accept()
            ready = select.select([client, ], [], [], 2)
            if ready[0]:
                data = client.recv(4096)
                commandThread.add(data)
        except KeyboardInterrupt:
            print
            print "Stopping server."
            break
        except socket.error, msg:
            print "Socket error %s" % msg
            break

    cleanup()

def cleanup():
    commandThread.stop()
    commandThread.join()

if __name__ == "__main__":
    main()

Paste that into server.py then run the following:

sudo python server.py

You should see some output in the terminal as it’ll print out any incoming commands. Then its up to you to connect onto that socket with a client of your choice. I’m using an android app (which I’ve detailed here), but you could use something as simple as the following Java client

import java.io.*;
import java.net.Socket;

public class Runner {

    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("raspberrypi", 3033);

        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

        osw.write("L-FORWARD-Stop");
        osw.flush();
    }
}

Resources

Any thoughts / suggestions? Please comment below!

Installing a new Java JDK on a Mac

Updating Java on a Mac is easy, it’s just a case of installing a new JDK and recreating the symbolic link that is used to point to the current JDK.

Download the Java .dmg for mac from the Oracle website, then run through the installer.

That will install Java for you, but your default Java installation won’t be updated to point to the new version, but fortunately its easy to correct that

Open up a terminal and type

 cd /System/Library/Frameworks/JavaVM.framework/Versions/

You will probably see something like this

 lrwxr-xr-x  1 root  wheel   60 10 Dec 17:23 CurrentJDK -> /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/

As you can see, CurrentJDK is pointing to 1.6

Delete the symbolic link

 sudo rm CurrentJDK

Then recreate it and point to the version of Java you want to use as the default

 sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/ CurrentJDK
 

Then if you run java -version you should now see 1.7

 java version "1.7.0_45"
 Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
 Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)

Project Euler, problem 2, fibonacci sequence

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Attacking this problem in using brute force, I create a left and right ints, to hold 1 and 2 respectively, I use these to walk along the fibonacci sequence.

To count along the fibonacci sequence I add the left and right together, and shift them leftwards, until I reach the desired upper limit. On each sequence number, I check if it is even and add to a total if it is.

Here is my solution using Java

public class Problem2
{
    public static void main(String[] args)
    {
        System.out.println(execute(4000000));
    }


    public static int execute(int upperLimit)
    {
        // since we start with 1 & 2, we can assume result always starts from 2, as it's even
        int result = 2;
        int left = 1;
        int right = 2;

        while (left + right < upperLimit)
        {
            int temp = left + right;
            left = right;
            right = temp;
            if (right % 2 == 0)
            {
                result += right;
            }
        }

        return result;
    }
}

The answer is 4613732

Why all Java devs should at least consider Groovy and Spock for testing

As a developer, testing is very important. Some developers have the mindset of “Meh, I write code, testing is a QAs job”, which is pretty poor. It’s much better for the developer to be test driving their code, generally if adopted well it produces better quality code, and of course the sooner issues are caught the cheaper they are to address.

Most Java developers who are following TDD probably use mockito or powermock alongside JUnit. I’ve never been much of a fan of those combinations as I believe they involve far too much boilerplate code, and test code often becomes more verbose and harder to maintain than the actual production code itself.

After being introduced to Spock, and testing using Groovy last year, I’m absolutely sold on it and have subsequently used it on several other projects.

For the purpose of this post, I’ll base it around a service class that does some things with a domain object, via a data access layer, which is something most enterprise developers can relate to.

Heres the domain class:

public class User {

    private int id;
    private String name;
    private int age;

    // Accessors omitted
}

Heres the DAO interface:

public interface UserDao {

    public User get(int id);

}

And finally the service:

public class UserService {

    private UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public User findUser(int id){
        return null;
    }
}

Nothing too complex to mention here. The class that we’re going to put under test is the service. You can see that the service is dependant on a UserDao, which is passed into the constructor. This is a good design practice because you’re stating that in order to have a UserService, it must be constructed with a UserDao. This also becomes useful later when using dependency injection frameworks like Spring so you can mark them both as Components and Autowire the constructor arguments in, but alas.

Lets go ahead and create a test class for the service (command+shift+t if using IntelliJ on a mac).

class UserServiceTest extends Specification {

    UserService service
    UserDao dao = Mock(UserDao)

    def setup(){
        service = new UserService(dao)
    }

    def "it gets a user by id"(){
        given:
        def id = 1

        when:
        def result = service.findUser(id)

        then:
        1 * dao.get(id) >> new User(id:id, name:"James", age:27)
        result.id == 1
        result.name == "James"
        result.age == 27
    }
}

Here we go, right in at the deep end, let me explain what is going on here. Firstly, we’re using groovy, so although it looks like Java (I suppose it is in some respects as it compiles down to Java bytecode anyway) the syntax is a bit lighter, such as no semi-colons to terminate statements, no need for public accessor as everything is public by default, Strings for method names. If you want to learn more about groovy, check out their documentation here.

As you can see, the test class extends from spock.lang.Specification, this is a Spock base class and allows us to use the given, when and then blocks in our test.

You’ll see the subject of the test then, the service. I prefer to define this as a field and assign it in the setup, but others prefer to instantiate it in the given block of each test, I suppose this is really just a personal preference.

Creating mocks with Spock is easy, just use Mock(Class). I then pass the mocked DAO dependency into the userService in the setup method. Setup runs before each test is executed( likewise, cleanup() is run after each test completes). This is an excellent pattern for testing as you can mock out all dependencies and define their behaviour, so you’re literally just testing the service class.

A great feature of groovy is that you can use String literals to name your methods, this makes tests much easier to read and work out what it is actually testing rather than naming them as “public void testItGetsAUserById()”

Given, when, then

Spock is a behaviour driven development (BDD) testing framework, which is where it gets the given, when and then patterns from (amongst others). The easiest way I can explain it as follows:

Given some parts, when you do something, then you expect certain things to happen.

It’s probably easier to explain my test. We’re given an id of 1, you can think of this as a variable for the test. The when block is where the test starts, this is the invocation, we’re saying that when we call findUser() on the service passing in an id, we’ll get something back and assign it to the result.

The then block are your assertions, this is where you check the outcomes. The first line in the then block looks a little scary, but actually it’s very simple, lets dissect it.

1 * dao.get(id) >> new User(id:id, name:"James", age:27)

This line is setting an expectation on the mocked dao. We’re saying that we expect 1 (and only 1) invocation on the dao.get() method, that invocation must be passed id (which we defined as 1 earlier). Still with me? Good, we’re half way.

The double chevron “>>” is a spock feature, it means “then return”. So really this line reads as “we expect 1 hit on the mocked dao get(), and when we do, return a new User object”

You can also see that I’m using named parameters in the constructor of the User object, this is another neat little feature of groovy.

The rest of the then block are just assertions on the result object, not really required here as we’re doing a straight passthrough on the dao, but gives an insight as to what you’d normally want to do in more complex examples.

The implementation.

If you run the test, it’ll fail, as we haven’t implemented the service class, so lets go ahead and do that right now, its quite simple, just update the service class to the following:

public class UserService {

    private UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public User findUser(int id){
        return userDao.get(id);
    }
}

Run the test again, it should pass this time.

Stepping it up

That was a reasonably simple example, lets look at creating some users. Add the following into the UserService:

public void createUser(User user){
        // check name

        // if exists, throw exception

        // if !exists, create user
    }

Then add these methods into the UserDao

public User findByName(String name);
    public void createUser(User user);

Then start with this test

def "it saves a new user"(){
        given:
        def user = new User(id: 1, name: 'James', age:27)

        when:
        service.createUser(user)

        then:
        1 * dao.findByName(user.name) >> null

        then:
        1 * dao.createUser(user)
    }

This time, we’re testing the createUser() method on the service, you’ll notice that there is nothing returned this time.

You may be asking “why are there 2 then blocks?”, if you group everything into a single then block, Spock just asserts that they all happen, it doesn’t care about ordering. If you want ordering on assertions then you need to split into separate then blocks, spock then asserts them in order. In our case, we want to firstly find by user name to see if it exists, THEN we want to create it.

Run the test, it should fail. Implement with the following and it’ll pass

    public void createUser(User user){
        User existing = userDao.findByName(user.getName());

        if(existing == null){
            userDao.createUser(user);
        }
    }

Thats great for scenarios where the user doesn’t already exist, but what if it does? Lets write so co…NO! Test first!

    def "it fails to create a user because one already exists with that name"(){
        given:
        def user = new User(id: 1, name: 'James', age:27)

        when:
        service.createUser(user)

        then:
        1 * dao.findByName(user.name) >> user

        then:
        0 * dao.createUser(user)

        then:
        def exception = thrown(RuntimeException)
        exception.message == "User with name ${user.name} already exists!"
    }

This time, when we call findByName, we want to return an existing user. Then we want 0 interactions with the createUser() mocked method.

The third then block grabs hold of the thrown exception by calling thrown() and asserts the message. Note that groovy has a neat feature called GStrings that allow you to put arguments inside quoted strings.

Run the test, it will fail. Implement with the following at it’ll pass.

public void createUser(User user){
        User existing = userDao.findByName(user.getName());

        if(existing == null){
            userDao.createUser(user);
        } else{
            throw new RuntimeException(String.format("User with name %s already exists!", user.getName()));
        }
    }

I’ll leave it there, that should give you a brief intro to Spock, there is far more that you can do with it, this is just a basic example.

Snippets of wisdom

  • Read the spock documentation!
  • You can name spock blocks such as given:”Some variables”, this is useful if its not entirely clear what your test is doing.
  • You can use _ * mock.method() when you don’t care how many times a mock is invoked.
  • You can use underscores to wildcard methods and classes in the then block, such as 0 * mock._ to indicate you expect no other calls on the mock, or 0 * _._ to indicate no calls on anything.
  • I often write the given, when and then blocks, but then I start from the when block and work outwards, sounds like an odd approach but I find it easier to work from the invocation then work out what I need (given) and then what happens(then).
  • The expect block is useful for testing simpler methods that don’t require asserting on mocks.
  • You can wildcard arguments in the then block if you don’t care what gets passed into mocks.
  • Embrace groovy closures! They can be you’re best friend in assertions!
  • You can override setupSpec and cleanupSpec if you want things to run only once for the entire spec.

Conclusion

Having used Spock (and groovy for testing) on various work and hobby projects I must admit I’ve become quite a fan. Test code is there to be an aid to the developer, not a hinderance. I find that groovy has many shortcuts (collections API to name but a few!) that make writing test code much nicer.

Check out the Github Gist here

Project Euler, problem 1, multiple factors

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

To solve this in a brute force manner, we can count up to 1000, for each number we check to see if it divides into 3 and 5 leaving no remainder. If it does, they we add that number into our running total.

Heres my solution using Java.

public class Problem1 {

    public static void main(String[] args) {
        System.out.println(solve(1000));
    }

    public static int solve(final int subject) {
        int sum = 0;
        for (int i = 0; i < subject; i++) {
            if ((i % 3 == 0) || (i % 5 == 0)) {
                sum += i;
            }
        }
        return sum;
    }
}

The answer is 233168

An intro to Node.js, building a URL shortener

Node has been on my todo list of things to investigate for a little while now, whilst I don’t have much background in javascript, after constantly hearing about it when I was working at O2 Telefonica, I thought I better see what the fuss is all about.

To quote the Node website: “Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.”

The best way to learn how to use a new technology is to try and build something with it. I’ve chosen to build a URL shortener because its a relatively straightforward concept; you take a URL and store it against a key, then when that key is requested, you redirect to the original URL. These are commonly used on twitter and other social media where you are limited to sharing small messages, as it enables you to have short URLs (normally on short domains such as bit.ly) refer to a longer URL that you want to share.

I’ve decided to use express, which is a framework for node js for building web applications, I’ve also chosen to use Jade for my views, which is a node template engine for generating HTML views.

Lets get started.

Firstly, you’ll need to setup a development environment if you haven’t already got one. I’m using IntelliJ IDEA and am fortunate that there is node js support that will help you create a new project.

If you’re not using IDEA, or want to create a node project yourself, you’ll need to create a packages.json file, delcare your dependencies, and run npm install, then you can create the app.js and start developing. You can find more info on how to do that on the express documentation.

Creating the short URL

When the user first lands on the site they are present with a form where they can shorten a URL. As we can see from this line in the main.js file the index route is displayed for requests on the base URL:


app.get('/', routes.index);

This refers to the index.js file in the routes directory, which in turn renders a view back to the client, by doing the following:


exports.index = function (req, res) {
 console.log('Displaying index page where users can enter a long url')

res.render('index');
};

Node automatically knows that it needs to render a jade view, because we told it earlier where the views are located, and what view engine to use when we declared these in our main.js:


app.set('views', path.join(__dirname, 'views'));
 app.set('view engine', 'jade');

A quick peak at our index jade file and we can see that we have a very basic form that accepts a single text field and posts this to the /create endpoint


extends layout

block content
 h1= title
 h1.text-center Node.js URL Shortener

div.container
 div.content
 div.well
 form.form-horizontal(name="input", action="/create", method="post")
 div.form-group(align='center')
 p
 input(type="text", name="urlToShorten", class="form-control", placeholder="Enter a URL")
 p
 input(type="submit", value="Shorten", class="btn btn-primary")

Diving back to our main js file, we can see that requests (specifically POST requests) are handled by the createShort function in the shorty.js file:


app.post('/create', shorty.createShort);

This is where the magic happens. Firstly, we need to get hold of the URL that the user submitted in the form, that is relatively easy as we can get it directly off the request body, as shown in the below code snippet. Next we do a quick check to see if its null and display a message to the user if they didn’t provide a URL. If they have provided a URL, we check to see if we need to prepend it with http://., then we create a shortcode for that URL and render a page that will display the link for the user to share.


/*
 * POST creates a short url from a long url
 */
 exports.createShort = function (req, res) {

var urlToShorten = req.body.urlToShorten;
 if (!urlToShorten) {
 console.log('Request did not contain a url to shorten, please provide urlToShorten');
 res.render('short', {message: 'Request did not contain a url to shorten, please provide urlToShorten'});
 } else {

console.log("Request to shorten " + urlToShorten);

urlToShorten = addhttp(urlToShorten);
 var baseUrl = 'http://' + req.app.get('hostname') + '/';

var shortCode = createShortCode(urlToShorten);
 res.setHeader('Content-Type', 'text/html');
 res.statusCode = 200;
 res.render('short', { shortUrl: baseUrl + shortCode });
 }
 };

The reason for prepending the protocol onto the link, is because this is required for the Location header on a redirect which we will serve when the short URL is requested, as mentioned in the HTTP RFC spec, this needs to be an absolute URI. This is a bit of a dirty hack and I’m not that happy with it. Ideally, I would like to create a URL object with the string the user has supplied, regardless of what prefix it has, I was hoping that the node url functions would help with that, but it seems that when parsing and then formatting the URL, it doesn’t retain the protocol. It is also entirely possible that I’m not using the API correctly, perhaps someone can comment, or suggest a better mechanism for this.

To create the short code, we generate a random alphanumeric string of 5 characters, this is quite a simple function. We then add the short code and URL to a collection so we can look them up when the user requests the short code.

Redirecting to the original URL

Looking back at the main js file, we can see another route. This is used when a user requests their short url.


app.get('/:short', shorty.getLong);

Firstly, we grab the short code from the request path. We have to strip the first character as that will be a slash, such as “/ABC123”. Then we find the long URL that the short code refers to by looking in the collection where we stored it earlier. After that, its just a case of writing a 302 redirect response with the Location header set to the long URL, thats it really.


/*
 * GET retrieves long url from short url
 */
 exports.getLong = function (req, res) {

// grab the path and strip the leading slash
 var shortCode = req.path.substring(1);

console.log("Fetching URL indexed by " + shortCode);
 var theLongUrl = shortToLong[shortCode];

console.log('Short code ' + shortCode + " refers to " + theLongUrl);

console.log("redirecting to " + theLongUrl);
 res.writeHead(302, {'Location': theLongUrl});
 res.end();
 };

Conclusion

Whilst I don’t have much of a background in front end web development, my javascript skills are pretty basic, saying that, node js is quite intuitive and the documentation is good enough to get you through the basics. Node has quite a small learning curve (at least for the basics), coupled with StackOverflow for reference, you can build web apps relatively quickly and easily.

Would I use Node again? Absolutely, however I think it’d be far better suited to projects requiring a substantial number of concurrent users, such as web chat applications, or for gaming backends. For building web applications I’d probably choose Grails as I’m more familiar with Java and Groovy, plus you get all the benefits of Spring. Scaffolding is also great.

Node would be a great choice for building development stubs, I’ve built several mobile apps that require backends, for testing, you want a stubbed backend that returns canned responses. You can do this incredibly easy in node by using returning static files served up as JSON responses, plus its very lightweight so you can integrate into your CI nicely.

You can see a live demo of this on my cloudbees account here.

Resources

Robots! Part 2, the android client

Continuing on from my previous post, I’ve created an android client that I can use to send commands to my python server.

Ultimately I want to be able to control the robot remotely, the best way to do this would be to control the robot from a tablet or a phone which communicates wirelessly with the pi via bluetooth or wifi. In my previous post I described setting up a python application that will run on the raspberry pi and listen for commands. All I needed to do was to create a very basic android interface that can send commands to the raspberry pi.

The robot I intend to build will be based on tracks instead of wheels, there are many benefits to this but the most significant is that from an engineering perspective is that its much easier to build. A car needs forward and backwards drive, but also sideways drive for the front axle. In my opinion, it is far simpler to have a tracked vehicle with a motor controlling each side. When both motors are turned in the same direction the vehicle moves forward or backwards, and when the motors run in opposite directions the vehicle will turn on the spot.

My app interface mimics the layout of the vehicle itself, with an up and down button on the left and right hand side of the screen, as shown below.

Arrow buttons for controlling robots tracks

Arrow buttons for controlling robots tracks

You can see the code for this layout on the github repo here.

I want the user to be able to hold a button and the motor will run until they take their finger off. For this I’ve attached listeners on the buttons that will listen for the key up and key down events. It will send separate events for starting and stopping the motors, like so:

        Button leftForward = (Button) findViewById(R.id.leftForward);

        leftForward.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        sendCommand(leftForwardCommand + "-Start");
                        break;
                    }
                    case MotionEvent.ACTION_UP: {
                        sendCommand(leftForwardCommand + "-Stop");
                        break;
                    }
                }
                return false;
            }
        });

As the sendCommand needs send a message over the network, I need to take this off the main UI thread otherwise I’d get an exception such as:

android.os.NetworkOnMainThreadException

To take this off the UI thread, I simply move the sending of the command into an AsyncTask, like so:

private void sendCommand(String command) {
        new SendCommandTask().execute(command);
    }

    class SendCommandTask extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... commands) {
            String command = commands[0];
            try {
                //TODO: make this configurable inside the app
                Socket socket = new Socket("192.168.0.6", 3033);
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                out.println(command);

                Log.d(TAG, "Successfully sent " + command);
            } catch (IOException ioe) {
                Log.d(TAG, "Unable to send command", ioe);
            }
            return null;
        }
    }

Now if I run the python server and then send press the buttons in the app, I see this output from the python application.

Server listening on port 3033...
...L-FORWARD-Start…..L-FORWARD-Stop….

Thats all for now, you can access this code on my github repository. Next post will either be in relation to building the robot, or using the BrickPi APIs.

Robots! (part 1)

Inspired by the android controlled lego robots I saw at DroidCon UK this year, and with difficulty finding a use for my raspberry pi, I’ve decided to have a go at building a robot that I can control via an android app. Having a 24 hour flight home from Australia at the weekend, I’ve had plenty of time to think about how I might approach this task (or challenge as I refer to it as I’ve no prior experience with robotics / socket programming).

Lego robot powered by the BrickPi

My plan is to have a python socket server running on the pi. This will provide a socket that an android client can invoke commands on. This python server will also interact with the python scripts that the BrickPi uses to control lego motors.

Whilst most of my experience revolves around Java, I’ve opted for python for the following reasons

  • Python is supported on the pi out of the box, no need to mess around with installing Java
  • The BrickPi has support for Python (and C)
  • I feel like learning something new

Baby steps…

Starting simple, I thought it best to create a simple script that listens on a socket, and then create a client that sends it some data to print out to the console. Once I have this working I can expand on it and make the client more sophisticated (an android app for example) and also enhance the server so it can handle different types of commands.

Server
There are plenty of example python scripts online, I found a good one here and tweaked it slightly to remove the parts I don’t want. (full credit to pythonadventures!)

#!/usr/bin/env python
# server.py

import socket
import select
import Queue
from threading import Thread
import sys

class ProcessThread(Thread):
    def __init__(self):
        super(ProcessThread, self).__init__()
        self.running = True
        self.q = Queue.Queue()

    def add(self, data):
        self.q.put(data)

    def stop(self):
        self.running = False

    def run(self):
        q = self.q
        while self.running:
            try:
                # block for 1 second only:
                value = q.get(block=True, timeout=1)
                process(value)
            except Queue.Empty:
                sys.stdout.write('.')
                sys.stdout.flush()
        #
        if not q.empty():
            print "Elements left in the queue:"
            while not q.empty():
                print q.get()

t = ProcessThread()
t.start()

def process(value):
    print value

def main():
    s = socket.socket()
    host = socket.gethostname()
    port = 3033
    s.bind((host, port))

    print "Server listening on port {p}...".format(p=port)

    s.listen(5)                 # Now wait for client connection.

    while True:
        try:
            client, addr = s.accept()
            ready = select.select([client,],[], [],2)
            if ready[0]:
                data = client.recv(4096)
                t.add(data)
        except KeyboardInterrupt:
            print
            print "Stopping server."
            break
        except socket.error, msg:
            print "Socket error %s" % msg
            break

    cleanup()

def cleanup():
    t.stop()
    t.join()

if __name__ == "__main__":
    main()

The socket is bound to a port, and then continually listens for incoming data. Once some data is received, it is added onto a queue, which is then sequentially executed.

Client
The client is is fairly straightforward, it involves opening a connection on a socket and writing data to it, a few lines of Java code.

public static void main(String[] args) throws IOException {

        InetAddress address = InetAddress.getLocalHost();
        Socket socket = new Socket(address, 3033);

        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

        System.out.println("Sending message...");

        osw.write("Hello!");
        osw.flush();
    }

Thats it for now, you can checkout my code on github (or just copy/paste the above) and run the client and server and see it in action.

I’ll start on the client next..

Selecting partial elements of mongo db documents

By default, when you find documents on mongo it returns the entire document, similar to what SELECT * FROM TABLE; would do in a relational world.

> db.user.find().pretty()
{
	"_id" : ObjectId("5217705cc2e6fc761c0b5371"),
	"userId" : "james",
	"age" : 27,
	"favouriteVideoGame" : "Skyrim"
}

You can retrieve partial document info by using something known as a projection (see mongo docs here). Use find() with an empty query, but specify the fields you want from the document like so:

> db.user.find({}, {userId:true})
{ "_id" : ObjectId("5217705cc2e6fc761c0b5371"), "userId" : "james" }

> db.user.find({}, {userId:true, age:true})
{ "_id" : ObjectId("5217705cc2e6fc761c0b5371"), "userId" : "james", "age" : 27 }

For the Java devs using Spring data, you can do a similar thing using the Query APIs, notably the fields().include() (docs here):

Query q = Query.query(Criteria.where("userId").is(userId));
q.fields().include("age");

User score = mongoTemplate.findOne(q, User.class, "user");

What I thought of “Instant Android Fragmentation Management How-to”


I was recently contacted by the marketing team from Packt Publishing and asked if I could write a review for one of their new ebooks, so here it is!

This book gives a brief yet comprehensive overview of some of the processes you can follow to improve your applications chance of working on the varying versions of android that are currently in existence.

Having developed apps that work perfectly fine on my Galaxy S2 2.3.3, only to find they don’t work on a hardware identical S2 with 4.0, I certainly feel the pain of OS fragmentation!

The book discusses some of the approaches you can take using the android compatibility library, fragments, loaders and action bars that enable you to write against the latest APIs but still have a good chance of having your app work on previous versions.

Things I liked about this book

  • A short and focused read, I got through it in around an hour.
  • Lots of code examples and references to external reading material.
  • The reference to ActionBarSherlock I felt was very much needed, as always if there are open source alternatives that work better, we should adopt them rather than struggle!

Things I didn’t like

  • I did feel that having some more screenshots would have helped emphasised the topic in discussion, whilst there were some screenshots throughout I did constantly find myself thinking “what should this actually look like?”
  • The chapters could have done with a more expanded overview, particularly the loaders section as it jumped right into creating one before explaining what it is, and how it differs from other non-UI asynchronous mechanisms like async tasks.

All in all I rate this as 4/5. The ebook is very reasonably priced and for the price of a few beers it’d certainly worth it, even for the discussions on ActionBarSherlock and Fragments. If your struggling to support multiple android versions, this book is a good starting point for you.