Demo 14: How to use MQTT and Arduino ESP32 to build a simple Smart home system

1. Introduction
- Currently, there are many IoT protocols such as: CoAP, MQTT, AMQP, … In this tutorial, I will introduce MQTT, one of the famous IoT protocols. This protocol is to control and transfer data between devices in an IoT network
Note: for MQTTS please refer Demo 30: How to use Arduino ESP32 MQTTS with MQTTS Mosquitto broker (TLS/SSL).
MQTT is stand for Message Queuing Telemetry Transport. It has some features:
+    Use Publish/Subscribe/Topic mechanism
+    Lightweight protocol
+    Small code footprint
+    Build on top of the TCP/IP protocol
+    Less network bandwidth.
- The principal of MQTT is traditional Client-Server model. In this model, there is one MQTT Server (also called Broker) and many MQTT Clients. The MQTT Clients always keep connection with MQTT Server. The role of MQTT Server (broker) is to filter and forward the messages to subscribed MQTT Clients. The communication between clients is based on Publish/Subscribe/Topic pattern in which:
+ Message: has a topic.
+ Publish: sending the messages to network.
+ Subscribe: listening messages that contain topic that the client is interested in.
+ Broker: coordinating the communication between publishers and subscribers.
- Topic is an utf-8 string and has one - many levels which is separated by splash "/". For example: "floor1/room1/temp": this topic has 3 levels, human readable and easy to understand (we have floor 1 and in room 1 with temperature sensor). You can refer:
http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices
- Beside that, there are other concept that you need to know:
*QoS (Quality of Service): this indicator perform the guaranty of message exchange between sender and receiver. There are 3 levels:
+ QoS 0 - at most once (this level is the fastest, but not reliable)
+ QoS 1 - at least once (this is the default mode)
+ QoS 2 - exactly once (this level is the most reliable, but slowest)
You can refer at: 
*Retained Messages:  broker will keep the sent message so that when there is new subscriber that subscribe the topic that matches the retained message then that message will be sent to that subscriber.
- Most of MQTT libraries define some standard methods such as:
+    Connect(): connect to MQTT server.
+    Disconnect(): disconnect from MQTT server.
+    Subscribe(): subscribe a topic with MQTT server.
+    UnSubscribe(): unsubscribe a topic with MQTT server
+    Publish(): client publish a topic to network.
- For demo, we create a simple smart home network that have 3 client nodes (Smart phone, WiFi MCU with temperature sensor, WiFi MCU with LED/bulb controller) and 1 server node as a broker (PC or Raspberry Pi). In our application, we want to use smart phone to monitor the temperature and control the LED/bulb on or off.  So we design the MQTT model like below:
Figure: MQTT model for simple smart home application
2. Hardware
- To implement the model above, I will collect Node2 and Node3 into one node and this node is our ESP32 with DHT22 sensor and LED (bulb). Finally, we have 2 nodes: SM node and ESP32 node. We re-use the hardware schematic of Demo 13: How to display temperature/humidity using Google Chart/Jquery and control LED through Arduino ESP32 Web Server. In this demo we do not use microSD so please ignore it.
- Connections:
Connect VCC and GND of DHT22 (VCC=3.3V) to VCC (Vcc=3.3V) and GND of ESP32.
[ESP32 IO15 - DHT22 DATA]
[ESP32 IO2 - LED ANODE]
[ESP32 GND - LED CATHODE]
Figure: esp32 + dht22 + LED for MQTT smart home demo
3. Software
3.1 MQTT Client side

