Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

Sahil Tyagi

06114802717

Wireless Communication Lab

ETCS 463

Faculty Name: Mr Ashish Sharma Student Name: Sahil Tyagi

Enrolment No: 06114802717

Semester : 7th Sem

Maharaja Agrasen Institute of Technology, PSP Area,

Sector – 22, Rohini, New Delhi – 110086


Sahil Tyagi
06114802717

List of Experiments
1. (a) Write a program in Scilab to calculate the (D) Co-channel cell
distance and Frequency Reuse Ratio(q).
(b) Write a program in Scilab to plot the N (Number of channel) vs q
(Frequency Reuse Ratio).
(c) Write a program in Scilab to calculate the Number of Channels in
Single cell and Total capacity of the System.
(d) Write a program in Scilab to calculate the Signal to Noise Ratio
(SNR).
2. Write a Program in Scilab to calculate maximum traffic intensity and
maximum no. of users accommodated in Erlang B and Erlang C system
for given no of channels.
3. Write a Program in Scilab to calculate Bit Error rate performance of
BPSK modulated signal over only AWGN channel and AWGN and
Rayleigh channel both.
4. Program in Scilab to Generate Walsh Codes and then spread the user
information using it.
5. Program in Scilab to Generate PN Sequence for CDMA System.
6. Write a Program in NS3 to connect WIFI TO BUS (CSMA) Network.
7. Write a Program in NS3 to create WIFI Network in SIMPLE
INFRASTUCTURE MODE (of nodes).
8. Write a Program in NS3 to Create a wireless mobile ad-hoc network with
three nodes Node0, Node1 and Node2.
Sahil Tyagi
06114802717

EXPERIMENT 1(a)
AIM: Write a program in Scilab to calculate the co-channel cell distance (D)
and Frequency Reuse Ratio (q).
Code:
R = input("Enter the radius of the cell ")
// N = number of cells in cluster
N=7
D = R * sqrt(3*N)
disp("The reuse distance = ",D)
q = D/R
disp("The frequency reuse ratio(q=D/R)= ",q)
Sahil Tyagi
06114802717

clc
for i=1:1:2
for j = 1:1:2
N = i^2 + i*j + j^2
disp("I:",i, " J:",j," N:",N)
q = sqrt(3*N)
disp("q: ",q)
end
end
Sahil Tyagi
06114802717

EXPERIMENT 1(b)
Aim: Write a program in Scilab to plot the Number of Channel (N) vs
Frequency Reuse Ratio (q).

CODE:
clc
disp("Sahil Tyagi, 06114802717")
disp("Experiment 2")
function y=freq_ratio(N)
y = sqrt(3*N)
endfunction

for N= 1:1:10
disp("N= ",N,"q= ", sqrt(3*N))
end

n = [1:1:10]
y = [freq_ratio(n)]

xgrid()
plot(n,y)
xlabel("N -->")
ylabel("q -->")
title("N vs q graph ----------- Sahil Tyagi 06114802717")
Sahil Tyagi
06114802717
Sahil Tyagi
06114802717

EXPERIMENT 1(c)
AIM: Write a program in Scilab to calculate the Number of Channels in Single
cell and Total Capacity of the System
CODE:
clc
disp("Sahil Tyagi, 06114802717")
disp("Experiment 3")
K = input("Enter number of cells in cluster: ")
N = input("Enter total number of channels in cluster: ")
J = input("Enter number of clusters in the system: ")
//
cell = N/K
disp("Number of channels in single cell is ", N/K)
disp("Capacity: ", cell*J*K)
Sahil Tyagi
06114802717

EXPERIMENT 1(d)
AIM: Write a program in Scilab to calculate the Signal to Noise Ratio (SNR).
CODE using R and D:
clc
disp("Sahil Tyagi, 06114802717")
disp("Experiment 4")
D = R * sqrt(3*N)
R = input("Enter value of R ")
D = input("Enter value of D ")
a = input("Enter value of attenuation factor (3,4,5) ")
i0=6;
q = D/R
disp("R = ",R)
disp("D = ",D)
disp("a = ",a)
SNR = (q^a) / i0
disp("Signal to Noise Ratio (SNR) using q = ",SNR)
Sahil Tyagi
06114802717

