Internet of things , presentation, rajiv gandhi university

PulakMandal14 34 views 117 slides May 16, 2024
Slide 1
Slide 1 of 117
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117

About This Presentation

What Is an IoT Device?

It’s a physical object that connects to the Internet. It can be a fitness tracker, a thermostat, a lock or appliance – even a light bulb.

Imagine shoes that track your heartbeat… and can flag potential health problems. You don’t have to imagine – these “smart” ...


Slide Content

IoT(Internet of Things)
Dr. Rupam kr sharma
Asst. Professor(Sr), Dept. of Computer Applications

Course Outline
•Ovirview of Embedded system
•Overview vof IoT
•Components of IoT
•Introduction to Pi
•Basic operations of Pi
•Connecting Pi in a network
•Controlling a basic LED from Pi
•Introduction to python
•Controlling GPIO using python
•Understanding Basic Network
model(TCP)
•Communication between two
pi using sockets
•Understanding IoT broker
•Installing MQTT and using it
with Pi.
•Communication using MQTT
and CloudMQTT(Internet)
•Controlling sensors using Pi
•Introduction to Android app
development
•Controlling sensors using
Android app

Overview of Embedded system
Embeddedsystemisamicrocontrollerbased,
softwaredrivenreliablerealtimecontrolsystem
designedforperformingaspecifictask.
WhatisaSystem?
Allunitsassembledworktogetheraccordingto
certainsetofrules.
WhatisEmbedded?
Somethingattachedtoanother.Computer
Hardwaresystemwithsoftwareembeddedinit.

Components of Embedded
system
•Hardware
•Application software
•Real Time Operating System

Basic structure of an Embedded system

Basic types of processors..
•General Purpose Processor
•Microprocessor
•Microcontroller
•Embedded processor
•Digital signal processor
•Application specific system processor

Computer System

Block diagram of 8051

Rough register stack of x86

Your First Few Instructions
mov x, y x ← y
and x, yx ← x and y
or x, yx ← x or y
xor x, yx ← x xor y
add x, yx ← x + y
sub x, yx ← x –y
inc x x ← x + 1
dec x x ← x –1
syscallInvoke an operating system routine
db A pseudo-instruction that declares bytes that will be in
memory when the program runs

Structure of a NASM Program

What is IoT?
InternetofThings(IoT)isanecosystemof
connectedphysicalobjectsthatare
accessiblethroughtheinternet.
The‘thing’inIoTcouldbeapersonwith
aheartmonitororanautomobilewith
built-in-sensors,i.e.objectsthathavebeen
assignedanIPaddressandhavethe
abilitytocollectandtransferdataovera
networkwithoutmanualassistanceor
intervention.

IoT ELEMENTS

•Identification
•Naming
•Addressing
•Sensing:
•Collected information is sent to storage media
•actuators, RFID tags, smart sensors, wearable sensing devices, etc.
•Computation
•Used to remove unnecessary information that is not needed.
•Services
•Four types of services
•identity-related service. It is used to get the identity of objects that have sent the
request.
•Information aggregation is another service whose purpose is to collect all the
information from objects.
•The third service is a collaborative service that makes decisions according to the
collected information and sends appropriate responses to the devices.
•The last service is ubiquitous service, which is used to respond the devices immediately
without rigidity about time and place.

Three layered architecture

Common security threats of perception layer are:
Eavesdropping: Eavesdropping is an unauthorized real-time attack where private communications, such as phone calls,
text messages, fax transmissions or video conferences are intercepted by an attacker. It tries to steal information that is
transmitted over a network.
It takes advantage of unsecure transmission to access the information being sent and received.
Node Capture:It is one of the hazardous attacks faced in the perception layer of IoT. An attacker gains full control over a
key node, such as a gateway node. It may leak all information including communication between sender and receiver, a
key used to make secure communication and information stored in memory
Fake Node and Malicious: It is an attack in which an attacker adds a node to the system and inputs fake data. It aims to
stop transmitting real information. A node added by an attacker consumes precious energy of real nodes and potentially
control in order to destroy the network.
Replay Attack:It is also known as a play back attack. It is an attack in which an intruder eavesdrops on the conservation
between sender and receiver and takes authentic information from the sender

