#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/csma-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"
#include "ns3/basic-energy-source.h"
#include "ns3/simple-device-energy-model.h"
#include "ns3/config-store-module.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
#include "ns3/rtt-estimator.h"
#include "ns3/aodv-module.h"
#include <ns3/wsn-module.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("Broadcast_TWT_Agreement");
double simTime = 50;
AnimationInterface *anim;
double pk=0;
int TotalStations = 50;
int NoofAP=1;
uint32_t packetSize = 1024; 
uint32_t numPackets = 200;
double interval = 0.1; 
double TotalTime = 10.0;
double twtlist[100];
double Overheadvalue;
double distance1;
std::string rate="10Mbps";
std::string rate1="20Mbps";
int nodeSpeed = 1;
int rttval;
double kbs=0;
int rnd=0;
int rnd1=0;
double Trange=400;
double SNR=20;
double trans_recv=50; 
Time interPacketInterval = Seconds (interval);
NodeContainer StationNodes;
NodeContainer APNode;
int bytesTotal;
double ds=100000.0;
double energy=100.0;
int cHead;
double Initialtime=0;
double PICO=0.000001;
double NANO =0.001;
int dis=10;
int status=1;
int pz=50;
int nbees=5;
double q=5;
double ro=2;
double taumax=2;
int initCity=5;
uint32_t packetsReceived;
void GetDistance_From (NodeContainer node1, NodeContainer node2){
Ptr<MobilityModel> model1 = node1.Get(0)->GetObject<MobilityModel>();
Ptr<MobilityModel> model2 = node2.Get(10)->GetObject<MobilityModel>();
distance1 = model1->GetDistanceFrom (model2);}
void ReceivePacket (Ptr<Socket> socket){
Ptr<Packet> pckt;
while (pckt = socket->Recv ()){
rate="512Mbps";
Ptr<MobilityModel> model1 = APNode.Get(0)->GetObject<MobilityModel>();
Ptr<MobilityModel> model2 = StationNodes.Get(10)->GetObject<MobilityModel>();
distance1 = model1->GetDistanceFrom (model2);
bytesTotal = pckt->GetSize();
pk=pk+1;}}
void compare_Minimum(double dis){
if(ds>dis){
ds=dis;}}
void getNearbynode(NodeContainer nod,double x1,double y1){
int nn;
for(uint32_t i=0;i<nod.GetN ();i++){
Ptr<ConstantPositionMobilityModel> FCMob = nod.Get(i)->GetObject<ConstantPositionMobilityModel>();
Vector m_position = FCMob->GetPosition();
double x=m_position.x;
double y=m_position.y;
double xx=x1-x;
double yy=y1-y;
double x2=(xx*xx);
double y2=(yy*yy);
double sx=sqrt(x2);
double sy=sqrt(y2);
double dis=(sx+sy);
compare_Minimum(dis);
if(ds==dis){
nn=i;}}
std::cout<<"minimum Distance:" <<nn<<std::endl;}
void energyReceive(int bits,int mystatus){
double en;
if(mystatus==status){
en=(double)bits*50.0*NANO;
energy=energy-en;}}
void energyTransmit(int bits,double dist,int mystatus){
double en;
if(mystatus==status){
en=bits*10*PICO*dist+(double)bits*50.0*NANO;
energy=energy-en;}}
void energyDataAggr(int signals,int mystatus){
double en;
if(mystatus==status){
en=5*NANO*signals;
energy=energy-en;}}
void finish(){
std::cout<<"energy: "<<energy<<"\n";}
static void GenerateTraffic (Ptr<Socket> socket, uint32_t pktSize,uint32_t pktCount, Time pktInterval ){
if (pktCount > 0){
socket->Send (Create<Packet> (pktSize));
int b=pktCount*512;
energy=(double)trans_recv;
energyReceive(b,1);
energyTransmit( b,ds,1);
energyDataAggr(1*pktCount ,1);
Simulator::Schedule (pktInterval, &GenerateTraffic,socket, pktSize,pktCount-1, pktInterval);
}else{
socket->Close ();}}
void PKTtrans(NodeContainer c , NodeContainer d){
std::cout<<"\n During the network construction set the parameter values for like, Target Wake Time (TWT),TWT Wake interval,Minimum TWT wake duration,TWT Channel, TWT Protection,Next target beacon and Listen Interval.  \n";
for (int i = 0; i < TotalStations; ++i){
ApWifiMac obj;
double twtval=obj.Intervalgeneration1(i);
twtlist[i]=twtval;}
double min = 0.0;
double max = 49.0;
Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> ();
x->SetAttribute ("Min", DoubleValue (min));
x->SetAttribute ("Max", DoubleValue (max));
int value = x->GetValue ();  
rnd=value;
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr<Socket> recvSink = Socket::CreateSocket (d.Get (rnd), tid);
InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
recvSink->Bind (local);
recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));
Ptr<Socket> source = Socket::CreateSocket (c.Get (0), tid);
InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
source->SetAllowBroadcast (true);
source->Connect (remote);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),Seconds (0.1), &GenerateTraffic,source, packetSize, numPackets,interPacketInterval);}
void PKTtrans1(NodeContainer c , NodeContainer d){
std::cout<<"\n The station send the request/beacon transmission based on this the AP send the response with the TWT agreement. \n";
double min = 0.0;
double max = 49.0;
Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> ();
x->SetAttribute ("Min", DoubleValue (min));
x->SetAttribute ("Max", DoubleValue (max));
int value = x->GetValue ();  
rnd=value;
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 (d.Get (rnd), tid);
InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
source->SetAllowBroadcast (true);
source->Connect (remote);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),Seconds (0.1), &GenerateTraffic,source, packetSize, numPackets, interPacketInterval);}
void PKTtrans2(NodeContainer c , NodeContainer d){
std::cout<<"\n Next , the AP calculate the backoff-time.Next the AP sent the wake up time to the station based on Trigger–enabled. \n";
double min = 0.0;
double max = 49.0;
Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> ();
x->SetAttribute ("Min", DoubleValue (min));
x->SetAttribute ("Max", DoubleValue (max));
int value = x->GetValue ();  
rnd=value;
ApWifiMac obj1;
Time interval=(Time)twtlist[value];
obj1.SetBeaconInterval (interval);
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 (d.Get (rnd), tid);
InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
source->SetAllowBroadcast (true);
source->Connect (remote);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),Seconds (0.1), &GenerateTraffic,source, packetSize, numPackets, interPacketInterval);}
void PKTtrans3(NodeContainer c , NodeContainer d){
std::cout<<"\n Next the station1 send the data to the AP \n";
double min = 0.0;
double max = 49.0;
Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> ();
x->SetAttribute ("Min", DoubleValue (min));
x->SetAttribute ("Max", DoubleValue (max));
int value = x->GetValue ();  
rnd=value;
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 (d.Get (rnd), tid);
InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
source->SetAllowBroadcast (true);
source->Connect (remote);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),Seconds (0.1), &GenerateTraffic, source, packetSize, numPackets, interPacketInterval);}
void PKTtrans4(NodeContainer c , NodeContainer d){
std::cout<<"\n Next the AP send the data to the Station2 \n";
double min = 0.0;
double max = 49.0;
Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> ();
x->SetAttribute ("Min", DoubleValue (min));
x->SetAttribute ("Max", DoubleValue (max));
int value = x->GetValue ();
rnd1=value;
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr<Socket> recvSink = Socket::CreateSocket (d.Get (rnd), tid);
InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
recvSink->Bind (local);
recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));
Ptr<Socket> source = Socket::CreateSocket (c.Get (0), tid);
InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
source->SetAllowBroadcast (true);
source->Connect (remote);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),Seconds (0.1), &GenerateTraffic,source, packetSize, numPackets, interPacketInterval);}
void PKTtrans5(NodeContainer c , NodeContainer d){
double min = 0.0;
double max = 49.0;
Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> ();
x->SetAttribute ("Min", DoubleValue (min));
x->SetAttribute ("Max", DoubleValue (max));
int value = x->GetValue ();  
rnd=value;
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 (d.Get (rnd), tid);
InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
source->SetAllowBroadcast (true);
source->Connect (remote);
Simulator::ScheduleWithContext (source->GetNode ()->GetId (),Seconds (0.1), &GenerateTraffic,source, packetSize, numPackets, interPacketInterval);}
int main (int argc, char *argv[]){
std::cout<<"\n A 802.11ax based Network , its consists of 50  -Stations  and 1- Access Point (AP).\n";
CommandLine cmd;
cmd.Parse (argc,argv);
NodeContainer allNodes;
StationNodes.Create (TotalStations);
allNodes.Add (StationNodes);
APNode.Create (NoofAP);
allNodes.Add (APNode);
YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
channel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
channel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
phy.SetChannel (channel.Create ());
double txp=80;
std::string phyMode ("DsssRate11Mbps");
phy.Set ("TxPowerStart",DoubleValue (txp));
phy.Set ("TxPowerEnd", DoubleValue (txp));
Config::SetDefault ("ns3::OnOffApplication::PacketSize",StringValue ("64000"));
Config::SetDefault ("ns3::OnOffApplication::DataRate",StringValue (rate));
Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",StringValue (phyMode));
Config::SetDefault ("ns3::OnOffApplication::DataRate",StringValue (rate1));
WifiHelper wifi;
wifi.SetStandard (WIFI_PHY_STANDARD_80211ax);
uint32_t rtsThreshold = 65535;
wifi.SetRemoteStationManager ("ns3::MinstrelHtWifiManager", "RtsCtsThreshold", UintegerValue (rtsThreshold), "PrintStats", BooleanValue (true));
WifiMacHelper mac;
Ssid ssid = Ssid ("ns-3-ssid");
mac.SetType ("ns3::AdhocWifiMac");
NetDeviceContainer staDevices;
staDevices = wifi.Install (phy, mac, StationNodes);
mac.SetType ("ns3::ApWifiMac","Ssid", SsidValue (ssid));
NetDeviceContainer apDevices;
apDevices = wifi.Install (phy, mac, APNode);
MobilityHelper mobility;
int nodePause = 0; 
int64_t streamIndex = 0;
ObjectFactory pos;
pos.SetTypeId ("ns3::RandomRectanglePositionAllocator");
pos.Set ("X", StringValue ("ns3::UniformRandomVariable[Min=1.0|Max=250]")); 
pos.Set ("Y", StringValue ("ns3::UniformRandomVariable[Min=1.0|Max=250]"));
Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
streamIndex += taPositionAlloc->AssignStreams (streamIndex);
mobility.SetPositionAllocator(taPositionAlloc);
std::stringstream ssSpeed;
ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
std::stringstream ssPause;
ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
mobility.SetMobilityModel ("ns3::RandomWaypointMobilityModel","Speed", StringValue (ssSpeed.str ()),"Pause", StringValue (ssPause.str ()),
"PositionAllocator", PointerValue (taPositionAlloc));
MobilityHelper mobility1;
mobility1.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility1.Install (APNode);
mobility.Install (StationNodes);
AnimationInterface::SetConstantPosition (APNode.Get (0), 125, 125);
Time interPacketInterval = Seconds (interval);
AodvHelper aodv;
Ipv4StaticRoutingHelper staticRouting;
Ipv4ListRoutingHelper list;
list.Add (staticRouting, 0);
list.Add (aodv, 1);
InternetStackHelper internet;
internet.SetRoutingHelper (list); 
internet.Install (StationNodes);
internet.Install (APNode);
Ipv4AddressHelper ipv4;
NS_LOG_INFO ("Assign IP Addresses.");
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer i = ipv4.Assign (staDevices);
Ipv4InterfaceContainer ap = ipv4.Assign (apDevices);
Simulator::Schedule(Seconds(1.1), &PKTtrans, APNode,StationNodes);
Simulator::Schedule(Seconds(3.1), &PKTtrans1, APNode,StationNodes);
Simulator::Schedule(Seconds(5.1), &PKTtrans2, APNode,StationNodes);
Simulator::Schedule(Seconds(7.1), &PKTtrans3, APNode,StationNodes);
Simulator::Schedule(Seconds(9.1), &PKTtrans4, APNode,StationNodes);
Simulator::Schedule(Seconds(11.1), &PKTtrans5, APNode,StationNodes);
Simulator::Stop (Seconds (TotalTime));
anim= new AnimationInterface ("Broadcast_TWT_Agreement.xml");
tracewsn w;
w.stTracematrices(TotalStations,1);
anim->SetBackgroundImage ("/home/research/ns-allinone-3.26/netanim-3.107/img1/bg.png", -225, -210, 0.37500, 0.2500, 1.0);
uint32_t bsimg =anim->AddResource("/home/research/ns-allinone-3.26/netanim-3.107/img1/AP.png");
uint32_t sensorimg =anim->AddResource("/home/research/ns-allinone-3.26/netanim-3.107/img1/Station.png");
for (uint32_t i = 0; i < StationNodes.GetN (); ++i){
Ptr<Node> wid1= StationNodes.Get (i);
uint32_t nodeId1 = wid1->GetId ();
anim->UpdateNodeSize (nodeId1, 37.0,37.0); 
anim->UpdateNodeImage (nodeId1, sensorimg);
anim->UpdateNodeDescription (StationNodes.Get (i), "Station" ); 
anim->UpdateNodeColor (StationNodes.Get (i), 255, 0, 0); }
for (uint32_t i = 0; i < APNode.GetN (); ++i){
anim->UpdateNodeDescription (APNode.Get (i), "Access_Point" ); 
anim->UpdateNodeColor (APNode.Get (i), 200, 200, 200); 
Ptr<Node> wid2= APNode.Get (i);
uint32_t nodeId2 = wid2->GetId ();
anim->UpdateNodeSize (nodeId2, 112.0,112.0); 
anim->UpdateNodeImage (nodeId2, bsimg);}
Ptr<RttMeanDeviation> myrtt = CreateObject<RttMeanDeviation> ();  
Simulator::Run ();
Simulator::Destroy ();
system("gnuplot 'Energy_Consumption.plt'");
system("gnuplot 'Throughput.plt'");
system("gnuplot 'Delay.plt'");
return 0;}