ESP8266 MQTT Client Mosquitto Node-RED
For some time now the IoT Internet of things has been booming, opening up a possibility of interconnecting an Internet device, one of the most well-known protocols implemented is the MQTT protocol, this TCP/IP lightweight messaging protocol is excellent for sending Bidirectional data (sensors, actuators, etc.). An MQTT Broker installer is required in case of local tests as in this case, although there is a large number of IoT Platforms that have already implemented it.
This compilation of Tutorial videos about Node-RED will be a good introduction to this platform: Node-RED IoT.
Test
We will perform a small test of ESP8266 12E NodeMCU Lolinfde as an MQTT client, in this way our module (Client MQTT) through Mosquitto (Broker) will connect with Node-RED (Client MQTT).
We have connected a led diode (GPIO D15) and a pushbutton (GPIO D0) to module ESP8266, from Node-RED Dashboard activate and deactivate the led diode and display the status of the pushbutton.
Two MQTT topics have been created:
- client_MQTT.subscribe(“output”); /// activate Led – activa led
- client_MQTT.publish(“input”,buf); //// Array char mensage MQTT /// state input – estado entrada.
The following tutorial will explain the main points of the application.
ESP8266 MQTT Client Node-RED Mosquitto
Note: In this case the ESP8266 is constantly sending the value of the Input button and reading Output status, it is recommended to make periodical requests using delay’s to avoid conflicts.
IDE Arduino Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
#include <ESP8266WiFi.h> #include <PubSubClient.h> /* * Modified by Trialcommand * More Tutorials: * Website http://trialcommand.com * */ const char* ssid = "************"; const char* password = "*************"; const char* mqtt_server = "**************"; /// example 192.168.0.19 int mqtt_port = 1883; WiFiClient espClient; PubSubClient client_MQTT (espClient); void setup() { pinMode(14, OUTPUT); pinMode(16, INPUT); Serial.begin(9600); setup_wifi(); client_MQTT.setServer(mqtt_server, mqtt_port); client_MQTT.setCallback(callback); } void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); Serial.println("."); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("Connected "); Serial.print("MQTT Server "); Serial.print(mqtt_server); Serial.print(":"); Serial.println(String(mqtt_port)); Serial.print("ESP8266 IP "); Serial.print(WiFi.localIP()); } /* funtion callback * * Esta funcion realiza la recepcion de los topic suscritos * This function performs the reception of subscribed topics * */ void callback(char* topic, byte* payload, unsigned int length) { String string; Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { // Serial.print((char)payload[i]); string+=((char)payload[i]); } Serial.println(string); if (topic ="output") { /// select topic "output" Serial.print(" "); int resultado = string.toInt(); digitalWrite(14, resultado); } } /* * * Funcion que realiza la reconexion de cliente MQTT * Function that performs MQTT client reconnection * * enable/habilita client_MQTT.subscribe("event"); */ void reconnect() { // Loop until we're reconnected while (!client_MQTT.connected()) { if (client_MQTT.connect("ESP8266Client")) { } else { Serial.print("failed, rc="); Serial.print(client_MQTT.state()); } } } void loop() { if (!client_MQTT.connected()) { reconnect(); /// reconection MQTT } client_MQTT.loop(); client_MQTT.subscribe("output"); /// activate Led - activa led char buf[5]; /// array char String valor =String(digitalRead(16)); //// input to string String (valor).toCharArray(buf, 5); /// String to array char client_MQTT.publish("input",buf); //// Array char mensage MQTT /// state input - estado entrada } |
Subscribe
To define a subscription requires the function “client_MQTT.subscribe (” output “);” and the message will return messages in the function callback performs the reception of all subscriptions, with an if the required topics are filtered and assigned to local variables .
1 |
client_MQTT.subscribe("output"); /// activate Led - activa led |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
void callback(char* topic, byte* payload, unsigned int length) { String string; Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { // Serial.print((char)payload[i]); string+=((char)payload[i]); } Serial.println(string); if (topic ="output") { /// select topic "output" Serial.print(" "); int resultado = string.toInt(); digitalWrite(14, resultado); } } |
Publish
The function to publish “client_MQTT.publish (” input “, buf);” Use the parameters “topic”, “message” in this case the value of the input is converted from int to String, the function does not accept Strings, uses char array in this case and we have implemented this conversion function.
1 2 3 4 |
char buf[5]; /// array char String valor =String(digitalRead(16)); //// input to string String (valor).toCharArray(buf, 5); /// String to array char client_MQTT.publish("input",buf); //// Array char mensage MQTT /// state input - |
Conclusions
The MQTT protocol has become one of the standard protocols for Internet applications of IoT things. Comparing with other protocols we will mention some advantages:
- It allows the sending of Strings without limiting to Numbers.
- Send messages without requiring specific names of records.
- Simple grouping and organization of records can be performed.
- We consider that it is very fast, although in our example we abuse to have a constant sending, it is recommended to send data in fixed intervals.
Node-RED
Node-RED is a great tool for applications of these characteristics and has a Dashboard that allows a large number of applications.
Referencias
- Tutorials : Node-RED IoT.
- Install Lubuntu (Ubuntu) from Zero
- Installation of Mosquitto Broker MQTT in lubuntu (Ubuntu) linux
- Node-RED Platform Installation
- Node-RED Dashboard installation
Downloads
PubSubClient MQTT Client library for ESP8266
Created by knolleary Thank for contributions to community IoT!