Chapter 1
Introduction to IoT
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Outline
• IoT definition
• Characteristics of IoT
• Physical Design of IoT
• Logical Design of IoT
• IoT Protocols
• IoT Levels & Deployment Templates
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Definition of IoT
A dynamic global network infrastructure with self-configuring
capabilities based on standard and interoperable communication
protocols where physical and virtual "things" have identities, physical
attributes, and virtual personalities and use intelligent interfaces, and
are seamlessly integrated into the information network, often
communicate data associated with users and their environments.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Characteristics of IoT
• Dynamic & Self-Adapting
• Self-Configuring
• Interoperable Communication Protocols
• Unique Identity
• Integrated into Information Network
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Physical Design of IoT
• The "Things" in IoT usually refers to IoT devices which have unique
identities and can perform remote sensing, actuating and monitoring
capabilities.
• IoT devices can:
• Exchange data with other connected devices and applications (directly or
indirectly), or
• Collect data from other devices and process the data locally or
• Send the data to centralized servers or cloud-based application back-ends for
processing the data, or
• Perform some tasks locally and other tasks within the IoT infrastructure,
based on temporal and space constraints
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Generic block diagram of an IoT Device
• An IoT device may consist of
several interfaces for
connections to other devices,
both wired and wireless.
• I/O interfaces for sensors
• Interfaces for Internet
connectivity
• Memory and storage interfaces
• Audio/video interfaces.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Protocols
• Link Layer
• 802.3 – Ethernet
• 802.11 – WiFi
• 802.16 – WiMax
• 802.15.4 – LR-WPAN
• 2G/3G/4G
• Network/Internet Layer
• IPv4
• IPv6
• 6LoWPAN
• Transport Layer
• TCP
• UDP
• Application Layer
• HTTP
• CoAP
• WebSocket
• MQTT
• XMPP
• DDS
• AMQP
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Logical Design of IoT
• Logical design of an IoT system
refers to an abstract
representation of the entities
and processes without going
into the low-level specifics of
the implementation.
• An IoT system comprises of a
number of functional blocks
that provide the system the
capabilities for identification,
sensing, actuation,
communication, and
management.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Request-Response communication model
• Request-Response is a
communication model in which
the client sends requests to the
server and the server responds
to the requests.
• When the server receives a
request, it decides how to
respond, fetches the data,
retrieves resource
representations, prepares the
response, and then sends the
response to the client.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Publish-Subscribe communication model
• Publish-Subscribe is a
communication model that
involves publishers, brokers and
consumers.
• Publishers are the source of data.
Publishers send the data to the
topics which are managed by the
broker. Publishers are not aware
of the consumers.
• Consumers subscribe to the topics
which are managed by the broker.
• When the broker receives data for
a topic from the publisher, it
sends the data to all the
subscribed consumers.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Push-Pull communication model
• Push-Pull is a communication
model in which the data
producers push the data to
queues and the consumers pull
the data from the queues.
Producers do not need to be
aware of the consumers.
• Queues help in decoupling the
messaging between the producers
and consumers.
• Queues also act as a buffer which
helps in situations when there is a
mismatch between the rate at
which the producers push data
and the rate rate at which the
consumers pull data.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Exclusive Pair communication model
• Exclusive Pair is a
bidirectional, fully duplex
communication model that
uses a persistent connection
between the client and
server.
• Once the connection is setup
it remains open until the
client sends a request to
close the connection.
• Client and server can send
messages to each other after
connection setup.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
REST-based Communication APIs
• Representational State Transfer
(REST) is a set of architectural
principles by which you can design
web services and web APIs that
focus on a system’s resources and
how resource states are
addressed and transferred.
• REST APIs follow the request-
response communication model.
• The REST architectural constraints
apply to the components,
connectors, and data elements,
within a distributed hypermedia
system.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
WebSocket-based Communication APIs
• WebSocket APIs allow bi-
directional, full duplex
communication between
clients and servers.
• WebSocket APIs follow the
exclusive pair
communication model
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Exclusive Pair communication model
• Exclusive Pair is a
bidirectional, fully duplex
communication model that
uses a persistent connection
between the client and
server.
• Once the connection is setup
it remains open until the
client sends a request to
close the connection.
• Client and server can send
messages to each other after
connection setup.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Levels & Deployment Templates
An IoT system comprises of the following components:
• Device: An IoT device allows identification, remote sensing, actuating and
remote monitoring capabilities. You learned about various examples of IoT
devices in section
• Resource: Resources are software components on the IoT device for
accessing, processing, and storing sensor information, or controlling
actuators connected to the device. Resources also include the software
components that enable network access for the device.
• Controller Service: Controller service is a native service that runs on the
device and interacts with the web services. Controller service sends data
from the device to the web service and receives commands from the
application (via web services) for controlling the device.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Levels & Deployment Templates
• Database: Database can be either local or in the cloud and stores the data
generated by the IoT device.
• Web Service: Web services serve as a link between the IoT device,
application, database and analysis components. Web service can be either
implemented using HTTP and REST principles (REST service) or using
WebSocket protocol (WebSocket service).
• Analysis Component: The Analysis Component is responsible for analyzing
the IoT data and generate results in a form which are easy for the user to
understand.
• Application: IoT applications provide an interface that the users can use to
control and monitor various aspects of the IoT system. Applications also
allow users to view the system status and view the processed data.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Level-1
• A level-1 IoT system has a
single node/device that
performs sensing and/or
actuation, stores data,
performs analysis and hosts
the application
• Level-1 IoT systems are
suitable for modeling low-
cost and low-complexity
solutions where the data
involved is not big and the
analysis requirements are
not computationally
intensive.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Level-2
• A level-2 IoT system has a
single node that performs
sensing and/or actuation and
local analysis.
• Data is stored in the cloud and
application is usually cloud-
based.
• Level-2 IoT systems are
suitable for solutions where
the data involved is big,
however, the primary analysis
requirement is not
computationally intensive and
can be done locally itself.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Level-3
• A level-3 IoT system has a
single node. Data is stored
and analyzed in the cloud
and application is cloud-
based.
• Level-3 IoT systems are
suitable for solutions
where the data involved is
big and the analysis
requirements are
computationally intensive.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Level-4
• A level-4 IoT system has multiple
nodes that perform local analysis.
Data is stored in the cloud and
application is cloud-based.
• Level-4 contains local and cloud-
based observer nodes which can
subscribe to and receive
information collected in the cloud
from IoT devices.
• Level-4 IoT systems are suitable
for solutions where multiple
nodes are required, the data
involved is big and the analysis
requirements are computationally
intensive.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Level-5
• A level-5 IoT system has multiple end
nodes and one coordinator node.
• The end nodes that perform sensing
and/or actuation.
• Coordinator node collects data from
the end nodes and sends to the cloud.
• Data is stored and analyzed in the
cloud and application is cloud-based.
• Level-5 IoT systems are suitable for
solutions based on wireless sensor
networks, in which the data involved
is big and the analysis requirements
are computationally intensive.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Level-6
• A level-6 IoT system has multiple
independent end nodes that
perform sensing and/or actuation
and send data to the cloud.
• Data is stored in the cloud and
application is cloud-based.
• The analytics component analyzes
the data and stores the results in
the cloud database.
• The results are visualized with the
cloud-based application.
• The centralized controller is aware
of the status of all the end nodes
and sends control commands to
the nodes.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Chapter 5
IoT Design Methodology
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Outline
• IoT Design Methodology that includes:
• Purpose & Requirements Specification
• Process Specification
• Domain Model Specification
• Information Model Specification
• Service Specifications
• IoT Level Specification
• Functional View Specification
• Operational View Specification
• Device & Component Integration
• Application Development
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Design Methodology - Steps
Step 1: Purpose & Requirements Specification
• The first step in IoT system design methodology is to define the
purpose and requirements of the system. In this step, the system
purpose, behavior and requirements (such as data collection
requirements, data analysis requirements, system management
requirements, data privacy and security requirements, user interface
requirements, ...) are captured.
Step 2: Process Specification
• The second step in the IoT design methodology is to define the
process specification. In this step, the use cases of the IoT system are
formally described based on and derived from the purpose and
requirement specifications.
Step 3: Domain Model Specification
• The third step in the IoT design methodology is to define the Domain
Model. The domain model describes the main concepts, entities and
objects in the domain of IoT system to be designed. Domain model
defines the attributes of the objects and relationships between
objects. Domain model provides an abstract representation of the
concepts, objects and entities in the IoT domain, independent of any
specific technology or platform. With the domain model, the IoT
system designers can get an understanding of the IoT domain for
which the system is to be designed.
Step 4: Information Model Specification
• The fourth step in the IoT design methodology is to define the
Information Model. Information Model defines the structure of all
the information in the IoT system, for example, attributes of Virtual
Entities, relations, etc. Information model does not describe the
specifics of how the information is represented or stored. To define
the information model, we first list the Virtual Entities defined in the
Domain Model. Information model adds more details to the Virtual
Entities by defining their attributes and relations.
Step 5: Service Specifications
• The fifth step in the IoT design methodology is to define the service
specifications. Service specifications define the services in the IoT
system, service types, service inputs/output, service endpoints,
service schedules, service preconditions and service effects.
Step 6: IoT Level Specification
• The sixth step in the IoT design methodology is to define the IoT level
for the system. In Chapter-1, we defined five IoT deployment levels.
Step 7: Functional View Specification
• The seventh step in the IoT design methodology is to define the
Functional View. The Functional View (FV) defines the functions of
the IoT systems grouped into various Functional Groups (FGs). Each
Functional Group either provides functionalities for interacting with
instances of concepts defined in the Domain Model or provides
information related to these concepts.
Step 8: Operational View Specification
• The eighth step in the IoT design methodology is to define the
Operational View Specifications. In this step, various options
pertaining to the IoT system deployment and operation are defined,
such as, service hosting options, storage options, device options,
application hosting options, etc
Step 9: Device & Component Integration
• The ninth step in the IoT design methodology is the integration of the
devices and components.
Step 10: Application Development
• The final step in the IoT design methodology is to develop the IoT
application.
Home Automation Case Study
Step:1 - Purpose & Requirements
• Applying this to our example of a smart home automation system, the
purpose and requirements for the system may be described as follows:
• Purpose : A home automation system that allows controlling of the lights in a home
remotely using a web application.
• Behavior : The home automation system should have auto and manual modes. In
auto mode, the system measures the light level in the room and switches on the
light when it gets dark. In manual mode, the system provides the option of manually
and remotely switching on/off the light.
• System Management Requirement : The system should provide remote monitoring
and control functions.
• Data Analysis Requirement : The system should perform local analysis of the data.
• Application Deployment Requirement : The application should be deployed locally
on the device, but should be accessible remotely.
• Security Requirement : The system should have basic user authentication capability.
Step:2 - Process Specification
Step 3: Domain Model Specification
Step 4: Information Model Specification
Step 5: Service Specifications
Step 5: Service Specifications
Step 6: IoT Level Specification
Step 7: Functional View Specification
Step 8: Operational View Specification
Step 9: Device & Component Integration
Step 10: Application Development
• Auto
• Controls the light appliance automatically based on the lighting
conditions in the room
• Light
• When Auto mode is off, it is used for manually controlling the
light appliance.
• When Auto mode is on, it reflects the current state of the light
appliance.
Implementation: RESTful Web Services
# Models – models.py
from django.db import models
class Mode(models.Model):
name = models.CharField(max_length=50)
class State(models.Model):
name = models.CharField(max_length=50)
# Serializers – serializers.py
from myapp.models import Mode, State
from rest_framework import serializers
class ModeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Mode
fields = ('url', 'name')
class StateSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = State
fields = ('url', 'name')
REST services implemented with Django REST Framework
1. Map services to models. Model
fields store the states (on/off,
auto/manual)
2. Write Model serializers. Serializers allow
complex data (such as model instances) to be
converted to native Python datatypes that can
then be easily rendered into JSON, XML or
other content types.
Implementation: RESTful Web Services
# Views – views.py
from myapp.models import Mode, State
from rest_framework import viewsets
from myapp.serializers import ModeSerializer, StateSerializer
class ModeViewSet(viewsets.ModelViewSet):
queryset = Mode.objects.all()
serializer_class = ModeSerializer
class StateViewSet(viewsets.ModelViewSet):
queryset = State.objects.all()
serializer_class = StateSerializer
3. Write ViewSets for the Models which
combine the logic for a set of related views in
a single class.
# Models – models.py
from django.db import models
class Mode(models.Model):
name = models.CharField(max_length=50)
class State(models.Model):
name = models.CharField(max_length=50)
4. Write URL patterns for the services.
Since ViewSets are used instead of views, we
can automatically generate the URL conf by
simply registering the viewsets with a router
class.
Routers automatically determining how the
URLs for an application should be mapped to
the logic that deals with handling incoming
requests.
# URL Patterns – urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from rest_framework import routers
from myapp import views
admin.autodiscover()
router = routers.DefaultRouter()
router.register(r'mode', views.ModeViewSet)
router.register(r'state', views.StateViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
url(r'^home/', 'myapp.views.home'),
)
Implementation: RESTful Web Services
Screenshot of browsable
State REST API
Screenshot of browsable
Mode REST API
Implementation: Controller Native Service
#Controller service
import RPi.GPIO as GPIO
import time
import sqlite3 as lite
import sys
con = lite.connect('database.sqlite')
cur = con.cursor()
GPIO.setmode(GPIO.BCM)
threshold = 1000
LDR_PIN = 18
LIGHT_PIN = 25
def readldr(PIN):
reading=0
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(PIN, GPIO.IN)
while (GPIO.input(PIN)==GPIO.LOW):
reading=reading+1
return reading
def switchOnLight(PIN):
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, GPIO.HIGH)
def switchOffLight(PIN):
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, GPIO.LOW)
def runAutoMode():
ldr_reading = readldr(LDR_PIN)
if ldr_reading < threshold:
switchOnLight(LIGHT_PIN)
setCurrentState('on')
else:
switchOffLight(LIGHT_PIN)
setCurrentState('off')
def runManualMode():
state = getCurrentState()
if state=='on':
switchOnLight(LIGHT_PIN)
setCurrentState('on')
elif state=='off':
switchOffLight(LIGHT_PIN)
setCurrentState('off')
def getCurrentMode():
cur.execute('SELECT * FROM myapp_mode')
data = cur.fetchone() #(1, u'auto')
return data[1]
def getCurrentState():
cur.execute('SELECT * FROM myapp_state')
data = cur.fetchone() #(1, u'on')
return data[1]
def setCurrentState(val):
query='UPDATE myapp_state set name="'+val+'"'
cur.execute(query)
while True:
currentMode=getCurrentMode()
if currentMode=='auto':
runAutoMode()
elif currentMode=='manual':
runManualMode()
time.sleep(5)
Native service deployed locally
1. Implement the native service in
Python and run on the device
Implementation: Application
# Views – views.py
def home(request):
out=‘’
if 'on' in request.POST:
values = {"name": "on"}
r=requests.put('http://127.0.0.1:8000/state/1/', data=values, auth=(‘username', ‘password'))
result=r.text
output = json.loads(result)
out=output['name']
if 'off' in request.POST:
values = {"name": "off"}
r=requests.put('http://127.0.0.1:8000/state/1/', data=values, auth=(‘username', ‘password'))
result=r.text
output = json.loads(result)
out=output['name']
if 'auto' in request.POST:
values = {"name": "auto"}
r=requests.put('http://127.0.0.1:8000/mode/1/', data=values, auth=(‘username', ‘password'))
result=r.text
output = json.loads(result)
out=output['name']
if 'manual' in request.POST:
values = {"name": "manual"}
r=requests.put('http://127.0.0.1:8000/mode/1/', data=values, auth=(‘username', ‘password'))
result=r.text
output = json.loads(result)
out=output['name']
r=requests.get('http://127.0.0.1:8000/mode/1/', auth=(‘username', ‘password'))
result=r.text
output = json.loads(result)
currentmode=output['name']
r=requests.get('http://127.0.0.1:8000/state/1/', auth=(‘username', ‘password'))
result=r.text
output = json.loads(result)
currentstate=output['name']
return render_to_response('lights.html',{'r':out, 'currentmode':currentmode, 'currentstate':currentstate},
context_instance=RequestContext(request))
1. Implement Django Application View
Implementation: Application
<div class="app-content-inner">
<fieldset>
<div class="field clearfix">
<label class="input-label icon-lamp" for="lamp-state">Auto</label>
<input id="lamp-state" class="input js-lamp-state hidden" type="checkbox">
{% if currentmode == 'auto' %}
<div class="js-lamp-state-toggle ui-toggle " data-toggle=".js-lamp-state">
{% else %}
<div class="js-lamp-state-toggle ui-toggle js-toggle-off" data-toggle=".js-lamp-state">
{% endif %}
<span class="ui-toggle-slide clearfix">
<form id="my_form11" action="" method="post">{% csrf_token %}
<input name="auto" value="auto" type="hidden" />
<a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-off">OFF</strong></a>
</form>
<strong class="ui-toggle-handle brushed-metal"></strong>
<form id="my_form13" action="" method="post">{% csrf_token %}
<input name="manual" value="manual" type="hidden" />
<a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-on">ON</strong></a>
</form></span>
</div></div>
<div class="field clearfix">
<label class="input-label icon-lamp" for="tv-state">Light</label>
<input id="tv-state" class="input js-tv-state hidden" type="checkbox">
{% if currentstate == 'on' %}
<div class="js-tv-state-toggle ui-toggle " data-toggle=".js-tv-state">
{% else %}
<div class="js-tv-state-toggle ui-toggle js-toggle-off" data-toggle=".js-tv-state">
{% endif %}
{% if currentmode == 'manual' %}
<span class="ui-toggle-slide clearfix">
<form id="my_form2" action="" method="post">{% csrf_token %}
<input name="on" value="on" type="hidden" />
<a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-off">OFF</strong></a>
</form>
<strong class="ui-toggle-handle brushed-metal"></strong>
<form id="my_form3" action="" method="post">{% csrf_token %}
<input name="off" value="off" type="hidden" />
<a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-on">ON</strong></a>
</form>
</span>
{% endif %}
{% if currentmode == 'auto' %}
{% if currentstate == 'on' %}
<strong class="ui-toggle-on">&nbsp;&nbsp;&nbsp;&nbsp;ON</strong>
{% else %}
<strong class="ui-toggle-on">&nbsp;&nbsp;&nbsp;&nbsp;OFF</strong>
{% endif %}{% endif %}
</div>
</div>
</fieldset></div></div></div>
2. Implement Django Application
Template
Finally - Integrate the System
Django Application
REST services implemented with Django-REST framework
Native service implemented in Python
SQLite Database
Raspberry Pi device to which sensors and actuators are connected
OS running on Raspberry Pi
• Setup the device
• Deploy and run the REST and Native services
• Deploy and run the Application
• Setup the database
Chapter 7
IoT Physical Devices & Endpoints
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Outline
• Basic building blocks of an IoT Device
• Exemplary Device: Raspberry Pi
• Raspberry Pi interfaces
• Programming Raspberry Pi with Python
• Other IoT devices
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
What is an IoT Device
• A "Thing" in Internet of Things (IoT) can be any object that has a
unique identifier and which can send/receive data (including user
data) over a network (e.g., smart phone, smart TV, computer,
refrigerator, car, etc. ).
• IoT devices are connected to the Internet and send information
about themselves or about their surroundings (e.g. information
sensed by the connected sensors) over a network (to other devices or
servers/storage) or allow actuation upon the physical
entities/environment around them remotely.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
IoT Device Examples
• A home automation device that allows remotely monitoring the
status of appliances and controlling the appliances.
• An industrial machine which sends information abouts its operation
and health monitoring data to a server.
• A car which sends information about its location to a cloud-based
service.
• A wireless-enabled wearable device that measures data about a
person such as the number of steps walked and sends the data to a
cloud-based service.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Basic building blocks of an IoT Device
• Sensing
• Sensors can be either on-board the IoT device or attached to the device.
• Actuation
• IoT devices can have various types of actuators attached that allow taking
• actions upon the physical entities in the vicinity of the device.
• Communication
• Communication modules are responsible for sending collected data to other
devices or cloud-based servers/storage and receiving data from other devices
and commands from remote applications.
• Analysis & Processing
• Analysis and processing modules are responsible for making sense of the
collected data.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Block diagram of an IoT Device
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Exemplary Device: Raspberry Pi
• Raspberry Pi is a low-cost mini-computer with the physical size of a
credit card.
• Raspberry Pi runs various flavors of Linux and can perform almost all
tasks that a normal desktop computer can do.
• Raspberry Pi also allows interfacing sensors and actuators through
the general purpose I/O pins.
• Since Raspberry Pi runs Linux operating system, it supports Python
"out of the box".
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Exemplary Device: Raspberry Pi
• Raspberry Pi is a low-cost mini-computer with the physical size of a
credit card.
• Raspberry Pi runs various flavors of Linux and can perform almost all
tasks that a normal desktop computer can do.
• Raspberry Pi also allows interfacing sensors and actuators through
the general purpose I/O pins.
• Since Raspberry Pi runs Linux operating system, it supports Python
"out of the box".
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Raspberry Pi
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Linux on Raspberry Pi
• Raspbian
• Raspbian Linux is a Debian Wheezy port optimized for Raspberry Pi.
• Arch
• Arch is an Arch Linux port for AMD devices.
• Pidora
• Pidora Linux is a Fedora Linux optimized for Raspberry Pi.
• RaspBMC
• RaspBMC is an XBMC media-center distribution for Raspberry Pi.
• OpenELEC
• OpenELEC is a fast and user-friendly XBMC media-center distribution.
• RISC OS
• RISC OS is a very fast and compact operating system.
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Raspberry Pi GPIO
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Raspberry Pi Interfaces
• Serial
• The serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins
for communication with serial peripherals.
• SPI
• Serial Peripheral Interface (SPI) is a synchronous serial data protocol used
for communicating with one or more peripheral devices.
• I2C
• The I2C interface pins on Raspberry Pi allow you to connect hardware
modules. I2C interface allows synchronous data transfer with just two pins -
SDA (data line) and SCL (clock line).
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
Raspberry Pi Example:
Interfacing LED and switch with Raspberry Pi
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
#Switch Pin
GPIO.setup(25, GPIO.IN)
#LED Pin
GPIO.setup(18, GPIO.OUT)
state=false
def toggleLED(pin):
state = not state
GPIO.output(pin, state)
while True:
try:
if (GPIO.input(25) == True):
toggleLED(pin)
sleep(.01)
except KeyboardInterrupt:
exit()
Other Devices
Bahga & Madisetti, © 2015
Book website: http://www.internet-of-things-book.com
• pcDuino
• BeagleBone Black
• Cubieboard

