Sony Arouje

a programmer's log

Posts Tagged ‘MQTT

MQTT Communication with Arduino using ESP8266 ESP-01

with 76 comments

I was doing some experiments with Arduino connected to WiFi using ESP8266 module. The priority of my experiment was to establish MQTT communication with my local MQTT server and Arduino. I tried so many Arduino libraries for ESP8266 but none of them are compatible with PubSubClient, a good MQTT library for Arduino. Today I come across a library called WiFiEsp, it has similar footprints of Arduino WiFi library, and it can work with PubSubClient. This post deals with how to utilize both PubSubClient and WifiEsp libraries to establish MQTT communication with an MQTT server.

Connecting ESP8266 to Arduino

  • I powered ESP8266 directly from my Arduino’s 5V. You shouldn’t do that, it may damage the wifi module as it deals with 3.3v. This wifi module need more current than Arduino’s 3.3v pin can provide, so connecting Arduino 3.3v to Wifi module will not work. A good option is to connect Arduino 5v to a 3.3v voltage regulator like LM1117/LD117 and power the wifi module from LM*. Connect both VCC and CH_PD pin of ESP to 3.3v power.
  • ESP8266 GND to Arduino GND. If powering ESP externally then Arduino and ESP should have a common GND.
  • ESP8266 TXD to Arduino RXD, in the below sketch I used Softserial and connected to D2.
  • ESP8266 RXD to Arduino TXD. Arduino Pin supply 5v and can damage the wifi module. So I used two resistors to create a voltage divider (Google search and you will get it). In the below sketch I used Softserial and connected to D3.

 

Arduino Sketch

I decided to write a sketch to see the MQTT in action. Below sketch is just a combination of samples provided in WifiEsp and Pubsubclient. I just combined both sample codes to verify the communication, so nothing special. The end result is, Arduino could establish MQTT connection to my MQTT server and send and receive messages for subscribed topics.

 

#include <WiFiEsp.h> #include <WiFiEspClient.h> #include <WiFiEspUdp.h> #include "SoftwareSerial.h" #include <PubSubClient.h> IPAddress server(10, 0, 0, 2); char ssid[] = "XYZ"; // your network SSID (name) char pass[] = "pwd"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status // Initialize the Ethernet client object WiFiEspClient espClient; PubSubClient client(espClient); SoftwareSerial soft(2,3); // RX, TX void setup() { // initialize serial for debugging Serial.begin(9600); // initialize serial for ESP module soft.begin(9600); // initialize ESP module WiFi.init(&soft); // check for the presence of the shield if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue while (true); } // attempt to connect to WiFi network while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network status = WiFi.begin(ssid, pass); } // you're connected now, so print out the data Serial.println("You're connected to the network"); //connect to MQTT server client.setServer(server, 1883); client.setCallback(callback); } //print any message received for subscribed topic void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i=0;i<length;i++) { Serial.print((char)payload[i]); } Serial.println(); } void loop() { // put your main code here, to run repeatedly: if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect, just a name to identify the client if (client.connect("arduinoClient")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("command","hello world"); // ... and resubscribe client.subscribe("presence"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }

 

 

For testing MQTT communication, I wrote a Server and a Client couple of months ago, both are node js apps and can run in my development machine. Server uses Mosca and Client uses MQTT module.

Below is the code for Server and Client.

 

Server

