ESP32 MQTT

Hello readers, today we will learn about the messaging protocol supported by ESP32(called MQTT protocol), which is used for IoT applications. The communication protocol to be used for data transmission and connectivity in web-enabled devices depends upon the type of IoT application.

The Internet of Things (IoT) is a network of interconnected computing devices like digital machines, automobiles with inbuilt sensors, having unique identifiers and the ability to communicate data over a network without the need for human intervention.

Before implementation, let's first have a look at what is MQTT Protocol?
Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

What is MQTT?

  • MQTT stands for Message Queuing Telemetry Protocol and is a messaging or communication protocol used for IoT applications.
  • In MQTT protocol, a publisher sends a message to the broker with a specific topic tag, and the broker forwards this message to all the Subscribers of that mentioned topic.
  • So, in order to understand MQTT Protocol, we need to discuss these 4 terms:
    1. MQTT Topic
    2. MQTT Publisher
    3. MQTT Broker
    4. MQTT Subscriber
Note:
  • The OASIS technical committee is the in-charge of MQTT specifications. The OASIS or the Organization for the Advancement of Structured Information Standards is a non-profit organization dedicated to the development, convergence, and implementation of electronic business standards.

Fig 1: ESP32 MQTT Protocol

MQTT Topic

  • In MQTT protocol, a Topic is simply a UTF-8 string i.e. "Arduino", "ESP32", "Beginner Tutorials" etc.
  • MQTT Clients can subscribe to these Topics and are called Subscribers to that Topic.
  • MQTT Broker sends messages to the Clients based on their Topic subscription.
  • A topic may have multiple levels, separated by a forward slash.

MQTT Publisher

  • MQTT Publisher(also called MQTT client), as the name suggests, publishes the message on a specific topic and sends it to the broker.
  • In simple words, a publisher sends a message(normally a string) to the MQTT Broker, and this message also contains the Topic information.

MQTT Broker

  • MQTT Broker(also called MQTT server) acts as a coordinator between the subscriber and the publisher in order to create communication.
  • The broker's job description is as follows:
    • Receiving messages from the publisher
    • Filtering received messages based on assigned Topics from the publisher.
    • Determining the interested subscriber in each message based on the assigned Topic
    • Finally forwarding the messages to subscribers

MQTT Subscriber

  • MQTT Subscriber(also called MQTT client), subscribes to the MQTT Topics and receives the messages from the MQTT broker, sent by the Publisher.

How does MQTT Work

This messaging protocol follows the Publish and Subscribe model. The Publisher and Subscribers of the message, communicate via Topics and are separated from one another. The broker is in charge of their communication. The broker's job is to filter all incoming messages and distribute them to the subscribers in the most efficient way possible. The broker pushes the information to the client whenever something new becomes available, so the client doesn't have to pull the information.

Because there are so many ready-to-use brokers and client applications, getting started with MQTT is a breeze.

Fig 2: MQTT Publish and Subscribe architecture

MQTT Features

Light Weight

It is a lightweight and versatile IoT communication and data transfer protocol aimed at IoT developers who want to strike a compromise between flexibility and network resources.

All the MQTT messages have a small footprint which adds a lightweight feature to this protocol.

In MQTT every message has:

  1. 2-byte header (fixed)
  2. A 256 MB message payload
  3. A 2-byte variable header (optional)

Security

MQTT protocol implementation will allow you to use your User name and password for security purposes. If you added the authentication feature while creating the MQTT server then stranger clients can’t communicate to your MQTT server.

Bidirectional communication

There is no direct link between clients in MQTT.

A broker connects the subscriber and the publisher in this messaging protocol. As a result, the subscriber and publisher can converse about any issue that the broker handles.

Eliminate polling

Polling is a procedure in which the controlling devices wait for input from an external device to determine whether the device is ready to broadcast data. MQTT protocol follows instantaneous push-based delivery. So there is no need to continuously check or poll before sending data which results in reduced network traffic.

Storage and forwarding

MQTT supports the storage and forwarding of persistent messages on the broker. Clients can ask for the broker to keep messages after they've been published. When this feature is used, any persisted message will be broadcast to a client who has subscribed to a topic. The most recent persistent message is the only one that gets saved. Unlike typical messaging queues, however, the MQTT broker prevents these persisted messages from being backed up inside the server.

Decouple and scale

It enables changes in communication patterns and functionality without causing a system-wide ripple effect.

Simplifies communication

As we have already discussed that MQTT follows Subscriber and Publisher architecture where the broker acts as an interface between the clients. So there is no need of computer to computer interface hence providing simplified communication.

Dynamic targeting

  • It also supports authentication, publishing, subscribing, keep-alive pings.
  • It runs on top of Internet protocol and TCP.

Quality of service

Quality of service is a kind of indicator which ensures that messages are exchanged between the sender and the receiver. There are three levels of QoS:

  1. just once - this level is not reliable but is the fastest one
  2. at least once - this level is the default mode
just once - this level is the most reliable, but slowest

MQTT Applications

MQTT protocol is mostly used in IoT(internet of things) applications for data transmission. The data can be read from some sensors or some temperature value.

Fig 3: MQTT Applications

Some other applications where you can use it are :

  • Security and surveillance
  • Industries & energy
  • Logistics
  • Medical & healthcare

How to Publish a message using ESP32 MQTT?

  • The MQTT protocol is another functionality supported by the ESP32 module. To implement MQTT, we're utilizing the Arduino IDE.
  • If you're not sure where to begin coding with the ESP32, check out our prior tutorial, Introduction to the ESP32 Microcontroller Series.

Code Description

  • Global Declarations

Adding libraries will be the initial stage.

  • To use ESP32 MQTT to send a message, you'll need two libraries.
#include <WiFi.h> #include <PubSubClient.h>
  • PubSubClient library is not available in ESP32’s library list. You need to download the library first and add the library into Arduino IDE.

Fig 4: Adding library to Arduino IDE.

  • Click on Add. Zip Library.
  • Browse for the downloaded library file and add.
  • PubSubClient library and Wi-Fi library
  • We covered Wi-Fi in detail in our previous tutorial, ESP32 web server.
  • PubSubClient is a client library that may be used with MQTT applications.
  • Add your SSID and Password to create a wi-fi connection. Follow our previous tutorial, ESP32 web server, to learn more about ESP32 Wi-Fi.
const char* ssid = "public"; //add your SSID const char* password = "ESP32@123"; // add your password
  • Add the details about MQTT broker
const char* mqttServer = "m11.cloudmqtt.com"; const int mqttPort = 1883; //12948; const char* mqttUser = "public"; const char* mqttPassword = "ESP32@123";

Arduino setup() Function

  • Initialize the serial monitor.
  • Initialize the Wi-Fi. (follow the previous tutorial for more details about (ESP32 Wi-Fi)
Serial.begin(115200); WiFi.begin(ssid, password);   while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); }
  • Print Wi-Fi status on serial monitor
Serial.println("Connected to the Wi-Fi network");
  • Define the MQTT server's address and port address.
  • To do so, we use the PubSubClient object's setServer function.
  • The address and port, both defined early in global variables declaration, will be passed to this procedure as the first and second arguments, respectively.
  • setCallback method to define a handling function.
  • When a MQTT message is received on a subscribed topic, this handling function is called. This function's code will be saved for later.
client.setServer(mqttServer, mqttPort); while (!client.connected()) { Serial.println("Connecting to MQTT..."); if (client.connect("ESP32Client", mqttUser, mqttPassword )) { Serial.println("connected to MQTT"); } else { Serial.print("failed to connect "); Serial.print(client.state()); delay(2000); } }
  • Publish a topic
client.publish("esp/test", "ESP32");
  • Subscribe for the topic you want to.
client.subscribe("esp/test");
Finally, we'll subscribe to the topic we're interested in. Other clients' communications will be published on that topic, and we will receive them this way. For that purpose, we use the subscribe method, which takes the name of the topic we want to subscribe to as an argument.

Arduino loop() Function

  • The next task will be to connect with the MQTT server which will happen in the main loop
  • Here, the device will keep trying to connect with the server unless it establishes a connection.
  • In order for the client to process incoming messages and maintain the connection to the MQTT server, the function should be invoked on a regular basis.

MQTT Testing

For testing purposes, we will use MQTT_lens which is a Google Chrome application to establish a connection with the broker.

  • Here are some screenshots of the MQTT lens broker:
  • Create a connection after adding the following details:
  • Connection, Hostname, Port etc.

Fig: MQTT_lens broker

 

This concludes today’s tutorial, hope you find it helpful.

