Department of Computer Science &
Engineering
Subject: Adhoc and Wireless Sensor
Networks Lab
(BTCS 717-18)
B.Tech 4th Year- 7th Semester
Submitted to:
Submitted by:
Mr. Rajeev Sharma Name
Assistant Professor Rollno
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Chandigarh Engineering College-CGC,
Landran, Mohali-140307
INDEX
SNO EXPERIMENTS PAGE REMARK
. NO. S
1. Introduction of Wireless sensor network applications and 2-28
its simulation
2. Network Simulator installation of wireless sensor network. 29-33
3. Implementation of routing protocol in NS2 for DSR 34-39
protocol
4. Study other wireless sensor network simulators 40-41
(Mannasim. Contiki)
5. Implementation of routing protocol in NS2 for AODV 42-51
protocol for TORA protocol
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Experiment no 1
Aim: Introduction of Wireless sensor network applications and its
simulation.
a) Introduction of Wireless sensor network
A wireless sensor network consists of spatially distributed autonomous
sensors to cooperatively monitor physical or environmental conditions,
such as temperature, sound, vibration, pressure, motion or pollutants. The
development of wireless sensor networks was motivated by military
applications such as battlefield surveillance.
Sensor networks are composed of large numbers of tiny sensing and
computing devices. Each of these devices, called motes, has very limited
communication, computational and energy resources. Often embedded in
uncontrolled physical environments, these networks require distributed
algorithms for efficient data processing, while individual motes require
highly concurrent and reactive behavior for efficient operation. Sensor
networks face many problems that do not arise in other types of networks.
Power constraints, limited hardware, decreased reliability, and a typically
higher density and number of nodes than those found in conventional
networks are few of the problems that have to be considered when
developing protocols for use in sensor networks.
Figure.1.1 shows a typical simple wireless sensor network. As can be
seen, a complete wireless sensor network usually consists of one or more
base stations (or gateway), a number of sensor nodes, and the end user.
Sensor nodes are used to measure physical quantities such as
temperature, position, humidity, pressure etc. The output of those sensor
nodes are wirelessly transmitted to the base station (or gateway) for data
collection, analysis, and logging. End users may also be able to receive
and manage the data from the sensor via a website from long-distance or
applications in console terminal. However due to the associated cost, time
and complexity involved in implementation of such networks, developers
prefer to have first-hand information on feasibility and reflectivity crucial
to the implementation of the system prior to the hardware
implementation.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 1.1 Shows a typical simple wireless sensor network
This is especially true in sensor networks, where hardware may have to be
purchased in large quantities and at high cost. Even with readily available
sensor nodes, testing the network in the desired environment can be a
time consuming and difficult task. Simulation-based testing can help to
indicate whether or not the time and monetary investments are
worthwhile. Simulation is, therefore, the most common approach to
developing and testing new protocol for sensor networks. There are a
number of advantages to this approach including lower cost, ease of
implementation, and practicality of testing large-scale networks. In order
to effectively develop any protocol based on simulations, it is important to
know the different tools available and their benefits and drawbacks. Given
the facts that simulation is not perfect and that there are a number of
popular sensor network simulators available, thus making different
simulators accurate and most effective for different
situations/applications. It is crucial for a developer to choose a simulator
that best fits the application. However, without a working knowledge of
the available simulators, this is can be a challenging task. Additionally,
knowing the weaknesses of available simulators could help developers to
identify drawbacks of their own models, when compared with these
simulators, thus providing an opportunity for improvement. It is thus
imperative to have a detailed description of a number of the more
prominent simulators available. In this paper, we have compared various
sensor network simulators with emphasis on their ease of use, key
features, limitations, availability, and environments best supported.
They are now used in many industrial and civilian application areas,
including industrial process monitoring and control, machine health
monitoring, environment and habitat monitoring, healthcare applications,
home automation, and traffic control.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
A smart sensor node is a combination of sensing, processing and
communication technologies. Figure 1 shows the basic architectural
components of a sensor node. The sensing unit senses the change of
parameters, signal conditioning circuitry prepares the electrical signals to
convert to the digital domain, the sensed analog signal is converted and is
used as the input to the application algorithms or processing unit, the
memory helps processing of tasks and the transceiver is used for
communicating with other sensors or the base stations or sinks in WSN,
see figure 1.2.
Sensors can monitor temperature, pressure, humidity, soil makeup,
vehicular movement, noise levels, lighting conditions, the presence or
absence of certain kinds of objects or substances, mechanical stress
levels on attached objects, and other properties. Their mechanism may be
seismic, magnetic, thermal, visual, infrared, acoustic, or radar. A smart
sensor is also capable of self-identification and self-diagnosis. The
mechanisms of smart sensors work in one of three ways: by a line of sight
to the target (such as visual sensors), by proximity to target (such as
seismic sensors), and by propagation like a wave with possible bending
(such as acoustic sensors)
Figure 1.2: Basic architectural components of a smart sensor
DESIGN OF SENSOR NETWORK SIMULATOR:
The design of a Wireless Sensor Network (WSN) is a very application-
specific task, especially because of the peculiarity of the considered
deployment environment. Generic reliable predictive models for data
correlation or radio propagation are seldom available. A thorough
preliminary test phase is thus necessary, either by means of specifically
crafted test beds, or via reliable simulations. WSN applications must be
tested on a large scale, and under complex and varying conditions in
order to capture a sufficiently wide range of interactions, both among
nodes, and with the environment. A WSN simulator consists of various
modules namely events, medium, environment, node, transceiver,
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
protocols, and applications. Each category is represented by an interface
that defines its methods and events generated and consumed.
1. Event
Event is an abstract base class that provides basic functionality for all
events. It contains the time at which an event should work, and provides
methods to: compare events based on their fire times, determine whether
events are equal, print themselves to a string, and an abstract method to
fire the event.
2. Medium
Medium models the wireless medium. It allows nodes to broadcast signals,
and is responsible for informing nodes of signals that affect it. In order to
do this, Medium must be informed of the presence of every node, and any
changes in position or radio properties such as transmitter power or
receiver sensitivity. Medium has the properties of bandwidth and
wavelength of the medium modeled and a reference to a propagation
model that is given to it at the time of construction. The propagation
model provides the strength at a particular receiver from a signal
transmitted by a given transmitter.
3. Environment
The Environment module is similar to Medium module. The difference is
that the implementation of Environment has properties that relate to the
physical phenomenon modeled. Environment also has a propagation
model that models the propagation of the physical phenomena modeled.
Physical phenomena of interest in sensor networks include: temperature,
light, humidity, magnetic field, sound, optical, chemical presence.
4. Node
It represents a single node in a wireless sensor network. As such, it serves
as a container for all of the components, both hardware and software, in a
node. These components should be included: processor, transceiver,
sensors, actuators, energy source (such as a battery), network protocols,
and applications. In addition each node has the properties of location and
identification.
5. Transceiver
Transceiver models the hardware transceiver on each sensor node. It
models the transceiver states (i.e. sleep, standby, receive, and transmit),
and their associated behavior and power consumption. Transceiver
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
consumes events informing it of the beginning and ending of every signal
it receives. It sums active signals to maintain the interference. Transceiver
generates events for the beginning and ending of every signal it
transmits. These events are all exchanged with an instance of the Medium
module.
6. Physical Protocol
The Physical protocol is the lowest layer in a network stack. It is often
implemented in the transceiver hardware. The Physical layer provides
services for: changing the state of the transceiver, carrier sensing,
sending and receiving packets, received energy detection on received
packets, changing channels on physical layers that support multiple
channels.
7. MAC Protocol
The MAC protocol is the next layer in a network stack. It is usually
implemented in software running on the node’s processor. The MAC layer
provides services for: changing the state of the MAC layer (i.e. low power
mode), setting and getting protocol parameters, sending and receiving
packets, etc. A WSN simulator usually offers implementations for several
sensor network MAC protocols.
8. Routing Protocol
The Routing protocol resides above the MAC protocol and provides
services for routing messages over multiple hops between nodes that
cannot communicate directly.
9. Application Layer
The Application layer resides at the top of the network stack. It interfaces
with the lower layers in the network stack as well as the sensors and
actuators to implement a wireless sensor network application.
Most of the WSN simulators are based on the design described above. In
addition to including the different modules, a WSN simulator should also
have the following capabilities:
i. Reusability and availability Simulation is used to test novel
techniques in realistic and controlled scenarios. Researchers are
usually interested in comparing the performance of a new
technique against existing proposals.
ii. Performance and scalability Performance and scalability is a
major concern when facing WSN simulation. The former is usually
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
bounded to the programming language effectiveness. The latter
is constrained to the memory, processor and logs storage size
requirements.
iii. Support for rich-semantics scripting languages to define
experiments and process results the vast amount of variables
involved in the definition of a WSN experiment requires the use
of specific input scripting languages, with high-level semantics.
Additionally, it is likely that large quantities of output data will
also be generated through many replicas of the experiments.
Therefore, a suitable output scripting language, which helps to
obtain the results from the experiments quickly and precisely, is
desirable.
iv. Graphical, debug and trace support. Graphical support for
simulations is interesting in three aspects:
(a) As a debugging aid. The primary and more practical way to
quickly detect a bad behavior is to “watch” and follow the
execution of a simulation. The key features that a graphical
interface should support are: Capability of inspection of modules,
variables and event queues at real time, together with “step-by-
step” and “run-until” execution possibilities. These features make
graphical interfaces a very powerful debugging tool. Note that
the key is the ability to interact with the simulation.
(b) As a visual modeling and composition tool. This feature
usually facilitates and speeds the design of small experiments or
the composition of basic modules. However, for large scale
simulations, it is not very practical.
(c) Finally, it allows quick visualization of results without a post-
processing application.
However, there are various challenges associated with the available WSN
simulators. For instance, some simulator lack of available protocol models,
which causes the increase of developing time, some simulators limit the
scalability, etc. Additionally, modeling problems arise when considering
the new environment and the energy components. They also compromise
scalability and accuracy. A deep study of these issues is mandatory for a
better understanding and characterization of sensor networks and their
corresponding simulators.
Wireless Sensor Network Architecture
The most common wireless sensor network architecture follows the OSI
architecture Model. The architecture of the WSN includes five layers and
three cross layers. Mostly in sensor n/w, we require five layers, namely
application, transport, n/w, data link & physical layer. The three cross
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
planes are namely power management, mobility management, and task
management. These layers of the WSN are used to accomplish the n/w
and make the sensors work together in order to raise the complete
efficiency of the network. Please follow the below link for Types of wireless
sensor networks and WSN topologies
Types of WSN Architectures
The architecture used in WSN is sensor network architecture. This kind of
architecture is applicable in different places such as hospitals, schools,
roads, buildings as well as it is used in different applications such as
security management, disaster management & crisis management, etc.
There are two types of architectures used in wireless sensor networks
which include the following. There are 2 types of wireless sensor
architectures: Layered Network Architecture, and Clustered Architecture.
These are explained as following below.
Layered Network Architecture
Clustered Network Architecture
Layered Network Architecture:
This kind of network uses hundreds of sensor nodes as well as a
base station. Here the arrangement of network nodes can be
done into concentric layers. It comprises five layers as well as 3
cross layers which include the following.
The five layers in the architecture are:
Application Layer
Transport Layer
Network Layer
Data Link Layer
Physical Layer
The three cross layers include the following:
Power Management Plane
Mobility Management Plane
Task Management Plane
These three cross layers are mainly used for controlling the network as
well as to make the sensors function as one in order to enhance the overall
network efficiency. The above mentioned five layers of WSN are discussed
below.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 1 3: Wireless Sensor Network Architecture
Application Layer
The application layer is liable for traffic management and offers software
for numerous applications that convert the data in a clear form to find
positive information. Sensor networks arranged in numerous applications
in different fields such as agricultural, military, environment, medical, etc.
Transport Layer
The function of the transport layer is to deliver congestion avoidance and
reliability where a lot of protocols intended to offer this function are either
practical on the upstream. These protocols use dissimilar mechanisms for
loss recognition and loss recovery. The transport layer is exactly needed
when a system is planned to contact other networks.
Providing a reliable loss recovery is more energy-efficient and that is one
of the main reasons why TCP is not fit for WSN. In general, Transport
layers can be separated into Packet driven, Event-driven. There are some
popular protocols in the transport layer namely STCP (Sensor
Transmission Control Protocol), PORT (Price-Oriented Reliable Transport
Protocol and PSFQ (pump slow fetch quick).
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Network Layer
The main function of the network layer is routing, it has a lot of tasks
based on the application, but actually, the main tasks are in the power
conserving, partial memory, buffers, and sensor don’t have a universal ID
and have to be self-organized.
The simple idea of the routing protocol is to explain a reliable lane and
redundant lanes, according to a convincing scale called a metric, which
varies from protocol to protocol. There are a lot of existing protocols for
this network layer, they can be separated into; flat routing and hierarchal
routing or can be separated into time-driven, query-driven & event-driven.
Data Link Layer
The data link layer is liable for multiplexing data frame detection, data
streams, MAC, & error control, confirm the reliability of point–point (or)
point– multipoint.
Physical Layer
The physical layer provides an edge for transferring a stream of bits above
the physical medium. This layer is responsible for the selection of
frequency, generation of a carrier frequency, signal detection, Modulation
& data encryption. IEEE 802.15.4 is suggested as typical for low rate
particular areas & wireless sensor networks with low cost, power
consumption, density, the range of communication to improve the battery
life. CSMA/CA is used to support star & peer to peer topology. There are
several versions of IEEE 802.15.4.V.
The main benefits of using this kind of architecture in WSN is that every
node involves simply in less-distance, low- power transmissions to the
neighboring nodes due to which power utilization is low as compared with
other kinds of sensor network architecture. This kind of network is
scalable as well as includes a high fault tolerance.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
b) Wireless Sensor Network Applications
Wireless sensor networks may comprise numerous different types of
sensors like low sampling rate, seismic, magnetic, thermal, visual,
infrared, radar, and acoustic, which are clever to monitor a wide range of
ambient situations. Sensor nodes are used for constant sensing, event ID,
event detection & local control of actuators. The applications of wireless
sensor networks mainly include health, military, environmental, home, &
other commercial areas.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 1.4. Overview of the most popular categories of
applications of WSNs.
1) Military Applications: The military domain is not only the first field of
human activity that used WSNs but it is also considered to have motivated
the initiation of sensor network research. Smart Dust is a typical example
of these initial research efforts, which were performed in the late 90 s in
order to develop sensor nodes which despite their very small size would
be capable of accomplishing spying activities
The technological advances achieved since then made WSNs
capable of supporting various operations.
Figure 1.5. The subcategories of the military applications of WSNs and
the types of sensors
In Figure 1.5, the main subcategories of the military applications of
WSNs which namely are battlefield surveillance, combat monitoring,
and intruder detection, are illustrated along with the types of sensors
that are most commonly used in them.
Specifically, Chemical, Biological, Radiological, Nuclear and
Explosive (CBRNE), and Toxic Industrial Material (TIM) sensors may be
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
used to detect the presence of such substances. To detect intrusion,
WSNs may use infrared, photoelectric, laser, acoustic, and vibration
sensors. Similarly, RAdio Detection and Ranging (RADAR), LIght
Detection And Ranging (LIDAR), LAser Detection And Ranging (LADAR)
and ultrasonic sensors are used by nodes in WSNs in order to detect the
distance from objects of interest. Likewise, LADAR and infrared sensors
are used for imaging purposes.
Additionally, the flexibility that WSNs have in their structure enables
them to adapt to various requirements. For instance, in battlefield
operations large-scale WSNs consisting of many thousands of nodes,
which are non-manually deployed, are used. In urban warfare and force
protection operations, WSNs used consist of hundreds of manually
deployed nodes. In other-than-war operations all scales of WSNs and
deployment methods are used.
WSNs that have been developed for battlefield surveillance, combat
monitoring and intruder detection are examined in the following
subsection.
a) Battlefield Surveillance
In applications of this type, the sensor nodes of the WSN may be
deployed on a battlefield nearby of the paths that enemy forces may
use. The main advantage provided is that the WSN not only can be
spontaneously positioned but also can function, without need for
continuous attendance and maintenance. The terrain of the battlefield in
most cases is absolutely variable. This plays an important role for both
the coverage and the energy consumption of the sensor nodes. Some of
these applications are presented below.
The use of WSN technology for ground surveillance is studied.
Specifically, the authors propose a system that consists of low-cost
common nodes which are capable of sensing magnetic and acoustic
signals produced by various moving target objects. The system aims
to detect and categorize various targets, such as vehicles and troop
movements, based on the spatial differences of the signal strength
detected by the sensors. Figure 1.6 illustrates the architecture of this
system.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 1.6. Illustration of the system architecture proposed in for
target tracking.
In a submarine detection system for Anti-Submarine Warfare (ASW) is
presented. The system consists of inexpensive multi-sensing units that
combine both active and passive sonars. The system can be scaled to a
large number of sensors, which are deployed in littoral waters according
to a specific pattern and ocean depth. These sensing units utilize their
passive sonar to detect a diesel-electric submarine and their active sonar
to confirm their target. The unit that has confirmed a target notifies its
neighboring sensing units by using an alarm signal that contains its ID
code. Whenever the units send multiple alarm signals within a predefined
period of time, an alert is triggered. Furthermore, the system can acquire
low False Alarm Rate (FAR) due to the very low range of the active sonar
(50 m) that solves the acoustic multipath problem of the conventional son
buoys.
b) Combat Monitoring:
Within a battlefield the firing of guns, mortars artillery, and other
weaponry creates sound, heat, and vibrations. This information can be
recorded with the use of WSNs and provides an expectation of the
location of the enemy. This type of application is described below.
In the use of acoustic sensor arrays suspended below tethered
aerostats to detect and localize moving vehicles, transient signals from
mortars, artillery, small arms fire, and locate their source is
presented.
The specific detection system can be used in conjunction with an
acoustic vector sensor, to amplify the possibility of locating the threat
using the shockwave created by the supersonic bullet and the muzzle
blast created by the gun.
It describes a system consisting of interconnected Body Sensor
Networks (BSNs), a sub-family of WSNs, for real-time health monitoring
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
of soldiers. A key component of this system is a BSN that integrates
various physiological and biomedical sensors. These sensors are an
accelerometer, an EEG simulator, and a SpO 2 sensor, which can be
embedded within an advanced combat helmet worn by each soldier.
They monitor the various information of health status in real time, such
as blood pressure, oxygen saturation, and heart rate. By utilizing the
data collected, various methods can be applied in order to train soldiers
more efficiently and prepare them more adequately for future
engagements.
Intruder Detection: The knowledge of the location of the enemy is
considered to be one of the most critical pieces of information during
military operations. Whichever side in a conflict has this knowledge is
one step ahead and closer to victory. With the utilization of WSNs within
a battlefield, intruders can be detected in good time to prevent loss of
supplies or territory.
An intruder can be detected in various ways. To detect an intruder,
with the aid of these sensors, typical military activities, such as
equipment handling, walking, rifle loading, etc., have been measured
and recorded in a controlled environment and in the field. Although the
distance of detection may be small, the information provided by the
network can be used to locate an intruder in difficult terrains with large
vegetation where visibility is limited.
The application of WSNs, developed to detect intruders, is introduced.
The authors described a system with dense deployment of a large
number of miniaturized wireless sensors, which are small, low cost, and
consume low energy. This system utilizes acoustic and seismic sensors
to provide detection information to the user and tracking and visual
sensors in order to lower the false alarm rate.
c) Health Applications:
In the health domain, WSNs utilize advanced medical sensors to
monitor patients within a healthcare facility, as a hospital or within their
home, as well as to provide real time monitoring of patient’s vitals by
utilizing wearable hardware. In Figure 7, the main subcategories of
health applications of WSNs namely patient wearable monitoring, home
assisting systems, and hospital patient monitoring are illustrated along
with the types of sensors that are most commonly used in them. WSNs
that have been developed for these types of health applications are
examined in the following subsection.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 1.7. The subcategories of the health applications of WSNs
and the sensors used in them.
Patient Wearable Monitoring: Health monitoring applications can be
combined with wearable hardware with embedded biomedical sensors
that provide the patient’s health status in a remote environment or
within a healthcare facility.
It uses real-time sensors incorporated in smartphones along with a
barcode system to provide personalized medicine care assistance. The
mechanism developed, performs Electrocardiogram (ECG) monitoring in
real time. Also, the monitoring of the blood glucose level, blood
pressure, and several kinds of diagnostics could be possible too, by
using real-time sensors. This system developed is illustrated in Figure
1.8.
Figure 1.8. An illustration of the real time electrocardiogram (ECG)
monitoring environment
An alert portable tele-medical monitor system (AMON) is proposed in
, aiming to provide continuous monitoring for high-risk
cardiac/respiratory patients. The system collects multiple vital signs,
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
detects multi-parameter medical emergencies and is connected to a
cellular telemedicine center (TMC). This system uses a wrist worn
device, to monitor vital parameters of patients in order to provide an
integrated picture of their health condition.
d) Home Assisting Systems :
A homecare monitoring platform with internet remote connection to
assisted people and their environment. This platform can monitor and
diagnose patients remotely, in real time in their home environment by
the utilization of wearable or even surgically inserted bio- sensors. A
hybrid model of the platform is proposed, with various levels in terms of
functionality, combining fixed and mobile nodes. These levels range
from simple data acquisition of the assisted person to primary care and
emergency nodes, up to the communication and coordination with an
appointed help center as a hospital.
One of the main reasons behind this technology is to commercialize
it for the benefit of those patients who are not financially sound.
Furthermore, the system was developed in such a manner that any kind
of crisis phase is dealt with in terms of alerting messages that are
automatically sent to the doctor. An overview of the operation of this
system is shown in Figure 1.9.
Figure 1.9. The system configuration of the remote patient
monitoring application
e) Hospital Patient Monitoring (or Hospitalization):
Within healthcare facilities, such as a hospital, WSNs systems
can be integrated to provide real time patient monitoring and
emergency alerting for a more precise and quick response. A
WSN application where wireless sensors are placed within the
emergency rooms of John Hopkins hospital to monitor in real
time the blood oxygen and heart rate of the patients. The
researchers collected the performance statistics of the network
and despite the difficulty of the hospital environment due to
interference and radio noise, the application of WSNs can
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
improve the operation of a healthcare facility. The device
developed is depicted in Figure 1.10
Figure 1.10. A monitor that can both display and transmit vital
signs
2. Environmental Applications
Environmental applications that demand continuous monitoring of
ambient conditions at hostile and remote areas can be improved with
the utilization of WSNs. In Figure11, the main subcategories of
environmental applications of WSNs, namely water monitoring, air
monitoring, and emergency alerting, are depicted along with the types
of sensors that are typically used in them. WSNs that have been
developed for these types of environmental applications are studied in
the following subsection.
Figure 1.11. The subcategories of the environmental WSN
applications and the types of the sensors used in them.
a)Water Monitoring
Water, either for drinking or oceanic is an important factor in human
lives; therefore the monitoring of water has a great academic interest
for researchers as described below.
WSN application to evaluate the quality of fresh drinkable water.
They designed a Cyber physical system (CPS) called PipeSense, which is
an in-pipe system for water monitoring that utilizes RFID (Radio
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Frequency Identification) based WSN. The network can provide
information about water demand or water quality and various repair
information such as weak spots or pipe leakage. The in-pipe RFID
sensors collect information from the system and send them to the data
servers, where algorithms provide decision support.
In order to prevent damage to the flora and fauna of a fish farm from
feed and fecal waste, the authors designed an Underwater WSN (UWSN)
with ground based wireless sensor nodes capable of monitoring the
pollution of the farm. The sensor nodes are mobile in a limited space in
order to measure a greater area.
b)Air Monitoring
Air is a vital element for human lives and nowadays the air pollution
of the atmosphere is a result of many modern human activities. WSNs
can be utilized for air quality monitoring in occupied regions in order to
prevent dangerous diseases and contaminations or risk the health of
people.
The specific system combines gas sensors along with Libelium
waspmotes to measure air quality parameters of gases such as ozone,
CO, and NO2. The waspmotes monitor in real time the air quality and
utilize the Zigbee protocol for data communication. The authors further
introduced the Clustering Protocol for Air Sensor network (CPAS) in order
to support the operation of this system
c) Emergency Alerting
Proactive monitoring of the causes of natural disasters, can help to
avoid these disasters or/and lower their cost. WSNs can be utilized for
monitoring common disastrous causes in real time to provide proactive
alerts in order to lower damage or even prevent disaster. Typical
examples described in the rest of this subsection, are related to the
monitoring of seismic activity, volcanic activity, forest fires, and
tsunamis.
d) Seismic Activity Monitoring
Earthquakes can cause enormous damage to an occupied region
where they take place. WSNs can be utilized to monitor seismic activity
in real time in order to take precautionary measures and enable the
authorities to act in advance. A real time seismic activity monitoring
system is presented. The system monitors seismic activity by utilizing
primary waves (P-waves) and estimates local velocity and the
hypocenter’s location according to time delays in the arrival of the P-
waves at the sensors. Volcanic Activity Monitoring Volcanoes can cause
enormous damage to nearby towns or cities when they are activated.
Before a volcano erupts, there are many signs that a WSN system can
measure, proactively, in order to inform nearby citizens about the
eruption. When such a system is applied, citizens can protect their
families and belongings by transporting them outside of the area of the
eruption, preventing further damage. Below is an example of such a
system.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
The system is low cost, flexible, and easy to deploy and to maintain for
remote locations. The users of the system can choose GPS data
synchronization when the sensor nodes have signal reception, or a
specific algorithm when they have not, to collect accurate timestamps
of each sample. Pieces of the equipment used, are shown in Figure
1.12.
Figure 1.12. A depiction of a geophone sensor with a wireless antenna
deployed in the field.
e) Forest Fire Prevention
Forest fires can destroy both animals and vegetation, thus resulting
in huge ecological disasters. In order to prevent such disastrous events
WSNs can be deployed within forests and monitor in real time related
parameters in order to assist in forest fire prevention. One example of
this type of WSN application is presented below.
Due to the rapid climate change taking place, the necessity for
proper forest fire prevention means is extremely pressing. Related
parameters as temperature, humidity, etc. are monitored in real time
and sent to a monitoring center in order to be analyzed. Then the
system can make quick estimations of fire danger and inform the
authorities.
f) Tsunami Detection
Another natural disaster is the tsunami waves. It is crucial for
coastal regions to be informed early of such a catastrophe. WSNs can
be utilized for real time monitoring enabling the authorities to act
proactively. Below a Tsunami detection WSN application is presented.
A tsunami detection system which utilizes a WSN with underwater
sensor nodes deployed in coastal regions is proposed. In order to inform
proactively the authorities, the system utilizes a lexical resource
messaging system, called SentiWordNet, which is able to provide
information extracted from the sensor messages.
3) Flora and Fauna Applications
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Both flora and fauna domains are vital for every country. In
Figure12, the main subcategories of flora and fauna applications of
WSNs which namely are greenhouse monitoring, crop monitoring, and
livestock farming, are illustrated along with the types of sensors that are
most commonly used in them.
WSNs that have been developed for these types of flora and fauna
applications are examined in the following subsection.
a)Greenhouse Monitoring
An important sector of the agriculture domain involves greenhouses.
Within them many crops can be grown to provide sustainable food while
climate crops can be harvested all year round if certain conditions are
applied within the greenhouse. Therefore, WSNs can be applied in
greenhouse monitoring and control to improve their operation. Below
are some examples of these applications.
A system of this type, called the Agricultural Environment Monitoring
System (AEMS), is presented. It is an inexpensive and easy to apply
system that can collect and monitor data related to crop growth, inside
or outside a greenhouse via WSN sensors and CCTV cameras. The
system gathers vital environmental parameters such as temperature,
light intensity, humidity, air pressure, rainfall level, pH, and electrical
conductivity (EC).
Figure 1. 13. The subcategories of flora and fauna applications of
WSNs and the types of the sensors used in them.
The system monitors vital greenhouse parameters such as indoor
luminance, temperature, and relative humidity, via sensor nodes. The
indoor climate control is possible by the utilization of two fuzzy logic
controllers, P (Proportional) and PD (Proportional-Derivative) that use
the desired indoor climatic set-points. Furthermore, the system utilizes
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
output actuations of heating units, motor-controlled windows and
shading curtains, artificial lighting, etc. in order to achieve more precise
greenhouse control.
b)Crop Monitoring
Within the agriculture domain, the preservation of the crops plays a
vital role. In order to provide a better environment for the crops, various
WSNs applications can be implemented. Crop irrigation and fertilization
are some examples of the applications that have been designed as
described below.
the system used B/S a (browser/server) structure mode to provide
high interactivity. Also, a GIS analysis server was used to interpolate
the data from small experimental plots to larger plots to exploit data
reduction for energy conservation. An overview of the overall system
architecture is illustrated in Figure 1.14.
Figure 1.14. A structure diagram of the integrated optimal fertilization
decision support system.
This system aims at efficiently managing water supply in cultivated fields
in an automated way. The system takes into consideration the historical
data and the change in the climate values to calculate the quantity of
water that is needed for irrigation.
c) Livestock Farming
Livestock farming is a main sector of the fauna domain. WSNs can
be applied in various tasks such as livestock monitoring. Below we have
collected some examples of these applications.
Green pastures are used by cattle for grazing, so grass growth was
analyzed through photographic sensors, so that animals can be moved
towards them. Their major objective of work was to design rugged
hardware that could be used outdoors for modeling both individual and
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
herd behavior of animals. Although, specially designed sensors to
monitor animal behavior, such as sleeping, grazing, and ruminating, are
used, cattle monitoring still poses several challenges like radio
attenuation caused due to factors such as animal body, mobility etc.
The system developed uses a solar power relay router and two
antennas placed so that the collar radio coverage is optimized. Also, a
novel protocol, named Implicit Routing Protocol (IRP), was proposed in
order to cope with the packet losses, which are caused due to the
mobility of the animals.
3) Industrial Applications:
WSNs can be applied in various industrial applications to solve
many related problems. In Figure 1.15, the main subcategories of
industrial applications of WSNs namely logistics, robotics, and
machinery health monitoring are illustrated. These specific categories of
applications are studied in the rest of this subsection.
Figure 1.15. The subcategories of the industrial applications of
WSNs and the types of the sensors used in them.
a)Logistics
The domain of logistics is an area of interest where WSNs can be
applied, because many logistics systems need real time monitoring of
various environmental parameters and better handling of packages.
These requirements can be fulfilled by combining the logistics systems
with WSNs. Some types of these applications are described below.
The transport logistics sector requires low cost and high-quality
during deliveries. the development and deployment of a WSN based
system for monitoring transportation conditions, such as temperature
and humidity, within a cargo container travelling via both a trans-
Atlantic cargo vessel and a lorry is described. The main idea for the
deployment of the monitoring system is depicted in Figure 16. It is
shown that the use of a system of this kind, can increase quality by
providing better supervision and lower the cost by reducing losses
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
during transportation.
Figure 1.16. Depiction of the basic configuration of a WSN based
system for transport logistics applications
The application of WSNs in Cold Chain Logistics (a continuous
temperature-controlled supply chain) can greatly improve the
monitoring and management of these chains. WSNs are suitable for real
time monitoring of many environmental parameters and provide
accurate data collection that meets the demand of Cold Chain Logistics.
The researchers used a Zigbee ad hoc network model to build the
system’s framework. By using fuzzy control decision, the environmental
parameters are maintained in a stable range and with Maximum
Similarities Multiple Characteristic Recognition (MSMCR) the safety of
cold-chain food is ensured.
b) Robotics
Nowadays there are many applications that combine WSNs and
robots. Robots can cooperate and combat some of the major problems
of WSNs, such as sensor node mobility, node redeployment, travelling
salesman, etc. Typical WSN applications of this kind are presented
below.
Specifically, each sensor constructs a map, based on the traversable
area sensed. Then, all sensor maps are combined to create one large
map. Once the road maps are generated, the sensors are used to sense
areas of interest for the robot to travel to. The robot then considers all
possible roads to take and selects the most efficient path available in
the network. If an area becomes hazardous for the robot, the network
can reconfigure the road map, and remove this hazardous area from the
list of available paths.
c) Machinery Health Monitoring
The objective of machinery health monitoring is to examine the
performance of various types of technical equipment and to either
detect or predict the occurrence of faults that are obstructive or even
catastrophic for their operation.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
4 Urban Applications
The variety of sensing abilities offered by WSNs also provides an
opportunity to gain an unprecedented level of information about a
target area, be it a room, a building, or outdoors. WSNs are indeed a
tool to measure the spatial and temporal features of any phenomena
within an urban environment, providing a limitless number of
applications. The most popular applications of WSNs in the urban
domain are related to smart homes, smart cities, transportation
systems, and structural health monitoring, as depicted in Figure 1.17
and further described in the rest of this subsection.
Urban
Applications
Smart Smart Transportation Structural Health
Homes Cities Systems Monitoring
Gas & Accelero-
Motion Visual Optical Corrosion
Smoke
Sensors Sensors Sensors Sensors
Biomedical Pressure Acoustic Strain
Sensors Sensors Sensors Sensors
Figure 1.17. The subcategories of the urban applications of
WSNs and the types of the sensors used in them.
a) Smart Cities
In large cities monitoring of various parameters is crucial for the
optimal life of the citizens. WSNs have a huge amount of applications to
provide real time data to the authorities for the optimal function of a
city. Specifically, increased transportation of people creates problems
and time wastage, when a large number of vehicles is heading towards
common destinations. WSNs can be utilized for monitoring in order to
reduce traffic, indicate car parking spots, etc.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 1.18. A depiction of the various setups where WSNs can
be deployed
This system enables the remote control of street lighting lamps, by
using Doppler sensors to allow for vehicle detection. The light intensity
of the lamps is increased, to a preset level, in the presence of
approaching vehicles and reduced in the absence of them.
a) Smart Homes
In the era of informatics, various systems can improve human lives.
Wireless sensor networks can be applied in the indoor environment as
in smart homes where machine to machine communications take place.
Two typical examples are the indoor localization and motion monitoring
and the monitoring of the indoor air quality.
Specifically, the monitoring of indoor air quality (IAQ), which is a
term that refers to the air quality of a building, has become, with the
rapid urbanization process that is taking place, one of the most
important topics of WSN urban applications. Modern people spend a
great part of their life within a building, thus the air quality plays a
critical role for their health, safety, and comfort
Similarly, the WSN based IAQ monitoring system uses sensor nodes
that measure temperature, relative humidity, and concentration of
carbon dioxide in classrooms in order to correlate the level of indoor air
quality with the students’ level of performance in their studies. The
authors developed a system, which is used to estimate the position of a
person within an indoor environment. The system utilizes mobile sensor
nodes worn by the moving persons and a network of static sensor nodes
at known locations. To calculate the person’s position, the system
gathers data from the nodes in a central PC and applies Monte Carlo
based estimation algorithms to track the moving persons in real time.
b) Transportation Systems
The transportation of vehicles within the urban environment is an
important factor for the safety and proper function of public roads. In
the modern era various researchers have proposed many systems in
the transportation domain, which by utilizing WSNs can improve the
safety of roads and provide information during the use of them by
drivers. Below we present some relative WSN applications applied in the
transportation domain
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 1.19. A representation of the Secure Multimedia Broadcast
Framework (SMBP)
The system utilizes deployed sensor nodes on the road and a sink node
on the roadside. The sensors nodes detect the passing vehicles and
transmit data to the sink node. Furthermore, when an event occurs a
packet is created, the sink node implements a timestamp to it and
forwards it to the com node, which utilizes a level-based static routing
protocol. Next, the com node forwards this packet to the user, which
analyzes the provided information in order to determine various metrics
of the road such as a vehicle’s speed, lane vehicle density etc. A
depiction of the overall system configuration is shown in Figure 1.20.
Figure 1.20. A graphical depiction of the WSN based transportation
monitoring system
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
In recent years, various WSN have been deployed within cities
resulting in the formation of small WSN based islands Furthermore, the
authors utilize two wireless standards i.e., IEEE 802.15.4 and IEEE
802.11p due to the need for separate roadside sensor units. In order to
prevent accidents, the WSN islands constantly detect road conditions
and transmit information to the vehicles passing by the area, which
aggregate these data.
Figure 1.21. An illustration of the WSN deployed for an Intelligent
Transport system
Then the vehicle that has this information transmits warning messages to
nearby vehicles in order for the data to be disseminated along the road.
The post-accident gathered information is restricted, by the authors, in
order to be used only by authorized personnel such as insurance
companies, criminological teams, or other authorities. Moreover,
according to the authors, the post-accident management can function
properly by communicating with the WSN islands on the roadside,
without the use of VANETs. The overall system operation is illustrated in
Figure 21.
c) Structural Health Monitoring
The aim of Structural Health Monitoring (SHM) in buildings and other
types of civil engineering substructures, is to monitor their integrity and
to detect the existence and the extent of damages in the materials
or/and the structure of their bodies. The use of wireless sensors
facilitates the accomplishment of tasks of this kind both in a periodic
basis and after critical events (e.g., earthquakes).
Specifically, a WSN incorporating nodes with appropriate sensors, such
as accelerometers and strain gauges, was developed to monitor the
restoration works carried out in an old church building located in Italy,
which was damaged after an earthquake. The system monitored the on
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
the fly response of the structure to vibrations and enabled the
transmission of alert signals when needed.
WSN based, structural health monitoring platform for a stadium located in
the USA is described. By using vibration sensing, the system collects real
time, data during athletic and other major events to verify the structural
behavior of the stadium, in correlation with the behavior of the audience.
Name_Rollno CEC-Landran Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
.
c) SIMULATION TOOLS:
This section illustrates main-stream simulation tools used in WSNs are Glomosim,
NS-2, Sensor sim, prowler, omnet++, TOSSIM, EmStar, OMNeT++, J-Sim, ATEMU,
and Avrora, and analyzes the advantage and disadvantage of each simulation tool.
The network simulator is discrete event packet level simulator. The network
simulator covers a very large number of application of different kind of protocols of
different network types consisting of different network elements and traffic
models. Network simulator is a package of tools that simulates behavior of
networks such as creating network topologies, log events that happen under any
load,analyze the events and understand the network.
1) NS-2
NS-2[12] is the abbreviation of Network simulator version two, which first been
developed by 1989 using as the REAL network simulator. Now, NS-2 is supported
by (DARPA) Defense Advanced Research Projects Agency and (NSF) National
Science Foundation. NS-2 is a discrete event network simulator built in Object-
Oriented extension of Tool Command Language and C++ [C++]. People can run
NS-2 simulator on Linux Operating Systems or on Cygwin. This simulator is open
source and provides online document. It helps to use network simulator and to get
acquainted with the simulated objects and understand the operations of network
simulation and we also need to analyze the behavior of the simulation object using
network simulation. Steps followed to write a program
Initialization and termination aspects of network simulator.
Defining the network nodes, links, queues and topology as well.
Defining the agents and their applications
Network Animator(NAM)
Tracing
Advantage
Non-specific network simulator
Open source it saves time and money and easy to modify and improve the
code.
It helps to increase the efficiency of simulation.
It is used to provide details of the protocols and their operation.
It is used to reduce packet and event processing time.
OTcl helps in the following way:
With the help of OTcl we can describe different network topologies
It helps us to specify the protocols and their applications
It allows fast development
Tcl is compatible with many platforms and it is flexible for integration
Tcl is very easy to use and it is available in free
Disadvantage
Need to know Scripting language and modeling techniques
TCL(Tool Command Language)
More Complex sometimes to do desired job and time consuming than other.
No GUI
Name_Rollno CEC-Landran Page 30
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Continuous change of code base the result is not consistent.
2) TOSSIM
Tossim is an emulator specifically designed for WSN running on TinyOS, which is
an open source operating system targeting embedded operating system. In
2003, TOSSIM was first developed by UC Berkeley’s TinyOS project team. TOSSIM
is a bit-level discrete event network emulator built in Python [Python], a high-
level programming language emphasizing code readability, and C++. People can
run TOSSIM on Linux Operating Systems or on Cygwin on Windows. TOSSIM also
provides open sources and online documents.
Advantage
open source model free online document save the emulation cost
support thousands of nodes simulation
more accurately simulate the real world situation
Disadvantage
TOSSIM’s run-instantly execution model does not capture CPU time.
It does not model energy consumption, though there is an add-on
3) EmStar
EmStar is an emulator specifically designed in C for WSN, and it was first
developed by University of California, Los Angeles. EmStar is a trace-driven
emulator [Girod04] running in real-time. People can run this emulator on Linux
operating system. This emulator supports to develop WSN application on better
hardware sensors. Besides libraries, tools and services, an extension of Linux
microkernel is included in EmStar emulator.
Advantage
allows the users to run each module separately without sacrificing the
reusability of the software
Environment is flexible for deployment and simulation among sensors.
It is GUI and it is helpful for users to control electronic devices.
many online documents to facilities the widely use of this emulator
Disadvantage
Only applicable to iPAQ-class sensor nodes and MICA2 motes
Limited Scalability
Does not support parallel simulation
Not efficient as other frameworks
4) OMNeT++
OMNeT++ [14] is a discrete event network simulator built in C++. OMNeT++
provides both a noncommercial license, used at academic institutions or non-profit
research organizations, and a commercial license, used at "for-profit"
environments. This simulator supports module programming model. Users can run
OMNeT++ simulator on Linux Operating Systems, Unix-like system and Windows.
OMNeT++ is a popular non-specific network simulator, which can be used in both
wire and wireless area. Most of frameworks and simulation models in OMNeT++
are open sources.
Advantage
Name_Rollno CEC-Landran Page 31
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
GUI
support MAC protocols and localized protocol
Channel control
5) J-Sim
J-Sim is a discrete event network simulator built in Java. This simulator provides
GUI library, which facilities users to model or compile the Mathematical Modeling
Language, a “text-based language” written to J-Sim models. J-Sim provides open
source models and online documents. This simulator is commonly used in
physiology and biomedicine areas, but it also can be used in WSN simulation. In
addition, J-Sim can simulate real- time processes.
Advantage
Reusability, interchangeability
support MAC protocols and localized protocol
supports around 500 nodes
Independently platform
more accurately simulate the real world situation
Disadvantage
TOSSIM’s run-instantly execution model does not capture CPU time.
It does not model energy consumption, though there is an add-on
6) ATEMU
ATEMU is an emulator of an AVR processor for WSN built in C; AVR is a single
chip microcontroller commonly used in the MICA platform. ATEMU provides GUI,
Xatdb; people can use this GUI to run codes on sensor nodes, debug codes and
monitor program executions. People can run ATEMU on Solaris and Linux
operating system. ATEMU is a specific emulator for WSNs; it can support users to
run TinyOS on MICA2 hardware. ATEMU can emulate not only the communication
among the sensors, but also every instruction implemented in each sensor. This
emulator provides open sources and online documents.
Advantage
Multiple nodes at the same time and each node can run different programs
Large library with hard devices
Disadvantage
Simulation time is much longer than other simulation tools
Only few functions are used to simulate routing and clustering problems
7) Avrora
Avrora is a simulator specifically designed for WSNs built in Java. Similar to
ATEMU, Avrora can also simulate AVR-based microcontroller MICA2 sensor nodes.
This simulator was developed by University of California, Los Angeles Compilers
Group. Avrora provides a wide range of tools that can be used in simulating
WSNs.
Advantage
It is a combination of TOSSIM and ATEMU simulators
Name_Rollno CEC-Landran Page 32
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
It supports for energy consumption
It provides open source and online documents
Supports faster speed and better scalability
More accuracy than Tossim
Disadvantage
Not have GUI
It doesn’t support network communication tools
8) SENS
A Sensor Environment and Network Simulator. SENS is a wireless sensor network
simulator with modular, layered architecture with customizable components
which model an application, network communication, and the physical
environment. It enables realistic simulations, by using values from real sensors to
represent the behavior of component implementations. Such behavior includes
sound and radio signal strength characteristics and power usage.
Advantage
It is writtern in C++
Platform independent
WSN applications feature tight integration of computation, communication
Interaction with the physical environment
Disadvantage
Less customizable
9) COOJA (COntiki Os JAva)
COOJA is a simulator for the Contiki sensor node operating system. MSP Sim can be
integrated into COOJA, forming COOJA/MSP Sim. It allows simultaneous cross-level
simulation at application, operating system and machine code instruction set level.
COOJA combines low level simulation of sensor node hardware and simulation of
high-level behavior in a single simulation.
Advantage
COOJA is flexible and extensible in that all levels of the system can be
changed
Sensor node platforms, operating system software, radio transceivers, and radio
propagation models.
COOJA is a Java application, all interaction with compiled Contiki code is done
through Java Native Interface (JNI).
Disadvantage
It is extensible and it is low efficiency
GUI is absent and making extensible and time dependent difficult.
10) Castalia
Castalia is an application-level simulator for Wireless Sensor Network based on
OMNeT++. It can be used to evaluate different platform characteristics for specific
applications, since it is highly parametric, and can simulate a wide range of
platforms. In Castalia, sensor nodes are implemented as compound modules,
consisting of sub-modules that represent, for instance, network stack layers,
Name_Rollno CEC-Landran Page 33
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
application, and sensor.
Advantage
sensing device noise, bias and node clock drift
Disadvantage
Reliable and realistic framework for the first order validation of an algorithm
before moving to implementation on a specific sensor platform.
Experiment no 2
Aim: Network Simulator installation of wireless sensor network.
a) Network Simulator 2 (NS2) : Installing NS2 On Windows 7
NS2 stands for Network Simulator Version 2. It is an open-source event-driven
simulator designed specifically for research in computer communication networks.
NS2 uses OTcl to create and configure a network, and uses C++ to run simulation.
All C++ codes need to be compiled and linked to create an executable file.
Use OTcl
i. For configuration, setup, or one time simulation, or
ii. To run simulation with existing NS2 modules.
This option is preferable for most beginners, since it does not involve complicated
internal mechanism of NS2. Unfortunately, existing NS2 modules are fairly limited.
This option is perhaps not sufficient for most researchers.
Use C++
i. When you are dealing with a packet, or - when you need to modify existing
NS2 modules.
Name_Rollno CEC-Landran Page 34
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
This option perhaps discourages most of the beginners from using NS2. This book
particularly aims at helping the readers understand the structure of NS2 and feel
more comfortable in modifying NS2 modules.
b) Installing NS2 on windows 7
NS2 builds and runs under windows using Cygwin. Cygwin provides Linux like
environment under windows.
System Requirements: A computer with C++ compiler. Building full NS2
package requires large memory space approximately 250MB
I. Steps to install NS 2 on windows 7 are given below
1. Download Cygwin from following link https://www.cygwin.com/setup.exe
2. Run the downloaded setup.exe and you will see screen shown below click next.
Figure 2.1
3. Select option "Install From Internet". If you have already downloaded the
package select "Install from local directory" and click next
Name_Rollno CEC-Landran Page 35
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure: 2.2
4. Keep the default installation directory as "C:\cygwin" and click next
Name_Rollno CEC-Landran Page 36
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 2.3
5. Keep default local package directory as your download folder and click next.
Figure 2.4
Network Simulator 2 (NS2) : Steps For Installing NS2
II. Steps is to install NS2
1. Download NS2 from following link: https://www.isi.edu/nsnam/dist/ns-allinone-
2.28.tar.gz
2. Decompress the file use winrar. Copy the decompressed folder the Cygwin
installation directory under the subdirectory home. It will be C:\cygwin\home\
system_name : where system_name is name of your system in above Cygwin
installation this path will be C:\Cygwin\home\sys27
3. Run Cygwin from desktop and change the directory to folder you copied just
now in step 2 command to change directory:cd /home/sys27/ns-allinone-2.28
NOTE: please change sys27 to name of your system
4. To start installation type following command:"./install"(WITHOUT qoutes)
This will began the installation process if any Cygwin package is missing it will be
reported to you if so the run Cygwin setu.exe and install the missing package and
start again from step 2.
Installation is a long process and take quite some time once it is finished you will
get a screen as shown below:
Name_Rollno CEC-Landran Page 37
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 2.4
5. Add following lines to the .bashrc
export NS_HOME=/home/sys27/ns-allinone-2.28
export
PATH=$NS_HOME/nam-1.11:$NS_HOME/tcl8.4.5/unix:$NS_HOME/tk8.4.5/unix:
$NS_HOME/bin:$PATH
export LD_LIBRARY_PATH=$NS_HOME/tcl8.4.5/unix:$NS_HOME/tk8.4.5/unix:
$NS_HOME/otcl-1.9:$NS_HOME/lib:$LD_LIBRARY_PATH
export TCL_LIBRARY=$NS_HOME/tcl8.4.5/library
NOTE: replace sys27 with your system name
6. To check if NS2 is installed correctly you can run one sample example given in
ns-tutorials folder
To run the example change the directory to examples folder: cd ./home/sys27/ns-
allinone-2.28/ns-tutorial/examples
Then type following command:
ns example2.tcl
Name_Rollno CEC-Landran Page 38
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 2.5
Experiment no 3
Aim: Implementation of routing protocol in NS2 for DSR protocol.
The Dynamic Source Routing protocol (DSR) is a simple and efficient Routing
protocol designed specifically for use in multi-hop wireless mobile nodes networks
called Ad hoc networks. DSR allows the network to be completely selforganizing
and self-configuring, without the need for any existing network infrastructure or
administration. This paper describe the design of our own implementation of DSR
protocol using DSR MANET draft in NS2 simulator environment and provide a
summary of some the simulation and testbed implementation results for the
protocol.
The Dynamic Source Routing Protocol is a source-routed on-demand routing
protocol. A node maintains route caches containing the source routes that it is
aware of. The node updates entries in the route cache as and when it learns about
new routes. DSR does not rely on functions like periodic routing advertisement, link
status sensing or neighbor detection packets and because of the entirely on
demand behavior, the number of overhead packets caused by DSR scales down to
zero.
Name_Rollno CEC-Landran Page 39
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Source code:
Not all flies in ./dsr/ directory are used by the ns-2. the routing agent is
implemented as Agent/DSRAgent.
Thus, the source codes include:
dsragent.cc (h): DSR agent class. major state machine handling routings.
Important variables; net_id, mac_id in ID type. (IP and MAC address), both of
them are initialzied by tcl commands to set the initla valie, the commads are
"addr" amd "mac_addr"
hdr_sr.cc(h): define hdr_sr class.
request_table.cc(h)
Path.h(cc): Path class. First, define struct ID, it has an unsigned long addr
a enum of ID_type, and a time stamp t. and then in Path class, ID[] is the key
members of the path, and operator [] is defined to return an element of ID
array. thus whenever the SRPacket.route[n] will return to the reference of
ID[n]. Other member variables include cur_index, len,
srpacket.h: Just define SRPacket class which enclose the hdr_sr as a full
packet. The SRPacket construct has two parameters, a normal packet and a
SR (Source Route) Header (a path variable). The constructor of "path" class
makes a path from the bits of an NS source route header. And the other two
variables of the SR packet are "dst" and "src" IP addresses.
Data Structure for Route
It is found that srh->addr and p.route are two different structures. srh() is always
along with the packet. however, when DSR agent received a packet, it will
SRPacket p(packet, srh);
This generate a "p" which is frequently used by all other functions. remember p
does not go along with the packet leaving dsr agent. Before the packet was sent
out of the agent, another statement will be used to update "SRH"
in sendOutPacketwithRoute
p.route.fillSR(srh);
Also, the tap() entry is also generate a p for its use. however, another entry point
of agent "xmitFailed" use srh() directly.
Special tcl interface.
Unless other routing protocol, the ns-2.1b9a,has a special node type named as
"SRNodeNew". From those routines in the ns-lib.tcl. We can see that speical. Also,
there is a tcl file in mobiloty/dsr.tcl is also related.
Simulator instproc create-node-instance args
Name_Rollno CEC-Landran Page 40
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
{
$self instvar routingAgent_
# DSR is a special case
if {$routingAgent_ == "DSR"}
{
set nodeclass [$self set-dsr-nodetype]
}
else
{
set nodeclass Node/MobileNode
}
return [eval new $nodeclass $args]
}
Simulator instproc set-dsr-nodetype {}
{
$self instvar wiredRouting_
set nodetype SRNodeNew
# MIP mobilenode
if [Simulator set mobile_ip_] {
set nodetype SRNodeNew/MIPMH
}
# basestation dsr node
if { [info exists wiredRouting_] && $wiredRouting_
== "ON"} {
set nodetype
Node/MobileNode/BaseStationNode
}
return $nodetype
}
DSR Signaling Packets in Brief:
route-request. the packet itself is a layer 3 packet with a unique destination
address, but MAC_Broadcast (labeled in common header's next_hop())
route-reply: unicasting in both layer 2 and 3.
route-error. unicasting in both layer 2 and 3. Generated when tx_failure in
lower layer.
Name_Rollno CEC-Landran Page 41
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Entry Points for DSR agent:
first, as normal, the recv() function which means a packet with a address
destine to this node or from upper-target.
xmitFailed(). This is the callback function when a MAC transmission failes.
Based on this chance, route-error message generated
tap(). This is a hidden entry when you turn promiscuous on. snooping the
route and shorten the path.
Basic functions:
recv(), the entry for a receving packet. depends on the ip address of the
packet and the SR (Source Route) header, call different functions to handle
it. like the diagram below:
Figure 3.1
The route-reply, route-request messages need special handling routines
written in the handlePacketReceipt() funciton. Note that if the RRequest
message reached the destination, the receiptent should send a RReply
message, this is done by a function
named returnSrcRouteToRequestor(p) which is called
in handlePacketReceipt(). Otherwise, if the route-request and route-error are
Name_Rollno CEC-Landran Page 42
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
not destined to us, for route-request, the function handleRouteRequest() is
called handlePacketReceipt().
A signaling reached its destination. There are two case:
o if it is a route-request and "not processed", sends back a route-reply,
pkt "p" is forged in this function and returnSrcRouteToRequestor(p)
o if it is a route-reply, call functiuon acceptRouteReply(p);
handleRouteRequest(): From the version 2.27, we see some unused codes
but probably under develop for future versions. It includes more close mac-
routing cooperation, such as neighbor identity (is_neighnor()), and channel
status (air_time_free()).
Basically, this function has three branches:
1. already processed, checked by function ignoreRouteRequestp(p).
2. has a cached route, done by replyFromRouteCache(p), and "cached
route" is enabled by the
flag dsragent_reply_from_cache_on_propagating.
3. append myself in route
with p.route.appendToPath(net_id); and sendOutPacketWithRoute(p,
false);
handleForwarding. Forward packet on to next host in source route and
snooping as appropriate. So, a route-reply message is not treat as
exceptional. It is a normal packet with sr header and be snooped by this
node. The snooping is enabled by the flag "dsragent_snoop_source_routes" .
handleForwarding is dcallin "handleDefaultforwarding" for doing some simple
operations for DSR rules. At last, the packet will be sent
by sendOutPacketWithRoute
sendOutPacketWithRoute: The function is used as for send packets, Take
packet and send it out, packet must a have a route in it. return value is not
very meaningful. if fresh is true then reset the path before using it, if fresh is
false then our caller wants us use a path with the index set as it currently is.
Basically,
o cmn header's failure callback functon and data are set
o cmn header 's next hop is set to addr of next-hop in dsr header.
address type are also set.
o move the pointer in SR header to the next (increase 1).
Actually, the third operation is not valid in real DSR implementations. To
undo this effect in error-handing, we'd better find current Ip address first and
locate the position of this address in SR header. The other two operations are
also invalid, because there are no common headers in a real packet. For the
"next_hop()" in common header, it is used by DSR only for those packets
without valid SR header, refer to recv().
returnSrcRouteToRequestor(); this function
Name_Rollno CEC-Landran Page 43
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
xmitFailed(): when the common header->xmit_failure_ point to a callback
function, thus, when the packet cannot be delivered, the callback function is
used, and finally will generate a route-error messages. There is always a
pointer in the SR header curr() . ( Refer to manet-ietf-dsr draft, there is no
such a pointer in DSR Source Route Option, but has a "segments left" field to
indicate how many nodes still to visit to reach the destination. ). Thus, an
innovation needs to be done to re-interprete the "srh->cur_addr()" as a index
number of the position in the path where fail happens. So, when not all
nodes along the path handle the SR header, we need find the ip address of
the node from srh. and set that index as cur_addr();
processBrokenRouteError(p); This should be another branch under the main
recv() entry. It gives what to do when a Route Error message is receoived or
heard (snooped). Snoop means the message was sent to another node but it
passes myself, so i heard it.
tap(const Packet *packet): This is another entry point for DSR. When
dsragent_use_tap flag is true. the mac is working in promiscuous mode and
all overhearing packets will be processed if there is a SR header in it.
Other:
The longest route we can handle is defined in : define MAX_SR_LEN 16 //
longest source route we can handle
Possible Reason for xmit_failure below IP layer:
arp failure
interface queue is full
mac transmission failure ( exceed the retry-limit)
DSR scheme options:
In the beginning of dsragent.cc, it define many bool selectors of some options like:
/*************** selectors ******************/
bool dsragent_snoop_forwarded_errors = true;
// give errors we forward to our cache?
bool dsragent_snoop_source_routes = true;
// should we snoop on any source routes we see?
bool dsragent_reply_only_to_first_rtreq = false;
// should we only respond to the first route request we
receive from a host?
bool dsragent_propagate_last_error = true;
// should we take the data from the last route error msg
sent to us
// and propagate it around on the next propagating route
request we do?
Name_Rollno CEC-Landran Page 44
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
// this is aka grat route error propagation
bool dsragent_send_grat_replies = true;
// should we send gratuitous replies to effect route
shortening?
bool dsragent_salvage_with_cache = true;
// should we consult our cache for a route if we get a
xmitfailure
// and salvage the packet using the route if possible
bool dsragent_use_tap = true;
// should we listen to a promiscuous tap?
bool dsragent_reply_from_cache_on_propagating =
true;
// should we consult the route cache before propagating rt
req's and
// answer if possible?
bool dsragent_ring_zero_search = true;
// should we send a non-propagating route request as the
first action
// in each route discovery action?
// NOTE: to completely turn off replying from cache, you
should
// set both dsragent_ring_zero_search and
// dsragent_reply_from_cache_on_propagating to false
bool dsragent_dont_salvage_bad_replies = true;
// if we have an xmit failure on a packet, and the packet
contains a
// route reply, should we scan the reply to see if contains
the dead link?
// if it does, we won't salvage the packet unless there's
something aside
// from a reply in it (in which case we salvage, but cut out
the rt reply)
bool dsragent_require_bi_routes = true;
// do we need to have bidirectional source routes?
// [XXX this flag doesn't control all the behaviors and code
that assume
// bidirectional links -dam 5/14/98]
#if 0
bool lsnode_holdoff_rt_reply = true;
// if we have a cached route to reply to route_request with,
should we
// hold off and not send it for a while?
bool lsnode_require_use = true;
Name_Rollno CEC-Landran Page 45
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
// do we require ourselves to hear a route requestor use a
route
// before we withold our route, or is merely hearing
another (better)
// route reply enough?
#endif
About Flow State:
It is also desirable to disable the flow state stuff. it make the dsr code messy. flow
state is not an orginal idea.
static const bool dsragent_enable_flowstate = false;
static const bool dsragent_prefer_default_flow = false;
Experiment no 4
Aim: Study other wireless sensor network simulators (Mannasim.
Contiki)
Simulator Mannasim: Mannasim simulation environment for WSN is actually a
framework based on foregoing ns2. Finding some useful information about
Mannasim is difficult and the documentation is unclear according to the opinion of
the author of this thesis. This section describes how can Mannasim be utilized with
ns-2. It consists of two following parts:
Mannasim Framework – The Mannasim Framework is a module for WSN simulation
which extends ns-2 introducing new modules for design, development and analysis
of different WSN applications.
Script Generator Tool – The Script Generator Tool (SGT) is a front-end for Tcl
simulation scripts easy creation. It is written in Java.
Name_Rollno CEC-Landran Page 46
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Mannasim Framework:
Mannasim provides twelve files which contain classes that extend corresponding
native classes of ns-2. A class called SensorNode extends a class MobileNode of ns-
2 and specifies several sensor characteristics like power consumption for sensing
and processing, the number of instructions executed per seconds by its
microcontroller or states of different sensor parts. This class can be used as initial
approach for different sensor node types development.
A Battery class extends the EnergyModel of ns-2. It can be used to implement
different existing battery models. It provides methods like turning sensor node on
and off, it can put it into a sleep mode and it can decrease energy when the sensor
performs sensing, processing or disseminating.
DataGenerator simulates the sensing task. Sensing interval may be adjusted and
some classes for specialized sensing may extend this class.
TemperatureDataGenerator and TemperatureAppData are examples of such
extensions and add characteristics proper for temperature data and methods to
work with the gathered data.
A Processing class simulates processing of the sensed data in every single sensor
node. It provides methods for data aggregation, dissemination etc.
After processing, the data are represented by SensedData class. It is ready for
dissemination and provides, among others, information like source node
identification, message type or message priority.
OnDemandData and OnDemandParameter can be used for representing messages
for the user of the simulated WSN. The former class deals with such messages
while the latter is used for querying them according to a given parameter. A
SensorBaseApp and its children CommonNodeApp and ClusterHeadApp are classes
that represent different applications for WSN.
Contiki: Contiki is another open-source operating system for embedded systems
and wireless sensor networks which is being developed at Swedish Institute of
Computer Science lead by software engineer Adam Dunkels. It provides both full IP
(Internet Protocol) networking and low-power radio communication mechanisms.
Contiki is written in C.
Hardware Support: Contiki can be run on several different hardware platforms.
Tmote Sky is probably the most known one based on a microchip MSP430 and
Name_Rollno CEC-Landran Page 47
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
using radio chip CC2420. Another platform suitable for Contiki is ESB (Embedded
Sensor Board) also based on MSP430 and using TR1001 low-power radio
transceiver. It is equipped with several kinds of sensors like sound, vibration,
movement or temperature detection. The ESB has been developed at the Free
University of Berlin and maintained by Scatterweb. A protocol uIPv6 (micro Internet
Protocol version 6; described in the next section) has been successfully tested on
Atmel AVR Raven platform.
Protocol Support: As it was already outlined, Contiki is particularly aimed to
provide IP communication for low-power sensor networks. Both IPv4 and IPv6 are
supported thanks to uIPv4 and uIPv6 implementations and also thanks to the so-
called 6lowpan mechanism which is used to compress and frame packets to be
transmitted more efficiently over IEEE 802.15.4 radio link. RPL, which has been
discussed in section D.1, is implemented for Contiki as well.
Experiment no: 5
Aim: Implementation of routing protocol in NS2 for AODV protocol
for TORA protocol
Name_Rollno CEC-Landran Page 48
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Part A: AODV Protocol
Steps involved in AODV routing protocol:
Path discovery
Reverse path setup
Forward path setup
Rout table management
Path maintenance
Local connectivity management
Advantages of NS2 Simulation Code for AODV:
Scalable to large population of nodes.
Broadcast is minimized.
Reduces memory requirements and needless duplications.
Loop-free routes are maintained by use of destination sequence number.
Nose store only the routes that are needed.
Simple AODV simulation in NS2 code
# Define options
set val(chan) Channel/WirelessChannel ;#
channel type
set val(prop) Propagation/TwoRayGround ;# radio-
propagation model
set val(netif) Phy/WirelessPhy ;# network
interface type
set val(mac) Mac/802_11 ;#
MAC Type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue
type
set val(ll) LL ;#
link layer type
set val(ant) Antenna/OmniAntenna ;# antenna
model
set val(ifqlen) 50
Name_Rollno CEC-Landran Page 49
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
;# max packet in ifq
set val(nn) 25 ;#
number of mobilnodes
set val(rp) AODV ;# routing
protocol
set val(x) 500 ;# X
dimensions of topography
set val(y) 400 ;# Y
dimensions of topography
set val(stop) 150 ;#
time of simulation end
set ns [new Simulator]
set tracefd [open testAODV.tr w]
set windowVsTime2 [open win.tr w]
set namtrace [open testAODV.nam w]
$ns trace-all $tracefd
$ns namtrace-all-wireless $namtrace $val(x) $val(y)
#set up topography object
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
#
# Create nn mobilenodes [$val(nn)] and attach them to the
channel.
#
# configure the nodes
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
Name_Rollno CEC-Landran Page 50
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
-movementTrace ON
for {set i 0} {$i < $val(nn) } { incr i } {
set node_($i) [$ns node]
$node_($i) set X_ [ expr 10+round(rand()*480) ]
$node_($i) set Y_ [ expr 10+round(rand()*380) ]
$node_($i) set Z_ 0.0
}
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at [ expr 15+round(rand()*60) ] "$node_($i) setdest
[ expr 10+round(rand()*480) ] [ expr 10+round(rand()*380) ]
[ expr 2+round(rand()*15) ]"
}
# Generation of movements
# $ns at 10.0 "$node_(0) setdest 250.0 250.0 3.0"
# $ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"
# $ns at 70.0 "$node_(2) setdest 480.0 300.0 5.0"
# $ns at 20.0 "$node_(3) setdest 200.0 200.0 5.0"
# $ns at 25.0 "$node_(4) setdest 50.0 50.0 10.0"
# $ns at 60.0 "$node_(5) setdest 150.0 70.0 2.0"
# $ns at 90.0 "$node_(6) setdest 380.0 150.0 8.0"
# $ns at 42.0 "$node_(7) setdest 200.0 100.0 15.0"
# $ns at 55.0 "$node_(8) setdest 50.0 275.0 5.0"
# $ns at 19.0 "$node_(9) setdest 250.0 250.0 7.0"
# $ns at 90.0 "$node_(10) setdest 150.0 150.0 20.0"
# Set a TCP connection between node_(2) and node_(11)
set tcp [new Agent/TCP/Newreno]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns attach-agent $node_(2) $tcp
$ns attach-agent $node_(11) $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 10.0 "$ftp start"
# Printing the window size
proc plotWindow {tcpSource file} {
global ns
set time 0.01
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
puts $file "$now $cwnd"
Name_Rollno CEC-Landran Page 51
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 10.1 "plotWindow $tcp $windowVsTime2"
# Define node initial position in nam
for {set i 0} {$i < $val(nn) } { incr i } {
# 30 defines the node size for nam
$ns initial_node_pos $node_($i) 30
}
# Telling nodes when the simulation ends
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "$node_($i) reset";
}
# ending nam and the simulation
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "stop"
$ns at 150 "puts \"end simulation\" ; $ns halt"
proc stop {} {
global ns tracefd namtrace
$ns flush-trace
close $tracefd
close $namtrace
}
$ns run
Name_Rollno CEC-Landran Page 52
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Part B: TORA Protocol
TORA is a protocol in wireless adhoc networks that works with timing parameters.
NS-2.35 comes with the TORA protocol by default but it has to be tweaked
manually to make it run.
Step 1: Generate a Scenario for TORA protoco using NS2 Scenario Generator NSG
Software.
We have created a tcl file using NSG2.1.jar
$] java -jar NSG2.1.jar
Three files have to be modified
~ns-2.35/tora/tora.cc
~ns-2.35/tora/tora.h
~ns-2.35/imep/imep.cc
There are various websites that tells you how to configure TORA by making
changes to the above three files.
Change 1: tora.h
In the tora.h file, go to the end of the File before the agent completes, include
these two lines
#include <classifier/classifier-port.h>
protected:
PortClassifier *dmux_;
Name_Rollno CEC-Landran Page 53
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 5.1 Tora.h Change
Change 2: tora.cc
Open the tora.cc and include the following lines in the
"int toraAgent::command(int argc, const char*const* argv) " function as
indicated in the figure below.
else if (strcmp(argv[1], "port-dmux") == 0) {
dmux_ = (PortClassifier *)TclObject::lookup(argv[2]);
if (dmux_ == 0) {
fprintf (stderr, "%s: %s lookup of %s failed\n", __FILE__, argv[1], argv[2]);
return TCL_ERROR;
}
return TCL_OK;
}
Name_Rollno CEC-Landran Page 54
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 5.2 Tora.cc Change
Change 3: imep.cc
In the file imep.cc, change the following line
rexmitTimer.start(rexat - CURRENT_TIME);
to
if (rexat-CURRENT_TIME<0.000001) // Preventing eternal loop.
rexmitTimer.start(0.000001);
else
rexmitTimer.start(rexat - CURRENT_TIME);
Name_Rollno CEC-Landran Page 55
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 5.3 IMEP Change
Step 3:
We need to recompile ns2 using the command make from the folder ns-2.35/
Once the changes are made, Open the Terminal and go to ~ns-2.35 and execute
the command
prompt$] make
Step 4: Run the tcl file now
$] ns TORA.tcl
This file is generated in Step 1
I will give all these files to you for your simulation.
Copy the tora.cc and tora.h file in your ns-2.35/tora folder
then copy the imep.cc file in to the ns-2.35/imep folder
and then copy the TORA.tcl file in your home folder or any folder.
Then do the compilation $] make
and then run the TORA.tcl file using $] ns TORA.tcl
Name_Rollno CEC-Landran Page 56
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Figure 5.4 TORA Protocol Animation
Simple TORA simulation in NS2 code
#
==========================================
============================
# Default Script Options
#
==========================================
============================
set opt(imep) "ON" ;# Enable/Disable IMEP
set opt(ragent) Agent/rtProto/TORA
set opt(pos) NONE ;# Box or NONE
if { $opt(pos) == "Box" } {
puts "*** TORA using Box configuration..."
}
#
==========================================
============================
Agent instproc init args {
$self next $args
Name_Rollno CEC-Landran Page 57
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
}
Agent/rtProto instproc init args {
puts "DOWN HERE 2"
$self next $args
}
Agent/rtProto/TORA instproc init args {
puts "DOWN HERE"
$self next $args
}
Agent/rtProto/TORA set sport_ 0
Agent/rtProto/TORA set dport_ 0
#
==========================================
============================
proc create-routing-agent { node id } {
global ns_ ragent_ tracefd opt
#
# Create the Routing Agent and attach it to port 255.
#
set ragent_($id) [new $opt(ragent) $id]
set ragent $ragent_($id)
$node attach $ragent [Node set rtagent_port_]
$ragent if-queue [$node set ifq_(0)];# ifq between LL and MAC
# now that the Beacon/Hello messages have been
# moved to the IMEP layer, this is not necessary.
# $ns_ at 0.$id "$ragent_($id) start" ;# start BEACON/HELLO
Messages
#
# XXX: The routing protocol and the IMEP agents needs handles
# to each other.
#
$ragent imep-agent [$node set imep_(0)]
[$node set imep_(0)] rtagent $ragent
#
# Drop Target (always on regardless of other tracing)
#
set drpT [cmu-trace Drop "RTR" $node]
$ragent drop-target $drpT
#
# Log Target
#
set T [new Trace/Generic]
Name_Rollno CEC-Landran Page 58
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
$T target [$ns_ set nullAgent_]
$T attach $tracefd
$T set src_ $id
$ragent log-target $T
#
# XXX: let the IMEP agent use the same log target.
#
[$node set imep_(0)] log-target $T
}
proc create-mobile-node { id } {
global ns_ chan prop topo tracefd opt node_
global chan prop tracefd topo opt
set node_($id) [new Node/MobileNode]
set node $node_($id)
$node random-motion 0 ;# disable random motion
$node topography $topo
#
# This Trace Target is used to log changes in direction
# and velocity for the mobile node.
#
set T [new Trace/Generic]
$T target [$ns_ set nullAgent_]
$T attach $tracefd
$T set src_ $id
$node log-target $T
$node add-interface $chan $prop $opt(ll) $opt(mac) \
$opt(ifq) $opt(ifqlen) $opt(netif) $opt(ant)
#
# Create a Routing Agent for the Node
#
create-routing-agent $node $id
#
==========================================
==================
if { $opt(pos) == "Box" } {
#
# Box Configuration
#
set spacing 200
set maxrow 7
set col [expr ($id - 1) % $maxrow]
set row [expr ($id - 1) / $maxrow]
$node set X_ [expr $col * $spacing]
Name_Rollno CEC-Landran Page 59
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
$node set Y_ [expr $row * $spacing]
$node set Z_ 0.0
$node set speed_ 0.0
$ns_ at 0.0 "$node_($id) start"
}
}
Name_Rollno CEC-Landran Page 60