Network Layer:
Common security threats and problems to network layers are:
Denial of Service (DoS) Attack: A DoS attack is an attack to prevent authentic users from accessing devices or other
network resources. It is typically accomplished by flooding the targeted devices or network resources with redundant
requests in an order to make it impossible or difficult for some or all authentic users to use them
Main-in-The-Middle (MiTM) Attack: MiTM attack is an attack where the attacker secretly intercepts and alters the
communication between sender and receiver who believe they are directly communicating with each other
Storage Attack:The information of users is stored on storage devices or the cloud. Both storage devices and cloud can
be attacked by the attacker and user’s information may be changed to incorrect details. The replication of information
associated with the access of other information by different types of people provides more chances for attacks.
Exploit Attack:An exploit is any immoral or illegal attack in a form of software, chunks of data or a sequence of
commands. It takes advantage of security vulnerabilities in an application, system or hardware. It usually comes with the
aim of gaining control of the system and steals information stored on a network [

Application Layer
Common security threats and problem of application layer are:
Cross Site Scripting:It is an injection attack. It enables an attacker to insert a client-side script, such as java script in a
trusted site viewed other users. By doing so, an attacker can completely change the contents of the application according to
his needs and use original information in an illegal way.
Malicious Code Attack: It is a code in any part of software intended to cause undesired effects and damage to the system. It
is a type of threat that may not be blocked or controlled by the use of anti-virus tools. It can either activate itself or be like a
program requiring a user’s attention to perform an action.
The ability of dealing with Mass Data: Due to a large number of devices and a massive amount of data transmission
between users, it has no ability to deal with data processing according to the requirements. As a result, it leads to network
disturbance and data loss.

Support Layer:
The support layer has two responsibilities.
•It confirms that information is sent by theauthentic users and protected from threats. There are many ways
to verify the users and the information. The most commonly used method is the authentication. It is
implemented by using pre-shared secrets, keys and passwords.
•The second responsibility of the support layer issending information to the network layer. The medium to
transmit information from the support layer to network layer can be wireless and wire based.
•Common threats and problems of the support layer are
•DoS Attack: The DoS attack in a support layer is related to the network layer. An attacker sends a large
amount of data to make network traffic inundated. Thus, the massive consumption of system resources
exhausts the IoT and makes the user not capable of accessing the system.
•Malicious Insider Attack: It occurs from the inside of an IoT environment to access the personal
information of users. It is performed by an authorized user to access the information of other user. It is a
very different and complex attack that requires different mechanisms to prevent the threat

It is the responsibility of IoT to facilitate users by performing their tasks. It is the most important
element of IoT to fulfill its responsibilities. It acts like the brain of IoT. It gets all information and makes
appropriate decisions to send responses to the devices.

Five-layered Architecture

IoT stack

CLIENT
SENDS
REQUEST
TO SERVER
SERVER
Receives request
from client,
process request,
looks up/fetches
resources
prepares responds
and sends respondns
to client
Resources
Request
Response
Request -Response Communication Model

Publish and Subscribe Model

PUSH-PULL Communication Model

EXCLUSIVE PAIR COMMUNICATION MODEL

M2M System Architecture

M2M Gateway

Difference between M2M and IoT
Area IoT M2M
Communication Protocols Focus of communication in IoT is usually
on the protocols above the network
layer such as HTTP,CoAP,MQTT, etc.
Uses propreitary on non IP based
communication protocols for
communication within M2M networks.
eg. ZIGBEE,6LoWPAN,Bluetooth etc.
Machines in M2M vs things in IoTThings in IoT referes to physical objects
that have unique identifiers and can
sense and communicate with their
external environment or their internal
physical states. The unique identifiers
are the IP(or MAC). Things have software
components for accessing,processing
and storing sensor information.

Area IoT M2M
Hardware vs Software emphasis More on software More on Hardware
Data Collection and Analysis data collected on cloud Data collected in point solutions

COMMUNICATION WITH REST API

IoT Communication API
REST-Based Communication API (Representational State Transfer)
•Set of architectural principlas by which web services/API can be designed that focus
on system resources and how resources states are addressed and transferred.
•Follows the REQUEST-RESPONSE communication model.
•REST architectural constraints :
•Client-Server:
•Stateless
•Cache-able
•Layered System
•Uniform Interface
•Code on Demand

Client-Server:
Constraint of seperation of concerns.
Clients should not be concerned with storage of data which is a concern of server.
Server should not be concerned about the user interface which is a concern of client.
Seperation allows client and server to be independently developed
Stateless:
Each request from client to server must contain all the information necessary to understand the
request and cannot take advantage of any stored context on the server.
Cache-able:
Cache constraint requires that the data within a response to a request be implicitly or explicitly be
labeled as cache-abled or non-cache-abled.
If a response is cache-able,then a client-cache is given the right to reuse that response data for
later,equivalent requests.
Layered System:
constraints the behaviour of components such that each component cannot see beyond the
immediate layer with which they are interacting. For eg. a client cannot say if it is directly
connected to the end server or through an intermediate.

Uniform Interface:
Requires that the method of communication between a client and server is uniform.
Resources are identified in the requests.
Each message includes enough information to describe how to process the message.
Code on Demand:
Servers can provide executable code or scripts for clients to execute in their contexts.

REQUEST/RESPONSE MODEL USED IN REST

HTTP Request methods and actions

WEBSOCKET API

SDN and NFV for IoT

SDN Architecture

SDN Layers

Centralized Network Controller(CNC): With decoupled control and data planes and centralized
network controller , the network controller can rapidly configure the network.
SDN applications can be deployed through programmable open API.
Programmable Open API: SDN support programmable open API. for interface between SDN
application and control layers. With the open API various network services such as routing, QoS,
access control can be implemented.
Standard Communication Interface(OpenFlow):SDN uses a standard communication interface
between the control and infrastructure layers. OpenFLow which is defined by Open Networking
Foundation(ONF) is the broadly accepted protocol for the southbound interface.
With OpenFlow, the forwarding plane of the networking device can be directly accessed and
manipulated. OpenFlow uses the concept of flow to define network traffic based on pre-defined rules.
Flows can be programmed statically or dynamically by the SDN software.

Open Flow Switch

OPEN FLOW TABLE: Open FLow protocol is implemented on both sides of the interface between the controller
and the network device. The controller manages the switch via the open flow switch protocol. The controller can
add, update, delete flow entries in table.
Each flow table contains a set of flow entries. Each flow entries consists of match fields , counters and a set of
instructions to apply to matching packets.

Network Function Virtualization

NFV is a technology that leverages virtualization to consolidate the heterogenous network devices
onto industry standard high volume servers, switches and storage.
NFV is complimentay to SDNas NFV can provide infrastructure on which it runs. They are
mutually beneficial for each other but not dependent.
VNF: VNF is the software implementation of a network function which is capable of running over
the NVF Infrastructure(NVFI).
NVF Infrastructure(NVFI): NFVI includes compute,network and storage that are virtualized.
NFV Management and Orchestration:Focuses on all virtualization-specific management tasks and
covers the orchestration and life cycle management of physical and /or software resources that
support the infrastructure virtualization and the life cycle management of VNF.

Conventional Home Network Architecture

Home network with virtualized home gateway

IoT Platforms design methodology
•Important to design a generic design methodology independent of
specific product ,service or programming language.
•STEP 1:Purpose and Requirements specification:
•Define the purpose and requirements of the system(such as data collection
requirements,data analysis requirements,system management requirements,
data privacy and security requirements,user interface requirements).

Fig: Steps involved in the IoT system
design methodology

Process Specification: Here USE CASE of the system is formally described based and derived from purpose and
requirements specification.
Fig: Process specification for home
automation system

STEP 3:DOMAIN MODEL SPECIFICATION:
The domain model describes the main concepts, entities and objects in the domain of IoT system to be designed.
Domain model defines the attributes of the objects and the relationships between objects.
Defines the attributes of the objects and the relationships between objects.
Physical Entity: Identifiable entity in physical environment(eg. a room, a light, a car etc.) IoT system provides
information about physical entity using sensors. In home automation system two physical entities -one is the room
(of which lighting conditons to be monitored and other is the light appliance to be controlled.
Virtual Entity: Representation of physical entity in the digital world. For each physical entity there is a virtual entity
in the domain model.
Device: Provides a medium for interactions between physical entities and virtual entities. They are used to gather
information about physical entities.
Resource: Software components which can be either on device or network resources.
Service: Provides an interface for interacting with physical entities.

In HOME AUTOMATION there are three services:
1) Service that sets mode to auto or manual or retreives the current mode.
2) Service that sets the light appliance state to ON/OFF or retreives the current light state.
3) A controller service that runs as a native service on the device.
In AUTO Mode the controller service monitors the light level and swithches the light
ON/OFF and updates the status in the status database. In MANUAL mode,the controller
service retreives the current state from the database and switches the light ON/OFF.

