You are on page 1of 99

IoT Physical Servers, Cloud

Offerings and IoT Case Studies


Mrs. K.M. Sanghavi
Contents
• Communication API, Cloud Storage Models
• Web Application Messaging Protocol (WAMP) :
Autobahn for IoT
• Xively Cloud for IoT
• Python Web Application Framework: Djanjo
• Amazon Web Services for IoT
• SkyNet IoT Messaging Platform
• Case Studies
– Home Intrusion Detection
– Weather Monitoring System
– Air Pollution Monitoring
– Smart Irrigation
Communication API
• Facilitate
– Data Transfer
– Information Transfer
– Service Transfer
• Support
– Publish Subscribe models
• Use
– Remote Procedure Call
WebSocket
• WebSocket is a network communication
protocol, which is required for many advanced
features.
• Why do we need WebSocket?
• The answer is that because the HTTP protocol
has a flaw: communication only can be
initiated by the client.
WebSocket
• For example, let's say we want to know the
weather today: the server will return the
results of the query only if the client makes a
request to the server.
• The HTTP protocol doesn't allow the server to
push information to the client actively.
Problems with HTTP
• Unidirectional
• Half duplex
• Stateless
• For each request, TCP connection has to be
established first.
• Therefore, in order to find a better way,
engineers invented WebSocket.
WebSocket
• The biggest feature of the protocol is that the
server can push information to the client actively,
and the client can also send information to the
server actively.
• It is a true two-way equal communication and is
one of the server push technologies.
• It's based on the TCP protocol, and the
implementation on the server side is relatively
easy.
• It uses Publish – Subscribe communication model
WebSocket

• The data format is relatively light, and the


performance overhead is small, but the
communication is efficient
• Uses port number 443 and also 80
• Client can communicate with any server.
• The protocol identifier is ws (wss if encrypted)
, and the URL is exactly the server's URL.
• ws://example.com:80/some/path
WebSocket
WebSocket
Is Great for Apps like :
Chat Trading

Multiplayer games Real – time charts


Web Application Messaging Protocol
WAMP

Problem #1
• Its now no longer a time now to be static
• All the web applications need dynamism
• The web applications now should
automatically get updated

• To solve this we use WAMP.


WAMP
• It is a subprotocol of WebSocket
• It is a routed protocol that means it requires a central
router server to work.
• Enables different technologies, processes and machines
to communicate with each other at real time.
• It offers two messaging patterns : Remote Procedure
Call(RPC) and Pub / Sub
• WAMP uses WebSocket as its default transport, but can
be transmitted via any other protocol that allows for
ordered, reliable, bi-directional, and message-oriented
communications.
• Messages on WAMP are based on JSON format.
WAMP
WAMP
WAMP
WAMP
• Transport: Transport is a channel that connects two peers.
• Session: Session is a conversation between two peers that runs over a transport.
• Client: Clients are peers that can have one or more roles.
• In the publish–subscribe model, the Client can have the following roles:
–Publisher: Publisher publishes events (including payload) to the topic
maintained by the Broker.
–Subscriber: Subscriber subscribes to the topics and receives the events
including the payload.
•In the RPC model, the Client can have the following roles:
–Caller: Caller issues calls to the remote procedures along with call arguments.
–Callee: Callee executes the procedures to which the calls are issued by the
Caller and returns the results to the Caller.
WAMP
• Router: Routers are peers that perform generic call and event routing.
• In the publish–subscribe model, the Router has the role of a Broker.
–Broker: Broker acts as a Router and routes messages published to a topic to all
the subscribers subscribed to the topic.
• In the RPC model, the Router has the role of a Dealer.
–Dealer: Dealer acts a router and routes RPC calls from the Caller to the
Callee and routes results from the Callee to the Caller.
• Application code: Application code runs on the Clients (Publisher, Subscriber, Callee or
Caller).
WAMP Session between Client and
ROuter
Client Communication channel Router
Roles for Pub/Sub
Roles for Pub/Sub
Publisher
Transport Broker
Subscriber

Session
Roles for RPC
Roles for RPC
Caller

Dealer
Callee
WAMP protocol interactions among
two peers
Peer Peer

TCP Connection established

TLS Connection established

Request to WebSocket connection


Response to accepting the request
WAMP established

WAMP closed

Request to close WebSocket connection

Response to close WebSocket connection


TLS Connection closed

TCP Connection closed