CODE using N:
clc
disp("Sahil Tyagi, 06114802717")
disp("Experiment 4")
N = input("Enter value of N ")
a = input("Enter value of attenuation factor (3,4,5) ")
i0 = 6
disp("N =",N)
SNR2 = ((sqrt(3*N))^a)/i0
disp("Signal to Noise Ratio (SNR) using N= ",SNR2)
Sahil Tyagi
06114802717

TASKS 31 AUG 2020

CODE:
clc
disp("Sahil Tyagi, 06114802717")
disp("Task 1 - 31st August 2020")
totalChannel = 960
cellArea = 6
totalArea = 2000
disp("Total voice channels: ", totalChannel)
disp("Area of cell: ", cellArea)
disp("Area of system: ", totalArea)
N=4
cells = totalArea/cellArea
disp("N = ",N)
disp("Number of cells = total area/area of cell", cells)
disp("System Capacity = ", totalChannel*cells/N)

N=7
disp("N = ",N)
disp("Number of cells = total area/area of cell", cells)
disp("System Capacity = ", totalChannel*cells/N)
Sahil Tyagi
06114802717

Conclusion: By decreasing the value of N, the system capacity increases.


Sahil Tyagi
06114802717

CODE:
disp("Task 2 - 31st August 2020")
SNR = 18
a=4
disp("SNR= ", SNR)
disp("Path loss coeff= ", a)

N = (nthroot(SNR,a))^2/3
disp("Value of N= ",N)
disp("Value of reuse factor= ",1/N)

SNR = 12
disp("SNR= ", SNR)
disp("Path loss coeff= ", a)

N = (nthroot(SNR,a))^2/3
disp("Value of N= ",N)
disp("Value of reuse factor= ",1/N)
Sahil Tyagi
06114802717

EXPERIMENT 2
Aim: Write a Program in Scilab to calculate maximum traffic intensity and
maximum no. of users accommodated in Erlang B and Erlang C system for
given no of channels
Erlang-B

Code:
clc;
disp("Sahil Tyagi 06114802717")

function [Pb]=Erlang_B(A, C)
numerator = (A^C) / factorial(C)
denomiator = 0
for k = 1:1:C
denomiator = denomiator + ((A^k) / factorial(k))
end
Pb = numerator / denomiator
endfunction

disp("--------------- Erlang-B ---------------")


C = input("Enter the total number of Channels: ")
Pb = input("Enter the Blocking Probability: ")
call_Rate = input("Enter the call rate: ")
H = input("Input the avg call holding Time: ")

Au = H * call_Rate
p=0
A=1
while(p<=Pb)
[p] = Erlang_B(A,C)
A=A+1;
end

disp("Traffic Intensity Per User (Au)= ",Au)


disp("Total Traffic Intensity (A) = ",A-1)
Users = (A-1)/Au // number of users
Sahil Tyagi
06114802717

disp("Total number of Users = ",Users)


Sahil Tyagi
06114802717

Erlang-C

CODE:
clc;
disp("Sahil Tyagi 06114802717")
function [Pb]=Erlang_C(A, C)
numerator = (A^C)
denomiator = (A^C)
coeff_value = factorial(C) * (1-A/C)
for k = 1:1:C-1
denomiator = denomiator + coeff_value * (((A^k) / factorial(k)))
end
Pb = numerator / denomiator
endfunction

disp("--------------- Erlang-C ---------------")


C = input("Enter the total number of Channels: ")
Pb = input("Enter the Blocking Probability: ")
call_Rate = input("Enter the call rate: ")
H = input("Input the avg call holding Time: ")

Au = H * call_Rate
p=0
A=1

while(p<=Pb)
[p] = Erlang_C(A,C)
A=A+1;
end

disp("Traffic Intensity Per User (Au)= ",Au)


disp("Total Traffic Intensity (A) = ",A-1)
Users = (A-1)/Au // number of users
disp("Total number of Users = ",Users)
Sahil Tyagi
06114802717
Sahil Tyagi
06114802717

