Communication Protocol

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

Course : COMP8041 - Internet of Things (IoT)

Period : September / February 2020

INTERNET OF THINGS
Session 8 Communication Protocol

D5512 – Abba Suganda Girsang, PhD


(This slide is adopted from slide Digitalent.kominfo.go.id)
Outlines

• HTTP - Hyper Text Transfer Protocol


• MQTT
• REST API
HTTP - Hyper Text Transfer Protocol
Overview

HTTP berada pada application layer


Communication Chain

Client (web browser) mengirimkan HTTP request


lalu server (web server) membalas dengan mengirimkan
HTTP response
Request Method

• GET
• POST
• HEAD
• OPTIONS
• PUT
• DELETE
• TRACE
• CONNECT
Request Message
Request Header

• Accept
• Accept-Charset
• Accept-Encoding
• Accept-Language
• Host
• User-Agent
• Cookie
• Content-Length
• Referer
Response Message
Response Header

• Date
• Server
• Last-Modified
• Expires
• Refresh
• Content-Length
• Content-Type
• Accept-Ranges
Status Code

• 1xx - informational
• 2xx - success
– 200 - OK
• 3xx - redirection
– 301 - move permanently
– 304 - not modified
• 4xx - client error
– 403 - forbidden
• 5xx - server error
HTTPS

• Hyper Text Transfer Protocol Secure


• End to end encryption
• Menggunakan TLS atau SSL
Cookie
Making webserver ESP32
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>

const char* ssid = "........";


const char* password = "........";

WebServer server(80);

void handleRoot() {
server.send(200, "text/plain", "hello from esp!");
}
Making webserver ESP32
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
Making webserver ESP32
void setup(void) {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
}
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

if (MDNS.begin("esp32")) {
Serial.println("MDNS responder started");
}
Making webserver ESP32
server.on("/", handleRoot);
server.on("/inline", []() {
server.send(200, "text/plain", "this works as well");
});

server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}

void loop(void) {
server.handleClient();
}
MQTT
Overview MQTT
• Short for Message Queuing Telemetry Transport
• Open standard
• Simple & lightweight publish-subscribe messaging
protocol
• Runs on embedded devices and mobile platforms
• Low latency
• Low power
• Low bandwidth
• Efficient distribution process to multiple recipients
• Easy
• Minimal overhead
Publish/Subscribe
Publisher and Subscriber
Publisher and Subscriber
• Publisher:
– client yang melakukan publish terhadap suatu topic
– client ini mengirimkan message dengan topic tertentu

• Subscriber:
– client yang melakukan subscribe terhadap suatu topic
– client ini akan menerima semua message dalam topic
tersebut

• Antara publisher dan subscriber tidak saling mengenal


(tidak ada hubungan langsung)
Broker

• Broker: perantara antara publisher dan


subscriber.
Tools

• Eclipse Paho
• Mosquitto
• HiveMQ
• RabbitMQ
Topic Best Practice

• Keep the topic short and concise


• Use specific topics, instead of general ones
• Don’t forget extensibility
• Don’t use a leading forward slash
• Don’t use spaces in a topic
• Use only ASCII characters, avoid non printable
characters
• Don’t subscribe to #
Retained Message

• Message with the retained flag set to true.


• The broker will store the last retained
message and the corresponding QoS for that
topic
• Each client that subscribes to a topic pattern,
which matches the topic of the retained
message, will receive the message
immediately after subscribing.
• For each topic only one retained message will
be stored by the broker.
Will Message

• When clients connect, they can specify an


optional “will” message, to be delivered if they
are unexpectedly disconnected from the
network
• This “last will and testament” can be used to
notify other parts of the system that a node
has gone down
Topic

• Topic subscriptions can have wildcards


– ‘+’ matches anything at a given tree level so
the topic “sensor/+/temp” would match
“sensor/dev1/temp”, “sensor/dev2/temp”,
etc.
– ‘#’ matches a whole sub-tree, so “sensor/#”
would match all topics under “sensor/”.
• These enable nodes to subscribe to groups of
topics that don’t exist yet, allowing greater
flexibility in the network’s messaging structure
QoS
Keep Alive

• The keep alive functionality assures that the


connection is still open and both broker and
client are connected to one another
• Therefore the client specifies a time interval in
seconds and communicates it to the broker
during the establishment of the connection.
• The interval is the longest possible period of
time, which broker and client can endure
without sending a message
Persistent Session
• A persistent session saves all information relevant for the client on
the broker. The session is identified by the clientId provided by the
client on connection establishment
• So what will be stored in the session?
– Existence of a session, even if there are no subscriptions
– All subscriptions
– All messages in a Quality of Service (QoS) 1 or 2 flow, which are
not confirmed by the client
– All new QoS 1 or 2 messages, which the client missed while it
was offlne
– All received QoS 2 messages, which are not yet confirmed to the
client
– That means even if the client is offline all the above will be stored
by the broker and are available right after the client reconnects.
Security
• MQTT provides security, but it is not enabled by
default.
– As a basic solution we can rely on the encrypted
WiFi connection to provide a basic level of
security.
• MQTT has the option for Transport Layer Security
(TLS) encryption.
• MQTT also provides username/password
authentication.
– Note that the password is transmitted in clear
text. Thus, be sure to use TLS encryption if you
are using authentication.
REST API
API