var mosca = require('mosca'); var ascoltatore = { //using ascoltatore type: 'mongo', url: 'mongodb://localhost:27017/mqtt', pubsubCollection: 'ascoltatori', mongo: {} }; var moscaSettings = { port: 1883, backend: ascoltatore, persistence: { factory: mosca.persistence.Mongo, url: 'mongodb://localhost:27017/mqtt' } }; var server = new mosca.Server(moscaSettings); server.on('ready', setup); server.on('clientConnected', function (client) { console.log('client connected', client.id); }); // fired when a message is received server.on('published', function (packet, client) { console.log('Published', packet.payload); }); // fired when the mqtt server is ready function setup() { console.log('Mosca server is up and running'); }

As you can see, server uses Mongodb to persist the client connection, run a mongodb instance before running MQTT server.

Client

var mqtt = require('mqtt'); var client = mqtt.connect('mqtt://10.0.0.2', {clientId:'nodeapp'}); client.on('connect', function () { client.subscribe('command'); client.publish('presence', 'Hello mqtt'); }); client.on('message', function (topic, message) { console.log('from mqtt ' + message.toString()); });

Happy coding…

Written by Sony Arouje

March 15, 2016 at 5:35 pm

Posted in Arduino

Tagged with , ,

MQTT Protocol for Internet of Things (IoT)

with 8 comments

I was thinking about how to control my Aeroponic system remotely via internet. The Raspberry Pi controlling the system is connected to internet via a router. I could access RaspberryPi by Port forwarding and stuff like that but it’s complicated. Next option could be using Websockets but I felt it’s an overkill for the applications running in Pi.

Recently I received a Refcard from Dzone regarding a protocol called MQTT. I was not aware of this Protocol before. So thought of doing some experiment with it. I am not going much deeper into the protocol, Dzone refcard did a great job of explaining it well.

In a nutshell, MQTT consist of three parts.

  • Broker
  • Subscribers
  • Publishers

image

 

Publisher, publish message to a specific topic and any Subscriber subscribes for that topic receives the message. Broker is the central hub, both Publishers and Subscribers are connected to the Broker and it take care of delivering the message to all the subscribers subscribed for the topic.

Brokers

We can implement our own broker using RabitMQ or Mosca plugin for Node js or any other MQTT brokers available in the market. To experiment it, I used CloudMQTT addon in Heroku. I used Heroku just to manage every thing from one central place.

Dev Environment

I created two set off Node js application, one running in my computer as a publisher and another running in my RaspberryPi as a subscriber. Both have no direct connection instead they are connected to CoudMQTT broker. Below is a test code and nothing related to my Aeroponic system.

Publisher Code

var mqtt = require('mqtt');
var client = mqtt.createClient('<<PortNumber>>', 'm11.cloudmqtt.com', {
    username: '<<UserName>>',
    password: '<<Password>>'
});

client.on('connect', function () { // When connected
    
    // subscribe to a topic
    client.subscribe('TEMPERATURE_READING', function () {
        // when a message arrives, do something with it
        client.on('message', function (topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
        });
    });
    
    // publish a message to a topic
    client.publish('SET_TEMPERATURE', '24', function () {
        console.log("Message is published");
      });
});

 

The above code act as a Publisher as well as a Subscriber. For e.g. the above code can be a piece running in Internet and the Pi’s can Publish the Temperature readings in a periodic interval and logged in a central db. We can see the readings via a webapp or which ever the way we need. Also if required we can set a temperature to all the connected RPi’s by publishing a message to topic ‘SET_TEMPERATURE’.

Subscriber Code

var mqtt = require('mqtt'), url = require('url');
var client = mqtt.createClient('<<Portnumber>>', 'm11.cloudmqtt.com', {
    username: '<<UserName>>',
    password: '<<Password>>'
});

client.on('connect', function () { // When connected
    
    // subscribe to a topic
    client.subscribe('SET_TEMPERATURE', function () {
        // when a message arrives, do something with it
        client.on('message', function (topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
           // set the temperature. 
        });
    });
    
});

 

The code is very minimal and we could achieve an easy communication to all the connected devices. In the above scenario clients are always connected. If you want to end the connection then call ‘client.end()’.

Later I implemented a Broker using Mosca, both scenarios the system worked really well.

Written by Sony Arouje

September 3, 2015 at 5:29 pm

Posted in Raspberry Pi

Tagged with ,

%d bloggers like this: