0% found this document useful (0 votes)
4 views105 pages

NS2 Communication Network Experiments

The document outlines a series of experiments conducted in the Communication Network Laboratory at Jadavpur University, focusing on various networking concepts using the NS2 simulator. It includes detailed instructions for setting up simulations involving node and link creation, data link layer protocols, cryptography, and communication protocols like MQTT and GSM. Additionally, it provides TCL code examples for executing these experiments and exercises for students to practice their skills.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views105 pages

NS2 Communication Network Experiments

The document outlines a series of experiments conducted in the Communication Network Laboratory at Jadavpur University, focusing on various networking concepts using the NS2 simulator. It includes detailed instructions for setting up simulations involving node and link creation, data link layer protocols, cryptography, and communication protocols like MQTT and GSM. Additionally, it provides TCL code examples for executing these experiments and exercises for students to practice their skills.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JADAVPUR UNIVERSITY

Kolkata – 700 032

DEPARTMENT OF
ELECTRONICS AND TELE-COMMUNICATION ENGINEERING

COMMUNICATION NETWORK LABORATORY

Name of the Student:_______________________________________________________

Roll Number: ________________________________________

Year: _____ Session: _______________________________ Semester: _____________

Teacher in-Charge: __________________________________________________________

Co-Workers:

Name Roll Number


LIST OF EXPERIMENTS
EXPT. DATE NAME OF THE EXPERIMENT TEACHERS’
No. INITIAL
1.A 1. INTRODUCTION TO NS2
Node and Link Creation using NS2

2. INTRODUCTION TO DATA LINK


1.B LAYER
To Study the Transmission of Packets over
Ethernet LAN, and to verify CSMA/CD
Protocol using NS2

3. INTRODUCTION TO NETWORK
1.C LAYER
Verification of Distance Vector Routing
Protocol using NS2

4. INTRODUCTION TO TRANSPORT
1.D LAYER
 To Study the performance of UDP
using NS2
 To Study the performance of TCP
using NS2
 To Study the performance of UDP
and TCP together using NS2

1.E ASSIGNMENT/ EXERCISE ON NS2

2. Implementation of PC to PC Serial
Communication using RS-232C Serial
Port

3.A CRYPTOGRAPHY
Implementation of RSA Algorithm

3.B CRYPTOGRAPHY
Implementation of RC4 Algorithm

4 To transmit and receive strings of Data /


Messages through MQTT Protocol using
HiveMQ and MQTTBox

5 Sending SMS using GSM module and


Arduino Uno Board

6 Networking Study Software using


Vi-RtSim
EXPT. DATE NAME OF THE EXPERIMENT TEACHERS’
No. INITIAL
6 Networking Study Software using
Vi-RtSim:
To create Scenario and Simulate:
(A) TCP/IP Protocol
(B) CSMA/CD Protocol
(C) CSMA/CA Protocol
(D) Token Bus Protocol
(E) Token Ring Protocol
(F) Distance Vector Routing Algorithm
(G) Link State Routing Algorithm

6 (H) To Study and Simulate Transmission types like


Multicasting, Broadcasting & Point-to-Point
Communication
1. INTRODUCTION TO NS2
Node and Link Creation using NS2
1.0 Introduction: In this section, you are going to develop a TCL script for ns which
simulates a simple topology. You are going to learn how to set up nodes and links, how
to send data from one node to another, how to monitor a queue and how to start NAM
file and TRACE file from your simulation script to visualize your simulation.

1.1 Introduction to nam and trace file

First of all, you need to create a simulator object. This is done with the command

set ns [new Simulator]

Now we open a file for writing that is going to be used for the nam trace data.

set nf [open [Link] w]


$ns namtrace-all $nf
The first line opens the file '[Link]' for writing and gives it the file handle 'nf'. In the
second line we tell the simulator object that we created above to write all simulation data
that is going to be relevant for nam into this file.

The next step is to add a 'finish' procedure that closes the trace file and starts nam.

proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec [Link]&
exit 0
}

The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of
simulation time.

$ns at 5.0 "finish"

The last line finally starts the simulation.

$ns run

1.2 How to run/execute the code


You can actually save the file now and try to run it with 'ns [Link]'. You are going to
get an error message like 'nam: empty trace file [Link]' though, because until now we
haven't defined any objects (nodes, links, etc.) or events.
Experiment 1A : Node and Link creation using NS2

In this section we are going to define a very simple topology with two nodes that are
connected by a link. The following two lines define the two nodes.

set n0 [$ns node]


set n1 [$ns node]

A new node object is created with the command '$ns node'. The above code creates two
nodes and assigns them to the handles 'n0' and 'n1'.

The next line connects the two nodes.

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with
the bandwidth 1Megabit, a delay of 10ms and a DropTail queue.

Now you can save your file and start the script with 'ns [Link]'. nam will be started
automatically and you should see an output that resembles the picture below.

Sending data
In ns, data is always being sent from one 'agent' to another. So the next step is to create an
agent object that sends data from node n0, and another agent object that receives the data
on node n1.

#Create a UDP agent and attach it to node


n0 set udp0 [new Agent/UDP] $ns attach-
agent $n0 $udp0
# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

These lines create a UDP agent and attach it to the node n0, then attach a CBR traffic
generator to the UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be self-
explaining. The packetSize is being set to 500 bytes and a packet will be sent every 0.005
seconds (i.e. 200 packets per second).

The next lines create a Null agent which acts as traffic sink and attach it to node n1.

set null0 [new Agent/Null]


$ns attach-agent $n1 $null0

Now the two agents have to be connected with each other.

$ns connect $udp0 $null0

And now we have to tell the CBR agent when to send data and when to stop sending. Note:
It's probably best to put the following lines just before the line '$ns at 5.0 "finish"'.

$ns at 0.5 "$cbr0 start"


$ns at 4.5 "$cbr0 stop"

This code should be self-explaining again.

Now you can save the file and start the simulation again. When you click on the 'play' button in
the nam window, you will see that after 0.5 simulation seconds, node 0 starts sending data
packets to node 1. You might want to slow nam down then with the 'Step' slider.
Problem Statement

Create two Nodes with duplex link,naming as Node 0 and Node 1, with
Bandwidth 1 Megabit, a delay of 10ms and a Drop Tail queue. Create UDP
agents and attach it to Node 0 and Node 1. Attach CBR traffic to UDP agent.
Set the packet size to 500 bytes and packet interval at0.005 s. In the time
interval, t = 0.05s to t= 2.0s Node 0 sends packets to Node 1 and similarly from
time interval t= 2.5 s to 5.0 s Node 1 sends packets to Node 0(keeping all
parameters same). Simulation stops at t = 5.5 s.

Solution to Problem

set ns [new Simulator]

setntrace [open [Link] w]


