Top Banner
STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++ 1. INTRODUCTION 1.1 GENERAL OVEREVIEW OF THE PROJECT Wireless sensor networks are emerging as an important domain of research in field of Information Technology which involve hardware and system design, networking, distributed algorithms, programming models, data management and security. A wireless sensor network (WSN) is a computer network consisting of spatially distributed autonomous devices using sensors to cooperatively monitor physical or environmental conditions, such as temperature, sound, vibration, pressure, motion or pollutants, at different locations. WSNs were motivated by its first use in military applications such as battlefield surveillance but now they are used in many civilian application areas such as environmental and habitat monitoring, health care applications, home automation, and traffic control. A node in a wireless sensor network is very constrained in terms of energy, computational power and memory. Also in a deployed wireless sensor network the number of nodes run in factors of hundreds and thousands so it become a very tough job to route the information through the network keeping in mind the limited resources available with the nodes. Events such as sensing data, computation, storing data and SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 1
87
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

1. INTRODUCTION

1.1 GENERAL OVEREVIEW OF THE PROJECT

Wireless sensor networks are emerging as an important domain of research in field of

Information Technology which involve hardware and system design, networking,

distributed algorithms, programming models, data management and security.

A wireless sensor network (WSN) is a computer network consisting of spatially

distributed autonomous devices using sensors to cooperatively monitor physical or

environmental conditions, such as temperature, sound, vibration, pressure, motion or

pollutants, at different locations. WSNs were motivated by its first use in military

applications such as battlefield surveillance but now they are used in many civilian

application areas such as environmental and habitat monitoring, health care applications,

home automation, and traffic control.

A node in a wireless sensor network is very constrained in terms of energy,

computational power and memory. Also in a deployed wireless sensor network the

number of nodes run in factors of hundreds and thousands so it become a very tough job

to route the information through the network keeping in mind the limited resources

available with the nodes. Events such as sensing data, computation, storing data and

receiving and forwarding of data from node to node of node to base station are energy

consuming tasks. But most of the energy consumed is by the radio transmission and data

computation.

So it is very much desirable that the routing protocols designed and implemented for a

wireless sensor networks are efficient in terms of energy consumption as it helps in

extending the life of the WSN to longer periods.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 1

Page 2: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

1.2 LITERATURE SURVEY

1.2.1 WSN Node Architecture

A wireless sensor networks consists of tiny sensor nodes which are electronic devices

equipped with a sensor, a transceiver, a microcontroller, and an analog to digital

converter. The sensor is used to sense the environment and capture the sensed data and

provide it to the microcontroller through the ADC(analog to digital converter). The

microcontroller performs some basic computations like aggregation of data etc. and

stores it .The information is transmitted to other nodes through a wireless radio

transmitter.

The nodes in the network have very limited computational, memory and energy capacity.

All the operations of the node are performed using the limited battery energy which may

not be recharged. When the energy gets depleted completely the node is not able to

function and it dies.

The following figure describes the architecture of a typical WSN node:

Fig 1: A typical WSN node

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 2

Page 3: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

1.2.2 WSN Topologies

The development and deployment of wireless sensor networks(WSN) have taken the

traditional network topologies in new directions. Many of today’s sensor applications

require networking alternatives that reduce the cost and complexity while improving the

overall reliability. This section briefly describes four basic types of common wireless

sensor data network topologies.

i. Peer-to-Peer:

Peer-to-peer networks allow each node to communicate directly with another

node without needing to go through a centralized communications hub. Each

peer device is able to function as both a ‘client’ and ‘server’ to other nodes on

the network. An example of peer-to-peer network is shown in figure below.

Fig 2: a peer-to-peer network.

ii. Star topology:

Star networks are connected to a centralized communications hub. Each node

cannot communicate directly with one another; all communications must be

routed through the centralized hub. Each node is then a ‘client’ while the

central hub is the ‘server’. An example of a star network is shown in the figure

below:

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 3

Page 4: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

Fig 3: a star network.

iii. Tree Topology:

Tree networks use a central hub called root node as the main communications

router. One level down from the root node in the hierarchy is a central hub.

This lower level then forms a star network. The tree network can be

considered a hybrid of both the star and peer-to-peer networking topologies.

An example of a tree network is shown in the figure below:

Fig 4: a Tree network.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 4

Page 5: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

iv. Mesh Topology:

Mesh networks allow data to hop from node to node, this allows the network

to be self-healing. Each node is then able to communicate with each other as

the data is routed from node to node until it reaches the desired location. An

example of a Mesh network is shown in the figure below. This type of

network is one of the most complex and can cost a significant amount of

money to deploy properly.

Fig 5: a Mesh network.

1.2.3 WSN Applications

Wireless sensor networks found their first use in the military for battlefield surveillance.

Since then, WSNs are used in varied areas as listed below:

i. Military applications

a. Battlefield surveillance

b. Information collection.

c. Enemy tracking

d. Target classification.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 5

Page 6: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

ii. Environmental monitoring

a. Temperature monitoring

b. Rain monitoring

c. Pressure monitoring

d. Weather monitoring

e. Fire and smoke detection.

f. Structural monitoring.

g. Habitat monitoring.

h. Agriculture monitoring

iii. Support for logistics

a. Inventory control.

b. Asset tracking with RF ID tags.

c. Anti-theft detection systems.

iv. Application to robotics.

v. Health care monitoring.

and many more. The possible use of wireless sensor networks extends over a vast area of

human activity. Although most of the applications are still under research and few

completed products or services have become available for public use, there is remarkable

effort and progress.

1.3 ORGANISATION OF THE REPORT

Being a study based project most of the points relevant to software engineering principles

do not apply here but i have tried to illustrate the portions where any software

engineering methodology has been applied. Thus the report contains relevant categories

such as brief introduction of routing protocols, OMNET++ simulator introduction and

implementation details and conclusion.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 6

Page 7: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

2. STUDY OF ROUTING PROTOCOLS

Routing protocols are concerned with how a node communicates with any other node in

a network. When a node wants to send a packet to some destination node, which path is

followed is determined by the routing protocols. The routing technique is implemented in

the network layer of a network communication model like ISO-OSI or TCP/IP. So

routing may be defined as a process by which a node sends information messages or

packets to any destination node through zero or more intermediate nodes.

2.1 Design Issues

In case of wireless sensor networks, design and implementation of routing protocols are

the most important factor in determining the success of the WSN deployed. A wireless

sensor network is a form of wireless ad-hoc network and as such they have very limited

power resources, limited computational capabilities, limited communication capabilities

and limited memory. So the routing protocols for the WSNs must be designed keeping

these issues in mind.

i. Fault Tolerance: the failure of a sensor node should not affect the overall task of the

sensor network.

ii. Scalability: the number of sensor nodes deployed in a region may be in order of

hundreds or thousands or more and routing schemes must be scalable enough to

respond to events.

iii. Power Consumption: the transmission power of a wireless radio is proportional to

distance squared or even higher order in presence of obstacles. Sensor nodes are

equipped with limited power and node lifetime is strongly dependent on its battery

lifetime.

iv. Data Delivery Models: depending on the application of the WSN the data delivery

model to the sink can be continuous, event-driven, Query-driven or hybrid. In

continuous delivery model, each sensor sends data periodically. In event-driven

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 7

Page 8: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

models, the transmission of data is triggered when an event occurs. In query-driven

model, the transmission is triggered when the sink generates some query.

v. Data Aggregation: sensor nodes might generate redundant data and so similar

packets from multiple nodes can be aggregated so that transmissions would be

reduced. This computation will cost less energy consumption than required for

transmission of redundant packets each time and such substantial energy savings can

be made.

vi. Quality of Service (QoS): it means the quality service required by the application, it

could be the length of life time, data reliability, location awareness etc. These factors

affect the selection of a routing protocol for particular application. For example: In

military applications it may be required that data be delivered within a certain period

of time it is sensed.

vii. Data Latency and Overhead: data aggregation and multi-hop relays cause data

latency. Some routing protocols also create excessive overheads to implement their

algorithms, which are not suitable for serious energy constrained networks.

viii. Node Deployment: the node deployment is either deterministic or self-organising. In

deterministic situations the sensors are manually placed and data is routed through

pre-determined paths. In self organising systems, the sensor nodes are scattered

randomly creating an ad-hoc infrastructure. In that infrastructure the position of the

sink or cluster head is crucial in terms of energy efficiency and performance.

2.2 Classification of WSN Routing Protocols:

In general, there are three categories of routing algorithm in Wireless Sensor networks

depending on the network structure:

1. Flat based routing.

2. Cluster based routing, and

3. Location based routing.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 8

Page 9: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

In flat based routing, all the nodes in the network have equal roles. The all perform the

same job of sensing and gathering data.

In cluster based routing, different nodes play different roles in the network. Some nodes

