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!

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.

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.

The CoffeePi (Part 1 of 2)

When I asked if I could hack the 1300$ (8800 dkk) coffee machine at the Nabto headquarters the responses varied from “no way” to “I’ll give it 30 % chance of success”. Eventually they surrendered to my request, so let’s see if it all worked out!

Since this project was rather substantial, the coffee machine saga will be split in two (possibly three later on) parts.

In this part we will be dealing with

  • Disassembling the coffee machine and finding points of interest
  • Figure out the what is needed to control the buttons
  • Brew an actual cop of coffee using SSH.

Part 2 will deal with

  • Figure 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, get it seconds later in Denmark

Disassembling the coffee machine

before_dismantling.png

The starting point, a shiny functioning Siemens EQ 7 Plus coffee machine

The starting point was the Siemens EQ 7 (TE712201RW) coffee machine, as seen in its standard form in the image above.

First of I had to decide whether to try and access the three pin service port or to rip the machine apart and make some proper hacking. Since I found no information about this service port online I decided on the latter (plus it sounded like a lot more fun).

Machines like these are built with as few screws as possible and thus all side panels are hold in place by small plastic pins. Furthermore the machine is made such that to get to the main board you have to remove the back panel, then the side panels and finally the front panel. In total, dismantling the coffee machine was not easy but I did it MANY times in the process because of broken soldering or crushed wires.

20160218_120943

E-waste or successful hack?

With the front finally of it was time to have a look at the main board.

20160218_121202

The main board inclosure

We see 6 buttons and a rotary knob in the middle. Now we just need to check out what is underneath.

Controlling the buttons

20160218_121542 - marked.jpg

The main board of the coffee machine.

Using a multimeter I began by figuring out any common connections indicated by the blue lines in the above image.

When one of the buttons are pushed a connection is made between the blue and yellow side of the button. We want to be able to create artificial button pushes and thus we need to solder on wires at every yellow line in the above picture and a common blue wire.

20160223_194222.jpg

Strapped up for the party

We can now imitate a button push by simply shortening common with any of the buttons.
To control this programmatically I went with optocouplers, specifically Fairchild 817 chosen because it has a high CTR min. meaning that we can directly activate them using the 3.3V digital pins from a Raspberry Pi, as seen below.

20160222_165956.jpg

Using an optocoupler directly from the 3.3V pins from the Raspberry Pi.

I chose optocouplers since they are basically “light relays” as my colleague said.

opto

Cross-section through an optocoupler.[wiki] As can be seen the red LED is electronically isolated from the green sensor. Thus the two sides can have very different voltage levels without damaging anything.

This turned out to be a good choice since the logic of the coffee machine runs at 5V and the Raspberry digital pins run at 3.3V, as mentioned earlier.

All that is left is then to hook up the main board again and follow the on screen instructions:

20160218_145749

Please close the door!

After “closing the door” we need to mark the wires such that we know what they do.

20160218_155624

Almost assembled and soon labeled.

I simply shorted each wire with the common wire (see above) to figure out the function of each wire.

20160218_181952.jpg

Wires from coffee machine ready to rock

As seen above the wires are now coming out of the coffee machine in a nice little bundle. We now simply need to wire up alle the optocouplers to the raspberry pi and when that is done connect everything together.

20160222_161923

Heating the soldering iron.

Since I did not have any connectors lying around I had to create some using a bit of soldering.

20160222_172341

The optocouplers all wired up.

To avoid damaging the optocouplers (and RPi) I inserted a 270Ω resistor alongside each. The “red” wire above is common ground and the numbered “green” wires are the wires we can digitally set high/low. When we set an optocoupler high it means that power is allowed to flow through on the right hand side in the image above, i.e. a button on the coffee machine is pushed.

Have a cuppa

We can now finally wire everything together such that we can click any of the six buttons by issuing a simple command over SSH:

gpio write 10 1
gpio write 10 0

This basically emitates pushing the button in (first line) and then releasing it again (second line).

So far we still have to manually scroll to the desired item in the menu, but when we are there we can programmatically push the button, as seen below:

20160222_184911

The first cup of coffee ordered remotely (i.e. 5 meters away at my computer)

Great success! 

Issues

As mentioned, we still have to manually scroll to the desired menu item before we can programmatically push a button.