• Application Programming Interface  is a set of


routines, protocols, and tools for building
software applications.
Some various API

• Representational State Transfer (REST)


• Remote Procedure Calls (RPC)
• Simple Object Access Protocol (SOAP)
REST

• REST is short of REpresentational State


Transfer
REST

• The REST architectural style describes six


constraints.

• The six constraints are:


– Uniform Interface
– Stateless
– Cacheable
– Client-Server Separation
– Layered System
– Code on Demand (optional)
REST API

• Generality
• Familiarity
• Scalability
• Segmentation
• Speed
• Security
• Encapsulation
REST API

• Work on protocol HTTP


• Using JSON orXML to send data
Anatomy of REST API
Request
• endpoint
• method
• headers
• body
Endpoint

• Endpoint consists of root-endpoint and path.


• The root-endpoint is the starting point of the
API you’re requesting from.
• For example, the root-endpoint of Github’s API
is https://api.github.com while the root-
endpoint Twitter’s API is
https://api.twitter.com.
Endpoin

• The path determines the resource you’re


requesting for.
• Think of it like an automatic answering
machine that asks you to press 1 for a service,
press 2 for another service, 3 for yet another
service and so on.
Endpoint

• You can access paths just like you can link to


parts of a website.
• For example, to get a list of all posts tagged
under “JavaScript” on Smashing Magazine, you
navigate to
http://cybertrust.biz.id/tag/javascript/.
• http://cybertrust.biz.id / is the root-endpoint
and /tag/javascript is the path.
Method

The method is the type of request you send to


the server. You can choose from these 4 types
below:
• GET
• POST
• PUT
• DELETE
Method
Method Request Meaning

This request is used to get a resource from a server. If you perform a GET request, the server looks for the
GET data you requested and sends it back to you. In other words, a GET request performs a READ operation.
This is the default request method.

This request is used to create a new resource on a server. If you perform a POST request, the server creates a
POST new entry in the database and tells you whether the creation is successful. In other words, a POST request
performs an CREATE operation.

These two requests are used to update a resource on a server. If you perform a PUT request, the server
PUT updates an entry in the database and tells you whether the update is successful. In other words, a PUT
request performs an UPDATE operation.

This request is used to delete a resource from a server. If you perform a DELETE request, the server deletes
DELETE an entry in the database and tells you whether the deletion is successful. In other words, a DELETE request
performs a DELETE operation.
Header

• Headers are used to provide information to


both the client and server.
• It can be used for many purposes, such as
authentication and providing information
about the body content.
• Header example: "Content-Type:
application/json"
• You can find a list of valid headers on MDN’s 
HTTP Headers Reference.
Body

• The body contains information you want to be


sent to the server. 
• Body example: property1=value1
Another Example
JSON (JavaScript Object
Notation)
• Better Language Support
• Lightweight (much less code than XML)
JSON (JavaScript Object
Notation)
{ "name":"John", 
"age":30, 
"car":null 
}

{ 'sensorId': 'temp1',
'Value': 25
}
XML (eXtensible Markup
Language)
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Authentication

There are two main ways to authenticate


yourself:
• With a username and password (also called
basic authentication)
• With a secret token

The secret token method includes oAuth, which


lets you to authenticate yourself with social
media networks like Github, Google, Twitter,
Facebook, etc.
Secret Token

• Users should be provided with a unique API


key/ identifier that allows you to track, limit,
and enable features
• An OAuth token should be used to link API
keys to accounts instead of requesting
account usernames and passwords
• Tokens help prevent misuse of the system an
d limit access to the control panel.
Mengakses REST API Github

• You can send a request with any


programming language.
• JavaScript users can use methods like the 
Fetch API and jQuery’s Ajax method.
• Ruby users can use Ruby’s Net::HTTP class.
• Python users can use Python Requests.

• Here we’ll use the command line utility called 


cURL.
Mengakses REST API Github

• curl https://api.github.com
Mengakses REST API Github

• curl https://api.github.com/users/zellwk/repos
Mengakses REST API Github

• curl
https://api.github.com/users/zellwk/repos\?
sort\=pushed
Mengakses REST API Github

• curl -X POST
https://api.github.com/user/repos
Mengakses REST API Github

• curl -H "Content-Type: application/json"


https://api.github.com
Mengakses REST API Github

• curl -H "Content-Type: application/json"


https://api.github.com -v
Mengakses REST API Github

curl -X POST https://requestb.in/1ix963n1 \


-d property1=value1 \
-d property2=value2
Mengakses REST API Github

curl -X POST https://requestb.in/1ix963n1 \


-H "Content-Type: application/json" \
-d '{
"property1":"value1",
"property2":"value2"
}'
Mengakses REST API Github

curl -x POST -u "username:password"


https://api.github.com/user/repos

You might also like