Jorjin Ameba Arduino Library

Today we will have a look at the Arduino-like Jorjin Ameba board with built in support for WiFi and NFC. Taking the pricetag of 25$ into account makes this an easy choice for your IoT projects!

For this post I created a Jorjin Ameba library which can be imported directly into the Arduino IDE seamlessly, thus making the classic blink example a breeze.

We will walk through the following steps

  • Specs of jorjin board and “special features”
  • How to run the example
  • Demo

The Jorjin board

board

Overview of the Jorjin Ameba WiFi board.

The Jorjin Ameba WiFi board has built-in WiFi and  NFC thus making it very much prepared for IoT.

As can be seen from the above image, the Ameba board has an Arduino-like form factor with a similar pinout. For the simple LED blink example, we will be using a digital pin.

Getting the example up and running

To run the example we need to install the Ameba board libraries and the Ameba specific uNabto files. We also need a device name and key, both of which can be created at developer.nabto.com

Furthermore an LED (and appropriate resistor) is needed.

Step 1: Download General Ameba Libraries install

Follow the steps laid out here to install the general Ameba libraries into the Arduino IDE OR read it right here:

Open up the Arduino IDE. Click File -> Preferences and then copy this

https://github.com/Ameba8195/Arduino/raw/master/release/package_realtek.com_ameba_index.json

into the Additional Boards Manager URLs input field. Click OK

Now click Tools –> Board: -> Boards Manager

Here we search for Ameba and click Install

The Jorjin Ameba board Arduino libraries are now installed

Step 2: uNabto libraries install

There are two ways of getting the uNabto libraries.

Using git

git clone --recursive https://github.com/nabto/unabto-jorjin-sdk

then change directory to the unabto-jorjin-sdk folder and run

bash Make.sh

OR download the release zip file unabto-jorjin-sdk.zip

No matter which way, we can now add the library to the Arduino IDE via Sketch -> Include Library -> Add .ZIP Library... and then browse to and add the unabto-jorjin-sdk folder that was just downloaded.

Run the example

We can now open the LightSwitch.ino example by going to File -> Examples -> Nabto-Ameba -> LightSwitch

Here we need to enter the SSID and password of the wireless network we want to attach to. Furthermore we need to input the device name and key we created at developer.nabto.com

Finally we need to remember to wire the LED and resistor up like so (try switching pins around if it does not work at first)

jorjin_wiring

Wiring of the LED. Image taken from the Ameba documentaion, available from here (signing up is required)

When the example is compiled and uploaded to the device we simply need to press the reset button (see the above image). The board should now reset, connect to the specified wifi network and run uNabto.

We can now control the LED by going to devicename.demo.nab.to in the Nabto client of your choice. (devicename is the unique name created at portal.nabto.com). Simply use the guest account for this demo. We can now control the LED by moving the slider.

Demo

As always, the full code can be found at Github. If you feel like experimenting with the many uses of the Nabto framework, please visit our developer portal where you can manage up to 10 devices for free !

The Roomba (Part 2 of 2)

Please read Part 1 to read about the preliminary steps in the Roomba saga.

This part will be the fun part where we turn the Roomba into a fully fledged remote controlled vehicle fitted with realtime video feed as well!

If at any time you feel like trying this yourself, you can sign up for a free developer account or/and read more at developer.nabto.com.

In details, this part will be dealing with

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

The RC Roomba

Turning the Roomba into a remote controlled car is really easy once the groundwork is done correctly (see Part 1).

All we need are the new opcodes given to us in the documentation:

  • Drive straight (20 cm/s)
    • Using W
    • {137, 0, 255, 128, 0}
  • Reverse (20 cm/s)
    • Using S
    • {137, 255, 0, 128, 0}
  • Rotate counterclockwise
    • Using A
    • {137, 0, 255, 0, 1}
  • Rotate clockwise
    • Using D
    • {137, 0, 255, 255, 255}

This is all we need on the device side of things.
For the html part I simply chose to create a text input field which detects when a certain character is pressed in accordance with the keys given above. Say, for example, that you press W. The Roomba will now drive in a straight line until the user sends a new command.
If a key is pressed which does not have a predefined action, then the Roomba will stop driving. I usually use space to stop.

Adding sound effects

It is possible to store melodies in the Roomba. On our specific model, 581, we can store 4 melodies with 16 notes each (that storage!). From the documentation we find the serial sequence to be

[140] [Song Number] [Song Length] [Note Number 1] [Note Duration 1] [Note Number 2] [Note Duration 2].etc.