The next part will be dealing with this problem as well as a few others:

  • Figure 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, get it seconds later in Denmark

 

The SunPi control center

Ever since I first build my solar powered Raspberry Pi system, called the SunPi, I wanted to be able to remote control it.

More specifically, in the summertime, when the sun shines heavily the battery would be filled within an hour after sunrise. The rest of the day, the charge controller would simply waste/curtail excess energy by dumping it as heat.
Instead of doing that I wanted to use this energy for something. Specifically I wanted to be able to remote control a relay such that I could activate whatever device I had lying around.

total_overview

Overview of the SunPi system

To determine whether or not to activate the relay I had to be able to read the voltage level which is equivalent to how filled the battery is. I did this using a INA219 current sensor, some Python and plotted it here. But I really wanted to have everything on a single page such that I could quickly determine whether or not to activate the relay. I wanted to be able to access this control center from anywhere and in a secure way. With Nabto I found the solution.

How Nabto works

nabto_overview

Overview of the Nabto framework

As seen in the above figure the client side (e.g. the device you are reading this on) has HTML, CSS and JavaScript running when you visit the SunPi control center. Altering a slider in the HTML calls a JavaScript function which in turn sends a Nabto request to the device side of things.
In this case the device is a Raspberry Pi running some compiled C code. For our power and voltage readings (more below) a Python script is called from within the C code.
That is basically all there is to the framework.

To get a better feel of how to add functionality I will walk through

  • Controlling a GPIO pin
  • Retrieving data

Note that these examples build on the default html_dd (Client side) and this RPi demo (Device side).

Controlling a GPIO pin

HTML

We start by creating a slider with a unique id (rgb-r in this case) containing the OFF and ON options.

<li>
  <h2>Red</h2>
  <div class="ui-li-aside">
    <select id="rgb-r" data-role="slider">
      <option value="off">OFF</option>
      <option value="on">ON</option>
    </select> 
<li>>

JavaScript

When the slider with the rgb-r id is toggled, the accompanying JavaScript-script is activated.

$("#rgb-r").change(function(){
  var state = $(this).val() === "off"?0:1;
  jNabto.request("light_write.json?light_id=1&light_on="+state, setLight_r); 
}); 

Where the setLight_r function shifts the actual slider.
What is perhaps more interesting is the jNabto.request part. The jNabto requests are defined in the unabto_queries.xml file and the light_write.json used above look like this

<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 format="json">
    <parameter name="light_state" type="uint8"/>
  </response>
</query>

As seen, the request sends the two light_id and light_on variables containing information about which pin/light we are dealing with and which state (light_on) we want it in. After this, we expect to receive a json format response, specifically the light_state the pin has been set to. We notice that the query id is 1.

C code

On the device side we arrive at case 1 (in unabto_application.c) since the light_write.json has id = 1.

case 1: {
    uint8_t light_id;
    uint8_t light_on;
    uint8_t light_state;

    // Read parameters in request
    if (!buffer_read_uint8(read_buffer, &light_id)) {
        NABTO_LOG_ERROR(("Can't read light_id, the buffer is too small"));
        return AER_REQ_TOO_SMALL;
    }
    if (!buffer_read_uint8(read_buffer, &light_on)) {
        NABTO_LOG_ERROR(("Can't read light_state, the buffer is too small"));
        return AER_REQ_TOO_SMALL;
    }

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

    // Write back pin state
    if (!buffer_write_uint8(write_buffer, light_state)) {
        return AER_REQ_RSP_TOO_LARGE;
    }
    return AER_REQ_RESPONSE_READY;
}

Most of this is for error logging, we only need to focus on the setLight function and how we plan on sending a message back to the client side afterwards.
The setLight function looks like this

// Set GPIO pin and return state,
uint8_t setLight(uint8_t id, uint8_t onOff) {
    theLight[id] = onOff;

    NABTO_LOG_INFO(("Nabto: %s turned %s!\n", pin_name[id], on_off[theLight[id]]));

#ifdef __arm__
    /* Toggle GPIO pins on Raspberry Pi	*/
    //Change pin output according to id and theLight state

    if (theLight[id]){
        //Activate pin
        digitalWrite(pin_id[id], LOW);
    }
    else if(theLight[id]==0){
        digitalWrite(pin_id[id], HIGH);
    }
#endif

    return theLight[id];
}

