Internet of Things Foundation Service on Bluemix

Setting up an Internet of Things Foundation Service on IBM Bluemix and getting Devices to connect to the service via the MQTT protocol:



As I said,, I've been tinkering..... I decided to setup a Bluemix IoT Foundation Service, drop some client-code onto multiple Raspberry Pi's that uses MQTT for connectivity to Bluemix and then get adventurous to hook up the Arduino Robot to communicate via MQTT too.... The beauty of using MQTT....as shown in the image above, means it's a pub/sub protocol....ooooooOOOooo 2-way communications!  It also means I can have an Android mobile app running on my Samsung S6 that can allow me to monitor and manage the connected devices.

HOW TO SETUP IBM BLUEMIX

Create a new application in the Bluemix Dashboard.
Login to Bluemix using your Bluemix account.
Click Catalog from the menu at the top.
From the Boilerplates section click "Internet of Things Foundation Starter"


In the Name field, specify a unique name for your application.  I used tonybluemixmqtt
Click Create and wait a short while for your application to start.



HOW TO SETUP IOT FOUNDATION SERVICE

Click Add a Service.
Choose Internet of Things service under the Internet of Things section.
Click Create, click Restage when you are prompted to.
The service should now be created and will now be visible like this:

Click on the new service and you should see the following screen:

You can now press the [Launch dashboard] button to setup and configure the IoT Foundation Service.
As you can see, I already have the 3 Raspberry Pi's setup - you can ignore this for the moment - when you see this screen it will be empty.

Press the [Add Device] button at the bottom of the screen and you'll see the following screen to 'Add Device'.  Now, the simple way to go about this is to press the [Create device type] the first time to setup the type's of devices you want to use.  The second and subsequent times you'll just pick from the [Choose Device Type] dropdown box.

Then click [Create Device Type]

and you can now enter the details, such as the Name and Description.  I entered 'raspberryPi'.
Then select 'Next'.
You can then select which extra attributes you wish to be able to define for each device of this type:
Then select 'Next',
You can then enter some default values for the attributes:
When you then press Create you'll be returned to the 'Add Device' screen and the new type will be available in the dropdown list:
We can now add some devices, so select the value from the dropdown list and press 'Next',
You can now enter the device specific values and press 'Next',
We should then be prompted to make a decision about the Security token.  We'll go for the 'auto-generated authentication token'.

A summary screen is shown for you to confirm.
After pressing [Add] the token is generated ONCE, it cannot be looked up again - SO WRITE IT DOWN......NOW...
Once you've done that, press the (X) to close the window.  We should now see the list of devices.

HOW TO SETUP THE RASPBERRY PI'S

First of all, I'm assuming that you've installed Raspbian and have setup the networking to connect to the network to get out to the internet.
As a quick starter, I'm going to cheat a bit here and download some SAMPLE code.
(We can modify this code later on to do a variety of other things)

In a terminal window on the Pi, type
>curl -L0 https://github.com/ibm-messaging/iot-raspberrypi/releases/download/1.0.2.1/iot_1.0-2_armhf.deb

The type the following to install the package:
>sudo dpkg -i iot_1.0-2_armhf.deb

The iot process will start and will want to start publishing to the IoT Foundation service.  The iot process runs as a system service, and will start whenever the Raspberry Pi starts (so be careful as it sends data every second, if you forget, you could end up sending a lot of data over the network).
To verify the iot process is running, use the command:

>service iot status
[ ok ] iot is running.

As we've not configured anything yet, we should stop the service.
>sudo service iot stop

If you ever want to uninstall the package run:
>sudo dpkg -P iot

Now we will setup the device to be able to connect to our IoT Foundation service.

Type in the following command to create a new config file:
>sudo nano /etc/iotsample-raspberrypi/device.cfg

#Device configuration file
org = sfohua
type = raspberryPi
id = 111
auth-method = token
auth-token = yourAuthToken
#End of Configuration file

(Replace the values with the values you wrote down earlier.  Also, only token based authentication is currently supported.)

save the file by pressing CTRL-X and Y.

Start the iot process for the device to start in registered mode:
>sudo service iot start
[ ok ] iot is running.