I decided to add a reverse sound, the DSB sound and a Dixie Horn style, River Kwai March (warning: loud) sound. These were added with the following codes

  • Reverse sound
    • {140, 1, 6, 84, 32, 30, 32, 84, 32, 30, 32, 84, 32, 30, 32}
  • DSB sound
    • {140, 0, 3, 74, 40, 75, 20, 70, 32}
  • Dixie Horn sound
    • {140, 3, 12, 86,10, 83,10, 79,10, 79,10, 79,10, 81,10, 83,10, 84,10, 86,10, 86,10, 86,10, 83,10}

The songs can then be played back by this sequence [141][Song Number], like this

  • Reverse sound
    • Played when the Roomba goes in reverse
    • {141, 3}
  •  DSB
    • Using K
    • {141, 0}
  • Dixie Horn
    • Using L
    • {141, 3}

Sensor data

The Roomba has 58 different sensor data packets, which all return hex values. For this I want to query

  • Battery temperature
    • Packet ID 24
    • Data bytes: 1, signed.
    • Returns the temperature of the Roomba’s battery in degrees Celsius.
  • Battery charge
    • Packet ID 25
    • Data bytes: 2, unsigned
    • Returns the charge level in mAh
  • Battery capacity
    • Packet ID 26
    • Data bytes: 2, unsigned
    • Returns battery capacity in mAh
  • Charging state
    • Packet ID 34
    • Data bytes: 1, unsigned
    • Returns 1 if charging, 0 otherwise

We can query all these with a single sequence

[149][Number of Packets][Packet ID 1][Packet ID 2]...[Packet ID N]

which look likes this in our case

{149, 4, 24, 25, 26, 34}

Referencing the above Data bytes gives us a total sensor byte size of 6 bytes. The battery temp and charging state can be taken directly, since they only have 1 data byte. Charge and capacity need some attention since we need to bitwise left shift on the high (first) byte before we can get a decimal number. In C this is done like so

Number = [1]<<8 | [2]

We then calculate the battery level by simply doing

bat_level = 100 * (charge/capacity)

I then created a button for our html code which output charging state, battery level and battery temperature, when pressed.

Video streaming through Nabto tunnel

For this we selected to use a Raspberry Pi Camera Module since we already had one at the office. I then read about various ways of streaming the output and display it on a webserver. I tried many different approaches but eventually settled on RPi Cam Web Interface since it gave the best compromise between low latency, low bandwith usage and “high” resolution. Furthermore, these settings are fully costumisable and the user can thus change values for their needs. An extra feature is the ability to run motion detection and to take 2592 x 1944 pixel static images or 1080p @ 30fps, 720p @ 60fps  and 640x480p 60/90 video recording.

Setting up a webserver on our Pi

To get the video webserver up and running on our Pi is fairly easy when following the instructions laid out here.

sudo apt-get update
sudo apt-get dist-upgrade
git clone https://github.com/silvanmelchior/RPi_Cam_Web_Interface.git
cd RPi_Cam_Web_Interface
chmod u+x *.sh
./install.sh

The installation prompt will have some adjustable settings such as whether to run an apache or nginx webserver. Choose whatever you prefer. I chose to change the default port from 80 to 90 to avoid conflict with any other service running on our Pi. After installation a webserver should now be running. We can access it on our local network by going to pi_ip:port_chosen/html

If no video is running, try issuing ./start.sh or do an update by ./update.sh.

The default settings worked very well for me but if you happen to have a very low bandwith internet connection (or running this on one of the earlier Pi versions) you can try to adjust the bandwith settings.

Tunneling

To make our video feed available from anywhere, we will be running a Nabto tunnel on our Pi as well. Compiling a Nabto tunnel is very easy, simple issue these commands one line at a time on the Pi

cd unabto/apps/tunnel
cmake .
make

which we can execute by doing

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

where the id and key are generated at developer.nabto.com

Finally we need to run the other end of the tunnel on our client machine. I will present how to do this using our simpleclient_app solution which works on Linux, Windows and Mac OSX. Furthermore I will walk through how to use the special Tunnel manager tool for Windows. All this can be downloaded from developer.nabto.com where we also need the common Nabto Client SDK Resources.

Command line

On our client machine, combine the Simple Client and Client SDK Resources such that the structure look like this
./bin/simpleclient_app and ./share/nabto/users/guest.crt and then issue

./simpleclient_app -q "id".demo.nab.to --tunnel client_port:localhost:device_port

which should output a few lines ending with either
tunnelStatus LOCAL
or
tunnelStatus REMOTE_P2P
depending on if the connection to the Pi is local or remote.

Tunnel Manager for Windows

Grab a copy of Tunnel Manager and input

"id".demo.nab.to into "Server"
127.0.0.1:client_port into "Local endpoint"
127.0.0.1:device_port into "Remote endpoint"

