Unit 4
Unit 4
Introduction to Python
Python is a widely used general-purpose, high level programming language. It was initially designed by
Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for
emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new features.
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our programs. There
are certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.com/ or http://codepad.org/
that can be used to start Python without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software from
http://python.org/downloads/
# Script Begins
Statement1 Statement2
Statement3
# Script Ends
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and multiple inheritance.
4. It‟s Powerful
• Dynamic typing
• Built-in types and tools
• Library utilities
• Third party utilities (e.g. Numeric, NumPy, sciPy)
• Automatic memory management
5. It‟s Portable
• Python runs virtually every major platform used today
• As long as you have a compaitable python interpreter installed, python programs will run
in exactly the same manner, irrespective of platform.
• This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages. Structure and syntax are pretty intuitive and
easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
Python‟s traditional runtime execution model: Source code you type is translated to byte code, which is then
run by the Python Virtual Machine (PVM). Your code is automatically compiled, but then it is interpreted.
m.py m.pyc
PVM
• Interactive Mode
• Script Mode
Without passing python script file to the interpreter, directly execute code to Python prompt. Once you‟re
inside the python interpreter, then you can start.
>>> x=[0,1,2]
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to
indicate that it is ready. If the programmer types 2+6, the interpreter replies 8.
Alternatively, programmers can store Python script source code in a file with the .py extension,
and use the interpreter to execute the contents of the file. To execute the script by the interpreter, you have to
tell the interpreter the name of the file. For example, if you have a script name MyFile.py and you're working on
Unix, to run the script you have to type:
python MyFile.py
Working with the interactive mode is better when Python programmers deal with small pieces of code as you
can type and execute them immediately, but when the code is more than 2-4 lines, using the script for coding
can help to modify and use the code in future.
Example:
IoT development means combining hardware parts and software programs in such a way that the
final product could monitor specific values, collect and transfer data, analyze given data and
cause the physical device to act correspondingly. Creating such systems is a true challenge.
Moreover, the Internet of Things has already been transformed into an industry in its own right,
so the need for reliable and comprehensive developer toolkits has also increased. IoT
development tools needed to create complex applications are represented by IoT hardware
devices (boards, SoM, SoC, sensors, gateways, trackers, and more), IoT app development
platforms, IoT operating systems (e.g., Embedded Linux) and programming languages.
The 15 most popular tools currently used for IoT projects are
Arduino
Flutter
Kinoma
Tessel 2
M2MLabs Mainspring
Node-RED
Eclipse IoT
SiteWhere
DeviceHive
Home Assistant
OpenRemote
ThingsBoard
MilesightDeviceHub
Zetta
1. Arduino
Arduino is the leading company on the IoT market that produces electronic devices and software
for them. Arduino hardware offerings include microcontroller boards, modules, shields and kits.
Hardware specifications are suitable for creating various projects, such as robotics and home
automation.
Arduino IDE — an open-source prototyping platform, which can be used to easily write code
compatible with any Arduino board.
Arduino Cloud — a single platform that enables the wireless communication of IoT devices, as
well as their remote control and data collection.
IoT Cloud Remote — an application for creating dashboards to control cloud-connected devices.
2. Flutter
Another hardware product for IoT solutions is Flutter — a programmable processor core. The
board is based on Arduino, has a powerful ARM processor, built-in battery charging and a
security chip. A long-range wireless transmitter makes this board the perfect fit for wireless
networks of sensors.
Flutter offers:
Basic control module,Pro control module,Complete kits (Quick Start Kit, Vehicle Control Kits)
accessory boards (the Bluetooth adapter, the Breakout, the Remote Control, the Explorer),
3. Kinoma
Kinoma Create — a hardware platform for prototyping IoT devices. It’s powered by JavaScript
and has an integrated SD card, speaker, microphone, Bluetooth and Wi-Fi. It enables the
interaction of devices with cloud platforms via the WebSocket internet protocol.
Kinoma Studio — an integrated development environment (IDE) that provides the hardware
simulator and sensor library, allowing developers to create robust applications.
Kinoma Connect — an application for Android and iOS supporting IoT devices.
4. Tessel 2
To create connected devices, you can also use Tessel 2 — a programmable microcontroller
supporting JavaScript, Node.js libraries and other languages. It runs Linux and provides access to
many NPM modules with all their capabilities.
5. M2MLabs Mainspring
Raspberry Pi OS, formerly known as Raspbian, is the official operating system for the Raspberry
Pi hardware. A 32-bit version is available currently, with a 64-bit version in active development.
This is a free, Debian-based system. Raspberry includes basic programs and utilities to make the
hardware run, but it also compiles thousands of packages and pre-compiled software for easy
installation.
7. Node-RED
Node-RED is a free programming tool based on Node.js and designed to integrate distributed
IoT hardware and software systems and automate their interaction. It works primarily in Linux
environments but can be installed on Android and Windows as well (you’ll only need a Linux
subsystem for WIndows). Node-RED offers out-of-the-box repositories, interfaces for
connecting to MQTT, logic sets and format parsers, as well as the ability to write custom
components.
8. Eclipse IoT
A wide range of open-source projects for IoT development is gathered under the Eclipse
umbrella. They include software development platforms, frameworks, services, standards, tools
for building digital twins, fog computing and edge computing solutions, and many more. Eclipse
IoT projects focus on working with the Lua programming language, which is considered a good
fit for Internet of Things projects.
9. SiteWhere
SiteWhere is an open-source multi-tenant platform for building, deploying and supporting IoT
applications at the industrial level. The platform uses technologies such as the Docker
framework, Kubernetes, microservices and Apache Kafka. SiteWhere facilitates big data
transfer, storage, processing and integration, device management and event handling. You can
deploy SitePlatform locally or to the cloud platforms, including Azure, AWS, GCP.
10. DeviceHive
Real-time data analytics using the best data solutions such as Apache Spark and Kafka.
Home Assistant is a comprehensive home automation software system. This single center
integrates smart home devices, providing local control and security. Home Assistant offers
convenient mobile applications that enable the remote management of your devices and send
notifications if something goes wrong. You can also extend the functionality of this tool by
integrating it with additional apps.
12. OpenRemote
Open Remote is a platform you can use to create and manage IoT monitoring applications. The
primary domains leveraging the tool are smart city and mobility, energy management and asset
management.
The Things Board IoT platform uses MQTT, CoAP and HTTP protocols to connect devices and
handle data from them. Out-of-the-box configurable dashboards, charts, maps and widgets
provide you with robust real-time visualization of your data, which you can share with partners.
In addition, you can create custom widgets using the built-in editor.
Things Board Rule Engine allows you to create rule chains and event-based workflows for the
perfect match with your use case requirements. The platform can support multiple tenants and
millions of devices. Cloud and on-prem deployment is available. You can choose a monolithic
architecture for a small project or a microservices architecture for a highly scalable project.
14. MilesightDeviceHub
Milesight is a leading global provider of surveillance cameras, AI systems, IoT hardware and
software products. DeviceHub is among the company’s key software solutions. This is a
connectivity suite that enables the deployment of multiple devices, their real-time monitoring
and remote upgrading. With DeviceHub, you get comprehensive reports on monitored devices
and take insightful actions. Both the cloud and on-premises versions of the platform are
available.
15. Zetta
Zetta is a platform for designing APIs for IoT devices. The platform is based on Node.js and
combines reactive programming, WebSockets and REST APIs. A Zetta server can run in the
cloud or locally on hardware such as Raspberry Pi or Intel Edison.
The development process is simplified due to abstractions and direct access to protocols
and conventions. Visualization tools ensure the continuous monitoring of device behavior and
timely reaction to abnormalities. With Zetta, you can create data-intensive mobile, device and
cloud applications and integrate smaller systems into one coherent system.
1. Eclipse IoT:
2. Node-RED:
3. Arduino:
4. Tessel 2:
5. Kinomo Create:
6. OpenSCADA:
7. Raspbian:
8. Device Hive:
9. PlatformIO:
Rohini College of Engineering and Technology Department of ECE
Summary:
Rohini College of Engineering and Technology Department of ECE
The essential component of the embedded system is a RISC family microcontroller like
Motorola 68HC11, PIC 16F84, Atmel 8051 and many more. The most important factor
that differentiates these microcontrollers with the microprocessor like 8085 is their
internal read and writable memory. The essential embedded device components and
system architecture are specified below.
Rohini College of Engineering and Technology Department of ECE
In both activities, we can utilize the Python programming language for their
development. Or we can utilize a functional and practical edition of MicroPython in
order to work on devices with small computing resources, and accordingly, at a very
low price.
In the following tutorial, we will understand the use of Python in programming Internet
of Things (IoT) devices and create a backend for them to work.
But before we get to that, let us briefly discuss the importance of IoT.
Back in the day, we could explain IoT with examples as shown below:
"We can utilize the phone to turn a light bulb on and off in the room."
Nowadays, hardly anyone would be amazed by a smart electricity meter that transmits
readings of the consumption of the electricity, uploads that information to the cloud,
and produces monthly bills sent directly to the e-mail.
IoT is increasingly utilized across industries in order to streamline processes and make
them more efficient. For instance, manufacturing production lines and agriculture are
great examples of various industries taking benefit of the different features of IoT. In
the particular scenario of agriculture, IoT helps in coordinating harvesters with trucks
that have elevators to handle grains efficiently.
Rohini College of Engineering and Technology Department of ECE
Python is the coding language that we can use to reduce the volume of data that we
need to deal with, accessible in the cloud. Python recognizes the needs regardless of
whether we create the IoT project from scratch or interact with actuators, sensors, and
accessories.
Some of the many benefits of working with Python for IoT devices are a large number
of libraries for all types of platforms and the speed it offers at which we can develop
the code.
Python is a great ally for developing device prototypes. Even if we rewrite some of the
scripts while producing to C, C++ or Java to improve performance, the system will
generally function perfectly in Python.
1. Python on Raspberry Pi
2. Python on PyBoard
3. ESP8266, ESP32 with Micropython
Python on Raspberry Pi
The primary objective of running Python on an IoT device that pops up in mind is
grabbing the Raspberry Pi from the table. Python is pre-installed in the operating
system, and the only objective left for us is to write the coding script.
In this scenario, we can control the I/O ports on the expansion bar of the Raspberry Pi.
Fortunately, the board supports wireless communication (Bluetooth and WiFi) and
Ethernet. We can also connect a monitor to the HDMI output, a specialized 3.2"
320x240 TFT LCD, or a low energy consumption E-Ink 2.13" 250x122 display for
Raspberry Pi.
Rohini College of Engineering and Technology Department of ECE
AD
There are controllers available in a large variety of computing power and budgets. We
can choose these controllers for the IoT system - ranging from the fast Raspberry Pi 4
Model B 8 GB to the smallest Raspberry Pi Zero, all supporting the Python
programming language. In case of necessity, we can install the earlier version of Python
2.7 for past compatibility.
Let us consider the following snippet of Python code where we have used the GPIO
Zero library in order to control the I/O ports.
Example:
Explanation:
The above example demonstrates the receiving and processing of the signals by
pressing the button on the second pin at the moment of release.
AD
The benefits of utilizing this approach are the availability of a large variety of
development utilities, libraries and communications for the most complex devices
based on Raspberry Pi involving video processing from cameras.
Python on PyBoard
Another great solution for Python in IoT devices is the PyBoard with an STM32F405RG
microcontroller.
Rohini College of Engineering and Technology Department of ECE
The board's dimensions are impressive, taking up around two quarters, 33mm x 43mm
and weighing only 6 grams.
Once we installed Python on the system, we can use the pip installer in the command
line in order to install the esptool module. The syntax for the same is shown below:
Syntax:
The installation procedure of the MicroPython is pretty easy. We can download the
firmware from the website and install it with the help of esptool, not forgetting to
format the board before installing it.
We can also use one of the IDEs used for developing with MircoPython. The complete
procedure of development is carried out on a working computer, and then it is
compiled and saved in the memory of an ESP8266 or ESP32 microcontroller.
Let us consider the following example to see how simple the script might look like:
Example:
Explanation:
In the above snippet of code, we have imported the Pin module from
the machine library along with the time module. We have then created an object
of Pin and execute some functions on it.
AD
We can use Python as a Backend programming language for the Internet of Things in
many ways. Some of them are as follows:
The Python client library called Eclipse Paho MQTT implements versions 3.1, 3.1.1,
and 5.0 of the MQTT protocol.
The code of the Poho library offers a client class that allows applications to link to an
MQTT broker in order to publish messages, subscribe to topics, and receive published
messages. It also delivers some helper functions to make things simpler in publishing
one-off messages to MQTT servers.
Moreover, this library supports Python 2.7.9 and above or 3.5 and above. The
integration of images with older 2.7 versions of Python is straightforward.
We can start by deciding the requests we have to serve from the IoT devices. We then
have to set up the Flask microframework and write a block of code. The GET method
will then return information as per the request from the side of the client.
In several cases, we are best off focusing on the RESTful protocol while working with
the IoT devices. This allows us to simplify the exchange between the components of
the system and helps us to expand the system of exchanging information in the future.
Let us consider a task that has arisen as follows: Display information from IoT devices
on a web page. The Flask microframework will rescue us again with its core template
mechanism where we can design the required web page with the data display involving
graphics.
Rohini College of Engineering and Technology Department of ECE
The disadvantage of utilizing this method is the potential lack of starting the data
transfer from the server to the device. Thus, the IoT must periodically and
independently pull from the server. Rest easy, as there are keys to report this risk. We
can utilize web sockets or a Python library for Pushsafer. PushSafer is an easy and safe
way to send and receive push notifications in real-time to Android, iOS, and Windows
devices (mobile as well as desktop), including internet browsers such as Google
Chrome, Mozilla Firefox, Opera, and many more.
For instance, we can utilize Azure CLI 2.0 to build an Azure Virtual Machine or IoT Hub.
The extension of CLI allows an Azure service to complement Azure CLI by providing
users access to additional capabilities specified to services.
Azure CLI 2.0 allows instant management of resources of Azure IoT Hub, devices
provisioning services instances, and associated hubs. The new IoT extension enriches
Azure CLI 2.0 with features such as device management and all IoT Edge capabilities:
Hacks of Python
Following are some amazingly cool hacks of Python that can make work easy for
users and developers:
1. List Comprehensions: It is the best and efficient technique for getting rid of writing
pointless lines of program.
Output expression
Input sequence
A member of the input sequence represented by a variable
The optional predicate parts.
Example:
import functools as FT
List: [11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
ODD SQUARE WHICH IS DIVISIBLE BY 5: [25]
Filter negative numbers: [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
Maximum Number in the List:
110
2. Printing a List: Lists are not printed according to our requirements; they are always
printed in unnecessary square brackets and single quotes. But in Python, we have a
solution for printing lists efficiently by using the join method of string. The "join
method" can turn the list into a string by classifying every item into a string and
connecting them with the string on which the join method is used.
Example:
3. Transpose a Matrix: In Python, a user can implement the matrix as a nested list,
which means a list inside a list. Every element of the list is treated as a row of the
matrix.
Example:
print (row)
rez_1 = [[M_1[K][L] for K in range(len(M_1))] for L in range(len(M_1[0]))]
print ("\n")
print ("Matrix 2: ")
for row in rez_1:
print (row)
Output:
Matrix 1:
[5, 3]
[1, 2]
[9, 8]
Matrix 2:
[5, 1, 9]
[3, 2, 8]
4. artition of List into "N" Groups: The users can use the iter() function as an iterator
over the sequence.
Example:
List after partitioning into different of groups of two elements: [('E_1', 'E_2'), ('E_3',
'E_4'), ('E_5', 'E_6')]
Explanation:
In the above code, we used "[iter(LIST_1)] * 2" which produced different groups
containing two elements of the 'LIST_1[]' list. That is, the lists of length two will be
generated using the elements from the first list.
AD
Example:
# Here, we will use zip() function which will take 2 equal length list
# and then merge them together into pairs
for K, L in zip(list_1, list_2):
print (K, L)
Output:
11 12
13 14
15 16
17 18
6. Take the String as Input and Convert it into List:
Rohini College of Engineering and Technology Department of ECE
Example:
AD
Input:
10 12 14 16 18 20 22
Output as Formatted list: [10, 12, 14, 16, 18, 20, 22]
7. Convert List of Lists into Single List:
Example:
list_2 = list(IT.chain.from_iterable(LIST_1))
print ("Iterated list of 'LIST_1': ", list_2)
Output:
8. Print the Repeated Characters: Suppose our task is to print the patterns like
"122333444455555666666". We can easily print this pattern in Python without using
for loop.
Example:
122333444455555666666
Rohini College of Engineering and Technology Department of ECE
In addition, it has inputs and outputs for sensors so that you can attach
all sorts of hardware to it. The General Purpose Input/Output (GPIO) pins on
Raspberry Pi allow you to connect status lights, switches, analog signals,
and more. You can use C++ or Python to control the board to sense or control
devices attached to it.
Internet of Things
Creating an interactive environment
Sensor
Electronic element
Actuator
Mechanical/Electro-mechanical device
System Overview
Sensor and actuator interfaced with Raspberry Pi
Requirements
DHT Sensor
Relay
Jumper wires
Raspberry Pi
Mini fan
DHT Sensor
Digital Humidity and Temperature Sensor (DHT)
PIN 2- Data
PIN 3- Null
PIN 4 - Ground
Rohini College of Engineering and Technology Department of ECE
Relay
Mechanical/electromechanical switch
3 output terminals (left to right)
NO (normal open)
Common
NC (normal close)
Connect the GND (ground) pin of relay to the ground pin of Raspberry
Pi
“Businesses can easily run and control IoT applications like smart
home devices, weather stations, agricultural designs, and more using
Raspberry Pi”, she adds.