SM node: I will use an Android Smartphone with a MQTT client application (IoT MQTT Dashboard) that is available on Google Play. You can download it here:
https://play.google.com/store/apps/details?id=com.thn.iotmqttdashboard
ESP2 node: I will use a MQTT client library (Pubsubclient). You can download it here:
https://github.com/knolleary/pubsubclient
Then unzip the downloaded file and copy it to Arduino/libraries folder.
- This library supports some standard functions that are mentioned above. To use these function we create an instance PubSubClient client(wifiClient). Because MQTT is built on top of the TCP/IP protocol so the input of this constructor is a TCP WiFiClient object.
3.2 MQTT server side
- I will use a popular MQTT server called Mosquito. You can download and install it here:
- Windows user
http://www.eclipse.org/downloads/download.php?file=/mosquitto/binary/win32/mosquitto-1.4.11-install-win32.exe
After finishing, from command line just run this command to start mosquito server: "mosquitto"
-  Ubuntu user:
From command line type the command below: 
sudo apt-get install mosquitto mosquitto-clients
This will install mosquito as a service. You can check whether the service is start or not by using command line: 
sudo service --status-all 2>&1 | grep mosquitto
-  Other OS, just follow:  https://mosquitto.org/download/
Note: when we install mosquito, it also install 2 client programs called "mosquitt_sub" and "mosquito_pub" that we can use for debugging. 
For example:
- To monitor all topic on network using:
mosquitto_sub -v -h broker_ip -p 1883 -t "#" (change broker_ip to mqtt server ip)
- To publish a topic (publish topic room1/temp with value 30) using:
mosquitto_pub -t 'room1/temp' -m 30
 3.3 Assign roles
We define topics: 
-  Topic1: smarthome/room1/bulb #value : value can take 0 or 1 means on/off the LED (bulb).
- Topic2: smarthome/room1/temperature #value : value can take float number to express temperature.
Example: smarthome/room1/temperature 30 
With these topics SM node can subscribe Topic2 and publish Topic1. ESP32 node can publish Topic2 and subscribe Topic1.
3.4 Steps to run the system
- Start the MQTT server (on Wins invoke it manually, on Linux it is a service so just check the service is started)
- From Terminal run this: mosquitto_sub -v -h broker_ip -p 1883 -t '#' for debugging. You will see all the messages on the network.
- Create an Arduino project and Save as esp32mqtt with 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
117
118
119
120
121
122
123
124
125
126
127
128
129
/* Here ESP32 will keep 2 roles: 
1/ read data from DHT11/DHT22 sensor
2/ control led on-off
So it willpublish temperature topic and scribe topic bulb on/off
*/

#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"

/* change it with your ssid-password */
const char* ssid = "dd-wrt";
const char* password = "0000000000";
/* this is the IP of PC/raspberry where you installed MQTT Server 
on Wins use "ipconfig" 
on Linux use "ifconfig" to get its IP address */
const char* mqtt_server = "192.168.1.103";

/* define DHT pins */
#define DHTPIN 14
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
float temperature = 0;

/* create an instance of PubSubClient client */
WiFiClient espClient;
PubSubClient client(espClient);

/*LED GPIO pin*/
const char led = 12;

/* topics */
#define TEMP_TOPIC    "smarthome/room1/temp"
#define LED_TOPIC     "smarthome/room1/led" /* 1=on, 0=off */

long lastMsg = 0;
char msg[20];

void receivedCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message received: ");
  Serial.println(topic);

  Serial.print("payload: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  /* we got '1' -> on */
  if ((char)payload[0] == '1') {
    digitalWrite(led, HIGH); 
  } else {
    /* we got '0' -> on */
    digitalWrite(led, LOW);
  }

}

void mqttconnect() {
  /* Loop until reconnected */
  while (!client.connected()) {
    Serial.print("MQTT connecting ...");
    /* client ID */
    String clientId = "ESP32Client";
    /* connect now */
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      /* subscribe topic with default QoS 0*/
      client.subscribe(LED_TOPIC);
    } else {
      Serial.print("failed, status code =");
      Serial.print(client.state());
      Serial.println("try again in 5 seconds");
      /* Wait 5 seconds before retrying */
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  /* set led as output to control led on-off */
  pinMode(led, OUTPUT);

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

  /* configure the MQTT server with IPaddress and port */
  client.setServer(mqtt_server, 1883);
  /* this receivedCallback function will be invoked 
  when client received subscribed topic */
  client.setCallback(receivedCallback);
  /*start DHT sensor */
  dht.begin();
}
void loop() {
  /* if client was disconnected then try to reconnect again */
  if (!client.connected()) {
    mqttconnect();
  }
  /* this function will listen for incomming 
  subscribed topic-process-invoke receivedCallback */
  client.loop();
  /* we measure temperature every 3 secs
  we count until 3 secs reached to avoid blocking program if using delay()*/
  long now = millis();
  if (now - lastMsg > 3000) {
    lastMsg = now;
    /* read DHT11/DHT22 sensor and convert to string */
    temperature = dht.readTemperature();
    if (!isnan(temperature)) {
      snprintf (msg, 20, "%lf", temperature);
      /* publish the message */
      client.publish(TEMP_TOPIC, msg);
    }
  }
}
- From Android smart phone, open IoT MQTT Dashboard) and follow steps below to set up it a MQTT client:
Figure: Configure MQTT Server that it will connect to
Figure: After configuring server, choose it 
Figure: Choose Subscribe tab and create topic temp
 Figure: Choose Publish tab to create a Switch for toogling LED
 Figure: Fill topic led for Switch