$ns trace-all $ntrace
setnamfile [open [Link] w]
$ns namtrace-all $namfile
proc finish {} {
global ns ntracenamfile
$ns flush-trace
close $ntrace
close $namfile
[Link]&
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set null0 [new Agent/UDP]
$ns attach-agent $n1 $null0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500 $cbr0 set
interval_ 0.005
$cbr0 attach-agent $udp0
$ns connect $udp0 $null0

set udp1 [new Agent/UDP]


$ns attach-agent $n1 $udp1
set null1 [new Agent/UDP]
$ns attach-agent $n0 $null1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500 $cbr1 set
interval_ 0.005
$cbr1 attach-agent $udp1
$ns connect $null1 $udp1

$ns at 0.5 "$cbr0 start"


$ns at 2.0 "$cbr1 start"
$ns at 2.5 "$cbr0 stop"
$ns at 5.0 "$cbr1 stop"
$ns at 5.5 "finish"

$ns run

Exercise:
ODD groups
 Set packet size = 1000
 Interval = .006
 Node 0 to Node 1 time interval = 0.3 s to 3 s
 Node 1 to Node 0 time interval = 3.5 s to 5s
 Stop the simulation at
5s. EVEN groups
 Set packet size = 800
 Interval = .008
 Node 0 to Node 1 time interval = 0.6 s to 2s
 Node 1 to Node 0 time interval = 2.5 s to 5s
 Stop the simulation at 5.5 s.

1.1 Conclusion

You have learned to create Nodes, links, define link type, setting time intervals
as per the requirement, starting and stopping of the simulation.

1.2 Reference
[a] TEL-WIMAX-NS2 project documentation [[Link]]
[b] [Link]
[c] Tutorial for the Network Simulator “ns” by Marc Greis
Introduction to Data Link layer

To Study the Transmission of Packets over Ethernet LAN and


to verify the CSMA/CD Protocol using NS2

2.1 CSMA/CD

This protocol, known as CSMA/CD (Carrier Sense Multiple Access with Collision
Detection), is the basis of the classic Ethernet LAN. It is important to realize that collision
detection is an analog process.
The station‟s hardware must listen to the channel while it is transmitting. If the signal it
reads back is different from the signal it is putting out, it knows that a collision is occurring.
The implications are that a received signal must not be tiny compared to the transmitted
signal (which is difficult for wireless, as received signals may be 1,000,000 times weaker
than transmitted signals) and that the modulation must be chosen to allow collisions to be
detected (e.g., a collision of two 0- volt signals may well be impossible to detect).
CSMA/CD, as well as many other LAN protocols, uses the conceptual model of Fig. At the
point marked t 0, a station has finished transmitting its frame.
Any other station having a frame to send may now attempt to do so. If two or more stations
decide to transmit simultaneously, there will be a collision. If a station detects a collision, it
aborts its transmission, waits a random period of time, and then tries again (assuming that
no other station has started transmitting in the meantime). Therefore, our model for
CSMA/CD will consist of alternating contention and transmission periods, with idle periods
occurring when all stations are quiet (e.g., for lack of work).

CSMA/CD can be contention, transmission or idle state


Experiment 1B :
To Study the Transmission of Packets over Ethernet LAN
and to verify CSMA/CD Protocol using NS2
########################### TCL CODE #############################

#Create Simulator
set ns [new Simulator]

#Use colors to differentiate the traffic


$ns color 1 Blue
$ns color 2 Red

#Open trace and NAM trace file


Set ntrace [open [Link] w]
$ns trace-all $ntrace
Set namfile [open [Link] w]
$ns namtrace-all $namfile
#Finish Procedure
proc Finish {} {
global ns ntracenamfile
#Dump all trace data and close the files
$ns flush-trace
close $ntrace
close $namfile
#Execute the nam animation file
execnam [Link] &
exit 0
}

#Create 6 nodes
for {set i 0} {$i< 6} {incr i} {
set n($i) [$ns node]
}

#Create duplex links between the nodes


$ns duplex-link $n(0) $n(2) 2Mb 10ms DropTail
$ns duplex-link $n(1) $n(2) 2Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 4Mb 100ms DropTail
Set lan [$ns newLan "$n(3) $n(4) $n(5)" 1Mb 40ms LL
Queue/DropTail MAC/csma/cd Channel]
$ns duplex-link-op $n(0) $n(2) orient right-down
$ns duplex-link-op $n(1) $n(2) orient right-up
$ns duplex-link-op $n(2) $n(3) orient right

$ns queue-limit $n(2) $n(3) 20


$ns duplex-link-op $n(2) $n(3) queuePos 0.5
set tcp0 [new Agent/TCP]
$tcp0 set fid_ 1
#$tcp0 set window_ 8000
$tcp0 set packetSize_ 552
$ns attach-agent $n(0) $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n(4) $sink0
$ns connect $tcp0 $sink0
#Apply FTP Application over TCP
set ftp0 [new Application/FTP]
$ftp0 set type_ FTP
$ftp0 attach-agent $tcp0
#Setup UDP Connection between n(1) and n(5)
set udp0 [new Agent/UDP]
$udp0 set fid_ 2
$ns attach-agent $n(1) $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
#Apply CBR Traffic over UDP
set cbr0 [new Application/Traffic/CBR]
$cbr0 set type_ CBR
$cbr0 set packetSize_ 1000
#$cbr0 set rate_ 0.1Mb
$cbr0 set random_ false
$cbr0 attach-agent $udp0
#Schedule events
$ns at 0.1 "$cbr0 start"
$ns at 1.0 "$ftp0 start"
$ns at 20.0 "$ftp0 stop"
$ns at 24.0 "$cbr0 stop"
$ns at 25.0 "Finish"
#Run Simulation
$ns run
########################### AWK CODE #############################

BEGIN {
recvdSize = 0;
startTime = 400;
stopTime = 0;
}
{
event = $1;
time = $2;
node_id = $3;
pkt_size = $8;
level = $4;
#Store start time
if(level ==”AGT” && event ==”s” &&pkt_size>= 512)
{ if (time <startTime) {
startTime = time;
}
}
#Update total received packet’s size ans store
packet’s arrival time
if(level ==”AGT” && event ==”r” &&pkt_size>= 512)
{ if (time >stopTime) {
stopTime = time;
}
#Rip off the header
hdr_size = pkt_size %512;
pkt_size -= hdr_size;
#store received packet’s size
recvdSize += pkt_size;
}
}
END {
printf("Average Throughput[kbps] = %0.2f \t\t StartTime = %0.2f
StopTime = %0.2f \n”, recvdSize/(stopTime- startTime)) *(8/1000),
startTime, stopTime);
}
Introduction to Network Layer

Distance Vector Routing using NS2

3.1 Distance Vector Routing

In distance vector routing, each router maintains a routing table indexed by, and containing
one entry for each router in the network. This entry has two parts: the preferred outgoing
line to use for that destination and an estimate of the distance to that destination. The
distance might be measured as the number of hops or using another metric, as we discussed
for computing shortest paths. The router is assumed to know the „„distance‟‟ to each of its
neighbors. If the metric is hops, the distance is just one hop. If the metric is propagation
delay, the router can measure it directly with special ECHO packets that the receiver just
timestamps and sends back as fast as it can.

