0% found this document useful (0 votes)
80 views40 pages

Adhoc Practical File

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)
80 views40 pages

Adhoc Practical File

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
You are on page 1/ 40

DAV INSTITUTE OF ENGINEERING AND

TECHNOLOGY
JALANDHAR

ADHOC WIRELESS AND SENSOR


NETWORKS LAB
Lab File
(BTCS 717-18)

Submitted To : Submitted By :
Ms. Navdeep Kaur Name: Jaskaran Singh
Course: B.Tech
Branch & Sem: CSE – 7th Sem
Roll No.: 2103024
BTCS 717-18
INDEX

S.NO. EXPERIMENTS PAGE NO. REMARKS

1. Introduction of Wireless sensor network applications and its 2-19


simulation
2. Network Simulator installation of wireless sensor network. 20-23
3. Implementation of routing protocol in NS2 for DSR protocol 24-28

4. Study other wireless sensor network simulators (Mannasim. 29-30


Contiki)
5. Implementation of routing protocol in NS2 for AODV protocol for 31-39
TORA protocol

1
BTCS 717-18
Experiment : 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 the 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.

Figure 1.1Shows 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 protocols for sensor
networks. There are a number of advantages to this approach including lower cost, ease of

2
BTCS 717-18
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.
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.
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, protocols, and applications. Each category is represented by an
interface that defines its methods and events generated and consumed.
1. Event

3
BTCS 717-18
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 the 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 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

4
BTCS 717-18
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 bound 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 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.

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
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 below.

5
BTCS 717-18
● 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.

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
are arranged in numerous applications in different fields such as agricultural, military,
environment, medical, etc.

6
BTCS 717-18
● 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).
● 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
hierarchical 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.

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.

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

7
BTCS 717-18
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. Subcategories of Military Application and type of sensors in them.

Specifically, Chemical, Biological, Radiological, Nuclear, and Explosive (CBRNE) sensors,


along with Toxic Industrial Material (TIM) sensors, may be used to detect the presence of such
substances. To detect intrusions, WSNs may utilize infrared, photoelectric, laser, acoustic, and
vibration sensors.
The flexibility of WSN structures enables them to adapt to various requirements. For instance, in
battlefield operations, large-scale WSNs comprising thousands of nodes that are non-manually
deployed are commonly used. In urban warfare and force protection operations, WSNs typically
consist of hundreds of manually deployed nodes. In other-than-war operations, WSNs of all
scales and deployment methods are utilized.
WSNs 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 can be deployed on the battlefield near
the paths that enemy forces might use. The primary advantage is that the WSN can be
spontaneously positioned and function without requiring continuous attendance or maintenance.
The terrain of the battlefield is often highly variable, which significantly impacts both the
coverage and energy consumption of the sensor nodes. Some of these applications are outlined
below.
Figure1.6 illustrates the architecture of this system.

8
BTCS 717-18

In a submarine detection system for Anti-Submarine Warfare (ASW), 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.
Furthermore, the system can achieve a low False Alarm Rate (FAR) due to the very low range of
the active sonar (50 m), which solves the acoustic multipath problem of conventional sonobuoys.
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 using WSNs, providing an estimation of the
enemy's location. This type of application is described below.
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 their sources is
presented.
The specific detection system can be used in conjunction with an acoustic vector sensor to
amplify the possibility of locating threats by using the shockwave created by a supersonic bullet
and the muzzle blast produced by the gun.
They monitor various health status parameters in real time, such as blood pressure, oxygen
saturation, and heart rate. By utilizing the data collected, various methods can be applied to train
soldiers more efficiently and prepare them more effectively for future engagements.
c) Intruder Detection:
The knowledge of the location of the enemy is considered one of the most critical pieces of
information during military operations. Whichever side in a conflict possesses this knowledge
gains a significant advantage and moves closer to victory. By utilizing WSNs within a
battlefield, intruders can be detected in good time to prevent the loss of supplies or territory.
An intruder can be detected in various ways.
This system utilizes acoustic and seismic sensors to provide detection information to the user,
while tracking and visual sensors help lower the false alarm rate.

2) Health Applications: In the health domain, WSNs utilize advanced medical sensors to
monitor patients within a healthcare facility, such as a hospital, or within their home. They
also provide real-time monitoring of patients' vitals using 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 most commonly used in these applications.
WSNs developed for these types of health applications are examined in the following subsection.

9
BTCS 717-18