STEP 4: Information model specification: Here Information model defines the structure of all information in
the IoT system. Eg. attributes of virtual entities , relations etc.
First the virtual entities are listed defined in the DOMAIN model. Later more details are added to the virtual
entities by adding attributes and relations.
In home automation there are two virtual entities -a virtual entity for light appliance ( with attribute light
and state) and a virtual entity for the room( with attribute light level)

Connecting to Pi connected locally
•ssh [email protected]

Making ready the working environment

Basic Circuit
GND
OUT of
PI

Putting the LED 'ON & OFF'
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
blinkCount=3
count=0
LEDPin=22
#setup the pin the Led is connected to
GPIO.setup(LEDPin,GPIO.OUT)
while count < blinkCount:
GPIO.output(LEDPin,True)
print("LED ON")
sleep(3)
GPIO.output(LEDPin,False)
print("LED off")
sleep(1)
count +=1

Download Link:https://www.arduino.cc/en/software

For uploading error: Cannot write to serial port

windows

In the lower-right part of the Arduino board, you’ll see six pins marked “Analog In”; these are special pins
that can tell us not only whether there is a voltage applied to them, but if so, also its value. By using the
analogRead() function, we can read the voltage applied to one of the pins. This function returns a number
between 0 and 1023, which represents voltages between 0 and 5 volts. For example, if there is a voltage of
2.5 V applied to pin number 0, analogRead(0) returns 512.

