summaryrefslogtreecommitdiff
path: root/ns-3_wifi_tests/wifi-nodes-energy-consumption2.cc
blob: e778e112a7672f1c295733e9064633c241504a0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <fstream>
#include <iostream>
#include <string>
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/config-store-module.h"
#include "ns3/energy-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/flow-monitor-module.h"

// Default Network Topology
//
// Number of wifi Sta or Edge nodes can be increased up to 250
//                          |
//                 Rank 0   |   Rank 1
// -------------------------|----------------------------
// Wifi Sta 10.1.3.0
//                 AP
//  *    *    *    *                
//  |    |    |    |    10.1.1.0
// n3   n4   n5   n0 -------------- n1   n2   
//                   point-to-point  |    |     
//                                   *    *
//                                   Ap
//                                       WiFi Edge 10.1.2.0

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("WifiEnergyExample");

uint32_t PhyTxDropCount =0;
uint32_t PhyRxDropCount =0;
double offeredLoad = 0.0;
double throughput = 0.0;
double lastPacketTime = 0.0;

//FlowMonitorHelper flowmon;

/// Trace function for remaining energy at node.
void
RemainingEnergy (double oldValue, double remainingEnergy)
{
  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
                 << "s Current remaining energy = " << remainingEnergy << "J");
}

/// Trace function for total energy consumption at node.
void
TotalEnergy (double oldValue, double newValue)
{
    NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
                 << "\t"<< newValue-oldValue<<"\t"<<newValue);
}

void
PhyTxDrop(Ptr<const Packet> p)
{
  NS_LOG_UNCOND(Simulator::Now ().GetSeconds ()<<" Tx Packet Drop "<<++PhyTxDropCount);
}

void
PhyRxDrop(Ptr<const Packet> p)
{
  NS_LOG_UNCOND(Simulator::Now ().GetSeconds ()<<" Rx Packet Drop "<<++PhyRxDropCount);
}
int 
main (int argc, char *argv[])
{
  bool verbose = false;
  uint32_t nWifiSta = 1;
  uint32_t nWifiEdge = 1;
  bool tracing = false;
  double interval = 1.0;
  uint32_t maxPackets = 10;
  double simulationTime = 20.0;

  CommandLine cmd;
  cmd.AddValue ("nWifiEdge", "Number of wifi edge nodes/devices", nWifiEdge);
  cmd.AddValue ("nWifiSta", "Number of wifi STA devices", nWifiSta);
  cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);
  cmd.AddValue ("tracing", "Enable pcap tracing", tracing);
  cmd.AddValue ("interval", "Interval between packets", interval);
  cmd.AddValue ("maxPackets", "Maximum number of packets", maxPackets);


  cmd.Parse (argc,argv);

  // Check for valid number of csma or wifi nodes
  // 250 should be enough, otherwise IP addresses 
  // soon become an issue
  if (nWifiEdge > 250 || nWifiSta > 250)
    {
      std::cout << "Too many wifi station/edge nodes, no more than 250 each." << std::endl;
      return 1;
    }

  if (verbose)
    {
      LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
      LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
      //LogComponentEnable("YansWifiPhy",LOG_LEVEL_INFO);
    }

  NodeContainer p2pNodes;
  p2pNodes.Create (2);

  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("250Mbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("1ns"));

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

  NodeContainer wifiStaNodes;
  wifiStaNodes.Create (nWifiSta);
  NodeContainer staApNode = p2pNodes.Get (0);

  NodeContainer wifiEdgeNodes;
  wifiEdgeNodes.Create (nWifiEdge);
  NodeContainer edgeApNode = p2pNodes.Get (1);

  YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
  YansWifiPhyHelper phySta = YansWifiPhyHelper::Default ();
  phySta.SetChannel (channel.Create ());
  phySta.Set ("TxAntennas", UintegerValue (4));
  phySta.Set ("RxAntennas", UintegerValue (4)); 

  YansWifiPhyHelper phyEdge = YansWifiPhyHelper::Default ();
  phyEdge.SetChannel (channel.Create ());
  phyEdge.Set ("TxAntennas", UintegerValue (4));
  phyEdge.Set ("RxAntennas", UintegerValue (4)); 


  WifiHelper wifi;
  wifi.SetStandard (WIFI_PHY_STANDARD_80211n_5GHZ);
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager","DataMode", StringValue("HtMcs31"),"ControlMode",StringValue("HtMcs31"));

  WifiMacHelper macSta;
  Ssid ssid = Ssid ("ns-3-ssid-sta");
  macSta.SetType ("ns3::StaWifiMac",
               "Ssid", SsidValue (ssid),
               "ActiveProbing", BooleanValue (false));

  NetDeviceContainer staDevices;
  staDevices = wifi.Install (phySta, macSta, wifiStaNodes);
  
  macSta.SetType ("ns3::ApWifiMac",
               "Ssid", SsidValue (ssid));

  NetDeviceContainer staApDevices;
  staApDevices = wifi.Install (phySta, macSta, staApNode);

  WifiMacHelper macEdge;
  ssid = Ssid ("ns-3-ssid-edge");
  macEdge.SetType ("ns3::StaWifiMac",
               "Ssid", SsidValue (ssid),
               "ActiveProbing", BooleanValue (false));

  NetDeviceContainer edgeDevices;
  edgeDevices = wifi.Install (phyEdge, macEdge, wifiEdgeNodes);
  
  macEdge.SetType ("ns3::ApWifiMac",
               "Ssid", SsidValue (ssid));

  NetDeviceContainer edgeApDevices;
  edgeApDevices = wifi.Install (phyEdge, macEdge, edgeApNode);

  MobilityHelper mobility;

  mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                 "MinX", DoubleValue (0.0),
                                 "MinY", DoubleValue (0.0),
                                 "DeltaX", DoubleValue (0.5),
                                 "DeltaY", DoubleValue (0.5),
                                 "GridWidth", UintegerValue (3),
                                 "LayoutType", StringValue ("RowFirst"));

  mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
                             "Bounds", RectangleValue (Rectangle (-50, 50, -50, 50)));
  mobility.Install (wifiStaNodes);

  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (staApNode);
  mobility.Install (edgeApNode);
  mobility.Install (wifiEdgeNodes);

  InternetStackHelper stack;
  stack.Install (staApNode);
  stack.Install (edgeApNode);
  stack.Install (wifiStaNodes);
  stack.Install (wifiEdgeNodes);

  Ipv4AddressHelper address;

  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 edgeInterfaces;
  edgeInterfaces = address.Assign (edgeDevices);
  address.Assign(edgeApDevices);

  address.SetBase ("10.1.3.0", "255.255.255.0");
  address.Assign (staDevices);
  address.Assign (staApDevices);

  /** Energy Model **/
  /***************************************************************************/
  /* energy source */
  BasicEnergySourceHelper staBasicSourceHelper;
  BasicEnergySourceHelper edgeBasicSourceHelper;
  // configure energy source

  staBasicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (100));
  edgeBasicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (100));