AUTOBAHN for IoT

Open source(MIT) real-time framework

Framework for WAMP and WebSocket i.e Web,


Mobile and IoT

Compatible with Python 2.7

Supports TLS(Transport Layer Security) (secured


WebSocket)
Publish – Subscribe messaging using
WAMP -Autobahn
Client Server Client
Client Process Server Process Client Process

WAMP App WAMP Router WAMP App


Session Session Session
App Code App Code

Message published Subscriber receives


to topic message

WAMP-WebSocket
Communication
WAMP
• WAMP is all about creating systems from loosely
coupled application components.
• These application components are where your
application-specific code runs.
• A WAMP-based system consists of potentially
many application components, which all connect
to a WAMP router.
• The router is generic, which means, it does not
run any application code, but only provides
routing of events and calls.
WAMP
• These components use either Remote Procedure
Calls (RPC) or Publish/Subscribe (PubSub) to
communicate. Each
• Component can do any mix of: register, call,
subscribe or publish.
• For RPC, an application component registers a
callable method at a URI (“endpoint”), and other
components call it via that endpoint.
• In the Publish/Subscribe model, interested
components subscribe to an event URI and
when a publish to that URI happens, the event
payload is routed to all subscribers
WAMP
To create a WAMP application,
1. Write application components (using
Autobahn)
• There are four “life cycle” events that
Autobahn will trigger on the components:
connect, join, leave, and disconnect.
2. Connect the components to a router
Autobahn framework working

Router runs
WAMP on server and
Client Client
Application sends the
publishes the messages to
deploy on events to the
event the router
client Subscriber /
Callee
Autobahn Installation for WAMP

Installation
• $ sudo apt-get install python-twisted python-dev
• $ sudo apt-get install python-pip
• $ sudo pip install-upgrade twisted
• $ sudo pip install-upgrade autobahn
Implementation
• $ git clone https://github.com/tavendo/AutobahnPython.git
Creating Components

Two Ways
• First - Deriving from a particular class and overriding
methods
• Second- Based on functions and decorators.

For both approaches you get to decide if you


prefer to use Twisted or asyncio and express this
through import. This is autobahn.twisted. *
versus autobahn.asyncio. *
Creating Components
When using Twisted you
import from autobahn.twisted. Component
Creating Components

whereas when you are using asyncio


Xively Cloud

It is an IoT Cloud Platform

Builds , manages and derive business value from connected


products

Provides cloud base API

It is a PAAS via RESTful API

Supports messaging service based on MQTT


Xively Concepts
Xively device: It is your “device” or the IoT
project you are building. Consider it as an
envelope containing the data.

Channels: It is the streaming coming from


your sensors. Usually, the channel
number is equal to the sensor number
(as long as you want to monitor them all).
Sending data to Xively and monitoring

Adding the “device” to our account

Define the channels

Use the Xively library for your device

Send data to Cloud

Run the Code

Create a dashboard using the data stored in Xively.


