ESP8266 IBM Bluemix MQTT Client

This example contains the Arduino code that runs on the NodeMCU ESP8266 that publishes data collected from a Dallas 18B20 one wire temperature sensor that is attached to the NodeMCU board to the IBM Bluemix MQTT server that is part if the Bluemix IoT Foundation Service.

The example publishes to the following topic

iot-2/evt/status

and subscribes to the following topic

iot-2/cmd/

both in JSON format


To use this code you need to input your details for:
const char* ssid = "Your SSID";
const char* password = "Your password";
#define ORG "Your IBM Bluemix Organisation"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "Device MAC address"
#define TOKEN "Your Authentication token"

Upload the sample code below to the ESP8266. The device should connect to your WiFi Network and print the MAC address. Once you have the MAC address use this to as the device ID when you add the device to your IBM IoT Service following the instructions here.

/**
* Temperature sensing platfrom ESP8266 to the IBM IoT Foundation
*
* Modified from the original by: Ant Elder
* Author: Benn Thomsen
* License: Apache License v2
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>

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

#define ORG "Your IBM Bluemix Organisation"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "Device MAC address"
#define TOKEN "Your Authentication token"
//-------- Customise the above values --------

char mqtt_server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char pubtopic[] = "iot-2/evt/status/fmt/json";
char subTopic[] = "iot-2/cmd/+/fmt/json"; // MQTT subscribe topic
int mqttPort = 1883; // Port for MQTT connection
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
#define ONE_WIRE_BUS D4 // DS18B20 pin
#define REDLED D0 // GPIO16 labelled pin D0 on NodeMCU board this pin is also connected to the LED cathode on the NodeMCU board also used for wake on deep sleep

void callback(char* subtopic, byte* payload, unsigned int length) {
StaticJsonBuffer<200> jsonBuffer;
char message[200];
Serial.print("Message arrived [");
Serial.print(subtopic);
Serial.print("] ");

if(strstr(subtopic, "/cmd/light") != NULL) {
Serial.print("Command IS Supported : ");
for (int i = 0; i < length; i++) {
message[i] = (char)payload[i];
}
Serial.println();
JsonObject& root = jsonBuffer.parseObject(message);

if (root.success()) {
root.printTo(Serial);
Serial.println();
int cmd = root["d"]["light"];;
if(cmd) digitalWrite(REDLED,LOW);
else digitalWrite(REDLED,HIGH);
}
else {
Serial.println("parseObject() failed");
}
}
else {
Serial.print("Command is not Supported");
}
}

WiFiClient wifiClient;
PubSubClient client(mqtt_server, mqttPort, callback, wifiClient);

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);

float getTemperature() {
Serial.println("Requesting DS18B20 temperature...");
float temp;
do {
DS18B20.requestTemperatures();
temp = DS18B20.getTempCByIndex(0);
delay(100);
} while (temp == 85.0 || temp == (-127.0));
return temp;
}

void setup() {
pinMode(REDLED,OUTPUT);
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());
Serial.print("MAC address: ");
Serial.println(WiFi.macAddress());
}

int counter = 0;

void loop() {

if (!client.connected()) {
Serial.print("Reconnecting client to ");
Serial.println(mqtt_server);
while (!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
Serial.println("Connected");
// Subscribe to topic to receive data from MQTT server
if(client.subscribe(subTopic)){
Serial.println("Subscribe ok");
} else {
Serial.println("Subscribe failed");
}
}

float temperature = getTemperature();

String payload = "{\"d\":{\"myName\":\"ESP8266.";
payload += DEVICE_ID;
payload += "\",\"counter\":";
payload += counter;
payload += ",\"temperature\":";
payload += temperature;
payload += "}}";

Serial.print("Sending payload: ");
Serial.println(payload);

if (client.publish(pubtopic, (char*) payload.c_str())) {
Serial.println("Publish ok");
} else {
Serial.println("Publish failed");
}

client.loop(); // Check for any messaged that the system subscribes to..

++counter;
delay(10000);
}

Advertisements