Sunday 2 November 2014

Tutorial on TCL for Begineers

Firstly, we should get ns or tcl shell installed to work with tcl script. 
 
If you didn't install ns2, for the installation procedure. Else, follow the tutorial. 
After installing ns-2, type ns in terminal. Then, there appears % symbol, which symbolizes the invokement of tcl shell script.
 
Note(optional): TCL scripting individually can be practiced with in Linux system with tcl shell scripting.


Introduction: 
TCL is an abbreviation for Tool Command Language. Tcl is a string-based command (script) language, with simple syntax. Tcl is designed to be a glue that assembles software building blocks into applications.The latest version of TCL is 8.8.2. 

The goal of this tutorial is to introduce the learner to TCL scripting and make comfortable to do scripting required for ns2 network simulations. It covers working with variables, lists, arrays, control structures and other core features, in TCL. The tutorial was created on Ubuntu Linux, but the users can practice TCL scripting individually in WINDOWS by downloading ActiveTCL.


Working with TCL:

set – command to assign a value to a variable.

set variable_name value
set u 10

set variable_name2 $variable_name
set c $u

# - Symbol used for line comment. Tcl interpreter will not execute that line. There isn’t any paragraph commenter in tcl/otcl scripting.

expr – command to invoke any mathematical operation.
set variable_name [expr $var1+$var2]
set d [expr $b + $c]

puts – Command to print output to the console.
puts 10
puts d
puts $d
puts d is different from puts $d

In Tcl, there are no variable types. So, a variable can be a string or integer depending on value you assign to it. Also, the typecasting rules also apply here.
puts [expr 1/2]
puts [expr 1.0/2]
puts [expr 1/2.0]
puts [expr 1.0/2.0]

/  operator is used for division. \ operator is not defined in tcl. NOTE: spaces are not important
expr 5*3
expr 5    *     3

Both these statements, result the same answer. But, spaces are not preferable for good programming.

NOTE:
Dividing by zero
expr 1/0
Interpreter shows "DIVIDE BY ZERO" error.
This can't be done by a programming language

Working with strings, in TCL:

set e “udhay prakash”;
set f {udhayprakash.blogspot.in};
puts $e
puts “udhay prakash”
puts $f
puts “udhayprakash.blogspot.in”

Working with files, in TCL:
·         To create and write in a new file, with file1 as the filename: set file1 [open filename w]; 
·         To read an already existing file, with file2 as the filename:   set file2 [open filename r];
·         To print data into a file, with file2 as filename:                                   puts $file2 “text”;

Conditional Statements:
Syntax:
if {expression}
{          <execute some commands>
} else {
            <execute some commands>
}

Example:
set a 10;
set b 20;
if($a!=$b){
puts “$a!=$b”;
}else{
puts “$a=$b”;
}

Loop Statements:
for loop syntax:
for{initialization}{condition}{increment/decrement}
{ <execute some commands>
}

for loop example:
set i 0
for{set i 0}{$i<5}{incr i}{
puts “$i/t”
puts [expr $i/t]
}

while loop syntax:
while {condition}{
<execute some commands>
<increment/decrement looping variable>
}

while loop example:
set m 10
set n 2
while{$m!=0}{
puts {$m\n}
incr m -1
}

do-while loop syntax:
do{
<execute some commands>
<increment/decrement looping variable>
}while{condition};
do-while loop example:
set m 10
set n 2
do{
puts {$m\n}
incr m -1
}while{m};
return – command to return a value from procedure
continue – command to bypass a loop in a procedure
break – command to come out of a procedure
proc – command to create a procedure(function). The procedure receives some parameters that can be objects, files or variables.

Procedure syntax:
 proc procedure{in_par1, in_par2, …..}{
            global variable_list, file_list
            <execute some commands>
             return $something
            }
 
Procedure Example1:
proc factorial {j} {
for {set result 1} {$j > 1} {set j [expr $j ­1]} {
set result [expr $result * $j]
}
 
Procedure Example2:
#create a procedure
proc test{}{
set a 4
set b 2
set c [expr $a+$b]
set d [expr [expr $a-$b]*$c]
puts “c=$c, d=$d”
for {set k 0}{$k<10}{incr k}
if {$k<5}{
puts “k<5,pow=[expr pow($d,$k)]”
} else{
puts “k>=5,mod=[expr $d%$k]”
}
}}
Calling a Procedure:
Syntax: procedure_name
Example: test