EXPERIMENT-3
AIM:
Write a Program in Scilab to calculate Bit Error rate performance of BPSK
modulated signal over only AWGN channel and AWGN and Rayleigh channel
both.

CODE:
clc;
n = 10000;
data = grand(1,n,"uin",0,1);
bpsk_data = 2*data-1;
snr = 1:20;
list_err_awgn = [];
list_err_rayleigh = [];
for k = 1:1:length(snr)
//rayleigh
H = (1/sqrt(2)) * ( rand(1,length(bpsk_data),'normal') +
%i*(rand(1,length(bpsk_data),'normal')) );

awgn_noise = (1/sqrt(2))*(10^(-(k/20))) * ((rand(1,length(bpsk_data),'normal')) + %i*(


rand(1,length(bpsk_data),'normal') ));

white_noise_signal = bpsk_data + awgn_noise ;


rayleigh_noise_signal = H.*bpsk_data + awgn_noise ;
receiver_signal = conj(H).*rayleigh_noise_signal

received_data_awgn = []
received_data_rayleigh = []

for i=1:1:10000
Sahil Tyagi
06114802717

if real(white_noise_signal(i)) >= 0 then


bit = 1
else
bit = 0
end
received_data_awgn(i) = bit
end

for i=1:1:10000
if real(receiver_signal(i)) >= 0 then
bit = 1
else
bit = 0

end
received_data_rayleigh(i) = bit
end

err_awgn = 0;
err_rayleigh = 0;

for i = 1:1:length(data)
if received_data_awgn(i) ~= data(i) then
err_awgn = err_awgn + 1
end

if received_data_rayleigh(i) ~= data(i) then


err_rayleigh = err_rayleigh + 1
end
end
Sahil Tyagi
06114802717

list_error_awgn(k) = err_awgn/10000
list_error_rayleigh(k) = err_rayleigh/10000
end
snr = 1:1:20
snr=1:1:20
subplot(2,1,1)
plot(snr,list_error_awgn)
xgrid()
xtitle("Sahil Tyagi 06114802717")
subplot(2,1,2)
plot(snr,list_error_rayleigh)
xgrid()

OUTPUT:
Sahil Tyagi
06114802717
Sahil Tyagi
06114802717

EXPERIMENT 4
Aim: Program in Scilab to Generate Walsh Codes and then spread the user
information using it.

CODE:
clc;
// 0 -- -1
// 1 -- +1
disp("Sahil Tyagi; 06114802717")
function y=calu_spread_signal(s, user, n)
disp("User No : ",n);
disp("Infomation : ", user)
ans = [];
for i=1:length(user)
temp = user(i)*z(1,:);
ans=cat(1,ans,temp)
end
y = ans(:)
endfunction

s = input("Enter the number order for 2 : ");

if(s==1)
z=[-1];
elseif(s==2)
z=[-1 -1;-1 1];
else
x=[-1 -1;-1 1];
z=[];
new_s=log(s)/log(2);
for i=1:new_s-1
z=[x x;x -x];
x=z;
Sahil Tyagi
06114802717

end
end

user = [1 -1 -1;-1 1 -1;1 -1 1];

disp("Walsh Code Table : ",z)


for j=1:length(user(:,1))
disp("Spread Signal : ",calu_spread_signal(s,user(j,:),j))
end

OUTPUT:
Sahil Tyagi
06114802717
Sahil Tyagi
06114802717

EXPERIMENT 5
Aim: Program in Scilab to Generate PN Sequence for CDMA Systems.

CODE:
clc;
disp("Sahil Tyagi 06114802717")
function cal_receiving_signal(PN, c1)
spreaded_sig=[c1(1).*PN c1(2).*PN c1(3).*PN]
disp("Spreaded Signal : ")
disp(spreaded_sig)
detect_code=[spreaded_sig(1:7).*PN spreaded_sig(8:14).*PN spreaded_sig(15:21).*PN];
disp("Detect Code : ")
disp(detect_code)
corr_code=[sum(detect_code(1:7)) sum(detect_code(8:14)) sum(detect_code(15:21))];
disp("Correlation code : ")
disp(corr_code)
rec_sig=(1/7).*corr_code;
disp("received signal with correct PN sequence is");
disp(rec_sig);
endfunction

