The Roomba (Part 1 of 2)

As some of you might have seen on twitter we had a device laying around at the Nabto headquarters with Nabto written all over it.


Today is the grand reveal of our Roomba hack!

full_roomba_tilt.jpg

I would like one hacked Roomba, please!

Like the CoffeePi this project was rather substantial so the Roomba hack will be split in two parts.

In this part we will be dealing with a common use case, namely to start a clean cycle remotely. For this we will go through

  • Hardware hacking and wiring
  • Adding the Nabto framework

Part 2 will deal with the fun stuff

  • Turn the Roomba into a remote controlled car
  • Add soundeffects
  • Add sensor data
  • Add video streaming

Hardware hacking and wiring

Roombas manufactured after October 2005, have a Serial Command Interface (SCI) for which some great documentation (here and here) is given by the company itself. Reading these revealed that everything on the Roomba is configurable through this interface and it is indeed awesome that the company itself encourages the hacking community. So why not get some Nabto running on our Roomba?
The model we have is a 5xx series. For our specific model, 581, the serial port was hidden underneath a plastic shroud which we tore right off. Underneath we locate the 7 pin SCI which look like this (from the documentation)

sci_pinout.png

We will be using pin 3, 4, 5 and 6 for communication. For this, we settled on using a 5V (!) USB serial cable. If you plan on using a 3.3V serial cable, you will need a logic level converter.

Furthermore, we want the Roomba to truly be standalone so we need some way of converting the unregulated battery voltage of 14.4 V to 5V. My simple, cheap go to solution for situations like this is an USB car charger which can be had for around 1$. They are built for variable voltage inputs of everything from 12V to 24V so they will work just fine for our Roomba project.

car_charger.png

Our 1$ USB car charger all wired up

We then fit the + wire of our USB car charger to pin 1 or 2 on the Roomba and  the + wire to pin 7 on the Roomba, for ground. In total, our wiring should look like this

roomba_wiring

Full Roomba wiring. Please note that the right hand side names and colours refer to the serial cable names. The left hand side refer to the matching colours and +, – of the USB car charger.

Adding the Nabto framework

To use the USB serial cable I wrote some small helper functions, which we will use for waking, initialising and writing/reading to/from the Roomba.

First, we need to initialise our serial connection (which we only need to do once)


char *portname = "/dev/ttyUSB0";

fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
    NABTO_LOG_INFO(("error %d opening %s: %s\n", errno, portname, strerror (errno)));
    return 0;
}
else{
    NABTO_LOG_INFO(("Opening %s: %s\n", portname, strerror (errno)));
}

    set_interface_attribs (fd, B115200, 0);  // set speed to 115,200 bps, 8n1 (no parity)
    set_blocking (fd, 0);                // set no blocking

We continue by waking up the Roomba from sleep which we do by setting the Device Detect (DD) low for say, 100ms, (as stated in the documentation). This is done by controlling the RTS line of our serial.

// Wake Roomba
setRTS(fd, 0);
usleep(100000); //0.1 sec
setRTS(fd, 1);
sleep(2);

The Roomba is then ready for commands! The code for inputting a virtual clean button press is

// Start clean cycle
char clean[] = {135};
write(fd, &clean, sizeof(clean));
usleep ((sizeof(clean)+25) * 100);

The actual command, or opcode, is 135, taken from the documentation. To stop the cleaning process, we can either issue the clean command again or put the Roomba into sleep mode. To avoid ambiguity when sending commands, I chose the latter, which has the opcode 133.

For now, this is all we need but we will explore many more (much more fun) commands in part 2 (we will update with a link here when posted).

Since we have written the helper functions in pure C, this code can be compiled for multiple devices. I tested it on my laptop running Linux Mint 17.3 Cinnamon 64-bit and on a Raspberry Pi 2 running Raspbian Jessie. It should compile just fine on at least all versions of Raspberry Pi and possibly anything else running Linux with the required libraries.

For our standalone Roomba, we of course settled on using the Pi, which we first set up for wireless network access (check an easy howto here) followed by getting the uNabto files and compiling for the Raspberry Pi. This is done by issuing the following commands one line at a time