Figure: After finishing, here is the GUI for Publish tab, one Switch
 Figure: You can see smart phone received temp topic 
4. Result 

Post a Comment

66 Comments

Anonymous said…
I appreciate your tutorial, yet there are some mistakes that should be clarified, the most obvious being your statement:
"Topic: the message that is transferred on network"
A topic by far is not a message itself but rather a category for a message.
The client is never sending topics but sending messages that have a / a classified for a specific topic.
You should possibly consider a topic string as part of a message object from a sending client perspective.
Thank you very much, I updated it. I just want to express it in a general way so that users are easy to understand. :)
Jvision Apps said…
good effort...!very useful
UbiBot said…
IOT Based products changed the world. I would like to share this informative article with https://www.ubibot.io/ team.
Zuan said…
Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
mobile application development training online
mobile app development course
mobile application development training
mobile app development course online
mobile application development course
online mobile application development
learn mobile application development
adhi said…
thanks for your information really good and very nice web design company in velachery
daizy mathew said…
Thanks for sharing this useful information.
python training in chennai
daizy mathew said…
Thanks for sharing this useful information
php training in chennai
divi said…
Hi, Thanks for the great information and it is very useful to read your blog with easily understand for all readers. Well done!
web design company in velachery
Galia Co Hagan said…
Great Article. Thank you for sharing! Really an awesome post for every one.

IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

JavaScript Training in Chennai

JavaScript Training in Chennai
It’s interesting content and Great work....Sarkari Job are an attraction to a huge Indian population. Whenever one looks for a settled future, we tend to look at SSC Jobs, Railway Jobs, Bank Jobs, Defence Jobs and Civil Service Jobs.
samso said…
Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
Java training in chennai
Java training institute in chennai
Java course in chennai
Java training classes
Java training
Java programming classes
core java coure
<a
PYTHON TRAINING IN JAIPUR
Hey, Are you looking for the best python training in Jaipur ,so grab this opportunity . DZONE is here for you with the best online and offline Classes ,Techniques and Experiences .Join us to improve your skills and Better Future
REGISTRATION OPEN!!
ENROLL NOW!!
To book free demo session, feel free to call us at 8432830240 or 0141-4108506.
PHP Training In Jaipur
Hey, Are you looking for the best PHP online/offline training in Jaipur ,so grab this opportunity . DZONE is here for you with the best Techniques and Experiences .Join us to improve your skills and Better Future
https://traininginstituteinjaipur.net/
REGISTRATION OPEN!!
ENROLL NOW!!
To book free demo session, feel free to call us at 8432830240 or 0141-4108506.
#php #phptraining #phpinternship #phpwinterinternship #php #learnig #phpcareer #phpjobs #phpprogramming #phpinternhsip #phptraining
One of the greatest benefits of digital marketing is that it allows you to target your ideal buyers.
We Provide complete digital marketing course in 3 months.
include in this course: SEO, SEM,GOOGLE ADS,Email Marketing, Web Development etc.
✔️100% Best knowledge
✔️professional and experienced
✔️practical training
✔️100% certification after the complete cours
✔️Online Classes are available
DZone Internship/Training 2020
Are you searching for Python | Machine Learning | Data Science | Tableau | Java | Android | P.H.P | Digital Marketing Internship in Jaipur? Join our project based Job-Oriented online/offline Training under expert guidance. Hurry!! 50% discount available on all Courses. To Avail this Opportunity Reserve Your Seats Now !! ENROLL NOW!! To book free demo session, feel free to call us at 8432830240 or 0141-4108506..
subha said…
Great efforts put to find the list of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create relations. You’re doing great work. Keep it up. thanks
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
Tino Best said…
It helps the retailer to manage data and create a psychological picture of the customer to learn their sore points. Therefore, this trick used by the retailer tends to influence the customer easily. data science course syllabus
Mark Cybert said…
I liked your video. And even buy youtube likes from this site https://soclikes.com/ for you
Ashok said…
This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.

data science course in India
technology said…
If you have the proficiency in these fields, you will have an added advantage over other professionals. Once you become an expert, you can demand a higher pay. data science course syllabus
Ashok said…
You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!!
Artificial Intelligence Course
I am glad to post a worthy article about the German Language Course and IELTS Coaching from KCR consultants, this may change your career growth and language skill.
KCR-German Language
KCR CONSULTANTS
jhansi said…
Nice Blog, Keep post more Blogs Thanks for sharing.clearly explained the multi tools latest version in android.
tally training in chennai

hadoop training in chennai

sap training in chennai

oracle training in chennai

angular js training in chennai
technology said…
How could that person be true to the values and the brand of the company, which the chief executive has spent so much time, energy and money developing? Salesforce interview questions
Aishwariya said…
Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
Primavera p6 Training Online | Primavera Training Chennai
Maradona Jons said…
Kardinal Stick Siam - relx a great promotion. Express delivery in 3 hours.

ufa football betting, casino, slots, lottery, direct website 1688, stable financial, 100% UFABET168.

Online Baccarat FOXZ24 Easy to apply, fast, บาคาร่า deposit-withdraw 10 seconds with the system.

Watch movies online sa-movie.com, watch new movies, series Netflix HD 4K ดูหนังออนไลน์, watch free movies on your mobile phone, Tablet, watch movies on the web.

SEE4K Watch movies, watch movies, free series, load without interruption, sharp images in HD FullHD 4k, ดูหนังใหม่ all matters, all tastes, see anywhere, anytime, on mobile phones, tablets, computers.

GangManga read manga, read manga, read manga online for free, fast loading, clear images in HD quality, อ่านการ์ตูน all titles, anywhere, anytime, on mobile, tablet, computer.

Watch live football ผลบอลสด, watch football online, link to watch live football, watch football for free.
aishu said…
Thanks for spending all your pleasant time to make such a Creative content for us. AWS Training in Chennai
With special privileges and services, UEFA BET offers opportunities for small capitalists. Together ufa with the best websites that collect the most games With a minimum deposit starting from just 100 baht, you are ready to enjoy the fun with a complete range of betting that is available within the website

ufabet , our one another option We are a direct website, not through an agent, where customers can have great confidence without deception The best of online betting sites is that our Ufa will give you the best price
อีกทั้งเรายังให้บริการ เกมสล็อต ยิงปลา แทงบอลออนไลน์ รองรับทุกการใช้งานในอุปกรณ์ต่าง ๆ HTML5 คอมพิวเตอร์ แท็บเล็ต สมาทโฟน คาสิโนออนไลน์ และมือถือทุกรุ่น เล่นได้ตลอด 24ชม. ไม่ต้อง Downloads เกมส์ให้ยุ่งยาก ด้วยระบบที่เสถียรที่สุดในประเทศไทย