R(1)=1;
R(2)=0;
R(3)=0;
m=3;
disp('output after every clock pulse');
disp('r1 r2 r3');
for i=1:((2^m)-1)
r1=R(1);
r2=R(2);
r3=R(3);
PN(i)=R(3);
R1=bitxor(r2,r3);
R(3)=R(2);
Sahil Tyagi
06114802717

R(2)=R(1);
R(1)=R1;
disp([R(1) R(2) R(3)]);
end
disp('PN sequence is');
disp(PN);
c1=[1 -1 -1];//information of user 1
// 0 --> -1
// 1 --> +1
for j=1:1:length(PN)
if PN(j)==0 then
PN(j)=PN(j)-1;
else PN(j)=PN(j);
end
end
disp("Mapping 0 --> -1 and 1 --> +1")
disp(PN);
cal_receiving_signal(PN,c1);

OUTPUT:
Sahil Tyagi
06114802717
Sahil Tyagi
06114802717

EXPERIMENT 6

Aim: Write a Program in NS3 to connect WIFI TO BUS (CSMA) Network.


Code:
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("SecondScriptExample");

int
main (int argc, char *argv[])
{
bool verbose = true;
uint32_t nCsma = 3;
CommandLine cmd (__FILE__);
cmd.AddValue ("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);

cmd.Parse (argc,argv);

if (verbose)
{
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
Sahil Tyagi
06114802717

nCsma = nCsma == 0 ? 1 : nCsma;

NodeContainer p2pNodes;
p2pNodes.Create (2);

NodeContainer csmaNodes;
csmaNodes.Add (p2pNodes.Get (1));
csmaNodes.Create (nCsma);

PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

NetDeviceContainer p2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);

CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));

NetDeviceContainer csmaDevices;
csmaDevices = csma.Install (csmaNodes);

InternetStackHelper stack;
stack.Install (p2pNodes.Get (0));
stack.Install (csmaNodes);

Ipv4AddressHelper address;
Sahil Tyagi
06114802717

address.SetBase ("10.1.1.0", "255.255.255.0");


Ipv4InterfaceContainer p2pInterfaces;
p2pInterfaces = address.Assign (p2pDevices);

address.SetBase ("10.1.2.0", "255.255.255.0");


Ipv4InterfaceContainer csmaInterfaces;
csmaInterfaces = address.Assign (csmaDevices);

UdpEchoServerHelper echoServer (9);

ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (nCsma));


serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));

UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma), 9);


echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));

ApplicationContainer clientApps = echoClient.Install (p2pNodes.Get (0));


clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));

Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
pointToPoint.EnablePcapAll ("second");
csma.EnablePcap ("second", csmaDevices.Get (1), true);
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
Sahil Tyagi
06114802717

OUTPUT:

VIVA QESTIONS:
Q.1 What is an Access Point in WIFI Networks?
A wireless access point (WAP) is a networking device that allows wireless-
capable devices to connect to a wired network.
Q.2 What are the role of UDP Server?
UDP (User Datagram Protocol) is a communications protocol that is primarily
used for establishing low-latency and loss-tolerating connections between
applications on the internet. It speeds up transmissions by enabling the transfer
of data before an agreement is provided by the receiving party.
Q.3 What are Port Numbers?
In computer networking, a port is a communication endpoint. At the software
level, within an operating system, a port is a logical construct that identifies a
specific process or a type of network service.
Q.4 What is the role of Net Device Container in NS3?
 Typically ns-3 NetDevices are installed on nodes using a net device
helper. The helper Install method takes a NodeContainer which holds
some number of Ptr<Node>.
 For each of the Nodes in the NodeContainer the helper will instantiate a
net device, add a MAC address and a queue to the device and install it to
the node.
 For each of the devices, the helper also adds the device into a Container