Every second, data will be sent from the device to the IoT Foundation service.  You can see this if you look at the 'C code' that is actually running, it collects the CPU%, Temp of the Raspberry Pi and will send it via MQTT to the IoT Foundation Service (that's why you need the device.cfg file to be correct as it reads those values in the code).
Check on the Server Dashboard, click on the connected device:

You will then see values displayed underneath the 'Recent Events' as the data is received by the IoT Foundation service.



As the Raspberry Pi Sample is running in registered mode, it supports the receipt of commands sent by an Application on the server-side.
This sample supports the Reboot Command.  When the user sends this command, the Raspberry Pi will reboot based on the seconds provided in the payload.  For example, if your device is registered with Type : raspberryPi and Id : 111, then

With a Topic of:
>iot-2/type/raspberryPi/id/111/cmd/reboot/fmt/json
and with a Payload of:
{ delay : 3 }

When this command is received by the Raspberry Pi, the device will be rebooted after 3 seconds.

HOW TO SETUP THE ARDUINO ROBOT

As you may (or may not) know, I already have a Robot built that is running on multiple Arduino's with an ESP8266 WiFi board that allows the device to be connected to the Internet.

When I was building the robot, I didn't really know to what extent I was going to use the WiFi board.  I was assuming that I could pass the IR and PING values to a server that would allow me to record and possibly map the area's that the robot has been.  I wrote the code that initialised the ESP8266 and connected to the Internet, but that's as far as I got.  I was pondering how I should write the server-side part....possibly with nodeJS/ExpressJS and a cloudantDB sitting behind it.  Anyway, I did the usual, which was to get distracted and do something else until I "needed" to do something.
Well, thankfully, that "needed" time has just arrived!

We setup the Device Type in the IoT Foundation service earlier, so we have the server-side covered, we just need to modify the code on the client-side.

We "can" just use the HTTP protocol to send data from the Robot to the Server, but we want to keep our approach standardised and use the MQTT protocol.

As I've already setup my environment, I'm good to go, but if you're starting from scratch you will need to download and install the Arduino IDE - Go for a version above v1.6.4 - I found that support for ESP8266 is easier.  Once installed use the Board Manager function to add support for the ESP8266.  See here for how to do that.
Then you need to add the MQTT PubSubClient library to the Arduino IDE.  This library needs to be a recent version (from v2.3), download from here and install in the normal way.

Here's an example of the Sketch to do what is needed.  Customise the lines after //------------
with your WiFi network SSID and password and with the IoT Device credentials that we recorded earlier.
/**
 * Helloworld style, connect an ESP8266 to the IBM IoT Foundation
 * 
 * Author: Ant Elder
 * License: Apache License v2
 */
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3

//-------- Customise these values -----------
const char* ssid = "<yourSSID>";
const char* password = "<yourPassword>";

#define ORG "<yourOrganization>"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "Test1"
#define TOKEN "<yourToken>"
//-------- Customise the above values --------

char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/evt/status/fmt/json";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;

WiFiClient wifiClient;
PubSubClient client(server, 1883, callback, wifiClient);

void setup() {
 Serial.begin(115200);
 Serial.println();

 Serial.print("Connecting to ");
 Serial.print(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
 delay(500);
 Serial.print(".");
 } 
 Serial.println("");

 Serial.print("WiFi connected, IP address: ");
 Serial.println(WiFi.localIP());
}

int counter = 0;

void loop() {

 if (!!!client.connected()) {
 Serial.print("Reconnecting client to ");
 Serial.println(server);
 while (!!!client.connect(clientId, authMethod, token)) {
 Serial.print(".");
 delay(500);
 }
 Serial.println();
 }

 String payload = "{"d":{"myName":"ESP8266.Test1","counter":";
 payload += counter;
 payload += "}}";
 
 Serial.print("Sending payload: ");
 Serial.println(payload);
 
 if (client.publish(topic, (char*) payload.c_str())) {
 Serial.println("Publish ok");
 } else {
 Serial.println("Publish failed");
 }

 ++counter;
 delay(10000);
}

void callback(char* topic, byte* payload, unsigned int length) {
 Serial.println("callback invoked");
}

Once modified, upload and run the sketch.

If you open the Serial Monitor, you should see values being published to the IoT Foundation service.

>Connecting to VirginMedia.....................
>WiFi connected, IP address: 192.168.0.20
>Reconnecting client to sfohua.messaging.internetofthings.ibmcloud.com

>Sending payload: {"d":{"myName":"ESP8266.Test1","counter":0}}
>Publish ok


In the same way as the Raspberry Pi, you can now go to the IoT Foundation service Dashboard and see the data being uploaded in the 'Recent Events' section.




I was going to continue further with this particular page / article, but I realised it would make it about another 2meters longer, so I'm making a new page that will explain how to setup the IoT Insights Service for visualising the data that has been captured/sent to the server and to create Actions that can be triggered by the data (for instance, if the CPU temp reaches 46degrees, let me know via email so I can do something about it).



HOW TO MAKE AN ANDROID MOBILE APP

....to do....

1 comment:

  1. The Internet of Things (IoT) is here and is becoming an increasing topic of interest among technology giants and business communities. The hype is not baseless as there are enough evidences to support the success of “Internet of Things” in the coming years.
    Visit : http://www.esntechnologies.com/services/iot-internet-of-things/

    ReplyDelete