From c0e7539b6e897cca3e404abbc8a2dcdbec26adb8 Mon Sep 17 00:00:00 2001 From: Leonard Tracy Date: Thu, 24 Jun 2010 14:35:29 -0400 Subject: [PATCH] UAN module addition --- examples/uan/uan-cw-example.cc | 326 ++++++++ examples/uan/uan-cw-example.h | 68 ++ examples/uan/uan-rc-example.cc | 309 ++++++++ examples/uan/uan-rc-example.h | 66 ++ examples/uan/wscript | 11 + src/devices/uan/uan-address.cc | 139 ++++ src/devices/uan/uan-address.h | 129 +++ src/devices/uan/uan-channel.cc | 190 +++++ src/devices/uan/uan-channel.h | 109 +++ src/devices/uan/uan-header-common.cc | 129 +++ src/devices/uan/uan-header-common.h | 96 +++ src/devices/uan/uan-header-rc.cc | 624 +++++++++++++++ src/devices/uan/uan-header-rc.h | 375 +++++++++ src/devices/uan/uan-mac-aloha.cc | 137 ++++ src/devices/uan/uan-mac-aloha.h | 83 ++ src/devices/uan/uan-mac-cw.cc | 371 +++++++++ src/devices/uan/uan-mac-cw.h | 126 +++ src/devices/uan/uan-mac-rc-gw.cc | 718 +++++++++++++++++ src/devices/uan/uan-mac-rc-gw.h | 164 ++++ src/devices/uan/uan-mac-rc.cc | 757 ++++++++++++++++++ src/devices/uan/uan-mac-rc.h | 214 +++++ src/devices/uan/uan-mac.h | 91 +++ src/devices/uan/uan-net-device.cc | 365 +++++++++ src/devices/uan/uan-net-device.h | 143 ++++ src/devices/uan/uan-noise-model-default.cc | 80 ++ src/devices/uan/uan-noise-model-default.h | 66 ++ src/devices/uan/uan-noise-model.h | 41 + src/devices/uan/uan-phy-dual.cc | 636 +++++++++++++++ src/devices/uan/uan-phy-dual.h | 277 +++++++ src/devices/uan/uan-phy-gen.cc | 864 +++++++++++++++++++++ src/devices/uan/uan-phy-gen.h | 253 ++++++ src/devices/uan/uan-phy.h | 340 ++++++++ src/devices/uan/uan-prop-model-ideal.cc | 67 ++ src/devices/uan/uan-prop-model-ideal.h | 50 ++ src/devices/uan/uan-prop-model-thorp.cc | 95 +++ src/devices/uan/uan-prop-model-thorp.h | 54 ++ src/devices/uan/uan-prop-model.cc | 339 ++++++++ src/devices/uan/uan-prop-model.h | 254 ++++++ src/devices/uan/uan-test.cc | 269 +++++++ src/devices/uan/uan-transducer-hd.cc | 223 ++++++ src/devices/uan/uan-transducer-hd.h | 70 ++ src/devices/uan/uan-transducer.h | 189 +++++ src/devices/uan/uan-tx-mode.cc | 305 ++++++++ src/devices/uan/uan-tx-mode.h | 207 +++++ src/devices/uan/uan.h | 182 +++++ src/devices/uan/waf | 1 + src/devices/uan/wscript | 51 ++ src/helper/uan-helper.cc | 228 ++++++ src/helper/uan-helper.h | 218 ++++++ src/helper/wscript | 2 + src/wscript | 2 + 51 files changed, 11103 insertions(+) create mode 100644 examples/uan/uan-cw-example.cc create mode 100644 examples/uan/uan-cw-example.h create mode 100644 examples/uan/uan-rc-example.cc create mode 100644 examples/uan/uan-rc-example.h create mode 100644 examples/uan/wscript create mode 100644 src/devices/uan/uan-address.cc create mode 100644 src/devices/uan/uan-address.h create mode 100644 src/devices/uan/uan-channel.cc create mode 100644 src/devices/uan/uan-channel.h create mode 100644 src/devices/uan/uan-header-common.cc create mode 100644 src/devices/uan/uan-header-common.h create mode 100644 src/devices/uan/uan-header-rc.cc create mode 100644 src/devices/uan/uan-header-rc.h create mode 100644 src/devices/uan/uan-mac-aloha.cc create mode 100644 src/devices/uan/uan-mac-aloha.h create mode 100644 src/devices/uan/uan-mac-cw.cc create mode 100644 src/devices/uan/uan-mac-cw.h create mode 100644 src/devices/uan/uan-mac-rc-gw.cc create mode 100644 src/devices/uan/uan-mac-rc-gw.h create mode 100644 src/devices/uan/uan-mac-rc.cc create mode 100644 src/devices/uan/uan-mac-rc.h create mode 100644 src/devices/uan/uan-mac.h create mode 100644 src/devices/uan/uan-net-device.cc create mode 100644 src/devices/uan/uan-net-device.h create mode 100644 src/devices/uan/uan-noise-model-default.cc create mode 100644 src/devices/uan/uan-noise-model-default.h create mode 100644 src/devices/uan/uan-noise-model.h create mode 100644 src/devices/uan/uan-phy-dual.cc create mode 100644 src/devices/uan/uan-phy-dual.h create mode 100644 src/devices/uan/uan-phy-gen.cc create mode 100644 src/devices/uan/uan-phy-gen.h create mode 100644 src/devices/uan/uan-phy.h create mode 100644 src/devices/uan/uan-prop-model-ideal.cc create mode 100644 src/devices/uan/uan-prop-model-ideal.h create mode 100644 src/devices/uan/uan-prop-model-thorp.cc create mode 100644 src/devices/uan/uan-prop-model-thorp.h create mode 100644 src/devices/uan/uan-prop-model.cc create mode 100644 src/devices/uan/uan-prop-model.h create mode 100644 src/devices/uan/uan-test.cc create mode 100644 src/devices/uan/uan-transducer-hd.cc create mode 100644 src/devices/uan/uan-transducer-hd.h create mode 100644 src/devices/uan/uan-transducer.h create mode 100644 src/devices/uan/uan-tx-mode.cc create mode 100644 src/devices/uan/uan-tx-mode.h create mode 100644 src/devices/uan/uan.h create mode 100755 src/devices/uan/waf create mode 100644 src/devices/uan/wscript create mode 100644 src/helper/uan-helper.cc create mode 100644 src/helper/uan-helper.h diff --git a/examples/uan/uan-cw-example.cc b/examples/uan/uan-cw-example.cc new file mode 100644 index 000000000..5c6ff19e1 --- /dev/null +++ b/examples/uan/uan-cw-example.cc @@ -0,0 +1,326 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + + +/** + * \file uan-cw-example.cc + * \ingroup uan + * + * This example showcases the "CW-MAC" described in System Design Considerations for Undersea Networks + * article in the IEEE Journal on Selected Areas of Communications 2008 by Nathan Parrish, Leonard Tracy + * and Sumit Roy. The MAC protocol is implemented in the class UanMacCw. CW-MAC is similar in nature + * to the IEEE 802.11 DCF with a constant backoff window. It requires two parameters to be set, + * the slot time and the contention window size. The contention window size is the backoff window + * size in slots, and the slot time is the duration of each slot. These parameters should be set + * according to the overall network size, internode spacing and the number of nodes in the network. + * + * This example deploys nodes randomly (according to RNG seed of course) in a finite square region with + * the X and Y coordinates of the nodes distributed uniformly. The CW parameter is varied throughout + * the simulation in order to show the variation in throughput with respect to changes in CW. + */ + +#include "uan-cw-example.h" +#include "ns3/core-module.h" +#include "ns3/common-module.h" +#include "ns3/uan-module.h" +#include "ns3/node-module.h" +#include "ns3/mobility-module.h" +#include "ns3/contrib-module.h" +#include "ns3/helper-module.h" + +#include + +using namespace ns3; + +NS_LOG_COMPONENT_DEFINE("UanCwExample"); + +Experiment::Experiment () + : m_numNodes (15), + m_dataRate (80), + m_depth (70), + m_boundary (500), + m_packetSize (32), + m_bytesTotal (0), + m_cwMin (10), + m_cwMax (400), + m_cwStep (10), + m_avgs (3), + m_slotTime (Seconds (0.2)), + m_simTime (Seconds (1000)), + m_gnudatfile ("uan-cw-example.gpl"), + m_asciitracefile ("uan-cw-example.asc"), + m_bhCfgFile ("uan-apps/dat/default.cfg") +{ +} + +void +Experiment::ResetData () +{ + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Resetting data"); + m_throughputs.push_back (m_bytesTotal * 8.0 / m_simTime.GetSeconds ()); + m_bytesTotal = 0; +} + +void +Experiment::IncrementCw (uint32_t cw) +{ + NS_ASSERT (m_throughputs.size () == m_avgs); + + double avgThroughput = 0.0; + for (uint32_t i=0; i mp = (*it)->GetObject (); + mp->SetPosition (Vector (uv.GetValue (), uv.GetValue (), 70.0)); + } +} + +void +Experiment::ReceivePacket (Ptr socket) +{ + Ptr packet; + + while (packet = socket->Recv()) + { + m_bytesTotal += packet->GetSize (); + } + packet = 0; +} + +Gnuplot2dDataset +Experiment::Run (UanHelper &uan) +{ + //uan.SetMac ("ns3::UanMacCw", "CW", UintegerValue (m_cwMin), "SlotTime", TimeValue (m_slotTime)); + uan.SetMac ("ns3::UanMacAloha"); + NodeContainer nc = NodeContainer (); + NodeContainer sink = NodeContainer (); + nc.Create (m_numNodes); + sink.Create (1); + + PacketSocketHelper socketHelper; + socketHelper.Install (nc); + socketHelper.Install (sink); + +#ifdef UAN_PROP_BH_INSTALLED + Ptr prop = CreateObjectWithAttributes ("ConfigFile", StringValue ("exbhconfig.cfg")); +#else + Ptr prop = CreateObjectWithAttributes (); +#endif //UAN_PROP_BH_INSTALLED + Ptr channel = CreateObjectWithAttributes ("PropagationModel", PointerValue (prop)); + + //Create net device and nodes with UanHelper + NetDeviceContainer devices = uan.Install (nc, channel); + NetDeviceContainer sinkdev = uan.Install (sink, channel); + + MobilityHelper mobility; + Ptr pos = CreateObject (); + + { + UniformVariable urv (0, m_boundary); + pos->Add (Vector (m_boundary / 2.0, m_boundary / 2.0, m_depth)); + double rsum = 0; + + double minr = 2 * m_boundary; + for (uint32_t i = 0; i < m_numNodes; i++) + { + double x = urv.GetValue (); + double y = urv.GetValue (); + double newr = sqrt ((x - m_boundary / 2.0) * (x - m_boundary / 2.0) + + (y - m_boundary / 2.0) * (y - m_boundary / 2.0)); + rsum += newr; + minr = std::min (minr, newr); + pos->Add (Vector (x, y, m_depth)); + + } + NS_LOG_DEBUG ("Mean range from gateway: " << rsum / m_numNodes + << " min. range " << minr); + + mobility.SetPositionAllocator (pos); + mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); + mobility.Install (sink); + + NS_LOG_DEBUG ("Position of sink: " + << sink.Get (0)->GetObject ()->GetPosition ()); + mobility.Install (nc); + + PacketSocketAddress socket; + socket.SetSingleDevice (sinkdev.Get(0)->GetIfIndex ()); + socket.SetPhysicalAddress (sinkdev.Get(0)->GetAddress ()); + socket.SetProtocol (0); + + OnOffHelper app ("ns3::PacketSocketFactory", Address (socket)); + app.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1))); + app.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0))); + app.SetAttribute ("DataRate", DataRateValue (m_dataRate)); + app.SetAttribute ("PacketSize", UintegerValue (m_packetSize)); + + ApplicationContainer apps = app.Install (nc); + apps.Start (Seconds (0.5)); + Time nextEvent = Seconds (0.5); + + + for (uint32_t cw = m_cwMin; cw <= m_cwMax; cw += m_cwStep) + { + + for (uint32_t an = 0; an < m_avgs; an++) + { + nextEvent += m_simTime; + Simulator::Schedule (nextEvent, &Experiment::ResetData, this); + Simulator::Schedule (nextEvent, &Experiment::UpdatePositions, this, nc); + } + Simulator::Schedule (nextEvent, &Experiment::IncrementCw, this, cw); + } + apps.Stop (nextEvent + m_simTime); + + Ptr sinkNode = sink.Get (0); + TypeId psfid = TypeId::LookupByName ("ns3::PacketSocketFactory"); + if (sinkNode->GetObject (psfid) == 0) + { + Ptr psf = CreateObject (); + sinkNode->AggregateObject (psf); + } + Ptr sinkSocket = Socket::CreateSocket (sinkNode, psfid); + sinkSocket->Bind (socket); + sinkSocket->SetRecvCallback (MakeCallback (&Experiment::ReceivePacket, this)); + + m_bytesTotal = 0; + + std::ofstream ascii (m_asciitracefile.c_str ()); + if (!ascii.is_open ()) + { + NS_FATAL_ERROR ("Could not open ascii trace file: " + << m_asciitracefile); + } + uan.EnableAsciiAll (ascii); + + Simulator::Run (); + sinkNode = 0; + sinkSocket = 0; + pos = 0; + channel = 0; + prop = 0; + for (uint32_t i=0; i < nc.GetN (); i++) + { + nc.Get (i) = 0; + } + for (uint32_t i=0; i < sink.GetN (); i++) + { + sink.Get (i) = 0; + } + + for (uint32_t i=0; i < devices.GetN (); i++) + { + devices.Get (i) = 0; + } + for (uint32_t i=0; i < sinkdev.GetN (); i++) + { + sinkdev.Get (i) = 0; + } + + Simulator::Destroy (); + return m_data; + } +} + +int +main (int argc, char **argv) +{ + + LogComponentEnable ("UanCwExample", LOG_LEVEL_ALL); + + Experiment exp; + + std::string gnudatfile ("cwexpgnuout.dat"); + std::string perModel = "ns3::UanPhyPerGenDefault"; + std::string sinrModel = "ns3::UanPhyCalcSinrDefault"; + + CommandLine cmd; + cmd.AddValue ("NumNodes", "Number of transmitting nodes", exp.m_numNodes); + cmd.AddValue ("Depth", "Depth of transmitting and sink nodes", exp.m_depth); + cmd.AddValue ("RegionSize", "Size of boundary in meters", exp.m_boundary); + cmd.AddValue ("PacketSize", "Generated packet size in bytes", exp.m_packetSize); + cmd.AddValue ("DataRate", "DataRate in bps", exp.m_dataRate); + cmd.AddValue ("CwMin", "Min CW to simulate", exp.m_cwMin); + cmd.AddValue ("CwMax", "Max CW to simulate", exp.m_cwMax); + cmd.AddValue ("SlotTime", "Slot time duration", exp.m_slotTime); + cmd.AddValue ("Averages", "Number of topologies to test for each cw point", exp.m_avgs); + cmd.AddValue ("GnuFile", "Name for GNU Plot output", exp.m_gnudatfile); + cmd.AddValue ("PerModel", "PER model name", perModel); + cmd.AddValue ("SinrModel", "SINR model name", sinrModel); + cmd.Parse (argc, argv); + + ObjectFactory obf; + obf.SetTypeId (perModel); + Ptr per = obf.Create (); + obf.SetTypeId (sinrModel); + Ptr sinr = obf.Create (); + + UanHelper uan; + UanTxMode mode; + mode = UanTxModeFactory::CreateMode (UanTxMode::FSK, exp.m_dataRate, + exp.m_dataRate, 12000, + exp.m_dataRate, 2, + "Default mode"); + UanModesList myModes; + myModes.AppendMode (mode); + + uan.SetPhy ("ns3::UanPhyGen", + "PerModel", PointerValue (per), + "SinrModel", PointerValue (sinr), + "SupportedModes", UanModesListValue (myModes)); + + Gnuplot gp; + Gnuplot2dDataset ds; + ds = exp.Run (uan); + + gp.AddDataset (ds); + + std::ofstream of (exp.m_gnudatfile.c_str ()); + if (!of.is_open ()) + { + NS_FATAL_ERROR ("Can not open GNU Plot outfile: " << exp.m_gnudatfile); + } + gp.GenerateOutput (of); + + per = 0; + sinr = 0; + +} + diff --git a/examples/uan/uan-cw-example.h b/examples/uan/uan-cw-example.h new file mode 100644 index 000000000..1c7cb7ae1 --- /dev/null +++ b/examples/uan/uan-cw-example.h @@ -0,0 +1,68 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANCWEXAMPLE_H +#define UANCWEXAMPLE_H + +#include "ns3/common-module.h" +#include "ns3/node-module.h" +#include "ns3/contrib-module.h" +#include "ns3/helper-module.h" + +using namespace ns3; + +/** + * \class Experiment + * \brief Helper class for UAN CW MAC example + * + */ +class Experiment +{ +public: + Gnuplot2dDataset Run (UanHelper &uan); + void ReceivePacket (Ptr socket); + void UpdatePositions (NodeContainer &nodes); + void ResetData (); + void IncrementCw (uint32_t cw); + uint32_t m_numNodes; + uint32_t m_dataRate; + double m_depth; + double m_boundary; + uint32_t m_packetSize; + uint32_t m_bytesTotal; + uint32_t m_cwMin; + uint32_t m_cwMax; + uint32_t m_cwStep; + uint32_t m_avgs; + + Time m_slotTime; + Time m_simTime; + + std::string m_gnudatfile; + std::string m_asciitracefile; + std::string m_bhCfgFile; + + Gnuplot2dDataset m_data; + std::vector m_throughputs; + + Experiment (); +}; + +#endif //UANCWEXAMPLE_H diff --git a/examples/uan/uan-rc-example.cc b/examples/uan/uan-rc-example.cc new file mode 100644 index 000000000..8276cb1f0 --- /dev/null +++ b/examples/uan/uan-rc-example.cc @@ -0,0 +1,309 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +/** + * \file uan-rc-example.cc + * \ingroup UAN + * This example uses UanMacRc and UanMacRcGw which combined form a system + * using what is reffered to as RC-MAC. Details of RC-MAC will be published + * soon. In brief terms, RC-MAC is a dual channel protocol wherein the + * available bandwidth is dynamically divided into two channels, + * a reservation channel and a data channel. The network is assumed + * to consist of a single gateway node which services several + * non-gateway nodes. + * + * Time is divided into cycles. The non-gateway nodes transmit RTS packets + * on the reservation channel in parallel to scheduled data transmissions + * (scheduled in the previous cycle), and the gateway stores these requests + * for the duration of the cycle. At the start of the next cycle + * the gateway node transmits a CTS which contains packet transmission times + * for reserved packets as well as bandwidth allocation information + * + * This script deploys a single gateway node (current UanMacRc only supports + * a single gateway) in the center of a region and then distributes + * non-gateway nodes around the gateway with a uniformly distributed range + * between each node and the gateway. + * + * The script supports two simulation types. By default the gateway + * dynamically determines the optimal parameter settings and + * simulations are run with varying number of nodes (SimMin to SimMax as + * set by the command line). If DoNode=0 is given as a command line option + * then the mac parameter "a" (approximate expected number of successful + * RTS arrivals per cycle) is varied as the simulation parameter. + * + * For questions about this MAC protocol email "lentracy@gmail.com" + */ + +#include "uan-rc-example.h" +#include "ns3/core-module.h" +#include "ns3/common-module.h" +#include "ns3/uan-module.h" +#include "ns3/helper-module.h" +#include "ns3/mobility-module.h" +#include "ns3/node-module.h" +#include "ns3/log.h" +#include "ns3/config.h" +#include "ns3/callback.h" +#include "ns3/contrib-module.h" + +#include + +using namespace ns3; + +NS_LOG_COMPONENT_DEFINE ("UanRcExample"); + + +Experiment::Experiment () + : m_simMin (1), + m_simMax (1), + m_simStep (1), + m_numRates (1023), + m_totalRate (4096), + m_maxRange (3000), + m_numNodes (15), + m_pktSize (1000), + m_doNode (true), + m_sifs (Seconds (0.05)), + m_simTime (Seconds (5000)), + m_gnuplotfile ("uan-rc-example.gpl"), + m_bytesTotal (0) +{ +} + +void +Experiment::ReceivePacket (Ptr socket) +{ + Ptr packet; + while (packet = socket->Recv ()) + { + m_bytesTotal += packet->GetSize (); + } +} + +UanTxMode +Experiment::CreateMode (uint32_t kass, + uint32_t fc, + bool upperblock, + std::string name) +{ + + std::ostringstream buf; + buf << name << " " << kass; + + uint32_t rate = m_totalRate/(m_numRates+1)* (kass); + uint32_t bw = kass * m_totalRate / (m_numRates+1); + uint32_t fcmode; + if(upperblock) + fcmode = (m_totalRate - bw)/2 + fc; + else + fcmode = (uint32_t)((-((double) m_totalRate ) + (double) bw)/2.0 + (double) fc); + + + uint32_t phyrate = m_totalRate; + + UanTxMode mode; + mode = UanTxModeFactory::CreateMode (UanTxMode::OTHER, + rate, + phyrate, + fcmode, + bw, + 2, + buf.str()); + return mode; +} + +//Creates m_numRates different modes each dividing m_totalRate Hz (assumes 1 bit per hz) +//centered at frequency fc +void +Experiment::CreateDualModes (uint32_t fc) +{ + + + for (uint32_t i=1; i < m_numRates+1; i++) + { + m_controlModes.AppendMode (CreateMode (i, fc, false, "control ")); + } + for (uint32_t i=m_numRates; i > 0; i--) + { + m_dataModes.AppendMode (CreateMode (i, fc, true, "data ")); + } +} + +uint32_t +Experiment::Run (UanHelper &uan, uint32_t param) +{ + + m_bytesTotal=0; + + uint32_t nNodes; + uint32_t a; + if(m_doNode) + { + a=0; + nNodes = param; + } + else + { + nNodes = m_numNodes; + a = param; + } + Time pDelay = Seconds((double) m_maxRange / 1500.0); + + uan.SetMac ("ns3::UanMacRcGw", + "NumberOfRates", UintegerValue (m_numRates), + "NumberOfNodes", UintegerValue (nNodes), + "MaxReservations", UintegerValue (a), + "RetryRate", DoubleValue(1/30.0), + "SIFS", TimeValue (m_sifs), + "MaxPropDelay", TimeValue (pDelay), + "FrameSize", UintegerValue (m_pktSize)); + Ptr chan = CreateObject(); + + NodeContainer sink; + sink.Create(1); + NetDeviceContainer sinkDev = uan.Install(sink, chan); + + uan.SetMac ("ns3::UanMacRc", + "NumberOfRates", UintegerValue (m_numRates), + "MaxPropDelay", TimeValue (pDelay), + "RetryRate", DoubleValue(1.0/100.0)); + NodeContainer nodes; + nodes.Create (nNodes); + NetDeviceContainer devices = uan.Install (nodes, chan); + + MobilityHelper mobility; + uint32_t depth = 70; + Ptr pos = CreateObject (); + + UniformVariable urv (0,m_maxRange); + UniformVariable utheta (0, 2.0*M_PI); + pos->Add (Vector (m_maxRange, m_maxRange, depth)); + + for (uint32_t i=0; iAdd (Vector (x, y, depth)); + + } + + mobility.SetPositionAllocator (pos); + mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); + mobility.Install (sink); + mobility.Install (nodes); + + PacketSocketHelper pktskth; + pktskth.Install (nodes); + pktskth.Install (sink); + + PacketSocketAddress socket; + socket.SetSingleDevice (sinkDev.Get(0)->GetIfIndex ()); + socket.SetPhysicalAddress (sinkDev.Get(0)->GetAddress ()); + socket.SetProtocol (0); + + OnOffHelper app ("ns3::PacketSocketFactory", Address (socket)); + app.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1))); + app.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0))); + app.SetAttribute ("DataRate", DataRateValue (m_totalRate)); + app.SetAttribute ("PacketSize", UintegerValue (m_pktSize)); + + ApplicationContainer apps = app.Install (nodes); + + apps.Start (Seconds (0.5)); + apps.Stop (m_simTime + Seconds(0.5)); + + Ptr sinkNode = sink.Get (0); + TypeId psfid = TypeId::LookupByName ("ns3::PacketSocketFactory"); + + Ptr sinkSocket = Socket::CreateSocket(sinkNode, psfid); + sinkSocket->Bind(socket); + sinkSocket->SetRecvCallback (MakeCallback (&Experiment::ReceivePacket, this)); + + Simulator::Stop (m_simTime + Seconds(0.6)); + + chan = 0; + sinkNode = 0; + sinkSocket = 0; + pos = 0; + + Simulator::Run (); + Simulator::Destroy (); + + return m_bytesTotal; +} +int +main(int argc, char *argv[]) +{ + + LogComponentEnable ("UanRcExample", LOG_LEVEL_ALL); + + Experiment exp; + + CommandLine cmd; + cmd.AddValue ("TotalRate", "Total channel capacity", exp.m_totalRate); + cmd.AddValue ("NumberRates", "Number of divided rates ( (NumberRates+1)%TotalRate should be 0)", exp.m_numRates); + cmd.AddValue ("MaxRange", "Maximum range between gateway and acoustic node", exp.m_maxRange); + cmd.AddValue ("SimMin", "Minimum parameter to test (nodes if DoNode=1, \"a\" param otherwise)", exp.m_simMin); + cmd.AddValue ("SimMax", "Maximum parameter to test (nodes if DoNode=1, \"a\" param otherwise)", exp.m_simMax); + cmd.AddValue ("SimStep", "Ammount to increment param per trial", exp.m_simStep); + cmd.AddValue ("DataFile", "Filename for GnuPlot", exp.m_gnuplotfile); + cmd.AddValue ("NumberNodes", "Number of nodes (invalid for doNode=1)", exp.m_numNodes); + cmd.AddValue ("SIFS", "SIFS time duration", exp.m_sifs); + cmd.AddValue ("PktSize", "Packet size in bytes", exp.m_pktSize); + cmd.AddValue ("SimTime", "Simulation time per trial", exp.m_simTime); + cmd.AddValue ("DoNode", "1 for do max nodes simulation (invalidates AMin and AMax values)", exp.m_doNode); + cmd.Parse (argc, argv); + + + + exp.CreateDualModes (12000); + + UanHelper uan; + uan.SetPhy ("ns3::UanPhyDual", + "SupportedModesPhy1", UanModesListValue (exp.m_dataModes), + "SupportedModesPhy2", UanModesListValue (exp.m_controlModes)); + + Gnuplot2dDataset ds; + for (uint32_t param=exp.m_simMin; param<=exp.m_simMax; param += exp.m_simStep) + { + uint32_t bytesRx = exp.Run (uan, param); + NS_LOG_DEBUG ("param=" << param << ": Received " << bytesRx << " bytes at sink"); + + double util = bytesRx*8.0/(exp.m_simTime.GetSeconds ()*exp.m_totalRate); + + ds.Add (param, util); + + SeedManager::SetRun (SeedManager::GetRun () + 1); + } + + Gnuplot gp; + gp.AddDataset (ds); + std::ofstream of (exp.m_gnuplotfile.c_str ()); + if (!of.is_open ()) + { + NS_FATAL_ERROR ("Can not open GNU Plot outfile: " << exp.m_gnuplotfile); + } + gp.GenerateOutput (of); + +} diff --git a/examples/uan/uan-rc-example.h b/examples/uan/uan-rc-example.h new file mode 100644 index 000000000..947e93b89 --- /dev/null +++ b/examples/uan/uan-rc-example.h @@ -0,0 +1,66 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANRCEXAMPLE_H +#define UANRCEXAMPLE_H + +#include "ns3/common-module.h" +#include "ns3/node-module.h" +#include "ns3/contrib-module.h" +#include "ns3/helper-module.h" +#include "ns3/uan-module.h" + +using namespace ns3; + +class Experiment +{ +public: + uint32_t m_simMin; + uint32_t m_simMax; + uint32_t m_simStep; + uint32_t m_numRates; + uint32_t m_totalRate; + uint32_t m_maxRange; + uint32_t m_numNodes; + uint32_t m_pktSize; + bool m_doNode; + Time m_sifs; + Time m_simTime; + + std::string m_gnuplotfile; + + uint32_t m_bytesTotal; + + UanModesList m_dataModes; + UanModesList m_controlModes; + + void ReceivePacket (Ptr socket); + UanTxMode CreateMode (uint32_t kass, + uint32_t fc, + bool upperblock, + std::string name); + void CreateDualModes (uint32_t fc); + uint32_t Run (UanHelper &uan, uint32_t param); + + Experiment(); + +}; + +#endif //UANRCEXAMPLE_H diff --git a/examples/uan/wscript b/examples/uan/wscript new file mode 100644 index 000000000..3520a5cbe --- /dev/null +++ b/examples/uan/wscript @@ -0,0 +1,11 @@ + +## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*- + +def build(bld): + obj = bld.create_ns3_program('uan-cw-example', ['core', 'simulator', 'mobility', 'uan']) + obj.source = 'uan-cw-example.cc' + + obj = bld.create_ns3_program('uan-rc-example', ['core', 'simulator', 'mobility', 'uan']) + obj.source = 'uan-rc-example.cc' + + diff --git a/src/devices/uan/uan-address.cc b/src/devices/uan/uan-address.cc new file mode 100644 index 000000000..376c877f3 --- /dev/null +++ b/src/devices/uan/uan-address.cc @@ -0,0 +1,139 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#include "uan-address.h" +#include "ns3/address.h" + +namespace ns3 { + +UanAddress::UanAddress () +{ + m_address = 255; +} + +UanAddress::UanAddress (uint8_t addr) + : m_address (addr) +{ +} + +UanAddress::~UanAddress () +{ +} + +uint8_t +UanAddress::GetType (void) +{ + static uint8_t type = Address::Register (); + return type; +} + +Address +UanAddress::ConvertTo (void) const +{ + return Address (GetType (), &m_address, 1); +} + +UanAddress +UanAddress::ConvertFrom (const Address &address) +{ + NS_ASSERT (IsMatchingType (address)); + UanAddress uAddr; + address.CopyTo (&uAddr.m_address); + return uAddr; +} + +uint8_t +UanAddress::GetAsInt (void) const +{ + return m_address; +} +bool +UanAddress::IsMatchingType (const Address &address) +{ + return address.CheckCompatible (GetType (), 1); +} + +UanAddress::operator Address () const +{ + return ConvertTo (); +} + +void +UanAddress::CopyFrom (const uint8_t *pBuffer) +{ + m_address = *pBuffer; +} + +void +UanAddress::CopyTo (uint8_t *pBuffer) +{ + *pBuffer = m_address; + +} + +UanAddress +UanAddress::GetBroadcast () +{ + return UanAddress (255); +} +UanAddress +UanAddress::Allocate () +{ + static uint8_t nextAllocated = 0; + + uint32_t address = nextAllocated++; + if (nextAllocated == 255) + { + nextAllocated = 0; + } + + return UanAddress (address); +} + +bool +operator == (const UanAddress &a, const UanAddress &b) +{ + return a.m_address == b.m_address; +} + +bool +operator != (const UanAddress &a, const UanAddress &b) +{ + return !(a == b); +} + +std::ostream& +operator<< (std::ostream& os, const UanAddress & address) +{ + os << (int) address.m_address; + return os; +} +std::istream& +operator>> (std::istream& is, UanAddress & address) +{ + int x; + is >> x; + NS_ASSERT (0 <= x); + NS_ASSERT (x <= 255); + address.m_address = x; + return is; +} + +} // namespace ns3 diff --git a/src/devices/uan/uan-address.h b/src/devices/uan/uan-address.h new file mode 100644 index 000000000..0cc931c67 --- /dev/null +++ b/src/devices/uan/uan-address.h @@ -0,0 +1,129 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANADDRESS_H +#define UANADDRESS_H + +#include "ns3/address.h" +#include + +namespace ns3 { + +/** + * \class UanAddress + * + * A class used for addressing UAN MAC's. This implementation uses a simple 8 bit + * flat addressing scheme. It is unlikely that perceived underwater networks will + * soon exceed 200 nodes (or the overlapping of two underwater networks - the ocean is big), + * so this should provide adequate addressing for most applications. + */ +class UanAddress +{ +public: + UanAddress (); + /** + * \param addr byte address to assign to this address + * \brief Create UanAddress object with address addr + */ + UanAddress (uint8_t addr); + virtual ~UanAddress (); + + /** + * \param address Address to convert to UAN address + * \returns UanAddress from Address + */ + static UanAddress ConvertFrom (const Address &address); + + /** + * \param address Address to test + * \returns True if address given is consistant with UanAddress + */ + static bool IsMatchingType (const Address &address); + + /** + * \brief Create UanAddress object with broadcast address + */ + operator Address () const; + + /** + * \param pBuffer Buffer to extract address from + * \brief Sets address to address stored in parameter + */ + void CopyFrom (const uint8_t *pBuffer); + + /** + * \param pBuffer + * \brief Writes address to buffer parameter + */ + void CopyTo (uint8_t *pBuffer); + + /** + * \returns 8 bit integer version of address + */ + uint8_t GetAsInt (void) const; + + /** + * \returns Broadcast address: 255 + */ + static UanAddress GetBroadcast (void); + + /** + * \brief Allocates UanAddress from 0-254 (will wrap back to 0 if more than 255 are allocated) + */ + static UanAddress Allocate (); + + +private: + uint8_t m_address; + + static uint8_t GetType (void); + Address ConvertTo (void) const; + + friend bool operator == (const UanAddress &a, const UanAddress &b); + friend bool operator != (const UanAddress &a, const UanAddress &b); + friend std::ostream& operator<< (std::ostream& os, const UanAddress & address); + friend std::istream& operator>> (std::istream& is, UanAddress & address); + +}; + + +/** + * \brief Returns true if byte address a is equal to byte address b + */ +bool operator == (const UanAddress &a, const UanAddress &b); + +/** + * \brief Returns true if byte address a is unequal to byte address b + */ +bool operator != (const UanAddress &a, const UanAddress &b); + +/** + * \brief Writes param address to stream os as 8 bit integer + */ +std::ostream& operator<< (std::ostream& os, const UanAddress & address); + +/** + * \brief Inputs param address from stream is as 8 bit integer + */ +std::istream& operator>> (std::istream& is, UanAddress & address); + +} // namespace ns3 + +#endif // UANADDRESS_H diff --git a/src/devices/uan/uan-channel.cc b/src/devices/uan/uan-channel.cc new file mode 100644 index 000000000..736a7ecbd --- /dev/null +++ b/src/devices/uan/uan-channel.cc @@ -0,0 +1,190 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#include "ns3/object.h" +#include "ns3/packet.h" +#include "ns3/simulator.h" +#include "ns3/mobility-model.h" +#include "ns3/net-device.h" +#include "ns3/node.h" +#include "ns3/log.h" +#include "ns3/pointer.h" +#include "ns3/log.h" + +#include "uan-channel.h" +#include "uan-phy.h" +#include "uan-prop-model.h" +#include "uan-tx-mode.h" +#include "uan-net-device.h" +#include "uan-transducer.h" +#include "uan-noise-model-default.h" +#include "uan-prop-model-ideal.h" + +NS_LOG_COMPONENT_DEFINE ("UanChannel"); +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED ( UanChannel); + +TypeId +UanChannel::GetTypeId () +{ + static TypeId tid = + TypeId ("ns3::UanChannel") + .SetParent () + .AddConstructor () + .AddAttribute ("PropagationModel", + "A pointer to the propagation model.", + PointerValue (CreateObject ()), + MakePointerAccessor (&UanChannel::m_prop), + MakePointerChecker ()) + .AddAttribute ("NoiseModel", + "A pointer to the model of the channel ambient noise.", + PointerValue (CreateObject ()), + MakePointerAccessor (&UanChannel::m_noise), + MakePointerChecker ()) + ; + + return tid; +} + +UanChannel::UanChannel () + : Channel (), + m_prop (0) +{ +} + +UanChannel::~UanChannel () +{ +} +void +UanChannel::DoDispose () +{ + UanDeviceList::iterator it = m_devList.begin (); + for (; it != m_devList.end (); it++) + { + it->first = 0; + it->second = 0; + } + m_devList.clear (); + m_prop = 0; + m_noise = 0; + Channel::DoDispose (); +} +void +UanChannel::SetPropagationModel (Ptr prop) +{ + NS_LOG_DEBUG ("Set Prop Model " << this); + m_prop = prop; +} + +uint32_t +UanChannel::GetNDevices () const +{ + return m_devList.size (); +} + +Ptr +UanChannel::GetDevice (uint32_t i) const +{ + return m_devList[i].first; +} + +void +UanChannel::AddDevice (Ptr dev, Ptr trans) +{ + NS_LOG_DEBUG ("Adding dev/trans pair number " << m_devList.size ()); + m_devList.push_back (std::make_pair (dev, trans)); +} + +void +UanChannel::TxPacket (Ptr src, Ptr packet, + double txPowerDb, UanTxMode txMode) +{ + Ptr senderMobility = 0; + + NS_LOG_DEBUG ("Channel scheduling"); + for (UanDeviceList::const_iterator i = m_devList.begin (); i + != m_devList.end (); i++) + { + + if (src == i->second) + { + senderMobility = i->first->GetNode ()->GetObject (); + break; + } + } + NS_ASSERT (senderMobility != 0); + uint32_t j = 0; + UanDeviceList::const_iterator i = m_devList.begin (); + for (; i != m_devList.end (); i++) + { + if (src != i->second) + { + NS_LOG_DEBUG ("Scheduling " << i->first->GetMac ()->GetAddress ()); + Ptr rcvrMobility = i->first->GetNode ()->GetObject (); + Time delay = m_prop->GetDelay (senderMobility, rcvrMobility, txMode); + UanPdp pdp = m_prop->GetPdp (senderMobility, rcvrMobility, txMode); + double rxPowerDb = txPowerDb + m_prop->GetPathLossDb (senderMobility, + rcvrMobility, + txMode); + + NS_LOG_DEBUG ("txPowerDb=" << txPowerDb << "dB, rxPowerDb=" + << rxPowerDb << "distance=" + << senderMobility->GetDistanceFrom (rcvrMobility) + << "m, delay=" << delay); + + uint32_t dstNodeId = i->first->GetNode ()->GetId (); + Ptr copy = packet->Copy (); + Simulator::ScheduleWithContext (dstNodeId, delay, + &UanChannel::SendUp, + this, + j, + copy, + rxPowerDb, + txMode, + pdp); + } + j++; + } +} + +void +UanChannel::SetNoiseModel (Ptr noise) +{ + NS_ASSERT (noise); + m_noise = noise; +} +void +UanChannel::SendUp (uint32_t i, Ptr packet, double rxPowerDb, + UanTxMode txMode, UanPdp pdp) +{ + NS_LOG_DEBUG ("Channel: In sendup"); + m_devList[i].second->Receive (packet, rxPowerDb, txMode, pdp); +} + +double +UanChannel::GetNoiseDbHz (double fKhz) +{ + NS_ASSERT (m_noise); + double noise = m_noise->GetNoiseDbHz (fKhz); + return noise; +} + +} // namespace ns3 diff --git a/src/devices/uan/uan-channel.h b/src/devices/uan/uan-channel.h new file mode 100644 index 000000000..8f44d1de6 --- /dev/null +++ b/src/devices/uan/uan-channel.h @@ -0,0 +1,109 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANCHANNEL_H +#define UANCHANNEL_H + +#include "ns3/net-device.h" +#include "ns3/channel.h" +#include "ns3/packet.h" +#include "ns3/uan-prop-model.h" +#include "ns3/uan-noise-model.h" + +#include +#include + +namespace ns3 { + +class UanNetDevice; +class UanPhy; +class UanTransducer; +class UanTxMode; + +/** + * \class UanChannel + * \brief Channel class used by UAN devices + */ +class UanChannel : public Channel +{ +public: + /** + * \brief UanDeviceList is a standard template vector of pairs (UanNetDevice, UanTransducer) + */ + typedef std::vector, Ptr > > UanDeviceList; + + + UanChannel (); + virtual ~UanChannel (); + + static TypeId GetTypeId (); + + // Methods inherrited from base class + virtual uint32_t GetNDevices (void) const; + virtual Ptr GetDevice (uint32_t i) const; + + /** + * \param src Transducer transmitting packet + * \param packet Packet to be transmitted + * \param txPowerDb Transmission power in dB + * \param txmode UanTxMode defining modulation of transmitted packet + * Send a packet out on the channel + */ + void TxPacket (Ptr src, Ptr packet, double txPowerDb, + UanTxMode txmode); + + /** + * \param dev Net Device of node + * \param trans Transducer of net device attached to this channel + * + * Adds device to receiver list for this channel + */ + void AddDevice (Ptr dev, Ptr trans); + + /** + * \param prop Propagation model this channel will use for path loss/propagation delay + */ + void SetPropagationModel (Ptr prop); + + /** + * \param noise Noise model this channel will use to determine ambient channel noise. + * + */ + void SetNoiseModel (Ptr noise); + + /** + * \param fKhz Frequency in kHz + * \returns Ambient noise in dB/Hz on channel at a frequency + */ + double GetNoiseDbHz (double fKhz); + +private: + UanDeviceList m_devList; + Ptr m_prop; + Ptr m_noise; + + void SendUp (uint32_t i, Ptr packet, double rxPowerDb, UanTxMode txMode, UanPdp pdp); +protected: + virtual void DoDispose (); +}; + +} + +#endif // UANCHANNEL_H diff --git a/src/devices/uan/uan-header-common.cc b/src/devices/uan/uan-header-common.cc new file mode 100644 index 000000000..35eee0832 --- /dev/null +++ b/src/devices/uan/uan-header-common.cc @@ -0,0 +1,129 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#include "uan-header-common.h" +#include "uan-address.h" + +namespace ns3 { + +UanHeaderCommon::UanHeaderCommon () +{ +} + +UanHeaderCommon::UanHeaderCommon (const UanAddress src, const UanAddress dest, uint8_t type) + : Header (), + m_dest (dest), + m_src (src), + m_type (type) +{ + +} + +TypeId +UanHeaderCommon::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::UanHeaderCommon") + .SetParent
() + .AddConstructor () + ; + return tid; +} + +TypeId +UanHeaderCommon::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} +UanHeaderCommon::~UanHeaderCommon () +{ +} + + +void +UanHeaderCommon::SetDest (UanAddress dest) +{ + m_dest = dest; +} +void +UanHeaderCommon::SetSrc (UanAddress src) +{ + m_src = src; +} + +void +UanHeaderCommon::SetType (uint8_t type) +{ + m_type = type; +} + +UanAddress +UanHeaderCommon::GetDest (void) const +{ + return m_dest; +} +UanAddress +UanHeaderCommon::GetSrc (void) const +{ + return m_src; +} +uint8_t +UanHeaderCommon::GetType (void) const +{ + return m_type; +} + +// Inherrited methods + +uint32_t +UanHeaderCommon::GetSerializedSize (void) const +{ + return 1 + 1 + 1; +} + +void +UanHeaderCommon::Serialize (Buffer::Iterator start) const +{ + start.WriteU8 (m_src.GetAsInt ()); + start.WriteU8 (m_dest.GetAsInt ()); + start.WriteU8 (m_type); +} + +uint32_t +UanHeaderCommon::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator rbuf = start; + + m_src = UanAddress (rbuf.ReadU8 ()); + m_dest = UanAddress (rbuf.ReadU8 ()); + m_type = rbuf.ReadU8 (); + + return rbuf.GetDistanceFrom (start); +} + +void +UanHeaderCommon::Print (std::ostream &os) const +{ + os << "UAN src=" << m_src << " dest=" << m_dest << " type=" << (uint32_t) m_type; +} + + + + +} // namespace ns3 diff --git a/src/devices/uan/uan-header-common.h b/src/devices/uan/uan-header-common.h new file mode 100644 index 000000000..9329e1ca6 --- /dev/null +++ b/src/devices/uan/uan-header-common.h @@ -0,0 +1,96 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANHEADERCOMMON_H +#define UANHEADERCOMMON_H + +#include "ns3/header.h" +#include "ns3/nstime.h" +#include "ns3/simulator.h" +#include "uan-address.h" + +namespace ns3 { + +/** + * \class UanHeaderCommon + * + * Header includes 1 byte src address, 1 byte dest address, + * and a 1 byte type field. + */ +class UanHeaderCommon : public ns3::Header +{ +public: + UanHeaderCommon (); + /** + * \brief Create UanHeaderCommon object with given source and destination address and header type + * \param src Source address defined in header + * \param dest Destination address defined in header + * \param type Header type + */ + UanHeaderCommon (const UanAddress src, const UanAddress dest, uint8_t type); + virtual ~UanHeaderCommon (); + + static TypeId GetTypeId (void); + + /** + * \param dest Address of destination node + */ + void SetDest (UanAddress dest); + /** + * \param src Address of packet source node + */ + void SetSrc (UanAddress src); + /** + * \param type Value to set 1 byte type field to. Value has protocol specific meaning + */ + void SetType (uint8_t type); + + /** + * \returns UanAddress in destination field + */ + UanAddress GetDest (void) const; + /** + * \returns UanAddress in source field + */ + UanAddress GetSrc (void) const; + /** + * \returns value of type field + */ + uint8_t GetType (void) const; + + + + // Inherrited methods + virtual uint32_t GetSerializedSize (void) const; + virtual void Serialize (Buffer::Iterator start) const; + virtual uint32_t Deserialize (Buffer::Iterator start); + virtual void Print (std::ostream &os) const; + virtual TypeId GetInstanceTypeId (void) const; +private: + UanAddress m_dest; + UanAddress m_src; + uint8_t m_type; + + +}; + +} + +#endif // UANHEADERCOMMON_H diff --git a/src/devices/uan/uan-header-rc.cc b/src/devices/uan/uan-header-rc.cc new file mode 100644 index 000000000..19eceffe6 --- /dev/null +++ b/src/devices/uan/uan-header-rc.cc @@ -0,0 +1,624 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + + +#include "uan-header-rc.h" + +#include + +namespace ns3 { + +UanHeaderRcData::UanHeaderRcData () + : Header (), + m_frameNo (0), + m_propDelay (Seconds (0)) +{ +} + +UanHeaderRcData::UanHeaderRcData (uint8_t frameNo, Time propDelay) + : Header (), + m_frameNo (frameNo), + m_propDelay (propDelay) +{ + +} + +UanHeaderRcData::~UanHeaderRcData () +{ +} + + +TypeId +UanHeaderRcData::GetTypeId () +{ + static TypeId tid = TypeId ("ns3::UanHeaderRcData") + .SetParent
() + .AddConstructor () + ; + return tid; +} + +void +UanHeaderRcData::SetFrameNo (uint8_t no) +{ + m_frameNo = no; +} + +void +UanHeaderRcData::SetPropDelay (Time propDelay) +{ + m_propDelay = propDelay; +} + +uint8_t +UanHeaderRcData::GetFrameNo (void) const +{ + return m_frameNo; +} + +Time +UanHeaderRcData::GetPropDelay (void) const +{ + return m_propDelay; +} + +uint32_t +UanHeaderRcData::GetSerializedSize (void) const +{ + return 1 + 2; +} + +void +UanHeaderRcData::Serialize (Buffer::Iterator start) const +{ + start.WriteU8 (m_frameNo); + start.WriteU16 ( (uint16_t)(1000.0 * m_propDelay.GetSeconds () + 0.5)); +} +uint32_t +UanHeaderRcData::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator rbuf = start; + + m_frameNo = start.ReadU8 (); + m_propDelay = Seconds ( ((double) start.ReadU16 ()) / 1000.0 ); + + return rbuf.GetDistanceFrom (start); +} + +void +UanHeaderRcData::Print (std::ostream &os) const +{ + os << "Frame No=" << (uint32_t) m_frameNo << " Prop Delay=" << m_propDelay.GetSeconds (); +} + +TypeId +UanHeaderRcData::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} + + +UanHeaderRcRts::UanHeaderRcRts () + : Header (), + m_frameNo (0), + m_noFrames (0), + m_length (0), + m_timeStamp (Seconds (0)), + m_retryNo (0) +{ + +} + +UanHeaderRcRts::UanHeaderRcRts (uint8_t frameNo, uint8_t retryNo, uint8_t noFrames, uint16_t length, Time timeStamp) + : Header (), + m_frameNo (frameNo), + m_noFrames (noFrames), + m_length (length), + m_timeStamp (timeStamp), + m_retryNo (retryNo) +{ + +} + +UanHeaderRcRts::~UanHeaderRcRts () +{ + +} + +TypeId +UanHeaderRcRts::GetTypeId () +{ + static TypeId tid = TypeId ("ns3::UanHeaderRcRts") + .SetParent
() + .AddConstructor () + ; + return tid; + +} + +void +UanHeaderRcRts::SetFrameNo (uint8_t no) +{ + m_frameNo = no; +} + +void +UanHeaderRcRts::SetNoFrames (uint8_t no) +{ + m_noFrames = no; +} + +void +UanHeaderRcRts::SetLength (uint16_t length) +{ + m_length = length; +} +void +UanHeaderRcRts::SetTimeStamp (Time timeStamp) +{ + m_timeStamp = timeStamp; +} + +void +UanHeaderRcRts::SetRetryNo (uint8_t no) +{ + m_retryNo = no; +} +uint8_t +UanHeaderRcRts::GetNoFrames () const +{ + return m_noFrames; +} + +uint16_t +UanHeaderRcRts::GetLength () const +{ + return m_length; +} + +Time +UanHeaderRcRts::GetTimeStamp (void) const +{ + return m_timeStamp; +} + +uint8_t +UanHeaderRcRts::GetRetryNo (void) const +{ + return m_retryNo; +} + +uint8_t +UanHeaderRcRts::GetFrameNo (void) const +{ + return m_frameNo; +} + +uint32_t +UanHeaderRcRts::GetSerializedSize (void) const +{ + return 1 + 1 + 1 + 4 + 2; +} + +void +UanHeaderRcRts::Serialize (Buffer::Iterator start) const +{ + start.WriteU8 (m_frameNo); + start.WriteU8 (m_retryNo); + start.WriteU8 (m_noFrames); + start.WriteU16 (m_length); + start.WriteU32 ((uint32_t)(m_timeStamp.GetSeconds () * 1000.0 + 0.5)); + // start.WriteU16(uint16_t (m_timeStamp.GetSeconds ()*1000)); +} + +uint32_t +UanHeaderRcRts::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator rbuf = start; + m_frameNo = rbuf.ReadU8 (); + m_retryNo = rbuf.ReadU8 (); + m_noFrames = rbuf.ReadU8 (); + m_length = rbuf.ReadU16 (); + m_timeStamp = Seconds ( ((double) rbuf.ReadU32 ()) / 1000.0 ); + // m_timeStamp = Seconds ( rbuf.ReadU16 ()/1000 ); + return rbuf.GetDistanceFrom (start); +} + +void +UanHeaderRcRts::Print (std::ostream &os) const +{ + os << "Frame #=" << (uint32_t) m_frameNo << " Retry #=" << (uint32_t) m_retryNo << " Num Frames=" << (uint32_t) m_noFrames << "Length=" << m_length << " Time Stamp=" << m_timeStamp.GetSeconds (); +} + +TypeId +UanHeaderRcRts::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} + + + + +UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal () + : Header (), + m_retryRate (0), + m_rateNum (0) +{ + +} + +UanHeaderRcCtsGlobal::UanHeaderRcCtsGlobal (Time wt, Time ts, uint16_t rate, uint16_t retryRate) + : Header (), + m_timeStampTx (ts), + m_winTime (wt), + m_retryRate (retryRate), + m_rateNum (rate) +{ + +} + +UanHeaderRcCtsGlobal::~UanHeaderRcCtsGlobal () +{ + +} + +TypeId +UanHeaderRcCtsGlobal::GetTypeId () +{ + static TypeId tid = TypeId ("ns3::UanHeaderRcCtsGlobal") + .SetParent
() + .AddConstructor () + ; + return tid; + +} + + +void +UanHeaderRcCtsGlobal::SetRateNum (uint16_t rate) +{ + m_rateNum = rate; +} + +void +UanHeaderRcCtsGlobal::SetRetryRate (uint16_t rate) +{ + m_retryRate = rate; +} + +void +UanHeaderRcCtsGlobal::SetWindowTime (Time t) +{ + m_winTime = t; +} + +void +UanHeaderRcCtsGlobal::SetTxTimeStamp (Time t) +{ + m_timeStampTx = t; +} + +Time +UanHeaderRcCtsGlobal::GetWindowTime (void) const +{ + return m_winTime; +} + +Time +UanHeaderRcCtsGlobal::GetTxTimeStamp (void) const +{ + return m_timeStampTx; +} + +uint16_t +UanHeaderRcCtsGlobal::GetRetryRate (void) const +{ + return m_retryRate; +} + +uint16_t +UanHeaderRcCtsGlobal::GetRateNum (void) const +{ + return m_rateNum; +} +uint32_t +UanHeaderRcCtsGlobal::GetSerializedSize (void) const +{ + return 4 + 4 + 2 + 2; +} + +void +UanHeaderRcCtsGlobal::Serialize (Buffer::Iterator start) const +{ + start.WriteU16 (m_rateNum); + start.WriteU16 (m_retryRate); + start.WriteU32 ( (uint32_t)(m_timeStampTx.GetSeconds () * 1000.0 + 0.5)); + start.WriteU32 ( (uint32_t)(m_winTime.GetSeconds () * 1000.0 + 0.5)); +} + +uint32_t +UanHeaderRcCtsGlobal::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator rbuf = start; + m_rateNum = rbuf.ReadU16 (); + m_retryRate = rbuf.ReadU16 (); + m_timeStampTx = Seconds ( ( (double) rbuf.ReadU32 ()) / 1000.0 ); + m_winTime = Seconds ( ( (double) rbuf.ReadU32 ()) / 1000.0 ); + return rbuf.GetDistanceFrom (start); + +} + +void +UanHeaderRcCtsGlobal::Print (std::ostream &os) const +{ + os << "CTS Global (Rate #=" << m_rateNum << ", Retry Rate=" << m_retryRate << ", TX Time=" << m_timeStampTx.GetSeconds () << ", Win Time=" << m_winTime.GetSeconds () << ")"; +} + +TypeId +UanHeaderRcCtsGlobal::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} + +UanHeaderRcCts::UanHeaderRcCts () + : Header (), + m_frameNo (0), + m_timeStampRts (Seconds (0)), + m_retryNo (0), + m_delay (Seconds (0)), + m_address (UanAddress::GetBroadcast ()) +{ + +} + +UanHeaderRcCts::UanHeaderRcCts (uint8_t frameNo, uint8_t retryNo, Time ts, Time delay, UanAddress addr) + : Header (), + m_frameNo (frameNo), + m_timeStampRts (ts), + m_retryNo (retryNo), + m_delay (delay), + m_address (addr) +{ + +} + +UanHeaderRcCts::~UanHeaderRcCts () +{ + +} + +TypeId +UanHeaderRcCts::GetTypeId () +{ + static TypeId tid = TypeId ("ns3::UanHeaderRcCts") + .SetParent
() + .AddConstructor () + ; + return tid; + +} + +void +UanHeaderRcCts::SetFrameNo (uint8_t frameNo) +{ + m_frameNo = frameNo; +} + +void +UanHeaderRcCts::SetRtsTimeStamp (Time timeStamp) +{ + m_timeStampRts = timeStamp; +} + + +void +UanHeaderRcCts::SetDelayToTx (Time delay) +{ + m_delay = delay; +} + +void +UanHeaderRcCts::SetRetryNo (uint8_t no) +{ + m_retryNo = no; +} + +void +UanHeaderRcCts::SetAddress (UanAddress addr) +{ + m_address = addr; +} +uint8_t +UanHeaderRcCts::GetFrameNo () const +{ + return m_frameNo; +} + +Time +UanHeaderRcCts::GetRtsTimeStamp (void) const +{ + return m_timeStampRts; +} + +Time +UanHeaderRcCts::GetDelayToTx (void) const +{ + return m_delay; +} + +uint8_t +UanHeaderRcCts::GetRetryNo () const +{ + return m_retryNo; +} + +UanAddress +UanHeaderRcCts::GetAddress () const +{ + return m_address; +} + +uint32_t +UanHeaderRcCts::GetSerializedSize (void) const +{ + return 1 + 1 + 1 + 4 + 4; +} + + +void +UanHeaderRcCts::Serialize (Buffer::Iterator start) const +{ + start.WriteU8 (m_address.GetAsInt ()); + start.WriteU8 (m_frameNo); + start.WriteU8 (m_retryNo); + start.WriteU32 ((uint32_t)(m_timeStampRts.GetSeconds () * 1000.0 + 0.5)); + start.WriteU32 ((uint32_t)(m_delay.GetSeconds () * 1000.0 + 0.5)); +} + +uint32_t +UanHeaderRcCts::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator rbuf = start; + m_address = UanAddress (rbuf.ReadU8 ()); + m_frameNo = rbuf.ReadU8 (); + m_retryNo = rbuf.ReadU8 (); + m_timeStampRts = Seconds ( ( (double) rbuf.ReadU32 ()) / 1000.0 ); + m_delay = Seconds ( ( (double) rbuf.ReadU32 ()) / 1000.0 ); + + return rbuf.GetDistanceFrom (start); +} + +void +UanHeaderRcCts::Print (std::ostream &os) const +{ + os << "CTS (Addr=" << m_address << " Frame #=" << (uint32_t) m_frameNo << " Retry #=" << (uint32_t) m_retryNo << " RTS Rx Timestamp=" << m_timeStampRts.GetSeconds () << " Delay until TX=" << m_delay.GetSeconds () << ")"; +} + +TypeId +UanHeaderRcCts::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} + +UanHeaderRcAck::UanHeaderRcAck () + : m_frameNo (0) +{ +} + +UanHeaderRcAck::~UanHeaderRcAck () +{ + m_nackedFrames.clear (); +} + +TypeId +UanHeaderRcAck::GetTypeId () +{ + static TypeId tid = TypeId ("ns3::UanHeaderRcAck") + .SetParent
() + .AddConstructor () + ; + return tid; +} + +void +UanHeaderRcAck::SetFrameNo (uint8_t noFrames) +{ + m_frameNo = noFrames; +} + +void +UanHeaderRcAck::AddNackedFrame (uint8_t frame) +{ + m_nackedFrames.insert (frame); +} + +const std::set & +UanHeaderRcAck::GetNackedFrames (void) const +{ + return m_nackedFrames; +} + +uint8_t +UanHeaderRcAck::GetFrameNo (void) const +{ + return m_frameNo; +} + +uint8_t +UanHeaderRcAck::GetNoNacks (void) const +{ + return m_nackedFrames.size (); +} + +uint32_t +UanHeaderRcAck::GetSerializedSize (void) const +{ + return 1 + 1 + GetNoNacks (); +} + +void +UanHeaderRcAck::Serialize (Buffer::Iterator start) const +{ + start.WriteU8 (m_frameNo); + start.WriteU8 (GetNoNacks ()); + std::set::iterator it = m_nackedFrames.begin (); + for (; it != m_nackedFrames.end (); it++) + { + start.WriteU8 (*it); + } +} + +uint32_t +UanHeaderRcAck::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator rbuf = start; + m_frameNo = rbuf.ReadU8 (); + uint8_t noAcks = rbuf.ReadU8 (); + m_nackedFrames.clear (); + for (uint32_t i = 0; i < noAcks; i++) + { + m_nackedFrames.insert (rbuf.ReadU8 ()); + } + return rbuf.GetDistanceFrom (start); +} + +void +UanHeaderRcAck::Print (std::ostream &os) const +{ + os << "# Frames=" << (uint32_t) m_frameNo << " # nacked=" << (uint32_t) GetNoNacks () << " Nacked: "; + if (GetNoNacks () > 0) + { + std::set::iterator it = m_nackedFrames.begin (); + os << (uint32_t) *it; + it++; + for (; it != m_nackedFrames.end (); it++) + { + os << ", " << (uint32_t) *it; + } + } +} + +TypeId +UanHeaderRcAck::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} + +} // namespace ns3 diff --git a/src/devices/uan/uan-header-rc.h b/src/devices/uan/uan-header-rc.h new file mode 100644 index 000000000..4ffccf1b9 --- /dev/null +++ b/src/devices/uan/uan-header-rc.h @@ -0,0 +1,375 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + + +#ifndef UANHEADERRC_H +#define UANHEADERRC_H + +#include "ns3/header.h" +#include "ns3/nstime.h" +#include "ns3/uan-address.h" + +#include + +namespace ns3 { + +/** + * \class UanHeaderRcData + * + * \brief Extra data header information + * + * Adds prop. delay measure, and frame number info to + * transmitted data packet + */ +class UanHeaderRcData : public ns3::Header +{ +public: + UanHeaderRcData (); + /** + * \param frameNum Data frame # of reservation being transmitted + * \param propDelay Measured propagation delay found in handshaking + * \note Prop. delay is transmitted with 16 bits and ms accuracy + */ + UanHeaderRcData (uint8_t frameNum, Time propDelay); + virtual ~UanHeaderRcData (); + + static TypeId GetTypeId (void); + + /** + * \param frameNum Data frame # of reservation being transmitted + */ + void SetFrameNo (uint8_t frameNum); + /** + * \param propDelay Measured propagation delay found in handshaking + * \note Prop. delay is transmitted with 16 bits and ms accuracy + */ + void SetPropDelay (Time propDelay); + /** + * \returns Data frame # of reservation being transmitted + */ + uint8_t GetFrameNo (void) const; + /** + * \returns Measured propagation delay found in handshaking + * \note Prop. delay is transmitted with 16 bits and ms accuracy + */ + Time GetPropDelay (void) const; + + // Inherrited methods + virtual uint32_t GetSerializedSize (void) const; + virtual void Serialize (Buffer::Iterator start) const; + virtual uint32_t Deserialize (Buffer::Iterator start); + virtual void Print (std::ostream &os) const; + virtual TypeId GetInstanceTypeId (void) const; + +private: + uint8_t m_frameNo; + Time m_propDelay; +}; + +/** + * \class UanHeaderRcRts + * + * \brief RTS header + * + * Contains frame #, retry #, # frames, length, and timestamp + */ +class UanHeaderRcRts : public ns3::Header +{ +public: + UanHeaderRcRts (); + /** + * \param frameNo Reservation frame # + * \param retryNo Retry # of RTS packet + * \param noFrames # of data frames in reservation + * \param length # of bytes (including headers) in data + * \param ts RTS TX timestamp + * \note Timestamp is serialized into 32 bits with ms accuracy + */ + UanHeaderRcRts (uint8_t frameNo, uint8_t retryNo, uint8_t noFrames, uint16_t length, Time ts); + virtual ~UanHeaderRcRts (); + + static TypeId GetTypeId (void); + + /** + * \param fno TX frame # + */ + void SetFrameNo (uint8_t fno); + /** + * \param no Number of data frames included in this reservation request + */ + void SetNoFrames (uint8_t no); + /** + * \param timeStamp RTS transmission time + */ + void SetTimeStamp (Time timeStamp); + /** + * \param length Total number of data bytes in reservation (including headers) + * \note Timestamp is serialized with 32 bits in ms precision + */ + void SetLength (uint16_t length); + /** + * \param no Retry number of this RTS (Used to match timestamp to correctly received RTS) + */ + void SetRetryNo (uint8_t no); + + /** + * \returns Frame # + */ + uint8_t GetFrameNo (void) const; + /** + * \returns # of data frames in reservation + */ + uint8_t GetNoFrames (void) const; + /** + * \returns TX time of the RTS packet + * \note Timestamp is serialized with 32 bits in ms precision + */ + Time GetTimeStamp (void) const; + /** + * \returns Total # of bytes in data packets for reservation (including headers) + */ + uint16_t GetLength (void) const; + /** + * \returns Retry number of this RTS packet + */ + uint8_t GetRetryNo (void) const; + + // Inherrited methods + virtual uint32_t GetSerializedSize (void) const; + virtual void Serialize (Buffer::Iterator start) const; + virtual uint32_t Deserialize (Buffer::Iterator start); + virtual void Print (std::ostream &os) const; + virtual TypeId GetInstanceTypeId (void) const; + +private: + uint8_t m_frameNo; + uint8_t m_noFrames; + uint16_t m_length; + Time m_timeStamp; + uint8_t m_retryNo; +}; + +/** + * \class UanHeaderRcCtsGlobal + * + * \brief Cycle broadcast information for + */ + + +class UanHeaderRcCtsGlobal : public Header +{ +public: + /** + * \brief Create UanHeaderRcCtsGlobal with fields zeroed out + */ + UanHeaderRcCtsGlobal (); + /** + * \brief Create object with given window time, time stamp, rate, and retry rate. + * \param wt Window time + * \param ts Timestamp + * \param rate Rate number + * \param retryRate Retry rate value + */ + UanHeaderRcCtsGlobal (Time wt, Time ts, uint16_t rate, uint16_t retryRate); + ~UanHeaderRcCtsGlobal (); + + static TypeId GetTypeId (); + + /** + * \param rate Rate number corresponding to data rate of current cycle + */ + void SetRateNum (uint16_t rate); + /** + * \param rate Retry rate number for current cycle + */ + void SetRetryRate (uint16_t rate); + /** + * \param t Time duration following blocking time to allow RTS transmissions + */ + void SetWindowTime (Time t); + + /** + * \param timeStamp Time of CTS transmission + */ + void SetTxTimeStamp (Time timeStamp); + + /** + * \returns Rate # corresponding to data rate of current cycle + */ + uint16_t GetRateNum (void) const; + /** + * \returns retry rate # of retry rate for current cycle + */ + uint16_t GetRetryRate (void) const; + /** + * \returns Time duration after blocking time allowed for RTS transmissions + */ + Time GetWindowTime (void) const; + /** + * \returns Timestamp of CTS transmission + */ + Time GetTxTimeStamp (void) const; + + // Inherrited methods + virtual uint32_t GetSerializedSize (void) const; + virtual void Serialize (Buffer::Iterator start) const; + virtual uint32_t Deserialize (Buffer::Iterator start); + virtual void Print (std::ostream &os) const; + virtual TypeId GetInstanceTypeId (void) const; + +private: + Time m_timeStampTx; + Time m_winTime; + uint16_t m_retryRate; + uint16_t m_rateNum; +}; +/** + * \class UanHeaderRcCts + * + * \brief CTS header + * + * Includes RTS RX time, CTS TX time, delay until TX, RTS blocking period, + * RTS tx period, rate #, and retry rate # + */ + +class UanHeaderRcCts : public ns3::Header +{ +public: + UanHeaderRcCts (); + /** + * \param frameNo Resrvation frame # being cleared + * \param retryNo Retry # of received RTS packet + * \param rtsTs RX time of RTS packet at gateway + * \param delay Delay until transmission + * \param addr Destination of CTS packet + * \note Times are serialized, with ms precission, into 32 bit fields. + */ + UanHeaderRcCts (uint8_t frameNo, uint8_t retryNo, Time rtsTs, Time delay, UanAddress addr); + virtual ~UanHeaderRcCts (); + + static TypeId GetTypeId (void); + + /** + * \param frameNo Frame # of RTS being cleared + */ + void SetFrameNo (uint8_t frameNo); + /** + * \param timeStamp Time of RTS reception + */ + void SetRtsTimeStamp (Time timeStamp); + /** + * \param delay Time duration, from CTS TX, before first data frame arrival + */ + void SetDelayToTx (Time delay); + /** + * \param no Retry number of RTS frame being cleared + */ + void SetRetryNo (uint8_t no); + /** + * \param addr Destination for scheduling info + */ + void SetAddress (UanAddress addr); + + /** + * \returns Frame # of RTS being cleared + */ + uint8_t GetFrameNo (void) const; + /** + * \returns RX time of RTS being cleared + */ + Time GetRtsTimeStamp (void) const; + /** + * \returns Delay from TX time of CTS packet until arrival of first data frame + */ + Time GetDelayToTx (void) const; + /** + * \returns Retry # of RTS packet being cleared + */ + uint8_t GetRetryNo (void) const; + /** + * \returns Destination for scheduling info + */ + UanAddress GetAddress (void) const; + + // Inherrited methods + virtual uint32_t GetSerializedSize (void) const; + virtual void Serialize (Buffer::Iterator start) const; + virtual uint32_t Deserialize (Buffer::Iterator start); + virtual void Print (std::ostream &os) const; + virtual TypeId GetInstanceTypeId (void) const; + +private: + uint8_t m_frameNo; + Time m_timeStampRts; + uint8_t m_retryNo; + Time m_delay; + UanAddress m_address; +}; + +/** + * \class UanHeaderRcAck + * \brief Header used for ACK packets by protocol ns3::UanMacRc + */ +class UanHeaderRcAck : public Header +{ +public: + UanHeaderRcAck (); + virtual ~UanHeaderRcAck (); + + static TypeId GetTypeId (void); + + /** + * \param frameNo Frame # of reservation being acknowledged + */ + void SetFrameNo (uint8_t frameNo); + /** + * \param frame Data frame # being nacked + */ + void AddNackedFrame (uint8_t frame); + + /** + * \returns Set of nacked frames + */ + const std::set &GetNackedFrames (void) const; + /** + * \returns Reservation frame # being acknowledged. + */ + uint8_t GetFrameNo (void) const; + /** + * \returns Number of data frames being NACKED + */ + uint8_t GetNoNacks (void) const; + + // Inherrited methods + virtual uint32_t GetSerializedSize (void) const; + virtual void Serialize (Buffer::Iterator start) const; + virtual uint32_t Deserialize (Buffer::Iterator start); + virtual void Print (std::ostream &os) const; + virtual TypeId GetInstanceTypeId (void) const; + +private: + uint8_t m_frameNo; + std::set m_nackedFrames; + +}; + +} + +#endif // UANHEADERRC_H diff --git a/src/devices/uan/uan-mac-aloha.cc b/src/devices/uan/uan-mac-aloha.cc new file mode 100644 index 000000000..6ef1d7ead --- /dev/null +++ b/src/devices/uan/uan-mac-aloha.cc @@ -0,0 +1,137 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#include "uan-mac-aloha.h" +#include "uan-tx-mode.h" +#include "uan-address.h" +#include "ns3/log.h" +#include "uan-phy.h" +#include "uan-header-common.h" + +#include +NS_LOG_COMPONENT_DEFINE ("UanMacAloha"); + + +namespace ns3 +{ + +NS_OBJECT_ENSURE_REGISTERED (UanMacAloha); + +UanMacAloha::UanMacAloha () + : UanMac () +{ +} + +UanMacAloha::~UanMacAloha () +{ +} + +void +UanMacAloha::DoDispose () +{ + m_phy = 0; + UanMac::DoDispose (); +} + +TypeId +UanMacAloha::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::UanMacAloha") + .SetParent () + .AddConstructor () + ; + return tid; +} + +Address +UanMacAloha::GetAddress (void) +{ + return m_address; +} + +void +UanMacAloha::SetAddress (UanAddress addr) +{ + m_address=addr; +} +bool +UanMacAloha::Enqueue (Ptr packet, const Address &dest, uint16_t protocolNumber) +{ + NS_LOG_DEBUG ("" << Simulator::Now ().GetSeconds () << " MAC " << UanAddress::ConvertFrom (GetAddress ()) << " Queueing packet for " << UanAddress::ConvertFrom (dest)); + + if (!m_phy->IsStateTx ()) + { + UanAddress src = UanAddress::ConvertFrom (GetAddress ()); + UanAddress udest = UanAddress::ConvertFrom (dest); + + UanHeaderCommon header; + header.SetSrc (src); + header.SetDest (udest); + header.SetType (0); + + packet->AddHeader (header); + m_phy->SendPacket (packet, protocolNumber); + return true; + } + else + return false; +} + +void +UanMacAloha::SetForwardUpCb (Callback, const UanAddress& > cb) +{ + m_forUpCb = cb; +} +void +UanMacAloha::AttachPhy (Ptr phy) +{ + m_phy = phy; + m_phy->SetReceiveOkCallback (MakeCallback (&UanMacAloha::RxPacketGood, this)); + m_phy->SetReceiveErrorCallback (MakeCallback (&UanMacAloha::RxPacketError, this)); + +} +void +UanMacAloha::RxPacketGood (Ptr pkt, double sinr, UanTxMode txMode) +{ + UanHeaderCommon header; + pkt->RemoveHeader (header); + NS_LOG_DEBUG ("Receiving packet from " << header.GetSrc () << " For " << header.GetDest ()); + + if (header.GetDest () == GetAddress () || header.GetDest () == UanAddress::GetBroadcast ()) + { + m_forUpCb (pkt, header.GetSrc ()); + } + +} + +void +UanMacAloha::RxPacketError (Ptr pkt, double sinr) +{ + NS_LOG_DEBUG ("" << Simulator::Now () << " MAC " << UanAddress::ConvertFrom (GetAddress ()) << " Received packet in error with sinr " << sinr); +} + +Address +UanMacAloha::GetBroadcast (void) const +{ + UanAddress broadcast (255); + return broadcast; +} + +} diff --git a/src/devices/uan/uan-mac-aloha.h b/src/devices/uan/uan-mac-aloha.h new file mode 100644 index 000000000..fcd4c400b --- /dev/null +++ b/src/devices/uan/uan-mac-aloha.h @@ -0,0 +1,83 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANMACALOHA_H +#define UANMACALOHA_H + +#include "uan-mac.h" +#include "uan-address.h" + +namespace ns3 +{ + + +class UanPhy; +class UanTxMode; + +/** + * \class UanMacAloha + * \brief ALOHA MAC Protocol + * + * The simplest MAC protocol for wireless networks. Packets enqueued + * are immediately transmitted. This MAC attaches a UanHeaderCommon + * to outgoing packets for address information. (The type field is not used) + */ +class UanMacAloha : public ns3::UanMac +{ +public: + UanMacAloha (); + virtual ~UanMacAloha (); + static TypeId GetTypeId (void); + + + //Inheritted functions + Address GetAddress (void); + virtual void SetAddress (UanAddress addr); + virtual bool Enqueue (Ptr pkt, const Address &dest, uint16_t protocolNumber); + virtual void SetForwardUpCb (Callback, const UanAddress& > cb); + virtual void AttachPhy (Ptr phy); + virtual Address GetBroadcast (void) const; + +private: + UanAddress m_address; + Ptr m_phy; + Callback, const UanAddress& > m_forUpCb; + + /** + * \brief Receive packet from lower layer (passed to PHY as callback) + * \param pkt Packet being received + * \param sinr SINR of received packet + * \param txMode Mode of received packet + */ + void RxPacketGood (Ptr pkt, double sinr, UanTxMode txMode); + + /** + * \brief Packet received at lower layer in error + * \param pkt Packet received in error + * \param sinr SINR of received packet + */ + void RxPacketError (Ptr pkt, double sinr); +protected: + virtual void DoDispose (); +}; + +} + +#endif // UANMACALOHA_H diff --git a/src/devices/uan/uan-mac-cw.cc b/src/devices/uan/uan-mac-cw.cc new file mode 100644 index 000000000..99e331291 --- /dev/null +++ b/src/devices/uan/uan-mac-cw.cc @@ -0,0 +1,371 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#include "uan-mac-cw.h" +#include "ns3/attribute.h" +#include "ns3/uinteger.h" +#include "ns3/double.h" +#include "ns3/nstime.h" +#include "ns3/random-variable.h" +#include "ns3/uan-header-common.h" +#include "ns3/trace-source-accessor.h" +#include "ns3/log.h" + +NS_LOG_COMPONENT_DEFINE ("UanMacCw"); + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (UanMacCw); + +UanMacCw::UanMacCw () + : UanMac (), + m_phy (0), + m_pktTx (0), + m_state (IDLE) + +{ +} + +UanMacCw::~UanMacCw () +{ +} + +void +UanMacCw::DoDispose () +{ + m_pktTx = 0; + m_phy = 0; + m_sendEvent.Cancel (); + m_txEndEvent.Cancel (); + UanMac::DoDispose (); +} + +TypeId +UanMacCw::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::UanMacCw") + .SetParent () + .AddConstructor () + .AddAttribute ("CW", + "The MAC parameter CW", + UintegerValue (10), + MakeUintegerAccessor (&UanMacCw::m_cw), + MakeUintegerChecker ()) + .AddAttribute ("SlotTime", + "Time slot duration for MAC backoff", + TimeValue (MilliSeconds (20)), + MakeTimeAccessor (&UanMacCw::m_slotTime), + MakeTimeChecker ()) + .AddTraceSource ("Enqueue", + "A packet arrived at the MAC for transmission", + MakeTraceSourceAccessor (&UanMacCw::m_enqueueLogger)) + .AddTraceSource ("Dequeue", + "A was passed down to the PHY from the MAC", + MakeTraceSourceAccessor (&UanMacCw::m_dequeueLogger)) + .AddTraceSource ("RX", + "A packet was destined for this MAC and was received", + MakeTraceSourceAccessor (&UanMacCw::m_rxLogger)) + + ; + return tid; +} + +Address +UanMacCw::GetAddress () +{ + return this->m_address; +} + +void +UanMacCw::SetAddress (UanAddress addr) +{ + m_address = addr; +} + +bool +UanMacCw::Enqueue (Ptr packet, const Address &dest, uint16_t protocolNumber) +{ + + switch (m_state) + { + case CCABUSY: + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " MAC " << GetAddress () << " Starting enqueue CCABUSY"); + if (m_txEndEvent.IsRunning () == TX) + { + NS_LOG_DEBUG ("State is TX"); + } + else + { + NS_LOG_DEBUG ("State is not TX"); + } + + NS_ASSERT (m_phy->GetTransducer ()->GetArrivalList ().size () >= 1 || m_phy->IsStateTx ()); + return false; + case RUNNING: + NS_LOG_DEBUG ("MAC " << GetAddress () << " Starting enqueue RUNNING"); + NS_ASSERT (m_phy->GetTransducer ()->GetArrivalList ().size () == 0 && !m_phy->IsStateTx ()); + return false; + case TX: + case IDLE: + { + NS_ASSERT (!m_pktTx); + + UanHeaderCommon header; + header.SetDest (UanAddress::ConvertFrom (dest)); + header.SetSrc (m_address); + header.SetType (0); + packet->AddHeader (header); + + m_enqueueLogger (packet, protocolNumber); + + if (m_phy->IsStateBusy ()) + { + m_pktTx = packet; + m_pktTxProt = protocolNumber; + m_state = CCABUSY; + UniformVariable rv (0,m_cw); + uint32_t cw = (uint32_t) rv.GetValue (); + m_savedDelayS = Seconds ((double)(cw) * m_slotTime.GetSeconds ()); + m_sendTime = Simulator::Now () + m_savedDelayS; + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << ": Addr " << GetAddress () << ": Enqueuing new packet while busy: (Chose CW " << cw << ", Sending at " << m_sendTime.GetSeconds () << " Packet size: " << packet->GetSize ()); + NS_ASSERT (m_phy->GetTransducer ()->GetArrivalList ().size () >= 1 || m_phy->IsStateTx ()); + } + else + { + NS_ASSERT (m_state != TX); + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << ": Addr " << GetAddress () << ": Enqueuing new packet while idle (sending)"); + NS_ASSERT (m_phy->GetTransducer ()->GetArrivalList ().size () == 0 && !m_phy->IsStateTx ()); + m_state = TX; + m_phy->SendPacket (packet,protocolNumber); + + } + break; + } + default: + NS_LOG_DEBUG ("MAC " << GetAddress () << " Starting enqueue SOMETHING ELSE"); + return false; + } + + return true; + + +} + +void +UanMacCw::SetForwardUpCb (Callback, const UanAddress&> cb) +{ + m_forwardUpCb = cb; +} + +void +UanMacCw::AttachPhy (Ptr phy) +{ + m_phy = phy; + m_phy->SetReceiveOkCallback (MakeCallback (&UanMacCw::PhyRxPacketGood, this)); + m_phy->SetReceiveErrorCallback (MakeCallback (&UanMacCw::PhyRxPacketError, this)); + m_phy->RegisterListener (this); +} + +Address +UanMacCw::GetBroadcast (void) const +{ + return UanAddress::GetBroadcast (); +} + + +void +UanMacCw::NotifyRxStart (void) +{ + if (m_state == RUNNING) + { + + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << ": Switching to channel busy"); + SaveTimer (); + m_state = CCABUSY; + } + +} +void +UanMacCw::NotifyRxEndOk (void) +{ + if (m_state == CCABUSY && !m_phy->IsStateCcaBusy ()) + { + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << ": Switching to channel idle"); + m_state = RUNNING; + StartTimer (); + + } + +} +void +UanMacCw::NotifyRxEndError (void) +{ + if (m_state == CCABUSY && !m_phy->IsStateCcaBusy ()) + { + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << ": Switching to channel idle"); + m_state = RUNNING; + StartTimer (); + + } + +} +void +UanMacCw::NotifyCcaStart (void) +{ + if (m_state == RUNNING) + { + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << ": Switching to channel busy"); + m_state = CCABUSY; + SaveTimer (); + + } + +} +void +UanMacCw::NotifyCcaEnd (void) +{ + if (m_state == CCABUSY) + { + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << ": Switching to channel idle"); + m_state = RUNNING; + StartTimer (); + + } + +} +void +UanMacCw::NotifyTxStart (Time duration) +{ + + if (m_txEndEvent.IsRunning ()) + { + Simulator::Cancel (m_txEndEvent); + } + + m_txEndEvent = Simulator::Schedule (duration, &UanMacCw::EndTx, this); + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " scheduling TxEndEvent with delay " << duration.GetSeconds ()); + if (m_state == RUNNING) + { + NS_ASSERT (0); + m_state = CCABUSY; + SaveTimer (); + + } + +} + +void +UanMacCw::EndTx (void) +{ + NS_ASSERT (m_state == TX || m_state == CCABUSY); + if (m_state == TX) + { + m_state = IDLE; + } + else if (m_state == CCABUSY) + { + if (m_phy->IsStateIdle ()) + { + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << ": Switching to channel idle (After TX!)"); + m_state = RUNNING; + StartTimer (); + } + } + else + { + NS_FATAL_ERROR ("In strange state at UanMacCw EndTx"); + } +} +void +UanMacCw::SetCw (uint32_t cw) +{ + m_cw = cw; +} +void +UanMacCw::SetSlotTime (Time duration) +{ + m_slotTime = duration; +} +uint32_t +UanMacCw::GetCw (void) +{ + return m_cw; +} +Time +UanMacCw::GetSlotTime (void) +{ + return m_slotTime; +} +void +UanMacCw::PhyRxPacketGood (Ptr packet, double sinr, UanTxMode mode) +{ + UanHeaderCommon header; + packet->RemoveHeader (header); + + if (header.GetDest () == m_address) + { + m_forwardUpCb (packet, header.GetSrc ()); + } +} +void +UanMacCw::PhyRxPacketError (Ptr packet, double sinr) +{ + +} +void +UanMacCw::SaveTimer (void) +{ + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << " Saving timer (Delay = " << (m_savedDelayS = m_sendTime - Simulator::Now ()).GetSeconds () << ")"); + NS_ASSERT (m_pktTx); + NS_ASSERT (m_sendTime >= Simulator::Now ()); + m_savedDelayS = m_sendTime - Simulator::Now (); + Simulator::Cancel (m_sendEvent); + + +} +void +UanMacCw::StartTimer (void) +{ + + m_sendTime = Simulator::Now () + m_savedDelayS; + if (m_sendTime == Simulator::Now ()) + { + SendPacket (); + } + else + { + m_sendEvent = Simulator::Schedule (m_savedDelayS, &UanMacCw::SendPacket, this); + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << " Starting timer (New send time = " << this->m_sendTime.GetSeconds () << ")"); + } +} + +void +UanMacCw::SendPacket (void) +{ + NS_LOG_DEBUG ("Time " << Simulator::Now ().GetSeconds () << " Addr " << GetAddress () << " Transmitting "); + NS_ASSERT (m_state == RUNNING); + m_state = TX; + m_phy->SendPacket (m_pktTx,m_pktTxProt); + m_pktTx = 0; + m_sendTime = Seconds (0); + m_savedDelayS = Seconds (0); +} + +} // namespace ns3 diff --git a/src/devices/uan/uan-mac-cw.h b/src/devices/uan/uan-mac-cw.h new file mode 100644 index 000000000..45d2f54bb --- /dev/null +++ b/src/devices/uan/uan-mac-cw.h @@ -0,0 +1,126 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANMACCW_H +#define UANMACCW_H + +#include "ns3/uan-mac.h" +#include "ns3/nstime.h" +#include "ns3/simulator.h" +#include "ns3/uan-phy.h" +#include "ns3/uan-tx-mode.h" +#include "ns3/uan-address.h" + + +namespace ns3 { + +/** + * \class UanMacCw + * \brief CW-MAC A MAC protocol similar in idea to the 802.11 DCF with constant backoff window + * + * For more information on this MAC protocol, see: + * Parrish, N.; Tracy, L.; Roy, S.; Arabshahi, P.; Fox, W., + * "System Design Considerations for Undersea Networks: Link and Multiple Access Protocols," + * Selected Areas in Communications, IEEE Journal on , vol.26, no.9, pp.1720-1730, December 2008 + */ +class UanMacCw : public ns3::UanMac, + public ns3::UanPhyListener +{ +public: + UanMacCw (); + virtual ~UanMacCw (); + static TypeId GetTypeId (void); + + /** + * \param cw Contention window size + */ + virtual void SetCw (uint32_t cw); + /** + * \param duration Slot time duration + */ + virtual void SetSlotTime (Time duration); + /** + * \returns Contention window size + */ + virtual uint32_t GetCw (void); + /** + * \returns slot time duration + */ + virtual Time GetSlotTime (void); + + // Inherited methods + virtual Address GetAddress (); + virtual void SetAddress (UanAddress addr); + virtual bool Enqueue (Ptr pkt, const Address &dest, uint16_t protocolNumber); + virtual void SetForwardUpCb (Callback, const UanAddress&> cb); + virtual void AttachPhy (Ptr phy); + virtual Address GetBroadcast (void) const; + + // PHY listeners + /// Function called by UanPhy object to notify of packet reception + virtual void NotifyRxStart (void); + /// Function called by UanPhy object to notify of packet received successfully + virtual void NotifyRxEndOk (void); + /// Function called by UanPhy object to notify of packet received in error + virtual void NotifyRxEndError (void); + /// Function called by UanPhy object to notify of channel sensed busy + virtual void NotifyCcaStart (void); + /// Function called by UanPhy object to notify of channel no longer sensed busy + virtual void NotifyCcaEnd (void); + /// Function called by UanPhy object to notify of outgoing transmission start + virtual void NotifyTxStart (Time duration); +private: + typedef enum { + IDLE, CCABUSY, RUNNING, TX + } State; + + Callback , const UanAddress& > m_forwardUpCb; + UanAddress m_address; + Ptr m_phy; + TracedCallback, UanTxMode > m_rxLogger; + TracedCallback, uint16_t > m_enqueueLogger; + TracedCallback, uint16_t > m_dequeueLogger; + + // Mac parameters + uint32_t m_cw; + Time m_slotTime; + + // State variables + Time m_sendTime; + Time m_savedDelayS; + Ptr m_pktTx; + uint16_t m_pktTxProt; + EventId m_sendEvent; + EventId m_txEndEvent; + State m_state; + + void PhyRxPacketGood (Ptr packet, double sinr, UanTxMode mode); + void PhyRxPacketError (Ptr packet, double sinr); + void SaveTimer (void); + void StartTimer (void); + void SendPacket (void); + void EndTx (void); +protected: + virtual void DoDispose (); +}; + +} + +#endif // UANMACCW_H diff --git a/src/devices/uan/uan-mac-rc-gw.cc b/src/devices/uan/uan-mac-rc-gw.cc new file mode 100644 index 000000000..c2e584089 --- /dev/null +++ b/src/devices/uan/uan-mac-rc-gw.cc @@ -0,0 +1,718 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#include "uan-mac-rc-gw.h" +#include "uan-mac-rc.h" +#include "uan-header-common.h" +#include "uan-header-rc.h" +#include "uan-phy.h" +#include "uan-tx-mode.h" + +#include "ns3/assert.h" +#include "ns3/log.h" +#include "ns3/trace-source-accessor.h" +#include "ns3/nstime.h" +#include "ns3/double.h" +#include "ns3/uinteger.h" + +#include +#include +#include +#include +#include + +NS_LOG_COMPONENT_DEFINE ("UanMacRcGw"); + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (UanMacRcGw); + +bool +operator < (UanAddress &a, UanAddress &b) +{ + return a.GetAsInt () < b.GetAsInt (); +} + + +UanMacRcGw::UanMacRcGw () + : UanMac (), + m_state (IDLE), + m_currentRateNum (0) +{ + UanHeaderCommon ch; + UanHeaderRcRts rts; + UanHeaderRcCts cts; + UanHeaderRcAck ack; + UanHeaderRcCtsGlobal ctsg; + + m_rtsSize = ch.GetSerializedSize () + rts.GetSerializedSize (); + m_ctsSizeN = cts.GetSerializedSize (); + m_ctsSizeG = ch.GetSerializedSize () + ctsg.GetSerializedSize (); + m_ackSize = ch.GetSerializedSize () + ack.GetSerializedSize (); + + NS_LOG_DEBUG ("Gateway initialized"); +} + +UanMacRcGw::~UanMacRcGw () +{ +} + +void +UanMacRcGw::DoDispose () +{ + m_propDelay.clear (); + std::map::iterator it = m_ackData.begin (); + for (; it != m_ackData.end (); it++) + { + it->second.rxFrames.clear (); + } + m_ackData.clear (); + m_requests.clear (); + m_sortedRes.clear (); + UanMac::DoDispose (); +} +TypeId +UanMacRcGw::GetTypeId (void) +{ + TypeId tid = TypeId ("ns3::UanMacRcGw") + .SetParent () + .AddConstructor () + .AddAttribute ("MaxReservations", + "Maximum number of reservations to accept per cycle", + UintegerValue (10), + MakeUintegerAccessor (&UanMacRcGw::m_maxRes), + MakeUintegerChecker ()) + .AddAttribute ("NumberOfRates", + "Number of rates per Phy layer", + UintegerValue (1023), + MakeUintegerAccessor (&UanMacRcGw::m_numRates), + MakeUintegerChecker ()) + .AddAttribute ("RetryRate", + "Number of retry rates per second at non-gateway nodes", + DoubleValue (1 / 10.0), + MakeDoubleAccessor (&UanMacRcGw::m_retryRate), + MakeDoubleChecker ()) + .AddAttribute ("MaxPropDelay", + "Maximum propagation delay between gateway and non-gateway nodes", + TimeValue (Seconds (2)), + MakeTimeAccessor (&UanMacRcGw::m_maxDelta), + MakeTimeChecker ()) + .AddAttribute ("SIFS", + "Spacing between frames to account for timing error and processing delay", + TimeValue (Seconds (0.2)), + MakeTimeAccessor (&UanMacRcGw::m_sifs), + MakeTimeChecker ()) + .AddAttribute ("NumberOfNodes", + "Number of non-gateway nodes in this gateway's neighborhood", + UintegerValue (10), + MakeUintegerAccessor (&UanMacRcGw::m_numNodes), + MakeUintegerChecker ()) + .AddAttribute ("MinRetryRate", + "Smallest allowed RTS retry rate", + DoubleValue (0.01), + MakeDoubleAccessor (&UanMacRcGw::m_minRetryRate), + MakeDoubleChecker ()) + .AddAttribute ("RetryStep", + "Retry rate increment", + DoubleValue (0.01), + MakeDoubleAccessor (&UanMacRcGw::m_retryStep), + MakeDoubleChecker ()) + .AddAttribute ("NumberOfRetryRates", + "Number of retry rates", + UintegerValue (100), + MakeUintegerAccessor (&UanMacRcGw::m_numRetryRates), + MakeUintegerChecker ()) + .AddAttribute ("TotalRate", + "Total available channel rate in bps (for a single channel, without splitting reservation channel)", + UintegerValue (4096), + MakeUintegerAccessor (&UanMacRcGw::m_totalRate), + MakeUintegerChecker ()) + .AddAttribute ("RateStep", + "Increments available for rate assignment in bps", + UintegerValue (4), + MakeUintegerAccessor (&UanMacRcGw::m_rateStep), + MakeUintegerChecker ()) + .AddAttribute ("FrameSize", + "Size of data frames in bytes", + UintegerValue (1000), + MakeUintegerAccessor (&UanMacRcGw::m_frameSize), + MakeUintegerChecker ()) + .AddTraceSource ("RX", + "A packet was destined for and received at this MAC layer", + MakeTraceSourceAccessor (&UanMacRcGw::m_rxLogger)) + .AddTraceSource ("Cycle", + "Trace cycle statistics", + MakeTraceSourceAccessor (&UanMacRcGw::m_cycleLogger)) + + ; + + return tid; +} + +Address +UanMacRcGw::GetAddress (void) +{ + return m_address; +} + +void +UanMacRcGw::SetAddress (UanAddress addr) +{ + m_address = addr; +} + +bool +UanMacRcGw::Enqueue (Ptr packet, const Address &dest, uint16_t protocolNumber) +{ + NS_LOG_WARN ("RCMAC Gateway transmission to acoustic nodes is not yet implemented"); + return false; +} + +void +UanMacRcGw::SetForwardUpCb (Callback, const UanAddress&> cb) +{ + m_forwardUpCb = cb; +} + +void +UanMacRcGw::AttachPhy (Ptr phy) +{ + m_phy = phy; + phy->SetReceiveOkCallback (MakeCallback (&UanMacRcGw::ReceivePacket, this)); + phy->SetReceiveErrorCallback (MakeCallback (&UanMacRcGw::ReceiveError, this)); +} + +void +UanMacRcGw::ReceiveError (Ptr pkt, double sinr) +{ +} + +Address +UanMacRcGw::GetBroadcast (void) const +{ + return UanAddress::GetBroadcast (); +} + +void +UanMacRcGw::ReceivePacket (Ptr pkt, double sinr, UanTxMode mode) +{ + UanHeaderCommon ch; + pkt->PeekHeader (ch); + + if (ch.GetDest () == m_address || ch.GetDest () == UanAddress::GetBroadcast ()) + { + m_rxLogger (pkt, mode); + } + else + { + return; + } + + pkt->RemoveHeader (ch); + + switch (ch.GetType ()) + { + case UanMacRc::TYPE_DATA: + { + UanHeaderRcData dh; + pkt->RemoveHeader (dh); + m_propDelay[ch.GetSrc ()] = dh.GetPropDelay (); + if (m_ackData.find (ch.GetSrc ()) == m_ackData.end ()) + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GATEWAY Received unexpected data packet"); + } + else + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GW Received data packet from " << ch.GetSrc () << " length = " << pkt->GetSize ()); + m_ackData[ch.GetSrc ()].rxFrames.insert (dh.GetFrameNo ()); + } + m_forwardUpCb (pkt, ch.GetSrc ()); + } + break; + case UanMacRc::TYPE_GWPING: + case UanMacRc::TYPE_RTS: + if (m_state == CTSING) + { + return; + } + + { + UanHeaderRcRts rh; + pkt->RemoveHeader (rh); + + if (m_requests.find (ch.GetSrc ()) == m_requests.end ()) + { + Request req; + req.numFrames = rh.GetNoFrames (); + req.rxTime = Simulator::Now (); + req.frameNo = rh.GetFrameNo (); + req.retryNo = rh.GetRetryNo (); + req.length = rh.GetLength (); + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GW storing reservation from " << ch.GetSrc () << " with length " << req.length); + m_requests.insert (std::make_pair (ch.GetSrc (), req)); + std::map::iterator it = m_propDelay.find (ch.GetSrc ()); + if (it == m_propDelay.end ()) + { + m_sortedRes.insert (std::make_pair (m_maxDelta, ch.GetSrc ())); + } + else + { + m_sortedRes.insert (std::make_pair ( (*it).second, ch.GetSrc ())); + } + } + } + if (m_state == IDLE) + { + StartCycle (); + } + break; + case UanMacRc::TYPE_CTS: + NS_FATAL_ERROR ("Received CTS at GW. Currently only support single GW network!"); + break; + case UanMacRc::TYPE_ACK: + NS_FATAL_ERROR ("Received ACK at GW. Currently only support single GW network!"); + break; + default: + NS_FATAL_ERROR ("Received unknown packet at GW!"); + } +} + +void +UanMacRcGw::StartCycle (void) +{ + uint32_t numRts = m_sortedRes.size (); + + if (numRts) + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Simulator starting non-empty cycle"); + } + else + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Simulator starting EMPTY cycle"); + } + + // Calculate dataRate + uint32_t totalBytes = 0; + uint32_t totalFrames = 0; + double pDelay = 0; + if (numRts > 0) + { + std::map::iterator rit = m_requests.begin (); + for (; rit != m_requests.end (); rit++) + { + totalBytes += (*rit).second.length; + totalFrames += (*rit).second.numFrames; + } + pDelay = 2 * m_sortedRes.begin ()->first.GetSeconds (); + } + + + double minRate = m_phy->GetMode (m_numRates).GetDataRateBps (); + + uint32_t optA = m_maxRes; + if (m_maxRes == 0) + { + optA = FindOptA (); + } + double thAlpha = ComputeAlpha (totalFrames, totalBytes, m_numNodes, optA, pDelay / 2.0); + + double thCtlRate = m_totalRate * thAlpha; + + double temprate = (thCtlRate - minRate) / ((double) m_rateStep) + 0.5; + m_currentRateNum = (uint32_t) temprate; + if (m_currentRateNum >= m_numRates) + { + m_currentRateNum = m_numRates - 1; + } + + NS_LOG_DEBUG ("Found theoretical alpha: " << thAlpha << " Found associated rate = " << thCtlRate << " Giving rate number: " << temprate); + double thX = thAlpha * m_totalRate / (2.0 * m_numNodes * m_rtsSize * 8.0); + + double dataRate = m_phy->GetMode (m_currentRateNum).GetDataRateBps (); + + + if (thX < m_minRetryRate) + { + NS_LOG_WARN ("Gateway found optimum RTS retry rate is below minimum"); + m_currentRetryRate = 0; + } + else + { + m_currentRetryRate = (uint16_t)((thX - m_minRetryRate) / m_retryStep + 0.5) ; + } + + double actualX = m_currentRetryRate * m_retryStep + m_minRetryRate; + + uint32_t ctlRate = m_phy->GetMode (m_currentRateNum + m_numRates).GetDataRateBps (); + + + double winSize = (double)(totalBytes) * 8.0 / dataRate + m_sifs.GetSeconds () * totalFrames + pDelay; + if (numRts == 0) + { + winSize = (optA * exp (1.0) + 0.5) * 2.0 * 8.0 * m_rtsSize / (thAlpha * m_totalRate) + 2 * m_maxDelta.GetSeconds (); + } + double effWinSize = winSize - m_rtsSize * 8 / ctlRate - 2 * m_maxDelta.GetSeconds (); + + + // Before fast CTS/ACK(below) + double cycleSeconds = winSize + (totalFrames + 1.0) * m_sifs.GetSeconds () + m_ctsSizeG * 8.0 / dataRate + (m_ctsSizeN + m_ackSize) * 8.0 * numRts / dataRate; + + Time ctsTxTimeG = Seconds (m_ctsSizeG * 8.0 / dataRate); + Time ctsTxTimeTotal = Seconds (m_ctsSizeN * 8.0 * numRts / dataRate) + ctsTxTimeG; + if (numRts == 0) + { + UanHeaderRcCtsGlobal ctsg; + ctsg.SetWindowTime (Seconds (effWinSize)); + ctsg.SetRateNum (m_currentRateNum); + ctsg.SetRetryRate (m_currentRetryRate); + ctsg.SetTxTimeStamp (Simulator::Now ()); + + UanHeaderCommon ch (m_address, UanAddress::GetBroadcast (), UanMacRc::TYPE_CTS); + Ptr p = Create (); + p->AddHeader (ctsg); + p->AddHeader (ch); + SendPacket (p, m_currentRateNum); + + + Simulator::Schedule (Seconds (cycleSeconds), &UanMacRcGw::StartCycle, this); + m_state = INCYCLE; + m_cycleLogger (Simulator::Now (), Seconds (0), numRts, totalBytes, effWinSize, ctlRate, actualX); + return; + } + + Time nextEarliest = ctsTxTimeTotal + m_sifs; + + m_state = CTSING; + Simulator::Schedule (nextEarliest, &UanMacRcGw::CycleStarted, this); + + std::set >::iterator it = m_sortedRes.begin (); + Time minPdelay = (*it).first; + Ptr cts = Create (); + + for (; it != m_sortedRes.end (); it++) + { + Request req = m_requests[(*it).second]; + Time pdelay = (*it).first; + + AckData newData; + newData.expFrames = req.numFrames; + newData.frameNo = req.frameNo; + UanAddress dest = (*it).second; + m_ackData.insert (std::make_pair (dest, newData)); + + Time earliestArr = ctsTxTimeTotal + pdelay + pdelay + m_sifs; + Time arrivalTime = std::max (earliestArr, nextEarliest); + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GW: Scheduling request for prop. delay " << pdelay.GetSeconds () << " for " << (*it).second << " Earliest possible arrival=" << earliestArr.GetSeconds () << " Next arrival time=" << nextEarliest.GetSeconds ()); + nextEarliest = arrivalTime + Seconds (req.length * 8.0 / dataRate) + Seconds (m_sifs.GetSeconds () * req.numFrames); + + UanHeaderRcCts ctsh; + ctsh.SetAddress (dest); + ctsh.SetRtsTimeStamp (req.rxTime); + ctsh.SetFrameNo (req.frameNo); + ctsh.SetRetryNo (req.retryNo); + ctsh.SetDelayToTx (arrivalTime); + cts->AddHeader (ctsh); + + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GW Scheduling reception for " << (uint32_t) req.numFrames << " frames at " << (Simulator::Now () + arrivalTime).GetSeconds () << " (delaytiltx of " << arrivalTime.GetSeconds () << ") Total length is " << req.length << " with txtime " << req.length * 8 / dataRate << " seconds"); + } + + UanHeaderRcCtsGlobal ctsg; + ctsg.SetRateNum (m_currentRateNum); + ctsg.SetRetryRate (m_currentRetryRate); + ctsg.SetWindowTime (Seconds (effWinSize)); + ctsg.SetTxTimeStamp (Simulator::Now ()); + UanHeaderCommon ch; + ch.SetDest (UanAddress::GetBroadcast ()); + ch.SetSrc (m_address); + ch.SetType (UanMacRc::TYPE_CTS); + cts->AddHeader (ctsg); + cts->AddHeader (ch); + SendPacket (cts, m_currentRateNum); + + m_requests.clear (); + m_sortedRes.clear (); + Simulator::Schedule (nextEarliest, &UanMacRcGw::EndCycle, this); + + + m_cycleLogger (Simulator::Now (), minPdelay, numRts, totalBytes, cycleSeconds, ctlRate, actualX); +} + +void +UanMacRcGw::CycleStarted () +{ + m_state = INCYCLE; +} +void +UanMacRcGw::EndCycle () +{ + + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GW Ending cycle"); + + Time nextAck = Seconds (0); + + Time ackTime = Seconds (m_ackSize * 8.0 / m_phy->GetMode (m_currentRateNum).GetDataRateBps ()); + + std::map::iterator it = m_ackData.begin (); + for (; it != m_ackData.end (); it++) + { + UanAddress dest = (*it).first; + AckData &data = (*it).second; + + std::list toNack; + for (uint32_t i = 0; i < data.expFrames; i++) + { + if (data.rxFrames.find (i) == data.rxFrames.end ()) + { + toNack.push_back (i); + } + } + UanHeaderCommon ch; + ch.SetDest (dest); + ch.SetSrc (m_address); + ch.SetType (UanMacRc::TYPE_ACK); + UanHeaderRcAck ah; + ah.SetFrameNo (data.frameNo); + std::list::iterator nit = toNack.begin (); + for (; nit != toNack.end (); nit++) + { + ah.AddNackedFrame (*nit); + } + + Ptr ack = Create (); + ack->AddHeader (ah); + ack->AddHeader (ch); + Simulator::Schedule (nextAck, &UanMacRcGw::SendPacket, this, ack, m_currentRateNum); + nextAck = nextAck + ackTime + m_sifs; + } + m_ackData.clear (); + Simulator::Schedule (nextAck, &UanMacRcGw::StartCycle, this); + +} +void +UanMacRcGw::SendPacket (Ptr pkt, uint32_t rate) +{ + UanHeaderCommon ch; + pkt->PeekHeader (ch); + std::string type; + switch (ch.GetType ()) + { + case UanMacRc::TYPE_DATA: + type = "DATA"; + break; + case UanMacRc::TYPE_RTS: + type = "RTS"; + break; + case UanMacRc::TYPE_CTS: + type = "CTS"; + break; + case UanMacRc::TYPE_ACK: + type = "ACK"; + break; + case UanMacRc::TYPE_GWPING: + type = "GWPING"; + break; + default: + type = "UNKNOWN"; + break; + } + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GW sending " << type << " packet with size " << pkt->GetSize () << " to " << ch.GetDest () << " at rate " << rate); + m_phy->SendPacket (pkt, rate); +} + + +double +UanMacRcGw::ComputeAlpha (uint32_t totalFrames, uint32_t totalBytes, uint32_t n, uint32_t a, double deltaK) +{ + + double alpha; + double lrae = m_rtsSize * 8.0*a*std::exp (1.0); + if (totalFrames == 0) + { + + alpha = (2.0 * lrae + 8.0 * m_rtsSize - std::sqrt (m_ctsSizeG * 8.0 * 8.0 * m_rtsSize + 2 * 8.0 * m_ctsSizeG * 8.0 * m_rtsSize * a * std::exp (1.0)) ) / + (2 * lrae + 8.0 * m_rtsSize - 8.0 * m_ctsSizeG); + } + else + { + double w = totalBytes * 8.0 + totalFrames*m_sifs.GetSeconds () * m_totalRate; + double v = m_rtsSize * 8.0 + 2 * lrae; + double u = (2 * m_maxDelta.GetSeconds () - 2 * deltaK) * m_totalRate; + + double gamma = (w - u + v) / (2 * (u - totalFrames * m_sifs.GetSeconds () * m_totalRate)); + + alpha = -gamma + sqrt (gamma * gamma + v / (u - totalFrames * m_sifs.GetSeconds () * m_totalRate)); + + if (alpha < 0 || alpha > 1) + { + alpha = -gamma - sqrt (gamma * gamma + v / (u - totalFrames * m_sifs.GetSeconds () * m_totalRate)); + } + } + NS_ASSERT_MSG (alpha > 0 && alpha < 1, "Error computing alpha. Alpha out of valid range!"); + return alpha; +} + +std::vector +UanMacRcGw::GetExpPdk (void) +{ + uint32_t n = m_numNodes; + std::vector pds; + std::map::iterator pdit = m_propDelay.begin (); + + for (; pdit != m_propDelay.end (); pdit++) + { + pds.push_back (pdit->second.GetSeconds ()); + } + while (pds.size () < m_numNodes) + { + pds.push_back (m_maxDelta.GetSeconds ()); + } + + std::sort (pds.begin (), pds.end ()); + // Find expected min. prop. delay for k nodes + std::vector exppdk; + exppdk.push_back (m_maxDelta.GetSeconds ()); + for (uint32_t k = 1; k <= n; k++) + { + uint32_t ind = CompExpMinIndex (n,k) - 1; + exppdk.push_back (pds[ind]); + } + return exppdk; +} + +double +UanMacRcGw::ComputeExpS (uint32_t a, uint32_t ld, std::vector exppdk) +{ + UanHeaderCommon ch; + uint32_t lh = ch.GetSerializedSize (); + + uint32_t n = m_numNodes; + double expk = n * (1 - std::exp (-((double) a) / (double) n)); + NS_LOG_DEBUG ("expk = " << expk); + + // Compute expected data per cycle + double expdata = 8 * ld * expk; + + // Compute expected time per cycle + double alpha0 = ComputeAlpha (0,0,n,a,exppdk[0]); + double c0 = 8.0 * m_ctsSizeG / ( m_totalRate * (1 - alpha0)) + 2 * m_maxDelta.GetSeconds () + (a * std::exp (1.0) + 0.5) * 2 * m_rtsSize * 8.0 / (alpha0 * m_totalRate); + double exptime = ComputePiK (a,n,0) * c0; + double expp = 0; + for (uint32_t i = 1; i <= n; i++) + { + expp += ComputePiK (a,n,i) * exppdk[i - 1]; + } + + exptime += ComputeExpBOverA (n,a,ld + lh,exppdk) + expk * 2 * m_sifs.GetSeconds () + m_sifs.GetSeconds () + 2 * expp; + double s = (1.0 / m_totalRate) * expdata / exptime; + + return s; +} + +double +UanMacRcGw::ComputeExpS (uint32_t a, uint32_t ld) +{ + return ComputeExpS (a, ld, GetExpPdk ()); +} + +uint32_t +UanMacRcGw::CompExpMinIndex (uint32_t n, uint32_t k) +{ + double sum = 0; + for (uint32_t i = 1; i <= n - k + 1; i++) + { + double p = (double) NchooseK (n - i, k - 1) / NchooseK (n, k); + sum += p * i; + } + return (uint32_t)(sum + 0.5); +} + +double +UanMacRcGw::ComputePiK (uint32_t a, uint32_t n, uint32_t k) +{ + double nck = (double) NchooseK (n, k); + return nck * std::pow ( (std::exp ( (double) a / (double) n) - 1.0), (double) k) * std::exp (-( (double) a)); +} + +double +UanMacRcGw::ComputeExpBOverA (uint32_t n, uint32_t a, uint32_t ldlh, std::vector deltaK) +{ + + double sum = 0; + uint32_t lt = 8.0 * (m_ctsSizeN + ldlh + m_ackSize); + for (uint32_t k = 1; k <= n; k++) + { + double num = 8.0 * m_ctsSizeG + k * lt; + double denom = (1.0 - ComputeAlpha (k, k * ldlh, n, a, deltaK[k])) * m_totalRate; + double pik = ComputePiK (a, n, k); + double term = pik * num / denom; + + sum += term; + } + + return sum; +} + +uint64_t +UanMacRcGw::NchooseK (uint32_t n, uint32_t k) +{ + if (k > n) + { + return 0; + } + + if (k > n / 2) + { + k = n - k; + } + + double accum = 1; + for (uint32_t i = 1; i <= k; i++) + { + accum = accum * (n - k + i) / i; + } + + return (uint64_t)(accum + 0.5); + +} + +uint32_t +UanMacRcGw::FindOptA (void) +{ + double tput = 0; + uint32_t a = 1; + while (1) + { + + double newtput = ComputeExpS (a, m_frameSize); + if (newtput < tput) + { + a--; + break; + } + else + { + tput = newtput; + a++; + } + } + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " GW: Found optimum a = " << a); + return a; +} +} // namespace ns3 diff --git a/src/devices/uan/uan-mac-rc-gw.h b/src/devices/uan/uan-mac-rc-gw.h new file mode 100644 index 000000000..eed0e6a14 --- /dev/null +++ b/src/devices/uan/uan-mac-rc-gw.h @@ -0,0 +1,164 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANMACRCGW_H +#define UANMACRCGW_H + +#include "uan-mac.h" +#include "uan-address.h" + +#include "ns3/nstime.h" +#include "ns3/traced-callback.h" + + + + +#include +#include + +namespace ns3 { + +class UanTxMode; + +/** + * \class UanMacRcGw + * + * \brief Gateway side of RC-MAC + * + * + * + * This MAC protocol assumes a network topology where all traffic + * is destined for a set of GW nodes which are connected via + * some out of band (RF?) means. UanMacRcGw is the protocol + * which runs on the gateway nodes. + * + * This particular implementation + * assumes that there is only a single gateway. + * + * For more information on class operation email + * lentracy@u.washington.edu + * (This work is, as of yet, unpublished) + */ + +class UanMacRcGw : public ns3::UanMac +{ +public: + UanMacRcGw (); + virtual ~UanMacRcGw (); + + static TypeId GetTypeId (void); + + // Inherited virtual functions + virtual Address GetAddress (void); + virtual void SetAddress (UanAddress addr); + virtual bool Enqueue (Ptr pkt, const Address &dest, uint16_t protocolNumber); + virtual void SetForwardUpCb (Callback, const UanAddress&> cb); + virtual void AttachPhy (Ptr phy); + virtual Address GetBroadcast (void) const; + +private: + enum State { + IDLE, INCYCLE, CTSING + }; + State m_state; + + struct Request + { + uint8_t numFrames; + uint8_t frameNo; + uint8_t retryNo; + uint16_t length; + Time rxTime; + }; + + struct AckData + { + uint8_t frameNo; + std::set rxFrames; + uint8_t expFrames; + }; + Callback, const UanAddress& > m_forwardUpCb; + Ptr m_phy; + UanAddress m_address; + Time m_maxDelta; + Time m_sifs; + uint32_t m_maxRes; + uint32_t m_numRates; + uint32_t m_rtsSize; + uint32_t m_ctsSizeN; + uint32_t m_ctsSizeG; + uint32_t m_ackSize; + double m_retryRate; + uint16_t m_currentRetryRate; + uint32_t m_currentRateNum; + uint32_t m_numNodes; + uint32_t m_totalRate; + uint32_t m_rateStep; + uint32_t m_frameSize; + + uint16_t m_numRetryRates; + double m_minRetryRate; + double m_retryStep; + + std::map m_propDelay; + + std::map m_ackData; + + + std::map m_requests; + std::set > m_sortedRes; + + TracedCallback, UanTxMode > m_rxLogger; + + // Start time, min p-delay, reservations, frames, bytes, window size, ctl rate, retry rate + TracedCallback m_cycleLogger; + + void ReceivePacket (Ptr pkt, double sinr, UanTxMode mode); + void StartCycle (void); + void EndCycle (void); + void SendPacket (Ptr pkt, uint32_t rate); + void CycleStarted (void); + void ReceiveError (Ptr pkt, double sinr); + + // Stuff for computing exp throughput + double ComputeAlpha (uint32_t totalFrames, uint32_t totalBytes, uint32_t n, uint32_t a, double deltaK); + std::vector GetExpPdk (void); + double ComputeExpS (uint32_t a, uint32_t ld, std::vector exppdk); + double ComputeExpS (uint32_t a, uint32_t ld); + uint32_t CompExpMinIndex (uint32_t n, uint32_t k); + double ComputePiK (uint32_t a, uint32_t n, uint32_t k); + double ComputeExpBOverA (uint32_t n, uint32_t a, uint32_t ldlh, std::vector deltaK); + uint64_t NchooseK (uint32_t n, uint32_t k); + uint32_t FindOptA (void); +protected: + virtual void DoDispose (); + +}; + +/** + * \brief Defined for use in UanMacRcGw + * \param a Address to compare + * \param b Address to compare + */ +bool operator < (UanAddress &a, UanAddress &b); + +} + +#endif // UANMACRCGW_H diff --git a/src/devices/uan/uan-mac-rc.cc b/src/devices/uan/uan-mac-rc.cc new file mode 100644 index 000000000..926d3a45a --- /dev/null +++ b/src/devices/uan/uan-mac-rc.cc @@ -0,0 +1,757 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#include "uan-mac-rc.h" +#include "uan-header-rc.h" +#include "uan-tx-mode.h" +#include "uan-phy.h" +#include "uan-header-common.h" +#include "uan-phy-dual.h" + +#include "ns3/log.h" +#include "ns3/nstime.h" +#include "ns3/simulator.h" +#include "ns3/random-variable.h" +#include "ns3/assert.h" +#include "ns3/double.h" +#include "ns3/uinteger.h" + +#include +#include + + + +NS_LOG_COMPONENT_DEFINE ("UanMacRc"); +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (UanMacRc); + +Reservation::Reservation () + : m_length (0), + m_frameNo (0), + m_retryNo (0), + m_transmitted (false) +{ + +} + +Reservation::Reservation (std::list, UanAddress > > &list, uint8_t frameNo, uint32_t maxPkts) + : m_frameNo (frameNo), + m_retryNo (0), + m_transmitted (false) +{ + uint32_t numPkts = (maxPkts) ? maxPkts : list.size (); + uint32_t length = 0; + UanHeaderRcData dh; + UanHeaderCommon ch; + + for (uint32_t i = 0; i < numPkts; i++) + { + length += list.front ().first->GetSize () + + ch.GetSerializedSize () + + dh.GetSerializedSize (); + m_pktList.push_back (list.front ()); + list.pop_front (); + } + m_length = length; +} + +Reservation::~Reservation () +{ + std::list, UanAddress > >::iterator it; + for (it = m_pktList.begin (); it != m_pktList.end (); it++) + { + it->first = Ptr ((Packet *) 0); + } + m_pktList.clear (); + m_timestamp.clear (); +} +uint32_t +Reservation::GetNoFrames () const +{ + return m_pktList.size (); +} + +uint32_t +Reservation::GetLength () const +{ + return m_length; +} + +const std::list, UanAddress > > & +Reservation::GetPktList (void) const +{ + return m_pktList; +} + +uint8_t +Reservation::GetFrameNo () const +{ + return m_frameNo; +} + +uint8_t +Reservation::GetRetryNo () const +{ + return m_retryNo; +} + +Time +Reservation::GetTimestamp (uint8_t n) const +{ + return m_timestamp[n]; +} + +bool +Reservation::IsTransmitted () const +{ + return m_transmitted; +} + +void +Reservation::SetFrameNo (uint8_t fn) +{ + m_frameNo = fn; +} + +void +Reservation::AddTimestamp (Time t) +{ + m_timestamp.push_back (t); +} + +void +Reservation::IncrementRetry () +{ + m_retryNo++; +} + +void +Reservation::SetTransmitted (bool t) +{ + m_transmitted = true; +} + +uint32_t UanMacRc::m_cntrlSends = 0; + +UanMacRc::UanMacRc () + : UanMac (), + m_state (UNASSOCIATED), + m_rtsBlocked (false), + m_currentRate (10), + m_frameNo (0) +{ + UanHeaderCommon ch; + UanHeaderRcCts ctsh; + UanHeaderRcCtsGlobal ctsg; + + m_ctsSizeN = ctsh.GetSerializedSize (); + m_ctsSizeG = ch.GetSerializedSize () + ctsg.GetSerializedSize (); +} + +UanMacRc::~UanMacRc () +{ +} + +void +UanMacRc::DoDispose () +{ + m_phy = 0; + std::list, UanAddress > >::iterator it; + for (it = m_pktQueue.begin (); it != m_pktQueue.end (); it++) + { + it->first = 0; + } + m_pktQueue.clear (); + m_resList.clear (); + m_startAgain.Cancel (); + m_rtsEvent.Cancel (); + + UanMac::DoDispose (); +} + +TypeId +UanMacRc::GetTypeId (void) +{ + TypeId tid = TypeId ("ns3::UanMacRc") + .SetParent () + .AddConstructor () + .AddAttribute ("RetryRate", + "Number of retry attempts per second (of RTS/GWPING)", + DoubleValue (1 / 5.0), + MakeDoubleAccessor (&UanMacRc::m_retryRate), + MakeDoubleChecker ()) + .AddAttribute ("MaxFrames", + "Maximum number of frames to include in a single RTS", + UintegerValue (1), + MakeUintegerAccessor (&UanMacRc::m_maxFrames), + MakeUintegerChecker ()) + .AddAttribute ("QueueLimit", + "Maximum packets to queue at MAC", + UintegerValue (10), + MakeUintegerAccessor (&UanMacRc::m_queueLimit), + MakeUintegerChecker ()) + .AddAttribute ("SIFS", + "Spacing to give between frames (this should match gateway)", + TimeValue (Seconds (0.2)), + MakeTimeAccessor (&UanMacRc::m_sifs), + MakeTimeChecker ()) + .AddAttribute ("NumberOfRates", + "Number of rate divisions supported by each PHY", + UintegerValue (0), + MakeUintegerAccessor (&UanMacRc::m_numRates), + MakeUintegerChecker ()) + .AddAttribute ("MinRetryRate", + "Smallest allowed RTS retry rate", + DoubleValue (0.01), + MakeDoubleAccessor (&UanMacRc::m_minRetryRate), + MakeDoubleChecker ()) + .AddAttribute ("RetryStep", + "Retry rate increment", + DoubleValue (0.01), + MakeDoubleAccessor (&UanMacRc::m_retryStep), + MakeDoubleChecker ()) + .AddAttribute ("NumberOfRetryRates", + "Number of retry rates", + UintegerValue (100), + MakeUintegerAccessor (&UanMacRc::m_numRetryRates), + MakeUintegerChecker ()) + .AddAttribute ("MaxPropDelay", + "Maximum possible propagation delay to gateway", + TimeValue (Seconds (2)), + MakeTimeAccessor (&UanMacRc::m_learnedProp), + MakeTimeChecker ()) + .AddTraceSource ("Enqueue", + "A (data) packet arrived at MAC for transmission", + MakeTraceSourceAccessor (&UanMacRc::m_enqueueLogger)) + .AddTraceSource ("Dequeue", + "A (data) packet was passed down to PHY from MAC", + MakeTraceSourceAccessor (&UanMacRc::m_dequeueLogger)) + .AddTraceSource ("RX", + "A packet was destined for and received at this MAC layer", + MakeTraceSourceAccessor (&UanMacRc::m_rxLogger)) + ; + return tid; +} + + +Address +UanMacRc::GetAddress (void) +{ + return m_address; +} + +void +UanMacRc::SetAddress (UanAddress addr) +{ + m_address = addr; +} + +bool +UanMacRc::Enqueue (Ptr packet, const Address &dest, uint16_t protocolNumber) +{ + if (protocolNumber > 0) + { + NS_LOG_WARN ("Warning: UanMacRc does not support multiple protocols. protocolNumber argument to Enqueue is being ignored"); + } + + + if (m_pktQueue.size () >= m_queueLimit) + { + return false; + } + + m_pktQueue.push_back (std::make_pair (packet, UanAddress::ConvertFrom (dest))); + + switch (m_state) + { + case UNASSOCIATED: + Associate (); + return true; + case IDLE: + if (!m_rtsEvent.IsRunning ()) + { + SendRts (); + } + return true; + case GWPSENT: + case RTSSENT: + case DATATX: + return true; + } + + return true; +} + +void +UanMacRc::SetForwardUpCb (Callback, const UanAddress&> cb) +{ + m_forwardUpCb = cb; +} + +void +UanMacRc::AttachPhy (Ptr phy) +{ + m_phy = phy; + m_phy->SetReceiveOkCallback (MakeCallback (&UanMacRc::ReceiveOkFromPhy, this)); +} + +Address +UanMacRc::GetBroadcast (void) const +{ + return UanAddress::GetBroadcast (); +} + +void +UanMacRc::ReceiveOkFromPhy (Ptr pkt, double sinr, UanTxMode mode) +{ + + UanHeaderCommon ch; + pkt->RemoveHeader (ch); + if (ch.GetDest () == m_address || ch.GetDest () == UanAddress::GetBroadcast ()) + { + m_rxLogger (pkt, mode); + } + + switch (ch.GetType ()) + { + case TYPE_DATA: + + if (ch.GetDest () == m_address) + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " UanMacRc Receiving DATA packet from PHY"); + UanHeaderRcData dh; + pkt->RemoveHeader (dh); + m_forwardUpCb (pkt, ch.GetSrc ()); + } + break; + case TYPE_RTS: + // Currently don't respond to RTS packets at non-gateway nodes + // (Code assumes single network neighberhood) + break; + case TYPE_CTS: + { + uint32_t ctsBytes = ch.GetSerializedSize () + pkt->GetSize (); + m_assocAddr = ch.GetSrc (); + UanHeaderRcCtsGlobal ctsg; + pkt->RemoveHeader (ctsg); + m_currentRate = ctsg.GetRateNum (); + m_retryRate = m_minRetryRate + m_retryStep*ctsg.GetRetryRate (); + + UanHeaderRcRts rhtmp; + + Time winDelay = ctsg.GetWindowTime (); + + if (winDelay.GetSeconds () > 0) + { + m_rtsBlocked = false; + Simulator::Schedule (winDelay, &UanMacRc::BlockRtsing, this); + } + else + { + NS_FATAL_ERROR (Simulator::Now ().GetSeconds () << " Node " << m_address << " Received window period < 0"); + } + + UanHeaderRcCts ctsh; + ctsh.SetAddress (UanAddress::GetBroadcast ()); + while (pkt->GetSize () > 0) + { + pkt->RemoveHeader (ctsh); + if (ctsh.GetAddress () == m_address) + { + if (m_state == GWPSENT) + { + m_assocAddr = ch.GetSrc (); + ScheduleData (ctsh, ctsg, ctsBytes); + } + else if (m_state == RTSSENT) + { + ScheduleData (ctsh, ctsg, ctsBytes); + } + else + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " received CTS while state != RTSSENT or GWPING"); + } + } + } + } + break; + case TYPE_GWPING: + // Do not respond to GWPINGS at non-gateway nodes + break; + case TYPE_ACK: + m_rtsBlocked = true; + if (ch.GetDest () != m_address) + { + return; + } + ProcessAck (pkt); + break; + default: + NS_FATAL_ERROR ("Unknown packet type " << ch.GetType () << " received at node " << GetAddress ()); + } + +} + +void +UanMacRc::ScheduleData (const UanHeaderRcCts &ctsh, const UanHeaderRcCtsGlobal &ctsg, uint32_t ctsBytes) +{ + NS_ASSERT (m_state == RTSSENT || m_state == GWPSENT); + + + + std::list::iterator it = m_resList.begin (); + for (; it != m_resList.end (); it++) + { + if (it->GetFrameNo () == ctsh.GetFrameNo ()) + { + break; + } + } + if (it == m_resList.end ()) + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " received CTS packet with no corresponding reservation!"); + return; + } + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " received CTS packet. Scheduling data"); + it->SetTransmitted (); + + double currentBps = m_phy->GetMode (m_currentRate).GetDataRateBps (); + + m_learnedProp = Simulator::Now () - ctsg.GetTxTimeStamp () - Seconds (ctsBytes * 8.0 / currentBps); + + + Time arrTime = ctsg.GetTxTimeStamp () + ctsh.GetDelayToTx (); + Time txTime = arrTime - m_learnedProp; + + Time startDelay = txTime - Simulator::Now (); + + Time frameDelay = Seconds (0); + + const std::list, UanAddress > > l = it->GetPktList (); + std::list, UanAddress > >::const_iterator pit; + pit = l.begin (); + + + + for (uint32_t i = 0; i < it->GetNoFrames (); i++, pit++) + { + Ptr pkt = (*pit).first->Copy (); + + UanHeaderRcData dh; + dh.SetFrameNo (i); + dh.SetPropDelay (m_learnedProp); + pkt->AddHeader (dh); + + UanHeaderCommon ch; + ch.SetType (TYPE_DATA); + ch.SetDest (m_assocAddr); + ch.SetSrc (m_address); + + pkt->AddHeader (ch); + Time eventTime = startDelay + frameDelay; + if (eventTime.GetSeconds () < 0) + { + if (eventTime.GetSeconds () > -0.001) + { + eventTime = Seconds (0); + } + else + { + NS_FATAL_ERROR ("Scheduling error resulted in very negative data transmission time! eventTime = " << eventTime.GetSeconds ()); + } + } + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " scheduling with delay " << eventTime.GetSeconds () << " propDelay " << m_learnedProp.GetSeconds () << " start delay " << startDelay.GetSeconds () << " arrival time " << arrTime.GetSeconds ()); + Simulator::Schedule (eventTime, &UanMacRc::SendPacket, this, pkt, m_currentRate); + frameDelay = frameDelay + m_sifs + Seconds (pkt->GetSize () / currentBps); + } + + m_state = IDLE; + if (!m_pktQueue.empty ()) + { + + if (m_rtsEvent.IsRunning ()) + { + m_rtsEvent.Cancel (); + } + ExponentialVariable ev (1 / m_retryRate); + double timeout = ev.GetValue (); + m_rtsEvent = Simulator::Schedule (Seconds (timeout), &UanMacRc::SendRts, this); + } + +} + +void +UanMacRc::SendPacket (Ptr pkt, uint32_t rate) +{ + UanHeaderCommon ch; + pkt->PeekHeader (ch); + std::string type; + switch (ch.GetType ()) + { + case TYPE_DATA: + type = "DATA"; + break; + case TYPE_RTS: + type = "RTS"; + break; + case TYPE_CTS: + type = "CTS"; + break; + case TYPE_ACK: + type = "ACK"; + break; + case TYPE_GWPING: + type = "GWPING"; + break; + default: + type = "UNKNOWN"; + break; + } + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " transmitting " << pkt->GetSize () << " byte packet of type " << type << " with rate " << rate << "(" << m_phy->GetMode (rate).GetDataRateBps () << ") to " << ch.GetDest ()); + m_dequeueLogger (pkt, rate); + m_phy->SendPacket (pkt, rate); +} + +void +UanMacRc::ProcessAck (Ptr ack) +{ + UanHeaderRcAck ah; + ack->RemoveHeader (ah); + + std::list::iterator it = m_resList.begin (); + for (; it != m_resList.end (); it++) + { + if (it->GetFrameNo () == ah.GetFrameNo ()) + { + break; + } + } + if (it == m_resList.end ()) + { + NS_LOG_DEBUG ("In " << __func__ << " could not find reservation corresponding to received ACK"); + return; + } + if (!it->IsTransmitted ()) + { + return; + } + if (ah.GetNoNacks () > 0) + { + const std::list, UanAddress > > l = it->GetPktList (); + std::list, UanAddress > >::const_iterator pit; + pit = l.begin (); + + const std::set &nacks = ah.GetNackedFrames (); + std::set::iterator nit = nacks.begin (); + uint8_t pnum = 0; + for (; nit != nacks.end (); nit++) + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " Received NACK for " << (uint32_t) *nit); + while (pnum < *nit) + { + pit++; + pnum++; + } + UanHeaderRcData dh; + UanHeaderCommon ch; + m_pktQueue.push_front (*pit); + } + } + else + { + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Node " << m_address << " received ACK for all frames"); + } + m_resList.erase (it); +} + +UanHeaderRcRts +UanMacRc::CreateRtsHeader (const Reservation &res) +{ + UanHeaderRcRts rh = UanHeaderRcRts (); + + rh.SetLength (res.GetLength ()); + rh.SetNoFrames (res.GetNoFrames ()); + rh.SetTimeStamp (res.GetTimestamp (res.GetRetryNo ())); + rh.SetFrameNo (res.GetFrameNo ()); + rh.SetRetryNo (res.GetRetryNo ()); + return rh; +} + +void +UanMacRc::Associate (void) +{ + m_cntrlSends++; + + Reservation res (m_pktQueue, m_frameNo, m_maxFrames); + res.AddTimestamp (Simulator::Now ()); + m_frameNo++; + m_resList.push_back (res); + Ptr phyDual = m_phy->GetObject (); + bool phy1ok = IsPhy1Ok (); + if (phy1ok && !phyDual->IsPhy2Tx () & !m_rtsBlocked) + { + Ptr pkt = Create (0); + pkt->AddHeader (CreateRtsHeader (res)); + pkt->AddHeader (UanHeaderCommon (m_address, UanAddress::GetBroadcast (), (uint8_t) TYPE_GWPING)); + NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Sending first GWPING " << *pkt); + SendPacket (pkt,m_currentRate + m_numRates); + } + m_state = GWPSENT; + NS_ASSERT (!m_rtsEvent.IsRunning ()); + ExponentialVariable ev (1.0 / m_retryRate); + double timeout = ev.GetValue (); + m_rtsEvent = Simulator::Schedule (Seconds (timeout), &UanMacRc::AssociateTimeout, this); +} + +void +UanMacRc::AssociateTimeout () +{ + m_cntrlSends++; + if (m_state != GWPSENT) + { + return; + } + Ptr phyDual = m_phy->GetObject (); + bool phy1ok = IsPhy1Ok (); + if (phy1ok && !phyDual->IsPhy2Tx () && !m_rtsBlocked) + { + Ptr pkt = Create (); + + Reservation res = m_resList.back (); + m_resList.pop_back (); + res.AddTimestamp (Simulator::Now ()); + res.IncrementRetry (); + + pkt->AddHeader (CreateRtsHeader (res)); + pkt->AddHeader (UanHeaderCommon (m_address, UanAddress::GetBroadcast (), (uint8_t) TYPE_GWPING)); + + SendPacket (pkt,m_currentRate + m_numRates); + m_resList.push_back (res); + } + NS_ASSERT (!m_rtsEvent.IsRunning ()); + ExponentialVariable ev (1.0 / m_retryRate); + double timeout = ev.GetValue (); + m_rtsEvent = Simulator::Schedule (Seconds (timeout), &UanMacRc::AssociateTimeout, this); +} + + +void +UanMacRc::SendRts (void) +{ + m_cntrlSends++; + if (m_state == RTSSENT) + { + return; + } + + NS_ASSERT (!m_pktQueue.empty ()); + + Reservation res (m_pktQueue, m_frameNo, m_maxFrames); + res.AddTimestamp (Simulator::Now ()); + m_frameNo++; + m_resList.push_back (res); + Ptr phyDual = m_phy->GetObject (); + bool phy1ok = IsPhy1Ok (); + if (phy1ok && !phyDual->IsPhy2Tx () && !m_rtsBlocked ) + { + Ptr pkt = Create (0); + pkt->AddHeader (CreateRtsHeader (res)); + pkt->AddHeader (UanHeaderCommon (m_address, UanAddress::GetBroadcast (), (uint8_t) TYPE_RTS)); + SendPacket (pkt,m_currentRate + m_numRates); + } + m_state = RTSSENT; + NS_ASSERT (!m_rtsEvent.IsRunning ()); + ExponentialVariable ev (1.0 / m_retryRate); + double timeout = ev.GetValue (); + m_rtsEvent = Simulator::Schedule (Seconds (timeout), &UanMacRc::RtsTimeout, this); + +} + +// We assume here that packet types are known at detection. +bool +UanMacRc::IsPhy1Ok () +{ + Ptr phyDual = m_phy->GetObject (); + + bool phy1ok = true; + if (phyDual->IsPhy1Rx ()) + { + Ptr pkt = phyDual->GetPhy1PacketRx (); + UanHeaderCommon ch; + pkt->PeekHeader (ch); + if (ch.GetType () == TYPE_CTS || ch.GetType () == TYPE_ACK) + { + phy1ok = false; + } + else if (ch.GetDest () == m_address) + { + phy1ok = false; + } + } + return phy1ok; +} + +void +UanMacRc::RtsTimeout (void) +{ + m_cntrlSends++; + + if (m_state != RTSSENT) + { + return; + } + Ptr phyDual = m_phy->GetObject (); + + bool phy1ok = IsPhy1Ok (); + if (phy1ok && !phyDual->IsPhy2Tx () && !m_rtsBlocked) + { + + if (m_resList.empty ()) + { + NS_FATAL_ERROR (Simulator::Now ().GetSeconds () << " Node " << m_address << " tried to retry RTS with empty reservation list"); + } + Ptr pkt = Create (0); + + Reservation res = m_resList.back (); + NS_ASSERT (!res.IsTransmitted ()); + m_resList.pop_back (); + res.AddTimestamp (Simulator::Now ()); + res.IncrementRetry (); + m_resList.push_back (res); + pkt->AddHeader (CreateRtsHeader (res)); + pkt->AddHeader (UanHeaderCommon (m_address, UanAddress::GetBroadcast (), (uint8_t) TYPE_RTS)); + SendPacket (pkt,m_currentRate + m_numRates); + + } + m_state = RTSSENT; + NS_ASSERT (!m_rtsEvent.IsRunning ()); + ExponentialVariable ev (1.0 / m_retryRate); + double timeout = ev.GetValue (); + m_rtsEvent = Simulator::Schedule (Seconds (timeout), &UanMacRc::RtsTimeout, this); +} + +void +UanMacRc::BlockRtsing (void) +{ + m_rtsBlocked = true; +} + +} // namespace ns3 diff --git a/src/devices/uan/uan-mac-rc.h b/src/devices/uan/uan-mac-rc.h new file mode 100644 index 000000000..d534fa7a2 --- /dev/null +++ b/src/devices/uan/uan-mac-rc.h @@ -0,0 +1,214 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * 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 + * + * Author: Leonard Tracy + */ + +#ifndef UANMACRC_H +#define UANMACRC_H + +#include "uan-mac.h" +#include "uan-address.h" + +#include "ns3/nstime.h" +#include "ns3/trace-source-accessor.h" +#include "ns3/traced-callback.h" +#include "ns3/event-id.h" + +#include +#include +#include + + +namespace ns3 { + +class Address; +class UanTxMode; +class UanHeaderRcRts; +class UanHeaderRcCts; +class UanHeaderRcCtsGlobal; +class UanPhy; + + +/** + * \class Reservation + * \brief Stores reservation info for use in scheduling data channel by reservation channel MAC + */ +class Reservation +{ +public: + /** + * \brief Create empty object with default values + */ + Reservation (); + /** + * \brief Create Reservation object with given packet list, frame number and max packets + * \param list List of packets for assigned to reservation + * \param frameNo Frame number of reservation transmission + * \param maxPkts Maximum number of packets to assign to reservation from packet list (0 = no maximum) + */ + Reservation (std::list, UanAddress > > &list, uint8_t frameNo, uint32_t maxPkts = 0); + ~Reservation (); + /** + * \returns number of frames in reservation + */ + uint32_t GetNoFrames () const; + /** + * \returns total byte length of reservation (sum of all packets with headers) + */ + uint32_t GetLength () const; + /** + * \returns reference to list of packets in this reservation + */ + const std::list, UanAddress > > &GetPktList (void) const; + /** + * \returns Frame number of reservation + */ + uint8_t GetFrameNo () const; + /** + * \returns Retry number of reservation + */ + uint8_t GetRetryNo () const; + /** + * \returns Timestamp nth RTS send for this reservation + * \param n Timestamp for retry number n to return + */ + Time GetTimestamp (uint8_t n) const; + /** + * \returns True if reservation packets have been transmitted + */ + bool IsTransmitted () const; + /** + * \param fn Frame number to set reservation to + */ + void SetFrameNo (uint8_t fn); + /** + * \param t Time of latest RTS send + */ + void AddTimestamp (Time t); + /** + * \brief Increments retry count by 1 + */ + void IncrementRetry (); + /** + * \param t True if resevation has been transmitted + * \brief Sets reservation transmitted state + */ + void SetTransmitted (bool t = true); +private: + std::list, UanAddress > > m_pktList; + uint32_t m_length; + uint8_t m_frameNo; + std::vector