are only meant to sense the data and some nodes have the job to process and send the

information.

In location based routing, nodes location in the network is used as a means for effective

routing. The distance between nodes are measured based on their incoming signal

strength and the appropriate route decided on that basis.

On basis of protocol operation the routing for WSN can be classified into the following:

1. Query-based.

2. Negotiation-based.

3. Multipath-based.

4. QoS –based

5. Coherent-based

A routing algorithm can be adaptive if certain system parameters can be changed to

adapt to the current network conditions.

In query based routing the destination node send a query of data to the network. The node

which has the requested data sends the data back as per the query to the node that

initiated the query.

In negotiation based routing high level data descriptors are used in order to eliminate

redundant data transmissions through negotiations.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 9

Page 10: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

In multipath based routing, multiple paths are maintained and used between the source

and the destination.

In QoS based routing, the quality of service is maintained by balancing between the data

quality and the energy consumption.

In coherent based routing, data processing is a major component in the operation of

wireless sensor networks.

Direct Routing : This is the simplest way of routing which falls under flat based routing

category. In this routing protocol each node directly communicates with the base node.

But this technique although has optimal accuracy, is unrealistic in real world applications

as the base has only limited number of channels to communicate with the sensor nodes.

Also the communication distance of a sensor node is limited so over a large area where

the nodes are very far this method cannot be applied successfully.

Multi-hop Routing: Due to the limitations in the direct routing approach, multi-hop

routing is used to communicate with the base station. Here the data travels from source to

destination through one or more intermediate nodes. This ensures that nodes in the

network die slow as compared to the direct approach and also that the data reaches the

base station.

2.3 Comparison of Routing Protocols:

In this section one protocol for each routing category is listed and summarized:

2.3.1 Flat based routing :

In flat based routing each node plays the same role and sensor nodes collaborate together

to perform sensing task. Due to large number of such nodes it is not feasible to assign a

global identifier to each node. This consideration has led to data-centric routing, where

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 10

Page 11: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

the base station sends queries to certain regions and waits for the data from the sensors

located in the selected regions. Since data is being requested through queries, attribute

based naming is necessary to specify the properties of data. SPIN and Directed Diffusion

are two of the data centric flat based routing protocols that have motivated the design of

many other similar protocols.

Sensor Protocols for Information via Negotiation (SPIN): In this protocol the

information at each node is disseminated to every other node in the network assuming

that all the nodes are potential base stations. This enables user to query any node and get

the required information immediately. These protocols make use of the property that

nodes in close proximity have similar data, and hence there is a need to only distribute

the data that other nodes do not posses. Nodes running SPIN assign a high level name to

completely describe their collected data (called meta-data) and perform meta-data

negotiations before any data is transmitted. This assures that there is no redundant data

sent throughout the network.

One of the advantages of SPIN is that topological changes are localized since each node

needs to know only its single hop neighbours. It provides much energy saving than

flooding and meta-data negotiations almost halves the redundant data. However SPIN

data advertisement mechanism cannot guarantee the delivery of data. To see this,

consider the application of intrusion detection where data should be reliably reported over

periodic intervals and assume that nodes in the data are located far away from the source

node and the nodes between source and destination nodes are not interested in that data,

such data will not be delivered to the destination at all.

2.3.2 Hierarchical routing :

Concept of hierarchical routing is also utilized to perform energy efficient routing in

WSNs. In hierarchical architecture, the higher energy nodes can be used to process and

send the information while low energy nodes can be used to perform the sensing in the

proximity of the target. This means that creation of clusters and assigning special tasks to

the cluster heads can greatly contribute to overall system scalability, lifetime, and energy

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 11

Page 12: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

efficiency. Hierarchical routing is mainly two layer routing where one layer is used to

select cluster heads and the other layer is used for routing. However, most techniques in

this category are not about routing, rather on “ who and when to send or

process/aggregate “ the information, channel allocation. LEACH protocol is the foremost

protocol in this category and has inspired many routing protocols designed and improved

upon it.

Low Energy Adaptive Clustering Hierarchy (LEACH): It is a hierarchical protocol in

which most nodes transmit to cluster heads, and the cluster heads aggregate and compress

the data and forward it to the base station. Each node uses stochastic algorithm at each

round to determine whether it will become a cluster head in this round. LEACH assumes

that each node has a radio powerful enough to directly reach the base station or the

nearest cluster head, but that using this radio at full power all the time would waste

energy.

Nodes that have been cluster heads cannot become cluster heads again for P rounds,

where P is the desired percentage of cluster heads. Thereafter each node has a 1/P

probability of becoming the cluster head in each in each round. At the end of each round,

each node that is not a cluster head selects the closest cluster head and joins the cluster.

The cluster head then creates a schedule for each node in its cluster to transmit its data.

All nodes that are not cluster heads only communicate with the cluster head in TDMA

( Time Division Multiple Access ) fashion, according to the schedule created by the

cluster head. They do so using the minimum energy needed to reach the cluster head, and

only need to keep their radios on during their time slot.

The operation of LEACH is separated in two phases : i). The setup phase and ii). The

steady state phase. In setup phase the clusters are organised and the cluster heads are

selected. In the steady state phase the actual data transfer to the base station takes place.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 12

Page 13: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

i). The setup phase:

During this phase a predetermined fraction of nodes, P, elect themselves as cluster heads

as follows.

A sensor node chooses a random number , r, between 0 and 1. If this random number is

less than a threshold value, T(n), the node becomes the cluster head for the current round.

The threshold value is calculated based on a equation that incorporates the desired

percentage to become a cluster head, the current round, and the set of nodes that have not

been selected as a cluster head in the last (1/P) rounds, denoted by G. It is given by:

T (n )=P/¿ , if n ε G.

Where G, is the set of nodes that are involved in cluster head election. Each selected

cluster head broadcast an advertisement message to the rest of the nodes in the network

that they are the new cluster heads. All the non- cluster head nodes, after receiving this

advertisement decide in the cluster to which they want to belong to. This decision is

based in the signal strength of the advertisement. The non-cluster head nodes inform the

cluster heads that they will be a member of the cluster. After receiving all the message

from the nodes that would like to be included in the cluster and based on the number of

nodes in the cluster, the cluster head node creates a TDMA schedule and assigns each

node a time slot when it can transmit. This schedule is broadcast to all nodes in the

cluster.

ii). The steady state phase: during this phase, the sensor nodes can begin sensing and

transmitting data to the cluster heads. The cluster head node, after receiving all the data,

aggregates it before sending it to the base station. After a certain time which is determine

a priori, the network goes back into the setup phase again and enters another round of

selecting new cluster head. Each cluster communicates using different CDMA codes to

reduce interference from nodes belonging to other clusters.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 13

Page 14: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

Although the LEACH protocol acts in a good manner, it suffers from many drawbacks

such as:

1. Cluster head selection is done randomly, that does not take into account energy

consumption. All node start with equal energy residual levels.

2. It cannot cover a large area. LEACH assumes that all nodes can transmit with enough

power to reach the base station if needed and each node has computational power to

support different MAC protocols.

3. It also assumes that nodes always have data to send, and nodes located close to each

other have correlated data.

4. Cluster heads are not uniformly distributed; whereas the cluster heads can be located

at the edges of the cluster. It may also lead to concentration of cluster-head in one

area of the network.

5. It is not efficient for large scale networks.

6. Fixed percentage of cluster-heads for any size networks.

7. It assumes that all nodes can communicate over one hop(directly) with the base

station.

Fig 6: LEACH protocol architecture.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 14

Page 15: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

2.3.3 Location based routing:

In this kind of routing sensor nodes are addressed by means of their locations. The

distance between the neighbouring nodes can be estimated on the basis of incoming

signal strengths. Relative coordinates of neighbouring nodes can be obtained by

exchanging such information between neighbours. Alternatively the location of nodes

may be available directly by communicating with a satellite, using GPS (Global

Positioning System), if nodes are equipped with small low power GPS receiver. To save

energy, some location based schemes demand that nodes should go to sleep when there is

no activity. SPAN, GEAR, GAF are some examples of geographical routing protocols.

Geographic and Energy Aware Routing (GEAR) : the key idea in GEAR is to restrict

the number of interests in directed diffusion by only considering a certain region rather

than sending the interests to the whole network. By doing this GEAR can conserve more

energy than directed diffusion. Each node in GEAR keeps an estimated cost and a

learning cost of reaching the destination through its neighbours. The estimated cost is a

combination of residual energy and distance to the destination. The learned cost is a

refinement of the estimated cost that accounts for routing around holes in the network. A

hole occurs when a node does not have any close neighbour to the target region than

itself. If there are no holes, the estimated cost is equal to the learned cost.

There are two phases in the algorithm:

1. Forwarding packets towards the target region: upon receiving a packet a node checks its

neighbours to see if there is one neighbour, which is closer to the target region then itself.