SUMO Simulation of Urban Mobility installation in Linux (Debian/Ubuntu/Mint)

SUMO-Simulation of Urban Mobility

SUMO an open source, microscopic, multi-modal traffic simulation. 

It allows to simulate how a given traffic demand which consists of single vehicles moves through a given road network. The simulation allows to address a large set of traffic management topics. It is purely microscopic: each vehicle is modelled explicitly, has an own route, and moves individually through the network.

SUMO INSTALLATION PROCEDURE:

Step 1: Download the SUMO latest source-tarball from here. At the time of this writing, it was version sumo-src-0.21.0.tar.gz.

Step 2: Change into the directory in which you downloaded the tarball file. In my case, it's the Downloads directory, inside my home:

$ cd
$ cd Downloads


Step 3: Two Prerequisites packages are necessary to build SUMO with GUI: type

$ sudo apt-get install libgdal1-dev proj libxerces-c2-dev
$ sudo apt-get install libfox-1.6-dev libgl1-mesa-dev libglu1-mesa-dev


Step 4: Ubuntu 12.04 does not ship with libgdal.so, only with libgdal1.7.0.so. So, create a symbolic link:
$ sudo ln -s /usr/lib/libgdal1.7.0.so /usr/lib/libgdal.

Note: Ubuntu 14.04 doesnt require this step. It comes inbuilt with libgdal package.

Step 5: Installation:

Decompress the tarball:

$ tar -xzvf sumo-src-0.15.0.tar.gz

Step 6:
Move the decompressed directory to '/usr/local/src':

$ sudo mv -v sumo-0.15.0 /usr/local/src

Step 7:
Enter the source directory and call configure, make and make install:

$ cd /usr/local/src/sumo-0.15.0

$ ./configure --with-fox-includes=/usr/include/fox-1.6 \
--with-gdal-includes=/usr/include/gdal --with-proj-libraries=/usr \
--with-gdal-libraries=/usr --with-proj-gdal



Step 8: type
$ make
$ sudo make install


Step 9: To call SUMO in the command line, type:

$ sumo-gui

For more details about SUMO, go to their homesite.http://sumo-sim.org/userdoc/Sumo_at_a_Glance.html


Mail me for any installation issues.

To know whether my Linux system is 32 bit or 64 bit ?

Generally, during any software installation, one gets puzzled regarding the system architecture i.e., whether the PC/desktop is 32 bit or 64 bit build...

Simplest way to know is here.

Step1: Open the terminal.

Step 2: type uname -a
Result for 32-bit Ubuntu:
Linux discworld 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386GNU/Linux
whereas the 64-bit Ubuntu will show:
Linux discworld 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 x86_64 x86_64x86_64 GNU/Linux

Identify whether it is i386 or x86_64; correspondingly it is 32 bit or 64 bit build architecture, respectively.


Note: There are many other alternative ways in Linux, to determine the system architecture; but, this is probably the simplest way.

Beginners tutorial MATLAB 

Its a simulation tool. Very useful for ECE EEE ME 

MATLAB is abbreviation for MATrix LABoratory.

MATLAB is an integrated development environment and computer language that enables users to perform computationally intensive tasks.  The software is used for numerical computation tasks, visualization, and mathematical programming.
For more details, see http://www.mathworks.com/products/matlab.

Latest release of MATLAB is R2014a.

As the name emphasis, MATLAB considers every variable/value in terms of matrices.
MatLab vs c: MatLab is not a programming language, but it is a scripting language. In simple English, you use English-like commands in the MatLab program; whereas corresponding c program will run in the background.

So, MatLab program is slower than c program; but is more flexible and lightweight than the former. 


The latest MATLAB constitutes FOUR platforms, within its environment.
1. M-file/Script file platform
2. Simulink
3. GUIDE- Graphical User Interface IDE(Integrated Development  Envinirment)
4. Matlab APPLICATIONS


Note: All these four are not independent, but dependent on each other. It is recommended to start with M-file/script-file programming for a beginner.


Cost of MatLab: MatLab is a proprietary software, but it is worthy-enough to pay for it. Even there is free student version of MatLab, which is available on demand from the mathworks website.
A humble request is to buy the MatLab products, and don't be a part of pirating the software(which is done by many torrent-hosting/file-sharing  websites).
Platform support: MatLab is available in Windows, Unix  and Macintosh platforms. The Unix flavor is used for linux too.
Alternatives to MatLab: In contract, there are free alternatives for MatLab, such as Octave, Scilab,etc. Scilab is available in windows and linux platforms; whereas Octave is available only for Linux platform.