Maradona Jons said…
หาคุณกำลังหาเกมส์ออนไลน์ที่สามารถสร้างรายได้ให้กับคุณ เรามีเกมส์แนะนำ เกมยิงปลา รูปแบบใหม่เล่นง่ายบนมือถือ คาสิโนออนไลน์ บนคอม เล่นได้ทุกอุปกรณ์รองรับทุกเครื่องมือ มีให้เลือกเล่นหลายเกมส์ เล่นได้ทั่วโลกเพราะนี้คือเกมส์ออนไลน์แบบใหม่ เกมยิงปลา
thomas said…
ยูฟ่าเบท หรือ UFABET คือ เว็บให้บริการเดิมพันออนไลน์แบบครบวงจรโดยไม่ผ่านเอเย่นต์หรือตัวแทนใดๆ ซึ่งมีเกมและกีฬาให้เลือกเดิมพันมากมายหลากหลายประเภท รวมไปถึงคาสิโนออนไลน์หลายชนิด UFABET ถือได้ว่าเป็นเว็บไซต์ให้บริการเดิมพันออนไลน์ที่ผู้คนส่วนใหญ่นิยมใช้บริการ เพราะด้วยรูปแบบเว็บไซต์ที่ใช้งานง่ายและไม่จำเป็นต้องทำความเข้าใจอะไรเยอะ ประกอบกับเว็บนี้ยังรองรับการใช้งานในหลายๆภาษา ทั้ง จีน ฮ่องกง ไทย อังกฤษฯ จึงทำให้ผู้ใช้งานส่วนใหญ่ทั้งหน้าใหม่หรือหน้าเก่าต่างเลือกที่จะหันมาใช้บริการกับทาง ยูฟ่าเบท มากขึ้น จึงเป็นเว็บเดิมพันออนไลน์ที่ดีที่สุดในภูมิภาคเอเชีย ufa
Alia parker said…
Microsoft Project (MSP) is an extended administration program made for project directors so they can control their projects. Depending on your arrangement, Microsoft Project lets you arrange projects, relegate assignments, oversee assets, make reports, and more. Microsoft Project Training
pgslot ซึ่งเกมคาสิโนออนไลน์เกมนี้เป็นเกมที่เรียกว่าเกม สล็อตเอ็กซ์โอ คุณรู้จักเกมส์เอ็กซ์โอหรือไม่ 90% ต้องรู้จักเกมส์เอ็กซ์โออย่างแน่นอนเพราะในตอนนี้เด็กนั้นเราทุกคนมักที่จะเอาก็ได้ขึ้นมา สล็อต เล่นเกมส์เอ็กซ์โอกับเพื่อนเพื่อนแล้วคุณรู้หรือไม่ว่าในปัจจุบันนี้เกมส์เอ็กซ์โอนั้นกลายมาเป็นเกมซะลอสออนไลน์ที่ให้บริการด้วยเว็บคาสิโนออนไลน์คุณสามารถเดิมพันเกมส์เอ็กซ์โอกับเว็บคาสิโนออนไลน์ได้โดยที่จะทำให้คุณนั้นสามารถสร้างกำไรจากการเล่นเกมส์เดิมพันออนไลน์ได้เราแนะนำเกมส์ชนิดนี้ให้คุณได้รู้จักก็เพราะว่าเชื่อว่าทุก

Jon Rarine said…
This article was quite interesting to read. I’d want to express my gratitude for the time and attention you put into making this fantastic post. Enterprises may use our industrial IoT platform to create unique IoT applications. UbiBot create, deploy, and support an industrial IoT platform that enables you to create custom industrial IoT applications for your business. Our IoT platform is only offered to manufacturers and government agencies working on smart city projects.

KROOTEZ said…
Your post is exactly what I was looking for. There are a few existing solutions for smart homes on the market such as the Xiaomi smart home set, for example. Arduino has a lot of pros for its flexibility. Many posts on Instagram talk about it, look for the ones that have dozens of likes and comments on. By the way, you can get the same numbers on any post by simply following to https://krootez.com/buy-instagram-likes/. They got an ultimate set of tips on how to win more eyes for your posts on IG devoted to smart homes.
Jobi Johnson said…
Thanks for posting this info. I just want to let you know that I just check out your site. Blade Runner 2049 Coat
John P. Ketchum said…
We help private individuals top security companies in London
and companies all over the UK with a wide range of complex assignments requiring specialist services to securely and safely deliver or protect their assets.
fantasy expert 11 Cricket Fantasy League with Best play Fantasy Cricket App Play Cricket earn Money. Download App to know more Play and win Exclusive Prizes & Experiences only with Fantasy Power 11.Instant Paytm Withdrawal Fantasy Power 11 Fantasy Cricket Best App
Great post I would like to thank you for the effort you put into writing this interesting and informative article, no matter what is the purpose of your trip to Turkey, you need to pay the visa cost Turkey before submitting the visa application .Depending on your desired option, the e Visa Turkey cost are calculated.
What Should I Do To Resolve Cash App Won't Let Me Send Money Issue?
Do you know what you would do if Cash App Won't Let Me Send Money? In such a case, you will need to share your problems and hurdles permanently from the root. All you have to do is to take necessary suggestions and troubleshooting assistance to get rid of such problems within the least time frame.
Great info.. Thank you If you are transiting through Kenya to your destination, then you can apply online for Kenya transit visa through online Kenya e vias application