If there is more than one, the nearest neighbour to the target region is selected as the next

hop. If they are all further than the node itself, this means there is a hole. In this case one

of the neighbours is picked to forward the packet based on learning cost function.

2. Forwarding the packets within the region: If the packet has reached the region, it can be

diffused in that region by either recursive geographic forwarding or restricted flooding.

Restricted flooding is good when the sensors are not densely deployed.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 15

Page 16: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

3. A BRIEF INTRODUCTION OF OMNET++

OMNET++ is an object-oriented modular discrete event network simulator. The

simulator can be used for:

Traffic modelling of telecommunication networks

Protocol modelling

Modelling queuing networks.

Modelling multiprocessors and other distributed hardware systems.

Validating hardware architectures.

Evaluating performance aspects of complex software systems.

Modelling any other system where discrete event approach is suitable.

OMNET++ provides the basic machinery and tools to write simulations, but itself it does

not provide any components specifically for computer network simulations, queuing

network simulations, system architecture simulations or any other area. Instead these

application areas are supported by various simulation models and frameworks such as the

Mobility Framework and the INET Framework. These models are developed completely

independently of OMNET++, and follow their own release cycles.

An OMNET++ model consists of hierarchically nested modules. The depth of module

nesting is not limited, which allows the user to reflect the logical structure of the actual

system in the model structure. Modules communicate through message passing.

Messages can contain arbitrarily complex data structures. Modules can send messages

either directly to their destination or along a predefined path, through gates and

connections.

Modules can have their own parameters. Parameters can be used to customize module

behaviour and to parameterize the model’s topology.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 16

Page 17: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

Modules at the lowest level of the module hierarchy encapsulate behaviour. These

modules are termed simple modules, and they are programmed in C++ using the

simulation library.

OMNET++ simulations can feature varying user interfaces for different purposes:

debugging, demonstration and batch execution. Advanced user interfaces make the inside

of the model visible to the user, allow control over simulation execution and to intervene

by changing variables/objects inside the model. This is very useful in the

development/debugging phase of the simulation project. User interfaces also facilitate

demonstration of how a model works.

The simulator as well as user interfaces and tools are portable: they are known to work on

windows and on several Unix flavours, using various C++ compilers.

Hierarchical Modules

An OMNET++ model consists of hierarchically nested modules, which communicate by

passing messages to each other. OMNET++ models are often referred to as networks. The

top level module is the system module. The system module contains submodules, which

can also contain submodules themselves. The depth of the module nesting is not limited,

this allows user to reflect the logical structure of the actual system in the model structure.

Model structure is described in OMNET++’s NED language.

Both simple and compound modules are instances of module types. While describing the

model, the user defines module types; instances of these module types serve as

components for more complex module types. Finally, the user creates the system moduls

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 17

Page 18: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

as an instance of a previously defined module type; all modules of the network are

instantiated as submodules and sub-submodules of the system modules.

When a module type is used as a building block, there is no distinction whether it is a

simple or a compound module. This allows the user to split a simple module into several

simple modules embedded into a compound module, or vice versa, aggregate the

functionality of a compound module into a single module, without affecting existing

users of the module type.

Messages, Gates and Links

Modules communicate by exchanging messages. In actual simulation messages can

represent frames or packets in a computer network, jobs or customers in a queuing

network or other types of mobile entities. Messages can contain arbitrarily complex data

structures. Simple modules can send messages either directly to their destination or along

a predefined path, through gates and connections.

The “local simulation time” of a module advances when the module receives a message.

The message can arrive from another module or from the same module( self –messages

are used to implement timers).

Gates are the input and output interfaces of the modules; messages are sent through

output gates and arrive through input gates.

Each connection(also called link) is created within a single level of the module hierarchy.

Within a compound module, one can connect the corresponding gates of two submodules,

or a gate of one submodule and a gate of the compound module.

Fig 7: submodules connected to each other submodules connected to parent module.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 18

Page 19: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

The simple modules of a model contain algorithms as C++ functions. The full flexibility

and power of the programming language can be used, supported by the OMNET++

simulation class library. The simulation programmer can chose between event-driven and

process-style description, and can freely use object-oriented concepts and design patterns

to extend the functionality of the simulator.

Simulation objects(messages, modules, queues) are represented by the C++ classes. They

have been designed to work together efficiently creating a powerful simulation

programming framework. The following classes are part of the simulation class library:

Modules, gates, connection etc.

Parameters

Messages

Container classes(e.g. queue, array)

Data collection classes

Static and distribution estimation classes( histograms, P2 algorithm for calculating

quantities etc.)

Transient detection and result accuracy detection classes

The classes are also instruments, allowing one to traverse objects of a running simulation

and display information about them such as name, class name, state variables or contents.

This feature has made it possible to create a simulation GUI where all internals of the

simulation are visible.

Compound Modules

Parameters and gates for compound modules are declared and work in the same way as

with the simple modules. Typically, compound module parameters are passed to

submodules and used for initializing their parameters.

Parameters can also be used in defining the internal structure of the compound module:

the number of submodules and iszes of gate vectors can b defines with th help of

parameters, and parameters can also be used in defining the connections inside the

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 19

Page 20: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

compound module. As a practical example, you can create a router compound module

with a variable number of ports, specified in a numOfPorts parameter.

Parameters affecting the internal structure should always be declared const, so that

accessing them always yields same value. Otherwise, if a parameter was assigned a

random value, one could get a different value each time the parameter is accessed during

building the internals of the compound module, which is surely not what was meant.

Example:

Module Router

parameters:

packetsPerSecond: numeric,

bufferSize: numeric,

numOfPorts: const;

gates:

in: inPort[];

out: outPort[];

submodules://…

connections://…

endmodule

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 20

Page 21: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

4. IMPLEMENTATION OF LEACH

This section presents a detailed implementation code for the SolarLeach- LeachFarBs

which improves upon the classic LEACH code by introducing solar nodes to increase the

life of the network in whole. The section is divided into two parts : the NED description

for different modules and the C++ implementation code for the modules.

4.1 Network Topology Description(NED):

1. node.ned

simple Node

parameters: id: const, energy, sunstart, xpos: const, ypos: const; gates: in: in[]; out: out[];

endsimple

2. bs.ned

simple B parameters: id: const, xpos: const, ypos: const; gates: in: in[]; out: out[];

endsimple

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 21

Page 22: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

3. solar.ned

import "node", "bs";

module Solar parameters: numNodes: numeric, trRange: numeric, rounds: numeric, frames: numeric, solarOn: numeric, sunDuration: numeric, sunNodes: numeric, xMax: numeric, yMax: numeric; submodules: bs: BS; parameters: id = 1, xpos = xMax/2, ypos = 600; node: Node[numNodes]; parameters: energy = intuniform(499900,500000), sunstart = intuniform(20,(numNodes/sunNodes)*sunDuration), //energy = energy, id = index+2, xpos = intuniform(0, xMax), ypos = intuniform(0, yMax); connections nocheck:endmodule

//// Instantiates the network//network solar : Solarendnetwork

msg file: cl_msg.msg

// Base class for message types//message ClusterMessage

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 22

Page 23: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

{ fields: int proto; int srcAddress; int destAddress;}

//// Status sent from Node to BS//message Status2BSMessage extends ClusterMessage{ fields: int energy; int status; int cluster; int xpos; int ypos;}

//// BS sends this message to anounce cluster heads to nodes//message ClusterHeadMessage extends ClusterMessage{ fields: int cHead[103];}

//// TDMA message//message TDMAMessage extends ClusterMessage{ fields: int frames; int frameTime; int tdma[103]; // XXX constant

}

//// Data sent by nodes to cluster heads//message DataToCHMessage extends ClusterMessage{

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 23

Page 24: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

fields: int newSun; // node has now sun, become new cluster head? int data;}

//// Data sent by nodes to BS//message Data2BSMessage extends ClusterMessage{ fields: int data;}

4.2 C++ CODE:

node.h :

#ifndef NODE_H#define NODE_H

#include <omnetpp.h>#include "solar.h"#include "nodebase.h"#include "bs.h"