Figure 1.7.The subcategories of the health applications of WSNs and the sensors used
in them.
a) Patient Wearable Monitoring:
Health monitoring applications can be combined with wearable hardware that includes
embedded biomedical sensors, providing the patient’s health status in a remote environment or
within a healthcare facility.
This system uses real-time sensors incorporated into smartphones, along with a barcode system,
to offer personalized medicine care assistance. The developed mechanism performs
Electrocardiogram (ECG) monitoring in real time. Additionally, the monitoring of blood glucose
levels, blood pressure, and several other diagnostics is also possible using real-time sensors. This
system 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, aiming to provide


continuous monitoring for high-risk cardiac/respiratory patients. The system collects multiple
vital signs, detects multi-parameter medical emergencies, and is connected to a cellular
telemedicine center (TMC). This system uses a wrist-worn device to monitor the vital
parameters of patients, providing an integrated picture of their health condition.
b) Home AssistingSystems :

A homecare monitoring platform with internet remote connection is designed to assist people
and their environment. This platform can monitor and diagnose patients remotely, in real time,
within their home environment by utilizing wearable or even surgically inserted bio-sensors. A
hybrid model of the platform is proposed, with various levels 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 communication and coordination with an appointed
help center, such as a hospital.
One of the main reasons behind this technology is to commercialize it for the benefit of patients

10
BTCS 717-18
who are not financially sound. Furthermore, the system was developed in such a way that any
crisis phase is handled by automatically sending alert messages to the doctor.

Figure 1.9.The system configuration of the remote patient monitoring application


c) Hospital Patient Monitoring (orHospitalization):

Within healthcare facilities, such as a hospital, WSN systems can be integrated to provide
real-time patient monitoring and emergency alerting for a more precise and quick
response. One such WSN application involves wireless sensors placed within the
emergency rooms of John Hopkins Hospital to monitor the blood oxygen levels and heart
rate of patients in real time. The researchers collected the performance statistics of the
network, and despite the challenges posed by interference and radio noise in the hospital
environment, the application of WSNs can 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

3) Environmental Applications: Environmental applications that demand continuous


monitoring of ambient conditions in hostile and remote areas can be improved with the
utilization of WSNs. In Figure 11, 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.

Figure1.11. The subcategories of the environmental WSN applications and the types
of sensors used in them.
a) Water Monitoring:
Water, whether for drinking or oceanic purposes, is an important factor in human lives;
therefore, the monitoring of water is of great academic interest for researchers, as described

11
BTCS 717-18
below.
A WSN application is used to evaluate the quality of fresh drinkable water. Researchers designed
a Cyber Physical System (CPS) called PipeSense, which is an in-pipe system for water
monitoring that utilizes RFID (Radio Frequency Identification) based WSN. The network can
provide information about water demand, water quality, and various repair details, such as weak
spots or pipe leakage. The in-pipe RFID sensors collect data from the system and send it to the
data servers, where algorithms offer decision support.
b) Air Monitoring:
Air is a vital element for human life, and nowadays, air pollution in the atmosphere is a result of
many modern human activities. WSNs can be utilized for air quality monitoring in occupied
regions to prevent dangerous diseases, contamination, or risks to people's health.
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 the air
quality in real time and utilize the Zigbee protocol for data communication. The authors further
introduced the Clustering Protocol for Air Sensor Network (CPAS) 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
lower their costs. WSNs can be utilized for monitoring common disastrous causes in real time
to provide proactive alerts, helping to lower damage or even prevent a disaster. Typical
examples described in the rest of this subsection are related to the monitoring of seismic
activity, volcanic activity, forest fires, and tsunamis.
● 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, allowing for precautionary measures and
enabling authorities to act in advance. A real-time seismic activity monitoring system is
presented.
— Volcanic Activity Monitoring
Volcanoes can cause enormous damage to nearby towns or cities when they erupt. Before a
volcano erupts, there are many signs that a WSN system can proactively measure in order to
inform nearby citizens about the eruption.
The system is low-cost, flexible, and easy to deploy and maintain for remote locations. Users of
the system can choose GPS data synchronization when the sensor nodes have signal reception, or
a specific algorithm when they do not, to collect accurate timestamps for 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.

12
BTCS 717-18
● Forest Fire Prevention
Forest fires can destroy both animals and vegetation, resulting in huge ecological disasters. To
prevent such disastrous events, WSNs can be deployed within forests to monitor related
parameters in real time and 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
measures is extremely pressing. Related parameters such as temperature, humidity, etc., are
monitored in real time and sent to a monitoring center for analysis. The system can then make
quick estimations of fire danger and inform the authorities.
● Tsunami Detection
Another natural disaster is the tsunami wave. 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 utilizes a WSN with underwater sensor nodes deployed in coastal
regions. To inform authorities proactively, the system uses a lexical resource messaging system,
called SentiWordNet, which is able to provide information extracted from the sensor messages.

4) Flora and FaunaApplications: Both flora and fauna domains are vital for every country. In
Figure 12, the main subcategories of flora and fauna applications of WSNs—namely 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.