//  edgeBasicSourceHelper.Set ("BasicEnergySupplyVoltageV", DoubleValue (220));
  // install source
  EnergySourceContainer wifiStaNodesSources = staBasicSourceHelper.Install (wifiStaNodes);
  EnergySourceContainer wifiEdgeNodesSources = edgeBasicSourceHelper.Install (wifiEdgeNodes);

  /* device energy model */
  WifiRadioEnergyModelHelper radioEnergyHelper;
  // configure radio energy model
/*
  radioEnergyHelper.Set ("TxCurrentA", DoubleValue (0.0857));
  radioEnergyHelper.Set ("RxCurrentA", DoubleValue (0.0528));
  radioEnergyHelper.Set ("IdleCurrentA", DoubleValue (0.0188));
*/
  // install device model
  DeviceEnergyModelContainer staDeviceModels = radioEnergyHelper.Install (staDevices, wifiStaNodesSources);
  DeviceEnergyModelContainer edgeDeviceModels = radioEnergyHelper.Install (edgeDevices, wifiEdgeNodesSources);

  /***************************************************************************/
  UdpEchoServerHelper echoServer (9);

  ApplicationContainer serverApps = echoServer.Install (wifiEdgeNodes.Get (0));
  serverApps.Start (Seconds (0));
  serverApps.Stop (Seconds (simulationTime));

  UdpEchoClientHelper echoClient (edgeInterfaces.GetAddress (0), 9);
  echoClient.SetAttribute ("MaxPackets", UintegerValue (maxPackets));
  echoClient.SetAttribute ("Interval", TimeValue (Seconds ((interval/1000.0))));
  echoClient.SetAttribute ("PacketSize", UintegerValue (1472));

  ApplicationContainer clientApps = 
  echoClient.Install (wifiStaNodes);
  clientApps.Start (Seconds (0.5));
  clientApps.Stop (Seconds (simulationTime));

  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

  /** connect trace sources **/
  /***************************************************************************/
  // all sources are connected to node 1
  // energy source

  Ptr<BasicEnergySource> basicSourcePtr0 = DynamicCast<BasicEnergySource> (wifiEdgeNodesSources.Get (0));

  //basicSourcePtr0->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback (&RemainingEnergy));
  //device energy model

  Ptr<DeviceEnergyModel> basicRadioModelPtr0 =
  basicSourcePtr0->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel").Get (0);

  NS_ASSERT (basicRadioModelPtr0 != NULL);
  basicRadioModelPtr0->TraceConnectWithoutContext ("TotalEnergyConsumption", MakeCallback (&TotalEnergy));