Which can look something like this

tunnelmanager_windows

Tunnel Manager for Windows. Change the Server name, Local endpoint and Remote endpoint to whatever you chose earlier on.

The tunnel is now up and running on the Pi and we are connected to from the client.

Let’s have some fun!

Everything is now setup. On our device side we are running a Roomba remote ./unabto_raspberry and a ./unabto_tunnel.

On the client side we are either running no tunnel (if we do not need video streaming) or either a command line ./simpleclient_app or the Tunnel Manager for Windows.

We can now finally access our uNabto Roomba webpage as we did in Part 1 where we will be greeted with this.

roomba_video_html

uNabto Roomba remote control html device driver

As stated below the image, clicking it will open a new window showing us the tunneled stream from the webserver running on the Pi.
Just below the image is a button for reading sensor data and below that I placed the input field for controlling the uNabto Roomba.

All that is left is to test it out!

If you feel like doing the same thing, please feel free to check out the code on Github and sign up for a developer account at 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 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.

Nabto + FreeRTOS running on Cortex-M7 using the ST STM32F746G-DISCO Board

When working with STM32 ARM Cortex-M microcontrollers, the free embedded software STM32Cube from ST provides all necessary drivers and a collection of middleware components to reduce the initial development effort. One of the mentioned middleware components is the popular FreeRTOS real-time operating system Nabto is partnering with to create a powerful combined FreeRTOS+Nabto solution. This article explains the implementation of a demo project running Nabto + FreeRTOS on a STM32F746G-DISCO board.

nabto+stm32

STM32F74G-DISCO board running the demo

What you need

This demo is based and tested on the STM32F746G-DISCO board, but should be portable to similar STM32 boards. Same applies to your favorite IDE.

Why Nabto and how does it work?

Have you ever thought about connecting to your STM32 device from outside your local network without nerve-racking router and firewall configurations or heavy and intransparent cloud services? Running the uNabto server on your STM32 device, 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 STM32 board 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 STM32 board, 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.

Screen Shot 2016-02-29 at 13.23.22

Nabto in the STM32Cube Architecture

As mentioned before the STM32Cube provides a Hardware Abstraction Layer API and a selection of Middleware components. The uNabto server we want to implement builds on top of the STM32Cube middleware, as can be seen in the following diagram:

nabto+stm32cube-architecture.png

The uNabto server itself is divided into two layers:

  • The actual uNabto framework (uNabto SDK)
  • The uNabto Platform Adapter abstraction layer between the uNabto framework and the STM32Cube middleware

Hence, we only need to implement the uNabto Platform Adapter, in order to port the uNabto server to the STM32 platform.

Implementing the Platform Adapter

The Platform Adapter acts as link between the generic uNabto framework and the STM32Cube middleware layer, including the LwIP TCP/IP stack which will be used for networking. The LCD Log Utility is used to display the Nabto output on the screen.

The adapter is divided into single files, as suggested in the Nabto documentation (TEN023 Writing a uNabto device application, chapter 12):

  • unabto_config.h: Basic uNabto configuration
  • unabto_platform_types.h: Defines all necessary uNabto types
  • unabto_platform.h: Platform specific ad-hoc functions
  • network_adapter.c: Init, close, read and write functionality for network data
  • time_adapter.c: Time functions
  • dns_adapter.c: DNS resolving
  • random_adapter.c: Random generator
  • log_adapter.c: Logging

If you are interested in how the platform adapter is implemented in detail, check the adapter files in the Inc and Src directories of the demo on GitHub.

Implementing the Nabto Thread

After creating the Platform Adapter the uNabto Server is ready to use and the actual uNabto Device Application can be implemented. This is done in Src/nabto.c. Since the server will run in its own FreeRTOS thread, we first create the following thread method.

static void nabto_thread(void const *argument)
{
const char* nabtoId = "...";
const char* presharedKey = "...";

struct netif *netif = (struct netif *) argument;

// Initialize Nabto
nabto_main_setup* nms = unabto_init_context();
nms->ipAddress = netif->ip_addr.addr;
nms->id = nabtoId;
nms->secureAttach = 1;
nms->secureData = 1;
nms->cryptoSuite = CRYPT_W_AES_CBC_HMAC_SHA256;

const char *p;
unsigned char *up;
for (p = presharedKey, up = nms->presharedKey; *p; p += 2, ++up)
*up = hctoi(p[0]) * 16 + hctoi(p[1]); // convert hex string to byte array

unabto_init();

for (;;) {
osDelay(10);
unabto_tick();
}
}

