IoT Protocol Stack - Application layer
IoT Protocol Stack - Application layer
1
What is MQTT?
MQTT : Message Queueing Telemetry Transport protocol.
• Reliable, Lightweight, Cost-effective protocol that transports messages between
devices.
• Suited for the transport of telemetry data (sensor and actuator data)
M
Q
T
T
A
MQTT Characteristics
Publish / Subscribe
(PubSub) model
Decoupling of data
producer (publisher)
and data consumer
(subscriber) through
topics (message
queues)
Asynchronous
communication model
with messages (events)
Publisher and
Subscriber need not be
Advantages of MQTT
Source: https://www.u-
blox.com/en/blogs/insights/mqtt-beginners-guide
Publish & Subscribe Messaging
A producer sends (publishes) a message (publication) on a topic (subject)
A consumer subscribes (makes a subscription) for messages on a topic (subject)
A message server / broker matches publications to subscriptions
Topic
A topic forms the namespace in hierarchical with each “sub topic” separated by /
(forward slash)
An example topic space :
A house publishes information about itself on:
<country>/<region>/<town>/<postalcode>/<house no>/energyConsumption
<country>/<region>/<town>/<postalcode>/<house no>/solarEnergy
• It subscribes for control commands:
<country>/<region>/<town>/<postalcode>/<house no>/thermostat/setTemp
Cont…
Wildcards
A subscriber can subscribe to an absolute topic OR can use wildcards:
Single-level wildcards “+” can appear anywhere in the topic string
For example:
Let the Topic:
<country>/<region>/<town>/<postalcode>/<house
no>/energyConsumption
India/Tamilnadu/Chennai/600127/AB1/
energyConsumption
India/Tamilnadu/Chennai/600127/AB2/
energyConsumption
India/Tamilnadu/Chennai/600128/AB3/
energyConsumption
India/Tamilnadu/Chennai/600127/AB4/smartMeter
NOTE :
Wildcards must be next to a separator
Wildcards cannot be used when publishing
Cont…
A subscription can be durable or non-durable
Durable:
Once a subscription is in place,
A broker will forward matching messages to the subscriber immediately if the subscriber is
connected.
If the subscriber is not connected, messages are stored on the server/broker until the next
time the subscriber connects.
Non-durable / Transient (i.e. subscription ends with client session):
• The subscription lifetime is the same as the time the subscriber is connected to the server /
broker
MQTT Message Format
MQTT is lightweight
because each packets consists of a 2-byte fixed header with optional variable header
and payload fields
Cont…
Message header field Description / Values
Message Type (4 bits) 0: Reserved 8: SUBSCRIBE
1: CONNECT 9: SUBACK
2: CONNACK 10: UNSUBSCRIBE
14 message types, 3: PUBLISH 11: UNSUBACK
2 are reserved
4: PUBACK (Publish ACK) 12: PINGREQ
5: PUBREC (Publish Received) 13: PINGRESP
6: PUBREL (Publish Release) 14: DISCONNECT
7: PUBCOMP (Publish Complete) 15: Reserved
DUP (1 bit) Duplicate message flag. Indicates to the receiver that this message may have already been received.
1: Client or server (broker) re-delivers a PUBLISH, PUBREL, SUBSCRIBE or UNSUBSCRIBE message
(duplicate message).
QoS Level (2 bits) Indicates the level of delivery assurance of a PUBLISH message.
0: At-most-once delivery, no guarantees, «Fire and Forget».
1: At-least-once delivery, acknowledged delivery.
2: Exactly-once delivery.
RETAIN (1 bit) 1: Instructs the server to retain the last received PUBLISH message and deliver it as a first message
to new subscriptions.
Remaining Length (1-4 bytes) Indicates the number of remaining bytes in the message, i.e. the length of the (optional) variable
length header and (optional) payload.
Message Types
RETAIN
RETAIN=1 in a PUBLISH message instructs the server to keep the message for this topic.
When a new client subscribes to the topic, the server sends the retained message quickly.
Example:
Subscribers receive last known temperature value from the temperature data topic.
RETAIN=1 indicates to subscriber B that the message may have been published some time ago.
Remaining Length (RL)
• The remaining length field encodes the sum of the lengths of:
1. (Optional) variable length header
2. (Optional) variable length payload
Therefore, MQTT adds 3 quality of service (QoS) levels on top of TCP
PUBREC (REC:
received) Packet is the
response to a PUBLISH
Packet
at least
once PUBREL (REL: release)
Packet is the response to a
PUBREC Packet
PUBCOMP (COMP:
complete) Packet is the
response to a PUBREL
Packet.
Cont…
QoS level 0:
At-most-once delivery («best effort»).
Messages are delivered according to the delivery guarantees of the underlying network (TCP/IP).
Example application: Temperature sensor data which is regularly published. Loss of an individual
value is not critical since applications (i.e. consumers of the data) will anyway integrate the values
over time
QoS level 1:
•
At-least-once delivery.
Messages are guaranteed to arrive, but there may be duplicates.
Example application: A door sensor senses the door state. It is important that door state
changes (closed->open, open->closed) are published losslessly to subscribers (e.g. alarming
function). Applications simply discard duplicate messages by comparing the message ID field.
QoS level 2:
Exactly-once delivery.
This is the highest level that also incurs most overhead in terms of control messages and the need
for locally storing the messages.
Exactly-once is a combination of at-least-once and at-most-once delivery guarantee.
Example application: Applications where duplicate events could lead to incorrect actions, e.g.
sounding an alarm as a reaction to an event received by a message. So, it avoids duplicate.
PUBLISH msg flow
QoS level 0:
With QoS level 0, a message is delivered with at-most-once delivery semantics («fire-and-forget»).
QoS level 1:
QoS level 1 affords at-least-once delivery semantics. If the client does not receive the PUBACK in
time, it re-sends the message.
Cont…
QoS level 2:
QoS level 2 affords the highest quality delivery semantics exactly-once, but comes with the cost of
additional control messages.
Example: CONNECT & SUBSCRIBE msg flow
Case 1:
• Session/connection and subscription setup with clean session flag = 1 (non-durable subscription)
Cont…
Case 2:
• Session/connection and subscription setup with clean session flag = 0 (durable subscription)
What is MQTT-SN?
MQTT-SN (MQTT for sensor networks) is a variant of MQTT that has been optimized for
use in low power environments such as sensor networks, as the name suggests.
• Topic aliases: allows for simplified publishing and reduced data overheads
• Sleep mode (disconnected sessions): allows messages to be queued on the broker while the
remote Thing or device is powered off
Send Sensor values to Cloud using MQTT
Protocol
• The Ultrasonic Sensor
reads the distance
between itself & the
object
Software
•Arduino IDE
•Fritzing
Cloud Platform
•ThingSpeak Account
MQTT Client
(Publisher) MQTT Server
(Broker)
"192.168.0.104"
Programming ESP8266
#include <ESP8266WiFi.h> void setup_wifi () {
#include <PubSubClient.h> delay(10);
Serial.println();
#define TRIGGER D6 Serial.print("Connecting to ");
#define ECHO D8 Serial.println(ssid);
long duration, cm;
WiFi.begin(ssid, password);
const char* ssid = while (WiFi.status() != WL_CONNECTED)
"TP-LINK_ED34"; { delay(500);
const char* Serial.print(".");
password = }
"48193580"; Serial.println("");
Serial.print("WiFi connected - ESP IP
//Raspberry Pi IP address: ");
Address
const char* Serial.println(WiFi.localIP());
}
mqtt_server =
"192.168.0.104";
WiFiClient
espClient;
PubSubClient
Cont…
void callback (String topic, byte* message, void reconnect ()
unsigned int length) {
{ // Loop until we're reconnected
Serial.print("Message arrived on topic: "); while (! client.connected ()) {
Serial.print(topic); Serial.print("Attempting
Serial.print("Message: "); MQTT connection...");
String messageTemp; if
for (int i = 0; i < length; i++) (client.connect("ESP8266Clie
{ Serial.print((char)message[i]); nt"))
messageTemp += (char)message[i]; {
} Serial.println("connected"
Serial.println(); );
} client.subscribe("esp8266
/4");
}
else {
A callback is a function that is
} Serial.print("failed, rc=");
passed as an argument to } Serial.print(client.state());
another function. Serial.println(" try again in 5 seconds");
delay(15000);
}
Cont…
void setup () digitalWrite(TRIGGER, LOW);
{ Serial.begin(115200); delayMicroseconds(2);
pinMode(TRIGGER,OUTPUT); digitalWrite(TRIGGER, HIGH);
pinMode(ECHO,INPUT); delayMicroseconds(10);
digitalWrite(TRIGGER, LOW);
setup_wifi ();
duration = pulseIn(ECHO, HIGH);
client.setServer (mqtt_server, 1883);
cm = duration / 29 / 2;
client.setCallback (callback); static char distanceincm[7];
}
dtostrf(cm, 6, 2, distanceincm);
client.publish("/esp8266/distance", distanceincm);
Source: https://www.slideshare.net/aniruddha.chakrabarti/coap-web-protocol-for-iot
CoAP Message Format
• TKL (4 bit): Specifies the size (0-8 bytes) of the Token field
• Token (0-8 byte): correlates requests and responses
• They are unreliable messages or in other words messages that do not contain critical information that
must be delivered to the server.
o Example : Messages that contain sensed values from sensors.
o Even if these messages are unreliable, they have a unique ID.
CoAP Request/Response Model
The CoAP Request/Response is the second layer in the CoAP Abstraction layer.
• The request is sent using a Confirmable (CON) or Non-confirmable (NON) message.
• There are several scenarios (e.g. Piggy-Backed, Separate Response) depending on if the server can
answer immediately to the client request or if not available.
CoAP
URI:
Cont…
If the server can answer immediately to the client request (Piggy-Backed response)
• If the request is carried using a Confirmable message (CON).
the server sends back an ACK message to client containing the response or the error code.
• The Token is different from the Message-ID and it is used to match the request and the response.
Cont…
If the server can’t answer immediately to the request coming from the client (Separate Response).
• It sends an ACK message with an empty response.
• When response is available, then the server sends a new CON message to the client containing the
response.
• At this point, the client sends back an ACK message.
CoAP Security Aspects
• CoAP uses UDP to transport information.
• CoAP relies on UDP security aspects to protect the information.