for later use by the caller. This is that container used to hold the
Ptr<NetDevice> which are instantiated by the device helper.
Sahil Tyagi
06114802717

EXPERIMENT 7

Aim: Write a Program in NS3 to create WIFI Network in SIMPLE


INFRASTUCTURE MODE (of nodes).
Code:
#include "ns3/command-line.h"
#include "ns3/config.h"
#include "ns3/double.h"
#include "ns3/string.h"
#include "ns3/log.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/ssid.h"
#include "ns3/mobility-helper.h"
#include "ns3/ipv4-address-helper.h"
#include "ns3/yans-wifi-channel.h"
#include "ns3/mobility-model.h"
#include "ns3/internet-stack-helper.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("WifiSimpleInfra");

void ReceivePacket (Ptr<Socket> socket)


{
while (socket->Recv ())
{
NS_LOG_UNCOND ("Received one packet!");
}
}
Sahil Tyagi
06114802717

static void GenerateTraffic (Ptr<Socket> socket, uint32_t pktSize,


uint32_t pktCount, Time pktInterval )
{
if (pktCount > 0)
{
socket->Send (Create<Packet> (pktSize));
Simulator::Schedule (pktInterval, &GenerateTraffic,
socket, pktSize,pktCount - 1, pktInterval);
}
else { socket->Close () }
int main (int argc, char *argv[])
{
std::string phyMode ("DsssRate1Mbps");
double rss = -80; // -dBm
uint32_t packetSize = 1000; // bytes
uint32_t numPackets = 1;
double interval = 1.0; // seconds
bool verbose = false;

CommandLine cmd (__FILE__);


cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
cmd.AddValue ("rss", "received signal strength", rss);
cmd.AddValue ("packetSize", "size of application packet sent", packetSize);
cmd.AddValue ("numPackets", "number of packets generated", numPackets);
cmd.AddValue ("interval", "interval (seconds) between packets", interval);
cmd.AddValue ("verbose", "turn on all WifiNetDevice log components", verbose);
cmd.Parse (argc, argv);
// Convert to time object
Time interPacketInterval = Seconds (interval);
Sahil Tyagi
06114802717

// Fix non-unicast data rate to be the same as that of unicast


Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",
StringValue (phyMode));

NodeContainer c;
c.Create (2);

// The below set of helpers will help us to put together the wifi NICs we want
WifiHelper wifi;
if (verbose)
{
wifi.EnableLogComponents (); // Turn on all Wifi logging
}
wifi.SetStandard (WIFI_STANDARD_80211b);

YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();


// This is one parameter that matters when using FixedRssLossModel
// set it to zero; otherwise, gain will be added
wifiPhy.Set ("RxGain", DoubleValue (0) );
// ns-3 supports RadioTap and Prism tracing extensions for 802.11b
wifiPhy.SetPcapDataLinkType (WifiPhyHelper::DLT_IEEE802_11_RADIO);

YansWifiChannelHelper wifiChannel;
wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
// The below FixedRssLossModel will cause the rss to be fixed regardless
// of the distance between the two stations, and the transmit power
wifiChannel.AddPropagationLoss ("ns3::FixedRssLossModel","Rss",DoubleValue (rss));
wifiPhy.SetChannel (wifiChannel.Create ());

// Add a mac and disable rate control


Sahil Tyagi
06114802717

WifiMacHelper wifiMac;
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
"DataMode",StringValue (phyMode),
"ControlMode",StringValue (phyMode));

// Setup the rest of the mac


Ssid ssid = Ssid ("wifi-default");
// setup sta.
wifiMac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid));
NetDeviceContainer staDevice = wifi.Install (wifiPhy, wifiMac, c.Get (0));
NetDeviceContainer devices = staDevice;
// setup ap.
wifiMac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
NetDeviceContainer apDevice = wifi.Install (wifiPhy, wifiMac, c.Get (1));
devices.Add (apDevice);

// Note that with FixedRssLossModel, the positions below are not


// used for received signal strength.
MobilityHelper mobility;
Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
positionAlloc->Add (Vector (0.0, 0.0, 0.0));
positionAlloc->Add (Vector (5.0, 0.0, 0.0));
mobility.SetPositionAllocator (positionAlloc);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (c);