It initializes the server among others with your unique Nabto ID and the pre-shared encryption key from developer.nabto.com (insert in highlighted lines). Then it starts an infinite loop calling the unabto_tick() method. This triggers the framework to check for new UDP packets and send responses. The time between ticks should be around 10 milliseconds, which is achieved by a hard OS delay.
To start the Nabto thread we provide a nabto_init() method. It is called by the main program after initializing the TCP/IP stack and either setting a static IP address or obtaining a dynamic IP address from a DHCP server.

void nabto_init(struct netif *netif)
{
sys_thread_new("Nabto", nabto_thread, netif, DEFAULT_THREAD_STACKSIZE, NABTO_THREAD_PRIO);
}

The actual handling of received Nabto messages from the client is implemented in the application_event() function. The handler uses the message format used in the default HTML Device Driver, provided in the Nabto portal. In this demo the LCD display can be switched on and off by the client. For more information on how to create your own HTML DD, please refer to TEN024 Writing a uNabto HTML client.

application_event_result application_event(application_request* request,
                                           buffer_read_t* read_buffer,
                                           buffer_write_t* write_buffer)
{
  switch (request->queryId) {
  case 1: {
    // <query name="light_write.json" description="Turn light on and off" id="1">
    // <request>
    // <parameter name="light_id" type="uint8"/>
    // <parameter name="light_on" type="uint8"/>
    // </request>
    // <response>
    // <parameter name="light_state" type="uint8"/>
    // </response>
    // </query>

    uint8_t light_id;
    uint8_t light_on;

    // Read parameters in request
    if (!buffer_read_uint8(read_buffer, &light_id))
      return AER_REQ_TOO_SMALL;
    if (!buffer_read_uint8(read_buffer, &light_on))
      return AER_REQ_TOO_SMALL;

    // Set display according to request
    display_state = light_on;
    if (display_state)
      BSP_LCD_DisplayOn();
    else
      BSP_LCD_DisplayOff();

    // Write back display state
    if (!buffer_write_uint8(write_buffer, display_state))
      return AER_REQ_RSP_TOO_LARGE;

    return AER_REQ_RESPONSE_READY;
  }
  case 2: {
    // <query name="light_read.json" description="Read light status" id="2">
    // <request>
    // <parameter name="light_id" type="uint8"/>
    // </request>
    // <response>
    // <parameter name="light_state" type="uint8"/>
    // </response>
    // </query>

    uint8_t light_id;

    // Read parameters in request
    if (!buffer_read_uint8(read_buffer, &light_id))
      return AER_REQ_TOO_SMALL;

    // Write back led state
    if (!buffer_write_uint8(write_buffer, display_state))
      return AER_REQ_RSP_TOO_LARGE;

    return AER_REQ_RESPONSE_READY;
  }
  }
}

Hands-On!

Enough theory. Let’s try out the demo! It is available as System Workbench for STM32 (SW4STM32) project here on GitHub.

  1. Clone the demo. Make sure you do that recursively in order to also clone the uNabto SDK submodule:
    git clone --recursive https://github.com/nabto/unabto-stm32-sdk.git
  2. Download the STM32CubeF7 package and place it in the /STM32CubeF7 folder. You should end up with the folder structure described in the Readme.
  3. Import the project from /SW4STM32/NABTO_STM32 into your System Workbench for STM32 (SW4STM32) workspace (File -> Import… -> Existing Projects into Workspace -> Next -> Browse to the /SW4STM32/NABTO_STM32 folder -> Finish).
  4. Insert your Nabto ID and the preshared key from developer.nabto.com in /Src/nabto.c.
  5. Define USE_DHCP or specify static IP address in /Inc/main.h.
  6. Build project. (Right-click on Project in Project Explorer -> Build Project)
  7. Connect the device to the ethernet.
  8. Transfer the image to the device memory. (Right-click on Project in Project Explorer -> Transfer -> Program Chip…)

The board should now print out the Nabto log on the LCD screen, like on the picture in the beginning of the article.

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 LCD Display on and off from everywhere!

stm32-demo-screenshot

Nabto Cordova Plugin

nabto_and_cordova-fs8

We have now officially released our Nabto client Cordova plugin for everybody to use. This is a great step in improving the development speed and familiarity of creating a Nabto app.

https://www.npmjs.com/package/cordova-plugin-nabto

It is a shift in Nabto customer front-end development that we have long been wanting to make, since it enables developers to get started quicker and hopefully be more productive. Developers now have the ability to use standard tools, update mechanisms and seamlessly combine it with other Cordova plugins.

After adding the plugin to your cordova project by using “cordova plugin add cordova-plugin-nabto“, it is now incredibly easy to request data from your uNabto device:

// Start Nabto and login as guest
nabto.startup(function() {
// Make a Nabto request to a device
  var url = 'nabto://demo.nabto.net/wind_speed.json?';
  nabto.fetchUrl(url, function(status, result) {

    // Print out the response if it succeeded
    if (!status &amp;&amp; result.response) {
      console.log(result.response);
    }

  });

});

For more details on usage visit https://github.com/nabto/cordova-plugin-nabto.

The old way of creating universal web-based Nabto apps using HTML Device Drivers is quietly being deprecated, while support for that solution is still kept. We will in the following days update the Nabto documentation and https://developer.nabto.com to reflect this change in strategy.

So far iOS and Android are the only platforms supported, but a plan for web-based desktop applications will be added later.

We also chose to open source the plugin at Github, including the library wrappers, for everybody to see and contribute to. These days we are moving a lot of our open source projects to Github repositories for better transparency towards our users.

A natural next step would be to create a couple of ionic apps for demonstrating full use cases using the new Cordova plugin.

The CoffeePi (Part 2 of 2)

Breaking news!

The CoffeePi will be appearing at Smart IoT London 2016!
smart-iot-london

Feel free to drop by our booth and get a hot beverage from the CoffeePi served using Nabto!

Back to the story

Please read Part 1 to read about the preliminary steps in the coffee saga.

This part will be dealing with the following points

  • Figuring out how to wire up and emulate the rotary knob
  • Adding the Nabto framework
  • Making the full menu available
  • Order a cup of coffee in London, trigger instant brewing in Denmark

The rotary knob

The rotary knob has three pins as seen in the image below

no_finger.png

The backside of the rotary knob. We see the three pins, the center being common high and the two outer pins which go high or low according to the rotation of the knob

The center pin is common high and the outer pins output the necessary encoder pulse needed for the main board. To get an idea of how these pulses look we checked it out using a logic tester

20160222_131353.jpg

The logic tester in use

which gave an output like this

logic

The output from the logic tester. The upper section is the output for moving to the left and the bottom section is the output for going right.

The upper section, in the image above, shows the output from the rotary knob when turning the knob counterclockwise which if equivalent to going  left on the main board display. Likewise the bottom section shows the clockwise rotation which result in a right movement on the main board display.

From this we see that the direction the knob is turned can be directly translated into which direction we are moving on the main board display simply by relating which pins changes state first. In other words, to move left/right we need to emulate an output like the top/bottom one seen in the image above.

Before doing that, we need a common starting point, meaning that we need to know if the pins are high or low to begin with. The simplest way to control this was to cut the pins like this

rotary_knob_pinout

The two switches represent two optocouplers. This means that we can disable the manual rotary knob controls by switching a pin on our Raspberry Pi. Doing that results in the receiving end of the pins to be pulled low. We thus have our starting point.

In total, our wiring should now look something like this

total_wiring

Wiring diagram for the CoffeePi. In total 10 optocouplers were needed, 6 for the buttons and 4 for the rotary knob. Common high, H, from the CoffeePi and common ground from the Raspberry Pi.

As can be seen from the wiring diagram above the 6 OCs on the left side controls the 6 buttons and the 4 on the right hand side controls the rotary knob. We input a digital high/low value on the bottom which signals a certain output on top, to the coffee machine.
The resistors are 270Ω, common ground is from the Raspberry Pi and H is common high from the CoffeePi (the blue markings in this image from The CoffeePi (Part 1 of 2)).

When the dis. pin is set high the rotary knob works in its normal manual way. When we set it low, the black inputs (generated from manual rotation of the knob) are disabled and we can instead send our own pulses using Rot.1 & 2.

For reference, the wiring looks like this in real life

IMG_20160317_122230 - Kopi

Wiring for the CoffeePi in real life. Notice the two extra optocouplers in the middle which are not hooked up for any output.

As always, the real projects end up being messier than on paper but both images have the same layout: 6 OCs for the buttons on the left and 4 OCs for the rotary knob on the right.

Adding the Nabto framework

Since our platform is the Raspberry Pi (Linux) I suggest checking out Raspberry Pi 3 IoT, perfect for Nabto for instructions on how to get the uNabto software up and running in no time. After that please check out The SunPi control center to get an idea of how we get a browser to communicate with our uNabto software.
For now we only need to worry about unabto_application.c in the src folder.

Making the full menu available

In The CoffeePi (Part 1 of 2) we were only able to progammaticrally push a button after we manually turned the rotary knob to the correct position. Since we now have an understanding of how the rotary knob creates pulses we can now make the full menu available. This is done in the following few steps (code snippets taken directly from unabto_application.c)

Disable manual control

