Internet of things , presentation, rajiv gandhi university
PulakMandal14
34 views
117 slides
May 16, 2024
Slide 1 of 117
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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” ...
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” shoes already exist!
How Will It Affect Me?
The Internet of Things has arrived and it’s going to introduce incredible opportunity over the next five years. And while smart things are exactly that, the IoT industry has a long way to go in terms of overall security. Many of today’s IoT devices are rushed to market with little consideration for basic security and privacy protections: “Insecurity by design.”
This puts you and everyone else at risk: from unwittingly being spied on or having your data compromised to being unable to lock your own home. You could even become part of a botnet that attacks the Internet. Your insecure webcam – along with millions of others – could be used to attack the power grid of an entire country.
From dental sensors that can monitor what a person eats to kitty litters that can track a cat’s every movement, it can be difficult to sort fact from fiction when it comes to the Internet of Things. Can you tell which is real and which is not?
Read More
Size: 2.99 MB
Language: en
Added: May 16, 2024
Slides: 117 pages
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)
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 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()
Interacting App with Pi.
•https://medium.com/@gaikwadchetan93/android-real-time-
communication-using-mqtt-9ea42551475d
•except the service version in the build gradle
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
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.