delay takes parameter in milliseconds i.e 1000ms=1sec

Connecting through a PUSH Button
WeconnectthreewirestotheArduinoboard.Thefirstgoesfromonelegofthepushbuttonthroughapull-up
resistor(here2.2KOhms)tothe5voltsupply.Thesecondgoesfromthecorrespondinglegofthepushbuttonto
ground.Thethirdconnectstoadigitali/opin(herepin7)whichreadsthebutton'sstate.
Whenthepushbuttonisopen(unpressed)thereisnoconnectionbetweenthetwolegsofthepushbutton,so
thepinisconnectedto5volts(throughthepull-upresistor)andwereadaHIGH.Whenthebuttonisclosed
(pressed),itmakesaconnectionbetweenitstwolegs,connectingthepintoground,sothatwereadaLOW.(The
pinisstillconnectedto5volts,buttheresistorin-betweenthemmeansthatthepinis"closer"toground.)

ULTRASONIC SENSOR

For example, if the object is 20 cm away from the sensor, and the speed of the sound is 340 m/s or 0.034
cm/µs the sound wave will need to travel about 588 microseconds. But what you will get from the Echo
pin will be double that number because the sound wave needs to travel forward and bounce backward. So
in order to get the distancein cm we need to multiply the received travel time value from the echo pin by
0.034 and divide it by 2.

