Connect the ESP8266 to IBM Bluemix

IBM Bluemix

In the previous tutorial I introduced to you the MQTT protocol and showed you how to use it with the ESP8266 system on a chip. Although we developed some simple applications, I hope you can see the potential of the MQTT.

In the next few tutorials we will use a platform called IBM Bluemix to build more complex IoT applications.

What is IBM Bluemix?

IBM Bluemix is a cloud platform as a service (PaaS), which means that it allows customers to develop, run and manage applications without the complexity of building and maintaining the whole infrastructure that is normally associated with application development. The reason we are using it is that it offers IoT services – we can easily connect and manage our devices. In addition to that, there are plenty of other services that we can easily connect our applications to, that allows us to quickly develop fairly complex systems. As an electronics engineer and someone who hasn’t experience in web/cloud development, I find IBM Bluemix as an excellent platform to build applications that would otherwise require me to spend a lot of time learning new things from scratch. Instead being stuck and giving up from my idea or desperately asking someone for help, with IBM Bluemix I can do a lot of cool stuff. For example, I need to visualize all my devices on a map, with the possibility to retrieve particular sensor value by clicking on a marker on a map that represents one of my devices, that’s something you can easily and quickly develop with IBM Bluemix and I will show you how to do that in this series of tutorials.

In order to start building your applications you have to make an account. Go to https://console.ng.bluemix.net/ and sign up. You can use IBM Bluemix completely free for 30 days. After that, you have to add your credit card, but you won’t be charged unless you exceed certain limit, which is enough if you are just playing around or testing your ideas and you still don’t plan to use it for commercial purposes. For more details about pricing click here.

After you make an account, log in. First time you log in a window asking you to set up environment should be displayed.

Setting up environment

Name your organization (project or team that shares resources, such as apps, databases, and other services) and choose the region (geographic region where your organization exists). For region choose US South because some features that we will use are support only in that region right now. New organizations can be added later if needed. Now you have to choose space name, dev for example. After setting up your environment, you are ready to use IBM Bluemix.

If you go to the Dashboard, in your space you can see all applications you create and also all services, containers and virtual servers you choose to use.

Main dashboard

We haven’t created anything yet. Under Catalog tab, you can see plenty options for development, various services (Boilerplates, Data, Mobile, third party…) that you can use to build wide variety of applications.

Catalog

 

IoT Platform

At the bottom, you will see Internet of Things section. Click on the Internet of Things Platform.

Choose free plan, which has certain limitations but it is more than enough for us now. This service will be unbound because we don’t have any apps yet. Later on, when we start building our app we will bind this service to it so that we can exploit its features. Click create.

Create IoT platform

If you go back to main dashboard, you should see Internet of Things Platform under services.

We want to connect our devices to Bluemix. In order to do that, launch Internet of Things Platform dashboard.

Launch IoT Platform dashboard

On the left side of the dashboard, click devices.

Go to Devices

Click Add Device

You can choose to add a new device or to create a device type. Since we don’t have any device types created yet, we have to create one. We will call this type ESP8266. We have to do this only once for each device type. After we create this type, we have to use it whenever we want to add a new ESP8266 device. Click create device type and name it ESP8266. Description is optional. Click next. There are some other fields (serial number, manufacturer, model…) that you can select but they are not mandatory. Continue with this process until you can click the create button. We still haven’t added any particular devices, we have just created a template, a device type, that we have to choose each time we want to add a new device. Now choose ESP8266 device type and click next. We need to add a device ID. Device ID should be the MAC address of your ESP8266 module. To obtain address, you can use this program:

#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  String clientMac = "";
  unsigned char mac[6];
  WiFi.macAddress(mac);
  clientMac += macToStr(mac);
  Serial.println();
  Serial.println(clientMac);
}

String macToStr(const uint8_t* mac){
 String result;
   for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);
   if (i < 5)
    result += ':';
 }
 return result;
}

void loop() {

}

When adding a device ID, all letters should be capitalized and remove all colons, for example: 18FE34D81E46. If you want, you can fill additional fields about manufacturer, model etc. and proceed. You can avoid metadata and click the next twice. You should see the summary of the device.

Add your ESP8266 device

Click Add. The window that appears is very important. You have to copy authentication token now, because you won’t be able to access it any more after you close the window! Copy all parameters because you will need them in the code.

Copy these strings

You have added a new device and you should see it in the dashboard.

List of all your devices

You can register up to 20 devices for free plan of the Internet of Things Platform.

 

Publishing Events to Bluemix

We are ready to connect our physical device, the ESP8266 module, to Bluemix. We will use the same library and similar code as in the previous tutorial. Difference is that this time there is a security protection and we have to provide authentication token. Firstly, our device will be publisher. We will set the counter and publish its value in regular intervals. Update the following code with the parameters you have just saved and upload it to the ESP8266. Also, don’t forget to add SSID and password for WI-FI connection.

#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3

//-------- Customise these values -----------
const char* ssid = "";
const char* password = "";

