Iot Unit2
Iot Unit2
Developing
Internet of
Things
Dr. Lakshmi. S
Associate Professor,
ECE, RIT, Bangalore
IoT Platforms Design Methodology
IoT systems comprise of multiple components,
deployment levels and configurations etc
based on the application
The design process of an IoT system has to
consider – interactions between various
components / devices, network resources,
web services, components like analytics,
applications and DB services
As there are wide choices available for the
components etc, the design process of an IoT
system is both challenging and complex
A design done considering a specific product
/ service would lead to a product or service or
vendor lock-in whereby complicating system
upgrades, maintenance etc for the customer
IoT System Design Methodology – Steps (1 of 2)
Purpose and Requirements
Define the purpose, behavior and Requirements (like Management, Data analysis)of
the IoT system
Service Specifications
Map Process and Information models to services and define service
specifications
A
IoT System Design Methodology – Steps (2 of 2)
A
Application Development
Develop Applications
IOT Design Methodology
Ex: Designing a Smart Home Automation System!!
Mode
auto manua
l
Light- Light-
Level State
Level: State: State:
Level:
High On Off
Low
Linux
#Install Dependencies
sudo apt-get install build-essential
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev
libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
#Download Python
wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz
tar -xvf Python-2.7.5.tgz
cd Python-2.7.5
#Install Python
./configure
make
sudo make install
Numbers
Numbers
Number data type is used to store numeric values. Numbers are immutable data
types, therefore changing the value of a number data type results in a newly
allocated object.
#Integer
>>>a=5 #Addition #Division
>>>type(a) >>>c=a+b >>>f=b/a
<type ’int’> >>>c >>>f
#Floating Point 7.5 0.5
>>>b=2.5 >>>type(c) >>>type(f)
>>>type(b) <type ’float’> <type float’>
<type ’float’>
#Long #Subtraction #Power
>>>x=9898878787676L >>>d=a-b >>>g=a**2
>>>type(x) >>>d >>>g
<type ’long’> 2.5 25
#Complex >>>type(d)
>>>y=2+5j <type ’float’>
>>>y
(2+5j) #Multiplication
>>>type(y) >>>e=a*b
<type ’complex’> >>>e
>>>y.real 12.5
2 >>>type(e)
>>>y.imag <type ’float’>
5
Strings
Strings
A string is simply a list of characters in order. There are no limits to the number of
characters you can have in a string.
#Printstring
#Create string
>>>print s
#strip: Returns a copy
>>>s="Hello World!" of the string with the
Hello World!
>>>type(s)
#leading and trailing
<type ’str’>
#Formatting output characters removed.
>>>print "The string (The
#String concatenation
string (Hello World!) has >>>s.strip("!")
>>>t="This is sample
12 characters
program." ’Hello World’
>>>r = s+t
#Convert to upper/lower
>>>r
case
’Hello World!This is sample
>>>s.upper()
program.’
’HELLO WORLD!’
>>>s.lower()
#Get length of string
’hello world!’
>>>len(s)
12
#Accessing sub-strings
>>>s[0]
#Convert string to integer
’H’
>>>x="100"
>>>s[6:]
>>>type(s)
’World!’
<type ’str’>
>>>s[6:-1]
>>>y=int(x)
’World’
>>>y
100
Lists
List a compound data type used to group together other values. List items need not
all have the same type. A list contains items separated by commas and enclosed
within square brackets.
#Create a dictionary
>>>student={’name’:’Mary’
#Get all keys in a dictionary #Check if dictionary has
>>>student.keys() a key
,’id’:’8776’,’major’:’CS’} [’gender’, ’major’, ’name’,
>>>student >>>student.has_key(’na
’id’]
{’major’: ’CS’, ’name’: #Get all values in a me’)
’Mary’, ’id’: ’8776’} True
dictionary
>>>type(student) >>>student.has_key(’gr
>>>student.values()
<type ’dict’> [’female’, ’CS’, ’Mary’, ade’)
’8776’] False
#Get length of a dictionary #Add new key-value pair
>>>len(student) >>>student[’gender’]=’fema
3 le’
>>>student
#Get the value of a key in {’gender’: ’female’, ’major’:
dictionary ’CS’, ’name’: ’Mary’, ’id’:
>>>student[’name’] ’8776’}
’Mary’
#A value in a dictionary can
be another dictionary
#Get all items in a >>>student1={’name’:’David
dictionary ’,’id’:’9876’,’major’:’ECE’}
>>>student.items() >>>students={’1’:
[(’gender’, ’female’), student,’2’:student1}
(’major’, ’CS’), (’name’, >>>students
’Mary’), (’id’, ’8776’)] {’1’: {’gender’: ’female’,
Type Conversions
Type conversion examples
print "Less
than 10k"
W
O
R
Control Flow – while statement
The while statement in Python executes the statements within the
while loop as long as the while condition is true.
>>> i = 0
break
print y
4
Continue 32
384
Continue statement continues with the next iteration.
apple
orange
Control Flow – pass statement
The pass statement in Python is a null operation.
The pass statement is used when a statement is required
syntactically but you do not want any command or code to
execute.
>fruits=[’apple’,’orange’,’banana’
,’mango’]
>for item in fruits:
if item == "banana":
pass
else:
print item
apple
orange
mango
Write the program that prompts the user for a list of numbers and prints out the maximum and
minimum of the numbers at the end when the user enters “done”. Write the program to store
the numbers the user enters in a list and use the max() and min() functions to compute the
maximum and minimum numbers after the loop completes
numlist = list()
while ( True ) :
inp = input('Enter a number: ')
if inp == 'done' :
break
value = float(inp)
numlist.append(value)
print(numlist)
print(max(numlist))
print(min(numlist))
Functions
A function is a block of code that takes
information in (in the form of parameters), students = { '1': {'name': 'Bob', 'grade': 2.5},
does some computation, and returns a '2': {'name': 'Mary', 'grade': 3.5},
new piece of information based on the '3': {'name': 'David', 'grade':
parameter information. 4.2},
A function in Python is a block of code '4': {'name': 'John', 'grade': 4.1},
that begins with the keyword def '5': {'name': 'Alex', 'grade': 3.8}}
followed by the function name and
parentheses. The function parameters
are enclosed within the parenthesis. def averageGrade(students):
The code block within a function begins ‘’’This function computes the average
after a colon that comes after the grade’’’
parenthesis enclosing the parameters. sum = 0.0
The first statement of the function body for key in students:
can optionally be a documentation sum = sum + students[key]['grade']
string or docstring. average = sum/len(students)
return average
Syntax
avg = averageGrade(students)
def functionname( print ("The average grade is: %0.2f" % (avg))
parameters ):
“’function_docstring“’
function_suite
return [expression]
Functions - Default Arguments
Functions can have default values of the parameters.
If a function with default values is called with fewer parameters or without
any parameter, the default values of the parameters are used
Output
Name: miki
Age 50
Name: miki
Age 35
Functions - Passing by Reference
All parameters in the Python functions are passed by reference.
If a parameter is changed within a function the change also reflected
back in the calling function.
# Function definition is here def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ",mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
Output
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Functions - Keyword Arguments
Functions can also be called using keyword arguments that identifies the
arguments by the parameter name when the function is called.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters
def #Correct use
printStudentRecords(name,age=20,major=’C printStudentRecords(name=’Alex’)
S’): Name: Alex
print( "Name: " , name) Age: 20
print ("Age: " , age) Major: CS
print ("Major: “ , major)
printStudentRecords(name=’Bob’,age=22,major
#This will give error as name is required =’ECE’)
argument Name: Bob
printStudentRecords() Age: 22
Major: ECE
Output
Traceback (most recent call last): printStudentRecords(name=’Alan’,major=’ECE’)
File "<stdin>", line 1, in <module> Name: Alan
TypeError: printStudentRecords() takes at Age: 20
least 1 argument (0 given) Major: ECE
Functions - Variable Length Arguments
Python functions can have variable length arguments. The variable length
arguments are passed to as a tuple to the function with an argument
prefixed with asterix (*)
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed
arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return
Output is: 10
Output is: 70 60 50
Modules #Using student module
>>>import student
#student module - saved as student.py
def averageGrade(students): >>>students =
Python allows sum = 0.0 '1': 'name': 'Bob', 'grade': 2.5,
organizing the for key in students: '2': 'name': 'Mary', 'grade': 3.5,
'3': 'name': 'David', 'grade': 4.2,
program code into sum = sum +
students[key]['grade'] '4': 'name': 'John', 'grade': 4.1,
different modules average = sum/len(students) '5': 'name': 'Alex', 'grade': 3.8
which improves the return average
>>>student.printRecords(students)
code readability and
def printRecords(students): There are 5 students
management. Print( "There are %d students“ Student-1:
Consider a module %(len(students))) Name: Bob
i=1 Grade: 2.5
to be the same as a for key in students: Student-2:
code library. A file print( "Student-%d: " % (i)) Name: David
containing a set of print ("Name: " Grade: 4.2
,students[key]['name']) Student-3:
functions you want to print "Grade: " Name: Mary
include in your ,str(students[key]['grade']) Grade: 3.5
application. i = i+1 Student-4:
Name: Alex
Modules can be # Importing a specific function Grade: 3.8
from a module Student-5:
imported using the >from student import Name: John
import keyword. averageGrade Grade: 4.1
Modules to be # Listing all names defined in a >>>avg = student.
imported must be module averageGrade(students)
present in the search >>>dir(student) >>>print ("The average grade is:
path. %0.2f" % (avg))
3.62
File Handling
In Python, a file is categorized as either text or
binary, and the difference between the two file
types is important.
Text files are structured as a sequence of lines,
where each line includes a sequence of
characters. This is what you know as code or
syntax.
Each line is terminated with a special character,
called the EOL or End of Line character. There are
several types, but the most common is the comma
{,} or newline character. It ends the current line
and tells the interpreter a new one has begun.
File generation
Create a text file
file =
To get more familiar with text files in
Python, let’s create our own and do
open(“testfile.txt”,”w”)
some additional exercises.
Using a simple text editor, let’s file.write(“Hello World”)
create a file. You can name it
anything you like, and it’s better to file.write(“This is our new
use something you’ll identify with.
For the purpose of this tutorial,
text file”)
however, we are going to call it
“testfile.txt”. file.write(“and this is another
Just create the file and leave it
blank.
line.”)
To manipulate the file, write the
following in your Python file.write(“Why? Because
environment (you can copy and
paste if you’d like):
we can.”)
file.close()
File Handling
Python allows reading and writing to files # Syntax for opening a file
using the file object. file_object = open(“filename”, “mode”) where
The open(filename, mode) function is file_object is the variable to add the file object.
used to get a file object.
The mode can be read (r), write (w), # Example of reading an entire
append (a), read and write (r+ or w+), file
read-binary (rb), write-binary (wb), etc. >>>fp = open('file.txt','r')
After the file contents have been read >>>content = fp.read()
the close function is called which closes >>>print content
the file object. This is a test file.
>>>fp.close()
• There is a special method by the name __init__() which is called the class
constructor. The class constructor initializes a new instance when it is
created.
• The function __del__() is the class destructor
• The variable empCount is a class variable whose value is shared among
all the instances of this class. This can be accessed as
Employee.empCount from inside the class or outside the class.
• You declare other class methods like normal functions with the
exception that the first argument to each method is self. Python adds
the self argument to the list for you; you do not need to include it when
you call the methods
• Members declared without underscore are public
• Members declared with one underscore are protected
• Members declared with two underscores are private
WAP for adding two numbers using class
class num:
def __init__(self, aa, bb):
self.a = aa
self.b = bb
def add(self):
return self.a + self.b
e = num(8, 6)
print(e.add())
Output
14
Write a program to create and display an
employee data base using classes in python
class Employee:
‘’’Common base class for all employees’’’
empCount = 0
def __init__(self, n, s):
self.name = n
self.salary = s
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary )
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
Output
#This would create first object of Employee class" Name : Zara ,Salary: 2000
emp1 = Employee("Zara", 2000) Name : Manni ,Salary: 5000
#This would create second object of Employee class" Total Employee 2
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
Data Hiding
Data Hiding
One of the key parts of object-oriented programming is encapsulation, which
involves the packaging of variables and related functions in one simple-to-use
object: the instance of a class.
A concept related to this is data hiding, which consists in hiding the
implementation details of a class. In this way the user interface of this class is
clean and more intuitive. In other programming languages, data hiding is
done by creating private methods and attributes, to which their external
access to the function is blocked. In Python, however, the philosophy is slightly
different “we are all consenting adults” and therefore there are no particular
restrictions on access. So there is nothing that can deprive an attribute or
method in such a way as to make it inaccessible to the outside of the
classroom.
In Python, the so-called weakly-private methods have a single underscore (_)
prefixed in their name. This prefix indicates the presence of a private method,
which should not be used outside the class. But this is just a convention and
nothing avoids the opposite. The only real effect it has is to avoid importing
the method when using the wording
from modulename import *
Instead, there are methods and attributes, strongly private, that are
distinguished by the double underscore (__) as prefix in their name. Once a
method is marked with this double underscore, then the method will be really
private and will no longer be accessible from outside the class.
However, these methods can still be accessed from the outside, but using a
different name
Data Hiding
class JustCounter:
__secretCount = 0 • Python protects those members
def count(self):
self.__secretCount += 1
by internally changing the name
print (self.__secretCount) to include the class name.
• You can access such attributes as
counter = JustCounter() object._className__attrName.
counter.count() • If you would replace your last line
counter.count()
print (counter.__secretCount)
as following, then it works for you-
Output print
1 (counter._JustCounter__secretCou
2 nt)
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute
'__secretCount'
Class Inheritance
In this example parent is the base class and Child is the derived class.
The class Child inherits the attributes of the Parent class.
class Parent:
def __init__(self, a):
self.a = a
def print_var1(self):
print("The value of Parent class variables
are:")
print(self.a)
class Child(Parent):
def __init__(self, a, b):
Parent.__init__(self, a)
self.b = b
def print_var2(self):
print("The value of Child class variables
are:")
print(self.b) OutPut
X=Child(10,20) 10
X.print_var1() 20
X.print_var2()
Packages
# skimage package listing
Python package is hierarchical file skimage/ Top level package
structure that consists of modules __init__.py Treat directory as a
and subpackages. package
Packages allow better organization
of modules related to a single color/ color color
subpackage
application environment.
__init__.py
colorconv.py
colorlabel.py
rgb_colors.py
exposure/ exposure
subpackage
__init__.py
_adapthist.py
exposure.py
import requests
r = requests.get('http://httpbin.org/')
print(type(r))
print(r.status_code)
print(r.headers)
print(r.headers['content-type'])
#print(r.text)
import requests
r = requests.get('http://httpbin.org/ip')
print(r.headers['content-type'])
print(r.text)
data = r.json()
print(data)
print(data['origin'])
The content-type is
application/json
The json method converts the JSON string into a Python data structure. In our case it is a
dictionary holding a single key and the IP address of our computer as the value:
{u'origin': u'31.168.135.94'}
We can access the individual values (in this case the IP address), just as we do with any other
dictionary in Python:
data['origin']
Python HTTP Client Request – GET, POST
import http.client
connection =
http.client.HTTPSConnection("www.journaldev.com")
connection.request("GET", "/")
response = connection.getresponse()
print("Status: {} and reason: {}".format(response.status,
response.reason))
connection.close()
Output: Status: 200 and reason: OK
Getting the Header list from Response
import http.client
import pprint
connection =
http.client.HTTPSConnection("www.journaldev.c
om")
connection.request("GET", "/")
response = connection.getresponse()
headers = response.getheaders()
pp = pprint.PrettyPrinter(indent=4)
pp.pprint("Headers: {}".format(headers))
print(content)
max-age=0'), ('Expires', 'Mon, 22 Oct "
"2018 00:29:51 GMT'), ('Content-Type', 'text/html;
charset=UTF-8'), ('Link', "
'\'<https://www.journaldev.com/wp-json/>;
rel="https://api.w.org/"\'), '
"('X-LiteSpeed-Cache-Control', 'public,max-
age=604800'), ('X-LiteSpeed-Tag', "
"'0e81_URL.6666cd76f96956469e7be39d750cc7d
9,0e81_F,0e81_'), ('Etag', "
'\'"5093-1540168191;;;"\'), (\'X-Litespeed-
Cache\', \'miss\'), '
"('Transfer-Encoding', 'chunked'), ('Date', 'Mon,
22 Oct 2018 00:29:51 GMT'), "
"('Server', 'LiteSpeed'), ('Vary', 'User-Agent'), ('X-
Content-Type-Options', "
"'nosniff'), ('X-XSS-Protection', '1; mode=block'), "
"('Strict-Transport-Security', 'max-age=31536000;
includeSubDomains'), "
'(\'Connection\', \'Keep-Alive\'), (\'Alt-Svc\',
\'quic=":443"; ma=2592000; '
'v="35,39,43"\')]')
Python HTTP POST
import http.client
import json
conn =
http.client.HTTPSConnection('www.httpbin.org')
OUTPUT:{
"args": {},
headers = {'Content-type': 'application/json'} "data": "{\"text\": \"Hello HTTP #1 **cool**,
and #1!\"}",
foo = {'text': 'Hello HTTP #1 **cool**, and #1!'}
"files": {},
json_data = json.dumps(foo) "form": {},
"headers": {
conn.request('POST', '/post', json_data, headers)"Accept-Encoding": "identity",
"Connection": "close",
"Content-Length": "43",
response = conn.getresponse()
"Content-Type": "application/json",
print(response.read().decode()) "Host": "www.httpbin.org"
},
"json": {
"text": "Hello HTTP #1 **cool**, and #1!"
},
"origin": "223.237.223.57",
"url": "https://www.httpbin.org/post"
}
Further Reading