Adding the “device” to our account
Define the channels
Add Xively library to the device
#include <b64.h>
#include <HttpClient.h>
#include <SPI.h>
#include <Ethernet.h>
#include <HttpClient.h>
#include <Xively.h>
#include "DHT.h“
#define DHTPIN 2
#define DHTTYPE DHT11
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
EthernetClient client;
Add Xively library to the device
IPAddress ip(192, 168, 1, 40); // Arduino IP Add
IPAddress myDns(8,8,8,8);
IPAddress myGateway(192,168,1,1);
int moisturePin = 0;
int lightPin = 3;
DHT dht(DHTPIN, DHTTYPE);
// Xively setup
char xivelyKey[] = "your_Xively_key_here";
char lightId[] = "Light";
char tempId[] = "Temperature";
char pressId[] = "Humidity";
char moistId[] = "Moisture";
Add Xively library to the device
XivelyDatastream datastreams[] = {
XivelyDatastream(lightId, strlen(lightId), DATASTREAM_FLOAT),
XivelyDatastream(tempId, strlen(tempId),DATASTREAM_FLOAT),
XivelyDatastream(pressId, strlen(pressId),DATASTREAM_FLOAT),
XivelyDatastream(moistId, strlen(moistId),DATASTREAM_FLOAT)
};
XivelyFeed feed(739668463, datastreams, 4);
XivelyClient xivelyclient(client);
Add Xively library to the device
void setup() {
Serial.begin(9600);
Serial.print("Starting...");
setupNet();
dht.begin();
}
void loop() {
float soilHum = analogRead(moisturePin);
soilHum = (1023 - soilHum) * 100 /1023;
Serial.println("Soil Humidty: " + String(soilHum));
// Read light
float volts = analogRead(lightPin) * 5.0 / 1024.0;
float amps = volts /10000.0;
Add Xively library to the device
float microamps = amps * 1000000;
float lux = microamps * 2.0;
Serial.println("Lux: " + String(lux));
float h = dht.readHumidity();
float temp = dht.readTemperature();
Serial.println("Temp: " + String(temp,2));
Serial.println("Hum: " + String(h,2));
// Prepare to send data
datastreams[0].setFloat(lux);
datastreams[1].setFloat(temp);
datastreams[2].setFloat(h);
datastreams[3].setFloat(soilHum);
int ret = xivelyclient.put(feed, xivelyKey);
Serial.println("Client returns ["+String(ret)+"]");
delay(5000);
}
Add Xively library to the device
void setupNet() {
Serial.println("Set up network access.....");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using
DHCP");
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac,ip,myDns,myGateway);
}
}
Add Xively library to the device
• XivelyDatastream that holds the four stream we
send to Xively platform.
• Each channel defined previously using Xively
interface corresponds to a XivelyDatastream.
• Remember to use in the data stream the same
name used in the Xively interface.
Xively data
Creating dashboard
• Use Freeboard.io. This is a free IoT dashboard tool
that can be integrated with Xively easily.
• It helps us to represent the information stored in
Xively using charts.
Creating dashboard..connect
freeboard.io
• Connecting Freeboard.io to Xively.
• This can be done easily using API Key.
Creating dashboard..create chart
• Create charts connecting them to the Xively
channels covered before.
Creating dashboard..create your
dashboard
• Create dashboard
ThingSpeak
1. Setting up the ThingSpeak Account
• Go to the following link and sign up to ThingSpeak. If you already
have an account, then sign (https://thingspeak.com/)
ThingSpeak
2. After creating the account or logging in, you will be see a page
like shown below. Click on new channel.
ThingSpeak
3. Enter the information like shown below. Select two fields because
we will be sending the data for the two fields from the raspberry pi.
Save the channel.
ThingSpeak
4 From there, go to the API keys tab.
ThingSpeak
5. In the API keys tab, copy the write API key. This is the API key at
which we will send the data from the Raspberry pi.
Raspberry Pi to ThingSpeak

• Make the connections of the DHT11 with the Raspberry pi


as described below
• Install DHT11 Adafruit Library

DHT11 Raspberry pi
VCC 5v
Connect to GPIO 23 and
Data pin also connect to 5V
through 10K resistor
GND GND
Raspberry Pi to ThingSpeak
• Make the connections of the DHT11 with the Raspberry pi as described below and
Install DHT11 Adafruit Library
import sys
import urllib2
from time import sleep
import Adafruit_DHT as dht

# Enter Your API key here


myAPI = '5QTYDNRHSJ5RESA5'

# URL where we will send the data, Don't change it


baseURL = 'https://api.thingspeak.com/update?api_key=%s' %myAPI
def DHT11_data():
# Reading from DHT11 and storing the temperature and humidity
humi, temp = dht.read_retry(dht.DHT11, 23)
return humi, temp
while True:
try:
Raspberry Pi to ThingSpeak
humi, temp = DHT11_data()
# If Reading is valid
if isinstance(humi, float) and isinstance(temp, float):
# Formatting to two decimal places
humi = '%.2f' % humi
temp = '%.2f' % temp
# Sending the data to thingspeak
conn = urllib2.urlopen
(baseURL + '&field1=%s&field2=%s'%(temp, humi))
print conn.read()
# Closing the connection
conn.close()
else:
print 'Error'
Raspberry Pi to ThingSpeak
# DHT11 requires 2 seconds to give a reading, so make sure to
add #delay of above 2 seconds.
sleep(20)
except:
break
Raspberry Pi to ThingSpeak
5. After running it for some hours, output looks like below
Django

K M Sanghavi
Agenda

Why Django framework and what is it

MVC-MVT Architecture

HandOn Django

Building Blocks of Django

Django Project Web Application


Why Django framework
 Django is a python framework which a code library that provide tools
and libraries to simplify common web development operations.
 A framework provides a structure and common methods to make a
life of a web app developer much easier for flexible , scalable and
maintainable web applications
What is Django framework
It is a high level and It is written in
has MVC-MVT style powerful python
based architecture language
Features of Django
Django MVC-MVT Architecture
 It is slightly different from MVC, as here Django takes part of Controller itself .
 The template is either HTML or forms mixed with Django Template
Language(DTL)
Django MVT

 The developer provides the model, the view and template then just maps
it to the URL and Django provides service to the user.
Hands On

Let’s create a Web App Using Django…on Linux


Django Installation
• Update the System
$ sudo apt-get update
• Install Django
$ sudo apt-get install python-django
• Check if Django is Installed
$ django-admin --version
Django Web App..Create Project
• Open the terminal and create a directory
$ mkdir ks1
• Change the directory to the newly formed directory
$ cd ks1
• Create the Django Project
ks1 $ django-admin startproject Kfirst
This will create Kfirst folder with following structure
Kfirst/
manage.py
Kfirst/
_init_.py
settings.py
urls.py
wsgi.py
Django Project Structure
Kfirst folder is just the project container / directory. We
Kfirst/ can rename it to anything we like
manage.py

KFirst/
This Kfirst folder is actual python package of your project
_init_.py
wchich contains some default files

settings.py

urls.py

wsgi.py
Django Web App…RunServer
• Change the directory to the Kfirst
$ cd Kfirst
• Run the Server
ks1/Kfirst/ $ python manage.py runserver
• Go to the browser and type
localhost:8000
The following o/p is shown on browser window
Django Web App…Create App
• Create the App
ks1/Kfirst $ python manage.py startapp Kfirstapp
This adds certain files into Kfirstapp folder
• Register the Kfirstapp it with our Django project
“Kfirst".
– To do so, update INSTALLED_APPS tuple in the settings.py
file of your project Kfirst\Kfirst (add your app name)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
‘Kfirstapp',
)
Django Web App…Admin Interface
• Initiate the database, to have access to admin
interface
ks1/Kfirst $ python manage.py syncdb
• Open the Kfirst/urls.py and you should have
something like −
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(‘ ‘,

url(r'^admin/', include(admin.site.urls)), )
Django Web App…Admin Interface
• Run the Server #ignore if server is already running
ks1/Kfirst/ $ python manage.py runserver