/** * Represents a node in the network */class Node : public NodeBase{ Module_Class_Members(Node, NodeBase, 0);

protected: virtual void initialize(); virtual void handleMessage(cMessage * msg); virtual void finish();

void sendExploratory(int src, int rec, char attr, int value, int data, int scount, int bcount, int hopcount, int seqNumber); void sendData(int src, int rec, char attr, int value, int data, int scount, int bcount, int mustShortest); void sendReinforcement(int src, int rec, char attr, int value, int bcount, int scount, int hops,

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 24

Page 25: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

int seqNumber, int period, int strategy);

void send2BS(int src, int rec, int energy, int status, int cluster, int xpos, int ypos); void initNodes(); void sendTDMA(); void sendDataToCHead(int newSun); void sendData2BS(int data); void energyReceive(int bits); void energyTransmit(int bits, int dist); void energyDataAggr(int signals);

public: //XXX int minhops; // min hops to sink int minBCount; // min hops with batteryCount

int xpos; // just for simulation int ypos; int nrRounds; // number of rounds (each round starts with setups) int nrFrames; // number of "rounds in a round" (called frames) int curFrame; int frameTime; // how many slots has one frame int myData; int mySlot; // slot in current frame int bsId; // ID of base station

double energy; // XXX energy in microJoule XXX nnode.h int headDist; // distance to head int bsDist; int myCluster; // to which cluster this node belongs

Node *nodePtr[103]; int clusterNodes;

int cHead; // flag denoting if I this node is cluster head int headId; // id of cluster head (my cluster)

int nrDataPackets; // nr of data packets head has received in this frame int sentBS; // how many status updates sent to BS by this node int wasHead; // ctr denoting how often a node was cluster head int headSun; int headBatt;

// variables for solar stuff int sunStart; int solarOn; int sunDuration;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 25

Page 26: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

int repeatTime; int sunNodes; int expectedEndTime;};

#endif

node.cpp:

#include <stdio.h>#include <string.h>

#include <omnetpp.h>#include "node.h"#include "bs.h"#include "cl_msg_m.h"#include "cgate.h"

Define_Module(Node);

void Node::initialize(){ int i; cMessage *cm; cMessage *cm2; cModule *parent = parentModule();

this->initStats(); this->myId = par("id"); this->xpos = par("xpos"); this->ypos = par("ypos"); this->nrGates = (int) parent->par("numNodes") + 3; this->energy = (double) par("energy"); this->myCluster = 0; this->nrNodes = (int) parent->par("numNodes"); this->nrFrames = (int) parent->par("frames"); this->nrRounds = (int) parent->par("rounds"); this->solarOn = (int) parent->par("solarOn"); this->sunDuration = (int) parent->par("sunDuration"); this->sunStart = par("sunstart"); this->sunNodes = (int) parent->par("sunNodes");

this->myData = 0; this->curFrame = 0; this->sentBS = 0;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 26

Page 27: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

this->wasHead = 0; this->headSun = 0; this->headBatt = 0;

// default, set black this->myStatus = STATUS_BATT; this->setDisplayString("p=$xpos,$ypos;o=black");

// schedule SUN //if (this->solarOn) { cm = new cMessage(); cm2 = new cMessage();

cm->setKind(SMSG_CHANGESTATUS); cm2->setKind(SMSG_CHANGESTATUS);

int max = this->nrRounds * (this->nrFrames * 30); int endSun = this->sunStart + this->sunDuration;

this->repeatTime = (this->nrNodes / this->sunNodes) * this->sunDuration; this->expectedEndTime = (30 * this->nrFrames) * nrRounds; ev << "repeatTime " << this->repeatTime << " expected end " << this-> expectedEndTime << "\n";

if (endSun > max) endSun = max - 100;

scheduleAt(simTime() + this->sunStart, cm); // XXXXXXXX scheduleAt(simTime() + endSun, cm2); // XXXXXXXX }

ev << this->myId << " energy: " << energy << "status " << this->myStatus << "\n";

{ cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_INIT); scheduleAt(simTime() + INIT_WAIT, cmsg); }

}

// making the gates on the flyvoid Node::initNodes(){ int i;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 27

Page 28: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

cModule *parent = parentModule(); cModule *mod; cModule *myMod; // this is my Module int numNodes; int trRange; int delx, dely; int ritems;

numNodes = (int) parent->par("numNodes"); ev << "numNodes is: " << numNodes << " energy: " << energy << "\n";