As an example, assume that delay is used as a metric and that the router knows the delay to
each of its neighbors. Once every T msec, each router sends to each neighbor a list of its
estimated delays to each destination. It also receives a similar list from each neighbor.
Imagine that one of these tables has just come in from neighbor X, with Xi being X‟s
estimate of how long it takes to get to router i.
If the router knows that the delay to X is m msec, it also knows that it can reach router i via
X in Xi + m msec. By performing this calculation for each neighbor, a router can find out
which estimate seems the best and use that estimate and the corresponding link in its new
routing table.
Table1 : Initial distance stored at each node(Global view)

Table 2: Initial routing table of node A

Table 3: Final routing table of node A


Experiment 1C :
Verification of Distance Vector Routing using NS2
########################### TCL CODE #############################

set ns [new Simulator]

set nr [open [Link] w]


$ns trace-all $nr
Set nf [open [Link] w]
$ns namtrace-all $nf

proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
[Link]&
exit 0
}

for { set i 0 } { $i < 12} { incri 1 } {


set n($i) [$ns node]
}

for {set i 0} {$i < 8} {incr i} {


$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail
}
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail

set udp0 [new Agent/UDP]


$ns attach-agent $n(0) $udp0

set cbr0 [new Application/Traffic/CBR]


$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]

$cbr1 set packetSize_ 500

$cbr1 set interval_ 0.005


$cbr1 attach-agent $udp1

set null0 [new Agent/Null]


$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto DV

$ns rtmodel-at 10.0 down $n(11) $n(5)


$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)

$udp0 set fid_ 1


$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run

============================================================
Introduction to Transport layer

4.1 UDP

The User Datagram Protocol (UDP) provides a connectionless service for application-level
procedures.
Thus, UDP is basically an unreliable service; delivery and duplicate protection are not
guaranteed. However, this does reduce the overhead of the protocol and may be adequate in
many cases. An example of the use of UDP is in the context of network management.
The strengths of the connection-oriented approach are clear. It allows connection- related
features such as flow control, error control, and sequenced delivery.
Connectionless service, however, is more appropriate in some contexts. At lowerlayers
(internet, network), a connectionless service is more. In addition, it represents a “least
common denominator” of service to be expected at higher layers. Further, even at transport
and above there is justification for a connectionless [Link] are instances in which the
overhead of connection establishment and termination is unjustified or even
counterproductive.

Examples include the following:

• Request-response: Applications in which a transaction service is provided by a common


server to a number of distributed TS users, and for which a single request-response
sequence is typical. Use of the service is regulated at the application level, and lower-level
connections are often unnecessary and cumbersome.
• Real-time applications: Such as voice and telemetry, involving a degree of redundancy
and/or a real-time transmission requirement. These must not have connection-oriented
functions such as retransmission.
Thus, there is a place at the transport level for both a connection-oriented and a
connectionless type of service.

4.2 TCP

TCP is designed to provide reliable communication between pairs of processes (TCP users)
across a variety of reliable and unreliable networks and internets. TCP provides two useful
facilities forlabeling data: push and urgent.

TCP Mechanisms
We can group TCP mechanisms into the categories of connection establishment, data
transfer, and connection termination.
Experiment 1D :
(i) To Study the Performance of UDP using NS2
###############################TCL CODE################################
#Create a simulator object
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
setnf [open [Link] w]
$ns namtrace-all $nf

#Open the traffic trace file to record all events

setnd [open [Link] w]


$ns trace-all $nd
#Define a 'finish' procedure

proc finish {} {
global ns nfnd
$ns flush-trace
#Close the NAM trace file

close $nf
close $nd

#Execute NAM on the trace file

execnam [Link] &


exit 0
}

#Create six nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns color 1 Blue
$ns color 2 Red

$ns at 0.0 "$n0 label Sender"


$ns at 0.0 "$n1 label Sender"
$ns at 0.0 "$n2 label Sender"
$ns at 0.0 "$n3 label Sender"
$ns at 0.0 "$n5 label Receiver"

#Create links between the nodes

$ns duplex-link $n0 $n4 3Mb 10ms DropTail


$ns duplex-link $n1 $n4 3Mb 10ms DropTail
$ns duplex-link $n2 $n4 3Mb 10ms DropTail
$ns duplex-link $n3 $n4 3Mb 10ms DropTail
$ns duplex-link $n4 $n5 12Mb 20ms RED

#Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n5 $n4 8
#Give node position (for NAM)
$ns duplex-link-op $n0 $n4 orient right-down
$ns duplex-link-op $n1 $n4 orient right-down
$ns duplex-link-op $n2 $n4 orient right-up
$ns duplex-link-op $n3 $n4 orient right-up

#Monitor the queue for link (n2-n3). (for NAM)

$ns duplex-link-op $n4 $n5 queuePos 0.5

#$ns duplex-link-op $n0 $n2 queuePos 0.5

#$ns duplex-link-op $n1 $n2 queuePos 0.5

#Create a UDP agent and attach it to node


n0 set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500 $cbr0 set
interval_ 0.005
$cbr0 attach-agent $udp0

#Create a UDP agent and attach it to node


n1 set
udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1

# Create a CBR traffic source and attach it to udp1

set cbr1 [new Application/Traffic/CBR]


$cbr1 set packetSize_ 500 $cbr1 set
interval_ 0.005
$cbr1 attach-agent $udp1

#$ns attach-agent
$n1 $null0

#$udp0 set fid_ 1

#$udp1 set fid_ 2

#$udp0 set packetSize_ 500

#$udp1 set packetSize_ 500

#$udp0 set rate_ 1.0Mb

#$udp1 set rate_ 1.0Mb

#set sink0 [new Agent/UDPSink]


#set sink1 [new Agent/UDPSink]

set null0 [new Agent/Null]

$ns attach-agent $n3 $null0

set null1 [new Agent/Null]

$ns attach-agent
$n3 $null1
$ns connect $udp0 $null0
$ns connect $udp1 $null1

$ns at 0.0 "$cbr0 start"


$ns at 4.5 "$cbr0 stop"
$ns at 0.0 "$cbr1 start"
$ns at 4.5 "$cbr1 stop"
#Call the finish procedure after 5 seconds of simulation time

$ns at 5.0 "finish"

#Run the simulation

$ns run

(ii) To Study the Performance of TCP using NS2


###############################TCL CODE################################

#Create a simulator object

set ns [new Simulator]

#Define different colors for data flows (for NAM)

$ns color 1 Blue

$ns color 2 Red

#Open the NAM trace file

setnf [open [Link] w]

$ns namtrace-all $nf

#Open the traffic trace file to record all events

setnd [open [Link] w]

$ns trace-all $nd

#Define a 'finish' procedure