1. First do the wiring as shown in the picture
2. Open Arduino IDE Software and write down your code, or download the code below and open it
3. Choose your own Arduino board (in this case Arduino Uno), by selecting Tools > Board > Arduino/Geniuno Uno
4. Choose your COM Port (usually it appears only one existing port), Tools > Port > COM.. (If there are more than
one ports, try it one by one)
5. Upload your code by pressing Ctrl + U or Sketch > Upload
6. To display the measurement data you can use Serial Monitor by pressing Ctrl + Shift + M (make sure that the
baudrate speed is 9600)
pulsein():Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to
go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the
pulse in microseconds or gives up and returns 0 if no complete pulse was received within the timeout.

#define echoPin 2// attach pin D9 Arduino to pin Echo of HC-SR04
#define trigPin 3//attach pin D8 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
}

void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}

int sensorPin = A0;
int sensorValue;
int limit = 300;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
Serial.println("Analog Value : ");
Serial.println(sensorValue);
if (sensorValue<limit) {
digitalWrite(13, HIGH);
}
else {
digitalWrite(13, LOW);
}
delay(1000);
}
Connecting moisture sensor to arduino

waterproof temperature sensor

Installing Library For DS18B20

This Dallas Temperature library is a hardware-specific library which handles lower-level functions. It needs to
be paired with One Wire Library to communicate with any one-wire device not just DS18B20. Install this
library as well.

#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into digital pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate
with any OneWire device
OneWire oneWire(ONE_WIRE_BUS);
// Pass oneWire reference to DallasTemperature library
DallasTemperature sensors(&oneWire);
void setup(void)
{
sensors.begin();// Start up the library
Serial.begin(9600);
}
void loop(void)
{
// Send the command to get temperatures
sensors.requestTemperatures();
//print the temperature in Celsius
Serial.print("Temperature: ");
Serial.print(sensors.getTempCByIndex(0));
Serial.print((char)176);//shows degrees character
Serial.print("C | ");
//print the temperature in Fahrenheit
Serial.print((sensors.getTempCByIndex(0) * 9.0) / 5.0 +
32.0);
Serial.print((char)176);//shows degrees character
Serial.println("F");
delay(500);
}

Arduino IR sensor
int IRSensor = 2; // connect ir sensor to arduino pin 2
int LED = 13; // conect Led to arduino pin 13
void setup()
{
pinMode (IRSensor, INPUT); // sensor pin INPUT
pinMode (LED, OUTPUT); // Led pin OUTPUT
}
void loop()
{
int statusSensor = digitalRead (IRSensor);
if (statusSensor == 1)
digitalWrite(LED, LOW); // LED LOW
}
else
{
digitalWrite(LED, HIGH); // LED High
}
}

4 digit 7 -segment display

import serial
import time
# Define the serial port and baud rate.
# Ensure the 'COM#' corresponds to what was seen in the Windows Device Manager
ser = serial.Serial('/dev/ttyACM2', 9600)
def led_on_off():
user_input = input()
user_input.strip()
if user_input =="on":
print("LED is on...")
time.sleep(0.1)
ser.write(b'H')
led_on_off()
elif user_input =="off":
print("LED is off...")
time.sleep(0.1)
ser.write(b'L')
led_on_off()
elif user_input =="quit" or user_input == "q":
print("Program Exiting")
time.sleep(0.1)
ser.write(b'L')
ser.close()
else:
print("Invalid input. Type on / off / quit.")
led_on_off()
time.sleep(2) # wait for the serial connection to initialize
led_on_off()
Python Ardudino Interaction to control LED