More Related Content

PPTX
Iot logical design
PDF
IoT and m2m
PPTX
Internet of Things
PPTX
HyperText Transfer Protocol (HTTP)
PPT
Introduction to Google App Engine
PPTX
SDN( Software Defined Network) and NFV(Network Function Virtualization) for I...
PPTX
Iot presentation
PPTX
NEAR FIELD COMMUNICATION
Iot logical design
IoT and m2m
Internet of Things
HyperText Transfer Protocol (HTTP)
Introduction to Google App Engine
SDN( Software Defined Network) and NFV(Network Function Virtualization) for I...
Iot presentation
NEAR FIELD COMMUNICATION

What's hot (20)

PPT
ECG ANALYSIS IN CLOUD COMPUTING
PPTX
message communication protocols in IoT
PPTX
Wireless Communication ppt
PPTX
IOT Network architecture and Design.pptx
PPTX
IOT DATA MANAGEMENT AND COMPUTE STACK.pptx
PPTX
Chapter_1.pptx
PDF
Security Aspects in IoT - A Review
PPTX
Big Data and Hadoop Guide
PPT
Bluetooth technology presentation
PDF
IEEE 802.11ax
PPTX
Zigbee Presentation
PPTX
zigbee full ppt
PPTX
M2M Communication
PPTX
Communication technologies
PPTX
Edge Computing.pptx
PPT
Wireless transmission
PPTX
IOT.pptx
PPTX
PDF
Google App Engine
ECG ANALYSIS IN CLOUD COMPUTING
message communication protocols in IoT
Wireless Communication ppt
IOT Network architecture and Design.pptx
IOT DATA MANAGEMENT AND COMPUTE STACK.pptx
Chapter_1.pptx
Security Aspects in IoT - A Review
Big Data and Hadoop Guide
Bluetooth technology presentation
IEEE 802.11ax
Zigbee Presentation
zigbee full ppt
M2M Communication
Communication technologies
Edge Computing.pptx
Wireless transmission
IOT.pptx
Google App Engine
Ad