Matlab programs are backward compatible.

MATLAB is a proprietary software, patented by MathWorks Inc.
Though it is commercial, the free student version can be downloaded from MathWorks website, on registration.

Windows in MATLAB:

By default, you will see the default window layout.
Else, to get the default layout of windows in MATLAB, go to File->Desktop->Desktop Layout->Default.

1. Command Window: It is heart of MATLAB, where the response of all inputted commands will the displayed, expect the graphical responses.

2. Command History: It stores all the commands executed in the command window, including the date and time of their execution.
It doesn't store commands executed through script-files.


3. Current Folder (Current working Directory): Indicates the current folder to which matlab is associated. All user-defined functions and other files(images, audio files, video files..) must be in the current folder. Also, the current folder association can also be changed.

4. Workspace: It stores all the variables, their data, data types, and some more information about the variables used in current computations. The variables can be cleared. Closing Matlab, automatically results in clearing of workspace.

5. Editor Window: All the M-files/script files must be written in this editor. Optionally, notepad can also be used as matlab editor, where the file should be saved with .m extension to make an M-file. But, Editor Window has some advanced options like direct execution, publishing, ...

6. Figure Window: All the graphical responses will be displayed in this window. By default, it saves with .fig extension; but there are options to save as conventional file formats like .jpg. .png,...

 File Types in MATLAB:

1) .m files -> These are the Matlab script files. user-defined functions are also saved as .m files.
2) .fig files -> The default file type to save the images/figures. The GUIDE files are also saved with .fig extension.
3) .mdl files -> The Simulink Model files are saved with .mdl extension. mdl files are text files.
4) .slx files -> New file format to save the simulink models, release from R2012a. SLX is a compressed file that contains model information in XML format.
 Note: It is optional to the user to choose between .mdl and .slx extensions.

5).mat files-> It is similar to the .dat file, used to store data.


Apart from these proprietary file formats, Matlab supports few file formats to import and export data.
 
How to open Matlab
    Method1: click on matlab shortcut in start menu or on desktop
    Method2: for windows os ::::Press windows+R--->type cmd--->type "matlab"
             for linux os:::::::go to terminal/Konsole--->type "matlab"

Note: It is recommended not to do any action, atleast-for-a-vial, while opening MATLAB because Matlab consumes more RAM while invoking.

2. Basic commands
 
   ver
   version
   license/hostid
   computer/computer('arch')
   ispc/isunix/ismac
   matlabpath/path/setpath
   dir/ls---files in current working directory
   delete filename.m
   mkdir/rmdir
   diary
   cd/pwd----present working directory
   diary('filename'),diary on ....diary off

Working 
Type the following following commands in the Command Window, and observe(verify) their corresponding results  12

ans =     12

% commenting operator in matlab
%12

a=23

a =

    23

a=23; %; is a output suppressor operator

who

Your variables are:

a    ans

whos
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double            
  ans       1x1                 8  double            


who---- This command lists the variables in workspace.

whos----This command details the variables in workspace.


12+23

ans =

    35

12-23

ans =

   -11

mul=12*23

mul =

   276

div=12/23;
; is the output suppressing operator

who

Your variables are:

a    ans  div  mul

div

div =

    0.5217

1/2

ans =

    0.5000

2/1

ans =

     2

1/2

ans =

    0.5000

1\2

ans =

     2

%   \ is the inverted division operator a\b=b/a
2/3

ans =

    0.6667

2\3

ans =

    1.5000

3/2

ans =

    1.5000

% exponential representation

1e3

ans =

        1000
% e and E holds fine

1E3

ans =

        1000
% But, matlab is case-sensitive

a=exp(2)

a =

    7.3891

A=exp(1)

A =

    2.7183
who
a   A

% lookfor ----This command is used for command search
% Syntax: lookfor keywork_to_search

% we know the relation between exponential and logarithm

q=exp(12)

q =

   1.6275e+05

log(q)

ans =

    12

% = assignment operator
% == equivalence operator, tests equality between variables on both sides
% == results 1, if both are equal; 0, if they are not equal
1==2

ans =

     0

1==1

ans =

     1

a=exp(12),b=log(a)

a =

   1.6275e+05


b =

    12

log(exp(12))

ans =

    12