Figure 1.13. The subcategories of flora and fauna applications of WSNs and the types of
the sensors used in them.
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

13
BTCS 717-18
to crop growth, both inside and 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).
The system monitors vital greenhouse parameters such as indoor luminance, temperature, and
relative humidity, via sensor nodes. The indoor climate control is possible by utilizing two fuzzy
logic controllers, P (Proportional) and PD (Proportional-Derivative), that set the desired indoor
climatic set-points. Furthermore, the system utilizes output actuations of heating units, motor-
controlled windows, 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 WSN applications can be implemented. Crop
irrigation and fertilization are some examples of the applications that have been designed, as
described below.
The system used a B/S (browser/server) structure model to provide high interactivity. Also, a
GIS analysis server was used to interpolate the data from small experimental plots to larger plots,
exploiting 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, allowing animals to be moved towards them. The major objective of the
work was to design rugged hardware that could be used outdoors for modeling both individual
and 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 by factors such as animal body, mobility, etc.

14
BTCS 717-18

5) 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 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 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 decisions, the

15
BTCS 717-18
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, traveling 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 roadmap 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.

c) Simulation Tools:

This section illustrates main-stream simulation tools used in WSNs, such as Glomosim, NS-2,
SensorSim, Prowler, OMNeT++, TOSSIM, EmStar, J-Sim, ATEMU, and Avrora, and analyzes
the advantages and disadvantages of each simulation tool. The network simulator is a discrete
event packet-level simulator. The network simulator covers a very large number of applications
of different kinds of protocols for different network types, consisting of various network
elements and traffic models.
1) NS-2
NS-2[12] is the abbreviation for Network Simulator version 2, which was first developed in 1989
as the REAL network simulator. Now, NS-2 is supported by the Defense Advanced Research
Projects Agency (DARPA) and the National Science Foundation (NSF). NS-2 is a discrete event
network simulator built in an Object-Oriented extension of Tool Command Language (Tcl) and
C++ [C++]. Users can run the NS-2 simulator on Linux Operating Systems or on Cygwin. The
steps followed to write a program include:
● Initialization and termination aspects of the network simulator.
● Defining the network nodes, links, queues, and topology.
● Defining the agents and their applications.
● Network Animator (NAM).
● Tracing.
Advantage
● Non-specific network simulator
● Open source saves time and money and is 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

16
BTCS 717-18
● 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 jobs and time consuming than others.
● No GUI
● 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 systems. 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 running in real-time.
People can run this emulator on the Linux operating system..

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 a 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

17
BTCS 717-18
commercial license, used at "for-profit" environments. This simulator supports the module
programming model. Users can run OMNeT++ simulator on Linux Operating Systems, Unix-
like systems and Windows. OMNeT++ is a popular non-specific network simulator, which can
be used in both wired and wireless areas. Most frameworks and simulation models in OMNeT++
are open source.
Advantage
● 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 a GUI library,
which facilitates users to model or compile the Mathematical Modeling Language, a ―text-based
language‖ written to J-Sim models.

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 systems.ATEMU is a specific
emulator for WSNs; it can support users to run TinyOS on MICA2 hardware.

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

18
BTCS 717-18
● 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.

Advantage
● It is written in C++
● Platform independent
● WSN applications feature tight integration of computation, communication
● Interaction with the physical environment
Disadvantage
● Less customizable

9) COOJA (COntiki JAva)


COOJA is a simulator for the Contiki sensor node operating system. MSP Sim can be integrated
into COOJA, forming COOJA/MSPSim. 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
● 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, 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.

19
BTCS 717-18
Experiment : 2

Aim: Network Simulator installation of wireless sensor network.


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
mechanisms 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.
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.
Installing NS2 on windows 7
NS2 builds and runs under windows using Cygwin. Cygwin provides a 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 the screen shown below click next.

20
BTCS 717-18
Figure 2.1
3. Select option "Install From Internet". If you have already downloaded the package select
"Install from local directory" and click next

Figure: 2.2
4. Keep the default installation directory as "C:\cygwin" and click next

Figure 2.3
5. Keep default local package directory as your download folder and click next.

21
BTCS 717-18

Figure 2.4
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 using winrar. Copy the decompressed folder of 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 quotes)
This will begin the installation process if any Cygwin package is missing it will be reported to
you if so then run Cygwin setu.exe and install the missing package and start again from step 2.

22
BTCS 717-18
Installation is a long process and take quite some time once it is finished you will get a screen as
shown below:

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

Figure 2.5