for (i = 1; i <= simulation.lastModuleIndex(); i++) { int x, y, id;

//scan the simulation module vector mod = (cModule *) simulation.module(i);

// check for nodes in transmission range if ((strcmp(mod->name(), "node") == 0) || (strcmp(mod->name(), "bs") == 0)) { if (strcmp(mod->name(), "node") == 0) { id = ((Node *) mod)->myId; x = ((Node *) mod)->xpos; y = ((Node *) mod)->ypos; nodePtr[id] = ((Node *) mod); } if (strcmp(mod->name(), "bs") == 0) { id = ((BS *) mod)->myId; this->bsId = id; x = ((BS *) mod)->xpos; y = ((BS *) mod)->ypos; this->bsDist = (x / 10 - this->xpos / 10) * (x / 10 - this->xpos / 10) + (y / 10 - this->ypos / 10) * (y / 10 - this->ypos / 10); } if (id != this->myId && id == this->bsId) { cGate *g; char gName[32]; int items;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 28

Page 29: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

// ev << this->myId << "(" << this->xpos << "," << this->ypos <<") found node with id " << id << " xpos: " << x << " ypos: " << y<< "\n";

if ((((this->ypos - ypos) * (this->ypos - ypos)) + ((this->xpos - xpos) * (this->xpos - xpos))) < 2500 || id == this->bsId) {

items = this->gatev.items(); ritems = mod->gatev.items();

// make new gate here sprintf(gName, "O_%d", id); g = new cGate(gName, 'O'); this->gatev.addAt(items, g); // position, element g->setOwnerModule((cModule *) this, items);

// make new gate at other side sprintf(gName, "I_%d", this->myId); g = new cGate(gName, 'I'); mod->gatev.addAt(ritems, g); // position, element g->setOwnerModule((cModule *) mod, ritems);

//CHANNEL cLinkType *etere = findLink("etere"); connect((cModule *) this, items, (cLinkType *) etere, (cModule *) mod, ritems); //draw the link g = this->gate(items); //g->setDisplayString( g->displayString(), true); } } } } // send energy and solar status to BS ev << "call send2BS\n"; send2BS(this->myId, this->bsId, this->energy, this->myStatus, this->myCluster, this->xpos, this->ypos);}

void Node::handleMessage(cMessage * msg){ if (!msg->isSelfMessage()) { // // BS announces head with this message

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 29

Page 30: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

// broadcasted to all nodes by BS // if (((ClusterMessage *) msg)->getProto() == CL_TOHEAD) { int head; // cluster head of the cluster

// reduce energy for packet reception of header energyReceive(25 * 8);

head = ((ClusterHeadMessage *) msg)->getCHead(this->myId); ev << this->myId << " my head is " << head << "\n"; if (head != this->myId) { // setup connection to host cGate *g; char gName[32]; int items; int xpos, ypos; cModule *mod; int ritems; ; this->cHead = 0; this->headId = head; if (myStatus == STATUS_SUN) this->setDisplayString("p=$xpos,$ypos;o=yellow"); else this->setDisplayString("p=$xpos,$ypos;o=black");

xpos = nodePtr[head]->xpos; ypos = nodePtr[head]->ypos; mod = (Node *) nodePtr[head];

items = this->gatev.items(); ritems = mod->gatev.items();

// make new gate here sprintf(gName, "O_%d", head); g = new cGate(gName, 'O'); this->gatev.addAt(items, g); // position, element g->setOwnerModule((cModule *) this, items);

// make new gate at other side sprintf(gName, "I_%d", this->myId); g = new cGate(gName, 'I'); mod->gatev.addAt(ritems, g); // position, element g->setOwnerModule((cModule *) mod, ritems);

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 30

Page 31: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

//CHANNEL cLinkType *etere = findLink("etere"); connect((cModule *) this, items, (cLinkType *) etere, (cModule *) mod, ritems); //draw the link g = this->gate(items); //g->setDisplayString( g->displayString(), true); } else { // now this node is cluster head this->cHead = 1; this->headId = head; this->wasHead++; if (this->myStatus == STATUS_BATT) this->headBatt++; else this->headSun++; this->setDisplayString("p=$xpos,$ypos;o=red");

// want to create TDMA in next step { cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_MAKETDMA); scheduleAt(simTime() + INIT_WAIT, cmsg); }

// must stay awake and receive data packets from other nodes // reset number of packets received in this frame this->nrDataPackets = 0; // must collect data and send it to BS

} } // // cluster head announces its TDMA scheme with this message // received by nodes in cluster // if (((ClusterMessage *) msg)->getProto() == CL_TDMA) { int i, s; int sTime;

// reset data and counters this->myData = 0; // reset myData

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 31

Page 32: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

this->curFrame = 0;

// reduce energy for packet reception of header energyReceive(25 * 8);

this->nrFrames = ((TDMAMessage *) msg)->getFrames(); this->frameTime = ((TDMAMessage *) msg)->getFrameTime(); this->headId = ((TDMAMessage *) msg)->getSrcAddress(); ev << this->myId << ": received TDMA frameTime " << this->frameTime << "\n";

// find slot for this node for (i = 0; this->frameTime; i++) { if (((TDMAMessage *) msg)->getTdma(i) == this->myId && ((TDMAMessage *) msg)->getTdma(i) != 0) { ev << this->myId << ": found slot time " << i + 1 << "\n"; sTime = i + 1; this->mySlot = i + 1; break; } } ev << "loop done\n"; // sleep until slot time, then wake up and send data { cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_SENDDATA); scheduleAt(simTime() + sTime, cmsg); } ev << "tdma " << this->myId << "done\n"; } // // cluster head receives data // if (((ClusterMessage *) msg)->getProto() == CL_CHDATA) { int newHead = 0; // XXX update in case someone

// reduce energy for packet reception of data energyReceive(500 * 8);

// cluster head received data this->nrDataPackets++; // check if all packets if (this->nrDataPackets == this->clusterNodes) // XXX

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 32

Page 33: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

{ this->nrDataPackets = 0; // if new cluster head (due to SUN reason) if (newHead) { // inform this node that it is the new head

// one "seconds" until processed data is sent to BS } else { // two "seconds" until processed data is sent to BS cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_DATA2BS); scheduleAt(simTime() + 2, cmsg); } } } } else { // self message if (msg->kind() == SMSG_CHANGESTATUS) //we update the status { int receiver;

if (this->myStatus != STATUS_DEAD) {

if (myStatus == STATUS_SUN) { cMessage *cm; cMessage *cm2;

myStatus = STATUS_BATT; this->setDisplayString("p=$xpos,$ypos;o=black");

if (simTime() + this->repeatTime < this->expectedEndTime) { cm = new cMessage(); cm2 = new cMessage(); cm->setKind(SMSG_CHANGESTATUS); cm2->setKind(SMSG_CHANGESTATUS);

scheduleAt(simTime() + this->repeatTime - this->sunDuration, cm); scheduleAt(simTime() + this->repeatTime, cm2); }

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 33

Page 34: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

} else { myStatus = STATUS_SUN; this->setDisplayString("p=$xpos,$ypos;o=yellow"); } } ev << "new status " << this->myStatus << "\n"; } else if (msg->kind() == SMSG_INIT) { this->initNodes(); } else if (msg->kind() == SMSG_SENDDATA) { int newSun = 0; // set to 1 if you want to take over as clusterhead

// node has been woken up to transmit data to clusterhead //ev << this->myId << "to send data to clusterhead\n"; sendDataToCHead(newSun); this->curFrame++; if (this->curFrame < this->nrFrames) { // sleep until slot time, then wake up and send data cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_SENDDATA); scheduleAt(simTime() + this->frameTime, cmsg); } else { // XXX must wake up to send new status to BS, so new cluster head can be chosen cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_STATUS2BS); scheduleAt(simTime() + (this->frameTime - this->mySlot), cmsg); } } else if (msg->kind() == SMSG_DATA2BS) { // cluster head sends data to BS sendData2BS(this->myId); } else if (msg->kind() == SMSG_MAKETDMA) { // reset some values

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 34

Page 35: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

this->curFrame = 0;

// cluster head sends data to BS this->sendTDMA(); } else if (msg->kind() == SMSG_STATUS2BS) { if (this->myId == 25) ev << this->myId << ": send STATUS to BS with EL " << this-> energy << " head:" << this->cHead << "\n"; this->cHead = 0; send2BS(this->myId, this->bsId, this->energy, this->myStatus, this->myCluster, this->xpos, this->ypos); this->sentBS++; } else { ev << "got strange self-message!!\n"; } } delete(msg);}

void Node::send2BS(int src, int rec, int energy, int status, int cluster, int xpos, int ypos){

// send out a TOCLUSTER message Status2BSMessage *cmsg = new Status2BSMessage(); // create new status2BS message cmsg->setProto(CL_TOBS); cmsg->setSrcAddress(this->myId); // XXX node id cmsg->setDestAddress(rec); cmsg->setStatus(status); cmsg->setEnergy(energy); cmsg->setCluster(cluster); cmsg->setYpos(ypos); cmsg->setXpos(xpos);

ev << "in send2BS:" << this->myId << "\n"; { char str[32];

sprintf(str, "O_%d", rec); if (findGate(str) > 1) { cGate *g = gate(str);

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 35

Page 36: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

if (g->isConnected()) { ev << this->myId << ": sToCluster to" << rec << "\n"; send((Status2BSMessage *) cmsg, str); // reduce energy for header this->energyTransmit(25 * 8, this->bsDist); } } }}

void Node::sendTDMA(){ int n; int nrPeers = 0; // number of nodes in my cluster char str[32]; int i, j; TDMAMessage *tmsg; int items, ritems; cGate *g; char gName[32];

// create new Message including TDMA slots tmsg = new TDMAMessage(); tmsg->setProto(CL_TDMA); tmsg->setSrcAddress(this->myId); tmsg->setDestAddress(BROADCAST);

// compute number of nodes in cluster and update cluster head for (n = 2; n < this->nrNodes + 2; n++) { if (n != this->myId && nodePtr[n]->headId == this->myId) { // set TDMA slot tmsg->setTdma(nrPeers, n); ev << "tdma " << nrPeers << ": " << n << "\n"; // make a connection to this node

items = this->gatev.items(); ritems = nodePtr[n]->gatev.items();

// make new gate here sprintf(gName, "O_%d", nodePtr[n]->myId); g = new cGate(gName, 'O'); this->gatev.addAt(items, g); // position, element g->setOwnerModule((cModule *) this, items);

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 36

Page 37: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

// make new gate at other side sprintf(gName, "I_%d", this->myId); g = new cGate(gName, 'I'); nodePtr[n]->gatev.addAt(ritems, g); // position, element g->setOwnerModule(nodePtr[n], ritems);

//CHANNEL cLinkType *etere = findLink("etere"); connect((cModule *) this, items, (cLinkType *) etere, nodePtr[n], ritems); //draw the link g = this->gate(items); g->setDisplayString(g->displayString(), true);

// compute distance as well nodePtr[n]->headDist = (((nodePtr[n])->xpos / 10 - this->xpos / 10) * ((nodePtr[n])->xpos / 10 - this->xpos / 10)) + (((nodePtr[n])->ypos / 10 - this->ypos / 10) * ((nodePtr[n])->ypos / 10 - this->ypos / 10)); ev << "dist: " << nodePtr[n]->headDist << "\n"; nrPeers++; } } ev << "clusterhead " << this->myId << ": have peers " << nrPeers << "\n";

tmsg->setFrames(this->nrFrames); // XXX nr Frames ??? tmsg->setFrameTime(nrPeers + 2); // XXX frame length?

this->clusterNodes = nrPeers; // give two slots to cluster head at the end of each round tmsg->setTdma(nrPeers, this->myId); tmsg->setTdma(nrPeers + 1, this->myId);

for (i = 0; i < nrPeers; i++) { int rec = tmsg->getTdma(i); sprintf(str, "O_%d", rec); if (findGate(str) > 1) { cGate *g = gate(str); if (g->isConnected()) { ev << this->myId << ": sTDMA to" << rec << "\n"; send((TDMAMessage *) tmsg->dup(), str); // reduce energy for header

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 37

Page 38: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

this->energyTransmit(25 * 8, nodePtr[rec]->headDist); } } else ev << "no gate\n"; }

// if we have 0 peers we do not do anything, so we can send our new status // to BS if (nrPeers == 0) { ev << "call send2BS\n"; send2BS(this->myId, this->bsId, this->energy, this->myStatus, this->myCluster, this->xpos, this->ypos); }}

void Node::sendDataToCHead(int newSun){ int rec = this->headId; // this data is sent to the cluster head

//ev << this->myId << " send data to " << rec << "\n"; // send out a TOCLUSTER message DataToCHMessage *dmsg = new DataToCHMessage(); dmsg->setProto(CL_CHDATA); dmsg->setSrcAddress(this->myId); // XXX node id dmsg->setDestAddress(rec); dmsg->setData(this->myData); this->myData++; dmsg->setNewSun(newSun);

{ char str[32];

sprintf(str, "O_%d", rec); if (findGate(str) > 1) { cGate *g = gate(str); if (g->isConnected()) { //ev << this->myId << ": sDataCH to" << rec << "\n"; send((DataToCHMessage *) dmsg, str); // reduce energy for data packet this->energyTransmit(500 * 8, this->headDist); }

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 38

Page 39: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

} }}

void Node::sendData2BS(int data){ int rec = this->bsId; // this data is sent to the cluster head

ev << this->myId << "send data to BBBBBSSSS\n\n\n"; // send out a TOCLUSTER message Data2BSMessage *dmsg = new Data2BSMessage(); // create new toCenter message dmsg->setProto(CL_CHDATA); dmsg->setSrcAddress(this->myId); // XXX node id dmsg->setDestAddress(rec); dmsg->setData(this->myData); this->myData++;

{ char str[32];

sprintf(str, "O_%d", rec); if (findGate(str) > 1) { cGate *g = gate(str); if (g->isConnected()) { //ev << this->myId << ": sDataCH to" << rec << "\n"; send((Data2BSMessage *) dmsg, str); // reduce energy for data packet to BS this->energyTransmit(500 * 8, this->bsDist); } } }

// reduce energy for data aggregation energyDataAggr(this->clusterNodes);

// now done with this round this->curFrame++; if (this->curFrame == this->nrFrames) { ev << "cHead: round done\n"; // reset from being a cluster head //this->cHead = 0; {

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 39

Page 40: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

// XXX must wake up to send new status to BS, so new cluster head can be chosen cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_STATUS2BS); scheduleAt(simTime(), cmsg); // XXX constant } this->curFrame = 0; }}

// energy consumption for reception of bitsvoid Node::energyReceive(int bits){ double en; // lost energy

if (this->myStatus == STATUS_BATT) { en = (double) bits *50.0 * NANO; ev << "REC-energy: " << en << "\n"; this->energy = this->energy - en; }}

// energy consumption for transmission of bits over distance dist// node that dist is already the squarevoid Node::energyTransmit(int bits, int dist){ double en;

if (this->myStatus == STATUS_BATT) { en = bits * 10 * PICO * dist + (double) bits *50.0 * NANO; if (this->cHead == 1) ev << "TR-energy HEAD: " << en << "\n"; this->energy = this->energy - en; }}

// energy consumption for data aggregation (cluster head only)void Node::energyDataAggr(int signals){ double en;

if (this->myStatus == STATUS_BATT) { en = 5 * NANO * signals;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 40

Page 41: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

ev << "AGG-energy: " << en << "\n"; this->energy = this->energy - en; }}

void Node::finish(){#if 0 recordScalar("node id", this->myId); recordScalar("energy", this->energy); recordScalar("xpos ", this->xpos); recordScalar("ypos ", this->ypos); recordScalar("wasHead", this->wasHead); recordScalar("sunstart", this->sunStart); recordScalar("status", this->myStatus);

recordScalar("wasHead", this->wasHead); recordScalar("headSun", this->headSun); recordScalar("headBatt", this->headBatt);#endif}

bs.h:

#ifndef BS_H#define BS_H

#include <omnetpp.h>#include "solar.h"#include "node.h"#include "nodebase.h"

/** * Implements the base station */class BS : public NodeBase{ Module_Class_Members(BS, NodeBase, 0); // this is a macro; it expands to constructor definition etc. // 0 says that we use MessageHandlers, not activity()

void BS::initNodes(); virtual void initialize(void); virtual void handleMessage(cMessage * msg); void BS::resetStatus();

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 41

Page 42: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

void BS::computeBest(); void BS::finish();

int xpos; // just for simulation int ypos;

int nrStatusRec; // number of received status // struct _adv advInfo[NR_CLUSTERS]; struct _adv advInfo[104]; // XXX

cModule *nodePtr[104];

int roundEnergyLoss; int xMax; int yMax; int roundsDone; int nrRounds; int firstDead;

int roundTimes[400]; // XXX times when round starts int sunnyNodes[400]; int deadRound[400]; int sunnyCtr; int calledEnd; int solarOn; int halfDead; int halfDeadCtr; int oldDeadNodes; int deadNodes; int sunNodes; int sunDuration;};

#endif

bs.cpp:

#include <stdio.h>#include <string.h>

#include <omnetpp.h>#include "node.h"#include "bs.h"#include "cl_msg_m.h"

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 42

Page 43: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

#define EXPL_TIME 5

Define_Module(BS);

void BS::initialize(){ int xpos, ypos, i; cModule *parent = parentModule();

this->myId = par("id"); this->nrGates = (int) parent->par("numNodes") + 2; this->xpos = par("xpos"); this->ypos = par("ypos"); this->nrNodes = (int) parent->par("numNodes"); this->xMax = (int) parent->par("xMax"); this->yMax = (int) parent->par("yMax"); this->resetStatus(); this->roundEnergyLoss = 80001.0; this->roundsDone = 0; this->nrRounds = (int) parent->par("rounds"); this->firstDead = 0; this->calledEnd = 0; this->solarOn = (int) parent->par("solarOn"); this->sunNodes = (int) parent->par("sunNodes"); this->sunDuration = (int) parent->par("sunDuration"); this->sunnyCtr = 0; this->halfDead = 0; this->halfDeadCtr = 0; this->deadNodes = 0; this->oldDeadNodes = 0;

for (i = 0; i < 104; i++) { advInfo[i].id = 0; advInfo[i].energy = 0; advInfo[i].status = 0; }

for (i = 0; i < this->nrRounds; i++) { this->roundTimes[i] = 0; this->sunnyNodes[i] = 0; }

// schedule first sending this->setDisplayString("p=$xpos,$ypos;b=,,rect;o=blue");

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 43

Page 44: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

ev << "BS: id " << this->myId << " nrGates: " << this->nrGates << " x,y " << this-> xpos << this->ypos << "\n";

{ cMessage *cmsg = new cMessage(); cmsg->setKind(SMSG_INIT); scheduleAt(simTime(), cmsg); }}

// making the gates on the flyvoid BS::initNodes(){ int i; cModule *parent = parentModule(); cModule *mod; cModule *myMod; // this is my Module int numNodes; int trRange; int delx, dely; int ritems;

// new stuff numNodes = (int) parent->par("numNodes"); ev << "BS numNodes is: " << numNodes << "\n"; // new stuff trRange = (int) parent->par("trRange"); ev << "BS trRange is: " << trRange << "\n";

for (i = 1; i <= simulation.lastModuleIndex(); i++) { int x, y, id;

//scan the simulation module vector mod = (cModule *) simulation.module(i);

if (strcmp(mod->name(), "node") == 0) { id = ((Node *) mod)->myId; x = ((Node *) mod)->xpos; y = ((Node *) mod)->ypos; nodePtr[id] = ((Node *) mod);

if (id != this->myId) {

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 44

Page 45: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

cGate *g; char gName[32]; int items;

ev << "BS: " << this->myId << "(" << this->xpos << "," << this-> ypos << ") found node with id " << id << " xpos: " << x << " ypos: " << y << "\n";

items = this->gatev.items(); ritems = mod->gatev.items();

ev << "items " << items << "\n";

// make new gate here sprintf(gName, "O_%d", id); g = new cGate(gName, 'O'); this->gatev.addAt(items, g); // position, element g->setOwnerModule((cModule *) this, items);

// make new gate at other side sprintf(gName, "I_%d", this->myId); g = new cGate(gName, 'I'); mod->gatev.addAt(ritems, g); // position, element g->setOwnerModule((cModule *) mod, ritems);

//CHANNEL cLinkType *etere = findLink("etere"); connect((cModule *) this, items, (cLinkType *) etere, (cModule *) mod, ritems); //draw the link //g = this->gate(items); //g->setDisplayString( g->displayString(), true); } } }}

void BS::handleMessage(cMessage * msg){

if (msg->isSelfMessage()) { ev << "BS: got self message type " << msg->kind() << "\n"; if (msg->kind() == SMSG_INIT) {

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 45

Page 46: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

ev << "BS: got start message\n"; this->initNodes(); } } else { // no self message if (((ClusterMessage *) msg)->getProto() == CL_TOBS) { int energy; int cluster; int status; int sender; int clHead; int curHEnergy; // energy of current head int curHStatus; // status of current head int rating; int xpos, ypos;

sender = ((Status2BSMessage *) msg)->getSrcAddress(); energy = ((Status2BSMessage *) msg)->getEnergy(); cluster = ((Status2BSMessage *) msg)->getCluster(); status = ((Status2BSMessage *) msg)->getStatus(); xpos = ((Status2BSMessage *) msg)->getXpos(); ypos = ((Status2BSMessage *) msg)->getYpos();

if (energy < 0 && this->firstDead == 0) this->firstDead = this->roundsDone;

if (energy < 0 && this->halfDead == 0) this->halfDeadCtr++;

if (this->roundsDone < 300) this->roundTimes[roundsDone] = (int) simTime();

advInfo[sender].id = sender; advInfo[sender].energy = energy; advInfo[sender].status = status; advInfo[sender].xpos = xpos; advInfo[sender].ypos = ypos;

if (advInfo[sender].energy < 0) { if (((Node *) nodePtr[sender])->myStatus != STATUS_DEAD) this->deadNodes++; advInfo[sender].status = STATUS_DEAD; status = STATUS_DEAD; // XXX debug only

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 46

Page 47: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

((Node *) nodePtr[sender])->myStatus = STATUS_DEAD; }

if (status == STATUS_SUN) this->sunnyCtr++;

// compute rating if (this->solarOn) { if (status == STATUS_SUN) rating = energy - roundEnergyLoss / 2; else rating = energy - roundEnergyLoss; } else rating = energy - roundEnergyLoss;

advInfo[sender].rating = rating;

ev << "BS received from " << sender << "status " << status << " rating: " << rating << "\n"; this->nrStatusRec++; ev << "BS rec " << this->nrStatusRec << " nrNodes: " << this->nrNodes << "\n";

// check if done if (this->nrStatusRec == this->nrNodes - this->oldDeadNodes) { this->oldDeadNodes += this->deadNodes; ev << "nodes dead " << this->deadNodes << "all dead " << this->oldDeadNodes << "\n"; this->deadRound[this->roundsDone] = this->deadNodes;

this->sunnyNodes[this->roundsDone] = this->sunnyCtr; if (this->halfDeadCtr > this->nrNodes / 2 && this->halfDead == 0) { this->halfDead = roundsDone; ev << " HALF DEAD\n"; this->calledEnd = 2; endSimulation(); } this->roundsDone++; if (this->roundsDone <= this->nrRounds) { ev << "BS call compute best\n"; // now compute best nodes

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 47

Page 48: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

computeBest(); resetStatus(); }

if (this->roundsDone > this->nrRounds) { this->calledEnd = 1; endSimulation(); } } } }

delete(msg);}

void BS::resetStatus(){ int i;

this->nrStatusRec = 0; // number of received status this->sunnyCtr = 0; this->deadNodes = 0;}

//// Note: this method is far too long, bad programming style!!//#define FBEST 8 // best after first round#define LBEST 6 // 6 best are in last round, 5 survivevoid BS::computeBest(){ struct _adv best[FBEST]; int i, j; int min = 999999999; int minPtr = 0; int sum = 0; int nrSolar = 0; // nr of solar nodes

ev << "first 8\n"; // put FBEST nodes in best, compute min for (i = 0; i < FBEST; i++) { if (this->advInfo[i + 2].rating < min) { min = this->advInfo[i + 2].rating;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 48

Page 49: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

minPtr = i; } best[i].id = this->advInfo[i + 2].id; best[i].xpos = this->advInfo[i + 2].xpos; best[i].ypos = this->advInfo[i + 2].ypos; best[i].status = this->advInfo[i + 2].status; best[i].rating = this->advInfo[i + 2].rating; ev << "Id: " << best[i].id << " rating: " << best[i].rating << "\n"; }

for (i = FBEST; i < this->nrNodes; i++) { // ev << "i: " << i << "\n"; // search for the ones larger tha min (smallest in best) if (this->advInfo[i + 2].rating > min) { // replace min min = this->advInfo[i + 2].rating; best[minPtr].id = this->advInfo[i + 2].id; best[minPtr].rating = this->advInfo[i + 2].rating; best[minPtr].xpos = this->advInfo[i + 2].xpos; best[minPtr].ypos = this->advInfo[i + 2].ypos; // recompute min and minPtr minPtr = 0; min = 9999999; for (j = 0; j < FBEST; j++) { if (best[j].rating < min) { min = best[j].rating; minPtr = j; } } } }

// print out FBEST best, count solar nodes ev << "computeBest:\n"; nrSolar = 0; for (i = 0; i < FBEST; i++) { ev << "Id: " << best[i].id << " rating: " << best[i].rating << "\n"; nodePtr[best[i].id]->setDisplayString("p=$xpos,$ypos;o=green"); if (best[i].status == STATUS_SUN) nrSolar++; }

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 49

Page 50: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

// now find one node with minimum distance to all other best nodes // usually one in the middle will be removed // do not through away solar nodes (if not all are solar nodes) minPtr = 0; min = 99999999; for (i = 0; i < FBEST; i++) { sum = 0; for (j = 0; j < FBEST; j++) { if (j != i) sum += ((best[i].xpos - best[j].xpos) * (best[i].xpos - best[j].xpos)) + ((best[i].ypos - best[j].ypos) * (best[i].ypos - best[j].ypos));

} //ev << "distance sum " << sum << " id " << best[i].id << " min " << min << "\n"; if (sum < min && (nrSolar < 5 && best[i].status == STATUS_BATT)) { minPtr = i; min = sum; } } ev << "remove node " << best[minPtr].id << " from cluster \n"; nodePtr[best[minPtr].id]->setDisplayString("p=$xpos,$ypos;o=red"); if (minPtr != FBEST - 1) { best[minPtr].id = best[FBEST - 1].id; best[minPtr].xpos = best[FBEST - 1].xpos; best[minPtr].ypos = best[FBEST - 1].ypos; best[minPtr].rating = best[FBEST - 1].rating; } // print out FBEST best ev << "computeBest now:\n"; for (i = 0; i < FBEST - 1; i++) { ev << "Id: " << best[i].id << " rating: " << best[i].rating << "\n"; }

// search for node closest to another node, if one of them close to // the border, remove the one close to the border { int n1, n2, tmp; int close = 0;

min = 9999999;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 50

Page 51: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

for (i = 0; i < FBEST - 1; i++) { for (j = 0; j < FBEST - 1; j++) { if (j != i) { tmp = ((best[i].xpos - best[j].xpos) * (best[i].xpos - best[j].xpos)) + ((best[i].ypos - best[j].ypos) * (best[i].ypos - best[j].ypos)); if (tmp < min) { min = tmp; n1 = i; n2 = j; } } } } ev << "n1: " << best[n1].id << " n2: " << best[n2].id << "\n";

#define BORDER 180 // now choose one of the two if (best[n1].xpos<BORDER || best[n1].xpos>this->xMax - BORDER || best[n1].ypos<BORDER || best[n1].ypos>this->yMax - BORDER) close = n1; else close = n2;

// do not remove solar if (this->solarOn && best[n1].status == STATUS_SUN && best[n2].status == STATUS_BATT) close = n2; if (this->solarOn && best[n2].status == STATUS_SUN && best[n1].status == STATUS_BATT) close = n1; // update array, remove close ev << "remove close" << best[close].id << "\n"; nodePtr[best[close].id]->setDisplayString("p=$xpos,$ypos;o=red"); if (close != FBEST - 2) { best[close].id = best[FBEST - 2].id; best[close].xpos = best[FBEST - 2].xpos; best[close].ypos = best[FBEST - 2].ypos; best[close].rating = best[FBEST - 2].rating; } // print out FBEST best ev << "computeBest now:\n";

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 51

Page 52: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

for (i = 0; i < FBEST - 2; i++) { ev << "Id: " << best[i].id << " rating: " << best[i].rating << "\n"; } }

// now we do a real optimization { int sumWithout[LBEST]; int n; int tmp;

for (i = 0; i < LBEST; i++) { // reset sum sum = 0; // loop through all nodes to find minimun distance for (n = 2; n < this->nrNodes + 2; n++) { Node *nPtr = (Node *) nodePtr[n];

if (nPtr->myStatus != STATUS_DEAD) { min = 9999999; for (j = 0; j < LBEST; j++) { if (i != j) { tmp = (nPtr->xpos - best[j].xpos) * (nPtr->xpos - best[j].xpos) + (nPtr->ypos - best[j].ypos) * (nPtr->ypos - best[j].ypos); if (tmp < min) { // ev << "min " << j << "\n"; min = tmp; } } } sum += min; } } sumWithout[i] = sum; ev << "sumwithout " << best[i].id << ": " << sum << "\n"; } // the one is lowest number gets kicked out min = 99999999; for (i = 0; i < LBEST; i++)

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 52

Page 53: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

{ if (sumWithout[i] < min) { min = sumWithout[i]; n = i; } } ev << "time " << simTime() << " OUT goes " << best[n].id << "\n"; nodePtr[best[n].id]->setDisplayString("p=$xpos,$ypos;o=red"); // remove that node if (n != LBEST - 1) { best[n].id = best[LBEST - 1].id; best[n].xpos = best[LBEST - 1].xpos; best[n].ypos = best[LBEST - 1].ypos; best[n].rating = best[LBEST - 1].rating; } // print out LBEST best ev << "computeBest now:\n"; for (i = 0; i < LBEST - 1; i++) { ev << "Id: " << best[i].id << " rating: " << best[i].rating << " x,y " << best[i]. xpos << "," << best[i].ypos << "\n"; } }

// now we send message to all nodes and announce their cluster head { int head = 0; int tmp; char str[32];

ClusterHeadMessage *cmsg = new ClusterHeadMessage(); ev << "send messages to nodes announcing cluster heads\n"; cmsg->setProto(CL_TOHEAD); // XXX new name (to all now) cmsg->setSrcAddress(this->myId); for (int rec = 2; rec < this->nrNodes + 2; rec++) { Node *nPtr = (Node *) nodePtr[rec]; head = 0; if (nPtr->myStatus != STATUS_DEAD) { //ev << "rec: " << rec; min = 9999999; for (j = 0; j < LBEST - 1; j++) {

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 53

Page 54: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

if (rec != best[j].id) { tmp = (nPtr->xpos - best[j].xpos) * (nPtr->xpos - best[j].xpos) + (nPtr->ypos - best[j].ypos) * (nPtr->ypos - best[j].ypos); //ev << " cmp with " << best[j].id << "gives" << tmp << " "; if (tmp < min) { //ev << "new min\n"; min = tmp; head = best[j].id; } } else { head = best[j].id; break; } }

} ev << " BS: rec " << rec << " x,y " << nPtr->xpos << "," << nPtr-> ypos << " has head: " << head << "\n"; cmsg->setCHead(rec, head); } cmsg->setDestAddress(BROADCAST); for (int rec = 2; rec < this->nrNodes + 2; rec++) { ev << "BS sendHEAD for" << rec << ":" << cmsg->getCHead(rec) << "\n"; if (cmsg->getCHead(rec) != 0) // no head when dead { sprintf(str, "O_%d", rec); if (findGate(str) > 1) { cGate *g = gate(str); if (g->isConnected()) { //ev << this->myId << ": sToCHEAD to" << rec << "\n"; send((ClusterHeadMessage *) cmsg->dup(), str); } } } else ev << "DEAD DEAD " << rec << "\n"; } } // here we can reset everything

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 54

Page 55: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

this->resetStatus();}

void BS::finish(){ int i;

//recordScalar("BS BS node id",this->myId); recordScalar("solarOn", this->solarOn); recordScalar("sunDuration", this->sunDuration); recordScalar("roundsDone", this->roundsDone); recordScalar("nrRounds", this->nrRounds); recordScalar("firstDead", this->firstDead); recordScalar("halfDead", this->halfDead); recordScalar("sunNodes", this->sunNodes);

#if 0 recordScalar("calledEnd", this->calledEnd); for (i = 0; i < this->roundsDone; i++) { recordScalar("roundsDone", this->roundTimes[i]); recordScalar("sunny nodes", this->sunnyNodes[i]); }#endif}

nodebase.h:

#ifndef NNODE_H#define NNODE_H

#include <omnetpp.h>#include "solar.h"

/** * Base class for Node and BS. */class NodeBase : public cSimpleModule{ Module_Class_Members(NodeBase, cSimpleModule, 0);

protected: virtual void initialize() = 0; virtual void handleMessage(cMessage * msg) = 0;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 55

Page 56: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

virtual void finish(); void updateStats(); void initStats();

public: //XXX cArray nHosts; // XXX IT neighbouring hosts int myId;

int myStatus; // SUNNY STUFF for stats int nrAllMsgBatt; int nrAllMsgSun; int nrDataBatt; int nrDataSun; int nrExplBatt; int sinkFromTwo; int sinkFromThree;

// how many gates int nrGates; int nrNodes;};

extern void updateStats();

#endif

nodebase.cpp:

#include <stdio.h>#include <string.h>

#include <omnetpp.h>#include "nodebase.h"#include "cl_msg_m.h"

void NodeBase::updateStats(){ if (this->myStatus == STATUS_SUN) this->nrAllMsgSun++; else this->nrAllMsgBatt++;}

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 56

Page 57: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

void NodeBase::initStats(){ this->nrAllMsgBatt = 0; this->nrAllMsgSun = 0; this->nrDataBatt = 0; this->nrDataSun = 0;}

void NodeBase::finish(){#if 0 ev << "finished node id: "; ev << this->myId; ev << " nrAllMsgBatt: "; ev << this->nrAllMsgBatt; ev << " nrAllMsgSun "; ev << this->nrAllMsgSun; ev << " nrDataBatt "; ev << this->nrDataBatt; ev << " nrDataSun "; ev << this->nrDataSun; ev << "\n";#endif

#if 0 recordScalar(" nrAllMsgBatt", this->nrAllMsgBatt); recordScalar("nrAllMsgSun", this->nrAllMsgSun); recordScalar("nrDataBatt ", this->nrDataBatt); recordScalar("nrDataSun ", this->nrDataSun); recordScalar("nrExplBatt", this->nrExplBatt);#endif}

solar.h:

#ifndef SOLAR_H#define SOLAR_H

// define if we want to use NOSUN or not//#define NOSUN 1#undef NOSUN

#define NANO 0.001#define PICO 0.000001

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 57

Page 58: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

// NEW: CLUSTER_STUFF#define NR_CLUSTERS 1 // XXX update#define BS_ID 1 // ID of base station#define CH_MIN_ENERGY 30 // XXX want to change this!!#define CLUSTER_SIZE 30#define FRAME_TIME CLUSTER_SIZE+1 // how long is one frame (how many slots)

// messagetypes for clusters#define CL_TOBS 1#define CL_TOHEAD 2#define CL_TDMA 3#define CL_CHDATA 4

// self message types#define SMSG_SENDDATA 11#define SMSG_CHANGESTATUS 12#define SMSG_DATA2BS 13 // cluster head sends data to BS#define SMSG_STATUS2BS 14 // nodes send their new status to BS#define SMSG_SINKSTART 15#define SMSG_SEQUPDATE 16 // nodes update seq number for expl messages#define SMSG_INIT 17 // init updates#define SMSG_MAKETDMA 18

#define BROADCAST 0

#define STATUS_SUN

1 // status: running with solar energy#define STATUS_BATT 2 // status: running on battery#define STATUS_DEAD 3 // this node is dead

struct _node{ int id; int status; int outgate; int hops; int bcount; int scount; int seqNumber; // per node};

struct _adv{ int id;

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 58

Page 59: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

int energy; int status; int rating; int xpos; int ypos;};

struct _peerInfo{ int id; int xpos; int ypos;};

// status for myGrad#define GS_INIT 0#define GS_ACTIVE 1

// define some events and times#define INIT_WAIT 1 // wait to init nodes#define SINK_WAIT 2 // sink waits until start#define EVENT_SENSORDATA 1#define EVENT_BC

2#define BC_TIME

1#define EVENT_CHANGESTATUS 3#define EVENT_PRINTSTATS 4//#define END_TIME 1250#define END_TIME

900//#define END_TIME 1100//#define END_TIME 1750#define CHANGE2_1 200#define CHANGE2_2 400#define CHANGE3_1 100#define CHANGE3_2 450

#define EXPL_PERIOD 300#define DATA_PERIOD 40

#define MAX_NEIGHBOURS 5 /* for hop counter */#define MAX_DOWNS 2 /* how many downs */

#endif

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 59

Page 60: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

5. RESULTS

The following snapshots describe the various stages of the LEACH implementation done

using OMNET++:

fig 8: initial WSN network

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 60

Page 61: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

Setup phase:

Fig 9: node discovery phase

Fig 10: cluster formation and TDMA allocation

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 61

Page 62: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

Fig 11: data transmission- node to CH & CH to Base station.

Fig 12: re-clustering for selection of new cluster heads.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 62

Page 63: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

6. SUMMARY AND CONCLUSION

6.1 Summary of Achievements

Studied about wireless sensor networks, its node architecture and compared various

categories of its routing protocols.

Got an experience in using OMNET++ simulator.

Studied about LEACH protocol in detail.

Implemented the simulation of a LEACH variant in OMNET++ simulator.

6.2 Major difficulties encountered

The major difficulty encountered during this project was – learning to use the OMNET++

simulator like installation on a windows platform, understanding ned files, messages, and

using simulation library. The other major difficulty was to implement the LEACH

protocol in the simulator.

The solarleach simulation published in the public domain by Thiemo Voigt as his

research work was used to study the simulation of the leach protocol in OMNET++.

6.3 Limitations of the Project

The main limitation of the project implementation are as follows:

The number of cluster heads are predetermined

The base station is fixed.

The nodes are not mobile.

all the nodes are assumed to be of equal capabilities.

Solar nodes are not stripped from the network.

6.4 Future Scope of work

The sensor node can be made mobile and dynamic clustering algorithms implemented

without fixing the limit on the number cluster heads.

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 63

Page 64: Main Document

STUDY OF WSN ROUTING & IMPLEMENTATION USING OMNET++

BIBLIOGRAPHY

[1] Heinzelman W., Chandrakasan A., Balakrishnan H.: Energy-Efficient

Communication Protocol for Wireless Microsensor Networks. International

Conference on System Sciences, Hawaii, January 2000.

[2] Varga A.: The OMNeT++ Discrete Event Simulation System. European Simulation

Multiconference, Prague, Czech Republic, June 2001.

[3] Bandyopadhyay S., Coyle E.: An Energy Efficient Hierarchical Clustering Algorithm

for Wireless Sensor Networks. Infocom 2003, San Francisco, CA, USA, April 2003.

Sites:

http://www.omnetpp.org/

SIKKIM MANIPAL INSTITUTE OF TECHNOLOGY Page 64