• Go to the browser and type


localhost:8000/admin/
The following o/p is shown on browser window
Django Web App…Create View
• Open the Kfirstapp/views.py and add as per
following −
from django.http import HttpResponse

def hello(request):
text = """<h1>welcome to my app !</h1>"""
return HttpResponse(text)
Django Web App…URL Mapping
• Open the myproject/urls.py and add as per following

from django.conf.urls import patterns, include, url
from django.contrib import admin
from Kfirstapp import views
admin.autodiscover()
urlpatterns = patterns(‘ ‘,

url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', views.hello, name=‘hello')
)
Django Web App…Access Web App
• Run the Server #ignore if server is already running
ks1/Kfirst/ $ python manage.py runserver

• Go to the browser and type


localhost:8000/hello
Hands On

Let’s create a Web App Using Django…on


Windows
For Django Installation..On Windows
• Install Python
– https://python.org/downloads/
• Check if Python is Installed
$ python –version
• If O/P is Python 3.x.x …python has been installed
• Install Django
$ pip install django
• verify your Django installation by executing
$ django-admin --version
$ If O/P is 2.1.7…Django has been installed
Django Web App..Create Project ..On
Windows
• Open the command prompt and create a directory
$ mkdir ks1
• Change the directory to the newly formed directory
$ cd ks1
• Create the Django Project
ks1 $ django-admin startproject Kfirst
This will create Kfirst folder with following structure
Kfirst/
manage.py
Kfirst/
_init_.py
settings.py
urls.py
wsgi.py
Django Web App…RunServer..On
Windows
• Change the directory to the Kfirst
$ cd Kfirst
• Run the Server
ks1/Kfirst/ $ python manage.py runserver
• Go to the browser and type
localhost:8000
The following o/p is shown on browser window
Django Web App…Create App…On
Windows
• Create the App in another command-prompt in Kfirst
folder
ks1/Kfirst $ python manage.py startapp Kfirstapp
This adds certain files into Kfirstapp folder
• Register the Kfirstapp it with our Django project “Kfirst".
– To do so, update INSTALLED_APPS tuple in the settings.py file
(in Kfirst\Kfirst folder)
(add your app name) INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
‘Kfirstapp',
)
Django Web App…Admin Interface..on
Windows
• Initiate the database, to have access to admin
interface …(Run this command in the project folder)
ks1/Kfirst $ python manage.py migrate
• Open the Kfirst/Kfirst/urls.py and you should have
something like −
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
path(‘admin/', admin.site.urls),
]
Django Web App…Admin Interface..
On Windows
• Run the Server #ignore if server is already running
ks1/Kfirst/ $ python manage.py runserver