// Shut off manual control
digitalWrite(11, LOW);
delay(wait_msec);

As well as disabling manual control from the rotary knob, the two pins are pulled low such that we always have the same initial setting.

Get a starting point

Since we have 9 available items on our menu we begin by going 8 steps to the left

// Go all the way to the left
for (i = 0; i &amp;amp;amp;lt; 5; i++){

    digitalWrite(13, HIGH);
    delay(wait_msec);
    digitalWrite(14, HIGH);
    delay(wait_msec);
    digitalWrite(13, LOW);
    delay(wait_msec);
    digitalWrite(14, LOW);

    delay(wait_msec);
}

This is done to ensure that we always have the same starting point when getting to the next step.

Selecting desired product

All our pins are now low and it is finally time to go to the desired product. Each item has a certain number associated with them (from the radio buttons) which directly corresponds to how many steps we need to move to the right.

html_page

The CoffeePi is up and running!

The most popular choice is, of course, Coffee and thus it is pre checked when accessing the CoffeePi online. This button has a value, or id, of 3 so when we click Brew the number/id is send using a Nabto request.

// Go id amount of steps to the right to the desired item
for (i = 0; i &amp;amp;amp;lt; id; i++){
    // If odd
    if (i % 2 != 0){
        digitalWrite(14, LOW);
        delay(wait_msec);
        digitalWrite(13, LOW);
    }
    else{
        digitalWrite(14, HIGH);
        delay(wait_msec);
        digitalWrite(13, HIGH);
    }
    delay(wait_msec);
}

After that bit we should now be at the desired item, and we can now emulate a button press

// Push button
digitalWrite(10, LOW);
digitalWrite(10, HIGH);
delay(100); // 0.1 sec
digitalWrite(10, LOW);

The item should now be brewing!

Clean up

While our lovely hot beverage is being brewed we send a few extra commands. First, we ensure that the two pins controlling the pulses are being set low again and finally, we turn on manual control of the rotary knob again.

// Set the steppers to low
digitalWrite(13, LOW);
digitalWrite(14, LOW);

// Turn on manual control
digitalWrite(11, HIGH);

Remarks

Since we started using a synchronous event handler, the Nabto framework expects to get a response in just 10 msec – so we need to run all this pin switching in a separate thread. The thread is set to being detachable, such that it will self terminate when all code inside the thread has been executed. Please see the appropriate code. In a later post, we will show how to use an asynchronous approach instead and save this separate thread.

From London with love

What better way to demonstrate the true IoT this coffee machine has now become by ordering a cup of coffee from London and then seeing it being brewed in Denmark a few seconds later?

Notice how my colleague in London is laughing through the process!

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 portal.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 the CoffeePi can be found right here.

ESP8266 WiFi Module + Nabto

The ESP8266 is a low-cost WiFi module that can be programmed directly like a microcontroller. Already thinking of your next Internet of Things project?

While an available Arduino library allows a quick start, there is still one problem to overcome: How to access your ESP8266 from outside your home network without nerve-racking router and firewall configurations or heavy and intransparent cloud services? Running the uNabto server on your ESP8266, you can establish a fast and secure Peer-to-Peer connection using only a static ID – from everywhere, no matter what is in between.

What hardware you’ll need

IMG_20160303_153803

Adafruit HUZZAH ESP8266 Breakout

IMG_20160303_153830

USB to TTL Serial Cable

This project is tested on an Adafruit ESP8266 board. It’s not the cheapest you can get, but very prototyping friendly. You can put it on a breadboard and it has a 3.3V voltage regulator onboard. Of course, you can also use a different ESP8266 module. Wikipedia provides an extensive list of available modules.

Regarding the USB to TTL Serial Cable (get it e.g. here), there are no special requirements when using the Adafruit module. If you use a different module, make sure the voltage levels match, since most boards only accept 3.3V.

Solder the pin header to your ESP8266 board and connect it to your USB to TTL adapter using 4 wires:

wiring

What software you’ll need

This project is tested on Ubuntu 15.10 but should work on any OS supported by the Arduino IDE.

We want to program the ESP8266 directly, instead of using any higher level interpreters available for the module. Adafruit provides a nice tutorial on how to setup your  Arduino IDE accordingly.

If everything is running, you should be able to compile the following simple sketch and upload it to your ESP8266. This will make the onboard LED blink every second.

const int led = BUILTIN_LED;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);
  delay(500);
  digitalWrite(led, LOW);
  delay(500);
}

How the Nabto platform works

