ns-2 의 센서 네트워크 시뮬레이션 응용
DESCRIPTION
NS-2 의 센서 네트워크 시뮬레이션 응용. 김 대 영 , 박 노 성 July 28, 2004 Real-time & Embedded Systems Laboratory Mobile Multimedia Research Center [email protected] http://resl.icu.ac.kr/~kimd. Contents. Introduction to Sensor Networks Power Aware Data-centric (PAD) Routing Protocol - PowerPoint PPT PresentationTRANSCRIPT
1
NS-2 의 센서 네트워크 시뮬레이션 응용
김 대 영 , 박 노 성
July 28, 2004
Real-time & Embedded Systems LaboratoryMobile Multimedia Research Center
[email protected]://resl.icu.ac.kr/~kimd
2
Contents
Introduction to Sensor Networks
Power Aware Data-centric (PAD) Routing Protocol
Minimum Energy Path and Minimum Energy Property Graph MEPG and TMEPG algorithm Distributed Data-centric Bellman-Ford algorithm
Simulation of PAD on NS-2 Implementation of new routing protocol, PAD Wireless network and simulation environment setting Simulation analysis
3
What is Sensor Network? Network of sensor nodes with computation & sensing & wireless
communication capabilities
What we can do with Sensor Networks? Sensing(Actuation) : Motion -> Image -> Classification Collaboration : estimate moving direction & speed of an event Mobile sensors : tracking
Internet /
Other network
Internet /
Other network
BaseStation Sensor field
Sensor node
4
Sensor Network Applications
Military Digital (Smart) Home Healthcare Logistics, Supply Chain Management ITS Process Automation Environment Intelligent Robot Automotive (Vehicle) Factory Automation Etc.
5
Research Topics in Sensor Networks – ICU ANTS (An evolvable Network of Tiny Sensors)
Operating Systems
Network Protocols
Middleware
Application Framework/Profile
Secu
rity
Pow
er E
fficie
ncy
Sensor Network Applications
(Digital Home, Military, U-SCM)
Hardware Platforms
Localiz
atio
n/S
yn
ch
ron
izatio
n
ANTS@ICU 2004
6
Network layer
Functions: Routing (Ad-Hoc) internetworking with external network: other sensor
network, control system, Internet. Base nodes used as gateway to other network
Design principles: Power efficiency Data-centric Data aggregation Ideal sensor network has attribute-based addressing &
location awareness
7
Network layer – Energy Efficient
Energy-efficient routes based on: Available power (PA) Energy required ( )
Energy-efficient routes approaches: Maximum PA route: route with maximum total PA is preferred. (Route 4
PA=5 ) Minimum energy (ME) route: route consumes minimum energy (Route 1
=3 ) Minimum hop route: with minimum hop (Route 3) Maximum minimum PA node route: route whichhas largest minimum PA (Route 3, minimum PA=3)
Route 1: Sink-A-B-T PA=4 =3 Route 2: Sink-A-B-C-T PA=6 =6
(Route 1 with extra node-> not power efficient) Route 3: Sink-D-T PA=3 =4 Route 4: Sink-E-F-T PA=5 =6
8
Data Centric / Data Aggregation Data-centric routing
interest dissemination to assign sensor tasks to nodes – two approaches Base nodes broadcast interest Sensor nodes broadcast advertisement of available data and wait for request
from interested nodes Requires attribute-based naming
Users are more interested in querying attributes of phenomenon than individual node
“Areas where temperature is over 300C” Than “the temperature read by a certain node
Data aggregation (Data fusion) Technique used to solve implosion and overlap problem in data-centric
routing Base node asks sensor nodes to report their surrounding conditions Data from multiple sensor nodes are aggregated -> combining data
from many nodes into set of meaningful information Specifics data (e.g location of reporting nodes) should not be left out Node E aggregates data from sensor nodes A,B
9
Sensors – Network ProtocolsHierarchical routing
Data-centricprotocols
Flooding/Gossiping
DirectedDiffusion
SPIN
SPIN-PP
SPIN-EC
SPIN-BC
SPIN-RI
Rumor routing
Gradient-basedrouting
LEACH TEEN
PEGASIS
HEED
CADRCOUGARACQUIRE
Hierarchical PEGASIS
APTEEN
Location-basedrouting
MECN GAF
SMECN
GEAR
PAD
10
Directed Diffusion
Representative Data Centric protocol Sink broadcasts interest (task description) The interest has timestamp and gradient field As the interest is propagated, the gradients from the source back to
the sink are set up When the source detect the event meeting the interest, send data
back to the sink through the gradient Local data aggregation When the sink receives data, refresh and reinforce the interest
11
LEACH (Low Energy Adaptive Clustering Hierarchy ) - MIT
Representative Data aggregation protocol
Assumption Base node can directly communicate with all nodes, that is single hop distance
Clustering hierarchy Setup phase
Each node choose a number between 0 and 1 If this random number is less than the threshold, the node becomes the head Heads advertise to all nodes Once the nodes receive the advertisement, they select their head based on
signal strength Steady state
A node send data to the head and head aggregate the data After certain period of time, back to setup phase
12
Geographic and Energy Aware Routing (GEAR)
An energy efficient routing algorithm that propagates a query to the appropriate geographical region, without flooding
Procedure Forwarding the packets towards the target region:
When a closer neighbor to the destination exists: GEAR picks a next-hop that are closer to the destination
When all neighbors are further away: GEAR picks a next-hop node that minimizes some cost value of this neighbor.
Disseminating the packet within the region
13
Power Aware Data-centric routing protocol
PAD@ANTS
14
Basic Knowledge :Relay Region and Relay Node
The minimum signal strength is proportional to , (2≤ ≤5) power of distance.
If this inequality is true, the indirect transmission consumes less energy.
• Relay Region : the area where the inequality is always true
• Relay Node : the node located in the Relay Region such as r in the above figure
• k-Relay Node : k denote the number of intermediate nodes in the path, e.g. r is 1-Relay Node.
(t, r) + > (t, i) + (i, r) + 2 , where ( : receiving cost)
t → r t → i → r
= 2 = 4
The shape of boundary depends on .
15
Basic Knowledge :Enclosure Region and Enclosure Graph
The nodes inside Relay Region is out of concern because it is not energy efficient.
• Enclosure Region : surrounded region by Relay Regions
• Minimum Energy Property Graph (MEPG) : the graph has all minimum energy paths (MEPs) but total number of edges are smaller than the original graph. (Cut the edges not related to MEPs in the original graph)
• Enclosure Graph : the graph whose edges are connected only to the nodes of Enclosure Region. Enclosure Graph contains MEPG.
Routing on MEPG is more efficient than on the original graph.
16
Related Works :MECN, SMECN and etc.
The first maker of Minimum Energy Property Graph (MEPG) concept.
• Find Enclosure Graph and do routing.
• The node r is inside the Relay Region of h, so that r must be excluded from Enclosure Graph. However, MECN cannot do that because of it’s incorrect algorithm.
•In addition, MECN removes edges only to 1-Relay Node. For the optimality, edged to k-Relay Node, (k≥1) must be cut down. The complexity of MECN is O(n3).• SMECN removes k-Relay Node, but still complicated. Not such different, just a simple update.
• Li and Wan said that Enclosure Region is similar to the Voronoi region. They suggested the simple O(nlogn) algorithm using the Voronoi region. Their algorithm makes just the approximation of MEPG.
17
Related Works :Drawbacks
Not optimal MECN removes only subset of 1-Relay Nodes. Result of Li and Wan’s algorithm is the approximation.
Too complicated O(n3) algorithm Computation for Enclosure Region
Not reasonable assumption Receiving cost is 0 and alpha is 2. (Li and Wan’s assumption)
Path-loss In noisy situation, the minimum signal strength is not just proportional to power of dis
tance. Only Minimum Energy Property Graph is possible.
Summary MECN : Not optimal, too complicated, and only path-loss SMECN : Optimal result, too complicated, and only path-loss Li and Wan : approximated result, not reasonable assumption, and only path-loss but si
mple algorithm
18
Introduction to PAD
Minimum energy consumption Finding MEPs
Data-centric Minimum Energy Path Tree (MEPT)
Set of two schemes New MEPG algorithm
Reducing edges Afford to support other weight values such as delay and packet loss
Distributed Data-centric Bellman-Ford (DDBF) algorithm Finding MEPs Dynamic selecting of next node for equivalent remaining energy. Low transmission delay
19
New MEPG algorithm
The MEPG algorithm of PAD adopts totally different approach from the existing works.
It is optimal and lightweight O(VlogV+E) algorithm. Real estimation except path-loss can be used and any assumptions are not needed.
Main idea Unit Minimum Energy Path (UMEP) : the direct edge consume
s less energy than any other paths. MEP consists of UMEPs.
A⇒D→E →F < A ⇒D →X →Y → E →F
20
An example of MEPG algorithm
1. A collects the information of the local graph.Vertex = {A, B, C, D, E}
2. A runs the Dijkstra’s algorithm on the local graph.The MEPs from A to B, C, D, and E are found.Found MEPs : A→B, A→B→E, A→C, A→C→D
3. A extracts the MEPs whose length 1.Found UMEPs : A→B, A→C
B
CE
A
D
B
CE
A
D
B
CE
A
D
B
CE
A
D
Local Graph MEPs UMEPs
The edges from C to D, and from B to E has been removed.C and B are responsible for finding the removed edges.
21
An example of MEPG algorithm
Original Graph BN is finding UMEPs.10 > 4 + 2
6 > 3 + 2
10 > 2 + 4 7 > 2 + 36 > 2 + 2
Done.1/3 edges are
removed.
22
Distributed Data-centric Bellman-Ford algorithm
A kind of Distance Vector (DV) whose metric is power consumption (PC) and hop count (HC).
PC is the main metric, HC just records the hop count of the MEP.
The result is the routing tree for the data-centric.
Triggering based, Non-continuous broadcasting of the routing information
After the update period, the base node initiates new routing information.
Routing Table of node u
• It has two metric, PC for minimum energy routing and HC for low-delay routing.
• PC is the main metric, such that found HC doesn’t guarantee not the minimum hop path but the path shorter than or at least the same length as MEP.
23
Other functionality
Prolongation of the lifetime Dynamic selection of the next node → ARM (Acyclic
Rerouting Method) Nodes’ battery is consumed as evenly as possibly.
Urgent delivery MEP is longer than minimum hop path.
Mobility Maintain the routing table without
Slow-convergence Loop of routing path
Self-healing Broken nodes are excluded from the routing.
24
Simulation Environment
NS-2
MICA2 as a sensor node model 433MHz, sensitivity -109dBm, peak output 10dBm 5.3mA~26.7mA in tx mode, 7.4mA in rx mode More than 30pkts/s, pkt size 42bytes Omni-directional, 1dB gain, and 10cm over the ground so 10m tx rang
e Min-hop DV routing protocol
50x50 field, 1 base and 199 sensor nodes deployed randomly
CBR traffic whose period is randomly generated between 1 sec and 10 sec
25
Simulation Result
Initial Graph
MEPG MEPG, where = 0
26
Simulation Result
0 100 200 300 400 500 6000
10
20
30
40
50
60
70
80
90
Time (sec)
Th
e n
um
be
r o
f n
od
es
co
ns
um
ing
all
en
erg
y
Min-hop RoutingDDBF on initial graphPAD
0 100 200 300 400 500 6000
0.5
1
1.5
2
2.5x 104
Time (sec)
Th
e n
um
be
r o
f p
ac
ke
tsth
e b
as
e n
od
e h
av
e r
ec
eiv
ed
Min-hop RoutingDDBF on initial graphPAD
0 10 20 30 40 50 600
5
10
15
20
25
30
The number of broadcasted routing information
Th
e n
um
be
r o
f n
od
es
Min-hop RoutingDDBF on initial graphPAD
27
Simulation of PADon
NS-2
28
NS-2 Simulator
Discrete event simulator Wired, wireless, and combined network of wired and wireless Comparison and analysis of protocols and traffics Traffic (CBR, FTP, TELNET, WEB…), Transport (TCP, UDP), Routing
(DV, LS, DSDV, AODV…), MAC (802.3, 802.11, SMAC…), QoS, Queuing, Link, Delay, Scheduler…
Status 200K lines of C++ and OTcl source code Most UNIX like systems and MS Windows family
29
Sensor Network related part ofNS-2 Simulator
Mobile node Not only for sensor network Derived from Node class Not connected by Link Ability to move within a given topology Energy model
SMAC MAC protocol for sensor network Not stable Some bugs (abnormal working in the situation of dense and large number of
nodes, recent double precision bugs) Not finished work Not connected to energy model
Directed Diffusion Famous sensor network routing protocol in the early period.
Many other sensor network protocol had simulated on NS-2 but they are not contributed to NS-2 release.
We think that peoples interested in the simulation of sensor network in NS-2 may want to implement their own protocol.
30
Combination of OTcl and C++
OTcl is the frontend and C++ is hidden to users. They have similar class hierarchy and closely related to each other.
<OTcl class> <C++ class>
– Simulation script
– Configure the node and topology
– Manipulating bytes and packets
– Complicated algorithm
31
C++/OTcl Linkage
Root of ns-2 object hierarchy
bind(): link variable values between C++ and OTcl TclObject
command(): link OTcl methods to C++ implementations
TclClass Create and initialize TclObject’s
Tcl C++ methods to access Tcl interpreter
TclCommand Standalone global commands
EmbeddedTcl ns script initialization
<from IEC 2000 Workshop>
32
Mobile Node Architecture
Node
ARP
Propagation and antenna models MobileNode
LL
MAC
PHY
LL
CHANNEL
LL
MAC
PHY
Classifier: Forwarding
Agent: Protocol EntityNode Entry
LL: Link layer object
IFQ: Interface queue
MAC: Mac object
PHY: Net interface
protocolAgent
(sink/source)
routingagent
addrclassifier
portclassifier
255
IFQIFQ
defaulttarget_
Radio propagation/antenna models
Prop/ant<from ISI ns tutorial 2002>
33
Signal reception
Node 1
Node 2
Node 3
Node 4
2. R ≥ CSThresh3. R ≥ RXThresh4. R/P ≥ CPThresh (in collision)
Unless, two packets are discarded5. Delivered to MAC
1. Signal will be delivered to all nodes
2. R ≥ CSThresh3. R < RXThreshCan not regenerate the bit stream from the signal
2. R < CSThreshCan not be recognized
R: signal strength of received packetP: signal strength of previous packet
C
H
A
N
N
E
L
34
Packet flow
Node
ARP
Propagation and antenna models MobileNode
LL
MAC
PHY
LL
CHANNEL
protocolAgent
(sink/source)
routingagent
addrclassifier
portclassifier
255
IFQ
defaulttarget_
ignore
Generated pkt
Received pkt
35
Implementing new routing protocol
Routing protocol → Routing Agent which is the child of Agent class
Responsibility Maintaining the routing table Dealing with the routing information delivered to port 255 Marking the next node in pkt from the source and send to LL Forwarding the received pkt
TTL over → drop Loop occurred → drop Re-marking the next node and send to LL
36
Directory structure
Ns-2.27├ mac│ └ wireless-phy.cc├ pad│ ├ rtable.cc/h │ └ pad.cc/h├ tools│ └ loss-monitor.cc/h └ tcl └ lib └ ns-lib.tcl
For per packet style tx power control
For PAD routing agent
Couting received pkts, average hop count, etc
For OTcl part of PAD routing agent
37
PAD Implementation : C++/OTcl Linkage
static class PADClass : public TclClass {public: PADClass() : TclClass("Agent/PAD") {} TclObject *create(int argc, const char *const *argv) { return (new PAD_Agent()); }} class_pad;
PAD_Agent::PAD_Agent(){ helper_ = new PAD_Helper (this); bind_time("initrig_", &initrig_t); bind_time("update_period_", &update_period_); : bind("report_unit_", &report_unit_); bind("betta_", &betta_); bind("gamma_", &gamma_); bind("limit_", &limit_);}
A kind of declaration of the OTcl calss that C++ class mirrors
Return new C++ class whenever OTcl class created.
OTcl can access C++ variables.
Root of ns-2 object hierarchy
bind(): link variable values between C++ and OTcl TclObject
command(): link OTcl methods to C++ implementations
TclClass Create and initialize TclObject’s
Tcl C++ methods to access Tcl interpreter
TclCommand Standalone global commands
EmbeddedTcl ns script initialization
<pad/pad.cc>
<pad/pad.cc>
38
PAD Implementation : C++/OTcl Linkage
Tcl& tcl = Tcl::instance();if (thisnode->energy_model()->energy() == 0.0 && mylevel_ != 0) { level_[1]--; level_[0]++; mylevel_ = 0; printf("dead %d %d\n", (int) Scheduler::instance().clock(), myaddr_);}if (myaddr_ == 0) { printf("%d %d ", (int) Scheduler::instance().clock(), level_[0]); tcl.eval("$sink log");}Scheduler::instance().schedule(helper_, energy_, 1);
int PAD_Agent::command(int argc, const char *const *argv) { if (argc == 2) { if (!strcmp(argv[1], "start-pad")) { startUp(); return TCL_OK; } } else if (argc == 3) { if (!strcmp(argv[1], "addr")) { myaddr_ = Address::instance().str2addr(argv[2]); return TCL_OK; } : } return Agent::command (argc, argv);}
Root of ns-2 object hierarchy
bind(): link variable values between C++ and OTcl TclObject
command(): link OTcl methods to C++ implementations
TclClass Create and initialize TclObject’s
Tcl C++ methods to access Tcl interpreter
TclCommand Standalone global commands
EmbeddedTcl ns script initialization
Create the instance of Tcl interpreter
Command the Tcl interpreter
Compare the command from Tcl
If nothing matched, it may be for the Agent class.
<pad/pad.cc>
<pad/pad.cc>
39
PAD Implementation : recv()
void PAD_Agent::recv(Packet *p, Handler *h) { hdr_ip *iph = HDR_IP(p); hdr_cmn *cmh = HDR_CMN(p); int src = Address::instance().get_nodeaddr(iph->saddr()); int dst = cmh->next_hop(); Node* srcnode = Node::get_node_by_address(myaddr_); double r, e, f = srcnode->energy_model()->initialenergy(); int l, i;
if (src == myaddr_ && cmh->num_forwards() == 0) { if (adj_table_.next_index() == -1) { drop(p, DROP_RTR_TTL); return; } cmh->size() += IP_HDR_LEN; iph->ttl_ = IP_DEF_TTL; } else if (src == myaddr_) { drop(p, DROP_RTR_ROUTE_LOOP); return; } else { if (--iph->ttl_ == 0) { drop(p, DROP_RTR_TTL); return; } }
if (src != myaddr_ && iph->dport() == ROUTER_PORT) { //trg_rcv_++; processUpdate(p); } else { if (src == myaddr_ && cmh->num_forwards() == 0) gen_pkt_++; else if (src != myaddr_ && cmh->num_forwards() > 0) rcv_pkt_++; else flt_pkt_++; forward(p); }
Recv() Entry point of the agent Pkt is delivered to recv() of each ag
ent. Sending up and down to another lay
er is just the call of recv() whose parameter is the pointer of pkt.
Generated at upper layer
Loop occurred
TTL over
Routing information
Dealing with routing information
Forward the pkt
<pad/pad.cc>
40
PAD Implementation : processUpdate()
void PAD_Agent::processUpdate(Packet *p) {hdr_ip *iph = HDR_IP(p); int src = Address::instance().get_nodeaddr(iph->saddr());Node* srcnode = Node::get_node_by_address(myaddr_); double myenergy = srcnode->energy_model()->energy();unsigned char *d = p->accessdata(); unsigned char *walk = d + 1; unsigned char type = *d; int i, j, found = 0;
if (type == PAD_LOCATION) { double x, y, z, dist; unsigned char tmp; for (i = 0; i < sizeof(double); i++) { memcpy((unsigned char *) ((int)&x + i), walk++, 1); } for (i = 0; i < sizeof(double); i++) { memcpy((unsigned char *) ((int)&y + i), walk++, 1); } for (i = 0; i < sizeof(double); i++) { memcpy((unsigned char *) ((int)&z + i), walk++, 1); } dist = sqrt((x_-x)*(x_-x) + (y_-y)*(y_-y)); // printf("%d receives location info from %d, %g, %g, %g (%g) ", myaddr_, src, x, y, z, dist); adj_table_.add_adj_loc(src, x, y, z, dist, prev_report_);} else if (myaddr_ != 0 && type == PAD_TRIGGER) { int nei_n; double p_consume; int hop, era, tmp; walk = is_neighbor(walk, &found); if (!found) { Packet::free(p); return; } trg_rcv_++; for (i = 0; i < sizeof(double); i++) memcpy((unsigned char *) ((int)&p_consume + i), walk++, 1); for (i = 0; i < sizeof(int); i++) memcpy((unsigned char *) ((int)&hop + i), walk++, 1); for (i = 0; i < sizeof(int); i++) memcpy((unsigned char *) ((int)&era + i), walk++, 1); if (era_ != era) { adj_table_.new_era(); era_ = era; } tmp = adj_table_.tbl_index(src); if (adj_table_.update_nei(tmp, p_consume, hop, era, lowpow_)) { if (myenergy > (srcnode->energy_model()->initialenergy()*0.20)) { adj_table_.get_next_metric(&p_consume, &hop); trg_snd_++; initTrigger(p_consume, hop, era, trig_jitter_); } }
:
Location information from adjacent nodes
Extracting location information from the pkt
Routing information receivedIs it neighbor? (Is it connected on MEPG?)
Extracting metrics from the received pkt
If received pkt is better than previous one, broadcast it.
<pad/pad.cc>
41
PAD Implementation : MEPG algorithm
void AdjTable::calc_nei_table(int use, int limit) { double PQ[TBL_SIZE], dist[TBL_SIZE]; int PL[TBL_SIZE], p[TBL_SIZE], l[TBL_SIZE]; int v, i, j, u; double c;
// Dijkstra's Algorithm PQ[0] = dist[0] = 0; PL[0] = 0; p[0] = 0; l[0] = 0; for (v = 1; v <= adj_num_; v++) { PQ[v] = dist[v] = POW_INFINITY; PL[v] = v; p[v] = -1; l[v] = HOP_INFINITY; } i = adj_num_; while (i >= 0) { for (j = 0; j < i; j++) { if (PQ[j] < PQ[i]) { swap(&PQ[j], &PQ[i]); swap(&PL[j], &PL[i]); } } u = PL[i]; for (v = 0; v <= adj_num_; v++) { if (adj_table_[u][v] == POW_INFINITY) continue; c = dist[u] + adj_table_[u][v]; if (c < dist[v] && l[u]+1 <= limit) { dist[v] = c; p[v] = u; l[v] = l[u] + 1; } } for (v = 0; v <= adj_num_; v++) { for (j = 0; j <= adj_num_; j++) { if (v == PL[j]) PQ[j] = dist[v]; } } i--; }
// Choosing UMEPs for (i = 1; i <= adj_num_; i++) {// printf("%d->%d->c %g\n", i, p[i], dist[i]); // printf("%d->%d->c %g\n", i, p[0][i], adj_table_[0][i]); if (use == 1) { if (p[i] == 0) {// printf("find UMEP %d\n", i); add_nei_ent(i-1); } } else add_nei_ent(i-1); }}
, ( [ ] )
' , ( [ ] ')
'' ' , ( [ '] '')
c u v p v u
c u u v p u u
c u u u v p u u
<pad/rtable.cc>
42
PAD Implementation : forward()
void PAD_Agent::forward(Packet *p) { hdr_ip *iph = HDR_IP(p); hdr_cmn *hdrc = HDR_CMN(p); unsigned char *walk; double p_tmp = adj_table_.get_p(adj_table_.next_index()); double p_con_tmp = adj_table_.get_pconsume(adj_table_.next_index()); int i; walk = p->accessdata();
if (walk == NULL) { p->allocdata(sizeof(double)*2 + 1); hdrc->size_ += sizeof(double)*5 + 1 + IP_HDR_LEN; walk = p->accessdata(); } if (txctrl_t > 0.0) *(walk++) = PAD_DATA; else *(walk++) = PAD_NO_CONTROL; for (i = 0; i < sizeof(double); i++) memcpy(walk++, (unsigned char *) ((int)&p_tmp + i), 1); for (i = 0; i < sizeof(double); i++) memcpy(walk++, (unsigned char *) ((int)&p_con_tmp + i), 1); hdrc->direction() = hdr_cmn::DOWN; hdrc->addr_type_ = NS_AF_INET; hdrc->xmit_failure_ = mac_callback; hdrc->xmit_failure_data_ = this; hdrc->next_hop_ = adj_table_.next_node_n(); assert(!HDR_CMN(p)->xmit_failure || HDR_CMN(p)->xmit_failure_ == mac_callback); snd_pkt_++; target_->recv(p, (Handler *)0);}
Per pkt power control
Send down to the link layer
The function called when tx failed
Remarking the next node
<pad/pad.cc>
43
PAD Implementation : OTcl code
Simulator instproc create-wireless-node args { $self instvar routingAgent_ wiredRouting_ propInstance_ llType_ \
macType_ ifqType_ ifqlen_ phyType_ chan antType_ energyModel_ \initialEnergy_ txPower_ rxPower_ idlePower_ \topoInstance_ level1_ level2_ inerrProc_ outerrProc_ FECProc_
Simulator set IMEPFlag_ OFF
# create node instance set node [eval $self create-node-instance $args] # basestation address setting if { [info exist wiredRouting_] && $wiredRouting_ == "ON" } { $node base-station [AddrParams addr2id [$node node-addr]] } switch -exact $routingAgent_ { PAD { set ragent [$self create-pad-agent $node] } DSDV { set ragent [$self create-dsdv-agent $node] }
Simulator instproc create-pad-agent { node } { # Create a pad routing agent for this node set ragent [new Agent/PAD] # Setup address (supports hier-addr) for pad agent # and mobilenode set addr [$node node-addr] $ragent addr $addr $ragent node $node if [Simulator set mobile_ip_] { $ragent port-dmux [$node demux] } $node addr $addr $node set ragent_ $ragent $self at 0.0 "$ragent start-pad"
return $ragent}
Create the Mobile Node
Create the routing agent
<tcl/lib/Ns-lib.tcl>
44
PAD Simulation Script #1
# ======================================================================# Define options# ======================================================================set val(chan) Channel/WirelessChannel ;# channel typeset val(prop) Propagation/TwoRayGround ;# radio-propagation modelset val(netif) Phy/WirelessPhy ;# network interface typeset val(mac) Mac/802_11 ;# MAC typeset val(ifq) Queue/DropTail/PriQueue ;# interface queue typeset val(ll) LL ;# link layer typeset val(ant) Antenna/OmniAntenna ;# antenna modelset val(energymodel) EnergyModel ;#set val(initialenergy) 2.0 ;#set val(baseenergy) 600 ;#set val(p_rx) 22.2e-3 ;#set val(p_tx) 80.1e-3 ;#set val(x) 50 ;# X dimension of the topography set val(y) 50 ;# Y dimension of the topographyset val(ifqlen) 50 ;# max packet in ifqset val(nn) 200 ;# number of mobilenodesset val(rp) PAD ;# routing protocolset val(stop) 600.0 ;# simulation timeset val(cbr_stop) 597.0 ;# simulation time
Antenna/OmniAntenna set Z_ 0.1
#Phy/WirelessPhy set CPThresh_ 10#Phy/WirelessPhy set CSThresh_ 1e-10 ;#1.559e-11Phy/WirelessPhy set RXThresh_ 1e-10Phy/WirelessPhy set Rb_ 1.38e3Phy/WirelessPhy set Pt_ 10.0e-3Phy/WirelessPhy set freq_ 433.0e+6
Height of antenna : 10cm → tx range 10m, 1.5m → tx range 150m
Berkeley’s MICA2 spec
45
PAD Simulation Script #2
Agent/PAD set node_num_ $val(nn)Agent/PAD set calcnei_ 5.5Agent/PAD set initrig_ 6.0Agent/PAD set update_period_ 100.0Agent/PAD set txctrl_ 19.9Agent/PAD set report_599.9Agent/PAD set use_mepg_ 1Agent/PAD set use_energy_ 1Agent/PAD set loc_jitter_ 5.0Agent/PAD set trig_jitter_ 2.5Agent/PAD set energy_jitter_ 0.01Agent/PAD set lowpow_ 1
Agent/PAD set limit_ 100Agent/PAD set betta_ 1.0Agent/PAD set gamma_ 1.0Agent/PAD set report_unit_ 0.15
# ======================================================================# Main Program# ======================================================================if {$argc < 1} {
puts "Uage: ns pad.tcl \[replication number\]"exit
}set run 0if {$argc == 1} {
set run [lindex $argv 0]}
# Initialize Global Variablesset ns [new Simulator]set tracefd [open pad.tr w]set namtrace [open pad.nam w]
The number of nodesRun MEPG algorithm atRun DDBF algorithm at
Routing table update period, base node resend trigger message in this periodTeach the physical layer maximum tx power
Print simulation result at
1:Do routing on MEPG, 0:on the original graph1:Use tx power control 0:always emit in maximum strength
Jitter for the initial location information broadcastingJitter for routing information broadcastingJitter for remaining battery capacity broadcasting
1:minimum energy routing, 0:minimum hop routing
limit value for TMEPG algorithm
Coefficients for ARM
Choose stream of RNG for the simulation of different environment
46
PAD Simulation Script #3
# configure base node$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) \ -rxPower $val(p_rx) \ -txPower $val(p_tx) \ -energyModel $val(energymodel) \ -initialEnergy $val(baseenergy) \ -channelType $val(chan) \ -topoInstance $topo \ -agentTrace ON \ -routerTrace ON \ -macTrace OFF \ -movementTrace OFF
set node_(0) [$ns node] $node_(0) random-motion 0 ;# disable random mo
tion
# configure sensor node$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) \-rxPower $val(p_rx) \-txPower $val(p_tx) \-energyModel $val(energymodel) \-initialEnergy $val(initialenergy) \-channelType $val(chan) \-topoInstance $topo \-agentTrace ON \-routerTrace ON \-macTrace OFF \-movementTrace OFF
for {set i 1} {$i < $val(nn) } {incr i} {
set node_($i) [$ns node]$node_($i) random-motion 0 ;# disable ran
dom motion}
47
PAD Simulation Script #4
set rng_ux [new RNG]for {set j 0} {$j < $run} {incr j} {
$rng_ux next-substream}
set rng_uy [new RNG]for {set j 0} {$j < $run} {incr j} {
$rng_uy next-substream} :set ux [new RandomVariable/Uniform]$ux use-rng $rng_ux$ux set min_ 0$ux set max_ $val(x) :set us [new RandomVariable/Uniform]$us use-rng $rng_us$us set min_ 20$us set max_ 30 ;#$val(stop)/2
set ui [new RandomVariable/Uniform]$ui use-rng $rng_ui$ui set min_ 1$ui set max_ 10
# Provide initial (X,Y, for now Z=0) co-ordinates for mobilenodesfor {set i 0} {$i < $val(nn)} {incr i} {
$node_($i) set X_ [$ux value]$node_($i) set Y_ [$uy value]$node_($i) set Z_ 0.0
}
48
PAD Simulation Script #5
# Setup traffic flow between nodesset sink [new Agent/LossMonitor]$ns attach-agent $node_(0) $sink$ns at 599.91 "$sink log“
for {set i 1} {$i < $val(nn)} {incr i} {set udp_($i) [new Agent/UDP]$ns attach-agent $node_($i) $udp_($i)$ns connect $udp_($i) $sinkset cbr_($i) [new Application/Traffic/CBR]$cbr_($i) set packetSize_ 42$cbr_($i) set interval_ [$ui value]$cbr_($i) attach-agent $udp_($i)$ns at [$us value] "$cbr_($i) start"$ns at $val(cbr_stop) "$cbr_($i) stop"
}
entry_point_ Routing Agent
Loss Monitor UDP
CBRCount the number of received pkt
Generate pkt according to RNG
49
Extracting data from the result
Post-processing of trace file Some protocol doesn’t fully generate the trace
information.
Insert the code in the Agent Print the result at the end of simulation Port-processing with AWK, SED.
50
AWK and SED
num_nodes is set 2001 0 0 nan2 0 0 nan
:19 0 0 nan20 0 0 nan21 0 18 4.3888922 0 40 5.123 0 68 5.4558824 0 97 5.443325 0 127 5.393726 0 163 5.39877
:596 61 18845 6.13462dead 596 97597 62 18846 6.13435598 62 18846 6.13435599 62 18846 6.134350 15 12 131 0.0180012 0 0 597.477 0 0 0 0 0 0 1000000000 -1 -11 23 22 77 0.0168975 2 0.0557542 0 234 12 53 1425 1473 5 5 5 62 17 16 46 0.0215665 46 0.0215665 0.230704 175 12 77 2183 2249 11 13 13
153 12 12 132 0.0297361 132 0.0297361 1.75927 421 34 122 0 122 0 13 13 144 18 16 107 0.0627739 107 0.0627739 1.28186 469 16 159 0 158 1 9 9 125 21 18 169 0.0214703 198 0.0163407 0.266743 340 27 102 906 1008 0 6 6 86 28 21 16 0.0222356 16 0.0222356 0 125 7 34 571 605 0 3 3 47 17 16 38 0.0611482 38 0.0611482 0 94 13 58 4 59 3 15 15 15
:
<Result file>
#!/usr/bin/awk -fBEGIN { time[600]; dead[600]; rcv[600]; hop[600];}
{ time[$1] += 1; dead[$1] += $2; rcv[$1] += $3; hop[$1] += $4;}
END { for (i = 21; i < 600; i++) printf i" "time[i]" "dead[i]/time[i]" "…"\n";}
#!/usr/bin/sed -f/^dead/d/^num_nodes/ds/nan/0//[^\.]*\.[^\.]*\.[^\.]*$/d/^[0-9]\{1,\} [0-9]\{1,\}\.[0-9]\{1,\}$/d/^[0-9]\{1,\} 0 0 0$/d/^graph/d/^}/d/.pos./d/.--./d
0 100 200 300 400 500 6000
10
20
30
40
50
60
70
80
90
Time (sec)
Th
e n
um
be
r o
f n
od
es
co
ns
um
ing
all
en
erg
yMin-hop RoutingPADPAD on MEPG
51
Copy the patch file into your ns-2.27 directorycp s6.tar ~/ns-allinone-2.27/ns-2.27
Untartar xvf s6.tar
Modify Makefile
Exercise
dsdv/dsdv.o dsdv/rtable.o queue/rtqueue.o \Line 239: pad/pad.o pad/rtable.o\
routing/rttable.o \
tags: force ctags -wtd *.cc *.h webcache/*.cc webcache/*.h dsdv/*.cc dsdv/*.h \
Line 498: pad/*.cc pad/*.h \ dsr/*.cc dsr/*.h webcache/*.cc webcache/*.h lib/*.cc lib/*.h \ ../Tcl/*.cc ../Tcl/*.h
TAGS: force etags *.cc *.h webcache/*.cc webcache/*.h dsdv/*.cc dsdv/*.h \
Line 504: pad/*.cc pad/*.h \ dsr/*.cc dsr/*.h webcache/*.cc webcache/*.h lib/*.cc lib/*.h \ ../Tcl/*.cc ../Tcl/*.h
52
Clean unpatched ns binary and remakemake clean; make
Run the simulation under sim directorycd simvi pad.tcl line 21: set val(stop) 100 line 38: Agent/PAD set report_ 99.9
chmod +x *run 1 5 pad ( ns pad.tcl 1 > pad.log )
Post-processing of the resultextdead pad.log | ./calcdeadmkres pad 5
Exercise
53
References
“NS Manual,” http://www.isi.edu/nsnam/ns/ns-documentation.html
“NS worksop and presentation,” http://www.isi.edu/nsnam/ns/ns-tutorial/index.html
박노성 , 김대영 , 이상수 , 도윤미 , 김지태 , " 센서 네트워크를 위한 저전력 라우팅과 네트워크 수명 연장 기법 ," 제 14 회 통신정보합동학술대회 (The 14th JOINT CONFERENCE ON COMMUNICATIONS & INFORMATION), Apr 2004
54
An example ofCycle and Straying Data
Node u wants to send data but node r doesn’t have enough energy to afford it.
Node u selects node s for its temporary next node. If ARM is applied, u cannot select s, because Hop Count is same.
Node t doesn’t have enough energy, either. Node s chooses node v for its temporary next node.
Node s is the next node of v. Data is sent to node s again.
Cycle occurs at node s, and the data will roams the node u, s, and v to find the node having enough energy.