23
BTCS 717-18
Experiment : 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 node networks called Ad hoc
networks. DSR allows the network to be completely self organizing and self-configuring,
without the need for any existing network infrastructure or administration. This paper describes
the design of our own implementation of the DSR protocol using the DSR MANET draft in the
NS2 simulator environment and provides a summary of some of 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.

Source code:

Not all files 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 initial value, the commands 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 SRPacketclass 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

SRPacketp(packet, srh);

This generates 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

24
BTCS 717-18

p.route.fillSR(srh);

Also, the tap() entry also generates a p for its use. However, another entry point of agent
"xmitFailed" uses 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 special. Also, there is a tcl file in
mobility/dsr.tcl is also related.
Simulator instproc create-node-instance args
{
$self instvarroutingAgent_
# 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 instvarwiredRouting_
set nodetypeSRNodeNew
# MIP mobilenode
if [Simulator set mobile_ip_] {
set nodetypeSRNodeNew/MIPMH
}

# basestationdsr 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 the lower
layer.

Entry Points for DSR agent:

25
BTCS 717-18
● First, as normal, the recv() function which means a packet with an address destined 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
shortening the path.

Basic functions:
● recv(), the entry for a receiving 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() function. Note that if the RRequest message reached the
destination, the recipient 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 not destined to us, for route-request,
the function handleRouteRequest() is calledhandlePacketReceipt().
● A signal 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 function 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:
0. already processed, checked by function ignoreRouteRequest(p).
1. has a cached route, done by replyFromRouteCache(p), and "cached route" is
enabled by the flag dsragent_reply_from_cache_on_propagating.
2. append myself in route
with p.route.appendToPath(net_id); and sendOutPacketWithRoute(p, false);

26
BTCS 717-18
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 calling "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 function 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-handling, we'd better find the current Ip address first and locate the position of
this address in the 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
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 message. 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-interpret the "srh->cur_addr()" as an 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 received or heard (snooped). Snoop means the
message was sent to another node but it passes by myself, so i heard it.
tap(const Packet *packet): This is another entry point for DSR. When the
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:

27
BTCS 717-18

/*************** selectors ******************/


bool dsragent_snoop_forwarded_errors = true;
// give errors we forward to our cache?
booldsragent_snoop_source_routes = true;
// should we snoop on any source routes we see?
booldsragent_reply_only_to_first_rtreq = false;
// should we only respond to the first route request we receive from a host?
booldsragent_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?
// this is aka grat route error propagation
bool dsragent_send_grat_replies = true;
// should we send gratuitous replies to effect route shortening?
booldsragent_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_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?
boollsnode_require_use = true;
// 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 makes the dsr code messy. flow state is not an
original idea.
static const bool dsragent_enable_flowstate = false;

static const bool dsragent_prefer_default_flow = false;

28
BTCS 717-18
Experiment : 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 Mannasim can 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.
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 an initial approach for different sensor node types development.
DataGenerator simulates the sensing task. Sensing intervals 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 the SensedData class. It is ready for dissemination
and provides, among others, information like source node identification, message type or
message priority.

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 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.

29
BTCS 717-18
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.

30
BTCS 717-18
Experiment : 5

Aim: Implementation of routing protocol in NS2 for AODV protocol for TORA
protocol

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 a large population of nodes.
● Broadcast is minimized.
● Reduces memory requirements and needless duplications.
● Loop-free routes are maintained by use of destination sequence numbers.
● Nose stores 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 ;# 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

31
BTCS 717-18

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 nnmobilenodes [$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 \
-movementTrace ON

for {set i 0} {$i< $val(nn) } { incri } {


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) } { incri } {


$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)
]"
}

32
BTCS 717-18

# 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"
$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) } { incri } {
# 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) } { incri } {
$ns at $val(stop) "$node_($i) reset";
}

33
BTCS 717-18
# 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 tracefdnamtrace
$ns flush-trace
close $tracefd
close $namtrace
}

$ns run

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 protocol 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>

34
BTCS 717-18
protected:
PortClassifier *dmux_;

Change 2: tora.cc
Open the tora.cc and include the following lines in the "int toraAgent::command(intargc,
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;
}

Figure 5.2Tora.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);

35
BTCS 717-18

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

36
BTCS 717-18

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 instprocinitargs {
$self next $args
}
Agent/rtProtoinstprocinitargs {
puts "DOWN HERE 2"
$self next $args
}
Agent/rtProto/TORA instprocinitargs {
puts "DOWN HERE"

37
BTCS 717-18
$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.
#
$ragentimep-agent [$node set imep_(0)]
[$node set imep_(0)] rtagent $ragent

#
# 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)

38
BTCS 717-18
$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]
$node set Y_ [expr $row * $spacing]
$node set Z_ 0.0
$node set speed_ 0.0

$ns_ at 0.0 "$node_($id) start"


}
}

39

You might also like