So far, so good. But how does the Nabto platform actually work? The drawing below gives a brief overview. Your ESP8266 module 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 ESP8266, a connect request with the ID is sent to the Basestation, and a direct connection to the device is established. A client can be an HTML page running in a desktop browser extension (IE, Firefox) or the Nabto Mobile App (iOS, Android), or a custom Nabto API Client.

nabto-platform-basics

Get more information on the Nabto platform and the Client/Device SDKs on developer.nabto.com.

The uNabto Platform Adapter

The uNabto server is divided into two layers:

  • The actual uNabto framework (uNabto SDK)
  • The uNabto Platform Adapter abstraction layer between the framework and the Native Platform

unabto-platform-adapter

Hence, we only need to implement the uNabto Platform Adapter, in order to port the uNabto server to the ESP8266 module.

Implementing the Platform Adapter

The Platform Adapter acts as link between the generic uNabto framework and the Arduino platform, including the ESP8266 WiFi library. The adapter is divided into single files, as suggested in the Nabto documentation (TEN023 Writing a uNabto device application, chapter 12):

  • unabto_config.h: Basic uNabto configuration
  • unabto_platform_types.h: Define all necessary uNabto types
  • unabto_platform.h: Platform specific ad-hoc functions
  • network_adapter.cpp: Init, close, read and write functionality for network data
  • time_adapter.cpp: Time functions
  • dns_adapter.cpp: DNS resolving
  • random_adapter.cpp: Random generator
  • log.cpp: Logging

If you are interested in how the platform adapter is implemented in detail, check the adapter files in the src directory of the library on GitHub.

Using the Library

Get the Nabto ESP8266 Arduino library from https://github.com/nabto/unabto-esp8266-sdk and place it in your Arduino library directory. If you don’t know where your library directory is located, see the guide on manual installation of Arduino libraries.

After restarting your IDE the library is installed. An example sketch can be found in

File -> Examples -> Nabto-ESP8266 -> LightSwitch

The sample sketch includes the Nabto class, which encapsulates the Nabto setup. First, some settings are made. This includes the WiFi SSID and password, followed by the unique Nabto ID and preshared key of the device, as well as the pin of the onboard LED to be controlled.

#include <Nabto.h>

// Enter ssid and password of your WiFi network
const char* ssid = "...";
const char* password = "...";

// Enter device id and preshared key from developer.nabto.com
const char* nabtoId = "...";
const char* presharedKey = "...";

// Specify LED pin
const int led1_pin = BUILTIN_LED;

The setup function is used to init the LED pin and the Serial module. In line 42 you can see how the Nabto module is initialised. The begin(..) function is blocking, therefore, the following printout of the Nabto version number only takes place, if the WiFi connection was established.

void setup() {
// Initialize built-in led
pinMode(led1_pin, OUTPUT);
digitalWrite(led1_pin, 1);

// Initialize Serial
Serial.begin(115200);

// Initialize Nabto
Serial.println("Init...");
Nabto.begin(ssid, password, nabtoId, presharedKey);

// Optionally get nabto firmware version
char versionString[10];
Nabto.version(versionString);
Serial.print("Nabto v");
Serial.print(versionString);
Serial.println(" running...");
}

The only thing that needs to be done in the loop function is to call the tick() method of the Nabto class. This triggers the framework to check for new UDP packets and send responses. The time between ticks should be around 10 milliseconds. This is achieved by a hard delay, but you can also use the time to do application related stuff.

void loop() {
 // Check for new nabto udp packets and send response. Non-blocking
 Nabto.tick();

 // We have chosen to sleep 10 milliseconds between tics
 delay(10);
}

The following two functions provide a convenient way to set and read the LEDs, although we will only use one LED in this example.

// Set LED and return state.
// Only using ID #1 in this simple example
uint8_t setLed(uint8_t led_id, uint8_t led_on) {
 if (led_id == 1) {
 // inverted
 digitalWrite(led1_pin, !led_on);
 return !digitalRead(led1_pin);
 }
 else {
 return 0;
 }
}

// Return LED state.
// Only using ID #1 in this simple example.
uint8_t readLed(uint8_t led_id) {
 if (led_id == 1) {
 // inverted
 return !digitalRead(led1_pin);
 }
 else {
 return 0;
 }
}

The actual handling of received Nabto messages from the client is implemented in the application_event(..) function. The handler uses the message format used in the default HTML Device Driver, provided in the Nabto portal. For more information on how to create your own HTML DD, please refer to TEN024 Writing a uNabto HTML client.