proc finish {} {

global ns nfnd

$ns flush-trace

#Close the NAM trace file

close $nf

close $nd

#Execute NAM on the trace file

execnam [Link] &

exit 0

#Create four nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

$ns color 1 Blue

$ns color 2 Red

$ns at 0.0 "$n0 label Sender"


$ns at 0.0 "$n1 label Sender"
$ns at 0.0 "$n3 label Receiver"
#Create links between the nodes

$ns duplex-link $n0 $n2 2Mb 10ms DropTail

$ns duplex-link $n1 $n2 2Mb 10ms DropTail

$ns duplex-link $n2 $n3 2Mb 20ms RED

#Set Queue Size of link (n2-n3) to 10

$ns queue-limit $n3 $n2 4


#Give node position (for NAM)

$ns duplex-link-op $n0 $n2 orient right-down

$ns duplex-link-op $n1 $n2 orient right-up

$ns duplex-link-op $n2 $n3 orient right

#Monitor the queue for link (n2-n3). (for NAM)

$ns duplex-link-op $n2 $n3 queuePos 0.5


#$ns duplex-link-op $n0 $n2 queuePos 0.5
#$ns duplex-link-op $n1 $n2 queuePos 0.5
#Setup a TCP connection
set tcp0 [new Agent/TCP]
set tcp1 [new Agent/TCP]
$tcp0 set fid_ 1
$tcp1 set fid_ 2
$tcp0 set packetSize_ 1000
$tcp1 set packetSize_ 1000
$tcp0 set rate_ 1.0Mb
$tcp1 set rate_ 1.0Mb
$ns attach-agent $n0 $tcp0
$ns attach-agent $n1 $tcp1
set sink0 [new Agent/TCPSink]
set sink1 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
$ns attach-agent $n3 $sink1
$ns connect $tcp0 $sink0

$ns connect $tcp1 $sink1

#Setup a FTP over TCP connection


set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1

$ns at 0.5 "$ftp0 start"

$ns at 4.5 "$ftp0 stop"

$ns at 1.0 "$ftp1 start"

$ns at 4.0 "$ftp1 stop"


#Call the finish procedure after 5 seconds of simulation time

$ns at 5.0 "finish"

#Run the simulation

$ns run

(iii) To Study the Performance of UDP and TCP together


using NS2
###############################TCL CODE################################

#Create a simulator object


set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
setnf [open [Link] w]
$ns namtrace-all $nf
setnd [open [Link] w]
$ns trace-all $nd
#Define a 'finish' procedure
proc finish {} {
global ns nfnd
$ns flush-trace
close $nd
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
[Link]&
exit 0
}
#Create four nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns color 1 Blue

$ns color 2 Red

$ns at 0.0 "$n0 label Sender"


$ns at 0.0 "$n1 label Sender"

$ns at 0.0 "$n3 label Receiver"


#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 4Mb 20ms DropTail
#Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 4
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
#Monitor the queue for link (n2-n3). (for NAM)
$ns duplex-link-op $n2 $n3 queuePos 0.5

#Setup a TCP connection


settcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

#Setup a UDP connection


setudp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2
#Setup a CBR over UDP connection
setcbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packetSize_ 1000

#Schedule events for the CBR and FTP


agents $ns at 0.0 " $cbr start" $ns at
10.0 "$ftp start"
$ns at 80.0 "$ftp stop"
$ns at 90.0 "$cbr stop"

#Call the finish procedure after 5 seconds of simulation


time $ns at 100.0 "finish"

#Run the simulation


$ns run

===================================================================

1. E. Assignment / Exercise

1. Repeat the experiment of DSR with 10 nodes, with defining shortest


path from Node0 to Node4. After half of the simulation time given to
you, down the link between Node2 and Node3. Again make the link up
after one fourth simulation time. Explain the meaning of each code
used in your program in detail.

2. Taking the number of nodes as 6 for ODD groups and 8 for EVEN groups
, packet size 500 for ODD groups and 800 for EVEN groups ,simulate all
three programs of experiment 1D with full explanation of each code used.

3. Explain the relevance of TRACE file with explaining all its parameters.

4. Explain the effect of Changing the packet size, bit rate etc.
National Semiconductor's 8250B UART

The UART chip has a total of 12 different registers that are mapped into 8 different Port I/O
locations.

RBR, receiver buffer register , THR, transmitter holding register ,

IER, interrupt enable register

IIR, interrupt identification register FCR, FIFO control register , LCR, line control register

MCR, modem control register , LSR, line status register , MSR, modem status register

SCR, scratch register , DLL, divisor latch LSB , DLM, divisor latch MSB

For a "typical" PC system, the following are the Port I/O addresses and IRQs for each serial
COM port:

Common UART IRQ and I/O Port Addresses


COM Port IRQ Base Port I/O address
COM1 IRQ4 $3F8
COM2 IRQ3 $2F8
COM3 IRQ4 $3E8
COM4 IRQ3 $2E8
Serial UART, an introduction
A UART, universal asynchronous receiver / transmitter is responsible for performing the
main task in serial communications with computers. The device changes incoming parallel
information to serial data which can be sent on a communication line. A second UART can
be used to receive the information. The UART performs all the tasks, timing, parity checking,
etc. needed for the communication. The only extra devices attached are line driver chips
capable of transforming the TTL level signals to line voltages and vice versa.

To use the UART in different environments, registers are accessible to set or review the
communication parameters. Settable parameters are for example the communication speed,
the type of parity check, and the way incoming information is signalled to the running
software.

Serial UART types


Serial communication on PC compatibles started with the 8250 UART in the IBM XT. In the years
after, new family members were introduced like the 8250A and 8250B revisions and the 16450. The
last one was first implemented in the AT. The higher bus speed in this computer could not be
reached by the 8250 series. The differences between these first UART series were rather minor. The
most important property changed with each new release was the maximum allowed speed at the
processor bus side.

The 16450 was capable of handling a communication speed of 38.4 kbs without problems.
The demand for higher speeds led to the development of newer series which would be able to
release the main processor from some of its tasks. The main problem with the original series
was the need to perform a software action for each single byte to transmit or receive. To
overcome this problem, the 16550 was released which contained two on-board FIFO buffers,
each capable of storing 16 bytes. One buffer for incoming, and one buffer for outgoing bytes.

A marvellous idea, but it didn't work out that way. The 16550 chip contained a firmware bug
which made it impossible to use the buffers. The 16550A which appeared soon after was the
first UART which was able to use its FIFO buffers. This made it possible to increase
maximum reliable communication speeds to 115.2 kbs. This speed was necessary to use
effectively modems with on-board compression. A further enhancement introduced with the
16550 was the ability to use DMA, direct memory access for the data transfer. Two pins were
redefined for this purpose. DMA transfer is not used with most applications. Only special
serial I/O boards with a high number of ports contain sometimes the necessary extra circuitry
to make this feature work.

The 16550A is the most common UART at this moment. Newer versions are under
development, including the 16650 which contains two 32 byte FIFO's and on board support
for software flow control. Texas Instruments is developing the 16750 which contains 64 byte
FIFO's.
Registers
Eight I/O bytes are used for each UART to access its registers. The following table shows, where each
register can be found. The base address used in the table is the lowest I/O port number assigned.
The switch bit DLAB can be found in the line control register LCR as bit 7 at I/O address base + 3.

UART register to port conversion table


DLAB = 0 DLAB = 1
I/O port Read Write Read Write
base RBR THR DLL divisor latch LSB
receiver transmitter
buffer holding
base + 1 IER IER DLM divisor latch MSB
interrupt interrupt
enable enable
base + 2 IIR FCR IIR FCR
interrupt FIFO interrupt FIFO
identification control identification control
base + 3 LCR line control
base + 4 MCR modem control
base + 5 LSR – LSR –
line factory line factory
status test status test
base + 6 MSR – MSR –
modem not modem not
status used status used
base + 7 SCR scratch
Available registers

RBR, receiver buffer register

THR, transmitter holding register

IER, interrupt enable register

IIR, interrupt identification register

FCR, FIFO control register

LCR, line control register

MCR, modem control register

LSR, line status register

MSR, modem status register

SCR, scratch register

DLL, divisor latch LSB

DLM, divisor latch MSB


The communication between the processor and the UART is completely controlled by twelve
registers. These registers can be read or written to check and change the behaviour of the
communication device. Each register is eight bits wide. On a PC compatible, the registers are
accessible in the I/O address area. The function of each register will be discussed here in
detail.

RBR : Receiver buffer register (RO)


The RBR, receiver buffer register contains the byte received if no FIFO is used, or the oldest unread
byte with FIFO's. If FIFO buffering is used, each new read action of the register will return the next
byte, until no more bytes are present. Bit 0 in the LSR line status register can be used to check if all
received bytes have been read. This bit wil change to zero if no more bytes are present.

THR : Transmitter holding register (WO)


The THR, transmitter holding register is used to buffer outgoing characters. If no FIFO buffering is
used, only one character can be stored. Otherwise the amount of characters depends on the type of
UART. Bit 5 in the LSR, line status register can be used to check if new information must be written
to THR. The value 1 indicates that the register is empty. If FIFO buffering is used, more than one
character can be written to the transmitter holding register when the bit signals an empty state.
There is no indication of the amount of bytes currently present in the transmitter FIFO.

The transmitter holding register is not used to transfer the data directly. The byte is first
transferred to a shift register where the information is broken in single bits which are sent one
by one.

IER : Interrupt enable register (R/W)


The smartest way to perform serial communications on a PC is using interrupt driven routines. In
that configuration, it is not necessary to poll the registers of the UART periodically for state changes.
The UART will signal each change by generating a processor interrupt. A software routine must be
present to handle the interrupt and to check what state change was responsible for it.

Interrupts are not generated, unless the UART is told to do so. This is done by setting bits in
the IER, interrupt enable register. A bit value 1 indicates, that an interrupt may take place.

IER : Interrupt enable register


Bit Description
0 Received data available
1 Transmitter holding register empty
2 Receiver line status register change
3 Modem status register change
4 Sleep mode (16750 only)
5 Low power mode (16750 only)
6 reserved
7 reserved

IIR : Interrupt identification register (RO)

A UART is capable of generating a processor interrupt when a state change on the


communication device occurs. One interrupt signal is used to call attention. This means, that
additional information is needed for the software before the necessary actions can be
performed. The IIR, interrupt identification register is helpful in this situation. Its bits show
the current state of the UART and which state change caused the interrupt to occur.

IIR : Interrupt identification register


Bit Value Description Reset by
0 0 Interrupt pending –
1 No interrupt pending –
1,2,3 Bit 3 Bit 2 Bit 1
0 0 0 Modem status change MSR read
0 0 1 Transmitter holding register empty IIR read or THR write
0 1 0 Received data available RBR read
0 1 1 Line status change LSR read
1 1 0 Character timeout (16550) RBR read
4 0 Reserved –
5 0 Reserved (8250, 16450, 16550) –
1 64 byte FIFO enabled (16750) –
6,7 Bit 7 Bit 6
0 0 No FIFO –
1 0 Unusable FIFO (16550 only) –
1 1 FIFO enabled –

FCR : FIFO control register (WO)

The FCR, FIFO control register is present starting with the 16550 series. This register
controls the behaviour of the FIFO's in the UART. If a logical value 1 is written to bits 1 or 2,
the function attached is triggered. The other bits are used to select a specific FIFO mode.

FCR : FIFO control register


Bit Value Description
0 0 Disable FIFO's
1 Enable FIFO's
1 0 –
1 Clear receive FIFO
2 0 –
1 Clear transmit FIFO
3 0 Select DMA mode 0
1 Select DMA mode 1
4 0 Reserved
5 0 Reserved (8250, 16450, 16550)
1 Enable 64 byte FIFO (16750)
6,7 Bit 7 Bit 6 Receive FIFO interrupt trigger level
0 0 1 byte
0 1 4 bytes
1 0 8 bytes
1 1 14 bytes
LCR : Line control register (R/W)

The LCR, line control register is used at initialisation to set the communication parameters.
Parity and number of data bits can be changed for example. The register also controls the
accessibility of the DLL and DLM registers. These registers are mapped to the same I/O port
as the RBR, THR and IER registers. Because they are only accessed at initialisation when no
communication occurs this register swapping has no influence on performance.

LCR : line control register


Bit Value Description
0,1 Bit 1 Bit 0 Data word length
0 0 5 bits
0 1 6 bits
1 0 7 bits
1 1 8 bits
2 0 1 stop bit
1 1.5 stop bits (5 bits word)
2 stop bits (6, 7 or 8 bits word)
3,4,5 Bit 5 Bit 4 Bit 3
x x 0 No parity
0 0 1 Odd parity
0 1 1 Even parity
1 0 1 High parity (stick)
1 1 1 Low parity (stick)
6 0 Break signal disabled
1 Break signal enabled
7 0 DLAB : RBR, THR and IER accessible
1 DLAB : DLL and DLM accessible

Some remarks about parity:

The UART is capable of generating a trailing bit at the end of each dataword which can be
used to check some data distortion. Because only one bit is used, the parity system is capable
of detecting only an odd number of false bits. If an even number of bits has been flipped, the
error will not be seen.

When even parity is selected, the UART assures that the number of high bit values in the sent
or received data is always even. Odd parity setting does the opposite. Using stick parity has
very little use. It sets the parity bit to always 1, or always 0.

Common settings are:

 8 data bits, one stop bit, no parity


 7 data bits, one stop bit, even parity

MCR : Modem control register (R/W)

The MCR, modem control register is used to perform handshaking actions with the attached
device. In the original UART series including the 16550, setting and resetting of the control
signals must be done by software. The new 16750 is capable of handling flow control
automatically, thereby reducing the load on the processor.

MCR : Modem control register


Bit Description
0 Data terminal ready
1 Request to send
2 Auxiliary output 1
3 Auxiliary output 2
4 Loopback mode
5 Autoflow control (16750 only)
6 Reserved
7 Reserved

The two auxiliary outputs are user definable. Output 2 is sometimes used in circuitry which
controls the interrupt process on a PC. Output 1 is normally not used, however on some I/O
cards, it controls the selection of a second oscillator working at 4 MHz. This is mainly for
MIDI purposes.

LSR : Line status register (RO)

The LSR, line status register shows the current state of communication. Errors are reflected in
this register. The state of the receive and transmit buffers is also available.

LSR : Line status register


Bit Description
0 Data available
1 Overrun error
2 Parity error
3 Framing error
4 Break signal received
5 THR is empty
6 THR is empty, and line is idle
7 Errornous data in FIFO

Bit 5 and 6 both show the state of the transmitting cycle. The difference is, that bit 5 turns
high as soon as the transmitter holding register is empty whereas bit 6 indicates that also the
shift register which outputs the bits on the line is empty.

MSR : Modem status register (RO)

The MSR, modem status register contains information about the four incoming modem
control lines on the device. The information is split in two nibbles. The four most significant
bits contain information about the current state of the inputs where the least significant bits
are used to indicate state changes. The four LSB's are reset, each time the register is read.
MSR : Modem status register
Bit Description
0 change in Clear to send
1 change in Data set ready
2 trailing edge Ring indicator
3 change in Carrier detect
4 Clear to send
5 Data set ready
6 Ring indicator
7 Carrier detect

SCR : Scratch register (R/W)

The SCR, scratch register was not present on the 8250 and 8250B UART. It can be used to
store one byte of information. In practice, it has only limited use. The only real use I know of
is checking if the UART is a 8250/8250B, or a 8250A/16450 series. Because the 8250 series
are only found in XT's even this use of the register is not commonly seen anymore.

DLL and DLM : Divisor latch registers (R/W)

For generating its timing information, each UART uses an oscillator generating a frequency
of about 1.8432 MHz. This frequency is divided by 16 to generate the time base for
communication. Because of this division, the maximum allowed communication speed is
115200 bps. Modern UARTS like the 16550 are capable of handling higher input frequencies
up to 24 MHz which makes it possible to communicate with a maximum speed of 1.5 Mbps.
On PC's higher frequencies than the 1.8432 MHz are rarely seen because this would be
software incompatible with the original XT configuration. This 115200 bps communication
speed is not suitable for all applications. To change the communication speed, the frequency
can be further decreased by dividing it by a programmable value. For very slow
communications, this value can go beyond 255. Therefore, the divisor is stored in two
seperate bytes, the divisor latch registers DLL and DLM which contain the least, and most
significant byte. For error free communication, it is necessary that both the transmitting and
receiving UART use the same time base. Default values have been defined which are
commonly used. The table shows the most common values with the appropriate settings of
the divisor latch bytes. Note that these values only hold for a PC compatible system where a
clock frequency of 1.8432 MHz is used.

DLL and DLM : Divisor latch registers


Speed (bps) Divisor DLL DLM
50 2,304 0x00 0x09
300 384 0x80 0x01
1,200 96 0x60 0x00
2,400 48 0x30 0x00
4,800 24 0x18 0x00
9,600 12 0x0C 0x00
19,200 6 0x06 0x00
38,400 3 0x03 0x00
57,600 2 0x02 0x00
115,200 1 0x01 0x00
Ex. No.4 To Transmit and Receive strings of Data / Messages
through MQTT Protocol using HiveMQ and MQTTBox

Introduction
MQTT stands for Message Queuing Telemetry [Link] was invented by Dr Andy Stanford-
Clark of IBM, and Arlen Nipper of Arcom (now Eurotech), in 1999. It is a publish/subscribe, extremely
simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-
latency or unreliable networks. The design principles are to minimise network bandwidth and device
resource requirements whilst also attempting to ensure reliability and some degree of assurance of
delivery. These principles also turn out to make the protocol ideal of the emerging “machine-to-machine”
(M2M) or “Internet of Things” world of connected devices, and for mobile applications where bandwidth
and battery power are at a premium.

Theory
The protocol uses a publish/subscribe architecture in contrast to HTTP with its request/response
paradigm. Publish/Subscribe is event-driven and enables messages to be pushed to clients. The central
communication point is the MQTT broker, it is in charge of dispatching all messages between the senders
and the rightful receivers. Each client that publishes a message to the broker, includes a topic into the
message. The topic is the routing information for the broker. Each client that wants to receive messages
subscribes to a certain topic and the broker delivers all messages with the matching topic to the client.
Therefore, the clients don’t have to know each other, they only communicate over the topic. This
architecture enables highly scalable solutions without dependencies between the data producers and the
data consumers.
The difference to HTTP is that a client doesn’t have to pull the information it needs, but the broker pushes
the information to the client, in the case there
is something new. Therefore, each MQTT
client has a permanently open TCP
connection to the broker. If this connection is
interrupted by any circumstances, the MQTT
broker can buffer all messages and send them
to the client when it is back online. As
mentioned before the central concept in
MQTT to dispatch messages are topics.
Because MQTT decouples the publisher from the subscriber, client connections are always handled by a
broker.
Client
MQTT client: Both publishers and subscribers are MQTT clients. The publisher and subscriber labels
refer to whether the client is currently publishing messages or subscribing to messages (publish and
subscribe functionality can also be implemented in the same MQTT client). An MQTT client is any
device (from a micro controller up to a full-fledged server) that runs an MQTT library and connects to an
MQTT broker over a network. For example, the MQTT client can be a very small, resource-constrained
device that connects over a wireless network and has a bare-minimum library. The MQTT client can also
be a typical computer running a graphical MQTT client for testing purposes. Basically, any device that
speaks MQTT over a TCP/IP stack can be called an MQTT client. The client implementation of the
MQTT protocol is very straight forward and streamlined. The ease of implementation is one of the
reasons why MQTT is ideally suited for small devices. MQTT client libraries are available for a huge
variety of programming languages. For example, Android, Arduino, C, C++, C#, Go, iOS, Java,
JavaScript, and .NET.
Broker
The counterpart of the MQTT client is the MQTT broker. The broker is at the heart of any
publish/subscribe protocol. Depending on the implementation, a broker can handle up to thousands of
concurrently connected MQTT clients. The broker is responsible for receiving all messages, filtering the
messages, determining who is subscribed to each message, and sending the message to these subscribed
clients. The broker also holds the sessions of all persisted clients, including subscriptions and missed
messages (more details). Another responsibility of the broker is the authentication and authorization of
clients. Usually, the broker is extensible, which facilitates custom authentication, authorization, and
integration into backend systems. Integration is particularly important because the broker is frequently the
component that is directly exposed on the internet, handles a lot of clients, and needs to pass messages to
downstream analyzing and processing systems. In brief, the broker is the central hub through which every
message must pass.
Here we use HiveMQ as a broker and MQTTBox to set-up and manage clients.
MQTT Client Settings:
When creating new MQTT client from MQTTBox app, there are wide range of connection settings one
can specify. Most of the settings are set by default to most used values, however they are customisable
and the terms are explained below:
1. MQTT Client Name:
Name to identify MQTT client and display on dashboard. It can be any string value.
e.g.: client_test_1
2. Client Id:
The client identifier is an identifier of each MQTT client connecting to a MQTT broker. It should be
unique per client for given broker. The broker uses it for identifying the client and the current state of the
client. It is auto generated by default. Trying to connect two MQTT clients with same client identifier,
connection will be rejected by broker. If 2 instances of MQTTBox app are open, it must be made sure
they have unique client id's otherwise the clients will be rejected by broker and may show offline.
e.g.: client_id_1
3. Append timestamp to MQTT client id?
If checked, timestamp will be appended to client Id. This is enabled by default. Many a times, users open
multiple instances of MQTTBox app on same or different machines with same MQTT client settings
including same client id unknowingly. This causes both client connections to be rejected by broker
because of same client id. If this option is enabled, MQTTBox will append timestamp to every client id
making it almost unique which helps save time debugging unnecessary issues.
4. Broker is MQTT v3.1.1 compliant?
If you are connecting to a MQTT broker that only supports older versions of MQTT protocol 3.1 or less
(v3.1.1 is latest and current standard), you should un-check this option. By default, it is checked and
assumes MQTT broker is compliant with current MQTT standard v3.1.1 (or higher).
5. Protocol:
Network protocol used by MQTT client to connect with MQTT broker.
MQTTBox supports TCP, SSL/TLS, MQTT, MQTTS, WebSockets (WS) and Secure WebSockets
(WSS). Depending on the platform, all Protocol may not be supported because of platform limitations.
(For this experiment, TCP/IP will be used.)
6. Host:
MQTT host to connect. One needs to specify right host and port number depending on MQTT connection
protocol selected. MQTT client may not get connected if wrong port number is mentioned or port
numbers are interchanged.
e.g.: [Link]
7. Clean Session?
The clean session flag indicates the broker whether the client wants to establish a persistent session or not.
If you need a persistent session, meaning, that the broker will store all subscriptions for the client and also
all missed messages, when subscribing with Quality of Service (QoS) 1 or 2, un-check/No this option. By
default, this is checked or Yes, which means broker will start new session, won’t store anything for the
client and will also purge all information from a previous persistent session.
8. Auto connect on app launch?
If you check Yes, this option, client will try to connect to broker automatically when MQTTBox app is
launched and can be in "Connected", or "Connection Error" state depending on if client was connected to
broker or not. If un-checked/No this option, client will be in "Not connected" state and you need to
manually connect client to broker.
9. Username:
Username required by broker, if any. MQTT allows to send username for authenticating and authorization
of client.
10. Password:
Password required by broker, if any. MQTT allows to send password for authenticating and authorization
of client. Please note, all passwords are saved in plain text. Make sure you never save production
passwords inside MQTTBox app. In fact, all fields are saved as plain text, make sure you never save any
sensitive information/settings inside MQTTBox app.
11. Reschedule Pings?
If checked/yes, reschedules ping messages after sending packets.
12. Queue outgoing QoS zero messages:
If checked yes, if connection is broken between client and broker, client queue's outgoing QoS zero
messages. All these messages will be published when connection is established.
13. Reconnect Period (in milliseconds):
Interval between two reconnections
14. Connect Timeout (in milliseconds):
Time to wait before a CONNACK is received
15. KeepAlive (in seconds):
The keep alive is a time interval, the clients commits to by sending regular PING Request messages to the
broker. The broker response with PING Response and this mechanism will allow both sides to determine
if the other one is still alive and reachable. By default, it is set to 10 seconds. Set to 0 to disable.
16. Will Settings:
The will message is part of the last will of MQTT Client. It allows to notify other clients, when a client
disconnects ungracefully. A connecting client will provide his will in form of an MQTT message and
topic in the CONNECT message. If the client gets disconnected ungracefully, the broker sends this
message on behalf of the client automatically.
16.1 Will Settings - Topic: The topic to publish will payload. A simple string, which can have
hierarchically structured with forward slashes as delimiters.
e.g.: topic_test_1 or home/kitchen/humidity
16.2 Will Settings - QoS: Publish payload with QoS set. By default, it is 0.
16.3 Will Settings - Retain: Retain flag for will payload.
16.4 Will Settings - Payload: The message to publish when the client disconnects badly.

Publisher Settings:
1. Topic to publish: is the topic to publish to. A simple string, which can have hierarchically structured
with forward slashes as delimiters.
e.g.: topic_test_1 or home/kitchen/humidity
2. QoS: A Quality of Service Level (QoS) for this message. The level (0,1 or 2) determines the guarantee
of a message delivered.
3. Retain: This flag determines if the message will be saved by the broker for the specified topic as last
known good value. New clients that subscribe to that topic will receive the last retained message on that
topic instantly after subscribing.
To delete retain message of topic, send a retained message with a zero byte payload on that topic.
4. Payload: This is the actual content of the message to publish to topic.

Subscriber settings:
Topic: is a String topic to subscribe to. You can specify Single Level(+) and Multilevel(#) subscription to
topics.
e.g.: topic_test_1 or home/+/humidity or home/#
QoS: A Quality of Service Level (QoS) for this message. The level (0,1 or 2) determines the guarantee of
a message delivered.
For further reading:
[Link]
Software Requirements
Although the hardware requirements for this does not extend beyond a simple PC running Windows or
Linux and an internet connection, there are a few software requirements to get started.
1. Environment: Java - OpenJDK JRE/JDK 11 or newer is required.
2. MQTT Broker: HiveMQ is being used in this case. (Some alternatives are Mosquitto, Mosca, emqttd,
Python Test Broker, VerneMQ)
3. MQTTBox: This helps create MQTT clients to publish or subscript topics, create MQTT virtual device
networks, load test MQTT devices or brokers and offers some additional features.
Setting up and testing:
1. Java Runtime Environment: Download and install a compatible version of JRE
2. HiveMQ broker:
2.1. Download the HiveMQ zip file from [Link]
2.2. Unzip the file
2.3. Open the “[Link]” file in the directory ~\hivemq-4.1.0\hivemq-4.1.0\conf (using any standard
text editors)
2.4. Change the IP under “bind-address” from <[Link]> to the IP of your computer
2.5. Go to ~\hivemq-4.1.0\hivemq-4.1.0\bin and run the “[Link]” as administrator

3. MQTTBox app:
3.1. It can be installed from the Windows Store itself. Alternatively one can download the installer
file from their website [Link] which comes
with instructions to install for non-Windows systems as well.
3.2. Once installed, launch the app and click on “Create MQTT Client” inside the app and follow the
steps given below for a basic setup with minimal customization:
3.2.1. Fill in a name under “MQTT Client Name”
3.2.2. Change the protocol to “mqtt/tcp” from the drop-down menu
3.2.3. Fill in a topic name under “Will-Topic” (optional)
3.2.4. Change the “Host” to the IP of your machine (or in the case of multiple machines, the
machine acting as “publisher” will put their own IP and the machines acting as
“subscribers” will put the IP of the “publisher”) and click on save
3.3. Once a MQTT client is created, two boxes will appear one for the publisher and one for the
subscriber.
3.4. Publisher setup:
3.4.1. Give a topic name in the box designated to “topic to publish”
3.4.2. Check the “retain” box
3.4.3. Under “Payload” type the message you wish to send
3.4.4. Before hitting “publish” make sure at least one person is subscribed to the same topic as
you are publishing in order to verify that it is working
3.5. Subscriber setup:
3.5.1. Under “topic” fill in the topic of interest and set the corresponding QoS accordingly and
click on “Subscribe”.
3.5.2. You may type a message from the publisher window and check if it is working now.
An example flow diagram:
Observations:

Conclusions:

Assignments:
1. Publish DHT sensor data using Arduino Uno through MQTT.
2. Publish Ultrasonic sensor data using Node MCU through MQTT.
Ex. No. 5 Sending SMS using GSM module and Arduino Uno Board

Introduction
Arduino:
The Arduino UNO is an open-source microcontroller board based on the Microchip ATmega328P
microcontroller and developed by [Link]. The board is equipped with sets of digital and analog
input/output (I/O) pins that may be interfaced to various expansion boards (shields) and other circuits.
The board has 14 digital pins, 6 analog pins, and programmable with the Arduino IDE (Integrated
Development Environment) via a type B USB cable. It can be powered by the USB cable or by an
external 9-volt battery, though it accepts voltages between 7 and 20 volts.
GSM module:
SIM900A is a miniature cellular module which allows for GPRS transmission, sending and receiving
SMS and making and receiving voice calls. Low cost and small footprint and quad band frequency
support make this module perfect solution for any project that require long range connectivity. After
connecting power module boots up, searches for cellular network and login automatically. On board
LED displays connection state (no network coverage - fast blinking, logged in - slow blinking).

NOTE: Power consumption peeks up to 2A. Maximum voltage on UART in this module is 2.8V.
Higher voltage will kill the module. So, an external power supply is provided using an AC adapter.

Note: This may not be identical to the board in the laboratory. Only the TX, RX and Gnd need to be
connected to the Arduino. Power is to be supplied externally.

Hardware requirements:
1. Arduino Uno board
2. GSM Module
3. Jumper wires
4. SIM card (adapters too in case the SIM card is a micro or nano type)
5. Power adapter for the GSM module

Software requirements:
1. Arduino IDE
A GSM Module is basically a GSM Modem (like SIM 900) connected to a PCB with
different types of output taken from the board – say TTL Output (for Arduino, 8051 and other
microcontrollers) and RS232 Output to interface directly with a PC (personal computer). The
board will also have pins or provisions to attach mic and speaker, to take out +5V or other
values of power and ground connections. These type of provisions vary with different
modules.

Lots of varieties of GSM modem and GSM Modules are available in the market to choose
from. For our project of connecting a gsm modem or module to arduino and hence send and
receive sms using arduino – its always good to choose an arduino compatible GSM
Module – that is a GSM module with TTL Output provision.

Notes on GSM Module

1. We use SIM900 GSM Module – This means the module supports communication in
900MHz band. We are from India and most of the mobile network providers in this country
operate in the 900Mhz band. If you are from another country, you have to check the mobile
network band in your area. A majority of United States mobile networks operate in 850Mhz
band (the band is either 850Mhz or 1900Mhz). Canada operates primarily on 1900 Mhz
band.
2. Check the power requirements of GSM module – GSM modules are manufactured by
different companies. They all have different input power supply specs. You need to double
check your GSM modules power requirements. In this tutorial, our gsm module requires a 12
volts input. So we feed it using a 12V,1A DC power supply. Some gsm modules which
require 15 volts and some other types which needs only 5 volts input. They differ with
manufacturers. If you are having a 5V module, you can power it directly from Arduino‟s 5V
out.
Note:- GSM Modules are manufactured by connecting a particular GSM modem to a PCB
and then giving provisions for RS232 outputs, TTL outputs, Mic and Speaker interfacing
provisions etc. The most popular modem under use is SIM 900 gsm modem from
manufacturer SIMCom. They also manufacture GSM Modems in bands 850, 300 and other
frequency bands.

3. Check for TTL Output Pins in the module – You can feed the data from gsm module
directly to Arduino only if the module is enabled with TTL output pins. Otherwise you have
to convert the RS232 data to TTL using MAX232 IC and feed it to Arduino. Most of the
gsm modules in market are equipped with TTL output pins.
Setup:
Hardware connections:
1. Connect the Arduino Uno Board to the PC using the USB connector cable.
2. Without connecting the Arduino and GSM module, insert the SIM card in the GSM
module.
3. Connect the GSM module to power source using the power adapter, and power up the
device. (The connection can be checked via the LED as well as calling the number whose
SIM card is inserted in the module.)
[(a) Now wait for some time (say 1 minute) and see the blinking rate of „status LED‟ or „network
LED‟ (GSM module will take some time to establish connection with mobile network)
(b) Once the connection is established successfully, the status/network LED will blink
continuously every 3 seconds. You may try making a call to the mobile number of the sim card
inside GSM module. If you hear a ring back, the gsm module has successfully established
network connection].
3. Open Arduino IDE and write the required program, select the correct board (Arduino
Genuino Uno in this case) and port (COM2/COM5/COM6/whichever is applicable)
under “Tools” menu.
4. Compile and then Upload the sketch (code) to the Arduino.
Note: The problem with this connection is that, while programming, Arduino uses serial ports
to load program from the Arduino IDE. If these pins are used in wiring, the program will not
be loaded successfully to Arduino. So you have to disconnect wiring in Rx and Tx each time
you burn the program to arduino. Once the program is loaded successfully, you can reconnect
these pins and have the system working!
5. Now connect the Tx pin of the GSM module to the D8 pin of the Arduino board (Rx)
and Rx pin of the GSM module to the D7 pin of the Arduino board (Tx)using the
jumper wires. Connect the Ground pins of the two boards as well.
6. You can check the output in the “Serial Monitor”. Click on Serial Monitor, Then
Press “1” followed by “Enter ⅃” to see the output of the Program. Also, the check
that the SMS delivered to the intended recipient Mobile #.
____________________________________
Optional Procedure:
7. Click on the serial monitor and select the Baud rate specified in the program (9600 in
this case) from the bottom right corner to view the output. Verify with the recipient‟s
phone.
Note:
a. Remember to change the recipient‟s phone number in the Program.
b. Adjust the antenna on the GSM module for better cellular network receptivity.
c. If you wish to send text messages in a loop, it can be done simply by
copying/cutting the code in “void setup()” and inserting the code in “void
loop()”.
ARDUINO Code Required For The Implementation:
void setup()
{

[Link](9600); //Set baud rate to 9600 Setting the baud rate of Serial Monitor (Arduino)

}
void loop()
{
//You can skip the first three lines if you are sure your sim900 gsm setup is
//perfect and there is no error in circuit connection and power requirements.
//delay(1200);
//[Link]("AT"); “AT” This will check if the module is connected properly and its
functioning, the module will reply with an acknowledgment.
//delay(3000);
[Link]();

[Link]("AT+CMGF=1"); // Set the GSM Module in Text Mode (SMS)

delay(3000);
[Link]();
[Link]("AT+CMGS="); // Write the Mobile number, To whom the message is to be
sent to (ie. the Receiver mobile #)
[Link]("\"+91XXXXXXXXXX\"");
[Link]();
delay(3000);
[Link]("Hello Sir"); // SMS-Message body
delay(4000);
[Link]();
[Link](26); //CTRL+Z key combination indicating the end of the text message

ASCII 26 is End of File/ Substitute [Link]() –


Prints data to serial monitor of arduino : Prints the data collected from software serial
port to serial monitor of arduino

while(1); // For ever control


}
Observations:

Conclusions:

Assignments:
1. Send the Roll number of any of your group members, instead of test message in the
example.
2. Write a Program for sending an SMS, if any movement is detected by a PIR sensor
using Arduino Uno.

You might also like