sudo apt-get install git
sudo apt-get install cmake
git clone https://github.com/MarcusTherkildsen/unabto
cd unabto/apps/raspberry_pi_roomba
cmake .
make

We now have uNabto compiled on our Pi!
All that is left to do is to create a new device at developer.nabto.com. Simply Add Device and copy the newly created Key 

We now return to the Raspberry Pi and issue the following command for initiating the Nabto software

sudo ./unabto_raspberrypi -d "id".demo.nab.to -s -k "key"

You should see a couple of lines of output ending with

13:40:47:548 unabto_attach.c(575) State change from WAIT_GSP to ATTACHED

Which means uNabto is successfully up and running!
That’s all, we can now remotely start a cleaning cycle and stop it again by opening a browser and access id.demo.nab.to in your browser. You will be met with a log in page, simply click Guest, followed by an image like this

html_dd_screenshoot_roomba.png

uNabto Roomba html device driver

Sliding the switch to either side will now trigger the clean cycle on our Roomba, check it out!

If you suddenly got the urge to create your own IoT device using Nabto feel free to check out nabto.com and sign up for a developer account developer.nabto.com, it is all free and you can create and manage 10 devices. This is also where you can find the SDKs and other Nabto software!

The full code for this simple Roomba uNabto hack can be found at github.

Stay tuned for part 2 where we’ll have some fun!

Dartino + uNabto

The experimental open-source project Dartino enables you to write software for embedded systems using the modern Dart language and a set of libraries, that let you be highly productive. So why not add another powerful library? Thanks to  improvements to the FFI library in the latest Dartino SDK, we are now able to use the uNabto framework from within Dartino!

dartino-logo

Note: Due to remaining limitations of the Dartino FFI library this is currently only working on a local PC. Thanks to the Dartino team this might be resolved in the near future…stay tuned!

Why use uNabto in your Dartino solution?

Have you ever thought about connecting to your embedded system running Dartino from outside your local network without nerve-racking router and firewall configurations or heavy and intransparent cloud services? Running the uNabto server on your embedded system, you can establish a fast and secure Peer-to-Peer connection using only a static ID – from everywhere, no matter what is in between.

So how does Nabto do this? The drawing below gives a brief overview. Your embedded system represents the Device running the uNabto server. As soon as it connects to the internet it identifies itself at the Nabto Basestation, using its unique ID. If a Client wants to connect to the embedded system, a connect request with the ID is sent to the Basestation, and a direct connection to the device is established. A client can be a HTML page running in a desktop browser extension (IE, Firefox) or the Nabto Mobile App (iOS, Android), or a custom Nabto API Client. If you prefer Cordova also check out our recently released Nabto Cordova Plugin.

nabto-security

Get the sample application

We published a sample application including the uNabto Dartino library on GitHub. In order to set it up, follow the three steps below.

Step 1: Clone the repository

$ git clone --recursive https://github.com/nabto/unabto-dartino
$ cd unabto-dartino

Step 2: Download and unzip the latest Dartino SDK

Linux:
$ curl "https://storage.googleapis.com/dartino-archive/channels/dev/raw/0.4.0-dev.0.0/sdk/dartino-sdk-linux-x64-release.zip" -o "/tmp/dartino-sdk.zip"
$ unzip /tmp/dartino-sdk.zip

Mac OS:
$ curl "https://storage.googleapis.com/dartino-archive/channels/dev/raw/0.4.0-dev.0.0/sdk/dartino-sdk-macos-x64-release.zip" -o "/tmp/dartino-sdk.zip"
$ unzip /tmp/dartino-sdk.zip

Step 3: Build the C library

$ mkdir build
$ cd build
$ cmake ..
$ make
$ cd ..

Use the sample application

The sample application acts as an embedded device that controls a virtual living room light. To connect to the application we first need to assign a unique Device ID and a pre-shared encryption Key to it. You can get them from developer.nabto.com after adding a new Device. Both id and key are passed as strings to the constructor of the uNabto server:

