Internet of Things
Internet of Things
UNIT - I
Introduction to Internet of Things -Introduction of IoT, Physical Design of IoT, Logical Design of
IoT, IoT enabled Technologies –, IoT Levels and Templates, Domain Specific IoTs
– Home, City, Environment, Energy, Retail, Logistics, Agriculture, Industry, health
and Lifestyle.
UNIT - II
IoT and M2M - Software defined networks, network function virtualization, difference between
SDN and NFV for IoT. Basics of IoT System Management with NETCOZF, YANG -
NETCONF, YANG, SNMP NETOPEER
UNIT - III
Introduction to Python - Language features of Python, Data types, data structures, Control of
flow, functions, modules, packaging, file handling, data/time operations, classes, Exception
handling. Python packages - JSON, XML, HTTP Lib, URL Lib, SMTP Lib.
UNIT - IV
IoT Physical Devices and Endpoints - Introduction to Raspberry PI - Interfaces (serial, SPI, I2C).
Programming – Python program with Raspberry PI with focus of interfacing external gadgets,
controlling output, reading input from pins.
UNIT - V
IoT Physical Servers and Cloud Offerings - Introduction to Cloud Storage models and
communication APIs. Web server – Web server for IoT, Cloud for IoT, Python web application
framework. Designing a REST ful web API.
TEXT BOOK:
1. Internet of Things - A Hands-on Approach, Arshdeep Bahga and Vijay Madisetti,
Universities Press, 2015, ISBN: 9788173719547
2. Getting Started with Raspberry Pi, Matt Richardson & Shawn Wallace, O'Reilly (SPD),
2014, ISBN: 9789350239759.
INTERNET OF THINGS
UNIT – I
INTRODUCTION TO INTERNET OF THINGS
Introduction:
The concept of a network of smart devices was discussed as early as 1982, with a
modified Coke machine at Carnegie Mellon University becoming the first internet-connected
appliance, able to report its inventory and whether newly loaded drinks were cold. Kevin Ashton
(born 1968) is a British technology pioneer who is known for inventing the term "the Internet of
Things" to describe a system where the Internet is connected to the physical world via ubiquitous
sensors. IoT is able to interact without human intervention. Some preliminary IoT applications
have been already developed in healthcare, transportation, and automotive industries. IoT
technologies are at their infant stages; however, many new developments have occurred in the
integration of objects with sensors in the Internet. The development of IoT involves many issues
such as infrastructure, communications, interfaces, protocols, and standards. The objective of this
paper is to give general concept of IoT, the architecture and layers in IoT, some basic terms
associated with it and the services provided. The below fig 1.1 give an example things connected
to internet.
The IOT concept was coined by a member of the Radio Frequency Identification
(RFID) development community in 1999, and it has recently become more relevant to the
practical world largely because of the growth of mobile devices, embedded and ubiquitous
communication, cloud computing and data analytics
1
INTERNET OF THINGS
Definition of IoT:
The Internet of Things (IoT) is the network of physical objects—devices, instruments,
vehicles, buildings and other items embedded with electronics, circuits , software, sensors and
network connectivity that enables these objects to collect and exchange data. The Internet of
Things allows objects to be sensed and controlled remotely across existing network
infrastructure, creating opportunities for more direct integration of the physical world into
computer-based systems, and resulting in improved efficiency and accuracy.
IoT refers to the interconnection via the internet of computing devices embedded in
everyday objects, enabled them to send and receive the data.
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 use intelligent interfaces, and are seamlessly integrated into
information network that communicate data with users and environments.
Characteristics of IoT :
1. Dynamic & Self-Adapting: IoT device and system may have the capability to dynamically
adapt with the changing contexts and take actions based on their operating conditions, user’s
context, or sensed environment. For example, consider a surveillance adpt their modes based on
the weather it is day or night, cameras could switch from lower resolution to higher resolution
modes when any motion is detected and alert nearby cameras to do the same.
2. Self-Configuring: IoT devices may have self-configuring capability, allowing a large number of
devices to work together to provide certain functionality (such as weather monitoring). These
devices have the ability configure themselves, setup the networking and fetch latest software
upgrades with minimal manual or user intervention.
3. Interoperable Communication Protocols: IoT devices may support a number of interoperable
communication protocols and can communicate with other devices and also with the
infrastructure.
4. Unique Identity: Each IoT device has a unique identity and a unique identifier (such as an IP
address). IoT systems may have intelligent interface which adapt based on the context, allow
communicating with user and the environmental contexts, IoT device interfaces allow users to
query the devices, monitor their status and control them remotely.
5. Integrated into Information Network: IoT devices are usually integrated into the information
network that allows them to communicate and exchange data with other devices and systems,
IoT dvices can be dynamically discovered in the network, by other devices and/or the network,
and have the capability to describe themselves to other devices or user applications.
2
INTERNET OF THINGS
Physical Design of
IoT Things in IoT
1. Refers to IoT devices which have unique identities that can perform sensing, actuating
and monitoring capabilities.
2. IoT devices can exchange data with other connected devices or collect data from other
devices and process the data either locally or send the data to centralized servers or cloud
– based application back-ends for processing the data.
The IoT devices are typically connected to the Internet via an IP (Internet Protocol) network.
However, devices such as Bluetooth and RFID allow IoT devices to connect locally. In these
cases, there’s a difference in power, range, and memory used. Connection through IP networks
3
INTERNET OF THINGS
are comparatively complex, requires increased memory and power from the IoT devices while
the range is not a problem. On the other hand, non-IP networks demand comparatively less
power and memory but have a range limitation.
As far as the IoT communication protocols or technologies are concerned, a mix of both IP and
non-IP networks can be considered depending on usage.
and a link protocol is a suite of methods and standards that operate only between adjacent
network nodes of a network segment.
4 802.3.ae Fiber…..10Gbits/s
WiFi Standard
1 2G GSM-CDMA
5
INTERNET OF THINGS
The above Table 1.1 shows the different method of link layer with different
standards. For Ethernet method Data Rates are provided from 10Gbit/s to 40Gb/s and
higher. Collection of Wireless LAN Data Rates from 1Mb/s to 6.75 Gb/s. Collection of
Wireless Broadband standards Data Rates from 1.5Mb/s to 1 Gb/s. LR-WPAN:
Collection of standards for low-rate wireless personal area networks, Basis for high level
communication protocols such as Zigbee, Data Rates from 40Kb/s to 250Kb/s. 2G/3G/4G
–Mobile Communication: Data Rates from 9.6Kb/s (for 2G) to up to 100Mb/s (for 4G).
2. Network/Internet Layer:
The internet layer is a group of internetworking methods, protocols, and specifications in
the Internet protocol suite that are used to transport network packets from the originating host
across network boundaries; if necessary, to the destination host specified by an IP address. The
internet layer derives its name from its function facilitating internetworking, which is the concept
of connecting multiple networks with each other through gateways.
• Responsible for sending of IP datagrams from source to destination network
• Performs the host addressing and packet routing
• Host identification is done using hierarchical IP addressing schemes such as IPV4 or
IPV6
IPV4
Used to identify the devices on a network using hierarchical addressing scheme
Uses 32-bit address scheme
IPV6
Uses 128-bit address scheme
6LoWPAN (IPV6 over Low power Wireless Personal Area Network)
Used for devices with limited processing capacity, Operates in 2.4 Ghz , Data Rates of
250Kb/s.
3. Transport Layer:
In computer networking, the transport layer is a conceptual division of methods in the
layered architecture of protocols in the network stack in the Internet protocol suite and the OSI
model. The protocols of this layer provide host-to-host communication services for applications.
It provides services such as connection-oriented communication, reliability, flow control, and
multiplexing.
6
INTERNET OF THINGS
The best-known transport protocol of the Internet protocol suite is the Transmission
Control Protocol (TCP). It is used for connection-oriented transmissions, whereas the
connectionless User Datagram Protocol (UDP) is used for simpler messaging transmissions.
4. Application Layer:
An application layer is an abstraction layer that specifies the shared communications
protocols and interface methods used by hosts in a communications network. The application
layer abstraction is used in both of the standard models of computer networking: the Internet
Protocol Suite (TCP/IP) and the OSI model. Although both models use the same term for their
respective highest level layer, the detailed definitions and purposes are different.
Hyper Transfer Protocol:
• Forms foundation of World Wide Web(WWW)
• Includes commands such as GET,PUT, POST, HEAD, OPTIONS, TRACE..etc
• Follows a request-response model
• Uses Universal Resource Identifiers(URIs) to identify HTTP resources.
Constrained Application Protocol (CoAP):
• Used for Machine to machine (M2M) applications meant for constrained devices and
n/w’s
• Web transfer protocol for IoT and uses request-response model
7
INTERNET OF THINGS
🞂 An IoT system comprises a number of functional blocks that provide the system
the capabilities for identification, sensing, actuation, communication and management.
🞂 Fig 1.4 shows the functional block diagram of IoT. Below are the individual
block explanation.
1. Device : Devices such as sensing, actuation, monitoring and control functions.
2. Communication : IoT Protocols
3. Services like device monitoring, device control services, data publishing services and
device discovery
4. Management : Functions to govern the system
5. Security : Functions as authentication, authorization, message and content integrity, and
data security Applications
8
INTERNET OF THINGS
9
INTERNET OF THINGS
10
INTERNET OF THINGS
11
INTERNET OF THINGS
12
INTERNET OF THINGS
13
INTERNET OF THINGS
14
INTERNET OF THINGS
15
INTERNET OF THINGS
16
INTERNET OF THINGS
4. Embedded Systems:
17
INTERNET OF THINGS
Communication Protocols:
Communication protocols from the backbone of IoT systems and enabled network
connectivity and coupling to applications. Communication protocols allow devices to
exchange data over the network. In internet protocol session we discussed about various
Link, Network, Transport and Application Layer protocols.
IoT Levels and Deployment Templates:
An IoT system comprises the following components:
• Device: An IoT device allows identification, remote sensing, actuating and remote
monitoring capabilities.
• Resource: Resources are software components on the IoT device for accessing,
processing and storing sensor information, or for 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 implemented using HTTP and REST
principles (REST service) or using the WebSocket protocol (WebSocket service).
• Analysis Component: This is responsible for analyzing the IoT data and generating
results in a form that is 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 the processed data.
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.
18
INTERNET OF THINGS
• Level-1 IoT systems are suitable for modelling low-cost and low-complexity solutions
where the data involved is not big and the analysis requirements are not computationally
intensive.
19
INTERNET OF THINGS
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 the 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.
Example-Smart Irrigation:
20
INTERNET OF THINGS
IoT Level-4:
• A level-4 IoT system has multiple nodes that perform local analysis. Data is stored in the
cloud and the 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.
21
INTERNET OF THINGS
Example-Noise Monitoring:
IoT Level-5:
• A level-5 IoT system has multiple end nodes and one coordinator node.
22
INTERNET OF THINGS
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 the 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.
23
INTERNET OF THINGS
1) Home Automation:
a) Smart Lighting: helps in saving energy by adapting the lighting to the ambient conditions and
switching on/off or diming the light when needed.
b) Smart Appliances: make the management easier and also provide status information to the
users remotely.
c) Intrusion Detection: use security cameras and sensors (PIR sensors and door sensors) to detect
intrusion and raise alerts. Alerts can be in the form of SMS or email sent to the user.
d) Smoke/Gas Detectors: Smoke detectors are installed in homes and buildings to detect smoke
that is typically an early sign of fire. Alerts raised by smoke detectors can be in the form of
signals to a fire alarm system. Gas detectors can detect the presence of harmful gases such as
CO, LPG etc.,
24
INTERNET OF THINGS
2) Cities:
a) Smart Parking: make the search for parking space easier and convenient for drivers. Smart
parking are powered by IoT systems that detect the no. of empty parking slots and send
information over internet to smart application back ends.
b) Smart Lighting: for roads, parks and buildings can help in saving energy.
c) Smart Roads: Equipped with sensors can provide information on driving condition, travel
time estimating and alert in case of poor driving conditions, traffic condition and accidents.
d) Structural Health Monitoring: uses a network of sensors to monitor the vibration levels in the
structures such as bridges and buildings.
e) Surveillance: The video feeds from surveillance cameras can be aggregated in cloud based
scalable storage solution.
f) Emergency Response: IoT systems for fire detection, gas and water leakage detection can help
in generating alerts and minimizing their effects on the critical infrastructures.
3) Environment:
a) Weather Monitoring: Systems collect data from a no. of sensors attached and send the data to
cloud based applications and storage back ends. The data collected in cloud can then be analyzed
and visualized by cloud based applications.
b) Air Pollution Monitoring: System can monitor emission of harmful gases (CO2, CO, NO,
NO2 etc.,) by factories and automobiles using gaseous and meteorological sensors. The collected
data can be analyzed to make informed decisions on pollutions control approaches.
c) Noise Pollution Monitoring: Due to growing urban development, noise levels in cities have
increased and even become alarmingly high in some cities. IoT based noise pollution monitoring
systems use a no. of noise monitoring systems that are deployed at different places in a city. The
data on noise levels from the station is collected on servers or in the cloud. The collected data is
then aggregated to generate noise maps.
d) Forest Fire Detection: Forest fire can cause damage to natural resources, property and human
life. Early detection of forest fire can help in minimizing damage.
e) River Flood Detection: River floods can cause damage to natural and human resources and
human life. Early warnings of floods can be given by monitoring the water level and flow rate.
IoT based river flood monitoring system uses a no. of sensor nodes that monitor the water level
and flow ratesensors.
4) Energy:
a) Smart Grids: is a data communication network integrated with the electrical grids that collects
and analyze data captured in near-real-time about power transmission, distribution and
consumption. Smart grid technology provides predictive information and recommendations to
utilities, their suppliers, and their customers on how best to manage power. By using IoT based
25
INTERNET OF THINGS
sensing and measurement technologies, the health of equipment and integrity of the grid can be
evaluated.
b) Renewable Energy Systems: IoT based systems integrated with the transformers at the point
of interconnection measure the electrical variables and how much power is fed into the grid. For
wind energy systems, closed-loop controls can be used to regulate the voltage at point of
interconnection which coordinate wind turbine outputs and provides power support.
c) Prognostics: In systems such as power grids, real-time information is collected using
specialized electrical sensors called Phasor Measurment Units (PMUs) at the substations. The
information received from PMUs must be monitored in real-time for estimating the state of the
system and for predicting failures.
5) Retail:
a) Inventory Management: IoT systems enable remote monitoring of inventory using data
collected by RFID readers.
b) Smart Payments: Solutions such as contact-less payments powered by technologies such as
Near Field Communication (NFC) and Bluetooth.
c) Smart Vending Machines: Sensors in a smart vending machines monitors its operations and
send the data to cloud which can be used for predictive maintenance.
6) Logistics:
a) Route generation & scheduling: IoT based system backed by cloud can provide first response
to the route generation queries and can be scaled up to serve a large transportation network.
b) Fleet Tracking: Use GPS to track locations of vehicles in real-time.
c) Shipment Monitoring: IoT based shipment monitoring systems use sensors such as temp,
humidity, to monitor the conditions and send data to cloud, where it can be analyzed to detect
food spoilage.
d) Remote Vehicle Diagnostics: Systems use on-board IoT devices for collecting data on Vehicle
operations (speed, RPM etc.,) and status of various vehicle subsystems.
7) Agriculture:
a) Smart Irrigation: to determine moisture amount in soil.
b) Green House Control: to improve productivity.
8) Industry:
a) Machine diagnosis and prognosis
b) Indoor Air Quality Monitoring
26
INTERNET OF THINGS
27
INTERNET OF THINGS
UNIT - II
INTRODUCTION TO M2M:
Machine-to-Machine (M2M) refers to networking of machines (or devices) for the purpose of
remote monitoring and control and data exchange.
Term which is often synonymous with IoT is Machine-to-Machine (M2M).
IoT and M2M are often used interchangeably.
Fig. Shows the end-to-end architecture of M2M systems comprises of M2M area networks,
communication networks and application fomain.
An M2M area network comprises of machines ( or M2M nodes) which have embedded
network modules for sensing, actuation and communicating various communication
protocols can be used for M2M LAN such as ZigBee, Bluetooth, M-bus, Wireless M-Bus
etc., These protocols provide connectivity between M2M nodes within an M2M area
network.
28
INTERNET OF THINGS
The communication network provides connectivity to remote M2M area networks. The
communication network provides connectivity to remote M2M area network. The
communication network can use either wired or wireless network (IP based). While the
M2M are networks use either properitorary or non-IP based communication protocols,
the communication network uses IP-based network. Since non-IP based protocols are
used within M2M area network, the M2M nodes within one network cannot
communicate with nodes in an external network.
To enable the communication between remote M2M are network, M2M gateways are
used.
29
INTERNET OF THINGS
5) Applications
M2M data is collected in point solutions and can be accessed by on-premises applications
such as diagnosis applications, service management applications, and on- premisis
enterprise applications.
IoT data is collected in the cloud and can be accessed by cloud applications such as
analytics applications, enterprise applications, remote diagnosis and management
applications, etc.
30
INTERNET OF THINGS
• The underlying infrastructure in SDN uses simple packet forwarding hardware as opposed to
specialized hardware in conventional networks.
SDN Architectur e
Key elements of SDN:
1) Centralized Network Controller
With decoupled control and data planes and centralized network controller, the network
administrators can rapidly configure the network.
2) Programmable Open APIs
31
INTERNET OF THINGS
SDN architecture supports programmable open APIs for interface between the SDN application
and control layers (Northbound interface).
32
INTERNET OF THINGS
33
INTERNET OF THINGS
Limitations of SNMP:
🞂 SNMP is stateless in nature and each SNMP request contains all the information
to process the request. The application needs to be intelligent to manage the
device.
🞂 SNMP is a connectionless protocol which uses UDP as the transport protocol, making
it unreliable as there was no support for acknowledgement of requests.
🞂 MIBs often lack writable objects without which device configuration is not possible
34
INTERNET OF THINGS
using SNMP.
35
INTERNET OF THINGS
NETCONF:
🞂 Network Configuration Protocol (NETCONF) is a session-based network management
protocol. NETCONF allows retrieving state or configuration data and manipulating
configuration data on network devices
36
INTERNET OF THINGS
YANG:
🞂 YANG is a data modeling language used to model configuration and state
data manipulated by the NETCONF protocol
🞂 YANG modules contain the definitions of the configuration data, state data, RPC
calls that can be issued and the format of the notifications.
37
INTERNET OF THINGS
🞂 YANG modules defines the data exchanged between the NETCONF client and server.
🞂 A module comprises of a number of 'leaf' nodes which are organized into a
hierarchical tree structure.
🞂 The 'leaf' nodes are specified using the 'leaf' or 'leaf-list' constructs.
🞂 Leaf nodes are organized using 'container' or 'list' constructs.
🞂 A YANG module can import definitions from other modules.
🞂 Constraints can be defined on the data nodes, e.g. allowed values.
🞂 YANG can model both configuration data and state data using the 'config' statement.
YANG Module Example:
🞂 This YANG module is a YANG version of the toaster MIB
🞂 The toaster YANG module begins with the header information followed by
identity declarations which define various bread types.
🞂 The leaf nodes (‘toaster Manufacturer’, ‘toaster Model Number’ and ‘toaster Status’)
are defined in the ‘toaster’ container.
🞂 Each leaf node definition has a type and optionally a description and default value.
🞂 The module has two RPC definitions (‘make-toast’ and ‘cancel-toast’).
The generic approach of IoT device management with NETCONF-YANG. Roles of various
components are:
1) Management System
2) Management API
3) Transaction Manager
4) Rollback Manager
5) Data Model Manager
6) Configuration Validator
7) Configuration Database
8) Configuration API
9) Data Provider API
39
INTERNET OF THINGS
Management System: The operator uses a management system to send NETCONF messages to
configure the IoT device and receives state information and notifications from the device as
NETCONF messages.
2) Management API: allows management application to start NETCONF sessions.
3) Transaction Manager: executes all the NETCONF transactions and ensures that ACID
properties hold true for the transactions.
4) Rollback Manager: is responsible for generating all the transactions necessary to rollback a
current configuration to its original state.
40
INTERNET OF THINGS
5) Data Model Manager: Keeps track of all the YANG data models and the corresponding
managed objects. Also keeps track of the applications which provide data for each part of a
datam, odel.
6) Configuration Validator: checks if the resulting configuration after applying a transaction
would be a valid configuration.
7) Configuration Database: contains both configuration and operational data.
8) Configuration API: Using the configuration API the application on the IoT device can be
read configuration data from the configuration data store and write operational data to the
operational data store.
9) Data Provider API: Applications on the IoT device can register for callbacks for various
events using the Data Provider API. Through the Data Provider API, the applications can report
statistics and operational data.
3) Fill in the IoT device management code in the Trans API module.
5) Load the YANG module and the TransAPI module into the Netopeer server using Netopeer
manager tool.
6) The operator can now connect from the management system to the Netopeer server using the
NetopeerCLI.
7) Operator can issue NETCONF commands from the Netopeer CLI. Command can be issued to
change the configuration data, get operational data or execute an RPC on the IoT device.
41
INTERNET OF THINGS
UNIT - III
INTRODUCTION TO PYTHON:
Python is one of the most dynamic and versatile programming languages available in the
industry today. Since its inception in the 1990s, Python has become hugely popular and even
today there are thousands who are learning this Object-Oriented Programming language. If you
are new to the world of programming, you have already heard the buzz it has created in recent
times because of the features of Python and must be wondering what makes this programming
language special.
Python is an object-oriented programming language that is designed in C. By nature, it is
a high-level programming language that allows for the creation of both simple as well as
complex operations. Along with this Python comes inbuilt with a wide array of modules as well
as libraries which allows it to support many different programming languages like Java, C, C++,
and JSON.
Python is a general-purpose high level programming language and suitable for providing
a solid foundation to the reader in the area of cloud computing.
The main characteristics of Python are:
1) Multi-paradigm programming language.
2) Python supports more than one programming paradigms including object- oriented
programming and structured programming.
3) Interpreted Language.
4) Python is an interpreted language and does not require an explicit compilation step.
5) The Python interpreter executes the program source code directly, statement by statement, as a
processor or scripting engine does.
6) Interactive Language
7) Python provides an interactive mode in which the user can submit commands at the Python
prompt and interact with the interpreter directly.
Features of Python
As a programming language, the features of Python brought to the table are many. Some of the
most significant features of Python are:
42
INTERNET OF THINGS
Easy to Code: Python is a very developer-friendly language which means that anyone and
everyone can learn to code it in a couple of hours or days. As compared to other object-oriented
programming languages like Java, C, C++, and C#, Python is one of the easiest to learn.
Open Source and Free: Python is an open-source programming language which means that
anyone can create and contribute to its development. Python has an online forum where
thousands of coders gather daily to improve this language further. Along with this Python is free
to download and use in any operating system, be it Windows, Mac or Linux.
43
INTERNET OF THINGS
Support for GUI: GUI or Graphical User Interface is one of the key aspects of any
programming language because it has the ability to add flair to code and make the results more
visual. Python has support for a wide array of GUIs which can easily be imported to the
interpreter, thus making this one of the most favorite languages for developers.
Object-Oriented Approach: One of the key aspects of Python is its object-oriented approach.
This basically means that Python recognizes the concept of class and object encapsulation thus
allowing programs to be efficient in the long run.
Integrated by Nature: Python is an integrated language by nature. This means that the python
interpreter executes codes one line at a time. Unlike other object-oriented programming
languages, we don’t need to compile Python code thus making the debugging process much
easier and efficient. Another advantage of this is, that upon execution the Python code is
immediately converted into an intermediate form also known as byte-code which makes it easier
to execute and also saves runtime in the long run.
Highly Portable: Suppose you are running Python on Windows and you need to shift the same
to either a Mac or a Linux system, then you can easily achieve the same in Python without
having to worry about changing the code. This is not possible in other programming languages,
thus making Python one of the most portable languages available in the industry.
Highly Dynamic: As mentioned in an earlier paragraph, Python is one of the most dynamic
languages available in the industry today. What this basically means is that the type of a variable
is decided at the run time and not in advance. Due to the presence of this feature, we do not need
to specify the type of the variable during coding, thus saving time and increasing efficiency.
Extensive Array of Library: Out of the box, Python comes inbuilt with a large number of
libraries that can be imported at any instance and be used in a specific program. The presence of
libraries also makes sure that you don’t need to write all the code yourself and can import the
same from those that already exist in the libraries.
Support for Other Languages: Being coded in C, Python by default supports the execution of
code written in other programming languages such as Java, C, and C#, thus making it one of the
versatile in the industry.
44
INTERNET OF THINGS
Data types are the classification or categorization of data items. Data types represent a kind of
value which determines what operations can be performed on that data. Numeric, non-numeric
and Boolean (true/false) data are the most used data types. However, each programming
language has its own classification largely reflecting its programming philosophy.
Python has the following standard or built-in data types: Built-in Data Types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Numeric
A numeric value is any representation of data which has a numeric value. Python identifies three
types of numbers:
Boolean
Data with one of two built-in values True or False. Notice that 'T' and 'F' are capital. true
and false are not valid booleans and Python will throw an error for them.
45
INTERNET OF THINGS
Sequence Type
A sequence is an ordered collection of similar or different data types. Python has the following
built-in sequence data types:
String: A string value is a collection of one or more characters put in single, double or
triple quotes.
List : A list object is an ordered collection of one or more data items, not necessarily of
the same type, put in square brackets.
Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily
of the same type, put in parentheses.
Dictionary
type() function
Python has an in-built function type() to ascertain the data type of a certain value. For example,
enter type(1234) in Python shell and it will return <class 'int'>, which means 1234 is
an integer value. Try and verify the data type of different values in Python shell, as shown below.
Data objects of the above types are stored in a computer's memory for processing. Some of these
values can be modified during processing, but contents of others can't be altered once they are
created in the memory.
Number values, strings, and tuple are immutable, which means their contents can't be altered
after creation.
On the other hand, collection of items in a List or Dictionary object can be modified. It is
possible to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable
objects.
46
INTERNET OF THINGS
Python has implicit support for Data Structures which enable you to store and access data. These
structures are called List, Dictionary, Tuple and Set.
Python allows its users to create their own Data Structures enabling them to have full control
over their functionality. The most prominent Data Structures are Stack, Queue, Tree, Linked List
and so on which are also available to you in other programming languages. So now that you
know what are the types available to you, why don’t we move ahead to the Data Structures and
implement them using Python.
As the name suggests, these Data Structures are built-in with Python which makes programming
easier and helps programmers use them to obtain solutions faster. Let’s discuss each of them in
detail.
Lists
Lists are used to store data of different data types in a sequential manner. There are addresses
assigned to every element of the list, which is called as Index. The index value starts from 0 and
goes on until the last element called the positive index. There is also negative indexing which
starts from -1 enabling you to access elements from the last to first. Let us now understand lists
better with the help of an example program.
Creating a list
To create a list, you use the square brackets and add elements into it accordingly. If you do not
pass any elements inside the square brackets, you get an empty list as the output.
Output:
[]
[1, 2, 3, ‘example’, 3.132]
47
INTERNET OF THINGS
Dictionary
Dictionaries are used to store key-value pairs. To understand better, think of a phone directory
where hundreds and thousands of names and their corresponding numbers have been added. Now
the constant values here are Name and the Phone Numbers which are called as the keys. And the
various names and phone numbers are the values that have been fed to the keys. If you access the
values of the keys, you will obtain all the names and phone numbers. So that is what a key-value
pair is. And in Python, this structure is stored using Dictionaries. Let us understand this better
with an example program.
Creating a Dictionary
Dictionaries can be created using the flower braces or using the dict() function. You need to add
the key-value pairs whenever you work with dictionaries.
Output:
{}
{1: ‘Python’, 2: ‘Java’}
Tuple
Tuples are the same as lists are with the exception that the data once entered into the tuple cannot
be changed no matter what. The only exception is when the data inside the tuple is mutable, only
then the tuple data can be changed. The example program will help you understand better.
48
INTERNET OF THINGS
Creating a Tuple
2print(my_tuple)
Output:
(1, 2, 3)
Sets
Sets are a collection of unordered elements that are unique. Meaning that even if the data is
repeated more than one time, it would be entered into the set only once. It resembles the sets that
you have learnt in arithmetic. The operations also are the same as is with the arithmetic sets. An
example program would help you understand better.
Creating a set
Sets are created using the flower braces but instead of adding key-value pairs, you just pass
values to it.
Output:
{1, 2, 3, 4, 5}
Arrays and lists are the same structure with one difference. Lists allow heterogeneous data
element storage whereas Arrays allow only homogenous elements to be stored within them.
49
INTERNET OF THINGS
Stack
Stacks are linear Data Structures which are based on the principle of Last-In-First-Out (LIFO)
where data which is entered last will be the first to get accessed. It is built using the array
structure and has operations namely, pushing (adding) elements, popping (deleting) elements and
accessing elements only from one point in the stack called as the TOP. This TOP is the pointer to
the current position of the stack. Stacks are prominently used in applications such as Recursive
Programming, reversing words, undo mechanisms in word editors and so forth.
Queue
A queue is also a linear data structure which is based on the principle of First-In-First-Out
(FIFO) where the data entered first will be accessed first. It is built using the array structure and
has operations which can be performed from both ends of the Queue, that is, head-tail or front-
back. Operations such as adding and deleting elements are called En-Queue and De-Queue and
accessing the elements can be performed. Queues are used as Network Buffers for traffic
congestion management, used in Operating Systems for Job Scheduling and many more.
Tree
Trees are non-linear Data Structures which have root and nodes. The root is the node from where
the data originates and the nodes are the other data points that are available to us. The node that
precedes is the parent and the node after is called the child. There are levels a tree has to show
the depth of information. The last nodes are called the leaves. Trees create a hierarchy which can
be used in a lot of real-world applications such as the HTML pages use trees to distinguish which
tag comes under which block. It is also efficient in searching purposes and much more.
50
INTERNET OF THINGS
Linked List
Linked lists are linear Data Structures which are not stored consequently but are linked with each
other using pointers. The node of a linked list is composed of data and a pointer called next.
These structures are most widely used in image viewing applications, music player applications
and so forth.
Graph
Graphs are used to store data collection of points called vertices (nodes) and edges (edges).
Graphs can be called as the most accurate representation of a real-world map. They are used to
find the various cost-to-distance between the various data points called as the nodes and hence
find the least path. Many applications such as Google Maps, Uber, and many more use Graphs to
find the least distance and increase profits in the best ways.
HashMaps
HashMaps are the same as what dictionaries are in Python. They can be used to implement
applications such as phonebooks, populate data according to the lists and much more.
51
INTERNET OF THINGS
Besides the while statement just introduced, Python uses the usual flow control statements
known from other languages, with some twists.
1. if Statements
Perhaps the most well-known statement type is the if statement. For example:
>>>
There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for
‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a
substitute for the switch or case statements found in other languages.
52
INTERNET OF THINGS
2. for Statements
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather
than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the
user the ability to define both the iteration step and halting condition (as C), Python’s for
statement iterates over the items of any sequence (a list or a string), in the order that they appear
in the sequence. For example (no pun intended):
>>>
Code that modifies a collection while iterating over that same collection can be tricky to get
right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create
a new collection:
If you do need to iterate over a sequence of numbers, the built-in function range() comes in
handy. It generates arithmetic progressions:
53
INTERNET OF THINGS
>>>
The given end point is never part of the generated sequence; range(10) generates 10 values, the
legal indices for items of a sequence of length 10. It is possible to let the range start at another
number, or to specify a different increment (even negative; sometimes this is called the ‘step’):
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
To iterate over the indices of a sequence, you can combine range() and len() as follows:
>>>
In most such cases, however, it is convenient to use the enumerate() function, see Looping
Techniques.
54
INTERNET OF THINGS
>>>
>>> print(range(10))
range(0, 10)
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an
object which returns the successive items of the desired sequence when you iterate over it, but it
doesn’t really make the list, thus saving space.
We say such an object is iterable, that is, suitable as a target for functions and constructs that
expect something from which they can obtain successive items until the supply is exhausted. We
have seen that the for statement is such a construct, while an example of a function that takes an
iterable is sum():
>>>
>>> sum(range(4)) # 0 + 1 + 2 + 3
6
Later we will see more functions that return iterables and take iterables as arguments. Lastly,
maybe you are curious about how to get a list from a range. Here is the solution:
>>>
>>> list(range(4))
[0, 1, 2, 3]
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
Loop statements may have an else clause; it is executed when the loop terminates through
exhaustion of the iterable (with for) or when the condition becomes false (with while), but not
when the loop is terminated by a break statement. This is exemplified by the following loop,
which searches for prime numbers:
>>>
55
INTERNET OF THINGS
(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if
statement.)
When used with a loop, the else clause has more in common with the else clause of a try
statement than it does with that of if statements: a try statement’s else clause runs when no
exception occurs, and a loop’s else clause runs when no break occurs. For more on the try
statement and exceptions, see Handling Exceptions.
The continue statement, also borrowed from C, continues with the next iteration of the loop:
>>>
56
INTERNET OF THINGS
5. pass Statements
The pass statement does nothing. It can be used when a statement is required syntactically but
the program requires no action. For example:
>>>
>>>
Another place pass can be used is as a place-holder for a function or conditional body when you
are working on new code, allowing you to keep thinking at a more abstract level. The pass is
silently ignored:
>>>
Functions:
We can create a function that writes the Fibonacci series to an arbitrary boundary:
>>>
The keyword def introduces a function definition. It must be followed by the function name and
the parenthesized list of formal parameters. The statements that form the body of the function
start at the next line, and must be indented.
The first statement of the function body can optionally be a string literal; this string literal is the
function’s documentation string, or docstring. (More about docstrings can be found in the section
Documentation Strings) There are tools which use docstrings to automatically produce online or
printed documentation, or to let the user interactively browse through code; it’s good practice to
include docstrings in code that you write, so make a habit of it.
The execution of a function introduces a new symbol table used for the local variables of the
function. More precisely, all variable assignments in a function store the value in the local
symbol table; whereas variable references first look in the local symbol table, then in the local
symbol tables of enclosing functions, then in the global symbol table, and finally in the table of
built-in names. Thus, global variables and variables of enclosing functions cannot be directly
assigned a value within a function (unless, for global variables, named in a global statement, or,
for variables of enclosing functions, named in a nonlocal statement), although they may be
referenced.
The actual parameters (arguments) to a function call are introduced in the local symbol table of
the called function when it is called; thus, arguments are passed using call by value (where the
value is always an object reference, not the value of the object). When a function calls another
function, a new local symbol table is created for that call.
A function definition associates the function name with the function object in the current symbol
table. The interpreter recognizes the object pointed to by that name as a user-defined function.
Other names can also point to that same function object and can also be used to access the
function:
58
INTERNET OF THINGS
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
Coming from other languages, you might object that fib is not a function but a procedure since it
doesn’t return a value. In fact, even functions without a return statement do return a value, albeit
a rather boring one. This value is called None (it’s a built-in name). Writing the value None is
normally suppressed by the interpreter if it would be the only value written. You can see it if you
really want to using print():
>>>
>>> fib(0)
>>> print(fib(0))
None
It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of
printing it:
>>>
The return statement returns with a value from a function. return without an expression
argument returns None. Falling off the end of a function also returns None.
59
INTERNET OF THINGS
The statement result.append(a) calls a method of the list object result. A method is a
function that ‘belongs’ to an object and is named obj.methodname, where obj is some
object (this may be an expression), and methodname is the name of a method that is
defined by the object’s type. Different types define different methods. Methods of
different types may have the same name without causing ambiguity. (It is possible to
define your own object types and methods, using classes, see Classes) The method
append() shown in the example is defined for list objects; it adds a new element at the
end of the list. In this example it is equivalent to result = result + [a], but more
efficient.
It is also possible to define functions with a variable number of arguments. There are three
forms, which can be combined.
The most useful form is to specify a default value for one or more arguments. This creates a
function that can be called with fewer arguments than it is defined to allow. For example:
giving only the mandatory argument: ask_ok('Do you really want to quit?')
giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)
or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only
yes or no!')
60
INTERNET OF THINGS
This example also introduces the in keyword. This tests whether or not a sequence contains a
certain value.
The default values are evaluated at the point of function definition in the defining scope, so that
i=5
def f(arg=i):
print(arg)
i=6
f()
will print 5.
Important warning: The default value is evaluated only once. This makes a difference when
the default is a mutable object such as a list, dictionary, or instances of most classes. For
example, the following function accumulates the arguments passed to it on subsequent calls:
print(f(1))
print(f(2))
print(f(3))
This will
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function
like this instead:
62
INTERNET OF THINGS
L.append(a)
return L
2. Keyword Arguments
Functions can also be called using keyword arguments of the form kwarg=value. For instance,
the following function:
accepts one required argument (voltage) and three optional arguments (state, action, and type).
This function can be called in any of the following ways:
In a function call, keyword arguments must follow positional arguments. All the keyword
arguments passed must match one of the arguments accepted by the function (e.g. actor is not a
valid argument for the parrot function), and their order is not important. This also includes non-
optional arguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value
more than once. Here’s an example that fails due to this restriction:
>>>
63
INTERNET OF THINGS
>>> def function(a):
64
INTERNET OF THINGS
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'
When a final formal parameter of the form **name is present, it receives a dictionary (see
Mapping Types — dict) containing all keyword arguments except for those corresponding to a
formal parameter. This may be combined with a formal parameter of the form *name (described
in the next subsection) which receives a tuple containing the positional arguments beyond the
formal parameter list. (*name must occur before **name.) For example, if we define a function
like this:
65
INTERNET OF THINGS
Note that the order in which the keyword arguments are printed is guaranteed to match the order
in which they were provided in the function call.
3. Special parameters
| | |
| Positional or keyword |
| - Keyword only
-- Positional only
where / and * are optional. If used, these symbols indicate the kind of parameter by how the
arguments may be passed to the function: positional-only, positional-or-keyword, and keyword-
only. Keyword parameters are also referred to as named parameters.
If / and * are not present in the function definition, arguments may be passed to a function by
position or by keyword.
Looking at this in a bit more detail, it is possible to mark certain parameters as positional-only. If
positional-only, the parameters’ order matters, and the parameters cannot be passed by keyword.
Positional-only parameters are placed before a / (forward-slash). The / is used to logically
separate the positional-only parameters from the rest of the parameters. If there is no / in the
function definition, there are no positional-only parameters.
Consider the following example function definitions paying close attention to the markers / and
*:
>>>
The first function definition, standard_arg, the most familiar form, places no restrictions on the
calling convention and arguments may be passed by position or keyword:
>>>
>>> standard_arg(2)
2
>>> standard_arg(arg=2)
67
INTERNET OF THINGS
and another module would be responsible for drawing the game on the screen. Each module is a
different file, which can be edited separately.
Writing modules
Modules in Python are simply Python files with a .py extension. The name of the module will be
the name of the file. A Python module can have a set of functions, classes or variables defined
and implemented.
The Python script game.py will implement the game. It will use the function draw_game
from the file draw.py, or in other words, thedraw module, that implements the logic for
drawing the game on the screen.
You may have noticed that in this example, draw_game does not precede with the
name of the module it is imported from, because we've specified the module name in the
import command.
The advantages of using this notation is that it is easier to use the functions inside the
current module because you don't need to specify which module the function comes from.
However, any namespace cannot have two objects with the exact same name, so the import
command may replace an existing object in the namespace.
This might be a bit risky as changes in the module might affect the module which imports
it, but it is shorter and also does not require you to specify which objects you wish to import
from the module.
We may also load modules under any name we want. This is useful when we want to
import a module conditionally to use the same name in the rest of the code.
68
INTERNET OF THINGS
Module initialization
The first time a module is loaded into a running Python script, it is initialized by
executing the code in the module once. If another module in your code imports the same module
again, it will not be loaded twice but once only - so local variables inside the module act as a
"singleton" - they are initialized only once.
This is useful to know, because this means that you can rely on this behavior for initializing
objects.
There are a couple of ways we could tell the Python interpreter where to look for
modules, aside from the default, which is the local directory and the built-in modules. You could
either use the environment variable PYTHONPATH to specify additional directories to look for
modules.
This will execute game.py, and will enable the script to load modules from the foo
directory as well as the local directory.
Check out the full list of built-in modules in the Python standard library here.
Two very important functions come in handy when exploring modules in Python - the dir and
help functions.
If we want to import the module urllib, which enables us to create read data from
URLs.
When we find the function in the module we want to use, we can read about it more using the
help function, inside the Python interpreter:
script.py
IPython Shell
69
INTERNET OF THINGS
Writing packages:
Packages are namespaces which contain multiple packages and modules themselves.
They are simply directories, but with a twist.
Each package in Python is a directory which MUST contain a special file called
init .py. This file can be empty, and it indicates that the directory it contains is a Python
package, so it can be imported the same way a module can be imported.
If we create a directory called foo, which marks the package name, we can then create a
module inside that package called bar. We also must not forget to add the init .py file
inside the foo directory.
script.py
IPython Shell.
UNIT – IV
IoT Physical Devices and Endpoints
70
INTERNET OF THINGS
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.
71
INTERNET OF THINGS
Raspberry Pi
72
INTERNET OF THINGS
Linux on Raspberry Pi
1. Raspbian: Raspbian Linux is a Debian Wheezy port optimized for RaspberryPi.
2. Arch: Arch is an Arch Linux port for AMDdevices.
3. Pidora: Pidora Linux is a Fedora Linux optimized for RaspberryPi.
4. RaspBMC: RaspBMC is an XBMC media-center distribution for RaspberryPi.
5. OpenELEC: OpenELEC is a fast and user-friendly XBMC media-centerdistribution.
6. RISC OS: RISC OS is a very fast and compact operatingsystem.
Raspberry Pi GPIO
Raspberry Pi Interfaces
73
INTERNET OF THINGS
1. Serial: The serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins for
communication with serialperipherals.
2. SPI: Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for
communicating with one or more peripheraldevices.
3. 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
(clockline).
74
INTERNET OF THINGS
UNIT
IV
75
INTERNET OF THINGS
76
INTERNET OF THINGS
77
INTERNET OF THINGS
realizing smart city applications with extremely low power consumption. A comparative
summary2 of the major communicationprotocols.
Service Providers
Pike Research on smart cities estimated this market will grow to hundreds of billion dollars by
2020, with an annual growth of nearly 16 billion. IoT is recognized as a potential source to
increase revenue of service providers. Thus, well-known worldwide service providers have
already started exploring this novel cutting edge communication paradigm. Major service
providers include Telefonica, SK telecom, Nokia, Ericsson, Vodafone, NTT Docomo, Orange,
Telenor group and AT&T which offer variety of services and platforms for smart city
applications such as ITS and logistics, smart metering, home automation and e-healthcare.
Network Types
IoT based smart city applications rely on numerous network topologies to accomplish a
fully autonomous environment. The capillary IoT networks offer services over a short range.
Examples include wireless local area networks (WLANs), BANs and wireless personal area
networks (WPANs). The application areas include indoor e-healthcare services, home
automation, street lighting. On the other hand, applications such as ITS, mobile e-healthcare and
waste management use wide area networks (WANs), metropolitan area networks (MANs),and
mobile communication networks. The above networks pose distinct features in terms of data,
size, coverage, latency requirements, and capacity.
Case Study in IoT: Smart Environment
The rapid advancements in communication technologies and the explosive growth of
Internet of Things (IoT) have enabled the physical world to invisibly interweave with actuators,
sensors, and other computational elements while maintaining continuous network connectivity.
The continuously connected physical world with computational elements forms a smart
environment. A smart environment aims to support and enhance the abilities of its dwellers in
executing their tasks, such as navigating through unfamiliar space and moving heavy objects for
the elderly, to name a few. Researchers have conducted a number of efforts to use IoT to
facilitate our lives and to investigate the effect of IoTbased smart environments on human life.
This paper surveys the state-of-the-art research efforts to enable the IoT-based smart
environments. We categorize and classify the literature by devising a taxonomy based on
communication enablers, network types, technologies, local area wireless standards, objectives,
and characteristics. Moreover, the paper highlights the unprecedented opportunities brought
about by IoT-based smart environments and their effect on human life. Some reported case
studies from different enterprises are also presented. Finally, we discuss open research
challenges for enabling IoT-based smart environments. Immense developments and increasing
miniaturization of computer technology have enabled tiny sensors and processors to be
integrated into everyday objects. This advancement is further supported by tremendous
developments in areas such as portable appliances and devices, pervasive computing, wireless
78
INTERNET OF THINGS
79
INTERNET OF THINGS
Technologies
IoT-based smart environments leverage various technologies to form a comfortable and suitable
ecosystem. These technologies are include sensing, communication, data fusion, emerging
computing, and information security. Sensing technologies are commonly used to acquire data
from various locations and transmit it using communication technologies to a central location.
The emerging computing technologies, such as cloud computing and fog computing, deployed in
the central location, leverage the data fusion technologies for integrating the data coming from
heterogeneous resources. In addition, smart environments also use information security
technologies to ensure data integrity and user privacy.
Local Area Wireless Standards
The commonly used local area wireless standards in IoT-based smart environments are IEEE
802.11, IEEE 802.15.1, and IEEE 802.15.4. These standard technologies are used inside the
smart environment to transfer the collected data among different devices. IEEE 802.11 is used in
smart homes, smart buildings, and smart cities. IEEE 802.15.1 and IEEE 802.15.4 have relatively
shorter coverage than IEEE 802.11 and are used mainly in sensors and other objects deployed in
the smart environments.
80