exp(log(12))

ans =

    12

% log ---command to compute natural logarithm
% log10---command to compute base 10 logarithm
exp(log10(12))

ans =

    2.9423

log10(exp(12))==log(exp(12))

ans =

     0

% both are not equal

log10(10^12)==10^(log10(12))
ans=
 
     1
%both are equal

%trigonometric computations
sin(90)

ans =

    0.8940

pi

ans =

    3.1416

22/7

ans =

    3.1429

sin(pi/2)

ans =

     1

sin(pi/2)==sin(90)

ans =

     0

sin(0)

ans =

     0

asin(sin(pi/2))

ans =

    1.5708

asin(sin(90))

ans =

    1.1062

sin(5)

ans =

   -0.9589

% Matlab’s trig functions are permanently set to radians mode

% The up-arrow key will display previous commands.
% And when you back up to a previous command that you like, hit Enter and it will execute.
% Or you can edit it when you get to it (use , , and Del), then execute it. Try doing this
% Now to re-execute the commands you have already typed.
diary off

clear all %to clear the workspace. Execute and observe the workspace window

close all % closes safely all the windows opened, except main window and the editor window

clc%clears the command window. Execute it and observe the command window

who
% As "clear all" command clears all the variables; so "who" can't display any variable.

% who lists active variables

% whos----lists active variables and their sizes

% what-------lists .m files available in the current directory


% Numerical Accuracy in MATLAB
225/331

ans =

    0.6798

format long e
225/331

ans =

     6.797583081570997e-01

format short% (the default format)
225/331

ans =

    0.6798

format long
225/331

ans =

   0.679758308157100

format short e
%e stands for exponential notation
225/331

ans =

   6.7976e-01

format bank
225/331

ans =

    0.67

format short% (the default format)

225/331

ans =

    0.6798


pi

ans =

    3.1416

who

Your variables are:

ans

pi=2%can be done

pi =

     2

who

Your variables are:

ans  pi 

pi

pi =

     2

% please don't do so. "pi" was assigned to 3.1416, by default
pi=3.1416

pi =

    3.1416

clear all
pi

ans =

    3.1416

power(2,5)
ans =

    32

power(10,2)

ans =

   100

pow2(2)

ans =

     4

%pow2(2) means 2^2
%X = pow2(Y) for each element of Y is 2 raised to the power Y
%  X = pow2(F,E) for each element of the real array F and a integer
%    array E computes X = F .* (2 .^ E).

X = pow2(Y) for each element of Y is 2 raised to the power Y

sqrt(25)

ans =

     5

% sqrt---to calculate the squarate


% working with complex numbers
a=2+2j

a =

   2.0000 + 2.0000i

b=3+5i

b =

   3.0000 + 5.0000i

% either "i" or "j" can be used to represent the imaginary number
diary off
2j

ans =

        0 + 2.0000i

2i

ans =

        0 + 2.0000i

%but, the notation "i2" or "j2" is forbidden
i2
{ Undefined function or variable 'i2'.
}
j2
{ Undefined function or variable 'j2'.
}
% abs----to calculate the absolute value of a complex number
who

Your variables are:

a    ans  b  

w=3;
abs(w)

ans =

     3
% abs(real_number)=real_number

% abs(imaginary_number)=real_number
abs(3j)

ans =

     3

abs(3.33j)

ans =

    3.3300

a

a =

   2.0000 + 2.0000i

abs(a)

ans =

    2.8284

%abs(m+nj)=sqrt(power(m,2)+power(n,2))
sqrt(power(2,2)+power(2,2))

ans =

    2.8284

z1=1+2i

z1 =

   1.0000 + 2.0000i

%% or you can multiply by i, like this
z1=1+2*i

z1 =

   1.0000 + 2.0000i

z2=2-3i

z2 =

   2.0000 - 3.0000i

% add and subtract
addition=z1+z2

addition =

   3.0000 - 1.0000i

subtraction=z1-z2

subtraction =

  -1.0000 + 5.0000i

% multiply and divide
multiply=z1*z2

multiply =

   8.0000 + 1.0000i

division=z1/z2

division =

  -0.3077 + 0.5385i

d1=z1\z2

d1 =

  -0.8000 - 1.4000i

z=3+4i

z =

   3.0000 + 4.0000i

real(z)

ans =

     3

imag(z)

ans =

     4

conj(z)

ans =

   3.0000 - 4.0000i