/*

  Ptr<BasicEnergySource> basicSourcePtr1 = DynamicCast<BasicEnergySource> (wifiStaNodesSources.Get (0));

  Ptr<DeviceEnergyModel> basicRadioModelPtr1 =
  basicSourcePtr1->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel").Get (0);

  NS_ASSERT (basicRadioModelPtr1 != NULL);
  basicRadioModelPtr1->TraceConnectWithoutContext ("TotalEnergyConsumption", MakeCallback (&TotalEnergy));
*/



  if (tracing == true)
    {
      //AsciiTraceHelper ascii;
      //pointToPoint.EnableAsciiAll(ascii.CreateFileStream ("energy-wifi.tr"));
      pointToPoint.EnablePcapAll ("wifiEnergy");
    //  phySta.EnablePcapAll ("wifiEnergy");
     // phyEdge.EnablePcapAll ("wifiEnergy");

    }

 //Set simulation time and launch simulation
  Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/PhyRxDrop", MakeCallback(&PhyRxDrop));
  Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/PhyTxDrop", MakeCallback(&PhyTxDrop));

 
//  edgeDevices.Get(0)->TraceConnectWithoutContext("PhyTxDrop",MakeCallback(&PhyTxDrop));



  FlowMonitorHelper flowmon;
  Ptr<FlowMonitor> monitor = flowmon.InstallAll();
  Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ());

  Simulator::Stop (Seconds (simulationTime));
  Simulator::Run ();

  std::map<FlowId, FlowMonitor::FlowStats> stats = monitor->GetFlowStats ();

  double totalThroughput = 0.0;
  double totalLostPackets = 0.0;
 for (std::map< FlowId, FlowMonitor::FlowStats>::iterator flow=stats.begin(); flow!=stats.end(); flow++)
 {
  Ipv4FlowClassifier::FiveTuple  t = classifier->FindFlow(flow->first);
  NS_LOG_UNCOND( "\nFlowID: " << flow->first << " (" 
             << t.sourceAddress << " / " << t.sourcePort << " --> "
             << t.destinationAddress << " / " << t.destinationPort << ")" ); 
  NS_LOG_UNCOND( "  Tx Packets:   " << flow->second.txPackets );
  NS_LOG_UNCOND( "  Tx Bytes:   " << flow->second.txBytes );

  offeredLoad = flow->second.txBytes * 8.0 / (flow->second.timeLastTxPacket.GetSeconds () - flow->second.timeFirstTxPacket.GetSeconds ()) / 1000000 ; 
  NS_LOG_UNCOND( "  Offered Load: " << offeredLoad << " Mbps");

  NS_LOG_UNCOND( "  Rx Packets:   " << flow->second.rxPackets );
  NS_LOG_UNCOND( "  Rx Bytes:   " << flow->second.rxBytes );

  throughput = flow->second.rxBytes * 8.0 / (flow->second.timeLastRxPacket.GetSeconds () - flow->second.timeFirstRxPacket.GetSeconds ()) / 1000000; 
  NS_LOG_UNCOND( "  Throughput: " << throughput  << " Mbps");

  NS_LOG_UNCOND( "  Lost Packets: " << flow->second.lostPackets );
  NS_LOG_UNCOND( "  Time last packet Transmited: " << flow->second.timeLastTxPacket.GetSeconds() );
  NS_LOG_UNCOND( "  Time last packet Received: " << flow->second.timeLastRxPacket.GetSeconds() );

  if(t.destinationPort == 9){ 

    totalThroughput = totalThroughput + throughput;
    totalLostPackets = totalLostPackets + flow->second.lostPackets;   
  
  }
  if(t.destinationPort == 9 && (lastPacketTime < flow->second.timeLastRxPacket.GetSeconds ())){

     lastPacketTime = flow->second.timeLastRxPacket.GetSeconds ();
  }
   
}
  double averageThroughput = totalThroughput/nWifiSta; 
  double averageLostPackets = totalLostPackets/nWifiSta;

  NS_LOG_UNCOND( "\nLast Packet Time: " << lastPacketTime);
  NS_LOG_UNCOND( "Average Throughput: " << averageThroughput  << " Mbps");
  NS_LOG_UNCOND( "Average Lost Packet : " << averageLostPackets);

  Simulator::Destroy ();

   return 0;
}