Similar to unit 3.pdf (20)

PPTX
unit1-iot introduction,logical design ,physical design
DOCX
U 1 Physical and logical.RGPV internet of things notes
PPTX
Chapter-1 - Internet of Things: A Hands-on Approach
PDF
Chapter 1 updated.pdf
PPTX
IoT heap 1
PPTX
Chapter - 1.pptx
PPTX
IoT.pptx
PPTX
chapter-1_iot.pptx
PPT
IOT UNIT 1B.ppt
PPTX
1427264023243345TGFGBBGHGJKU6Y767GGGBGGH
PPTX
Introduction to Internet of things Introduction to Internet of things
PDF
intro to iot.pdf
PPTX
Iot unit i
PPTX
Iot unit i present by JAVVAJI VENKATRAO SVEC,TIRUPATI
PPTX
Introduction to Internet of thingsT-Unit-1.pptx
PPTX
IT18503 Internet of Things unit-1 introduction.pptx
PPTX
ppt-3-iotlogicdesign-210125034351.pptx
PPTX
Chapter-1.pptx
PPTX
Ppt 3 - IOT logic design
PPTX
An overview IoT Platform 2024 07082024.pptx
unit1-iot introduction,logical design ,physical design
U 1 Physical and logical.RGPV internet of things notes
Chapter-1 - Internet of Things: A Hands-on Approach
Chapter 1 updated.pdf
IoT heap 1
Chapter - 1.pptx
IoT.pptx
chapter-1_iot.pptx
IOT UNIT 1B.ppt
1427264023243345TGFGBBGHGJKU6Y767GGGBGGH
Introduction to Internet of things Introduction to Internet of things
intro to iot.pdf
Iot unit i
Iot unit i present by JAVVAJI VENKATRAO SVEC,TIRUPATI
Introduction to Internet of thingsT-Unit-1.pptx
IT18503 Internet of Things unit-1 introduction.pptx
ppt-3-iotlogicdesign-210125034351.pptx
Chapter-1.pptx
Ppt 3 - IOT logic design
An overview IoT Platform 2024 07082024.pptx
Ad