abs(z)

ans =

     5

angle(z)

ans =

    0.9273

diary off
%angle(m+nj)=atan(b/a)
z

z =

   3.0000 + 4.0000i

atan(4/3)==angle(3+4j)

ans =

     1

%Here, 1 means both are equal
%Euler’s famous formula e
%exp(xi)= cos x + i sin x
exp(i*pi/4)

ans =

   0.7071 + 0.7071i

%% Housekeeping Functions
% ceil(x)---the nearest integer to x looking toward +
% close 3--- closes figure window 3
% fix(x)---- the nearest integer to x looking toward zero
% fliplr(A)------ flip a matrix A, left for right
% flipud(A)-----flip a matrix A, up for down
% floor(x)------- the nearest integer to x looking toward -
% length(a)------the number of elements in a vector
% mod(x,y)-----the integer remainder of x/y; see online help if x or y are negative
% rem(x,y)------the integer remainder of x/y; see online help if x or y are negative
% rot90(A)------rotate a matrix A by 90
% round(x)------the nearest integer to x
% sign(x)--------the sign of x and returns 0 if x=0
% size(c)---------the dimensions of a matrix

List of Websites, to get free e-books

www.bookfi.org

www.ebookee.org

www.bookboon.com

www.gutenberg.org


Note: Not all books come with .pdf (portable documentation format) format. Other popular ebook formats are .ePub and .djvu formats, which deserve us to install (free) ePub reader and djvu reader, respectively.

I request the readers to add more such websites, in the comments.

NS 2 - Tutorial for beginners 1

Explanation for a Simple Script

To start we have to set a few variables like simulator object, trace file and object, nam file and object.

set ns [new Simulator]
This would set the simulator with the simulator object which is to be accessed in the script.

set nf [open out.nam w]
$ns namtrace-all $nf
This would set the nam file (network animation file) with the object and connect to ns.
set tr [open out.tr w]
$ns trace-all $tr
This would set the trace file and would connect to the simulator. The trace file is required to analyze the various packets which are send, received type of application used etc.


set n0 [$ns node]
Now the nodes could be set as many as you want, for loop could be used if many nodes are to be made.
$ns duplex-link $n0 $n1 10Mb 10ms DropTail
The connection for the various nodes with each other with the band width and rate.
$ns duplex-link-op $n0 $n1 orient right-up
The nodes could be given with various orientations with this option. right, right-up and right down could be used depending on the node.
For the application like tcp or udp to run, we need to set two agents and the application which should run in between.
When using tcp, we have ftp as the application and tcpsink as the end agent. connection must be made between tcp and tcpsink, same in udp with cbr and null respectively.
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
This would make a tcp agent and connect it with the node.
set ftp [new Application/FTP]
$ftp attach-agent $tcp

Now the ftp is connected with the tcp

set agent [new Agent/TCPSink]
$ns attach-agent $n3 $sink
Now the tcpsink is set to a node where the tcp packets are received.
The tcp and sink (agents) needs to be connected, such that the network flows.
$ns connect $tcp $sink
Similarly, for udp,
set udp [new Agent/UDP]
$ns attach-agent $n2 $udp

set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp

set null [new Agent/Null]
$ns attach-agent $n3 $null

$ns connect $udp $null
We can use the routing protocols in the simulator using rtmodel (to break the link), rtproto (to use the protocol)
$ns rtmodel-at 1.0 down $n1 $n2
$ns rtmodel-at 2.0 up $n1 $n3
For distance vector we could use
$ns rtproto DV
For linkstate we could use
$ns rtproto LS
When all this is done the TCP could be started at some point and could call the finish procedure to end. 
The out.tr file is used to trace the packets. A normal awk command could be used to analyse the packets.
$ns at 0.0 "$ftp start"
$ns at 0.0 "$cbr start"


$ns at 5.0 "finish"
We could also stop the TCP or UDP in between using stop instead of start, hence nam out.nam need to be used if finish is not used.
run is used to run the whole simulation.

$ns run
The file should be saved in .tcl format and should use ns filename.tcl to run
How to install Wine in Ubuntu or Mint Linux?

Q:Why Wine?
A:If you want do run windows platform-based applications (i.e., with extension .exe), then we should install WINE in linux.
A: If the apps which are available over windows platform, are the only requirements making you to compromise with windows, then WINE is the solution. It is a free software under GNU License.