• Go to the browser and type


localhost:8000/admin/
The following o/p is shown on browser window
Django Web App…Create View…On
windows
• Open the Kfirstapp/views.py and add as per
following −

from django.http import HttpResponse

def hello(request):
text = """<h1>welcome to my app !</h1>"""
return HttpResponse(text)
URL Mapping…On windows
• To call the view, we need to map it to a URL - and
for this we need a URLconf.
• To create a URLconf in the Kfirstapp directory, create
a file called urls.py. Your app directory should now
look like:
from django.urls import path
from .import views

urlpatterns= [
path(‘ ‘, views.hello, name=‘hello’),
)
URL Mapping…On windows
• Change the urls.py in Kfirst\Kfirst folder.

from django.urls import include, path


from django.contrib import admin

urlpatterns = [
path('admin/', admin.site.urls),
path('Kfirstapp/', include(‘Kfirstapp.urls’)),
)
Django Web App…Access Web App
• Run the Server #ignore if server is already running
ks1/Kfirst/ $ python manage.py runserver

• Go to the browser and type


localhost:8000/Kfirstapp

• This is the final output.


Amazon Web Services

• What is AWS
• Why to Use AWS
• AWS Service Overview
• Cost of AWS
• Future of AWS
Amazon Web Services

Used by 80% of
Global Cloud fortune 500
Platform Companies

Infrastructure as a Platform as a
service service

Software as a Cloud Storage


service PLatform
Why to Use AWS

Per Hour Billing Easy Sign Up

Simple Billing Stable

Trusted Vendor
AWS Service Overview
Elastic Cloud Compute Virtual Private Simple Storage
(EC2) Cloud(VPC) Service(S3)
• Gives PAAS Service as per • Allows to create networks • Gives Opportunity to Upload
requirements and allows servers to be in and Store filesi.e File
those networks Storage and Sharng service

Relational Database AutoScaling Route 53


Service(RDS) • Adds Capacity on a fly to • It has DNS Routing Service
• Allows to Run and the ELB , so as to let the
manage database on application never down
cloud due to load

Elastic Load Balanacer(ELB)


• Gives Opportunity to Load Balance in the coming
traffic to multiple machines; so that web app can
scale up to any number of users
Cost of AWS

• Per Hour Billing


• Region Wise Billing
• Term specific billing
• Spot Resources…Bidding
Future of AWS

• 64 Services there in total


• Focus on Machine Learning
• Focus on SAAS products
• Reduction in Costs
SKYNET ..IOT
MESSAGING
PLATFORM
K M Sanghavi
Skynet

■ Open source
■ Instant Messaging (IM) service for connected devices
and services
■ Launched recently.
■ Cloud-based MQTT-powered network
■ Scales to meet any needs whether the nodes are smart home
devices, sensors, cloud resources, drones, Arduinos,
Raspberry Pis, among others.
■ Powered by Node.JS,
■ Combines IoT with Artificial Intelligence
■ Supports Pub/SUb
Skynet

■ When nodes and devices register with Skynet, they


are assigned a unique id known as a UUID along
with a security token
■ Upon connecting your node or device to Skynet,
you can query and update devices on the
network and send machine-to-machine (M2M)
messages in an RPC-style fashion.
■ Real time M2M communication is what Skynet aims
for.
■ SkyNet runs as an IoT platform-as-a-service
(PaaS) as well as a private cloud through Docker
Skynet

■ With SkyNet platform, we are able to save a


ton of work by not having to develop our
own communication tools,
authentication scheme, or backend
service to handle the streams of data
■ Instead, our devices simply turn on,
authenticate and connect with SkyNet
automatically, and we are able to start
passing data securely
Skynet

■ Details can be found on :


https://www.youtube.com/watch?v=iCLe1
XScr2M
■ Skynet.im

You might also like