Where we toggle the chosen pin on or off depending on the light_on variable passed from the client.

When we sucessfully set the actual pin we write back the pin state to the client using the buffer_write_uint_8 command. And that is bascially all you need to control a GPIO pin on the Raspberry Pi using the Nabto framework.

Retrieving data

HTML

The HTML code for retrieving data is basically just a button which signals the JavaScript to do a certain task, in this case we are dealing with id=”ina_update” (remember, we are using a INA219 current sensor).

<li>
  <input type="button" id="ina_update" data-icon="refresh" value="Read Voltage and Power"/>
</li>

JavaScript

The accompanying JavaScript function look like this

$("#ina_update").click(function() {
  queryINA219($(this));
});

where

function queryINA219(input) {
  jNabto.request("ina_data.json?", function(err, data) {
    if (!err) {
      temp_power = data.power_w/10000

      // Check if negative
      if (temp_power > 100)
      {
        temp_power = temp_power - 200
      }

      input.val("Voltage: " + (data.voltage_v/10000).toFixed(2) + "V, Power: " + temp_power.toFixed(2) + "W").button("refresh");
    }
  });
}

contain the ina_data.json jNabto request. Again we check the unabto_queries.xml file and make sure that

<query name="ina_data.json" description="Read voltage and power status" id="3">
  <request>
  </request>
  <response format="json">
    <parameter name="voltage_v" type="uint32"/>
    <parameter name="power_w" type="uint32"/>
  </response>
</query>

the ina_data.json query id is 3.

C code

The request is sent to the device side where we end up in case 3 because the ina_data.json request has id = 3.

case 3: {
    // Get voltage from INA219
    getINA219_data(&voltage, &power);

    NABTO_LOG_INFO(("Nabto: Read voltage=%f and power=%f\n", voltage, power));

    // Write back data
    if (!buffer_write_uint32(write_buffer, voltage*10000)) 
    {
        return AER_REQ_RSP_TOO_LARGE;
    }

    // Prepare for negative numbers. This will be converted back in the html_dd app.js file
    if (power<0)
    {
        power = power + 200;
    }
            
    // Write back data
    if (!buffer_write_uint32(write_buffer, power*10000))
    {
        return AER_REQ_RSP_TOO_LARGE;
    }
    return AER_REQ_RESPONSE_READY;
}

As seen above, the power data needs special preparation since we are writing uint32 (unsigned, i.e. numbers are always positive). When the battery charges the power is defined to be positive and when it discharges it is of course negative. Since my solar panel has a maximum rated power of 100W (which it never reaches) and my maximum power consumption is 10W at any given time, I simply add 200 to the power measurement. I made sure to undo this addition in the accompanying JavaScript as seen above (// Check if negative).
Finally we take a look at the getINA219_data function,

// Get INA219 data
void getINA219_data(float* voltage, float* power){

    FILE *fp;
    char path[1035];
    /* Open the command for reading. */
    fp = popen("sudo python path/to/ina219_python_c.py", "r");

    if (fp == NULL) {
        NABTO_LOG_INFO(("Failed to run Python script\n"));
        exit(1);
    }
    /* Read the output a line at a time - output it. */
    int k = 0;
    while (fgets(path, sizeof(path)-1, fp) != NULL) {
        k = k + 1;
        if (k==1){
            *voltage = atof(path);
        }
        else if(k==2){
            *power = atof(path);
        }
    }
    /* close */
    pclose(fp);
}

The function calls a Python script which print out two lines of data. The lines contain the voltage and the power flowing in or out of the SunPi battery, respectively.
The data is then sent back to the client side using the buffer_write_uint32t command as seen above.
These are the building stones for how to write a simple Nabto application. After expanding on this a bit I finally had my control center.

The SunPi control center

control_center

The control center enables the user to control a RGB LED as well as a single relay or retrieve the voltage and power flowing into (or out) of the SunPi battery. It is also possible to retrieve the internal temperature of the SunPi.

Thus I can now simply access the Nabto SunPi control center (just click on guest to try it out. NOTE: no longer available) and then check the voltage. The battery is full when the voltage is above ~13V. If that is the case I can activate the relay or use the extra power for an RGB LED.

The full code is available on Github.

That’s all!