Here is the shortcut for the installation of latest stable version of WINE i.e., WINE 1.6

Step 1: Open the terminal, and type the following commands
Step 2: sudo apt-get update
Step 3: sudo add-apt-repository ppa:ubuntu-wine/ppa
Step 4: sudo apt-get update
Step 5: sudo apt-get install wine16


Note: Please restart the system for effective installation.

AODV simulation for a Sensor network 802.15.4

           The reason to write this topic is many people asked me how to simulate sensor networks.
Obviously, authors of 802.15.4/Zigbee protocol developers on NS2 have given a sample examples. But, these examples do not run correctly, and give some kind of unknown error (at least I don’t know what errors mean).
Therefore, I have decided to test AODV using 802.15.4 MAC/PHY. Thus, if my tests work, I hope you can test your own routing protocols using this source code.

Alright, the TCL file is fairly simple. I briefly explain what means what. We first set simulation environment. We are going to deploy 500 nodes, in 1000×500 sqm area, simulation time is 500 seconds. And we are using 802.15.4 MAC/PHY and interface queue is 100. We also set simulator and files to trace the simulation.
1# Generated by Topology Generator for Network Simulator
2set val(chan)          Channel/WirelessChannel      ;# channel type
3set val(prop)          Propagation/TwoRayGround     ;# radio-propagation model
4set val(netif)         Phy/WirelessPhy/802_15_4     ;# network interface type
5set val(mac)           Mac/802_15_4                 ;# MAC type
6set val(ifq)           Queue/DropTail/PriQueue      ;# interface queue type
7set val(ll)            LL                           ;# link layer type
8set val(ant)           Antenna/OmniAntenna          ;# antenna model
9set val(ifqlen)        100                  ;# max packet in ifq
10set val(nn)            500              ;# number of mobilenodes
11set val(rp)            AODV             ;# protocol tye
12set val(x)             1000             ;# X dimension of topography
13set val(y)             500              ;# Y dimension of topography
14set val(stop)          500              ;# simulation period
15set val(energymodel)   EnergyModel          ;# Energy Model
16set val(initialenergy) 100              ;# value
17 
18set ns              [new Simulator]
19set tracefd         [open trace-aodv-802-15-4.tr w]
20set namtrace        [open nam-aodv-802-15-4.nam w]
21 
22$ns trace-all $tracefd
23$ns namtrace-all-wireless $namtrace $val(x) $val(y)
Let’s set radio transmission range to 40 meters, but this does not mean exactly 40 meters. The code below filters packet with receiving signal strength above “40 meters”.
1set dist(5m7.69113e-06
2set dist(9m2.37381e-06
3set dist(10m) 1.92278e-06
4set dist(11m) 1.58908e-06
5set dist(12m) 1.33527e-06
6set dist(13m) 1.13774e-06
7set dist(14m) 9.81011e-07
8set dist(15m) 8.54570e-07
9set dist(16m) 7.51087e-07
10set dist(20m) 4.80696e-07
11set dist(25m) 3.07645e-07
12set dist(30m) 2.13643e-07
13set dist(35m) 1.56962e-07
14set dist(40m) 1.20174e-07
15Phy/WirelessPhy set CSThresh_ $dist(40m)
16Phy/WirelessPhy set RXThresh_ $dist(40m)
And lets set topography as flat, deploy nodes randomly in an area of 1000 x 500 sqm.
1# set up topography object
2set topo       [new Topography]
3$topo load_flatgrid $val(x) $val(y)
4 
5create-god $val(nn)
6 
7# configure the nodes
8$ns node-config -adhocRouting $val(rp)
9            -llType $val(ll)
10             -macType $val(mac)
11             -ifqType $val(ifq)
12             -ifqLen $val(ifqlen)
13             -antType $val(ant)
14             -propType $val(prop)
15             -phyType $val(netif)
16             -channel [new $val(chan)]
17             -topoInstance $topo
18             -agentTrace ON
19             -routerTrace ON
20             -macTrace  OFF
21             -movementTrace OFF
22             -energyModel $val(energymodel)
23             -initialEnergy $val(initialenergy)
24             -rxPower 35.28e-3
25             -txPower 31.32e-3
26         -idlePower 712e-6
27         -sleepPower 144e-9
28 
29             #-IncomingErrProc MultistateErrorProc
30             #-OutgoingErrProc MultistateErrorProc
31 
32for {set i 0} {$i < $val(nn) } { incr i } {
33        set mnode_($i) [$ns node]
34}
35 
36for {set i 1} {$i < $val(nn) } { incr i } {
37    $mnode_($i) set X_ [ expr {$val(x) * rand()} ]
38    $mnode_($i) set Y_ [ expr {$val(y) * rand()} ]
39    $mnode_($i) set Z_ 0
40}
And we are goig to deploy sink node in the center of area, i.e. at [500, 250].
1# Position of Sink
2$mnode_(0) set X_ [ expr {$val(x)/2} ]
3$mnode_(0) set Y_ [ expr {$val(y)/2} ]
4$mnode_(0) set Z_ 0.0
5$mnode_(0) label "Sink" 

The code below is useful how big the nodes are going to be shown in NAM (network animator), thus it does not have meaning in real simulation.
1for {set i 0} {$i < $val(nn)} { incr i } {
2    $ns initial_node_pos $mnode_($i) 10
3}
Finally, we have deployed nodes, and remained important thing is establish connection. We are going to use UDP protocol with CBR (constant bit rate, interval (interval_) is set to 2 seconds)
1#Setup a UDP connection
2set udp [new Agent/UDP]
3$ns attach-agent $mnode_(10) $udp
4 
5set sink [new Agent/Null]
6$ns attach-agent $mnode_(0) $sink
7 
8$ns connect $udp $sink
9$udp set fid_ 2
10 
11#Setup a CBR over UDP connection
12set cbr [new Application/Traffic/CBR]
13$cbr attach-agent $udp
14$cbr set type_ CBR
15$cbr set packet_size_ 50
16$cbr set rate_ 0.1Mb
17$cbr set interval_ 2
18#$cbr set random_ false
19 
20$ns at 5.0 "$cbr start"
21$ns at [expr $val(stop) - 5] "$cbr stop"
22 
23# Telling nodes when the simulation ends
24for {set i 0} {$i < $val(nn) } { incr i } {
25    $ns at $val(stop) "$mnode_($i) reset;"
26}
27 
28# ending nam and the simulation
29$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
30$ns at $val(stop) "stop"
31$ns at [expr $val(stop) + 0.01] "puts "end simulation"; $ns halt"
32proc stop {} {
33    global ns tracefd namtrace
34    $ns flush-trace
35    close $tracefd
36    close $namtrace
37}
38 
39$ns run
We have finished writing sample AODV TCL script, we can run it
1ns aodv_802_15_4.tcl
Download whole source code here : aodv_802_15_4.tcl . If you find any problem with that, leave comment here. If you want to test your own routing protocol simply change $val(rp) AODV with your own.

NS2: Printing Routing Table in AODV

Actually you can find all this information in trace file which NS2 made, however using following code simplifies getting required informaiton during running time. The code stores

Add following code to aodv.h after void rt_down(aodv_rt_entry *rt);
1void  rt_print(nsaddr_t node_id);
Add following code to aodv.cc after혻void혻 AODV::rt_down(aodv_rt_entry *rt)
1void  AODV::rt_print(nsaddr_t node_id) {
2    FILE * dumpFile;
3    char dumpFileName[50] = "rtable.txt";
4 
5    dumpFile = fopen(dumpFileName, 'a');
6 
7    aodv_rt_entry *rt;
8 
9    fprintf(dumpFile, "=======================================================");
10 
11    for (rt=rtable.head();rt; rt = rt->rt_link.le_next) {
12 
13        fprintf(dumpFile, "NODE: %it %.4lft %it %it %it %it %it %.4lft %d n", node_id, CURRENT_TIME, rt->rt_dst, rt->rt_nexthop, rt->rt_hops, rt->rt_seqno, rt->rt_expire, rt->rt_flags)
14 
15    }
16 
17    fclose(dumpFile);
18}
The function (rt_print) can be used anywhere in AODV. For example, I am using the function, when route request generated혻node receives route reply message (RREP).

1if (ih->daddr() == index) { // If I am the original source
2  // Update the route discovery latency statistics
3  // rp->rp_timestamp is the time of request origination
4 
5    rt_print(index); // print this nodes whole routing table
6 
7    rt->rt_disc_latency[(unsigned char)rt->hist_indx] = (CURRENT_TIME - rp->rp_timestamp)
8                                         / (double) rp->rp_hop_count;
9    // increment indx for next time
10    rt->hist_indx = (rt->hist_indx + 1) % MAX_HISTORY;
11}