main() {
  // Configure the uNabto server with a server ID and a pre-shared key obtained
  // from `developer.nabto.com`.
  var unabto = new UNabto("devicename.demo.nab.to", "35d0dca...");

You can now fire up the application on you local PC with the Dartino tool:

$ ./dartino-sdk/bin/dartino run src/app.dart

You should see a log printout similar to this:

15:18:54:118 unabto_common_main.c(127) Device id: 'devicename.demo.nab.to'
15:18:54:118 unabto_common_main.c(128) Program Release 123.456
15:18:54:118 unabto_app_adapter.c(698) Application event framework using SYNC model
15:18:54:118 unabto_context.c(55) SECURE ATTACH: 1, DATA: 1
15:18:54:118 unabto_context.c(63) NONCE_SIZE: 32, CLEAR_TEXT: 0
15:18:54:118 unabto_common_main.c(206) Nabto was successfully initialized
15:18:54:118 unabto_context.c(55) SECURE ATTACH: 1, DATA: 1
15:18:54:118 unabto_context.c(63) NONCE_SIZE: 32, CLEAR_TEXT: 0
15:18:54:118 unabto_attach.c(787) State change from IDLE to WAIT_DNS
15:18:54:118 unabto_attach.c(788) Resolving dns: devicename.demo.nab.to
uNabto version 123.456.
15:18:54:330 unabto_attach.c(809) State change from WAIT_DNS to WAIT_BS
15:18:54:353 unabto_attach.c(474) State change from WAIT_BS to WAIT_GSP
15:18:54:364 unabto_attach.c(266) ######## U_INVITE with LARGE nonce sent, version: - URL: -
15:18:54:375 unabto_attach.c(575) State change from WAIT_GSP to ATTACHED

The uNabto server is now ready and you can connect to it from any client. When entering you device ID into your browser or Nabto App, you can see the uNabto Demo client. Using the light switch you can now turn the virtual living room light on and off from everywhere!

dartino-firefox

Light 1 turned ON!
Light 1 turned OFF!

For demonstration purposes, the example application closes the server connection after ~10 seconds.

The sample application in detail

The sample application is quite straightforward since all complicated interfacing to the native C library is done in the uNabto library. We only need to include it with

import 'unabto.dart';

In the main() function we construct the uNabto server object by passing the Device ID and the pre-shared Key as parameters. However, the server is started later with the init() function. You also might want to check if there were any errors doing that.

  var unabto = new UNabto("devicename.demo.nab.to", "35d0dca...");

  // Get version information.
  print("uNabto version ${unabto.version}.");

  // Attempt to init and start the server.
  int result = unabto.init();
  if (result != 0) {
    print("Init error: $result.");
  } else {

To handle incoming events from the client we register handler functions for every query ID. We’ll come back to the handlers later on.

    // Register two event handlers for the `light_write.json` and
    // `light_read.json` queries.
    unabto.registerReceiver(1, onLightWrite);
    unabto.registerReceiver(2, onLightRead);

You can now do other stuff. The sample application just sleeps for 10 seconds to demonstrate how to close the uNabto server in the end.

    // This is where the main app code would usually run.
    // In this sample we just sleep a bit.
    sleep(10000);

    // Clean-up: Deallocate foreign memory and functions.
    unabto.close();

The following handler takes care of the query with ID #1. It reads the light’s ID and the light’s new state from the incoming readBuffer. The new state is applied to the virtual light. Afterwards, it returns the new state to the client by writing it to the outgoing writeBuffer.

void onLightWrite(UNabtoRequest appRequest, UNabtoReadBuffer readBuffer,
    UNabtoWriteBuffer writeBuffer) {
  // Read the request parameters.
  int lightId = readBuffer.readUint8();
  int lightOn = readBuffer.readUint8();

  // Set the light state.
  int lightState = setLight(lightId, lightOn);

  // Write the response parameter.
  writeBuffer.writeUint8(lightState);
}

The following handler takes care of the query with ID #2. It reads requested light’s ID from the incoming readBuffer, retrieves the state of the virtual light and returns the light’s state to the client by writing it to the outgoing writeBuffer.

void onLightRead(UNabtoRequest appRequest, UNabtoReadBuffer readBuffer,
    UNabtoWriteBuffer writeBuffer) {
  // Read the request parameters.
  int lightId = readBuffer.readUint8();
  int lightState = readLight(lightId);

  // Write the response parameter.
  writeBuffer.writeUint8(lightState);
}

Diving deeper

If you want to explore the whole available interface of the uNabto library have a look at it on GitHub. It also demonstrates how to use the Dartino FFI library to access a foreign library and work with its structures and byte arrays.

Finally, if you want to modify the underlying uNabto C library checkout the files in this directory. For example, In the unabto_config.h you can turn off the logging or disable remote connections.

Snappy Ubuntu Core + uNabto

Today we will have a look at Snappy Ubuntu Core, why it is nice, in principle, and why it still has some way to go before it will really be useful in reality.

Snappy Ubuntu Core, the basics

snappy

Their logo represents the blocks (snaps, kernels, daemons, etc.) that make up a full system.

Snappy Ubuntu Core is “a new, transactionally-updated Ubuntu for IoT devices, clouds and more”. In other words, it’s a new rendition of Ubuntu with some new features as well as a lot of features removed, which we will get back to. It should be noted that the system is also referred to as simply Ubuntu Core (not even the name is set in stone yet) so you will see both ways of writing it in this post.
The main selling point of this free product is that each app, hereafter denounced snaps, are independent blocks, ideally with no external dependencies. This has the huge advantage that a snap can be installed or removed without breaking anything else on the machine. The system can thus be seen as being build by legos, individually separated but put together into a full system.

Installing Ubuntu Core

Getting a copy of Ubuntu Core is fairly straightforward if you just follow the instructions laid out here. As you will quickly notice, Ubuntu Core is available for quite a number of devices although only the Raspberry Pi 2 is supported out of the Pi family at the moment. For IoT projects it does not make a whole lot of sense to run a virtual Ubuntu Core image on a desktop system, but for developing I used it extensively.

So either run a virtual machine using kvm or get your Pi 2 up and running if you feel like following along!

Installing a snap

Once we have Ubuntu Core up and running we can either SSH into it by issuing ssh -p 8022 ubuntu@localhost (virtual kvm) or ssh ubuntu@webdm.local (Pi2) both with the standard password: ubuntu.
Once in, let’s start by getting an overview of the stuff already installed on the machine. We do this by issuing

$ snappy list

The listed items can be either kernels, daemon services or executable binaries, basically everything that makes up our environment.

You should see something like
Name Date Version Developer
ubuntu-core 2016-01-28 7 ubuntu
webdm 2016-01-28 0.11 canonical
pi2 2016-01-28 0.16 canonical

First of,  version 7 of the ubuntu-core is quite old so we run

$ sudo snappy update

to update the system. If webdm is not installed already, then we also install it by issuing

$ sudo snappy install webdm

This service basically gives us a graphical user interface to the Snappy Store which we can access if we are on the Pi2 by opening a browser (on desktop machine) and going to webdm.local:4200.

webdm_store

The Snappy store

Here we basically see the graphical presentation of what we just saw in the command line. We can also see the available snaps for this architecture.
Going back to the command line we can also get a list of all the available snaps for the current architecture by issuing

$ snappy search '*'

At the time of writing this (10th of May 2016) there are exactly 100 snaps available for the Pi2 and 92 for amd64 so the framework is still in its infancy. To search for a specific app we try searching for the unabto snap

$ snappy search unabto

if successful we can install it as before, by issuing

$ sudo snappy install unabto

After it installs, we can try issuing

$ unabto.unabto

which will work perfectly on a 64 bit machine but on the Pi2 we will see this error

$ wiringPiSetup: Must be root. (Did you forget sudo?)

trying the same command with sudo will result in

$ wiringPiSetup: Unable to open /dev/mem: Operation not permitted

to find out why, we need to have a look at how snaps are created

Creating a snap

As mentioned, the number of available snaps to install is still fairly limited and so is the documentation for creating snaps. Through the iterations of the build tool and the Ubuntu Core itself, the specific commands and instructions have changed and there is thus no consensus on how to actually do essential things. Many of the examples given cannot compile with my version of their build tool, called snapcraft.
But still, we march on and we will begin with the way Ubuntu Core wants you to use it.
On my amd64 machine I installed snapcraft by following the instructions here

$ sudo add-apt-repository ppa:snappy-dev/tools
$ sudo apt-get update
$ sudo apt-get install snapcraft

To get a feel of how snapcraft “crafts” programs into snaps we issue

$ snapcraft help plugins

to see all the steps that snapcraft does behind the scenes. For future reference the version I used was 1.1.0 on Linux Mint 17.3 Cinnamon 64-bit.
The only thing we really need to get something going for us is a snapcraft.yaml file as well as an icon. snapcraft.yaml contain instructions for snapcraft so that it knows what to do. In our simple example we write (you can find this code on github as well)

# Notice! Name cannot contain underscore
name: unabto-test
version: 0.1
summary: some summary
description: some description
vendor: mt@nabto.com
icon: icon.png

# Needed packages. If not found on system, snapcraft will install them
build-packages: [openssl, cmake, git]

# To be able to call the binaries in our snap directly from the command line we define binaries
binaries:
  # note, the name to write for
  # executing the binary below it. These two names cannot
  # be the same !
  unabto:
    exec: bin/unabto_raspberrypi
    # We have to allow the bin/binary to open
    # sockets and the like. For this, we use set permissions using the plugs term
    plugs: [network-bind]

# The parts the snap will consist of
parts:
  unabto:
    plugin: cmake
    source: git://github.com/nabto/unabto.git

Note that the above example is NOT exactly how most of the examples found in the Ubuntu Core github  are made at the moment (most of them cannot compile with my version of snapcraft). I suspect this is due to differences between releases and will probably be resolved in time.
Having the snapcraft.yaml file and icon.png in the same folder, now comes the magic!
Simply issue

$ snapcraft

Which will go through the stages laid out in $ snapcraft help plugins. You will notice that the directory now contain
unabto, parts, stage and snap as well as what we are actually interested in, unabto_0.1_amd64.snap, which is our snap! So yeah, that was really all we needed to create a standalone snap, wow !

Now we would like to check out how it works. You will no doubt have noticed the _amd64 in the filename, meaning that this snap is for an Ubuntu Core 64 bit machine. The reason for this is that snapcraft does not support cross compiling (I could not get it to work, at least) and we will later see how to circumvent this.
For now, we transfer and install our newly created snap on our virtual machine by issuing

$ snappy-remote --url=ssh://localhost:8022 install unabto_0.1_amd64.snap

This should run without any problems. We can check if the snap was succesfully installed by sshing into the virtual machine and issue $ snappy list as before. unabto should now appear on the list and we can run the binary we specified in the snapcraft.yaml file by issuing

$ unabto-test.unabto -d id -s -k key

where id and key is created at developer.nabto.com
If everything went as it should you will see a few lines of output ending with

$ 00:04:32:160 unabto_attach.c(575) State change from WAIT_GSP to ATTACHED

which is a sign of success !
We can now access the id in a browser and thus remotely control whatever unabto is running on, great success !
To see some real life uses please check out The CoffeePi (Part 1 of 2)The CoffeePi (Part 2 of 2) and The SunPi control center

Creating a multi architecture snap and creating some actual value into it

Now, I already said snapcraft can’t do crosscompiling so we need to do something else. The easiest way is to create a binary the old fashioned way for each architecture. For this we simply need a compiler for that architecture, as the name suggest. I used this to compile for the raspberry pi. Simply download it and go to the unabto/apps/raspberry_pi folder. If you don’t already have a copy of the uNabto SDK, you can grab one here. In this folder we issue

$ export CC=path/to/raspi_gcc

before issuing the usual

$ cmake .

and

$ make

We can check if the resulting binary really was compiled for an arm board by issuing

$ file raspberry_binary

which should return something like

$ unabto: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, BuildID[sha1]=cbb7dfe8560ba3e63dfffa621cad56f301fff1e7, not stripped

Make sure your main snap folder contain a bin, lib and meta folder as can be seen in the uNabto Ubuntu Core github repository. In bin we create a folder for each architecture as well as an executable that makes sure which to choose depending on the device. You can check that out on github as well. In meta we need an icon, a readme.md and a file almost like before, but this time called package.yaml

name: unabto
vendor: Marcus Therkildsen
architecture: [amd64, armhf]
icon: meta/icon.png
version: 0.1

binaries:
- name: bin/unabto

This time we notice that we defined “architecture: [amd64, armhf]” which should list all the archs we plan on incorporating in our multisnap. Now we can simply issue

$ snappy build

which will create unabto_0.1_multi.snap. This snap can now be installed on all the architectures we compiled each package for. This is done in the same way as before using the snappy-remote command. Again we can run it by issuing

$ unabto.unabto -d id -s -k key

and voila, we now have a working multi arch snap.
Still, the snap doesn’t really do anything other than controlling a dummy switch in the unabto code

Adding functionality

So what if we wanted to use the gpio pins on the RPi2?
Well, all functionality that a snap should have should be contained in the snap itself. That is, after all, the main selling point of Ubuntu Snappy Core. If you had the audacity to try to do anything on Ubuntu Snappy Core anyway you would quickly realise that

curl
wget
apt-get
make
cmake

and many other commands we are used to from Linux is missing. Ubuntu Snappy Core is truly not made for creating anything ON but made for executing stuff made for it on a different, ordinary linux distro. This gets really frustrating fast until you accept that this is the premise of Ubuntu Snappy Core.

The library I usually use for controlling gpio pins on any Raspberry Pi is called wiringPi  so we are going to compile that for our Pi2 and add it as a library. I ended up busting out my old Pi1 to compile the wiringPi library, then transferred it to my 64 bit machine and put it into lib/arm-linux-gnueabihf, as can be seen here. For future reference, these binaries are wiringPi 2.29.
Again, I compiled using snappy build and got a nice multi arch snap which we install as before.

Back on the Pi2 we issue

$ unabto.unabto

and are met with

$ wiringPiSetup: Must be root. (Did you forget sudo?)

and with sudo

$ wiringPiSetup: Unable to open /dev/mem: Permission denied

which leaves us exactly back at where we started.
So I tried many things to get this working. Since the newest version of wiringPi has a workaround for running without sudo (which I actually got working on my Pi1 running Raspbian) I tried to do the same thing here.
This involved remounting the read-only filesystem to make it writable, move around some libraries, add some paths and so forth. This totally goes against the Ubuntu Snappy Core principles and ultimately did not work anyway.
Now, if we run snappy -h on our Pi2 we see there is a way of assigning a hardware device to a package. We try that by issuing

$ sudo snappy hw-assign unabto.nabto /dev/mem

but it still did not work.
Thus, we saw that we cannot add hardware support the way Ubuntu Snappy Core states at their website and we really should not be messing around with remounting the filesystem.

This leaves us with the compromise of creating a custom wrapper, setting the library paths and calling the correct executable. This is already in the package (run_unabto)  so what we ultimately have to do to finally get something working is this:
Just after sshing into you Pi2 Ubuntu Snappy Core, issue this

$ echo "alias run_unabto=/apps/unabto.nabto/current/bin/arm-linux-gnueabihf/run_unabto" >> .bashrc

and then reboot. After this, we are now able to write

$ run_unabto -d id -s -k key

where id and key are found at developer.nabto.com and unabto should finally be running, wopeeh! But what is perhaps even more interesting, is the fact that if we hook up an LED to wiringPi pin number 0 we actually control something now instead of just the dummy switch we saw earlier plus we are as close as can be to the philosophy of Ubuntu Snappy Core: snaps should be selfcontained.
If we decide to remove unabto by issuing

$ sudo snappy remove unabto

and

$ sudo snappy purge unabto

the only remnant of unabto will be the last line in our .bashrc file and I can live with that.

Whuu, that was a bit of a mouthfull!

As seen, it is definitely possible to create snaps for Ubuntu Snappy Core. With time, glitches like examples that won’t compile and outdated tutorials will hopefully be fixed.

If nothing else, it is now possible to run unabto on Ubuntu Snappy Core and actually do something useful with it !

To finish things of, you can publish your snap to the Ubuntu store very easily by following the instructions here. If you would like to check out the code we used for creating the uNabto snap, please check out the relevant github repository.
If you would like to see how to add some more funtionality into your own uNabto snap, please check out The CoffeePi (Part 1 of 2)The CoffeePi (Part 2 of 2) and The SunPi control center.