How has Technology Transformed the Healthcare Sector?

The evolution of technology over the decades has helped almost all sectors to grow and flourish. And, the medical sector is no different. The way medicine was practiced a couple of decades ago has been completely changed today. This has obviously brought in multiple benefits to the patients. The treatment time has lowered and so has the accuracy increased. People now trust technology to get their treatments done.

This article highlights certain technologies that have transformed modern medicine.

Electronic health records

This is the prime example of how technology has transformed the way of conducting treatments and keeping records. The paper filing system of patients is now long gone. It is now replaced with electronic record-keeping. This has made collaboration easier and smoother and facilities can focus better on patient care now. The entire medical history of patients is available in just a click and doctors can make better and detailed decisions about their treatment plan.

Personalized treatment

This is yet another great way by which technology is driving healthcare. With the evolution of wearable technology, patient engagement has increased more than ever. And, more healthcare facilities are trying to connect with their patients through these hyper-targeted and extremely personalized health and fitness plans. The data that is driving the results is extremely accurate and the recommendations are loved by the patients. The technology tries to understand every individual motivation and design solutions that reflect well with their lifestyles and that are manageable on both ends.

Telehealth

Virtual healthcare or telehealth was there initially also but it gained popularity pretty recently after the outbreak of the global COVID-19 pandemic. It has increased the communication efficiency between the clinics, healthcare providers, and the patients who are seeking help. The information exchange has become simpler and one can easily track and monitor the changes that are visible after every telehealth interaction. The data is optimized and your treatment is curated across a stable plan of action.

Surgical technology

Surgeries are equally benefited through this progressive technology. It is now possible to draw virtual 3D reconstructions before any major surgery on trauma patients. It helps the surgeons to make the most accurate incisions on the skin and have bony reconstruction with plates. This is a great way to plan the surgeries and monitor the flow of blood in those regions. We are hopeful the future will see more advanced improvements in this field to help the surgeons.

AI and augmented reality

When both of these are combined, many new opportunities arise. There are handheld devices that use both of these technologies to make veins in a patient's body visible. They also help the doctors to sense heat by just using a single device. The combination of both these technologies improves the activities like drawing blood or IV insertions.

Besides these, there are many other innovations in health care devices that have streamlined the treatments to a great extent while helping the industry move forward. The patients can now confidently rely on the system for their treatments.

How Energy Monitoring System Helps In Managing and Functioning Of Business

If you want to monitor the utility usage in real-time and if you want to optimize the business utilities, you should make use of the energy monitoring system. It is the software that monitors the utility consumption online like the energy, fluids, gas, and so on. This system helps to calculate the consumption per area like the departments and production lines. It also helps in calculating the consumption per the production like the orders and the items that further helps in calculating the real production cost. With the help of the best type of energy monitoring tool, you can forecast the energy usage in several sectors and then create the alarm if it finds that the site has reached the contractual capacity.

The energy management system will further help detect the failures in the process, leaks or anomalies, and provide information on how much the utilities are used during the non-production time. After assessing the data offered by this tool, you can decide to depend upon the real data and then collate the production data with the utility usage. You can get the best energy monitoring software online, one of the best places to get tools for energy management and monitoring for businesses.

Benefits of using the Energy Monitoring System

There Are Various Benefits Of Using This Tool, And They Are-

  • Lower the utility usage
  • Detecting the utility waste
  • Précising the forecast on the utility usage
  • CO2 footprint awareness
  • Reduce the downtime
  • Improve the OEE of the functioning
  • Make decisions depending upon the real-time data from the machines

Features Of Energy Monitoring System

As said before, Energy checking frameworks give clients information about their utilization designs so they can settle on informed energy the board choices and expand investment funds. It is completed utilizing energy observing programming that accumulates energy utilization information, dissects it. Afterward, gives valuable data straightforwardly to the customer's gadget.

The product utilizes counters or sub-counters situated nearby or in the structure to accumulate information for every item (power, heat, water, gas) to give a total image of energy utilization. Because of these energy observing methods, clients can monitor the amount they are devouring. They can also monitor how the item is utilized at some random season of day or night.

Keeping all the utilities under control