application_event_result application_event(application_request* request, buffer_read_t* read_buffer, buffer_write_t* write_buffer) {
switch(request->queryId) {
case 1:
{
// <query name="light_write.json" description="Turn light on and off" id="1">
// <request>
// <parameter name="light_id" type="uint8"/>
// <parameter name="light_on" type="uint8"/>
// </request>
// <response>
// <parameter name="light_state" type="uint8"/>
// </response>
// </query>

uint8_t light_id;
uint8_t light_on;
uint8_t light_state;

// Read parameters in request
if (!buffer_read_uint8(read_buffer, &light_id)) return AER_REQ_TOO_SMALL;
if (!buffer_read_uint8(read_buffer, &light_on)) return AER_REQ_TOO_SMALL;

// Set light according to request
light_state = setLed(light_id, light_on);

// Write back led state
if (!buffer_write_uint8(write_buffer, light_state)) return AER_REQ_RSP_TOO_LARGE;

return AER_REQ_RESPONSE_READY;
}
case 2:
{
// <query name="light_read.json" description="Read light status" id="2">
// <request>
// <parameter name="light_id" type="uint8"/>
// </request>
// <response>
// <parameter name="light_state" type="uint8"/>
// </response>
// </query>

uint8_t light_id;
uint8_t light_state;

// Read parameters in request
if (!buffer_read_uint8(read_buffer, &light_id)) return AER_REQ_TOO_SMALL;

// Read light state
light_state = readLed(light_id);

// Write back led state
if (!buffer_write_uint8(write_buffer, light_state)) return AER_REQ_RSP_TOO_LARGE;

return AER_REQ_RESPONSE_READY;

default:
return AER_REQ_INV_QUERY_ID;
}
}
}

Test your device

After compiling and uploading your LightSwitch sketch to the ESP8266, it establishes a connection to your WiFi network and starts the uNabto server. In your serial monitor you should see the following printout:

Init...
Device id: 'mydeviceid.demo.nab.to'
Program Release 2.21889
Application event framework using SYNC model
SECURE ATTACH: 1, DATA: 1
NONCE_SIZE: 32, CLEAR_TEXT: 0
Nabto was successfully initialized
Nabto v2.21889 running...
SECURE ATTACH: 1, DATA: 1
NONCE_SIZE: 32, CLEAR_TEXT: 0
State change from IDLE to WAIT_DNS
Resolving dns: mydeviceid.demo.nab.to
State change from WAIT_DNS to WAIT_BS
State change from WAIT_BS to WAIT_GSP
######## U_INVITE with LARGE nonce sent, version: - URL: -
State change from WAIT_GSP to ATTACHED

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 built-in LED on and off from everywhere!

Screenshot_2016-03-05-14-50-37

Future improvements

Currently, the WiFi SSID and password, as well as the device ID and the preshared key are stored in the ESP8266’s flash memory. This requires an update of the source code and a firmware upload on every change of these parameters. A possible solution to this problem could be a very small web server running on the ESP8266, which is accessible through a parallel running WiFi access point. The parameters entered through the web interface could then be persistently stored in the EEPROM.

Raspberry Pi 3 IoT, perfect for Nabto

A few days ago (29/2-2016) the new Raspberry Pi 3 was announced. Of course we were all excited here at the Nabto headquarters and quickly bought a few.

Since they are reviewed as the perfect platform for IoT we wanted to check out if it is perfect for Nabto as well. Spoiler alert: it is !

Setting up the Pi 3

The fastest way to get wifi and Nabto up and running on your Pi 3 is to burn an image to your sd card (for this post we are using Raspbian Jessie Lite). After doing that, hook up your Pi3 by wire to your local network. You can now access the Pi, either directly by HDMI and a keyboard or over SSH.

One of the main features of the new Pi3 is the onboard wifi module so the first thing to do is to search for available networks and make the Pi autoconnect to the one we want. This is most easily done by issuing the following commands one line at a time

wpa_cli
scan
scan_results
add_network
set_network 0 ssid "ssid_name"
set_network 0 psk "password_stuff"
enable_network 0
save_config
quit

Where you should, of course, replace ssid_name and password_stuff with the SSID and password of the network you are trying to connect to.
After that you can reboot the Pi and remove the wire and you have a Raspberry Pi 3 ready for IoT!

Setting up Nabto

Setting up Nabto is as easy as setting up the wifi. First of we need to get the necessary tools for 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/nabto/unabto.git
cd unabto/apps/raspberry_pi
cmake .
make

We now have Nabto compiled on our Pi!
All that is left to do is to create a new device at portal.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 Nabto is successfully up and running!

Trying out Nabto

Now that everything is up and running the final thing to do is to 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

The uNabto demo is up and running!

Sliding the switch to either side will now trigger the onboard activity light on your Raspberry Pi, check it out!

For a more in depth introduction on how to write your own functionality into the Nabto framework, please refer to this blog post The SunPi control center.