int data;
int LED=13;
String x;
int y;
void setup() {
Serial.begin(9600); //initialize serial COM at 9600 baudrate
pinMode(LED, OUTPUT); //declare the LED pin (13) as output
digitalWrite (LED, LOW); //Turn OFF the Led in the beginning
Serial.println("Hello!,How are you Python ?");
}
void loop() {
while (!Serial.available());
x = Serial.readString();
x.trim();
Serial.print(x[0]);
Serial.print("before if x");
Serial.print(x);
//Turn On the Led
if (x[0]=='H')
{
digitalWrite (LED, HIGH); //Turn
On the Led
Serial.print("true");
}
else if (x[0] =='L')
digitalWrite (LED, LOW);
//Turn OFF the Led
}

To Do Task
sand
7-segment
display
temperature
sensor
moisture
IR
ultrasonic

MQTT

sudo apt-get update sudo apt-get install mosquitto; sudo apt-get install mosquitto-clients

The architecture
MQTT BROKER(MAY
ALSO RUN ON A
CLOUD SERVER)
MQTT PUBLISHER(Commands ON or
OFF
MQTT SUBSCRIBER
LED
CIRCUIT
ssh [email protected]

MQTT SUBSCRIBER
importpaho.mqtt.clientasmqtt
fromblink2importblin
broker_url="192.168.60.252"
broker_port=1883
defon_connect(client,userdata,flags,rc):
print("ConnectedWithResultCode",rc)
defon_disconnect(client,userdata,rc):
print("ClientGotDisconnected")
defon_message(client,userdata,message):
strng=message.payload.decode()
print("Messagereceived"+strng)
blin(strng)
client=mqtt.Client()
client.on_connect=on_connect
client.on_message=on_message
client.connect(broker_url,broker_port)
client.subscribe("LED",qos=1)
client.loop_forever()

MQTT PUBLISHER
import paho.mqtt.client as mqtt
import sys
broker_url="192.168.60.252"
broker_port=1883
def on_connect(client, userdata, flags, rc):
print("Connected With Result Code " (rc))
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
client=mqtt.Client()
client.connect(broker_url,broker_port)
#If the connection is successful, you will see it output 0 on
the screen.
client.publish(topic="LED", payload=sys.argv[1], qos=0,
retain=False)
#client.loop_forever()
Running the code:
python mqttpub.py ON

Modified blink to blink2
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
LEDPin=22
#setup the pin the Led is connected to
GPIO.setup(LEDPin,GPIO.OUT)
def blin(param):
if param=="ON":
GPIO.output(LEDPin,True)
sleep(3)
elif param=="OFF":
GPIO.output(LEDPin,False)
print("LED off")
sleep(1)

MQTT & moisture sensor

Testing water content from PI
5v
GND
DO

import RPi.GPIO as GPIO
import time
#GPIO SETUP
channel = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(channel, GPIO.IN)
def callback(channel):
if GPIO.input(channel):
print "Water Detected!"
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH
or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change

Interfacing with MQTT
5v
GND
DO
Mqtt publisher
output
output
mqtt
subscriber

MQTT MOIST_PUBLISHER
import paho.mqtt.client as mqtt
import sys
import RPi.GPIO as GPIO
channel=16
msg="N"
broker_url="192.168.60.252"
broker_port=1883
def on_connect(client, userdata, flags, rc):
print("Connected With Result Code " (rc))
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
client=mqtt.Client()
client.connect(broker_url,broker_port)
#If the connection is successful,
you will see it output 0 on the screen.
GPIO.setmode(GPIO.BOARD)
GPIO.setup(channel,GPIO.IN)
def mycallback(channel):
global msg
if GPIO.input(channel):
msg="ON"
client.publish(topic="MOIST",payload=msg,qos=0,retain=Fa
lse)
print("ON")
else:
msg="OFF"
client.publish(topic="MOIST",payload=msg,qos=0,retain=Fa
lse)
print("OFF")
GPIO.add_event_detect(channel,GPIO.BOTH)
GPIO.add_event_callback(channel,mycallback)
#client.publish(topic="MOIST", payload=msg, qos=0,
retain=False)
client.loop_forever()