EMS framework focuses on unlimited authority over the Utilization and cost of utilities in the processing plant. Counters cautions and controlling dashboards give the client the likelihood of dealing with the utilities. They are also expected in all pieces of the processing plant – from the creation floor to workplaces. Relationship with creation information takes into consideration full examination and straightforwardness of the actual production costs. Dynamic checking upholds the identification of holes and misuse of utilities that can be not entirely obvious and fixed.

Determining the Utilization per area

It helps to analyze all utilities in the current location with detailed information on planned and actual usage. It also helps in displaying trends and forecasts.

Compare the utilities and consumers

Information on utility utilization can get a connection with creation information, showing a precise image of complete creation and non-creation costs.

Make use of Power Guard

It is a tool for controlling the total amount of electrical power used to avoid the expensive penalties for breaching or crossing the limits. With the help of tracking the system, it issues warnings on the incoming faults with the proper advance.

Choose the EMS or the energy monitoring system, an advanced solution for monitoring energy consumption. In addition, it allows for the implementation of additional software like the contracted capacity guard. Choose EMS for the higher energy management at the workplace.

Selecting a Prototyping Firm: Factors to Contemplate

Choosing a prototyping firm to manufacture your things is a crucial decision. Identifying the right match is a difficult task for any firm. Cost, effectiveness, dependability, and operational processes must all be considered before assigning any production assets.

Dealing with a prototyping firm should be straightforward once you learn what to look for. The following are important considerations to consider while looking for a producer to help you bring your prototype idea to life.

Familiarity with the Business

You can look through the portfolios of the best prototyping businesses to see their previous work. This data is crucial in determining whether they have experience with similar initiatives and specialize in your required prototypes.

You'll need a corporation with experience in your sector throughout this early stage of product development. They are more knowledgeable about the resources to utilize, the equipment that can be employed to make the finished output, and they are conversant in industry jargon.

Working with organizations that specialize in modeling will make the production process much smoother.

The Available Services

You might need a simple 3D printing concept part right now, but you could require a perfectly functioning prototype for a trade show or business meeting tomorrow. It's vital to know whether your prototyping partner can handle many tasks.

Enquire about the many sorts of 3D printing services offered and just about every other service that may be accessible. Determine what kind of finishing services they provide, such as smoothing, polishing, and laser engraving.

A reputable specialist will have both current and 'traditional' talents, such as SLA and Vacuum Casting solutions, and other 3D printing services and a CNC suite if you select them.

Full-cycle prototyping competences

If you're working with complex or advanced prototypes that involve several production processes such as CNC machining and plastic injection molding, a prototyping company should ideally have all of the design development they'll use to manufacture your prototypes under one roof.

Why? You don't have to squander weeks or months working with a modeling company that collects all of your model's components from numerous vendors and then assembles them before delivering them to you. This is a worthless exercise that you almost certainly do not have.

Manufacturing your product by a unified prototyping company addresses both of these potential difficulties by providing for quick alterations and hiring integrated and comprehensive specialists who can supervise all areas of the design process.

Another benefit of engaging with a consistent, reputable prototyping company that can provide all of the prototyping solutions you need under one roof is IP protection.

Your ideas are more likely to get robbed if a lot of people see them. Collaboration with a lone prototyping company means fewer eyes on your concepts and a lower risk of a vital file ending in the wrong hands.

Speed

To maintain a competitive advantage, prototypes must be released into the market considerably more quickly. As a result, you must only hire a firm with a trained workforce of design professionals who can work rapidly and get concepts to market.

If you wish to obtain a competitive advantage, you must meet this criterion. To produce models in a matter of days, the leading rapid prototyping businesses rely on their innovative technologies. As a result, if your prototyping firm fails to fulfill timelines, you should hunt for a new supplier.

Inquire about the company's ability to act quickly to orders throughout product innovation, market launch, or implementation stage. Few companies also offer rapid prototyping.

Cost

Consider cost in mind while choosing a prototype manufacturer. Prototyping prices vary from one prototyping company to another, as you may be familiar with. Some companies charge per hour, while others charge per order.

It's vital to remember that the manufacturing process and materials used also influence the pricing. The complexity of the design may also have an impact on prototyping expenses.

Before engaging in prototyping solutions and services, make sure you understand the cost split. While at that, you can request a CNC instant quote as it will help you have a plan in place.

Help with Design

If you're an entrepreneur, or if this is your first time working with a prototyping firm, you may not have been an expert in most production procedures. Consequently, while choosing a production provider, please make certain that they provide continual information and coaching.