#define ORG "<yourOrganization>"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "<yourDeviceID>"
#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, NULL, 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\":{\"Name\":\"18FE34D81E46\"";
 payload += ",\"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");
 }

 delay(5000);
}

Take a look at the topic string. Evt refers to events, which means that we are publishing events. We could also put cmd for command. String ends with fmt/json which means that data is published in json format. If we want to publish data as an arbitrary string, we could put fmt/String. After you upload the code, find the device you have added in IoT Platform dashboard and click on it. You should see new events under Recent Events section if your device is successfully publishing counter values.

Published events

If you can see events arriving in regular intervals, congratulations, you have successfully connected your device to IBM Bluemix.

 

Create an App with Node-RED

What now? At the moment, we are able to verify that our device connects to Bluemix and publishes some data which we can see in event list, but we can’t do much more than that. We want to make use of our data, store it, graph it, set triggers and act upon it. That’s why we are going to build an application.

In the main dashboard, click Create App and choose Web.

Create app

You can see that Bluemix supports several programming languages. We will build our app using Node-Red. It is a visual tool for wiring together hardware devices, APIs and online services. Let’s build our app firstly and then you will have a better insight in Node-Red. Click on browse boilerplates and choose Node-Red Starter. Enter your app name and click create. After some time, if everything went ok, your app will be running. If you go to the main dashboard, you should see your app listed under applications. If you click on it, you will see app status, available memory, bound services etc. Note that Cloudant Database service is bound to your app by default.

App overview

You can access your app by clicking on the link <app name>.mybluemix.net (http://esp8266iot.mybluemix.net in my case). Click on the link and open Node-Red flow editor. On the left side, you can see nodes divided in several categories (input, output, function, storage etc.) Nodes are building blocks of our app. We place them in the editor and wire them to create a flow. You can have many flows within an editor. After we finish with wiring nodes, we click Deploy button in the upper right corner. For example, the simplest possible flow looks like this:

Simple flow

Inject and debug nodes wired together. Double click on the inject node to configure it. Choose string as payload type and enter arbitrary payload, “Hello World” for example. Each time you click inject, the string you entered is displayed on the debug console (to see debug console click debug under Deploy button).

Here is slightly more complicated flow. We have added a function node with JavaScript code to analyze input number.

Simple flow with function node

You get the idea now. You choose nodes and wire them to build functional flows that form our application.

How can we see incoming data from our devices within the app? There is a node called IBM IoT node among input nodes, but before we start using it, we need to bind the Internet of Things Platform service to our app. Go to status page of your app (from the main dashboard), click Bind a Service or API, check Internet of Things Platform service, click Add and restage your app.

Bind IoT Platform to your app

After the process of restaging is finished, you are ready to use IoT nodes. Let’s go back to Node-Red editor. For the begging, we will make the simplest possible flow – an IoT input node and debug node wired together. Later on, we will add function, storage and many more nodes.

Flow with IoT In node

Configure IoT In node

Replace device ID with the ID of your ESP8266 module. Input type field has to correspond with the code. Since we have put evt in the topic, we had to selected Device Event. Deploy your app. If you could see published events in IoT Platform dashboard, like described before, you should see published events in the debug console.

Debug console with published events

 

Sending Commands to ESP8266

If we want our device to subscribe to a certain topic and receive commands from Bluemix, we have to use IBM IoT output node. This time will also create very simple flow:

Flow with IoT Out node

Each time we press inject node, a string we specified (command 1) is sent to the ESP8266 and printed on serial monitor within callback function. Configuration of the IBM IoT output node has to correspond to the topic.

Configure IoT Out node

Upload the following code:

#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3

const char* ssid = "";
const char* password = "";

#define ORG "<yourOrganization>"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "<yourDeviceID>"
#define TOKEN "<yourToken>"

char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/cmd/test/fmt/String";
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();
  wifiConnect();
  mqttConnect();
}

void loop() {
  if (!client.loop()) {
    mqttConnect();
  }
}

void wifiConnect() {
  Serial.print("Connecting to "); Serial.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.print("nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}

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

void initManagedDevice() {
  if (client.subscribe(topic)) {
    Serial.println("subscribe to cmd OK");
  } else {
    Serial.println("subscribe to cmd FAILED");
  }
}

void callback(char* topic, byte* payload, unsigned int payloadLength) {
  Serial.print("callback invoked for topic: "); Serial.println(topic);

  for (int i = 0; i < payloadLength; i++) {
    Serial.print((char)payload[i]);
  }
}

In this tutorial you have learnt how to set up Bluemix environment, use the Internet of Things service to connect devices and exchange data and make an app using Node-Red editor. Although we build very simple flows in our app, they are very important since they will foundation for later projects.

Lessons of this Series

Online computer science courses to jumpstart your future.
WP Engine Managed WordPress Hosting

Trending

Newsletter

Subscribe to our newsletter for good news, sent out every month.

Tags