IOT
IOT
UNIT-1(CO1)
Introduction to Internet of Things
IOT definition
The Internet of Things is a global network of computers, sensors, and actuators connected
through Internet protocols.
almost all every area, every device, every sensor, every software are connected to
each other and those devices we can able to access remotely through a smart phone or
through a computer is called IoT.
• And are seamlessly integrated into the information network, often communicate data
associated with users and their environments.
1)Smart device: Any mechanical or electronic device that can take intelligent decisions on its
own.
2)Sensor: A small chip that senses the surrounding activities. A sensor detects(senses) changes
in the ambient conditions or in the state of another device or a system and forwards or processes
this information in a certain manner. sensors are electronic devices that senses the physical
environments.
Sensor types:
Light
Temp
Flow
Position
Speed
voltage
humidity
Characteristics of IoT:
• Dynamic & Self-Adapting
• Self-Configuring
• Unique Identity
Dynamic & Self-Adopting: may have the capability to dynamically adopt with changing
contexts and take actions based on their operating conditions, user’s context or sensed
environment. Ex: surveillance system comprising number of cameras.
• 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.
• Audio/video interfaces
An IoT device can collect various types of data from onboard or attached sensors such as
temperature, humidity, light intensity.
The device can be connected to actuators that allow them to interact with other physical
entities (including non IoT device and system) in the vicinity of the device.
IoT devices can be varied types, sensor data generated by a soil moisture gathering device
can in a garden, when processed determining optimum watering schedule.
Fig:Generic block diagram of an IoT Device
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
Fig:IoT Protocols
Link Layer protocols: determine how the data is physically sent over the network’s
physical layer or medium. The scope of the link layer is the local connection to which host is
attached.
• Link layer determines how the packets are coded and signaled by hardware device over r
medium to which host is attached.
802.3 Ethernet: Is a collection of wired ethernet standards for the link layer, standards
provide data rates from 10Mb/s to 40Gb/s and higher.
2G-digital communications.
3G-multimedia services.
Application Layer—protocols define how the applications interface with the lower layer
protocols to send the data over network.
The Constrained Application Protocol (CoAP) is a specialized web transfer protocol for
use with constrained nodes and constrained (e.g., low-power, lossy) networks. The nodes often
have 8-bit microcontrollers with small amounts of ROM and RAM, while constrained networks
such as 6LoWPAN often have high packet error rates and a typical throughput of 10s of kbit/s.
The protocol is designed for machine-to-machine (M2M) applications such as smart energy and
building automation.
Web Socket—Allows full duplex communication over a single socket connection for
sending messages between client and server. Websocket is based on TCP and allows
streams of messages to be sent back and forth between the client and server while
keeping TCP connection open.
The WebSocket Protocol enables two-way communication between a client running untrusted
code in a controlled environment to a remote host that has opted-in to communications from that
code. The security model used for this is the origin-based security model commonly used by
web browsers. The protocol consists of an opening handshake followed by basic message
framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-
based applications that need two-way communication with servers that does not rely on opening
multiple HTTP connections (e.g., using XMLHttpRequest or <iframe>s and long polling).
• An IoT system comprises of a number of functional blocks that provide the system the
capabilities for identification, sensing, actuation, communication, and management .
Device: An IoT system comprises of devices that provide sensing, actuation, monitoring
and control functions.
Communication: The communication block handles the communication for the Iot
system. the various protocols used for communication by Iot Systems.
Services: An IoT System uses various types of IoT services such as services for device
monitoring, device control services, data publishing services and services for device
discovery.
Security: Security functional block secures the IoT system and by providing functions
such as authentication, authorization, message and content integrity, and data security.
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 or analyze the processed data.
• 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.
Fig: Request-Response communication model
• 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.
• When the broker receives data for a topic from the publisher, it sends the data to all the
subscribed 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 at which the consumers pull data.
Fig:Push-Pull communication model
• 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.
REST (Representational State Transfer) is a concept, not a protocol. But it is the basis of the most
widely used form of API today. RESTful APIs are widely used in the modern web, and data
transfer usually takes place using JSON or XML over HTTP.REST is a stateless concept — e.g.
that the client will connect and consumethe API on demand, passing any data which is relevant to
the request at time of use. It does not maintain a constantly open connection so it is very scalable.
REST APIs typically use methods of the HTTP specification to perform different actions.
For example — POST, GET, PUT, DELETE can be logically mapped to SQL CREATE, SELECT
(READ), UPDATE and DELETE functions. This is known as CRUD and it means that
everything you might want to do to a piece of data stored on a remote server can be done
predictably through a REST API. Requests originate from the client, and the common HTTP
verbs include GET, POST, PUT, DELETE but there are several others. They correspond to
expected operations, retrieving data, submitting data, updating data, and deleting data.
As it uses HTTP, any device which can connect to the web and request a web page can use
a REST API. REST is a good model for IoT because each device can easily make its state
information available, and can standardize on a way to create, read, update, and delete that data.
Developers can quickly build (or leverage from DreamFactory) a REST model for many IoT
devices. You can then, for example, easily get the state of the lightbulb: it is off. Then, send a
request to turn it on. Get the current temperature from the space heater: it is too hot. Send a lower
target temperature. This model intuitively matches the problem space.
REST addresses:
1. Performance
2. Scalability
3. Simplicity of interfaces
4. Modifiability
5. Visibility
6. Portability
7. Reliability
APIs allow developers to build context based applications that can interact with
the physical world instead of purely through UI (proximity and location aware). To
truly achieve IoT we need a REST API for every device. REST allows data to flow
over internet protocols and to delegate and manage authorization.
Web Socket API:
WebSocket APIs allow bidirectional, full duplex communication between clients and
servers.
• WebSocket APIs follow the exclusive pair communication model.
Web Socket allows communication among two devices. Web Sockets send data using a
continuous connection that is established between the client and the server. The user builds up a
Web Socket connection through a process known as the Web Socket handshake. The user then
sends a normal HTTP request to the server. An Upgrade header is incorporated into this request
informing the server that the user wishes to build up a Web Socket connection. When the
handshake is finished, it replaces the HTTP connection to the Web Socket connection which uses
the same hidden TCP/IP connection. This allows both parties to send data among each other.
Web Sockets require the browser side to run a java script library that can identify Web
Socket handshake, establish and maintain a Web Socket connection.
IOT Enabling Technologies:
Cloud Computing:is the on-demand delivery of compute power, database storage,
applications, and other IT resources through a cloud services platform via the internet with pay-
as-you-go pricing.
Cloud Computing Models Cloud Providers offer services that can be grouped into three
categories.
Bigdata is the term for collection of data sets so large and complex that it
becomes difficult to process using on-hand database system tools or traditional data
processing applications.
Volume:
We currently see the exponential growth in the data storage as the data is now more than
text data. We can find data in the format of videos, music’s and large images on our social media
channels. It is very common to have Terabytes and Peta-bytes of the storage system for
enterprises. As the database grows the applications and architecture built to support the data
needs to be reevaluated quite often. Sometimes the same data is re-evaluated with multiple
angles and even though the original data is the same the new found intelligence
creates explosion of the data. The big volume indeed represents Big Data.
Velocity:
Velocity is another important characteristic of big data and the primary reason for
exponential growth of data. Velocity of data refers to how fast the data is generated and how
frequently it varies. Modern IT, industrial and other systems are generating data at increasingly
higher speeds.
Variety:
Variety refers to the forms of the data. Big data come in different forms such as
structured or unstructured data, including text data, image, audio, video and sensor data.
A wireless sensor network (WSN):
A Wireless Sensor Network is a self-configuring network of small sensor nodes
communicating among themselves using radio signals, and deployed in quantity to sense,
monitor and understand the physical world.
A wireless sensor network (WSN) in its simplest form can be defined as a network of
(possibly low-size and low-complex) devices denoted as nodes that can sense the environment
and communicate the information gathered from the monitored field through wireless links; the
data is forwarded, possibly via multiple hops relaying, to a sink that can use it locally, or is
connected to other networks (e.g., the Internet) through a gateway.
WSN are enabled by wireless communication protocols such as IEEE 802.15.4. ZigBee is
one of the most popular wireless technologies used by WSNs. ZigBee specifications are based on
IEE 802.15.4.ZigBee operates at 2.4 GHz frequency and offers data rates up to 250 KB/s and
range from 10 to 100 meters depending on the power output and environmental conditions.
ZigBee:
ZigBee is an open global standard built on the IEEE 802.15.4 MAC/PHY.
• ZigBee defines a network layer above the 802.15.4 layers to support advanced mesh routing
capabilities.
• The ZigBee specification is developed by a growing consortium of companies that make up the
ZigBee Alliance. The Alliance is made up of over 300 members, including semiconductor,
module, stack, and software developers.
WSNs Applications:
WSNs may consist of many different types of sensor. As a result, a wide range of
applications are possible.
• 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.
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.
IoT Level-1:
A level-1 IoT system has a single node/device that performs sensing and/or actuation, stores
data,
• Level-1 IoT systems are suitable for modeling lowcost and low-complexity solutions where the
data involved is not big and the analysis requirements are not computationally intensive.
IoT
Level-2:
•A level-2 IoT system has a single node that performs sensing and/or actuation and local
analysis.
• 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.
IoT
Level-3
• A level-3 IoT system has a single node. Data is stored and analyzed in the cloud and
application is cloudbased.
• Level-3 IoT systems are suitable for solutions where the data involved is big and the analysis
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 cloudbased observer nodes which can subscribe to and receive
• Level-4 IoT systems are suitable for solutions where multiple nodes are required, the data
• Coordinator node collects data from the end nodes and sends to the cloud.
• 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.
IoT Level-6
A level-6 IoT system has multiple independent end nodes that perform sensing and/or actuation
• The analytics component analyzes the data and stores the results in the cloud database.
• The centralized controller is aware of the status of all the end nodes and sends control
commands to the nodes.
I2C
Raghava M, PhD
Schematic Diagram
Internals
• I2C is a low speed two wire serial protocol to connect devices using
the I2C standard.
• Devices using the I2C standard have a master slave relationship.
• There can be more than one master, but each slave device requires a
unique address, obtained by the manufacturer from NXP, formerly
known as Philips Semiconductors.
• This means that we can talk to multiple devices on a single I2C
connection as each device is unique and discoverable by the user and
the computer using Linux commands such as i2cdetect.
• The Raspberry Pi has two I2C1 connections at 3 and 5 (SDA and SCL)
are for I2C1 (master) and
• I2C0- Physical pins 27 and 28 are I2C pins that enable the Pi to talk to
compatible HAT (Hardware Attached on Top) add on boards.
I2C BUS
I2C Interface
• I2C uses only two wires: SCL (serial clock) and SDA (serial data). Both need
to be pulled up with a resistor to +Vdd. There are also I2C level shifters
which can be used to connect to two I2C buses with different voltages.
I2C Addresses
• Basic I2C communication is using transfers of 8 bits or bytes. Each I2C slave
device has a 7-bit address that needs to be unique on the bus. Some
devices have fixed I2C address while others have few address lines which
determine lower bits of the I2C address. This makes it very easy to have all
I2C devices on the bus with unique I2C address. There are also devices
which have 10-bit address as allowed by the specification.
Protocol Structure
I2C Address
• 7-bit address represents bits 7 to 1 while bit 0 is used to signal
reading from or writing to the device. If bit 0 (in the address byte) is
set to 1 then the master device will read from the slave I2C device.
• Master device needs no address since it generates the clock (via SCL)
and addresses individual I2C slave devices.
Address Structure
I2C Protocol Structure
• THE CLOCK
• The clock signal synchronizes the output of data bits from the master to
the sampling of bits by the slave. One bit of data is transferred in each
clock cycle, so the speed of data transfer is determined by the frequency of
the clock signal. SPI communication is always initiated by the master since
the master configures and generates the clock signal.
• Any communication protocol where devices share a clock signal is known
as synchronous. SPI is a synchronous communication protocol. There are
also asynchronous methods that don’t use a clock signal. For example, in
UART communication, both sides are set to a pre-configured baud rate that
dictates the speed and timing of data transmission.
Transmission Internals
• Transmissions normally involve two shift registers of some given word-size,
such as eight bits, one in the master and one in the slave; they are
connected in a virtual ring topology.
• Data is usually shifted out with the most significant bit first.
• On the clock edge, both master and slave shift out a bit and output it on
the transmission line to the counterpart.
• On the next clock edge, at each receiver the bit is sampled from the
transmission line and set as a new least-significant bit of the shift register.
• After the register bits have been shifted out and in, the master and slave
have exchanged register values. If more data needs to be exchanged, the
shift registers are reloaded and the process repeats. Transmission may
continue for any number of clock cycles. When complete, the master stops
toggling the clock signal, and typically deselects the slave.
4 Pin mode
• MOSI AND MISO
• The master sends data to the slave bit by bit, in serial through the
MOSI line. The slave receives the data sent from the master at the
MOSI pin. Data sent from the master to the slave is usually sent with
the most significant bit first.
• The slave can also send data back to the master through the MISO
line in serial. The data sent from the slave back to the master is
usually sent with the least significant bit first.
SPI
• Devices communicating via SPI are in a master-slave relationship. The master is the controlling device
(usually a microcontroller), while the slave (usually a sensor, display, or memory chip) takes instruction
from the master. The simplest configuration of SPI is a single master, single slave system, but one master
can control more than one slave.
MOSI (Master Output/Slave Input) – Line for the master SCLK (Clock) – Line for the clock signal.
to send data to the slave.
MISO (Master Input/Slave Output) – Line for the slave to SS/CS (Slave Select/Chip Select) – Line for the master
send data to the master. to select which slave to send data to.
STEPS OF SPI DATA TRANSMISSION
• 1. The master outputs the clock signal:
• 4. If a response is needed, the slave returns data one bit at a time to the
master along the MISO line. The master reads the bits as they are received:
• SLAVE SELECT
• The master can choose which slave it wants to talk to by setting the slave’s CS/SS
line to a low voltage level. In the idle, non-transmitting state, the slave select line
is kept at a high voltage level. Multiple CS/SS pins may be available on the master,
which allows for multiple slaves to be wired in parallel. If only one CS/SS pin is
present, multiple slaves can be wired to the master by daisy-chaining.
• MULTIPLE SLAVES
• SPI can be set up to operate with a single master and a single slave, and it can be
set up with multiple slaves controlled by a single master. There are two ways to
connect multiple slaves to the master. If the master has multiple slave select pins,
the slaves can be wired in parallel like this:
•
Multiple slaves
• ADVANTAGES
• No start and stop bits, so the data can be streamed continuously
without interruption
• No complicated slave addressing system like I2C
• Higher data transfer rate than I2C (almost twice as fast)
• Separate MISO and MOSI lines, so data can be sent and received at
the same time
• DISADVANTAGES
• Uses four wires (I2C and UARTs use two)
• No acknowledgement that the data has been successfully received
(I2C has this)
• No form of error checking like the parity bit in UART
• Only allows for a single master
GPIO Programming
• RPi.GPIO
• GPIOZERO
Polarity- longer leg- +ve
Shorter one- -ve
Python Program- LED
GOPIZERO
Turn an LED on and off
repeatedly:
button = Button(2)
while True:
if button.is_pressed:
print("Button is pressed")
else:
print("Button is not pressed")
Turn on an LED when a Button is pressed:
from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(2)
button.when_pressed = led.on
button.when_released = led.off
pause()
from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(2)
led.source = button
pause()
Camera Modules
Video Recording
END
IoT AND M2M
UNIT -III
2. Web APIs are designed to represent widely used resources like HTML
pages and are accessed using a simple HTTP protocol. Any web URL
activates a web API. Web APIs are often called REST (representational
state transfer) or RESTful because the publisher of REST interfaces
doesn't save any data internally between requests. As such, requests
from many users can be intermingled as they would be on theinternet.
3. Program APIs are based on remote procedure call (RPC) technology that
makes a remote program component appear to be local to the rest of the
software. Service oriented architecture (SOA) APIs, such as Microsoft's
WS-series of APIs, are program APIs.
IoT / Cloud Convergence
• Infrastructure-as-a-Service (IaaS) IoT/Clouds: These services provide the
means for accessing sensors and actuator in the cloud. The associated
business model involves the IoT/Cloud provide to act either as data or
sensor provider. IaaS services for IoT provide access control to resources
as a prerequisite for the offering of related pay-as-you-go services.
• Platform-as-a-Service (PaaS) IoT/Clouds: This is the most widespread
model for IoT/cloud services, given that it is the model provided by all
public IoT/cloud infrastructures outlined above
• Software-as-a-Service (SaaS) IoT/Clouds: SaaS IoT services are the ones
enabling their uses to access complete IoT-based software applications
through the cloud, on-demand and in a pay-as-you-go fashion.
WAMP Protocol
Unit 5
IoT Physical Servers, Cloud
Offerings
Content
• Introduction to Cloud Storage Models
• Communication API
• WAMP: AutoBahn for IoT
• Xively Cloud for IoT
• Python Web Application Framework:
Djanjo
• Amazon Web Services for IoT
• SkyNet IoT Messaging Platform.
Introduction to Cloud StorageModels
• Popular Models are
• Amazon Web Service
(AWS)
• Xively Cloud (PAAS)
Communication API
• Cloud Models are relied on Communication API
• Communication API facilitate data transfer, control
information transfer from application to cloud, one service
to another
• It also exist in the form of Communication Protocols
• It supports RPC, PUBSUB and WAMP
• Eg. Popular API is RESTful API (communication in cloud
model)
• Django web framework is used to implement
Communication API
WAMP: AutoBahn forIoT
• WAMP : Web Application Messaging Protocol
• Mainly used in cloud storage model for IoT & other messaging services
• WAMP is a routed protocol, with all components connecting to a WAMP
Router,
where the WAMP Router performs message routing between the component
• It is protocol for Web Socket (PUBSUB based protocol) : uses RPC
Messaging Pattern
• Some Important Key Terminologies
• Transport
• Session
• Clients (Publisher & Subscriber)
• Router
• Broker
• Dealer
• Application Code
WAMP for IoT
reservation = conn.run_instances(image_id=AMI_ID,
key_name=EC2_KEY_HANDLE,
instance_type=INSTANCE_TYPE,
Book website: http://www.internet-of-things-book.com security_groups = [ Bahga & Madisetti, © 2015
Amazon AutoScaling – Python
Example #Python program for creating an AutoScaling group (code
• AutoScaling Service excerpt)
import boto.ec2.autoscale
• A connection to the AutoScaling service is first :
established by calling the print "Connecting to Autoscaling Service"
boto.ec2.autoscale.connect_to_region function. conn =
boto.ec2.autoscale.connect_to_region(REGION,
aws_access_key_id=ACCESS_KEY,
• Launch Configuration aws_secret_access_key=SECRET_KEY)
• After connecting to the AutoScaling service, a new
launch configuration is created by calling print "Creating launch configuration"
conn.create_launch_con f iguration. Launch
configuration contains instructions on how to launch lc = LaunchConfiguration(name='My-Launch-Config-2',
new instances including the AMI-ID, instance type, image_id=AMI_ID,
security groups, etc. key_name=EC2_KEY_HAND
= 1 is defined. cooldown=180)
• Similarly, a scale down policy with adjustment
scale_down_policy =
type ChangeInCapacity and scaling_ad
justment = −1 is defined. ScalingPolicy(name='scale_down',
adjustment_type='ChangeInCapacity'
scaling_adjustment=-
,1,
cooldown=180) as_name='My-Group',
conn.create_scaling_policy(scale_up_policy
)
conn.create_scaling_policy(scale_down_pol
icy)
Book website: http://www.internet-of-things-book.com Bahga & Madisetti, © 2015
Amazon AutoScaling – Python
Example #Connecting to CloudWatch
• CloudWatch cloudwatch = boto.ec2.cloudwatch.connect_to_region(REGION,
aws_access_key_id=ACCESS_KE
• With the scaling policies defined, the next step is
Alarms Y,
aws_secret_access_key=SECRET
to create Amazon CloudWatch alarms that _KEY)
trigger these policies. alarm_dimensions = {"AutoScalingGroupName": 'My-Group'}
• The scale up alarm is defined using the #Creating scale-up alarm
CPUUtilization metric with the Average statistic scale_up_alarm = MetricAlarm(
and threshold greater 70% for a period of 60 sec. name='scale_up_on_cpu',
namespace='AWS/EC2',
The scale up policy created previously is metric='CPUUtilization', statistic='Average',
associated with this alarm. This alarm is triggered comparison='>', threshold='70',
period='60', evaluation_periods=2,
when the average CPU utilization of the instances alarm_actions=[scale_up_policy.policy_a
in the group becomes greater than 70% for more rn], dimensions=alarm_dimensions)
than 60 seconds. cloudwatch.create_alarm(scale_up_alarm)
conn =
boto.connect_s3(aws_access_key_id='<enter>',
aws_secret_access_key='<enter>')
def percent_cb(complete,
total): print ('.')
Book website: http://www.internet-of-things-book.com #Creating an RDS instance Bahga & Madisetti, © 2015
Amazon DynamoDB –Non Relational
Databases Python Example
# Python program for creating a DynamoDB table (excerpt)
• In this example, a connection to the import boto.dynamodb
• Model
• The model acts as a definition of some stored data and handles the interactions with the database. In a web
application, the data can be stored in a relational database, non-relational database, an XML file, etc. A Django
model is a Python class that outlines the variables and methods for a particular type of data.
• Template
• In a typical Django web application, the template is simply an HTML page with a few extra placeholders.
Django’s template language can be used to create various forms of text files (XML, email, CSS,
Javascript, CSV, etc.).
• View
• The view ties the model to the template. The view is where you write the code that actually generates the
web pages. View determines what data is to be displayed, retrieves the data from the database and passes
the data to the template.
def question_list(request):
questions =
Question.objects.all()
return
render_to_response(‘question_list.html’, {
‘questions’:questions})
Quick CRUD Operations with GenericViews
• ListView
• UpdateView
• CreateView
• If Model is specified, automagically creates a matching
ModelForm
• Form will save the Model if data passes validation
• Override form_valid() method to provide custom logic (i.e
sending email or setting additional fields)
Sample – As Class Based View
from .models import Question
from django.views.generic import
ListView
class
QuestionList(ListView):
model = Question
context_object_name = ‘questions’
Django Templates
• Very simple syntax:
variables =
{{variable_name}}
template tags = {%tag%}
• Flexible – can be used to render html, text, csv, email, you
name it!
• Dot notation – template engine attempts to resolve by
looking for matching attributes, hashes and methods
Question List Template
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>List of Questions</title>
</head>
<body>
{%if questions%}
<ul>
{%for q in questions%}
<li>{{q.question_text}}</li>
{%endfor%}
</ul>
{%else%}
<p>No questions have been
defined</p>
{%endif%}
</body>
</html>
urls.py
• Defines routes to send urls to various views
• Can use regular expressions
• Extract parameters from a url and pass to the view as a
named parameter:
r(‘^question/(?P<question_id>\d+)/$’,’views.question_det
ail’)
• Extensible – urls.py can include additional url files from
apps: r(‘^question/’,include(question.urls))
Hooking up the QuestionList
from django.conf.urls import patterns, url,
include urlpatterns = patterns(‘’,
(r’^questions/$’,’views.QuestionList’)
)
OR:
from django.conf.urls import
patterns from views import
QuestionListView
urlpatterns = patterns(‘’,
(r’^questions/$’,’views.QuestionList.as_vie
w())
)
Forms in Django
• django.forms provides a class to build HTML forms and
validation. Example:
from django import forms
class EditQuestionForm(forms.Form):
question_text = forms.CharField(max_length = 200)
@method_decorator(login_requir
ed) def dispatch(self, *args,
**kwargs):
super(MyView,self).dispatch(*args, **kwargs)
Custom Auth Backend for theBubble
Sending Email
• django.core.mail includes functions and classes for handling
email
• Set EMAIL_HOST in settings.py to outgoing mailserver
• Import send_mail for simple mail:
send_mail(subject, message, from,
to_emails)
• Use django.template.render_to_string to format a message
using a template
• Use EmailMultiAlternatives to create a text message and
attach a html version as well.
Unit-5
Domain Specific IoTs
Applications
• Home
• Cities
• Environment
• Energy systems
• Retail
• Logistics
• Industry
• Agriculture
• Health and lifestyle
Home Automation
• Smart Lighting
• Smart Appliances
• Intrusion Detection
• Smoke/Gas Detectors
Smart Lighting
Helps in saving energy by adapting the lighting to the ambient conditions
and switching on/off or diming the light when needed.
Key enabling technologies for smart lighting include solid state lighting and
IP-enabled lights.
Smart lighting solutions for home achieve energy saving by sensing the
human movements and their environments and controlling the lights
accordingly.
Open Remote is an open source automation platform for smart home and
building that can control various appliances using mobile and web
applications.
• Smart parking makes the search for parking space easier and convenient
for driver.
• It can detect the number of empty parking slots and send the information
over the Internet to the smart parking applications which can be accessed
by the drivers using their smart phones, tablets, and in car navigation
systems.
• Sensors are used for each parking slot to detect whether the slot is empty
or not, and this information is aggregated by local controller and then sent
over the Internet to database.
Smart Lighting for Roads
It can help in saving energy
• Such information can help in making the roads safer and help
in reducing traffic jams
• In the system such as power grids, real time information is collected using
specialized electrical sensors called Phasor Measurement Units (PMU)
2. Smart Payments
NFC maybe used in combination with Bluetooth, where NFC initiates initial
pairing of devices to establish a Bluetooth connection while the actual
data transfer takes place over Bluetooth.
Smart Vending Machines
Smart vending machines connected to the Internet allow remote
monitoring of inventory levels, elastic pricing of products, promotions, and
contact-less payments using NFC.
For perishable items, the smart vending machines can reduce the price as
the expiry date nears.
Logistics
b) Fleet Tracking
c) Shipment Monitoring
IoT based systems backed by cloud can provide fast response to route
generation queries and scale up to serve a large transportation network
Fleet Tracking
Use GPS to track locations of vehicles in real-time.
The vehicle locations and routes data can be aggregated and analysed
for detecting Traffic congestions on routes, assignments and generation of
alternate routes and Supply chain optimization.
The analysis and interpretation of data can enable more effective routing
decisions in real time
• These diagnostic systems use on-board IoT devices for collecting data on
vehicle operations and status of various vehicle subsystems.
• The systems use IoT devices with soil moisture sensors to determine the
amount of moisture in the soil and release flow of water through the
irrigation pipes only when the moisture levels go below a predefined
threshold
• IoT systems plays an important role in green house control and help in
improving productivity.
b) Wearable Electronics
Health & Fitness Monitoring
• Wearable IoT devices that allow continuous monitoring of
physiological parameters can help in continuous heath and
fitness monitoring