More from KavithaK23 (10)

DOCX
PHP record- with all programs and output
DOCX
PHP Lab template for lecturer log book- and syllabus
DOCX
CRUD OPERATIONS using MySQL connectivity in php
DOCX
Unit III.docx
DOCX
Unit 4 - 2.docx
PDF
unit 4 - 1.pdf
PDF
unit 5 -2.pdf
PDF
unit 5 -1.pdf
DOCX
UNIT 5.docx
PDF
unit 2 -program security.pdf
PHP record- with all programs and output
PHP Lab template for lecturer log book- and syllabus
CRUD OPERATIONS using MySQL connectivity in php
Unit III.docx
Unit 4 - 2.docx
unit 4 - 1.pdf
unit 5 -2.pdf
unit 5 -1.pdf
UNIT 5.docx
unit 2 -program security.pdf

Recently uploaded (20)

PDF
ENT MedMap you can study for the exam with this.pdf
PPTX
Nancy Caroline Emergency Paramedic Chapter 1
PPTX
POSTURE.pptx......,............. .........
PPTX
Fever and skin rash - Approach.pptxBy Dr Gururaja R , Paediatrician. An usef...
PPTX
Nancy Caroline Emergency Paramedic Chapter 11
PPTX
Nepal health service act.pptx by Sunil Sharma
PPTX
Understanding The Self : 1Sexual health
PPTX
ANALGESIC AND ANTI-INFLAMMssssssATORY DRUGS.pptx
PDF
_OB Finals 24.pdf notes for pregnant women
PPTX
Hospital Services healthcare management in india
PPTX
Nancy Caroline Emergency Paramedic Chapter 7
PDF
Culturally Sensitive Health Solutions: Engineering Localized Practices (www....
PDF
01. Histology New Classification of histo is clear calssification
DOCX
PT10 continues to explose your mind right after reading
PDF
cerebral aneurysm.. neurosurgery , anaesthesia
PPT
Pyramid Points Acid Base Power Point (10).ppt
PDF
chapter 14.pdf Ch+12+SGOB.docx hilighted important stuff on exa,
PPTX
Nancy Caroline Emergency Paramedic Chapter 17
PDF
Introduction to Clinical Psychology, 4th Edition by John Hunsley Test Bank.pdf
PPTX
Arthritis Types, Signs & Treatment with physiotherapy management
ENT MedMap you can study for the exam with this.pdf
Nancy Caroline Emergency Paramedic Chapter 1
POSTURE.pptx......,............. .........
Fever and skin rash - Approach.pptxBy Dr Gururaja R , Paediatrician. An usef...
Nancy Caroline Emergency Paramedic Chapter 11
Nepal health service act.pptx by Sunil Sharma
Understanding The Self : 1Sexual health
ANALGESIC AND ANTI-INFLAMMssssssATORY DRUGS.pptx
_OB Finals 24.pdf notes for pregnant women
Hospital Services healthcare management in india
Nancy Caroline Emergency Paramedic Chapter 7
Culturally Sensitive Health Solutions: Engineering Localized Practices (www....
01. Histology New Classification of histo is clear calssification
PT10 continues to explose your mind right after reading
cerebral aneurysm.. neurosurgery , anaesthesia
Pyramid Points Acid Base Power Point (10).ppt
chapter 14.pdf Ch+12+SGOB.docx hilighted important stuff on exa,
Nancy Caroline Emergency Paramedic Chapter 17
Introduction to Clinical Psychology, 4th Edition by John Hunsley Test Bank.pdf
Arthritis Types, Signs & Treatment with physiotherapy management

unit 3.pdf

  • 1. Chapter 1 Introduction to IoT Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 2. Outline • IoT definition • Characteristics of IoT • Physical Design of IoT • Logical Design of IoT • IoT Protocols • IoT Levels & Deployment Templates Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 3. Definition of IoT A dynamic global network infrastructure with self-configuring capabilities based on standard and interoperable communication protocols where physical and virtual "things" have identities, physical attributes, and virtual personalities and use intelligent interfaces, and are seamlessly integrated into the information network, often communicate data associated with users and their environments. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 4. Characteristics of IoT • Dynamic & Self-Adapting • Self-Configuring • Interoperable Communication Protocols • Unique Identity • Integrated into Information Network Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 5. Physical Design of IoT • The "Things" in IoT usually refers to IoT devices which have unique identities and can perform remote sensing, actuating and monitoring capabilities. • IoT devices can: • Exchange data with other connected devices and applications (directly or indirectly), or • Collect data from other devices and process the data locally or • Send the data to centralized servers or cloud-based application back-ends for processing the data, or • Perform some tasks locally and other tasks within the IoT infrastructure, based on temporal and space constraints Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 6. Generic block diagram of an IoT Device • An IoT device may consist of several interfaces for connections to other devices, both wired and wireless. • I/O interfaces for sensors • Interfaces for Internet connectivity • Memory and storage interfaces • Audio/video interfaces. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 7. IoT Protocols • Link Layer • 802.3 – Ethernet • 802.11 – WiFi • 802.16 – WiMax • 802.15.4 – LR-WPAN • 2G/3G/4G • Network/Internet Layer • IPv4 • IPv6 • 6LoWPAN • Transport Layer • TCP • UDP • Application Layer • HTTP • CoAP • WebSocket • MQTT • XMPP • DDS • AMQP Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 8. Logical Design of IoT • Logical design of an IoT system refers to an abstract representation of the entities and processes without going into the low-level specifics of the implementation. • An IoT system comprises of a number of functional blocks that provide the system the capabilities for identification, sensing, actuation, communication, and management. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 9. Request-Response communication model • Request-Response is a communication model in which the client sends requests to the server and the server responds to the requests. • When the server receives a request, it decides how to respond, fetches the data, retrieves resource representations, prepares the response, and then sends the response to the client. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 10. Publish-Subscribe communication model • Publish-Subscribe is a communication model that involves publishers, brokers and consumers. • Publishers are the source of data. Publishers send the data to the topics which are managed by the broker. Publishers are not aware of the consumers. • Consumers subscribe to the topics which are managed by the broker. • When the broker receives data for a topic from the publisher, it sends the data to all the subscribed consumers. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 11. Push-Pull communication model • Push-Pull is a communication model in which the data producers push the data to queues and the consumers pull the data from the queues. Producers do not need to be aware of the consumers. • Queues help in decoupling the messaging between the producers and consumers. • Queues also act as a buffer which helps in situations when there is a mismatch between the rate at which the producers push data and the rate rate at which the consumers pull data. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 12. Exclusive Pair communication model • Exclusive Pair is a bidirectional, fully duplex communication model that uses a persistent connection between the client and server. • Once the connection is setup it remains open until the client sends a request to close the connection. • Client and server can send messages to each other after connection setup. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 13. REST-based Communication APIs • Representational State Transfer (REST) is a set of architectural principles by which you can design web services and web APIs that focus on a system’s resources and how resource states are addressed and transferred. • REST APIs follow the request- response communication model. • The REST architectural constraints apply to the components, connectors, and data elements, within a distributed hypermedia system. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 14. WebSocket-based Communication APIs • WebSocket APIs allow bi- directional, full duplex communication between clients and servers. • WebSocket APIs follow the exclusive pair communication model Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 15. Exclusive Pair communication model • Exclusive Pair is a bidirectional, fully duplex communication model that uses a persistent connection between the client and server. • Once the connection is setup it remains open until the client sends a request to close the connection. • Client and server can send messages to each other after connection setup. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 16. IoT Levels & Deployment Templates An IoT system comprises of the following components: • Device: An IoT device allows identification, remote sensing, actuating and remote monitoring capabilities. You learned about various examples of IoT devices in section • Resource: Resources are software components on the IoT device for accessing, processing, and storing sensor information, or controlling actuators connected to the device. Resources also include the software components that enable network access for the device. • Controller Service: Controller service is a native service that runs on the device and interacts with the web services. Controller service sends data from the device to the web service and receives commands from the application (via web services) for controlling the device. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 17. IoT Levels & Deployment Templates • Database: Database can be either local or in the cloud and stores the data generated by the IoT device. • Web Service: Web services serve as a link between the IoT device, application, database and analysis components. Web service can be either implemented using HTTP and REST principles (REST service) or using WebSocket protocol (WebSocket service). • Analysis Component: The Analysis Component is responsible for analyzing the IoT data and generate results in a form which are easy for the user to understand. • Application: IoT applications provide an interface that the users can use to control and monitor various aspects of the IoT system. Applications also allow users to view the system status and view the processed data. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 18. IoT Level-1 • A level-1 IoT system has a single node/device that performs sensing and/or actuation, stores data, performs analysis and hosts the application • Level-1 IoT systems are suitable for modeling low- cost and low-complexity solutions where the data involved is not big and the analysis requirements are not computationally intensive. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 19. IoT Level-2 • A level-2 IoT system has a single node that performs sensing and/or actuation and local analysis. • Data is stored in the cloud and application is usually cloud- based. • Level-2 IoT systems are suitable for solutions where the data involved is big, however, the primary analysis requirement is not computationally intensive and can be done locally itself. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 20. IoT Level-3 • A level-3 IoT system has a single node. Data is stored and analyzed in the cloud and application is cloud- based. • Level-3 IoT systems are suitable for solutions where the data involved is big and the analysis requirements are computationally intensive. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 21. IoT Level-4 • A level-4 IoT system has multiple nodes that perform local analysis. Data is stored in the cloud and application is cloud-based. • Level-4 contains local and cloud- based observer nodes which can subscribe to and receive information collected in the cloud from IoT devices. • Level-4 IoT systems are suitable for solutions where multiple nodes are required, the data involved is big and the analysis requirements are computationally intensive. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 22. IoT Level-5 • A level-5 IoT system has multiple end nodes and one coordinator node. • The end nodes that perform sensing and/or actuation. • Coordinator node collects data from the end nodes and sends to the cloud. • Data is stored and analyzed in the cloud and application is cloud-based. • Level-5 IoT systems are suitable for solutions based on wireless sensor networks, in which the data involved is big and the analysis requirements are computationally intensive. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 23. IoT Level-6 • A level-6 IoT system has multiple independent end nodes that perform sensing and/or actuation and send data to the cloud. • Data is stored in the cloud and application is cloud-based. • The analytics component analyzes the data and stores the results in the cloud database. • The results are visualized with the cloud-based application. • The centralized controller is aware of the status of all the end nodes and sends control commands to the nodes. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 24. Chapter 5 IoT Design Methodology Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 25. Outline • IoT Design Methodology that includes: • Purpose & Requirements Specification • Process Specification • Domain Model Specification • Information Model Specification • Service Specifications • IoT Level Specification • Functional View Specification • Operational View Specification • Device & Component Integration • Application Development Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 27. Step 1: Purpose & Requirements Specification • The first step in IoT system design methodology is to define the purpose and requirements of the system. In this step, the system purpose, behavior and requirements (such as data collection requirements, data analysis requirements, system management requirements, data privacy and security requirements, user interface requirements, ...) are captured.
  • 28. Step 2: Process Specification • The second step in the IoT design methodology is to define the process specification. In this step, the use cases of the IoT system are formally described based on and derived from the purpose and requirement specifications.
  • 29. Step 3: Domain Model Specification • The third step in the IoT design methodology is to define the Domain Model. The domain model describes the main concepts, entities and objects in the domain of IoT system to be designed. Domain model defines the attributes of the objects and relationships between objects. Domain model provides an abstract representation of the concepts, objects and entities in the IoT domain, independent of any specific technology or platform. With the domain model, the IoT system designers can get an understanding of the IoT domain for which the system is to be designed.
  • 30. Step 4: Information Model Specification • The fourth step in the IoT design methodology is to define the Information Model. Information Model defines the structure of all the information in the IoT system, for example, attributes of Virtual Entities, relations, etc. Information model does not describe the specifics of how the information is represented or stored. To define the information model, we first list the Virtual Entities defined in the Domain Model. Information model adds more details to the Virtual Entities by defining their attributes and relations.
  • 31. Step 5: Service Specifications • The fifth step in the IoT design methodology is to define the service specifications. Service specifications define the services in the IoT system, service types, service inputs/output, service endpoints, service schedules, service preconditions and service effects.
  • 32. Step 6: IoT Level Specification • The sixth step in the IoT design methodology is to define the IoT level for the system. In Chapter-1, we defined five IoT deployment levels.
  • 33. Step 7: Functional View Specification • The seventh step in the IoT design methodology is to define the Functional View. The Functional View (FV) defines the functions of the IoT systems grouped into various Functional Groups (FGs). Each Functional Group either provides functionalities for interacting with instances of concepts defined in the Domain Model or provides information related to these concepts.
  • 34. Step 8: Operational View Specification • The eighth step in the IoT design methodology is to define the Operational View Specifications. In this step, various options pertaining to the IoT system deployment and operation are defined, such as, service hosting options, storage options, device options, application hosting options, etc
  • 35. Step 9: Device & Component Integration • The ninth step in the IoT design methodology is the integration of the devices and components.
  • 36. Step 10: Application Development • The final step in the IoT design methodology is to develop the IoT application.
  • 38. Step:1 - Purpose & Requirements • Applying this to our example of a smart home automation system, the purpose and requirements for the system may be described as follows: • Purpose : A home automation system that allows controlling of the lights in a home remotely using a web application. • Behavior : The home automation system should have auto and manual modes. In auto mode, the system measures the light level in the room and switches on the light when it gets dark. In manual mode, the system provides the option of manually and remotely switching on/off the light. • System Management Requirement : The system should provide remote monitoring and control functions. • Data Analysis Requirement : The system should perform local analysis of the data. • Application Deployment Requirement : The application should be deployed locally on the device, but should be accessible remotely. • Security Requirement : The system should have basic user authentication capability.
  • 39. Step:2 - Process Specification
  • 40. Step 3: Domain Model Specification
  • 41. Step 4: Information Model Specification
  • 42. Step 5: Service Specifications
  • 43. Step 5: Service Specifications
  • 44. Step 6: IoT Level Specification
  • 45. Step 7: Functional View Specification
  • 46. Step 8: Operational View Specification
  • 47. Step 9: Device & Component Integration
  • 48. Step 10: Application Development • Auto • Controls the light appliance automatically based on the lighting conditions in the room • Light • When Auto mode is off, it is used for manually controlling the light appliance. • When Auto mode is on, it reflects the current state of the light appliance.
  • 49. Implementation: RESTful Web Services # Models – models.py from django.db import models class Mode(models.Model): name = models.CharField(max_length=50) class State(models.Model): name = models.CharField(max_length=50) # Serializers – serializers.py from myapp.models import Mode, State from rest_framework import serializers class ModeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Mode fields = ('url', 'name') class StateSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = State fields = ('url', 'name') REST services implemented with Django REST Framework 1. Map services to models. Model fields store the states (on/off, auto/manual) 2. Write Model serializers. Serializers allow complex data (such as model instances) to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types.
  • 50. Implementation: RESTful Web Services # Views – views.py from myapp.models import Mode, State from rest_framework import viewsets from myapp.serializers import ModeSerializer, StateSerializer class ModeViewSet(viewsets.ModelViewSet): queryset = Mode.objects.all() serializer_class = ModeSerializer class StateViewSet(viewsets.ModelViewSet): queryset = State.objects.all() serializer_class = StateSerializer 3. Write ViewSets for the Models which combine the logic for a set of related views in a single class. # Models – models.py from django.db import models class Mode(models.Model): name = models.CharField(max_length=50) class State(models.Model): name = models.CharField(max_length=50) 4. Write URL patterns for the services. Since ViewSets are used instead of views, we can automatically generate the URL conf by simply registering the viewsets with a router class. Routers automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. # URL Patterns – urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from rest_framework import routers from myapp import views admin.autodiscover() router = routers.DefaultRouter() router.register(r'mode', views.ModeViewSet) router.register(r'state', views.StateViewSet) urlpatterns = patterns('', url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), url(r'^home/', 'myapp.views.home'), )
  • 51. Implementation: RESTful Web Services Screenshot of browsable State REST API Screenshot of browsable Mode REST API
  • 52. Implementation: Controller Native Service #Controller service import RPi.GPIO as GPIO import time import sqlite3 as lite import sys con = lite.connect('database.sqlite') cur = con.cursor() GPIO.setmode(GPIO.BCM) threshold = 1000 LDR_PIN = 18 LIGHT_PIN = 25 def readldr(PIN): reading=0 GPIO.setup(PIN, GPIO.OUT) GPIO.output(PIN, GPIO.LOW) time.sleep(0.1) GPIO.setup(PIN, GPIO.IN) while (GPIO.input(PIN)==GPIO.LOW): reading=reading+1 return reading def switchOnLight(PIN): GPIO.setup(PIN, GPIO.OUT) GPIO.output(PIN, GPIO.HIGH) def switchOffLight(PIN): GPIO.setup(PIN, GPIO.OUT) GPIO.output(PIN, GPIO.LOW) def runAutoMode(): ldr_reading = readldr(LDR_PIN) if ldr_reading < threshold: switchOnLight(LIGHT_PIN) setCurrentState('on') else: switchOffLight(LIGHT_PIN) setCurrentState('off') def runManualMode(): state = getCurrentState() if state=='on': switchOnLight(LIGHT_PIN) setCurrentState('on') elif state=='off': switchOffLight(LIGHT_PIN) setCurrentState('off') def getCurrentMode(): cur.execute('SELECT * FROM myapp_mode') data = cur.fetchone() #(1, u'auto') return data[1] def getCurrentState(): cur.execute('SELECT * FROM myapp_state') data = cur.fetchone() #(1, u'on') return data[1] def setCurrentState(val): query='UPDATE myapp_state set name="'+val+'"' cur.execute(query) while True: currentMode=getCurrentMode() if currentMode=='auto': runAutoMode() elif currentMode=='manual': runManualMode() time.sleep(5) Native service deployed locally 1. Implement the native service in Python and run on the device
  • 53. Implementation: Application # Views – views.py def home(request): out=‘’ if 'on' in request.POST: values = {"name": "on"} r=requests.put('http://127.0.0.1:8000/state/1/', data=values, auth=(‘username', ‘password')) result=r.text output = json.loads(result) out=output['name'] if 'off' in request.POST: values = {"name": "off"} r=requests.put('http://127.0.0.1:8000/state/1/', data=values, auth=(‘username', ‘password')) result=r.text output = json.loads(result) out=output['name'] if 'auto' in request.POST: values = {"name": "auto"} r=requests.put('http://127.0.0.1:8000/mode/1/', data=values, auth=(‘username', ‘password')) result=r.text output = json.loads(result) out=output['name'] if 'manual' in request.POST: values = {"name": "manual"} r=requests.put('http://127.0.0.1:8000/mode/1/', data=values, auth=(‘username', ‘password')) result=r.text output = json.loads(result) out=output['name'] r=requests.get('http://127.0.0.1:8000/mode/1/', auth=(‘username', ‘password')) result=r.text output = json.loads(result) currentmode=output['name'] r=requests.get('http://127.0.0.1:8000/state/1/', auth=(‘username', ‘password')) result=r.text output = json.loads(result) currentstate=output['name'] return render_to_response('lights.html',{'r':out, 'currentmode':currentmode, 'currentstate':currentstate}, context_instance=RequestContext(request)) 1. Implement Django Application View
  • 54. Implementation: Application <div class="app-content-inner"> <fieldset> <div class="field clearfix"> <label class="input-label icon-lamp" for="lamp-state">Auto</label> <input id="lamp-state" class="input js-lamp-state hidden" type="checkbox"> {% if currentmode == 'auto' %} <div class="js-lamp-state-toggle ui-toggle " data-toggle=".js-lamp-state"> {% else %} <div class="js-lamp-state-toggle ui-toggle js-toggle-off" data-toggle=".js-lamp-state"> {% endif %} <span class="ui-toggle-slide clearfix"> <form id="my_form11" action="" method="post">{% csrf_token %} <input name="auto" value="auto" type="hidden" /> <a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-off">OFF</strong></a> </form> <strong class="ui-toggle-handle brushed-metal"></strong> <form id="my_form13" action="" method="post">{% csrf_token %} <input name="manual" value="manual" type="hidden" /> <a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-on">ON</strong></a> </form></span> </div></div> <div class="field clearfix"> <label class="input-label icon-lamp" for="tv-state">Light</label> <input id="tv-state" class="input js-tv-state hidden" type="checkbox"> {% if currentstate == 'on' %} <div class="js-tv-state-toggle ui-toggle " data-toggle=".js-tv-state"> {% else %} <div class="js-tv-state-toggle ui-toggle js-toggle-off" data-toggle=".js-tv-state"> {% endif %} {% if currentmode == 'manual' %} <span class="ui-toggle-slide clearfix"> <form id="my_form2" action="" method="post">{% csrf_token %} <input name="on" value="on" type="hidden" /> <a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-off">OFF</strong></a> </form> <strong class="ui-toggle-handle brushed-metal"></strong> <form id="my_form3" action="" method="post">{% csrf_token %} <input name="off" value="off" type="hidden" /> <a href="#" onclick="$(this).closest('form').submit()"><strong class="ui-toggle-on">ON</strong></a> </form> </span> {% endif %} {% if currentmode == 'auto' %} {% if currentstate == 'on' %} <strong class="ui-toggle-on">&nbsp;&nbsp;&nbsp;&nbsp;ON</strong> {% else %} <strong class="ui-toggle-on">&nbsp;&nbsp;&nbsp;&nbsp;OFF</strong> {% endif %}{% endif %} </div> </div> </fieldset></div></div></div> 2. Implement Django Application Template
  • 55. Finally - Integrate the System Django Application REST services implemented with Django-REST framework Native service implemented in Python SQLite Database Raspberry Pi device to which sensors and actuators are connected OS running on Raspberry Pi • Setup the device • Deploy and run the REST and Native services • Deploy and run the Application • Setup the database
  • 56. Chapter 7 IoT Physical Devices & Endpoints Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 57. Outline • Basic building blocks of an IoT Device • Exemplary Device: Raspberry Pi • Raspberry Pi interfaces • Programming Raspberry Pi with Python • Other IoT devices Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 58. What is an IoT Device • A "Thing" in Internet of Things (IoT) can be any object that has a unique identifier and which can send/receive data (including user data) over a network (e.g., smart phone, smart TV, computer, refrigerator, car, etc. ). • IoT devices are connected to the Internet and send information about themselves or about their surroundings (e.g. information sensed by the connected sensors) over a network (to other devices or servers/storage) or allow actuation upon the physical entities/environment around them remotely. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 59. IoT Device Examples • A home automation device that allows remotely monitoring the status of appliances and controlling the appliances. • An industrial machine which sends information abouts its operation and health monitoring data to a server. • A car which sends information about its location to a cloud-based service. • A wireless-enabled wearable device that measures data about a person such as the number of steps walked and sends the data to a cloud-based service. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 60. Basic building blocks of an IoT Device • Sensing • Sensors can be either on-board the IoT device or attached to the device. • Actuation • IoT devices can have various types of actuators attached that allow taking • actions upon the physical entities in the vicinity of the device. • Communication • Communication modules are responsible for sending collected data to other devices or cloud-based servers/storage and receiving data from other devices and commands from remote applications. • Analysis & Processing • Analysis and processing modules are responsible for making sense of the collected data. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 61. Block diagram of an IoT Device Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 62. Exemplary Device: Raspberry Pi • Raspberry Pi is a low-cost mini-computer with the physical size of a credit card. • Raspberry Pi runs various flavors of Linux and can perform almost all tasks that a normal desktop computer can do. • Raspberry Pi also allows interfacing sensors and actuators through the general purpose I/O pins. • Since Raspberry Pi runs Linux operating system, it supports Python "out of the box". Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 63. Exemplary Device: Raspberry Pi • Raspberry Pi is a low-cost mini-computer with the physical size of a credit card. • Raspberry Pi runs various flavors of Linux and can perform almost all tasks that a normal desktop computer can do. • Raspberry Pi also allows interfacing sensors and actuators through the general purpose I/O pins. • Since Raspberry Pi runs Linux operating system, it supports Python "out of the box". Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 64. Raspberry Pi Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 65. Linux on Raspberry Pi • Raspbian • Raspbian Linux is a Debian Wheezy port optimized for Raspberry Pi. • Arch • Arch is an Arch Linux port for AMD devices. • Pidora • Pidora Linux is a Fedora Linux optimized for Raspberry Pi. • RaspBMC • RaspBMC is an XBMC media-center distribution for Raspberry Pi. • OpenELEC • OpenELEC is a fast and user-friendly XBMC media-center distribution. • RISC OS • RISC OS is a very fast and compact operating system. Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 66. Raspberry Pi GPIO Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 67. Raspberry Pi Interfaces • Serial • The serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins for communication with serial peripherals. • SPI • Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for communicating with one or more peripheral devices. • I2C • The I2C interface pins on Raspberry Pi allow you to connect hardware modules. I2C interface allows synchronous data transfer with just two pins - SDA (data line) and SCL (clock line). Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com
  • 68. Raspberry Pi Example: Interfacing LED and switch with Raspberry Pi Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com from time import sleep import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) #Switch Pin GPIO.setup(25, GPIO.IN) #LED Pin GPIO.setup(18, GPIO.OUT) state=false def toggleLED(pin): state = not state GPIO.output(pin, state) while True: try: if (GPIO.input(25) == True): toggleLED(pin) sleep(.01) except KeyboardInterrupt: exit()
  • 69. Other Devices Bahga & Madisetti, © 2015 Book website: http://www.internet-of-things-book.com • pcDuino • BeagleBone Black • Cubieboard