InternetStackHelper internet;
internet.Install (c);
Sahil Tyagi
06114802717

Ipv4AddressHelper ipv4;
NS_LOG_INFO ("Assign IP Addresses.");
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer i = ipv4.Assign (devices);

TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");


Ptr<Socket> recvSink = Socket::CreateSocket (c.Get (0), tid);
InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
recvSink->Bind (local);
recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));
Ptr<Socket> source = Socket::CreateSocket (c.Get (1), tid);
InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
source->SetAllowBroadcast (true);
source->Connect (remote);
// Tracing
wifiPhy.EnablePcap ("wifi-simple-infra", devices);
// Output what we are doing
NS_LOG_UNCOND ("Testing " << numPackets << " packets sent with receiver rss " <<
rss );
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),
Seconds (1.0), &GenerateTraffic,
source, packetSize, numPackets, interPacketInterval);
Simulator::Stop (Seconds (30.0));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}

OUTPUT:
Sahil Tyagi
06114802717

VIVA QESTIONS:
Q1. What are the advantages of using Infrastructure type WiFi Networks?
 Convenience
 Mobility
 Productivity
 Deployment
 Expandability
 Cost
Q2 What is DSSS and FHSS?
DSSS is type spread spectrum the most widely known and most widely used.
Meanwhile, in FHSS the data is modulated directly onto a single carrier
frequency, but that carrier frequency hops across a number of channels.
Q3 Which method is used to detect errors in WiFi Networks?
Single Parity Check [Single Parity checking].
Sahil Tyagi
06114802717

EXPERIMENT 8

Aim: Write a Program in NS3 to Create a wireless mobile ad-hoc network


with three nodes Node0, Node1 and Node2.
Code:
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/wifi-module.h"
#include "ns3/olsr-module.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/mobility-module.h"
#include "myapp.h"

NS_LOG_COMPONENT_DEFINE ("Lab4")
using namespace ns3;
static void SetPosition (Ptr<Node> node, double x)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
Vector pos = mobility->GetPosition();
pos.x = x;
mobility->SetPosition(pos);
}

Void ReceivePacket(Ptr<const Packet> p, const Address & addr)


{
std::cout << Simulator::Now ().GetSeconds () << "\t" << p->GetSize() <<"\n";
}
Sahil Tyagi
06114802717

int main (int argc, char *argv[])


{
bool enableFlowMonitor = false;
std::string phyMode ("DsssRate1Mbps");

CommandLine cmd;
cmd.AddValue ("EnableMonitor", "Enable Flow Monitor", enableFlowMonitor);
cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
cmd.Parse (argc, argv);
NS_LOG_INFO ("Create nodes.");
NodeContainer c; // ALL Nodes
c.Create(3);

// Set up WiFi
WifiHelper wifi;

YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();


wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11);

YansWifiChannelHelper wifiChannel ;
wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
wifiChannel.AddPropagationLoss ("ns3::TwoRayGroundPropagationLossModel",
"SystemLoss",
DoubleValue(1),
"HeightAboveZ",
DoubleValue(1.5));

// For range near 250m


wifiPhy.Set ("TxPowerStart", DoubleValue(33));
wifiPhy.Set ("TxPowerEnd", DoubleValue(33));
wifiPhy.Set ("TxPowerLevels", UintegerValue(1));
Sahil Tyagi
06114802717

wifiPhy.Set ("TxGain", DoubleValue(0));


wifiPhy.Set ("RxGain", DoubleValue(0));
wifiPhy.Set ("EnergyDetectionThreshold", DoubleValue(-61.8));
wifiPhy.Set ("CcaMode1Threshold", DoubleValue(-64.8));

wifiPhy.SetChannel (wifiChannel.Create ());

// Add a non-QoS upper mac


NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifiMac.SetType ("ns3::AdhocWifiMac");

// Set 802.11b standard


wifi.SetStandard (WIFI_PHY_STANDARD_80211b);

wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
"DataMode",StringValue(phyMode),
"ControlMode",StringValue(phyMode));
NetDeviceContainer devices;
devices = wifi.Install (wifiPhy, wifiMac, c)

// Enable OLSR
OlsrHelper olsr;

// Install the routing protocol


Ipv4ListRoutingHelper list;
list.Add (olsr, 10);

// Set up internet stack


InternetStackHelper internet;
internet.SetRoutingHelper (list);
internet.Install (c);
Sahil Tyagi
06114802717

// Set up Addresses
Ipv4AddressHelper ipv4;
NS_LOG_INFO ("Assign IP Addresses.");
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer ifcont = ipv4.Assign (devices);

NS_LOG_INFO ("Create Applications.");

// UDP connfection from N0 to N2

uint16_t sinkPort = 6;
Address sinkAddress (InetSocketAddress (ifcont.GetAddress (2), sinkPort)); // interface of
n2
PacketSinkHelper packetSinkHelper ("ns3::UdpSocketFactory", InetSocketAddress
(Ipv4Address::GetAny (), sinkPort));
ApplicationContainer sinkApps = packetSinkHelper.Install (c.Get (2)); //n2 as sink
sinkApps.Start (Seconds (0.));
sinkApps.Stop (Seconds (100.));

Ptr<Socket> ns3UdpSocket = Socket::CreateSocket (c.Get (0),


UdpSocketFactory::GetTypeId ()); //source at n0

// Create UDP application at n0


Ptr<MyApp> app = CreateObject<MyApp> ();
app->Setup (ns3UdpSocket, sinkAddress, 1040, 100000, DataRate ("250Kbps"));
c.Get (0)->AddApplication (app);
app->SetStartTime (Seconds (1.));
app->SetStopTime (Seconds (100.));

// Set Mobility for all nodes


MobilityHelper mobility;
Ptr<ListPositionAllocator> positionAlloc = CreateObject <ListPositionAllocator>();
Sahil Tyagi
06114802717

positionAlloc ->Add(Vector(0, 0, 0)); // node0


positionAlloc ->Add(Vector(1000, 0, 0)); // node1 -- starting very far away
positionAlloc ->Add(Vector(450, 0, 0)); // node2
mobility.SetPositionAllocator(positionAlloc);
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
mobility.Install(c);

// node 1 comes in the communication range of both


Simulator::Schedule (Seconds (20.0), &SetPosition, c.Get (1), 200.0);

// node 1 goes out of the communication range of both


Simulator::Schedule (Seconds (35.0), &SetPosition, c.Get (1), 1000.0);

// Trace Received Packets


Config::ConnectWithoutContext("/NodeList/*/ApplicationList/*/$ns3::PacketSink/Rx",
MakeCallback (&ReceivePacket));

// Trace devices (pcap)


wifiPhy.EnablePcap ("lab-4-dev", devices);

// Flow Monitor
Ptr<FlowMonitor> flowmon;
if (enableFlowMonitor)
{
FlowMonitorHelper flowmonHelper;
flowmon = flowmonHelper.InstallAll ();
}

//
// Now, do the actual simulation.
//
Sahil Tyagi
06114802717

NS_LOG_INFO ("Run Simulation.");


Simulator::Stop (Seconds(100.0));
Simulator::Run ();
if (enableFlowMonitor)
{
flowmon->CheckForLostPackets ();
flowmon->SerializeToXmlFile("lab-4.flowmon", true, true);
}
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
Output:

VIVA QESTIONS:
Q.1 What are the advantages of using Adhoc type Wifi Networks?
 Router Free
 Mobility: Ad hoc networks can be created on the fly in nearly any
situation where there are multiple wireless devices.
 Speed
Q.2 How Power management is done in Adhoc Networks?
Sahil Tyagi
06114802717

The nodes in an ad hoc wireless network are constrained by limited battery


power for their operation. Hence, energy management is an important issue in
such networks. The use of multi-hop radio relaying requires a sufficient number
of relaying nodes to maintain the network connectivity.
Q.3 Which method is used to detect errors in Wifi Networks?
Single Parity Check Single Parity checking.

You might also like