MQTT MOIST_SUBSCRIBER
import paho.mqtt.client as mqtt
from blink3 import blin
broker_url="192.168.60.252"
broker_port=1883
def on_connect(client, userdata, flags, rc):
print("Connected With Result Code ", rc)
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
def on_message(client, userdata, message):
strng=message.payload.decode()
print("Message received" + strng)
blin(strng)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker_url, broker_port)
client.subscribe("MOIST", qos=1)
client.loop_forever()

CloudMqtt
•From subscriber ubuntu terminal
•mosquitto_sub -h postman.cloudmqtt.com -p 14798 -t LED -u
xejupbki -P ReeIdW8jsAv0

Android Studio

Understanding Activity and Layout

Understanding Permissions

The first App-Hello world

Interacting App with Pi.
•https://medium.com/@gaikwadchetan93/android-real-time-
communication-using-mqtt-9ea42551475d
•except the service version in the build gradle

MQTT: Message Queuing Telemetry Transport

Atanytime,clientscansubscribetoandunsubscribefromoneormoretopicsbyconnectingtoabroker.Soifanew
industrialdeviceisinstalled(e.g.,anewreactor,“reactorX”),theIToperationswillhavetoconfigureitsIoTnodewith
theInternetProtocol(IP)addressandconnectiondetailsofthebroker.Whenbootingup,thenewIoTnodewill
announceitspresencetothebrokerandsubscribetotherequestedtopics.MQTTsubscribersandpublishersare
transientandcancomeandgoatanytime,andcouldreceiveold,queuedmessageswhentheycomebackonline.

CoAP: Constrained Application Protocol
CoAP is a client-server protocol, which means that the data exchange is initiated by a client node with a
request sent to a server node, which will answer with a response.
CoAP does not require the client to open or keep a connection to a server because it’s based on User
Datagram Protocol (UDP). At any time, a client can send one CoAP packet to a server.
Each request has a few options, with the most important one being the Uniform Resource Identifier (URI),
which indicates the “path” to the requested resource —much like Uniform Resource Locators (URLs) for
websites.
Note that a node could be both server and client at the same time, implementing a point-to-point, full-
duplex data layer.

Following the same example used in the MQTT description above, a client node could command
another node to, say, “turn on” or “execute a given task,” by sending a CoAP packet such as
“/station1/substation3/reactor3” with payload “on” . The CoAP server will interpret the URI, extract
the “on” payload, and decide what to do according to its logic. Depending on the request, the server could
reply with an acknowledgment, or just remain silent: Not all requests must be acknowledged.

Vulenerability in MQTT Implementation
•MQTT Vulnerability

Design Issues (MQTT)

Previousversionsofthestandardcontainedvulnerablepseudocodeexamplesasareferencefor
developers.Forexample,thecodeexampletoparsethe“remaininglength”fieldinpacketschanged
betweenversions3.18and3.1.19+errata,10goingfroma“nocheck”to“wrongcheck”andthen
to“correctcheck”.Thisturnedouttobeaninterestingpatterntolookfor,leadingustodiscovera
memoryerror(exploitabletoobtainaremotecodeexecutionprimitive)inrealMQTT
implementations.
Ontopofthis,theMQTTversion5.0specification11isnotentirelycompatiblewithprevious
versions,whichcoulddelayitsfutureadoptiondespitethesecurityimprovementsthatitbrings.

Unicode Handling in Topic Strings
Another interesting venue prone to error is the handling of topic strings. The first issue is that the
standard leaves it up to the developers’ choice to close the connection upon failing validation of
disallowed UTF-8 code points.
Tags