A reputable prototyping company should constantly provide you with advice, information, and choices for the greatest materials to use and the ideal technique to follow. Consequently, if you're unclear about which methods to employ, it's not a bad idea to seek advice from the company.

Conclusion

Selecting the right company may impact how much money and work you put into the entire production cycle. Please do your research to confirm that they meet the required standards.

What is SLS (Selective Laser Sintering) used for?

Hello friends, I hope you all are doing great. In today's tutorial, we will discuss what is Selective Laser Sintering, why is it used for. Selective Laser Sintering is a popular 3D printing technology used to create durable prototypes and end-use parts from CAD files. Its one of the oldest and most popular forms of additive manufacturing techniques and thanks to further technological advances, its use is becoming widespread. In this guide, we will explore what SLS is and what it is used for. 

How does Selective Laser Sintering work?

SLS uses a nylon or polyamide powder which is spread successively in thin layers with a high-powered laser that selectively sinters the powder according to data derived from digital models. This process is repeated layer after layer, binding the powdered material together to produce a final, firm structure. Excess powder is removed manually to reveal the final shape before bead blasting is applied to further remove powder residue. 

What is SLS used for?  

SLS is used for high productivity manufacturing tasks thanks to the laser’s high power and capability to scan quickly and accurately. It is a technology able to produce durable prototypes from a broad range of nylon-based materials, and it is also capable of printing independently moving parts in a single build. SLS is known as the go-to technology for producing complex shapes. It does not require a support structure and utilises unused powder to further add to its strength. In industries where lightweight material is imperative to a successful design (for example, aircraft building and automotive) SLS printed parts are invaluable. 

What kind of products are made with SLS? 

Being able to produce high strength products at a low volume, using different materials, like glass, plastic, metal and ceramics, means SLS printing is used to create many different tailored products. Medical and dentistry products such as prosthetics, hearing and dental aids are made using SLS. SLS is often utilised in industries where high-volume production is not required, for example, end-use parts for aeroplanes where only small quantities are needed on an infrequent basis. Businesses are able to store the digital files needed for SLS printing inexpensively and reproduce designs as and when required, instead of spending money on the expensive storage of moulds used in traditional manufacturing.

Benefits of Selective Laser Sintering 

SLS has an impressive number of benefits. Primarily, it is a technology suitable for high productivity and quick turnaround times of less than 24 hours. The nylon powder used needs only a very brief exposure to the laser for sintering, making the process faster than other technologies. The associated cost of moulds is not required meaning it is ideal for rapid prototyping. Along with these benefits, SLS is a self-supporting technology, affording greater scope for more complex designs. This differs from the more widely adopted FDM (Fused deposition modelling) printing and stereolithography (SLA) which require structure support during printing. Laser adhesion is also stronger with SLS printing and the porous surfaces created to allow for a very effective dyeing process to final shapes and products. 

How does SLS compare to other technologies?

Although SLS has a huge array of advantages there are some limitations to its use, warranting the need for other forms of 3D printing technology. One of its key drawbacks is cost. Compared to FDM and SLA printers which are obtainable for around $500 or less, a desktop SLS printer is a few thousand dollars, thus compromising its appeal for hobbyists. SLS prints are excellent for prototypes but for end-use functional parts, there are some disadvantages because of the porous quality of the final product. Although this porosity lends itself to excellent dyeing and colouring potential, this is not the case for the structural integrity of the final product. In addition, because SLS prints go through a cooling process following sintering, there is the propensity for shrinking and warping leading to the production of inaccurate shapes.  Compared to SLA printing, where liquid resin is used instead of powder, SLS printing can generate more waste. This is because the resin in SLA printing can be reused whereas the quality of reused powder in SLS printing is compromised and needs to be disposed of. Coupled with this, the process of cleaning the powder from the finished product is messy. In an industrial setting, this does not cause a problem as cleaning chambers are often used, however, this necessary procedure can be off-putting for those using a small scale or desktop printers as the powder is difficult to control. 

Conclusion 

SLS is a proven and effective form of 3D printing and has been used in manufacturing for decades. Predominantly used in an industrial setting for rapid prototyping, it is difficult to envisage its use for smaller-scale activities as the inherent expense, poor recyclability of powder and complexity of use have so far formed a barrier for 3D printing novices. 
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir