From 98a4e05df33beaea1c9703c876823b0e6bafdaf9 Mon Sep 17 00:00:00 2001 From: Giovanni Grieco Date: Mon, 3 Apr 2023 20:03:35 +0000 Subject: [PATCH] refactor: align IoD_Sim with ns-3 code style --- src/CMakeLists.txt | 2 +- src/application/drone-client-application.cc | 443 ++--- src/application/drone-client-application.h | 181 +- src/application/drone-communications.cc | 55 +- src/application/drone-communications.h | 118 +- src/application/drone-server-application.cc | 309 ++-- src/application/drone-server-application.h | 62 +- src/application/nat-application.cc | 297 +-- src/application/nat-application.h | 122 +- src/application/random-udp-application.cc | 177 +- src/application/random-udp-application.h | 96 +- .../tcp-client-server-application.cc | 293 +-- .../tcp-client-server-application.h | 53 +- .../tcp-echo-server-application.cc | 80 +- src/application/tcp-echo-server-application.h | 21 +- .../tcp-storage-client-application.cc | 208 ++- .../tcp-storage-client-application.h | 55 +- .../tcp-stub-client-application.cc | 86 +- src/application/tcp-stub-client-application.h | 37 +- .../udp-echo-client-application.cc | 168 +- src/application/udp-echo-client-application.h | 104 +- src/configuration/base/double-vector.cc | 101 +- src/configuration/base/double-vector.h | 49 +- src/configuration/base/int-vector.cc | 101 +- src/configuration/base/int-vector.h | 49 +- .../base/model-configuration-matrix.cc | 156 +- .../base/model-configuration-matrix.h | 194 +- .../base/model-configuration-vector.cc | 155 +- .../base/model-configuration-vector.h | 194 +- src/configuration/base/model-configuration.cc | 186 +- src/configuration/base/model-configuration.h | 190 +- src/configuration/base/str-vec.cc | 105 +- src/configuration/base/str-vec.h | 51 +- src/configuration/base/vector-type.cc | 109 +- src/configuration/base/vector-type.h | 56 +- src/configuration/base/vector.cc | 95 +- src/configuration/base/vector.h | 70 +- src/configuration/entity-configuration.cc | 89 +- src/configuration/entity-configuration.h | 65 +- .../helper/drone-energy-model-helper.cc | 31 +- .../helper/drone-energy-model-helper.h | 53 +- .../helper/entity-configuration-helper.cc | 367 ++-- .../helper/entity-configuration-helper.h | 56 +- .../helper/ipv4-simulation-helper.cc | 33 +- .../helper/ipv4-simulation-helper.h | 73 +- .../helper/lte-phy-simulation-helper.cc | 45 +- .../helper/lte-phy-simulation-helper.h | 37 +- src/configuration/helper/lte-setup-helper.cc | 11 +- src/configuration/helper/lte-setup-helper.h | 42 +- .../helper/mac-layer-configuration-helper.h | 31 +- .../helper/mobility-factory-helper.cc | 39 +- .../helper/mobility-factory-helper.h | 29 +- .../helper/model-configuration-helper.cc | 509 +++--- .../helper/model-configuration-helper.h | 85 +- .../network-layer-configuration-helper.h | 29 +- .../helper/phy-layer-configuration-helper.cc | 145 +- .../helper/phy-layer-configuration-helper.h | 29 +- .../helper/remote-configuration-helper.cc | 63 +- .../helper/remote-configuration-helper.h | 39 +- .../helper/scenario-configuration-helper.cc | 1589 ++++++++--------- .../helper/scenario-configuration-helper.h | 892 ++++----- .../helper/wifi-mac-factory-helper.cc | 19 +- .../helper/wifi-mac-factory-helper.h | 32 +- .../helper/wifi-mac-simulation-helper.cc | 13 +- .../helper/wifi-mac-simulation-helper.h | 30 +- .../helper/wifi-phy-factory-helper.cc | 32 +- .../helper/wifi-phy-factory-helper.h | 49 +- .../helper/wifi-phy-simulation-helper.cc | 21 +- .../helper/wifi-phy-simulation-helper.h | 35 +- .../ipv4-network-layer-configuration.cc | 35 +- .../ipv4-network-layer-configuration.h | 69 +- src/configuration/lte-bearer-configuration.cc | 149 +- src/configuration/lte-bearer-configuration.h | 59 +- .../lte-netdevice-configuration.cc | 70 +- .../lte-netdevice-configuration.h | 97 +- .../lte-phy-layer-configuration.cc | 28 +- .../lte-phy-layer-configuration.h | 64 +- src/configuration/mac-layer-configuration.cc | 15 +- src/configuration/mac-layer-configuration.h | 43 +- .../mobility-model-configuration.cc | 27 +- .../mobility-model-configuration.h | 30 +- src/configuration/netdevice-configuration.cc | 23 +- src/configuration/netdevice-configuration.h | 57 +- .../network-layer-configuration.cc | 15 +- .../network-layer-configuration.h | 43 +- src/configuration/phy-layer-configuration.cc | 22 +- src/configuration/phy-layer-configuration.h | 56 +- src/configuration/remote-configuration.cc | 23 +- src/configuration/remote-configuration.h | 22 +- .../wifi-mac-layer-configuration.cc | 26 +- .../wifi-mac-layer-configuration.h | 56 +- .../wifi-netdevice-configuration.cc | 21 +- .../wifi-netdevice-configuration.h | 52 +- .../wifi-phy-layer-configuration.cc | 79 +- .../wifi-phy-layer-configuration.h | 78 +- src/entity/drone-container.cc | 43 +- src/entity/drone-container.h | 87 +- src/entity/drone-energy-model.cc | 130 +- src/entity/drone-energy-model.h | 236 ++- src/entity/drone-list.cc | 286 +-- src/entity/drone-list.h | 63 +- src/entity/drone.cc | 123 +- src/entity/drone.h | 162 +- src/entity/remote-list.cc | 283 +-- src/entity/remote-list.h | 63 +- src/entity/zsp-list.cc | 283 +-- src/entity/zsp-list.h | 63 +- src/helper/debug-helper.h | 165 +- src/irs/irs-assisted-spectrum-channel.cc | 1083 +++++------ src/irs/irs-assisted-spectrum-channel.h | 145 +- src/irs/irs-list.cc | 272 +-- src/irs/irs-list.h | 64 +- src/irs/irs-patch.cc | 309 ++-- src/irs/irs-patch.h | 190 +- src/irs/irs.cc | 226 +-- src/irs/irs.h | 226 +-- src/main.cc | 1505 ++++++++-------- ...stant-acceleration-drone-mobility-model.cc | 147 +- ...nstant-acceleration-drone-mobility-model.h | 62 +- .../constant-acceleration-flight.cc | 170 +- .../constant-acceleration-flight.h | 60 +- .../constant-acceleration-param.cc | 20 +- .../constant-acceleration-param.h | 20 +- src/mobility/curve-point.cc | 100 +- src/mobility/curve-point.h | 147 +- src/mobility/curve.cc | 167 +- src/mobility/curve.h | 110 +- src/mobility/flight-plan.cc | 179 +- src/mobility/flight-plan.h | 381 ++-- .../parametric-speed-drone-mobility-model.cc | 144 +- .../parametric-speed-drone-mobility-model.h | 65 +- .../parametric-speed-flight.cc | 339 ++-- .../parametric-speed-flight.h | 78 +- .../parametric-speed-param.cc | 17 +- .../parametric-speed/parametric-speed-param.h | 17 +- src/mobility/planner.cc | 135 +- src/mobility/planner.h | 45 +- src/mobility/proto-point.cc | 74 +- src/mobility/proto-point.h | 125 +- src/peripheral/drone-peripheral-container.cc | 138 +- src/peripheral/drone-peripheral-container.h | 215 +-- src/peripheral/drone-peripheral.cc | 133 +- src/peripheral/drone-peripheral.h | 227 ++- src/peripheral/input-peripheral.cc | 123 +- src/peripheral/input-peripheral.h | 131 +- src/peripheral/storage-peripheral.cc | 126 +- src/peripheral/storage-peripheral.h | 110 +- src/report/drone-control-layer.cc | 62 +- src/report/drone-control-layer.h | 56 +- src/report/ipv4-layer.cc | 81 +- src/report/ipv4-layer.h | 58 +- src/report/lte-ue-phy-layer.cc | 143 +- src/report/lte-ue-phy-layer.h | 56 +- src/report/protocol-layer.cc | 56 +- src/report/protocol-layer.h | 27 +- src/report/report-container.cc | 81 +- src/report/report-container.h | 123 +- src/report/report-data-stats.cc | 71 +- src/report/report-data-stats.h | 61 +- src/report/report-default-iterator.h | 63 +- src/report/report-drone.cc | 344 ++-- src/report/report-drone.h | 118 +- src/report/report-entity.cc | 757 ++++---- src/report/report-entity.h | 253 ++- src/report/report-helper.cc | 10 +- src/report/report-helper.h | 5 +- src/report/report-location.cc | 96 +- src/report/report-location.h | 29 +- src/report/report-peripheral.cc | 100 +- src/report/report-peripheral.h | 16 +- src/report/report-protocol-stack.cc | 58 +- src/report/report-protocol-stack.h | 75 +- src/report/report-remote.cc | 207 +-- src/report/report-remote.h | 62 +- src/report/report-simulation.cc | 144 +- src/report/report-simulation.h | 108 +- src/report/report-transfer.cc | 249 ++- src/report/report-transfer.h | 99 +- src/report/report-world.cc | 163 +- src/report/report-world.h | 14 +- src/report/report-zsp.cc | 232 +-- src/report/report-zsp.h | 89 +- src/report/report.cc | 122 +- src/report/report.h | 96 +- src/report/schema.xsd | 2 +- src/report/simulation-duration.cc | 106 +- src/report/simulation-duration.h | 76 +- src/report/transfer-direction.cc | 36 +- src/report/transfer-direction.h | 97 +- src/report/wifi-inspector.cc | 213 +-- src/report/wifi-inspector.h | 115 +- src/report/wifi-mac-layer.cc | 75 +- src/report/wifi-mac-layer.h | 58 +- src/report/wifi-phy-layer.cc | 327 ++-- src/report/wifi-phy-layer.h | 122 +- src/world/interest-region-container.cc | 79 +- src/world/interest-region-container.h | 143 +- src/world/interest-region.cc | 71 +- src/world/interest-region.h | 70 +- 199 files changed, 13497 insertions(+), 12988 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2991aa2..d863fc3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -234,4 +234,4 @@ build_example( ${libnetwork} ${libwifi} ${libinternet} -) +) \ No newline at end of file diff --git a/src/application/drone-client-application.cc b/src/application/drone-client-application.cc index 39265bb..0329c91 100644 --- a/src/application/drone-client-application.cc +++ b/src/application/drone-client-application.cc @@ -15,331 +15,336 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -#include -#include -#include +#include "drone-client-application.h" -#include -#include -#include +#include "drone-communications.h" +#include #include #include +#include +#include #include -#include "drone-client-application.h" -#include "drone-communications.h" +#include +#include +#include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("DroneClientApplication"); -NS_OBJECT_ENSURE_REGISTERED (DroneClientApplication); +NS_LOG_COMPONENT_DEFINE("DroneClientApplication"); +NS_OBJECT_ENSURE_REGISTERED(DroneClientApplication); TypeId -DroneClientApplication::GetTypeId () +DroneClientApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::DroneClientApplication") - .SetParent () - .AddConstructor () - .AddAttribute ("DestinationIpv4Address", "IPv4 Address of the destination device", - Ipv4AddressValue (Ipv4Address::GetBroadcast ()), - MakeIpv4AddressAccessor (&DroneClientApplication::m_destAddr), - MakeIpv4AddressChecker ()) - .AddAttribute ("Port", "Destination application port.", - UintegerValue (80), - MakeUintegerAccessor (&DroneClientApplication::m_destPort), - MakeUintegerChecker ()) - .AddAttribute ("TransmissionInterval", "Interval between the transmission of packets, in seconds.", - DoubleValue (1.0), - MakeDoubleAccessor (&DroneClientApplication::m_interval), - MakeDoubleChecker ()) - .AddAttribute ("InitialHandshake", "Flag for initial HELLO handshake between client and server.", - BooleanValue (true), - MakeBooleanAccessor (&DroneClientApplication::m_initialHandshakeEnable), - MakeBooleanChecker ()) - .AddAttribute ("FreeData", "Free data if the StoragePeripheral is available.", - BooleanValue (false), - MakeBooleanAccessor (&DroneClientApplication::m_storage), - MakeBooleanChecker()) - .AddTraceSource ("Tx", "A new packet is created and is sent", - MakeTraceSourceAccessor (&DroneClientApplication::m_txTrace), - "ns3::Packet::TracedCallback") - ; - - return tid; + static TypeId tid = + TypeId("ns3::DroneClientApplication") + .SetParent() + .AddConstructor() + .AddAttribute("DestinationIpv4Address", + "IPv4 Address of the destination device", + Ipv4AddressValue(Ipv4Address::GetBroadcast()), + MakeIpv4AddressAccessor(&DroneClientApplication::m_destAddr), + MakeIpv4AddressChecker()) + .AddAttribute("Port", + "Destination application port.", + UintegerValue(80), + MakeUintegerAccessor(&DroneClientApplication::m_destPort), + MakeUintegerChecker()) + .AddAttribute("TransmissionInterval", + "Interval between the transmission of packets, in seconds.", + DoubleValue(1.0), + MakeDoubleAccessor(&DroneClientApplication::m_interval), + MakeDoubleChecker()) + .AddAttribute("InitialHandshake", + "Flag for initial HELLO handshake between client and server.", + BooleanValue(true), + MakeBooleanAccessor(&DroneClientApplication::m_initialHandshakeEnable), + MakeBooleanChecker()) + .AddAttribute("FreeData", + "Free data if the StoragePeripheral is available.", + BooleanValue(false), + MakeBooleanAccessor(&DroneClientApplication::m_storage), + MakeBooleanChecker()) + .AddTraceSource("Tx", + "A new packet is created and is sent", + MakeTraceSourceAccessor(&DroneClientApplication::m_txTrace), + "ns3::Packet::TracedCallback"); + + return tid; } -DroneClientApplication::DroneClientApplication () +DroneClientApplication::DroneClientApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_state = CLOSED; - m_sequenceNumber = 0; + m_state = CLOSED; + m_sequenceNumber = 0; } -DroneClientApplication::~DroneClientApplication () +DroneClientApplication::~DroneClientApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_state = CLOSED; + m_state = CLOSED; } void -DroneClientApplication::DoDispose () +DroneClientApplication::DoDispose() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - if (m_socket != NULL) - m_socket->Close (); + if (m_socket != NULL) + m_socket->Close(); - m_state = CLOSED; + m_state = CLOSED; - Application::DoDispose (); + Application::DoDispose(); } void -DroneClientApplication::StartApplication () +DroneClientApplication::StartApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - if (m_socket == NULL) + if (m_socket == NULL) { - Ptr socketFactory = GetNode ()->GetObject (UdpSocketFactory::GetTypeId ()); - m_socket = socketFactory->CreateSocket (); + Ptr socketFactory = + GetNode()->GetObject(UdpSocketFactory::GetTypeId()); + m_socket = socketFactory->CreateSocket(); - m_socket->SetAllowBroadcast (true); - m_socket->SetRecvCallback (MakeCallback (&DroneClientApplication::ReceivePacket, this)); + m_socket->SetAllowBroadcast(true); + m_socket->SetRecvCallback(MakeCallback(&DroneClientApplication::ReceivePacket, this)); - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] new client socket (" << m_socket << ")"); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] new client socket (" << m_socket << ")"); - /* set CourseChange callback using ns-3 XPath addressing system */ - const uint32_t nodeId = GetNode ()->GetId (); - std::stringstream xPathCallback; - xPathCallback << "/NodeList/" << nodeId - << "/$ns3::MobilityModel/CourseChange"; - Config::Connect (xPathCallback.str (), - MakeCallback (&DroneClientApplication::CourseChange, this)); - } + /* set CourseChange callback using ns-3 XPath addressing system */ + const uint32_t nodeId = GetNode()->GetId(); + std::stringstream xPathCallback; + xPathCallback << "/NodeList/" << nodeId << "/$ns3::MobilityModel/CourseChange"; + Config::Connect(xPathCallback.str(), + MakeCallback(&DroneClientApplication::CourseChange, this)); + } - Simulator::Cancel (m_sendEvent); + Simulator::Cancel(m_sendEvent); - if (m_initialHandshakeEnable) + if (m_initialHandshakeEnable) { - m_sendEvent = Simulator::ScheduleNow (&DroneClientApplication::SendPacket, this, NEW, m_socket, m_destAddr); + m_sendEvent = Simulator::ScheduleNow(&DroneClientApplication::SendPacket, + this, + NEW, + m_socket, + m_destAddr); } - else + else { - m_state = CONNECTED; + m_state = CONNECTED; - for (double i = Simulator::Now ().GetSeconds (); i < m_stopTime.GetSeconds (); i += m_interval) + for (double i = Simulator::Now().GetSeconds(); i < m_stopTime.GetSeconds(); i += m_interval) { - Simulator::ScheduleWithContext (GetNode ()->GetId (), - Seconds (i), - &DroneClientApplication::SendPacket, - this, - NEW, - m_socket, - m_destAddr); + Simulator::ScheduleWithContext(GetNode()->GetId(), + Seconds(i), + &DroneClientApplication::SendPacket, + this, + NEW, + m_socket, + m_destAddr); } } } void -DroneClientApplication::StopApplication () +DroneClientApplication::StopApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - Simulator::Cancel (m_sendEvent); + Simulator::Cancel(m_sendEvent); - if (m_socket != NULL) + if (m_socket != NULL) { - NS_LOG_LOGIC ("[Node " << GetNode ()->GetId () - << "] Closing client socket"); - m_socket->Close (); + NS_LOG_LOGIC("[Node " << GetNode()->GetId() << "] Closing client socket"); + m_socket->Close(); } } void -DroneClientApplication::SendPacket (const Intent i, - const Ptr socket, - const Ipv4Address targetAddress) const +DroneClientApplication::SendPacket(const Intent i, + const Ptr socket, + const Ipv4Address targetAddress) const { - NS_LOG_FUNCTION (this << ToString (i) << socket << targetAddress); + NS_LOG_FUNCTION(this << ToString(i) << socket << targetAddress); - if (m_socket != NULL) + if (m_socket != NULL) { - const char *command; - const auto nodeId = GetNode ()->GetId (); + const char* command; + const auto nodeId = GetNode()->GetId(); - if (m_state == CLOSED && i == NEW) + if (m_state == CLOSED && i == NEW) { - command = PacketType (PacketType::HELLO).ToString (); - m_state = HELLO_SENT; + command = PacketType(PacketType::HELLO).ToString(); + m_state = HELLO_SENT; } - else if (m_state == CONNECTED) + else if (m_state == CONNECTED) { - switch (i) + switch (i) { case NEW: - command = PacketType (PacketType::UPDATE).ToString (); - break; + command = PacketType(PacketType::UPDATE).ToString(); + break; case ACK: - command = PacketType (PacketType::UPDATE_ACK).ToString (); - break; + command = PacketType(PacketType::UPDATE_ACK).ToString(); + break; } } - else + else { - NS_LOG_WARN ("[Node " << nodeId << "] SendPacket" - << " reached an untained state."); - return; + NS_LOG_WARN("[Node " << nodeId << "] SendPacket" + << " reached an untained state."); + return; } - rapidjson::StringBuffer jsonBuf; - rapidjson::Writer writer (jsonBuf); - - // Try to get node info about current position and velocity - const auto mobilityModel = GetNode ()->GetObject (); - const auto pos = mobilityModel->GetPosition (); - const auto vel = mobilityModel->GetVelocity (); - - writer.StartObject (); - writer.Key ("id"); - writer.Int (nodeId); - writer.Key ("sn"); // Sequence Number - writer.Int (m_sequenceNumber++); - writer.Key ("cmd"); - writer.String (command); - writer.Key ("gps"); - writer.StartObject (); - writer.Key ("lat"); - writer.Double (pos.x); - writer.Key ("lon"); - writer.Double (pos.y); - writer.Key ("alt"); - writer.Double (pos.z); - writer.Key ("vel"); - writer.StartArray (); - writer.Double (vel.x); - writer.Double (vel.y); - writer.Double (vel.z); - writer.EndArray (); - writer.EndObject (); - writer.EndObject (); - - const char *json = jsonBuf.GetString (); - Ptr packet = Create ((const uint8_t*) json, - strlen (json) * sizeof (char)); - - socket->SendTo (packet, 0, InetSocketAddress (targetAddress, m_destPort)); - if (GetNode ()->GetInstanceTypeId().GetName() == "ns3::Drone" && DroneList::GetDrone(nodeId)->getPeripherals()->thereIsStorage() && m_storage) - { - Ptr storage = StaticCast (DroneList::GetDrone (nodeId)->getPeripherals ()->Get (0)); - if (storage->Free (strlen (json) * sizeof (char), StoragePeripheral::byte)) - NS_LOG_INFO ("[Node " << GetNode ()->GetId () << "] Freed " << strlen (json) * sizeof (char) << " bytes "); - } - m_txTrace (packet); - - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] sending packet " << json - << " to " << targetAddress << ":" << m_destPort); + rapidjson::StringBuffer jsonBuf; + rapidjson::Writer writer(jsonBuf); + + // Try to get node info about current position and velocity + const auto mobilityModel = GetNode()->GetObject(); + const auto pos = mobilityModel->GetPosition(); + const auto vel = mobilityModel->GetVelocity(); + + writer.StartObject(); + writer.Key("id"); + writer.Int(nodeId); + writer.Key("sn"); // Sequence Number + writer.Int(m_sequenceNumber++); + writer.Key("cmd"); + writer.String(command); + writer.Key("gps"); + writer.StartObject(); + writer.Key("lat"); + writer.Double(pos.x); + writer.Key("lon"); + writer.Double(pos.y); + writer.Key("alt"); + writer.Double(pos.z); + writer.Key("vel"); + writer.StartArray(); + writer.Double(vel.x); + writer.Double(vel.y); + writer.Double(vel.z); + writer.EndArray(); + writer.EndObject(); + writer.EndObject(); + + const char* json = jsonBuf.GetString(); + Ptr packet = Create((const uint8_t*)json, strlen(json) * sizeof(char)); + + socket->SendTo(packet, 0, InetSocketAddress(targetAddress, m_destPort)); + if (GetNode()->GetInstanceTypeId().GetName() == "ns3::Drone" && + DroneList::GetDrone(nodeId)->getPeripherals()->thereIsStorage() && m_storage) + { + Ptr storage = StaticCast( + DroneList::GetDrone(nodeId)->getPeripherals()->Get(0)); + if (storage->Free(strlen(json) * sizeof(char), StoragePeripheral::byte)) + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] Freed " + << strlen(json) * sizeof(char) << " bytes "); + } + m_txTrace(packet); + + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] sending packet " << json << " to " + << targetAddress << ":" << m_destPort); } - else + else { - NS_LOG_ERROR ("[Node " << GetNode ()->GetId () - << "] called SendPacket but socket is not initialized yet!"); + NS_LOG_ERROR("[Node " << GetNode()->GetId() + << "] called SendPacket but socket is not initialized yet!"); } } void -DroneClientApplication::ReceivePacket (const Ptr socket) +DroneClientApplication::ReceivePacket(const Ptr socket) { - NS_LOG_FUNCTION (this << socket); + NS_LOG_FUNCTION(this << socket); - Ptr packet; - Address senderAddr; + Ptr packet; + Address senderAddr; - while ((packet = socket->RecvFrom (senderAddr))) + while ((packet = socket->RecvFrom(senderAddr))) { - if (InetSocketAddress::IsMatchingType (senderAddr)) + if (InetSocketAddress::IsMatchingType(senderAddr)) { - const auto senderIpv4 = InetSocketAddress::ConvertFrom (senderAddr).GetIpv4 (); + const auto senderIpv4 = InetSocketAddress::ConvertFrom(senderAddr).GetIpv4(); - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] client received " << packet->GetSize() - << " bytes from " << senderIpv4); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] client received " << packet->GetSize() + << " bytes from " << senderIpv4); - uint8_t* payload = (uint8_t*) calloc (packet->GetSize () + 1, - sizeof (uint8_t)); - packet->CopyData (payload, packet->GetSize ()); + uint8_t* payload = (uint8_t*)calloc(packet->GetSize() + 1, sizeof(uint8_t)); + packet->CopyData(payload, packet->GetSize()); - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] packet contents: " << (char*) payload); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] packet contents: " << (char*)payload); - rapidjson::Document d; - d.Parse ((char*) payload); - const char* command = d["cmd"].GetString (); + rapidjson::Document d; + d.Parse((char*)payload); + const char* command = d["cmd"].GetString(); - if (PacketType (command) == PacketType::HELLO_ACK && m_state == HELLO_SENT) + if (PacketType(command) == PacketType::HELLO_ACK && m_state == HELLO_SENT) { - m_destAddr = senderIpv4; + m_destAddr = senderIpv4; - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] received HELLO_ACK with IP " << m_destAddr); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] received HELLO_ACK with IP " + << m_destAddr); - m_state = CONNECTED; + m_state = CONNECTED; - // It's safe to use Simulator::Now() here because we execute this code during the simulation. - // If we use Application Start Time attribute, we risk to insert events in the past, which is pure garbage. - for (double i = Simulator::Now ().GetSeconds (); i < m_stopTime.GetSeconds (); i += m_interval) + // It's safe to use Simulator::Now() here because we execute this code during the + // simulation. If we use Application Start Time attribute, we risk to insert events + // in the past, which is pure garbage. + for (double i = Simulator::Now().GetSeconds(); i < m_stopTime.GetSeconds(); + i += m_interval) { - Simulator::ScheduleWithContext (GetNode ()->GetId (), - Seconds (i), - &DroneClientApplication::SendPacket, - this, - NEW, - m_socket, - m_destAddr); + Simulator::ScheduleWithContext(GetNode()->GetId(), + Seconds(i), + &DroneClientApplication::SendPacket, + this, + NEW, + m_socket, + m_destAddr); } } - else if (PacketType (command) == PacketType::UPDATE_ACK - && m_state == CONNECTED) + else if (PacketType(command) == PacketType::UPDATE_ACK && m_state == CONNECTED) { - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] UPDATE_ACK received!"); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] UPDATE_ACK received!"); } - else if (PacketType (command) == PacketType::UPDATE - && m_state == CONNECTED) + else if (PacketType(command) == PacketType::UPDATE && m_state == CONNECTED) { - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] UPDATE received!"); - - m_sendEvent = Simulator::ScheduleNow (&DroneClientApplication::SendPacket, - this, - ACK, - socket, - senderIpv4); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] UPDATE received!"); + + m_sendEvent = Simulator::ScheduleNow(&DroneClientApplication::SendPacket, + this, + ACK, + socket, + senderIpv4); } - free (payload); + free(payload); } } } void -DroneClientApplication::CourseChange (const std::string context, - const Ptr mobility) const +DroneClientApplication::CourseChange(const std::string context, + const Ptr mobility) const { - //NS_LOG_FUNCTION (context << mobility); + // NS_LOG_FUNCTION (context << mobility); - const Vector position = mobility->GetPosition (); - const Vector velocity = mobility->GetVelocity (); + const Vector position = mobility->GetPosition(); + const Vector velocity = mobility->GetVelocity(); - NS_LOG_INFO (Simulator::Now () << " [Node " << GetNode ()->GetId () << "]" - << "; Pos: (" << position.x << ":" << position.y << ":" << position.z - << "); Vel: (" << velocity.x << ":" << velocity.y << ":" << velocity.z - << ")"); + NS_LOG_INFO(Simulator::Now() << " [Node " << GetNode()->GetId() << "]" + << "; Pos: (" << position.x << ":" << position.y << ":" + << position.z << "); Vel: (" << velocity.x << ":" << velocity.y + << ":" << velocity.z << ")"); } } // namespace ns3 diff --git a/src/application/drone-client-application.h b/src/application/drone-client-application.h index 980cf98..e53cf79 100644 --- a/src/application/drone-client-application.h +++ b/src/application/drone-client-application.h @@ -19,49 +19,48 @@ #define DRONE_CLIENT_APPLICATION_H #include +#include #include #include -#include -namespace ns3 { +namespace ns3 +{ /** * \brief the client states */ -enum -ClientState - { - CLOSED, /// the client has no sockets open - HELLO_SENT, /// the client has sent a HELLO packet in broadcast - CONNECTED /// the client has received a HELLO_ACK packet from a ZSP - }; +enum ClientState +{ + CLOSED, /// the client has no sockets open + HELLO_SENT, /// the client has sent a HELLO packet in broadcast + CONNECTED /// the client has received a HELLO_ACK packet from a ZSP +}; /** * \brief the intent of a packet */ -enum -Intent - { - NEW, /// this packet contains new information - ACK /// this packet represents an acknowledgement of a previous one - }; +enum Intent +{ + NEW, /// this packet contains new information + ACK /// this packet represents an acknowledgement of a previous one +}; /** * \brief Helper function to translate an Intent to a string, useful * for debugging purposes and serialization. */ inline const std::string -ToString (Intent i) +ToString(Intent i) { - switch (i) + switch (i) { case NEW: - return std::string("NEW"); + return std::string("NEW"); case ACK: - return std::string("ACK"); + return std::string("ACK"); } - return std::string("UNKNOWN"); + return std::string("UNKNOWN"); } /** @@ -70,79 +69,75 @@ ToString (Intent i) */ class DroneClientApplication : public Application { -public: - /** - * \brief Register this application as a type in ns-3 TypeId System. - */ - static TypeId GetTypeId (void); - - /** - * \brief default constructor - */ - DroneClientApplication (); - /** - * \brief default destructor - */ - virtual ~DroneClientApplication (); - -protected: - /** - * \brief Destructor implementation for the ns-3 TypeId System. - */ - virtual void DoDispose (); - -private: - /** - * \brief Start endpoint to conform with the Application Interface - */ - virtual void StartApplication (); - /** - * \brief Stop endpoint to conform with the Application Interface - */ - virtual void StopApplication (); - - /** - * \brief Send a packet to a given address in the IoD. - * - * \param i the intent of the packet to be sent. - * \param s the socket to be used. - * \param a the target address. - */ - void SendPacket (const Intent i, - const Ptr s, - const Ipv4Address a) const; - - /** - * \brief Callback to detect a new packet arrival. - * - * \param s the socket to be listened. - */ - void ReceivePacket (const Ptr s); - - /** - * \brief Callback to detect a variation in the mobility model and get - * new position and velocity vectors. - * - * \param context the context of the simulation - * \param mobility the mobility model - */ - void CourseChange (const std::string context, - const Ptr mobility) const; - - Ipv4Address m_destAddr; - uint32_t m_destPort; - double m_interval; - bool m_initialHandshakeEnable; - - Ptr m_socket; /// socket to be used for communications. - EventId m_sendEvent; /// event scheduled to send a new packet. - - mutable int32_t m_sequenceNumber; - mutable ClientState m_state; - - - TracedCallback> m_txTrace; - bool m_storage = false; + public: + /** + * \brief Register this application as a type in ns-3 TypeId System. + */ + static TypeId GetTypeId(void); + + /** + * \brief default constructor + */ + DroneClientApplication(); + /** + * \brief default destructor + */ + virtual ~DroneClientApplication(); + + protected: + /** + * \brief Destructor implementation for the ns-3 TypeId System. + */ + virtual void DoDispose(); + + private: + /** + * \brief Start endpoint to conform with the Application Interface + */ + virtual void StartApplication(); + /** + * \brief Stop endpoint to conform with the Application Interface + */ + virtual void StopApplication(); + + /** + * \brief Send a packet to a given address in the IoD. + * + * \param i the intent of the packet to be sent. + * \param s the socket to be used. + * \param a the target address. + */ + void SendPacket(const Intent i, const Ptr s, const Ipv4Address a) const; + + /** + * \brief Callback to detect a new packet arrival. + * + * \param s the socket to be listened. + */ + void ReceivePacket(const Ptr s); + + /** + * \brief Callback to detect a variation in the mobility model and get + * new position and velocity vectors. + * + * \param context the context of the simulation + * \param mobility the mobility model + */ + void CourseChange(const std::string context, const Ptr mobility) const; + + Ipv4Address m_destAddr; + uint32_t m_destPort; + double m_interval; + bool m_initialHandshakeEnable; + + Ptr m_socket; /// socket to be used for communications. + EventId m_sendEvent; /// event scheduled to send a new packet. + + mutable int32_t m_sequenceNumber; + mutable ClientState m_state; + + TracedCallback> m_txTrace; + bool m_storage = false; }; } // namespace ns3 diff --git a/src/application/drone-communications.cc b/src/application/drone-communications.cc index 37de3b7..74b8d89 100644 --- a/src/application/drone-communications.cc +++ b/src/application/drone-communications.cc @@ -19,58 +19,59 @@ #include -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_VALUE_IMPLEMENT (PacketType); -ATTRIBUTE_CHECKER_IMPLEMENT (PacketType); +ATTRIBUTE_VALUE_IMPLEMENT(PacketType); +ATTRIBUTE_CHECKER_IMPLEMENT(PacketType); -PacketType::PacketType (const char *a) +PacketType::PacketType(const char* a) { - for (uint8_t i = 0; i < numValues; i++) + for (uint8_t i = 0; i < numValues; i++) { - if (std::strcmp (a, stringValue[i]) == 0) + if (std::strcmp(a, stringValue[i]) == 0) { - m_value = Value (i); - return; + m_value = Value(i); + return; } } - NS_FATAL_ERROR ("Cannot decode packet type correctly: " << a); + NS_FATAL_ERROR("Cannot decode packet type correctly: " << a); } -PacketType::PacketType (const std::string a) +PacketType::PacketType(const std::string a) { - const char *aC = a.c_str (); + const char* aC = a.c_str(); - for (uint8_t i = 0; i < numValues; i++) + for (uint8_t i = 0; i < numValues; i++) { - if (std::strcmp (aC, stringValue[i]) == 0) + if (std::strcmp(aC, stringValue[i]) == 0) { - m_value = Value (i); - return; + m_value = Value(i); + return; } } - NS_FATAL_ERROR ("Cannot decode packet type correctly: " << aC); + NS_FATAL_ERROR("Cannot decode packet type correctly: " << aC); } -PacketType::PacketType (uint8_t i) +PacketType::PacketType(uint8_t i) { - if (i < numValues) - m_value = Value (i); - else - NS_FATAL_ERROR ("PacketType Index is out of range: " << i); + if (i < numValues) + m_value = Value(i); + else + NS_FATAL_ERROR("PacketType Index is out of range: " << i); } -std::istream & -operator >> (std::istream &is, PacketType &packetType) +std::istream& +operator>>(std::istream& is, PacketType& packetType) { - std::string packetString; + std::string packetString; - is >> packetString; - packetType = PacketType (packetString); + is >> packetString; + packetType = PacketType(packetString); - return is; + return is; } } // namespace ns3 diff --git a/src/application/drone-communications.h b/src/application/drone-communications.h index dc22772..4df5a87 100644 --- a/src/application/drone-communications.h +++ b/src/application/drone-communications.h @@ -18,67 +18,81 @@ #ifndef DRONE_COMMUNICATIONS_H #define DRONE_COMMUNICATIONS_H +#include + #include #include -#include - -namespace ns3 { +namespace ns3 +{ class PacketType { -public: - enum Value : uint8_t - { - HELLO, - HELLO_ACK, - UPDATE, - UPDATE_ACK, - UNKNOWN - }; - - constexpr static const uint8_t numValues = 5; - - const char *stringValue[numValues] = { - "HELLO", - "HELLO_ACK", - "UPDATE", - "UPDATE_ACK", - "UNKNOWN" - }; - - PacketType () = default; - constexpr PacketType (Value aType) : m_value {aType} {} - /** - * From C String - */ - PacketType (const char * a); - /** - * From C++ String - */ - PacketType (const std::string a); - /** - * From corresponding index - */ - PacketType (uint8_t i); - - operator Value () const { return m_value; } - explicit operator bool () = delete; - - constexpr bool operator == (Value a) { return m_value == a; } - constexpr bool operator != (Value a) { return m_value == a; } - - constexpr const char * ToString () const { return stringValue [m_value]; } - -private: - Value m_value; + public: + enum Value : uint8_t + { + HELLO, + HELLO_ACK, + UPDATE, + UPDATE_ACK, + UNKNOWN + }; + + constexpr static const uint8_t numValues = 5; + + const char* stringValue[numValues] = {"HELLO", "HELLO_ACK", "UPDATE", "UPDATE_ACK", "UNKNOWN"}; + + PacketType() = default; + + constexpr PacketType(Value aType) + : m_value{aType} + { + } + + /** + * From C String + */ + PacketType(const char* a); + /** + * From C++ String + */ + PacketType(const std::string a); + /** + * From corresponding index + */ + PacketType(uint8_t i); + + operator Value() const + { + return m_value; + } + + explicit operator bool() = delete; + + constexpr bool operator==(Value a) + { + return m_value == a; + } + + constexpr bool operator!=(Value a) + { + return m_value == a; + } + + constexpr const char* ToString() const + { + return stringValue[m_value]; + } + + private: + Value m_value; }; -ATTRIBUTE_VALUE_DEFINE (PacketType); -ATTRIBUTE_ACCESSOR_DEFINE (PacketType); -ATTRIBUTE_CHECKER_DEFINE (PacketType); +ATTRIBUTE_VALUE_DEFINE(PacketType); +ATTRIBUTE_ACCESSOR_DEFINE(PacketType); +ATTRIBUTE_CHECKER_DEFINE(PacketType); -std::istream & operator >> (std::istream &is, PacketType &packetType); +std::istream& operator>>(std::istream& is, PacketType& packetType); } // namespace ns3 diff --git a/src/application/drone-server-application.cc b/src/application/drone-server-application.cc index 28bd312..9b0be3e 100644 --- a/src/application/drone-server-application.cc +++ b/src/application/drone-server-application.cc @@ -17,249 +17,248 @@ */ #include "drone-server-application.h" +#include "drone-communications.h" + #include -#include +#include +#include #include +#include +#include #include -#include #include +#include -#include -#include -#include - -#include "drone-communications.h" - -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("DroneServerApplication"); +namespace ns3 +{ -NS_OBJECT_ENSURE_REGISTERED (DroneServerApplication); +NS_LOG_COMPONENT_DEFINE("DroneServerApplication"); +NS_OBJECT_ENSURE_REGISTERED(DroneServerApplication); TypeId -DroneServerApplication::GetTypeId () +DroneServerApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::DroneServerApplication") - .SetParent () - .AddConstructor () - .AddAttribute ("Port", "Listening port.", - UintegerValue (80), - MakeUintegerAccessor (&DroneServerApplication::m_port), - MakeUintegerChecker ()) - .AddAttribute ("StoreData", "Store data if the StoragePeripheral is available.", - BooleanValue (false), - MakeBooleanAccessor (&DroneServerApplication::m_storage), - MakeBooleanChecker()) - ; - - return tid; + static TypeId tid = TypeId("ns3::DroneServerApplication") + .SetParent() + .AddConstructor() + .AddAttribute("Port", + "Listening port.", + UintegerValue(80), + MakeUintegerAccessor(&DroneServerApplication::m_port), + MakeUintegerChecker()) + .AddAttribute("StoreData", + "Store data if the StoragePeripheral is available.", + BooleanValue(false), + MakeBooleanAccessor(&DroneServerApplication::m_storage), + MakeBooleanChecker()); + + return tid; } -DroneServerApplication::DroneServerApplication () +DroneServerApplication::DroneServerApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_state = SERVER_CLOSED; - m_sequenceNumber = 0; + m_state = SERVER_CLOSED; + m_sequenceNumber = 0; } -DroneServerApplication::~DroneServerApplication () +DroneServerApplication::~DroneServerApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_state = SERVER_CLOSED; + m_state = SERVER_CLOSED; } void -DroneServerApplication::DoDispose () +DroneServerApplication::DoDispose() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - if (m_socket != NULL) - m_socket->Close (); + if (m_socket != NULL) + m_socket->Close(); - m_state = SERVER_CLOSED; + m_state = SERVER_CLOSED; - Application::DoDispose (); + Application::DoDispose(); } void -DroneServerApplication::StartApplication () +DroneServerApplication::StartApplication() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - if (m_state == SERVER_CLOSED) + if (m_state == SERVER_CLOSED) { - if (m_socket == NULL) + if (m_socket == NULL) { - Ptr socketFactory = - GetNode ()->GetObject (UdpSocketFactory::GetTypeId ()); + Ptr socketFactory = + GetNode()->GetObject(UdpSocketFactory::GetTypeId()); - m_socket = socketFactory->CreateSocket (); + m_socket = socketFactory->CreateSocket(); - m_socket->SetAllowBroadcast (true); - m_socket->Bind (InetSocketAddress (Ipv4Address::GetAny (), m_port)); - m_socket->SetRecvCallback (MakeCallback (&DroneServerApplication::ReceivePacket, this)); + m_socket->SetAllowBroadcast(true); + m_socket->Bind(InetSocketAddress(Ipv4Address::GetAny(), m_port)); + m_socket->SetRecvCallback(MakeCallback(&DroneServerApplication::ReceivePacket, this)); - NS_LOG_INFO ("[Node " << GetNode ()->GetId () << "] " - "new server socket (" << m_socket << ")"); + NS_LOG_INFO("[Node " << GetNode()->GetId() + << "] " + "new server socket (" + << m_socket << ")"); } - m_state = SERVER_LISTEN; + m_state = SERVER_LISTEN; - Simulator::Cancel (m_sendEvent); + Simulator::Cancel(m_sendEvent); } } void -DroneServerApplication::StopApplication () +DroneServerApplication::StopApplication() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - if (m_socket != NULL && m_state == SERVER_LISTEN) + if (m_socket != NULL && m_state == SERVER_LISTEN) { - NS_LOG_LOGIC ("[Node " << GetNode ()->GetId () << "] Closing server socket"); - m_socket->Close (); + NS_LOG_LOGIC("[Node " << GetNode()->GetId() << "] Closing server socket"); + m_socket->Close(); } } void -DroneServerApplication::ReceivePacket (const Ptr socket) const +DroneServerApplication::ReceivePacket(const Ptr socket) const { - NS_LOG_FUNCTION (socket); + NS_LOG_FUNCTION(socket); - Ptr packet; - Address senderAddr; + Ptr packet; + Address senderAddr; - while ((packet = socket->RecvFrom (senderAddr))) + while ((packet = socket->RecvFrom(senderAddr))) { - if (InetSocketAddress::IsMatchingType (senderAddr)) + if (InetSocketAddress::IsMatchingType(senderAddr)) { - const auto sockAddr = InetSocketAddress::ConvertFrom (senderAddr); - const auto senderIpv4 = sockAddr.GetIpv4 (); - const auto senderPort = sockAddr.GetPort (); - - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] received " << packet->GetSize () - << " bytes from " << senderIpv4); - - uint8_t *payload = (uint8_t *) calloc - (packet->GetSize () + 1, sizeof (uint8_t)); - - packet->CopyData (payload, packet->GetSize ()); - if (GetNode ()->GetInstanceTypeId().GetName() == "ns3::Drone" && DroneList::GetDrone(GetNode ()->GetId ())->getPeripherals()->thereIsStorage() && m_storage) - { - Ptr storage = StaticCast (DroneList::GetDrone (GetNode ()->GetId ())->getPeripherals ()->Get (0)); - if (storage->Alloc (strlen ((char*) payload) * sizeof (char), StoragePeripheral::byte)) - NS_LOG_INFO ("[Node " << GetNode ()->GetId () << "] Stored " << strlen ((char*) payload) * sizeof (char) << " bytes "); - } - - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] packet contents: " << (char*) payload); - - rapidjson::Document d; - d.Parse ((char *) payload); - if (d.HasParseError ()) + const auto sockAddr = InetSocketAddress::ConvertFrom(senderAddr); + const auto senderIpv4 = sockAddr.GetIpv4(); + const auto senderPort = sockAddr.GetPort(); + + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] received " << packet->GetSize() + << " bytes from " << senderIpv4); + + uint8_t* payload = (uint8_t*)calloc(packet->GetSize() + 1, sizeof(uint8_t)); + + packet->CopyData(payload, packet->GetSize()); + if (GetNode()->GetInstanceTypeId().GetName() == "ns3::Drone" && + DroneList::GetDrone(GetNode()->GetId())->getPeripherals()->thereIsStorage() && + m_storage) + { + Ptr storage = StaticCast( + DroneList::GetDrone(GetNode()->GetId())->getPeripherals()->Get(0)); + if (storage->Alloc(strlen((char*)payload) * sizeof(char), StoragePeripheral::byte)) + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] Stored " + << strlen((char*)payload) * sizeof(char) << " bytes "); + } + + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] packet contents: " << (char*)payload); + + rapidjson::Document d; + d.Parse((char*)payload); + if (d.HasParseError()) { - NS_LOG_INFO ("[Node " << GetNode ()->GetId () << "] Received malformed packet! DROP"); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] Received malformed packet! DROP"); } - else + else { - const char *commandStr = d["cmd"].GetString (); - const PacketType command = PacketType (commandStr); + const char* commandStr = d["cmd"].GetString(); + const PacketType command = PacketType(commandStr); - switch (command) + switch (command) { case PacketType::HELLO: - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] HELLO packet!"); - m_sendEvent = Simulator::ScheduleNow (&DroneServerApplication::SendHelloAck, - this, - socket, - senderIpv4, - senderPort); - break; + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] HELLO packet!"); + m_sendEvent = Simulator::ScheduleNow(&DroneServerApplication::SendHelloAck, + this, + socket, + senderIpv4, + senderPort); + break; case PacketType::UPDATE: - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] UPDATE packet!"); - m_sendEvent = Simulator::ScheduleNow (&DroneServerApplication::SendUpdateAck, - this, - socket, - senderIpv4, - senderPort); - break; + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] UPDATE packet!"); + m_sendEvent = Simulator::ScheduleNow(&DroneServerApplication::SendUpdateAck, + this, + socket, + senderIpv4, + senderPort); + break; case PacketType::UPDATE_ACK: - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] UPDATE_ACK received!"); - break; + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] UPDATE_ACK received!"); + break; default: - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] unknown packet received!"); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] unknown packet received!"); } } - free (payload); + free(payload); } } } void -DroneServerApplication::SendHelloAck (const Ptr socket, - const Ipv4Address senderAddr, - const uint32_t senderPort) const +DroneServerApplication::SendHelloAck(const Ptr socket, + const Ipv4Address senderAddr, + const uint32_t senderPort) const { - NS_LOG_FUNCTION (socket << senderAddr); + NS_LOG_FUNCTION(socket << senderAddr); - NS_LOG_INFO ("[Node " << GetNode ()->GetId () - << "] sending HELLO ACK back."); + NS_LOG_INFO("[Node " << GetNode()->GetId() << "] sending HELLO ACK back."); - const std::string command = PacketType (PacketType::HELLO_ACK).ToString (); + const std::string command = PacketType(PacketType::HELLO_ACK).ToString(); - rapidjson::StringBuffer jsonBuf; - rapidjson::Writer writer (jsonBuf); + rapidjson::StringBuffer jsonBuf; + rapidjson::Writer writer(jsonBuf); - writer.StartObject (); - writer.Key ("cmd"); - writer.String (command.c_str ()); - writer.Key ("sn"); - writer.Int (m_sequenceNumber++); - writer.EndObject (); + writer.StartObject(); + writer.Key("cmd"); + writer.String(command.c_str()); + writer.Key("sn"); + writer.Int(m_sequenceNumber++); + writer.EndObject(); - const char *json = jsonBuf.GetString (); - const auto packet = Create ((const uint8_t *) json, strlen (json) * sizeof (char)); + const char* json = jsonBuf.GetString(); + const auto packet = Create((const uint8_t*)json, strlen(json) * sizeof(char)); - socket->SendTo (packet, 0, InetSocketAddress (senderAddr, senderPort)); - m_txTrace (packet); + socket->SendTo(packet, 0, InetSocketAddress(senderAddr, senderPort)); + m_txTrace(packet); } void -DroneServerApplication::SendUpdateAck (const Ptr socket, - const Ipv4Address senderAddr, - const uint32_t senderPort) const +DroneServerApplication::SendUpdateAck(const Ptr socket, + const Ipv4Address senderAddr, + const uint32_t senderPort) const { - NS_LOG_FUNCTION (socket << senderAddr); - NS_LOG_INFO ("[Node " << GetNode ()->GetId () << "] " - "sending UPDATE ACK back."); + NS_LOG_FUNCTION(socket << senderAddr); + NS_LOG_INFO("[Node " << GetNode()->GetId() + << "] " + "sending UPDATE ACK back."); - const std::string command = PacketType (PacketType::UPDATE_ACK).ToString (); + const std::string command = PacketType(PacketType::UPDATE_ACK).ToString(); - rapidjson::StringBuffer jsonBuf; - rapidjson::Writer writer (jsonBuf); + rapidjson::StringBuffer jsonBuf; + rapidjson::Writer writer(jsonBuf); - writer.StartObject (); - writer.Key ("cmd"); - writer.String (command.c_str ()); - writer.Key ("sn"); - writer.Int (m_sequenceNumber++); - writer.EndObject (); + writer.StartObject(); + writer.Key("cmd"); + writer.String(command.c_str()); + writer.Key("sn"); + writer.Int(m_sequenceNumber++); + writer.EndObject(); - const char *json = jsonBuf.GetString (); - const auto packet = Create ((const uint8_t *) json, strlen (json) * sizeof (char)); + const char* json = jsonBuf.GetString(); + const auto packet = Create((const uint8_t*)json, strlen(json) * sizeof(char)); - socket->SendTo (packet, 0, InetSocketAddress (senderAddr, senderPort)); - m_txTrace (packet); + socket->SendTo(packet, 0, InetSocketAddress(senderAddr, senderPort)); + m_txTrace(packet); } } // namespace ns3 diff --git a/src/application/drone-server-application.h b/src/application/drone-server-application.h index 7b36e55..50bb9b4 100644 --- a/src/application/drone-server-application.h +++ b/src/application/drone-server-application.h @@ -22,50 +22,50 @@ #include #include -namespace ns3 { +namespace ns3 +{ -enum -ServerState - { - SERVER_CLOSED, - SERVER_LISTEN - }; +enum ServerState +{ + SERVER_CLOSED, + SERVER_LISTEN +}; class DroneServerApplication : public Application { -public: - static TypeId GetTypeId (); + public: + static TypeId GetTypeId(); - DroneServerApplication (); - virtual ~DroneServerApplication (); + DroneServerApplication(); + virtual ~DroneServerApplication(); -protected: - virtual void DoDispose (); + protected: + virtual void DoDispose(); -private: - virtual void StartApplication (); - virtual void StopApplication (); + private: + virtual void StartApplication(); + virtual void StopApplication(); - void ReceivePacket (const Ptr socket) const; - void SendHelloAck (const Ptr socket, - const Ipv4Address senderAddr, - const uint32_t senderPort) const; - void SendUpdateAck (const Ptr socket, + void ReceivePacket(const Ptr socket) const; + void SendHelloAck(const Ptr socket, const Ipv4Address senderAddr, const uint32_t senderPort) const; - void SendUpdateBroadcast () const; + void SendUpdateAck(const Ptr socket, + const Ipv4Address senderAddr, + const uint32_t senderPort) const; + void SendUpdateBroadcast() const; - Ptr m_socket; - Ipv4Address m_address; - Ipv4Mask m_subnetMask; - uint32_t m_port; - ServerState m_state; + Ptr m_socket; + Ipv4Address m_address; + Ipv4Mask m_subnetMask; + uint32_t m_port; + ServerState m_state; - mutable EventId m_sendEvent; - TracedCallback> m_txTrace; + mutable EventId m_sendEvent; + TracedCallback> m_txTrace; - mutable int32_t m_sequenceNumber; // correlated with the node, not the connection - bool m_storage = false; + mutable int32_t m_sequenceNumber; // correlated with the node, not the connection + bool m_storage = false; }; } // namespace ns3 diff --git a/src/application/nat-application.cc b/src/application/nat-application.cc index d661013..be27feb 100644 --- a/src/application/nat-application.cc +++ b/src/application/nat-application.cc @@ -19,243 +19,256 @@ #include #include -#include +#include +#include #include -#include #include #include #include -#include #include +#include +#include +#include #include -#include +#include #include #include -#include -#include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("NatApplication"); +NS_LOG_COMPONENT_DEFINE("NatApplication"); -NS_OBJECT_ENSURE_REGISTERED (NatApplication); +NS_OBJECT_ENSURE_REGISTERED(NatApplication); TypeId -NatApplication::GetTypeId () +NatApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::NatApplication") - .SetParent () - .SetGroupName ("drone") - .AddConstructor () - .AddAttribute ("InternalNetDeviceId", "Identifier of the Internal Network Device", - IntegerValue (0), - MakeIntegerAccessor (&NatApplication::m_intNetDevId), - MakeIntegerChecker ()) - .AddAttribute ("ExternalNetDeviceId", "Identifier of the External Network Device", - IntegerValue (1), - MakeIntegerAccessor (&NatApplication::m_extNetDevId), - MakeIntegerChecker ()) - ; - - return tid; + static TypeId tid = TypeId("ns3::NatApplication") + .SetParent() + .SetGroupName("drone") + .AddConstructor() + .AddAttribute("InternalNetDeviceId", + "Identifier of the Internal Network Device", + IntegerValue(0), + MakeIntegerAccessor(&NatApplication::m_intNetDevId), + MakeIntegerChecker()) + .AddAttribute("ExternalNetDeviceId", + "Identifier of the External Network Device", + IntegerValue(1), + MakeIntegerAccessor(&NatApplication::m_extNetDevId), + MakeIntegerChecker()); + + return tid; } -NatApplication::NatApplication () : - m_curNatPort {1} +NatApplication::NatApplication() + : m_curNatPort{1} { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); } -NatApplication::~NatApplication () +NatApplication::~NatApplication() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); } void -NatApplication::DoInitialize (void) +NatApplication::DoInitialize(void) { - NS_LOG_FUNCTION (m_intNetDevId << m_extNetDevId); + NS_LOG_FUNCTION(m_intNetDevId << m_extNetDevId); - auto node = GetNode (); + auto node = GetNode(); - // Set default route to loopback - Ipv4StaticRoutingHelper routingHelper; - Ptr nodeStaticRouting = routingHelper.GetStaticRouting (node->GetObject ()); + // Set default route to loopback + Ipv4StaticRoutingHelper routingHelper; + Ptr nodeStaticRouting = + routingHelper.GetStaticRouting(node->GetObject()); - for (uint32_t i = 0; i < nodeStaticRouting->GetNRoutes (); i++) + for (uint32_t i = 0; i < nodeStaticRouting->GetNRoutes(); i++) { - auto route = nodeStaticRouting->GetRoute (i).GetDestNetwork (); - if (route == Ipv4Address::GetAny ()) + auto route = nodeStaticRouting->GetRoute(i).GetDestNetwork(); + if (route == Ipv4Address::GetAny()) { - nodeStaticRouting->RemoveRoute (i); - i--; + nodeStaticRouting->RemoveRoute(i); + i--; } } - nodeStaticRouting->SetDefaultRoute (Ipv4Address::GetLoopback (), m_extNetDevId); + nodeStaticRouting->SetDefaultRoute(Ipv4Address::GetLoopback(), m_extNetDevId); - m_intNetDev = node->GetDevice(m_intNetDevId); - m_extNetDev = node->GetDevice(m_extNetDevId); + m_intNetDev = node->GetDevice(m_intNetDevId); + m_extNetDev = node->GetDevice(m_extNetDevId); - m_intNetDev->SetPromiscReceiveCallback (MakeCallback (&NatApplication::RecvPktFromIntNetDev, this)); - m_extNetDev->SetReceiveCallback (MakeCallback (&NatApplication::RecvPktFromExtNetDev, this)); + m_intNetDev->SetPromiscReceiveCallback( + MakeCallback(&NatApplication::RecvPktFromIntNetDev, this)); + m_extNetDev->SetReceiveCallback(MakeCallback(&NatApplication::RecvPktFromExtNetDev, this)); - Application::DoInitialize (); + Application::DoInitialize(); } bool -NatApplication::RecvPktFromIntNetDev (Ptr netdev, - Ptr pkt, - uint16_t protocol, - const Address& sender, - const Address& receiver, - enum NetDevice::PacketType pktType) +NatApplication::RecvPktFromIntNetDev(Ptr netdev, + Ptr pkt, + uint16_t protocol, + const Address& sender, + const Address& receiver, + enum NetDevice::PacketType pktType) { - NS_LOG_FUNCTION (this << netdev << pkt << protocol << sender << receiver << pktType); - return RecvPktFromNetDev (netdev, pkt, protocol, sender, receiver, pktType); + NS_LOG_FUNCTION(this << netdev << pkt << protocol << sender << receiver << pktType); + return RecvPktFromNetDev(netdev, pkt, protocol, sender, receiver, pktType); } bool -NatApplication::RecvPktFromExtNetDev (Ptr netdev, - Ptr pkt, - uint16_t protocol, - const Address& sender) +NatApplication::RecvPktFromExtNetDev(Ptr netdev, + Ptr pkt, + uint16_t protocol, + const Address& sender) { - NS_LOG_FUNCTION (this << netdev << pkt << protocol << sender); - //TODO: This is a fake address. How can we easily retrieve the receiver IP Address from the packet? - auto receiver = Ipv4Address::GetZero (); - - return RecvPktFromNetDev (netdev, pkt, protocol, sender, receiver, NetDevice::PacketType::PACKET_OTHERHOST); + NS_LOG_FUNCTION(this << netdev << pkt << protocol << sender); + // TODO: This is a fake address. How can we easily retrieve the receiver IP Address from the + // packet? + auto receiver = Ipv4Address::GetZero(); + + return RecvPktFromNetDev(netdev, + pkt, + protocol, + sender, + receiver, + NetDevice::PacketType::PACKET_OTHERHOST); } bool -NatApplication::RecvPktFromNetDev (Ptr netdev, - Ptr pkt, - uint16_t protocol, - const Address& senderMacAddr, - const Address& receiverMacAddr, - enum NetDevice::PacketType pktType) +NatApplication::RecvPktFromNetDev(Ptr netdev, + Ptr pkt, + uint16_t protocol, + const Address& senderMacAddr, + const Address& receiverMacAddr, + enum NetDevice::PacketType pktType) { - NS_LOG_FUNCTION (netdev << pkt << protocol << senderMacAddr << receiverMacAddr << pktType); + NS_LOG_FUNCTION(netdev << pkt << protocol << senderMacAddr << receiverMacAddr << pktType); - Ipv4Header ipHdr; - UdpHeader udpHdr; - uint8_t ipv4Protocol; // https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml + Ipv4Header ipHdr; + UdpHeader udpHdr; + uint8_t + ipv4Protocol; // https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml - // https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml - if (m_intNetDev == netdev && protocol == 2048 /* IPv4 */) + // https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml + if (m_intNetDev == netdev && protocol == 2048 /* IPv4 */) { - auto toBeSent = pkt->Copy (); - toBeSent->RemoveHeader (ipHdr); - ipv4Protocol = ipHdr.GetProtocol (); + auto toBeSent = pkt->Copy(); + toBeSent->RemoveHeader(ipHdr); + ipv4Protocol = ipHdr.GetProtocol(); - //TODO: if (ipv4Protocol == 6 /* TCP */) - if (ipv4Protocol == 17 /* UDP */) + // TODO: if (ipv4Protocol == 6 /* TCP */) + if (ipv4Protocol == 17 /* UDP */) { - toBeSent->RemoveHeader (udpHdr); + toBeSent->RemoveHeader(udpHdr); - NatEntry entry = { - .ipv4Addr = ipHdr.GetSource (), - .port = udpHdr.GetSourcePort (), - .macAddr = senderMacAddr - }; + NatEntry entry = {.ipv4Addr = ipHdr.GetSource(), + .port = udpHdr.GetSourcePort(), + .macAddr = senderMacAddr}; - auto outPort = m_natTable[entry]; - if (!outPort) + auto outPort = m_natTable[entry]; + if (!outPort) { - // TODO: TCP could break! - if (m_curNatPort <= 0 || m_curNatPort >= UINT16_MAX) - m_curNatPort = 1; + // TODO: TCP could break! + if (m_curNatPort <= 0 || m_curNatPort >= UINT16_MAX) + m_curNatPort = 1; - m_natTable[entry] = m_curNatPort; - outPort = m_curNatPort; + m_natTable[entry] = m_curNatPort; + outPort = m_curNatPort; - m_curNatPort++; + m_curNatPort++; } - // substitute source IP and port - auto ifId = m_extNetDev->GetIfIndex (); /* LTE does something strange with interface index */ - auto extIpv4Addr = GetNode ()->GetObject ()->GetAddress (ifId + 1, 0).GetLocal (); + // substitute source IP and port + auto ifId = + m_extNetDev->GetIfIndex(); /* LTE does something strange with interface index */ + auto extIpv4Addr = GetNode()->GetObject()->GetAddress(ifId + 1, 0).GetLocal(); - NS_LOG_LOGIC (ipHdr.GetSource () << ":" << udpHdr.GetSourcePort () << " -> " << extIpv4Addr << ":" << outPort); - ipHdr.SetSource (extIpv4Addr); - udpHdr.SetSourcePort (outPort); + NS_LOG_LOGIC(ipHdr.GetSource() << ":" << udpHdr.GetSourcePort() << " -> " << extIpv4Addr + << ":" << outPort); + ipHdr.SetSource(extIpv4Addr); + udpHdr.SetSourcePort(outPort); - toBeSent->AddHeader (udpHdr); - toBeSent->AddHeader (ipHdr); + toBeSent->AddHeader(udpHdr); + toBeSent->AddHeader(ipHdr); - // check if we have LTE UE as external net device - auto netdevObjName = m_extNetDev->GetInstanceTypeId ().GetName (); - if (netdevObjName == "ns3::LteUeNetDevice") + // check if we have LTE UE as external net device + auto netdevObjName = m_extNetDev->GetInstanceTypeId().GetName(); + if (netdevObjName == "ns3::LteUeNetDevice") { - auto netdevLteUe = StaticCast (m_extNetDev); - netdevLteUe->GetNas ()->Send (toBeSent, protocol); + auto netdevLteUe = StaticCast(m_extNetDev); + netdevLteUe->GetNas()->Send(toBeSent, protocol); } } } - else if (m_extNetDev == netdev && protocol == 2048 /* IPv4 */) + else if (m_extNetDev == netdev && protocol == 2048 /* IPv4 */) { - auto toBeSent = pkt->Copy (); - toBeSent->RemoveHeader (ipHdr); - ipv4Protocol = ipHdr.GetProtocol (); + auto toBeSent = pkt->Copy(); + toBeSent->RemoveHeader(ipHdr); + ipv4Protocol = ipHdr.GetProtocol(); - //TODO: if (ipv4Protocol == 6 /* TCP */) - if (ipv4Protocol == 17 /* UDP */) + // TODO: if (ipv4Protocol == 6 /* TCP */) + if (ipv4Protocol == 17 /* UDP */) { - toBeSent->RemoveHeader (udpHdr); + toBeSent->RemoveHeader(udpHdr); - auto currentDestPort = udpHdr.GetDestinationPort (); + auto currentDestPort = udpHdr.GetDestinationPort(); - auto matchedRule = InverseLookup (currentDestPort); - if (matchedRule == m_natTable.end ()) + auto matchedRule = InverseLookup(currentDestPort); + if (matchedRule == m_natTable.end()) { - NS_LOG_WARN ("Got a packet on the external interface that was never send from the internal network. DROP."); - return false; + NS_LOG_WARN("Got a packet on the external interface that was never send from the " + "internal network. DROP."); + return false; } - auto destIpv4Addr = matchedRule->first.ipv4Addr; - auto destPort = matchedRule->first.port; - auto destMacAddr = matchedRule->first.macAddr; + auto destIpv4Addr = matchedRule->first.ipv4Addr; + auto destPort = matchedRule->first.port; + auto destMacAddr = matchedRule->first.macAddr; - ipHdr.SetDestination (destIpv4Addr); - udpHdr.SetDestinationPort (destPort); - toBeSent->AddHeader (udpHdr); - toBeSent->AddHeader (ipHdr); + ipHdr.SetDestination(destIpv4Addr); + udpHdr.SetDestinationPort(destPort); + toBeSent->AddHeader(udpHdr); + toBeSent->AddHeader(ipHdr); - m_intNetDev->Send (toBeSent, destMacAddr, protocol); + m_intNetDev->Send(toBeSent, destMacAddr, protocol); } } - return true; + return true; } NatApplication::NatTableI -NatApplication::InverseLookup (uint16_t port) +NatApplication::InverseLookup(uint16_t port) { - for (auto rule = m_natTable.begin(); rule != m_natTable.end(); rule++) + for (auto rule = m_natTable.begin(); rule != m_natTable.end(); rule++) { - if (rule->second == port) - return rule; + if (rule->second == port) + return rule; } - return m_natTable.end(); + return m_natTable.end(); } size_t -NatApplication::NatEntryHash::operator() (NatApplication::NatEntry const &x) const +NatApplication::NatEntryHash::operator()(const NatApplication::NatEntry& x) const { - auto hashf = Hash::Function::Fnv1a(); - uint32_t raw_buf[2] = {'\0'}; + auto hashf = Hash::Function::Fnv1a(); + uint32_t raw_buf[2] = {'\0'}; - raw_buf[0] = x.ipv4Addr.Get (); - raw_buf[1] = x.port; + raw_buf[0] = x.ipv4Addr.Get(); + raw_buf[1] = x.port; - return hashf.GetHash32 ((const char*) &raw_buf, 2); + return hashf.GetHash32((const char*)&raw_buf, 2); }; -bool operator== (const NatApplication::NatEntry x, const NatApplication::NatEntry y) +bool +operator==(const NatApplication::NatEntry x, const NatApplication::NatEntry y) { - return x.ipv4Addr == y.ipv4Addr && x.macAddr == y.macAddr && x.port == y.port; + return x.ipv4Addr == y.ipv4Addr && x.macAddr == y.macAddr && x.port == y.port; } } // namespace ns3 diff --git a/src/application/nat-application.h b/src/application/nat-application.h index 817050d..b1c68e1 100644 --- a/src/application/nat-application.h +++ b/src/application/nat-application.h @@ -18,77 +18,79 @@ #ifndef NAT_APPLICATION_H #define NAT_APPLICATION_H -#include - #include #include #include #include -namespace ns3 { +#include + +namespace ns3 +{ class NatApplication : public Application { -public: - /** - * \brief Get the type ID. - * \return the object TypeId - */ - static TypeId GetTypeId (); - // virtual void DoDispose (); - - NatApplication (); - virtual ~NatApplication (); - - bool RecvPktFromIntNetDev (Ptr netdev, - Ptr pkt, - uint16_t protocol, - const Address& sender, - const Address& receiver, - enum NetDevice::PacketType pktType); - - bool RecvPktFromExtNetDev (Ptr netdev, - Ptr pkt, - uint16_t protocol, - const Address& sender); - - bool RecvPktFromNetDev (Ptr netdev, - Ptr pkt, - uint16_t protocol, - const Address& sender, - const Address& receiver, - enum NetDevice::PacketType pktType); - - typedef struct __NatEntry { - Ipv4Address ipv4Addr; - uint32_t port; - Address macAddr; - } NatEntry; - -protected: - virtual void DoInitialize (void); - -private: - class NatEntryHash - { public: - size_t operator() (NatEntry const &x) const; - }; - - typedef std::unordered_map NatTable; - typedef std::unordered_map::iterator NatTableI; - - NatTableI InverseLookup (uint16_t port); - - uint32_t m_intNetDevId; - uint32_t m_extNetDevId; - Ptr m_intNetDev; - Ptr m_extNetDev; - NatTable m_natTable; - uint16_t m_curNatPort; + /** + * \brief Get the type ID. + * \return the object TypeId + */ + static TypeId GetTypeId(); + // virtual void DoDispose (); + + NatApplication(); + virtual ~NatApplication(); + + bool RecvPktFromIntNetDev(Ptr netdev, + Ptr pkt, + uint16_t protocol, + const Address& sender, + const Address& receiver, + enum NetDevice::PacketType pktType); + + bool RecvPktFromExtNetDev(Ptr netdev, + Ptr pkt, + uint16_t protocol, + const Address& sender); + + bool RecvPktFromNetDev(Ptr netdev, + Ptr pkt, + uint16_t protocol, + const Address& sender, + const Address& receiver, + enum NetDevice::PacketType pktType); + + typedef struct __NatEntry + { + Ipv4Address ipv4Addr; + uint32_t port; + Address macAddr; + } NatEntry; + + protected: + virtual void DoInitialize(void); + + private: + class NatEntryHash + { + public: + size_t operator()(const NatEntry& x) const; + }; + + typedef std::unordered_map NatTable; + typedef std::unordered_map::iterator NatTableI; + + NatTableI InverseLookup(uint16_t port); + + uint32_t m_intNetDevId; + uint32_t m_extNetDevId; + Ptr m_intNetDev; + Ptr m_extNetDev; + NatTable m_natTable; + uint16_t m_curNatPort; }; -bool operator== (const NatApplication::NatEntry x, const NatApplication::NatEntry y); +bool operator==(const NatApplication::NatEntry x, const NatApplication::NatEntry y); } // namespace ns3 diff --git a/src/application/random-udp-application.cc b/src/application/random-udp-application.cc index 31f6f1c..09222f2 100644 --- a/src/application/random-udp-application.cc +++ b/src/application/random-udp-application.cc @@ -23,10 +23,11 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("RandomUdpApplication"); -NS_OBJECT_ENSURE_REGISTERED (RandomUdpApplication); +NS_LOG_COMPONENT_DEFINE("RandomUdpApplication"); +NS_OBJECT_ENSURE_REGISTERED(RandomUdpApplication); constexpr uint16_t IPv4_HDR_SZ = 24; /// Header size of IPv4 Header, in bytes. constexpr uint16_t UDP_HDR_SZ = 4; /// Header size of UDP Header, in bytes. @@ -34,136 +35,144 @@ constexpr uint16_t SEQTS_HDR_SZ = 12; /// Header size of SeqTsHeader, in bytes. constexpr uint16_t HDR_SZ = IPv4_HDR_SZ + UDP_HDR_SZ + SEQTS_HDR_SZ; TypeId -RandomUdpApplication::GetTypeId () +RandomUdpApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::RandomUdpApplication") - .SetParent () - .SetGroupName ("Applications") - .AddConstructor () - .AddAttribute ("RemoteAddress", "IP Address of the server.", - Ipv4AddressValue (Ipv4Address::GetBroadcast ()), - MakeIpv4AddressAccessor (&RandomUdpApplication::m_destAddr), - MakeIpv4AddressChecker ()) - .AddAttribute ("RemotePort", "Destination application port.", - UintegerValue (80), - MakeUintegerAccessor (&RandomUdpApplication::m_destPort), - MakeUintegerChecker ()) - .AddAttribute ("TransmissionRate", "Rate of the tranmission, in Hz.", - UintegerValue (1), - MakeUintegerAccessor (&RandomUdpApplication::m_txFreq), - MakeUintegerChecker (1)) - .AddAttribute ("PacketSize", "Size of the packet, in bytes, comprehensive of L3,4 header sizes.", - UintegerValue (UINT16_MAX), - MakeUintegerAccessor (&RandomUdpApplication::m_packetSize), - MakeUintegerChecker (HDR_SZ + 1, std::numeric_limits::max ())) - .AddTraceSource ("Tx", "A new packet is created and is sent", - MakeTraceSourceAccessor (&RandomUdpApplication::m_txTrace), - "ns3::Packet::TracedCallback") - ; - - return tid; + static TypeId tid = + TypeId("ns3::RandomUdpApplication") + .SetParent() + .SetGroupName("Applications") + .AddConstructor() + .AddAttribute("RemoteAddress", + "IP Address of the server.", + Ipv4AddressValue(Ipv4Address::GetBroadcast()), + MakeIpv4AddressAccessor(&RandomUdpApplication::m_destAddr), + MakeIpv4AddressChecker()) + .AddAttribute("RemotePort", + "Destination application port.", + UintegerValue(80), + MakeUintegerAccessor(&RandomUdpApplication::m_destPort), + MakeUintegerChecker()) + .AddAttribute("TransmissionRate", + "Rate of the tranmission, in Hz.", + UintegerValue(1), + MakeUintegerAccessor(&RandomUdpApplication::m_txFreq), + MakeUintegerChecker(1)) + .AddAttribute( + "PacketSize", + "Size of the packet, in bytes, comprehensive of L3,4 header sizes.", + UintegerValue(UINT16_MAX), + MakeUintegerAccessor(&RandomUdpApplication::m_packetSize), + MakeUintegerChecker(HDR_SZ + 1, std::numeric_limits::max())) + .AddTraceSource("Tx", + "A new packet is created and is sent", + MakeTraceSourceAccessor(&RandomUdpApplication::m_txTrace), + "ns3::Packet::TracedCallback"); + + return tid; } -RandomUdpApplication::RandomUdpApplication () : - m_sendEvent {EventId ()}, - m_seqNum {0} +RandomUdpApplication::RandomUdpApplication() + : m_sendEvent{EventId()}, + m_seqNum{0} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -RandomUdpApplication::~RandomUdpApplication () +RandomUdpApplication::~RandomUdpApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -RandomUdpApplication::DoInitialize () +RandomUdpApplication::DoInitialize() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_packetInterval = 1 / m_txFreq; - m_payloadSize = m_packetSize - IPv4_HDR_SZ - UDP_HDR_SZ - SEQTS_HDR_SZ; + m_packetInterval = 1 / m_txFreq; + m_payloadSize = m_packetSize - IPv4_HDR_SZ - UDP_HDR_SZ - SEQTS_HDR_SZ; - // Forward initialization event to parent objects - Application::DoInitialize (); + // Forward initialization event to parent objects + Application::DoInitialize(); } void -RandomUdpApplication::StartApplication () +RandomUdpApplication::StartApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - if (m_socket == NULL) + if (m_socket == NULL) { - Ptr socketFactory = GetNode ()->GetObject (UdpSocketFactory::GetTypeId ()); - m_socket = socketFactory->CreateSocket (); + Ptr socketFactory = + GetNode()->GetObject(UdpSocketFactory::GetTypeId()); + m_socket = socketFactory->CreateSocket(); - NS_ABORT_MSG_IF (m_socket->Bind () == -1, "Failed to bind IPv4-based Socket."); - m_socket->Connect (InetSocketAddress (m_destAddr, m_destPort)); + NS_ABORT_MSG_IF(m_socket->Bind() == -1, "Failed to bind IPv4-based Socket."); + m_socket->Connect(InetSocketAddress(m_destAddr, m_destPort)); } - // As this socket will be used for Tx only, make dummy callback if it Rx something - m_socket->SetRecvCallback (MakeNullCallback > ()); - m_socket->SetAllowBroadcast (true); // handle special cases where the remote address is broadcast - m_sendEvent = Simulator::ScheduleNow (&RandomUdpApplication::SendPacket, this); + // As this socket will be used for Tx only, make dummy callback if it Rx something + m_socket->SetRecvCallback(MakeNullCallback>()); + m_socket->SetAllowBroadcast(true); // handle special cases where the remote address is broadcast + m_sendEvent = Simulator::ScheduleNow(&RandomUdpApplication::SendPacket, this); } void -RandomUdpApplication::StopApplication () +RandomUdpApplication::StopApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - Simulator::Cancel (m_sendEvent); - if (m_socket != NULL) - m_socket->Close (); + Simulator::Cancel(m_sendEvent); + if (m_socket != NULL) + m_socket->Close(); } void -RandomUdpApplication::SendPacket () +RandomUdpApplication::SendPacket() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - SeqTsHeader seqTs; - auto p = CreatePacket (m_payloadSize); + SeqTsHeader seqTs; + auto p = CreatePacket(m_payloadSize); - seqTs.SetSeq (m_seqNum++); - p->AddHeader (seqTs); + seqTs.SetSeq(m_seqNum++); + p->AddHeader(seqTs); - if (m_socket->Send (p) >= 0) + if (m_socket->Send(p) >= 0) { - m_txTrace (p); + m_txTrace(p); } - else + else { - std::stringstream addrStr; + std::stringstream addrStr; - if (Ipv4Address::IsMatchingType (m_destAddr)) - addrStr << Ipv4Address::ConvertFrom (m_destAddr); - else if (Ipv6Address::IsMatchingType (m_destAddr)) - addrStr << Ipv6Address::ConvertFrom (m_destAddr); - else - addrStr << m_destAddr; + if (Ipv4Address::IsMatchingType(m_destAddr)) + addrStr << Ipv4Address::ConvertFrom(m_destAddr); + else if (Ipv6Address::IsMatchingType(m_destAddr)) + addrStr << Ipv6Address::ConvertFrom(m_destAddr); + else + addrStr << m_destAddr; - NS_LOG_WARN ("Error while sending " << m_packetSize << " bytes to " << addrStr.str ()); + NS_LOG_WARN("Error while sending " << m_packetSize << " bytes to " << addrStr.str()); } - m_sendEvent = Simulator::Schedule (Seconds (m_packetInterval), &RandomUdpApplication::SendPacket, this); + m_sendEvent = + Simulator::Schedule(Seconds(m_packetInterval), &RandomUdpApplication::SendPacket, this); } Ptr -RandomUdpApplication::CreatePacket (uint32_t size) const +RandomUdpApplication::CreatePacket(uint32_t size) const { - Ptr p; - uint8_t* buf = new uint8_t[size]; - uint16_t* buf16 = (uint16_t*) (buf); + Ptr p; + uint8_t* buf = new uint8_t[size]; + uint16_t* buf16 = (uint16_t*)(buf); - for (uint32_t i = 0; i < size / 2; i++) - buf16[i] = i; + for (uint32_t i = 0; i < size / 2; i++) + buf16[i] = i; - p = Create (buf, size); + p = Create(buf, size); delete[] buf; - return p; + return p; } } // namespace ns3 diff --git a/src/application/random-udp-application.h b/src/application/random-udp-application.h index 19a18ae..fbb8ee6 100644 --- a/src/application/random-udp-application.h +++ b/src/application/random-udp-application.h @@ -22,63 +22,67 @@ #include #include -namespace ns3 { +namespace ns3 +{ /** * Application that sends random packets with Seq.Num. and Timestamp to a remote server */ class RandomUdpApplication : public Application { -public: - /** - * \brief Register this application as a type in ns-3 TypeId System - */ - static TypeId GetTypeId (); - /** - * \brief Default constructor - */ - RandomUdpApplication (); - /** - * \brief Default destructor - */ - virtual ~RandomUdpApplication (); + public: + /** + * \brief Register this application as a type in ns-3 TypeId System + */ + static TypeId GetTypeId(); + /** + * \brief Default constructor + */ + RandomUdpApplication(); + /** + * \brief Default destructor + */ + virtual ~RandomUdpApplication(); -protected: - /** - * \brief Initialize the Object registered as TypeId - */ - virtual void DoInitialize (); + protected: + /** + * \brief Initialize the Object registered as TypeId + */ + virtual void DoInitialize(); -private: - /** - * \brief Start endpoint to conform with the Application Interface - */ - virtual void StartApplication (); - /** - * \brief Stop endpoint to conform with the Application Interface - */ - virtual void StopApplication (); + private: + /** + * \brief Start endpoint to conform with the Application Interface + */ + virtual void StartApplication(); + /** + * \brief Stop endpoint to conform with the Application Interface + */ + virtual void StopApplication(); - /** - * \brief Send a random packet - */ - void SendPacket (); - /** - * \brief Create the payload to be sent - */ - Ptr CreatePacket (uint32_t size) const; + /** + * \brief Send a random packet + */ + void SendPacket(); + /** + * \brief Create the payload to be sent + */ + Ptr CreatePacket(uint32_t size) const; - Ipv4Address m_destAddr; /// Remote Server Address - FIXME: Ipv6Address needs an additional parameter - uint16_t m_destPort; /// UDP Port - uint32_t m_txFreq; /// Transmission frequency - uint16_t m_packetSize; /// Packet size in bytes - 16 bits are given as limit due to UDP header field - TracedCallback> m_txTrace; /// Trace to signal the transmission of packets from application-level + Ipv4Address + m_destAddr; /// Remote Server Address - FIXME: Ipv6Address needs an additional parameter + uint16_t m_destPort; /// UDP Port + uint32_t m_txFreq; /// Transmission frequency + uint16_t + m_packetSize; /// Packet size in bytes - 16 bits are given as limit due to UDP header field + TracedCallback> + m_txTrace; /// Trace to signal the transmission of packets from application-level - EventId m_sendEvent; /// Event of a packet being sent - Ptr m_socket; /// The socket to be used for communications - uint32_t m_seqNum; /// Packet Sequence Number - uint16_t m_payloadSize; /// Payload size, excluding L3,4 header sizes - double m_packetInterval; /// Packet Tx interval, the inverse of m_txFreq, in Seconds + EventId m_sendEvent; /// Event of a packet being sent + Ptr m_socket; /// The socket to be used for communications + uint32_t m_seqNum; /// Packet Sequence Number + uint16_t m_payloadSize; /// Payload size, excluding L3,4 header sizes + double m_packetInterval; /// Packet Tx interval, the inverse of m_txFreq, in Seconds }; } // namespace ns3 diff --git a/src/application/tcp-client-server-application.cc b/src/application/tcp-client-server-application.cc index de90602..2c92d7b 100644 --- a/src/application/tcp-client-server-application.cc +++ b/src/application/tcp-client-server-application.cc @@ -21,218 +21,239 @@ #include #include -namespace ns3 { +namespace ns3 +{ NS_LOG_COMPONENT_DEFINE("TcpClientServerApplication"); NS_OBJECT_ENSURE_REGISTERED(TcpClientServerApplication); TypeId -TcpClientServerApplication::GetTypeId () +TcpClientServerApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::TcpClientServerApplication") - .SetParent () - .SetGroupName ("Applications") - .AddConstructor () - .AddAttribute ("Address", "Remote/Listening IP Address.", - Ipv4AddressValue (Ipv4Address::GetLoopback ()), - MakeIpv4AddressAccessor (&TcpClientServerApplication::m_addr), - MakeIpv4AddressChecker ()) - .AddAttribute ("Port", "Remote/Listening port.", - UintegerValue (4242), - MakeUintegerAccessor (&TcpClientServerApplication::m_port), - MakeUintegerChecker ()) - .AddTraceSource ("ConnectionEstablished", "A new connection has been established.", - MakeTraceSourceAccessor (&TcpClientServerApplication::m_connectionEstablishedTrace), - "ns3::TcpClientServerApplication::ConnectionSucceededCallback") - .AddTraceSource ("ConnectionClosed", "A connection has been closed successfully.", - MakeTraceSourceAccessor (&TcpClientServerApplication::m_connectionClosedTrace), - "ns3::TcpClientServerApplication::NormalCloseCallback") - ; - - return tid; + static TypeId tid = + TypeId("ns3::TcpClientServerApplication") + .SetParent() + .SetGroupName("Applications") + .AddConstructor() + .AddAttribute("Address", + "Remote/Listening IP Address.", + Ipv4AddressValue(Ipv4Address::GetLoopback()), + MakeIpv4AddressAccessor(&TcpClientServerApplication::m_addr), + MakeIpv4AddressChecker()) + .AddAttribute("Port", + "Remote/Listening port.", + UintegerValue(4242), + MakeUintegerAccessor(&TcpClientServerApplication::m_port), + MakeUintegerChecker()) + .AddTraceSource( + "ConnectionEstablished", + "A new connection has been established.", + MakeTraceSourceAccessor(&TcpClientServerApplication::m_connectionEstablishedTrace), + "ns3::TcpClientServerApplication::ConnectionSucceededCallback") + .AddTraceSource( + "ConnectionClosed", + "A connection has been closed successfully.", + MakeTraceSourceAccessor(&TcpClientServerApplication::m_connectionClosedTrace), + "ns3::TcpClientServerApplication::NormalCloseCallback"); + + return tid; } -TcpClientServerApplication::TcpClientServerApplication () +TcpClientServerApplication::TcpClientServerApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -TcpClientServerApplication::~TcpClientServerApplication () +TcpClientServerApplication::~TcpClientServerApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -TcpClientServerApplication::StartApplication () +TcpClientServerApplication::StartApplication() { - NS_LOG_FUNCTION (this); - NS_ABORT_MSG_IF (m_socket != NULL, "Application was called for startup, but the socket has been already initialized!"); - - Ptr socketFactory = GetNode ()->GetObject (TcpSocketFactory::GetTypeId ()); - m_socket = socketFactory->CreateSocket (); - - m_socket->SetAcceptCallback (MakeCallback (&TcpClientServerApplication::ConnectionRequestCallback, this), - MakeCallback (&TcpClientServerApplication::ConnectionEstablishedCallback, this)); - m_socket->SetConnectCallback (MakeCallback (&TcpClientServerApplication::ConnectionSucceededCallback, this), - MakeCallback (&TcpClientServerApplication::ConnectionFailedCallback, this)); - m_socket->SetCloseCallbacks (MakeCallback (&TcpClientServerApplication::NormalCloseCallback, this), - MakeCallback (&TcpClientServerApplication::ErrorCloseCallback, this)); - // m_socket->SetRecvCallback (MakeCallback (&TcpClientServerApplication::ReceivedDataCallback, this)); - m_socket->SetRecvCallback (MakeNullCallback> ()); + NS_LOG_FUNCTION(this); + NS_ABORT_MSG_IF( + m_socket != NULL, + "Application was called for startup, but the socket has been already initialized!"); + + Ptr socketFactory = + GetNode()->GetObject(TcpSocketFactory::GetTypeId()); + m_socket = socketFactory->CreateSocket(); + + m_socket->SetAcceptCallback( + MakeCallback(&TcpClientServerApplication::ConnectionRequestCallback, this), + MakeCallback(&TcpClientServerApplication::ConnectionEstablishedCallback, this)); + m_socket->SetConnectCallback( + MakeCallback(&TcpClientServerApplication::ConnectionSucceededCallback, this), + MakeCallback(&TcpClientServerApplication::ConnectionFailedCallback, this)); + m_socket->SetCloseCallbacks( + MakeCallback(&TcpClientServerApplication::NormalCloseCallback, this), + MakeCallback(&TcpClientServerApplication::ErrorCloseCallback, this)); + // m_socket->SetRecvCallback (MakeCallback + // (&TcpClientServerApplication::ReceivedDataCallback, this)); + m_socket->SetRecvCallback(MakeNullCallback>()); } void -TcpClientServerApplication::StopApplication () +TcpClientServerApplication::StopApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - if (m_socket != nullptr) + if (m_socket != nullptr) { - m_socket->Close (); - - m_socket->SetAcceptCallback (MakeNullCallback, const Address &> (), - MakeNullCallback, const Address &> ()); - m_socket->SetConnectCallback (MakeNullCallback> (), - MakeNullCallback> ()); - m_socket->SetCloseCallbacks (MakeNullCallback> (), - MakeNullCallback> ()); - m_socket->SetRecvCallback (MakeNullCallback> ()); + m_socket->Close(); + + m_socket->SetAcceptCallback(MakeNullCallback, const Address&>(), + MakeNullCallback, const Address&>()); + m_socket->SetConnectCallback(MakeNullCallback>(), + MakeNullCallback>()); + m_socket->SetCloseCallbacks(MakeNullCallback>(), + MakeNullCallback>()); + m_socket->SetRecvCallback(MakeNullCallback>()); } - m_socket = nullptr; + m_socket = nullptr; } void -TcpClientServerApplication::Listen () +TcpClientServerApplication::Listen() { - NS_LOG_FUNCTION (this); - int ret = 0; + NS_LOG_FUNCTION(this); + int ret = 0; - ret = m_socket->Bind (InetSocketAddress (m_addr, m_port)); - NS_ABORT_MSG_IF (ret < 0, "Failed to bind IPv4-based Socket to " << m_addr << ":" << m_port << "."); + ret = m_socket->Bind(InetSocketAddress(m_addr, m_port)); + NS_ABORT_MSG_IF(ret < 0, + "Failed to bind IPv4-based Socket to " << m_addr << ":" << m_port << "."); - ret = m_socket->Listen (); - NS_ABORT_MSG_IF (ret < 0, "Failed to listen to " << m_addr << ":" << m_port << ". ErrNo=" << m_socket->GetErrno ()); + ret = m_socket->Listen(); + NS_ABORT_MSG_IF(ret < 0, + "Failed to listen to " << m_addr << ":" << m_port + << ". ErrNo=" << m_socket->GetErrno()); } bool -TcpClientServerApplication::Connect () +TcpClientServerApplication::Connect() { - NS_LOG_FUNCTION (this); - int ret = 0; + NS_LOG_FUNCTION(this); + int ret = 0; - ret = m_socket->Bind (); - NS_ABORT_MSG_IF (ret < 0, "Failed to bind IPv4-based Socket."); + ret = m_socket->Bind(); + NS_ABORT_MSG_IF(ret < 0, "Failed to bind IPv4-based Socket."); - ret = m_socket->Connect (InetSocketAddress (m_addr, m_port)); - if (ret < 0) - NS_LOG_LOGIC ("Failed to connect to " << m_addr << ":" << m_port << " ErrNo=" << m_socket->GetErrno ()); + ret = m_socket->Connect(InetSocketAddress(m_addr, m_port)); + if (ret < 0) + NS_LOG_LOGIC("Failed to connect to " << m_addr << ":" << m_port + << " ErrNo=" << m_socket->GetErrno()); - return (ret == 0) ? true : false; + return (ret == 0) ? true : false; } void -TcpClientServerApplication::ReceivedDataCallback (Ptr s) +TcpClientServerApplication::ReceivedDataCallback(Ptr s) { - NS_LOG_FUNCTION (this << s); - // placeholder for child objects lacking receive functionality + NS_LOG_FUNCTION(this << s); + // placeholder for child objects lacking receive functionality } const Ipv4Address& -TcpClientServerApplication::GetAddress () const +TcpClientServerApplication::GetAddress() const { - return m_addr; + return m_addr; } const uint16_t& -TcpClientServerApplication::GetPort () const +TcpClientServerApplication::GetPort() const { - return m_port; + return m_port; } Ptr -TcpClientServerApplication::GetSocket () +TcpClientServerApplication::GetSocket() { - return m_socket; + return m_socket; } bool -TcpClientServerApplication::ConnectionRequestCallback (Ptr s, const Address& from) +TcpClientServerApplication::ConnectionRequestCallback(Ptr s, const Address& from) { - if (InetSocketAddress::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << InetSocketAddress::ConvertFrom (from)); - else if (Inet6SocketAddress::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << Inet6SocketAddress::ConvertFrom (from)); - else if (Ipv4Address::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << Ipv4Address::ConvertFrom (from)); - else if (Ipv6Address::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << Ipv6Address::ConvertFrom (from)); - else - NS_LOG_FUNCTION (this << s << from); - - return true; // Unconditionally accept new connection requests + if (InetSocketAddress::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << InetSocketAddress::ConvertFrom(from)); + else if (Inet6SocketAddress::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << Inet6SocketAddress::ConvertFrom(from)); + else if (Ipv4Address::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << Ipv4Address::ConvertFrom(from)); + else if (Ipv6Address::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << Ipv6Address::ConvertFrom(from)); + else + NS_LOG_FUNCTION(this << s << from); + + return true; // Unconditionally accept new connection requests } void -TcpClientServerApplication::ConnectionEstablishedCallback (Ptr s, const Address& from) -{ - if (InetSocketAddress::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << InetSocketAddress::ConvertFrom (from)); - else if (Inet6SocketAddress::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << Inet6SocketAddress::ConvertFrom (from)); - else if (Ipv4Address::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << Ipv4Address::ConvertFrom (from)); - else if (Ipv6Address::IsMatchingType (from)) - NS_LOG_FUNCTION (this << s << Ipv6Address::ConvertFrom (from)); - else - NS_LOG_FUNCTION (this << s << from); - - /* - * A typical connection is established after receiving an empty (i.e., no - * data) TCP packet with ACK flag. The actual data will follow in a separate - * packet after that and will be received by ReceivedDataCallback(). - * - * However, that empty ACK packet might get lost. In this case, we may - * receive the first data packet right here already, because it also counts - * as a new connection. The statement below attempts to fetch the data from - * that packet, if any. - */ - m_connectionEstablishedTrace (this, s); - s->SetRecvCallback (MakeCallback (&TcpClientServerApplication::ReceivedDataCallback, this)); +TcpClientServerApplication::ConnectionEstablishedCallback(Ptr s, const Address& from) +{ + if (InetSocketAddress::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << InetSocketAddress::ConvertFrom(from)); + else if (Inet6SocketAddress::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << Inet6SocketAddress::ConvertFrom(from)); + else if (Ipv4Address::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << Ipv4Address::ConvertFrom(from)); + else if (Ipv6Address::IsMatchingType(from)) + NS_LOG_FUNCTION(this << s << Ipv6Address::ConvertFrom(from)); + else + NS_LOG_FUNCTION(this << s << from); + + /* + * A typical connection is established after receiving an empty (i.e., no + * data) TCP packet with ACK flag. The actual data will follow in a separate + * packet after that and will be received by ReceivedDataCallback(). + * + * However, that empty ACK packet might get lost. In this case, we may + * receive the first data packet right here already, because it also counts + * as a new connection. The statement below attempts to fetch the data from + * that packet, if any. + */ + m_connectionEstablishedTrace(this, s); + s->SetRecvCallback(MakeCallback(&TcpClientServerApplication::ReceivedDataCallback, this)); } void -TcpClientServerApplication::ConnectionSucceededCallback (Ptr s) +TcpClientServerApplication::ConnectionSucceededCallback(Ptr s) { - NS_LOG_FUNCTION (this << s); - m_connectionEstablishedTrace (this, s); - s->SetRecvCallback (MakeCallback (&TcpClientServerApplication::ReceivedDataCallback, this)); + NS_LOG_FUNCTION(this << s); + m_connectionEstablishedTrace(this, s); + s->SetRecvCallback(MakeCallback(&TcpClientServerApplication::ReceivedDataCallback, this)); } void -TcpClientServerApplication::ConnectionFailedCallback (Ptr s) +TcpClientServerApplication::ConnectionFailedCallback(Ptr s) { - NS_LOG_FUNCTION (this << s); - NS_LOG_ERROR ("Cannot connect to " << m_addr << ":" << m_port); - s->SetCloseCallbacks (MakeNullCallback > (), MakeNullCallback > ()); + NS_LOG_FUNCTION(this << s); + NS_LOG_ERROR("Cannot connect to " << m_addr << ":" << m_port); + s->SetCloseCallbacks(MakeNullCallback>(), + MakeNullCallback>()); } void -TcpClientServerApplication::NormalCloseCallback (Ptr s) +TcpClientServerApplication::NormalCloseCallback(Ptr s) { - NS_LOG_FUNCTION (this << s); - NS_LOG_LOGIC (this << " Connection terminated."); - s->ShutdownSend (); - s->SetCloseCallbacks (MakeNullCallback > (), MakeNullCallback > ()); + NS_LOG_FUNCTION(this << s); + NS_LOG_LOGIC(this << " Connection terminated."); + s->ShutdownSend(); + s->SetCloseCallbacks(MakeNullCallback>(), + MakeNullCallback>()); } void -TcpClientServerApplication::ErrorCloseCallback (Ptr s) +TcpClientServerApplication::ErrorCloseCallback(Ptr s) { - NS_LOG_FUNCTION (this << s); - NS_LOG_ERROR (this << " Connection terminated abruptly. ErrNo=" << s->GetErrno ()); - s->Close (); - s->SetCloseCallbacks (MakeNullCallback > (), MakeNullCallback > ()); + NS_LOG_FUNCTION(this << s); + NS_LOG_ERROR(this << " Connection terminated abruptly. ErrNo=" << s->GetErrno()); + s->Close(); + s->SetCloseCallbacks(MakeNullCallback>(), + MakeNullCallback>()); } } // namespace ns3 diff --git a/src/application/tcp-client-server-application.h b/src/application/tcp-client-server-application.h index e26eddb..6163ca0 100644 --- a/src/application/tcp-client-server-application.h +++ b/src/application/tcp-client-server-application.h @@ -22,43 +22,44 @@ #include #include -namespace ns3 { +namespace ns3 +{ /** * Base application for reliable TCP-based client-server communications. */ class TcpClientServerApplication : public Application { -public: - static TypeId GetTypeId (); - TcpClientServerApplication (); - virtual ~TcpClientServerApplication (); + public: + static TypeId GetTypeId(); + TcpClientServerApplication(); + virtual ~TcpClientServerApplication(); -protected: - virtual void StartApplication (); - virtual void StopApplication (); - virtual void Listen (); - virtual bool Connect (); - virtual void ReceivedDataCallback (Ptr s); + protected: + virtual void StartApplication(); + virtual void StopApplication(); + virtual void Listen(); + virtual bool Connect(); + virtual void ReceivedDataCallback(Ptr s); - const Ipv4Address& GetAddress () const; - const uint16_t& GetPort () const; - Ptr GetSocket (); + const Ipv4Address& GetAddress() const; + const uint16_t& GetPort() const; + Ptr GetSocket(); -private: - bool ConnectionRequestCallback (Ptr s, const Address& a); - void ConnectionEstablishedCallback (Ptr s, const Address& a); - void ConnectionSucceededCallback (Ptr s); - void ConnectionFailedCallback (Ptr s); - void NormalCloseCallback (Ptr s); - void ErrorCloseCallback (Ptr s); + private: + bool ConnectionRequestCallback(Ptr s, const Address& a); + void ConnectionEstablishedCallback(Ptr s, const Address& a); + void ConnectionSucceededCallback(Ptr s); + void ConnectionFailedCallback(Ptr s); + void NormalCloseCallback(Ptr s); + void ErrorCloseCallback(Ptr s); - Ipv4Address m_addr; - uint16_t m_port; - Ptr m_socket; + Ipv4Address m_addr; + uint16_t m_port; + Ptr m_socket; - TracedCallback, Ptr > m_connectionEstablishedTrace; - TracedCallback, Ptr > m_connectionClosedTrace; + TracedCallback, Ptr> m_connectionEstablishedTrace; + TracedCallback, Ptr> m_connectionClosedTrace; }; } // namespace ns3 diff --git a/src/application/tcp-echo-server-application.cc b/src/application/tcp-echo-server-application.cc index 28c1657..4df775b 100644 --- a/src/application/tcp-echo-server-application.cc +++ b/src/application/tcp-echo-server-application.cc @@ -20,10 +20,11 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("TcpEchoServerApplication"); -NS_OBJECT_ENSURE_REGISTERED (TcpEchoServerApplication); +NS_LOG_COMPONENT_DEFINE("TcpEchoServerApplication"); +NS_OBJECT_ENSURE_REGISTERED(TcpEchoServerApplication); constexpr uint16_t IPv4_HDR_SZ = 24; /// Header size of IPv4 Header, in bytes. constexpr uint16_t TCP_HDR_SZ = 28; /// Max Header size of TCP Header, in bytes. @@ -31,66 +32,69 @@ constexpr uint16_t SEQTS_HDR_SZ = 12; /// Header size of SeqTsHeader, in bytes. constexpr uint16_t HDR_SZ = IPv4_HDR_SZ + TCP_HDR_SZ + SEQTS_HDR_SZ; TypeId -TcpEchoServerApplication::GetTypeId () +TcpEchoServerApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::TcpEchoServerApplication") - .SetParent () - .SetGroupName ("Applications") - .AddConstructor () - .AddTraceSource ("Rx", "A new packet has been received.", - MakeTraceSourceAccessor (&TcpEchoServerApplication::m_rxTrace), - "ns3::Packet::PacketAddressTracedCallback") - ; + static TypeId tid = + TypeId("ns3::TcpEchoServerApplication") + .SetParent() + .SetGroupName("Applications") + .AddConstructor() + .AddTraceSource("Rx", + "A new packet has been received.", + MakeTraceSourceAccessor(&TcpEchoServerApplication::m_rxTrace), + "ns3::Packet::PacketAddressTracedCallback"); - return tid; + return tid; } -TcpEchoServerApplication::TcpEchoServerApplication () +TcpEchoServerApplication::TcpEchoServerApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -TcpEchoServerApplication::~TcpEchoServerApplication () +TcpEchoServerApplication::~TcpEchoServerApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -TcpEchoServerApplication::StartApplication () +TcpEchoServerApplication::StartApplication() { - NS_LOG_FUNCTION (this); - TcpClientServerApplication::StartApplication (); - Listen (); + NS_LOG_FUNCTION(this); + TcpClientServerApplication::StartApplication(); + Listen(); } void -TcpEchoServerApplication::ReceivedDataCallback (Ptr s) +TcpEchoServerApplication::ReceivedDataCallback(Ptr s) { - NS_LOG_FUNCTION (this << s); - Ptr p; - Address from; + NS_LOG_FUNCTION(this << s); + Ptr p; + Address from; - while ((p = s->RecvFrom (from))) + while ((p = s->RecvFrom(from))) { - if (InetSocketAddress::IsMatchingType (from)) + if (InetSocketAddress::IsMatchingType(from)) { - auto sockAddr = InetSocketAddress::ConvertFrom (from); - NS_LOG_INFO (this << " Rx Packet (Size=" << p->GetSize () << "," - << "Sender=" << sockAddr.GetIpv4 () << ":" << sockAddr.GetPort () << ")"); + auto sockAddr = InetSocketAddress::ConvertFrom(from); + NS_LOG_INFO(this << " Rx Packet (Size=" << p->GetSize() << "," + << "Sender=" << sockAddr.GetIpv4() << ":" << sockAddr.GetPort() + << ")"); } - else if (Inet6SocketAddress::IsMatchingType (from)) + else if (Inet6SocketAddress::IsMatchingType(from)) { - auto sockAddr = Inet6SocketAddress::ConvertFrom (from); - NS_LOG_INFO (this << " Rx Packet (Size=" << p->GetSize () << "," - << "Sender=" << sockAddr.GetIpv6 () << ":" << sockAddr.GetPort () << ")"); + auto sockAddr = Inet6SocketAddress::ConvertFrom(from); + NS_LOG_INFO(this << " Rx Packet (Size=" << p->GetSize() << "," + << "Sender=" << sockAddr.GetIpv6() << ":" << sockAddr.GetPort() + << ")"); } - else + else { - NS_LOG_INFO (this << " Rx Packet (Size=" << p->GetSize () << "," - << "Sender=" << from << ")"); + NS_LOG_INFO(this << " Rx Packet (Size=" << p->GetSize() << "," + << "Sender=" << from << ")"); } - m_rxTrace (p, from); + m_rxTrace(p, from); } } diff --git a/src/application/tcp-echo-server-application.h b/src/application/tcp-echo-server-application.h index b3d17f3..5b6888d 100644 --- a/src/application/tcp-echo-server-application.h +++ b/src/application/tcp-echo-server-application.h @@ -20,24 +20,25 @@ #include "tcp-client-server-application.h" -namespace ns3 { +namespace ns3 +{ /** * Basic Server TCP application that echoes in case data is received. */ class TcpEchoServerApplication : public TcpClientServerApplication { -public: - static TypeId GetTypeId (); - TcpEchoServerApplication (); - virtual ~TcpEchoServerApplication (); + public: + static TypeId GetTypeId(); + TcpEchoServerApplication(); + virtual ~TcpEchoServerApplication(); -protected: - virtual void StartApplication (); - virtual void ReceivedDataCallback (Ptr s); + protected: + virtual void StartApplication(); + virtual void ReceivedDataCallback(Ptr s); -private: - TracedCallback, const Address& > m_rxTrace; + private: + TracedCallback, const Address&> m_rxTrace; }; } // namespace ns3 diff --git a/src/application/tcp-storage-client-application.cc b/src/application/tcp-storage-client-application.cc index c4e8d8f..1c9b7e5 100644 --- a/src/application/tcp-storage-client-application.cc +++ b/src/application/tcp-storage-client-application.cc @@ -17,16 +17,16 @@ */ #include "tcp-storage-client-application.h" +#include +#include #include #include -#include -#include - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("TcpStorageClientApplication"); -NS_OBJECT_ENSURE_REGISTERED (TcpStorageClientApplication); +NS_LOG_COMPONENT_DEFINE("TcpStorageClientApplication"); +NS_OBJECT_ENSURE_REGISTERED(TcpStorageClientApplication); constexpr uint16_t IPv4_HDR_SZ = 24; /// Header size of IPv4 Header, in bytes. constexpr uint16_t TCP_HDR_SZ = 28; /// Max Header size of TCP Header, in bytes. @@ -34,165 +34,177 @@ constexpr uint16_t SEQTS_HDR_SZ = 12; /// Header size of SeqTsHeader, in bytes. constexpr uint16_t HDR_SZ = IPv4_HDR_SZ + TCP_HDR_SZ + SEQTS_HDR_SZ; TypeId -TcpStorageClientApplication::GetTypeId () +TcpStorageClientApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::TcpStorageClientApplication") - .SetParent () - .SetGroupName ("Applications") - .AddConstructor () - .AddAttribute ("PayloadSize", "Size of the payload, in bytes.", - UintegerValue (std::numeric_limits::max () - HDR_SZ - 1), - MakeUintegerAccessor (&TcpStorageClientApplication::m_payloadSize), - MakeUintegerChecker (1, std::numeric_limits::max () - HDR_SZ - 1)) - .AddTraceSource ("Tx", "A new packet is created and sent", - MakeTraceSourceAccessor (&TcpStorageClientApplication::m_txTrace), - "ns3::Packet::TracedCallback") - ; - - return tid; + static TypeId tid = + TypeId("ns3::TcpStorageClientApplication") + .SetParent() + .SetGroupName("Applications") + .AddConstructor() + .AddAttribute( + "PayloadSize", + "Size of the payload, in bytes.", + UintegerValue(std::numeric_limits::max() - HDR_SZ - 1), + MakeUintegerAccessor(&TcpStorageClientApplication::m_payloadSize), + MakeUintegerChecker(1, std::numeric_limits::max() - HDR_SZ - 1)) + .AddTraceSource("Tx", + "A new packet is created and sent", + MakeTraceSourceAccessor(&TcpStorageClientApplication::m_txTrace), + "ns3::Packet::TracedCallback"); + + return tid; } -TcpStorageClientApplication::TcpStorageClientApplication () : - m_seqNum {0} +TcpStorageClientApplication::TcpStorageClientApplication() + : m_seqNum{0} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -TcpStorageClientApplication::~TcpStorageClientApplication () +TcpStorageClientApplication::~TcpStorageClientApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -TcpStorageClientApplication::DoInitialize () +TcpStorageClientApplication::DoInitialize() { - NS_LOG_FUNCTION (this); - TcpClientServerApplication::DoInitialize (); + NS_LOG_FUNCTION(this); + TcpClientServerApplication::DoInitialize(); - m_storage = FindStorage (); + m_storage = FindStorage(); } void -TcpStorageClientApplication::StartApplication () +TcpStorageClientApplication::StartApplication() { - NS_LOG_FUNCTION (this); - TcpClientServerApplication::StartApplication (); - Connect (); + NS_LOG_FUNCTION(this); + TcpClientServerApplication::StartApplication(); + Connect(); - m_storage->TraceConnectWithoutContext ("RemainingCapacity", - MakeCallback (&TcpStorageClientApplication::StorageUpdateCallback, this)); + m_storage->TraceConnectWithoutContext( + "RemainingCapacity", + MakeCallback(&TcpStorageClientApplication::StorageUpdateCallback, this)); } bool -TcpStorageClientApplication::DoSendPacket (const uint16_t payloadSize) +TcpStorageClientApplication::DoSendPacket(const uint16_t payloadSize) { - NS_LOG_FUNCTION (this << payloadSize); - const auto sock = GetSocket (); + NS_LOG_FUNCTION(this << payloadSize); + const auto sock = GetSocket(); - if (sock == nullptr) - return false; + if (sock == nullptr) + return false; - SeqTsHeader seqTs; - auto p = CreatePacket (payloadSize); + SeqTsHeader seqTs; + auto p = CreatePacket(payloadSize); - seqTs.SetSeq (m_seqNum++); - p->AddHeader (seqTs); + seqTs.SetSeq(m_seqNum++); + p->AddHeader(seqTs); - if (sock->Send (p) >= 0) + if (sock->Send(p) >= 0) { - m_txTrace (p); - return true; + m_txTrace(p); + return true; } - else + else { - std::stringstream addrStr; - const auto addr = GetAddress (); + std::stringstream addrStr; + const auto addr = GetAddress(); - if (Ipv4Address::IsMatchingType (addr)) - addrStr << Ipv4Address::ConvertFrom (addr); - else if (Ipv6Address::IsMatchingType (addr)) - addrStr << Ipv6Address::ConvertFrom (addr); - else - addrStr << addr; + if (Ipv4Address::IsMatchingType(addr)) + addrStr << Ipv4Address::ConvertFrom(addr); + else if (Ipv6Address::IsMatchingType(addr)) + addrStr << Ipv6Address::ConvertFrom(addr); + else + addrStr << addr; - NS_LOG_WARN ("Error while sending " << m_payloadSize << " bytes to " << addrStr.str () << "." - << " ErrNo=" << sock->GetErrno ()); + NS_LOG_WARN("Error while sending " << m_payloadSize << " bytes to " << addrStr.str() << "." + << " ErrNo=" << sock->GetErrno()); - return false; + return false; } } const uint16_t -TcpStorageClientApplication::GetPayloadSize () +TcpStorageClientApplication::GetPayloadSize() { - NS_LOG_FUNCTION (this); - return m_payloadSize; + NS_LOG_FUNCTION(this); + return m_payloadSize; } void -TcpStorageClientApplication::SendPacket (const uint16_t payloadSize) +TcpStorageClientApplication::SendPacket(const uint16_t payloadSize) { - NS_LOG_FUNCTION (this << payloadSize << GetNode ()->GetId ()); + NS_LOG_FUNCTION(this << payloadSize << GetNode()->GetId()); - if (DoSendPacket (payloadSize)) - Simulator::ScheduleNow (&StoragePeripheral::Free, m_storage, - (uint64_t) payloadSize, StoragePeripheral::byte); + if (DoSendPacket(payloadSize)) + Simulator::ScheduleNow(&StoragePeripheral::Free, + m_storage, + (uint64_t)payloadSize, + StoragePeripheral::byte); } Ptr -TcpStorageClientApplication::CreatePacket (uint32_t size) const +TcpStorageClientApplication::CreatePacket(uint32_t size) const { - NS_LOG_FUNCTION (this << size); + NS_LOG_FUNCTION(this << size); - Ptr p; - uint8_t* buf = new uint8_t[size]; - uint16_t* buf16 = (uint16_t*) (buf); + Ptr p; + uint8_t* buf = new uint8_t[size]; + uint16_t* buf16 = (uint16_t*)(buf); - for (uint32_t i = 0; i < size / 2; i++) - buf16[i] = i; + for (uint32_t i = 0; i < size / 2; i++) + buf16[i] = i; - p = Create (buf, size); + p = Create(buf, size); delete[] buf; - return p; + return p; } Ptr -TcpStorageClientApplication::FindStorage () const +TcpStorageClientApplication::FindStorage() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - auto drone = StaticCast (GetNode ()); - NS_ASSERT_MSG (drone != nullptr, "This application must be installed on a drone."); + auto drone = StaticCast(GetNode()); + NS_ASSERT_MSG(drone != nullptr, "This application must be installed on a drone."); - auto peripherals = drone->getPeripherals (); - NS_ASSERT_MSG (peripherals->thereIsStorage (), "Drone must be equipped with a storage peripheral"); + auto peripherals = drone->getPeripherals(); + NS_ASSERT_MSG(peripherals->thereIsStorage(), + "Drone must be equipped with a storage peripheral"); - // Drone storage is always the first one in the container - auto storage = StaticCast (peripherals->Get (0)); - NS_ASSERT_MSG (storage != nullptr, "Drone must be equipped with a storage peripheral."); + // Drone storage is always the first one in the container + auto storage = StaticCast(peripherals->Get(0)); + NS_ASSERT_MSG(storage != nullptr, "Drone must be equipped with a storage peripheral."); - return storage; + return storage; } void -TcpStorageClientApplication::StorageUpdateCallback (const uint64_t oldValBits, const uint64_t newValBits) +TcpStorageClientApplication::StorageUpdateCallback(const uint64_t oldValBits, + const uint64_t newValBits) { - NS_LOG_FUNCTION (this << oldValBits << newValBits); + NS_LOG_FUNCTION(this << oldValBits << newValBits); - const uint64_t maxPayloadSizeBits = m_payloadSize * StoragePeripheral::byte; - const uint64_t occupiedStorageBits = m_storage->GetCapacity () - newValBits; + const uint64_t maxPayloadSizeBits = m_payloadSize * StoragePeripheral::byte; + const uint64_t occupiedStorageBits = m_storage->GetCapacity() - newValBits; - if (occupiedStorageBits == 0) - return; + if (occupiedStorageBits == 0) + return; - NS_LOG_LOGIC ("Occupied memory in bits: " << occupiedStorageBits << " | MaxPayloadSize bits " << maxPayloadSizeBits); + NS_LOG_LOGIC("Occupied memory in bits: " << occupiedStorageBits << " | MaxPayloadSize bits " + << maxPayloadSizeBits); - uint16_t nextPayloadSizeBytes = (occupiedStorageBits >= maxPayloadSizeBits) - ? m_payloadSize - : occupiedStorageBits / StoragePeripheral::byte; + uint16_t nextPayloadSizeBytes = (occupiedStorageBits >= maxPayloadSizeBits) + ? m_payloadSize + : occupiedStorageBits / StoragePeripheral::byte; - Simulator::Schedule (Seconds(0.1), &TcpStorageClientApplication::SendPacket, this, nextPayloadSizeBytes); + Simulator::Schedule(Seconds(0.1), + &TcpStorageClientApplication::SendPacket, + this, + nextPayloadSizeBytes); } } // namespace ns3 diff --git a/src/application/tcp-storage-client-application.h b/src/application/tcp-storage-client-application.h index 8eddb81..eccdcaa 100644 --- a/src/application/tcp-storage-client-application.h +++ b/src/application/tcp-storage-client-application.h @@ -22,43 +22,44 @@ #include -namespace ns3 { +namespace ns3 +{ /** - * TCP client that transmits data to a remote server to free as much memory as possible on the storage peripheral - * attached to the same node. + * TCP client that transmits data to a remote server to free as much memory as possible on the + * storage peripheral attached to the same node. */ class TcpStorageClientApplication : public TcpClientServerApplication { -public: - static TypeId GetTypeId (); - TcpStorageClientApplication (); - virtual ~TcpStorageClientApplication (); + public: + static TypeId GetTypeId(); + TcpStorageClientApplication(); + virtual ~TcpStorageClientApplication(); -protected: - virtual void DoInitialize (); - virtual void StartApplication (); - /// \brief Send a random packet of a given size. - virtual bool DoSendPacket (const uint16_t payloadSize); + protected: + virtual void DoInitialize(); + virtual void StartApplication(); + /// \brief Send a random packet of a given size. + virtual bool DoSendPacket(const uint16_t payloadSize); - const uint16_t GetPayloadSize (); + const uint16_t GetPayloadSize(); -private: - /// \brief Send a packet and, if successful, free storage memory. - void SendPacket (const uint16_t payloadSize); - /// \brief Create the payload to be sent. - Ptr CreatePacket (uint32_t size) const; - /// \brief Find storage in drone. - Ptr FindStorage () const; - /// \brief Callback when the underlying drone storage receives data updates. - void StorageUpdateCallback (const uint64_t oldvalue, const uint64_t newvalue); + private: + /// \brief Send a packet and, if successful, free storage memory. + void SendPacket(const uint16_t payloadSize); + /// \brief Create the payload to be sent. + Ptr CreatePacket(uint32_t size) const; + /// \brief Find storage in drone. + Ptr FindStorage() const; + /// \brief Callback when the underlying drone storage receives data updates. + void StorageUpdateCallback(const uint64_t oldvalue, const uint64_t newvalue); - uint16_t m_payloadSize; /// Payload size in bytes. - uint32_t m_seqNum; /// Packet Sequence Number. - Ptr m_storage; /// Reference to drone storage peripheral. + uint16_t m_payloadSize; /// Payload size in bytes. + uint32_t m_seqNum; /// Packet Sequence Number. + Ptr m_storage; /// Reference to drone storage peripheral. - /// Trace to signal the transmission of packets from application-level. - TracedCallback > m_txTrace; + /// Trace to signal the transmission of packets from application-level. + TracedCallback> m_txTrace; }; } // namespace ns3 diff --git a/src/application/tcp-stub-client-application.cc b/src/application/tcp-stub-client-application.cc index f63b22a..d10770c 100644 --- a/src/application/tcp-stub-client-application.cc +++ b/src/application/tcp-stub-client-application.cc @@ -17,87 +17,89 @@ */ #include "tcp-stub-client-application.h" +#include +#include #include #include #include #include #include -#include -#include - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("TcpStubClientApplication"); -NS_OBJECT_ENSURE_REGISTERED (TcpStubClientApplication); +NS_LOG_COMPONENT_DEFINE("TcpStubClientApplication"); +NS_OBJECT_ENSURE_REGISTERED(TcpStubClientApplication); TypeId -TcpStubClientApplication::GetTypeId () +TcpStubClientApplication::GetTypeId() { - static TypeId tid = TypeId ("ns3::TcpStubClientApplication") - .SetParent () - .SetGroupName ("Applications") - .AddConstructor () - .AddAttribute ("TxFrequency", "Transmission frequency for packets.", - DoubleValue (1), - MakeDoubleAccessor (&TcpStubClientApplication::m_txFrequency), - MakeDoubleChecker (0)) - ; - - return tid; + static TypeId tid = + TypeId("ns3::TcpStubClientApplication") + .SetParent() + .SetGroupName("Applications") + .AddConstructor() + .AddAttribute("TxFrequency", + "Transmission frequency for packets.", + DoubleValue(1), + MakeDoubleAccessor(&TcpStubClientApplication::m_txFrequency), + MakeDoubleChecker(0)); + + return tid; } -TcpStubClientApplication::TcpStubClientApplication () +TcpStubClientApplication::TcpStubClientApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -TcpStubClientApplication::~TcpStubClientApplication () +TcpStubClientApplication::~TcpStubClientApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -TcpStubClientApplication::DoInitialize () +TcpStubClientApplication::DoInitialize() { - m_txInterval = Seconds (1.0 / m_txFrequency); + m_txInterval = Seconds(1.0 / m_txFrequency); } void -TcpStubClientApplication::StartApplication () +TcpStubClientApplication::StartApplication() { - NS_LOG_FUNCTION (this); - TcpClientServerApplication::StartApplication (); + NS_LOG_FUNCTION(this); + TcpClientServerApplication::StartApplication(); - Simulator::ScheduleNow (&TcpStubClientApplication::Connect, this); // TODO: parametrize Seconds (0.5) - //Simulator::Schedule (m_txInterval, &TcpStubClientApplication::SendPacket, this); + Simulator::ScheduleNow(&TcpStubClientApplication::Connect, + this); // TODO: parametrize Seconds (0.5) + // Simulator::Schedule (m_txInterval, &TcpStubClientApplication::SendPacket, this); } bool -TcpStubClientApplication::Connect () +TcpStubClientApplication::Connect() { - NS_LOG_FUNCTION (this); - const bool isConnected = TcpClientServerApplication::Connect (); + NS_LOG_FUNCTION(this); + const bool isConnected = TcpClientServerApplication::Connect(); - if (isConnected) + if (isConnected) { - Simulator::Schedule (m_txInterval, &TcpStubClientApplication::SendPacket, this); + Simulator::Schedule(m_txInterval, &TcpStubClientApplication::SendPacket, this); } - else + else { - NS_LOG_LOGIC ("Connect will retry again later."); - Simulator::Schedule (Seconds (0.5), &TcpStubClientApplication::Connect, this); + NS_LOG_LOGIC("Connect will retry again later."); + Simulator::Schedule(Seconds(0.5), &TcpStubClientApplication::Connect, this); } - return isConnected; + return isConnected; } void -TcpStubClientApplication::SendPacket () +TcpStubClientApplication::SendPacket() { - NS_LOG_FUNCTION (this << GetNode ()->GetId ()); - DoSendPacket (GetPayloadSize ()); - Simulator::Schedule (m_txInterval, &TcpStubClientApplication::SendPacket, this); + NS_LOG_FUNCTION(this << GetNode()->GetId()); + DoSendPacket(GetPayloadSize()); + Simulator::Schedule(m_txInterval, &TcpStubClientApplication::SendPacket, this); } } // namespace ns3 diff --git a/src/application/tcp-stub-client-application.h b/src/application/tcp-stub-client-application.h index a435d2f..eadda0d 100644 --- a/src/application/tcp-stub-client-application.h +++ b/src/application/tcp-stub-client-application.h @@ -25,30 +25,31 @@ #include #include -namespace ns3 { +namespace ns3 +{ /** * Application that sends random packets with Seq.Num. and Timestamp to a remote server */ class TcpStubClientApplication : public TcpStorageClientApplication { -public: - static TypeId GetTypeId (); - TcpStubClientApplication (); - virtual ~TcpStubClientApplication (); - -protected: - virtual void DoInitialize (); - virtual void StartApplication (); - -private: - /// \brief Schedule intial handshake with remote server - bool Connect (); - /// \brief Send a random packet of a given size - void SendPacket (); - - double m_txFrequency; /// Transmission frequency - ns3::Time m_txInterval; /// Frequency inverse + public: + static TypeId GetTypeId(); + TcpStubClientApplication(); + virtual ~TcpStubClientApplication(); + + protected: + virtual void DoInitialize(); + virtual void StartApplication(); + + private: + /// \brief Schedule intial handshake with remote server + bool Connect(); + /// \brief Send a random packet of a given size + void SendPacket(); + + double m_txFrequency; /// Transmission frequency + ns3::Time m_txInterval; /// Frequency inverse }; } // namespace ns3 diff --git a/src/application/udp-echo-client-application.cc b/src/application/udp-echo-client-application.cc index 384dac8..c17dcf3 100644 --- a/src/application/udp-echo-client-application.cc +++ b/src/application/udp-echo-client-application.cc @@ -22,142 +22,142 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("IoDSim::UdpEchoClientApplication"); +NS_LOG_COMPONENT_DEFINE("IoDSim::UdpEchoClientApplication"); -NS_OBJECT_ENSURE_REGISTERED (UdpEchoClientApplication); +NS_OBJECT_ENSURE_REGISTERED(UdpEchoClientApplication); TypeId -UdpEchoClientApplication::GetTypeId (void) +UdpEchoClientApplication::GetTypeId(void) { - static TypeId tid = TypeId ("ns3::UdpEchoClientApplication") - .SetParent () - .SetGroupName("Applications") - .AddConstructor () - .AddAttribute ("Interval", - "The time to wait between packets", TimeValue (Seconds (1.0)), - MakeTimeAccessor (&UdpEchoClientApplication::m_interval), - MakeTimeChecker ()) - .AddAttribute ("RemoteAddress", - "The destination Address of the outbound packets", - Ipv4AddressValue (), - MakeIpv4AddressAccessor (&UdpEchoClientApplication::m_peerAddress), - MakeIpv4AddressChecker ()) - .AddAttribute ("RemotePort", "The destination port of the outbound packets", - UintegerValue (100), - MakeUintegerAccessor (&UdpEchoClientApplication::m_peerPort), - MakeUintegerChecker ()) - .AddAttribute ("PacketSize", - "Size of packets generated. The minimum packet size is 12 bytes which is the size of the header carrying the sequence number and the time stamp.", - UintegerValue (1024), - MakeUintegerAccessor (&UdpEchoClientApplication::m_size), - MakeUintegerChecker (12,65507)) - ; - return tid; + static TypeId tid = + TypeId("ns3::UdpEchoClientApplication") + .SetParent() + .SetGroupName("Applications") + .AddConstructor() + .AddAttribute("Interval", + "The time to wait between packets", + TimeValue(Seconds(1.0)), + MakeTimeAccessor(&UdpEchoClientApplication::m_interval), + MakeTimeChecker()) + .AddAttribute("RemoteAddress", + "The destination Address of the outbound packets", + Ipv4AddressValue(), + MakeIpv4AddressAccessor(&UdpEchoClientApplication::m_peerAddress), + MakeIpv4AddressChecker()) + .AddAttribute("RemotePort", + "The destination port of the outbound packets", + UintegerValue(100), + MakeUintegerAccessor(&UdpEchoClientApplication::m_peerPort), + MakeUintegerChecker()) + .AddAttribute("PacketSize", + "Size of packets generated. The minimum packet size is 12 bytes which is " + "the size of the header carrying the sequence number and the time stamp.", + UintegerValue(1024), + MakeUintegerAccessor(&UdpEchoClientApplication::m_size), + MakeUintegerChecker(12, 65507)); + return tid; } -UdpEchoClientApplication::UdpEchoClientApplication () +UdpEchoClientApplication::UdpEchoClientApplication() { - NS_LOG_FUNCTION (this); - m_sent = 0; - m_totalTx = 0; - m_socket = 0; - m_sendEvent = EventId (); + NS_LOG_FUNCTION(this); + m_sent = 0; + m_totalTx = 0; + m_socket = 0; + m_sendEvent = EventId(); } -UdpEchoClientApplication::~UdpEchoClientApplication () +UdpEchoClientApplication::~UdpEchoClientApplication() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -UdpEchoClientApplication::SetRemote (Ipv4Address ip, uint16_t port) +UdpEchoClientApplication::SetRemote(Ipv4Address ip, uint16_t port) { - NS_LOG_FUNCTION (this << ip << port); - m_peerAddress = ip; - m_peerPort = port; + NS_LOG_FUNCTION(this << ip << port); + m_peerAddress = ip; + m_peerPort = port; } void -UdpEchoClientApplication::SetRemote (Ipv4Address addr) +UdpEchoClientApplication::SetRemote(Ipv4Address addr) { - NS_LOG_FUNCTION (this << addr); - m_peerAddress = addr; + NS_LOG_FUNCTION(this << addr); + m_peerAddress = addr; } void -UdpEchoClientApplication::DoDispose (void) +UdpEchoClientApplication::DoDispose(void) { - NS_LOG_FUNCTION (this); - Application::DoDispose (); + NS_LOG_FUNCTION(this); + Application::DoDispose(); } void -UdpEchoClientApplication::StartApplication (void) +UdpEchoClientApplication::StartApplication(void) { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); if (m_socket == nullptr) { - TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory"); - m_socket = Socket::CreateSocket (GetNode (), tid); + TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory"); + m_socket = Socket::CreateSocket(GetNode(), tid); - if (m_socket->Bind () == -1) + if (m_socket->Bind() == -1) { - NS_FATAL_ERROR ("Failed to bind socket"); + NS_FATAL_ERROR("Failed to bind socket"); } - m_socket->Connect (InetSocketAddress (m_peerAddress, m_peerPort)); + m_socket->Connect(InetSocketAddress(m_peerAddress, m_peerPort)); } - m_socket->SetRecvCallback (MakeNullCallback > ()); - m_socket->SetAllowBroadcast (true); - m_sendEvent = Simulator::Schedule (Seconds (0.0), &UdpEchoClientApplication::Send, this); + m_socket->SetRecvCallback(MakeNullCallback>()); + m_socket->SetAllowBroadcast(true); + m_sendEvent = Simulator::Schedule(Seconds(0.0), &UdpEchoClientApplication::Send, this); } void -UdpEchoClientApplication::StopApplication (void) +UdpEchoClientApplication::StopApplication(void) { - NS_LOG_FUNCTION (this); - Simulator::Cancel (m_sendEvent); + NS_LOG_FUNCTION(this); + Simulator::Cancel(m_sendEvent); } void -UdpEchoClientApplication::Send (void) +UdpEchoClientApplication::Send(void) { - NS_LOG_FUNCTION (this); - NS_ASSERT (m_sendEvent.IsExpired ()); - SeqTsHeader seqTs; - seqTs.SetSeq (m_sent); - Ptr p = Create (m_size - 8 + 4); // 8+4 : the size of the seqTs header - p->AddHeader (seqTs); - - if ((m_socket->Send (p)) >= 0) + NS_LOG_FUNCTION(this); + NS_ASSERT(m_sendEvent.IsExpired()); + SeqTsHeader seqTs; + seqTs.SetSeq(m_sent); + Ptr p = Create(m_size - 8 + 4); // 8+4 : the size of the seqTs header + p->AddHeader(seqTs); + + if ((m_socket->Send(p)) >= 0) { - ++m_sent; - m_totalTx += p->GetSize (); - - NS_LOG_INFO ("TX " << m_size << " bytes to " - << m_peerAddress << " " - << "Uid: " << p->GetUid () << " " - << "Time: " << Simulator::Now ().As (Time::S) << " " - << "Packet: " << p->ToString ()); + ++m_sent; + m_totalTx += p->GetSize(); + + NS_LOG_INFO("TX " << m_size << " bytes to " << m_peerAddress << " " + << "Uid: " << p->GetUid() << " " + << "Time: " << Simulator::Now().As(Time::S) << " " + << "Packet: " << p->ToString()); } - else + else { - NS_LOG_INFO ("Error while sending " << m_size << " bytes to " - << m_peerAddress); + NS_LOG_INFO("Error while sending " << m_size << " bytes to " << m_peerAddress); } - m_sendEvent = Simulator::Schedule (m_interval, &UdpEchoClientApplication::Send, this); + m_sendEvent = Simulator::Schedule(m_interval, &UdpEchoClientApplication::Send, this); } - uint64_t -UdpEchoClientApplication::GetTotalTx () const +UdpEchoClientApplication::GetTotalTx() const { - return m_totalTx; + return m_totalTx; } - } // Namespace ns3 diff --git a/src/application/udp-echo-client-application.h b/src/application/udp-echo-client-application.h index aaeeba7..1ff8c4c 100644 --- a/src/application/udp-echo-client-application.h +++ b/src/application/udp-echo-client-application.h @@ -20,12 +20,13 @@ #define UDP_ECHO_CLIENT_APPLICATION_H #include -#include #include +#include #include #include -namespace ns3 { +namespace ns3 +{ /** * \ingroup udpclientserver @@ -36,56 +37,55 @@ namespace ns3 { */ class UdpEchoClientApplication : public Application { -public: - /** - * \brief Get the type ID. - * \return the object TypeId - */ - static TypeId GetTypeId (void); - - UdpEchoClientApplication (); - - virtual ~UdpEchoClientApplication (); - - /** - * \brief set the remote address and port - * \param ip remote IP address - * \param port remote port - */ - void SetRemote (Ipv4Address ip, uint16_t port); - /** - * \brief set the remote address - * \param addr remote address - */ - void SetRemote (Ipv4Address addr); - - /** - * \return the total bytes sent by this app - */ - uint64_t GetTotalTx () const; - -protected: - virtual void DoDispose (void); - -private: - - virtual void StartApplication (void); - virtual void StopApplication (void); - - /** - * \brief Send a packet - */ - void Send (void); - - Time m_interval; //!< Packet inter-send time - uint32_t m_size; //!< Size of the sent packet (including the SeqTsHeader) - - uint32_t m_sent; //!< Counter for sent packets - uint64_t m_totalTx; //!< Total bytes sent - Ptr m_socket; //!< Socket - Ipv4Address m_peerAddress; //!< Remote peer address - uint16_t m_peerPort; //!< Remote peer port - EventId m_sendEvent; //!< Event to send the next packet + public: + /** + * \brief Get the type ID. + * \return the object TypeId + */ + static TypeId GetTypeId(void); + + UdpEchoClientApplication(); + + virtual ~UdpEchoClientApplication(); + + /** + * \brief set the remote address and port + * \param ip remote IP address + * \param port remote port + */ + void SetRemote(Ipv4Address ip, uint16_t port); + /** + * \brief set the remote address + * \param addr remote address + */ + void SetRemote(Ipv4Address addr); + + /** + * \return the total bytes sent by this app + */ + uint64_t GetTotalTx() const; + + protected: + virtual void DoDispose(void); + + private: + virtual void StartApplication(void); + virtual void StopApplication(void); + + /** + * \brief Send a packet + */ + void Send(void); + + Time m_interval; //!< Packet inter-send time + uint32_t m_size; //!< Size of the sent packet (including the SeqTsHeader) + + uint32_t m_sent; //!< Counter for sent packets + uint64_t m_totalTx; //!< Total bytes sent + Ptr m_socket; //!< Socket + Ipv4Address m_peerAddress; //!< Remote peer address + uint16_t m_peerPort; //!< Remote peer port + EventId m_sendEvent; //!< Event to send the next packet }; } // namespace ns3 diff --git a/src/configuration/base/double-vector.cc b/src/configuration/base/double-vector.cc index 492cb1c..f1deab3 100644 --- a/src/configuration/base/double-vector.cc +++ b/src/configuration/base/double-vector.cc @@ -21,125 +21,124 @@ #include #include -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_HELPER_CPP (DoubleVector); +ATTRIBUTE_HELPER_CPP(DoubleVector); -DoubleVector::DoubleVector () +DoubleVector::DoubleVector() { } -DoubleVector::DoubleVector (std::vector coeffs) +DoubleVector::DoubleVector(std::vector coeffs) { - for (auto c : coeffs) + for (auto c : coeffs) { - Add (c); + Add(c); } } -DoubleVector::DoubleVector (const DoubleVector &a) +DoubleVector::DoubleVector(const DoubleVector& a) { - for (auto c = a.Begin (); c != a.End (); c++) + for (auto c = a.Begin(); c != a.End(); c++) { - Add (*c); + Add(*c); } } DoubleVector::Iterator -DoubleVector::Begin () const +DoubleVector::Begin() const { - return m_DoubleVector.begin (); + return m_DoubleVector.begin(); } DoubleVector::Iterator -DoubleVector::End () const +DoubleVector::End() const { - return m_DoubleVector.end (); + return m_DoubleVector.end(); } uint32_t -DoubleVector::GetN () const +DoubleVector::GetN() const { - return m_DoubleVector.size (); + return m_DoubleVector.size(); } std::vector -DoubleVector::Get () const +DoubleVector::Get() const { - std::vector v; + std::vector v; - for (auto c : m_DoubleVector) + for (auto c : m_DoubleVector) { - v.push_back (c); + v.push_back(c); } - return v; + return v; } double -DoubleVector::Get (const uint32_t i) const +DoubleVector::Get(const uint32_t i) const { - return m_DoubleVector[i]; + return m_DoubleVector[i]; } double -DoubleVector::GetFront () const +DoubleVector::GetFront() const { - return m_DoubleVector.front (); + return m_DoubleVector.front(); } double -DoubleVector::GetBack () const +DoubleVector::GetBack() const { - return m_DoubleVector.back (); + return m_DoubleVector.back(); } void -DoubleVector::Add (double coeff) +DoubleVector::Add(double coeff) { - m_DoubleVector.push_back (coeff); + m_DoubleVector.push_back(coeff); } -std::ostream & -operator<< (std::ostream &os, const DoubleVector &coeffs) +std::ostream& +operator<<(std::ostream& os, const DoubleVector& coeffs) { - os << coeffs.GetN () << ";"; + os << coeffs.GetN() << ";"; - for (auto coeff = coeffs.Begin (); - coeff != coeffs.End (); - coeff++) + for (auto coeff = coeffs.Begin(); coeff != coeffs.End(); coeff++) { - os << (*coeff) << ";"; + os << (*coeff) << ";"; } - return os; + return os; } -std::istream & -operator>> (std::istream &is, DoubleVector &coeffs) +std::istream& +operator>>(std::istream& is, DoubleVector& coeffs) { - char separator = '\0'; - uint32_t n; - double coeff; + char separator = '\0'; + uint32_t n; + double coeff; - is >> n >> separator; - if (separator != ';') - is.setstate (std::ios::failbit); + is >> n >> separator; + if (separator != ';') + is.setstate(std::ios::failbit); - for (uint32_t i = 0; i < n; i++) + for (uint32_t i = 0; i < n; i++) { - is >> coeff >> separator; + is >> coeff >> separator; - if (separator != ';') + if (separator != ';') { - is.setstate (std::ios::failbit); - break; + is.setstate(std::ios::failbit); + break; } - coeffs.Add (coeff); + coeffs.Add(coeff); } - return is; + return is; } } // namespace ns3 diff --git a/src/configuration/base/double-vector.h b/src/configuration/base/double-vector.h index 2e42b63..f055e2f 100644 --- a/src/configuration/base/double-vector.h +++ b/src/configuration/base/double-vector.h @@ -18,51 +18,50 @@ #ifndef DOUBLE_VECTOR_H #define DOUBLE_VECTOR_H +#include +#include +#include + #include #include #include -#include -#include -#include - -namespace ns3 { +namespace ns3 +{ /** * \brief Definition of a new attribute type, in the form vector. */ class DoubleVector { -public: - typedef std::vector::const_iterator Iterator; + public: + typedef std::vector::const_iterator Iterator; - DoubleVector (); - DoubleVector (std::vector coefficients); - DoubleVector (const DoubleVector &a); + DoubleVector(); + DoubleVector(std::vector coefficients); + DoubleVector(const DoubleVector& a); - Iterator Begin () const; - Iterator End () const; + Iterator Begin() const; + Iterator End() const; - uint32_t GetN () const; + uint32_t GetN() const; - std::vector Get () const; - double Get (const uint32_t i) const; + std::vector Get() const; + double Get(const uint32_t i) const; - double GetFront () const; - double GetBack () const; + double GetFront() const; + double GetBack() const; - void Add (double coefficient); + void Add(double coefficient); -private: - std::vector m_DoubleVector; + private: + std::vector m_DoubleVector; }; -ATTRIBUTE_HELPER_HEADER (DoubleVector); +ATTRIBUTE_HELPER_HEADER(DoubleVector); -std::ostream & operator<< (std::ostream &os, - const DoubleVector &DoubleVector); -std::istream & operator>> (std::istream &is, - DoubleVector &DoubleVector); +std::ostream& operator<<(std::ostream& os, const DoubleVector& DoubleVector); +std::istream& operator>>(std::istream& is, DoubleVector& DoubleVector); } // namespace ns3 diff --git a/src/configuration/base/int-vector.cc b/src/configuration/base/int-vector.cc index abaec11..9b72ebb 100644 --- a/src/configuration/base/int-vector.cc +++ b/src/configuration/base/int-vector.cc @@ -21,125 +21,124 @@ #include #include -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_HELPER_CPP (IntVector); +ATTRIBUTE_HELPER_CPP(IntVector); -IntVector::IntVector () +IntVector::IntVector() { } -IntVector::IntVector (std::vector coeffs) +IntVector::IntVector(std::vector coeffs) { - for (auto c : coeffs) + for (auto c : coeffs) { - Add (c); + Add(c); } } -IntVector::IntVector (const IntVector &a) +IntVector::IntVector(const IntVector& a) { - for (auto c = a.Begin (); c != a.End (); c++) + for (auto c = a.Begin(); c != a.End(); c++) { - Add (*c); + Add(*c); } } IntVector::Iterator -IntVector::Begin () const +IntVector::Begin() const { - return m_IntVector.begin (); + return m_IntVector.begin(); } IntVector::Iterator -IntVector::End () const +IntVector::End() const { - return m_IntVector.end (); + return m_IntVector.end(); } uint32_t -IntVector::GetN () const +IntVector::GetN() const { - return m_IntVector.size (); + return m_IntVector.size(); } std::vector -IntVector::Get () const +IntVector::Get() const { - std::vector v; + std::vector v; - for (auto c : m_IntVector) + for (auto c : m_IntVector) { - v.push_back (c); + v.push_back(c); } - return v; + return v; } int -IntVector::Get (const uint32_t i) const +IntVector::Get(const uint32_t i) const { - return m_IntVector[i]; + return m_IntVector[i]; } int -IntVector::GetFront () const +IntVector::GetFront() const { - return m_IntVector.front (); + return m_IntVector.front(); } int -IntVector::GetBack () const +IntVector::GetBack() const { - return m_IntVector.back (); + return m_IntVector.back(); } void -IntVector::Add (int coeff) +IntVector::Add(int coeff) { - m_IntVector.push_back (coeff); + m_IntVector.push_back(coeff); } -std::ostream & -operator<< (std::ostream &os, const IntVector &coeffs) +std::ostream& +operator<<(std::ostream& os, const IntVector& coeffs) { - os << coeffs.GetN () << ";"; + os << coeffs.GetN() << ";"; - for (auto coeff = coeffs.Begin (); - coeff != coeffs.End (); - coeff++) + for (auto coeff = coeffs.Begin(); coeff != coeffs.End(); coeff++) { - os << (*coeff) << ";"; + os << (*coeff) << ";"; } - return os; + return os; } -std::istream & -operator>> (std::istream &is, IntVector &coeffs) +std::istream& +operator>>(std::istream& is, IntVector& coeffs) { - char separator = '\0'; - uint32_t n; - int coeff; + char separator = '\0'; + uint32_t n; + int coeff; - is >> n >> separator; - if (separator != ';') - is.setstate (std::ios::failbit); + is >> n >> separator; + if (separator != ';') + is.setstate(std::ios::failbit); - for (uint32_t i = 0; i < n; i++) + for (uint32_t i = 0; i < n; i++) { - is >> coeff >> separator; + is >> coeff >> separator; - if (separator != ';') + if (separator != ';') { - is.setstate (std::ios::failbit); - break; + is.setstate(std::ios::failbit); + break; } - coeffs.Add (coeff); + coeffs.Add(coeff); } - return is; + return is; } } // namespace ns3 diff --git a/src/configuration/base/int-vector.h b/src/configuration/base/int-vector.h index 314345a..790dadf 100644 --- a/src/configuration/base/int-vector.h +++ b/src/configuration/base/int-vector.h @@ -18,51 +18,50 @@ #ifndef INT_VECTOR_H #define INT_VECTOR_H +#include +#include +#include + #include #include #include -#include -#include -#include - -namespace ns3 { +namespace ns3 +{ /** * \brief Definition of a new attribute type, in the form vector. */ class IntVector { -public: - typedef std::vector::const_iterator Iterator; + public: + typedef std::vector::const_iterator Iterator; - IntVector (); - IntVector (std::vector coefficients); - IntVector (const IntVector &a); + IntVector(); + IntVector(std::vector coefficients); + IntVector(const IntVector& a); - Iterator Begin () const; - Iterator End () const; + Iterator Begin() const; + Iterator End() const; - uint32_t GetN () const; + uint32_t GetN() const; - std::vector Get () const; - int Get (const uint32_t i) const; + std::vector Get() const; + int Get(const uint32_t i) const; - int GetFront () const; - int GetBack () const; + int GetFront() const; + int GetBack() const; - void Add (int coefficient); + void Add(int coefficient); -private: - std::vector m_IntVector; + private: + std::vector m_IntVector; }; -ATTRIBUTE_HELPER_HEADER (IntVector); +ATTRIBUTE_HELPER_HEADER(IntVector); -std::ostream & operator<< (std::ostream &os, - const IntVector &IntVector); -std::istream & operator>> (std::istream &is, - IntVector &IntVector); +std::ostream& operator<<(std::ostream& os, const IntVector& IntVector); +std::istream& operator>>(std::istream& is, IntVector& IntVector); } // namespace ns3 diff --git a/src/configuration/base/model-configuration-matrix.cc b/src/configuration/base/model-configuration-matrix.cc index 073fb89..c2c15f1 100644 --- a/src/configuration/base/model-configuration-matrix.cc +++ b/src/configuration/base/model-configuration-matrix.cc @@ -17,171 +17,173 @@ */ #include "model-configuration-matrix.h" -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_HELPER_CPP (ModelConfigurationMatrix); +ATTRIBUTE_HELPER_CPP(ModelConfigurationMatrix); -ModelConfigurationMatrix::ModelConfigurationMatrix () +ModelConfigurationMatrix::ModelConfigurationMatrix() { } -ModelConfigurationMatrix::ModelConfigurationMatrix (ModelConfigurationVector conf) : - m_confs {conf} +ModelConfigurationMatrix::ModelConfigurationMatrix(ModelConfigurationVector conf) + : m_confs{conf} { } -ModelConfigurationMatrix::ModelConfigurationMatrix (const std::vector& confs) : - m_confs {confs} +ModelConfigurationMatrix::ModelConfigurationMatrix( + const std::vector& confs) + : m_confs{confs} { } -ModelConfigurationMatrix::ModelConfigurationMatrix (const ModelConfigurationMatrix& v1, - const ModelConfigurationMatrix& v2) +ModelConfigurationMatrix::ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2) { - Add (v1); - Add (v2); + Add(v1); + Add(v2); } -ModelConfigurationMatrix::ModelConfigurationMatrix (const ModelConfigurationMatrix& v1, - const ModelConfigurationMatrix& v2, - const ModelConfigurationMatrix& v3) +ModelConfigurationMatrix::ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2, + const ModelConfigurationMatrix& v3) { - Add (v1); - Add (v2); - Add (v3); + Add(v1); + Add(v2); + Add(v3); } -ModelConfigurationMatrix::ModelConfigurationMatrix (const ModelConfigurationMatrix& v1, - const ModelConfigurationMatrix& v2, - const ModelConfigurationMatrix& v3, - const ModelConfigurationMatrix& v4) +ModelConfigurationMatrix::ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2, + const ModelConfigurationMatrix& v3, + const ModelConfigurationMatrix& v4) { - Add (v1); - Add (v2); - Add (v3); - Add (v4); + Add(v1); + Add(v2); + Add(v3); + Add(v4); } -ModelConfigurationMatrix::ModelConfigurationMatrix (const ModelConfigurationMatrix& v1, - const ModelConfigurationMatrix& v2, - const ModelConfigurationMatrix& v3, - const ModelConfigurationMatrix& v4, - const ModelConfigurationMatrix& v5) +ModelConfigurationMatrix::ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2, + const ModelConfigurationMatrix& v3, + const ModelConfigurationMatrix& v4, + const ModelConfigurationMatrix& v5) { - Add (v1); - Add (v2); - Add (v3); - Add (v4); - Add (v5); + Add(v1); + Add(v2); + Add(v3); + Add(v4); + Add(v5); } ModelConfigurationMatrix::Iterator -ModelConfigurationMatrix::Begin () const +ModelConfigurationMatrix::Begin() const { - return m_confs.begin (); + return m_confs.begin(); } ModelConfigurationMatrix::Iterator -ModelConfigurationMatrix::begin () const +ModelConfigurationMatrix::begin() const { - return Begin (); + return Begin(); } ModelConfigurationMatrix::MutableIterator -ModelConfigurationMatrix::MutableBegin () +ModelConfigurationMatrix::MutableBegin() { - return m_confs.begin (); + return m_confs.begin(); } ModelConfigurationMatrix::Iterator -ModelConfigurationMatrix::End () const +ModelConfigurationMatrix::End() const { - return m_confs.end (); + return m_confs.end(); } ModelConfigurationMatrix::Iterator -ModelConfigurationMatrix::end () const +ModelConfigurationMatrix::end() const { - return End (); + return End(); } ModelConfigurationMatrix::MutableIterator -ModelConfigurationMatrix::MutableEnd () +ModelConfigurationMatrix::MutableEnd() { - return m_confs.end(); + return m_confs.end(); } uint32_t -ModelConfigurationMatrix::GetN () const +ModelConfigurationMatrix::GetN() const { - return m_confs.size (); + return m_confs.size(); } ModelConfigurationVector -ModelConfigurationMatrix::operator[] (uint32_t i) const +ModelConfigurationMatrix::operator[](uint32_t i) const { - return m_confs[i]; + return m_confs[i]; } ModelConfigurationVector -ModelConfigurationMatrix::Get (uint32_t i) const +ModelConfigurationMatrix::Get(uint32_t i) const { - return m_confs[i]; + return m_confs[i]; } ModelConfigurationVector -ModelConfigurationMatrix::GetFront () const +ModelConfigurationMatrix::GetFront() const { - return m_confs.front (); + return m_confs.front(); } ModelConfigurationVector -ModelConfigurationMatrix::GetBack () const +ModelConfigurationMatrix::GetBack() const { - return m_confs.back (); + return m_confs.back(); } void -ModelConfigurationMatrix::Add (const ModelConfigurationMatrix& v) +ModelConfigurationMatrix::Add(const ModelConfigurationMatrix& v) { - for (auto i = v.Begin (); i != v.End (); ++i) - Add (*i); + for (auto i = v.Begin(); i != v.End(); ++i) + Add(*i); } void -ModelConfigurationMatrix::Add (ModelConfigurationVector conf) +ModelConfigurationMatrix::Add(ModelConfigurationVector conf) { - m_confs.push_back (conf); + m_confs.push_back(conf); } std::ostream& -operator<< (std::ostream &os, const ModelConfigurationMatrix &vector) +operator<<(std::ostream& os, const ModelConfigurationMatrix& vector) { - os << vector.GetN () << ";"; + os << vector.GetN() << ";"; - for (auto i = vector.Begin (); i != vector.End (); ++i) - os << *i << ";"; + for (auto i = vector.Begin(); i != vector.End(); ++i) + os << *i << ";"; - return os; + return os; } std::istream& -operator>> (std::istream &is, ModelConfigurationMatrix &vector) +operator>>(std::istream& is, ModelConfigurationMatrix& vector) { - uint32_t n; - is >> n; - is.ignore (1); + uint32_t n; + is >> n; + is.ignore(1); - for (uint32_t i = 0; i < n; ++i) + for (uint32_t i = 0; i < n; ++i) { - ModelConfigurationVector conf; - is >> conf; - vector.Add (conf); + ModelConfigurationVector conf; + is >> conf; + vector.Add(conf); - is.ignore (1); + is.ignore(1); } - return is; + return is; } } // namespace ns3 diff --git a/src/configuration/base/model-configuration-matrix.h b/src/configuration/base/model-configuration-matrix.h index 94adec1..2d79c6a 100644 --- a/src/configuration/base/model-configuration-matrix.h +++ b/src/configuration/base/model-configuration-matrix.h @@ -18,117 +18,119 @@ #ifndef MODEL_CONFIGURATION_MATRIX_H #define MODEL_CONFIGURATION_MATRIX_H -#include -#include -#include - #include #include #include -namespace ns3 { +#include +#include +#include + +namespace ns3 +{ /** * \brief Represent a container of Model Configurations. */ class ModelConfigurationMatrix { -public: - typedef std::vector::const_iterator Iterator; - typedef std::vector::iterator MutableIterator; + public: + typedef std::vector::const_iterator Iterator; + typedef std::vector::iterator MutableIterator; - /** Default constructor. Create an empty vector of IRS Patches. */ - ModelConfigurationMatrix (); - /** - * Create a new ModelConfigurationMatrix with exactly one Patch which has been - * previously istantiated. This single Patch is specified by a smart pointer. - * - * \param patch The ModelConfiguration to add to the container. - */ - ModelConfigurationMatrix (ModelConfigurationVector patch); - /** - * Create a new ModelConfigurationMatrix from a standard vector of ModelConfiguration - */ - ModelConfigurationMatrix (const std::vector& patches); - /** - * Create a new ModelConfigurationMatrix from a concatenation of two ModelConfigurationMatrixs. - * - * \param v1 The first ModelConfigurationMatrix. - * \param v2 The second ModelConfigurationMatrix. - */ - ModelConfigurationMatrix (const ModelConfigurationMatrix &v1, - const ModelConfigurationMatrix &v2); - /** - * Create a new ModelConfigurationMatrix from a concatenation of three ModelConfigurationMatrixs. - * - * \param v1 The first ModelConfigurationMatrix. - * \param v2 The second ModelConfigurationMatrix. - * \param v3 The third ModelConfigurationMatrix. - */ - ModelConfigurationMatrix (const ModelConfigurationMatrix &v1, - const ModelConfigurationMatrix &v2, - const ModelConfigurationMatrix &v3); - /** - * Create a new ModelConfigurationMatrix from a concatenation of four ModelConfigurationMatrixs. - * - * \param v1 The first ModelConfigurationMatrix. - * \param v2 The second ModelConfigurationMatrix. - * \param v3 The third ModelConfigurationMatrix. - * \param v4 The fourth ModelConfigurationMatrix. - */ - ModelConfigurationMatrix (const ModelConfigurationMatrix &v1, - const ModelConfigurationMatrix &v2, - const ModelConfigurationMatrix &v3, - const ModelConfigurationMatrix &v4); - /** - * Create a new ModelConfigurationMatrix from a concatenation of five ModelConfigurationMatrixs. - * - * \param v1 The first ModelConfigurationMatrix. - * \param v2 The second ModelConfigurationMatrix. - * \param v3 The third ModelConfigurationMatrix. - * \param v4 The fourth ModelConfigurationMatrix. - * \param v5 The fifth ModelConfigurationMatrix. - */ - ModelConfigurationMatrix (const ModelConfigurationMatrix &v1, - const ModelConfigurationMatrix &v2, - const ModelConfigurationMatrix &v3, - const ModelConfigurationMatrix &v4, - const ModelConfigurationMatrix &v5); - /** Get an iterator to the first element of the vector. */ - Iterator Begin () const; - /** Get an iterator to the first element of the vector. */ - Iterator begin () const; - /** Get an iterator to the first element of the vector. */ - MutableIterator MutableBegin (); - /** Get an iterator to the last element of the vector. */ - Iterator End () const; - /** Get an iterator to the last element of the vector. */ - Iterator end () const; - /** Get an iterator to the last element of the vector. */ - MutableIterator MutableEnd (); - /** Get the number of elements in the vector. */ - uint32_t GetN () const; - /** Get the ModelConfiguration at the given index. */ - ModelConfigurationVector operator[] (uint32_t i) const; - /** Get the ModelConfiguration at the given index. */ - ModelConfigurationVector Get (uint32_t i) const; - /** Get the first ModelConfiguration in the vector. */ - ModelConfigurationVector GetFront () const; - /** Get the last ModelConfiguration in the vector. */ - ModelConfigurationVector GetBack () const; - /** Append an existing ModelConfigurationMatrix to the end of this one. */ - void Add (const ModelConfigurationMatrix &v); - /** Append a new ModelConfiguration to the vector. */ - void Add (ModelConfigurationVector patch); + /** Default constructor. Create an empty vector of IRS Patches. */ + ModelConfigurationMatrix(); + /** + * Create a new ModelConfigurationMatrix with exactly one Patch which has been + * previously istantiated. This single Patch is specified by a smart pointer. + * + * \param patch The ModelConfiguration to add to the container. + */ + ModelConfigurationMatrix(ModelConfigurationVector patch); + /** + * Create a new ModelConfigurationMatrix from a standard vector of ModelConfiguration + */ + ModelConfigurationMatrix(const std::vector& patches); + /** + * Create a new ModelConfigurationMatrix from a concatenation of two ModelConfigurationMatrixs. + * + * \param v1 The first ModelConfigurationMatrix. + * \param v2 The second ModelConfigurationMatrix. + */ + ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2); + /** + * Create a new ModelConfigurationMatrix from a concatenation of three + * ModelConfigurationMatrixs. + * + * \param v1 The first ModelConfigurationMatrix. + * \param v2 The second ModelConfigurationMatrix. + * \param v3 The third ModelConfigurationMatrix. + */ + ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2, + const ModelConfigurationMatrix& v3); + /** + * Create a new ModelConfigurationMatrix from a concatenation of four ModelConfigurationMatrixs. + * + * \param v1 The first ModelConfigurationMatrix. + * \param v2 The second ModelConfigurationMatrix. + * \param v3 The third ModelConfigurationMatrix. + * \param v4 The fourth ModelConfigurationMatrix. + */ + ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2, + const ModelConfigurationMatrix& v3, + const ModelConfigurationMatrix& v4); + /** + * Create a new ModelConfigurationMatrix from a concatenation of five ModelConfigurationMatrixs. + * + * \param v1 The first ModelConfigurationMatrix. + * \param v2 The second ModelConfigurationMatrix. + * \param v3 The third ModelConfigurationMatrix. + * \param v4 The fourth ModelConfigurationMatrix. + * \param v5 The fifth ModelConfigurationMatrix. + */ + ModelConfigurationMatrix(const ModelConfigurationMatrix& v1, + const ModelConfigurationMatrix& v2, + const ModelConfigurationMatrix& v3, + const ModelConfigurationMatrix& v4, + const ModelConfigurationMatrix& v5); + /** Get an iterator to the first element of the vector. */ + Iterator Begin() const; + /** Get an iterator to the first element of the vector. */ + Iterator begin() const; + /** Get an iterator to the first element of the vector. */ + MutableIterator MutableBegin(); + /** Get an iterator to the last element of the vector. */ + Iterator End() const; + /** Get an iterator to the last element of the vector. */ + Iterator end() const; + /** Get an iterator to the last element of the vector. */ + MutableIterator MutableEnd(); + /** Get the number of elements in the vector. */ + uint32_t GetN() const; + /** Get the ModelConfiguration at the given index. */ + ModelConfigurationVector operator[](uint32_t i) const; + /** Get the ModelConfiguration at the given index. */ + ModelConfigurationVector Get(uint32_t i) const; + /** Get the first ModelConfiguration in the vector. */ + ModelConfigurationVector GetFront() const; + /** Get the last ModelConfiguration in the vector. */ + ModelConfigurationVector GetBack() const; + /** Append an existing ModelConfigurationMatrix to the end of this one. */ + void Add(const ModelConfigurationMatrix& v); + /** Append a new ModelConfiguration to the vector. */ + void Add(ModelConfigurationVector patch); -private: - std::vector m_confs; + private: + std::vector m_confs; }; -ATTRIBUTE_HELPER_HEADER (ModelConfigurationMatrix); +ATTRIBUTE_HELPER_HEADER(ModelConfigurationMatrix); -std::ostream& operator<< (std::ostream &os, const ModelConfigurationMatrix &vector); -std::istream& operator>> (std::istream &is, ModelConfigurationMatrix &vector); +std::ostream& operator<<(std::ostream& os, const ModelConfigurationMatrix& vector); +std::istream& operator>>(std::istream& is, ModelConfigurationMatrix& vector); } // namespace ns3 diff --git a/src/configuration/base/model-configuration-vector.cc b/src/configuration/base/model-configuration-vector.cc index e4e26ce..9b38d93 100644 --- a/src/configuration/base/model-configuration-vector.cc +++ b/src/configuration/base/model-configuration-vector.cc @@ -17,171 +17,172 @@ */ #include "model-configuration-vector.h" -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_HELPER_CPP (ModelConfigurationVector); +ATTRIBUTE_HELPER_CPP(ModelConfigurationVector); -ModelConfigurationVector::ModelConfigurationVector () +ModelConfigurationVector::ModelConfigurationVector() { } -ModelConfigurationVector::ModelConfigurationVector (ModelConfiguration conf) : - m_confs {conf} +ModelConfigurationVector::ModelConfigurationVector(ModelConfiguration conf) + : m_confs{conf} { } -ModelConfigurationVector::ModelConfigurationVector (const std::vector& confs) : - m_confs {confs} +ModelConfigurationVector::ModelConfigurationVector(const std::vector& confs) + : m_confs{confs} { } -ModelConfigurationVector::ModelConfigurationVector (const ModelConfigurationVector& v1, - const ModelConfigurationVector& v2) +ModelConfigurationVector::ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2) { - Add (v1); - Add (v2); + Add(v1); + Add(v2); } -ModelConfigurationVector::ModelConfigurationVector (const ModelConfigurationVector& v1, - const ModelConfigurationVector& v2, - const ModelConfigurationVector& v3) +ModelConfigurationVector::ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2, + const ModelConfigurationVector& v3) { - Add (v1); - Add (v2); - Add (v3); + Add(v1); + Add(v2); + Add(v3); } -ModelConfigurationVector::ModelConfigurationVector (const ModelConfigurationVector& v1, - const ModelConfigurationVector& v2, - const ModelConfigurationVector& v3, - const ModelConfigurationVector& v4) +ModelConfigurationVector::ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2, + const ModelConfigurationVector& v3, + const ModelConfigurationVector& v4) { - Add (v1); - Add (v2); - Add (v3); - Add (v4); + Add(v1); + Add(v2); + Add(v3); + Add(v4); } -ModelConfigurationVector::ModelConfigurationVector (const ModelConfigurationVector& v1, - const ModelConfigurationVector& v2, - const ModelConfigurationVector& v3, - const ModelConfigurationVector& v4, - const ModelConfigurationVector& v5) +ModelConfigurationVector::ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2, + const ModelConfigurationVector& v3, + const ModelConfigurationVector& v4, + const ModelConfigurationVector& v5) { - Add (v1); - Add (v2); - Add (v3); - Add (v4); - Add (v5); + Add(v1); + Add(v2); + Add(v3); + Add(v4); + Add(v5); } ModelConfigurationVector::Iterator -ModelConfigurationVector::Begin () const +ModelConfigurationVector::Begin() const { - return m_confs.begin (); + return m_confs.begin(); } ModelConfigurationVector::Iterator -ModelConfigurationVector::begin () const +ModelConfigurationVector::begin() const { - return Begin (); + return Begin(); } ModelConfigurationVector::MutableIterator -ModelConfigurationVector::MutableBegin () +ModelConfigurationVector::MutableBegin() { - return m_confs.begin (); + return m_confs.begin(); } ModelConfigurationVector::Iterator -ModelConfigurationVector::End () const +ModelConfigurationVector::End() const { - return m_confs.end (); + return m_confs.end(); } ModelConfigurationVector::Iterator -ModelConfigurationVector::end () const +ModelConfigurationVector::end() const { - return End (); + return End(); } ModelConfigurationVector::MutableIterator -ModelConfigurationVector::MutableEnd () +ModelConfigurationVector::MutableEnd() { - return m_confs.end (); + return m_confs.end(); } uint32_t -ModelConfigurationVector::GetN () const +ModelConfigurationVector::GetN() const { - return m_confs.size (); + return m_confs.size(); } ModelConfiguration -ModelConfigurationVector::operator[] (uint32_t i) const +ModelConfigurationVector::operator[](uint32_t i) const { - return m_confs[i]; + return m_confs[i]; } ModelConfiguration -ModelConfigurationVector::Get (uint32_t i) const +ModelConfigurationVector::Get(uint32_t i) const { - return m_confs[i]; + return m_confs[i]; } ModelConfiguration -ModelConfigurationVector::GetFront () const +ModelConfigurationVector::GetFront() const { - return m_confs.front (); + return m_confs.front(); } ModelConfiguration -ModelConfigurationVector::GetBack () const +ModelConfigurationVector::GetBack() const { - return m_confs.back (); + return m_confs.back(); } void -ModelConfigurationVector::Add (const ModelConfigurationVector& v) +ModelConfigurationVector::Add(const ModelConfigurationVector& v) { - for (auto i = v.Begin (); i != v.End (); ++i) - Add (*i); + for (auto i = v.Begin(); i != v.End(); ++i) + Add(*i); } void -ModelConfigurationVector::Add (ModelConfiguration conf) +ModelConfigurationVector::Add(ModelConfiguration conf) { - m_confs.push_back (conf); + m_confs.push_back(conf); } std::ostream& -operator<< (std::ostream &os, const ModelConfigurationVector &vector) +operator<<(std::ostream& os, const ModelConfigurationVector& vector) { - os << vector.GetN () << ";"; + os << vector.GetN() << ";"; - for (auto i = vector.Begin (); i != vector.End (); ++i) - os << *i << ";"; + for (auto i = vector.Begin(); i != vector.End(); ++i) + os << *i << ";"; - return os; + return os; } std::istream& -operator>> (std::istream &is, ModelConfigurationVector &vector) +operator>>(std::istream& is, ModelConfigurationVector& vector) { - uint32_t n; - is >> n; - is.ignore (1); + uint32_t n; + is >> n; + is.ignore(1); - for (uint32_t i = 0; i < n; ++i) + for (uint32_t i = 0; i < n; ++i) { - ModelConfiguration conf; - is >> conf; - vector.Add (conf); + ModelConfiguration conf; + is >> conf; + vector.Add(conf); - is.ignore (1); + is.ignore(1); } - return is; + return is; } } // namespace ns3 diff --git a/src/configuration/base/model-configuration-vector.h b/src/configuration/base/model-configuration-vector.h index 3e8befc..c92df42 100644 --- a/src/configuration/base/model-configuration-vector.h +++ b/src/configuration/base/model-configuration-vector.h @@ -18,117 +18,119 @@ #ifndef MODEL_CONFIGURATION_VECTOR_H #define MODEL_CONFIGURATION_VECTOR_H -#include -#include -#include - #include #include #include -namespace ns3 { +#include +#include +#include + +namespace ns3 +{ /** * \brief Represent a container of Model Configurations. */ class ModelConfigurationVector { -public: - typedef std::vector::const_iterator Iterator; - typedef std::vector::iterator MutableIterator; + public: + typedef std::vector::const_iterator Iterator; + typedef std::vector::iterator MutableIterator; - /** Default constructor. Create an empty vector of IRS Patches. */ - ModelConfigurationVector (); - /** - * Create a new ModelConfigurationVector with exactly one Patch which has been - * previously istantiated. This single Patch is specified by a smart pointer. - * - * \param patch The ModelConfiguration to add to the container. - */ - ModelConfigurationVector (ModelConfiguration patch); - /** - * Create a new ModelConfigurationVector from a standard vector of ModelConfiguration - */ - ModelConfigurationVector (const std::vector& patches); - /** - * Create a new ModelConfigurationVector from a concatenation of two ModelConfigurationVectors. - * - * \param v1 The first ModelConfigurationVector. - * \param v2 The second ModelConfigurationVector. - */ - ModelConfigurationVector (const ModelConfigurationVector &v1, - const ModelConfigurationVector &v2); - /** - * Create a new ModelConfigurationVector from a concatenation of three ModelConfigurationVectors. - * - * \param v1 The first ModelConfigurationVector. - * \param v2 The second ModelConfigurationVector. - * \param v3 The third ModelConfigurationVector. - */ - ModelConfigurationVector (const ModelConfigurationVector &v1, - const ModelConfigurationVector &v2, - const ModelConfigurationVector &v3); - /** - * Create a new ModelConfigurationVector from a concatenation of four ModelConfigurationVectors. - * - * \param v1 The first ModelConfigurationVector. - * \param v2 The second ModelConfigurationVector. - * \param v3 The third ModelConfigurationVector. - * \param v4 The fourth ModelConfigurationVector. - */ - ModelConfigurationVector (const ModelConfigurationVector &v1, - const ModelConfigurationVector &v2, - const ModelConfigurationVector &v3, - const ModelConfigurationVector &v4); - /** - * Create a new ModelConfigurationVector from a concatenation of five ModelConfigurationVectors. - * - * \param v1 The first ModelConfigurationVector. - * \param v2 The second ModelConfigurationVector. - * \param v3 The third ModelConfigurationVector. - * \param v4 The fourth ModelConfigurationVector. - * \param v5 The fifth ModelConfigurationVector. - */ - ModelConfigurationVector (const ModelConfigurationVector &v1, - const ModelConfigurationVector &v2, - const ModelConfigurationVector &v3, - const ModelConfigurationVector &v4, - const ModelConfigurationVector &v5); - /** Get an iterator to the first element of the vector. */ - Iterator Begin () const; - /** Get an iterator to the first element of the vector. */ - Iterator begin () const; - /** Get an iterator to the first element of the vector. */ - MutableIterator MutableBegin (); - /** Get an iterator to the last element of the vector. */ - Iterator End () const; - /** Get an iterator to the last element of the vector. */ - Iterator end () const; - /** Get an iterator to the last element of the vector. */ - MutableIterator MutableEnd (); - /** Get the number of elements in the vector. */ - uint32_t GetN () const; - /** Get the ModelConfiguration at the given index. */ - ModelConfiguration operator[] (uint32_t i) const; - /** Get the ModelConfiguration at the given index. */ - ModelConfiguration Get (uint32_t i) const; - /** Get the first ModelConfiguration in the vector. */ - ModelConfiguration GetFront () const; - /** Get the last ModelConfiguration in the vector. */ - ModelConfiguration GetBack () const; - /** Append an existing ModelConfigurationVector to the end of this one. */ - void Add (const ModelConfigurationVector &v); - /** Append a new ModelConfiguration to the vector. */ - void Add (ModelConfiguration patch); + /** Default constructor. Create an empty vector of IRS Patches. */ + ModelConfigurationVector(); + /** + * Create a new ModelConfigurationVector with exactly one Patch which has been + * previously istantiated. This single Patch is specified by a smart pointer. + * + * \param patch The ModelConfiguration to add to the container. + */ + ModelConfigurationVector(ModelConfiguration patch); + /** + * Create a new ModelConfigurationVector from a standard vector of ModelConfiguration + */ + ModelConfigurationVector(const std::vector& patches); + /** + * Create a new ModelConfigurationVector from a concatenation of two ModelConfigurationVectors. + * + * \param v1 The first ModelConfigurationVector. + * \param v2 The second ModelConfigurationVector. + */ + ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2); + /** + * Create a new ModelConfigurationVector from a concatenation of three + * ModelConfigurationVectors. + * + * \param v1 The first ModelConfigurationVector. + * \param v2 The second ModelConfigurationVector. + * \param v3 The third ModelConfigurationVector. + */ + ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2, + const ModelConfigurationVector& v3); + /** + * Create a new ModelConfigurationVector from a concatenation of four ModelConfigurationVectors. + * + * \param v1 The first ModelConfigurationVector. + * \param v2 The second ModelConfigurationVector. + * \param v3 The third ModelConfigurationVector. + * \param v4 The fourth ModelConfigurationVector. + */ + ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2, + const ModelConfigurationVector& v3, + const ModelConfigurationVector& v4); + /** + * Create a new ModelConfigurationVector from a concatenation of five ModelConfigurationVectors. + * + * \param v1 The first ModelConfigurationVector. + * \param v2 The second ModelConfigurationVector. + * \param v3 The third ModelConfigurationVector. + * \param v4 The fourth ModelConfigurationVector. + * \param v5 The fifth ModelConfigurationVector. + */ + ModelConfigurationVector(const ModelConfigurationVector& v1, + const ModelConfigurationVector& v2, + const ModelConfigurationVector& v3, + const ModelConfigurationVector& v4, + const ModelConfigurationVector& v5); + /** Get an iterator to the first element of the vector. */ + Iterator Begin() const; + /** Get an iterator to the first element of the vector. */ + Iterator begin() const; + /** Get an iterator to the first element of the vector. */ + MutableIterator MutableBegin(); + /** Get an iterator to the last element of the vector. */ + Iterator End() const; + /** Get an iterator to the last element of the vector. */ + Iterator end() const; + /** Get an iterator to the last element of the vector. */ + MutableIterator MutableEnd(); + /** Get the number of elements in the vector. */ + uint32_t GetN() const; + /** Get the ModelConfiguration at the given index. */ + ModelConfiguration operator[](uint32_t i) const; + /** Get the ModelConfiguration at the given index. */ + ModelConfiguration Get(uint32_t i) const; + /** Get the first ModelConfiguration in the vector. */ + ModelConfiguration GetFront() const; + /** Get the last ModelConfiguration in the vector. */ + ModelConfiguration GetBack() const; + /** Append an existing ModelConfigurationVector to the end of this one. */ + void Add(const ModelConfigurationVector& v); + /** Append a new ModelConfiguration to the vector. */ + void Add(ModelConfiguration patch); -private: - std::vector m_confs; + private: + std::vector m_confs; }; -ATTRIBUTE_HELPER_HEADER (ModelConfigurationVector); +ATTRIBUTE_HELPER_HEADER(ModelConfigurationVector); -std::ostream& operator<< (std::ostream &os, const ModelConfigurationVector &vector); -std::istream& operator>> (std::istream &is, ModelConfigurationVector &vector); +std::ostream& operator<<(std::ostream& os, const ModelConfigurationVector& vector); +std::istream& operator>>(std::istream& is, ModelConfigurationVector& vector); } // namespace ns3 diff --git a/src/configuration/base/model-configuration.cc b/src/configuration/base/model-configuration.cc index 9e88411..370ba5d 100644 --- a/src/configuration/base/model-configuration.cc +++ b/src/configuration/base/model-configuration.cc @@ -19,191 +19,187 @@ #include -namespace ns3 { - -ModelConfiguration::ModelConfiguration (const std::string name, - const std::vector attributes) : - m_name {name}, - m_attributes {attributes} +namespace ns3 { +ModelConfiguration::ModelConfiguration(const std::string name, + const std::vector attributes) + : m_name{name}, + m_attributes{attributes} +{ } -ModelConfiguration::ModelConfiguration (const std::string name, - const std::vector attributes, - const std::vector aggregates) : - m_name {name}, - m_attributes {attributes}, - m_aggregates {aggregates} +ModelConfiguration::ModelConfiguration(const std::string name, + const std::vector attributes, + const std::vector aggregates) + : m_name{name}, + m_attributes{attributes}, + m_aggregates{aggregates} { - } -ModelConfiguration::~ModelConfiguration () +ModelConfiguration::~ModelConfiguration() { - } std::string -ModelConfiguration::GetName () const +ModelConfiguration::GetName() const { - return m_name; + return m_name; } ModelConfiguration::AttributeIterator -ModelConfiguration::AttributesBegin () const +ModelConfiguration::AttributesBegin() const { - return m_attributes.begin (); + return m_attributes.begin(); } ModelConfiguration::AttributeIterator -ModelConfiguration::AttributesEnd () const +ModelConfiguration::AttributesEnd() const { - return m_attributes.end (); + return m_attributes.end(); } ModelConfiguration::AggregateIterator -ModelConfiguration::AggregatesBegin () const +ModelConfiguration::AggregatesBegin() const { - return m_aggregates.begin (); + return m_aggregates.begin(); } ModelConfiguration::AggregateIterator -ModelConfiguration::AggregatesEnd () const +ModelConfiguration::AggregatesEnd() const { - return m_aggregates.end (); + return m_aggregates.end(); } std::vector -ModelConfiguration::GetAttributes () const +ModelConfiguration::GetAttributes() const { - return m_attributes; + return m_attributes; } std::vector -ModelConfiguration::GetAggregates () const +ModelConfiguration::GetAggregates() const { - return m_aggregates; + return m_aggregates; } void -ModelConfiguration::SetAttribute (const std::string name, Ptr value) +ModelConfiguration::SetAttribute(const std::string name, Ptr value) { - for (auto& attribute : m_attributes) + for (auto& attribute : m_attributes) { - if (attribute.name == name) + if (attribute.name == name) { - attribute.value = value; - return; + attribute.value = value; + return; } } - m_attributes.push_back (Attribute {name, value}); + m_attributes.push_back(Attribute{name, value}); } std::ostream& -operator<< (std::ostream &os, const ModelConfiguration &mc) +operator<<(std::ostream& os, const ModelConfiguration& mc) { - os << mc.GetName () << ";"; - os << mc.GetAttributes () << ";"; - os << mc.GetAggregates () << ";"; + os << mc.GetName() << ";"; + os << mc.GetAttributes() << ";"; + os << mc.GetAggregates() << ";"; - return os; + return os; } std::ostream& -operator<< (std::ostream &os, const ModelConfiguration::AttributeVector &attrs) +operator<<(std::ostream& os, const ModelConfiguration::AttributeVector& attrs) { - os << attrs.size () << ";"; + os << attrs.size() << ";"; - for (auto& attr : attrs) - os << attr << ";"; + for (auto& attr : attrs) + os << attr << ";"; - return os; + return os; } std::ostream& -operator<< (std::ostream &os, const ModelConfiguration::Attribute &attr) +operator<<(std::ostream& os, const ModelConfiguration::Attribute& attr) { - os << attr.name << "=" << attr.value << ";"; - return os; + os << attr.name << "=" << attr.value << ";"; + return os; } std::ostream& -operator<< (std::ostream &os, const ModelConfiguration::ModelConfigurationVector &aggs) +operator<<(std::ostream& os, const ModelConfiguration::ModelConfigurationVector& aggs) { - os << aggs.size () << ";"; - for (auto& agg : aggs) - os << agg << ";"; - return os; + os << aggs.size() << ";"; + for (auto& agg : aggs) + os << agg << ";"; + return os; } std::istream& -operator>> (std::istream &is, ModelConfiguration &mc) +operator>>(std::istream& is, ModelConfiguration& mc) { - std::string name; - ModelConfiguration::AttributeVector attributes; - ModelConfiguration::ModelConfigurationVector aggregates; + std::string name; + ModelConfiguration::AttributeVector attributes; + ModelConfiguration::ModelConfigurationVector aggregates; - is >> name; - is.ignore (1); // ; - is >> attributes; - is.ignore (1); // ; - is >> aggregates; - is.ignore (1); // ; + is >> name; + is.ignore(1); // ; + is >> attributes; + is.ignore(1); // ; + is >> aggregates; + is.ignore(1); // ; - mc = ModelConfiguration (name, attributes, aggregates); - return is; + mc = ModelConfiguration(name, attributes, aggregates); + return is; } std::istream& -operator>> (std::istream &is, ModelConfiguration::AttributeVector &attrs) +operator>>(std::istream& is, ModelConfiguration::AttributeVector& attrs) { - uint32_t n; - is >> n; - is.ignore (1); // ; + uint32_t n; + is >> n; + is.ignore(1); // ; - for (uint32_t i = 0; i < n; ++i) + for (uint32_t i = 0; i < n; ++i) { - ModelConfiguration::Attribute attr {}; - is >> attr; - is.ignore (1); // ; - attrs.push_back (attr); + ModelConfiguration::Attribute attr{}; + is >> attr; + is.ignore(1); // ; + attrs.push_back(attr); } - return is; + return is; } std::istream& -operator>> (std::istream &is, ModelConfiguration::Attribute &attr) +operator>>(std::istream& is, ModelConfiguration::Attribute& attr) { - is >> attr.name; - is.ignore (1); // = + is >> attr.name; + is.ignore(1); // = - uint64_t attrValueAddress; - is >> attrValueAddress; - attr.value = Ptr {(AttributeValue *) attrValueAddress}; - is.ignore (1); // ; + uint64_t attrValueAddress; + is >> attrValueAddress; + attr.value = Ptr{(AttributeValue*)attrValueAddress}; + is.ignore(1); // ; - return is; + return is; } std::istream& -operator>> (std::istream &is, ModelConfiguration::ModelConfigurationVector &aggs) +operator>>(std::istream& is, ModelConfiguration::ModelConfigurationVector& aggs) { - uint32_t n; - is >> n; - is.ignore (1); // ; - for (uint32_t i = 0; i < n; ++i) + uint32_t n; + is >> n; + is.ignore(1); // ; + for (uint32_t i = 0; i < n; ++i) { - ModelConfiguration agg; - is >> agg; - is.ignore (1); // ; - aggs.push_back (agg); + ModelConfiguration agg; + is >> agg; + is.ignore(1); // ; + aggs.push_back(agg); } - return is; + return is; } - - } // namespace ns3 diff --git a/src/configuration/base/model-configuration.h b/src/configuration/base/model-configuration.h index 7e0c512..a72b8b6 100644 --- a/src/configuration/base/model-configuration.h +++ b/src/configuration/base/model-configuration.h @@ -18,112 +18,116 @@ #ifndef MODEL_CONFIGURATION_H #define MODEL_CONFIGURATION_H +#include + #include #include -#include - -namespace ns3 { +namespace ns3 +{ /** * Data class to recognize and configure a TypeId that is registered on ns-3. */ class ModelConfiguration { -public: - class Attribute - { public: - std::string name; - Ptr value; - - Attribute () = default; - Attribute (std::string name, Ptr value) : - name {name}, - value {value} - {} - }; - - typedef std::vector AttributeVector; - typedef std::vector ModelConfigurationVector; - typedef AttributeVector::const_iterator AttributeIterator; - typedef ModelConfigurationVector::const_iterator AggregateIterator; - - /** \brief Default constructor for an empty ModelConfiguration. */ - ModelConfiguration () = default; - /** - * Create a new object instance. - * - * \param name The name of the ns-3 model. It must be a valid and registered TypeId Model. - * \param attributes The list of attributes that configures the chosen model. - */ - ModelConfiguration (const std::string name, - const AttributeVector attributes); - /** - * Create a new object instance. - * - * \param name The name of the ns-3 model. It must be a valid and registered TypeId Model. - * \param attributes The list of attributes that configures the chosen model. - * \param aggregates The list of aggregates that customize the chosen model with additional features. - */ - ModelConfiguration (const std::string name, - const AttributeVector attributes, - const ModelConfigurationVector aggregates); - - /** Default destructor */ - ~ModelConfiguration (); - - /** - * \return The model name. - */ - std::string GetName () const; - - /** - * \return The begin iterator of the list of attributes. - */ - AttributeIterator AttributesBegin () const; - /** - * \return The end iterator of the list of attributes. - */ - AttributeIterator AttributesEnd () const; - /** - * \return The begin iterator of the list of aggregates. - */ - AggregateIterator AggregatesBegin () const; - /** - * \return The end iterator of the list of aggregates. - */ - AggregateIterator AggregatesEnd () const; - /** - * \return The list of attributes as a std::pair of attribute name and its configured value. - */ - AttributeVector GetAttributes () const; - /** - * \return The list of models to be aggregated to this one. - */ - ModelConfigurationVector GetAggregates () const; - /** - * \brief Update or set the value of an attribute. - * \param name The name of the attribute to be updated. - * \param value The new value of the attribute. - */ - void SetAttribute (const std::string name, Ptr value); - -private: - std::string m_name; - AttributeVector m_attributes; - ModelConfigurationVector m_aggregates; + class Attribute + { + public: + std::string name; + Ptr value; + + Attribute() = default; + + Attribute(std::string name, Ptr value) + : name{name}, + value{value} + { + } + }; + + typedef std::vector AttributeVector; + typedef std::vector ModelConfigurationVector; + typedef AttributeVector::const_iterator AttributeIterator; + typedef ModelConfigurationVector::const_iterator AggregateIterator; + + /** \brief Default constructor for an empty ModelConfiguration. */ + ModelConfiguration() = default; + /** + * Create a new object instance. + * + * \param name The name of the ns-3 model. It must be a valid and registered TypeId Model. + * \param attributes The list of attributes that configures the chosen model. + */ + ModelConfiguration(const std::string name, const AttributeVector attributes); + /** + * Create a new object instance. + * + * \param name The name of the ns-3 model. It must be a valid and registered TypeId Model. + * \param attributes The list of attributes that configures the chosen model. + * \param aggregates The list of aggregates that customize the chosen model with additional + * features. + */ + ModelConfiguration(const std::string name, + const AttributeVector attributes, + const ModelConfigurationVector aggregates); + + /** Default destructor */ + ~ModelConfiguration(); + + /** + * \return The model name. + */ + std::string GetName() const; + + /** + * \return The begin iterator of the list of attributes. + */ + AttributeIterator AttributesBegin() const; + /** + * \return The end iterator of the list of attributes. + */ + AttributeIterator AttributesEnd() const; + /** + * \return The begin iterator of the list of aggregates. + */ + AggregateIterator AggregatesBegin() const; + /** + * \return The end iterator of the list of aggregates. + */ + AggregateIterator AggregatesEnd() const; + /** + * \return The list of attributes as a std::pair of attribute name and its configured value. + */ + AttributeVector GetAttributes() const; + /** + * \return The list of models to be aggregated to this one. + */ + ModelConfigurationVector GetAggregates() const; + /** + * \brief Update or set the value of an attribute. + * \param name The name of the attribute to be updated. + * \param value The new value of the attribute. + */ + void SetAttribute(const std::string name, Ptr value); + + private: + std::string m_name; + AttributeVector m_attributes; + ModelConfigurationVector m_aggregates; }; -std::ostream& operator<< (std::ostream &os, const ModelConfiguration &mc); -std::ostream& operator<< (std::ostream &os, const ModelConfiguration::AttributeVector &attrs); -std::ostream& operator<< (std::ostream &os, const ModelConfiguration::Attribute &attr); -std::ostream& operator<< (std::ostream &os, const ModelConfiguration::ModelConfigurationVector &aggs); +std::ostream& operator<<(std::ostream& os, const ModelConfiguration& mc); +std::ostream& operator<<(std::ostream& os, const ModelConfiguration::AttributeVector& attrs); +std::ostream& operator<<(std::ostream& os, const ModelConfiguration::Attribute& attr); +std::ostream& operator<<(std::ostream& os, + const ModelConfiguration::ModelConfigurationVector& aggs); -std::istream& operator>> (std::istream &is, ModelConfiguration &mc); -std::istream& operator>> (std::istream &is, ModelConfiguration::AttributeVector &attrs); -std::istream& operator>> (std::istream &is, ModelConfiguration::Attribute &attr); -std::istream& operator>> (std::istream &is, ModelConfiguration::ModelConfigurationVector &aggs); +std::istream& operator>>(std::istream& is, ModelConfiguration& mc); +std::istream& operator>>(std::istream& is, ModelConfiguration::AttributeVector& attrs); +std::istream& operator>>(std::istream& is, ModelConfiguration::Attribute& attr); +std::istream& operator>>(std::istream& is, ModelConfiguration::ModelConfigurationVector& aggs); } // namespace ns3 diff --git a/src/configuration/base/str-vec.cc b/src/configuration/base/str-vec.cc index 9cf68fd..ca52b9a 100644 --- a/src/configuration/base/str-vec.cc +++ b/src/configuration/base/str-vec.cc @@ -21,126 +21,125 @@ #include #include -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_HELPER_CPP (StrVec); +ATTRIBUTE_HELPER_CPP(StrVec); -StrVec::StrVec () +StrVec::StrVec() { } -StrVec::StrVec (std::vector strs) +StrVec::StrVec(std::vector strs) { - for (auto s : strs) - Add (s); + for (auto s : strs) + Add(s); } -StrVec::StrVec (const StrVec &a) +StrVec::StrVec(const StrVec& a) { - for (auto c = a.Begin (); c != a.End (); c++) - Add (*c); + for (auto c = a.Begin(); c != a.End(); c++) + Add(*c); } StrVec::Iterator -StrVec::Begin () const +StrVec::Begin() const { - return m_stringVector.begin (); + return m_stringVector.begin(); } StrVec::Iterator -StrVec::begin () const +StrVec::begin() const { - return m_stringVector.begin (); + return m_stringVector.begin(); } StrVec::Iterator -StrVec::End () const +StrVec::End() const { - return m_stringVector.end (); + return m_stringVector.end(); } StrVec::Iterator -StrVec::end () const +StrVec::end() const { - return m_stringVector.end (); + return m_stringVector.end(); } uint32_t -StrVec::GetN () const +StrVec::GetN() const { - return m_stringVector.size (); + return m_stringVector.size(); } std::vector -StrVec::Get () const +StrVec::Get() const { - return m_stringVector; + return m_stringVector; } std::string -StrVec::Get (const uint32_t i) const +StrVec::Get(const uint32_t i) const { - return m_stringVector[i]; + return m_stringVector[i]; } std::string -StrVec::GetFront () const +StrVec::GetFront() const { - return m_stringVector.front (); + return m_stringVector.front(); } std::string -StrVec::GetBack () const +StrVec::GetBack() const { - return m_stringVector.back (); + return m_stringVector.back(); } void -StrVec::Add (std::string s) +StrVec::Add(std::string s) { - m_stringVector.push_back (s); + m_stringVector.push_back(s); } -std::ostream & -operator<< (std::ostream &os, const StrVec &v) +std::ostream& +operator<<(std::ostream& os, const StrVec& v) { - os << v.GetN () << ";"; + os << v.GetN() << ";"; - for (auto s = v.Begin (); - s != v.End (); - s++) + for (auto s = v.Begin(); s != v.End(); s++) { - os << (*s) << ";"; + os << (*s) << ";"; } - return os; + return os; } -std::istream & -operator>> (std::istream &is, StrVec &v) +std::istream& +operator>>(std::istream& is, StrVec& v) { - char separator = '\0'; - uint32_t n; - std::string s; + char separator = '\0'; + uint32_t n; + std::string s; - is >> n >> separator; - if (separator != ';') - is.setstate (std::ios::failbit); + is >> n >> separator; + if (separator != ';') + is.setstate(std::ios::failbit); - for (uint32_t i = 0; i < n; i++) + for (uint32_t i = 0; i < n; i++) { - is >> s >> separator; + is >> s >> separator; - if (separator != ';') + if (separator != ';') { - is.setstate (std::ios::failbit); - break; + is.setstate(std::ios::failbit); + break; } - v.Add (s); + v.Add(s); } - return is; + return is; } -} // namespace iodsim +} // namespace ns3 diff --git a/src/configuration/base/str-vec.h b/src/configuration/base/str-vec.h index 0ebc427..dd630a4 100644 --- a/src/configuration/base/str-vec.h +++ b/src/configuration/base/str-vec.h @@ -18,53 +18,52 @@ #ifndef STRING_VECTOR_H #define STRING_VECTOR_H +#include +#include + #include #include #include #include -#include -#include - -namespace ns3 { +namespace ns3 +{ /** * \brief Definition of a new attribute type, in the form vector. */ class StrVec { -public: - typedef std::vector::const_iterator Iterator; + public: + typedef std::vector::const_iterator Iterator; - StrVec (); - StrVec (std::vector coefficients); - StrVec (const StrVec &a); + StrVec(); + StrVec(std::vector coefficients); + StrVec(const StrVec& a); - Iterator Begin () const; - Iterator begin () const; - Iterator End () const; - Iterator end () const; + Iterator Begin() const; + Iterator begin() const; + Iterator End() const; + Iterator end() const; - uint32_t GetN () const; + uint32_t GetN() const; - std::vector Get () const; - std::string Get (const uint32_t i) const; + std::vector Get() const; + std::string Get(const uint32_t i) const; - std::string GetFront () const; - std::string GetBack () const; + std::string GetFront() const; + std::string GetBack() const; - void Add (std::string str); + void Add(std::string str); -private: - std::vector m_stringVector; + private: + std::vector m_stringVector; }; -ATTRIBUTE_HELPER_HEADER (StrVec); +ATTRIBUTE_HELPER_HEADER(StrVec); -std::ostream & operator<< (std::ostream &os, - const StrVec &sv); -std::istream & operator>> (std::istream &is, - StrVec &sv); +std::ostream& operator<<(std::ostream& os, const StrVec& sv); +std::istream& operator>>(std::istream& is, StrVec& sv); } // namespace ns3 diff --git a/src/configuration/base/vector-type.cc b/src/configuration/base/vector-type.cc index 73279c2..02d42a3 100644 --- a/src/configuration/base/vector-type.cc +++ b/src/configuration/base/vector-type.cc @@ -16,133 +16,132 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +#include "int-vector.h" + #include #include #include -#include "int-vector.h" - -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_HELPER_CPP (VectorType); +ATTRIBUTE_HELPER_CPP(VectorType); -template -VectorType () +template +VectorType() { } -template -VectorType::VectorType (std::vector coeffs) +template +VectorType::VectorType(std::vector coeffs) { - for (auto c : coeffs) + for (auto c : coeffs) { - Add (c); + Add(c); } } -VectorType::VectorType (const VectorType &a) +VectorType::VectorType(const VectorType& a) { - for (auto c = a.Begin (); c != a.End (); c++) + for (auto c = a.Begin(); c != a.End(); c++) { - Add (*c); + Add(*c); } } VectorType::Iterator -VectorType::Begin () const +VectorType::Begin() const { - return m_VectorType.begin (); + return m_VectorType.begin(); } VectorType::Iterator -VectorType::End () const +VectorType::End() const { - return m_VectorType.end (); + return m_VectorType.end(); } uint32_t -VectorType::GetN () const +VectorType::GetN() const { - return m_VectorType.size (); + return m_VectorType.size(); } std::vector -VectorType::Get () const +VectorType::Get() const { - std::vector v; + std::vector v; - for (auto c : m_VectorType) + for (auto c : m_VectorType) { - v.push_back (c); + v.push_back(c); } - return v; + return v; } int -VectorType::Get (const uint32_t i) const +VectorType::Get(const uint32_t i) const { - return m_VectorType[i]; + return m_VectorType[i]; } int -VectorType::GetFront () const +VectorType::GetFront() const { - return m_VectorType.front (); + return m_VectorType.front(); } int -VectorType::GetBack () const +VectorType::GetBack() const { - return m_VectorType.back (); + return m_VectorType.back(); } void -VectorType::Add (int coeff) +VectorType::Add(int coeff) { - m_VectorType.push_back (coeff); + m_VectorType.push_back(coeff); } -std::ostream & -operator<< (std::ostream &os, const VectorType &coeffs) +std::ostream& +operator<<(std::ostream& os, const VectorType& coeffs) { - os << coeffs.GetN () << ";"; + os << coeffs.GetN() << ";"; - for (auto coeff = coeffs.Begin (); - coeff != coeffs.End (); - coeff++) + for (auto coeff = coeffs.Begin(); coeff != coeffs.End(); coeff++) { - os << (*coeff) << ";"; + os << (*coeff) << ";"; } - return os; + return os; } -std::istream & -operator>> (std::istream &is, VectorType &coeffs) +std::istream& +operator>>(std::istream& is, VectorType& coeffs) { - char separator = '\0'; - uint32_t n; - int coeff; + char separator = '\0'; + uint32_t n; + int coeff; - is >> n >> separator; - if (separator != ';') - is.setstate (std::ios::failbit); + is >> n >> separator; + if (separator != ';') + is.setstate(std::ios::failbit); - for (uint32_t i = 0; i < n; i++) + for (uint32_t i = 0; i < n; i++) { - is >> coeff >> separator; + is >> coeff >> separator; - if (separator != ';') + if (separator != ';') { - is.setstate (std::ios::failbit); - break; + is.setstate(std::ios::failbit); + break; } - coeffs.Add (coeff); + coeffs.Add(coeff); } - return is; + return is; } } // namespace ns3 diff --git a/src/configuration/base/vector-type.h b/src/configuration/base/vector-type.h index b397860..7c0c1f1 100644 --- a/src/configuration/base/vector-type.h +++ b/src/configuration/base/vector-type.h @@ -20,11 +20,11 @@ #ifndef VECTOR_TYPE_H #define VECTOR_TYPE_H -#include -#include - -#include #include +#include + +#include +#include /** * \file @@ -32,18 +32,19 @@ * ns3::VectorTypeValue attribute value declarations and template implementations. */ -namespace ns3 { +namespace ns3 +{ // Additional docs for class VectorTypeValue: /** * This class can be used to hold variables of floating point type * such as 'std::vector' or 'float'. The internal format is 'std::vector'. */ -ATTRIBUTE_VALUE_DEFINE_WITH_NAME (std::vector, VectorType); -ATTRIBUTE_ACCESSOR_DEFINE (VectorType); +ATTRIBUTE_VALUE_DEFINE_WITH_NAME(std::vector, VectorType); +ATTRIBUTE_ACCESSOR_DEFINE(VectorType); template -Ptr MakeVectorTypeChecker (void); +Ptr MakeVectorTypeChecker(void); /** * Make a checker with a minimum value. @@ -55,7 +56,7 @@ Ptr MakeVectorTypeChecker (void); * \see AttributeChecker */ template -Ptr MakeVectorTypeChecker (std::vector min); +Ptr MakeVectorTypeChecker(std::vector min); /** * Make a checker with a minimum and a maximum value. @@ -68,48 +69,49 @@ Ptr MakeVectorTypeChecker (std::vector min); * \see AttributeChecker */ template -Ptr MakeVectorTypeChecker (std::vector min, std::vector max); - +Ptr MakeVectorTypeChecker(std::vector min, std::vector max); } // namespace ns3 - /*************************************************************** * Implementation of the templates declared above. ***************************************************************/ #include -namespace ns3 { +namespace ns3 +{ -namespace internal { +namespace internal +{ -Ptr MakeVectorTypeChecker (std::vector min, std::vector max, std::string name); +Ptr MakeVectorTypeChecker(std::vector min, + std::vector max, + std::string name); } // namespace internal template -Ptr MakeVectorTypeChecker (void) +Ptr +MakeVectorTypeChecker(void) { - return internal::MakeVectorTypeChecker (-std::numeric_limits::max (), - std::numeric_limits::max (), - TypeNameGet ()); + return internal::MakeVectorTypeChecker(-std::numeric_limits::max(), + std::numeric_limits::max(), + TypeNameGet()); } template -Ptr MakeVectorTypeChecker (std::vector min) +Ptr +MakeVectorTypeChecker(std::vector min) { - return internal::MakeVectorTypeChecker (min, - std::numeric_limits::max (), - TypeNameGet ()); + return internal::MakeVectorTypeChecker(min, std::numeric_limits::max(), TypeNameGet()); } template -Ptr MakeVectorTypeChecker (std::vector min, std::vector max) +Ptr +MakeVectorTypeChecker(std::vector min, std::vector max) { - return internal::MakeVectorTypeChecker (min, - max, - TypeNameGet ()); + return internal::MakeVectorTypeChecker(min, max, TypeNameGet()); } } // namespace ns3 diff --git a/src/configuration/base/vector.cc b/src/configuration/base/vector.cc index c8110b5..93aac4d 100644 --- a/src/configuration/base/vector.cc +++ b/src/configuration/base/vector.cc @@ -19,12 +19,14 @@ #include -namespace ns3 { +namespace ns3 +{ // This internal namespace is used to implement the templated methods of VectorChecker // that is instanciated in MakePairChecker. The non-templated base ns3::VectorChecker // is returned in that function. This is the same pattern as ObjectPtrContainer. -namespace internal { +namespace internal +{ /** * Internal checker class templated to each AttributeChecker @@ -33,81 +35,82 @@ namespace internal { template class VectorChecker : public AttributeChecker { -public: - /** Default Ctor */ - VectorChecker (); - /** - * Construct from an AttributeChecker - * \param [in] checker The AttributeChecker that will be copied in. - */ - VectorChecker (const AttributeChecker &checker); - void SetChecker (Ptr checker); - Ptr GetChecker () const; - -private: - /** The checker for each entry in the vector */ - Ptr m_checker; + public: + /** Default Ctor */ + VectorChecker(); + /** + * Construct from an AttributeChecker + * \param [in] checker The AttributeChecker that will be copied in. + */ + VectorChecker(const AttributeChecker& checker); + void SetChecker(Ptr checker); + Ptr GetChecker() const; + + private: + /** The checker for each entry in the vector */ + Ptr m_checker; }; template -VectorChecker::VectorChecker () : - m_checker {0} -{} +VectorChecker::VectorChecker() + : m_checker{0} +{ +} template -VectorChecker::VectorChecker (Ptr &checker) : - m_checker {checker} -{} +VectorChecker::VectorChecker(Ptr& checker) + : m_checker{checker} +{ +} template void -VectorChecker::SetChecker (Ptr checker) +VectorChecker::SetChecker(Ptr checker) { - m_checker = checker; + m_checker = checker; } template Ptr -VectorChecker::GetChecker () const +VectorChecker::GetChecker() const { - return m_checker; + return m_checker; } } // namespace internal template Ptr -MakeVectorChecker (const VectorValue& value) +MakeVectorChecker(const VectorValue& value) { - return MakeVectorChecker (); + return MakeVectorChecker(); } template Ptr -MakeVectorChecker () +MakeVectorChecker() { - std::string pairName; - std::string underlyingType; - std::string typeName = typeid (T).name (); - - { - std::ostringstream oss; - oss << "ns3::VectorValue<" << typeName << ">"; - pairName = oss.str (); - } - - { - std::ostringstream oss; - - } - + std::string pairName; + std::string underlyingType; + std::string typeName = typeid(T).name(); + + { + std::ostringstream oss; + oss << "ns3::VectorValue<" << typeName << ">"; + pairName = oss.str(); + } + + { + std::ostringstream oss; + } } } // namespace ns3 template Ptr -MakeVectorChecker (void) +MakeVectorChecker(void) { - return MakeSimpleAttributeChecker, VectorChecker> ("VectorValue", "std::vector"); + return MakeSimpleAttributeChecker, VectorChecker>("VectorValue", + "std::vector"); } diff --git a/src/configuration/base/vector.h b/src/configuration/base/vector.h index 14899c9..33aaa6e 100644 --- a/src/configuration/base/vector.h +++ b/src/configuration/base/vector.h @@ -20,15 +20,17 @@ #ifndef NS_VECTOR_H #define NS_VECTOR_H -namespace ns3 { +namespace ns3 +{ -#include #include +#include #include -#include #include -//#include +#include + +// #include /** * Output streamer for std::vector @@ -38,15 +40,16 @@ namespace ns3 { * \returns The output stream */ template -std::ostream & operator << (std::ostream &os, const std::vector &v) +std::ostream& +operator<<(std::ostream& os, const std::vector& v) { - os << "["; - for (auto& i : v) + os << "["; + for (auto& i : v) { - os << i << ","; + os << i << ","; } - os << "]"; - return os; + os << "]"; + return os; } /** @@ -55,31 +58,29 @@ std::ostream & operator << (std::ostream &os, const std::vector &v) template class VectorValue : public AttributeValue { -public: - /** Type of value stored in the VectorValue. */ - typedef std::vector> value_type; - /** Type of the elements stored in the Vector. */ + public: + /** Type of value stored in the VectorValue. */ + typedef std::vector> value_type; + /** Type of the elements stored in the Vector. */ typedef typename std::invoke_result_t element_type; /** Type returned by Get or passed to Set. */ typedef typename std::vector result_type; - VectorValue (); - VectorValue (const result_type &value); // "import" constructor - void Set (const result_type &value); - result_type Get (void) const; + VectorValue(); + VectorValue(const result_type& value); // "import" constructor + void Set(const result_type& value); + result_type Get(void) const; template - bool GetAccessor (U &value) const { - value = U (m_value); - return value; + bool GetAccessor(U& value) const + { + value = U(m_value); + return value; } - virtual Ptr Copy (void) const; - virtual std::string - SerializeToString (Ptr checker) const; - virtual bool - DeserializeFromString (std::string value, - Ptr checker); + virtual Ptr Copy(void) const; + virtual std::string SerializeToString(Ptr checker) const; + virtual bool DeserializeFromString(std::string value, Ptr checker); private: value_type m_value; @@ -88,10 +89,8 @@ class VectorValue : public AttributeValue class VectorChecker : public AttributeChecker { public: - - - virtual void SetChecker (Ptr checker) = 0; - virtual Ptr GetChecker (void) const = 0; + virtual void SetChecker(Ptr checker) = 0; + virtual Ptr GetChecker(void) const = 0; }; /** @@ -101,8 +100,7 @@ class VectorChecker : public AttributeChecker * \returns A Pointer to a non-const VectorChecker. */ template -Ptr -MakeVectorChecker (const VectorValue &value); +Ptr MakeVectorChecker(const VectorValue& value); /** * Make a VectorChecker without a given std::vector. @@ -110,11 +108,9 @@ MakeVectorChecker (const VectorValue &value); * \returns A Pointer to a non-const VectorChecker instnace. */ template -Ptr -MakeVectorChecker (); +Ptr MakeVectorChecker(); -tmeplate -Ptr MakePairAccessor (T a); +tmeplate Ptr MakePairAccessor(T a); } // namespace ns3 diff --git a/src/configuration/entity-configuration.cc b/src/configuration/entity-configuration.cc index 7000378..f368226 100644 --- a/src/configuration/entity-configuration.cc +++ b/src/configuration/entity-configuration.cc @@ -17,87 +17,84 @@ */ #include "entity-configuration.h" -namespace ns3 { - -EntityConfiguration::EntityConfiguration (std::vector> netDevices, - MobilityModelConfiguration mobility, - std::vector applications) : - m_netDevices {netDevices}, - m_mobility {mobility}, - m_applications {applications} +namespace ns3 { +EntityConfiguration::EntityConfiguration(std::vector> netDevices, + MobilityModelConfiguration mobility, + std::vector applications) + : m_netDevices{netDevices}, + m_mobility{mobility}, + m_applications{applications} +{ } -EntityConfiguration::EntityConfiguration (std::vector> netDevices, - MobilityModelConfiguration mobility, - std::vector applications, - ModelConfiguration mechanics, - ModelConfiguration battery) : - m_netDevices {netDevices}, - m_mobility {mobility}, - m_applications {applications}, - m_mechanics {mechanics}, - m_battery {battery} +EntityConfiguration::EntityConfiguration(std::vector> netDevices, + MobilityModelConfiguration mobility, + std::vector applications, + ModelConfiguration mechanics, + ModelConfiguration battery) + : m_netDevices{netDevices}, + m_mobility{mobility}, + m_applications{applications}, + m_mechanics{mechanics}, + m_battery{battery} { - } -EntityConfiguration::EntityConfiguration (std::vector> netDevices, - MobilityModelConfiguration mobility, - std::vector applications, - ModelConfiguration mechanics, - ModelConfiguration battery, - std::vector peripherals) : - m_netDevices {netDevices}, - m_mobility {mobility}, - m_applications {applications}, - m_mechanics {mechanics}, - m_battery {battery}, - m_peripherals {peripherals} +EntityConfiguration::EntityConfiguration(std::vector> netDevices, + MobilityModelConfiguration mobility, + std::vector applications, + ModelConfiguration mechanics, + ModelConfiguration battery, + std::vector peripherals) + : m_netDevices{netDevices}, + m_mobility{mobility}, + m_applications{applications}, + m_mechanics{mechanics}, + m_battery{battery}, + m_peripherals{peripherals} { - } -EntityConfiguration::~EntityConfiguration () +EntityConfiguration::~EntityConfiguration() { - } const std::vector>& -EntityConfiguration::GetNetDevices () const +EntityConfiguration::GetNetDevices() const { - return m_netDevices; + return m_netDevices; } const MobilityModelConfiguration& -EntityConfiguration::GetMobilityModel () const +EntityConfiguration::GetMobilityModel() const { - return m_mobility; + return m_mobility; } const std::vector& -EntityConfiguration::GetApplications () const +EntityConfiguration::GetApplications() const { - return m_applications; + return m_applications; } const ModelConfiguration& -EntityConfiguration::GetMechanics () const +EntityConfiguration::GetMechanics() const { - return m_mechanics; + return m_mechanics; } const ModelConfiguration& -EntityConfiguration::GetBattery () const +EntityConfiguration::GetBattery() const { - return m_battery; + return m_battery; } const std::vector& -EntityConfiguration::GetPeripherals () const +EntityConfiguration::GetPeripherals() const { - return m_peripherals; + return m_peripherals; } } // namespace ns3 diff --git a/src/configuration/entity-configuration.h b/src/configuration/entity-configuration.h index 684de3b..1898e08 100644 --- a/src/configuration/entity-configuration.h +++ b/src/configuration/entity-configuration.h @@ -18,13 +18,13 @@ #ifndef ENTITY_CONFIGURATION_H #define ENTITY_CONFIGURATION_H -#include - -#include #include +#include #include +#include -namespace ns3 { +namespace ns3 +{ /** * \brief Describe the configuration of a generic entity to be simulated. @@ -32,42 +32,41 @@ namespace ns3 { class EntityConfiguration : public Object { public: - EntityConfiguration (std::vector> m_netDevices, - MobilityModelConfiguration m_mobility, - std::vector m_applications); + EntityConfiguration(std::vector> m_netDevices, + MobilityModelConfiguration m_mobility, + std::vector m_applications); - EntityConfiguration (std::vector> m_netDevices, - MobilityModelConfiguration m_mobility, - std::vector m_applications, - ModelConfiguration m_mechanics, - ModelConfiguration m_battery); + EntityConfiguration(std::vector> m_netDevices, + MobilityModelConfiguration m_mobility, + std::vector m_applications, + ModelConfiguration m_mechanics, + ModelConfiguration m_battery); - EntityConfiguration (std::vector> m_netDevices, - MobilityModelConfiguration m_mobility, - std::vector m_applications, - ModelConfiguration m_mechanics, - ModelConfiguration m_battery, - std::vector m_peripherals); + EntityConfiguration(std::vector> m_netDevices, + MobilityModelConfiguration m_mobility, + std::vector m_applications, + ModelConfiguration m_mechanics, + ModelConfiguration m_battery, + std::vector m_peripherals); - ~EntityConfiguration (); + ~EntityConfiguration(); - const std::vector>& GetNetDevices () const; - const MobilityModelConfiguration& GetMobilityModel () const; - const std::vector& GetApplications () const; - const ModelConfiguration& GetMechanics () const; - const ModelConfiguration& GetBattery () const; - const std::vector& GetPeripherals () const; + const std::vector>& GetNetDevices() const; + const MobilityModelConfiguration& GetMobilityModel() const; + const std::vector& GetApplications() const; + const ModelConfiguration& GetMechanics() const; + const ModelConfiguration& GetBattery() const; + const std::vector& GetPeripherals() const; -private: - const std::vector> m_netDevices; - const MobilityModelConfiguration m_mobility; - const std::vector m_applications; - const ModelConfiguration m_mechanics; - const ModelConfiguration m_battery; - const std::vector m_peripherals; + private: + const std::vector> m_netDevices; + const MobilityModelConfiguration m_mobility; + const std::vector m_applications; + const ModelConfiguration m_mechanics; + const ModelConfiguration m_battery; + const std::vector m_peripherals; }; } // namespace ns3 - #endif /* ENTITY_CONFIGURATION_H */ diff --git a/src/configuration/helper/drone-energy-model-helper.cc b/src/configuration/helper/drone-energy-model-helper.cc index 5273c80..6561216 100644 --- a/src/configuration/helper/drone-energy-model-helper.cc +++ b/src/configuration/helper/drone-energy-model-helper.cc @@ -19,35 +19,36 @@ #include -namespace ns3 { +namespace ns3 +{ -DroneEnergyModelHelper::DroneEnergyModelHelper () +DroneEnergyModelHelper::DroneEnergyModelHelper() { - m_droneEnergyModel.SetTypeId ("ns3::DroneEnergyModel"); + m_droneEnergyModel.SetTypeId("ns3::DroneEnergyModel"); } void -DroneEnergyModelHelper::Set (std::string name, const AttributeValue &v) +DroneEnergyModelHelper::Set(std::string name, const AttributeValue& v) { - m_droneEnergyModel.Set (name, v); + m_droneEnergyModel.Set(name, v); } Ptr -DroneEnergyModelHelper::Install (Ptr drone, Ptr source) +DroneEnergyModelHelper::Install(Ptr drone, Ptr source) { - Ptr model = m_droneEnergyModel.Create (); - model->SetDrone (drone); - model->SetEnergySource (source); - source->AppendDeviceEnergyModel (model); - source->SetNode (drone); - return model; + Ptr model = m_droneEnergyModel.Create(); + model->SetDrone(drone); + model->SetEnergySource(source); + source->AppendDeviceEnergyModel(model); + source->SetNode(drone); + return model; } Ptr -DroneEnergyModelHelper::DoInstall (Ptr device, Ptr source) const +DroneEnergyModelHelper::DoInstall(Ptr device, Ptr source) const { - Ptr model = m_droneEnergyModel.Create (); - return model; + Ptr model = m_droneEnergyModel.Create(); + return model; } } // namespace ns3 diff --git a/src/configuration/helper/drone-energy-model-helper.h b/src/configuration/helper/drone-energy-model-helper.h index b654b41..bbfead7 100644 --- a/src/configuration/helper/drone-energy-model-helper.h +++ b/src/configuration/helper/drone-energy-model-helper.h @@ -21,7 +21,8 @@ #include #include -namespace ns3 { +namespace ns3 +{ /** * \ingroup energy @@ -29,31 +30,31 @@ namespace ns3 { */ class DroneEnergyModelHelper : public DeviceEnergyModelHelper { -public: - DroneEnergyModelHelper (); - - /** - * \param name Name of attribute to set. - * \param v Value of the attribute. - * - * Sets one of the attributes of underlying DroneEnergyModel. - */ - virtual void Set (std::string name, const AttributeValue &v); - - /** - * \param drone Pointer to the Drone to install DroneEnergyModel. - * \param source The EnergySource the DroneEnergyModel will be using. - * \returns The resultant DeviceEnergyModel. - * - * Installs a DroneEnergyModel with a specified EnergySource onto a - * Drone. - */ - Ptr Install (Ptr drone, Ptr source); - -private: - Ptr DoInstall (Ptr device, Ptr source) const; - - ObjectFactory m_droneEnergyModel; + public: + DroneEnergyModelHelper(); + + /** + * \param name Name of attribute to set. + * \param v Value of the attribute. + * + * Sets one of the attributes of underlying DroneEnergyModel. + */ + virtual void Set(std::string name, const AttributeValue& v); + + /** + * \param drone Pointer to the Drone to install DroneEnergyModel. + * \param source The EnergySource the DroneEnergyModel will be using. + * \returns The resultant DeviceEnergyModel. + * + * Installs a DroneEnergyModel with a specified EnergySource onto a + * Drone. + */ + Ptr Install(Ptr drone, Ptr source); + + private: + Ptr DoInstall(Ptr device, Ptr source) const; + + ObjectFactory m_droneEnergyModel; }; } // namespace ns3 diff --git a/src/configuration/helper/entity-configuration-helper.cc b/src/configuration/helper/entity-configuration-helper.cc index 3d748cb..4ce1700 100644 --- a/src/configuration/helper/entity-configuration-helper.cc +++ b/src/configuration/helper/entity-configuration-helper.cc @@ -17,274 +17,293 @@ */ #include "entity-configuration-helper.h" -#include +#include "model-configuration-helper.h" +#include #include +#include +#include #include #include +#include #include #include #include #include #include - -#include -#include #include -#include -#include -#include "model-configuration-helper.h" +#include -namespace ns3 { +namespace ns3 +{ Ptr -EntityConfigurationHelper::GetConfiguration (const rapidjson::Value& json) +EntityConfigurationHelper::GetConfiguration(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsObject (), - "Entity configuration must be an object."); - NS_ASSERT_MSG (json.HasMember ("mobilityModel"), - "Entity configuration must have 'mobilityModel'property."); - NS_ASSERT_MSG (json.HasMember ("applications"), - "Entity configuration must have 'applications' property defined."); - - const auto netDevices = json.HasMember ("netDevices") - ? DecodeNetdeviceConfigurations (json["netDevices"]) - : std::vector> (); - const auto mobilityModel = DecodeMobilityConfiguration (json["mobilityModel"]); - const auto applications = DecodeApplicationConfigurations (json["applications"]); - - if (json.HasMember("mechanics") && json.HasMember("battery")) + NS_ASSERT_MSG(json.IsObject(), "Entity configuration must be an object."); + NS_ASSERT_MSG(json.HasMember("mobilityModel"), + "Entity configuration must have 'mobilityModel'property."); + NS_ASSERT_MSG(json.HasMember("applications"), + "Entity configuration must have 'applications' property defined."); + + const auto netDevices = json.HasMember("netDevices") + ? DecodeNetdeviceConfigurations(json["netDevices"]) + : std::vector>(); + const auto mobilityModel = DecodeMobilityConfiguration(json["mobilityModel"]); + const auto applications = DecodeApplicationConfigurations(json["applications"]); + + if (json.HasMember("mechanics") && json.HasMember("battery")) { - const auto mechanics = DecodeMechanicsConfiguration (json["mechanics"]); - const auto battery = DecodeBatteryConfiguration (json["battery"]); - if (json.HasMember("peripherals")) + const auto mechanics = DecodeMechanicsConfiguration(json["mechanics"]); + const auto battery = DecodeBatteryConfiguration(json["battery"]); + if (json.HasMember("peripherals")) { - const auto peripherals = DecodePeripheralConfigurations (json["peripherals"]); - return CreateObject (netDevices, mobilityModel, applications, mechanics, battery, peripherals); + const auto peripherals = DecodePeripheralConfigurations(json["peripherals"]); + return CreateObject(netDevices, + mobilityModel, + applications, + mechanics, + battery, + peripherals); } - return CreateObject (netDevices, mobilityModel, applications, mechanics, battery); + return CreateObject(netDevices, + mobilityModel, + applications, + mechanics, + battery); } - else + else { - return CreateObject (netDevices, mobilityModel, applications); + return CreateObject(netDevices, mobilityModel, applications); } - } -EntityConfigurationHelper::EntityConfigurationHelper () +EntityConfigurationHelper::EntityConfigurationHelper() { - } const std::vector> -EntityConfigurationHelper::DecodeNetdeviceConfigurations (const rapidjson::Value& json) +EntityConfigurationHelper::DecodeNetdeviceConfigurations(const rapidjson::Value& json) { - if (json.IsNull ()) - return {}; + if (json.IsNull()) + return {}; - NS_ASSERT_MSG (json.IsArray (), - "Entity configuration 'netDevices' property must be an array."); + NS_ASSERT_MSG(json.IsArray(), "Entity configuration 'netDevices' property must be an array."); - std::vector> confs; - for (auto& netdev : json.GetArray ()) + std::vector> confs; + for (auto& netdev : json.GetArray()) { - NS_ASSERT_MSG (netdev.IsObject (), - "Every Entity Network Device configuration must be an object."); - NS_ASSERT_MSG (netdev.HasMember ("type"), - "Entity Network Device must have 'type' property defined."); - NS_ASSERT_MSG (netdev["type"].IsString (), - "Entity Network Device 'type' property must be a string."); + NS_ASSERT_MSG(netdev.IsObject(), + "Every Entity Network Device configuration must be an object."); + NS_ASSERT_MSG(netdev.HasMember("type"), + "Entity Network Device must have 'type' property defined."); + NS_ASSERT_MSG(netdev["type"].IsString(), + "Entity Network Device 'type' property must be a string."); - const std::string type = netdev["type"].GetString (); + const std::string type = netdev["type"].GetString(); - NS_ASSERT_MSG (netdev.HasMember ("networkLayer"), - "Entity Network Device must have 'networkLayer' property defined."); - NS_ASSERT_MSG (netdev["networkLayer"].IsUint (), - "Entity Network Device 'networkLayer' property must be an unsigned integer."); + NS_ASSERT_MSG(netdev.HasMember("networkLayer"), + "Entity Network Device must have 'networkLayer' property defined."); + NS_ASSERT_MSG(netdev["networkLayer"].IsUint(), + "Entity Network Device 'networkLayer' property must be an unsigned integer."); - const uint32_t networkLayerId = netdev["networkLayer"].GetUint (); + const uint32_t networkLayerId = netdev["networkLayer"].GetUint(); - if (type == "wifi") + if (type == "wifi") { - NS_ASSERT_MSG (netdev.HasMember ("macLayer"), - "Entity WiFi Network Device must have 'macLayer' property defined."); - NS_ASSERT_MSG (netdev["macLayer"].IsObject (), - "Entity WiFi Network Device 'macLayer' property must be an object."); + NS_ASSERT_MSG(netdev.HasMember("macLayer"), + "Entity WiFi Network Device must have 'macLayer' property defined."); + NS_ASSERT_MSG(netdev["macLayer"].IsObject(), + "Entity WiFi Network Device 'macLayer' property must be an object."); - const auto macLayer = ModelConfigurationHelper::Get (netdev["macLayer"]); + const auto macLayer = ModelConfigurationHelper::Get(netdev["macLayer"]); - confs.push_back (CreateObject (type, macLayer, networkLayerId)); + confs.push_back( + CreateObject(type, macLayer, networkLayerId)); } - else if (type == "lte") + else if (type == "lte") { - NS_ASSERT_MSG (netdev.HasMember ("role"), - "Entity LTE Network Device must have 'role' property defined."); - NS_ASSERT_MSG (netdev["role"].IsString (), - "Entity LTE Network Device 'role' property must be a string."); - - const std::string role = netdev["role"].GetString (); - - NS_ASSERT_MSG (netdev.HasMember ("bearers"), - "Entity LTE Network Device must have 'bearers' property defined."); - NS_ASSERT_MSG (netdev["bearers"].IsArray (), - "Entity LTE Network Device 'bearers' must be an array."); - - const auto bearers = DecodeLteBearerConfigurations (netdev["bearers"].GetArray ()); - const auto antennaModel = ModelConfigurationHelper::GetOptional (netdev.GetObject (), "antennaModel"); - const auto phyTid = (role == "eNB") - ? LteEnbPhy::GetTypeId () - : LteUePhy::GetTypeId (); - const std::optional phyModel = ModelConfigurationHelper::GetOptionalCoaleshed (netdev.GetObject (), "phy", phyTid); - - confs.push_back (CreateObject (type, role, bearers, networkLayerId, antennaModel, phyModel)); + NS_ASSERT_MSG(netdev.HasMember("role"), + "Entity LTE Network Device must have 'role' property defined."); + NS_ASSERT_MSG(netdev["role"].IsString(), + "Entity LTE Network Device 'role' property must be a string."); + + const std::string role = netdev["role"].GetString(); + + NS_ASSERT_MSG(netdev.HasMember("bearers"), + "Entity LTE Network Device must have 'bearers' property defined."); + NS_ASSERT_MSG(netdev["bearers"].IsArray(), + "Entity LTE Network Device 'bearers' must be an array."); + + const auto bearers = DecodeLteBearerConfigurations(netdev["bearers"].GetArray()); + const auto antennaModel = + ModelConfigurationHelper::GetOptional(netdev.GetObject(), "antennaModel"); + const auto phyTid = (role == "eNB") ? LteEnbPhy::GetTypeId() : LteUePhy::GetTypeId(); + const std::optional phyModel = + ModelConfigurationHelper::GetOptionalCoaleshed(netdev.GetObject(), "phy", phyTid); + + confs.push_back(CreateObject(type, + role, + bearers, + networkLayerId, + antennaModel, + phyModel)); } - else + else { - NS_FATAL_ERROR ("Entity Network Device of Type " << type << " is not supported!"); + NS_FATAL_ERROR("Entity Network Device of Type " << type << " is not supported!"); } } - return confs; + return confs; } const std::vector -EntityConfigurationHelper::DecodeLteBearerConfigurations (const JsonArray& jsonArray) +EntityConfigurationHelper::DecodeLteBearerConfigurations(const JsonArray& jsonArray) { - auto bearers = std::vector (); + auto bearers = std::vector(); - for (auto& bearerConf : jsonArray) + for (auto& bearerConf : jsonArray) { - NS_ASSERT_MSG (bearerConf.HasMember ("type"), - "Entity LTE Bearer configuration must have 'type' property defined."); - NS_ASSERT_MSG (bearerConf["type"].IsString (), - "Entity LTE Bearer configuration 'type' must be an array."); - NS_ASSERT_MSG (bearerConf.HasMember ("bitrate"), - "Entity LTE Bearer configuration must have 'bitrate' property defined."); - NS_ASSERT_MSG (bearerConf["bitrate"].IsObject (), - "Entity LTE Bearer configuration 'bitrate' must be an object."); - NS_ASSERT_MSG (bearerConf["bitrate"].HasMember ("guaranteed"), - "Entity LTE Bearer configuration bitrate must have 'guaranteed' property defined."); - NS_ASSERT_MSG (bearerConf["bitrate"]["guaranteed"].IsObject (), - "Entity LTE Bearer configuration 'guaranteed' bitrate must be an object."); - NS_ASSERT_MSG (bearerConf["bitrate"]["guaranteed"].HasMember ("downlink"), - "Entity LTE Bearer configuration guaranteed bitrate must have 'downlink' property defined."); - NS_ASSERT_MSG (bearerConf["bitrate"]["guaranteed"]["downlink"].IsDouble (), - "Entity LTE Bearer configuration 'downlink' guaranteed bitrate must be an unsigned integer."); - NS_ASSERT_MSG (bearerConf["bitrate"]["guaranteed"].HasMember ("uplink"), - "Entity LTE Bearer configuration guaranteed bitrate must have 'uplink' property defined."); - NS_ASSERT_MSG (bearerConf["bitrate"]["guaranteed"]["uplink"].IsDouble (), - "Entity LTE Bearer configuration 'uplink' guaranteed bitrate must be an unsigned integer."); - NS_ASSERT_MSG (bearerConf["bitrate"].HasMember ("maximum"), - "Entity LTE Bearer configuration bitrate must have 'maximum' property defined."); - NS_ASSERT_MSG (bearerConf["bitrate"]["maximum"].IsObject (), - "Entity LTE Bearer configuration 'maximum' bitrate must be an object."); - NS_ASSERT_MSG (bearerConf["bitrate"]["maximum"].HasMember ("downlink"), - "Entity LTE Bearer configuration maximum bitrate must have 'downlink' property defined."); - NS_ASSERT_MSG (bearerConf["bitrate"]["maximum"]["downlink"].IsDouble (), - "Entity LTE Bearer configuration 'downlink' maximum bitrate must be an unsigned integer."); - NS_ASSERT_MSG (bearerConf["bitrate"]["maximum"].HasMember ("uplink"), - "Entity LTE Bearer configuration maximum bitrate must have 'uplink' property defined."); - NS_ASSERT_MSG (bearerConf["bitrate"]["maximum"]["uplink"].IsDouble (), - "Entity LTE Bearer configuration 'uplink' maximum bitrate must be an unsigned integer."); - - const std::string type = bearerConf["type"].GetString (); - const double gbrDl = bearerConf["bitrate"]["guaranteed"]["downlink"].GetDouble (); - const double gbrUl = bearerConf["bitrate"]["guaranteed"]["uplink"].GetDouble (); - const double mbrDl = bearerConf["bitrate"]["maximum"]["downlink"].GetDouble (); - const double mbrUl = bearerConf["bitrate"]["maximum"]["uplink"].GetDouble (); - - NS_ASSERT_MSG (gbrDl >= 0.0 && gbrUl >= 0.0 && mbrDl >= 0.0 && mbrUl >= 0.0 && - floor(gbrDl) == gbrDl && floor(gbrUl) == gbrUl && floor(mbrDl) == mbrDl && floor(mbrUl) == mbrUl, - "Bitrate must be a positive integral number."); - - bearers.push_back (LteBearerConfiguration (type, (uint64_t) gbrDl, (uint64_t) gbrUl, (uint64_t) mbrDl, (uint64_t) mbrUl)); + NS_ASSERT_MSG(bearerConf.HasMember("type"), + "Entity LTE Bearer configuration must have 'type' property defined."); + NS_ASSERT_MSG(bearerConf["type"].IsString(), + "Entity LTE Bearer configuration 'type' must be an array."); + NS_ASSERT_MSG(bearerConf.HasMember("bitrate"), + "Entity LTE Bearer configuration must have 'bitrate' property defined."); + NS_ASSERT_MSG(bearerConf["bitrate"].IsObject(), + "Entity LTE Bearer configuration 'bitrate' must be an object."); + NS_ASSERT_MSG( + bearerConf["bitrate"].HasMember("guaranteed"), + "Entity LTE Bearer configuration bitrate must have 'guaranteed' property defined."); + NS_ASSERT_MSG(bearerConf["bitrate"]["guaranteed"].IsObject(), + "Entity LTE Bearer configuration 'guaranteed' bitrate must be an object."); + NS_ASSERT_MSG(bearerConf["bitrate"]["guaranteed"].HasMember("downlink"), + "Entity LTE Bearer configuration guaranteed bitrate must have 'downlink' " + "property defined."); + NS_ASSERT_MSG(bearerConf["bitrate"]["guaranteed"]["downlink"].IsDouble(), + "Entity LTE Bearer configuration 'downlink' guaranteed bitrate must be an " + "unsigned integer."); + NS_ASSERT_MSG(bearerConf["bitrate"]["guaranteed"].HasMember("uplink"), + "Entity LTE Bearer configuration guaranteed bitrate must have 'uplink' " + "property defined."); + NS_ASSERT_MSG(bearerConf["bitrate"]["guaranteed"]["uplink"].IsDouble(), + "Entity LTE Bearer configuration 'uplink' guaranteed bitrate must be an " + "unsigned integer."); + NS_ASSERT_MSG( + bearerConf["bitrate"].HasMember("maximum"), + "Entity LTE Bearer configuration bitrate must have 'maximum' property defined."); + NS_ASSERT_MSG(bearerConf["bitrate"]["maximum"].IsObject(), + "Entity LTE Bearer configuration 'maximum' bitrate must be an object."); + NS_ASSERT_MSG(bearerConf["bitrate"]["maximum"].HasMember("downlink"), + "Entity LTE Bearer configuration maximum bitrate must have 'downlink' " + "property defined."); + NS_ASSERT_MSG(bearerConf["bitrate"]["maximum"]["downlink"].IsDouble(), + "Entity LTE Bearer configuration 'downlink' maximum bitrate must be an " + "unsigned integer."); + NS_ASSERT_MSG( + bearerConf["bitrate"]["maximum"].HasMember("uplink"), + "Entity LTE Bearer configuration maximum bitrate must have 'uplink' property defined."); + NS_ASSERT_MSG(bearerConf["bitrate"]["maximum"]["uplink"].IsDouble(), + "Entity LTE Bearer configuration 'uplink' maximum bitrate must be an " + "unsigned integer."); + + const std::string type = bearerConf["type"].GetString(); + const double gbrDl = bearerConf["bitrate"]["guaranteed"]["downlink"].GetDouble(); + const double gbrUl = bearerConf["bitrate"]["guaranteed"]["uplink"].GetDouble(); + const double mbrDl = bearerConf["bitrate"]["maximum"]["downlink"].GetDouble(); + const double mbrUl = bearerConf["bitrate"]["maximum"]["uplink"].GetDouble(); + + NS_ASSERT_MSG(gbrDl >= 0.0 && gbrUl >= 0.0 && mbrDl >= 0.0 && mbrUl >= 0.0 && + floor(gbrDl) == gbrDl && floor(gbrUl) == gbrUl && floor(mbrDl) == mbrDl && + floor(mbrUl) == mbrUl, + "Bitrate must be a positive integral number."); + + bearers.push_back(LteBearerConfiguration(type, + (uint64_t)gbrDl, + (uint64_t)gbrUl, + (uint64_t)mbrDl, + (uint64_t)mbrUl)); } - return bearers; + return bearers; } const MobilityModelConfiguration -EntityConfigurationHelper::DecodeMobilityConfiguration (const rapidjson::Value& json) +EntityConfigurationHelper::DecodeMobilityConfiguration(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsObject (), - "Entity mobility model configuration must be an object."); + NS_ASSERT_MSG(json.IsObject(), "Entity mobility model configuration must be an object."); - const ModelConfiguration base = ModelConfigurationHelper::Get (json); - const std::optional initialPosition = DecodeInitialPosition (json); + const ModelConfiguration base = ModelConfigurationHelper::Get(json); + const std::optional initialPosition = DecodeInitialPosition(json); - return MobilityModelConfiguration (base.GetName (), base.GetAttributes (), initialPosition); + return MobilityModelConfiguration(base.GetName(), base.GetAttributes(), initialPosition); } const std::vector -EntityConfigurationHelper::DecodeApplicationConfigurations (const rapidjson::Value& json) +EntityConfigurationHelper::DecodeApplicationConfigurations(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsArray (), - "Entity configuration 'applications' property must be an array."); + NS_ASSERT_MSG(json.IsArray(), "Entity configuration 'applications' property must be an array."); - std::vector confs; - for (auto& appl : json.GetArray ()) + std::vector confs; + for (auto& appl : json.GetArray()) { - NS_ASSERT_MSG (appl.IsObject (), - "Application model configuration must be an object."); + NS_ASSERT_MSG(appl.IsObject(), "Application model configuration must be an object."); - confs.push_back (ModelConfigurationHelper::Get (appl)); + confs.push_back(ModelConfigurationHelper::Get(appl)); } - return confs; + return confs; } const ModelConfiguration -EntityConfigurationHelper::DecodeMechanicsConfiguration (const rapidjson::Value& json) +EntityConfigurationHelper::DecodeMechanicsConfiguration(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsObject (), - "Entity mechanics configuration must be an object."); + NS_ASSERT_MSG(json.IsObject(), "Entity mechanics configuration must be an object."); - return ModelConfigurationHelper::Get (json); + return ModelConfigurationHelper::Get(json); } const ModelConfiguration -EntityConfigurationHelper::DecodeBatteryConfiguration (const rapidjson::Value& json) +EntityConfigurationHelper::DecodeBatteryConfiguration(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsObject (), - "Entity battery configuration must be an object."); + NS_ASSERT_MSG(json.IsObject(), "Entity battery configuration must be an object."); - return ModelConfigurationHelper::Get (json); + return ModelConfigurationHelper::Get(json); } const std::vector -EntityConfigurationHelper::DecodePeripheralConfigurations (const rapidjson::Value& json) +EntityConfigurationHelper::DecodePeripheralConfigurations(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsArray (), - "Entity configuration 'peripherals' property must be an array."); + NS_ASSERT_MSG(json.IsArray(), "Entity configuration 'peripherals' property must be an array."); - std::vector confs; - for (auto& peripheral : json.GetArray ()) + std::vector confs; + for (auto& peripheral : json.GetArray()) { - NS_ASSERT_MSG (peripheral.IsObject (), - "Peripheral model configuration must be an object."); + NS_ASSERT_MSG(peripheral.IsObject(), "Peripheral model configuration must be an object."); - confs.push_back (ModelConfigurationHelper::Get (peripheral)); + confs.push_back(ModelConfigurationHelper::Get(peripheral)); } - return confs; + return confs; } const std::optional -EntityConfigurationHelper::DecodeInitialPosition (const rapidjson::Value& jsonModel) +EntityConfigurationHelper::DecodeInitialPosition(const rapidjson::Value& jsonModel) { - // Initial Position is optional as not all mobility models use it! - if (!(jsonModel.HasMember ("initialPosition"))) - return std::nullopt; + // Initial Position is optional as not all mobility models use it! + if (!(jsonModel.HasMember("initialPosition"))) + return std::nullopt; - NS_ASSERT_MSG (jsonModel["initialPosition"].IsArray (), - "Mobility Model initialPosition must be an array of 3 coordinates."); + NS_ASSERT_MSG(jsonModel["initialPosition"].IsArray(), + "Mobility Model initialPosition must be an array of 3 coordinates."); - auto arr = jsonModel["initialPosition"].GetArray(); - NS_ASSERT_MSG (arr.Size () != 3 || !arr[0].IsDouble () || !arr[1].IsDouble () || !arr[2].IsDouble (), - "Mobility Model initialPosition must be an array of 3 coordinates."); + auto arr = jsonModel["initialPosition"].GetArray(); + NS_ASSERT_MSG(arr.Size() != 3 || !arr[0].IsDouble() || !arr[1].IsDouble() || !arr[2].IsDouble(), + "Mobility Model initialPosition must be an array of 3 coordinates."); - return Vector(arr[0].GetDouble (), arr[1].GetDouble (), arr[2].GetDouble ()); + return Vector(arr[0].GetDouble(), arr[1].GetDouble(), arr[2].GetDouble()); } } // namespace ns3 diff --git a/src/configuration/helper/entity-configuration-helper.h b/src/configuration/helper/entity-configuration-helper.h index eee4038..108f899 100644 --- a/src/configuration/helper/entity-configuration-helper.h +++ b/src/configuration/helper/entity-configuration-helper.h @@ -18,18 +18,20 @@ #ifndef ENTITY_CONFIGURATION_HELPER_H #define ENTITY_CONFIGURATION_HELPER_H -#include - #include #include #include -namespace ns3 { +#include + +namespace ns3 +{ using JsonArray = rapidjson::GenericArray; /** - * Helper to decode an Entity (i.e., Drone or ZSP) from a JSON configuration file and read the following properties: + * Helper to decode an Entity (i.e., Drone or ZSP) from a JSON configuration file and read the + * following properties: * - Its network device(s) * - Its associated mobility model * - Its application(s) @@ -37,29 +39,35 @@ using JsonArray = rapidjson::GenericArray; */ class EntityConfigurationHelper { -public: - /** - * Parse an entity configuration from a given JSON tree and map it on an EntityConfiguration data class. - * - * \param json The JSON tree to parse. - * \return The configuration as a pointer to EntityConfiguration to easily retrieve parsed data. - */ - static Ptr GetConfiguration (const rapidjson::Value& json); + public: + /** + * Parse an entity configuration from a given JSON tree and map it on an EntityConfiguration + * data class. + * + * \param json The JSON tree to parse. + * \return The configuration as a pointer to EntityConfiguration to easily retrieve parsed data. + */ + static Ptr GetConfiguration(const rapidjson::Value& json); -private: - EntityConfigurationHelper (); + private: + EntityConfigurationHelper(); - static const std::vector> DecodeNetdeviceConfigurations (const rapidjson::Value& json); - static const std::vector DecodeLteBearerConfigurations (const JsonArray& json); - static const MobilityModelConfiguration DecodeMobilityConfiguration (const rapidjson::Value& json); - static const std::optional DecodeInitialPosition (const rapidjson::Value& json); - static const std::vector DecodeApplicationConfigurations (const rapidjson::Value& json); - static const ModelConfiguration DecodeMechanicsConfiguration (const rapidjson::Value& json); - static const ModelConfiguration DecodeBatteryConfiguration (const rapidjson::Value& json); - static const std::vector DecodePeripheralConfigurations(const rapidjson::Value& json); - static const ModelConfiguration DecodeModelConfiguration (const rapidjson::Value &json); + static const std::vector> DecodeNetdeviceConfigurations( + const rapidjson::Value& json); + static const std::vector DecodeLteBearerConfigurations( + const JsonArray& json); + static const MobilityModelConfiguration DecodeMobilityConfiguration( + const rapidjson::Value& json); + static const std::optional DecodeInitialPosition(const rapidjson::Value& json); + static const std::vector DecodeApplicationConfigurations( + const rapidjson::Value& json); + static const ModelConfiguration DecodeMechanicsConfiguration(const rapidjson::Value& json); + static const ModelConfiguration DecodeBatteryConfiguration(const rapidjson::Value& json); + static const std::vector DecodePeripheralConfigurations( + const rapidjson::Value& json); + static const ModelConfiguration DecodeModelConfiguration(const rapidjson::Value& json); }; -} +} // namespace ns3 #endif /* ENTITY_CONFIGURATION_HELPER_H */ diff --git a/src/configuration/helper/ipv4-simulation-helper.cc b/src/configuration/helper/ipv4-simulation-helper.cc index 761169f..0348cad 100644 --- a/src/configuration/helper/ipv4-simulation-helper.cc +++ b/src/configuration/helper/ipv4-simulation-helper.cc @@ -17,48 +17,47 @@ */ #include "ipv4-simulation-helper.h" -namespace ns3 { - -Ipv4SimulationHelper::Ipv4SimulationHelper (const std::string mask, const std::string gatewayAddress) : - m_mask {mask}, - m_gatewayAddress {gatewayAddress.c_str ()} +namespace ns3 { +Ipv4SimulationHelper::Ipv4SimulationHelper(const std::string mask, const std::string gatewayAddress) + : m_mask{mask}, + m_gatewayAddress{gatewayAddress.c_str()} +{ } -Ipv4SimulationHelper::~Ipv4SimulationHelper () +Ipv4SimulationHelper::~Ipv4SimulationHelper() { - } Ipv4InterfaceContainer& -Ipv4SimulationHelper::GetIpv4Interfaces () +Ipv4SimulationHelper::GetIpv4Interfaces() { - return m_ifacesIps; + return m_ifacesIps; } InternetStackHelper& -Ipv4SimulationHelper::GetInternetHelper () +Ipv4SimulationHelper::GetInternetHelper() { - return m_internetHelper; + return m_internetHelper; } Ipv4AddressHelper& -Ipv4SimulationHelper::GetIpv4Helper () +Ipv4SimulationHelper::GetIpv4Helper() { - return m_ipv4Helper; + return m_ipv4Helper; } const std::string& -Ipv4SimulationHelper::GetMask () +Ipv4SimulationHelper::GetMask() { - return m_mask; + return m_mask; } const Ipv4Address& -Ipv4SimulationHelper::GetGatewayAddress () +Ipv4SimulationHelper::GetGatewayAddress() { - return m_gatewayAddress; + return m_gatewayAddress; } } // namespace ns3 diff --git a/src/configuration/helper/ipv4-simulation-helper.h b/src/configuration/helper/ipv4-simulation-helper.h index 446bb4b..90dc20d 100644 --- a/src/configuration/helper/ipv4-simulation-helper.h +++ b/src/configuration/helper/ipv4-simulation-helper.h @@ -18,53 +18,54 @@ #ifndef IPV4_SIMULATION_HELPER_H #define IPV4_SIMULATION_HELPER_H -#include -#include #include #include +#include +#include -namespace ns3 { +namespace ns3 +{ /** * A data class to store information about an IPv4 layer configuration for a simulation. */ class Ipv4SimulationHelper : public Object { -public: - /** - * Default constructor. It is needed the network mask used for the configured IPv4 network. - */ - Ipv4SimulationHelper (const std::string mask, const std::string gatewayAddress); - /** Default destructor */ - ~Ipv4SimulationHelper (); + public: + /** + * Default constructor. It is needed the network mask used for the configured IPv4 network. + */ + Ipv4SimulationHelper(const std::string mask, const std::string gatewayAddress); + /** Default destructor */ + ~Ipv4SimulationHelper(); - /** - * \return The container of IPv4 Interfaces associated to this layer. - */ - Ipv4InterfaceContainer& GetIpv4Interfaces (); - /** - * \return The Internet Stack Helper used to configure this layer. - */ - InternetStackHelper& GetInternetHelper (); - /** - * \return The Address Helper used to configure this layer. - */ - Ipv4AddressHelper& GetIpv4Helper (); - /** - * \return The network mask associated to this layer. - */ - const std::string& GetMask(); - /** - * \return The Gateway Address. - */ - const Ipv4Address& GetGatewayAddress (); + /** + * \return The container of IPv4 Interfaces associated to this layer. + */ + Ipv4InterfaceContainer& GetIpv4Interfaces(); + /** + * \return The Internet Stack Helper used to configure this layer. + */ + InternetStackHelper& GetInternetHelper(); + /** + * \return The Address Helper used to configure this layer. + */ + Ipv4AddressHelper& GetIpv4Helper(); + /** + * \return The network mask associated to this layer. + */ + const std::string& GetMask(); + /** + * \return The Gateway Address. + */ + const Ipv4Address& GetGatewayAddress(); -private: - Ipv4InterfaceContainer m_ifacesIps; - InternetStackHelper m_internetHelper; - Ipv4AddressHelper m_ipv4Helper; - const std::string m_mask; - const Ipv4Address m_gatewayAddress; + private: + Ipv4InterfaceContainer m_ifacesIps; + InternetStackHelper m_internetHelper; + Ipv4AddressHelper m_ipv4Helper; + const std::string m_mask; + const Ipv4Address m_gatewayAddress; }; } // namespace ns3 diff --git a/src/configuration/helper/lte-phy-simulation-helper.cc b/src/configuration/helper/lte-phy-simulation-helper.cc index ed3e83a..49e9a8f 100644 --- a/src/configuration/helper/lte-phy-simulation-helper.cc +++ b/src/configuration/helper/lte-phy-simulation-helper.cc @@ -18,30 +18,30 @@ #include "lte-phy-simulation-helper.h" #include -#include - #include +#include -namespace ns3 { +namespace ns3 +{ class LtePhySimulationHelperPriv { -public: - static std::string GetS1uLinkPcapPrefix (const size_t stackId) - { - std::stringstream prefixBuilder; - prefixBuilder << CONFIGURATOR->GetResultsPath () << "lte-" << stackId << "-s1u"; + public: + static std::string GetS1uLinkPcapPrefix(const size_t stackId) + { + std::stringstream prefixBuilder; + prefixBuilder << CONFIGURATOR->GetResultsPath() << "lte-" << stackId << "-s1u"; - return prefixBuilder.str (); - } + return prefixBuilder.str(); + } - static std::string GetX2LinkPcapPrefix (const size_t stackId) - { - std::stringstream prefixBuilder; - prefixBuilder << CONFIGURATOR->GetResultsPath () << "lte-" << stackId << "-x2"; + static std::string GetX2LinkPcapPrefix(const size_t stackId) + { + std::stringstream prefixBuilder; + prefixBuilder << CONFIGURATOR->GetResultsPath() << "lte-" << stackId << "-x2"; - return prefixBuilder.str (); - } + return prefixBuilder.str(); + } }; LtePhySimulationHelper::LtePhySimulationHelper(const size_t stackId) @@ -56,24 +56,23 @@ LtePhySimulationHelper::LtePhySimulationHelper(const size_t stackId) "X2LinkPcapPrefix", StringValue(LtePhySimulationHelperPriv::GetX2LinkPcapPrefix(stackId)))} { - m_lte->SetEpcHelper(m_epc); + m_lte->SetEpcHelper(m_epc); } -LtePhySimulationHelper::~LtePhySimulationHelper () +LtePhySimulationHelper::~LtePhySimulationHelper() { - } Ptr -LtePhySimulationHelper::GetLteHelper () +LtePhySimulationHelper::GetLteHelper() { - return m_lte; + return m_lte; } Ptr -LtePhySimulationHelper::GetEpcHelper () +LtePhySimulationHelper::GetEpcHelper() { - return m_epc; + return m_epc; } } // namespace ns3 diff --git a/src/configuration/helper/lte-phy-simulation-helper.h b/src/configuration/helper/lte-phy-simulation-helper.h index 8e967a0..e975efc 100644 --- a/src/configuration/helper/lte-phy-simulation-helper.h +++ b/src/configuration/helper/lte-phy-simulation-helper.h @@ -18,35 +18,36 @@ #ifndef LTE_PHY_SIMULATION_HELPER_H #define LTE_PHY_SIMULATION_HELPER_H -#include #include +#include #include -namespace ns3 { +namespace ns3 +{ /** * A data class to store information about a WiFi PHY layer configuration for a simulation. */ class LtePhySimulationHelper : public Object { -public: - /** Default constructor */ - LtePhySimulationHelper (const size_t stackId); - /** Default destructor */ - ~LtePhySimulationHelper (); + public: + /** Default constructor */ + LtePhySimulationHelper(const size_t stackId); + /** Default destructor */ + ~LtePhySimulationHelper(); - /** - * \return The LTE Helper used to configure this layer. - */ - Ptr GetLteHelper (); - /** - * \return The LTE EPC PHY Helper used to configure this layer. - */ - Ptr GetEpcHelper (); + /** + * \return The LTE Helper used to configure this layer. + */ + Ptr GetLteHelper(); + /** + * \return The LTE EPC PHY Helper used to configure this layer. + */ + Ptr GetEpcHelper(); -private: - Ptr m_lte; - Ptr m_epc; + private: + Ptr m_lte; + Ptr m_epc; }; } // namespace ns3 diff --git a/src/configuration/helper/lte-setup-helper.cc b/src/configuration/helper/lte-setup-helper.cc index 7b67853..9dec4b2 100644 --- a/src/configuration/helper/lte-setup-helper.cc +++ b/src/configuration/helper/lte-setup-helper.cc @@ -17,18 +17,19 @@ */ #include "lte-setup-helper.h" -namespace ns3 { +namespace ns3 +{ Ptr -LteSetupHelper::InstallSingleEnbDevice (Ptr helper, Ptr n) +LteSetupHelper::InstallSingleEnbDevice(Ptr helper, Ptr n) { - return helper->InstallSingleEnbDevice (n); + return helper->InstallSingleEnbDevice(n); } Ptr -LteSetupHelper::InstallSingleUeDevice (Ptr helper, Ptr n) +LteSetupHelper::InstallSingleUeDevice(Ptr helper, Ptr n) { - return helper->InstallSingleUeDevice (n); + return helper->InstallSingleUeDevice(n); } } // namespace ns3 diff --git a/src/configuration/helper/lte-setup-helper.h b/src/configuration/helper/lte-setup-helper.h index 775bb19..bb5051f 100644 --- a/src/configuration/helper/lte-setup-helper.h +++ b/src/configuration/helper/lte-setup-helper.h @@ -20,34 +20,36 @@ #include -namespace ns3 { +namespace ns3 +{ /** * Helper to enhance ns-3 LteHelper functionalities with additional * features, without modifying objects external to IoD_Sim. */ -class LteSetupHelper { -public: - /** - * Create an eNodeB device (LteEnbNetDevice) on the given node. - * \param helper A pre-inizialized instance of the Lte Helper. - * \param n the node where the device is to be installed - * \return pointer to the created device - */ - static Ptr InstallSingleEnbDevice (Ptr helper, Ptr n); +class LteSetupHelper +{ + public: + /** + * Create an eNodeB device (LteEnbNetDevice) on the given node. + * \param helper A pre-inizialized instance of the Lte Helper. + * \param n the node where the device is to be installed + * \return pointer to the created device + */ + static Ptr InstallSingleEnbDevice(Ptr helper, Ptr n); - /** - * Create a User Equipment device (LteUeNetDevice) on the given node. - * \param helper A pre-inizialized instance of the Lte Helper. - * \param n Target node to install the LTE device. - * \return pointer to the created device. - */ - static Ptr InstallSingleUeDevice (Ptr helper, Ptr n); + /** + * Create a User Equipment device (LteUeNetDevice) on the given node. + * \param helper A pre-inizialized instance of the Lte Helper. + * \param n Target node to install the LTE device. + * \return pointer to the created device. + */ + static Ptr InstallSingleUeDevice(Ptr helper, Ptr n); -private: - LteSetupHelper (); + private: + LteSetupHelper(); }; -} +} // namespace ns3 #endif /* LTE_SETUP_HELPER_H */ diff --git a/src/configuration/helper/mac-layer-configuration-helper.h b/src/configuration/helper/mac-layer-configuration-helper.h index da17dad..3aaf7fc 100644 --- a/src/configuration/helper/mac-layer-configuration-helper.h +++ b/src/configuration/helper/mac-layer-configuration-helper.h @@ -18,30 +18,33 @@ #ifndef MAC_LAYER_CONFIGURATION_HELPER_H #define MAC_LAYER_CONFIGURATION_HELPER_H -#include - #include #include -namespace ns3 { +#include + +namespace ns3 +{ /** * Helper to decode a MAC Layer from a JSON configuration file. */ class MacLayerConfigurationHelper { -public: - /** - * Parse a MAC Layer configuration from a given JSON tree and map it on a MacLayerConfiguration data class. - * - * \param jsonMacLayer The JSON tree to parse. - * \return The configuration as a pointer to MacLayerConfiguration to easily retrieve parsed data. - */ - static Ptr GetConfiguration (const rapidjson::Value& jsonMacLayer); + public: + /** + * Parse a MAC Layer configuration from a given JSON tree and map it on a MacLayerConfiguration + * data class. + * + * \param jsonMacLayer The JSON tree to parse. + * \return The configuration as a pointer to MacLayerConfiguration to easily retrieve parsed + * data. + */ + static Ptr GetConfiguration(const rapidjson::Value& jsonMacLayer); -private: - MacLayerConfigurationHelper(); - static const ModelConfiguration DecodeModelConfiguration (const rapidjson::Value& jsonModel); + private: + MacLayerConfigurationHelper(); + static const ModelConfiguration DecodeModelConfiguration(const rapidjson::Value& jsonModel); }; } // namespace ns3 diff --git a/src/configuration/helper/mobility-factory-helper.cc b/src/configuration/helper/mobility-factory-helper.cc index 0db7d27..85af29e 100644 --- a/src/configuration/helper/mobility-factory-helper.cc +++ b/src/configuration/helper/mobility-factory-helper.cc @@ -19,38 +19,39 @@ #include -namespace ns3 { +namespace ns3 +{ void -MobilityFactoryHelper::SetMobilityModel (MobilityHelper& helper, const ModelConfiguration& modelConf) +MobilityFactoryHelper::SetMobilityModel(MobilityHelper& helper, const ModelConfiguration& modelConf) { - helper.m_mobility.SetTypeId (modelConf.GetName ()); + helper.m_mobility.SetTypeId(modelConf.GetName()); - if (modelConf.GetName () == "ns3::ConstantPositionMobilityModel") + if (modelConf.GetName() == "ns3::ConstantPositionMobilityModel") { - if (modelConf.GetAttributes ().size() == 0) - return; - - auto positionAllocator = CreateObject (); - Vector3D initialPosition = StaticCast (modelConf.GetAttributes ()[0].value)->Get(); - positionAllocator->Add (initialPosition); - helper.SetPositionAllocator (positionAllocator); + if (modelConf.GetAttributes().size() == 0) + return; + + auto positionAllocator = CreateObject(); + Vector3D initialPosition = + StaticCast(modelConf.GetAttributes()[0].value)->Get(); + positionAllocator->Add(initialPosition); + helper.SetPositionAllocator(positionAllocator); } - else if (modelConf.GetName () == "ns3::RandomWalk2dOutdoorMobilityModel") + else if (modelConf.GetName() == "ns3::RandomWalk2dOutdoorMobilityModel") { - static auto positionAllocator = CreateObject (); - helper.SetPositionAllocator (positionAllocator); + static auto positionAllocator = CreateObject(); + helper.SetPositionAllocator(positionAllocator); } - else + else { - for (auto& attr : modelConf.GetAttributes ()) - helper.m_mobility.Set (attr.name, *attr.value); + for (auto& attr : modelConf.GetAttributes()) + helper.m_mobility.Set(attr.name, *attr.value); } } -MobilityFactoryHelper::MobilityFactoryHelper () +MobilityFactoryHelper::MobilityFactoryHelper() { - } } // namespace ns3 diff --git a/src/configuration/helper/mobility-factory-helper.h b/src/configuration/helper/mobility-factory-helper.h index 6d30c63..b5de8a1 100644 --- a/src/configuration/helper/mobility-factory-helper.h +++ b/src/configuration/helper/mobility-factory-helper.h @@ -21,26 +21,29 @@ #include #include -namespace ns3 { +namespace ns3 +{ /** * Helper to enhance ns-3 MobilityHelper functionalities with additional * features, without modifying objects external to IoD_Sim. */ -class MobilityFactoryHelper { -public: - /** - * Set the mobility model to be used from a ModelConfiguration data class. - * - * \param helper The MobilityHelper instance. - * \param modelConf The configuration data class that defines the mobility model to be used and its configuration. - */ - static void SetMobilityModel (MobilityHelper& helper, const ModelConfiguration& modelConf); +class MobilityFactoryHelper +{ + public: + /** + * Set the mobility model to be used from a ModelConfiguration data class. + * + * \param helper The MobilityHelper instance. + * \param modelConf The configuration data class that defines the mobility model to be used and + * its configuration. + */ + static void SetMobilityModel(MobilityHelper& helper, const ModelConfiguration& modelConf); -private: - MobilityFactoryHelper (); + private: + MobilityFactoryHelper(); }; -} +} // namespace ns3 #endif /* MOBILITY_FACTORY_HELPER_H */ diff --git a/src/configuration/helper/model-configuration-helper.cc b/src/configuration/helper/model-configuration-helper.cc index 53c926a..05b964d 100644 --- a/src/configuration/helper/model-configuration-helper.cc +++ b/src/configuration/helper/model-configuration-helper.cc @@ -19,369 +19,378 @@ #include #include -#include #include +#include #include +#include +#include #include +#include +#include +#include #include #include #include #include +#include #include #include #include -#include -#include -#include -#include -#include -#include - -namespace ns3 { +namespace ns3 +{ const ModelConfiguration -ModelConfigurationHelper::Get (const JsonValue& jModel) +ModelConfigurationHelper::Get(const JsonValue& jModel) { - NS_ASSERT_MSG (jModel.HasMember ("name"), - "Model configuration must have 'name' property."); - NS_ASSERT_MSG (jModel["name"].IsString (), - "Model configuration 'name' property must be a string."); - NS_ASSERT_MSG (jModel.HasMember ("attributes"), - "Model configuration must have 'attributes' property."); - NS_ASSERT_MSG (jModel["attributes"].IsArray (), - "Model configuration 'attributes' property must be an array."); - - const std::string modelName = jModel["name"].GetString (); - const TypeId modelTid = TypeId::LookupByName (modelName); - const auto jsonAttributes = jModel["attributes"].GetArray (); - const auto attributes = GetAttributes (modelTid, jsonAttributes); - - std::vector aggregates; - if (jModel.HasMember ("aggregates")) + NS_ASSERT_MSG(jModel.HasMember("name"), "Model configuration must have 'name' property."); + NS_ASSERT_MSG(jModel["name"].IsString(), + "Model configuration 'name' property must be a string."); + NS_ASSERT_MSG(jModel.HasMember("attributes"), + "Model configuration must have 'attributes' property."); + NS_ASSERT_MSG(jModel["attributes"].IsArray(), + "Model configuration 'attributes' property must be an array."); + + const std::string modelName = jModel["name"].GetString(); + const TypeId modelTid = TypeId::LookupByName(modelName); + const auto jsonAttributes = jModel["attributes"].GetArray(); + const auto attributes = GetAttributes(modelTid, jsonAttributes); + + std::vector aggregates; + if (jModel.HasMember("aggregates")) { - NS_ASSERT_MSG (jModel["aggregates"].IsArray (), - "Model configuration 'aggregates' property must be an array."); - aggregates = DecodeModelAggregates (jModel["aggregates"].GetArray ()); + NS_ASSERT_MSG(jModel["aggregates"].IsArray(), + "Model configuration 'aggregates' property must be an array."); + aggregates = DecodeModelAggregates(jModel["aggregates"].GetArray()); } - return ModelConfiguration (modelName, attributes, aggregates); + return ModelConfiguration(modelName, attributes, aggregates); } const std::optional -ModelConfigurationHelper::GetOptional (const JsonObject& jObj, const std::string& name) +ModelConfigurationHelper::GetOptional(const JsonObject& jObj, const std::string& name) { - const auto& key = name.c_str (); - if (jObj.HasMember (key)) - return Get (jObj[key]); - else - return std::nullopt; + const auto& key = name.c_str(); + if (jObj.HasMember(key)) + return Get(jObj[key]); + else + return std::nullopt; } const std::optional -ModelConfigurationHelper::GetOptionalCoaleshed (const JsonObject& jObj, - const std::string& name, - const ns3::TypeId& tid) +ModelConfigurationHelper::GetOptionalCoaleshed(const JsonObject& jObj, + const std::string& name, + const ns3::TypeId& tid) { - const auto& key = name.c_str (); - if (jObj.HasMember (key) && jObj[key].IsObject ()) - return DecodeCoaleshedModel (tid, jObj[key].GetObject ()); - else - return std::nullopt; + const auto& key = name.c_str(); + if (jObj.HasMember(key) && jObj[key].IsObject()) + return DecodeCoaleshedModel(tid, jObj[key].GetObject()); + else + return std::nullopt; } -ModelConfigurationHelper::ModelConfigurationHelper () +ModelConfigurationHelper::ModelConfigurationHelper() { - } const std::vector -ModelConfigurationHelper::GetAttributes (const TypeId& model, const rapidjson::Value::ConstArray& jAttrs) +ModelConfigurationHelper::GetAttributes(const TypeId& model, + const rapidjson::Value::ConstArray& jAttrs) { - std::vector attributes; - attributes.reserve (jAttrs.Size ()); - for (auto& el : jAttrs) - attributes.push_back (DecodeModelAttribute (model, el)); + std::vector attributes; + attributes.reserve(jAttrs.Size()); + for (auto& el : jAttrs) + attributes.push_back(DecodeModelAttribute(model, el)); - return attributes; + return attributes; } const ModelConfiguration -ModelConfigurationHelper::DecodeCoaleshedModel (const TypeId& model, - const JsonObject& jModel) +ModelConfigurationHelper::DecodeCoaleshedModel(const TypeId& model, const JsonObject& jModel) { - std::vector attributes; - std::vector aggregates; - TypeId::AttributeInformation attrInfo; + std::vector attributes; + std::vector aggregates; + TypeId::AttributeInformation attrInfo; - attributes.reserve (jModel.MemberCount ()); + attributes.reserve(jModel.MemberCount()); - for (auto it = jModel.MemberBegin (); it != jModel.MemberEnd (); it++) + for (auto it = jModel.MemberBegin(); it != jModel.MemberEnd(); it++) { - const std::string attrName = it->name.GetString (); + const std::string attrName = it->name.GetString(); - if (model.LookupAttributeByName (attrName, &attrInfo)) + if (model.LookupAttributeByName(attrName, &attrInfo)) { - const auto& value = DecodeAttributeValue(model.GetName (), - it->value, - attrInfo); - const auto attr = ModelConfiguration::Attribute (attrName, value); - attributes.push_back (attr); + const auto& value = DecodeAttributeValue(model.GetName(), it->value, attrInfo); + const auto attr = ModelConfiguration::Attribute(attrName, value); + attributes.push_back(attr); } - else if (attrName == "aggregates") + else if (attrName == "aggregates") { - NS_ASSERT_MSG (it->value.IsArray (), - "'aggregates' must be an array of objects."); - aggregates = DecodeModelAggregates (it->value.GetArray ()); + NS_ASSERT_MSG(it->value.IsArray(), "'aggregates' must be an array of objects."); + aggregates = DecodeModelAggregates(it->value.GetArray()); } - else + else { - NS_FATAL_ERROR ("Attribute '" << attrName - << "' is not defined in model " << model.GetName ()); + NS_FATAL_ERROR("Attribute '" << attrName << "' is not defined in model " + << model.GetName()); } } - return ModelConfiguration (model.GetName (), attributes, aggregates); + return ModelConfiguration(model.GetName(), attributes, aggregates); } const Ptr -ModelConfigurationHelper::DecodeAttributeValue (const std::string& modelName, const JsonValue& jAttr, const TypeId::AttributeInformation& attrInfo) +ModelConfigurationHelper::DecodeAttributeValue(const std::string& modelName, + const JsonValue& jAttr, + const TypeId::AttributeInformation& attrInfo) { - const auto attrValueType = jAttr.GetType (); - Ptr attrValue; + const auto attrValueType = jAttr.GetType(); + Ptr attrValue; - switch (attrValueType) + switch (attrValueType) { - case rapidjson::Type::kStringType: - { - const auto attrValueString = jAttr.GetString (); - attrValue = attrInfo.checker->CreateValidValue (StringValue (attrValueString)); - } - break; - case rapidjson::Type::kNumberType: - { - if (jAttr.IsInt64 ()) - { - const auto attrValueInt = jAttr.GetInt64 (); - const auto acceptedType = attrInfo.checker->GetValueTypeName (); + case rapidjson::Type::kStringType: { + const auto attrValueString = jAttr.GetString(); + attrValue = attrInfo.checker->CreateValidValue(StringValue(attrValueString)); + } + break; + case rapidjson::Type::kNumberType: { + if (jAttr.IsInt64()) + { + const auto attrValueInt = jAttr.GetInt64(); + const auto acceptedType = attrInfo.checker->GetValueTypeName(); if (acceptedType == "ns3::IntegerValue") - attrValue = attrInfo.checker->CreateValidValue (IntegerValue (attrValueInt)); + attrValue = attrInfo.checker->CreateValidValue(IntegerValue(attrValueInt)); else if (acceptedType == "ns3::UintegerValue") - attrValue = attrInfo.checker->CreateValidValue (UintegerValue (attrValueInt)); + attrValue = attrInfo.checker->CreateValidValue(UintegerValue(attrValueInt)); else - NS_FATAL_ERROR ("The attribute value for property " << attrInfo.name << " defined in model " << modelName - << " has incompatible type: " << acceptedType << " is needed."); - } - else if (jAttr.IsUint64 ()) - { - const auto attrValueInt = jAttr.GetUint64 (); - const auto acceptedType = attrInfo.checker->GetValueTypeName (); + NS_FATAL_ERROR("The attribute value for property " + << attrInfo.name << " defined in model " << modelName + << " has incompatible type: " << acceptedType << " is needed."); + } + else if (jAttr.IsUint64()) + { + const auto attrValueInt = jAttr.GetUint64(); + const auto acceptedType = attrInfo.checker->GetValueTypeName(); if (acceptedType == "ns3::IntegerValue") - attrValue = attrInfo.checker->CreateValidValue (IntegerValue (attrValueInt)); + attrValue = attrInfo.checker->CreateValidValue(IntegerValue(attrValueInt)); else if (acceptedType == "ns3::UintegerValue") - attrValue = attrInfo.checker->CreateValidValue (UintegerValue (attrValueInt)); + attrValue = attrInfo.checker->CreateValidValue(UintegerValue(attrValueInt)); else - NS_FATAL_ERROR ("The attribute value for property " << attrInfo.name << " defined in model " << modelName - << " has incompatible type: " << acceptedType << " is needed."); - } - else if (jAttr.IsDouble ()) - { - const double attrValueDouble = jAttr.GetDouble (); - - if (attrInfo.checker->Check (DoubleValue (attrValueDouble))) - attrValue = attrInfo.checker->CreateValidValue (DoubleValue (attrValueDouble)); - else if (attrInfo.checker->Check (TimeValue (Seconds (attrValueDouble)))) - attrValue = attrInfo.checker->CreateValidValue (TimeValue (Seconds (attrValueDouble))); + NS_FATAL_ERROR("The attribute value for property " + << attrInfo.name << " defined in model " << modelName + << " has incompatible type: " << acceptedType << " is needed."); + } + else if (jAttr.IsDouble()) + { + const double attrValueDouble = jAttr.GetDouble(); + + if (attrInfo.checker->Check(DoubleValue(attrValueDouble))) + attrValue = attrInfo.checker->CreateValidValue(DoubleValue(attrValueDouble)); + else if (attrInfo.checker->Check(TimeValue(Seconds(attrValueDouble)))) + attrValue = attrInfo.checker->CreateValidValue(TimeValue(Seconds(attrValueDouble))); else - NS_FATAL_ERROR ("Cannot read attribute " << attrInfo.name << " for model " << modelName); - } + NS_FATAL_ERROR("Cannot read attribute " << attrInfo.name << " for model " + << modelName); + } else - { - NS_FATAL_ERROR ("Cannot read attribute " << attrInfo.name << " for model " << modelName << ". " - << "A number was detected, but it is not a valid Integer neither a Double."); - } - } - break; - case rapidjson::Type::kArrayType: - { - const auto arr = jAttr.GetArray (); + { + NS_FATAL_ERROR( + "Cannot read attribute " + << attrInfo.name << " for model " << modelName << ". " + << "A number was detected, but it is not a valid Integer neither a Double."); + } + } + break; + case rapidjson::Type::kArrayType: { + const auto arr = jAttr.GetArray(); if (arr[0].IsString()) // StrVecValue - { + { std::vector values; - values.reserve (arr.Size ()); + values.reserve(arr.Size()); for (auto& el : arr) - values.push_back (el.GetString ()); + values.push_back(el.GetString()); attrValue = attrInfo.checker->CreateValidValue(StrVecValue(values)); - } - else if (arr.Size () == 3 && arr[0].IsDouble () && attrInfo.name == "Position") - { - const Vector3D vec {arr[0].GetDouble (), arr[1].GetDouble (), arr[2].GetDouble ()}; - attrValue = attrInfo.checker->CreateValidValue (Vector3DValue (vec)); - } - else if ((attrInfo.name == "SpeedCoefficients" || attrInfo.name == "PowerConsumption") && arr[0].IsNumber ()) - { + } + else if (arr.Size() == 3 && arr[0].IsDouble() && attrInfo.name == "Position") + { + const Vector3D vec{arr[0].GetDouble(), arr[1].GetDouble(), arr[2].GetDouble()}; + attrValue = attrInfo.checker->CreateValidValue(Vector3DValue(vec)); + } + else if ((attrInfo.name == "SpeedCoefficients" || attrInfo.name == "PowerConsumption") && + arr[0].IsNumber()) + { std::vector coeffs; - for (auto& c : arr) { - coeffs.push_back (c.GetDouble ()); + for (auto& c : arr) + { + coeffs.push_back(c.GetDouble()); } - attrValue = attrInfo.checker->CreateValidValue (DoubleVectorValue (coeffs)); - } - else if (attrInfo.name == "FlightPlan" && arr[0].IsObject ()) - { - FlightPlan fp {}; + attrValue = attrInfo.checker->CreateValidValue(DoubleVectorValue(coeffs)); + } + else if (attrInfo.name == "FlightPlan" && arr[0].IsObject()) + { + FlightPlan fp{}; for (auto& p : arr) - { - NS_ASSERT_MSG (p.IsObject () && - p.HasMember ("position") && - p["position"].IsArray () && - p["position"][0].IsDouble () && - p.HasMember ("interest") && - p["interest"].IsUint (), - "FlightPlan contains invalid points."); - - const Vector3D position { p["position"][0].GetDouble (), - p["position"][1].GetDouble (), - p["position"][2].GetDouble () }; - const double restTime = (p.HasMember ("restTime") && p["restTime"].IsDouble ()) - ? p["restTime"].GetDouble () - : 0; - fp.Add (CreateObjectWithAttributes ("Position", VectorValue (position), - "Interest", IntegerValue (p["interest"].GetUint ()), - "RestTime", TimeValue (Seconds (restTime)))); - } - - attrValue = attrInfo.checker->CreateValidValue (FlightPlanValue (fp)); - } - else if (attrInfo.name == "RoITrigger" && arr[0].IsInt ()) - { + { + NS_ASSERT_MSG(p.IsObject() && p.HasMember("position") && p["position"].IsArray() && + p["position"][0].IsDouble() && p.HasMember("interest") && + p["interest"].IsUint(), + "FlightPlan contains invalid points."); + + const Vector3D position{p["position"][0].GetDouble(), + p["position"][1].GetDouble(), + p["position"][2].GetDouble()}; + const double restTime = (p.HasMember("restTime") && p["restTime"].IsDouble()) + ? p["restTime"].GetDouble() + : 0; + fp.Add(CreateObjectWithAttributes("Position", + VectorValue(position), + "Interest", + IntegerValue(p["interest"].GetUint()), + "RestTime", + TimeValue(Seconds(restTime)))); + } + + attrValue = attrInfo.checker->CreateValidValue(FlightPlanValue(fp)); + } + else if (attrInfo.name == "RoITrigger" && arr[0].IsInt()) + { std::vector coeffs; - for (auto& c : arr) { - coeffs.push_back (c.GetDouble ()); + for (auto& c : arr) + { + coeffs.push_back(c.GetDouble()); } - attrValue = attrInfo.checker->CreateValidValue (IntVectorValue (coeffs)); - } - else if (attrInfo.name == "Bounds" && arr[0].IsDouble() && arr.Size () == 4) - { - auto rect = Rectangle (arr[0].GetDouble (), arr[1].GetDouble (), - arr[2].GetDouble (), arr[3].GetDouble ()); - attrValue = attrInfo.checker->CreateValidValue (RectangleValue (rect)); - } - else if (attrInfo.name == "Patches" && arr[0].IsObject ()) - { + attrValue = attrInfo.checker->CreateValidValue(IntVectorValue(coeffs)); + } + else if (attrInfo.name == "Bounds" && arr[0].IsDouble() && arr.Size() == 4) + { + auto rect = Rectangle(arr[0].GetDouble(), + arr[1].GetDouble(), + arr[2].GetDouble(), + arr[3].GetDouble()); + attrValue = attrInfo.checker->CreateValidValue(RectangleValue(rect)); + } + else if (attrInfo.name == "Patches" && arr[0].IsObject()) + { std::vector patches; - patches.reserve (arr.Size ()); + patches.reserve(arr.Size()); for (auto& p : arr) - { - const auto patchConfiguration = DecodeCoaleshedModel (IrsPatch::GetTypeId (), p.GetObject ()); - patches.push_back (patchConfiguration); - } - - attrValue = attrInfo.checker->CreateValidValue (ModelConfigurationVectorValue (patches)); - } - else if (attrInfo.name == "Configurations" && arr[0].IsArray () && arr[0].GetArray ()[0].IsObject ()) - { + { + const auto patchConfiguration = + DecodeCoaleshedModel(IrsPatch::GetTypeId(), p.GetObject()); + patches.push_back(patchConfiguration); + } + + attrValue = attrInfo.checker->CreateValidValue(ModelConfigurationVectorValue(patches)); + } + else if (attrInfo.name == "Configurations" && arr[0].IsArray() && + arr[0].GetArray()[0].IsObject()) + { std::vector configurations; - configurations.reserve (arr.Size ()); + configurations.reserve(arr.Size()); for (auto& c : arr) - { - const auto patches = c.GetArray (); + { + const auto patches = c.GetArray(); ModelConfigurationVector patchesConfiguration; for (auto& p : patches) - { - const auto patchConfiguration = DecodeCoaleshedModel (IrsPatch::GetTypeId (), p.GetObject ()); - patchesConfiguration.Add (patchConfiguration); - } + { + const auto patchConfiguration = + DecodeCoaleshedModel(IrsPatch::GetTypeId(), p.GetObject()); + patchesConfiguration.Add(patchConfiguration); + } configurations.push_back(patchesConfiguration); - } + } - attrValue = attrInfo.checker->CreateValidValue (ModelConfigurationMatrixValue (configurations)); - } - else if (arr[0].IsInt ()) - { + attrValue = + attrInfo.checker->CreateValidValue(ModelConfigurationMatrixValue(configurations)); + } + else if (arr[0].IsInt()) + { std::vector els; for (auto& c : arr) - els.push_back (c.GetInt ()); - attrValue = attrInfo.checker->CreateValidValue (IntVectorValue (els)); - } - else if (arr[0].IsDouble ()) - { + els.push_back(c.GetInt()); + attrValue = attrInfo.checker->CreateValidValue(IntVectorValue(els)); + } + else if (arr[0].IsDouble()) + { std::vector els; for (auto& c : arr) - els.push_back (c.GetDouble ()); - attrValue = attrInfo.checker->CreateValidValue (DoubleVectorValue (els)); - } + els.push_back(c.GetDouble()); + attrValue = attrInfo.checker->CreateValidValue(DoubleVectorValue(els)); + } else - { - NS_FATAL_ERROR ("Unsupported attribute value type of array " << attrInfo.name << ": " << attrInfo.checker->GetValueTypeName ()); - } - } - break; + { + NS_FATAL_ERROR("Unsupported attribute value type of array " + << attrInfo.name << ": " << attrInfo.checker->GetValueTypeName()); + } + } + break; case rapidjson::Type::kFalseType: - case rapidjson::Type::kTrueType: - { - const auto attrValueBool = jAttr.GetBool (); - attrValue = attrInfo.checker->CreateValidValue (BooleanValue (attrValueBool)); - } - break; + case rapidjson::Type::kTrueType: { + const auto attrValueBool = jAttr.GetBool(); + attrValue = attrInfo.checker->CreateValidValue(BooleanValue(attrValueBool)); + } + break; case rapidjson::Type::kNullType: case rapidjson::Type::kObjectType: default: - NS_FATAL_ERROR ("Cannot determine attribute value type of " << attrInfo.name << ": " << attrInfo.checker->GetValueTypeName ()); - break; + NS_FATAL_ERROR("Cannot determine attribute value type of " + << attrInfo.name << ": " << attrInfo.checker->GetValueTypeName()); + break; } - NS_ABORT_MSG_IF (attrValue == nullptr, "The attribute value for property " << attrInfo.name - << " defined in model " << modelName << " was not accepted. " - << "Insert a valid value according to " - << attrInfo.checker->GetUnderlyingTypeInformation ()); - return attrValue; + NS_ABORT_MSG_IF(attrValue == nullptr, + "The attribute value for property " + << attrInfo.name << " defined in model " << modelName + << " was not accepted. " + << "Insert a valid value according to " + << attrInfo.checker->GetUnderlyingTypeInformation()); + return attrValue; } const std::vector -ModelConfigurationHelper::DecodeModelAggregates (const JsonArray& jAggs) +ModelConfigurationHelper::DecodeModelAggregates(const JsonArray& jAggs) { - std::vector aggregates; - aggregates.reserve (jAggs.Size ()); + std::vector aggregates; + aggregates.reserve(jAggs.Size()); - for (auto& jAgg : jAggs) + for (auto& jAgg : jAggs) { - NS_ASSERT_MSG (jAgg.IsObject (), "Invalid aggregate definition."); - aggregates.push_back (Get (jAgg)); + NS_ASSERT_MSG(jAgg.IsObject(), "Invalid aggregate definition."); + aggregates.push_back(Get(jAgg)); } - return aggregates; + return aggregates; } const ModelConfiguration::Attribute -ModelConfigurationHelper::DecodeModelAttribute (const TypeId& model, const rapidjson::Value& el) +ModelConfigurationHelper::DecodeModelAttribute(const TypeId& model, const rapidjson::Value& el) { - NS_ASSERT_MSG (el.IsObject (), - "Attribute model definition must be an object, got " << el.GetType ()); - NS_ASSERT_MSG (el.HasMember ("name"), - "Attribute model must have 'name' property."); - NS_ASSERT_MSG (el["name"].IsString (), - "Attribute model name must be a string."); - NS_ASSERT_MSG (el.HasMember ("value"), - "Attribute model must have 'value' property."); - - const std::string attrName = el["name"].GetString(); - TypeId::AttributeInformation attrInfo = {}; - - NS_ASSERT_MSG (model.LookupAttributeByName (attrName, &attrInfo), - "Attribute '" << attrName << "' for model '" << model.GetName () << "' does not exist!"); - - auto attrValue = DecodeAttributeValue (model.GetName (), el["value"], attrInfo); - return ModelConfiguration::Attribute (attrName, attrValue); + NS_ASSERT_MSG(el.IsObject(), + "Attribute model definition must be an object, got " << el.GetType()); + NS_ASSERT_MSG(el.HasMember("name"), "Attribute model must have 'name' property."); + NS_ASSERT_MSG(el["name"].IsString(), "Attribute model name must be a string."); + NS_ASSERT_MSG(el.HasMember("value"), "Attribute model must have 'value' property."); + + const std::string attrName = el["name"].GetString(); + TypeId::AttributeInformation attrInfo = {}; + + NS_ASSERT_MSG(model.LookupAttributeByName(attrName, &attrInfo), + "Attribute '" << attrName << "' for model '" << model.GetName() + << "' does not exist!"); + + auto attrValue = DecodeAttributeValue(model.GetName(), el["value"], attrInfo); + return ModelConfiguration::Attribute(attrName, attrValue); } } // namespace ns3 diff --git a/src/configuration/helper/model-configuration-helper.h b/src/configuration/helper/model-configuration-helper.h index d79862d..2d1000b 100644 --- a/src/configuration/helper/model-configuration-helper.h +++ b/src/configuration/helper/model-configuration-helper.h @@ -18,15 +18,14 @@ #ifndef MODEL_CONFIGURATION_HELPER_H #define MODEL_CONFIGURATION_HELPER_H -#include - +#include #include +#include #include -#include - -namespace ns3 { +namespace ns3 +{ using JsonArray = rapidjson::Value::ConstArray; using JsonObject = rapidjson::Value::ConstObject; @@ -39,46 +38,42 @@ using JsonValue = rapidjson::Value; */ class ModelConfigurationHelper { -public: - /** - * Parse a model configuration from a given JSON tree and map it on an ModelConfiguration data class. - * - * \param json The JSON tree to parse. - * \return The configuration as a pointer to ModelConfiguration to easily retrieve parsed data. - */ - static const ModelConfiguration Get (const JsonValue &json); - - static const std::optional - GetOptional (const JsonObject &jsonObject, - const std::string &key); - - static const std::optional - GetOptionalCoaleshed (const JsonObject &jsonObject, - const std::string &key, - const ns3::TypeId &tid); - - static const std::vector - GetAttributes (const TypeId &model, - const JsonArray &jAttrs); - -private: - ModelConfigurationHelper (); - - static const ModelConfiguration::Attribute - DecodeModelAttribute (const TypeId &model, - const JsonValue &jAttr); - - static const std::vector - DecodeModelAggregates (const JsonArray &jAggs); - - static const ModelConfiguration - DecodeCoaleshedModel (const ns3::TypeId &model, - const JsonObject &jAttrs); - - static const Ptr - DecodeAttributeValue (const std::string &modelName, - const JsonValue &jAttr, - const TypeId::AttributeInformation &checker); + public: + /** + * Parse a model configuration from a given JSON tree and map it on an ModelConfiguration data + * class. + * + * \param json The JSON tree to parse. + * \return The configuration as a pointer to ModelConfiguration to easily retrieve parsed data. + */ + static const ModelConfiguration Get(const JsonValue& json); + + static const std::optional GetOptional(const JsonObject& jsonObject, + const std::string& key); + + static const std::optional GetOptionalCoaleshed( + const JsonObject& jsonObject, + const std::string& key, + const ns3::TypeId& tid); + + static const std::vector GetAttributes(const TypeId& model, + const JsonArray& jAttrs); + + private: + ModelConfigurationHelper(); + + static const ModelConfiguration::Attribute DecodeModelAttribute(const TypeId& model, + const JsonValue& jAttr); + + static const std::vector DecodeModelAggregates(const JsonArray& jAggs); + + static const ModelConfiguration DecodeCoaleshedModel(const ns3::TypeId& model, + const JsonObject& jAttrs); + + static const Ptr DecodeAttributeValue( + const std::string& modelName, + const JsonValue& jAttr, + const TypeId::AttributeInformation& checker); }; } // namespace ns3 diff --git a/src/configuration/helper/network-layer-configuration-helper.h b/src/configuration/helper/network-layer-configuration-helper.h index 4adc821..344e234 100644 --- a/src/configuration/helper/network-layer-configuration-helper.h +++ b/src/configuration/helper/network-layer-configuration-helper.h @@ -18,28 +18,31 @@ #ifndef NETWORK_LAYER_CONFIGURATION_HELPER_H #define NETWORK_LAYER_CONFIGURATION_HELPER_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ /** * Helper to decode a Network Layer from a JSON configuration file. */ class NetworkLayerConfigurationHelper { -public: - /** - * Parse a Network configuration from a given JSON tree and map it on a NetworkLayerConfiguration data class. - * - * \param json The JSON tree to parse. - * \return The configuration as a pointer to NetworkLayerConfiguration to easily retrieve parsed data. - */ - static Ptr GetConfiguration (const rapidjson::Value& json); + public: + /** + * Parse a Network configuration from a given JSON tree and map it on a + * NetworkLayerConfiguration data class. + * + * \param json The JSON tree to parse. + * \return The configuration as a pointer to NetworkLayerConfiguration to easily retrieve parsed + * data. + */ + static Ptr GetConfiguration(const rapidjson::Value& json); -private: - NetworkLayerConfigurationHelper(); + private: + NetworkLayerConfigurationHelper(); }; } // namespace ns3 diff --git a/src/configuration/helper/phy-layer-configuration-helper.cc b/src/configuration/helper/phy-layer-configuration-helper.cc index e812d4d..335892e 100644 --- a/src/configuration/helper/phy-layer-configuration-helper.cc +++ b/src/configuration/helper/phy-layer-configuration-helper.cc @@ -17,100 +17,109 @@ */ #include "phy-layer-configuration-helper.h" +#include "model-configuration-helper.h" + #include #include #include +#include #include #include - -#include #include -#include "model-configuration-helper.h" - -namespace ns3 { +namespace ns3 +{ Ptr -PhyLayerConfigurationHelper::GetConfiguration (const rapidjson::Value& jsonPhyLayer) +PhyLayerConfigurationHelper::GetConfiguration(const rapidjson::Value& jsonPhyLayer) { - NS_ASSERT_MSG (jsonPhyLayer.IsObject (), - "PHY Layer definition must be an object, got " << jsonPhyLayer.GetType ()); - NS_ASSERT_MSG (jsonPhyLayer.HasMember ("type"), - "PHY Layer definition must have 'type' property."); - NS_ASSERT_MSG (jsonPhyLayer["type"].IsString (), - "PHY Layer 'type' property must be a string."); + NS_ASSERT_MSG(jsonPhyLayer.IsObject(), + "PHY Layer definition must be an object, got " << jsonPhyLayer.GetType()); + NS_ASSERT_MSG(jsonPhyLayer.HasMember("type"), + "PHY Layer definition must have 'type' property."); + NS_ASSERT_MSG(jsonPhyLayer["type"].IsString(), "PHY Layer 'type' property must be a string."); - const std::string phyType = jsonPhyLayer["type"].GetString (); - Ptr phyConfig{nullptr}; + const std::string phyType = jsonPhyLayer["type"].GetString(); + Ptr phyConfig{nullptr}; - if (phyType == "wifi") + if (phyType == "wifi") { - NS_ASSERT_MSG (jsonPhyLayer.HasMember ("standard"), - "Wi-Fi PHY Layer definition must have 'standard' property."); - NS_ASSERT_MSG (jsonPhyLayer["standard"].IsString (), - "Wi-Fi PHY Layer 'standard' property must be a string."); - NS_ASSERT_MSG (jsonPhyLayer.HasMember ("attributes"), - "Wi-Fi PHY Layer definition must have 'attributes' property."); - NS_ASSERT_MSG (jsonPhyLayer["attributes"].IsArray (), - "Wi-Fi PHY Layer 'attributes' must be an object."); - NS_ASSERT_MSG (jsonPhyLayer.HasMember ("channel"), - "Wi-Fi PHY Layer definition must have 'channel' property."); - NS_ASSERT_MSG (jsonPhyLayer["channel"].IsObject (), - "Wi-Fi PHY Layer 'mode' property must be an object."); - NS_ASSERT_MSG (jsonPhyLayer["channel"].HasMember ("propagationDelayModel"), - "Wi-Fi PHY Layer channel definition must have 'propagationDelayModel' property."); - NS_ASSERT_MSG (jsonPhyLayer["channel"]["propagationDelayModel"].IsObject (), - "Wi-Fi PHY Layer channel 'propagationDelayModel' must be an object"); - NS_ASSERT_MSG (jsonPhyLayer["channel"].HasMember ("propagationLossModel"), - "Wi-Fi PHY Layer channel definition must have 'propagationLossModel' property."); - NS_ASSERT_MSG (jsonPhyLayer["channel"]["propagationLossModel"].IsObject (), - "Wi-Fi PHY Layer channel 'propagationLossModel' must be an object"); + NS_ASSERT_MSG(jsonPhyLayer.HasMember("standard"), + "Wi-Fi PHY Layer definition must have 'standard' property."); + NS_ASSERT_MSG(jsonPhyLayer["standard"].IsString(), + "Wi-Fi PHY Layer 'standard' property must be a string."); + NS_ASSERT_MSG(jsonPhyLayer.HasMember("attributes"), + "Wi-Fi PHY Layer definition must have 'attributes' property."); + NS_ASSERT_MSG(jsonPhyLayer["attributes"].IsArray(), + "Wi-Fi PHY Layer 'attributes' must be an object."); + NS_ASSERT_MSG(jsonPhyLayer.HasMember("channel"), + "Wi-Fi PHY Layer definition must have 'channel' property."); + NS_ASSERT_MSG(jsonPhyLayer["channel"].IsObject(), + "Wi-Fi PHY Layer 'mode' property must be an object."); + NS_ASSERT_MSG( + jsonPhyLayer["channel"].HasMember("propagationDelayModel"), + "Wi-Fi PHY Layer channel definition must have 'propagationDelayModel' property."); + NS_ASSERT_MSG(jsonPhyLayer["channel"]["propagationDelayModel"].IsObject(), + "Wi-Fi PHY Layer channel 'propagationDelayModel' must be an object"); + NS_ASSERT_MSG( + jsonPhyLayer["channel"].HasMember("propagationLossModel"), + "Wi-Fi PHY Layer channel definition must have 'propagationLossModel' property."); + NS_ASSERT_MSG(jsonPhyLayer["channel"]["propagationLossModel"].IsObject(), + "Wi-Fi PHY Layer channel 'propagationLossModel' must be an object"); - const auto phyAttributes = ModelConfigurationHelper::GetAttributes (TypeId::LookupByName ("ns3::WifiPhy"), jsonPhyLayer["attributes"].GetArray ()); - const auto propagationDelayModel = ModelConfigurationHelper::Get (jsonPhyLayer["channel"]["propagationDelayModel"]); - const auto propagationLossModel = ModelConfigurationHelper::Get (jsonPhyLayer["channel"]["propagationLossModel"]); + const auto phyAttributes = + ModelConfigurationHelper::GetAttributes(TypeId::LookupByName("ns3::WifiPhy"), + jsonPhyLayer["attributes"].GetArray()); + const auto propagationDelayModel = + ModelConfigurationHelper::Get(jsonPhyLayer["channel"]["propagationDelayModel"]); + const auto propagationLossModel = + ModelConfigurationHelper::Get(jsonPhyLayer["channel"]["propagationLossModel"]); - return Create (phyType, - jsonPhyLayer["standard"].GetString (), - phyAttributes, - propagationDelayModel, - propagationLossModel); + return Create(phyType, + jsonPhyLayer["standard"].GetString(), + phyAttributes, + propagationDelayModel, + propagationLossModel); } - else if (phyType == "lte") + else if (phyType == "lte") { - NS_ASSERT_MSG (jsonPhyLayer.HasMember ("attributes"), - "LTE PHY Layer definition must have 'attributes' property."); - NS_ASSERT_MSG (jsonPhyLayer["attributes"].IsArray (), - "LTE PHY Layer 'attributes' must be an object."); - NS_ASSERT_MSG (jsonPhyLayer.HasMember ("channel"), - "LTE PHY Layer definition must have 'channel' property."); - NS_ASSERT_MSG (jsonPhyLayer["channel"].IsObject (), - "LTE PHY Layer 'mode' property must be an object."); - NS_ASSERT_MSG (jsonPhyLayer["channel"].HasMember ("spectrumModel"), - "LTE PHY Layer channel definition must have 'spectrumModel' property."); - NS_ASSERT_MSG (jsonPhyLayer["channel"]["spectrumModel"].IsObject (), - "LTE PHY Layer channel 'spectrumModel' must be an object"); + NS_ASSERT_MSG(jsonPhyLayer.HasMember("attributes"), + "LTE PHY Layer definition must have 'attributes' property."); + NS_ASSERT_MSG(jsonPhyLayer["attributes"].IsArray(), + "LTE PHY Layer 'attributes' must be an object."); + NS_ASSERT_MSG(jsonPhyLayer.HasMember("channel"), + "LTE PHY Layer definition must have 'channel' property."); + NS_ASSERT_MSG(jsonPhyLayer["channel"].IsObject(), + "LTE PHY Layer 'mode' property must be an object."); + NS_ASSERT_MSG(jsonPhyLayer["channel"].HasMember("spectrumModel"), + "LTE PHY Layer channel definition must have 'spectrumModel' property."); + NS_ASSERT_MSG(jsonPhyLayer["channel"]["spectrumModel"].IsObject(), + "LTE PHY Layer channel 'spectrumModel' must be an object"); - const auto phyAttributes = ModelConfigurationHelper::GetAttributes (TypeId::LookupByName ("ns3::LteHelper"), jsonPhyLayer["attributes"].GetArray ()); - const auto spectrumModel = ModelConfigurationHelper::Get (jsonPhyLayer["channel"]["spectrumModel"]); - const auto propagationLossModel = ModelConfigurationHelper::GetOptional (jsonPhyLayer["channel"].GetObject (), "propagationLossModel"); + const auto phyAttributes = + ModelConfigurationHelper::GetAttributes(TypeId::LookupByName("ns3::LteHelper"), + jsonPhyLayer["attributes"].GetArray()); + const auto spectrumModel = + ModelConfigurationHelper::Get(jsonPhyLayer["channel"]["spectrumModel"]); + const auto propagationLossModel = + ModelConfigurationHelper::GetOptional(jsonPhyLayer["channel"].GetObject(), + "propagationLossModel"); - phyConfig = Create (phyType, - phyAttributes, - propagationLossModel, - spectrumModel); + phyConfig = Create(phyType, + phyAttributes, + propagationLossModel, + spectrumModel); } - else + else { - NS_FATAL_ERROR ("PHY Layer of Type " << phyType << " is not supported!"); + NS_FATAL_ERROR("PHY Layer of Type " << phyType << " is not supported!"); } - return phyConfig; + return phyConfig; } -PhyLayerConfigurationHelper::PhyLayerConfigurationHelper () +PhyLayerConfigurationHelper::PhyLayerConfigurationHelper() { - } } // namespace ns3 diff --git a/src/configuration/helper/phy-layer-configuration-helper.h b/src/configuration/helper/phy-layer-configuration-helper.h index db1f02e..fb94516 100644 --- a/src/configuration/helper/phy-layer-configuration-helper.h +++ b/src/configuration/helper/phy-layer-configuration-helper.h @@ -18,29 +18,32 @@ #ifndef PHY_LAYER_CONFIGURATION_HELPER_H #define PHY_LAYER_CONFIGURATION_HELPER_H -#include - #include #include -namespace ns3 { +#include + +namespace ns3 +{ /** * Helper to decode a PHY Layer from a JSON configuration file. */ class PhyLayerConfigurationHelper { -public: - /** - * Parse a PHY configuration from a given JSON tree and map it on a PhyLayerConfiguration data class. - * - * \param jsonPhyLayer The JSON tree to parse. - * \return The configuration as a pointer to PhyLayerConfiguration to easily retrieve parsed data. - */ - static Ptr GetConfiguration (const rapidjson::Value& jsonPhyLayer); + public: + /** + * Parse a PHY configuration from a given JSON tree and map it on a PhyLayerConfiguration data + * class. + * + * \param jsonPhyLayer The JSON tree to parse. + * \return The configuration as a pointer to PhyLayerConfiguration to easily retrieve parsed + * data. + */ + static Ptr GetConfiguration(const rapidjson::Value& jsonPhyLayer); -private: - PhyLayerConfigurationHelper(); + private: + PhyLayerConfigurationHelper(); }; } // namespace ns3 diff --git a/src/configuration/helper/remote-configuration-helper.cc b/src/configuration/helper/remote-configuration-helper.cc index 74e4a0b..9246a19 100644 --- a/src/configuration/helper/remote-configuration-helper.cc +++ b/src/configuration/helper/remote-configuration-helper.cc @@ -17,69 +17,64 @@ */ #include "remote-configuration-helper.h" +#include "model-configuration-helper.h" + +#include #include +#include +#include #include +#include #include #include #include - -#include -#include #include -#include -#include - -#include "model-configuration-helper.h" -namespace ns3 { +namespace ns3 +{ Ptr -RemoteConfigurationHelper::GetConfiguration (const rapidjson::Value& json) +RemoteConfigurationHelper::GetConfiguration(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsObject (), - "Remote configuration must be an object."); - NS_ASSERT_MSG (json.HasMember ("networkLayer"), - "Remote configuration must have 'networkLayer' property defined."); - NS_ASSERT_MSG (json.HasMember ("applications"), - "Remote configuration must have 'applications' property defined."); + NS_ASSERT_MSG(json.IsObject(), "Remote configuration must be an object."); + NS_ASSERT_MSG(json.HasMember("networkLayer"), + "Remote configuration must have 'networkLayer' property defined."); + NS_ASSERT_MSG(json.HasMember("applications"), + "Remote configuration must have 'applications' property defined."); - const auto networkLayerId = DecodeNetworkLayerId (json["networkLayer"]); - const auto applications = DecodeApplicationConfigurations (json["applications"]); - - return CreateObject (networkLayerId, applications); + const auto networkLayerId = DecodeNetworkLayerId(json["networkLayer"]); + const auto applications = DecodeApplicationConfigurations(json["applications"]); + return CreateObject(networkLayerId, applications); } -RemoteConfigurationHelper::RemoteConfigurationHelper () +RemoteConfigurationHelper::RemoteConfigurationHelper() { - } const uint32_t -RemoteConfigurationHelper::DecodeNetworkLayerId (const rapidjson::Value& json) +RemoteConfigurationHelper::DecodeNetworkLayerId(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsInt () && json.GetInt () >= 0, - "Remote configuration 'networkLayer' property must be a positive integer."); + NS_ASSERT_MSG(json.IsInt() && json.GetInt() >= 0, + "Remote configuration 'networkLayer' property must be a positive integer."); - return json.GetInt (); + return json.GetInt(); } const std::vector -RemoteConfigurationHelper::DecodeApplicationConfigurations (const rapidjson::Value& json) +RemoteConfigurationHelper::DecodeApplicationConfigurations(const rapidjson::Value& json) { - NS_ASSERT_MSG (json.IsArray (), - "Remote configuration 'applications' property must be an array."); + NS_ASSERT_MSG(json.IsArray(), "Remote configuration 'applications' property must be an array."); - std::vector confs; - for (auto& appl : json.GetArray ()) + std::vector confs; + for (auto& appl : json.GetArray()) { - NS_ASSERT_MSG (appl.IsObject (), - "Application model configuration must be an object."); + NS_ASSERT_MSG(appl.IsObject(), "Application model configuration must be an object."); - confs.push_back (ModelConfigurationHelper::Get (appl)); + confs.push_back(ModelConfigurationHelper::Get(appl)); } - return confs; + return confs; } } // namespace ns3 diff --git a/src/configuration/helper/remote-configuration-helper.h b/src/configuration/helper/remote-configuration-helper.h index 9ca8a06..ad4e16e 100644 --- a/src/configuration/helper/remote-configuration-helper.h +++ b/src/configuration/helper/remote-configuration-helper.h @@ -18,11 +18,12 @@ #ifndef REMOTE_CONFIGURATION_HELPER_H #define REMOTE_CONFIGURATION_HELPER_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ using JsonArray = rapidjson::GenericArray; @@ -33,22 +34,24 @@ using JsonArray = rapidjson::GenericArray; */ class RemoteConfigurationHelper { -public: - /** - * Parse an entity configuration from a given JSON tree and map it on an RemoteConfiguration data class. - * - * \param json The JSON tree to parse. - * \return The configuration as a pointer to RemoteConfiguration to easily retrieve parsed data. - */ - static Ptr GetConfiguration (const rapidjson::Value& json); - -private: - RemoteConfigurationHelper (); - - static const uint32_t DecodeNetworkLayerId (const rapidjson::Value& json); - static const std::vector DecodeApplicationConfigurations (const rapidjson::Value& json); + public: + /** + * Parse an entity configuration from a given JSON tree and map it on an RemoteConfiguration + * data class. + * + * \param json The JSON tree to parse. + * \return The configuration as a pointer to RemoteConfiguration to easily retrieve parsed data. + */ + static Ptr GetConfiguration(const rapidjson::Value& json); + + private: + RemoteConfigurationHelper(); + + static const uint32_t DecodeNetworkLayerId(const rapidjson::Value& json); + static const std::vector DecodeApplicationConfigurations( + const rapidjson::Value& json); }; -} +} // namespace ns3 #endif /* REMOTE_CONFIGURATION_HELPER_H */ diff --git a/src/configuration/helper/scenario-configuration-helper.cc b/src/configuration/helper/scenario-configuration-helper.cc index 76e55b6..386dcad 100644 --- a/src/configuration/helper/scenario-configuration-helper.cc +++ b/src/configuration/helper/scenario-configuration-helper.cc @@ -17,1431 +17,1398 @@ */ #include "scenario-configuration-helper.h" -#include -#include /* put_time */ -#include - #include #include #include +#include +#include #include +#include +#include #include +#include +#include /* put_time */ +#include +#include #include #include -#include -#include -#include -#include -#include - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE_MASK ("ScenarioConfigurationHelper", LOG_PREFIX_ALL); +NS_LOG_COMPONENT_DEFINE_MASK("ScenarioConfigurationHelper", LOG_PREFIX_ALL); void -ScenarioConfigurationHelper::Initialize (int argc, - char **argv) +ScenarioConfigurationHelper::Initialize(int argc, char** argv) { - auto now = std::chrono::system_clock::now (); - auto in_time_t = std::chrono::system_clock::to_time_t(now); - std::stringstream dateTime; + auto now = std::chrono::system_clock::now(); + auto in_time_t = std::chrono::system_clock::to_time_t(now); + std::stringstream dateTime; - dateTime << std::put_time (std::localtime (&in_time_t), "%Y-%m-%d.%H-%M-%S"); + dateTime << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d.%H-%M-%S"); - m_dateTime = dateTime.str (); + m_dateTime = dateTime.str(); - InitializeConfiguration (argc, argv); - InitializeLogging (GetLogOnFile ()); + InitializeConfiguration(argc, argv); + InitializeLogging(GetLogOnFile()); } void -ScenarioConfigurationHelper::Initialize (int argc, - char **argv, - const std::string name) +ScenarioConfigurationHelper::Initialize(int argc, char** argv, const std::string name) { - auto now = std::chrono::system_clock::now (); - auto in_time_t = std::chrono::system_clock::to_time_t (now); - std::stringstream dateTime; + auto now = std::chrono::system_clock::now(); + auto in_time_t = std::chrono::system_clock::to_time_t(now); + std::stringstream dateTime; - dateTime << std::put_time (std::localtime (&in_time_t), "%Y-%m-%d-%H-%M-%S"); + dateTime << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d-%H-%M-%S"); - m_dateTime = dateTime.str (); - m_name = name; + m_dateTime = dateTime.str(); + m_name = name; - InitializeConfiguration (argc, argv); - InitializeLogging (GetLogOnFile ()); + InitializeConfiguration(argc, argv); + InitializeLogging(GetLogOnFile()); } -ScenarioConfigurationHelper::~ScenarioConfigurationHelper () +ScenarioConfigurationHelper::~ScenarioConfigurationHelper() { - DisposeLogging (); - DisposeConfiguration (); + DisposeLogging(); + DisposeConfiguration(); } const std::string -ScenarioConfigurationHelper::GetName () +ScenarioConfigurationHelper::GetName() { - if (m_name.empty()) + if (m_name.empty()) { - NS_ASSERT_MSG (m_config.HasMember ("name"), - "Please define scenario 'name' in configuration file."); - NS_ASSERT_MSG (m_config["name"].IsString(), - "Scenario 'name' must be a String."); + NS_ASSERT_MSG(m_config.HasMember("name"), + "Please define scenario 'name' in configuration file."); + NS_ASSERT_MSG(m_config["name"].IsString(), "Scenario 'name' must be a String."); - m_name = m_config["name"].GetString (); - NS_ASSERT_MSG (!m_name.empty(), "Scenario 'name' must be non empty."); + m_name = m_config["name"].GetString(); + NS_ASSERT_MSG(!m_name.empty(), "Scenario 'name' must be non empty."); } - return m_name; + return m_name; } const std::string -ScenarioConfigurationHelper::GetCurrentDateTime () const +ScenarioConfigurationHelper::GetCurrentDateTime() const { - return m_dateTime; + return m_dateTime; } const std::string -ScenarioConfigurationHelper::GetResultsPath () +ScenarioConfigurationHelper::GetResultsPath() { - NS_ASSERT_MSG (m_config.HasMember ("resultsPath"), - "Please define 'resultsPath' in configuration file."); - NS_ASSERT_MSG (m_config["resultsPath"].IsString (), - "'resultsPath' must be a string."); + NS_ASSERT_MSG(m_config.HasMember("resultsPath"), + "Please define 'resultsPath' in configuration file."); + NS_ASSERT_MSG(m_config["resultsPath"].IsString(), "'resultsPath' must be a string."); - std::stringstream path; + std::stringstream path; - path << m_config["resultsPath"].GetString () - << "/" - << GetName () << "-" - << m_dateTime; + path << m_config["resultsPath"].GetString() << "/" << GetName() << "-" << m_dateTime; - SystemPath::MakeDirectories (path.str ()); + SystemPath::MakeDirectories(path.str()); - path << "/"; + path << "/"; - return path.str (); + return path.str(); } const bool ScenarioConfigurationHelper::GetLogOnFile() const { - // this is an optional parameter. Default to false if not specified. - if (m_config.HasMember("logOnFile")) - { - NS_ASSERT_MSG(m_config["logOnFile"].IsBool(), "'logOnFile' property must be boolean."); - return m_config["logOnFile"].GetBool(); - } - else - { - return false; - } + // this is an optional parameter. Default to false if not specified. + if (m_config.HasMember("logOnFile")) + { + NS_ASSERT_MSG(m_config["logOnFile"].IsBool(), "'logOnFile' property must be boolean."); + return m_config["logOnFile"].GetBool(); + } + else + { + return false; + } } const std::string -ScenarioConfigurationHelper::GetLoggingFilePath () +ScenarioConfigurationHelper::GetLoggingFilePath() { - std::stringstream ss; + std::stringstream ss; - ss << GetResultsPath () << "scenario.log"; + ss << GetResultsPath() << "scenario.log"; - return ss.str (); + return ss.str(); } const std::vector> -ScenarioConfigurationHelper::GetStaticConfig () +ScenarioConfigurationHelper::GetStaticConfig() { - if (m_staticConfig.empty ()) + if (m_staticConfig.empty()) { - NS_ASSERT_MSG (m_config.HasMember ("staticNs3Config"), - "Please define 'staticNs3Config' in configuration file."); - NS_ASSERT_MSG (m_config["staticNs3Config"].IsArray (), - "'staticNs3Config' property must be an array."); - - std::vector> staticConfigsDecoded = {}; - const auto staticConfigsArr = m_config["staticNs3Config"].GetArray (); - for (auto& sc : staticConfigsArr) + NS_ASSERT_MSG(m_config.HasMember("staticNs3Config"), + "Please define 'staticNs3Config' in configuration file."); + NS_ASSERT_MSG(m_config["staticNs3Config"].IsArray(), + "'staticNs3Config' property must be an array."); + + std::vector> staticConfigsDecoded = {}; + const auto staticConfigsArr = m_config["staticNs3Config"].GetArray(); + for (auto& sc : staticConfigsArr) { - NS_ASSERT_MSG (sc.IsObject (), - "A static config definition is invalid."); - - const auto obj = sc.GetObject (); - NS_ASSERT_MSG (obj.HasMember ("name"), - "'name' is required in staticNs3Config definition."); - NS_ASSERT_MSG (obj["name"].IsString (), - "'name' property must be a string in staticNs3Config definition."); - NS_ASSERT_MSG (obj.HasMember ("value"), - "'value' is required in staticNs3Config definiton."); - NS_ASSERT_MSG (obj["value"].IsString () || obj["value"].IsNumber (), - "'value' property must be a string or a number in staticNs3Config definition."); - - std::stringstream value; - if (obj["value"].IsDouble ()) - value << obj["value"].GetDouble (); - else if (obj["value"].IsInt ()) - value << obj["value"].GetInt (); - else if (obj["value"].IsString ()) - value << obj["value"].GetString (); - - staticConfigsDecoded.push_back({ - obj["name"].GetString (), - value.str () - }); + NS_ASSERT_MSG(sc.IsObject(), "A static config definition is invalid."); + + const auto obj = sc.GetObject(); + NS_ASSERT_MSG(obj.HasMember("name"), + "'name' is required in staticNs3Config definition."); + NS_ASSERT_MSG(obj["name"].IsString(), + "'name' property must be a string in staticNs3Config definition."); + NS_ASSERT_MSG(obj.HasMember("value"), + "'value' is required in staticNs3Config definiton."); + NS_ASSERT_MSG( + obj["value"].IsString() || obj["value"].IsNumber(), + "'value' property must be a string or a number in staticNs3Config definition."); + + std::stringstream value; + if (obj["value"].IsDouble()) + value << obj["value"].GetDouble(); + else if (obj["value"].IsInt()) + value << obj["value"].GetInt(); + else if (obj["value"].IsString()) + value << obj["value"].GetString(); + + staticConfigsDecoded.push_back({obj["name"].GetString(), value.str()}); } - m_staticConfig = staticConfigsDecoded; + m_staticConfig = staticConfigsDecoded; } - return m_staticConfig; + return m_staticConfig; } const std::vector> -ScenarioConfigurationHelper::GetPhyLayers () const +ScenarioConfigurationHelper::GetPhyLayers() const { - NS_ASSERT_MSG (m_config.HasMember ("phyLayer"), - "Please define phyLayer in your JSON configuration."); - NS_ASSERT_MSG (m_config["phyLayer"].IsArray (), - "'phyLayer' property must be an array."); + NS_ASSERT_MSG(m_config.HasMember("phyLayer"), + "Please define phyLayer in your JSON configuration."); + NS_ASSERT_MSG(m_config["phyLayer"].IsArray(), "'phyLayer' property must be an array."); - const auto arr = m_config["phyLayer"].GetArray (); - std::vector> phyConfs; - for(auto& el : arr) + const auto arr = m_config["phyLayer"].GetArray(); + std::vector> phyConfs; + for (auto& el : arr) { - auto conf = PhyLayerConfigurationHelper::GetConfiguration (el); - phyConfs.emplace_back (conf); + auto conf = PhyLayerConfigurationHelper::GetConfiguration(el); + phyConfs.emplace_back(conf); } - return phyConfs; + return phyConfs; } const std::vector> -ScenarioConfigurationHelper::GetMacLayers ()const +ScenarioConfigurationHelper::GetMacLayers() const { - NS_ASSERT_MSG (m_config.HasMember ("macLayer"), - "Please define macLayer in your JSON configuration."); - NS_ASSERT_MSG (m_config["macLayer"].IsArray (), - "'macLayer' property must be an array."); + NS_ASSERT_MSG(m_config.HasMember("macLayer"), + "Please define macLayer in your JSON configuration."); + NS_ASSERT_MSG(m_config["macLayer"].IsArray(), "'macLayer' property must be an array."); - const auto arr = m_config["macLayer"].GetArray (); - std::vector> macConfs; - for(auto& el : arr) + const auto arr = m_config["macLayer"].GetArray(); + std::vector> macConfs; + for (auto& el : arr) { - auto conf = MacLayerConfigurationHelper::GetConfiguration (el); - macConfs.emplace_back (conf); + auto conf = MacLayerConfigurationHelper::GetConfiguration(el); + macConfs.emplace_back(conf); } - return macConfs; + return macConfs; } const std::vector> -ScenarioConfigurationHelper::GetNetworkLayers () const +ScenarioConfigurationHelper::GetNetworkLayers() const { - NS_ASSERT_MSG (m_config.HasMember ("networkLayer"), - "Please define 'networkLayer' in your JSON configuration."); - NS_ASSERT_MSG (m_config["networkLayer"].IsArray (), - "'networkLayer' property must be an array."); + NS_ASSERT_MSG(m_config.HasMember("networkLayer"), + "Please define 'networkLayer' in your JSON configuration."); + NS_ASSERT_MSG(m_config["networkLayer"].IsArray(), "'networkLayer' property must be an array."); - const auto arr = m_config["networkLayer"].GetArray (); - std::vector> netConfs; - for(auto& el : arr) + const auto arr = m_config["networkLayer"].GetArray(); + std::vector> netConfs; + for (auto& el : arr) { - auto conf = NetworkLayerConfigurationHelper::GetConfiguration (el); - netConfs.emplace_back (conf); + auto conf = NetworkLayerConfigurationHelper::GetConfiguration(el); + netConfs.emplace_back(conf); } - return netConfs; + return netConfs; } const std::vector> -ScenarioConfigurationHelper::GetEntitiesConfiguration (const std::string &entityKey) const +ScenarioConfigurationHelper::GetEntitiesConfiguration(const std::string& entityKey) const { - const char *entityKeyCStr = entityKey.c_str (); - if (!m_config.HasMember (entityKeyCStr)) - return {}; + const char* entityKeyCStr = entityKey.c_str(); + if (!m_config.HasMember(entityKeyCStr)) + return {}; - NS_ASSERT_MSG (m_config[entityKeyCStr].IsArray (), - "JSON property '" << entityKey << "' must be an array."); + NS_ASSERT_MSG(m_config[entityKeyCStr].IsArray(), + "JSON property '" << entityKey << "' must be an array."); - const auto arr = m_config[entityKeyCStr].GetArray (); - std::vector> entityConf{}; + const auto arr = m_config[entityKeyCStr].GetArray(); + std::vector> entityConf{}; - entityConf.reserve (arr.Size ()); - for (auto &el : arr) + entityConf.reserve(arr.Size()); + for (auto& el : arr) { - auto conf = EntityConfigurationHelper::GetConfiguration (el); - entityConf.push_back (conf); + auto conf = EntityConfigurationHelper::GetConfiguration(el); + entityConf.push_back(conf); } - return entityConf; + return entityConf; } const std::vector> -ScenarioConfigurationHelper::GetRemotesConfiguration () const +ScenarioConfigurationHelper::GetRemotesConfiguration() const { - std::vector> remoteConf; + std::vector> remoteConf; - if (!m_config.HasMember ("remotes")) - return remoteConf; + if (!m_config.HasMember("remotes")) + return remoteConf; - NS_ASSERT_MSG (m_config["remotes"].IsArray (), - "JSON property 'remotes' must be an array."); + NS_ASSERT_MSG(m_config["remotes"].IsArray(), "JSON property 'remotes' must be an array."); - const auto arr = m_config["remotes"].GetArray (); - for (auto& el : arr) + const auto arr = m_config["remotes"].GetArray(); + for (auto& el : arr) { - auto conf = RemoteConfigurationHelper::GetConfiguration (el); - remoteConf.push_back (conf); + auto conf = RemoteConfigurationHelper::GetConfiguration(el); + remoteConf.push_back(conf); } - return remoteConf; + return remoteConf; } const double -ScenarioConfigurationHelper::GetDuration () const +ScenarioConfigurationHelper::GetDuration() const { - NS_ASSERT (m_config.HasMember ("duration")); - NS_ASSERT_MSG (m_config["duration"].IsNumber (), - "Please define duration in configuration file."); + NS_ASSERT(m_config.HasMember("duration")); + NS_ASSERT_MSG(m_config["duration"].IsNumber(), "Please define duration in configuration file."); - double duration = 0.0; + double duration = 0.0; - if (m_config["duration"].IsUint ()) { - duration = static_cast (m_config["duration"].GetUint ()); - } else { - duration = m_config["duration"].GetDouble (); - } + if (m_config["duration"].IsUint()) + { + duration = static_cast(m_config["duration"].GetUint()); + } + else + { + duration = m_config["duration"].GetDouble(); + } - return duration; + return duration; } std::size_t ScenarioConfigurationHelper::GetN(const char* ek) const { - if (!m_config.HasMember(ek)) - return 0; + if (!m_config.HasMember(ek)) + return 0; - NS_ASSERT_MSG(m_config[ek].IsArray(), - "'" << ek << "' property in the configuration file must be an array of objects."); + NS_ASSERT_MSG(m_config[ek].IsArray(), + "'" << ek << "' property in the configuration file must be an array of objects."); - return m_config[ek].Size(); + return m_config[ek].Size(); } std::size_t -ScenarioConfigurationHelper::GetNodesN () const +ScenarioConfigurationHelper::GetNodesN() const { - // optional field - if (!m_config.HasMember ("nodes")) - return 0; + // optional field + if (!m_config.HasMember("nodes")) + return 0; - NS_ASSERT_MSG (m_config["nodes"].IsArray (), - "Expected \"nodes\" property to be an array of objects."); + NS_ASSERT_MSG(m_config["nodes"].IsArray(), + "Expected \"nodes\" property to be an array of objects."); - return m_config["nodes"].Size (); + return m_config["nodes"].Size(); } const std::string -ScenarioConfigurationHelper::GetPhyPropagationLossModel () const +ScenarioConfigurationHelper::GetPhyPropagationLossModel() const { - constexpr const char* jRootKey = "phyPropagationLoss"; - constexpr const char* jModelKey = "model"; + constexpr const char* jRootKey = "phyPropagationLoss"; + constexpr const char* jModelKey = "model"; - NS_ASSERT (m_config.HasMember (jRootKey)); - NS_ASSERT_MSG (m_config[jRootKey].IsObject (), - jRootKey << " must be a valid JSON object per specification."); + NS_ASSERT(m_config.HasMember(jRootKey)); + NS_ASSERT_MSG(m_config[jRootKey].IsObject(), + jRootKey << " must be a valid JSON object per specification."); - NS_ASSERT (m_config[jRootKey].HasMember (jModelKey)); - NS_ASSERT_MSG (m_config[jRootKey][jModelKey].IsString (), - jModelKey << " must be a valid JSON string per specification."); + NS_ASSERT(m_config[jRootKey].HasMember(jModelKey)); + NS_ASSERT_MSG(m_config[jRootKey][jModelKey].IsString(), + jModelKey << " must be a valid JSON string per specification."); - return m_config[jRootKey][jModelKey].GetString (); + return m_config[jRootKey][jModelKey].GetString(); } -const std::vector > -ScenarioConfigurationHelper::GetThreeLogDistancePropagationLossModelAttributes () const +const std::vector> +ScenarioConfigurationHelper::GetThreeLogDistancePropagationLossModelAttributes() const { - constexpr const char* jRootKey = "phyPropagationLoss"; - constexpr const char* jAttrKey = "attributes"; + constexpr const char* jRootKey = "phyPropagationLoss"; + constexpr const char* jAttrKey = "attributes"; - NS_ASSERT (m_config.HasMember (jRootKey)); - NS_ASSERT_MSG (m_config[jRootKey].IsObject (), - jRootKey << " must be a valid JSON object per specification."); + NS_ASSERT(m_config.HasMember(jRootKey)); + NS_ASSERT_MSG(m_config[jRootKey].IsObject(), + jRootKey << " must be a valid JSON object per specification."); - NS_ASSERT (m_config[jRootKey].HasMember (jAttrKey)); - NS_ASSERT_MSG (m_config[jRootKey][jAttrKey].IsArray (), - jAttrKey << " must be a valid JSON array per specification."); + NS_ASSERT(m_config[jRootKey].HasMember(jAttrKey)); + NS_ASSERT_MSG(m_config[jRootKey][jAttrKey].IsArray(), + jAttrKey << " must be a valid JSON array per specification."); - const auto jAttrArr = m_config[jRootKey][jAttrKey].GetArray (); + const auto jAttrArr = m_config[jRootKey][jAttrKey].GetArray(); - // check if we have an array of objects - for (auto& el : jAttrArr) + // check if we have an array of objects + for (auto& el : jAttrArr) { - NS_ASSERT_MSG (el.IsObject (), - jAttrKey << " must be a valid array of objects."); - - NS_ASSERT_MSG (el.HasMember ("key") - && el["key"].IsString () - && el.HasMember ("value") - && !el["value"].IsArray () - && !el["value"].IsObject (), - jAttrKey << " contains a malformed structure."); + NS_ASSERT_MSG(el.IsObject(), jAttrKey << " must be a valid array of objects."); + + NS_ASSERT_MSG(el.HasMember("key") && el["key"].IsString() && el.HasMember("value") && + !el["value"].IsArray() && !el["value"].IsObject(), + jAttrKey << " contains a malformed structure."); } - // "safe" to decode the data - std::vector > attrList; + // "safe" to decode the data + std::vector> attrList; - for (auto& el : jAttrArr) + for (auto& el : jAttrArr) { - const std::string attrKey = el["key"].GetString (); - const float attrVal = el["value"].GetFloat (); + const std::string attrKey = el["key"].GetString(); + const float attrVal = el["value"].GetFloat(); - attrList.push_back ({attrKey, attrVal}); + attrList.push_back({attrKey, attrVal}); } - return attrList; + return attrList; } const std::string -ScenarioConfigurationHelper::GetPhyMode () const +ScenarioConfigurationHelper::GetPhyMode() const { - NS_ASSERT_MSG (m_config.HasMember ("phyMode") - && m_config["phyMode"].IsString (), - "Please define phyMode in configuration file."); + NS_ASSERT_MSG(m_config.HasMember("phyMode") && m_config["phyMode"].IsString(), + "Please define phyMode in configuration file."); - return m_config["phyMode"].GetString (); + return m_config["phyMode"].GetString(); } const uint32_t -ScenarioConfigurationHelper::GetDronesN () const +ScenarioConfigurationHelper::GetDronesN() const { - if (!m_config.HasMember ("drones")) - return 0; + if (!m_config.HasMember("drones")) + return 0; - NS_ASSERT_MSG (m_config["drones"].IsArray (), - "'drones' property in the configuration file must be an array of objects."); + NS_ASSERT_MSG(m_config["drones"].IsArray(), + "'drones' property in the configuration file must be an array of objects."); - return m_config["drones"].Size (); + return m_config["drones"].Size(); } const std::string -ScenarioConfigurationHelper::GetDronesMobilityModel () const +ScenarioConfigurationHelper::GetDronesMobilityModel() const { - NS_ASSERT_MSG (m_config.HasMember ("dronesMobilityModel") - && m_config["dronesMobilityModel"].IsString (), - "Please define dronesMobilityModel in configuration file."); + NS_ASSERT_MSG(m_config.HasMember("dronesMobilityModel") && + m_config["dronesMobilityModel"].IsString(), + "Please define dronesMobilityModel in configuration file."); - return m_config["dronesMobilityModel"].GetString (); + return m_config["dronesMobilityModel"].GetString(); } void -ScenarioConfigurationHelper::GetDronesPosition (Ptr allocator) const +ScenarioConfigurationHelper::GetDronesPosition(Ptr allocator) const { - NS_ASSERT_MSG (GetDronesMobilityModel () == "ns3::ConstantPositionMobilityModel", - "Drones position parameter can be used only when dronesMobilityModel is ns3::ConstantPositionMobilityModel"); + NS_ASSERT_MSG(GetDronesMobilityModel() == "ns3::ConstantPositionMobilityModel", + "Drones position parameter can be used only when dronesMobilityModel is " + "ns3::ConstantPositionMobilityModel"); - for (uint32_t i = 0; i < m_config["drones"].GetArray ().Size (); ++i) + for (uint32_t i = 0; i < m_config["drones"].GetArray().Size(); ++i) { - Vector v = GetDronePosition (i); - NS_LOG_LOGIC ("Allocating a drone in space at " << v); - allocator->Add (v); + Vector v = GetDronePosition(i); + NS_LOG_LOGIC("Allocating a drone in space at " << v); + allocator->Add(v); } } const std::vector -ScenarioConfigurationHelper::GetDroneWaypoints (uint32_t i) const +ScenarioConfigurationHelper::GetDroneWaypoints(uint32_t i) const { - NS_ASSERT_MSG (GetDroneMobilityModel (i) == "ns3::WaypointMobilityModel", - "Waypoints are usable only with ns3::WaypointMobilityModel"); + NS_ASSERT_MSG(GetDroneMobilityModel(i) == "ns3::WaypointMobilityModel", + "Waypoints are usable only with ns3::WaypointMobilityModel"); - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[i].GetObject (); + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[i].GetObject(); - std::vector waypoints; + std::vector waypoints; - Time prevTime = Seconds (0); + Time prevTime = Seconds(0); - for (auto point = drone["trajectory"].Begin (); - point != drone["trajectory"].End (); - point++) + for (auto point = drone["trajectory"].Begin(); point != drone["trajectory"].End(); point++) { - NS_ASSERT_MSG (point->IsObject (), - "Each waypoint in drone trajectory must be a JSON object."); - NS_ASSERT_MSG (point->HasMember ("position") - && (*point)["position"].IsArray () - && (*point)["position"][0].IsDouble () - && (*point)["position"][1].IsDouble () - && (*point)["position"][2].IsDouble () - && point->HasMember ("time") - && (*point)["time"].IsDouble (), - "Cannot decode waypoint, please check that each point in trajectory has at least position and time."); + NS_ASSERT_MSG(point->IsObject(), + "Each waypoint in drone trajectory must be a JSON object."); + NS_ASSERT_MSG(point->HasMember("position") && (*point)["position"].IsArray() && + (*point)["position"][0].IsDouble() && + (*point)["position"][1].IsDouble() && + (*point)["position"][2].IsDouble() && point->HasMember("time") && + (*point)["time"].IsDouble(), + "Cannot decode waypoint, please check that each point in trajectory has at " + "least position and time."); - Time time = Seconds ((*point)["time"].GetDouble ()); + Time time = Seconds((*point)["time"].GetDouble()); - NS_ASSERT_MSG (time >= prevTime, - "Check waypoints, time of a waypoint must be greater or equal to the previous"); + NS_ASSERT_MSG( + time >= prevTime, + "Check waypoints, time of a waypoint must be greater or equal to the previous"); - Vector position = Vector ({(*point)["position"][0].GetDouble (), - (*point)["position"][1].GetDouble (), - (*point)["position"][2].GetDouble ()}); + Vector position = Vector({(*point)["position"][0].GetDouble(), + (*point)["position"][1].GetDouble(), + (*point)["position"][2].GetDouble()}); - waypoints.emplace_back (Waypoint (time, position)); + waypoints.emplace_back(Waypoint(time, position)); - prevTime = time; + prevTime = time; } - return waypoints; + return waypoints; } const float -ScenarioConfigurationHelper::GetCurveStep () const +ScenarioConfigurationHelper::GetCurveStep() const { - if (m_config.HasMember ("curveStep")) + if (m_config.HasMember("curveStep")) { - NS_ASSERT (m_config["curveStep"].IsFloat ()); - return m_config["curveStep"].GetFloat (); + NS_ASSERT(m_config["curveStep"].IsFloat()); + return m_config["curveStep"].GetFloat(); } - else + else { - return 0.001; + return 0.001; } } const FlightPlan -ScenarioConfigurationHelper::GetDroneFlightPlan (uint32_t i) const +ScenarioConfigurationHelper::GetDroneFlightPlan(uint32_t i) const { - // checks for drones were already made in ::ConfGetNumDrones. - // Let's skip them. - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[i].GetObject (); + // checks for drones were already made in ::ConfGetNumDrones. + // Let's skip them. + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[i].GetObject(); - FlightPlan flightPlan; + FlightPlan flightPlan; - for (auto point = drone["trajectory"].Begin (); - point != drone["trajectory"].End (); - point++) + for (auto point = drone["trajectory"].Begin(); point != drone["trajectory"].End(); point++) { - NS_ASSERT_MSG (point->IsObject (), - "Each point in drone must be a JSON object."); - NS_ASSERT_MSG (point->HasMember ("position") - && (*point)["position"].IsArray () - && (*point)["position"][0].IsDouble () - && (*point)["position"][1].IsDouble () - && (*point)["position"][2].IsDouble () - && point->HasMember ("interest") - && (*point)["interest"].IsUint (), - "Cannot decode trajectory, please check that each point has at least position and interest."); - - // restTime is optional - double restTime = 0.0; - if (point->HasMember ("restTime")) + NS_ASSERT_MSG(point->IsObject(), "Each point in drone must be a JSON object."); + NS_ASSERT_MSG(point->HasMember("position") && (*point)["position"].IsArray() && + (*point)["position"][0].IsDouble() && + (*point)["position"][1].IsDouble() && + (*point)["position"][2].IsDouble() && point->HasMember("interest") && + (*point)["interest"].IsUint(), + "Cannot decode trajectory, please check that each point has at least " + "position and interest."); + + // restTime is optional + double restTime = 0.0; + if (point->HasMember("restTime")) { - NS_ASSERT ((*point)["restTime"].IsDouble ()); - restTime = (*point)["restTime"].GetDouble (); + NS_ASSERT((*point)["restTime"].IsDouble()); + restTime = (*point)["restTime"].GetDouble(); } - auto protoPoint = CreateObjectWithAttributes ( - "Position", VectorValue ({(*point)["position"][0].GetDouble (), - (*point)["position"][1].GetDouble (), - (*point)["position"][2].GetDouble ()}), - "Interest", IntegerValue ((*point)["interest"].GetUint ()), - "RestTime", TimeValue (Seconds (restTime))); - - flightPlan.Add (protoPoint); + auto protoPoint = CreateObjectWithAttributes( + "Position", + VectorValue({(*point)["position"][0].GetDouble(), + (*point)["position"][1].GetDouble(), + (*point)["position"][2].GetDouble()}), + "Interest", + IntegerValue((*point)["interest"].GetUint()), + "RestTime", + TimeValue(Seconds(restTime))); + + flightPlan.Add(protoPoint); } - return flightPlan; + return flightPlan; } const double -ScenarioConfigurationHelper::GetDroneAcceleration (uint32_t i) const +ScenarioConfigurationHelper::GetDroneAcceleration(uint32_t i) const { - // checks for drones were already made in ::ConfGetNumDrones. - // Let's skip them. - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[i].GetObject (); + // checks for drones were already made in ::ConfGetNumDrones. + // Let's skip them. + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[i].GetObject(); - NS_ASSERT_MSG (drone.HasMember ("acceleration") - && drone["acceleration"].IsDouble (), - "Every done must have defined the parameter \"acceleration\"."); + NS_ASSERT_MSG(drone.HasMember("acceleration") && drone["acceleration"].IsDouble(), + "Every done must have defined the parameter \"acceleration\"."); - return drone["acceleration"].GetDouble (); + return drone["acceleration"].GetDouble(); } const double -ScenarioConfigurationHelper::GetDroneMaxSpeed (uint32_t i) const +ScenarioConfigurationHelper::GetDroneMaxSpeed(uint32_t i) const { - // checks for drones were already made in ::ConfGetNumDrones. - // Let's skip them. - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[i].GetObject (); + // checks for drones were already made in ::ConfGetNumDrones. + // Let's skip them. + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[i].GetObject(); - NS_ASSERT_MSG (drone.HasMember ("maxSpeed") - && drone["maxSpeed"].IsDouble (), - "Every done must have defined the parameter \"maxSpeed\"."); + NS_ASSERT_MSG(drone.HasMember("maxSpeed") && drone["maxSpeed"].IsDouble(), + "Every done must have defined the parameter \"maxSpeed\"."); - return drone["maxSpeed"].GetDouble (); + return drone["maxSpeed"].GetDouble(); } const DoubleVector -ScenarioConfigurationHelper::GetDroneSpeedCoefficients (uint32_t i) const +ScenarioConfigurationHelper::GetDroneSpeedCoefficients(uint32_t i) const { - // checks for drones were already made in ::ConfGetNumDrones. - // Let's skip them. - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[i].GetObject (); + // checks for drones were already made in ::ConfGetNumDrones. + // Let's skip them. + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[i].GetObject(); - DoubleVector speedCoefficients; + DoubleVector speedCoefficients; - NS_ASSERT (drone.HasMember ("speedCoefficients") - && drone["speedCoefficients"].IsArray () - && drone["speedCoefficients"].Size () > 0); + NS_ASSERT(drone.HasMember("speedCoefficients") && drone["speedCoefficients"].IsArray() && + drone["speedCoefficients"].Size() > 0); - for (auto coefficient = drone["speedCoefficients"].Begin (); - coefficient != drone["speedCoefficients"].End (); - coefficient++) + for (auto coefficient = drone["speedCoefficients"].Begin(); + coefficient != drone["speedCoefficients"].End(); + coefficient++) { - NS_ASSERT ((*coefficient).IsDouble ()); - speedCoefficients.Add ((*coefficient).GetDouble ()); + NS_ASSERT((*coefficient).IsDouble()); + speedCoefficients.Add((*coefficient).GetDouble()); } - return speedCoefficients; + return speedCoefficients; } const double -ScenarioConfigurationHelper::GetDroneApplicationStartTime (uint32_t i) const +ScenarioConfigurationHelper::GetDroneApplicationStartTime(uint32_t i) const { - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[i].GetObject (); + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[i].GetObject(); - if (drone.HasMember ("applicationStartTime") && drone["applicationStartTime"].IsDouble ()) - return drone["applicationStartTime"].GetDouble (); - else - return 0.0; + if (drone.HasMember("applicationStartTime") && drone["applicationStartTime"].IsDouble()) + return drone["applicationStartTime"].GetDouble(); + else + return 0.0; } const double -ScenarioConfigurationHelper::GetDroneApplicationStopTime (uint32_t i) const +ScenarioConfigurationHelper::GetDroneApplicationStopTime(uint32_t i) const { - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[i].GetObject (); + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[i].GetObject(); - if (drone.HasMember ("applicationStopTime") && drone["applicationStopTime"].IsDouble ()) - return drone["applicationStopTime"].GetDouble (); - else - return GetDuration (); + if (drone.HasMember("applicationStopTime") && drone["applicationStopTime"].IsDouble()) + return drone["applicationStopTime"].GetDouble(); + else + return GetDuration(); } const uint32_t -ScenarioConfigurationHelper::GetZspsN () const +ScenarioConfigurationHelper::GetZspsN() const { - if (!m_config.HasMember ("ZSPs")) - return 0; + if (!m_config.HasMember("ZSPs")) + return 0; - NS_ASSERT_MSG (m_config["ZSPs"].IsArray (), - "'ZSPs' property in the configuration file must be an array of objects."); + NS_ASSERT_MSG(m_config["ZSPs"].IsArray(), + "'ZSPs' property in the configuration file must be an array of objects."); - return m_config["ZSPs"].Size (); + return m_config["ZSPs"].Size(); } void -ScenarioConfigurationHelper::GetZspsPosition (Ptr allocator) const +ScenarioConfigurationHelper::GetZspsPosition(Ptr allocator) const { - // checks for ZSP array were already made in ::ConfGetNumZsps. - // Let's skip them. - for (auto i = m_config["ZSPs"].Begin (); i != m_config["ZSPs"].End (); i++) + // checks for ZSP array were already made in ::ConfGetNumZsps. + // Let's skip them. + for (auto i = m_config["ZSPs"].Begin(); i != m_config["ZSPs"].End(); i++) { - NS_ASSERT_MSG (i->IsObject (), - "Each ZSP must be a JSON object."); - NS_ASSERT_MSG (i->HasMember ("position"), - "One or more ZSPs do not have defined position."); - - NS_ASSERT_MSG ((*i)["position"].IsArray () - && (*i)["position"].Size () == 3 - && (*i)["position"][0].IsDouble () - && (*i)["position"][1].IsDouble () - && (*i)["position"][2].IsDouble (), - "Please check that each ZSP position is an array of 3 doubles."); - - Vector v ((*i)["position"][0].GetDouble (), - (*i)["position"][1].GetDouble (), - (*i)["position"][2].GetDouble ()); - - NS_LOG_LOGIC ("Allocating a ZSP in space at " << v); - allocator->Add (v); + NS_ASSERT_MSG(i->IsObject(), "Each ZSP must be a JSON object."); + NS_ASSERT_MSG(i->HasMember("position"), "One or more ZSPs do not have defined position."); + + NS_ASSERT_MSG((*i)["position"].IsArray() && (*i)["position"].Size() == 3 && + (*i)["position"][0].IsDouble() && (*i)["position"][1].IsDouble() && + (*i)["position"][2].IsDouble(), + "Please check that each ZSP position is an array of 3 doubles."); + + Vector v((*i)["position"][0].GetDouble(), + (*i)["position"][1].GetDouble(), + (*i)["position"][2].GetDouble()); + + NS_LOG_LOGIC("Allocating a ZSP in space at " << v); + allocator->Add(v); } } const double -ScenarioConfigurationHelper::GetZspApplicationStartTime (uint32_t i) const +ScenarioConfigurationHelper::GetZspApplicationStartTime(uint32_t i) const { - // checks for drones were already made in ::ConfGetNumDrones. - // Let's skip them. - const auto zsps = m_config["ZSPs"].GetArray (); - const auto zsp = zsps[i].GetObject (); + // checks for drones were already made in ::ConfGetNumDrones. + // Let's skip them. + const auto zsps = m_config["ZSPs"].GetArray(); + const auto zsp = zsps[i].GetObject(); - if (zsp.HasMember ("applicationStartTime") && zsp["applicationStartTime"].IsDouble ()) - return zsp["applicationStartTime"].GetDouble (); - else - return 0.0; + if (zsp.HasMember("applicationStartTime") && zsp["applicationStartTime"].IsDouble()) + return zsp["applicationStartTime"].GetDouble(); + else + return 0.0; } const double -ScenarioConfigurationHelper::GetZspApplicationStopTime (uint32_t i) const +ScenarioConfigurationHelper::GetZspApplicationStopTime(uint32_t i) const { - // checks for drones were already made in ::ConfGetNumDrones. - // Let's skip them. - const auto zsps = m_config["ZSPs"].GetArray (); - const auto zsp = zsps[i].GetObject (); + // checks for drones were already made in ::ConfGetNumDrones. + // Let's skip them. + const auto zsps = m_config["ZSPs"].GetArray(); + const auto zsp = zsps[i].GetObject(); - if (zsp.HasMember ("applicationStopTime") && zsp["applicationStopTime"].IsDouble ()) - return zsp["applicationStopTime"].GetDouble (); - else - return GetDuration (); + if (zsp.HasMember("applicationStopTime") && zsp["applicationStopTime"].IsDouble()) + return zsp["applicationStopTime"].GetDouble(); + else + return GetDuration(); } const uint32_t -ScenarioConfigurationHelper::GetEnbsN () const +ScenarioConfigurationHelper::GetEnbsN() const { - NS_ASSERT (m_config.HasMember ("ENBs")); - NS_ASSERT (m_config["ENBs"].IsArray ()); - NS_ASSERT_MSG (m_config["ENBs"].Size () > 0, - "Please define at least one ENB in configuration file."); + NS_ASSERT(m_config.HasMember("ENBs")); + NS_ASSERT(m_config["ENBs"].IsArray()); + NS_ASSERT_MSG(m_config["ENBs"].Size() > 0, + "Please define at least one ENB in configuration file."); - return m_config["ENBs"].Size (); + return m_config["ENBs"].Size(); } void -ScenarioConfigurationHelper::GetEnbsPosition (Ptr allocator) const +ScenarioConfigurationHelper::GetEnbsPosition(Ptr allocator) const { - // checks for ZSP array were already made in ::ConfGetNumZsps. - // Let's skip them. - for (auto i = m_config["ENBs"].Begin (); i != m_config["ENBs"].End (); i++) + // checks for ZSP array were already made in ::ConfGetNumZsps. + // Let's skip them. + for (auto i = m_config["ENBs"].Begin(); i != m_config["ENBs"].End(); i++) { - NS_ASSERT_MSG (i->IsObject (), - "Each ENB must be a JSON object."); - NS_ASSERT_MSG (i->HasMember ("position"), - "One or more ENBs do not have defined position."); - - NS_ASSERT_MSG ((*i)["position"].IsArray () - && (*i)["position"].Size () == 3 - && (*i)["position"][0].IsDouble () - && (*i)["position"][1].IsDouble () - && (*i)["position"][2].IsDouble (), - "Please check that each ENB position is an array of 3 doubles."); - - Vector v ((*i)["position"][0].GetDouble (), - (*i)["position"][1].GetDouble (), - (*i)["position"][2].GetDouble ()); - - NS_LOG_LOGIC ("Allocating a ENB in space at " << v); - allocator->Add (v); + NS_ASSERT_MSG(i->IsObject(), "Each ENB must be a JSON object."); + NS_ASSERT_MSG(i->HasMember("position"), "One or more ENBs do not have defined position."); + + NS_ASSERT_MSG((*i)["position"].IsArray() && (*i)["position"].Size() == 3 && + (*i)["position"][0].IsDouble() && (*i)["position"][1].IsDouble() && + (*i)["position"][2].IsDouble(), + "Please check that each ENB position is an array of 3 doubles."); + + Vector v((*i)["position"][0].GetDouble(), + (*i)["position"][1].GetDouble(), + (*i)["position"][2].GetDouble()); + + NS_LOG_LOGIC("Allocating a ENB in space at " << v); + allocator->Add(v); } } const bool -ScenarioConfigurationHelper::IsDryRun () const +ScenarioConfigurationHelper::IsDryRun() const { - // This is an optional parameter, so no asserts! - if (m_config.HasMember ("dryRun")) + // This is an optional parameter, so no asserts! + if (m_config.HasMember("dryRun")) { - NS_ASSERT_MSG (m_config["dryRun"].IsBool (), "'dryRun' flag must be boolean type."); - return m_config["dryRun"].GetBool (); + NS_ASSERT_MSG(m_config["dryRun"].IsBool(), "'dryRun' flag must be boolean type."); + return m_config["dryRun"].GetBool(); } - else + else { - return false; + return false; } } void -ScenarioConfigurationHelper::InitializeConfiguration (int argc, char **argv) -{ - std::string configFilePath = ""; - constexpr const ssize_t configFileBufferSize = 64 * 1024; // KiB - char configFileBuffer [configFileBufferSize]; - m_radioMap=0; //no generation as default - CommandLine cmd; - cmd.AddValue ("name", "Name of the scenario", m_name); - cmd.AddValue ("config", "Configuration file path", configFilePath); - cmd.AddValue ("radioMap", "Enables the generation of the EnvironmentRadioMap", m_radioMap); - cmd.Parse (argc, argv); - - if (configFilePath.empty ()) +ScenarioConfigurationHelper::InitializeConfiguration(int argc, char** argv) +{ + std::string configFilePath = ""; + constexpr const ssize_t configFileBufferSize = 64 * 1024; // KiB + char configFileBuffer[configFileBufferSize]; + m_radioMap = 0; // no generation as default + CommandLine cmd; + cmd.AddValue("name", "Name of the scenario", m_name); + cmd.AddValue("config", "Configuration file path", configFilePath); + cmd.AddValue("radioMap", "Enables the generation of the EnvironmentRadioMap", m_radioMap); + cmd.Parse(argc, argv); + + if (configFilePath.empty()) { - NS_FATAL_ERROR ("Please specify a non-empty, JSON formatted configuration with --config!"); + NS_FATAL_ERROR("Please specify a non-empty, JSON formatted configuration with --config!"); } - // open configuration file and decode JSON data - m_configFilePtr = fopen (configFilePath.c_str (), "rb"); - if (m_configFilePtr == nullptr) + // open configuration file and decode JSON data + m_configFilePtr = fopen(configFilePath.c_str(), "rb"); + if (m_configFilePtr == nullptr) { - NS_FATAL_ERROR ("Cannot open " << configFilePath << ": " << std::strerror (errno)); + NS_FATAL_ERROR("Cannot open " << configFilePath << ": " << std::strerror(errno)); } - rapidjson::FileReadStream jsonFileStream (m_configFilePtr, - configFileBuffer, - configFileBufferSize); - m_config.ParseStream (jsonFileStream); + rapidjson::FileReadStream jsonFileStream(m_configFilePtr, + configFileBuffer, + configFileBufferSize); + m_config.ParseStream(jsonFileStream); - // close??? + // close??? - NS_ABORT_MSG_IF (m_config.HasParseError (), - "The given configuration schema is not valid JSON: " - << rapidjson::GetParseError_En(m_config.GetParseError ())); + NS_ABORT_MSG_IF(m_config.HasParseError(), + "The given configuration schema is not valid JSON: " + << rapidjson::GetParseError_En(m_config.GetParseError())); } void -ScenarioConfigurationHelper::DisposeConfiguration () +ScenarioConfigurationHelper::DisposeConfiguration() { - if (m_configFilePtr != nullptr) + if (m_configFilePtr != nullptr) { - std::fclose (m_configFilePtr); + std::fclose(m_configFilePtr); } } void -ScenarioConfigurationHelper::InitializeLogging (const bool &onFile) +ScenarioConfigurationHelper::InitializeLogging(const bool& onFile) { - EnableLogComponents (); + EnableLogComponents(); - if (onFile) + if (onFile) { - m_out = std::ofstream (GetLoggingFilePath ()); - std::clog.rdbuf (m_out.rdbuf ()); + m_out = std::ofstream(GetLoggingFilePath()); + std::clog.rdbuf(m_out.rdbuf()); } - NS_LOG_INFO ("####"); - NS_LOG_INFO ("# Drone Simulation"); - NS_LOG_INFO ("# Scenario: " << GetName ()); - NS_LOG_INFO ("# Date: " << GetCurrentDateTime ()); - NS_LOG_INFO ("####"); + NS_LOG_INFO("####"); + NS_LOG_INFO("# Drone Simulation"); + NS_LOG_INFO("# Scenario: " << GetName()); + NS_LOG_INFO("# Date: " << GetCurrentDateTime()); + NS_LOG_INFO("####"); - NS_LOG_LOGIC ("Number of drones: " << GetN ("drones")); - NS_LOG_LOGIC ("Number of ZSPs: " << GetN ("ZSPs")); - NS_LOG_LOGIC ("Number of plain nodes: " << GetN ("nodes")); - NS_LOG_LOGIC ("Number of remotes: " << GetN ("remotes")); - NS_LOG_LOGIC ("Duration: " << GetDuration () << "s"); + NS_LOG_LOGIC("Number of drones: " << GetN("drones")); + NS_LOG_LOGIC("Number of ZSPs: " << GetN("ZSPs")); + NS_LOG_LOGIC("Number of plain nodes: " << GetN("nodes")); + NS_LOG_LOGIC("Number of remotes: " << GetN("remotes")); + NS_LOG_LOGIC("Duration: " << GetDuration() << "s"); } void -ScenarioConfigurationHelper::DisposeLogging () +ScenarioConfigurationHelper::DisposeLogging() { - std::clog.rdbuf (std::cout.rdbuf ()); - m_out.close (); + std::clog.rdbuf(std::cout.rdbuf()); + m_out.close(); } void -ScenarioConfigurationHelper::EnableLogComponents () const +ScenarioConfigurationHelper::EnableLogComponents() const { - if (m_config.HasMember ("logComponents")) + if (m_config.HasMember("logComponents")) { - NS_ASSERT_MSG (m_config["logComponents"].IsArray (), - "'logComponents' property must be an array."); + NS_ASSERT_MSG(m_config["logComponents"].IsArray(), + "'logComponents' property must be an array."); - for (auto i = m_config["logComponents"].Begin (); - i != m_config["logComponents"].End (); - i++) + for (auto i = m_config["logComponents"].Begin(); i != m_config["logComponents"].End(); i++) { - NS_ASSERT_MSG ((*i).IsString (), - "'logComponents' elements must be strings."); - LogComponentEnable ((*i).GetString (), LOG_ALL); + NS_ASSERT_MSG((*i).IsString(), "'logComponents' elements must be strings."); + LogComponentEnable((*i).GetString(), LOG_ALL); } } - LogComponentEnableAll (LOG_PREFIX_ALL); + LogComponentEnableAll(LOG_PREFIX_ALL); } const uint32_t -ScenarioConfigurationHelper::GetAntennasN () const +ScenarioConfigurationHelper::GetAntennasN() const { - NS_ASSERT (m_config.HasMember ("antennas")); - NS_ASSERT (m_config["antennas"].IsArray ()); - NS_ASSERT_MSG (m_config["antennas"].Size () > 0, - "Please define at least one antenna in configuration file."); + NS_ASSERT(m_config.HasMember("antennas")); + NS_ASSERT(m_config["antennas"].IsArray()); + NS_ASSERT_MSG(m_config["antennas"].Size() > 0, + "Please define at least one antenna in configuration file."); - return m_config["antennas"].Size (); + return m_config["antennas"].Size(); } void -ScenarioConfigurationHelper::GetAntennasPosition (Ptr allocator) const +ScenarioConfigurationHelper::GetAntennasPosition(Ptr allocator) const { - for (auto i = m_config["antennas"].Begin (); i != m_config["antennas"].End (); i++) + for (auto i = m_config["antennas"].Begin(); i != m_config["antennas"].End(); i++) { - NS_ASSERT_MSG (i->IsObject (), - "Each antenna must be a JSON object."); - NS_ASSERT_MSG (i->HasMember ("position"), - "One or more antennas do not have defined position."); - - NS_ASSERT_MSG ((*i)["position"].IsArray () - && (*i)["position"].Size () == 3 - && (*i)["position"][0].IsDouble () - && (*i)["position"][1].IsDouble () - && (*i)["position"][2].IsDouble (), - "Please check that each antenna position is an array of 3 doubles."); - - Vector v ((*i)["position"][0].GetDouble (), - (*i)["position"][1].GetDouble (), - (*i)["position"][2].GetDouble ()); - - NS_LOG_LOGIC ("Allocating an antenna in space at " << v); - allocator->Add (v); + NS_ASSERT_MSG(i->IsObject(), "Each antenna must be a JSON object."); + NS_ASSERT_MSG(i->HasMember("position"), + "One or more antennas do not have defined position."); + + NS_ASSERT_MSG((*i)["position"].IsArray() && (*i)["position"].Size() == 3 && + (*i)["position"][0].IsDouble() && (*i)["position"][1].IsDouble() && + (*i)["position"][2].IsDouble(), + "Please check that each antenna position is an array of 3 doubles."); + + Vector v((*i)["position"][0].GetDouble(), + (*i)["position"][1].GetDouble(), + (*i)["position"][2].GetDouble()); + + NS_LOG_LOGIC("Allocating an antenna in space at " << v); + allocator->Add(v); } } const uint32_t -ScenarioConfigurationHelper::GetRemotesN () const +ScenarioConfigurationHelper::GetRemotesN() const { - if (!m_config.HasMember ("remotes")) - return 0; + if (!m_config.HasMember("remotes")) + return 0; - NS_ASSERT_MSG (m_config["remotes"].IsArray (), - "JSON property 'remotes' must be an array."); + NS_ASSERT_MSG(m_config["remotes"].IsArray(), "JSON property 'remotes' must be an array."); - return m_config["remotes"].Size (); + return m_config["remotes"].Size(); } const double -ScenarioConfigurationHelper::GetRemoteApplicationStartTime (uint32_t i) const +ScenarioConfigurationHelper::GetRemoteApplicationStartTime(uint32_t i) const { - const auto remotes = m_config["remotes"].GetArray (); - const auto remote = remotes[i].GetObject (); + const auto remotes = m_config["remotes"].GetArray(); + const auto remote = remotes[i].GetObject(); - if (remote.HasMember ("applicationStartTime") && remote["applicationStartTime"].IsDouble ()) + if (remote.HasMember("applicationStartTime") && remote["applicationStartTime"].IsDouble()) { - return remote["applicationStartTime"].GetDouble (); + return remote["applicationStartTime"].GetDouble(); } - else + else { - return 0.0; + return 0.0; } } const double -ScenarioConfigurationHelper::GetRemoteApplicationStopTime (uint32_t i) const +ScenarioConfigurationHelper::GetRemoteApplicationStopTime(uint32_t i) const { - const auto remotes = m_config["remotes"].GetArray (); - const auto remote = remotes[i].GetObject (); + const auto remotes = m_config["remotes"].GetArray(); + const auto remote = remotes[i].GetObject(); - if (remote.HasMember ("applicationStopTime") && remote["applicationStopTime"].IsDouble ()) + if (remote.HasMember("applicationStopTime") && remote["applicationStopTime"].IsDouble()) { - return remote["applicationStopTime"].GetDouble (); + return remote["applicationStopTime"].GetDouble(); } - else + else { - return GetDuration (); + return GetDuration(); } } -const std::vector > -ScenarioConfigurationHelper::GetGlobalSettings () const +const std::vector> +ScenarioConfigurationHelper::GetGlobalSettings() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - std::vector > settings; + std::vector> settings; - if (m_config.HasMember ("settings")) + if (m_config.HasMember("settings")) { - NS_ASSERT (m_config["settings"].IsArray ()); + NS_ASSERT(m_config["settings"].IsArray()); - NS_ASSERT_MSG (m_config["settings"].Size () % 2 == 0, - "Check \"settings\": elements in list are not an even number, something is missing."); + NS_ASSERT_MSG( + m_config["settings"].Size() % 2 == 0, + "Check \"settings\": elements in list are not an even number, something is missing."); - for (auto i = m_config["settings"].Begin (); i != m_config["settings"].End (); i += 2) + for (auto i = m_config["settings"].Begin(); i != m_config["settings"].End(); i += 2) { - NS_ASSERT ((*i).IsString ()); - NS_ASSERT ((*(i + 1)).IsString ()); + NS_ASSERT((*i).IsString()); + NS_ASSERT((*(i + 1)).IsString()); - if ((*i).GetString ()[0] == '/') + if ((*i).GetString()[0] == '/') { - continue; + continue; } - settings.push_back ({(*i).GetString (), (*(i + 1)).GetString ()}); + settings.push_back({(*i).GetString(), (*(i + 1)).GetString()}); } } - return settings; + return settings; } -const std::vector > -ScenarioConfigurationHelper::GetIndividualSettings () const +const std::vector> +ScenarioConfigurationHelper::GetIndividualSettings() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - std::vector > settings; + std::vector> settings; - if (m_config.HasMember ("settings")) + if (m_config.HasMember("settings")) { - NS_ASSERT (m_config["settings"].IsArray ()); + NS_ASSERT(m_config["settings"].IsArray()); - NS_ASSERT_MSG (m_config["settings"].Size () % 2 == 0, - "Check \"settings\": elements in list are not an even number, something is missing."); + NS_ASSERT_MSG( + m_config["settings"].Size() % 2 == 0, + "Check \"settings\": elements in list are not an even number, something is missing."); - for (auto i = m_config["settings"].Begin (); i != m_config["settings"].End (); i += 2) + for (auto i = m_config["settings"].Begin(); i != m_config["settings"].End(); i += 2) { - NS_ASSERT ((*i).IsString ()); - NS_ASSERT ((*(i + 1)).IsString ()); + NS_ASSERT((*i).IsString()); + NS_ASSERT((*(i + 1)).IsString()); - if ((*i).GetString ()[0] != '/') + if ((*i).GetString()[0] != '/') { - continue; + continue; } - settings.push_back ({(*i).GetString (), (*(i + 1)).GetString ()}); + settings.push_back({(*i).GetString(), (*(i + 1)).GetString()}); } } - return settings; + return settings; } -const std::vector > -ScenarioConfigurationHelper::GetBuildings () const +const std::vector> +ScenarioConfigurationHelper::GetBuildings() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - std::vector > buildings; + std::vector> buildings; - NS_ASSERT_MSG (m_config.HasMember ("world"), - "'world' definition is missing from the JSON file."); - NS_ASSERT_MSG (m_config["world"].IsObject (), - "'world' defined in the JSON configuration must be an object."); + NS_ASSERT_MSG(m_config.HasMember("world"), "'world' definition is missing from the JSON file."); + NS_ASSERT_MSG(m_config["world"].IsObject(), + "'world' defined in the JSON configuration must be an object."); - if (m_config["world"].HasMember ("buildings") == false) + if (m_config["world"].HasMember("buildings") == false) { - return buildings; + return buildings; } - NS_ASSERT_MSG (m_config["world"]["buildings"].IsArray (), - "'buildings' needs to be an array of objects, check the configuration file."); + NS_ASSERT_MSG(m_config["world"]["buildings"].IsArray(), + "'buildings' needs to be an array of objects, check the configuration file."); - auto arr = m_config["world"]["buildings"].GetArray (); + auto arr = m_config["world"]["buildings"].GetArray(); - for (auto b = arr.Begin (); b != arr.End (); ++b) + for (auto b = arr.Begin(); b != arr.End(); ++b) { - Ptr building = CreateObject (); + Ptr building = CreateObject(); - NS_ASSERT_MSG (b->HasMember ("boundaries") && (*b)["boundaries"].IsArray () && (*b)["boundaries"].Size () == 6, - "'boundaries' must be defined as an array of 6 doubles for each building."); - auto bounds = (*b)["boundaries"].GetArray (); - for (uint8_t i = 0; i < 6; ++i) + NS_ASSERT_MSG(b->HasMember("boundaries") && (*b)["boundaries"].IsArray() && + (*b)["boundaries"].Size() == 6, + "'boundaries' must be defined as an array of 6 doubles for each building."); + auto bounds = (*b)["boundaries"].GetArray(); + for (uint8_t i = 0; i < 6; ++i) { - NS_ASSERT_MSG (bounds[i].IsDouble (), "'boundaries' elements must be doubles."); + NS_ASSERT_MSG(bounds[i].IsDouble(), "'boundaries' elements must be doubles."); } - building->SetBoundaries (Box (bounds[0].GetDouble (), bounds[1].GetDouble (), - bounds[2].GetDouble (), bounds[3].GetDouble (), - bounds[4].GetDouble (), bounds[5].GetDouble ())); - - if (b->HasMember ("type")) + building->SetBoundaries(Box(bounds[0].GetDouble(), + bounds[1].GetDouble(), + bounds[2].GetDouble(), + bounds[3].GetDouble(), + bounds[4].GetDouble(), + bounds[5].GetDouble())); + + if (b->HasMember("type")) { - auto type = std::string ((*b)["type"].GetString ()); - NS_ASSERT_MSG (type == "residential" || type == "office" || type == "commercial", - "Unknown type of building: '" << type << "'."); - if (type == "residential") + auto type = std::string((*b)["type"].GetString()); + NS_ASSERT_MSG(type == "residential" || type == "office" || type == "commercial", + "Unknown type of building: '" << type << "'."); + if (type == "residential") { - building->SetBuildingType (Building::Residential); + building->SetBuildingType(Building::Residential); } - if (type == "office") + if (type == "office") { - building->SetBuildingType (Building::Office); + building->SetBuildingType(Building::Office); } - if (type == "commercial") + if (type == "commercial") { - building->SetBuildingType (Building::Commercial); + building->SetBuildingType(Building::Commercial); } } - if (b->HasMember ("walls")) + if (b->HasMember("walls")) { - auto walls = std::string ((*b)["walls"].GetString ()); - NS_ASSERT_MSG (walls == "wood" || walls == "concreteWithWindows" || walls == "concreteWithoutWindows" || walls == "stoneBlocks", - "Unknown type of walls for a building: '" << walls << "'."); - if (walls == "wood") + auto walls = std::string((*b)["walls"].GetString()); + NS_ASSERT_MSG(walls == "wood" || walls == "concreteWithWindows" || + walls == "concreteWithoutWindows" || walls == "stoneBlocks", + "Unknown type of walls for a building: '" << walls << "'."); + if (walls == "wood") { - building->SetExtWallsType (Building::Wood); + building->SetExtWallsType(Building::Wood); } - if (walls == "concreteWithWindows") + if (walls == "concreteWithWindows") { - building->SetExtWallsType (Building::ConcreteWithWindows); + building->SetExtWallsType(Building::ConcreteWithWindows); } - if (walls == "concreteWithoutWindows") + if (walls == "concreteWithoutWindows") { - building->SetExtWallsType (Building::ConcreteWithoutWindows); + building->SetExtWallsType(Building::ConcreteWithoutWindows); } - if (walls == "stoneBlocks") + if (walls == "stoneBlocks") { - building->SetExtWallsType (Building::StoneBlocks); + building->SetExtWallsType(Building::StoneBlocks); } } - if (b->HasMember ("floors")) + if (b->HasMember("floors")) { - NS_ASSERT_MSG ((*b)["floors"].IsInt (), "'floors' must be an integer."); - building->SetNFloors ((*b)["floors"].GetInt ()); + NS_ASSERT_MSG((*b)["floors"].IsInt(), "'floors' must be an integer."); + building->SetNFloors((*b)["floors"].GetInt()); } - if (b->HasMember ("rooms")) + if (b->HasMember("rooms")) { - auto rooms = (*b)["rooms"].GetArray (); - NS_ASSERT_MSG (rooms.Size () == 2 && rooms[0].IsInt () && rooms[1].IsInt (), - "'rooms' needs to be an array of 2 integers."); - building->SetNRoomsX (rooms[0].GetInt ()); - building->SetNRoomsY (rooms[1].GetInt ()); + auto rooms = (*b)["rooms"].GetArray(); + NS_ASSERT_MSG(rooms.Size() == 2 && rooms[0].IsInt() && rooms[1].IsInt(), + "'rooms' needs to be an array of 2 integers."); + building->SetNRoomsX(rooms[0].GetInt()); + building->SetNRoomsY(rooms[1].GetInt()); } - buildings.push_back (building); + buildings.push_back(building); } - return buildings; + return buildings; } const std::string -ScenarioConfigurationHelper::GetDroneMobilityModel (uint32_t n) const +ScenarioConfigurationHelper::GetDroneMobilityModel(uint32_t n) const { - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[n].GetObject (); + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[n].GetObject(); - if (drone.HasMember ("mobilityModel") && drone["mobilityModel"].IsString ()) + if (drone.HasMember("mobilityModel") && drone["mobilityModel"].IsString()) { - return drone["mobilityModel"].GetString (); + return drone["mobilityModel"].GetString(); } - return ""; + return ""; } const Vector -ScenarioConfigurationHelper::GetDronePosition (uint32_t n) const +ScenarioConfigurationHelper::GetDronePosition(uint32_t n) const { - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[n].GetObject (); + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[n].GetObject(); - NS_ASSERT_MSG (GetDroneMobilityModel (n) == "ns3::ConstantPositionMobilityModel" - || GetDronesMobilityModel () == "ns3::ConstantPositionMobilityModel", - "Drone position parameter can be used only when the mobility model is ns3::ConstantPositionMobilityModel"); + NS_ASSERT_MSG(GetDroneMobilityModel(n) == "ns3::ConstantPositionMobilityModel" || + GetDronesMobilityModel() == "ns3::ConstantPositionMobilityModel", + "Drone position parameter can be used only when the mobility model is " + "ns3::ConstantPositionMobilityModel"); - NS_ASSERT_MSG (drone.HasMember ("position"), - "Drone #" << n << " does not have a position defined."); + NS_ASSERT_MSG(drone.HasMember("position"), + "Drone #" << n << " does not have a position defined."); - NS_ASSERT_MSG (drone["position"].IsArray () - && drone["position"].Size () == 3 - && drone["position"][0].IsDouble () - && drone["position"][1].IsDouble () - && drone["position"][2].IsDouble (), - "Please check that drone #" << n << " position is an array of 3 doubles."); + NS_ASSERT_MSG(drone["position"].IsArray() && drone["position"].Size() == 3 && + drone["position"][0].IsDouble() && drone["position"][1].IsDouble() && + drone["position"][2].IsDouble(), + "Please check that drone #" << n << " position is an array of 3 doubles."); - Vector v (drone["position"][0].GetDouble (), - drone["position"][1].GetDouble (), - drone["position"][2].GetDouble ()); + Vector v(drone["position"][0].GetDouble(), + drone["position"][1].GetDouble(), + drone["position"][2].GetDouble()); - return v; + return v; } const std::string -ScenarioConfigurationHelper::GetObjectName (const char* field, uint32_t index) const +ScenarioConfigurationHelper::GetObjectName(const char* field, uint32_t index) const { - NS_ASSERT (index < m_config[field].GetArray ().Size ()); - return m_config[field].GetArray ()[index].GetObject ()["name"].GetString (); + NS_ASSERT(index < m_config[field].GetArray().Size()); + return m_config[field].GetArray()[index].GetObject()["name"].GetString(); } const uint32_t -ScenarioConfigurationHelper::GetObjectIndex (const char* field, const std::string& name) const +ScenarioConfigurationHelper::GetObjectIndex(const char* field, const std::string& name) const { - auto array = m_config[field].GetArray (); - for (uint32_t i = 0; i < array.Size (); i++) + auto array = m_config[field].GetArray(); + for (uint32_t i = 0; i < array.Size(); i++) { - std::string objName = array[i].GetObject ()["name"].GetString (); - if (objName == name) + std::string objName = array[i].GetObject()["name"].GetString(); + if (objName == name) { - return i; + return i; } } - //NS_LOG_ERROR("No element found with name \"" << name << "\" in field \"" << field << "\"."); - return array.Size (); + // NS_LOG_ERROR("No element found with name \"" << name << "\" in field \"" << field << "\"."); + return array.Size(); } const std::vector -ScenarioConfigurationHelper::GetDroneNetworks (uint32_t id) const +ScenarioConfigurationHelper::GetDroneNetworks(uint32_t id) const { - const auto drones = m_config["drones"].GetArray (); - const auto drone = drones[id].GetObject (); + const auto drones = m_config["drones"].GetArray(); + const auto drone = drones[id].GetObject(); - NS_ASSERT_MSG (drone.HasMember ("interfaces"), - "The drone " << id << " has no key \"interfaces\"."); + NS_ASSERT_MSG(drone.HasMember("interfaces"), + "The drone " << id << " has no key \"interfaces\"."); - const auto nets = drone["interfaces"].GetArray (); + const auto nets = drone["interfaces"].GetArray(); - std::vector droneNetworks; + std::vector droneNetworks; - for (auto net = nets.Begin (); net != nets.End (); net++) + for (auto net = nets.Begin(); net != nets.End(); net++) { - if (net->IsInt ()) + if (net->IsInt()) { - droneNetworks.push_back (net->GetUint ()); + droneNetworks.push_back(net->GetUint()); } - else if (net->IsString ()) + else if (net->IsString()) { - droneNetworks.push_back (GetObjectIndex ("networks", net->GetString ())); + droneNetworks.push_back(GetObjectIndex("networks", net->GetString())); } - else + else { - NS_LOG_ERROR ("A network in array is neither a string nor an integer."); + NS_LOG_ERROR("A network in array is neither a string nor an integer."); } } - return droneNetworks; + return droneNetworks; } const std::vector -ScenarioConfigurationHelper::GetDroneNetworks (const std::string& name) const +ScenarioConfigurationHelper::GetDroneNetworks(const std::string& name) const { - return GetDroneNetworks (GetObjectIndex ("drones", name)); + return GetDroneNetworks(GetObjectIndex("drones", name)); } const std::vector -ScenarioConfigurationHelper::GetAntennaNetworks (uint32_t id) const +ScenarioConfigurationHelper::GetAntennaNetworks(uint32_t id) const { - const auto antennas = m_config["antennas"].GetArray (); - const auto antenna = antennas[id].GetObject (); + const auto antennas = m_config["antennas"].GetArray(); + const auto antenna = antennas[id].GetObject(); - NS_ASSERT_MSG (antenna.HasMember ("interfaces"), - "The antenna " << id << " has no key \"interfaces\"."); + NS_ASSERT_MSG(antenna.HasMember("interfaces"), + "The antenna " << id << " has no key \"interfaces\"."); - const auto nets = antenna["interfaces"].GetArray (); + const auto nets = antenna["interfaces"].GetArray(); - std::vector antennaNetworks; + std::vector antennaNetworks; - for (auto net = nets.Begin (); net != nets.End (); net++) + for (auto net = nets.Begin(); net != nets.End(); net++) { - if (net->IsInt ()) + if (net->IsInt()) { - antennaNetworks.push_back (net->GetUint ()); + antennaNetworks.push_back(net->GetUint()); } - else if (net->IsString ()) + else if (net->IsString()) { - antennaNetworks.push_back (GetObjectIndex ("networks", net->GetString ())); + antennaNetworks.push_back(GetObjectIndex("networks", net->GetString())); } - else + else { - NS_LOG_ERROR ("A network in array is neither a string nor an integer."); + NS_LOG_ERROR("A network in array is neither a string nor an integer."); } } - return antennaNetworks; + return antennaNetworks; } const std::vector -ScenarioConfigurationHelper::GetAntennaNetworks (const std::string& name) const +ScenarioConfigurationHelper::GetAntennaNetworks(const std::string& name) const { - return GetAntennaNetworks (GetObjectIndex ("antennas", name)); + return GetAntennaNetworks(GetObjectIndex("antennas", name)); } const std::vector -ScenarioConfigurationHelper::GetDronesInNetwork (uint32_t id) const +ScenarioConfigurationHelper::GetDronesInNetwork(uint32_t id) const { - std::vector dronesInNet; - auto drones = m_config["drones"].GetArray (); - for (uint32_t i = 0; i < drones.Size (); i++) + std::vector dronesInNet; + auto drones = m_config["drones"].GetArray(); + for (uint32_t i = 0; i < drones.Size(); i++) { - auto nets = drones[i].GetObject ()["interfaces"].GetArray (); - for (auto el = nets.Begin (); el != nets.End (); el++) + auto nets = drones[i].GetObject()["interfaces"].GetArray(); + for (auto el = nets.Begin(); el != nets.End(); el++) { - if ( (el->IsInt () && el->GetUint () == id) - || (el->IsString () && GetObjectIndex ("networks", el->GetString ()) == id) ) + if ((el->IsInt() && el->GetUint() == id) || + (el->IsString() && GetObjectIndex("networks", el->GetString()) == id)) { - dronesInNet.push_back (i); + dronesInNet.push_back(i); } } } - return dronesInNet; + return dronesInNet; } const std::vector -ScenarioConfigurationHelper::GetDronesInNetwork (const std::string& net_name) const +ScenarioConfigurationHelper::GetDronesInNetwork(const std::string& net_name) const { - return GetDronesInNetwork (GetObjectIndex ("networks", net_name)); + return GetDronesInNetwork(GetObjectIndex("networks", net_name)); } const std::vector -ScenarioConfigurationHelper::GetAntennasInNetwork (uint32_t id) const +ScenarioConfigurationHelper::GetAntennasInNetwork(uint32_t id) const { - std::vector antennasInNet; - auto antennas = m_config["antennas"].GetArray (); - for (uint32_t i = 0; i < antennas.Size (); i++) + std::vector antennasInNet; + auto antennas = m_config["antennas"].GetArray(); + for (uint32_t i = 0; i < antennas.Size(); i++) { - auto nets = antennas[i].GetObject ()["interfaces"].GetArray (); - for (auto el = nets.Begin (); el != nets.End (); el++) + auto nets = antennas[i].GetObject()["interfaces"].GetArray(); + for (auto el = nets.Begin(); el != nets.End(); el++) { - if ( (el->IsInt () && el->GetUint () == id) - || (el->IsString () && GetObjectIndex ("networks", el->GetString ()) == id) ) + if ((el->IsInt() && el->GetUint() == id) || + (el->IsString() && GetObjectIndex("networks", el->GetString()) == id)) { - antennasInNet.push_back (i); + antennasInNet.push_back(i); } } } - return antennasInNet; + return antennasInNet; } const std::vector -ScenarioConfigurationHelper::GetAntennasInNetwork (const std::string& net_name) const +ScenarioConfigurationHelper::GetAntennasInNetwork(const std::string& net_name) const { - return GetAntennasInNetwork (GetObjectIndex ("networks", net_name)); + return GetAntennasInNetwork(GetObjectIndex("networks", net_name)); } const uint32_t -ScenarioConfigurationHelper::RadioMap () const +ScenarioConfigurationHelper::RadioMap() const { - return m_radioMap; + return m_radioMap; } -const std::vector > -ScenarioConfigurationHelper::GetRadioMapParameters () const +const std::vector> +ScenarioConfigurationHelper::GetRadioMapParameters() const { - std::vector > parameters; - NS_ASSERT_MSG (m_config.HasMember ("radioMapParameters"), - "'radioMapParameters' key is not present in the configuration file."); + std::vector> parameters; + NS_ASSERT_MSG(m_config.HasMember("radioMapParameters"), + "'radioMapParameters' key is not present in the configuration file."); - NS_ASSERT_MSG (m_config["radioMapParameters"].IsArray () && m_config["radioMapParameters"].Size () % 2 == 0, - "Check 'radioMapParameters': should be an array of even number elements."); + NS_ASSERT_MSG(m_config["radioMapParameters"].IsArray() && + m_config["radioMapParameters"].Size() % 2 == 0, + "Check 'radioMapParameters': should be an array of even number elements."); - for (auto i = m_config["radioMapParameters"].Begin (); i != m_config["radioMapParameters"].End (); i += 2) + for (auto i = m_config["radioMapParameters"].Begin(); i != m_config["radioMapParameters"].End(); + i += 2) { - NS_ASSERT ((*i).IsString ()); - NS_ASSERT ((*(i + 1)).IsString ()); + NS_ASSERT((*i).IsString()); + NS_ASSERT((*(i + 1)).IsString()); - parameters.push_back ({(*i).GetString (), (*(i + 1)).GetString ()}); + parameters.push_back({(*i).GetString(), (*(i + 1)).GetString()}); } - return parameters; + return parameters; } const std::string -ScenarioConfigurationHelper::MakePath (const std::string& path1, const std::string& path2 /* ="" */) const +ScenarioConfigurationHelper::MakePath(const std::string& path1, + const std::string& path2 /* ="" */) const { - std::string npath (path1); - if (npath.at (0) != '/') + std::string npath(path1); + if (npath.at(0) != '/') { - npath.insert (0, "/"); + npath.insert(0, "/"); } - if (!path2.empty ()) + if (!path2.empty()) { - if (npath.back () != '/') + if (npath.back() != '/') { - npath.push_back ('/'); + npath.push_back('/'); } - npath.append (path2); + npath.append(path2); } - if (npath.back () == '/') + if (npath.back() == '/') { - npath.pop_back (); + npath.pop_back(); } - return npath; + return npath; } const std::string -ScenarioConfigurationHelper::MakePath (const std::string& path, uint32_t index) const +ScenarioConfigurationHelper::MakePath(const std::string& path, uint32_t index) const { - return MakePath (path, std::to_string (index)); + return MakePath(path, std::to_string(index)); } bool -ScenarioConfigurationHelper::CheckPath (const std::string& path) const +ScenarioConfigurationHelper::CheckPath(const std::string& path) const { - return rapidjson::Pointer (MakePath (path).c_str ()).Get (m_config) != nullptr; + return rapidjson::Pointer(MakePath(path).c_str()).Get(m_config) != nullptr; } const std::pair -ScenarioConfigurationHelper::GetInt (const std::string& path) const +ScenarioConfigurationHelper::GetInt(const std::string& path) const { - const rapidjson::Value* value = rapidjson::Pointer (MakePath (path).c_str ()).Get (m_config); - if (value == nullptr) + const rapidjson::Value* value = rapidjson::Pointer(MakePath(path).c_str()).Get(m_config); + if (value == nullptr) { - return std::make_pair (false, 0); + return std::make_pair(false, 0); } - NS_ASSERT_MSG (value->IsInt (), "Object at path '" << path << "' is not an integer"); + NS_ASSERT_MSG(value->IsInt(), "Object at path '" << path << "' is not an integer"); - return std::make_pair (true, value->GetInt ()); + return std::make_pair(true, value->GetInt()); } const std::pair -ScenarioConfigurationHelper::GetUint (const std::string& path) const +ScenarioConfigurationHelper::GetUint(const std::string& path) const { - const rapidjson::Value* value = rapidjson::Pointer (MakePath (path).c_str ()).Get (m_config); - if (value == nullptr) + const rapidjson::Value* value = rapidjson::Pointer(MakePath(path).c_str()).Get(m_config); + if (value == nullptr) { - return std::make_pair (false, 0); + return std::make_pair(false, 0); } - NS_ASSERT_MSG (value->IsUint (), "Object at path '" << path << "' is not an unsigned integer"); + NS_ASSERT_MSG(value->IsUint(), "Object at path '" << path << "' is not an unsigned integer"); - return std::make_pair (true, value->GetUint ()); + return std::make_pair(true, value->GetUint()); } const std::pair -ScenarioConfigurationHelper::GetDouble (const std::string& path) const +ScenarioConfigurationHelper::GetDouble(const std::string& path) const { - const rapidjson::Value* value = rapidjson::Pointer (MakePath (path).c_str ()).Get (m_config); - if (value == nullptr) + const rapidjson::Value* value = rapidjson::Pointer(MakePath(path).c_str()).Get(m_config); + if (value == nullptr) { - return std::make_pair (false, 0.0); + return std::make_pair(false, 0.0); } - NS_ASSERT_MSG (value->IsDouble (), "Object at path '" << path << "' is not a double"); + NS_ASSERT_MSG(value->IsDouble(), "Object at path '" << path << "' is not a double"); - return std::make_pair (true, value->GetDouble ()); + return std::make_pair(true, value->GetDouble()); } const std::pair -ScenarioConfigurationHelper::GetBool (const std::string& path) const +ScenarioConfigurationHelper::GetBool(const std::string& path) const { - const rapidjson::Value* value = rapidjson::Pointer (MakePath (path).c_str ()).Get (m_config); - if (value == nullptr) + const rapidjson::Value* value = rapidjson::Pointer(MakePath(path).c_str()).Get(m_config); + if (value == nullptr) { - return std::make_pair (false, false); + return std::make_pair(false, false); } - NS_ASSERT_MSG (value->IsBool (), "Object at path '" << path << "' is not a boolean"); + NS_ASSERT_MSG(value->IsBool(), "Object at path '" << path << "' is not a boolean"); - return std::make_pair (true, value->GetBool ()); + return std::make_pair(true, value->GetBool()); } const std::pair -ScenarioConfigurationHelper::GetString (const std::string& path) const +ScenarioConfigurationHelper::GetString(const std::string& path) const { - const rapidjson::Value* value = rapidjson::Pointer (MakePath (path).c_str ()).Get (m_config); - if (value == nullptr) + const rapidjson::Value* value = rapidjson::Pointer(MakePath(path).c_str()).Get(m_config); + if (value == nullptr) { - return std::make_pair (false, ""); + return std::make_pair(false, ""); } - NS_ASSERT_MSG (value->IsString (), "Object at path '" << path << "' is not a string"); + NS_ASSERT_MSG(value->IsString(), "Object at path '" << path << "' is not a string"); - return std::make_pair (true, value->GetString ()); + return std::make_pair(true, value->GetString()); } const std::vector ScenarioConfigurationHelper::GetRegionsOfInterest() const { - std::vector final_regions; + std::vector final_regions; - if (!m_config.HasMember ("world")) - return final_regions; + if (!m_config.HasMember("world")) + return final_regions; - const auto world = m_config["world"].GetObject (); - if (world.HasMember ("regionsOfInterest")) - { - const auto regions = world["regionsOfInterest"].GetArray(); - for (auto region = regions.Begin (); region != regions.End (); region++) + const auto world = m_config["world"].GetObject(); + if (world.HasMember("regionsOfInterest")) { - const auto xMin = (*region)[0].GetDouble(); - const auto xMax = (*region)[1].GetDouble(); - const auto yMin = (*region)[2].GetDouble(); - const auto yMax = (*region)[3].GetDouble(); - const auto zMin = (*region)[4].GetDouble(); - const auto zMax = (*region)[5].GetDouble(); - final_regions.push_back(DoubleVector({ - xMin,xMax,yMin,yMax,zMin,zMax - })); + const auto regions = world["regionsOfInterest"].GetArray(); + for (auto region = regions.Begin(); region != regions.End(); region++) + { + const auto xMin = (*region)[0].GetDouble(); + const auto xMax = (*region)[1].GetDouble(); + const auto yMin = (*region)[2].GetDouble(); + const auto yMax = (*region)[3].GetDouble(); + const auto zMin = (*region)[4].GetDouble(); + const auto zMax = (*region)[5].GetDouble(); + final_regions.push_back(DoubleVector({xMin, xMax, yMin, yMax, zMin, zMax})); + } } - } - return final_regions; + return final_regions; } } // namespace ns3 diff --git a/src/configuration/helper/scenario-configuration-helper.h b/src/configuration/helper/scenario-configuration-helper.h index 5b13fbd..33970b8 100644 --- a/src/configuration/helper/scenario-configuration-helper.h +++ b/src/configuration/helper/scenario-configuration-helper.h @@ -18,29 +18,28 @@ #ifndef SCENARIO_CONFIGURATION_HELPER_H #define SCENARIO_CONFIGURATION_HELPER_H -#include -#include -#include - #include -#include -#include -#include -#include - -#include - #include #include #include +#include #include #include #include +#include #include +#include +#include -#define CONFIGURATOR ScenarioConfigurationHelper::Get () +#include +#include +#include +#include -namespace ns3 { +#define CONFIGURATOR ScenarioConfigurationHelper::Get() + +namespace ns3 +{ /** * \brief Configuration Helper for a scenario. @@ -52,438 +51,441 @@ namespace ns3 { */ class ScenarioConfigurationHelper : public Singleton { -public: - /** - * \brief default destructor - */ - ~ScenarioConfigurationHelper (); - - /** - * \brief Bootstrap Singleton with basic data. - * \param argc The number of command line arguments. - * \param argv The list of command line arguments. - */ - void Initialize (int argc, char ** argv); - - /** - * \brief Bootstrap Singleton with basic data. - * - * \param argc The number of command line arguments. - * \param argv The list of command line arguments. - * \param name The name of the scenario. - */ - void Initialize (int argc, char ** argv, const std::string name); - - /** - * \return The name of the scenario. - */ - const std::string GetName (); - - /** - * \return The current date and time as a human-readable string. - */ - const std::string GetCurrentDateTime () const; - - /** - * \brief Gets the preconfigured path from the configuration file, then makes a new - * folder at /- where to place files - * \return The full path of the folder where to put result files - */ - const std::string GetResultsPath (); - - /** - * \brief Check if the user wants to save trace results or not. - */ - const bool GetLogOnFile() const; - - /** - * \return The file path of the logging file. - */ - const std::string GetLoggingFilePath (); - - /** - * \brief Retrieve Static Configuration Parameters as a key/value pair. - * - * \return Static configuration defined in the configuration file. - */ - const std::vector> GetStaticConfig (); - - /** - * \brief Retrieve the list of PHY Layers defined for this simulation. - * - * \return The list of PHY Layers to be defined for this simulation. - */ - const std::vector> GetPhyLayers () const; - - /** - * \brief Retrieve the list of MAC Layers defined for this simulation. - * - * \return The list of MAC Layers to be defined for this simulation. - */ - const std::vector> GetMacLayers () const; - - /** - * \brief Retrieve the list of Network Layers defined for this simulation. - * - * \return The list of Network Layers to be defined for this simulation. - */ - const std::vector> GetNetworkLayers () const; - - /** - * \brief Retrieve the list of generic enetities to be defined for this simulation. - * - * \return The list of Entities to be defined for this simulation. - */ - const std::vector> GetEntitiesConfiguration (const std::string& entityKey) const; - - /** - * \brief Retrieve the list of remotes to be defined for this simulation. - * - * \return The list of remotes to be defined for this simulation. - */ - const std::vector> GetRemotesConfiguration () const; - - /** - * \return The duration of the simulation in seconds. - */ - const double GetDuration () const; - - /** - * \return The number of entities in the given entityKey category. - */ - std::size_t GetN(const char* entityKey) const; - - /** - * \return The number of plain nodes to be simulated. - */ - std::size_t GetNodesN () const; - -// DRONE RELATED CONFIGURATORS - - /** - * \return the number of drones to be simulated. - */ - const uint32_t GetDronesN () const; - /** - * \return a string identifying the mobility model for the drones. - */ - const std::string GetDronesMobilityModel () const; - /** - * \param n the index of the drone in the list - * \return a string identifying the mobility model of the n-th drone - */ - const std::string GetDroneMobilityModel (uint32_t n) const; - /** - * \param n the index of the drone in the list - * \return a ns3::Vector with the coordinates of the position of the n-th drone - */ - const Vector GetDronePosition (uint32_t n) const; - /** - * \brief allocate the position of the drones (if dronesMobilityModel is - * set to "ns3::ConstantPositionMobilityModel") - * \param allocator the allocator to be filled with drones positions. - */ - void GetDronesPosition (Ptr allocator) const; - /** - * \param n the index of the drone in the list - * \return the list of waypoints of drone with index i - */ - const std::vector GetDroneWaypoints (uint32_t i) const; - /** - * \return the step of the curve to be generated. - */ - const float GetCurveStep () const; - /** - * \param i the drone index number. - * \return the flight plan of drone with index i - */ - const FlightPlan GetDroneFlightPlan (uint32_t i) const; - /** - * \param i the drone index number. - * \return the constant acceleration of the drone with index i. - */ - const double GetDroneAcceleration (uint32_t i) const; - /** - * \param i the drone index number. - * \return the maximum speed of the drone with index i. - */ - const double GetDroneMaxSpeed (uint32_t i) const; - /** - * \param i the drone index number. - * \return the polynomial speed coeffients. - */ - const DoubleVector GetDroneSpeedCoefficients (uint32_t i) const; - /** - * \param i the drone index number. - * \return the instant, in seconds, indicating the start of the application. - */ - const double GetDroneApplicationStartTime (uint32_t i) const; - /** - * \param i the drone index number. - * \return the instant, in seconds, indicating the end of the application. - */ - const double GetDroneApplicationStopTime (uint32_t i) const; - -// WIFI SPECIFIC CONFIGURATORS - - /** - * \return the phy mode for WiFi communications. - */ - const std::string GetPhyMode () const; - /** - * \return the phy path loss to use - */ - const std::string GetPhyPropagationLossModel () const; - /** - * \return the phy parameters - */ - const std::vector > GetThreeLogDistancePropagationLossModelAttributes () const; - - /** - * \return the number of ZSPs to be simulated. - */ - const uint32_t GetZspsN () const; - /** - * \brief allocate the position of the ZSPs - * \param allocator the allocator to be filled with ZSPs positions. - */ - void GetZspsPosition (Ptr allocator) const; - /** - * \param i the ZSP index number. - * \return the instant, in seconds, indicating the start of the application. - */ - const double GetZspApplicationStartTime (uint32_t i) const; - /** - * \param i the ZSP index number. - * \return the instant, in seconds, indicating the end of the application. - */ - const double GetZspApplicationStopTime (uint32_t i) const; - /** - * \return the number of ENBs to be simulated. - */ - const uint32_t GetEnbsN () const; - /** - * \brief allocate the position of the ENBs - * - * \param allocator the allocator to be filled with ENBs positions. - */ - void GetEnbsPosition (Ptr allocator) const; - /** - * \brief Check if dry run is wanted. - */ - const bool IsDryRun () const; - /** - * \return a structure containing points describing regions of interest - */ - const std::vector GetRegionsOfInterest() const; - -// LTE SPECIFIC CONFIGURATORS - - /** - * \return Radio Environment Map generation code, 0 for no generation, 1 for generation, 2 for generation with map plot. - */ - const uint32_t RadioMap () const; - - /** - * \return a list of parameters for the Radio Environment Map generator - */ - const std::vector > GetRadioMapParameters () const; - - /** - * \return the number of antennas to be simulated. - */ - const uint32_t GetAntennasN () const; - /** - * \brief allocate the position of the antennas - * \param allocator the allocator to be filled with antennas positions - */ - void GetAntennasPosition (Ptr allocator) const; - - /** - * \return the number of remote hosts to be simulated. - */ - const uint32_t GetRemotesN () const; - /** - * \param i the remote index number. - * \return the instant, in seconds, indicating the start of the application. - */ - const double GetRemoteApplicationStartTime (uint32_t i) const; - /** - * \param i the remote index number. - * \return the instant, in seconds, indicating the end of the application. - */ - const double GetRemoteApplicationStopTime (uint32_t i) const; - - /** - * \brief Returns a vector with all the global configuration strings for scenario. - * Use with Config::SetDefault(pair.first, pair.second) at the beginning of the script. - * \return a vector of pairs containing the key and the value extracted from config - */ - const std::vector > GetGlobalSettings () const; - /** - * \brief Returns a vector with all the per-object individual settings. - * Use with Config::Set(pair.first, pair.second) after creating all the object before simulation start. - * \return a vector of pairs containing the key and the value extracted from config - */ - const std::vector > GetIndividualSettings () const; - - /** - * \return a vector of Ptr created with the attributes in config - */ - const std::vector > GetBuildings () const; - - /** - * \param field the name of the field to search into - * \param index the index of the element to which retrieve the name - * \return the name associated to the object at the index in the field - */ - const std::string GetObjectName (const char* field, uint32_t index) const; - - /** - * \param field the name of the field to search into - * \param name the name of the element to which retrieve the index - * \return the index of the object of given name - */ - const uint32_t GetObjectIndex (const char* field, const std::string& name) const; - - -// NETWORKS SPECIFIC CONFIGURATORS - - /** - * \param id the index of the drone to query - * \return a list of the network IDs the drone is connected to - */ - const std::vector GetDroneNetworks (uint32_t id) const; - - /** - * \param name the name of the drone to query - * \return a list of the network IDs the drone is connected to - */ - const std::vector GetDroneNetworks (const std::string& name) const; - - /** - * \param id the index of the antenna to query - * \return a list of the network IDs the antenna is connected to - */ - const std::vector GetAntennaNetworks (uint32_t id) const; - - /** - * \param name the name of the antenna to query - * \return a list of the network IDs the antenna is connected to - */ - const std::vector GetAntennaNetworks (const std::string& name) const; - - /** - * \param id the index of the network - * \return a list of id of all the drones connected to a network - */ - const std::vector GetDronesInNetwork (uint32_t id) const; - - /** - * \param net_name the name of the network - * \return a list of id of all the drones connected to a network - */ - const std::vector GetDronesInNetwork (const std::string& net_name) const; - - /** - * \param id the index of the network - * \return a list of id of all the antennas connected to a network - */ - const std::vector GetAntennasInNetwork (uint32_t id) const; - - /** - * \param net_name the name of the network - * \return a list of id of all the antennas connected to a network - */ - const std::vector GetAntennasInNetwork (const std::string& net_name) const; - - -/// General purpose value retrieving methods - - /** - * \param path1 the first part of the path - * \param path2 the second part of the path - * \return the concatenation of those 2 paths adding a '/' if necessary - */ - const std::string MakePath (const std::string& path1, const std::string& path2 = "") const; - - /** - * \param path the first part of the path - * \param index the index of the element at the path - * \return the concatenation of path and index, adding a '/' if necessary - */ - const std::string MakePath (const std::string& path, uint32_t index) const; - - /** - * \param path the path to check in form eg "/parent/children/index/key" - * \return true if the path is valid else false - */ - bool CheckPath (const std::string& path) const; - - /** - * \param path the path of the value to retrieve in form eg "/parent/children/index/key" - * \returns if the path is valid returns a pair - */ - const std::pair GetInt (const std::string& path) const; - - /** - * \param path the path of the value to retrieve in form eg "/parent/children/index/key" - * \returns if the path is valid returns a pair - */ - const std::pair GetUint (const std::string& path) const; - - /** - * \param path the path of the value to retrieve in form eg "/parent/children/index/key" - * \returns if the path is valid returns a pair - */ - const std::pair GetDouble (const std::string& path) const; - - /** - * \param path the path of the value to retrieve in form eg "/parent/children/index/key" - * \returns if the path is valid returns a pair , else - */ - const std::pair GetBool (const std::string& path) const; - - /** - * \param path the path of the value to retrieve in form eg "/parent/children/index/key" - * \returns if the path is valid returns a pair , else - */ - const std::pair GetString (const std::string& path) const; - -private: - /** - * \brief part of the constructor, it focuses on command line decoding and JSON file parsing. - * \param argc the command line argument count number. - * \param argv the list of command line arguments - */ - void InitializeConfiguration (int argc, char **argv); - /** - * \brief part of the destructor, it releases any pointer bound to the command line and JSON files. - */ - void DisposeConfiguration (); - - /** - * \brief redirect clog to a proper log file or standard out - * \param onFile whether clog should print on a file or on standard output console. - */ - void InitializeLogging (const bool &onFile); - /** - * \brief recover previous state of clog output buffer and closes any log file opened. - */ - void DisposeLogging (); - /** - * \brief Optional array of log components to be enabled for the simulation. - */ - void EnableLogComponents () const; - - - std::FILE *m_configFilePtr; /// pointer to the JSON file - rapidjson::Document m_config; /// decoded JSON structure - std::ofstream m_out; /// output stream for clog - std::string m_name; /// name of the simulation - std::string m_dateTime; /// cache for the current datetime - std::vector> m_staticConfig; /// cache for ns-3 static config params - uint32_t m_radioMap; /// a code for radio map generation options + public: + /** + * \brief default destructor + */ + ~ScenarioConfigurationHelper(); + + /** + * \brief Bootstrap Singleton with basic data. + * \param argc The number of command line arguments. + * \param argv The list of command line arguments. + */ + void Initialize(int argc, char** argv); + + /** + * \brief Bootstrap Singleton with basic data. + * + * \param argc The number of command line arguments. + * \param argv The list of command line arguments. + * \param name The name of the scenario. + */ + void Initialize(int argc, char** argv, const std::string name); + + /** + * \return The name of the scenario. + */ + const std::string GetName(); + + /** + * \return The current date and time as a human-readable string. + */ + const std::string GetCurrentDateTime() const; + + /** + * \brief Gets the preconfigured path from the configuration file, then makes a new + * folder at /- where to place files + * \return The full path of the folder where to put result files + */ + const std::string GetResultsPath(); + + /** + * \brief Check if the user wants to save trace results or not. + */ + const bool GetLogOnFile() const; + + /** + * \return The file path of the logging file. + */ + const std::string GetLoggingFilePath(); + + /** + * \brief Retrieve Static Configuration Parameters as a key/value pair. + * + * \return Static configuration defined in the configuration file. + */ + const std::vector> GetStaticConfig(); + + /** + * \brief Retrieve the list of PHY Layers defined for this simulation. + * + * \return The list of PHY Layers to be defined for this simulation. + */ + const std::vector> GetPhyLayers() const; + + /** + * \brief Retrieve the list of MAC Layers defined for this simulation. + * + * \return The list of MAC Layers to be defined for this simulation. + */ + const std::vector> GetMacLayers() const; + + /** + * \brief Retrieve the list of Network Layers defined for this simulation. + * + * \return The list of Network Layers to be defined for this simulation. + */ + const std::vector> GetNetworkLayers() const; + + /** + * \brief Retrieve the list of generic enetities to be defined for this simulation. + * + * \return The list of Entities to be defined for this simulation. + */ + const std::vector> GetEntitiesConfiguration( + const std::string& entityKey) const; + + /** + * \brief Retrieve the list of remotes to be defined for this simulation. + * + * \return The list of remotes to be defined for this simulation. + */ + const std::vector> GetRemotesConfiguration() const; + + /** + * \return The duration of the simulation in seconds. + */ + const double GetDuration() const; + + /** + * \return The number of entities in the given entityKey category. + */ + std::size_t GetN(const char* entityKey) const; + + /** + * \return The number of plain nodes to be simulated. + */ + std::size_t GetNodesN() const; + + // DRONE RELATED CONFIGURATORS + + /** + * \return the number of drones to be simulated. + */ + const uint32_t GetDronesN() const; + /** + * \return a string identifying the mobility model for the drones. + */ + const std::string GetDronesMobilityModel() const; + /** + * \param n the index of the drone in the list + * \return a string identifying the mobility model of the n-th drone + */ + const std::string GetDroneMobilityModel(uint32_t n) const; + /** + * \param n the index of the drone in the list + * \return a ns3::Vector with the coordinates of the position of the n-th drone + */ + const Vector GetDronePosition(uint32_t n) const; + /** + * \brief allocate the position of the drones (if dronesMobilityModel is + * set to "ns3::ConstantPositionMobilityModel") + * \param allocator the allocator to be filled with drones positions. + */ + void GetDronesPosition(Ptr allocator) const; + /** + * \param n the index of the drone in the list + * \return the list of waypoints of drone with index i + */ + const std::vector GetDroneWaypoints(uint32_t i) const; + /** + * \return the step of the curve to be generated. + */ + const float GetCurveStep() const; + /** + * \param i the drone index number. + * \return the flight plan of drone with index i + */ + const FlightPlan GetDroneFlightPlan(uint32_t i) const; + /** + * \param i the drone index number. + * \return the constant acceleration of the drone with index i. + */ + const double GetDroneAcceleration(uint32_t i) const; + /** + * \param i the drone index number. + * \return the maximum speed of the drone with index i. + */ + const double GetDroneMaxSpeed(uint32_t i) const; + /** + * \param i the drone index number. + * \return the polynomial speed coeffients. + */ + const DoubleVector GetDroneSpeedCoefficients(uint32_t i) const; + /** + * \param i the drone index number. + * \return the instant, in seconds, indicating the start of the application. + */ + const double GetDroneApplicationStartTime(uint32_t i) const; + /** + * \param i the drone index number. + * \return the instant, in seconds, indicating the end of the application. + */ + const double GetDroneApplicationStopTime(uint32_t i) const; + + // WIFI SPECIFIC CONFIGURATORS + + /** + * \return the phy mode for WiFi communications. + */ + const std::string GetPhyMode() const; + /** + * \return the phy path loss to use + */ + const std::string GetPhyPropagationLossModel() const; + /** + * \return the phy parameters + */ + const std::vector> + GetThreeLogDistancePropagationLossModelAttributes() const; + + /** + * \return the number of ZSPs to be simulated. + */ + const uint32_t GetZspsN() const; + /** + * \brief allocate the position of the ZSPs + * \param allocator the allocator to be filled with ZSPs positions. + */ + void GetZspsPosition(Ptr allocator) const; + /** + * \param i the ZSP index number. + * \return the instant, in seconds, indicating the start of the application. + */ + const double GetZspApplicationStartTime(uint32_t i) const; + /** + * \param i the ZSP index number. + * \return the instant, in seconds, indicating the end of the application. + */ + const double GetZspApplicationStopTime(uint32_t i) const; + /** + * \return the number of ENBs to be simulated. + */ + const uint32_t GetEnbsN() const; + /** + * \brief allocate the position of the ENBs + * + * \param allocator the allocator to be filled with ENBs positions. + */ + void GetEnbsPosition(Ptr allocator) const; + /** + * \brief Check if dry run is wanted. + */ + const bool IsDryRun() const; + /** + * \return a structure containing points describing regions of interest + */ + const std::vector GetRegionsOfInterest() const; + + // LTE SPECIFIC CONFIGURATORS + + /** + * \return Radio Environment Map generation code, 0 for no generation, 1 for generation, 2 for + * generation with map plot. + */ + const uint32_t RadioMap() const; + + /** + * \return a list of parameters for the Radio Environment Map generator + */ + const std::vector> GetRadioMapParameters() const; + + /** + * \return the number of antennas to be simulated. + */ + const uint32_t GetAntennasN() const; + /** + * \brief allocate the position of the antennas + * \param allocator the allocator to be filled with antennas positions + */ + void GetAntennasPosition(Ptr allocator) const; + + /** + * \return the number of remote hosts to be simulated. + */ + const uint32_t GetRemotesN() const; + /** + * \param i the remote index number. + * \return the instant, in seconds, indicating the start of the application. + */ + const double GetRemoteApplicationStartTime(uint32_t i) const; + /** + * \param i the remote index number. + * \return the instant, in seconds, indicating the end of the application. + */ + const double GetRemoteApplicationStopTime(uint32_t i) const; + + /** + * \brief Returns a vector with all the global configuration strings for scenario. + * Use with Config::SetDefault(pair.first, pair.second) at the beginning of the script. + * \return a vector of pairs containing the key and the value extracted from config + */ + const std::vector> GetGlobalSettings() const; + /** + * \brief Returns a vector with all the per-object individual settings. + * Use with Config::Set(pair.first, pair.second) after creating all the object before + * simulation start. \return a vector of pairs containing the key and the value extracted from + * config + */ + const std::vector> GetIndividualSettings() const; + + /** + * \return a vector of Ptr created with the attributes in config + */ + const std::vector> GetBuildings() const; + + /** + * \param field the name of the field to search into + * \param index the index of the element to which retrieve the name + * \return the name associated to the object at the index in the field + */ + const std::string GetObjectName(const char* field, uint32_t index) const; + + /** + * \param field the name of the field to search into + * \param name the name of the element to which retrieve the index + * \return the index of the object of given name + */ + const uint32_t GetObjectIndex(const char* field, const std::string& name) const; + + // NETWORKS SPECIFIC CONFIGURATORS + + /** + * \param id the index of the drone to query + * \return a list of the network IDs the drone is connected to + */ + const std::vector GetDroneNetworks(uint32_t id) const; + + /** + * \param name the name of the drone to query + * \return a list of the network IDs the drone is connected to + */ + const std::vector GetDroneNetworks(const std::string& name) const; + + /** + * \param id the index of the antenna to query + * \return a list of the network IDs the antenna is connected to + */ + const std::vector GetAntennaNetworks(uint32_t id) const; + + /** + * \param name the name of the antenna to query + * \return a list of the network IDs the antenna is connected to + */ + const std::vector GetAntennaNetworks(const std::string& name) const; + + /** + * \param id the index of the network + * \return a list of id of all the drones connected to a network + */ + const std::vector GetDronesInNetwork(uint32_t id) const; + + /** + * \param net_name the name of the network + * \return a list of id of all the drones connected to a network + */ + const std::vector GetDronesInNetwork(const std::string& net_name) const; + + /** + * \param id the index of the network + * \return a list of id of all the antennas connected to a network + */ + const std::vector GetAntennasInNetwork(uint32_t id) const; + + /** + * \param net_name the name of the network + * \return a list of id of all the antennas connected to a network + */ + const std::vector GetAntennasInNetwork(const std::string& net_name) const; + + /// General purpose value retrieving methods + + /** + * \param path1 the first part of the path + * \param path2 the second part of the path + * \return the concatenation of those 2 paths adding a '/' if necessary + */ + const std::string MakePath(const std::string& path1, const std::string& path2 = "") const; + + /** + * \param path the first part of the path + * \param index the index of the element at the path + * \return the concatenation of path and index, adding a '/' if necessary + */ + const std::string MakePath(const std::string& path, uint32_t index) const; + + /** + * \param path the path to check in form eg "/parent/children/index/key" + * \return true if the path is valid else false + */ + bool CheckPath(const std::string& path) const; + + /** + * \param path the path of the value to retrieve in form eg "/parent/children/index/key" + * \returns if the path is valid returns a pair + */ + const std::pair GetInt(const std::string& path) const; + + /** + * \param path the path of the value to retrieve in form eg "/parent/children/index/key" + * \returns if the path is valid returns a pair + */ + const std::pair GetUint(const std::string& path) const; + + /** + * \param path the path of the value to retrieve in form eg "/parent/children/index/key" + * \returns if the path is valid returns a pair + */ + const std::pair GetDouble(const std::string& path) const; + + /** + * \param path the path of the value to retrieve in form eg "/parent/children/index/key" + * \returns if the path is valid returns a pair , else + */ + const std::pair GetBool(const std::string& path) const; + + /** + * \param path the path of the value to retrieve in form eg "/parent/children/index/key" + * \returns if the path is valid returns a pair , else + */ + const std::pair GetString(const std::string& path) const; + + private: + /** + * \brief part of the constructor, it focuses on command line decoding and JSON file parsing. + * \param argc the command line argument count number. + * \param argv the list of command line arguments + */ + void InitializeConfiguration(int argc, char** argv); + /** + * \brief part of the destructor, it releases any pointer bound to the command line and JSON + * files. + */ + void DisposeConfiguration(); + + /** + * \brief redirect clog to a proper log file or standard out + * \param onFile whether clog should print on a file or on standard output console. + */ + void InitializeLogging(const bool& onFile); + /** + * \brief recover previous state of clog output buffer and closes any log file opened. + */ + void DisposeLogging(); + /** + * \brief Optional array of log components to be enabled for the simulation. + */ + void EnableLogComponents() const; + + std::FILE* m_configFilePtr; /// pointer to the JSON file + rapidjson::Document m_config; /// decoded JSON structure + std::ofstream m_out; /// output stream for clog + std::string m_name; /// name of the simulation + std::string m_dateTime; /// cache for the current datetime + std::vector> + m_staticConfig; /// cache for ns-3 static config params + uint32_t m_radioMap; /// a code for radio map generation options }; } // namespace ns3 diff --git a/src/configuration/helper/wifi-mac-factory-helper.cc b/src/configuration/helper/wifi-mac-factory-helper.cc index 2f553f8..efc056a 100644 --- a/src/configuration/helper/wifi-mac-factory-helper.cc +++ b/src/configuration/helper/wifi-mac-factory-helper.cc @@ -17,23 +17,24 @@ */ #include "wifi-mac-factory-helper.h" -namespace ns3 { +namespace ns3 +{ void -WifiMacFactoryHelper::SetRemoteStationManager (WifiHelper& helper, const ModelConfiguration& modelConf) +WifiMacFactoryHelper::SetRemoteStationManager(WifiHelper& helper, + const ModelConfiguration& modelConf) { - ObjectFactory factory; + ObjectFactory factory; - factory.SetTypeId (modelConf.GetName ()); - for (auto& attr : modelConf.GetAttributes ()) - factory.Set (attr.name, *attr.value); + factory.SetTypeId(modelConf.GetName()); + for (auto& attr : modelConf.GetAttributes()) + factory.Set(attr.name, *attr.value); - helper.m_stationManager[0] = factory; + helper.m_stationManager[0] = factory; } -WifiMacFactoryHelper::WifiMacFactoryHelper () +WifiMacFactoryHelper::WifiMacFactoryHelper() { - } } // namespace ns3 diff --git a/src/configuration/helper/wifi-mac-factory-helper.h b/src/configuration/helper/wifi-mac-factory-helper.h index 315c05a..1f9158b 100644 --- a/src/configuration/helper/wifi-mac-factory-helper.h +++ b/src/configuration/helper/wifi-mac-factory-helper.h @@ -18,30 +18,32 @@ #ifndef WIFI_MAC_FACTORY_HELPER_H #define WIFI_MAC_FACTORY_HELPER_H -#include - #include +#include -namespace ns3 { +namespace ns3 +{ /** * Helper to enhance ns-3 WifiHelper functionalities with additional * features, without modifying objects external to IoD_Sim. */ -class WifiMacFactoryHelper { -public: - /** - * Set the wifi model to be used from a ModelConfiguration data class. - * - * \param helper The WifiHelper instance. - * \param modelConf The configuration data class that defines the WiFi model to be used and its configuration. - */ - static void SetRemoteStationManager (WifiHelper& helper, const ModelConfiguration& modelConf); +class WifiMacFactoryHelper +{ + public: + /** + * Set the wifi model to be used from a ModelConfiguration data class. + * + * \param helper The WifiHelper instance. + * \param modelConf The configuration data class that defines the WiFi model to be used and its + * configuration. + */ + static void SetRemoteStationManager(WifiHelper& helper, const ModelConfiguration& modelConf); -private: - WifiMacFactoryHelper (); + private: + WifiMacFactoryHelper(); }; -} +} // namespace ns3 #endif /* WIFI_MAC_FACTORY_HELPER_H */ diff --git a/src/configuration/helper/wifi-mac-simulation-helper.cc b/src/configuration/helper/wifi-mac-simulation-helper.cc index 2612956..ca80cbc 100644 --- a/src/configuration/helper/wifi-mac-simulation-helper.cc +++ b/src/configuration/helper/wifi-mac-simulation-helper.cc @@ -17,22 +17,21 @@ */ #include "wifi-mac-simulation-helper.h" -namespace ns3 { - -WifiMacSimulationHelper::WifiMacSimulationHelper () +namespace ns3 { +WifiMacSimulationHelper::WifiMacSimulationHelper() +{ } -WifiMacSimulationHelper::~WifiMacSimulationHelper () +WifiMacSimulationHelper::~WifiMacSimulationHelper() { - } WifiMacHelper& -WifiMacSimulationHelper::GetMacHelper () +WifiMacSimulationHelper::GetMacHelper() { - return m_macHelper; + return m_macHelper; } } // namespace ns3 diff --git a/src/configuration/helper/wifi-mac-simulation-helper.h b/src/configuration/helper/wifi-mac-simulation-helper.h index 7e0085e..48ea974 100644 --- a/src/configuration/helper/wifi-mac-simulation-helper.h +++ b/src/configuration/helper/wifi-mac-simulation-helper.h @@ -19,29 +19,29 @@ #define WIFI_MAC_SIMULATION_HELPER_H #include - #include -namespace ns3 { +namespace ns3 +{ /** * A data class to store information about a WiFi MAC layer configuration for a simulation. */ class WifiMacSimulationHelper : public Object { -public: - /** Default constructor */ - WifiMacSimulationHelper (); - /** Default destructor */ - ~WifiMacSimulationHelper (); - - /** - * \return The WiFi MAC Helper used to configure this layer. - */ - WifiMacHelper& GetMacHelper (); - -private: - WifiMacHelper m_macHelper; + public: + /** Default constructor */ + WifiMacSimulationHelper(); + /** Default destructor */ + ~WifiMacSimulationHelper(); + + /** + * \return The WiFi MAC Helper used to configure this layer. + */ + WifiMacHelper& GetMacHelper(); + + private: + WifiMacHelper m_macHelper; }; } // namespace ns3 diff --git a/src/configuration/helper/wifi-phy-factory-helper.cc b/src/configuration/helper/wifi-phy-factory-helper.cc index 56ec440..de37338 100644 --- a/src/configuration/helper/wifi-phy-factory-helper.cc +++ b/src/configuration/helper/wifi-phy-factory-helper.cc @@ -17,35 +17,37 @@ */ #include "wifi-phy-factory-helper.h" -namespace ns3 { +namespace ns3 +{ void -WifiPhyFactoryHelper::SetPropagationDelay (YansWifiChannelHelper& channelHelper, const ModelConfiguration& modelConf) +WifiPhyFactoryHelper::SetPropagationDelay(YansWifiChannelHelper& channelHelper, + const ModelConfiguration& modelConf) { - ObjectFactory factory; + ObjectFactory factory; - factory.SetTypeId (modelConf.GetName ()); - for (auto& attr : modelConf.GetAttributes ()) - factory.Set (attr.name, *attr.value); + factory.SetTypeId(modelConf.GetName()); + for (auto& attr : modelConf.GetAttributes()) + factory.Set(attr.name, *attr.value); - channelHelper.m_propagationDelay = factory; + channelHelper.m_propagationDelay = factory; } void -WifiPhyFactoryHelper::AddPropagationLoss (YansWifiChannelHelper& channelHelper, const ModelConfiguration& modelConf) +WifiPhyFactoryHelper::AddPropagationLoss(YansWifiChannelHelper& channelHelper, + const ModelConfiguration& modelConf) { - ObjectFactory factory; + ObjectFactory factory; - factory.SetTypeId (modelConf.GetName ()); - for (auto& attr : modelConf.GetAttributes ()) - factory.Set (attr.name, *attr.value); + factory.SetTypeId(modelConf.GetName()); + for (auto& attr : modelConf.GetAttributes()) + factory.Set(attr.name, *attr.value); - channelHelper.m_propagationLoss.push_back (factory); + channelHelper.m_propagationLoss.push_back(factory); } -WifiPhyFactoryHelper::WifiPhyFactoryHelper () +WifiPhyFactoryHelper::WifiPhyFactoryHelper() { - } } // namespace ns3 diff --git a/src/configuration/helper/wifi-phy-factory-helper.h b/src/configuration/helper/wifi-phy-factory-helper.h index 09d797d..f072e18 100644 --- a/src/configuration/helper/wifi-phy-factory-helper.h +++ b/src/configuration/helper/wifi-phy-factory-helper.h @@ -18,37 +18,42 @@ #ifndef WIFI_PHY_FACTORY_HELPER_H #define WIFI_PHY_FACTORY_HELPER_H -#include - #include +#include -namespace ns3 { +namespace ns3 +{ /** * Helper to enhance ns-3 WifiPhyHelper functionalities with additional * features, without modifying objects external to IoD_Sim. */ -class WifiPhyFactoryHelper { -public: - /** - * Set the propagation delay model to be used from a ModelConfiguration data class. - * - * \param channelHelper The YansWifiChannelHelper instance. - * \param modelConf The configuration data class that defines the propagation delay model to be used. - */ - static void SetPropagationDelay (YansWifiChannelHelper& channelHelper, const ModelConfiguration& modelConf); - /** - * Set the propagation loss model to be used from a ModelConfiguration data class. - * - * \param channelHelper The YansWifiChannelHelper instance. - * \param modelConf The configuration data class that defines the propagation loss model to be used. - */ - static void AddPropagationLoss (YansWifiChannelHelper& channelHelper, const ModelConfiguration& modelConf); +class WifiPhyFactoryHelper +{ + public: + /** + * Set the propagation delay model to be used from a ModelConfiguration data class. + * + * \param channelHelper The YansWifiChannelHelper instance. + * \param modelConf The configuration data class that defines the propagation delay model to be + * used. + */ + static void SetPropagationDelay(YansWifiChannelHelper& channelHelper, + const ModelConfiguration& modelConf); + /** + * Set the propagation loss model to be used from a ModelConfiguration data class. + * + * \param channelHelper The YansWifiChannelHelper instance. + * \param modelConf The configuration data class that defines the propagation loss model to be + * used. + */ + static void AddPropagationLoss(YansWifiChannelHelper& channelHelper, + const ModelConfiguration& modelConf); -private: - WifiPhyFactoryHelper (); + private: + WifiPhyFactoryHelper(); }; -} +} // namespace ns3 #endif /* WIFI_PHY_FACTORY_HELPER_H */ diff --git a/src/configuration/helper/wifi-phy-simulation-helper.cc b/src/configuration/helper/wifi-phy-simulation-helper.cc index 5cefb10..b021461 100644 --- a/src/configuration/helper/wifi-phy-simulation-helper.cc +++ b/src/configuration/helper/wifi-phy-simulation-helper.cc @@ -17,30 +17,29 @@ */ #include "wifi-phy-simulation-helper.h" -namespace ns3 { - -WifiPhySimulationHelper::WifiPhySimulationHelper () : - m_wifi {}, - m_wifiPhy {} +namespace ns3 { +WifiPhySimulationHelper::WifiPhySimulationHelper() + : m_wifi{}, + m_wifiPhy{} +{ } -WifiPhySimulationHelper::~WifiPhySimulationHelper () +WifiPhySimulationHelper::~WifiPhySimulationHelper() { - } WifiHelper* -WifiPhySimulationHelper::GetWifiHelper () +WifiPhySimulationHelper::GetWifiHelper() { - return &m_wifi; + return &m_wifi; } YansWifiPhyHelper* -WifiPhySimulationHelper::GetWifiPhyHelper () +WifiPhySimulationHelper::GetWifiPhyHelper() { - return &m_wifiPhy; + return &m_wifiPhy; } } // namespace ns3 diff --git a/src/configuration/helper/wifi-phy-simulation-helper.h b/src/configuration/helper/wifi-phy-simulation-helper.h index a370421..d199f1b 100644 --- a/src/configuration/helper/wifi-phy-simulation-helper.h +++ b/src/configuration/helper/wifi-phy-simulation-helper.h @@ -22,31 +22,32 @@ #include #include -namespace ns3 { +namespace ns3 +{ /** * A data class to store information about a WiFi PHY layer configuration for a simulation. */ class WifiPhySimulationHelper : public Object { -public: - /** Default constructor */ - WifiPhySimulationHelper (); - /** Default destructor */ - ~WifiPhySimulationHelper (); + public: + /** Default constructor */ + WifiPhySimulationHelper(); + /** Default destructor */ + ~WifiPhySimulationHelper(); - /** - * \return The WiFi Helper used to configure this layer. - */ - WifiHelper* GetWifiHelper (); - /** - * \return The YANS WiFi PHY Helper used to configure this layer. - */ - YansWifiPhyHelper* GetWifiPhyHelper (); + /** + * \return The WiFi Helper used to configure this layer. + */ + WifiHelper* GetWifiHelper(); + /** + * \return The YANS WiFi PHY Helper used to configure this layer. + */ + YansWifiPhyHelper* GetWifiPhyHelper(); -private: - WifiHelper m_wifi; - YansWifiPhyHelper m_wifiPhy; + private: + WifiHelper m_wifi; + YansWifiPhyHelper m_wifiPhy; }; } // namespace ns3 diff --git a/src/configuration/ipv4-network-layer-configuration.cc b/src/configuration/ipv4-network-layer-configuration.cc index ef2edf2..a5fea37 100644 --- a/src/configuration/ipv4-network-layer-configuration.cc +++ b/src/configuration/ipv4-network-layer-configuration.cc @@ -19,41 +19,40 @@ #include -namespace ns3 { - -Ipv4NetworkLayerConfiguration::Ipv4NetworkLayerConfiguration (std::string type, - std::string address, - std::string mask, - std::string gatewayAddress): - NetworkLayerConfiguration {type}, - m_address {address}, - m_mask {mask}, - m_gatewayAddress {gatewayAddress} +namespace ns3 { +Ipv4NetworkLayerConfiguration::Ipv4NetworkLayerConfiguration(std::string type, + std::string address, + std::string mask, + std::string gatewayAddress) + : NetworkLayerConfiguration{type}, + m_address{address}, + m_mask{mask}, + m_gatewayAddress{gatewayAddress} +{ } -Ipv4NetworkLayerConfiguration::~Ipv4NetworkLayerConfiguration () +Ipv4NetworkLayerConfiguration::~Ipv4NetworkLayerConfiguration() { - } const std::string -Ipv4NetworkLayerConfiguration::GetAddress () const +Ipv4NetworkLayerConfiguration::GetAddress() const { - return m_address; + return m_address; } const std::string -Ipv4NetworkLayerConfiguration::GetMask () const +Ipv4NetworkLayerConfiguration::GetMask() const { - return m_mask; + return m_mask; } const std::string -Ipv4NetworkLayerConfiguration::GetGatewayAddress () const +Ipv4NetworkLayerConfiguration::GetGatewayAddress() const { - return m_gatewayAddress; + return m_gatewayAddress; } } // namespace ns3 diff --git a/src/configuration/ipv4-network-layer-configuration.h b/src/configuration/ipv4-network-layer-configuration.h index a621658..28a3e12 100644 --- a/src/configuration/ipv4-network-layer-configuration.h +++ b/src/configuration/ipv4-network-layer-configuration.h @@ -18,50 +18,51 @@ #ifndef IPV4_NETWORK_LAYER_CONFIGURATION_H #define IPV4_NETWORK_LAYER_CONFIGURATION_H -#include - #include "network-layer-configuration.h" -namespace ns3 { +#include + +namespace ns3 +{ /** * A data class to store configuration information related to the set up of an IPv4 Network Layer. */ class Ipv4NetworkLayerConfiguration : public NetworkLayerConfiguration { -public: - /** - * Create a new object instance. - * - * \param type The type of network layer configuration. It must be "ipv4". - * \param address The network address. - * \param mask The network mask. - * \param gatewayAddress The gateway address. - */ - Ipv4NetworkLayerConfiguration (std::string type, - std::string address, - std::string mask, - std::string gatewayAddress); - /** Default destructor */ - ~Ipv4NetworkLayerConfiguration (); + public: + /** + * Create a new object instance. + * + * \param type The type of network layer configuration. It must be "ipv4". + * \param address The network address. + * \param mask The network mask. + * \param gatewayAddress The gateway address. + */ + Ipv4NetworkLayerConfiguration(std::string type, + std::string address, + std::string mask, + std::string gatewayAddress); + /** Default destructor */ + ~Ipv4NetworkLayerConfiguration(); - /** - * \return The configured network address. - */ - const std::string GetAddress () const; - /** - * \return The configured network mask. - */ - const std::string GetMask () const; - /** - * \return The configured network gateway address. - */ - const std::string GetGatewayAddress () const; + /** + * \return The configured network address. + */ + const std::string GetAddress() const; + /** + * \return The configured network mask. + */ + const std::string GetMask() const; + /** + * \return The configured network gateway address. + */ + const std::string GetGatewayAddress() const; -private: - const std::string m_address; - const std::string m_mask; - const std::string m_gatewayAddress; + private: + const std::string m_address; + const std::string m_mask; + const std::string m_gatewayAddress; }; } // namespace ns3 diff --git a/src/configuration/lte-bearer-configuration.cc b/src/configuration/lte-bearer-configuration.cc index 0460c44..94b5b72 100644 --- a/src/configuration/lte-bearer-configuration.cc +++ b/src/configuration/lte-bearer-configuration.cc @@ -17,100 +17,99 @@ */ #include "lte-bearer-configuration.h" -namespace ns3 { +namespace ns3 +{ class LteBearerConfigurationPriv { -public: - static const EpsBearer::Qci ParseBearerType (const std::string t) - { - if (t == "GBR_CONV_VOICE") - return EpsBearer::Qci::GBR_CONV_VOICE; - else if (t == "GBR_CONV_VIDEO") - return EpsBearer::Qci::GBR_CONV_VIDEO; - else if (t == "GBR_GAMING") - return EpsBearer::Qci::GBR_GAMING; - else if (t == "GBR_NON_CONV_VIDEO") - return EpsBearer::Qci::GBR_NON_CONV_VIDEO; - else if (t == "GBR_MC_PUSH_TO_TALK") - return EpsBearer::Qci::GBR_MC_PUSH_TO_TALK; - else if (t == "GBR_NMC_PUSH_TO_TALK") - return EpsBearer::Qci::GBR_NMC_PUSH_TO_TALK; - else if (t == "GBR_MC_VIDEO") - return EpsBearer::Qci::GBR_MC_VIDEO; - else if (t == "GBR_V2X") - return EpsBearer::Qci::GBR_V2X; - else if (t == "NGBR_IMS") - return EpsBearer::Qci::NGBR_IMS; - else if (t == "NGBR_VIDEO_TCP_OPERATOR") - return EpsBearer::Qci::NGBR_VIDEO_TCP_OPERATOR; - else if (t == "NGBR_VOICE_VIDEO_GAMING") - return EpsBearer::Qci::NGBR_VOICE_VIDEO_GAMING; - else if (t == "NGBR_VIDEO_TCP_PREMIUM") - return EpsBearer::Qci::NGBR_VIDEO_TCP_PREMIUM; - else if (t == "NGBR_VIDEO_TCP_DEFAULT") - return EpsBearer::Qci::NGBR_VIDEO_TCP_DEFAULT; - else if (t == "NGBR_MC_DELAY_SIGNAL") - return EpsBearer::Qci::NGBR_MC_DELAY_SIGNAL; - else if (t == "NGBR_MC_DATA") - return EpsBearer::Qci::NGBR_MC_DATA; - else if (t == "NGBR_V2X") - return EpsBearer::Qci::NGBR_V2X; - else if (t == "NGBR_LOW_LAT_EMBB") - return EpsBearer::Qci::NGBR_LOW_LAT_EMBB; - else if (t == "DGBR_DISCRETE_AUT_SMALL") - return EpsBearer::Qci::DGBR_DISCRETE_AUT_SMALL; - else if (t == "DGBR_DISCRETE_AUT_LARGE") - return EpsBearer::Qci::DGBR_DISCRETE_AUT_LARGE; - else if (t == "DGBR_ITS") - return EpsBearer::Qci::DGBR_ITS; - else if (t == "DGBR_ELECTRICITY") - return EpsBearer::Qci::DGBR_ELECTRICITY; - else - NS_FATAL_ERROR ("Unsupported LTE Bearer QCI of type " << t); - } + public: + static const EpsBearer::Qci ParseBearerType(const std::string t) + { + if (t == "GBR_CONV_VOICE") + return EpsBearer::Qci::GBR_CONV_VOICE; + else if (t == "GBR_CONV_VIDEO") + return EpsBearer::Qci::GBR_CONV_VIDEO; + else if (t == "GBR_GAMING") + return EpsBearer::Qci::GBR_GAMING; + else if (t == "GBR_NON_CONV_VIDEO") + return EpsBearer::Qci::GBR_NON_CONV_VIDEO; + else if (t == "GBR_MC_PUSH_TO_TALK") + return EpsBearer::Qci::GBR_MC_PUSH_TO_TALK; + else if (t == "GBR_NMC_PUSH_TO_TALK") + return EpsBearer::Qci::GBR_NMC_PUSH_TO_TALK; + else if (t == "GBR_MC_VIDEO") + return EpsBearer::Qci::GBR_MC_VIDEO; + else if (t == "GBR_V2X") + return EpsBearer::Qci::GBR_V2X; + else if (t == "NGBR_IMS") + return EpsBearer::Qci::NGBR_IMS; + else if (t == "NGBR_VIDEO_TCP_OPERATOR") + return EpsBearer::Qci::NGBR_VIDEO_TCP_OPERATOR; + else if (t == "NGBR_VOICE_VIDEO_GAMING") + return EpsBearer::Qci::NGBR_VOICE_VIDEO_GAMING; + else if (t == "NGBR_VIDEO_TCP_PREMIUM") + return EpsBearer::Qci::NGBR_VIDEO_TCP_PREMIUM; + else if (t == "NGBR_VIDEO_TCP_DEFAULT") + return EpsBearer::Qci::NGBR_VIDEO_TCP_DEFAULT; + else if (t == "NGBR_MC_DELAY_SIGNAL") + return EpsBearer::Qci::NGBR_MC_DELAY_SIGNAL; + else if (t == "NGBR_MC_DATA") + return EpsBearer::Qci::NGBR_MC_DATA; + else if (t == "NGBR_V2X") + return EpsBearer::Qci::NGBR_V2X; + else if (t == "NGBR_LOW_LAT_EMBB") + return EpsBearer::Qci::NGBR_LOW_LAT_EMBB; + else if (t == "DGBR_DISCRETE_AUT_SMALL") + return EpsBearer::Qci::DGBR_DISCRETE_AUT_SMALL; + else if (t == "DGBR_DISCRETE_AUT_LARGE") + return EpsBearer::Qci::DGBR_DISCRETE_AUT_LARGE; + else if (t == "DGBR_ITS") + return EpsBearer::Qci::DGBR_ITS; + else if (t == "DGBR_ELECTRICITY") + return EpsBearer::Qci::DGBR_ELECTRICITY; + else + NS_FATAL_ERROR("Unsupported LTE Bearer QCI of type " << t); + } - static const GbrQosInformation BuildQosInformation (const uint64_t gbrDl, - const uint64_t gbrUl, - const uint64_t mbrDl, - const uint64_t mbrUl) - { - auto qosInfo = GbrQosInformation (); - qosInfo.gbrDl = gbrDl; - qosInfo.gbrUl = gbrUl; - qosInfo.mbrDl = mbrDl; - qosInfo.mbrUl = mbrUl; + static const GbrQosInformation BuildQosInformation(const uint64_t gbrDl, + const uint64_t gbrUl, + const uint64_t mbrDl, + const uint64_t mbrUl) + { + auto qosInfo = GbrQosInformation(); + qosInfo.gbrDl = gbrDl; + qosInfo.gbrUl = gbrUl; + qosInfo.mbrDl = mbrDl; + qosInfo.mbrUl = mbrUl; - return qosInfo; - } + return qosInfo; + } }; -LteBearerConfiguration::LteBearerConfiguration (const std::string type, - const uint64_t gbrDl, - const uint64_t gbrUl, - const uint64_t mbrDl, - const uint64_t mbrUl) : - m_type {LteBearerConfigurationPriv::ParseBearerType (type)}, - m_qos {LteBearerConfigurationPriv::BuildQosInformation (gbrDl, gbrUl, mbrDl, mbrUl)} +LteBearerConfiguration::LteBearerConfiguration(const std::string type, + const uint64_t gbrDl, + const uint64_t gbrUl, + const uint64_t mbrDl, + const uint64_t mbrUl) + : m_type{LteBearerConfigurationPriv::ParseBearerType(type)}, + m_qos{LteBearerConfigurationPriv::BuildQosInformation(gbrDl, gbrUl, mbrDl, mbrUl)} { - } -LteBearerConfiguration::~LteBearerConfiguration () +LteBearerConfiguration::~LteBearerConfiguration() { - } const EpsBearer::Qci -LteBearerConfiguration::GetType () const +LteBearerConfiguration::GetType() const { - return m_type; + return m_type; } const GbrQosInformation -LteBearerConfiguration::GetQos () const +LteBearerConfiguration::GetQos() const { - return m_qos; + return m_qos; } } // namespace ns3 diff --git a/src/configuration/lte-bearer-configuration.h b/src/configuration/lte-bearer-configuration.h index c807948..9f81bd6 100644 --- a/src/configuration/lte-bearer-configuration.h +++ b/src/configuration/lte-bearer-configuration.h @@ -18,46 +18,47 @@ #ifndef LTE_BEARER_CONFIGURATION_H #define LTE_BEARER_CONFIGURATION_H -#include #include #include +#include -namespace ns3 { +namespace ns3 +{ /** * Data class to store parameters useful at LTE Bearer configuration. */ class LteBearerConfiguration : public Object { -public: - /** - * Create a new object instance. - * - * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol Stack). - * \param macLayer The configuration of the MAC Layer to be simulated for this network device. - * \param networkLayerId The identifier for the Network Layer that has been defined for this simulation. - * It must be compatible with the given type and macLayer. - */ - LteBearerConfiguration (const std::string type, - const uint64_t gbrDl, - const uint64_t gbrUl, - const uint64_t mbrDl, - const uint64_t mbrUl); - /** Default destructor */ - ~LteBearerConfiguration (); + public: + /** + * Create a new object instance. + * + * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol + * Stack). \param macLayer The configuration of the MAC Layer to be simulated for this network + * device. \param networkLayerId The identifier for the Network Layer that has been defined for + * this simulation. It must be compatible with the given type and macLayer. + */ + LteBearerConfiguration(const std::string type, + const uint64_t gbrDl, + const uint64_t gbrUl, + const uint64_t mbrDl, + const uint64_t mbrUl); + /** Default destructor */ + ~LteBearerConfiguration(); - /** - * \return The type of the Network Device. - */ - const EpsBearer::Qci GetType () const; - /** - * \return The reference network layer identifier. - */ - const GbrQosInformation GetQos () const; + /** + * \return The type of the Network Device. + */ + const EpsBearer::Qci GetType() const; + /** + * \return The reference network layer identifier. + */ + const GbrQosInformation GetQos() const; -private: - const EpsBearer::Qci m_type; - const GbrQosInformation m_qos; + private: + const EpsBearer::Qci m_type; + const GbrQosInformation m_qos; }; } // namespace ns3 diff --git a/src/configuration/lte-netdevice-configuration.cc b/src/configuration/lte-netdevice-configuration.cc index 49837e3..a48f468 100644 --- a/src/configuration/lte-netdevice-configuration.cc +++ b/src/configuration/lte-netdevice-configuration.cc @@ -17,70 +17,70 @@ */ #include "lte-netdevice-configuration.h" -namespace ns3 { +namespace ns3 +{ class LteNetdeviceConfigurationPriv { -public: - static const LteRole ParseRole (const std::string rawRole) - { - if (rawRole == "UE") - return LteRole::UE; - else if (rawRole == "eNB") - return LteRole::eNB; - else - NS_FATAL_ERROR ("Unsupported LTE Role: " << rawRole); - } + public: + static const LteRole ParseRole(const std::string rawRole) + { + if (rawRole == "UE") + return LteRole::UE; + else if (rawRole == "eNB") + return LteRole::eNB; + else + NS_FATAL_ERROR("Unsupported LTE Role: " << rawRole); + } }; -LteNetdeviceConfiguration::LteNetdeviceConfiguration (const std::string type, - const std::string rawRole, - const std::vector bearers, - const uint32_t networkLayerId, - const std::optional antennaModel, - const std::optional phyModel) : - NetdeviceConfiguration {type, networkLayerId}, - m_role {LteNetdeviceConfigurationPriv::ParseRole (rawRole)}, - m_bearers {bearers}, - m_antennaModel {antennaModel}, - m_phyModel {phyModel} +LteNetdeviceConfiguration::LteNetdeviceConfiguration( + const std::string type, + const std::string rawRole, + const std::vector bearers, + const uint32_t networkLayerId, + const std::optional antennaModel, + const std::optional phyModel) + : NetdeviceConfiguration{type, networkLayerId}, + m_role{LteNetdeviceConfigurationPriv::ParseRole(rawRole)}, + m_bearers{bearers}, + m_antennaModel{antennaModel}, + m_phyModel{phyModel} { - } -LteNetdeviceConfiguration::~LteNetdeviceConfiguration () +LteNetdeviceConfiguration::~LteNetdeviceConfiguration() { - } const LteRole -LteNetdeviceConfiguration::GetRole () const +LteNetdeviceConfiguration::GetRole() const { - return m_role; + return m_role; } const std::vector -LteNetdeviceConfiguration::GetBearers () const +LteNetdeviceConfiguration::GetBearers() const { - return m_bearers; + return m_bearers; } const uint32_t -LteNetdeviceConfiguration::GetNetworkLayerId () const +LteNetdeviceConfiguration::GetNetworkLayerId() const { - return NetdeviceConfiguration::GetNetworkLayerId (); + return NetdeviceConfiguration::GetNetworkLayerId(); } const std::optional -LteNetdeviceConfiguration::GetAntennaModel () const +LteNetdeviceConfiguration::GetAntennaModel() const { - return m_antennaModel; + return m_antennaModel; } const std::optional -LteNetdeviceConfiguration::GetPhyModel () const +LteNetdeviceConfiguration::GetPhyModel() const { - return m_phyModel; + return m_phyModel; } } // namespace ns3 diff --git a/src/configuration/lte-netdevice-configuration.h b/src/configuration/lte-netdevice-configuration.h index 1d8376e..37dffe8 100644 --- a/src/configuration/lte-netdevice-configuration.h +++ b/src/configuration/lte-netdevice-configuration.h @@ -18,18 +18,20 @@ #ifndef LTE_NETDEVICE_CONFIGURATION_H #define LTE_NETDEVICE_CONFIGURATION_H -#include +#include "lte-bearer-configuration.h" +#include "netdevice-configuration.h" #include -#include "lte-bearer-configuration.h" -#include "netdevice-configuration.h" +#include -namespace ns3 { +namespace ns3 +{ -enum LteRole { - UE, - eNB +enum LteRole +{ + UE, + eNB }; /** @@ -37,49 +39,48 @@ enum LteRole { */ class LteNetdeviceConfiguration : public NetdeviceConfiguration { -public: - /** - * Create a new object instance. - * - * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol Stack). - * \param rawRole The role of the network device in the LTE RAN (e.g., UE or eNB). - * This string will be parsed in the correct role. - * \param bearers The bearers to be initialised for this network device. - * \param networkLayerId The identifier for the Network Layer that has been defined for this simulation. - * It must be compatible with the given type and macLayer. - */ - LteNetdeviceConfiguration (const std::string type, - const std::string rawRole, - const std::vector bearers, - const uint32_t networkLayerId, - const std::optional antennaModel, - const std::optional phyModel); - /** Default destructor */ - ~LteNetdeviceConfiguration (); + public: + /** + * Create a new object instance. + * + * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol + * Stack). \param rawRole The role of the network device in the LTE RAN (e.g., UE or eNB). This + * string will be parsed in the correct role. \param bearers The bearers to be initialised for + * this network device. \param networkLayerId The identifier for the Network Layer that has been + * defined for this simulation. It must be compatible with the given type and macLayer. + */ + LteNetdeviceConfiguration(const std::string type, + const std::string rawRole, + const std::vector bearers, + const uint32_t networkLayerId, + const std::optional antennaModel, + const std::optional phyModel); + /** Default destructor */ + ~LteNetdeviceConfiguration(); - /** - * \return The role of the Network Device in the LTE network. - */ - const LteRole GetRole() const; - /** - * \return The bearers configuration for the Network Device. - */ - const std::vector GetBearers() const; - /** - * \brief Network Layer IDs are valid only in case of UEs, not eNBs. - * \return The network layer ID configured for the Network Device. - */ - const uint32_t GetNetworkLayerId () const override; - /** \return The antenna model configuration for the Network Device. */ - const std::optional GetAntennaModel () const; - /** \return The phy model configuration for the Network Device. */ - const std::optional GetPhyModel () const; + /** + * \return The role of the Network Device in the LTE network. + */ + const LteRole GetRole() const; + /** + * \return The bearers configuration for the Network Device. + */ + const std::vector GetBearers() const; + /** + * \brief Network Layer IDs are valid only in case of UEs, not eNBs. + * \return The network layer ID configured for the Network Device. + */ + const uint32_t GetNetworkLayerId() const override; + /** \return The antenna model configuration for the Network Device. */ + const std::optional GetAntennaModel() const; + /** \return The phy model configuration for the Network Device. */ + const std::optional GetPhyModel() const; -private: - const LteRole m_role; - const std::vector m_bearers; - const std::optional m_antennaModel; - const std::optional m_phyModel; + private: + const LteRole m_role; + const std::vector m_bearers; + const std::optional m_antennaModel; + const std::optional m_phyModel; }; } // namespace ns3 diff --git a/src/configuration/lte-phy-layer-configuration.cc b/src/configuration/lte-phy-layer-configuration.cc index 33ae82a..3996eb2 100644 --- a/src/configuration/lte-phy-layer-configuration.cc +++ b/src/configuration/lte-phy-layer-configuration.cc @@ -19,34 +19,34 @@ #include -namespace ns3 { - -LtePhyLayerConfiguration::LtePhyLayerConfiguration(std::string phyType, - std::vector attributes, - std::optional channelPropagationLossModel, - ModelConfiguration channelSpectrumModel) : - PhyLayerConfiguration {phyType, attributes}, - m_channelPropagationLossModel {channelPropagationLossModel}, - m_channelSpectrumModel {channelSpectrumModel} +namespace ns3 { +LtePhyLayerConfiguration::LtePhyLayerConfiguration( + std::string phyType, + std::vector attributes, + std::optional channelPropagationLossModel, + ModelConfiguration channelSpectrumModel) + : PhyLayerConfiguration{phyType, attributes}, + m_channelPropagationLossModel{channelPropagationLossModel}, + m_channelSpectrumModel{channelSpectrumModel} +{ } LtePhyLayerConfiguration::~LtePhyLayerConfiguration() { - } const std::optional -LtePhyLayerConfiguration::GetChannelPropagationLossModel () +LtePhyLayerConfiguration::GetChannelPropagationLossModel() { - return m_channelPropagationLossModel; + return m_channelPropagationLossModel; } const ModelConfiguration -LtePhyLayerConfiguration::GetChannelSpectrumModel () +LtePhyLayerConfiguration::GetChannelSpectrumModel() { - return m_channelSpectrumModel; + return m_channelSpectrumModel; } } // namespace ns3 diff --git a/src/configuration/lte-phy-layer-configuration.h b/src/configuration/lte-phy-layer-configuration.h index ad2ff43..7946b2f 100644 --- a/src/configuration/lte-phy-layer-configuration.h +++ b/src/configuration/lte-phy-layer-configuration.h @@ -18,50 +18,50 @@ #ifndef LTE_PHY_LAYER_CONFIGURATION_H #define LTE_PHY_LAYER_CONFIGURATION_H -#include -#include -#include - -#include +#include "phy-layer-configuration.h" #include +#include -#include "phy-layer-configuration.h" +#include +#include +#include -namespace ns3 { +namespace ns3 +{ /** * Data class to store information about the WiFi PHY Layer of a Scenario. */ class LtePhyLayerConfiguration : public PhyLayerConfiguration { -public: - /** - * Create a new object instance. - * - * \param phyType The type of the PHY Layer to be configured. It should be "wifi". - * \param channelPropagationLossModel The Propagation Loss Model to be used for this Layer. - * \param channelSpectrumModel The Spectrum Model type to be used. - */ - LtePhyLayerConfiguration (std::string phyType, - std::vector attributes, - std::optional channelPropagationLossModel, - ModelConfiguration channelSpectrumModel); - /** Default destructor */ - ~LtePhyLayerConfiguration (); + public: + /** + * Create a new object instance. + * + * \param phyType The type of the PHY Layer to be configured. It should be "wifi". + * \param channelPropagationLossModel The Propagation Loss Model to be used for this Layer. + * \param channelSpectrumModel The Spectrum Model type to be used. + */ + LtePhyLayerConfiguration(std::string phyType, + std::vector attributes, + std::optional channelPropagationLossModel, + ModelConfiguration channelSpectrumModel); + /** Default destructor */ + ~LtePhyLayerConfiguration(); - /** - * \return The Propagation Loss Model configuration. - */ - const std::optional GetChannelPropagationLossModel (); - /** - * \return The Propagation Loss Model configuration. - */ - const ModelConfiguration GetChannelSpectrumModel (); + /** + * \return The Propagation Loss Model configuration. + */ + const std::optional GetChannelPropagationLossModel(); + /** + * \return The Propagation Loss Model configuration. + */ + const ModelConfiguration GetChannelSpectrumModel(); -private: - const std::optional m_channelPropagationLossModel; - const ModelConfiguration m_channelSpectrumModel; + private: + const std::optional m_channelPropagationLossModel; + const ModelConfiguration m_channelSpectrumModel; }; } // namespace ns3 diff --git a/src/configuration/mac-layer-configuration.cc b/src/configuration/mac-layer-configuration.cc index ef5977a..56e7f82 100644 --- a/src/configuration/mac-layer-configuration.cc +++ b/src/configuration/mac-layer-configuration.cc @@ -17,23 +17,22 @@ */ #include "mac-layer-configuration.h" -namespace ns3 { - -MacLayerConfiguration::MacLayerConfiguration (std::string type) : - m_type {type} +namespace ns3 { +MacLayerConfiguration::MacLayerConfiguration(std::string type) + : m_type{type} +{ } -MacLayerConfiguration::~MacLayerConfiguration () +MacLayerConfiguration::~MacLayerConfiguration() { - } const std::string -MacLayerConfiguration::GetType () const +MacLayerConfiguration::GetType() const { - return m_type; + return m_type; } } // namespace ns3 diff --git a/src/configuration/mac-layer-configuration.h b/src/configuration/mac-layer-configuration.h index a0c2df7..c6a894b 100644 --- a/src/configuration/mac-layer-configuration.h +++ b/src/configuration/mac-layer-configuration.h @@ -18,11 +18,12 @@ #ifndef MAC_LAYER_CONFIGURATION_H #define MAC_LAYER_CONFIGURATION_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ /** * Data class to store information about the MAC Layer of a Scenario. @@ -30,25 +31,25 @@ namespace ns3 { */ class MacLayerConfiguration : public Object { -public: - /** - * Create a new object instance. - * - * \param type The type of the MAC Layer Configuration. - */ - MacLayerConfiguration (std::string type); - /** Default destructor */ - virtual ~MacLayerConfiguration (); - - /** - * \return The type of the decoded MAC Layer. - */ - virtual const std::string GetType () const; - -private: - const std::string m_type; /// MAC Layer type + public: + /** + * Create a new object instance. + * + * \param type The type of the MAC Layer Configuration. + */ + MacLayerConfiguration(std::string type); + /** Default destructor */ + virtual ~MacLayerConfiguration(); + + /** + * \return The type of the decoded MAC Layer. + */ + virtual const std::string GetType() const; + + private: + const std::string m_type; /// MAC Layer type }; -} // ns3 namespace +} // namespace ns3 #endif /* MAC_LAYER_CONFIGURATION_H */ diff --git a/src/configuration/mobility-model-configuration.cc b/src/configuration/mobility-model-configuration.cc index 5909d24..148fc15 100644 --- a/src/configuration/mobility-model-configuration.cc +++ b/src/configuration/mobility-model-configuration.cc @@ -17,32 +17,31 @@ */ #include "mobility-model-configuration.h" -namespace ns3 { - -MobilityModelConfiguration::MobilityModelConfiguration (const std::string name, - const std::vector attributes, - const std::optional initialPosition) : - ModelConfiguration (name, attributes), - m_initialPosition {initialPosition} +namespace ns3 { +MobilityModelConfiguration::MobilityModelConfiguration( + const std::string name, + const std::vector attributes, + const std::optional initialPosition) + : ModelConfiguration(name, attributes), + m_initialPosition{initialPosition} +{ } -MobilityModelConfiguration::MobilityModelConfiguration () : - ModelConfiguration () +MobilityModelConfiguration::MobilityModelConfiguration() + : ModelConfiguration() { - } -MobilityModelConfiguration::~MobilityModelConfiguration () +MobilityModelConfiguration::~MobilityModelConfiguration() { - } const std::optional -MobilityModelConfiguration::GetInitialPosition () const +MobilityModelConfiguration::GetInitialPosition() const { - return m_initialPosition; + return m_initialPosition; } } // namespace ns3 diff --git a/src/configuration/mobility-model-configuration.h b/src/configuration/mobility-model-configuration.h index 8a39dfe..a7d4956 100644 --- a/src/configuration/mobility-model-configuration.h +++ b/src/configuration/mobility-model-configuration.h @@ -18,31 +18,31 @@ #ifndef MOBILITY_MODEL_CONFIGURATION_H #define MOBILITY_MODEL_CONFIGURATION_H -#include - +#include #include -#include +#include -namespace ns3 { +namespace ns3 +{ /** - * Data class specific for Mobility Models configuration, which may set nodes to an initial position through a - * position allocator. + * Data class specific for Mobility Models configuration, which may set nodes to an initial position + * through a position allocator. */ class MobilityModelConfiguration : public ModelConfiguration { -public: - MobilityModelConfiguration (const std::string modelName, - const std::vector modelAttributes, - const std::optional initialPosition); - MobilityModelConfiguration (); - ~MobilityModelConfiguration (); + public: + MobilityModelConfiguration(const std::string modelName, + const std::vector modelAttributes, + const std::optional initialPosition); + MobilityModelConfiguration(); + ~MobilityModelConfiguration(); - const std::optional GetInitialPosition () const; + const std::optional GetInitialPosition() const; -private: - const std::optional m_initialPosition; + private: + const std::optional m_initialPosition; }; } // namespace ns3 diff --git a/src/configuration/netdevice-configuration.cc b/src/configuration/netdevice-configuration.cc index 69b5da1..c6e390b 100644 --- a/src/configuration/netdevice-configuration.cc +++ b/src/configuration/netdevice-configuration.cc @@ -17,31 +17,30 @@ */ #include "netdevice-configuration.h" -namespace ns3 { - -NetdeviceConfiguration::NetdeviceConfiguration (const std::string type, - const uint32_t networkLayerId) : - m_type {type}, - m_networkLayerId {networkLayerId} +namespace ns3 { +NetdeviceConfiguration::NetdeviceConfiguration(const std::string type, + const uint32_t networkLayerId) + : m_type{type}, + m_networkLayerId{networkLayerId} +{ } -NetdeviceConfiguration::~NetdeviceConfiguration () +NetdeviceConfiguration::~NetdeviceConfiguration() { - } const std::string -NetdeviceConfiguration::GetType () const +NetdeviceConfiguration::GetType() const { - return m_type; + return m_type; } const uint32_t -NetdeviceConfiguration::GetNetworkLayerId () const +NetdeviceConfiguration::GetNetworkLayerId() const { - return m_networkLayerId; + return m_networkLayerId; } } // namespace ns3 diff --git a/src/configuration/netdevice-configuration.h b/src/configuration/netdevice-configuration.h index 7362545..38a31bf 100644 --- a/src/configuration/netdevice-configuration.h +++ b/src/configuration/netdevice-configuration.h @@ -18,43 +18,42 @@ #ifndef NETDEVICE_CONFIGURATION_H #define NETDEVICE_CONFIGURATION_H -#include - #include +#include -namespace ns3 { +namespace ns3 +{ /** * Data class to recnognize and configure a Network Device for an entity to be simulated. */ class NetdeviceConfiguration : public Object { -public: - /** - * Create a new object instance. - * - * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol Stack). - * \param macLayer The configuration of the MAC Layer to be simulated for this network device. - * \param networkLayerId The identifier for the Network Layer that has been defined for this simulation. - * It must be compatible with the given type and macLayer. - */ - NetdeviceConfiguration (const std::string type, - const uint32_t networkLayerId); - /** Default destructor */ - ~NetdeviceConfiguration (); - - /** - * \return The type of the Network Device. - */ - const std::string GetType () const; - /** - * \return The reference network layer identifier. - */ - virtual const uint32_t GetNetworkLayerId () const; - -private: - const std::string m_type; - const uint32_t m_networkLayerId; + public: + /** + * Create a new object instance. + * + * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol + * Stack). \param macLayer The configuration of the MAC Layer to be simulated for this network + * device. \param networkLayerId The identifier for the Network Layer that has been defined for + * this simulation. It must be compatible with the given type and macLayer. + */ + NetdeviceConfiguration(const std::string type, const uint32_t networkLayerId); + /** Default destructor */ + ~NetdeviceConfiguration(); + + /** + * \return The type of the Network Device. + */ + const std::string GetType() const; + /** + * \return The reference network layer identifier. + */ + virtual const uint32_t GetNetworkLayerId() const; + + private: + const std::string m_type; + const uint32_t m_networkLayerId; }; } // namespace ns3 diff --git a/src/configuration/network-layer-configuration.cc b/src/configuration/network-layer-configuration.cc index 9a6fb12..1d7c373 100644 --- a/src/configuration/network-layer-configuration.cc +++ b/src/configuration/network-layer-configuration.cc @@ -17,23 +17,22 @@ */ #include "network-layer-configuration.h" -namespace ns3 { - -NetworkLayerConfiguration::NetworkLayerConfiguration (std::string type) : - m_type {type} +namespace ns3 { +NetworkLayerConfiguration::NetworkLayerConfiguration(std::string type) + : m_type{type} +{ } -NetworkLayerConfiguration::~NetworkLayerConfiguration () +NetworkLayerConfiguration::~NetworkLayerConfiguration() { - } const std::string -NetworkLayerConfiguration::GetType () const +NetworkLayerConfiguration::GetType() const { - return m_type; + return m_type; } } // namespace ns3 diff --git a/src/configuration/network-layer-configuration.h b/src/configuration/network-layer-configuration.h index 68998b7..5090b25 100644 --- a/src/configuration/network-layer-configuration.h +++ b/src/configuration/network-layer-configuration.h @@ -18,11 +18,12 @@ #ifndef NETWORK_LAYER_CONFIGURATION_H #define NETWORK_LAYER_CONFIGURATION_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ /** * Data class to store information about the Network Layer of a Scenario. @@ -30,25 +31,25 @@ namespace ns3 { */ class NetworkLayerConfiguration : public Object { -public: - /** - * Create a new object instance. - * - * \param type The type of the Network Layer to be configured. - */ - NetworkLayerConfiguration (std::string type); - /** Default destructor */ - virtual ~NetworkLayerConfiguration (); - - /** - * \return The type of the decoded Network Layer - */ - virtual const std::string GetType () const; - -private: - const std::string m_type; /// Network Layer type + public: + /** + * Create a new object instance. + * + * \param type The type of the Network Layer to be configured. + */ + NetworkLayerConfiguration(std::string type); + /** Default destructor */ + virtual ~NetworkLayerConfiguration(); + + /** + * \return The type of the decoded Network Layer + */ + virtual const std::string GetType() const; + + private: + const std::string m_type; /// Network Layer type }; -} // ns3 namespace +} // namespace ns3 #endif /* NETWORK_LAYER_CONFIGURATION_H */ diff --git a/src/configuration/phy-layer-configuration.cc b/src/configuration/phy-layer-configuration.cc index b146bac..e573e6f 100644 --- a/src/configuration/phy-layer-configuration.cc +++ b/src/configuration/phy-layer-configuration.cc @@ -17,30 +17,30 @@ */ #include "phy-layer-configuration.h" -namespace ns3 { - -PhyLayerConfiguration::PhyLayerConfiguration (std::string type, std::vector attributes) : - m_type {type}, - m_attributes {attributes} +namespace ns3 { +PhyLayerConfiguration::PhyLayerConfiguration(std::string type, + std::vector attributes) + : m_type{type}, + m_attributes{attributes} +{ } -PhyLayerConfiguration::~PhyLayerConfiguration () +PhyLayerConfiguration::~PhyLayerConfiguration() { - } const std::string -PhyLayerConfiguration::GetType () const +PhyLayerConfiguration::GetType() const { - return m_type; + return m_type; } const std::vector -PhyLayerConfiguration::GetAttributes () const +PhyLayerConfiguration::GetAttributes() const { - return m_attributes; + return m_attributes; } } // namespace ns3 diff --git a/src/configuration/phy-layer-configuration.h b/src/configuration/phy-layer-configuration.h index 03ae073..6bd03ce 100644 --- a/src/configuration/phy-layer-configuration.h +++ b/src/configuration/phy-layer-configuration.h @@ -18,14 +18,14 @@ #ifndef PHY_LAYER_CONFIGURATION_H #define PHY_LAYER_CONFIGURATION_H -#include -#include - +#include #include -#include +#include +#include -namespace ns3 { +namespace ns3 +{ /** * Data class to store information about the PHY Layer of a Scenario. @@ -33,30 +33,30 @@ namespace ns3 { */ class PhyLayerConfiguration : public Object { -public: - /** - * Create a new object instance. - * - * \param type The type of the PHY Layer to be configured. - */ - PhyLayerConfiguration (std::string type, std::vector attributes); - /** Default destructor */ - virtual ~PhyLayerConfiguration (); - - /** - * \brief The type of the decoded PHY Layer - */ - virtual const std::string GetType () const; - /** - * \brief The attributes of the decoded PHY Layer - */ - virtual const std::vector GetAttributes () const; - -private: - const std::string m_type; /// PHY Layer type - const std::vector m_attributes; /// PHY Layer Attributes + public: + /** + * Create a new object instance. + * + * \param type The type of the PHY Layer to be configured. + */ + PhyLayerConfiguration(std::string type, std::vector attributes); + /** Default destructor */ + virtual ~PhyLayerConfiguration(); + + /** + * \brief The type of the decoded PHY Layer + */ + virtual const std::string GetType() const; + /** + * \brief The attributes of the decoded PHY Layer + */ + virtual const std::vector GetAttributes() const; + + private: + const std::string m_type; /// PHY Layer type + const std::vector m_attributes; /// PHY Layer Attributes }; -} // ns3 namespace +} // namespace ns3 #endif /* PHY_LAYER_CONFIGURATION_H */ diff --git a/src/configuration/remote-configuration.cc b/src/configuration/remote-configuration.cc index b16476d..f5a3725 100644 --- a/src/configuration/remote-configuration.cc +++ b/src/configuration/remote-configuration.cc @@ -17,31 +17,30 @@ */ #include "remote-configuration.h" -namespace ns3 { - -RemoteConfiguration::RemoteConfiguration (uint32_t netId, - std::vector applications) : - m_networkLayerId {netId}, - m_applications {applications} +namespace ns3 { +RemoteConfiguration::RemoteConfiguration(uint32_t netId, + std::vector applications) + : m_networkLayerId{netId}, + m_applications{applications} +{ } -RemoteConfiguration::~RemoteConfiguration () +RemoteConfiguration::~RemoteConfiguration() { - } const uint32_t -RemoteConfiguration::GetNetworkLayerId () const +RemoteConfiguration::GetNetworkLayerId() const { - return m_networkLayerId; + return m_networkLayerId; } const std::vector& -RemoteConfiguration::GetApplications () const +RemoteConfiguration::GetApplications() const { - return m_applications; + return m_applications; } } // namespace ns3 diff --git a/src/configuration/remote-configuration.h b/src/configuration/remote-configuration.h index e4b66ff..373d9cd 100644 --- a/src/configuration/remote-configuration.h +++ b/src/configuration/remote-configuration.h @@ -18,11 +18,11 @@ #ifndef REMOTE_CONFIGURATION_H #define REMOTE_CONFIGURATION_H -#include - #include +#include -namespace ns3 { +namespace ns3 +{ /** * \brief Describe the configuration of a remote to be simulated. @@ -30,19 +30,17 @@ namespace ns3 { class RemoteConfiguration : public Object { public: - RemoteConfiguration (uint32_t networkLayerId, - std::vector m_applications); - ~RemoteConfiguration (); + RemoteConfiguration(uint32_t networkLayerId, std::vector m_applications); + ~RemoteConfiguration(); - const uint32_t GetNetworkLayerId () const; - const std::vector& GetApplications () const; + const uint32_t GetNetworkLayerId() const; + const std::vector& GetApplications() const; -private: - const uint32_t m_networkLayerId; - const std::vector m_applications; + private: + const uint32_t m_networkLayerId; + const std::vector m_applications; }; } // namespace ns3 - #endif /* REMOTE_CONFIGURATION_H */ diff --git a/src/configuration/wifi-mac-layer-configuration.cc b/src/configuration/wifi-mac-layer-configuration.cc index 8961878..b86aef4 100644 --- a/src/configuration/wifi-mac-layer-configuration.cc +++ b/src/configuration/wifi-mac-layer-configuration.cc @@ -19,33 +19,33 @@ #include -namespace ns3 { - -WifiMacLayerConfiguration::WifiMacLayerConfiguration(std::string macType, - std::string ssid, - ModelConfiguration remoteStationManagerConfiguration) : - MacLayerConfiguration {macType}, - m_ssid {ssid}, - m_remoteStationManagerConfiguration {remoteStationManagerConfiguration} +namespace ns3 { +WifiMacLayerConfiguration::WifiMacLayerConfiguration( + std::string macType, + std::string ssid, + ModelConfiguration remoteStationManagerConfiguration) + : MacLayerConfiguration{macType}, + m_ssid{ssid}, + m_remoteStationManagerConfiguration{remoteStationManagerConfiguration} +{ } WifiMacLayerConfiguration::~WifiMacLayerConfiguration() { - } const std::string -WifiMacLayerConfiguration::GetSsid () const +WifiMacLayerConfiguration::GetSsid() const { - return m_ssid; + return m_ssid; } const ModelConfiguration -WifiMacLayerConfiguration::GetRemoteStationManagerConfiguration () const +WifiMacLayerConfiguration::GetRemoteStationManagerConfiguration() const { - return m_remoteStationManagerConfiguration; + return m_remoteStationManagerConfiguration; } } // namespace ns3 diff --git a/src/configuration/wifi-mac-layer-configuration.h b/src/configuration/wifi-mac-layer-configuration.h index eba060b..452637c 100644 --- a/src/configuration/wifi-mac-layer-configuration.h +++ b/src/configuration/wifi-mac-layer-configuration.h @@ -18,45 +18,47 @@ #ifndef WIFI_MAC_LAYER_CONFIGURATION_H #define WIFI_MAC_LAYER_CONFIGURATION_H -#include +#include "mac-layer-configuration.h" #include -#include "mac-layer-configuration.h" +#include -namespace ns3 { +namespace ns3 +{ /** * Data class to store information about the WiFi MAC Layer of a Scenario. */ class WifiMacLayerConfiguration : public MacLayerConfiguration { -public: - /** - * Create a new object instance. - * - * \param macType The type of the MAC Layer to be configured. It should be "wifi". - * \param ssid The name of the ssid to configure the BSS. - * \param remoteStationManagerConfiguration The configuration of the Remote Station Manager to set up the BSS. - */ - WifiMacLayerConfiguration (std::string macType, - std::string ssid, - ModelConfiguration remoteStationManagerConfiguration); - /** Default destructor */ - ~WifiMacLayerConfiguration (); + public: + /** + * Create a new object instance. + * + * \param macType The type of the MAC Layer to be configured. It should be "wifi". + * \param ssid The name of the ssid to configure the BSS. + * \param remoteStationManagerConfiguration The configuration of the Remote Station Manager to + * set up the BSS. + */ + WifiMacLayerConfiguration(std::string macType, + std::string ssid, + ModelConfiguration remoteStationManagerConfiguration); + /** Default destructor */ + ~WifiMacLayerConfiguration(); - /** - * \return The configured SSID. - */ - const std::string GetSsid () const; - /** - * \return The Remote Station Manager model configuration. - */ - const ModelConfiguration GetRemoteStationManagerConfiguration () const; + /** + * \return The configured SSID. + */ + const std::string GetSsid() const; + /** + * \return The Remote Station Manager model configuration. + */ + const ModelConfiguration GetRemoteStationManagerConfiguration() const; -private: - const std::string m_ssid; - const ModelConfiguration m_remoteStationManagerConfiguration; + private: + const std::string m_ssid; + const ModelConfiguration m_remoteStationManagerConfiguration; }; } // namespace ns3 diff --git a/src/configuration/wifi-netdevice-configuration.cc b/src/configuration/wifi-netdevice-configuration.cc index 23bfc9e..c4c44e9 100644 --- a/src/configuration/wifi-netdevice-configuration.cc +++ b/src/configuration/wifi-netdevice-configuration.cc @@ -17,26 +17,25 @@ */ #include "wifi-netdevice-configuration.h" -namespace ns3 { - -WifiNetdeviceConfiguration::WifiNetdeviceConfiguration (const std::string type, - const ModelConfiguration macLayer, - const uint32_t networkLayerId) : - NetdeviceConfiguration {type, networkLayerId}, - m_macLayer {macLayer} +namespace ns3 { +WifiNetdeviceConfiguration::WifiNetdeviceConfiguration(const std::string type, + const ModelConfiguration macLayer, + const uint32_t networkLayerId) + : NetdeviceConfiguration{type, networkLayerId}, + m_macLayer{macLayer} +{ } -WifiNetdeviceConfiguration::~WifiNetdeviceConfiguration () +WifiNetdeviceConfiguration::~WifiNetdeviceConfiguration() { - } const ModelConfiguration -WifiNetdeviceConfiguration::GetMacLayer () const +WifiNetdeviceConfiguration::GetMacLayer() const { - return m_macLayer; + return m_macLayer; } } // namespace ns3 diff --git a/src/configuration/wifi-netdevice-configuration.h b/src/configuration/wifi-netdevice-configuration.h index 4568951..23fb696 100644 --- a/src/configuration/wifi-netdevice-configuration.h +++ b/src/configuration/wifi-netdevice-configuration.h @@ -18,41 +18,41 @@ #ifndef WIFI_NETDEVICE_CONFIGURATION_H #define WIFI_NETDEVICE_CONFIGURATION_H -#include +#include "netdevice-configuration.h" #include +#include -#include "netdevice-configuration.h" - -namespace ns3 { +namespace ns3 +{ /** * Data class to recnognize and configure a Network Device for an entity to be simulated. */ class WifiNetdeviceConfiguration : public NetdeviceConfiguration { -public: - /** - * Create a new object instance. - * - * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol Stack). - * \param macLayer The configuration of the MAC Layer to be simulated for this network device. - * \param networkLayerId The identifier for the Network Layer that has been defined for this simulation. - * It must be compatible with the given type and macLayer. - */ - WifiNetdeviceConfiguration (const std::string type, - const ModelConfiguration macLayer, - const uint32_t networkLayerId); - /** Default destructor */ - ~WifiNetdeviceConfiguration (); - - /** - * \return The MAC Layer configuration. - */ - const ModelConfiguration GetMacLayer () const; - -private: - const ModelConfiguration m_macLayer; + public: + /** + * Create a new object instance. + * + * \param type The type of the network device (e.g., "wifi" to use the underlying WiFi Protocol + * Stack). \param macLayer The configuration of the MAC Layer to be simulated for this network + * device. \param networkLayerId The identifier for the Network Layer that has been defined for + * this simulation. It must be compatible with the given type and macLayer. + */ + WifiNetdeviceConfiguration(const std::string type, + const ModelConfiguration macLayer, + const uint32_t networkLayerId); + /** Default destructor */ + ~WifiNetdeviceConfiguration(); + + /** + * \return The MAC Layer configuration. + */ + const ModelConfiguration GetMacLayer() const; + + private: + const ModelConfiguration m_macLayer; }; } // namespace ns3 diff --git a/src/configuration/wifi-phy-layer-configuration.cc b/src/configuration/wifi-phy-layer-configuration.cc index d7e462c..e76f752 100644 --- a/src/configuration/wifi-phy-layer-configuration.cc +++ b/src/configuration/wifi-phy-layer-configuration.cc @@ -19,64 +19,63 @@ #include -namespace ns3 { - -WifiPhyLayerConfiguration::WifiPhyLayerConfiguration(std::string phyType, - std::string standard, - std::vector attributes, - ModelConfiguration channelPropagationDelayModel, - ModelConfiguration channelPropagationLossModel) : - PhyLayerConfiguration {phyType, attributes}, - m_standard {standard}, - m_channelPropagationDelayModel {channelPropagationDelayModel}, - m_channelPropagationLossModel {channelPropagationLossModel} +namespace ns3 { +WifiPhyLayerConfiguration::WifiPhyLayerConfiguration( + std::string phyType, + std::string standard, + std::vector attributes, + ModelConfiguration channelPropagationDelayModel, + ModelConfiguration channelPropagationLossModel) + : PhyLayerConfiguration{phyType, attributes}, + m_standard{standard}, + m_channelPropagationDelayModel{channelPropagationDelayModel}, + m_channelPropagationLossModel{channelPropagationLossModel} +{ } WifiPhyLayerConfiguration::~WifiPhyLayerConfiguration() { - } const enum WifiStandard -WifiPhyLayerConfiguration::GetStandard () +WifiPhyLayerConfiguration::GetStandard() { - - if (m_standard == "802.11a") - return WIFI_STANDARD_80211a; - else if (m_standard == "802.11b") - return WIFI_STANDARD_80211b; - else if (m_standard == "802.11g") - return WIFI_STANDARD_80211g; - else if (m_standard == "802.11p") - return WIFI_STANDARD_80211p; - else if (m_standard == "802.11n-2.4GHz") - return WIFI_STANDARD_80211n; - else if (m_standard == "802.11n-5GHz") - return WIFI_STANDARD_80211n; - else if (m_standard == "802.11ac") - return WIFI_STANDARD_80211ac; - else if (m_standard == "802.11ax-2.4GHz") - return WIFI_STANDARD_80211ax; - else if (m_standard == "802.11ax-5GHz") - return WIFI_STANDARD_80211ax; - else if (m_standard == "802.11ax-6GHz") - return WIFI_STANDARD_80211ax; - else - NS_FATAL_ERROR ("Cannot decode Wifi Standard: " << m_standard); + if (m_standard == "802.11a") + return WIFI_STANDARD_80211a; + else if (m_standard == "802.11b") + return WIFI_STANDARD_80211b; + else if (m_standard == "802.11g") + return WIFI_STANDARD_80211g; + else if (m_standard == "802.11p") + return WIFI_STANDARD_80211p; + else if (m_standard == "802.11n-2.4GHz") + return WIFI_STANDARD_80211n; + else if (m_standard == "802.11n-5GHz") + return WIFI_STANDARD_80211n; + else if (m_standard == "802.11ac") + return WIFI_STANDARD_80211ac; + else if (m_standard == "802.11ax-2.4GHz") + return WIFI_STANDARD_80211ax; + else if (m_standard == "802.11ax-5GHz") + return WIFI_STANDARD_80211ax; + else if (m_standard == "802.11ax-6GHz") + return WIFI_STANDARD_80211ax; + else + NS_FATAL_ERROR("Cannot decode Wifi Standard: " << m_standard); } const ModelConfiguration -WifiPhyLayerConfiguration::GetChannelPropagationDelayModel () +WifiPhyLayerConfiguration::GetChannelPropagationDelayModel() { - return m_channelPropagationDelayModel; + return m_channelPropagationDelayModel; } const ModelConfiguration -WifiPhyLayerConfiguration::GetChannelPropagationLossModel () +WifiPhyLayerConfiguration::GetChannelPropagationLossModel() { - return m_channelPropagationLossModel; + return m_channelPropagationLossModel; } } // namespace ns3 diff --git a/src/configuration/wifi-phy-layer-configuration.h b/src/configuration/wifi-phy-layer-configuration.h index 0468f83..b85f6ec 100644 --- a/src/configuration/wifi-phy-layer-configuration.h +++ b/src/configuration/wifi-phy-layer-configuration.h @@ -18,57 +18,57 @@ #ifndef WIFI_PHY_LAYER_CONFIGURATION_H #define WIFI_PHY_LAYER_CONFIGURATION_H -#include - -#include +#include "phy-layer-configuration.h" #include +#include -#include "phy-layer-configuration.h" +#include -namespace ns3 { +namespace ns3 +{ /** * Data class to store information about the WiFi PHY Layer of a Scenario. */ class WifiPhyLayerConfiguration : public PhyLayerConfiguration { -public: - /** - * Create a new object instance. - * - * \param phyType The type of the PHY Layer to be configured. It should be "wifi". - * \param standard The reference WiFi Standard. - * \param attributes Wi-Fi PHY Attributes. - * \param mode The mode of WiFi PHY according to YANS. - * \param channelPropagationDelayModel The Propagation Delay Model to be used for this Layer. - * \param channelPropagationLossModel The Propagation Loss Model to be used for this Layer. - */ - WifiPhyLayerConfiguration (std::string phyType, - std::string standard, - std::vector attributes, - ModelConfiguration channelPropagationDelayModel, - ModelConfiguration channelPropagationLossModel); - /** Default destructor */ - ~WifiPhyLayerConfiguration (); + public: + /** + * Create a new object instance. + * + * \param phyType The type of the PHY Layer to be configured. It should be "wifi". + * \param standard The reference WiFi Standard. + * \param attributes Wi-Fi PHY Attributes. + * \param mode The mode of WiFi PHY according to YANS. + * \param channelPropagationDelayModel The Propagation Delay Model to be used for this Layer. + * \param channelPropagationLossModel The Propagation Loss Model to be used for this Layer. + */ + WifiPhyLayerConfiguration(std::string phyType, + std::string standard, + std::vector attributes, + ModelConfiguration channelPropagationDelayModel, + ModelConfiguration channelPropagationLossModel); + /** Default destructor */ + ~WifiPhyLayerConfiguration(); - /** - * \return The configured WiFi Standard. - */ - const enum WifiStandard GetStandard (); - /** - * \return The Propagation Delay Model configuration. - */ - const ModelConfiguration GetChannelPropagationDelayModel (); - /** - * \return The Propagation Loss Model configuration. - */ - const ModelConfiguration GetChannelPropagationLossModel (); + /** + * \return The configured WiFi Standard. + */ + const enum WifiStandard GetStandard(); + /** + * \return The Propagation Delay Model configuration. + */ + const ModelConfiguration GetChannelPropagationDelayModel(); + /** + * \return The Propagation Loss Model configuration. + */ + const ModelConfiguration GetChannelPropagationLossModel(); -private: - const std::string m_standard; - const ModelConfiguration m_channelPropagationDelayModel; - const ModelConfiguration m_channelPropagationLossModel; + private: + const std::string m_standard; + const ModelConfiguration m_channelPropagationDelayModel; + const ModelConfiguration m_channelPropagationLossModel; }; } // namespace ns3 diff --git a/src/entity/drone-container.cc b/src/entity/drone-container.cc index bb26197..c587159 100644 --- a/src/entity/drone-container.cc +++ b/src/entity/drone-container.cc @@ -15,52 +15,53 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -#include -#include +#include "drone-container.h" +#include "drone-energy-model.h" + +#include #include #include +#include -#include "drone-container.h" -#include "drone-energy-model.h" - -namespace ns3 { +namespace ns3 +{ void -DroneContainer::Create (uint32_t n) +DroneContainer::Create(uint32_t n) { - for (uint32_t i = 0; i < n; i++) + for (uint32_t i = 0; i < n; i++) { - auto drone = CreateObject (); - drone->getPeripherals()->SetDrone(drone); - m_drones.push_back (drone); - auto nativenode = StaticCast (drone); - NodeContainer::Add (nativenode); + auto drone = CreateObject(); + drone->getPeripherals()->SetDrone(drone); + m_drones.push_back(drone); + auto nativenode = StaticCast(drone); + NodeContainer::Add(nativenode); } } uint32_t -DroneContainer::GetN (void) const +DroneContainer::GetN(void) const { - return m_drones.size (); + return m_drones.size(); } Ptr -DroneContainer::Get (uint32_t i) const +DroneContainer::Get(uint32_t i) const { - return m_drones[i]; + return m_drones[i]; } DroneContainer::Iterator -DroneContainer::Begin (void) const +DroneContainer::Begin(void) const { - return m_drones.begin (); + return m_drones.begin(); } DroneContainer::Iterator -DroneContainer::End (void) const +DroneContainer::End(void) const { - return m_drones.end (); + return m_drones.end(); } } // namespace ns3 diff --git a/src/entity/drone-container.h b/src/entity/drone-container.h index 4c60a1e..50f1ada 100644 --- a/src/entity/drone-container.h +++ b/src/entity/drone-container.h @@ -18,63 +18,64 @@ #ifndef DRONE_CONTAINER_H #define DRONE_CONTAINER_H -#include - #include "drone.h" -namespace ns3 { +#include + +namespace ns3 +{ /** * \brief Keeps track of a set of drones pointers. */ class DroneContainer : public NodeContainer { -public: - /// Drone container iterator - typedef std::vector>::const_iterator Iterator; + public: + /// Drone container iterator + typedef std::vector>::const_iterator Iterator; - /** - * \brief Create n drones and append pointers to them to the end of this - * DroneContainer. - * - * \param n The number of Drones to create - */ - void Create (uint32_t n); + /** + * \brief Create n drones and append pointers to them to the end of this + * DroneContainer. + * + * \param n The number of Drones to create + */ + void Create(uint32_t n); - /** - * \brief Get an iterator which refers to the first Drone in the - * container. - * - * \returns an iterator which refers to the first Drone in the container. - */ - Iterator Begin (void) const; + /** + * \brief Get an iterator which refers to the first Drone in the + * container. + * + * \returns an iterator which refers to the first Drone in the container. + */ + Iterator Begin(void) const; - /** - * \brief Get an iterator which indicates past-the-last Drone in the - * container. - * - * \returns an iterator which indicates an ending condition for a loop. - */ - Iterator End (void) const; + /** + * \brief Get an iterator which indicates past-the-last Drone in the + * container. + * + * \returns an iterator which indicates an ending condition for a loop. + */ + Iterator End(void) const; - /** - * \brief Get the number of Ptr stored in this container. - * - * \returns the number of Ptr stored in this container. - */ - uint32_t GetN (void) const; + /** + * \brief Get the number of Ptr stored in this container. + * + * \returns the number of Ptr stored in this container. + */ + uint32_t GetN(void) const; - /** - * \brief Get the Ptr stored in this container at a given - * index. - * - * \param i the index of the requested drone pointer. - * \returns the requested drone pointer. - */ - Ptr Get (uint32_t i) const; + /** + * \brief Get the Ptr stored in this container at a given + * index. + * + * \param i the index of the requested drone pointer. + * \returns the requested drone pointer. + */ + Ptr Get(uint32_t i) const; -private: - std::vector> m_drones; //!< Drones smart pointers + private: + std::vector> m_drones; //!< Drones smart pointers }; } // namespace ns3 diff --git a/src/entity/drone-energy-model.cc b/src/entity/drone-energy-model.cc index 0bf6181..4e8c033 100644 --- a/src/entity/drone-energy-model.cc +++ b/src/entity/drone-energy-model.cc @@ -22,111 +22,115 @@ #define AIR_DENSITY 1.225 -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("DroneEnergyModel"); +NS_LOG_COMPONENT_DEFINE("DroneEnergyModel"); -NS_OBJECT_ENSURE_REGISTERED (DroneEnergyModel); +NS_OBJECT_ENSURE_REGISTERED(DroneEnergyModel); TypeId -DroneEnergyModel::GetTypeId (void) +DroneEnergyModel::GetTypeId(void) { - static TypeId tid = TypeId ("ns3::DroneEnergyModel") - .SetParent () - .SetGroupName ("Energy") - .AddConstructor (); - return tid; + static TypeId tid = TypeId("ns3::DroneEnergyModel") + .SetParent() + .SetGroupName("Energy") + .AddConstructor(); + return tid; } -DroneEnergyModel::DroneEnergyModel () +DroneEnergyModel::DroneEnergyModel() { - NS_LOG_FUNCTION (this); - m_source = 0; + NS_LOG_FUNCTION(this); + m_source = 0; } void -DroneEnergyModel::SetEnergySource (Ptr source) +DroneEnergyModel::SetEnergySource(Ptr source) { - NS_LOG_FUNCTION (this << source); - m_source = source; + NS_LOG_FUNCTION(this << source); + m_source = source; } void -DroneEnergyModel::SetDrone (Ptr drone) +DroneEnergyModel::SetDrone(Ptr drone) { - NS_LOG_FUNCTION (this << drone); - NS_ASSERT (drone != NULL); - m_drone = drone; + NS_LOG_FUNCTION(this << drone); + NS_ASSERT(drone != NULL); + m_drone = drone; } Ptr -DroneEnergyModel::GetDrone () const +DroneEnergyModel::GetDrone() const { - return m_drone; + return m_drone; } void -DroneEnergyModel::HandleEnergyDepletion () +DroneEnergyModel::HandleEnergyDepletion() { - Time time = Simulator::Now (); - NS_LOG_DEBUG ("DroneEnergyModel:LowBatteryThreshold on Drone #" - << GetDrone ()->GetId () << " crossed at " << time.GetSeconds () << " seconds."); + Time time = Simulator::Now(); + NS_LOG_DEBUG("DroneEnergyModel:LowBatteryThreshold on Drone #" + << GetDrone()->GetId() << " crossed at " << time.GetSeconds() << " seconds."); } double -DroneEnergyModel::GetPeripheralsPowerConsumption (void) const +DroneEnergyModel::GetPeripheralsPowerConsumption(void) const { - double peripheralsPowerConsumption = 0; + double peripheralsPowerConsumption = 0; - for (auto i = m_drone->getPeripherals ()->Begin (); i != m_drone->getPeripherals ()->End (); i++) + for (auto i = m_drone->getPeripherals()->Begin(); i != m_drone->getPeripherals()->End(); i++) { - peripheralsPowerConsumption += (*i)->GetPowerConsumption (); + peripheralsPowerConsumption += (*i)->GetPowerConsumption(); } - NS_LOG_DEBUG ("DroneEnergyModel:Peripherals Power Consumption on Drone #" - << GetDrone ()->GetId () << ": " << peripheralsPowerConsumption << " W"); - return peripheralsPowerConsumption; + NS_LOG_DEBUG("DroneEnergyModel:Peripherals Power Consumption on Drone #" + << GetDrone()->GetId() << ": " << peripheralsPowerConsumption << " W"); + return peripheralsPowerConsumption; } double -DroneEnergyModel::GetPower () const +DroneEnergyModel::GetPower() const { - Ptr drone = GetDrone (); - Ptr obj = StaticCast (drone); - Vector velocity = obj->GetObject ()->GetVelocity (); - double Phover = sqrt (drone->getWeight () / (2 * AIR_DENSITY * drone->getArea ())); - double Plevel = ((pow (drone->getWeight (), 2)) / (sqrt (2) * AIR_DENSITY * drone->getArea ())) * - (1 / sqrt (pow (velocity.x, 2) + pow (velocity.y, 2) + - sqrt (pow (sqrt (pow (velocity.x, 2) + pow (velocity.y, 2)), 4) + - (4 * pow (Phover, 4))))); - double Pdrag = (1 / 8) * drone->getDragCoefficient () * AIR_DENSITY * drone->getArea () * - pow (sqrt (pow (velocity.x, 2) + pow (velocity.y, 2)), 3); - double Pvertical = drone->getWeight () * velocity.z; - - if (Pvertical < 0.0) - Pvertical = 0.0; - - double PowerConsumption = Plevel + Pdrag + Pvertical; - - NS_LOG_LOGIC ("Plevel for Drone #" << GetDrone ()->GetId () << ": " << Plevel << " W"); - NS_LOG_LOGIC ("Pdrag for Drone #" << GetDrone ()->GetId () << ": " << Pdrag << " W"); - NS_LOG_LOGIC ("Pvertical for Drone #" << GetDrone ()->GetId () << ": " << Pvertical << " W"); - NS_LOG_LOGIC ("Mechanical Power Consumption for Drone #" << GetDrone ()->GetId () << ": " << PowerConsumption << " W"); - - return PowerConsumption; + Ptr drone = GetDrone(); + Ptr obj = StaticCast(drone); + Vector velocity = obj->GetObject()->GetVelocity(); + double Phover = sqrt(drone->getWeight() / (2 * AIR_DENSITY * drone->getArea())); + double Plevel = + ((pow(drone->getWeight(), 2)) / (sqrt(2) * AIR_DENSITY * drone->getArea())) * + (1 / + sqrt(pow(velocity.x, 2) + pow(velocity.y, 2) + + sqrt(pow(sqrt(pow(velocity.x, 2) + pow(velocity.y, 2)), 4) + (4 * pow(Phover, 4))))); + double Pdrag = (1 / 8) * drone->getDragCoefficient() * AIR_DENSITY * drone->getArea() * + pow(sqrt(pow(velocity.x, 2) + pow(velocity.y, 2)), 3); + double Pvertical = drone->getWeight() * velocity.z; + + if (Pvertical < 0.0) + Pvertical = 0.0; + + double PowerConsumption = Plevel + Pdrag + Pvertical; + + NS_LOG_LOGIC("Plevel for Drone #" << GetDrone()->GetId() << ": " << Plevel << " W"); + NS_LOG_LOGIC("Pdrag for Drone #" << GetDrone()->GetId() << ": " << Pdrag << " W"); + NS_LOG_LOGIC("Pvertical for Drone #" << GetDrone()->GetId() << ": " << Pvertical << " W"); + NS_LOG_LOGIC("Mechanical Power Consumption for Drone #" << GetDrone()->GetId() << ": " + << PowerConsumption << " W"); + + return PowerConsumption; } double -DroneEnergyModel::DoGetCurrentA (void) const +DroneEnergyModel::DoGetCurrentA(void) const { - double PowerConsumption = GetPower () + GetPeripheralsPowerConsumption (); - double VoltageV = m_source->GetSupplyVoltage (); - double CurrentA = (PowerConsumption / VoltageV); + double PowerConsumption = GetPower() + GetPeripheralsPowerConsumption(); + double VoltageV = m_source->GetSupplyVoltage(); + double CurrentA = (PowerConsumption / VoltageV); - NS_LOG_LOGIC ("Total Power Consumption for Drone #" << GetDrone ()->GetId () << ": " << PowerConsumption << " W"); - NS_LOG_LOGIC ("Current draw for Drone #" << GetDrone ()->GetId () << ": " << CurrentA << " A"); + NS_LOG_LOGIC("Total Power Consumption for Drone #" << GetDrone()->GetId() << ": " + << PowerConsumption << " W"); + NS_LOG_LOGIC("Current draw for Drone #" << GetDrone()->GetId() << ": " << CurrentA << " A"); - return CurrentA; + return CurrentA; } } // namespace ns3 diff --git a/src/entity/drone-energy-model.h b/src/entity/drone-energy-model.h index dacf6fe..c34431c 100644 --- a/src/entity/drone-energy-model.h +++ b/src/entity/drone-energy-model.h @@ -18,13 +18,14 @@ #ifndef DRONE_ENERGY_MODEL_H #define DRONE_ENERGY_MODEL_H +#include "drone.h" + #include #include #include -#include "drone.h" - -namespace ns3 { +namespace ns3 +{ /** * \ingroup energy @@ -33,122 +34,119 @@ namespace ns3 { */ class DroneEnergyModel : public DeviceEnergyModel { -public: - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); - - DroneEnergyModel (); - - ~DroneEnergyModel () - { - } - - /** - * \brief Sets the pointer to energy source installed on drone. - * - * \param source Pointer to energy source installed on drone. - */ - virtual void SetEnergySource (Ptr source); - - /** - * \brief Sets the pointer of the drone. - * - * \param drone Pointer of the drone. - */ - void SetDrone (Ptr drone); - - /** - * \brief Returns the pointer of the drone. - * - * \returns Pointer of the drone. - */ - Ptr GetDrone () const; - - /** - * \brief Implements DeviceEnergyModel::GetTotalEnergyConsumption. - * - * Not implemented. - * - * \returns Total energy consumption of the device. (Not implemented!) - */ - virtual double GetTotalEnergyConsumption (void) const - { - return 0; - } - - /** - * \brief Calculates the mechanical power consumption of the drone. - * - * This method implements the power consumption model employed in - * - * Sun, Y., Xu, D., Ng, D. W. K., Dai, L., & Schober, R. (2019). - * Optimal 3D-trajectory design and resource allocation for solar-powered UAV communication systems. - * IEEE Transactions on Communications, 67(6), 4281-4298. - * - * \returns Mechanical power consumption in Watt. - */ - double GetPower (void) const; - - /** - * \brief Calculates the power consumption of the drone peripherals. - * - * \returns Peripherals power consumption in Watt. - */ - double GetPeripheralsPowerConsumption (void) const; - - /** - * \brief Notifies the low battery threshold being crossed. - * - * This method logs the time at which the remaining energy in the EnergySource - * crosses the low battery threshold. - */ - virtual void HandleEnergyDepletion (void); - - /** - * \param newState New state the device is in. - * - * Not implemented - */ - virtual void - ChangeState (int newState) - { - } - - /** - * \brief Handles energy recharged. - * - * Not implemented - */ - virtual void - HandleEnergyRecharged (void) - { - } - - /** - * \brief Handles energy changed. - * - * Not implemented - */ - virtual void - HandleEnergyChanged (void) - { - } - -private: - /** - * \brief Computes the total current draw. - * - * \returns Current draw of the drone and its peripherals in Ampere. - */ - double DoGetCurrentA (void) const; - - Ptr m_source; - Ptr m_drone; - TracedValue m_totalEnergyConsumption; + public: + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); + + DroneEnergyModel(); + + ~DroneEnergyModel() + { + } + + /** + * \brief Sets the pointer to energy source installed on drone. + * + * \param source Pointer to energy source installed on drone. + */ + virtual void SetEnergySource(Ptr source); + + /** + * \brief Sets the pointer of the drone. + * + * \param drone Pointer of the drone. + */ + void SetDrone(Ptr drone); + + /** + * \brief Returns the pointer of the drone. + * + * \returns Pointer of the drone. + */ + Ptr GetDrone() const; + + /** + * \brief Implements DeviceEnergyModel::GetTotalEnergyConsumption. + * + * Not implemented. + * + * \returns Total energy consumption of the device. (Not implemented!) + */ + virtual double GetTotalEnergyConsumption(void) const + { + return 0; + } + + /** + * \brief Calculates the mechanical power consumption of the drone. + * + * This method implements the power consumption model employed in + * + * Sun, Y., Xu, D., Ng, D. W. K., Dai, L., & Schober, R. (2019). + * Optimal 3D-trajectory design and resource allocation for solar-powered UAV communication + * systems. IEEE Transactions on Communications, 67(6), 4281-4298. + * + * \returns Mechanical power consumption in Watt. + */ + double GetPower(void) const; + + /** + * \brief Calculates the power consumption of the drone peripherals. + * + * \returns Peripherals power consumption in Watt. + */ + double GetPeripheralsPowerConsumption(void) const; + + /** + * \brief Notifies the low battery threshold being crossed. + * + * This method logs the time at which the remaining energy in the EnergySource + * crosses the low battery threshold. + */ + virtual void HandleEnergyDepletion(void); + + /** + * \param newState New state the device is in. + * + * Not implemented + */ + virtual void ChangeState(int newState) + { + } + + /** + * \brief Handles energy recharged. + * + * Not implemented + */ + virtual void HandleEnergyRecharged(void) + { + } + + /** + * \brief Handles energy changed. + * + * Not implemented + */ + virtual void HandleEnergyChanged(void) + { + } + + private: + /** + * \brief Computes the total current draw. + * + * \returns Current draw of the drone and its peripherals in Ampere. + */ + double DoGetCurrentA(void) const; + + Ptr m_source; + Ptr m_drone; + TracedValue m_totalEnergyConsumption; }; } // namespace ns3 diff --git a/src/entity/drone-list.cc b/src/entity/drone-list.cc index b3d84e7..ee8ac6b 100644 --- a/src/entity/drone-list.cc +++ b/src/entity/drone-list.cc @@ -20,16 +20,16 @@ #include "drone-list.h" #include +#include #include -#include #include +#include #include -#include - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("DroneList"); +NS_LOG_COMPONENT_DEFINE("DroneList"); /** * \ingroup network @@ -37,191 +37,190 @@ NS_LOG_COMPONENT_DEFINE ("DroneList"); */ class DroneListPriv : public Object { -public: - /** - * \brief Get the type ID. - * \return the object TypeId. - */ - static TypeId GetTypeId (); - - DroneListPriv (); - ~DroneListPriv (); - - /** - * \param drone drone to add - * \returns index of drone in list - * - * This method should be called automatically from Drone::Drone at this time. - */ - uint32_t Add (Ptr drone); - - /** - * \returns a C++ iterator located at the beginning of this list. - */ - DroneList::Iterator Begin () const; - - /** - * \returns a C++ iterator located at the end of this list. - */ - DroneList::Iterator End () const; - - /** - * \param n index of requested Drone. - * \returns the Drone (Node) associated to index n. - */ - Ptr GetDrone (uint32_t n); - - /** - * \returns the number of drones currently in the list. - */ - uint32_t GetNDrones (); - - /** - * \brief Get the drone list object - * \returns the drone list - */ - static Ptr Get (); - -private: - /** - * \brief Get the drone list object - * \returns the drone list - */ - static Ptr *DoGet (); - - /** - * \brief Delete the drones list object - */ - static void Delete (); - - /** - * \brief Dispose the drones in the list - */ - virtual void DoDispose (); - - std::vector> m_drones; //!< drone objects container + public: + /** + * \brief Get the type ID. + * \return the object TypeId. + */ + static TypeId GetTypeId(); + + DroneListPriv(); + ~DroneListPriv(); + + /** + * \param drone drone to add + * \returns index of drone in list + * + * This method should be called automatically from Drone::Drone at this time. + */ + uint32_t Add(Ptr drone); + + /** + * \returns a C++ iterator located at the beginning of this list. + */ + DroneList::Iterator Begin() const; + + /** + * \returns a C++ iterator located at the end of this list. + */ + DroneList::Iterator End() const; + + /** + * \param n index of requested Drone. + * \returns the Drone (Node) associated to index n. + */ + Ptr GetDrone(uint32_t n); + + /** + * \returns the number of drones currently in the list. + */ + uint32_t GetNDrones(); + + /** + * \brief Get the drone list object + * \returns the drone list + */ + static Ptr Get(); + + private: + /** + * \brief Get the drone list object + * \returns the drone list + */ + static Ptr* DoGet(); + + /** + * \brief Delete the drones list object + */ + static void Delete(); + + /** + * \brief Dispose the drones in the list + */ + virtual void DoDispose(); + + std::vector> m_drones; //!< drone objects container }; TypeId -DroneListPriv::GetTypeId () +DroneListPriv::GetTypeId() { - static TypeId tid = TypeId ("ns3::DroneListPriv") - .SetParent () - .SetGroupName("Swarm") - .AddAttribute ("DroneList", "The list of all drones created during the simulation.", - ObjectVectorValue (), - MakeObjectVectorAccessor (&DroneListPriv::m_drones), - MakeObjectVectorChecker ()) - ; - - return tid; + static TypeId tid = TypeId("ns3::DroneListPriv") + .SetParent() + .SetGroupName("Swarm") + .AddAttribute("DroneList", + "The list of all drones created during the simulation.", + ObjectVectorValue(), + MakeObjectVectorAccessor(&DroneListPriv::m_drones), + MakeObjectVectorChecker()); + + return tid; } Ptr -DroneListPriv::Get () +DroneListPriv::Get() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return *DoGet (); + return *DoGet(); } -Ptr * -DroneListPriv::DoGet () +Ptr* +DroneListPriv::DoGet() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - static Ptr ptr = 0; - if (ptr == nullptr) + static Ptr ptr = 0; + if (ptr == nullptr) { - ptr = CreateObject (); - Config::RegisterRootNamespaceObject (ptr); - Simulator::ScheduleDestroy (&DroneListPriv::Delete); + ptr = CreateObject(); + Config::RegisterRootNamespaceObject(ptr); + Simulator::ScheduleDestroy(&DroneListPriv::Delete); } - return &ptr; + return &ptr; } void -DroneListPriv::Delete () +DroneListPriv::Delete() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - Config::UnregisterRootNamespaceObject (Get ()); - (*DoGet ()) = 0; + Config::UnregisterRootNamespaceObject(Get()); + (*DoGet()) = 0; } -DroneListPriv::DroneListPriv () +DroneListPriv::DroneListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -DroneListPriv::~DroneListPriv () +DroneListPriv::~DroneListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -DroneListPriv::DoDispose () +DroneListPriv::DoDispose() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - for (auto drone = m_drones.begin (); - drone != m_drones.end (); - drone++) + for (auto drone = m_drones.begin(); drone != m_drones.end(); drone++) { - (*drone)->Dispose (); + (*drone)->Dispose(); } - m_drones.erase (m_drones.begin (), m_drones.end ()); - Object::DoDispose (); + m_drones.erase(m_drones.begin(), m_drones.end()); + Object::DoDispose(); } uint32_t -DroneListPriv::Add (Ptr drone) +DroneListPriv::Add(Ptr drone) { - NS_LOG_FUNCTION (this << drone); + NS_LOG_FUNCTION(this << drone); - uint32_t index = m_drones.size (); + uint32_t index = m_drones.size(); - m_drones.push_back (drone); - Simulator::ScheduleWithContext (index, TimeStep (0), &Drone::Initialize, drone); + m_drones.push_back(drone); + Simulator::ScheduleWithContext(index, TimeStep(0), &Drone::Initialize, drone); - return index; + return index; } DroneList::Iterator -DroneListPriv::Begin () const +DroneListPriv::Begin() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_drones.begin (); + return m_drones.begin(); } DroneList::Iterator -DroneListPriv::End () const +DroneListPriv::End() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_drones.end (); + return m_drones.end(); } uint32_t -DroneListPriv::GetNDrones () +DroneListPriv::GetNDrones() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_drones.size (); + return m_drones.size(); } Ptr -DroneListPriv::GetDrone (uint32_t n) +DroneListPriv::GetDrone(uint32_t n) { - NS_LOG_FUNCTION (this << n); + NS_LOG_FUNCTION(this << n); - NS_ASSERT_MSG (n < m_drones.size (), "Drone index " << n << - " is out of range (only have " << m_drones.size () << " drones)."); + NS_ASSERT_MSG(n < m_drones.size(), + "Drone index " << n << " is out of range (only have " << m_drones.size() + << " drones)."); - return m_drones[n]; + return m_drones[n]; } } // namespace ns3 @@ -231,46 +230,47 @@ DroneListPriv::GetDrone (uint32_t n) * which calls into the private implementation though * the simulation of a singleton. */ -namespace ns3 { +namespace ns3 +{ uint32_t -DroneList::Add (Ptr drone) +DroneList::Add(Ptr drone) { - NS_LOG_FUNCTION (drone); + NS_LOG_FUNCTION(drone); - return DroneListPriv::Get ()->Add (drone); + return DroneListPriv::Get()->Add(drone); } DroneList::Iterator -DroneList::Begin () +DroneList::Begin() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return DroneListPriv::Get ()->Begin (); + return DroneListPriv::Get()->Begin(); } DroneList::Iterator -DroneList::End () +DroneList::End() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return DroneListPriv::Get ()->End (); + return DroneListPriv::Get()->End(); } Ptr -DroneList::GetDrone (uint32_t n) +DroneList::GetDrone(uint32_t n) { - NS_LOG_FUNCTION (n); + NS_LOG_FUNCTION(n); - return DroneListPriv::Get ()->GetDrone (n); + return DroneListPriv::Get()->GetDrone(n); } uint32_t -DroneList::GetNDrones () +DroneList::GetNDrones() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return DroneListPriv::Get ()->GetNDrones (); + return DroneListPriv::Get()->GetNDrones(); } } // namespace ns3 diff --git a/src/entity/drone-list.h b/src/entity/drone-list.h index 7a955fa..1dfc430 100644 --- a/src/entity/drone-list.h +++ b/src/entity/drone-list.h @@ -20,11 +20,12 @@ #ifndef DRONE_LIST_H #define DRONE_LIST_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ class Drone; class CallbackBase; @@ -38,39 +39,39 @@ class CallbackBase; */ class DroneList { -public: - /// Drone container iterator - typedef std::vector>::const_iterator Iterator; + public: + /// Drone container iterator + typedef std::vector>::const_iterator Iterator; - /** - * \param drone drone to add - * \returns index of drone in list - * - * This method must be called automatically in order to register - * a node as a Drone - */ - static uint32_t Add (Ptr drone); + /** + * \param drone drone to add + * \returns index of drone in list + * + * This method must be called automatically in order to register + * a node as a Drone + */ + static uint32_t Add(Ptr drone); - /** - * \returns a C++ iterator located at the beginning of this list - */ - static Iterator Begin (); + /** + * \returns a C++ iterator located at the beginning of this list + */ + static Iterator Begin(); - /** - * \returns a C++ iterator located at the end of this list - */ - static Iterator End (); + /** + * \returns a C++ iterator located at the end of this list + */ + static Iterator End(); - /** - * \param n the index of requested Drone - * \returns the drone (Node) associated to index n - */ - static Ptr GetDrone (uint32_t n); + /** + * \param n the index of requested Drone + * \returns the drone (Node) associated to index n + */ + static Ptr GetDrone(uint32_t n); - /** - * \returns the number of drones currently in the list - */ - static uint32_t GetNDrones (); + /** + * \returns the number of drones currently in the list + */ + static uint32_t GetNDrones(); }; } // namespace ns3 diff --git a/src/entity/drone.cc b/src/entity/drone.cc index 21bb3c7..99617ad 100644 --- a/src/entity/drone.cc +++ b/src/entity/drone.cc @@ -17,118 +17,123 @@ */ #include "drone.h" -#include -#include -#include #include -#include -#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Drone"); +NS_LOG_COMPONENT_DEFINE("Drone"); -NS_OBJECT_ENSURE_REGISTERED (Drone); +NS_OBJECT_ENSURE_REGISTERED(Drone); TypeId -Drone::GetTypeId (void) +Drone::GetTypeId(void) { - static TypeId tid = TypeId ("ns3::Drone") - .SetParent () - .SetGroupName ("Network") - .AddConstructor () - .AddAttribute ("Mass", "The mass of this Drone.", - DoubleValue (0), - MakeDoubleAccessor (&Drone::setMass, &Drone::getMass), - MakeDoubleChecker ()) - .AddAttribute ("RotorDiskArea", "The area of the rotor disk of this Drone.", - DoubleValue (0), - MakeDoubleAccessor (&Drone::setArea, &Drone::getArea), - MakeDoubleChecker ()) - .AddAttribute ("DragCoefficient", "Drag Coefficient relative to this Drone.", - DoubleValue (0), - MakeDoubleAccessor (&Drone::getDragCoefficient, &Drone::setDragCoefficient), - MakeDoubleChecker ()) - - ; - return tid; + static TypeId tid = TypeId("ns3::Drone") + .SetParent() + .SetGroupName("Network") + .AddConstructor() + .AddAttribute("Mass", + "The mass of this Drone.", + DoubleValue(0), + MakeDoubleAccessor(&Drone::setMass, &Drone::getMass), + MakeDoubleChecker()) + .AddAttribute("RotorDiskArea", + "The area of the rotor disk of this Drone.", + DoubleValue(0), + MakeDoubleAccessor(&Drone::setArea, &Drone::getArea), + MakeDoubleChecker()) + .AddAttribute("DragCoefficient", + "Drag Coefficient relative to this Drone.", + DoubleValue(0), + MakeDoubleAccessor(&Drone::getDragCoefficient, + &Drone::setDragCoefficient), + MakeDoubleChecker()) + + ; + return tid; } -Drone::Drone () +Drone::Drone() { - m_peripheralContainer = CreateObject (); + m_peripheralContainer = CreateObject(); } void -Drone::DoDispose () +Drone::DoDispose() { - NS_LOG_FUNCTION (this); - Node::DoDispose (); + NS_LOG_FUNCTION(this); + Node::DoDispose(); } void -Drone::DoInitialize (void) +Drone::DoInitialize(void) { - NS_LOG_FUNCTION (this); - Node::DoInitialize (); + NS_LOG_FUNCTION(this); + Node::DoInitialize(); } Ptr -Drone::getPeripherals () +Drone::getPeripherals() { - //NS_LOG_FUNCTION (this); - return m_peripheralContainer; + // NS_LOG_FUNCTION (this); + return m_peripheralContainer; } void -Drone::setMass (double mass) +Drone::setMass(double mass) { - m_mass = mass; - m_weightForce = m_mass * GRAVITY; + m_mass = mass; + m_weightForce = m_mass * GRAVITY; } void -Drone::setArea (double area) +Drone::setArea(double area) { - m_diskArea = area; + m_diskArea = area; } void -Drone::setDragCoefficient (double coefficient) +Drone::setDragCoefficient(double coefficient) { - m_dragCoefficient = coefficient; + m_dragCoefficient = coefficient; } double -Drone::getMass () const +Drone::getMass() const { - return m_mass; + return m_mass; } double -Drone::getWeight () const +Drone::getWeight() const { - return m_weightForce; + return m_weightForce; } double -Drone::getArea () const +Drone::getArea() const { - return m_diskArea; + return m_diskArea; } double -Drone::getDragCoefficient () const +Drone::getDragCoefficient() const { - return m_dragCoefficient; + return m_dragCoefficient; } } // namespace ns3 diff --git a/src/entity/drone.h b/src/entity/drone.h index 18639a5..0302790 100644 --- a/src/entity/drone.h +++ b/src/entity/drone.h @@ -21,14 +21,14 @@ #define GRAVITY 9.81 #include +#include #include #include #include #include -#include - -namespace ns3 { +namespace ns3 +{ class DronePeripheralContainer; @@ -41,85 +41,85 @@ class DronePeripheralContainer; */ class Drone : public Node { -public: - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); - - Drone (); - - /** - * \brief Sets the mass of the drone. - * - * \param mass Mass of the drone. - */ - void setMass (double mass); - - /** - * \brief Sets the area of the rotor disk. - * - * \param area Area of the rotor disk. - */ - void setArea (double area); - - /** - * \brief Sets the drag coefficient. - * - * \param coefficient Drag coefficient. - */ - void setDragCoefficient (double coefficient); - - /** - * \brief Returns the mass of the drone. - * - * \returns Mass of the drone. - */ - double getMass () const; - - /** - * \brief Returns the weight force applied to the drone. - * - * \returns Weight force. - */ - double getWeight () const; - - /** - * \brief Returns the area of the rotor disk. - * - * \returns Area of the rotor disk. - */ - double getArea () const; - - /** - * \brief Returns the drag coefficient. - * - * \returns Drag coefficient. - */ - double getDragCoefficient () const; - - /** - * \brief Returns the peripheral container of the drone. - * - * \returns peripheral Pointer to a DronePeripheralContainer. - */ - Ptr getPeripherals (); - -protected: - virtual void DoDispose (void); - virtual void DoInitialize (void); - -private: - double m_mass; //!< Mass of the drone - double m_diskArea; //!< Area of the rotor disk - double m_weightForce; //!< Weight force, equals to m*g - double m_airDensity; //!< Air density - double m_dragCoefficient; //!< Drag Coefficient - Ptr m_peripheralContainer; + public: + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); + + Drone(); + + /** + * \brief Sets the mass of the drone. + * + * \param mass Mass of the drone. + */ + void setMass(double mass); + + /** + * \brief Sets the area of the rotor disk. + * + * \param area Area of the rotor disk. + */ + void setArea(double area); + + /** + * \brief Sets the drag coefficient. + * + * \param coefficient Drag coefficient. + */ + void setDragCoefficient(double coefficient); + + /** + * \brief Returns the mass of the drone. + * + * \returns Mass of the drone. + */ + double getMass() const; + + /** + * \brief Returns the weight force applied to the drone. + * + * \returns Weight force. + */ + double getWeight() const; + + /** + * \brief Returns the area of the rotor disk. + * + * \returns Area of the rotor disk. + */ + double getArea() const; + + /** + * \brief Returns the drag coefficient. + * + * \returns Drag coefficient. + */ + double getDragCoefficient() const; + + /** + * \brief Returns the peripheral container of the drone. + * + * \returns peripheral Pointer to a DronePeripheralContainer. + */ + Ptr getPeripherals(); + + protected: + virtual void DoDispose(void); + virtual void DoInitialize(void); + + private: + double m_mass; //!< Mass of the drone + double m_diskArea; //!< Area of the rotor disk + double m_weightForce; //!< Weight force, equals to m*g + double m_airDensity; //!< Air density + double m_dragCoefficient; //!< Drag Coefficient + Ptr m_peripheralContainer; }; -} //namespace ns3 +} // namespace ns3 #endif /* DRONE_H */ diff --git a/src/entity/remote-list.cc b/src/entity/remote-list.cc index ed2b970..1dfd109 100644 --- a/src/entity/remote-list.cc +++ b/src/entity/remote-list.cc @@ -22,13 +22,14 @@ #include #include #include -#include #include +#include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("RemoteList"); +NS_LOG_COMPONENT_DEFINE("RemoteList"); /** * \ingroup network @@ -36,191 +37,190 @@ NS_LOG_COMPONENT_DEFINE ("RemoteList"); */ class RemoteListPriv : public Object { -public: - /** - * \brief Get the type ID. - * \return the object TypeId. - */ - static TypeId GetTypeId (); - - RemoteListPriv (); - ~RemoteListPriv (); - - /** - * \param remote remote to add - * \returns index of remote in list - * - * This method should be called automatically from Node::Node at this time. - */ - uint32_t Add (Ptr remote); - - /** - * \returns a C++ iterator located at the beginning of this list. - */ - RemoteList::Iterator Begin () const; - - /** - * \returns a C++ iterator located at the end of this list. - */ - RemoteList::Iterator End () const; - - /** - * \param n index of requested node. - * \returns the remote (Node) associated to index n. - */ - Ptr GetRemote (uint32_t n); - - /** - * \returns the number of drones currently in the list. - */ - uint32_t GetNRemotes (); - - /** - * \brief Get the remote list object - * \returns the remote list - */ - static Ptr Get (); - -private: - /** - * \brief Get the remote list object - * \returns the remote list - */ - static Ptr *DoGet (); - - /** - * \brief Delete the drones list object - */ - static void Delete (); - - /** - * \brief Dispose the drones in the list - */ - virtual void DoDispose (); - - std::vector> m_remotes; //!< remote objects container + public: + /** + * \brief Get the type ID. + * \return the object TypeId. + */ + static TypeId GetTypeId(); + + RemoteListPriv(); + ~RemoteListPriv(); + + /** + * \param remote remote to add + * \returns index of remote in list + * + * This method should be called automatically from Node::Node at this time. + */ + uint32_t Add(Ptr remote); + + /** + * \returns a C++ iterator located at the beginning of this list. + */ + RemoteList::Iterator Begin() const; + + /** + * \returns a C++ iterator located at the end of this list. + */ + RemoteList::Iterator End() const; + + /** + * \param n index of requested node. + * \returns the remote (Node) associated to index n. + */ + Ptr GetRemote(uint32_t n); + + /** + * \returns the number of drones currently in the list. + */ + uint32_t GetNRemotes(); + + /** + * \brief Get the remote list object + * \returns the remote list + */ + static Ptr Get(); + + private: + /** + * \brief Get the remote list object + * \returns the remote list + */ + static Ptr* DoGet(); + + /** + * \brief Delete the drones list object + */ + static void Delete(); + + /** + * \brief Dispose the drones in the list + */ + virtual void DoDispose(); + + std::vector> m_remotes; //!< remote objects container }; TypeId -RemoteListPriv::GetTypeId () +RemoteListPriv::GetTypeId() { - static TypeId tid = TypeId ("ns3::RemoteListPriv") - .SetParent () - .SetGroupName("Remotes") - .AddAttribute ("RemoteList", "The list of all remotes created during the simulation.", - ObjectVectorValue (), - MakeObjectVectorAccessor (&RemoteListPriv::m_remotes), - MakeObjectVectorChecker ()) - ; - - return tid; + static TypeId tid = TypeId("ns3::RemoteListPriv") + .SetParent() + .SetGroupName("Remotes") + .AddAttribute("RemoteList", + "The list of all remotes created during the simulation.", + ObjectVectorValue(), + MakeObjectVectorAccessor(&RemoteListPriv::m_remotes), + MakeObjectVectorChecker()); + + return tid; } Ptr -RemoteListPriv::Get () +RemoteListPriv::Get() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return *DoGet (); + return *DoGet(); } -Ptr * -RemoteListPriv::DoGet () +Ptr* +RemoteListPriv::DoGet() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - static Ptr ptr = 0; - if (ptr == nullptr) + static Ptr ptr = 0; + if (ptr == nullptr) { - ptr = CreateObject (); - Config::RegisterRootNamespaceObject (ptr); - Simulator::ScheduleDestroy (&RemoteListPriv::Delete); + ptr = CreateObject(); + Config::RegisterRootNamespaceObject(ptr); + Simulator::ScheduleDestroy(&RemoteListPriv::Delete); } - return &ptr; + return &ptr; } void -RemoteListPriv::Delete () +RemoteListPriv::Delete() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - Config::UnregisterRootNamespaceObject (Get ()); - (*DoGet ()) = 0; + Config::UnregisterRootNamespaceObject(Get()); + (*DoGet()) = 0; } -RemoteListPriv::RemoteListPriv () +RemoteListPriv::RemoteListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -RemoteListPriv::~RemoteListPriv () +RemoteListPriv::~RemoteListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -RemoteListPriv::DoDispose () +RemoteListPriv::DoDispose() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - for (auto remote = m_remotes.begin (); - remote != m_remotes.end (); - remote++) + for (auto remote = m_remotes.begin(); remote != m_remotes.end(); remote++) { - (*remote)->Dispose (); + (*remote)->Dispose(); } - m_remotes.erase (m_remotes.begin (), m_remotes.end ()); - Object::DoDispose (); + m_remotes.erase(m_remotes.begin(), m_remotes.end()); + Object::DoDispose(); } uint32_t -RemoteListPriv::Add (Ptr remote) +RemoteListPriv::Add(Ptr remote) { - NS_LOG_FUNCTION (this << remote); + NS_LOG_FUNCTION(this << remote); - uint32_t index = m_remotes.size (); + uint32_t index = m_remotes.size(); - m_remotes.push_back (remote); - Simulator::ScheduleWithContext (index, TimeStep (0), &Node::Initialize, remote); + m_remotes.push_back(remote); + Simulator::ScheduleWithContext(index, TimeStep(0), &Node::Initialize, remote); - return index; + return index; } RemoteList::Iterator -RemoteListPriv::Begin () const +RemoteListPriv::Begin() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_remotes.begin (); + return m_remotes.begin(); } RemoteList::Iterator -RemoteListPriv::End () const +RemoteListPriv::End() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_remotes.end (); + return m_remotes.end(); } uint32_t -RemoteListPriv::GetNRemotes () +RemoteListPriv::GetNRemotes() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_remotes.size (); + return m_remotes.size(); } Ptr -RemoteListPriv::GetRemote (uint32_t n) +RemoteListPriv::GetRemote(uint32_t n) { - NS_LOG_FUNCTION (this << n); + NS_LOG_FUNCTION(this << n); - NS_ASSERT_MSG (n < m_remotes.size (), "remote index " << n << - " is out of range (only have " << m_remotes.size () << " drones)."); + NS_ASSERT_MSG(n < m_remotes.size(), + "remote index " << n << " is out of range (only have " << m_remotes.size() + << " drones)."); - return m_remotes[n]; + return m_remotes[n]; } } // namespace ns3 @@ -230,46 +230,47 @@ RemoteListPriv::GetRemote (uint32_t n) * which calls into the private implementation though * the simulation of a singleton. */ -namespace ns3 { +namespace ns3 +{ uint32_t -RemoteList::Add (Ptr remote) +RemoteList::Add(Ptr remote) { - NS_LOG_FUNCTION (remote); + NS_LOG_FUNCTION(remote); - return RemoteListPriv::Get ()->Add (remote); + return RemoteListPriv::Get()->Add(remote); } RemoteList::Iterator -RemoteList::Begin () +RemoteList::Begin() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return RemoteListPriv::Get ()->Begin (); + return RemoteListPriv::Get()->Begin(); } RemoteList::Iterator -RemoteList::End () +RemoteList::End() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return RemoteListPriv::Get ()->End (); + return RemoteListPriv::Get()->End(); } Ptr -RemoteList::GetRemote (uint32_t n) +RemoteList::GetRemote(uint32_t n) { - NS_LOG_FUNCTION (n); + NS_LOG_FUNCTION(n); - return RemoteListPriv::Get ()->GetRemote (n); + return RemoteListPriv::Get()->GetRemote(n); } uint32_t -RemoteList::GetNRemotes () +RemoteList::GetNRemotes() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return RemoteListPriv::Get ()->GetNRemotes (); + return RemoteListPriv::Get()->GetNRemotes(); } } // namespace ns3 diff --git a/src/entity/remote-list.h b/src/entity/remote-list.h index 41e368e..0753ca1 100644 --- a/src/entity/remote-list.h +++ b/src/entity/remote-list.h @@ -20,11 +20,12 @@ #ifndef REMOTE_LIST_H #define REMOTE_LIST_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ class Node; class CallbackBase; @@ -38,39 +39,39 @@ class CallbackBase; */ class RemoteList { -public: - /// Remote container iterator - typedef std::vector>::const_iterator Iterator; + public: + /// Remote container iterator + typedef std::vector>::const_iterator Iterator; - /** - * \param remote Remote to add - * \returns index of Remote in list - * - * This method must be called automatically in order to register - * a node as a Remote - */ - static uint32_t Add (Ptr remote); + /** + * \param remote Remote to add + * \returns index of Remote in list + * + * This method must be called automatically in order to register + * a node as a Remote + */ + static uint32_t Add(Ptr remote); - /** - * \returns a C++ iterator located at the beginning of this list - */ - static Iterator Begin (); + /** + * \returns a C++ iterator located at the beginning of this list + */ + static Iterator Begin(); - /** - * \returns a C++ iterator located at the end of this list - */ - static Iterator End (); + /** + * \returns a C++ iterator located at the end of this list + */ + static Iterator End(); - /** - * \param n the index of requested node - * \returns the Remote (Node) associated to index n - */ - static Ptr GetRemote (uint32_t n); + /** + * \param n the index of requested node + * \returns the Remote (Node) associated to index n + */ + static Ptr GetRemote(uint32_t n); - /** - * \returns the number of Remotes currently in the list - */ - static uint32_t GetNRemotes (); + /** + * \returns the number of Remotes currently in the list + */ + static uint32_t GetNRemotes(); }; } // namespace ns3 diff --git a/src/entity/zsp-list.cc b/src/entity/zsp-list.cc index d0df815..f70c4da 100644 --- a/src/entity/zsp-list.cc +++ b/src/entity/zsp-list.cc @@ -22,13 +22,14 @@ #include #include #include -#include #include +#include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ZspList"); +NS_LOG_COMPONENT_DEFINE("ZspList"); /** * \ingroup network @@ -36,191 +37,190 @@ NS_LOG_COMPONENT_DEFINE ("ZspList"); */ class ZspListPriv : public Object { -public: - /** - * \brief Get the type ID. - * \return the object TypeId. - */ - static TypeId GetTypeId (); - - ZspListPriv (); - ~ZspListPriv (); - - /** - * \param zsp zsp to add - * \returns index of zsp in list - * - * This method should be called automatically from Node::Node at this time. - */ - uint32_t Add (Ptr zsp); - - /** - * \returns a C++ iterator located at the beginning of this list. - */ - ZspList::Iterator Begin () const; - - /** - * \returns a C++ iterator located at the end of this list. - */ - ZspList::Iterator End () const; - - /** - * \param n index of requested node. - * \returns the zsp (Node) associated to index n. - */ - Ptr GetZsp (uint32_t n); - - /** - * \returns the number of drones currently in the list. - */ - uint32_t GetNZsps (); - - /** - * \brief Get the zsp list object - * \returns the zsp list - */ - static Ptr Get (); - -private: - /** - * \brief Get the zsp list object - * \returns the zsp list - */ - static Ptr *DoGet (); - - /** - * \brief Delete the drones list object - */ - static void Delete (); - - /** - * \brief Dispose the drones in the list - */ - virtual void DoDispose (); - - std::vector> m_zsps; //!< zsp objects container + public: + /** + * \brief Get the type ID. + * \return the object TypeId. + */ + static TypeId GetTypeId(); + + ZspListPriv(); + ~ZspListPriv(); + + /** + * \param zsp zsp to add + * \returns index of zsp in list + * + * This method should be called automatically from Node::Node at this time. + */ + uint32_t Add(Ptr zsp); + + /** + * \returns a C++ iterator located at the beginning of this list. + */ + ZspList::Iterator Begin() const; + + /** + * \returns a C++ iterator located at the end of this list. + */ + ZspList::Iterator End() const; + + /** + * \param n index of requested node. + * \returns the zsp (Node) associated to index n. + */ + Ptr GetZsp(uint32_t n); + + /** + * \returns the number of drones currently in the list. + */ + uint32_t GetNZsps(); + + /** + * \brief Get the zsp list object + * \returns the zsp list + */ + static Ptr Get(); + + private: + /** + * \brief Get the zsp list object + * \returns the zsp list + */ + static Ptr* DoGet(); + + /** + * \brief Delete the drones list object + */ + static void Delete(); + + /** + * \brief Dispose the drones in the list + */ + virtual void DoDispose(); + + std::vector> m_zsps; //!< zsp objects container }; TypeId -ZspListPriv::GetTypeId () +ZspListPriv::GetTypeId() { - static TypeId tid = TypeId ("ns3::ZspListPriv") - .SetParent () - .SetGroupName("Zsps") - .AddAttribute ("ZspList", "The list of all ZSPs created during the simulation.", - ObjectVectorValue (), - MakeObjectVectorAccessor (&ZspListPriv::m_zsps), - MakeObjectVectorChecker ()) - ; - - return tid; + static TypeId tid = TypeId("ns3::ZspListPriv") + .SetParent() + .SetGroupName("Zsps") + .AddAttribute("ZspList", + "The list of all ZSPs created during the simulation.", + ObjectVectorValue(), + MakeObjectVectorAccessor(&ZspListPriv::m_zsps), + MakeObjectVectorChecker()); + + return tid; } Ptr -ZspListPriv::Get () +ZspListPriv::Get() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return *DoGet (); + return *DoGet(); } -Ptr * -ZspListPriv::DoGet () +Ptr* +ZspListPriv::DoGet() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - static Ptr ptr = 0; - if (ptr == nullptr) + static Ptr ptr = 0; + if (ptr == nullptr) { - ptr = CreateObject (); - Config::RegisterRootNamespaceObject (ptr); - Simulator::ScheduleDestroy (&ZspListPriv::Delete); + ptr = CreateObject(); + Config::RegisterRootNamespaceObject(ptr); + Simulator::ScheduleDestroy(&ZspListPriv::Delete); } - return &ptr; + return &ptr; } void -ZspListPriv::Delete () +ZspListPriv::Delete() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - Config::UnregisterRootNamespaceObject (Get ()); - (*DoGet ()) = 0; + Config::UnregisterRootNamespaceObject(Get()); + (*DoGet()) = 0; } -ZspListPriv::ZspListPriv () +ZspListPriv::ZspListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ZspListPriv::~ZspListPriv () +ZspListPriv::~ZspListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ZspListPriv::DoDispose () +ZspListPriv::DoDispose() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - for (auto zsp = m_zsps.begin (); - zsp != m_zsps.end (); - zsp++) + for (auto zsp = m_zsps.begin(); zsp != m_zsps.end(); zsp++) { - (*zsp)->Dispose (); + (*zsp)->Dispose(); } - m_zsps.erase (m_zsps.begin (), m_zsps.end ()); - Object::DoDispose (); + m_zsps.erase(m_zsps.begin(), m_zsps.end()); + Object::DoDispose(); } uint32_t -ZspListPriv::Add (Ptr zsp) +ZspListPriv::Add(Ptr zsp) { - NS_LOG_FUNCTION (this << zsp); + NS_LOG_FUNCTION(this << zsp); - uint32_t index = m_zsps.size (); + uint32_t index = m_zsps.size(); - m_zsps.push_back (zsp); - Simulator::ScheduleWithContext (index, TimeStep (0), &Node::Initialize, zsp); + m_zsps.push_back(zsp); + Simulator::ScheduleWithContext(index, TimeStep(0), &Node::Initialize, zsp); - return index; + return index; } ZspList::Iterator -ZspListPriv::Begin () const +ZspListPriv::Begin() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_zsps.begin (); + return m_zsps.begin(); } ZspList::Iterator -ZspListPriv::End () const +ZspListPriv::End() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_zsps.end (); + return m_zsps.end(); } uint32_t -ZspListPriv::GetNZsps () +ZspListPriv::GetNZsps() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_zsps.size (); + return m_zsps.size(); } Ptr -ZspListPriv::GetZsp (uint32_t n) +ZspListPriv::GetZsp(uint32_t n) { - NS_LOG_FUNCTION (this << n); + NS_LOG_FUNCTION(this << n); - NS_ASSERT_MSG (n < m_zsps.size (), "zsp index " << n << - " is out of range (only have " << m_zsps.size () << " drones)."); + NS_ASSERT_MSG(n < m_zsps.size(), + "zsp index " << n << " is out of range (only have " << m_zsps.size() + << " drones)."); - return m_zsps[n]; + return m_zsps[n]; } } // namespace ns3 @@ -230,46 +230,47 @@ ZspListPriv::GetZsp (uint32_t n) * which calls into the private implementation though * the simulation of a singleton. */ -namespace ns3 { +namespace ns3 +{ uint32_t -ZspList::Add (Ptr zsp) +ZspList::Add(Ptr zsp) { - NS_LOG_FUNCTION (zsp); + NS_LOG_FUNCTION(zsp); - return ZspListPriv::Get ()->Add (zsp); + return ZspListPriv::Get()->Add(zsp); } ZspList::Iterator -ZspList::Begin () +ZspList::Begin() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return ZspListPriv::Get ()->Begin (); + return ZspListPriv::Get()->Begin(); } ZspList::Iterator -ZspList::End () +ZspList::End() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return ZspListPriv::Get ()->End (); + return ZspListPriv::Get()->End(); } Ptr -ZspList::GetZsp (uint32_t n) +ZspList::GetZsp(uint32_t n) { - NS_LOG_FUNCTION (n); + NS_LOG_FUNCTION(n); - return ZspListPriv::Get ()->GetZsp (n); + return ZspListPriv::Get()->GetZsp(n); } uint32_t -ZspList::GetNZsps () +ZspList::GetNZsps() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return ZspListPriv::Get ()->GetNZsps (); + return ZspListPriv::Get()->GetNZsps(); } } // namespace ns3 diff --git a/src/entity/zsp-list.h b/src/entity/zsp-list.h index df2ea83..674d46e 100644 --- a/src/entity/zsp-list.h +++ b/src/entity/zsp-list.h @@ -20,11 +20,12 @@ #ifndef ZSP_LIST_H #define ZSP_LIST_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ class Node; class CallbackBase; @@ -38,39 +39,39 @@ class CallbackBase; */ class ZspList { -public: - /// Zsp container iterator - typedef std::vector>::const_iterator Iterator; + public: + /// Zsp container iterator + typedef std::vector>::const_iterator Iterator; - /** - * \param zsp Zsp to add - * \returns index of Zsp in list - * - * This method must be called automatically in order to register - * a node as a Zsp - */ - static uint32_t Add (Ptr zsp); + /** + * \param zsp Zsp to add + * \returns index of Zsp in list + * + * This method must be called automatically in order to register + * a node as a Zsp + */ + static uint32_t Add(Ptr zsp); - /** - * \returns a C++ iterator located at the beginning of this list - */ - static Iterator Begin (); + /** + * \returns a C++ iterator located at the beginning of this list + */ + static Iterator Begin(); - /** - * \returns a C++ iterator located at the end of this list - */ - static Iterator End (); + /** + * \returns a C++ iterator located at the end of this list + */ + static Iterator End(); - /** - * \param n the index of requested node - * \returns the Zsp (Node) associated to index n - */ - static Ptr GetZsp (uint32_t n); + /** + * \param n the index of requested node + * \returns the Zsp (Node) associated to index n + */ + static Ptr GetZsp(uint32_t n); - /** - * \returns the number of Zsps currently in the list - */ - static uint32_t GetNZsps (); + /** + * \returns the number of Zsps currently in the list + */ + static uint32_t GetNZsps(); }; } // namespace ns3 diff --git a/src/helper/debug-helper.h b/src/helper/debug-helper.h index c77bc95..3a4e486 100644 --- a/src/helper/debug-helper.h +++ b/src/helper/debug-helper.h @@ -18,95 +18,102 @@ #ifndef DEBUG_HELPER_H #define DEBUG_HELPER_H -#include - #include #include -#include #include +#include #include -namespace ns3 { +#include -class DebugHelper +namespace ns3 { -public: - static void ProbeNodes () - { - std::cout << "********************************************************************************" << std::endl; - - std::cout << "There are " << Config::GetRootNamespaceObjectN () << " root objects available." << std::endl; - for (size_t i = 0; i < Config::GetRootNamespaceObjectN (); i++) - { - auto obj = Config::GetRootNamespaceObject (i); - std::cout << std::endl << "TypeId " << obj->GetInstanceTypeId () << std::endl; - } - - const uint32_t nNodes = NodeList::GetNNodes (); - std::cout << "There are " << nNodes << " registered nodes." << std::endl; - for (auto iNode = NodeList::Begin (); iNode != NodeList::End (); iNode++) - { - std::cout << std::endl << (*iNode)->GetInstanceTypeId () << std::endl; - - auto aggregateIter = (*iNode)->GetAggregateIterator (); - std::cout << "Aggregate objects " << std::endl; - while (aggregateIter.HasNext ()) - { - auto o = aggregateIter.Next (); - std::cout << "Object " << o->GetInstanceTypeId () << std::endl; - } - std::cout << std::endl; - auto nDevices = (*iNode)->GetNDevices (); - std::cout << "There are " << nDevices << " devices" << std::endl; - - for (uint32_t iDev = 0; iDev < nDevices; iDev++) - { - auto dev = (*iNode)->GetDevice (iDev); - std::cout << "Device TypeId " << dev->GetInstanceTypeId () << std::endl; - } - - auto ipv4 = (*iNode)->GetObject (); - auto ipv4Ifaces = ipv4->GetNInterfaces (); - for (uint32_t ifaceId = 0; ifaceId < ipv4Ifaces; ifaceId++) - { - std::cout << "Device ID " << ifaceId << std::endl; - auto nAddresses = ipv4->GetNAddresses (ifaceId); - - for (uint32_t iAddr = 0; iAddr < nAddresses; iAddr++) - { - auto ipv4Addr = ipv4->GetAddress (ifaceId, iAddr); - std::cout << "IPv4: " << ipv4Addr << std::endl; - } - } - } - - std::cout << "********************************************************************************" << std::endl; - } - - static void ObjectAttributes(Ptr o) - { - for (size_t n=0; n < o->GetInstanceTypeId ().GetParent().GetAttributeN(); n++) - { - TypeId::AttributeInformation attrInfo = o->GetInstanceTypeId ().GetParent().GetAttribute(n); - Ptr attrValue; - std::string attrName = o->GetInstanceTypeId ().GetParent().GetAttribute(n).name; - std::string typeidvalue = attrInfo.checker->GetValueTypeName(); - std::cout<SerializeToString(attrInfo.checker)<GetInstanceTypeId ().GetAttributeN(); n++) - { - TypeId::AttributeInformation attrInfo = o->GetInstanceTypeId ().GetAttribute(n); - Ptr attrValue; - std::string attrName = o->GetInstanceTypeId ().GetAttribute(n).name; - std::string typeidvalue = attrInfo.checker->GetValueTypeName(); - std::cout<SerializeToString(attrInfo.checker)<GetInstanceTypeId() << std::endl; + } + + const uint32_t nNodes = NodeList::GetNNodes(); + std::cout << "There are " << nNodes << " registered nodes." << std::endl; + for (auto iNode = NodeList::Begin(); iNode != NodeList::End(); iNode++) + { + std::cout << std::endl << (*iNode)->GetInstanceTypeId() << std::endl; + + auto aggregateIter = (*iNode)->GetAggregateIterator(); + std::cout << "Aggregate objects " << std::endl; + while (aggregateIter.HasNext()) + { + auto o = aggregateIter.Next(); + std::cout << "Object " << o->GetInstanceTypeId() << std::endl; + } + std::cout << std::endl; + + auto nDevices = (*iNode)->GetNDevices(); + std::cout << "There are " << nDevices << " devices" << std::endl; + + for (uint32_t iDev = 0; iDev < nDevices; iDev++) + { + auto dev = (*iNode)->GetDevice(iDev); + std::cout << "Device TypeId " << dev->GetInstanceTypeId() << std::endl; + } + + auto ipv4 = (*iNode)->GetObject(); + auto ipv4Ifaces = ipv4->GetNInterfaces(); + for (uint32_t ifaceId = 0; ifaceId < ipv4Ifaces; ifaceId++) + { + std::cout << "Device ID " << ifaceId << std::endl; + auto nAddresses = ipv4->GetNAddresses(ifaceId); + + for (uint32_t iAddr = 0; iAddr < nAddresses; iAddr++) + { + auto ipv4Addr = ipv4->GetAddress(ifaceId, iAddr); + std::cout << "IPv4: " << ipv4Addr << std::endl; + } + } + } + + std::cout + << "********************************************************************************" + << std::endl; + } + + static void ObjectAttributes(Ptr o) + { + for (size_t n = 0; n < o->GetInstanceTypeId().GetParent().GetAttributeN(); n++) + { + TypeId::AttributeInformation attrInfo = + o->GetInstanceTypeId().GetParent().GetAttribute(n); + Ptr attrValue; + std::string attrName = o->GetInstanceTypeId().GetParent().GetAttribute(n).name; + std::string typeidvalue = attrInfo.checker->GetValueTypeName(); + std::cout << attrName << " " << typeidvalue << " " + << attrInfo.initialValue->SerializeToString(attrInfo.checker) << std::endl; + } + for (size_t n = 0; n < o->GetInstanceTypeId().GetAttributeN(); n++) + { + TypeId::AttributeInformation attrInfo = o->GetInstanceTypeId().GetAttribute(n); + Ptr attrValue; + std::string attrName = o->GetInstanceTypeId().GetAttribute(n).name; + std::string typeidvalue = attrInfo.checker->GetValueTypeName(); + std::cout << attrName << " " << typeidvalue << " " + << attrInfo.initialValue->SerializeToString(attrInfo.checker) << std::endl; + } + } }; - - } // namespace ns3 #endif /* DEBUG_HELPER_H */ diff --git a/src/irs/irs-assisted-spectrum-channel.cc b/src/irs/irs-assisted-spectrum-channel.cc index 156452e..8989286 100644 --- a/src/irs/irs-assisted-spectrum-channel.cc +++ b/src/irs/irs-assisted-spectrum-channel.cc @@ -18,11 +18,8 @@ */ #include "irs-assisted-spectrum-channel.h" -#include - -#include -#include -#include +#include "irs-list.h" +#include "irs-patch.h" #include #include @@ -45,752 +42,804 @@ #include #include -#include "irs-list.h" -#include "irs-patch.h" +#include +#include +#include +#include constexpr double SPEED_OF_LIGHT = 299792458.0; -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("IrsAssistedSpectrumChannel"); +NS_LOG_COMPONENT_DEFINE("IrsAssistedSpectrumChannel"); -NS_OBJECT_ENSURE_REGISTERED (IrsAssistedSpectrumChannel); +NS_OBJECT_ENSURE_REGISTERED(IrsAssistedSpectrumChannel); -IrsAssistedSpectrumChannel::IrsAssistedSpectrumChannel () +IrsAssistedSpectrumChannel::IrsAssistedSpectrumChannel() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -IrsAssistedSpectrumChannel::DoDispose () +IrsAssistedSpectrumChannel::DoDispose() { - NS_LOG_FUNCTION (this); - MultiModelSpectrumChannel::DoDispose (); + NS_LOG_FUNCTION(this); + MultiModelSpectrumChannel::DoDispose(); } TypeId -IrsAssistedSpectrumChannel::GetTypeId (void) +IrsAssistedSpectrumChannel::GetTypeId(void) { - static TypeId tid = - TypeId ("ns3::IrsAssistedSpectrumChannel") - .SetParent () - .SetGroupName ("Spectrum") - .AddConstructor () - .AddAttribute ("OutageProbability", "Outage probability threshold", DoubleValue (1e-2), - MakeDoubleAccessor (&IrsAssistedSpectrumChannel::SetEps), - MakeDoubleChecker ()) - .AddAttribute ("KMin", "Minimum k-factor for the environment, in dB", DoubleValue (6.), - MakeDoubleAccessor (&IrsAssistedSpectrumChannel::m_kmin), - MakeDoubleChecker ()) - .AddAttribute ("KMax", "Maximum k-factor for the environment, in dB", DoubleValue (10.), - MakeDoubleAccessor (&IrsAssistedSpectrumChannel::m_kmax), - MakeDoubleChecker ()) - .AddAttribute ("KNlos", "k-factor used in case of NLoS condition, in dB", DoubleValue (0.), - MakeDoubleAccessor (&IrsAssistedSpectrumChannel::m_knlos), - MakeDoubleChecker ()) - .AddAttribute ("AlphaLoss", "Environment attenuation factor", DoubleValue (2.), - MakeDoubleAccessor (&IrsAssistedSpectrumChannel::m_alpha), - MakeDoubleChecker ()) - .AddAttribute ("NoDirectLink", "Suppress the direct link with the communicating nodes", - BooleanValue (false), - MakeBooleanAccessor (&IrsAssistedSpectrumChannel::m_noDirectLink), - MakeBooleanChecker ()) - .AddAttribute ( - "NoIrsLink", "Suppress the IRS reflected link with the communicating nodes", - BooleanValue (false), MakeBooleanAccessor (&IrsAssistedSpectrumChannel::m_noIrsLink), - MakeBooleanChecker ()) - .AddAttribute ("MultipathInterference", - "Assume a perfect destructive, constructive, or " - "simulated multipath interference between direct and " - "reflected links", - EnumValue (MultipathInterferenceType::SIMULATED), - MakeEnumAccessor (&IrsAssistedSpectrumChannel::m_multipathType), - MakeEnumChecker (MultipathInterferenceType::DESTRUCTIVE, "DESTRUCTIVE", - MultipathInterferenceType::SIMULATED, "SIMULATED", - MultipathInterferenceType::CONSTRUCTIVE, "CONSTRUCTIVE")); - return tid; + static TypeId tid = + TypeId("ns3::IrsAssistedSpectrumChannel") + .SetParent() + .SetGroupName("Spectrum") + .AddConstructor() + .AddAttribute("OutageProbability", + "Outage probability threshold", + DoubleValue(1e-2), + MakeDoubleAccessor(&IrsAssistedSpectrumChannel::SetEps), + MakeDoubleChecker()) + .AddAttribute("KMin", + "Minimum k-factor for the environment, in dB", + DoubleValue(6.), + MakeDoubleAccessor(&IrsAssistedSpectrumChannel::m_kmin), + MakeDoubleChecker()) + .AddAttribute("KMax", + "Maximum k-factor for the environment, in dB", + DoubleValue(10.), + MakeDoubleAccessor(&IrsAssistedSpectrumChannel::m_kmax), + MakeDoubleChecker()) + .AddAttribute("KNlos", + "k-factor used in case of NLoS condition, in dB", + DoubleValue(0.), + MakeDoubleAccessor(&IrsAssistedSpectrumChannel::m_knlos), + MakeDoubleChecker()) + .AddAttribute("AlphaLoss", + "Environment attenuation factor", + DoubleValue(2.), + MakeDoubleAccessor(&IrsAssistedSpectrumChannel::m_alpha), + MakeDoubleChecker()) + .AddAttribute("NoDirectLink", + "Suppress the direct link with the communicating nodes", + BooleanValue(false), + MakeBooleanAccessor(&IrsAssistedSpectrumChannel::m_noDirectLink), + MakeBooleanChecker()) + .AddAttribute("NoIrsLink", + "Suppress the IRS reflected link with the communicating nodes", + BooleanValue(false), + MakeBooleanAccessor(&IrsAssistedSpectrumChannel::m_noIrsLink), + MakeBooleanChecker()) + .AddAttribute("MultipathInterference", + "Assume a perfect destructive, constructive, or " + "simulated multipath interference between direct and " + "reflected links", + EnumValue(MultipathInterferenceType::SIMULATED), + MakeEnumAccessor(&IrsAssistedSpectrumChannel::m_multipathType), + MakeEnumChecker(MultipathInterferenceType::DESTRUCTIVE, + "DESTRUCTIVE", + MultipathInterferenceType::SIMULATED, + "SIMULATED", + MultipathInterferenceType::CONSTRUCTIVE, + "CONSTRUCTIVE")); + return tid; } void -IrsAssistedSpectrumChannel::StartTx (Ptr txParams) +IrsAssistedSpectrumChannel::StartTx(Ptr txParams) { - NS_LOG_FUNCTION (this << txParams); + NS_LOG_FUNCTION(this << txParams); - NS_ASSERT (txParams->txPhy); - NS_ASSERT (txParams->psd); - Ptr txParamsTrace = - txParams - ->Copy (); // copy it since traced value cannot be const (because of potential underlying DynamicCasts) - m_txSigParamsTrace (txParamsTrace); + NS_ASSERT(txParams->txPhy); + NS_ASSERT(txParams->psd); + Ptr txParamsTrace = + txParams->Copy(); // copy it since traced value cannot be const (because of potential + // underlying DynamicCasts) + m_txSigParamsTrace(txParamsTrace); - Ptr txMobility = txParams->txPhy->GetMobility (); - SpectrumModelUid_t txSpectrumModelUid = txParams->psd->GetSpectrumModelUid (); - NS_LOG_LOGIC ("txSpectrumModelUid " << txSpectrumModelUid); + Ptr txMobility = txParams->txPhy->GetMobility(); + SpectrumModelUid_t txSpectrumModelUid = txParams->psd->GetSpectrumModelUid(); + NS_LOG_LOGIC("txSpectrumModelUid " << txSpectrumModelUid); - auto txInfoIt = FindAndEventuallyAddTxSpectrumModel(txParams->psd->GetSpectrumModel()); + auto txInfoIt = FindAndEventuallyAddTxSpectrumModel(txParams->psd->GetSpectrumModel()); - NS_LOG_LOGIC ("converter map for TX SpectrumModel with Uid " << txInfoIt->first); - NS_LOG_LOGIC ( - "converter map size: " << txInfoIt->second.m_spectrumConverterMap.size ()); - NS_LOG_LOGIC ("converter map first element: " - << txInfoIt->second.m_spectrumConverterMap.begin ()->first); + NS_LOG_LOGIC("converter map for TX SpectrumModel with Uid " << txInfoIt->first); + NS_LOG_LOGIC("converter map size: " << txInfoIt->second.m_spectrumConverterMap.size()); + NS_LOG_LOGIC( + "converter map first element: " << txInfoIt->second.m_spectrumConverterMap.begin()->first); - for (auto &rxInfo : GetRxSpectrumModelInfoMap ()) + for (auto& rxInfo : GetRxSpectrumModelInfoMap()) { - SpectrumModelUid_t rxSpectrumModelUid = rxInfo.second.m_rxSpectrumModel->GetUid (); - NS_LOG_LOGIC ("rxSpectrumModelUids " << rxSpectrumModelUid); + SpectrumModelUid_t rxSpectrumModelUid = rxInfo.second.m_rxSpectrumModel->GetUid(); + NS_LOG_LOGIC("rxSpectrumModelUids " << rxSpectrumModelUid); - Ptr convertedTxPowerSpectrum; - if (txSpectrumModelUid == rxSpectrumModelUid) + Ptr convertedTxPowerSpectrum; + if (txSpectrumModelUid == rxSpectrumModelUid) { - NS_LOG_LOGIC ("no spectrum conversion needed"); - convertedTxPowerSpectrum = txParams->psd; + NS_LOG_LOGIC("no spectrum conversion needed"); + convertedTxPowerSpectrum = txParams->psd; } - else + else { - NS_LOG_LOGIC ("converting txPowerSpectrum SpectrumModelUids " - << txSpectrumModelUid << " --> " << rxSpectrumModelUid); - auto rxConverterIt = - txInfoIt->second.m_spectrumConverterMap.find (rxSpectrumModelUid); // TODO: const ref? - if (rxConverterIt == txInfoIt->second.m_spectrumConverterMap.end ()) + NS_LOG_LOGIC("converting txPowerSpectrum SpectrumModelUids " + << txSpectrumModelUid << " --> " << rxSpectrumModelUid); + auto rxConverterIt = txInfoIt->second.m_spectrumConverterMap.find( + rxSpectrumModelUid); // TODO: const ref? + if (rxConverterIt == txInfoIt->second.m_spectrumConverterMap.end()) { - // No converter means TX SpectrumModel is orthogonal to RX SpectrumModel - continue; + // No converter means TX SpectrumModel is orthogonal to RX SpectrumModel + continue; } - convertedTxPowerSpectrum = rxConverterIt->second.Convert (txParams->psd); + convertedTxPowerSpectrum = rxConverterIt->second.Convert(txParams->psd); } - //Speculative calc. section - double K_BG, F_BG, F_BRG, Irs2TxGain, Irs2RxGain, Tx2RxGain, Rx2TxGain; - std::vector d_BR, d_BG, K_BR, K_BG_nu, K_BG_sigma, lambdav, d_RG_temp, etav_tmp, - K_RG_tmp, beta_BRG; - std::vector a_BR, a_RG_temp; - std::vector> d_RG, etav, K_RG; - std::vector> a_RG; - Vector IrsPosition, TxPosition, RxPosition; - Ptr condModel = - CreateObject (); - - const auto n_irs = IrsList::GetN(); // Number of Irs - const auto n_users = rxInfo.second.m_rxPhys.size (); //Number of receiving Phy layer - const double Kmin = std::pow (10., m_kmin / 10.); //A1 - const double Kmax = std::pow (10., m_kmax / 10.); - const double Knlos = std::pow (10., m_knlos / 10.); - const double A2 = std::log (std::pow (Kmax / Kmin, 2.)) / M_PI; - - NodeToIrssDistance (txMobility, d_BR); - NodeToIrssAngles (txMobility, a_BR); - - const auto f_l = convertedTxPowerSpectrum->GetSpectrumModel ()->Begin ()->fl; - const auto f_h = (--convertedTxPowerSpectrum->GetSpectrumModel ()->End ())->fh; - const double f_c = (f_h + f_l) / 2.0; - - const double beta_BG = std::pow (SPEED_OF_LIGHT / f_c, 2.) / std::pow (4. * M_PI, 2.); - IrsBeta (beta_BRG, f_c); - - int i = 0; - for (auto &rxPhy : rxInfo.second.m_rxPhys) + // Speculative calc. section + double K_BG, F_BG, F_BRG, Irs2TxGain, Irs2RxGain, Tx2RxGain, Rx2TxGain; + std::vector d_BR, d_BG, K_BR, K_BG_nu, K_BG_sigma, lambdav, d_RG_temp, etav_tmp, + K_RG_tmp, beta_BRG; + std::vector a_BR, a_RG_temp; + std::vector> d_RG, etav, K_RG; + std::vector> a_RG; + Vector IrsPosition, TxPosition, RxPosition; + Ptr condModel = + CreateObject(); + + const auto n_irs = IrsList::GetN(); // Number of Irs + const auto n_users = rxInfo.second.m_rxPhys.size(); // Number of receiving Phy layer + const double Kmin = std::pow(10., m_kmin / 10.); // A1 + const double Kmax = std::pow(10., m_kmax / 10.); + const double Knlos = std::pow(10., m_knlos / 10.); + const double A2 = std::log(std::pow(Kmax / Kmin, 2.)) / M_PI; + + NodeToIrssDistance(txMobility, d_BR); + NodeToIrssAngles(txMobility, a_BR); + + const auto f_l = convertedTxPowerSpectrum->GetSpectrumModel()->Begin()->fl; + const auto f_h = (--convertedTxPowerSpectrum->GetSpectrumModel()->End())->fh; + const double f_c = (f_h + f_l) / 2.0; + + const double beta_BG = std::pow(SPEED_OF_LIGHT / f_c, 2.) / std::pow(4. * M_PI, 2.); + IrsBeta(beta_BRG, f_c); + + int i = 0; + for (auto& rxPhy : rxInfo.second.m_rxPhys) { - RxPosition = rxPhy->GetMobility ()->GetPosition (); - TxPosition = txMobility->GetPosition (); - auto rxParams = txParams->Copy (); - rxParams->psd = convertedTxPowerSpectrum->Copy (); - F_BG = 1.; - - const auto channelCondBG = - condModel->GetChannelCondition(txMobility, rxPhy->GetMobility())->GetLosCondition(); - if (channelCondBG == ChannelCondition::LosConditionValue::LOS) + RxPosition = rxPhy->GetMobility()->GetPosition(); + TxPosition = txMobility->GetPosition(); + auto rxParams = txParams->Copy(); + rxParams->psd = convertedTxPowerSpectrum->Copy(); + F_BG = 1.; + + const auto channelCondBG = + condModel->GetChannelCondition(txMobility, rxPhy->GetMobility())->GetLosCondition(); + if (channelCondBG == ChannelCondition::LosConditionValue::LOS) { - K_BG = Kmin * exp(A2 * GetElevation(txMobility->GetPosition(), - rxPhy->GetMobility()->GetPosition())); + K_BG = Kmin * exp(A2 * GetElevation(txMobility->GetPosition(), + rxPhy->GetMobility()->GetPosition())); } - else + else { - K_BG = Knlos; + K_BG = Knlos; } - K_BG_nu.push_back (K_BG / (K_BG + 1.)); - K_BG_sigma.push_back (std::sqrt (1. / (K_BG + 1.))); - d_BG.push_back (txMobility->GetDistanceFrom (rxPhy->GetMobility ())); - NodeToIrssDistance (rxPhy->GetMobility (), d_RG_temp); - d_RG.push_back (d_RG_temp); - d_RG_temp.clear (); - NodeToIrssAngles (rxPhy->GetMobility (), a_RG_temp); - a_RG.push_back (a_RG_temp); - a_RG_temp.clear (); - etav_tmp.clear (); - K_RG_tmp.clear (); - - auto rxAntenna = DynamicCast(rxPhy->GetAntenna()); - - for (uint32_t j = 0; j < n_irs; ++j) + K_BG_nu.push_back(K_BG / (K_BG + 1.)); + K_BG_sigma.push_back(std::sqrt(1. / (K_BG + 1.))); + d_BG.push_back(txMobility->GetDistanceFrom(rxPhy->GetMobility())); + NodeToIrssDistance(rxPhy->GetMobility(), d_RG_temp); + d_RG.push_back(d_RG_temp); + d_RG_temp.clear(); + NodeToIrssAngles(rxPhy->GetMobility(), a_RG_temp); + a_RG.push_back(a_RG_temp); + a_RG_temp.clear(); + etav_tmp.clear(); + K_RG_tmp.clear(); + + auto rxAntenna = DynamicCast(rxPhy->GetAntenna()); + + for (uint32_t j = 0; j < n_irs; ++j) { - F_BRG = 1; - IrsPosition = IrsList::Get(j)->GetDrone()->GetObject()->GetPosition(); - const auto& txNodeIrsInclination = - NodeToIrsAngles(txMobility, IrsList::Get(j)).GetInclination(); - const auto& rxNodeIrsInclination = - NodeToIrsAngles(rxPhy->GetMobility(), IrsList::Get(j)).GetInclination(); - const auto& irsPowerState = IrsList::Get(j)->GetState(); - const auto& irsDroneMM = IrsList::Get(j)->GetDrone()->GetObject(); - const auto& chCondIrsRxNode = - condModel->GetChannelCondition(irsDroneMM, rxPhy->GetMobility()) - ->GetLosCondition(); - const auto& chCondTxNodeIrs = - condModel->GetChannelCondition(txMobility, irsDroneMM)->GetLosCondition(); - - if (rxParams->txAntenna != nullptr) - { - Irs2TxGain = rxParams->txAntenna->GetGainDb (Angles (IrsPosition, TxPosition)); - if (std::isinf (Irs2TxGain)) - F_BRG *= 0.; - else - F_BRG *= std::pow (10., Irs2TxGain / 10.); + F_BRG = 1; + IrsPosition = + IrsList::Get(j)->GetDrone()->GetObject()->GetPosition(); + const auto& txNodeIrsInclination = + NodeToIrsAngles(txMobility, IrsList::Get(j)).GetInclination(); + const auto& rxNodeIrsInclination = + NodeToIrsAngles(rxPhy->GetMobility(), IrsList::Get(j)).GetInclination(); + const auto& irsPowerState = IrsList::Get(j)->GetState(); + const auto& irsDroneMM = IrsList::Get(j)->GetDrone()->GetObject(); + const auto& chCondIrsRxNode = + condModel->GetChannelCondition(irsDroneMM, rxPhy->GetMobility()) + ->GetLosCondition(); + const auto& chCondTxNodeIrs = + condModel->GetChannelCondition(txMobility, irsDroneMM)->GetLosCondition(); + + if (rxParams->txAntenna != nullptr) + { + Irs2TxGain = rxParams->txAntenna->GetGainDb(Angles(IrsPosition, TxPosition)); + if (std::isinf(Irs2TxGain)) + F_BRG *= 0.; + else + F_BRG *= std::pow(10., Irs2TxGain / 10.); } - else + else { - NS_LOG_WARN ("TX Antenna not found, isotropic antenna is used by dafualt"); - F_BRG *= 1.; + NS_LOG_WARN("TX Antenna not found, isotropic antenna is used by dafualt"); + F_BRG *= 1.; } - if (rxAntenna != nullptr) + if (rxAntenna != nullptr) { - Irs2RxGain = rxAntenna->GetGainDb (Angles (IrsPosition, RxPosition)); - if (std::isinf (Irs2RxGain)) - F_BRG *= 0.; - else - F_BRG *= std::pow (10., Irs2RxGain / 10.); + Irs2RxGain = rxAntenna->GetGainDb(Angles(IrsPosition, RxPosition)); + if (std::isinf(Irs2RxGain)) + F_BRG *= 0.; + else + F_BRG *= std::pow(10., Irs2RxGain / 10.); } - else + else { - NS_LOG_WARN ("RX Antenna not found, isotropic antenna is used by dafualt"); - F_BRG *= 1.; + NS_LOG_WARN("RX Antenna not found, isotropic antenna is used by dafualt"); + F_BRG *= 1.; } - // Check if source and destination nodes are in LOS with the reflective face, if - // not, F_BRG=0 same logic applies even if the IRS is not ON. - if (txNodeIrsInclination > M_PI / 2. || rxNodeIrsInclination > M_PI / 2. || - irsPowerState != DronePeripheral::PeripheralState::ON) - { - //Irss doesn't reflect by both faces and doesn't refract - //Irs contribution is excluded - F_BRG *= 0.; - } - - if (!m_noIrsLink) + // Check if source and destination nodes are in LOS with the reflective face, if + // not, F_BRG=0 same logic applies even if the IRS is not ON. + if (txNodeIrsInclination > M_PI / 2. || rxNodeIrsInclination > M_PI / 2. || + irsPowerState != DronePeripheral::PeripheralState::ON) { - etav_tmp.push_back (std::sqrt (beta_BRG[j] * std::pow (d_BR[j] * d_RG[i][j], -2.) * F_BRG)); + // Irss doesn't reflect by both faces and doesn't refract + // Irs contribution is excluded + F_BRG *= 0.; } - else + + if (!m_noIrsLink) { - etav_tmp.push_back (0.); + etav_tmp.push_back( + std::sqrt(beta_BRG[j] * std::pow(d_BR[j] * d_RG[i][j], -2.) * F_BRG)); + } + else + { + etav_tmp.push_back(0.); } - if (chCondIrsRxNode == ChannelCondition::LosConditionValue::LOS) + if (chCondIrsRxNode == ChannelCondition::LosConditionValue::LOS) { - K_RG_tmp.push_back (Kmin * exp (A2 * (GetElevation (a_RG[i][j])))); + K_RG_tmp.push_back(Kmin * exp(A2 * (GetElevation(a_RG[i][j])))); } - else + else { - K_RG_tmp.push_back (Knlos); + K_RG_tmp.push_back(Knlos); } - if (chCondTxNodeIrs == ChannelCondition::LosConditionValue::LOS) + if (chCondTxNodeIrs == ChannelCondition::LosConditionValue::LOS) { - K_BR.push_back (Kmin * exp (A2 * (GetElevation (a_BR[j])))); + K_BR.push_back(Kmin * exp(A2 * (GetElevation(a_BR[j])))); } - else + else { - K_BR.push_back (Knlos); + K_BR.push_back(Knlos); } } - etav.push_back (etav_tmp); + etav.push_back(etav_tmp); - if (rxParams->txAntenna != nullptr) + if (rxParams->txAntenna != nullptr) { - Rx2TxGain = rxParams->txAntenna->GetGainDb (Angles (RxPosition, TxPosition)); - if (std::isinf (Rx2TxGain)) - F_BG *= 0.; - else - F_BG *= std::pow (10., Rx2TxGain / 10.); + Rx2TxGain = rxParams->txAntenna->GetGainDb(Angles(RxPosition, TxPosition)); + if (std::isinf(Rx2TxGain)) + F_BG *= 0.; + else + F_BG *= std::pow(10., Rx2TxGain / 10.); } - else + else { - NS_LOG_WARN ("TX Antenna not found, isotropic antenna is used by dafualt"); - F_BG *= 1.; + NS_LOG_WARN("TX Antenna not found, isotropic antenna is used by dafualt"); + F_BG *= 1.; } - if (rxAntenna != nullptr) + if (rxAntenna != nullptr) { - Tx2RxGain = rxAntenna->GetGainDb (Angles (TxPosition, RxPosition)); - if (std::isinf (Tx2RxGain)) - F_BG *= 0.; - else - F_BG *= std::pow (10., Tx2RxGain / 10.); + Tx2RxGain = rxAntenna->GetGainDb(Angles(TxPosition, RxPosition)); + if (std::isinf(Tx2RxGain)) + F_BG *= 0.; + else + F_BG *= std::pow(10., Tx2RxGain / 10.); } - else + else { - NS_LOG_WARN ("RX Antenna not found, isotropic antenna is used by dafualt"); - F_BG *= 1.; + NS_LOG_WARN("RX Antenna not found, isotropic antenna is used by dafualt"); + F_BG *= 1.; } - if (!m_noDirectLink) + if (!m_noDirectLink) { - lambdav.push_back (std::sqrt (beta_BG * std::pow (d_BG[i], -m_alpha) * F_BG)); + lambdav.push_back(std::sqrt(beta_BG * std::pow(d_BG[i], -m_alpha) * F_BG)); } - else + else { - lambdav.push_back (0.); + lambdav.push_back(0.); } - K_RG.push_back (K_RG_tmp); - ++i; + K_RG.push_back(K_RG_tmp); + ++i; } - const auto gain = GetGain (f_c, n_users, n_irs, d_BG, K_BR, K_RG, etav, lambdav, d_BR, d_RG, - a_BR, a_RG, K_BG_nu, K_BG_sigma); - - // - int u = 0; - for (auto &rxPhy : rxInfo.second.m_rxPhys) + const auto gain = GetGain(f_c, + n_users, + n_irs, + d_BG, + K_BR, + K_RG, + etav, + lambdav, + d_BR, + d_RG, + a_BR, + a_RG, + K_BG_nu, + K_BG_sigma); + + // + int u = 0; + for (auto& rxPhy : rxInfo.second.m_rxPhys) { - NS_ASSERT_MSG (rxPhy->GetRxSpectrumModel ()->GetUid () == rxSpectrumModelUid, - "SpectrumModel change was not notified to IrsAssistedSpectrumChannel " - "(i.e., AddRx should be called again after model is changed)"); + NS_ASSERT_MSG(rxPhy->GetRxSpectrumModel()->GetUid() == rxSpectrumModelUid, + "SpectrumModel change was not notified to IrsAssistedSpectrumChannel " + "(i.e., AddRx should be called again after model is changed)"); - if (rxPhy != txParams->txPhy) //Check if TX Phy is different from RX Phy + if (rxPhy != txParams->txPhy) // Check if TX Phy is different from RX Phy { - Ptr rxNetDevice = rxPhy->GetDevice (); - Ptr txNetDevice = txParams->txPhy->GetDevice (); - //Ignore communication between device on the same Node. - if (rxNetDevice && txNetDevice) + Ptr rxNetDevice = rxPhy->GetDevice(); + Ptr txNetDevice = txParams->txPhy->GetDevice(); + // Ignore communication between device on the same Node. + if (rxNetDevice && txNetDevice) { - // we assume that devices are attached to a node - if (rxNetDevice->GetNode ()->GetId () == txNetDevice->GetNode ()->GetId ()) + // we assume that devices are attached to a node + if (rxNetDevice->GetNode()->GetId() == txNetDevice->GetNode()->GetId()) { - NS_LOG_DEBUG ( - "Skipping the pathloss calculation among different antennas of the same " - "node, not supported yet by any pathloss model in ns-3."); - continue; + NS_LOG_DEBUG("Skipping the pathloss calculation among different antennas " + "of the same " + "node, not supported yet by any pathloss model in ns-3."); + continue; } } - NS_LOG_LOGIC ("copying signal parameters " << txParams); - Ptr rxParams = txParams->Copy (); - rxParams->psd = convertedTxPowerSpectrum->Copy (); - Time delay = MicroSeconds (0); + NS_LOG_LOGIC("copying signal parameters " << txParams); + Ptr rxParams = txParams->Copy(); + rxParams->psd = convertedTxPowerSpectrum->Copy(); + Time delay = MicroSeconds(0); - Ptr receiverMobility = rxPhy->GetMobility (); - //Channel gain calc. section - if (txMobility && receiverMobility) + Ptr receiverMobility = rxPhy->GetMobility(); + // Channel gain calc. section + if (txMobility && receiverMobility) { - double pathLossDb = 0.; + double pathLossDb = 0.; - if (gain[u] > 0) - pathLossDb = -10. * std::log10 (gain[u]); - else - pathLossDb = m_maxLossDb; + if (gain[u] > 0) + pathLossDb = -10. * std::log10(gain[u]); + else + pathLossDb = m_maxLossDb; - // Pathloss trace - m_pathLossTrace (txParams->txPhy, rxPhy, pathLossDb); + // Pathloss trace + m_pathLossTrace(txParams->txPhy, rxPhy, pathLossDb); - if (pathLossDb >= m_maxLossDb) + if (pathLossDb >= m_maxLossDb) { - // beyond range - continue; + // beyond range + continue; } - *(rxParams->psd) *= gain[u]; + *(rxParams->psd) *= gain[u]; - if (m_propagationDelay) + if (m_propagationDelay) { - delay = m_propagationDelay->GetDelay (txMobility, receiverMobility); + delay = m_propagationDelay->GetDelay(txMobility, receiverMobility); } } - if (rxNetDevice) + if (rxNetDevice) { - // the receiver has a NetDevice, so we expect that it is attached to a Node - const auto& dstNode = rxNetDevice->GetNode ()->GetId (); - Simulator::ScheduleWithContext ( - dstNode, delay, &IrsAssistedSpectrumChannel::StartRx, this, rxParams, rxPhy); + // the receiver has a NetDevice, so we expect that it is attached to a Node + const auto& dstNode = rxNetDevice->GetNode()->GetId(); + Simulator::ScheduleWithContext(dstNode, + delay, + &IrsAssistedSpectrumChannel::StartRx, + this, + rxParams, + rxPhy); } - else + else { - // the receiver is not attached to a NetDevice, so we cannot assume that it is attached to a node - Simulator::Schedule (delay, &IrsAssistedSpectrumChannel::StartRx, this, rxParams, - rxPhy); + // the receiver is not attached to a NetDevice, so we cannot assume that it is + // attached to a node + Simulator::Schedule(delay, + &IrsAssistedSpectrumChannel::StartRx, + this, + rxParams, + rxPhy); } } - ++u; + ++u; } } } std::vector -IrsAssistedSpectrumChannel::GetGain ( - const double f_c, const int n_users, const int n_irs, const std::vector &d_BG, - const std::vector &K_BR, const std::vector> &K_RG, - const std::vector> &etav, const std::vector &lambdav, - const std::vector &d_BR, const std::vector> &d_RG, - const std::vector &a_BR, const std::vector> &a_RG, - const std::vector &K_BG_nu, const std::vector &K_BG_sigma) +IrsAssistedSpectrumChannel::GetGain(const double f_c, + const int n_users, + const int n_irs, + const std::vector& d_BG, + const std::vector& K_BR, + const std::vector>& K_RG, + const std::vector>& etav, + const std::vector& lambdav, + const std::vector& d_BR, + const std::vector>& d_RG, + const std::vector& a_BR, + const std::vector>& a_RG, + const std::vector& K_BG_nu, + const std::vector& K_BG_sigma) { - double nu_BRG, sig_BRG, K, sigma; - std::vector phases_tmp, modules_tmp, gain; - std::vector> phases, modules; + double nu_BRG, sig_BRG, K, sigma; + std::vector phases_tmp, modules_tmp, gain; + std::vector> phases, modules; - double cos_BR = 0.; - double sin_BR = 0.; - double cos_RG = 0.; - double sin_RG = 0.; + double cos_BR = 0.; + double sin_BR = 0.; + double cos_RG = 0.; + double sin_RG = 0.; - for (int u = 0; u < n_users; ++u) + for (int u = 0; u < n_users; ++u) { - nu_BRG = 0.; - sig_BRG = 0.; + nu_BRG = 0.; + sig_BRG = 0.; - phases.clear (); - modules.clear (); - for (int d = 0; d < n_irs; ++d) + phases.clear(); + modules.clear(); + for (int d = 0; d < n_irs; ++d) { - const auto K_BRG_nu = - std::sqrt(K_BR[d] * K_RG[u][d] / (K_BR[d] + 1.) / (K_RG[u][d] + 1.)); - const auto K_BRG_sigma = - std::sqrt((K_BR[d] + K_RG[u][d]) / (K_BR[d] + 1) / (K_RG[u][d] + 1.)); - // For each patch - const auto irs = IrsList::Get(d); - const auto d_r = irs->GetPruY(); - const auto d_c = irs->GetPruX(); - const auto patches = irs->GetPatchVector(); - - phases_tmp.clear (); - modules_tmp.clear (); - const auto P = patches.size (); - for (std::size_t p = 0; p < P; ++p) + const auto K_BRG_nu = + std::sqrt(K_BR[d] * K_RG[u][d] / (K_BR[d] + 1.) / (K_RG[u][d] + 1.)); + const auto K_BRG_sigma = + std::sqrt((K_BR[d] + K_RG[u][d]) / (K_BR[d] + 1) / (K_RG[u][d] + 1.)); + // For each patch + const auto irs = IrsList::Get(d); + const auto d_r = irs->GetPruY(); + const auto d_c = irs->GetPruX(); + const auto patches = irs->GetPatchVector(); + + phases_tmp.clear(); + modules_tmp.clear(); + const auto P = patches.size(); + for (std::size_t p = 0; p < P; ++p) { - modules_tmp.push_back (etav[u][d] * K_BRG_nu); - double phaseY, phaseX, distance; - if (patches[p]->IsServing ()) + modules_tmp.push_back(etav[u][d] * K_BRG_nu); + double phaseY, phaseX, distance; + if (patches[p]->IsServing()) { - GetServedParam (irs, patches[p], phaseX, phaseY, distance); + GetServedParam(irs, patches[p], phaseX, phaseY, distance); } - else + else { - double theta_r, phi_r, z; - const auto theta_o = a_BR[d].GetInclination (); - const auto phi_o = a_BR[d].GetAzimuth (); - phaseX = patches[p]->GetPhaseX (); - phaseY = patches[p]->GetPhaseY (); - //Computation of Irs-Ground distance following the angle of reflection - if (phaseX == 0) + double theta_r, phi_r, z; + const auto theta_o = a_BR[d].GetInclination(); + const auto phi_o = a_BR[d].GetAzimuth(); + phaseX = patches[p]->GetPhaseX(); + phaseY = patches[p]->GetPhaseY(); + // Computation of Irs-Ground distance following the angle of reflection + if (phaseX == 0) { - theta_r = theta_o; + theta_r = theta_o; } - else + else { - if (!std::isnan (phi_o)) + if (!std::isnan(phi_o)) { - phi_r = std::atan (phaseY / phaseX - std::tan (phi_o)); - theta_r = std::asin ((phaseY - std::sin (theta_o) * std::sin (phi_o)) / std::sin (phi_r)); + phi_r = std::atan(phaseY / phaseX - std::tan(phi_o)); + theta_r = std::asin((phaseY - std::sin(theta_o) * std::sin(phi_o)) / + std::sin(phi_r)); } - else + else { - phi_r = std::atan (phaseY / phaseX); - theta_r = std::asin (phaseY - std::sin (theta_o) / std::sin (phi_r)); + phi_r = std::atan(phaseY / phaseX); + theta_r = std::asin(phaseY - std::sin(theta_o) / std::sin(phi_r)); } } - if (!std::isnan (theta_r)) + if (!std::isnan(theta_r)) { - z = irs->GetDrone ()->GetObject ()->GetPosition ().z; - distance = std::sqrt (std::pow (z, 2.) + std::pow (z * std::tan (theta_r), 2.)) + d_BR[d]; + z = irs->GetDrone()->GetObject()->GetPosition().z; + distance = + std::sqrt(std::pow(z, 2.) + std::pow(z * std::tan(theta_r), 2.)) + + d_BR[d]; } - else + else { - NS_ABORT_MSG ("The values of phaseX and phaseY are not valid."); + NS_ABORT_MSG("The values of phaseX and phaseY are not valid."); } } - cos_BR = 0.; - sin_BR = 0.; - cos_RG = 0.; - sin_RG = 0.; + cos_BR = 0.; + sin_BR = 0.; + cos_RG = 0.; + sin_RG = 0.; - if (!std::isnan (a_BR[d].GetAzimuth ())) + if (!std::isnan(a_BR[d].GetAzimuth())) { - cos_BR = std::cos (a_BR[d].GetAzimuth ()); - sin_BR = std::sin (a_BR[d].GetAzimuth ()); + cos_BR = std::cos(a_BR[d].GetAzimuth()); + sin_BR = std::sin(a_BR[d].GetAzimuth()); } - if (!std::isnan (a_RG[u][d].GetAzimuth ())) + if (!std::isnan(a_RG[u][d].GetAzimuth())) { - cos_RG = std::cos (a_RG[u][d].GetAzimuth ()); - sin_RG = std::sin (a_RG[u][d].GetAzimuth ()); + cos_RG = std::cos(a_RG[u][d].GetAzimuth()); + sin_RG = std::sin(a_RG[u][d].GetAzimuth()); } - const auto phi_x = d_c * (std::sin (a_BR[d].GetInclination ()) * cos_BR + - std::sin (a_RG[u][d].GetInclination ()) * cos_RG - phaseX); - const auto phi_y = d_r * (std::sin (a_BR[d].GetInclination ()) * sin_BR + - std::sin (a_RG[u][d].GetInclination ()) * sin_RG - phaseY); - - auto pigr = 2. * M_PI; - if (modf (phi_x * M_PI * f_c / SPEED_OF_LIGHT, &pigr) == - 0.) //if it is multiple of pi denominator is 0 - modules_tmp[p] = - modules_tmp[p] * patches[p]->GetSize ().GetColSize (); //Paper: Formula 19 (Chi) - else - modules_tmp[p] = - modules_tmp[p] * - std::sin (patches[p]->GetSize ().GetColSize () * phi_x * M_PI * f_c / - SPEED_OF_LIGHT) / - std::sin (phi_x * M_PI * f_c / SPEED_OF_LIGHT); //Paper: Formula 19 (Chi) - - if (modf (phi_y * M_PI * f_c / SPEED_OF_LIGHT, &pigr) == - 0) //if it is multiple of pi denominator is 0 + const auto phi_x = d_c * (std::sin(a_BR[d].GetInclination()) * cos_BR + + std::sin(a_RG[u][d].GetInclination()) * cos_RG - phaseX); + const auto phi_y = d_r * (std::sin(a_BR[d].GetInclination()) * sin_BR + + std::sin(a_RG[u][d].GetInclination()) * sin_RG - phaseY); + + auto pigr = 2. * M_PI; + if (modf(phi_x * M_PI * f_c / SPEED_OF_LIGHT, &pigr) == + 0.) // if it is multiple of pi denominator is 0 + modules_tmp[p] = modules_tmp[p] * + patches[p]->GetSize().GetColSize(); // Paper: Formula 19 (Chi) + else + modules_tmp[p] = + modules_tmp[p] * + std::sin(patches[p]->GetSize().GetColSize() * phi_x * M_PI * f_c / + SPEED_OF_LIGHT) / + std::sin(phi_x * M_PI * f_c / SPEED_OF_LIGHT); // Paper: Formula 19 (Chi) + + if (modf(phi_y * M_PI * f_c / SPEED_OF_LIGHT, &pigr) == + 0) // if it is multiple of pi denominator is 0 { - modules_tmp[p] = modules_tmp[p] * - patches[p]->GetSize ().GetRowSize (); //Paper: Formula 19 (Chi) + modules_tmp[p] = modules_tmp[p] * + patches[p]->GetSize().GetRowSize(); // Paper: Formula 19 (Chi) } - else - modules_tmp[p] = - modules_tmp[p] * - std::sin (patches[p]->GetSize ().GetRowSize () * phi_y * M_PI * f_c / - SPEED_OF_LIGHT) / - std::sin (phi_y * M_PI * f_c / SPEED_OF_LIGHT); //Paper: Formula 19 (Chi) - - phases_tmp.push_back (-2. * M_PI * f_c / SPEED_OF_LIGHT * - (d_BR[d] + d_RG[u][d] - distance)); //Paper: Formula 19 (Omega) + else + modules_tmp[p] = + modules_tmp[p] * + std::sin(patches[p]->GetSize().GetRowSize() * phi_y * M_PI * f_c / + SPEED_OF_LIGHT) / + std::sin(phi_y * M_PI * f_c / SPEED_OF_LIGHT); // Paper: Formula 19 (Chi) + + phases_tmp.push_back( + -2. * M_PI * f_c / SPEED_OF_LIGHT * + (d_BR[d] + d_RG[u][d] - distance)); // Paper: Formula 19 (Omega) } - modules.push_back (modules_tmp); - phases.push_back (phases_tmp); + modules.push_back(modules_tmp); + phases.push_back(phases_tmp); - for (std::size_t p = 0; p < P; ++p) + for (std::size_t p = 0; p < P; ++p) { - for (int d1 = 0; d1 <= d; ++d1) + for (int d1 = 0; d1 <= d; ++d1) { - for (std::size_t p1 = 0; p1 < P; ++p1) + for (std::size_t p1 = 0; p1 < P; ++p1) { - if (d == d1) + if (d == d1) { - if (p1 <= p) - p1 = p + 1; - if (p == P - 1) - break; + if (p1 <= p) + p1 = p + 1; + if (p == P - 1) + break; } - nu_BRG += 2. * std::abs (modules[d][p]) * std::abs (modules[d1][p1]) * - std::cos (phases[d][p] - phases[d1][p1]); + nu_BRG += 2. * std::abs(modules[d][p]) * std::abs(modules[d1][p1]) * + std::cos(phases[d][p] - phases[d1][p1]); } } - nu_BRG += std::pow (modules[d][p], 2.); + nu_BRG += std::pow(modules[d][p], 2.); - switch (m_multipathType) - { - case MultipathInterferenceType::SIMULATED: + switch (m_multipathType) + { + case MultipathInterferenceType::SIMULATED: nu_BRG += 2. * std::abs(modules[d][p]) * lambdav[u] * K_BG_nu[u] * std::cos(phases[d][p] + 2. * M_PI * f_c / SPEED_OF_LIGHT * d_BG[u]); break; - case MultipathInterferenceType::CONSTRUCTIVE: + case MultipathInterferenceType::CONSTRUCTIVE: nu_BRG += 2. * std::abs(modules[d][p]) * lambdav[u] * K_BG_nu[u]; break; - case MultipathInterferenceType::DESTRUCTIVE: + case MultipathInterferenceType::DESTRUCTIVE: nu_BRG -= 2. * std::abs(modules[d][p]) * lambdav[u] * K_BG_nu[u]; break; - } + } - sig_BRG += std::pow (etav[u][d], 2.) * std::pow (K_BRG_sigma, 2.) * - patches[p]->GetSize ().GetRowSize () * - patches[p]->GetSize ().GetColSize (); + sig_BRG += std::pow(etav[u][d], 2.) * std::pow(K_BRG_sigma, 2.) * + patches[p]->GetSize().GetRowSize() * patches[p]->GetSize().GetColSize(); } } - nu_BRG += std::pow (lambdav[u] * K_BG_nu[u], 2.); - sig_BRG += std::pow (lambdav[u] * K_BG_sigma[u], 2.); + nu_BRG += std::pow(lambdav[u] * K_BG_nu[u], 2.); + sig_BRG += std::pow(lambdav[u] * K_BG_sigma[u], 2.); - if (sig_BRG == 0. || nu_BRG == 0.) + if (sig_BRG == 0. || nu_BRG == 0.) { - gain.push_back (0.); + gain.push_back(0.); } - else + else { - K = nu_BRG / sig_BRG; - - sigma = nu_BRG + sig_BRG; - if (std::sqrt (2. * K) > 2.5848) - gain.push_back (std::pow (std::sqrt (2. * K) + - 0.5 / m_invqfunc * - std::log (std::sqrt (2. * K) / (std::sqrt (2. * K) - m_invqfunc)) - - m_invqfunc, - 2.) / - (2. * (K + 1.) / sigma)); - else - gain.push_back (std::pow (std::sqrt (-2. * std::log (1. - m_eps)) * exp (K / 2.), 2.) / - (2. * (K + 1.) / sigma)); + K = nu_BRG / sig_BRG; + + sigma = nu_BRG + sig_BRG; + if (std::sqrt(2. * K) > 2.5848) + gain.push_back(std::pow(std::sqrt(2. * K) + + 0.5 / m_invqfunc * + std::log(std::sqrt(2. * K) / + (std::sqrt(2. * K) - m_invqfunc)) - + m_invqfunc, + 2.) / + (2. * (K + 1.) / sigma)); + else + gain.push_back(std::pow(std::sqrt(-2. * std::log(1. - m_eps)) * exp(K / 2.), 2.) / + (2. * (K + 1.) / sigma)); } } - return gain; + return gain; } void -IrsAssistedSpectrumChannel::SetEps (const double e) +IrsAssistedSpectrumChannel::SetEps(const double e) { - m_eps = e; - SetInvqfunc (e); + m_eps = e; + SetInvqfunc(e); } void -IrsAssistedSpectrumChannel::SetInvqfunc (const double eps) +IrsAssistedSpectrumChannel::SetInvqfunc(const double eps) { - if (eps <= 0. || eps >= 1.) - NS_FATAL_ERROR ("epsilon must be between 0 and 1. Given: " << eps); + if (eps <= 0. || eps >= 1.) + NS_FATAL_ERROR("epsilon must be between 0 and 1. Given: " << eps); - constexpr double c[] = {2.515517, 0.802853, 0.010328}; - constexpr double d[] = {1.432788, 0.189269, 0.001308}; - double t = 0.; + constexpr double c[] = {2.515517, 0.802853, 0.010328}; + constexpr double d[] = {1.432788, 0.189269, 0.001308}; + double t = 0.; - if (eps < 0.5) - t = std::sqrt (-2. * std::log (eps)); - else - t = std::sqrt (-2. * std::log (1 - eps)); + if (eps < 0.5) + t = std::sqrt(-2. * std::log(eps)); + else + t = std::sqrt(-2. * std::log(1 - eps)); - m_invqfunc = (t - ((c[2] * t + c[1]) * t + c[0]) / (((d[2] * t + d[1]) * t + d[0]) * t + 1.)); + m_invqfunc = (t - ((c[2] * t + c[1]) * t + c[0]) / (((d[2] * t + d[1]) * t + d[0]) * t + 1.)); } Vector -IrsAssistedSpectrumChannel::BackRotate (const Vector &P, const RotoAxisType axis, double angle) +IrsAssistedSpectrumChannel::BackRotate(const Vector& P, const RotoAxisType axis, double angle) { - angle = -angle; - double x = 0., y = 0., z = 0.; - switch (axis) + angle = -angle; + double x = 0., y = 0., z = 0.; + switch (axis) { - case RotoAxisType::X_AXIS: //X=[1 0 0; 0 cos(angle) -sin(angle); 0 sin(angle) cos(angle)]; - x = P.x; - y = P.y * std::cos (angle) - P.z * std::sin (angle); - z = P.y * std::sin (angle) + P.z * std::cos (angle); - break; - case RotoAxisType::Y_AXIS: //Y=[cos(angle) 0 sin(angle); 0 1 0; -sin(angle) 0 cos(angle)]; - x = P.x * std::cos (angle) + P.z * std::sin (angle); - y = P.y; - z = P.z * std::cos (angle) - P.x * std::sin (angle); - break; - case RotoAxisType::Z_AXIS: //Z=[cos(angle) -sin(angle) 0; sin(angle) cos(angle) 0; 0 0 1]; - x = P.x * std::cos (angle) - P.y * std::sin (angle); - y = P.x * std::sin (angle) + P.y * std::cos (angle); - z = P.z; - break; + case RotoAxisType::X_AXIS: // X=[1 0 0; 0 cos(angle) -sin(angle); 0 sin(angle) cos(angle)]; + x = P.x; + y = P.y * std::cos(angle) - P.z * std::sin(angle); + z = P.y * std::sin(angle) + P.z * std::cos(angle); + break; + case RotoAxisType::Y_AXIS: // Y=[cos(angle) 0 sin(angle); 0 1 0; -sin(angle) 0 cos(angle)]; + x = P.x * std::cos(angle) + P.z * std::sin(angle); + y = P.y; + z = P.z * std::cos(angle) - P.x * std::sin(angle); + break; + case RotoAxisType::Z_AXIS: // Z=[cos(angle) -sin(angle) 0; sin(angle) cos(angle) 0; 0 0 1]; + x = P.x * std::cos(angle) - P.y * std::sin(angle); + y = P.x * std::sin(angle) + P.y * std::cos(angle); + z = P.z; + break; } - return {x, y, z}; + return {x, y, z}; } Vector -IrsAssistedSpectrumChannel::BackShift (const Vector &P, Ptr MM) +IrsAssistedSpectrumChannel::BackShift(const Vector& P, Ptr MM) { - const auto& pos = MM->GetPosition (); - return {P.x - pos.x, P.y - pos.y, P.z - pos.z}; + const auto& pos = MM->GetPosition(); + return {P.x - pos.x, P.y - pos.y, P.z - pos.z}; } void -IrsAssistedSpectrumChannel::NodeToIrssDistance (Ptr Node, - std::vector& d_Vector) +IrsAssistedSpectrumChannel::NodeToIrssDistance(Ptr Node, + std::vector& d_Vector) { - for (auto& irs : IrsList()) + for (auto& irs : IrsList()) { - const auto mm = irs->GetDrone()->GetObject(); - d_Vector.push_back (mm->GetDistanceFrom (Node)); + const auto mm = irs->GetDrone()->GetObject(); + d_Vector.push_back(mm->GetDistanceFrom(Node)); } } void -IrsAssistedSpectrumChannel::NodeToIrssAngles (Ptr node, - std::vector &a_Vector) +IrsAssistedSpectrumChannel::NodeToIrssAngles(Ptr node, std::vector& a_Vector) { - const Vector irsPos{0., 0., 0.}; - const Vector& nGlobalPos = node->GetPosition (); - // Is normalized the position of the node as if the res were centered - // in the origin of the axes and were parallel to the XY plane - for (auto& irs : IrsList()) + const Vector irsPos{0., 0., 0.}; + const Vector& nGlobalPos = node->GetPosition(); + // Is normalized the position of the node as if the res were centered + // in the origin of the axes and were parallel to the XY plane + for (auto& irs : IrsList()) { - const auto& rotoAxis = irs->GetRotoAxis(); - const auto& rotoAngles = irs->GetRotoAngles(); - const auto& irsMm = irs->GetDrone()->GetObject(); - auto nRelPos = BackShift(nGlobalPos, irsMm); + const auto& rotoAxis = irs->GetRotoAxis(); + const auto& rotoAngles = irs->GetRotoAngles(); + const auto& irsMm = irs->GetDrone()->GetObject(); + auto nRelPos = BackShift(nGlobalPos, irsMm); - for (auto i = rotoAxis.size(); i > 0; --i) - nRelPos = BackRotate(nRelPos, rotoAxis[i - 1], rotoAngles[i - 1]); + for (auto i = rotoAxis.size(); i > 0; --i) + nRelPos = BackRotate(nRelPos, rotoAxis[i - 1], rotoAngles[i - 1]); - a_Vector.push_back({nRelPos, irsPos}); + a_Vector.push_back({nRelPos, irsPos}); } } Angles -IrsAssistedSpectrumChannel::NodeToIrsAngles (Ptr node, Ptr irs) +IrsAssistedSpectrumChannel::NodeToIrsAngles(Ptr node, Ptr irs) { - const Vector irsPos{0., 0., 0.}; - // Is normalized the position of the node as if the res were centered - // in the origin of the axes and were parallel to the XY plane - const auto& irsMm = irs->GetDrone()->GetObject(); - const auto& rotoAxis = irs->GetRotoAxis(); - const auto& rotoAngles = irs->GetRotoAngles(); - Vector nPos = node->GetPosition(); - - nPos = BackShift(nPos, irsMm); - for (int i = rotoAxis.size(); i > 0; --i) - nPos = BackRotate(nPos, rotoAxis[i - 1], rotoAngles[i - 1]); - - return {nPos, irsPos}; + const Vector irsPos{0., 0., 0.}; + // Is normalized the position of the node as if the res were centered + // in the origin of the axes and were parallel to the XY plane + const auto& irsMm = irs->GetDrone()->GetObject(); + const auto& rotoAxis = irs->GetRotoAxis(); + const auto& rotoAngles = irs->GetRotoAngles(); + Vector nPos = node->GetPosition(); + + nPos = BackShift(nPos, irsMm); + for (int i = rotoAxis.size(); i > 0; --i) + nPos = BackRotate(nPos, rotoAxis[i - 1], rotoAngles[i - 1]); + + return {nPos, irsPos}; } void -IrsAssistedSpectrumChannel::IrsBeta (std::vector &beta, const double f_c) +IrsAssistedSpectrumChannel::IrsBeta(std::vector& beta, const double f_c) { - for (auto &irs : IrsList()) + for (auto& irs : IrsList()) { - const double s = irs->GetPruX () * irs->GetPruY (); - beta.push_back (std::pow (SPEED_OF_LIGHT / f_c, 2) * s / 64. / std::pow (M_PI, 3)); + const double s = irs->GetPruX() * irs->GetPruY(); + beta.push_back(std::pow(SPEED_OF_LIGHT / f_c, 2) * s / 64. / std::pow(M_PI, 3)); } } double -IrsAssistedSpectrumChannel::NodeToIrsDistance (Ptr node, Ptr irs) +IrsAssistedSpectrumChannel::NodeToIrsDistance(Ptr node, Ptr irs) { - const auto& irsMm = irs->GetDrone()->GetObject(); - return irsMm->GetDistanceFrom(node); + const auto& irsMm = irs->GetDrone()->GetObject(); + return irsMm->GetDistanceFrom(node); } void -IrsAssistedSpectrumChannel::GetServedParam (Ptr irs, Ptr patch, double &phaseY, - double &phaseX, double &distance) +IrsAssistedSpectrumChannel::GetServedParam(Ptr irs, + Ptr patch, + double& phaseY, + double& phaseX, + double& distance) { - const auto servedNodes = patch->GetServedNodes (); - const auto& node1Mm = servedNodes.first->GetObject (); - const auto& node2Mm = servedNodes.second->GetObject (); - const auto a_BR = NodeToIrsAngles (node1Mm, irs); - const auto a_RG = NodeToIrsAngles (node2Mm, irs); - - phaseY = std::sin(a_BR.GetInclination()) * std::cos(a_BR.GetAzimuth()) + - std::sin(a_RG.GetInclination()) * std::cos(a_RG.GetAzimuth()); - phaseX = std::sin(a_BR.GetInclination()) * std::sin(a_BR.GetAzimuth()) + - std::sin(a_RG.GetInclination()) * std::sin(a_RG.GetAzimuth()); - distance = NodeToIrsDistance (node1Mm, irs) + NodeToIrsDistance (node2Mm, irs); + const auto servedNodes = patch->GetServedNodes(); + const auto& node1Mm = servedNodes.first->GetObject(); + const auto& node2Mm = servedNodes.second->GetObject(); + const auto a_BR = NodeToIrsAngles(node1Mm, irs); + const auto a_RG = NodeToIrsAngles(node2Mm, irs); + + phaseY = std::sin(a_BR.GetInclination()) * std::cos(a_BR.GetAzimuth()) + + std::sin(a_RG.GetInclination()) * std::cos(a_RG.GetAzimuth()); + phaseX = std::sin(a_BR.GetInclination()) * std::sin(a_BR.GetAzimuth()) + + std::sin(a_RG.GetInclination()) * std::sin(a_RG.GetAzimuth()); + distance = NodeToIrsDistance(node1Mm, irs) + NodeToIrsDistance(node2Mm, irs); } double -IrsAssistedSpectrumChannel::GetElevation (const Vector &dest, const Vector &orig) +IrsAssistedSpectrumChannel::GetElevation(const Vector& dest, const Vector& orig) { - return fabs(asin((dest.z - orig.z) / CalculateDistance(dest, orig))); + return fabs(asin((dest.z - orig.z) / CalculateDistance(dest, orig))); } double -IrsAssistedSpectrumChannel::GetElevation (const Angles &angles) +IrsAssistedSpectrumChannel::GetElevation(const Angles& angles) { - double inclination = angles.GetInclination(); - double elevation = M_PI / 2. - inclination; + double inclination = angles.GetInclination(); + double elevation = M_PI / 2. - inclination; - if (inclination > M_PI / 2.) - { - // if the inclination is greater than 90 degrees, it needs to be - // normalized in the range [0,90] - elevation -= M_PI; - } + if (inclination > M_PI / 2.) + { + // if the inclination is greater than 90 degrees, it needs to be + // normalized in the range [0,90] + elevation -= M_PI; + } - return elevation; + return elevation; } } // namespace ns3 diff --git a/src/irs/irs-assisted-spectrum-channel.h b/src/irs/irs-assisted-spectrum-channel.h index 2800e04..9501201 100644 --- a/src/irs/irs-assisted-spectrum-channel.h +++ b/src/irs/irs-assisted-spectrum-channel.h @@ -20,13 +20,19 @@ #ifndef IRS_ASSISTED_SPECTRUM_CHANNEL_H #define IRS_ASSISTED_SPECTRUM_CHANNEL_H -#include - #include "irs.h" -namespace ns3 { +#include -enum MultipathInterferenceType { DESTRUCTIVE = -1, SIMULATED = 0, CONSTRUCTIVE = 1 }; +namespace ns3 +{ + +enum MultipathInterferenceType +{ + DESTRUCTIVE = -1, + SIMULATED = 0, + CONSTRUCTIVE = 1 +}; /** * \ingroup Irs @@ -39,68 +45,75 @@ enum MultipathInterferenceType { DESTRUCTIVE = -1, SIMULATED = 0, CONSTRUCTIVE = */ class IrsAssistedSpectrumChannel : public MultiModelSpectrumChannel { -public: - IrsAssistedSpectrumChannel (); - - /** - * \brief Get the type ID. - * \return the object TypeId - */ - static TypeId GetTypeId (void); - - virtual void StartTx (Ptr params); - -protected: - virtual void DoDispose (); - -private: - /*TODO*/ - std::vector - GetGain (const double f_c, const int n_users, const int n_irs, const std::vector &d_BG, - const std::vector &K_BR, const std::vector> &K_RG, - const std::vector> &etav, const std::vector &lambdav, - const std::vector &d_BR, const std::vector> &d_RG, - const std::vector &a_BR, const std::vector> &a_RG, - const std::vector &K_BG_nu, const std::vector &K_BG_sigma); - - /** - * \brief TODO - * - * \param - */ - void SetInvqfunc (const double epsilon); - - /** - * \brief TODO - * - * \param - */ - void SetEps (const double e); - - static Vector BackRotate (const Vector &P, const RotoAxisType axis, double angle); - static Vector BackShift (const Vector &P, Ptr MM); - static void NodeToIrssDistance (Ptr Node, std::vector &d_Vector); - static void NodeToIrssAngles (Ptr Node, std::vector &a_Vector); - static Angles NodeToIrsAngles (Ptr Node, Ptr irs); - static void IrsBeta (std::vector &beta, const double f_c); - static double NodeToIrsDistance (Ptr Node, Ptr irs); - static void GetServedParam(Ptr irs, - Ptr patch, - double& phaseY, - double& phaseX, - double& distance); - static double GetElevation(const Vector& destination, const Vector& origin); - static double GetElevation (const Angles &angles); - - double m_eps; - double m_invqfunc; - double m_kmin; - double m_kmax; - double m_knlos; - double m_alpha; - bool m_noDirectLink; - bool m_noIrsLink; - MultipathInterferenceType m_multipathType; + public: + IrsAssistedSpectrumChannel(); + + /** + * \brief Get the type ID. + * \return the object TypeId + */ + static TypeId GetTypeId(void); + + virtual void StartTx(Ptr params); + + protected: + virtual void DoDispose(); + + private: + /*TODO*/ + std::vector GetGain(const double f_c, + const int n_users, + const int n_irs, + const std::vector& d_BG, + const std::vector& K_BR, + const std::vector>& K_RG, + const std::vector>& etav, + const std::vector& lambdav, + const std::vector& d_BR, + const std::vector>& d_RG, + const std::vector& a_BR, + const std::vector>& a_RG, + const std::vector& K_BG_nu, + const std::vector& K_BG_sigma); + + /** + * \brief TODO + * + * \param + */ + void SetInvqfunc(const double epsilon); + + /** + * \brief TODO + * + * \param + */ + void SetEps(const double e); + + static Vector BackRotate(const Vector& P, const RotoAxisType axis, double angle); + static Vector BackShift(const Vector& P, Ptr MM); + static void NodeToIrssDistance(Ptr Node, std::vector& d_Vector); + static void NodeToIrssAngles(Ptr Node, std::vector& a_Vector); + static Angles NodeToIrsAngles(Ptr Node, Ptr irs); + static void IrsBeta(std::vector& beta, const double f_c); + static double NodeToIrsDistance(Ptr Node, Ptr irs); + static void GetServedParam(Ptr irs, + Ptr patch, + double& phaseY, + double& phaseX, + double& distance); + static double GetElevation(const Vector& destination, const Vector& origin); + static double GetElevation(const Angles& angles); + + double m_eps; + double m_invqfunc; + double m_kmin; + double m_kmax; + double m_knlos; + double m_alpha; + bool m_noDirectLink; + bool m_noIrsLink; + MultipathInterferenceType m_multipathType; }; } // namespace ns3 diff --git a/src/irs/irs-list.cc b/src/irs/irs-list.cc index ac20da0..9b24889 100644 --- a/src/irs/irs-list.cc +++ b/src/irs/irs-list.cc @@ -19,16 +19,16 @@ #include "irs-list.h" #include +#include #include #include #include #include -#include - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("IrsList"); +NS_LOG_COMPONENT_DEFINE("IrsList"); /** * \ingroup Irs @@ -36,191 +36,190 @@ NS_LOG_COMPONENT_DEFINE ("IrsList"); */ class IrsListPriv : public Object { -public: - /** - * \brief Get the type ID. - * \return the object TypeId. - */ - static TypeId GetTypeId (); - - IrsListPriv (); - ~IrsListPriv (); - - /** - * \param irs Irs to add - * \returns index of Irs in list - * - * This method should be called automatically from Irs::Irs at this time. - */ - uint32_t Add (Ptr irs); - - /** - * \returns a C++ iterator located at the beginning of this list. - */ - IrsList::Iterator Begin () const; - - /** - * \returns a C++ iterator located at the end of this list. - */ - IrsList::Iterator End () const; - - /** - * \param n index of requested Irs. - * \returns the Irs (Node) associated to index n. - */ + public: + /** + * \brief Get the type ID. + * \return the object TypeId. + */ + static TypeId GetTypeId(); + + IrsListPriv(); + ~IrsListPriv(); + + /** + * \param irs Irs to add + * \returns index of Irs in list + * + * This method should be called automatically from Irs::Irs at this time. + */ + uint32_t Add(Ptr irs); + + /** + * \returns a C++ iterator located at the beginning of this list. + */ + IrsList::Iterator Begin() const; + + /** + * \returns a C++ iterator located at the end of this list. + */ + IrsList::Iterator End() const; + + /** + * \param n index of requested Irs. + * \returns the Irs (Node) associated to index n. + */ Ptr Get(uint32_t n); - /** - * \returns the number of Irs currently in the list. - */ + /** + * \returns the number of Irs currently in the list. + */ uint32_t GetN(); - /** - * \brief Get the Irs list object - * \returns the Irs list - */ - static Ptr Get (); - -private: - /** - * \brief Get the irs list object - * \returns the irs list - */ - static Ptr *DoGet (); - - /** - * \brief Delete the Irs list object - */ - static void Delete (); - - /** - * \brief Dispose the Irs in the list - */ - virtual void DoDispose (); - - std::vector> m_irss; //!< Irs objects container + /** + * \brief Get the Irs list object + * \returns the Irs list + */ + static Ptr Get(); + + private: + /** + * \brief Get the irs list object + * \returns the irs list + */ + static Ptr* DoGet(); + + /** + * \brief Delete the Irs list object + */ + static void Delete(); + + /** + * \brief Dispose the Irs in the list + */ + virtual void DoDispose(); + + std::vector> m_irss; //!< Irs objects container }; TypeId -IrsListPriv::GetTypeId () +IrsListPriv::GetTypeId() { - static TypeId tid = TypeId ("ns3::IrsListPriv") - .SetParent () - .SetGroupName("Irs") - .AddAttribute ("IrsList", "The list of all Irs created during the simulation.", - ObjectVectorValue (), - MakeObjectVectorAccessor (&IrsListPriv::m_irss), - MakeObjectVectorChecker ()) - ; - - return tid; + static TypeId tid = TypeId("ns3::IrsListPriv") + .SetParent() + .SetGroupName("Irs") + .AddAttribute("IrsList", + "The list of all Irs created during the simulation.", + ObjectVectorValue(), + MakeObjectVectorAccessor(&IrsListPriv::m_irss), + MakeObjectVectorChecker()); + + return tid; } Ptr -IrsListPriv::Get () +IrsListPriv::Get() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return *DoGet (); + return *DoGet(); } -Ptr * -IrsListPriv::DoGet () +Ptr* +IrsListPriv::DoGet() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - static Ptr ptr = 0; - if (ptr == nullptr) + static Ptr ptr = 0; + if (ptr == nullptr) { - ptr = CreateObject (); - Config::RegisterRootNamespaceObject (ptr); - Simulator::ScheduleDestroy (&IrsListPriv::Delete); + ptr = CreateObject(); + Config::RegisterRootNamespaceObject(ptr); + Simulator::ScheduleDestroy(&IrsListPriv::Delete); } - return &ptr; + return &ptr; } void -IrsListPriv::Delete () +IrsListPriv::Delete() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - Config::UnregisterRootNamespaceObject (Get ()); - (*DoGet ()) = 0; + Config::UnregisterRootNamespaceObject(Get()); + (*DoGet()) = 0; } -IrsListPriv::IrsListPriv () +IrsListPriv::IrsListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -IrsListPriv::~IrsListPriv () +IrsListPriv::~IrsListPriv() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -IrsListPriv::DoDispose () +IrsListPriv::DoDispose() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - for (auto irs = m_irss.begin (); - irs != m_irss.end (); - irs++) + for (auto irs = m_irss.begin(); irs != m_irss.end(); irs++) { - (*irs)->Dispose (); + (*irs)->Dispose(); } - m_irss.erase (m_irss.begin (), m_irss.end ()); - Object::DoDispose (); + m_irss.erase(m_irss.begin(), m_irss.end()); + Object::DoDispose(); } uint32_t -IrsListPriv::Add (Ptr irs) +IrsListPriv::Add(Ptr irs) { - NS_LOG_FUNCTION (this << irs); + NS_LOG_FUNCTION(this << irs); - uint32_t index = m_irss.size (); + uint32_t index = m_irss.size(); - m_irss.push_back (irs); - Simulator::ScheduleWithContext (index, TimeStep (0), &Irs::Initialize, irs); + m_irss.push_back(irs); + Simulator::ScheduleWithContext(index, TimeStep(0), &Irs::Initialize, irs); - return index; + return index; } IrsList::Iterator -IrsListPriv::Begin () const +IrsListPriv::Begin() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_irss.begin (); + return m_irss.begin(); } IrsList::Iterator -IrsListPriv::End () const +IrsListPriv::End() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_irss.end (); + return m_irss.end(); } uint32_t IrsListPriv::GetN() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - return m_irss.size (); + return m_irss.size(); } Ptr IrsListPriv::Get(uint32_t n) { - NS_LOG_FUNCTION (this << n); + NS_LOG_FUNCTION(this << n); - NS_ASSERT_MSG (n < m_irss.size (), "Irs index " << n << - " is out of range (only have " << m_irss.size () << " irss)."); + NS_ASSERT_MSG(n < m_irss.size(), + "Irs index " << n << " is out of range (only have " << m_irss.size() + << " irss)."); - return m_irss[n]; + return m_irss[n]; } } // namespace ns3 @@ -230,54 +229,55 @@ IrsListPriv::Get(uint32_t n) * which calls into the private implementation though * the simulation of a singleton. */ -namespace ns3 { +namespace ns3 +{ uint32_t -IrsList::Add (Ptr irs) +IrsList::Add(Ptr irs) { - NS_LOG_FUNCTION (irs); + NS_LOG_FUNCTION(irs); - return IrsListPriv::Get ()->Add (irs); + return IrsListPriv::Get()->Add(irs); } IrsList::Iterator -IrsList::Begin () +IrsList::Begin() { - return IrsListPriv::Get ()->Begin (); + return IrsListPriv::Get()->Begin(); } IrsList::Iterator IrsList::begin() { - return IrsListPriv::Get()->Begin(); + return IrsListPriv::Get()->Begin(); } IrsList::Iterator -IrsList::End () +IrsList::End() { - return IrsListPriv::Get ()->End (); + return IrsListPriv::Get()->End(); } IrsList::Iterator IrsList::end() { - return IrsListPriv::Get()->End(); + return IrsListPriv::Get()->End(); } Ptr -IrsList::Get (uint32_t n) +IrsList::Get(uint32_t n) { - NS_LOG_FUNCTION (n); + NS_LOG_FUNCTION(n); - return IrsListPriv::Get ()->Get (n); + return IrsListPriv::Get()->Get(n); } uint32_t -IrsList::GetN () +IrsList::GetN() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return IrsListPriv::Get ()->GetN (); + return IrsListPriv::Get()->GetN(); } } // namespace ns3 diff --git a/src/irs/irs-list.h b/src/irs/irs-list.h index a99c872..a3675ad 100644 --- a/src/irs/irs-list.h +++ b/src/irs/irs-list.h @@ -18,16 +18,16 @@ #ifndef IRS_LIST_H #define IRS_LIST_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ class Irs; class CallbackBase; - /** * \ingroup Irs * @@ -37,40 +37,40 @@ class CallbackBase; */ class IrsList { -public: - /// Irs container iterator - typedef std::vector< Ptr >::const_iterator Iterator; + public: + /// Irs container iterator + typedef std::vector>::const_iterator Iterator; - /** - * \param irs drone to add - * \returns index of the Irs in list - * - * This method must be called automatically in order to register - * a node as a Irs - */ - static uint32_t Add (Ptr irs); + /** + * \param irs drone to add + * \returns index of the Irs in list + * + * This method must be called automatically in order to register + * a node as a Irs + */ + static uint32_t Add(Ptr irs); - /** - * \returns a C++ iterator located at the beginning of this list - */ - static Iterator Begin (); - static Iterator begin(); + /** + * \returns a C++ iterator located at the beginning of this list + */ + static Iterator Begin(); + static Iterator begin(); - /** - * \returns a C++ iterator located at the end of this list - */ - static Iterator End (); - static Iterator end(); + /** + * \returns a C++ iterator located at the end of this list + */ + static Iterator End(); + static Iterator end(); - /** - * \param n the index of requested Irs - * \returns the Irs (Node) associated to index n - */ + /** + * \param n the index of requested Irs + * \returns the Irs (Node) associated to index n + */ static Ptr Get(uint32_t n); - /** - * \returns the number of Irs currently in the list - */ + /** + * \returns the number of Irs currently in the list + */ static uint32_t GetN(); }; diff --git a/src/irs/irs-patch.cc b/src/irs/irs-patch.cc index 9fb5ef1..b0dbf8f 100644 --- a/src/irs/irs-patch.cc +++ b/src/irs/irs-patch.cc @@ -17,258 +17,267 @@ */ #include "irs-patch.h" -#include - #include #include -#include -#include -#include - #include +#include #include +#include +#include #include #include -namespace ns3 { +#include + +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("IrsPatch"); -NS_OBJECT_ENSURE_REGISTERED (IrsPatch); +NS_LOG_COMPONENT_DEFINE("IrsPatch"); +NS_OBJECT_ENSURE_REGISTERED(IrsPatch); TypeId -IrsPatch::GetTypeId () +IrsPatch::GetTypeId() { - static TypeId tid = - TypeId ("ns3::IrsPatch") - .SetParent () - .SetGroupName ("irs") - .AddConstructor () - .AddAttribute ("Size", - "Coordinates of the patch relative to the IRS. (Start Column Index, End " - "Column Index, Start Row Index, End Row Index)", - IntVectorValue (), MakeIntVectorAccessor (&IrsPatch::SetSizeSerialized), - MakeIntVectorChecker ()) - .AddAttribute ("PhaseX", - "Phase angle along the X axis in case the IRS is not serving any specific " - "communication.", - DoubleValue (), MakeDoubleAccessor (&IrsPatch::m_phaseX), - MakeDoubleChecker ()) - .AddAttribute ("PhaseY", - "Phase angle along the Y axis in case the IRS is not serving any specific " - "communication.", - DoubleValue (), MakeDoubleAccessor (&IrsPatch::m_phaseY), - MakeDoubleChecker ()) - .AddAttribute ("ServingNodes", "ns-3 XPath of serving nodes.", StrVecValue (), - MakeStrVecAccessor (&IrsPatch::SetServingNodesSerialized), - MakeStrVecChecker ()) - .AddAttribute ("LifeTime", "Life time of the patch in seconds.", - DoubleValue (0.0), // Use 0.0 to indicate that the patch will not expire - MakeDoubleAccessor (&IrsPatch::SetLifeTime), MakeDoubleChecker ()); - return tid; + static TypeId tid = + TypeId("ns3::IrsPatch") + .SetParent() + .SetGroupName("irs") + .AddConstructor() + .AddAttribute("Size", + "Coordinates of the patch relative to the IRS. (Start Column Index, End " + "Column Index, Start Row Index, End Row Index)", + IntVectorValue(), + MakeIntVectorAccessor(&IrsPatch::SetSizeSerialized), + MakeIntVectorChecker()) + .AddAttribute( + "PhaseX", + "Phase angle along the X axis in case the IRS is not serving any specific " + "communication.", + DoubleValue(), + MakeDoubleAccessor(&IrsPatch::m_phaseX), + MakeDoubleChecker()) + .AddAttribute( + "PhaseY", + "Phase angle along the Y axis in case the IRS is not serving any specific " + "communication.", + DoubleValue(), + MakeDoubleAccessor(&IrsPatch::m_phaseY), + MakeDoubleChecker()) + .AddAttribute("ServingNodes", + "ns-3 XPath of serving nodes.", + StrVecValue(), + MakeStrVecAccessor(&IrsPatch::SetServingNodesSerialized), + MakeStrVecChecker()) + .AddAttribute("LifeTime", + "Life time of the patch in seconds.", + DoubleValue(0.0), // Use 0.0 to indicate that the patch will not expire + MakeDoubleAccessor(&IrsPatch::SetLifeTime), + MakeDoubleChecker()); + return tid; } -IrsPatch::IrsPatch () +IrsPatch::IrsPatch() { - m_isServing = false; + m_isServing = false; } -IrsPatch::~IrsPatch () +IrsPatch::~IrsPatch() { } void -IrsPatch::DoDispose () +IrsPatch::DoDispose() { - NS_LOG_FUNCTION (this); - Object::DoDispose (); + NS_LOG_FUNCTION(this); + Object::DoDispose(); } void -IrsPatch::DoInitialize (void) +IrsPatch::DoInitialize(void) { - NS_LOG_FUNCTION (this); - Object::DoInitialize (); + NS_LOG_FUNCTION(this); + Object::DoInitialize(); } void -IrsPatch::SetSizeSerialized (const IntVector &a) +IrsPatch::SetSizeSerialized(const IntVector& a) { - NS_ASSERT_MSG (a.GetN () == 4, - "RowsRange needs extactly four values. Current input given: " << a); + NS_ASSERT_MSG(a.GetN() == 4, + "RowsRange needs extactly four values. Current input given: " << a); - m_size.startColIdx = a.Get (0); - m_size.endColIdx = a.Get (1); - m_size.startRowIdx = a.Get (2); - m_size.endRowIdx = a.Get (3); + m_size.startColIdx = a.Get(0); + m_size.endColIdx = a.Get(1); + m_size.startRowIdx = a.Get(2); + m_size.endRowIdx = a.Get(3); } void -IrsPatch::SetSize (const IrsPatch::Size &size) +IrsPatch::SetSize(const IrsPatch::Size& size) { - m_size = size; + m_size = size; } void IrsPatch::SetServingNodesSerialized(const StrVec& a) { - NS_ASSERT_MSG (a.GetN () == 2 || a.GetN () == 0, - "ServingNodes needs exactly two values or none, if dynamically configured. " - "Current input given: " - << a); - if (a.GetN () == 2) - SetServingNodes (a.Get (0), a.Get (1)); + NS_ASSERT_MSG(a.GetN() == 2 || a.GetN() == 0, + "ServingNodes needs exactly two values or none, if dynamically configured. " + "Current input given: " + << a); + if (a.GetN() == 2) + SetServingNodes(a.Get(0), a.Get(1)); } void -IrsPatch::SetServingNodes (const std::string &nodeXPath1, const std::string &nodeXPath2) +IrsPatch::SetServingNodes(const std::string& nodeXPath1, const std::string& nodeXPath2) { - SetServingNodes (LookupNodeByPath (nodeXPath1), LookupNodeByPath (nodeXPath2)); + SetServingNodes(LookupNodeByPath(nodeXPath1), LookupNodeByPath(nodeXPath2)); } Ptr -IrsPatch::LookupNodeByPath (const std::string &nodePath) const +IrsPatch::LookupNodeByPath(const std::string& nodePath) const { - auto matches = Config::LookupMatches (nodePath); - NS_ASSERT_MSG (matches.GetN () == 1, - "There is ambiguity with the given Node XPath: " << nodePath); - return StaticCast (matches.Get (0)); + auto matches = Config::LookupMatches(nodePath); + NS_ASSERT_MSG(matches.GetN() == 1, + "There is ambiguity with the given Node XPath: " << nodePath); + return StaticCast(matches.Get(0)); } void -IrsPatch::SetServingNodes (uint32_t nid1, uint32_t nid2) +IrsPatch::SetServingNodes(uint32_t nid1, uint32_t nid2) { - SetServingNodes (NodeList::GetNode (nid1), NodeList::GetNode (nid2)); + SetServingNodes(NodeList::GetNode(nid1), NodeList::GetNode(nid2)); } void -IrsPatch::SetServingNodes (Ptr n1, Ptr n2) +IrsPatch::SetServingNodes(Ptr n1, Ptr n2) { - NS_ASSERT_MSG (n1 != nullptr && n2 != nullptr, "ServingNodes must be set with two valid nodes."); - m_isServing = true; - m_servingNodes = std::make_pair (n1, n2); + NS_ASSERT_MSG(n1 != nullptr && n2 != nullptr, "ServingNodes must be set with two valid nodes."); + m_isServing = true; + m_servingNodes = std::make_pair(n1, n2); } void -IrsPatch::SetPhaseX (double phase) +IrsPatch::SetPhaseX(double phase) { - m_phaseX = phase; + m_phaseX = phase; } void -IrsPatch::SetPhaseY (double phase) +IrsPatch::SetPhaseY(double phase) { - m_phaseY = phase; + m_phaseY = phase; } const std::pair, Ptr> -IrsPatch::GetServedNodes () const +IrsPatch::GetServedNodes() const { - return m_servingNodes; + return m_servingNodes; } const IrsPatch::Size -IrsPatch::GetSize () const +IrsPatch::GetSize() const { - return m_size; + return m_size; } const bool -IrsPatch::IsServing () const +IrsPatch::IsServing() const { - return m_isServing; + return m_isServing; } const double -IrsPatch::GetPhaseX () const +IrsPatch::GetPhaseX() const { - return m_phaseX; + return m_phaseX; } const double -IrsPatch::GetPhaseY () const +IrsPatch::GetPhaseY() const { - return m_phaseY; + return m_phaseY; } void -IrsPatch::SetLifeTime (const double l) +IrsPatch::SetLifeTime(const double l) { - m_lifetime = (l == 0.0) ? CONFIGURATOR->GetDuration () : l; + m_lifetime = (l == 0.0) ? CONFIGURATOR->GetDuration() : l; } const double -IrsPatch::GetLifeTime () const +IrsPatch::GetLifeTime() const { - return m_lifetime; + return m_lifetime; } -std::ostream & -operator<< (std::ostream &os, const IrsPatch::Size &size) +std::ostream& +operator<<(std::ostream& os, const IrsPatch::Size& size) { - os << size.startColIdx << ";" << size.endColIdx << ";" << size.startRowIdx << ";" - << size.endRowIdx << ";"; - return os; + os << size.startColIdx << ";" << size.endColIdx << ";" << size.startRowIdx << ";" + << size.endRowIdx << ";"; + return os; } -std::ostream & -operator<< (std::ostream &os, const IrsPatch &patch) +std::ostream& +operator<<(std::ostream& os, const IrsPatch& patch) { - os << patch.GetSize () << ";" << patch.GetPhaseX () << ";" << patch.GetPhaseY () << ";" - << patch.IsServing () << ";" << patch.GetServedNodes ().first->GetId () << ";" - << patch.GetServedNodes ().second->GetId () << ";"; - return os; + os << patch.GetSize() << ";" << patch.GetPhaseX() << ";" << patch.GetPhaseY() << ";" + << patch.IsServing() << ";" << patch.GetServedNodes().first->GetId() << ";" + << patch.GetServedNodes().second->GetId() << ";"; + return os; } -std::istream & -operator>> (std::istream &is, IrsPatch::Size &size) +std::istream& +operator>>(std::istream& is, IrsPatch::Size& size) { - uint32_t startColIdx, endColIdx, startRowIdx, endRowIdx; - is >> startColIdx; - is.ignore (1); - is >> endColIdx; - is.ignore (1); - is >> startRowIdx; - is.ignore (1); - is >> endRowIdx; - is.ignore (1); - - size.startColIdx = startColIdx; - size.endColIdx = endColIdx; - size.startRowIdx = startRowIdx; - size.endRowIdx = endRowIdx; - - return is; + uint32_t startColIdx, endColIdx, startRowIdx, endRowIdx; + is >> startColIdx; + is.ignore(1); + is >> endColIdx; + is.ignore(1); + is >> startRowIdx; + is.ignore(1); + is >> endRowIdx; + is.ignore(1); + + size.startColIdx = startColIdx; + size.endColIdx = endColIdx; + size.startRowIdx = startRowIdx; + size.endRowIdx = endRowIdx; + + return is; } -std::istream & -operator>> (std::istream &is, IrsPatch &patch) +std::istream& +operator>>(std::istream& is, IrsPatch& patch) { - IrsPatch::Size size; - double phaseX, phaseY; - bool isServing; - int servingNodeId1, servingNodeId2; - - is >> size; - is.ignore (1); - is >> phaseX; - is.ignore (1); - is >> phaseY; - is.ignore (1); - is >> isServing; - is.ignore (1); - is >> servingNodeId1; - is.ignore (1); - is >> servingNodeId2; - is.ignore (1); - - patch.SetSize (size); - patch.SetPhaseX (phaseX); - patch.SetPhaseY (phaseY); - - if (isServing) - patch.SetServingNodes (servingNodeId1, servingNodeId2); - - return is; + IrsPatch::Size size; + double phaseX, phaseY; + bool isServing; + int servingNodeId1, servingNodeId2; + + is >> size; + is.ignore(1); + is >> phaseX; + is.ignore(1); + is >> phaseY; + is.ignore(1); + is >> isServing; + is.ignore(1); + is >> servingNodeId1; + is.ignore(1); + is >> servingNodeId2; + is.ignore(1); + + patch.SetSize(size); + patch.SetPhaseX(phaseX); + patch.SetPhaseY(phaseY); + + if (isServing) + patch.SetServingNodes(servingNodeId1, servingNodeId2); + + return is; } -} //namespace ns3 +} // namespace ns3 diff --git a/src/irs/irs-patch.h b/src/irs/irs-patch.h index 04c39e6..ec225d6 100644 --- a/src/irs/irs-patch.h +++ b/src/irs/irs-patch.h @@ -18,14 +18,13 @@ #ifndef IRS_PATCH_H #define IRS_PATCH_H -#include - #include #include #include #include #include +#include namespace ns3 { @@ -35,98 +34,109 @@ namespace ns3 */ class IrsPatch : public Object { -public: - /** Helper class to define the dimensions of the Patch relative to the IRS. */ - class Size - { public: - Size () : - startColIdx {0}, - endColIdx {0}, - startRowIdx {0}, - endRowIdx {0} - {} - Size (uint32_t startColIdx, uint32_t endColIdx, - uint32_t startRowIdx, uint32_t endRowIdx) : - startColIdx {startColIdx}, - endColIdx {endColIdx}, - startRowIdx {startRowIdx}, - endRowIdx {endRowIdx} - {} - - const uint32_t GetRowSize () const { return endRowIdx - startRowIdx + 1; } - const uint32_t GetColSize () const { return endColIdx - startColIdx + 1; } - - uint32_t startColIdx; - uint32_t endColIdx; - uint32_t startRowIdx; - uint32_t endRowIdx; - }; - - static TypeId GetTypeId (); - - IrsPatch (); - ~IrsPatch (); - - /** Set the size of the patch. - * \param serializedSize The coordinates of the patch specified through a - * serialized vector with the following sequence of ints: - * 0. Start Column Index - * 1. End Column Index - * 2. Start Row Index - * 3. End Row Index - */ - void SetSizeSerialized (const IntVector& serializedSize); - /** Set the size of the patch given a IrsPatch::Size object. */ - void SetSize (const IrsPatch::Size& size); - /** Set the nodes served by this Patch given a vector of two Node XPaths. */ - void SetServingNodesSerialized(const StrVec& nodeIds); - /** Set the nodes served by this Patch given their ns-3 XPath. */ - void SetServingNodes (const std::string& nodeXPath1, const std::string& nodeXPath2); - /** Lookup and retrieve Node reference given its ns-3 XPath. */ - Ptr LookupNodeByPath (const std::string& nodePath) const; - /** Set the nodes served by this Patch given two Node IDs. */ - void SetServingNodes (const uint32_t nodeId1, const uint32_t nodeId2); - /** Set the nodes served by this Patch given two Node pointers. */ - void SetServingNodes (const Ptr node1, const Ptr node2); - /** Set PhaseX of this Patch. */ - void SetPhaseX (const double phaseX); - /** Set PhaseY of this Patch. */ - void SetPhaseY (const double phaseY); - - const Size GetSize () const; - /** Get the served nodes. */ - const std::pair, Ptr> GetServedNodes () const; - /** Determine whether the IRS Patch is serving specific Nodes or not. */ - const bool IsServing () const; - /** Retrieve the phase shift along the X-axis. */ - const double GetPhaseX () const; - /** Retrieve the phase shift along the Y-axis. */ - const double GetPhaseY () const; - /**Set life periods from JSON using TypeId**/ - void SetLifeTime (const double l); - /**Get life periods**/ - const double GetLifeTime () const; - -protected: - void DoInitialize (void); - void DoDispose (void); - -private: - Size m_size; - bool m_isServing; /// Indicate if this patch is serving any Node - double m_phaseX; /// Phase shift on the X-axis used if the patch is not serving any PhyLayer (or Node) - double m_phaseY; /// Phase shift on the Y-axis used if the patch is not serving any PhyLayer (or Node) - std::pair, Ptr> m_servingNodes; /// The Nodes served by this Patch - double m_lifetime; /// The life time of this Patch + /** Helper class to define the dimensions of the Patch relative to the IRS. */ + class Size + { + public: + Size() + : startColIdx{0}, + endColIdx{0}, + startRowIdx{0}, + endRowIdx{0} + { + } + + Size(uint32_t startColIdx, uint32_t endColIdx, uint32_t startRowIdx, uint32_t endRowIdx) + : startColIdx{startColIdx}, + endColIdx{endColIdx}, + startRowIdx{startRowIdx}, + endRowIdx{endRowIdx} + { + } + + const uint32_t GetRowSize() const + { + return endRowIdx - startRowIdx + 1; + } + + const uint32_t GetColSize() const + { + return endColIdx - startColIdx + 1; + } + + uint32_t startColIdx; + uint32_t endColIdx; + uint32_t startRowIdx; + uint32_t endRowIdx; + }; + + static TypeId GetTypeId(); + + IrsPatch(); + ~IrsPatch(); + + /** Set the size of the patch. + * \param serializedSize The coordinates of the patch specified through a + * serialized vector with the following sequence of ints: + * 0. Start Column Index + * 1. End Column Index + * 2. Start Row Index + * 3. End Row Index + */ + void SetSizeSerialized(const IntVector& serializedSize); + /** Set the size of the patch given a IrsPatch::Size object. */ + void SetSize(const IrsPatch::Size& size); + /** Set the nodes served by this Patch given a vector of two Node XPaths. */ + void SetServingNodesSerialized(const StrVec& nodeIds); + /** Set the nodes served by this Patch given their ns-3 XPath. */ + void SetServingNodes(const std::string& nodeXPath1, const std::string& nodeXPath2); + /** Lookup and retrieve Node reference given its ns-3 XPath. */ + Ptr LookupNodeByPath(const std::string& nodePath) const; + /** Set the nodes served by this Patch given two Node IDs. */ + void SetServingNodes(const uint32_t nodeId1, const uint32_t nodeId2); + /** Set the nodes served by this Patch given two Node pointers. */ + void SetServingNodes(const Ptr node1, const Ptr node2); + /** Set PhaseX of this Patch. */ + void SetPhaseX(const double phaseX); + /** Set PhaseY of this Patch. */ + void SetPhaseY(const double phaseY); + + const Size GetSize() const; + /** Get the served nodes. */ + const std::pair, Ptr> GetServedNodes() const; + /** Determine whether the IRS Patch is serving specific Nodes or not. */ + const bool IsServing() const; + /** Retrieve the phase shift along the X-axis. */ + const double GetPhaseX() const; + /** Retrieve the phase shift along the Y-axis. */ + const double GetPhaseY() const; + /**Set life periods from JSON using TypeId**/ + void SetLifeTime(const double l); + /**Get life periods**/ + const double GetLifeTime() const; + + protected: + void DoInitialize(void); + void DoDispose(void); + + private: + Size m_size; + bool m_isServing; /// Indicate if this patch is serving any Node + double m_phaseX; /// Phase shift on the X-axis used if the patch is not serving any PhyLayer (or + /// Node) + double m_phaseY; /// Phase shift on the Y-axis used if the patch is not serving any PhyLayer (or + /// Node) + std::pair, Ptr> m_servingNodes; /// The Nodes served by this Patch + double m_lifetime; /// The life time of this Patch }; -ATTRIBUTE_HELPER_HEADER (IrsPatch); +ATTRIBUTE_HELPER_HEADER(IrsPatch); -std::ostream& operator<< (std::ostream& os, const IrsPatch::Size& s); -std::ostream& operator<< (std::ostream& os, const IrsPatch& p); -std::istream& operator>> (std::istream& is, IrsPatch::Size& s); -std::istream& operator>> (std::istream& is, IrsPatch& p); +std::ostream& operator<<(std::ostream& os, const IrsPatch::Size& s); +std::ostream& operator<<(std::ostream& os, const IrsPatch& p); +std::istream& operator>>(std::istream& is, IrsPatch::Size& s); +std::istream& operator>>(std::istream& is, IrsPatch& p); } // namespace ns3 diff --git a/src/irs/irs.cc b/src/irs/irs.cc index 7994cec..bcc41a3 100644 --- a/src/irs/irs.cc +++ b/src/irs/irs.cc @@ -17,189 +17,205 @@ */ #include "irs.h" -#include +#include +#include #include -#include - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Irs"); +NS_LOG_COMPONENT_DEFINE("Irs"); -NS_OBJECT_ENSURE_REGISTERED (Irs); +NS_OBJECT_ENSURE_REGISTERED(Irs); TypeId -Irs::GetTypeId () -{ - static TypeId tid = - TypeId ("ns3::Irs") - .SetParent () - .SetGroupName ("Irs") - .AddConstructor () - .AddAttribute ("Rows", "N, the number of rows", IntegerValue (1), - MakeIntegerAccessor (&Irs::m_rows), MakeIntegerChecker ()) - .AddAttribute ("Columns", "M, the number of columns", IntegerValue (1), - MakeIntegerAccessor (&Irs::m_columns), MakeIntegerChecker ()) - .AddAttribute ("PruX", "X-side dimension of the Passive Reflective Unit (in meter)", - DoubleValue (0.01), MakeDoubleAccessor (&Irs::m_pruX), - MakeDoubleChecker ()) - .AddAttribute ("PruY", "Y-side dimension of the Passive Reflective Unit (in meter)", - DoubleValue (0.01), MakeDoubleAccessor (&Irs::m_pruY), - MakeDoubleChecker ()) - .AddAttribute ( - "RotoAxis", - "Well-ordered list of axis used to set IRS rotation (or to BackRotate other points)", - StrVecValue (), MakeStrVecAccessor (&Irs::SetRotoAxis), - MakeStrVecChecker ()) - .AddAttribute ( - "RotoAngles", - "List of angles (in radians) used to rotate the IRS, the n-th angles refers to n-th " - "axis defined in m_rotoAxis (or to BackRotate other points)", - DoubleVectorValue (), MakeDoubleVectorAccessor (&Irs::SetRotoAnglesDegrees), - MakeDoubleVectorChecker ()) - .AddAttribute ("Patches", "List of patches used to build the IRS", - ModelConfigurationVectorValue (), - MakeModelConfigurationVectorAccessor (&Irs::SetPatchVector), - MakeModelConfigurationVectorChecker ()); - return tid; +Irs::GetTypeId() +{ + static TypeId tid = + TypeId("ns3::Irs") + .SetParent() + .SetGroupName("Irs") + .AddConstructor() + .AddAttribute("Rows", + "N, the number of rows", + IntegerValue(1), + MakeIntegerAccessor(&Irs::m_rows), + MakeIntegerChecker()) + .AddAttribute("Columns", + "M, the number of columns", + IntegerValue(1), + MakeIntegerAccessor(&Irs::m_columns), + MakeIntegerChecker()) + .AddAttribute("PruX", + "X-side dimension of the Passive Reflective Unit (in meter)", + DoubleValue(0.01), + MakeDoubleAccessor(&Irs::m_pruX), + MakeDoubleChecker()) + .AddAttribute("PruY", + "Y-side dimension of the Passive Reflective Unit (in meter)", + DoubleValue(0.01), + MakeDoubleAccessor(&Irs::m_pruY), + MakeDoubleChecker()) + .AddAttribute("RotoAxis", + "Well-ordered list of axis used to set IRS rotation (or to BackRotate " + "other points)", + StrVecValue(), + MakeStrVecAccessor(&Irs::SetRotoAxis), + MakeStrVecChecker()) + .AddAttribute("RotoAngles", + "List of angles (in radians) used to rotate the IRS, the n-th angles " + "refers to n-th " + "axis defined in m_rotoAxis (or to BackRotate other points)", + DoubleVectorValue(), + MakeDoubleVectorAccessor(&Irs::SetRotoAnglesDegrees), + MakeDoubleVectorChecker()) + .AddAttribute("Patches", + "List of patches used to build the IRS", + ModelConfigurationVectorValue(), + MakeModelConfigurationVectorAccessor(&Irs::SetPatchVector), + MakeModelConfigurationVectorChecker()); + return tid; } -Irs::Irs () +Irs::Irs() { } void -Irs::DoDispose () +Irs::DoDispose() { - NS_LOG_FUNCTION (this); - Object::DoDispose (); + NS_LOG_FUNCTION(this); + Object::DoDispose(); } void -Irs::DoInitialize (void) +Irs::DoInitialize(void) { - NS_LOG_FUNCTION (this); - Object::DoInitialize (); + NS_LOG_FUNCTION(this); + Object::DoInitialize(); } double -Irs::GetPruX () const +Irs::GetPruX() const { - return m_pruX; + return m_pruX; } double -Irs::GetPruY () const +Irs::GetPruY() const { - return m_pruY; + return m_pruY; } void Irs::SetRotoAxis(const StrVec& v) { - for (auto &x : v) + for (auto& x : v) { - if (x == "X_AXIS") - m_rotoAxis.push_back (RotoAxisType::X_AXIS); - else if (x == "Y_AXIS") - m_rotoAxis.push_back (RotoAxisType::Y_AXIS); - else if (x == "Z_AXIS") - m_rotoAxis.push_back (RotoAxisType::Z_AXIS); - else - NS_ABORT_MSG ("Cannot convert input \"" - << x - << "\" to any of the " - "following values: [\"X_AXIS\", \"Y_AXIS\", \"Z_AXIS\"]"); + if (x == "X_AXIS") + m_rotoAxis.push_back(RotoAxisType::X_AXIS); + else if (x == "Y_AXIS") + m_rotoAxis.push_back(RotoAxisType::Y_AXIS); + else if (x == "Z_AXIS") + m_rotoAxis.push_back(RotoAxisType::Z_AXIS); + else + NS_ABORT_MSG("Cannot convert input \"" + << x + << "\" to any of the " + "following values: [\"X_AXIS\", \"Y_AXIS\", \"Z_AXIS\"]"); } } -const std::vector & -Irs::GetRotoAxis () const +const std::vector& +Irs::GetRotoAxis() const { - return m_rotoAxis; + return m_rotoAxis; } void -Irs::SetRotoAnglesDegrees (const DoubleVector &a) +Irs::SetRotoAnglesDegrees(const DoubleVector& a) { - for (auto c = a.Begin (); c != a.End (); c++) + for (auto c = a.Begin(); c != a.End(); c++) { - m_rotoAngles.push_back (*c / 180 * M_PI); + m_rotoAngles.push_back(*c / 180 * M_PI); } } std::vector -Irs::GetRotoAngles () const +Irs::GetRotoAngles() const { - return m_rotoAngles; + return m_rotoAngles; } std::vector> -Irs::GetPatchVector () const +Irs::GetPatchVector() const { - return m_patches; + return m_patches; } void -Irs::SetPatchVector (ModelConfigurationVector patchConfs) +Irs::SetPatchVector(ModelConfigurationVector patchConfs) { - NS_LOG_FUNCTION (patchConfs); - ObjectFactory factory; + NS_LOG_FUNCTION(patchConfs); + ObjectFactory factory; - for (uint32_t i = 0; i < m_patches.size (); i++) + for (uint32_t i = 0; i < m_patches.size(); i++) { - m_patches[i]->Dispose (); + m_patches[i]->Dispose(); } - m_patches.clear (); + m_patches.clear(); - for (auto c = patchConfs.Begin (); c != patchConfs.End (); c++) + for (auto c = patchConfs.Begin(); c != patchConfs.End(); c++) { - factory = ObjectFactory{"ns3::IrsPatch"}; - for (auto attrIt = c->AttributesBegin (); attrIt != c->AttributesEnd (); attrIt++) - factory.Set (attrIt->name, *attrIt->value); + factory = ObjectFactory{"ns3::IrsPatch"}; + for (auto attrIt = c->AttributesBegin(); attrIt != c->AttributesEnd(); attrIt++) + factory.Set(attrIt->name, *attrIt->value); - auto patch = factory.Create (); + auto patch = factory.Create(); - for (auto aggIt = c->AggregatesBegin (); aggIt != c->AggregatesEnd (); aggIt++) + for (auto aggIt = c->AggregatesBegin(); aggIt != c->AggregatesEnd(); aggIt++) { - factory = ObjectFactory{aggIt->GetName ()}; - for (auto attrIt = aggIt->AttributesBegin (); attrIt != aggIt->AttributesEnd (); attrIt++) - factory.Set (attrIt->name, *attrIt->value); + factory = ObjectFactory{aggIt->GetName()}; + for (auto attrIt = aggIt->AttributesBegin(); attrIt != aggIt->AttributesEnd(); attrIt++) + factory.Set(attrIt->name, *attrIt->value); - auto obj = factory.Create (); - obj->AggregateObject (patch); - obj->Initialize (); + auto obj = factory.Create(); + obj->AggregateObject(patch); + obj->Initialize(); } - NS_ABORT_MSG_IF (!AddPatch (patch), - "Error while adding patch to the IRS, as there is overlapping."); + NS_ABORT_MSG_IF(!AddPatch(patch), + "Error while adding patch to the IRS, as there is overlapping."); } } bool -Irs::AddPatch (Ptr p) +Irs::AddPatch(Ptr p) { - for (auto &installedPatch : m_patches) - if (IsOverlapped (p->GetSize (), installedPatch->GetSize ())) - return false; + for (auto& installedPatch : m_patches) + if (IsOverlapped(p->GetSize(), installedPatch->GetSize())) + return false; - m_patches.push_back (p); - return true; + m_patches.push_back(p); + return true; } const bool -Irs::IsOverlapped (const uint32_t aStart, const uint32_t aEnd, const uint32_t bStart, const uint32_t bEnd) +Irs::IsOverlapped(const uint32_t aStart, + const uint32_t aEnd, + const uint32_t bStart, + const uint32_t bEnd) { - return (aStart <= bStart && aEnd >= bEnd) || (bStart <= aStart && aStart <= bEnd) || - (bStart <= aEnd && aEnd <= bEnd); + return (aStart <= bStart && aEnd >= bEnd) || (bStart <= aStart && aStart <= bEnd) || + (bStart <= aEnd && aEnd <= bEnd); } const bool -Irs::IsOverlapped (const IrsPatch::Size &a, const IrsPatch::Size &b) +Irs::IsOverlapped(const IrsPatch::Size& a, const IrsPatch::Size& b) { - return IsOverlapped (a.startColIdx, a.endColIdx, b.startColIdx, b.endColIdx) && - IsOverlapped (a.startRowIdx, a.endRowIdx, b.startRowIdx, b.endRowIdx); + return IsOverlapped(a.startColIdx, a.endColIdx, b.startColIdx, b.endColIdx) && + IsOverlapped(a.startRowIdx, a.endRowIdx, b.startRowIdx, b.endRowIdx); } -} //namespace ns3 +} // namespace ns3 diff --git a/src/irs/irs.h b/src/irs/irs.h index 170ac3e..e7c3a5c 100644 --- a/src/irs/irs.h +++ b/src/irs/irs.h @@ -18,127 +18,137 @@ #ifndef IRS_H #define IRS_H -#include - -#include -#include - #include #include #include #include +#include #include +#include + +#include -namespace ns3 { +namespace ns3 +{ -enum class RotoAxisType { X_AXIS = 0, Y_AXIS, Z_AXIS }; +enum class RotoAxisType +{ + X_AXIS = 0, + Y_AXIS, + Z_AXIS +}; /** - * \brief Base class describing an Intelligent Reflective Surface aggregable to a node like a peripheral. + * \brief Base class describing an Intelligent Reflective Surface aggregable to a node like a + * peripheral. */ class Irs : public DronePeripheral { -public: - typedef std::vector>::iterator PatchIterator; - - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); - - /** - * \brief constructor used to instantiate an IRS. - */ - Irs (); - - /** - * \brief Returns the X-side dimension of a single Passive Reflective Unit. - * - * \returns X-side dimension of the PRU. - */ - double GetPruX () const; - - /** - * \brief Returns the Y-side dimension of a single Passive Reflective Unit. - * - * \returns Y-side dimension of the PRU. - */ - double GetPruY () const; - /** - * \brief TODO - * - * \param a TODO - */ - void SetRotoAxis(const StrVec& v); - - /** - * \brief TODO - * - * \returns TODO - */ - const std::vector &GetRotoAxis () const; - - /** - * \brief TODO - * - * \param a TODO - */ - void SetRotoAnglesDegrees (const DoubleVector &a); - - /** - * \brief TODO - * - * \returns TODO - */ - std::vector GetRotoAngles () const; - - /** - * \returns Retrieve the current state of patches. - */ - std::vector> GetPatchVector () const; - - /** - * \returns Initialize the IRS with a new set of Patches from a Model description. - */ - void SetPatchVector (ModelConfigurationVector patchConfigurations); - - /** - * \brief Add a new patch to an irs. In order to guarantee consistency an overlap check is done. - * - * \param p Patch that needs to be added - * \returns Result of the overlap check - */ - bool AddPatch (Ptr p); - - uint32_t GetPatchN () const; //Not implemented - - Ptr GetPatch (uint32_t i) const; //Not implemented - - PatchIterator BeginPatch (); //Not implemented - - PatchIterator EndPatch (); //Not implemented - -protected: - virtual void DoDispose (void); - virtual void DoInitialize (void); - -private: - static const bool IsOverlapped (const uint32_t aStart, const uint32_t aEnd, const uint32_t bStart, const uint32_t bEnd); - static const bool IsOverlapped (const IrsPatch::Size &a, const IrsPatch::Size &b); - - int m_rows; //N, the number of rows - int m_columns; //M, the number of columns - double m_pruX; //X-side dimension of the Passive Reflective Unit (in meter) - double m_pruY; //Y-side dimension of the Passive Reflective Unit (in meter) - std::vector - m_rotoAxis; //Well-ordered list of axis used to set IRS rotation (or to BackRotate other points) - std::vector - m_rotoAngles; //List of angles (in radians) used to rotate the IRS, the n-th angles refers to n-th axis defined in m_rotoAxis (or to BackRotate other points) - std::vector> m_patches; //List of patches + public: + typedef std::vector>::iterator PatchIterator; + + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); + + /** + * \brief constructor used to instantiate an IRS. + */ + Irs(); + + /** + * \brief Returns the X-side dimension of a single Passive Reflective Unit. + * + * \returns X-side dimension of the PRU. + */ + double GetPruX() const; + + /** + * \brief Returns the Y-side dimension of a single Passive Reflective Unit. + * + * \returns Y-side dimension of the PRU. + */ + double GetPruY() const; + /** + * \brief TODO + * + * \param a TODO + */ + void SetRotoAxis(const StrVec& v); + + /** + * \brief TODO + * + * \returns TODO + */ + const std::vector& GetRotoAxis() const; + + /** + * \brief TODO + * + * \param a TODO + */ + void SetRotoAnglesDegrees(const DoubleVector& a); + + /** + * \brief TODO + * + * \returns TODO + */ + std::vector GetRotoAngles() const; + + /** + * \returns Retrieve the current state of patches. + */ + std::vector> GetPatchVector() const; + + /** + * \returns Initialize the IRS with a new set of Patches from a Model description. + */ + void SetPatchVector(ModelConfigurationVector patchConfigurations); + + /** + * \brief Add a new patch to an irs. In order to guarantee consistency an overlap check is done. + * + * \param p Patch that needs to be added + * \returns Result of the overlap check + */ + bool AddPatch(Ptr p); + + uint32_t GetPatchN() const; // Not implemented + + Ptr GetPatch(uint32_t i) const; // Not implemented + + PatchIterator BeginPatch(); // Not implemented + + PatchIterator EndPatch(); // Not implemented + + protected: + virtual void DoDispose(void); + virtual void DoInitialize(void); + + private: + static const bool IsOverlapped(const uint32_t aStart, + const uint32_t aEnd, + const uint32_t bStart, + const uint32_t bEnd); + static const bool IsOverlapped(const IrsPatch::Size& a, const IrsPatch::Size& b); + + int m_rows; // N, the number of rows + int m_columns; // M, the number of columns + double m_pruX; // X-side dimension of the Passive Reflective Unit (in meter) + double m_pruY; // Y-side dimension of the Passive Reflective Unit (in meter) + std::vector m_rotoAxis; // Well-ordered list of axis used to set IRS rotation (or + // to BackRotate other points) + std::vector + m_rotoAngles; // List of angles (in radians) used to rotate the IRS, the n-th angles refers + // to n-th axis defined in m_rotoAxis (or to BackRotate other points) + std::vector> m_patches; // List of patches }; -} //namespace ns3 +} // namespace ns3 #endif /* IRS_H */ diff --git a/src/main.cc b/src/main.cc index a67518b..6092958 100644 --- a/src/main.cc +++ b/src/main.cc @@ -15,67 +15,64 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -// Standard Library -#include -#include - -// NS3 Core Components #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -// IoD Sim Report Module -#include -// IoD Sim Components +#include #include #include #include #include -#include #include +#include #include #include #include +#include +#include +#include #include +#include #include +#include +#include +#include #include #include #include #include +#include #include +#include #include +#include +#include +#include +#include +#include +#include +#include #include -#include +#include +#include +#include +#include +#include +#include #include #include #include +#include #include #include #include #include -#include -#include -#include -#include -#include -#include -namespace ns3 { +#include +#include + +namespace ns3 +{ constexpr int N_LAYERS = 4; constexpr int PHY_LAYER = 0; @@ -86,144 +83,143 @@ constexpr int PROGRESS_REFRESH_INTERVAL_SECONDS = 1; class Scenario { -public: - Scenario (int argc, char **argv); - virtual ~Scenario (); - - void operator() (); - -private: - void GenerateRadioMap (); - void GenerateThreeDimensionalRem (); - void ApplyStaticConfig (); - void ConfigureWorld (); - void ConfigurePhy (); - void ConfigureMac (); - void ConfigureNetwork (); - void EnableIpv4RoutingTableReporting (); - void ConfigureEntities (const std::string& entityKey, NodeContainer& nodes); - void ConfigureEntityMobility (const std::string& entityKey, - Ptr entityConf, - const uint32_t entityId); - NetDeviceContainer ConfigureEntityWifiStack (std::string entityKey, - Ptr entityNetDev, - Ptr entityNode, - const uint32_t entityId, - const uint32_t deviceId, - const uint32_t netId); - void ConfigureLteEnb (Ptr entityNode, + public: + Scenario(int argc, char** argv); + virtual ~Scenario(); + + void operator()(); + + private: + void GenerateRadioMap(); + void GenerateThreeDimensionalRem(); + void ApplyStaticConfig(); + void ConfigureWorld(); + void ConfigurePhy(); + void ConfigureMac(); + void ConfigureNetwork(); + void EnableIpv4RoutingTableReporting(); + void ConfigureEntities(const std::string& entityKey, NodeContainer& nodes); + void ConfigureEntityMobility(const std::string& entityKey, + Ptr entityConf, + const uint32_t entityId); + NetDeviceContainer ConfigureEntityWifiStack(std::string entityKey, + Ptr entityNetDev, + Ptr entityNode, + const uint32_t entityId, + const uint32_t deviceId, + const uint32_t netId); + void ConfigureLteEnb(Ptr entityNode, + const uint32_t netId, + const std::optional antennaModel, + const std::optional phyConf); + void ConfigureLteUe(Ptr entityNode, + const std::vector bearers, const uint32_t netId, const std::optional antennaModel, const std::optional phyConf); - void ConfigureLteUe (Ptr entityNode, - const std::vector bearers, - const uint32_t netId, - const std::optional antennaModel, - const std::optional phyConf); - void InstallEntityIpv4 (Ptr entityNode, - NetDeviceContainer netDevices, - const uint32_t netId); - void InstallEntityIpv4 (Ptr entityNode, - Ptr netDevice, - const uint32_t netId); - void ConfigureEntityIpv4 (Ptr entityNode, - NetDeviceContainer devContainer, - const uint32_t deviceId, - const uint32_t netId); - void ConfigureEntityApplications (const std::string& entityKey, + void InstallEntityIpv4(Ptr entityNode, + NetDeviceContainer netDevices, + const uint32_t netId); + void InstallEntityIpv4(Ptr entityNode, Ptr netDevice, const uint32_t netId); + void ConfigureEntityIpv4(Ptr entityNode, + NetDeviceContainer devContainer, + const uint32_t deviceId, + const uint32_t netId); + void ConfigureEntityApplications(const std::string& entityKey, + const Ptr& conf, + const uint32_t& entityId); + void ConfigureEntityMechanics(const std::string& entityKey, + Ptr entityConf, + const uint32_t entityId); + Ptr ConfigureEntityBattery(const std::string& entityKey, + Ptr entityConf, + const uint32_t entityId); + void ConfigureEntityPeripherals(const std::string& entityKey, const Ptr& conf, const uint32_t& entityId); - void ConfigureEntityMechanics (const std::string& entityKey, - Ptr entityConf, - const uint32_t entityId); - Ptr ConfigureEntityBattery (const std::string& entityKey, - Ptr entityConf, - const uint32_t entityId); - void ConfigureEntityPeripherals (const std::string& entityKey, - const Ptr& conf, - const uint32_t& entityId); - void ConfigureInternetRemotes (); - void ConfigureInternetBackbone (); - void EnablePhyLteTraces (); - void ConfigureRegionsOfInterest (); - void CourseChange (std::string context, Ptr model); - void ConfigureSimulator (); - - NodeContainer m_plainNodes; - DroneContainer m_drones; - NodeContainer m_zsps; - NodeContainer m_remoteNodes; - NodeContainer m_backbone; - - std::array>, N_LAYERS> m_protocolStacks; + void ConfigureInternetRemotes(); + void ConfigureInternetBackbone(); + void EnablePhyLteTraces(); + void ConfigureRegionsOfInterest(); + void CourseChange(std::string context, Ptr model); + void ConfigureSimulator(); + + NodeContainer m_plainNodes; + DroneContainer m_drones; + NodeContainer m_zsps; + NodeContainer m_remoteNodes; + NodeContainer m_backbone; + + std::array>, N_LAYERS> m_protocolStacks; }; -NS_LOG_COMPONENT_DEFINE ("Scenario"); +NS_LOG_COMPONENT_DEFINE("Scenario"); -Scenario::Scenario (int argc, char **argv) +Scenario::Scenario(int argc, char** argv) { - CONFIGURATOR->Initialize (argc, argv); - m_plainNodes.Create (CONFIGURATOR->GetN ("nodes")); - m_drones.Create (CONFIGURATOR->GetN ("drones")); - m_zsps.Create (CONFIGURATOR->GetN ("ZSPs")); - m_remoteNodes.Create (CONFIGURATOR->GetN ("remotes")); - m_backbone.Add (m_remoteNodes); - - // Register created entities in their lists - for (auto drone = m_drones.Begin (); drone != m_drones.End (); drone++) - DroneList::Add (*drone); - - for (auto zsp = m_zsps.Begin (); zsp != m_zsps.End (); zsp++) - ZspList::Add (*zsp); - - for (auto remote = m_remoteNodes.Begin (); remote != m_remoteNodes.End (); remote++) - RemoteList::Add (*remote); - - ApplyStaticConfig (); - ConfigureWorld (); - ConfigurePhy (); - ConfigureMac (); - ConfigureNetwork (); - ConfigureRegionsOfInterest (); - ConfigureEntities ("nodes", m_plainNodes); - ConfigureEntities ("drones", m_drones); - ConfigureEntities ("ZSPs", m_zsps); - ConfigureInternetBackbone (); - ConfigureInternetRemotes (); - EnablePhyLteTraces (); - - //DebugHelper::ProbeNodes(); - ConfigureSimulator (); + CONFIGURATOR->Initialize(argc, argv); + m_plainNodes.Create(CONFIGURATOR->GetN("nodes")); + m_drones.Create(CONFIGURATOR->GetN("drones")); + m_zsps.Create(CONFIGURATOR->GetN("ZSPs")); + m_remoteNodes.Create(CONFIGURATOR->GetN("remotes")); + m_backbone.Add(m_remoteNodes); + + // Register created entities in their lists + for (auto drone = m_drones.Begin(); drone != m_drones.End(); drone++) + DroneList::Add(*drone); + + for (auto zsp = m_zsps.Begin(); zsp != m_zsps.End(); zsp++) + ZspList::Add(*zsp); + + for (auto remote = m_remoteNodes.Begin(); remote != m_remoteNodes.End(); remote++) + RemoteList::Add(*remote); + + ApplyStaticConfig(); + ConfigureWorld(); + ConfigurePhy(); + ConfigureMac(); + ConfigureNetwork(); + ConfigureRegionsOfInterest(); + ConfigureEntities("nodes", m_plainNodes); + ConfigureEntities("drones", m_drones); + ConfigureEntities("ZSPs", m_zsps); + ConfigureInternetBackbone(); + ConfigureInternetRemotes(); + EnablePhyLteTraces(); + + // DebugHelper::ProbeNodes(); + ConfigureSimulator(); } -Scenario::~Scenario () +Scenario::~Scenario() { } void -Scenario::operator() () +Scenario::operator()() { - NS_LOG_FUNCTION_NOARGS (); - bool anyLte = false; - const auto phyLayerConfs = CONFIGURATOR->GetPhyLayers (); - for (auto &phyLayerConf : phyLayerConfs) + NS_LOG_FUNCTION_NOARGS(); + bool anyLte = false; + const auto phyLayerConfs = CONFIGURATOR->GetPhyLayers(); + for (auto& phyLayerConf : phyLayerConfs) { - if (phyLayerConf->GetType () == "lte") + if (phyLayerConf->GetType() == "lte") { - anyLte = true; + anyLte = true; } } - if (CONFIGURATOR->RadioMap () > 0) + if (CONFIGURATOR->RadioMap() > 0) { - NS_ASSERT_MSG (anyLte, "Environment Radio Map can be generated only if an LTE network is " - "present. Aborting simulation."); - NS_LOG_INFO ("Generating Environment Radio Map, simulation will not run."); - if (CONFIGURATOR->RadioMap () == 2) + NS_ASSERT_MSG(anyLte, + "Environment Radio Map can be generated only if an LTE network is " + "present. Aborting simulation."); + NS_LOG_INFO("Generating Environment Radio Map, simulation will not run."); + if (CONFIGURATOR->RadioMap() == 2) { - this->GenerateThreeDimensionalRem (); - Simulator::Run (); - Simulator::Destroy (); + this->GenerateThreeDimensionalRem(); + Simulator::Run(); + Simulator::Destroy(); int plyRet = system(("python ../analysis/txt2ply.py " + CONFIGURATOR->GetResultsPath() + CONFIGURATOR->GetName() + "-3D-REM.txt") .c_str()); @@ -231,12 +227,12 @@ Scenario::operator() () { NS_ABORT_MSG("Something went wrong while generating the ply file"); } - int plotRet = + int plotRet = system(("python ../analysis/rem-3d-preview.py " + CONFIGURATOR->GetResultsPath() + CONFIGURATOR->GetName() + "-3D-REM.ply") .c_str()); - if (plotRet != 0) - { + if (plotRet != 0) + { NS_ABORT_MSG("Something went wrong while generating the plot"); } } @@ -262,552 +258,582 @@ Scenario::operator() () } } } - else + else { - if (CONFIGURATOR->IsDryRun ()) - return; - - std::stringstream progressLogFilePath; - progressLogFilePath << CONFIGURATOR->GetResultsPath () << "progress.log"; - auto progressLogSink = Create (progressLogFilePath.str (), std::ios::out); - - ShowProgress progressLog {Seconds (PROGRESS_REFRESH_INTERVAL_SECONDS), (*progressLogSink->GetStream ())}; - ShowProgress progressStdout {Seconds (PROGRESS_REFRESH_INTERVAL_SECONDS), std::cout}; - - Simulator::Run (); - if (CONFIGURATOR->GetLogOnFile()) - { - // Report Module needs the simulator context alive to introspect it - Report::Get()->Save(); - } - Simulator::Destroy (); + if (CONFIGURATOR->IsDryRun()) + return; + + std::stringstream progressLogFilePath; + progressLogFilePath << CONFIGURATOR->GetResultsPath() << "progress.log"; + auto progressLogSink = + Create(progressLogFilePath.str(), std::ios::out); + + ShowProgress progressLog{Seconds(PROGRESS_REFRESH_INTERVAL_SECONDS), + (*progressLogSink->GetStream())}; + ShowProgress progressStdout{Seconds(PROGRESS_REFRESH_INTERVAL_SECONDS), std::cout}; + + Simulator::Run(); + if (CONFIGURATOR->GetLogOnFile()) + { + // Report Module needs the simulator context alive to introspect it + Report::Get()->Save(); + } + Simulator::Destroy(); } } void -Scenario::GenerateRadioMap () +Scenario::GenerateRadioMap() { - //Making it static in order for it to be alive when simulation run - static Ptr m_remHelper = CreateObject (); - m_remHelper->SetAttribute ("OutputFile", StringValue (CONFIGURATOR->GetResultsPath () + - CONFIGURATOR->GetName () + "-2D-REM.txt")); - - auto parameters = CONFIGURATOR->GetRadioMapParameters (); - for (auto par : parameters) + // Making it static in order for it to be alive when simulation run + static Ptr m_remHelper = CreateObject(); + m_remHelper->SetAttribute( + "OutputFile", + StringValue(CONFIGURATOR->GetResultsPath() + CONFIGURATOR->GetName() + "-2D-REM.txt")); + + auto parameters = CONFIGURATOR->GetRadioMapParameters(); + for (auto par : parameters) { - m_remHelper->SetAttribute (par.first, StringValue (par.second)); + m_remHelper->SetAttribute(par.first, StringValue(par.second)); } - m_remHelper->Install (); + m_remHelper->Install(); } + void -Scenario::GenerateThreeDimensionalRem () +Scenario::GenerateThreeDimensionalRem() { - //Making it static in order for it to be alive when simulation run - static Ptr m_remHelper = CreateObject (); - m_remHelper->SetAttribute ("OutputFile", StringValue (CONFIGURATOR->GetResultsPath () + - CONFIGURATOR->GetName () + "-3D-REM.txt")); - - auto parameters = CONFIGURATOR->GetRadioMapParameters (); - for (auto par : parameters) + // Making it static in order for it to be alive when simulation run + static Ptr m_remHelper = CreateObject(); + m_remHelper->SetAttribute( + "OutputFile", + StringValue(CONFIGURATOR->GetResultsPath() + CONFIGURATOR->GetName() + "-3D-REM.txt")); + + auto parameters = CONFIGURATOR->GetRadioMapParameters(); + for (auto par : parameters) { - m_remHelper->SetAttribute (par.first, StringValue (par.second)); + m_remHelper->SetAttribute(par.first, StringValue(par.second)); } - m_remHelper->Install (); + m_remHelper->Install(); } void -Scenario::ApplyStaticConfig () +Scenario::ApplyStaticConfig() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - const auto staticConfig = CONFIGURATOR->GetStaticConfig (); - for (auto& param : staticConfig) - Config::SetDefault (param.first, StringValue (param.second)); + const auto staticConfig = CONFIGURATOR->GetStaticConfig(); + for (auto& param : staticConfig) + Config::SetDefault(param.first, StringValue(param.second)); } void -Scenario::ConfigureWorld () +Scenario::ConfigureWorld() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - CONFIGURATOR->GetBuildings (); // buildings created here are automatically added to BuildingsList + CONFIGURATOR->GetBuildings(); // buildings created here are automatically added to BuildingsList } void -Scenario::ConfigurePhy () +Scenario::ConfigurePhy() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - const auto phyLayerConfs = CONFIGURATOR->GetPhyLayers (); + const auto phyLayerConfs = CONFIGURATOR->GetPhyLayers(); - size_t phyId = 0; - for (auto& phyLayerConf : phyLayerConfs) + size_t phyId = 0; + for (auto& phyLayerConf : phyLayerConfs) { - if (phyLayerConf->GetType () == "wifi") + if (phyLayerConf->GetType() == "wifi") { - YansWifiChannelHelper wifiChannel; - const auto wifiConf = StaticCast (phyLayerConf); - const auto wifiSim = CreateObject (); - YansWifiPhyHelper* wifiPhy = wifiSim->GetWifiPhyHelper (); + YansWifiChannelHelper wifiChannel; + const auto wifiConf = + StaticCast(phyLayerConf); + const auto wifiSim = CreateObject(); + YansWifiPhyHelper* wifiPhy = wifiSim->GetWifiPhyHelper(); - wifiSim->GetWifiHelper ()->SetStandard (wifiConf->GetStandard ()); + wifiSim->GetWifiHelper()->SetStandard(wifiConf->GetStandard()); - for (auto& attr : wifiConf->GetAttributes ()) - wifiPhy->Set (attr.name, *attr.value); + for (auto& attr : wifiConf->GetAttributes()) + wifiPhy->Set(attr.name, *attr.value); - // ns-3 supports RadioTap and Prism tracing extensions for 802.11b - wifiPhy->SetPcapDataLinkType (WifiPhyHelper::DLT_IEEE802_11_RADIO); + // ns-3 supports RadioTap and Prism tracing extensions for 802.11b + wifiPhy->SetPcapDataLinkType(WifiPhyHelper::DLT_IEEE802_11_RADIO); - WifiPhyFactoryHelper::SetPropagationDelay (wifiChannel, wifiConf->GetChannelPropagationDelayModel ()); - WifiPhyFactoryHelper::AddPropagationLoss (wifiChannel, wifiConf->GetChannelPropagationLossModel ()); + WifiPhyFactoryHelper::SetPropagationDelay(wifiChannel, + wifiConf->GetChannelPropagationDelayModel()); + WifiPhyFactoryHelper::AddPropagationLoss(wifiChannel, + wifiConf->GetChannelPropagationLossModel()); - wifiPhy->SetChannel (wifiChannel.Create ()); + wifiPhy->SetChannel(wifiChannel.Create()); - m_protocolStacks[PHY_LAYER].push_back (wifiSim); + m_protocolStacks[PHY_LAYER].push_back(wifiSim); } - else if (phyLayerConf->GetType () == "lte") + else if (phyLayerConf->GetType() == "lte") { - auto lteSim = CreateObject (phyId); - auto lteConf = StaticCast (phyLayerConf); - auto lteHelper = lteSim->GetLteHelper(); + auto lteSim = CreateObject(phyId); + auto lteConf = + StaticCast(phyLayerConf); + auto lteHelper = lteSim->GetLteHelper(); - auto pathlossConf = lteConf->GetChannelPropagationLossModel (); - if (pathlossConf) + auto pathlossConf = lteConf->GetChannelPropagationLossModel(); + if (pathlossConf) { - lteHelper->SetAttribute ("PathlossModel", StringValue (pathlossConf->GetName ())); - for (auto& attr : pathlossConf->GetAttributes ()) - lteHelper->SetPathlossModelAttribute (attr.name, *attr.value); + lteHelper->SetAttribute("PathlossModel", StringValue(pathlossConf->GetName())); + for (auto& attr : pathlossConf->GetAttributes()) + lteHelper->SetPathlossModelAttribute(attr.name, *attr.value); } - auto spectrumConf = lteConf->GetChannelSpectrumModel (); - lteHelper->SetSpectrumChannelType (spectrumConf.GetName ()); - for (auto& attr : spectrumConf.GetAttributes ()) - lteHelper->SetSpectrumChannelAttribute (attr.name, *attr.value); + auto spectrumConf = lteConf->GetChannelSpectrumModel(); + lteHelper->SetSpectrumChannelType(spectrumConf.GetName()); + for (auto& attr : spectrumConf.GetAttributes()) + lteHelper->SetSpectrumChannelAttribute(attr.name, *attr.value); - for (auto& attr : lteConf->GetAttributes ()) - lteHelper->SetAttribute (attr.name, *attr.value); + for (auto& attr : lteConf->GetAttributes()) + lteHelper->SetAttribute(attr.name, *attr.value); - lteHelper->Initialize (); + lteHelper->Initialize(); - m_backbone.Add (lteSim->GetEpcHelper ()->GetPgwNode ()); + m_backbone.Add(lteSim->GetEpcHelper()->GetPgwNode()); - m_protocolStacks[PHY_LAYER].push_back (lteSim); + m_protocolStacks[PHY_LAYER].push_back(lteSim); } - else + else { - NS_FATAL_ERROR ("Unsupported PHY Layer Type: " << phyLayerConf->GetType ()); + NS_FATAL_ERROR("Unsupported PHY Layer Type: " << phyLayerConf->GetType()); } - phyId++; + phyId++; } } void -Scenario::ConfigureMac () +Scenario::ConfigureMac() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - const auto macLayerConfs = CONFIGURATOR->GetMacLayers (); + const auto macLayerConfs = CONFIGURATOR->GetMacLayers(); - size_t i = 0; - for (auto& macLayerConf : macLayerConfs) + size_t i = 0; + for (auto& macLayerConf : macLayerConfs) { - if (macLayerConf->GetType () == "wifi") + if (macLayerConf->GetType() == "wifi") { - const auto wifiPhy = StaticCast (m_protocolStacks[PHY_LAYER][i]); - const auto wifiMac = CreateObject (); - const auto wifiConf = StaticCast (macLayerConf); - Ssid ssid = Ssid (wifiConf->GetSsid ()); - - WifiMacFactoryHelper::SetRemoteStationManager (*(wifiPhy->GetWifiHelper ()), - wifiConf->GetRemoteStationManagerConfiguration ()); - - m_protocolStacks[MAC_LAYER].push_back (wifiMac); + const auto wifiPhy = + StaticCast(m_protocolStacks[PHY_LAYER][i]); + const auto wifiMac = CreateObject(); + const auto wifiConf = + StaticCast(macLayerConf); + Ssid ssid = Ssid(wifiConf->GetSsid()); + + WifiMacFactoryHelper::SetRemoteStationManager( + *(wifiPhy->GetWifiHelper()), + wifiConf->GetRemoteStationManagerConfiguration()); + + m_protocolStacks[MAC_LAYER].push_back(wifiMac); } - else if (macLayerConf->GetType () == "lte") + else if (macLayerConf->GetType() == "lte") { - // NO OPERATION NEEDED HERE - m_protocolStacks[MAC_LAYER].push_back (nullptr); + // NO OPERATION NEEDED HERE + m_protocolStacks[MAC_LAYER].push_back(nullptr); } - else + else { - NS_FATAL_ERROR ("Unsupported MAC Layer Type: " << macLayerConf->GetType ()); + NS_FATAL_ERROR("Unsupported MAC Layer Type: " << macLayerConf->GetType()); } - i++; + i++; } } void -Scenario::ConfigureNetwork () +Scenario::ConfigureNetwork() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - const auto layerConfs = CONFIGURATOR->GetNetworkLayers (); - for (auto& layerConf : layerConfs) + const auto layerConfs = CONFIGURATOR->GetNetworkLayers(); + for (auto& layerConf : layerConfs) { - if (layerConf->GetType () == "ipv4") + if (layerConf->GetType() == "ipv4") { - const auto ipv4Conf = StaticCast (layerConf); - const auto ipv4Sim = CreateObject (ipv4Conf->GetMask (), ipv4Conf->GetGatewayAddress ()); + const auto ipv4Conf = + StaticCast(layerConf); + const auto ipv4Sim = CreateObject(ipv4Conf->GetMask(), + ipv4Conf->GetGatewayAddress()); - ipv4Sim->GetIpv4Helper ().SetBase (Ipv4Address (ipv4Conf->GetAddress ().c_str ()), - Ipv4Mask (ipv4Conf->GetMask ().c_str ())); + ipv4Sim->GetIpv4Helper().SetBase(Ipv4Address(ipv4Conf->GetAddress().c_str()), + Ipv4Mask(ipv4Conf->GetMask().c_str())); - if (CONFIGURATOR->GetLogOnFile()) - EnableIpv4RoutingTableReporting (); + if (CONFIGURATOR->GetLogOnFile()) + EnableIpv4RoutingTableReporting(); - m_protocolStacks[NET_LAYER].push_back (ipv4Sim); + m_protocolStacks[NET_LAYER].push_back(ipv4Sim); } - else + else { - NS_FATAL_ERROR ("Unsupported Network Layer Type: " << layerConf->GetType ()); + NS_FATAL_ERROR("Unsupported Network Layer Type: " << layerConf->GetType()); } } } void -Scenario::EnableIpv4RoutingTableReporting () +Scenario::EnableIpv4RoutingTableReporting() { - // this method should be called once - static bool hasBeenCalled = false; - if (hasBeenCalled) - return; - else - hasBeenCalled = true; - - NS_LOG_FUNCTION_NOARGS (); - - std::stringstream routingTableFilePath; - routingTableFilePath << CONFIGURATOR->GetResultsPath () << "ipv4-routing-tables.txt"; - auto routingTableSink = Create (routingTableFilePath.str (), std::ios::out); - Ipv4RoutingHelper::PrintRoutingTableAllAt (Seconds (1.0), routingTableSink); + // this method should be called once + static bool hasBeenCalled = false; + if (hasBeenCalled) + return; + else + hasBeenCalled = true; + + NS_LOG_FUNCTION_NOARGS(); + + std::stringstream routingTableFilePath; + routingTableFilePath << CONFIGURATOR->GetResultsPath() << "ipv4-routing-tables.txt"; + auto routingTableSink = Create(routingTableFilePath.str(), std::ios::out); + Ipv4RoutingHelper::PrintRoutingTableAllAt(Seconds(1.0), routingTableSink); } void -Scenario::ConfigureEntities (const std::string& entityKey, NodeContainer& nodes) +Scenario::ConfigureEntities(const std::string& entityKey, NodeContainer& nodes) { - NS_LOG_FUNCTION (entityKey); - - const auto entityConfs = CONFIGURATOR->GetEntitiesConfiguration (entityKey); - size_t entityId = 0; - - for (auto& entityConf : entityConfs) { - size_t deviceId = 0; - - auto entityNode = nodes.Get (entityId); - ConfigureEntityMobility (entityKey, entityConf, entityId); - - for (auto& entityNetDev : entityConf->GetNetDevices ()) - { - const auto netId = entityNetDev->GetNetworkLayerId (); - - if (entityNetDev->GetType () == "wifi") - { - auto devContainer = ConfigureEntityWifiStack (entityKey, entityNetDev, entityNode, entityId, deviceId, netId); - InstallEntityIpv4 (entityNode, devContainer, netId); - ConfigureEntityIpv4 (entityNode, devContainer, deviceId, netId); - } - else if (entityNetDev->GetType () == "lte") - { - const auto entityLteDevConf = StaticCast (entityNetDev); - const auto role = entityLteDevConf->GetRole (); - const auto antennaModel = entityLteDevConf->GetAntennaModel (); - const auto phyConf = entityLteDevConf->GetPhyModel (); - - switch (role) - { - case eNB: - ConfigureLteEnb (entityNode, netId, antennaModel, phyConf); - break; - case UE: - ConfigureLteUe (entityNode, entityLteDevConf->GetBearers (), - netId, antennaModel, phyConf); - break; - default: - NS_FATAL_ERROR ("Unrecognized LTE role for entity ID " << entityId); - } - } - else - { - NS_FATAL_ERROR ("Unsupported Drone Network Device Type: " << entityNetDev->GetType ()); - } + NS_LOG_FUNCTION(entityKey); + + const auto entityConfs = CONFIGURATOR->GetEntitiesConfiguration(entityKey); + size_t entityId = 0; - deviceId++; - } + for (auto& entityConf : entityConfs) + { + size_t deviceId = 0; - ConfigureEntityApplications (entityKey, entityConf, entityId); + auto entityNode = nodes.Get(entityId); + ConfigureEntityMobility(entityKey, entityConf, entityId); - if (entityKey == "drones") + for (auto& entityNetDev : entityConf->GetNetDevices()) { - DroneEnergyModelHelper energyModel; - Ptr energySource; - - ConfigureEntityMechanics (entityKey, entityConf, entityId); - energySource = ConfigureEntityBattery (entityKey, entityConf, entityId); - /// Installing Energy Model on Drone - energyModel.Install (StaticCast (entityNode), energySource); - ConfigureEntityPeripherals (entityKey, entityConf, entityId); + const auto netId = entityNetDev->GetNetworkLayerId(); + + if (entityNetDev->GetType() == "wifi") + { + auto devContainer = ConfigureEntityWifiStack(entityKey, + entityNetDev, + entityNode, + entityId, + deviceId, + netId); + InstallEntityIpv4(entityNode, devContainer, netId); + ConfigureEntityIpv4(entityNode, devContainer, deviceId, netId); + } + else if (entityNetDev->GetType() == "lte") + { + const auto entityLteDevConf = + StaticCast(entityNetDev); + const auto role = entityLteDevConf->GetRole(); + const auto antennaModel = entityLteDevConf->GetAntennaModel(); + const auto phyConf = entityLteDevConf->GetPhyModel(); + + switch (role) + { + case eNB: + ConfigureLteEnb(entityNode, netId, antennaModel, phyConf); + break; + case UE: + ConfigureLteUe(entityNode, + entityLteDevConf->GetBearers(), + netId, + antennaModel, + phyConf); + break; + default: + NS_FATAL_ERROR("Unrecognized LTE role for entity ID " << entityId); + } + } + else + { + NS_FATAL_ERROR( + "Unsupported Drone Network Device Type: " << entityNetDev->GetType()); + } + + deviceId++; } - entityId++; - } + ConfigureEntityApplications(entityKey, entityConf, entityId); - BuildingsHelper::Install (nodes); + if (entityKey == "drones") + { + DroneEnergyModelHelper energyModel; + Ptr energySource; + + ConfigureEntityMechanics(entityKey, entityConf, entityId); + energySource = ConfigureEntityBattery(entityKey, entityConf, entityId); + /// Installing Energy Model on Drone + energyModel.Install(StaticCast(entityNode), energySource); + ConfigureEntityPeripherals(entityKey, entityConf, entityId); + } + + entityId++; + } + + BuildingsHelper::Install(nodes); } void -Scenario::ConfigureEntityMobility (const std::string& entityKey, - Ptr entityConf, - const uint32_t entityId) +Scenario::ConfigureEntityMobility(const std::string& entityKey, + Ptr entityConf, + const uint32_t entityId) { - NS_LOG_FUNCTION (entityKey << entityConf << entityId); + NS_LOG_FUNCTION(entityKey << entityConf << entityId); - MobilityHelper mobility; - const auto mobilityConf = entityConf->GetMobilityModel (); - const auto mobilityType = mobilityConf.GetName (); // Configure Entity Mobility - MobilityFactoryHelper::SetMobilityModel (mobility, mobilityConf); + MobilityHelper mobility; + const auto mobilityConf = entityConf->GetMobilityModel(); + const auto mobilityType = mobilityConf.GetName(); // Configure Entity Mobility + MobilityFactoryHelper::SetMobilityModel(mobility, mobilityConf); - if (entityKey == "drones") + if (entityKey == "drones") { - mobility.Install (m_drones.Get (entityId)); - std::ostringstream oss; - oss << - "/NodeList/" << m_drones.Get (entityId)->GetId () << - "/$ns3::MobilityModel/CourseChange"; - Config::Connect (oss.str (), MakeCallback (&Scenario::CourseChange,this)); + mobility.Install(m_drones.Get(entityId)); + std::ostringstream oss; + oss << "/NodeList/" << m_drones.Get(entityId)->GetId() + << "/$ns3::MobilityModel/CourseChange"; + Config::Connect(oss.str(), MakeCallback(&Scenario::CourseChange, this)); } - else if (entityKey == "ZSPs") + else if (entityKey == "ZSPs") { - mobility.Install (m_zsps.Get (entityId)); + mobility.Install(m_zsps.Get(entityId)); } - else if (entityKey == "nodes") + else if (entityKey == "nodes") { - mobility.Install (m_plainNodes.Get (entityId)); + mobility.Install(m_plainNodes.Get(entityId)); } } NetDeviceContainer -Scenario::ConfigureEntityWifiStack (const std::string entityKey, - Ptr entityNetDev, - Ptr entityNode, - const uint32_t entityId, - const uint32_t deviceId, - const uint32_t netId) +Scenario::ConfigureEntityWifiStack(const std::string entityKey, + Ptr entityNetDev, + Ptr entityNode, + const uint32_t entityId, + const uint32_t deviceId, + const uint32_t netId) { - NS_LOG_FUNCTION (entityNetDev << entityNode << entityId << deviceId << netId); - - auto wifiPhy = StaticCast (m_protocolStacks[PHY_LAYER][netId]); - auto wifiMac = StaticCast (m_protocolStacks[MAC_LAYER][netId]); - auto wifiNetDev = StaticCast (entityNetDev); - auto wifiMacAttrs = wifiNetDev->GetMacLayer ().GetAttributes (); - - if (wifiMacAttrs.size () == 0) - wifiMac->GetMacHelper ().SetType (wifiNetDev->GetMacLayer ().GetName ()); - else if (wifiMacAttrs.size () == 1) - wifiMac->GetMacHelper ().SetType (wifiNetDev->GetMacLayer ().GetName (), - wifiMacAttrs[0].name, - *wifiMacAttrs[0].value); - - NetDeviceContainer devContainer = wifiPhy->GetWifiHelper ()->Install (*wifiPhy->GetWifiPhyHelper (), - wifiMac->GetMacHelper (), - entityNode); - - if (CONFIGURATOR->GetLogOnFile()) - { - // Configure WiFi PHY Logging - std::stringstream phyTraceLog; - std::stringstream pcapLog; - AsciiTraceHelper ascii; - - // Configure WiFi TXT PHY Logging - phyTraceLog << CONFIGURATOR->GetResultsPath() << "wifi-phy-" << netId << "-" << entityKey - << "-host-" << entityId << "-" << deviceId << ".log"; - wifiPhy->GetWifiPhyHelper()->EnableAscii(ascii.CreateFileStream(phyTraceLog.str()), - entityNode->GetId(), - devContainer.Get(0)->GetIfIndex()); - - // Configure WiFi PCAP Logging - pcapLog << CONFIGURATOR->GetResultsPath() << "wifi-phy-" << netId << "-" << entityKey - << "-host"; - wifiPhy->GetWifiPhyHelper()->EnablePcap(pcapLog.str(), - entityNode->GetId(), - devContainer.Get(0)->GetIfIndex()); - } - - return devContainer; + NS_LOG_FUNCTION(entityNetDev << entityNode << entityId << deviceId << netId); + + auto wifiPhy = StaticCast(m_protocolStacks[PHY_LAYER][netId]); + auto wifiMac = StaticCast(m_protocolStacks[MAC_LAYER][netId]); + auto wifiNetDev = StaticCast(entityNetDev); + auto wifiMacAttrs = wifiNetDev->GetMacLayer().GetAttributes(); + + if (wifiMacAttrs.size() == 0) + wifiMac->GetMacHelper().SetType(wifiNetDev->GetMacLayer().GetName()); + else if (wifiMacAttrs.size() == 1) + wifiMac->GetMacHelper().SetType(wifiNetDev->GetMacLayer().GetName(), + wifiMacAttrs[0].name, + *wifiMacAttrs[0].value); + + NetDeviceContainer devContainer = + wifiPhy->GetWifiHelper()->Install(*wifiPhy->GetWifiPhyHelper(), + wifiMac->GetMacHelper(), + entityNode); + + if (CONFIGURATOR->GetLogOnFile()) + { + // Configure WiFi PHY Logging + std::stringstream phyTraceLog; + std::stringstream pcapLog; + AsciiTraceHelper ascii; + + // Configure WiFi TXT PHY Logging + phyTraceLog << CONFIGURATOR->GetResultsPath() << "wifi-phy-" << netId << "-" << entityKey + << "-host-" << entityId << "-" << deviceId << ".log"; + wifiPhy->GetWifiPhyHelper()->EnableAscii(ascii.CreateFileStream(phyTraceLog.str()), + entityNode->GetId(), + devContainer.Get(0)->GetIfIndex()); + + // Configure WiFi PCAP Logging + pcapLog << CONFIGURATOR->GetResultsPath() << "wifi-phy-" << netId << "-" << entityKey + << "-host"; + wifiPhy->GetWifiPhyHelper()->EnablePcap(pcapLog.str(), + entityNode->GetId(), + devContainer.Get(0)->GetIfIndex()); + } + + return devContainer; } void -Scenario::ConfigureLteEnb (Ptr entityNode, - const uint32_t netId, - const std::optional antennaModel, - const std::optional phyConf) +Scenario::ConfigureLteEnb(Ptr entityNode, + const uint32_t netId, + const std::optional antennaModel, + const std::optional phyConf) { - // !NOTICE: no checks are made for backbone/netid combination that do not represent an LTE backbone! - static std::vector backbonePerStack (m_protocolStacks[PHY_LAYER].size ()); - auto ltePhy = StaticCast (m_protocolStacks[PHY_LAYER][netId]); - auto lteHelper = ltePhy->GetLteHelper (); + // !NOTICE: no checks are made for backbone/netid combination that do not represent an LTE + // backbone! + static std::vector backbonePerStack(m_protocolStacks[PHY_LAYER].size()); + auto ltePhy = StaticCast(m_protocolStacks[PHY_LAYER][netId]); + auto lteHelper = ltePhy->GetLteHelper(); - if (antennaModel) + if (antennaModel) { - lteHelper->SetEnbAntennaModelType (antennaModel->GetName ()); - for (auto& attr : antennaModel->GetAttributes ()) - lteHelper->SetEnbAntennaModelAttribute (attr.name, *attr.value); + lteHelper->SetEnbAntennaModelType(antennaModel->GetName()); + for (auto& attr : antennaModel->GetAttributes()) + lteHelper->SetEnbAntennaModelAttribute(attr.name, *attr.value); } - auto dev = StaticCast - (LteSetupHelper::InstallSingleEnbDevice(lteHelper, entityNode)); + auto dev = StaticCast( + LteSetupHelper::InstallSingleEnbDevice(lteHelper, entityNode)); - if (phyConf) - for (const auto& attr : phyConf->GetAttributes ()) - dev->GetPhy ()->SetAttribute (attr.name, *attr.value); + if (phyConf) + for (const auto& attr : phyConf->GetAttributes()) + dev->GetPhy()->SetAttribute(attr.name, *attr.value); - for (NodeContainer::Iterator eNB = backbonePerStack[netId].Begin (); eNB != backbonePerStack[netId].End (); eNB++) - ltePhy->GetLteHelper ()->AddX2Interface (entityNode, *eNB); - backbonePerStack[netId].Add (entityNode); + for (NodeContainer::Iterator eNB = backbonePerStack[netId].Begin(); + eNB != backbonePerStack[netId].End(); + eNB++) + ltePhy->GetLteHelper()->AddX2Interface(entityNode, *eNB); + backbonePerStack[netId].Add(entityNode); } void -Scenario::ConfigureLteUe (Ptr entityNode, - const std::vector bearers, - const uint32_t netId, - const std::optional antennaModel, - const std::optional phyConf) +Scenario::ConfigureLteUe(Ptr entityNode, + const std::vector bearers, + const uint32_t netId, + const std::optional antennaModel, + const std::optional phyConf) { - // NOTICE: no checks are made for ue/netid combination that do not represent an LTE backbone! - static std::vector uePerStack (m_protocolStacks[PHY_LAYER].size ()); - auto ltePhy = StaticCast (m_protocolStacks[PHY_LAYER][netId]); - auto lteHelper = ltePhy->GetLteHelper (); - Ipv4StaticRoutingHelper routingHelper; + // NOTICE: no checks are made for ue/netid combination that do not represent an LTE backbone! + static std::vector uePerStack(m_protocolStacks[PHY_LAYER].size()); + auto ltePhy = StaticCast(m_protocolStacks[PHY_LAYER][netId]); + auto lteHelper = ltePhy->GetLteHelper(); + Ipv4StaticRoutingHelper routingHelper; - if (antennaModel) + if (antennaModel) { - lteHelper->SetUeAntennaModelType (antennaModel->GetName ()); - for (auto& attr : antennaModel->GetAttributes ()) - lteHelper->SetUeAntennaModelAttribute (attr.name, *attr.value); + lteHelper->SetUeAntennaModelType(antennaModel->GetName()); + for (auto& attr : antennaModel->GetAttributes()) + lteHelper->SetUeAntennaModelAttribute(attr.name, *attr.value); } - auto dev = StaticCast - (LteSetupHelper::InstallSingleUeDevice (lteHelper, entityNode)); + auto dev = StaticCast( + LteSetupHelper::InstallSingleUeDevice(lteHelper, entityNode)); - if (phyConf) - for (const auto& attr : phyConf->GetAttributes ()) - dev->GetPhy ()->SetAttribute (attr.name, *attr.value); + if (phyConf) + for (const auto& attr : phyConf->GetAttributes()) + dev->GetPhy()->SetAttribute(attr.name, *attr.value); - // Install network layer in order to proceed with IPv4 LTE configuration - InstallEntityIpv4 (entityNode, dev, netId); - // Register UEs into network 7.0.0.0/8 - // unfortunately this is hardwired into EpcHelper implementation + // Install network layer in order to proceed with IPv4 LTE configuration + InstallEntityIpv4(entityNode, dev, netId); + // Register UEs into network 7.0.0.0/8 + // unfortunately this is hardwired into EpcHelper implementation - auto assignedIpAddrs = ltePhy->GetEpcHelper ()->AssignUeIpv4Address (NetDeviceContainer (dev)); - for (auto assignedIpIter = assignedIpAddrs.Begin (); assignedIpIter != assignedIpAddrs.End (); assignedIpIter++) + auto assignedIpAddrs = ltePhy->GetEpcHelper()->AssignUeIpv4Address(NetDeviceContainer(dev)); + for (auto assignedIpIter = assignedIpAddrs.Begin(); assignedIpIter != assignedIpAddrs.End(); + assignedIpIter++) { - NS_LOG_LOGIC ("Assigned IPv4 Address to UE with Node ID " << entityNode->GetId () << ":" - << " Iface " << assignedIpIter->second); + NS_LOG_LOGIC("Assigned IPv4 Address to UE with Node ID " << entityNode->GetId() << ":" + << " Iface " + << assignedIpIter->second); - for (uint32_t i = 0; i < assignedIpIter->first->GetNAddresses (assignedIpIter->second); i++) + for (uint32_t i = 0; i < assignedIpIter->first->GetNAddresses(assignedIpIter->second); i++) { - NS_LOG_LOGIC (" Addr " << assignedIpIter->first->GetAddress (assignedIpIter->second, i)); + NS_LOG_LOGIC(" Addr " << assignedIpIter->first->GetAddress(assignedIpIter->second, i)); } } - // create a static route for each UE to the SGW/PGW in order to communicate - // with the internet - auto nodeIpv4 = entityNode->GetObject (); - Ptr ueStaticRoute = routingHelper.GetStaticRouting (nodeIpv4); - ueStaticRoute->SetDefaultRoute (ltePhy->GetEpcHelper ()->GetUeDefaultGatewayAddress (), - nodeIpv4->GetInterfaceForDevice(dev)); - // auto attach each drone UE to the eNB with the strongest signal - ltePhy->GetLteHelper ()->Attach (dev); - // init bearers on UE - for (auto& bearerConf : bearers) + // create a static route for each UE to the SGW/PGW in order to communicate + // with the internet + auto nodeIpv4 = entityNode->GetObject(); + Ptr ueStaticRoute = routingHelper.GetStaticRouting(nodeIpv4); + ueStaticRoute->SetDefaultRoute(ltePhy->GetEpcHelper()->GetUeDefaultGatewayAddress(), + nodeIpv4->GetInterfaceForDevice(dev)); + // auto attach each drone UE to the eNB with the strongest signal + ltePhy->GetLteHelper()->Attach(dev); + // init bearers on UE + for (auto& bearerConf : bearers) { - EpsBearer bearer (bearerConf.GetType (), bearerConf.GetQos ()); - ltePhy->GetLteHelper ()->ActivateDedicatedEpsBearer (dev, bearer, EpcTft::Default ()); + EpsBearer bearer(bearerConf.GetType(), bearerConf.GetQos()); + ltePhy->GetLteHelper()->ActivateDedicatedEpsBearer(dev, bearer, EpcTft::Default()); } } void -Scenario::InstallEntityIpv4 (Ptr entityNode, - NetDeviceContainer netDevices, - const uint32_t netId) +Scenario::InstallEntityIpv4(Ptr entityNode, + NetDeviceContainer netDevices, + const uint32_t netId) { - NS_LOG_FUNCTION (entityNode << netId); + NS_LOG_FUNCTION(entityNode << netId); - for (NetDeviceContainer::Iterator i = netDevices.Begin (); i != netDevices.End (); i++) - InstallEntityIpv4 (entityNode, *i, netId); + for (NetDeviceContainer::Iterator i = netDevices.Begin(); i != netDevices.End(); i++) + InstallEntityIpv4(entityNode, *i, netId); } void -Scenario::InstallEntityIpv4 (Ptr entityNode, - Ptr netDevice, - const uint32_t netId) +Scenario::InstallEntityIpv4(Ptr entityNode, Ptr netDevice, const uint32_t netId) { - NS_LOG_FUNCTION (entityNode << netId); + NS_LOG_FUNCTION(entityNode << netId); - auto ipv4Obj = entityNode->GetObject (); + auto ipv4Obj = entityNode->GetObject(); - if (ipv4Obj == nullptr) + if (ipv4Obj == nullptr) { - auto netLayer = StaticCast (m_protocolStacks[NET_LAYER][netId]); - netLayer->GetInternetHelper ().Install (entityNode); + auto netLayer = + StaticCast(m_protocolStacks[NET_LAYER][netId]); + netLayer->GetInternetHelper().Install(entityNode); } - else + else { - ipv4Obj->AddInterface (netDevice); + ipv4Obj->AddInterface(netDevice); } } void -Scenario::ConfigureEntityIpv4 (Ptr entityNode, - NetDeviceContainer devContainer, - const uint32_t deviceId, - const uint32_t netId) +Scenario::ConfigureEntityIpv4(Ptr entityNode, + NetDeviceContainer devContainer, + const uint32_t deviceId, + const uint32_t netId) { - NS_LOG_FUNCTION (entityNode << deviceId << netId); - NS_ASSERT_MSG (1 == devContainer.GetN (), - "ConfigureEntityIpv4 assumes to receive a NetDeviceContainer with only one NetDevice, but there are " - << devContainer.GetN ()); - - auto netLayer = StaticCast (m_protocolStacks[NET_LAYER][netId]); - auto assignedIPs = netLayer->GetIpv4Helper ().Assign (devContainer); - - Ipv4StaticRoutingHelper routingHelper; - auto deviceIP = assignedIPs.Get(0); - Ptr ueStaticRoute = routingHelper.GetStaticRouting (deviceIP.first); - - const Ipv4Address nodeAddr = assignedIPs.GetAddress(0, 0); - if (nodeAddr != netLayer->GetGatewayAddress ()) - ueStaticRoute->SetDefaultRoute (netLayer->GetGatewayAddress (), deviceIP.second); + NS_LOG_FUNCTION(entityNode << deviceId << netId); + NS_ASSERT_MSG(1 == devContainer.GetN(), + "ConfigureEntityIpv4 assumes to receive a NetDeviceContainer with only one " + "NetDevice, but there are " + << devContainer.GetN()); + + auto netLayer = StaticCast(m_protocolStacks[NET_LAYER][netId]); + auto assignedIPs = netLayer->GetIpv4Helper().Assign(devContainer); + + Ipv4StaticRoutingHelper routingHelper; + auto deviceIP = assignedIPs.Get(0); + Ptr ueStaticRoute = routingHelper.GetStaticRouting(deviceIP.first); + + const Ipv4Address nodeAddr = assignedIPs.GetAddress(0, 0); + if (nodeAddr != netLayer->GetGatewayAddress()) + ueStaticRoute->SetDefaultRoute(netLayer->GetGatewayAddress(), deviceIP.second); } void -Scenario::ConfigureEntityApplications (const std::string& entityKey, - const Ptr& conf, - const uint32_t& entityId) +Scenario::ConfigureEntityApplications(const std::string& entityKey, + const Ptr& conf, + const uint32_t& entityId) { - NS_LOG_FUNCTION (entityKey << conf << entityId); + NS_LOG_FUNCTION(entityKey << conf << entityId); - for (auto appConf : conf->GetApplications ()) + for (auto appConf : conf->GetApplications()) { - ObjectFactory f {appConf.GetName ()}; + ObjectFactory f{appConf.GetName()}; - for (auto attr : appConf.GetAttributes ()) - f.Set (attr.name, *attr.value); + for (auto attr : appConf.GetAttributes()) + f.Set(attr.name, *attr.value); - auto app = StaticCast (f.Create ()); + auto app = StaticCast(f.Create()); - if (entityKey == "drones") - m_drones.Get (entityId)->AddApplication (app); - else if (entityKey == "ZSPs") - m_zsps.Get (entityId)->AddApplication (app); - else if (entityKey == "nodes") - m_plainNodes.Get (entityId)->AddApplication (app); - else - NS_FATAL_ERROR ("Unsupported Entity Type " << entityKey); + if (entityKey == "drones") + m_drones.Get(entityId)->AddApplication(app); + else if (entityKey == "ZSPs") + m_zsps.Get(entityId)->AddApplication(app); + else if (entityKey == "nodes") + m_plainNodes.Get(entityId)->AddApplication(app); + else + NS_FATAL_ERROR("Unsupported Entity Type " << entityKey); } } @@ -816,10 +842,10 @@ Scenario::ConfigureEntityMechanics(const std::string& entityKey, Ptr entityConf, const uint32_t entityId) { - NS_LOG_FUNCTION_NOARGS(); - const auto mechanics = entityConf->GetMechanics(); - for (auto attr : mechanics.GetAttributes ()) - m_drones.Get(entityId)->SetAttribute (attr.name, *attr.value); + NS_LOG_FUNCTION_NOARGS(); + const auto mechanics = entityConf->GetMechanics(); + for (auto attr : mechanics.GetAttributes()) + m_drones.Get(entityId)->SetAttribute(attr.name, *attr.value); } Ptr @@ -827,144 +853,153 @@ Scenario::ConfigureEntityBattery(const std::string& entityKey, Ptr entityConf, const uint32_t entityId) { - NS_LOG_FUNCTION_NOARGS(); - const auto battery = entityConf->GetBattery(); - ObjectFactory batteryFactory; - batteryFactory.SetTypeId(entityConf->GetBattery().GetName()); - - for (auto attr : battery.GetAttributes ()) - batteryFactory.Set(attr.name, *attr.value); - auto mountedBattery = batteryFactory.Create(); - - mountedBattery->SetNode(m_drones.Get(entityId)); - m_drones.Get(entityId)->AggregateObject(mountedBattery); - return mountedBattery; + NS_LOG_FUNCTION_NOARGS(); + const auto battery = entityConf->GetBattery(); + ObjectFactory batteryFactory; + batteryFactory.SetTypeId(entityConf->GetBattery().GetName()); + + for (auto attr : battery.GetAttributes()) + batteryFactory.Set(attr.name, *attr.value); + auto mountedBattery = batteryFactory.Create(); + + mountedBattery->SetNode(m_drones.Get(entityId)); + m_drones.Get(entityId)->AggregateObject(mountedBattery); + return mountedBattery; } void -Scenario::ConfigureEntityPeripherals (const std::string& entityKey, - const Ptr& conf, - const uint32_t& entityId) +Scenario::ConfigureEntityPeripherals(const std::string& entityKey, + const Ptr& conf, + const uint32_t& entityId) { - NS_LOG_FUNCTION (entityKey << entityId << conf); - auto dronePeripheralsContainer = m_drones.Get (entityId)->getPeripherals (); + NS_LOG_FUNCTION(entityKey << entityId << conf); + auto dronePeripheralsContainer = m_drones.Get(entityId)->getPeripherals(); - if (conf->GetPeripherals ().size () == 0) - return; + if (conf->GetPeripherals().size() == 0) + return; - ObjectFactory factory; + ObjectFactory factory; - for (auto perConf : conf->GetPeripherals ()) + for (auto perConf : conf->GetPeripherals()) { - NS_LOG_INFO ("Configuring peripheral " << perConf.GetName ()); - dronePeripheralsContainer->Add (perConf.GetName ()); - for (auto attr : perConf.GetAttributes ()) - dronePeripheralsContainer->Set (attr.name, *attr.value); + NS_LOG_INFO("Configuring peripheral " << perConf.GetName()); + dronePeripheralsContainer->Add(perConf.GetName()); + for (auto attr : perConf.GetAttributes()) + dronePeripheralsContainer->Set(attr.name, *attr.value); - NS_LOG_INFO ("Peripheral configured"); - auto peripheral = dronePeripheralsContainer->Create (); + NS_LOG_INFO("Peripheral configured"); + auto peripheral = dronePeripheralsContainer->Create(); - for (auto aggIt = perConf.AggregatesBegin (); aggIt != perConf.AggregatesEnd (); aggIt++) + for (auto aggIt = perConf.AggregatesBegin(); aggIt != perConf.AggregatesEnd(); aggIt++) { - NS_LOG_INFO ("Aggregating " << aggIt->GetName () << " to " << peripheral->GetTypeId ().GetName ()); - factory = ObjectFactory {aggIt->GetName ()}; + NS_LOG_INFO("Aggregating " << aggIt->GetName() << " to " + << peripheral->GetTypeId().GetName()); + factory = ObjectFactory{aggIt->GetName()}; - for (auto attr : aggIt->GetAttributes ()) - factory.Set (attr.name, *attr.value); + for (auto attr : aggIt->GetAttributes()) + factory.Set(attr.name, *attr.value); - auto aggObject = factory.Create (); - peripheral->AggregateObject (aggObject); + auto aggObject = factory.Create(); + peripheral->AggregateObject(aggObject); } - peripheral->Initialize (); + peripheral->Initialize(); - for (uint32_t i = 0; i < (uint32_t) peripheral->GetNRoI (); i++) + for (uint32_t i = 0; i < (uint32_t)peripheral->GetNRoI(); i++) { - auto reg = irc->GetRoI (i); - if (!irc->GetRoI (i)) - NS_FATAL_ERROR ("Region of Interest #" << i << " does not exist."); + auto reg = irc->GetRoI(i); + if (!irc->GetRoI(i)) + NS_FATAL_ERROR("Region of Interest #" << i << " does not exist."); } } - dronePeripheralsContainer->InstallAll (m_drones.Get (entityId)); + dronePeripheralsContainer->InstallAll(m_drones.Get(entityId)); } void -Scenario::ConfigureInternetRemotes () +Scenario::ConfigureInternetRemotes() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - const auto remoteConfs = CONFIGURATOR->GetRemotesConfiguration (); - size_t remoteId = 0; + const auto remoteConfs = CONFIGURATOR->GetRemotesConfiguration(); + size_t remoteId = 0; - for (auto& conf : remoteConfs) + for (auto& conf : remoteConfs) { - const auto appConfs = conf->GetApplications (); + const auto appConfs = conf->GetApplications(); - for (auto& appConf : appConfs) + for (auto& appConf : appConfs) { - TypeId appTid; - NS_ASSERT_MSG (TypeId::LookupByNameFailSafe (appConf.GetName (), &appTid), - "Failed to initialize application " << appConf.GetName () << ". It does not exist!"); + TypeId appTid; + NS_ASSERT_MSG(TypeId::LookupByNameFailSafe(appConf.GetName(), &appTid), + "Failed to initialize application " << appConf.GetName() + << ". It does not exist!"); - ObjectFactory factory (appTid.GetName ()); + ObjectFactory factory(appTid.GetName()); - for (auto& appAttr : appConf.GetAttributes ()) - factory.Set (appAttr.name, *appAttr.value); + for (auto& appAttr : appConf.GetAttributes()) + factory.Set(appAttr.name, *appAttr.value); - auto app = StaticCast (factory.Create ()); - m_remoteNodes.Get (remoteId)->AddApplication (app); + auto app = StaticCast(factory.Create()); + m_remoteNodes.Get(remoteId)->AddApplication(app); } - remoteId++; + remoteId++; } } void -Scenario::ConfigureInternetBackbone () +Scenario::ConfigureInternetBackbone() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - InternetStackHelper internetHelper; - Ipv4StaticRoutingHelper routingHelper; + InternetStackHelper internetHelper; + Ipv4StaticRoutingHelper routingHelper; - internetHelper.Install (m_remoteNodes); + internetHelper.Install(m_remoteNodes); - // setup a CSMA LAN between all the remotes and network gateways in the backbone - CsmaHelper csma; - NetDeviceContainer backboneDevs = csma.Install (m_backbone); + // setup a CSMA LAN between all the remotes and network gateways in the backbone + CsmaHelper csma; + NetDeviceContainer backboneDevs = csma.Install(m_backbone); - // set a new address base for the backbone - Ipv4AddressHelper ipv4H; - ipv4H.SetBase (Ipv4Address ("200.0.0.0"), Ipv4Mask ("255.0.0.0")); - ipv4H.Assign (backboneDevs); + // set a new address base for the backbone + Ipv4AddressHelper ipv4H; + ipv4H.SetBase(Ipv4Address("200.0.0.0"), Ipv4Mask("255.0.0.0")); + ipv4H.Assign(backboneDevs); - //Ipv4GlobalRoutingHelper::PopulateRoutingTables (); + // Ipv4GlobalRoutingHelper::PopulateRoutingTables (); - // create static routes between each remote node to each network gateway - internetHelper.SetRoutingHelper (routingHelper); + // create static routes between each remote node to each network gateway + internetHelper.SetRoutingHelper(routingHelper); - for (uint32_t i = 0; i < m_remoteNodes.GetN (); i++) + for (uint32_t i = 0; i < m_remoteNodes.GetN(); i++) { - Ptr remoteNode = m_backbone.Get (i); - for (uint32_t j = m_remoteNodes.GetN (); j < m_backbone.GetN (); j++) + Ptr remoteNode = m_backbone.Get(i); + for (uint32_t j = m_remoteNodes.GetN(); j < m_backbone.GetN(); j++) { - Ptr netGwNode = m_backbone.Get (j); - uint32_t netGwBackboneDevIndex = netGwNode->GetNDevices () - 1; - - // since network gateway have at least 2 ipv4 addresses (one in the network and the other for the backbone) - // we should create a route to the internal ip using the backbone ip as next hop - Ipv4Address netGwBackboneIpv4 = netGwNode->GetObject () - ->GetAddress (netGwBackboneDevIndex, 0).GetLocal (); - Ipv4Address netGwInternalIpv4 = netGwNode->GetObject () - ->GetAddress (1, 0).GetLocal (); - - NS_LOG_LOGIC ("Setting-up static route: REMOTE " << i << " " - << "(" << remoteNode->GetObject ()->GetAddress (1, 0).GetLocal () << ") " - << "-> NETWORK " << j - m_remoteNodes.GetN () << " " - << "(" << netGwBackboneIpv4 << " -> " << netGwInternalIpv4 << ")"); - - Ptr staticRouteRem = routingHelper.GetStaticRouting (remoteNode->GetObject ()); - staticRouteRem->AddNetworkRouteTo (netGwInternalIpv4, Ipv4Mask ("255.0.0.0"), netGwBackboneIpv4, 1); + Ptr netGwNode = m_backbone.Get(j); + uint32_t netGwBackboneDevIndex = netGwNode->GetNDevices() - 1; + + // since network gateway have at least 2 ipv4 addresses (one in the network and the + // other for the backbone) we should create a route to the internal ip using the + // backbone ip as next hop + Ipv4Address netGwBackboneIpv4 = + netGwNode->GetObject()->GetAddress(netGwBackboneDevIndex, 0).GetLocal(); + Ipv4Address netGwInternalIpv4 = + netGwNode->GetObject()->GetAddress(1, 0).GetLocal(); + + NS_LOG_LOGIC("Setting-up static route: REMOTE " + << i << " " + << "(" << remoteNode->GetObject()->GetAddress(1, 0).GetLocal() + << ") " + << "-> NETWORK " << j - m_remoteNodes.GetN() << " " + << "(" << netGwBackboneIpv4 << " -> " << netGwInternalIpv4 << ")"); + + Ptr staticRouteRem = + routingHelper.GetStaticRouting(remoteNode->GetObject()); + staticRouteRem->AddNetworkRouteTo(netGwInternalIpv4, + Ipv4Mask("255.0.0.0"), + netGwBackboneIpv4, + 1); } } @@ -980,145 +1015,153 @@ Scenario::ConfigureInternetBackbone () } void -Scenario::EnablePhyLteTraces () +Scenario::EnablePhyLteTraces() { - NS_LOG_FUNCTION_NOARGS (); - if (!CONFIGURATOR->GetLogOnFile()) + NS_LOG_FUNCTION_NOARGS(); + if (!CONFIGURATOR->GetLogOnFile()) return; - for (size_t phyId = 0; phyId < m_protocolStacks[PHY_LAYER].size(); phyId++) + for (size_t phyId = 0; phyId < m_protocolStacks[PHY_LAYER].size(); phyId++) { - auto obj = m_protocolStacks[PHY_LAYER][phyId]; + auto obj = m_protocolStacks[PHY_LAYER][phyId]; - if (typeid(*obj) == typeid(LtePhySimulationHelper)) + if (typeid(*obj) == typeid(LtePhySimulationHelper)) { - /* LteHelperQuirk: - * This class is an hack to allow access to private members of LteHelper class, - * in particular to the StatsCalculators in order to set their output path. - * A structurally identical class is defined with all attributes set to public, - * then with a reinterpret_cast we interpret the LteHelper as this new class - * so the compiler won't complain about accessing its private members. - */ - class LteHelperQuirk : public Object - { - public: - Ptr dlC, ulC; - Ptr dlPlM, ulPlM; - ObjectFactory a, b, c, d, e, f, g, h, i, j, k; - std::string fMT; - ObjectFactory fMF; - Ptr fM; - bool fSA; - Ptr phyStat; - Ptr phyTxStat; - Ptr phyRxStat; - Ptr macStat; - Ptr rlcStat; - Ptr pdcpStat; - RadioBearerStatsConnector radioBearerStatsConnector; - Ptr m_epcHelper; - uint64_t m_imsiCounter; - uint16_t m_cellIdCounter; - bool l, m, n, o; - std::map< uint8_t, ComponentCarrier > m_componentCarrierPhyParams; - uint16_t m_noOfCcs; - }; - - auto phy = StaticCast (obj); - auto lteHelper = phy->GetLteHelper (); - std::stringstream basePath; - - basePath << CONFIGURATOR->GetResultsPath () << "lte-" << phyId << "-"; - - lteHelper->EnableTraces (); - - auto rlcStat = lteHelper->GetRlcStats (); - rlcStat->SetDlOutputFilename (basePath.str () + "RlcDlStats.txt"); - rlcStat->SetUlOutputFilename (basePath.str () + "RlcUlStats.txt"); - - auto pdcpStat = lteHelper->GetPdcpStats (); - pdcpStat->SetDlPdcpOutputFilename (basePath.str () + "PdcpDlStats.txt"); - pdcpStat->SetUlPdcpOutputFilename (basePath.str () + "PdcpUlStats.txt"); - - auto lteHelperQ = reinterpret_cast (&(*lteHelper)); - - lteHelperQ->phyStat->SetUeSinrFilename (basePath.str () + "PhySinrUlStats.txt"); - lteHelperQ->phyStat->SetInterferenceFilename (basePath.str () + "PhyInterferenceUlStats.txt"); - lteHelperQ->phyStat->SetCurrentCellRsrpSinrFilename (basePath.str () + "PhyRsrpSinrDlStats.txt"); - - lteHelperQ->phyRxStat->SetDlRxOutputFilename (basePath.str () + "PhyRxDlStats.txt"); - lteHelperQ->phyRxStat->SetUlRxOutputFilename (basePath.str () + "PhyRxUlStats.txt"); - - lteHelperQ->phyTxStat->SetDlTxOutputFilename (basePath.str () + "PhyTxDlStats.txt"); - lteHelperQ->phyTxStat->SetUlTxOutputFilename (basePath.str () + "PhyTxUlStats.txt"); - - lteHelperQ->macStat->SetDlOutputFilename (basePath.str () + "MacDlStats.txt"); - lteHelperQ->macStat->SetUlOutputFilename (basePath.str () + "MacUlStats.txt"); + /* LteHelperQuirk: + * This class is an hack to allow access to private members of LteHelper class, + * in particular to the StatsCalculators in order to set their output path. + * A structurally identical class is defined with all attributes set to public, + * then with a reinterpret_cast we interpret the LteHelper as this new class + * so the compiler won't complain about accessing its private members. + */ + class LteHelperQuirk : public Object + { + public: + Ptr dlC, ulC; + Ptr dlPlM, ulPlM; + ObjectFactory a, b, c, d, e, f, g, h, i, j, k; + std::string fMT; + ObjectFactory fMF; + Ptr fM; + bool fSA; + Ptr phyStat; + Ptr phyTxStat; + Ptr phyRxStat; + Ptr macStat; + Ptr rlcStat; + Ptr pdcpStat; + RadioBearerStatsConnector radioBearerStatsConnector; + Ptr m_epcHelper; + uint64_t m_imsiCounter; + uint16_t m_cellIdCounter; + bool l, m, n, o; + std::map m_componentCarrierPhyParams; + uint16_t m_noOfCcs; + }; + + auto phy = StaticCast(obj); + auto lteHelper = phy->GetLteHelper(); + std::stringstream basePath; + + basePath << CONFIGURATOR->GetResultsPath() << "lte-" << phyId << "-"; + + lteHelper->EnableTraces(); + + auto rlcStat = lteHelper->GetRlcStats(); + rlcStat->SetDlOutputFilename(basePath.str() + "RlcDlStats.txt"); + rlcStat->SetUlOutputFilename(basePath.str() + "RlcUlStats.txt"); + + auto pdcpStat = lteHelper->GetPdcpStats(); + pdcpStat->SetDlPdcpOutputFilename(basePath.str() + "PdcpDlStats.txt"); + pdcpStat->SetUlPdcpOutputFilename(basePath.str() + "PdcpUlStats.txt"); + + auto lteHelperQ = reinterpret_cast(&(*lteHelper)); + + lteHelperQ->phyStat->SetUeSinrFilename(basePath.str() + "PhySinrUlStats.txt"); + lteHelperQ->phyStat->SetInterferenceFilename(basePath.str() + + "PhyInterferenceUlStats.txt"); + lteHelperQ->phyStat->SetCurrentCellRsrpSinrFilename(basePath.str() + + "PhyRsrpSinrDlStats.txt"); + + lteHelperQ->phyRxStat->SetDlRxOutputFilename(basePath.str() + "PhyRxDlStats.txt"); + lteHelperQ->phyRxStat->SetUlRxOutputFilename(basePath.str() + "PhyRxUlStats.txt"); + + lteHelperQ->phyTxStat->SetDlTxOutputFilename(basePath.str() + "PhyTxDlStats.txt"); + lteHelperQ->phyTxStat->SetUlTxOutputFilename(basePath.str() + "PhyTxUlStats.txt"); + + lteHelperQ->macStat->SetDlOutputFilename(basePath.str() + "MacDlStats.txt"); + lteHelperQ->macStat->SetUlOutputFilename(basePath.str() + "MacUlStats.txt"); } } } void -Scenario::ConfigureRegionsOfInterest () +Scenario::ConfigureRegionsOfInterest() { - const auto regions = CONFIGURATOR->GetRegionsOfInterest (); - Ptr reg; - for (auto region : regions) - { - reg = irc->Create(region); - } + const auto regions = CONFIGURATOR->GetRegionsOfInterest(); + Ptr reg; + for (auto region : regions) + { + reg = irc->Create(region); + } } void -Scenario::CourseChange (std::string context, Ptr model) +Scenario::CourseChange(std::string context, Ptr model) { - Vector position = model->GetPosition (); - std::string start = "/NodeList/"; - std::string end = "/$ns3::MobilityModel/CourseChange"; - std::string id = context.substr (context.find (start) + start.length (), context.length () - end.length () - start.length ()); - auto dronePeripheralsContainer = m_drones.Get (std::stoi (id))->getPeripherals (); - Ptr peripheral; - std::vector regionindex; - for (DronePeripheralContainer::Iterator i = dronePeripheralsContainer->Begin (); i != dronePeripheralsContainer->End (); i++) - { - peripheral = *i; - regionindex = peripheral->GetRegionsOfInterest (); - int status = irc->IsInRegions (regionindex, position); - if (regionindex.empty ()) continue; - if (status >= 0 || status == -2) + Vector position = model->GetPosition(); + std::string start = "/NodeList/"; + std::string end = "/$ns3::MobilityModel/CourseChange"; + std::string id = context.substr(context.find(start) + start.length(), + context.length() - end.length() - start.length()); + auto dronePeripheralsContainer = m_drones.Get(std::stoi(id))->getPeripherals(); + Ptr peripheral; + std::vector regionindex; + for (DronePeripheralContainer::Iterator i = dronePeripheralsContainer->Begin(); + i != dronePeripheralsContainer->End(); + i++) { - if (peripheral->GetState () != DronePeripheral::PeripheralState::ON) - peripheral->SetState (DronePeripheral::PeripheralState::ON); - } else { - if (peripheral->GetState () == DronePeripheral::PeripheralState::ON) - peripheral->SetState (DronePeripheral::PeripheralState::IDLE); + peripheral = *i; + regionindex = peripheral->GetRegionsOfInterest(); + int status = irc->IsInRegions(regionindex, position); + if (regionindex.empty()) + continue; + if (status >= 0 || status == -2) + { + if (peripheral->GetState() != DronePeripheral::PeripheralState::ON) + peripheral->SetState(DronePeripheral::PeripheralState::ON); + } + else + { + if (peripheral->GetState() == DronePeripheral::PeripheralState::ON) + peripheral->SetState(DronePeripheral::PeripheralState::IDLE); + } } - } } void -Scenario::ConfigureSimulator () +Scenario::ConfigureSimulator() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - if (CONFIGURATOR->GetLogOnFile()) - { - // Enable Report - Report::Get()->Initialize(CONFIGURATOR->GetName(), - CONFIGURATOR->GetCurrentDateTime(), - CONFIGURATOR->GetResultsPath()); - } + if (CONFIGURATOR->GetLogOnFile()) + { + // Enable Report + Report::Get()->Initialize(CONFIGURATOR->GetName(), + CONFIGURATOR->GetCurrentDateTime(), + CONFIGURATOR->GetResultsPath()); + } - Simulator::Stop (Seconds (CONFIGURATOR->GetDuration ())); + Simulator::Stop(Seconds(CONFIGURATOR->GetDuration())); } } // namespace ns3 int -main (int argc, char **argv) +main(int argc, char** argv) { - ns3::Scenario s (argc, argv); - s (); // run the scenario as soon as it is ready + ns3::Scenario s(argc, argv); + s(); // run the scenario as soon as it is ready - return 0; + return 0; } diff --git a/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.cc b/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.cc index 2362062..adf8cc2 100644 --- a/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.cc +++ b/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.cc @@ -22,122 +22,131 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ConstantAccelerationDroneMobilityModel"); -NS_OBJECT_ENSURE_REGISTERED (ConstantAccelerationDroneMobilityModel); +NS_LOG_COMPONENT_DEFINE("ConstantAccelerationDroneMobilityModel"); +NS_OBJECT_ENSURE_REGISTERED(ConstantAccelerationDroneMobilityModel); TypeId -ConstantAccelerationDroneMobilityModel::GetTypeId () +ConstantAccelerationDroneMobilityModel::GetTypeId() { - NS_LOG_FUNCTION_NOARGS (); - - static TypeId tid = TypeId ("ns3::ConstantAccelerationDroneMobilityModel") - .SetParent () - .SetGroupName ("Mobility") - .AddConstructor () - .AddAttribute ("Acceleration", "The constant acceleration of the drone, in m/s^2", - DoubleValue (2.0), - MakeDoubleAccessor (&ConstantAccelerationDroneMobilityModel::m_acceleration), - MakeDoubleChecker ()) - .AddAttribute ("MaxSpeed", "Max speed of the drone, in m/s.", - DoubleValue (10.0), - MakeDoubleAccessor (&ConstantAccelerationDroneMobilityModel::m_maxSpeed), - MakeDoubleChecker ()) - .AddAttribute ("FlightPlan", "The ideal trajectory that the drone should run across.", - FlightPlanValue (), - MakeFlightPlanAccessor (&ConstantAccelerationDroneMobilityModel::m_flightPlan), - MakeFlightPlanChecker ()) - .AddAttribute ("CurveStep", "The step of the curve to generate. Lower step means more points generated, hence higher resolution.", - DoubleValue (0.001), - MakeDoubleAccessor (&ConstantAccelerationDroneMobilityModel::m_curveStep), - MakeDoubleChecker ()) - ; - - return tid; + NS_LOG_FUNCTION_NOARGS(); + + static TypeId tid = + TypeId("ns3::ConstantAccelerationDroneMobilityModel") + .SetParent() + .SetGroupName("Mobility") + .AddConstructor() + .AddAttribute( + "Acceleration", + "The constant acceleration of the drone, in m/s^2", + DoubleValue(2.0), + MakeDoubleAccessor(&ConstantAccelerationDroneMobilityModel::m_acceleration), + MakeDoubleChecker()) + .AddAttribute("MaxSpeed", + "Max speed of the drone, in m/s.", + DoubleValue(10.0), + MakeDoubleAccessor(&ConstantAccelerationDroneMobilityModel::m_maxSpeed), + MakeDoubleChecker()) + .AddAttribute( + "FlightPlan", + "The ideal trajectory that the drone should run across.", + FlightPlanValue(), + MakeFlightPlanAccessor(&ConstantAccelerationDroneMobilityModel::m_flightPlan), + MakeFlightPlanChecker()) + .AddAttribute("CurveStep", + "The step of the curve to generate. Lower step means more points " + "generated, hence higher resolution.", + DoubleValue(0.001), + MakeDoubleAccessor(&ConstantAccelerationDroneMobilityModel::m_curveStep), + MakeDoubleChecker()); + + return tid; } -ConstantAccelerationDroneMobilityModel::ConstantAccelerationDroneMobilityModel () : - m_flightParams {m_acceleration, m_maxSpeed}, - m_lastUpdate {-1} +ConstantAccelerationDroneMobilityModel::ConstantAccelerationDroneMobilityModel() + : m_flightParams{m_acceleration, m_maxSpeed}, + m_lastUpdate{-1} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ConstantAccelerationDroneMobilityModel::~ConstantAccelerationDroneMobilityModel () +ConstantAccelerationDroneMobilityModel::~ConstantAccelerationDroneMobilityModel() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ConstantAccelerationDroneMobilityModel::Update () const +ConstantAccelerationDroneMobilityModel::Update() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - const Time t = Simulator::Now (); - if (t.Compare (m_lastUpdate) <= 0) + const Time t = Simulator::Now(); + if (t.Compare(m_lastUpdate) <= 0) { - NS_LOG_LOGIC ("Update is being suppressed."); - return; + NS_LOG_LOGIC("Update is being suppressed."); + return; } - m_lastUpdate = t; + m_lastUpdate = t; - m_planner.Update (t); - m_position = m_planner.GetPosition (); - m_velocity = m_planner.GetVelocity (); + m_planner.Update(t); + m_position = m_planner.GetPosition(); + m_velocity = m_planner.GetVelocity(); - NotifyCourseChange (); + NotifyCourseChange(); } Vector -ConstantAccelerationDroneMobilityModel::DoGetPosition () const +ConstantAccelerationDroneMobilityModel::DoGetPosition() const { - NS_LOG_FUNCTION (this); - NS_LOG_LOGIC ("position: " << m_position); + NS_LOG_FUNCTION(this); + NS_LOG_LOGIC("position: " << m_position); - Update (); - return m_position; + Update(); + return m_position; } void -ConstantAccelerationDroneMobilityModel::DoSetPosition (const Vector &position) +ConstantAccelerationDroneMobilityModel::DoSetPosition(const Vector& position) { - NS_LOG_FUNCTION (this << position); + NS_LOG_FUNCTION(this << position); - m_position = position; + m_position = position; } Vector -ConstantAccelerationDroneMobilityModel::DoGetVelocity () const +ConstantAccelerationDroneMobilityModel::DoGetVelocity() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - Update (); + Update(); - NS_LOG_LOGIC ("velocity: " << m_velocity); - return m_velocity; + NS_LOG_LOGIC("velocity: " << m_velocity); + return m_velocity; } void -ConstantAccelerationDroneMobilityModel::DoInitialize () +ConstantAccelerationDroneMobilityModel::DoInitialize() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_flightParams = { m_acceleration, m_maxSpeed }; + m_flightParams = {m_acceleration, m_maxSpeed}; - m_planner = Planner - (m_flightPlan, m_flightParams, m_curveStep); + m_planner = Planner(m_flightPlan, + m_flightParams, + m_curveStep); - MobilityModel::DoInitialize (); + MobilityModel::DoInitialize(); } void -ConstantAccelerationDroneMobilityModel::DoDispose () +ConstantAccelerationDroneMobilityModel::DoDispose() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - MobilityModel::DoDispose (); + MobilityModel::DoDispose(); } -} // ns3 namespace +} // namespace ns3 diff --git a/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.h b/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.h index bc6c482..10fca4f 100644 --- a/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.h +++ b/src/mobility/constant-acceleration/constant-acceleration-drone-mobility-model.h @@ -18,53 +18,53 @@ #ifndef CONSTANT_ACCELERATION_DRONE_MOBILITY_MODEL_H #define CONSTANT_ACCELERATION_DRONE_MOBILITY_MODEL_H -#include -#include +#include "constant-acceleration-flight.h" +#include "constant-acceleration-param.h" #include +#include #include #include +#include -#include "constant-acceleration-flight.h" -#include "constant-acceleration-param.h" - -namespace ns3 { +namespace ns3 +{ class ConstantAccelerationDroneMobilityModel : public MobilityModel { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); - ConstantAccelerationDroneMobilityModel (); - ~ConstantAccelerationDroneMobilityModel (); + ConstantAccelerationDroneMobilityModel(); + ~ConstantAccelerationDroneMobilityModel(); -private: - virtual void DoInitialize (); - virtual void DoDispose (); + private: + virtual void DoInitialize(); + virtual void DoDispose(); - virtual void Update () const; - virtual void DoSetPosition (const Vector &position); - virtual Vector DoGetPosition () const; - virtual Vector DoGetVelocity () const; + virtual void Update() const; + virtual void DoSetPosition(const Vector& position); + virtual Vector DoGetPosition() const; + virtual Vector DoGetVelocity() const; -protected: - mutable Vector m_position; - mutable Vector m_velocity; + protected: + mutable Vector m_position; + mutable Vector m_velocity; - double m_acceleration; - double m_maxSpeed; + double m_acceleration; + double m_maxSpeed; - FlightPlan m_flightPlan; - ConstantAccelerationParam m_flightParams; - Planner m_planner; + FlightPlan m_flightPlan; + ConstantAccelerationParam m_flightParams; + Planner m_planner; - mutable Time m_lastUpdate; + mutable Time m_lastUpdate; - float m_curveStep; + float m_curveStep; }; } // namespace ns3 diff --git a/src/mobility/constant-acceleration/constant-acceleration-flight.cc b/src/mobility/constant-acceleration/constant-acceleration-flight.cc index 3908d4d..c417003 100644 --- a/src/mobility/constant-acceleration/constant-acceleration-flight.cc +++ b/src/mobility/constant-acceleration/constant-acceleration-flight.cc @@ -17,157 +17,155 @@ */ #include "constant-acceleration-flight.h" -#include -#include - #include #include -namespace ns3 { +#include +#include -NS_LOG_COMPONENT_DEFINE ("ConstantAccelerationFlight"); +namespace ns3 +{ -ConstantAccelerationFlight::ConstantAccelerationFlight (FlightPlan flightPlan, - ConstantAccelerationParam flightParam, - double step) : - Curve (flightPlan, step), - m_acceleration {flightParam.GetAcceleration ()}, - m_maxSpeed {flightParam.GetMaxSpeed ()}, - m_isHovering {flightPlan.GetN () == 1}, - m_currentDistance {0.0}, - m_currentT {0.0}, - m_currentSpeed {0.0} +NS_LOG_COMPONENT_DEFINE("ConstantAccelerationFlight"); + +ConstantAccelerationFlight::ConstantAccelerationFlight(FlightPlan flightPlan, + ConstantAccelerationParam flightParam, + double step) + : Curve(flightPlan, step), + m_acceleration{flightParam.GetAcceleration()}, + m_maxSpeed{flightParam.GetMaxSpeed()}, + m_isHovering{flightPlan.GetN() == 1}, + m_currentDistance{0.0}, + m_currentT{0.0}, + m_currentSpeed{0.0} { - NS_LOG_FUNCTION (this << m_acceleration << m_maxSpeed); + NS_LOG_FUNCTION(this << m_acceleration << m_maxSpeed); - Generate (); + Generate(); } -ConstantAccelerationFlight::~ConstantAccelerationFlight () +ConstantAccelerationFlight::~ConstantAccelerationFlight() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ConstantAccelerationFlight::Generate () +ConstantAccelerationFlight::Generate() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - if (m_isHovering) + if (m_isHovering) { - // this is a dummy flight plan to hover on a specific point. - m_length = 0; - m_currentVelocity = Vector3D (); - m_time = m_knots.GetBack ()->GetRestTime (); + // this is a dummy flight plan to hover on a specific point. + m_length = 0; + m_currentVelocity = Vector3D(); + m_time = m_knots.GetBack()->GetRestTime(); } - else + else { - m_length = Curve::Generate (); - m_accelerationZoneLength = 0.5 * std::pow (m_maxSpeed, 2) / m_acceleration; - m_accelerationZoneTime = m_maxSpeed / m_acceleration; + m_length = Curve::Generate(); + m_accelerationZoneLength = 0.5 * std::pow(m_maxSpeed, 2) / m_acceleration; + m_accelerationZoneTime = m_maxSpeed / m_acceleration; - const double aZonesL = 2 * m_accelerationZoneLength; // total length of acceleration zones - const double aZonesT = 2 * m_accelerationZoneTime; // total time of acceleration zones + const double aZonesL = 2 * m_accelerationZoneLength; // total length of acceleration zones + const double aZonesT = 2 * m_accelerationZoneTime; // total time of acceleration zones - m_time = Seconds (aZonesT + (m_length - aZonesL) / m_maxSpeed); + m_time = Seconds(aZonesT + (m_length - aZonesL) / m_maxSpeed); - if (m_time.GetSeconds () <= aZonesT) // in case the trajectory is too short to never reach m_maxSpeed - m_time = Seconds (std::sqrt (4.0 * m_length / m_acceleration)); + if (m_time.GetSeconds() <= + aZonesT) // in case the trajectory is too short to never reach m_maxSpeed + m_time = Seconds(std::sqrt(4.0 * m_length / m_acceleration)); } - m_currentPosition = CurvePoint (m_knots.GetFront ()->GetPosition ()); + m_currentPosition = CurvePoint(m_knots.GetFront()->GetPosition()); } void -ConstantAccelerationFlight::Update (const double &t) const +ConstantAccelerationFlight::Update(const double& t) const { - NS_LOG_FUNCTION (this << t); + NS_LOG_FUNCTION(this << t); - if (m_isHovering) - return; + if (m_isHovering) + return; - double a = (m_currentSpeed < m_maxSpeed) ? m_acceleration : 0.0; + double a = (m_currentSpeed < m_maxSpeed) ? m_acceleration : 0.0; - if (m_currentDistance >= m_length - 0.5 * std::pow (m_currentSpeed, 2) / m_acceleration) - a = -m_acceleration; + if (m_currentDistance >= m_length - 0.5 * std::pow(m_currentSpeed, 2) / m_acceleration) + a = -m_acceleration; - m_currentDistance += m_currentSpeed * (t - m_currentT) + 0.5 * a * std::pow (t - m_currentT, 2); - m_currentSpeed += a * (t - m_currentT); - m_currentT = t; + m_currentDistance += m_currentSpeed * (t - m_currentT) + 0.5 * a * std::pow(t - m_currentT, 2); + m_currentSpeed += a * (t - m_currentT); + m_currentT = t; - UpdatePosition (); - UpdateVelocity (); + UpdatePosition(); + UpdateVelocity(); - NS_LOG_LOGIC ("Current speed: " << m_currentSpeed); - NS_LOG_LOGIC ("Current distance: " << m_currentDistance); + NS_LOG_LOGIC("Current speed: " << m_currentSpeed); + NS_LOG_LOGIC("Current distance: " << m_currentDistance); } - Time -ConstantAccelerationFlight::GetTime () const +ConstantAccelerationFlight::GetTime() const { - return m_time; + return m_time; } Vector -ConstantAccelerationFlight::GetPosition () const +ConstantAccelerationFlight::GetPosition() const { - return m_currentPosition.GetPosition (); + return m_currentPosition.GetPosition(); } Vector -ConstantAccelerationFlight::GetVelocity () const +ConstantAccelerationFlight::GetVelocity() const { - return m_currentVelocity; + return m_currentVelocity; } void -ConstantAccelerationFlight::UpdatePosition () const +ConstantAccelerationFlight::UpdatePosition() const { - NS_LOG_FUNCTION (this); - NS_LOG_LOGIC ("old pos vector: " << m_currentPosition.GetPosition ()); - m_pastPosition = m_currentPosition; + NS_LOG_FUNCTION(this); + NS_LOG_LOGIC("old pos vector: " << m_currentPosition.GetPosition()); + m_pastPosition = m_currentPosition; - for (auto i = m_curve.begin (); i != m_curve.end (); i++) + for (auto i = m_curve.begin(); i != m_curve.end(); i++) { - if ((*i).GetAbsoluteDistance () > m_currentDistance) + if ((*i).GetAbsoluteDistance() > m_currentDistance) { - m_currentPosition = (*i); - break; + m_currentPosition = (*i); + break; } } - NS_LOG_LOGIC ("new pos vector: " << m_currentPosition.GetPosition ()); + NS_LOG_LOGIC("new pos vector: " << m_currentPosition.GetPosition()); } void -ConstantAccelerationFlight::UpdateVelocity () const +ConstantAccelerationFlight::UpdateVelocity() const { - NS_LOG_FUNCTION (this); - NS_LOG_LOGIC ("old vel: " << m_currentVelocity); + NS_LOG_FUNCTION(this); + NS_LOG_LOGIC("old vel: " << m_currentVelocity); - const Vector relativeDistance = m_currentPosition.GetRelativeDistanceVector (m_pastPosition); - const double relativeDistScalar = m_currentPosition.GetRelativeDistance (m_pastPosition); + const Vector relativeDistance = m_currentPosition.GetRelativeDistanceVector(m_pastPosition); + const double relativeDistScalar = m_currentPosition.GetRelativeDistance(m_pastPosition); - if (relativeDistScalar == 0.0) - return; + if (relativeDistScalar == 0.0) + return; - const double velX = (relativeDistance.x != 0) - ? (relativeDistance.x / relativeDistScalar) * m_currentSpeed - : 0; - const double velY = (relativeDistance.y != 0) - ? (relativeDistance.y / relativeDistScalar) * m_currentSpeed - : 0; - const double velZ = (relativeDistance.z != 0) - ? (relativeDistance.z / relativeDistScalar) * m_currentSpeed - : 0; + const double velX = + (relativeDistance.x != 0) ? (relativeDistance.x / relativeDistScalar) * m_currentSpeed : 0; + const double velY = + (relativeDistance.y != 0) ? (relativeDistance.y / relativeDistScalar) * m_currentSpeed : 0; + const double velZ = + (relativeDistance.z != 0) ? (relativeDistance.z / relativeDistScalar) * m_currentSpeed : 0; - NS_LOG_LOGIC ("relative distance: " << relativeDistance - << "; current speed: " << m_currentSpeed); + NS_LOG_LOGIC("relative distance: " << relativeDistance + << "; current speed: " << m_currentSpeed); - m_currentVelocity = {velX, velY, velZ}; + m_currentVelocity = {velX, velY, velZ}; - NS_LOG_LOGIC ("new vel: " << m_currentVelocity); + NS_LOG_LOGIC("new vel: " << m_currentVelocity); } } // namespace ns3 diff --git a/src/mobility/constant-acceleration/constant-acceleration-flight.h b/src/mobility/constant-acceleration/constant-acceleration-flight.h index 3975db1..c42978c 100644 --- a/src/mobility/constant-acceleration/constant-acceleration-flight.h +++ b/src/mobility/constant-acceleration/constant-acceleration-flight.h @@ -18,51 +18,51 @@ #ifndef CONSTANT_ACCELERATION_FLIGHT_H #define CONSTANT_ACCELERATION_FLIGHT_H -#include +#include "constant-acceleration-param.h" #include #include +#include -#include "constant-acceleration-param.h" - -namespace ns3 { +namespace ns3 +{ class ConstantAccelerationFlight : public Curve { -public: - ConstantAccelerationFlight (FlightPlan flightPlan, - ConstantAccelerationParam flightParam, - double step); - ~ConstantAccelerationFlight (); + public: + ConstantAccelerationFlight(FlightPlan flightPlan, + ConstantAccelerationParam flightParam, + double step); + ~ConstantAccelerationFlight(); - void Generate (); - void Update (const double &time) const; + void Generate(); + void Update(const double& time) const; - Time GetTime () const; - Vector GetPosition () const; - Vector GetVelocity () const; + Time GetTime() const; + Vector GetPosition() const; + Vector GetVelocity() const; -protected: - void UpdatePosition () const; - void UpdateVelocity () const; + protected: + void UpdatePosition() const; + void UpdateVelocity() const; - double m_length; /// Total length of the trajectory - Time m_time; /// Total time the drone would take to complete it + double m_length; /// Total length of the trajectory + Time m_time; /// Total time the drone would take to complete it - double m_acceleration; // m/s^2 - double m_maxSpeed; // m/s - bool m_isHovering; + double m_acceleration; // m/s^2 + double m_maxSpeed; // m/s + bool m_isHovering; - double m_accelerationZoneLength; - double m_accelerationZoneTime; + double m_accelerationZoneLength; + double m_accelerationZoneTime; - mutable CurvePoint m_currentPosition; - mutable CurvePoint m_pastPosition; - mutable double m_currentDistance; - mutable double m_currentT; + mutable CurvePoint m_currentPosition; + mutable CurvePoint m_pastPosition; + mutable double m_currentDistance; + mutable double m_currentT; - mutable Vector m_currentVelocity; - mutable double m_currentSpeed; + mutable Vector m_currentVelocity; + mutable double m_currentSpeed; }; } // namespace ns3 diff --git a/src/mobility/constant-acceleration/constant-acceleration-param.cc b/src/mobility/constant-acceleration/constant-acceleration-param.cc index 45e593d..1d0eb7f 100644 --- a/src/mobility/constant-acceleration/constant-acceleration-param.cc +++ b/src/mobility/constant-acceleration/constant-acceleration-param.cc @@ -17,29 +17,29 @@ */ #include "constant-acceleration-param.h" -namespace ns3 { +namespace ns3 +{ -ConstantAccelerationParam::ConstantAccelerationParam (double acceleration, - double maxSpeed) : - m_acceleration {acceleration}, - m_maxSpeed {maxSpeed} +ConstantAccelerationParam::ConstantAccelerationParam(double acceleration, double maxSpeed) + : m_acceleration{acceleration}, + m_maxSpeed{maxSpeed} { } -ConstantAccelerationParam::~ConstantAccelerationParam () +ConstantAccelerationParam::~ConstantAccelerationParam() { } const double -ConstantAccelerationParam::GetAcceleration () const +ConstantAccelerationParam::GetAcceleration() const { - return m_acceleration; + return m_acceleration; } const double -ConstantAccelerationParam::GetMaxSpeed () const +ConstantAccelerationParam::GetMaxSpeed() const { - return m_maxSpeed; + return m_maxSpeed; } } // namespace ns3 diff --git a/src/mobility/constant-acceleration/constant-acceleration-param.h b/src/mobility/constant-acceleration/constant-acceleration-param.h index 69ebd85..45e356a 100644 --- a/src/mobility/constant-acceleration/constant-acceleration-param.h +++ b/src/mobility/constant-acceleration/constant-acceleration-param.h @@ -18,21 +18,21 @@ #ifndef CONSTANT_ACCELERATION_PARAM_H #define CONSTANT_ACCELERATION_PARAM_H -namespace ns3 { +namespace ns3 +{ class ConstantAccelerationParam { -public: - ConstantAccelerationParam (double acceleration, - double maxSpeed); - virtual ~ConstantAccelerationParam (); + public: + ConstantAccelerationParam(double acceleration, double maxSpeed); + virtual ~ConstantAccelerationParam(); - const double GetAcceleration () const; - const double GetMaxSpeed () const; + const double GetAcceleration() const; + const double GetMaxSpeed() const; -private: - double m_acceleration; - double m_maxSpeed; + private: + double m_acceleration; + double m_maxSpeed; }; } // namespace ns3 diff --git a/src/mobility/curve-point.cc b/src/mobility/curve-point.cc index 35f4375..6bcd197 100644 --- a/src/mobility/curve-point.cc +++ b/src/mobility/curve-point.cc @@ -17,87 +17,89 @@ */ #include "curve-point.h" -#include - #include #include -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("CurvePoint"); - -CurvePoint::CurvePoint (const Vector position, - float t, - double relativeDistance, - double absoluteDistance) : - m_position {position}, - m_t {t}, - m_relativeDistance {relativeDistance}, - m_absoluteDistance {absoluteDistance} -{} - -CurvePoint::CurvePoint (const Vector position) : - m_position {position}, - m_t {0.0}, - m_relativeDistance {0.0}, - m_absoluteDistance {0.0} -{} - -CurvePoint::CurvePoint () : - m_position {0.0, 0.0, 0.0}, - m_t {0.0}, - m_relativeDistance {0.0}, - m_absoluteDistance {0.0} -{} - -CurvePoint::~CurvePoint () +#include + +namespace ns3 +{ + +NS_LOG_COMPONENT_DEFINE("CurvePoint"); + +CurvePoint::CurvePoint(const Vector position, + float t, + double relativeDistance, + double absoluteDistance) + : m_position{position}, + m_t{t}, + m_relativeDistance{relativeDistance}, + m_absoluteDistance{absoluteDistance} +{ +} + +CurvePoint::CurvePoint(const Vector position) + : m_position{position}, + m_t{0.0}, + m_relativeDistance{0.0}, + m_absoluteDistance{0.0} +{ +} + +CurvePoint::CurvePoint() + : m_position{0.0, 0.0, 0.0}, + m_t{0.0}, + m_relativeDistance{0.0}, + m_absoluteDistance{0.0} +{ +} + +CurvePoint::~CurvePoint() { } const Vector -CurvePoint::GetRelativeDistanceVector (const Vector &point) const +CurvePoint::GetRelativeDistanceVector(const Vector& point) const { - return m_position - point; + return m_position - point; } const Vector -CurvePoint::GetRelativeDistanceVector (const CurvePoint &point) const +CurvePoint::GetRelativeDistanceVector(const CurvePoint& point) const { - return m_position - point.GetPosition (); + return m_position - point.GetPosition(); } const double -CurvePoint::GetRelativeDistance (const Vector &point) const +CurvePoint::GetRelativeDistance(const Vector& point) const { - const Vector diff = GetRelativeDistanceVector (point); - return sqrt (pow (diff.x, 2) + pow (diff.y, 2) + pow (diff.z, 2)); + const Vector diff = GetRelativeDistanceVector(point); + return sqrt(pow(diff.x, 2) + pow(diff.y, 2) + pow(diff.z, 2)); } const double -CurvePoint::GetRelativeDistance (const CurvePoint &point) const +CurvePoint::GetRelativeDistance(const CurvePoint& point) const { - return GetRelativeDistance (point.GetPosition ()); + return GetRelativeDistance(point.GetPosition()); } const double -CurvePoint::GetAbsoluteDistance () const +CurvePoint::GetAbsoluteDistance() const { - return m_absoluteDistance; + return m_absoluteDistance; } const Vector -CurvePoint::GetPosition () const +CurvePoint::GetPosition() const { - return m_position; + return m_position; } bool -CurvePoint::operator!= (const CurvePoint& b) const +CurvePoint::operator!=(const CurvePoint& b) const { - return m_position != b.m_position - && m_t != b.m_t - && m_relativeDistance != b.m_relativeDistance - && m_absoluteDistance != b.m_absoluteDistance; + return m_position != b.m_position && m_t != b.m_t && + m_relativeDistance != b.m_relativeDistance && m_absoluteDistance != b.m_absoluteDistance; } } // namespace ns3 diff --git a/src/mobility/curve-point.h b/src/mobility/curve-point.h index 4031e2d..d00d9e0 100644 --- a/src/mobility/curve-point.h +++ b/src/mobility/curve-point.h @@ -20,7 +20,8 @@ #include -namespace ns3 { +namespace ns3 +{ /** * \brief A point constructed during curve generation with the position @@ -28,87 +29,83 @@ namespace ns3 { */ class CurvePoint { -public: - /** - * \brief constructor used by the curve generator. - * - * \param position position in space. - * \param t parameter used by the curve for the generation - * of the point. t is a float number between 0 and 1. - * \param relativeDistance the euclidean distance relative to the point - * preceding this one on the curve. - * \param absoluteDistance the total length of the curve from the origin to - * this point. - */ - CurvePoint (const Vector position, - float t, - double relativeDistance, - double absoluteDistance); - - CurvePoint (const Vector position); + public: + /** + * \brief constructor used by the curve generator. + * + * \param position position in space. + * \param t parameter used by the curve for the generation + * of the point. t is a float number between 0 and 1. + * \param relativeDistance the euclidean distance relative to the point + * preceding this one on the curve. + * \param absoluteDistance the total length of the curve from the origin to + * this point. + */ + CurvePoint(const Vector position, float t, double relativeDistance, double absoluteDistance); - /** - * \brief default constructor - */ - CurvePoint (); - /** - * \brief default destructor - */ - virtual ~CurvePoint (); + CurvePoint(const Vector position); + /** + * \brief default constructor + */ + CurvePoint(); + /** + * \brief default destructor + */ + virtual ~CurvePoint(); - /** - * \brief get the distance vector relative to a given point - * - * \param point the second point to calculate the distance vector - * \return the distance vector - */ - const Vector GetRelativeDistanceVector (const Vector &point) const; - /** - * \brief get the distance vector relative to a given point of the curve - * - * \param point the second point to calculate the distance vector - * \return the distance vector - */ - const Vector GetRelativeDistanceVector (const CurvePoint &point) const; - /** - * \brief get the distance relative to a given point - * - * \param point the second point to calculate the distance - * \return the scalar value of the euclidean distance - */ - const double GetRelativeDistance (const Vector &point) const; - /** - * \brief get the distance relative to a given point point of the curve - * - * \param point the second point to calculate the distance - * \return the scalar value of the euclidean distance - */ - const double GetRelativeDistance (const CurvePoint &point) const; + /** + * \brief get the distance vector relative to a given point + * + * \param point the second point to calculate the distance vector + * \return the distance vector + */ + const Vector GetRelativeDistanceVector(const Vector& point) const; + /** + * \brief get the distance vector relative to a given point of the curve + * + * \param point the second point to calculate the distance vector + * \return the distance vector + */ + const Vector GetRelativeDistanceVector(const CurvePoint& point) const; + /** + * \brief get the distance relative to a given point + * + * \param point the second point to calculate the distance + * \return the scalar value of the euclidean distance + */ + const double GetRelativeDistance(const Vector& point) const; + /** + * \brief get the distance relative to a given point point of the curve + * + * \param point the second point to calculate the distance + * \return the scalar value of the euclidean distance + */ + const double GetRelativeDistance(const CurvePoint& point) const; - /** - * \brief get the length of the curve up to the point of the curve - * - * \return the length of the curve up to this point of the curve - */ - const double GetAbsoluteDistance () const; + /** + * \brief get the length of the curve up to the point of the curve + * + * \return the length of the curve up to this point of the curve + */ + const double GetAbsoluteDistance() const; - /** - * \return the location of this point in space - */ - const Vector GetPosition () const; + /** + * \return the location of this point in space + */ + const Vector GetPosition() const; - bool operator!= (const CurvePoint& b) const; + bool operator!=(const CurvePoint& b) const; -private: - Vector m_position; /// Location of this point in space. - float m_t; /// Parameter used by the curve for the - /// generation of the point. t is a float - /// Number between 0 and 1. - double m_relativeDistance; /// The euclidean distance relative to the point - /// preceding this one on the curve. - double m_absoluteDistance; /// The total length of the curve from the origin - /// to this point. + private: + Vector m_position; /// Location of this point in space. + float m_t; /// Parameter used by the curve for the + /// generation of the point. t is a float + /// Number between 0 and 1. + double m_relativeDistance; /// The euclidean distance relative to the point + /// preceding this one on the curve. + double m_absoluteDistance; /// The total length of the curve from the origin + /// to this point. }; } // namespace ns3 diff --git a/src/mobility/curve.cc b/src/mobility/curve.cc index 71801bf..3f1eeb8 100644 --- a/src/mobility/curve.cc +++ b/src/mobility/curve.cc @@ -17,131 +17,132 @@ */ #include "curve.h" -#include - -#include - #include #include #include #include -namespace ns3 { +#include +#include + +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Curve"); +NS_LOG_COMPONENT_DEFINE("Curve"); class CurvePriv { -public: - /** - * Get virtual knots according to real knots' interest level. - */ - static const FlightPlan GetVirtualKnots (const FlightPlan knots) - { - FlightPlan virtualKnots {}; - - for (auto k = knots.Begin (); k != knots.End(); k++) - { - auto interestLevel = (*k)->GetInterest (); - - if (interestLevel <= 1) - { - virtualKnots.Add (*k); - } - else - { - for (uint32_t i = 0; i < interestLevel; i++) - { - virtualKnots.Add (*k); - } - } - } - - return virtualKnots; - } + public: + /** + * Get virtual knots according to real knots' interest level. + */ + static const FlightPlan GetVirtualKnots(const FlightPlan knots) + { + FlightPlan virtualKnots{}; + + for (auto k = knots.Begin(); k != knots.End(); k++) + { + auto interestLevel = (*k)->GetInterest(); + + if (interestLevel <= 1) + { + virtualKnots.Add(*k); + } + else + { + for (uint32_t i = 0; i < interestLevel; i++) + { + virtualKnots.Add(*k); + } + } + } + + return virtualKnots; + } }; -Curve::Curve (const FlightPlan knots, - const float step) : - m_knots {CurvePriv::GetVirtualKnots (knots)}, - m_knotsN {knots.GetN ()}, - m_step {step} +Curve::Curve(const FlightPlan knots, const float step) + : m_knots{CurvePriv::GetVirtualKnots(knots)}, + m_knotsN{knots.GetN()}, + m_step{step} { - NS_LOG_FUNCTION (knots.GetN () << step); + NS_LOG_FUNCTION(knots.GetN() << step); } -Curve::Curve (const FlightPlan knots) : - m_knots {CurvePriv::GetVirtualKnots (knots)}, - m_knotsN {knots.GetN ()} +Curve::Curve(const FlightPlan knots) + : m_knots{CurvePriv::GetVirtualKnots(knots)}, + m_knotsN{knots.GetN()} { - NS_LOG_FUNCTION (knots.GetN ()); + NS_LOG_FUNCTION(knots.GetN()); } -Curve::Curve () : - m_step {0.1} +Curve::Curve() + : m_step{0.1} { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); } -Curve::~Curve () +Curve::~Curve() { } const double -Curve::Generate () const +Curve::Generate() const { - NS_LOG_FUNCTION_NOARGS (); - - double absoluteDistance = 0.0; + NS_LOG_FUNCTION_NOARGS(); - NS_LOG_LOGIC ("Constructing Bézier curve with " << m_knotsN << " knots."); - for (float t = 0.0; t < 1.0; t += m_step) { - const Vector point = GetPoint (t); - double relativeDistance = 0.0; + double absoluteDistance = 0.0; - if (!m_curve.empty ()) - { - relativeDistance = m_curve.back ().GetRelativeDistance (point); - absoluteDistance += relativeDistance; - } - - NS_LOG_LOGIC (" NP: " << point << " | t: " << t << " | rD: " << relativeDistance << " | aD: " << absoluteDistance); - m_curve.push_back ({point, t, relativeDistance, absoluteDistance}); - } + NS_LOG_LOGIC("Constructing Bézier curve with " << m_knotsN << " knots."); + for (float t = 0.0; t < 1.0; t += m_step) + { + const Vector point = GetPoint(t); + double relativeDistance = 0.0; + + if (!m_curve.empty()) + { + relativeDistance = m_curve.back().GetRelativeDistance(point); + absoluteDistance += relativeDistance; + } + + NS_LOG_LOGIC(" NP: " << point << " | t: " << t << " | rD: " << relativeDistance + << " | aD: " << absoluteDistance); + m_curve.push_back({point, t, relativeDistance, absoluteDistance}); + } - return absoluteDistance; + return absoluteDistance; } const Vector -Curve::GetPoint (const float &t) const +Curve::GetPoint(const float& t) const { - const uint32_t n = m_knots.GetN (); - const uint32_t r = n - 1; + const uint32_t n = m_knots.GetN(); + const uint32_t r = n - 1; - Vector p {0.0, 0.0, 0.0}; + Vector p{0.0, 0.0, 0.0}; - const double fac_r = Factorial (r); + const double fac_r = Factorial(r); - for (uint32_t i = 0; i < n; i++) + for (uint32_t i = 0; i < n; i++) { - const double fact = fac_r / (Factorial (r - i) * Factorial (i)); - const double pdiff = pow (1 - t, r - i); - const double power = pow (t, i); - const auto k = m_knots.Get (i)->GetPosition (); - - p.x += fact * pdiff * power * k.x; - p.y += fact * pdiff * power * k.y; - p.z += fact * pdiff * power * k.z; + const double fact = fac_r / (Factorial(r - i) * Factorial(i)); + const double pdiff = pow(1 - t, r - i); + const double power = pow(t, i); + const auto k = m_knots.Get(i)->GetPosition(); + + p.x += fact * pdiff * power * k.x; + p.y += fact * pdiff * power * k.y; + p.z += fact * pdiff * power * k.z; } - // NS_LOG_LOGIC ("Curve at t " << t << ": " << p); - return p; + // NS_LOG_LOGIC ("Curve at t " << t << ": " << p); + return p; } const double -Curve::Factorial (const double x) const +Curve::Factorial(const double x) const { - return (x == 0) || (x == 1) ? 1 : x * Factorial(x - 1); + return (x == 0) || (x == 1) ? 1 : x * Factorial(x - 1); } } // namespace ns3 diff --git a/src/mobility/curve.h b/src/mobility/curve.h index 147c0f7..0e64b8d 100644 --- a/src/mobility/curve.h +++ b/src/mobility/curve.h @@ -18,15 +18,16 @@ #ifndef CURVE_H #define CURVE_H -#include -#include +#include "curve-point.h" +#include "flight-plan.h" #include -#include "curve-point.h" -#include "flight-plan.h" +#include +#include -namespace ns3 { +namespace ns3 +{ /** * Generate a discrete curve given a flight plan and a step using Bézier @@ -34,61 +35,60 @@ namespace ns3 { */ class Curve { -public: - typedef std::vector::iterator Iterator; + public: + typedef std::vector::iterator Iterator; - /** - * \brief the constructor requesting all the needed parameters. - */ - Curve (const FlightPlan knots, - const float step); - /** - * \brief the constructor requesting only the flight plan. The step will be - * 1/100. - */ - Curve (const FlightPlan knots); - /** - * \brief default constructor with no flight plan, hence no curve to - * generate. - */ - Curve (); - /** - * \brief default destructor - */ - virtual ~Curve (); + /** + * \brief the constructor requesting all the needed parameters. + */ + Curve(const FlightPlan knots, const float step); + /** + * \brief the constructor requesting only the flight plan. The step will be + * 1/100. + */ + Curve(const FlightPlan knots); + /** + * \brief default constructor with no flight plan, hence no curve to + * generate. + */ + Curve(); + /** + * \brief default destructor + */ + virtual ~Curve(); - /** - * \brief generate the curve using the given flight plan and step during - * object initialization. - * - * \return the length of the newly generated curve. - */ - const double Generate () const; + /** + * \brief generate the curve using the given flight plan and step during + * object initialization. + * + * \return the length of the newly generated curve. + */ + const double Generate() const; -protected: - /** - * \brief Calculate the point of a curve given using Bézier generator. - * - * \param t the parameter needed by Bézier general equation, a float between - * 0 and 1. - * \return the point in the curve. - */ - const Vector GetPoint (const float &t) const; + protected: + /** + * \brief Calculate the point of a curve given using Bézier generator. + * + * \param t the parameter needed by Bézier general equation, a float between + * 0 and 1. + * \return the point in the curve. + */ + const Vector GetPoint(const float& t) const; - /** - * \brief Helper function to calculate the factorial of a number using - * standard facilities. - * - * \param x the integer for which is needed it's factorial - * \reutrn x! - */ - const double Factorial (const double x) const; + /** + * \brief Helper function to calculate the factorial of a number using + * standard facilities. + * + * \param x the integer for which is needed it's factorial + * \reutrn x! + */ + const double Factorial(const double x) const; - mutable std::vector m_curve; /// The ordered set of points - /// representing the curve. - FlightPlan m_knots; /// Flight plan (as in virtual knots) used to generate the curve. - size_t m_knotsN; /// Number of real knots being used to generate the curve. - float m_step; /// Step of the curve. + mutable std::vector m_curve; /// The ordered set of points + /// representing the curve. + FlightPlan m_knots; /// Flight plan (as in virtual knots) used to generate the curve. + size_t m_knotsN; /// Number of real knots being used to generate the curve. + float m_step; /// Step of the curve. }; } // namespace ns3 diff --git a/src/mobility/flight-plan.cc b/src/mobility/flight-plan.cc index 7ff41d0..f62317b 100644 --- a/src/mobility/flight-plan.cc +++ b/src/mobility/flight-plan.cc @@ -21,174 +21,167 @@ #include #include -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_HELPER_CPP (FlightPlan); +ATTRIBUTE_HELPER_CPP(FlightPlan); -FlightPlan::FlightPlan () +FlightPlan::FlightPlan() { } -FlightPlan::FlightPlan (Ptr point) +FlightPlan::FlightPlan(Ptr point) { - m_protoPoints.push_back (point); + m_protoPoints.push_back(point); } -FlightPlan::FlightPlan (const FlightPlan &a, - const FlightPlan &b) +FlightPlan::FlightPlan(const FlightPlan& a, const FlightPlan& b) { - Add (a); - Add (b); + Add(a); + Add(b); } -FlightPlan::FlightPlan (const FlightPlan &a, - const FlightPlan &b, - const FlightPlan &c) +FlightPlan::FlightPlan(const FlightPlan& a, const FlightPlan& b, const FlightPlan& c) { - Add (a); - Add (b); - Add (c); + Add(a); + Add(b); + Add(c); } -FlightPlan::FlightPlan (const FlightPlan &a, - const FlightPlan &b, - const FlightPlan &c, - const FlightPlan &d) +FlightPlan::FlightPlan(const FlightPlan& a, + const FlightPlan& b, + const FlightPlan& c, + const FlightPlan& d) { - Add (a); - Add (b); - Add (c); - Add (d); + Add(a); + Add(b); + Add(c); + Add(d); } -FlightPlan::FlightPlan (const FlightPlan &a, - const FlightPlan &b, - const FlightPlan &c, - const FlightPlan &d, - const FlightPlan &e) +FlightPlan::FlightPlan(const FlightPlan& a, + const FlightPlan& b, + const FlightPlan& c, + const FlightPlan& d, + const FlightPlan& e) { - Add (a); - Add (b); - Add (c); - Add (d); - Add (e); + Add(a); + Add(b); + Add(c); + Add(d); + Add(e); } FlightPlan::Iterator -FlightPlan::Begin () const +FlightPlan::Begin() const { - return m_protoPoints.begin (); + return m_protoPoints.begin(); } FlightPlan::Iterator -FlightPlan::End () const +FlightPlan::End() const { - return m_protoPoints.end (); + return m_protoPoints.end(); } uint32_t -FlightPlan::GetN () const +FlightPlan::GetN() const { - return m_protoPoints.size (); + return m_protoPoints.size(); } Ptr -FlightPlan::Get (const uint32_t i) const +FlightPlan::Get(const uint32_t i) const { - return m_protoPoints[i]; + return m_protoPoints[i]; } Ptr -FlightPlan::GetFront () const +FlightPlan::GetFront() const { - return m_protoPoints.front (); + return m_protoPoints.front(); } Ptr -FlightPlan::GetBack () const +FlightPlan::GetBack() const { - return m_protoPoints.back (); + return m_protoPoints.back(); } void -FlightPlan::Add (const FlightPlan other) +FlightPlan::Add(const FlightPlan other) { - for (Iterator i = other.Begin (); i != other.End (); i++) - m_protoPoints.push_back(*i); + for (Iterator i = other.Begin(); i != other.End(); i++) + m_protoPoints.push_back(*i); } void -FlightPlan::Add (const Ptr point) +FlightPlan::Add(const Ptr point) { - m_protoPoints.push_back (point); + m_protoPoints.push_back(point); } void -FlightPlan::Add (const std::string pointName) +FlightPlan::Add(const std::string pointName) { - Ptr point = Names::Find (pointName); + Ptr point = Names::Find(pointName); - m_protoPoints.push_back (point); + m_protoPoints.push_back(point); } -std::ostream & -operator<< (std::ostream &os, const FlightPlan &prototrajectory) +std::ostream& +operator<<(std::ostream& os, const FlightPlan& prototrajectory) { - os << prototrajectory.GetN () << ";"; + os << prototrajectory.GetN() << ";"; - for (auto protoPoint = prototrajectory.Begin (); - protoPoint != prototrajectory.End (); - protoPoint++) + for (auto protoPoint = prototrajectory.Begin(); protoPoint != prototrajectory.End(); + protoPoint++) { - os << (*protoPoint)->GetPosition () << "$" - << (*protoPoint)->GetInterest () << "$" - << (*protoPoint)->GetRestTime () << ";"; + os << (*protoPoint)->GetPosition() << "$" << (*protoPoint)->GetInterest() << "$" + << (*protoPoint)->GetRestTime() << ";"; } - return os; + return os; } -std::istream & -operator>> (std::istream &is, FlightPlan &prototrajectory) +std::istream& +operator>>(std::istream& is, FlightPlan& prototrajectory) { - char sepInPoint1 = '\0'; - char sepInPoint2 = '\0'; - char sepInPoint3 = '\0'; - char sepInterPoint = '\0'; + char sepInPoint1 = '\0'; + char sepInPoint2 = '\0'; + char sepInPoint3 = '\0'; + char sepInterPoint = '\0'; - uint32_t n; - Vector position; - uint32_t interest; - double restTime; + uint32_t n; + Vector position; + uint32_t interest; + double restTime; - is >> n >> sepInterPoint; - if (sepInterPoint != ';') - is.setstate (std::ios::failbit); + is >> n >> sepInterPoint; + if (sepInterPoint != ';') + is.setstate(std::ios::failbit); - for (uint32_t i = 0; i < n; i++) + for (uint32_t i = 0; i < n; i++) { - is >> position >> sepInPoint1 - >> interest >> sepInPoint2 - >> restTime >> sepInterPoint; - - if (sepInPoint1 != '$' - || sepInPoint2 != '$' - || sepInPoint3 != '$' - || sepInterPoint != ';') + is >> position >> sepInPoint1 >> interest >> sepInPoint2 >> restTime >> sepInterPoint; + + if (sepInPoint1 != '$' || sepInPoint2 != '$' || sepInPoint3 != '$' || sepInterPoint != ';') { - is.setstate (std::ios::failbit); - break; + is.setstate(std::ios::failbit); + break; } - auto protoPoint = CreateObjectWithAttributes - ("Position", VectorValue (position), - "Interest", IntegerValue (interest), - "RestTime", TimeValue (Seconds (restTime))); + auto protoPoint = CreateObjectWithAttributes("Position", + VectorValue(position), + "Interest", + IntegerValue(interest), + "RestTime", + TimeValue(Seconds(restTime))); - prototrajectory.Add (protoPoint); + prototrajectory.Add(protoPoint); } - return is; + return is; } } // namespace ns3 diff --git a/src/mobility/flight-plan.h b/src/mobility/flight-plan.h index 45cf718..0af0b70 100644 --- a/src/mobility/flight-plan.h +++ b/src/mobility/flight-plan.h @@ -18,16 +18,17 @@ #ifndef FLIGHT_PLAN_H #define FLIGHT_PLAN_H -#include -#include -#include +#include "proto-point.h" -#include #include +#include -#include "proto-point.h" +#include +#include +#include -namespace ns3 { +namespace ns3 +{ /** * \brief keep track of a set of ProtoPoint pointers. @@ -38,197 +39,189 @@ namespace ns3 { */ class FlightPlan { -public: - /// ProtoPoint Container iterator - typedef std::vector>::const_iterator Iterator; - - /** - * Create an empty FlightPlan - */ - FlightPlan (); - /** - * Create a FlightPlan with exactly one ProtoPoint which has been - * previously instantiated. This single ProtoPoint is specified by a smart - * pointer. - * - * \param point The Ptr to add to the container. - */ - FlightPlan (Ptr point); - /** - * Create a FlightPlan with exactly one point which has been - * previously instantiated and assigned a name using the Object Name Service. - * This ProtoPoint is then specified by its assigned name. - * - * \param pointName The name of the ProtoPoint Object to add to the container. - */ - //FlightPlan (std::string pointName); - /** - * Create a FlightPlan which is a concatenation of two input - * FlightPlans. - * - * \param a The first FlightPlan - * \param b The second FlightPlan - */ - FlightPlan (const FlightPlan &a, - const FlightPlan &b); - /** - * Create a FlightPlan which is a concatenation of three input - * FlightPlans. - * - * \param a The first FlightPlan - * \param b The second FlightPlan - * \param c The third FlightPlan - */ - FlightPlan (const FlightPlan &a, - const FlightPlan &b, - const FlightPlan &c); - /** - * Create a FlightPlan which is a concatenation of four input - * FlightPlans. - * - * \param a The first FlightPlan - * \param b The second FlightPlan - * \param c The third FlightPlan - * \param d The fourth FlightPlan - */ - FlightPlan (const FlightPlan &a, - const FlightPlan &b, - const FlightPlan &c, - const FlightPlan &d); - /** - * Create a FlightPlan which is a concatenation of six input - * FlightPlans. - * - * \param a The first FlightPlan - * \param b The second FlightPlan - * \param c The third FlightPlan - * \param d The fourth FlightPlan - * \param e The fifth FlightPlan - */ - FlightPlan (const FlightPlan &a, - const FlightPlan &b, - const FlightPlan &c, - const FlightPlan &d, - const FlightPlan &e); - - /** - * \brief Get an iterator which refers to the first ProtoPoint in the - * container. - * - * ProtoPoints can be retrieved from the container in two ways. First, - * directly by an index into the container, and second, using an iterator. - * This method is used in the iterator method and is typically used in a - * for-loop to run through the ProtoPoints - * - * \code - * FlightPlan::Iterator i; - * for (i = container.Begin (); i != container.End (); i++) - * { - * (*i)->method (); // some ProtoPoint method - * } - * \endcode - * - * \return an iterator which refers to the first ProtoPoint in the container. - */ - Iterator Begin () const; - /** - * \brief Get an iterator which refers to the past-the-last ProtoPoint in the - * container. - * - * ProtoPoints can be retrieved from the container in two ways. First, - * directly by an index into the container, and second, using an iterator. - * This method is used in the iterator method and is typically used in a - * for-loop to run through the ProtoPoints - * - * \code - * FlightPlan::Iterator i; - * for (i = container.Begin (); i != container.End (); i++) - * { - * (*i)->method (); // some ProtoPoint method - * } - * \endcode - * - * \return an iterator which indicates an ending condition for a loop. - */ - Iterator End () const; - - /** - * \brief Get the number of Ptr stored in this container. - * - * ProtoPoints can be retrieved from the container in two ways. First, - * directly by and index into the container, and second, using an iterator. - * This method is used in the direct method and is typically used to define an - * ending condition in a for-loop that runs through the stored ProtoPoints - * - * \code - * uint32_t nProtoPoints = container.GetN (); - * for (uint32_t i = 0; i < nProtoPoints; ++i) - * { - * Ptr p = containter.Get (i); - * i->method (); // some ProtoPoint method - * } - * \endcode - * - * \return the number of Ptr stored in this container. - */ - uint32_t GetN () const; - - /** - * \brief Get the Ptr stored in this container at a given index. - * - * ProtoPoints can be retrieved from the container in two ways. First, - * directly by and index into the container, and second, using an iterator. - * This method is used in the direct method and is typically used to define an - * ending condition in a for-loop that runs through the stored ProtoPoints - * - * \code - * uint32_t nProtoPoints = container.GetN (); - * for (uint32_t i = 0; i < nProtoPoints; ++i) - * { - * Ptr p = containter.Get (i); - * i->method (); // some ProtoPoint method - * } - * \endcode - * - * \param i the index of the requested ProtoPoint pointer. - * \return the requested ProtoPoint pointer. - */ - Ptr Get (const uint32_t i) const; - - Ptr GetFront () const; - Ptr GetBack () const; - - /** - * \brief Append the contents of another FlightPlan to the end of - * this container. - * - * \param other The FlightPlan to append. - */ - void Add (const FlightPlan other); - /** - * \brief Append a single Ptr to this container. - * - * \param point the Ptr to append. - */ - void Add (const Ptr point); - /** - * \brief Append to this container the single Ptr referred to via - * its Object Name Service registered name. - * - * \param pointName The name of the ProtoPoint Object to add to the container. - */ - void Add (const std::string pointName); - -private: - std::vector> m_protoPoints; //!< ProtoPoints smart pointers + public: + /// ProtoPoint Container iterator + typedef std::vector>::const_iterator Iterator; + + /** + * Create an empty FlightPlan + */ + FlightPlan(); + /** + * Create a FlightPlan with exactly one ProtoPoint which has been + * previously instantiated. This single ProtoPoint is specified by a smart + * pointer. + * + * \param point The Ptr to add to the container. + */ + FlightPlan(Ptr point); + /** + * Create a FlightPlan with exactly one point which has been + * previously instantiated and assigned a name using the Object Name Service. + * This ProtoPoint is then specified by its assigned name. + * + * \param pointName The name of the ProtoPoint Object to add to the container. + */ + // FlightPlan (std::string pointName); + /** + * Create a FlightPlan which is a concatenation of two input + * FlightPlans. + * + * \param a The first FlightPlan + * \param b The second FlightPlan + */ + FlightPlan(const FlightPlan& a, const FlightPlan& b); + /** + * Create a FlightPlan which is a concatenation of three input + * FlightPlans. + * + * \param a The first FlightPlan + * \param b The second FlightPlan + * \param c The third FlightPlan + */ + FlightPlan(const FlightPlan& a, const FlightPlan& b, const FlightPlan& c); + /** + * Create a FlightPlan which is a concatenation of four input + * FlightPlans. + * + * \param a The first FlightPlan + * \param b The second FlightPlan + * \param c The third FlightPlan + * \param d The fourth FlightPlan + */ + FlightPlan(const FlightPlan& a, const FlightPlan& b, const FlightPlan& c, const FlightPlan& d); + /** + * Create a FlightPlan which is a concatenation of six input + * FlightPlans. + * + * \param a The first FlightPlan + * \param b The second FlightPlan + * \param c The third FlightPlan + * \param d The fourth FlightPlan + * \param e The fifth FlightPlan + */ + FlightPlan(const FlightPlan& a, + const FlightPlan& b, + const FlightPlan& c, + const FlightPlan& d, + const FlightPlan& e); + + /** + * \brief Get an iterator which refers to the first ProtoPoint in the + * container. + * + * ProtoPoints can be retrieved from the container in two ways. First, + * directly by an index into the container, and second, using an iterator. + * This method is used in the iterator method and is typically used in a + * for-loop to run through the ProtoPoints + * + * \code + * FlightPlan::Iterator i; + * for (i = container.Begin (); i != container.End (); i++) + * { + * (*i)->method (); // some ProtoPoint method + * } + * \endcode + * + * \return an iterator which refers to the first ProtoPoint in the container. + */ + Iterator Begin() const; + /** + * \brief Get an iterator which refers to the past-the-last ProtoPoint in the + * container. + * + * ProtoPoints can be retrieved from the container in two ways. First, + * directly by an index into the container, and second, using an iterator. + * This method is used in the iterator method and is typically used in a + * for-loop to run through the ProtoPoints + * + * \code + * FlightPlan::Iterator i; + * for (i = container.Begin (); i != container.End (); i++) + * { + * (*i)->method (); // some ProtoPoint method + * } + * \endcode + * + * \return an iterator which indicates an ending condition for a loop. + */ + Iterator End() const; + + /** + * \brief Get the number of Ptr stored in this container. + * + * ProtoPoints can be retrieved from the container in two ways. First, + * directly by and index into the container, and second, using an iterator. + * This method is used in the direct method and is typically used to define an + * ending condition in a for-loop that runs through the stored ProtoPoints + * + * \code + * uint32_t nProtoPoints = container.GetN (); + * for (uint32_t i = 0; i < nProtoPoints; ++i) + * { + * Ptr p = containter.Get (i); + * i->method (); // some ProtoPoint method + * } + * \endcode + * + * \return the number of Ptr stored in this container. + */ + uint32_t GetN() const; + + /** + * \brief Get the Ptr stored in this container at a given index. + * + * ProtoPoints can be retrieved from the container in two ways. First, + * directly by and index into the container, and second, using an iterator. + * This method is used in the direct method and is typically used to define an + * ending condition in a for-loop that runs through the stored ProtoPoints + * + * \code + * uint32_t nProtoPoints = container.GetN (); + * for (uint32_t i = 0; i < nProtoPoints; ++i) + * { + * Ptr p = containter.Get (i); + * i->method (); // some ProtoPoint method + * } + * \endcode + * + * \param i the index of the requested ProtoPoint pointer. + * \return the requested ProtoPoint pointer. + */ + Ptr Get(const uint32_t i) const; + + Ptr GetFront() const; + Ptr GetBack() const; + + /** + * \brief Append the contents of another FlightPlan to the end of + * this container. + * + * \param other The FlightPlan to append. + */ + void Add(const FlightPlan other); + /** + * \brief Append a single Ptr to this container. + * + * \param point the Ptr to append. + */ + void Add(const Ptr point); + /** + * \brief Append to this container the single Ptr referred to via + * its Object Name Service registered name. + * + * \param pointName The name of the ProtoPoint Object to add to the container. + */ + void Add(const std::string pointName); + + private: + std::vector> m_protoPoints; //!< ProtoPoints smart pointers }; -ATTRIBUTE_HELPER_HEADER (FlightPlan); +ATTRIBUTE_HELPER_HEADER(FlightPlan); -std::ostream & operator<< (std::ostream &os, - const FlightPlan &prototrajectory); -std::istream & operator>> (std::istream &is, - FlightPlan &prototrajectory); +std::ostream& operator<<(std::ostream& os, const FlightPlan& prototrajectory); +std::istream& operator>>(std::istream& is, FlightPlan& prototrajectory); } // namespace ns3 diff --git a/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.cc b/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.cc index 66bb2a9..affb99d 100644 --- a/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.cc +++ b/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.cc @@ -17,131 +17,137 @@ */ #include "parametric-speed-drone-mobility-model.h" +#include #include #include #include #include -#include - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ParametricSpeedDroneMobilityModel"); -NS_OBJECT_ENSURE_REGISTERED (ParametricSpeedDroneMobilityModel); +NS_LOG_COMPONENT_DEFINE("ParametricSpeedDroneMobilityModel"); +NS_OBJECT_ENSURE_REGISTERED(ParametricSpeedDroneMobilityModel); TypeId -ParametricSpeedDroneMobilityModel::GetTypeId () +ParametricSpeedDroneMobilityModel::GetTypeId() { - NS_LOG_FUNCTION_NOARGS (); - - static TypeId tid = TypeId ("ns3::ParametricSpeedDroneMobilityModel") - .SetParent () - .SetGroupName ("Mobility") - .AddConstructor () - .AddAttribute ("SpeedCoefficients", "Coefficients to construct speed curve.", - DoubleVectorValue (), - MakeDoubleVectorAccessor (&ParametricSpeedDroneMobilityModel::SetSpeedCoefficients), - MakeDoubleVectorChecker ()) - .AddAttribute ("FlightPlan", "The ideal trajectory that the drone should run across.", - FlightPlanValue (), - MakeFlightPlanAccessor (&ParametricSpeedDroneMobilityModel::m_flightPlan), - MakeFlightPlanChecker ()) - .AddAttribute ("CurveStep", "The step of the curve to generate. Lower step means more points generated, hence higher resolution.", - DoubleValue (0.001), - MakeDoubleAccessor (&ParametricSpeedDroneMobilityModel::m_curveStep), - MakeDoubleChecker ()) - ; - - return tid; + NS_LOG_FUNCTION_NOARGS(); + + static TypeId tid = + TypeId("ns3::ParametricSpeedDroneMobilityModel") + .SetParent() + .SetGroupName("Mobility") + .AddConstructor() + .AddAttribute( + "SpeedCoefficients", + "Coefficients to construct speed curve.", + DoubleVectorValue(), + MakeDoubleVectorAccessor(&ParametricSpeedDroneMobilityModel::SetSpeedCoefficients), + MakeDoubleVectorChecker()) + .AddAttribute("FlightPlan", + "The ideal trajectory that the drone should run across.", + FlightPlanValue(), + MakeFlightPlanAccessor(&ParametricSpeedDroneMobilityModel::m_flightPlan), + MakeFlightPlanChecker()) + .AddAttribute("CurveStep", + "The step of the curve to generate. Lower step means more points " + "generated, hence higher resolution.", + DoubleValue(0.001), + MakeDoubleAccessor(&ParametricSpeedDroneMobilityModel::m_curveStep), + MakeDoubleChecker()); + + return tid; } -ParametricSpeedDroneMobilityModel::ParametricSpeedDroneMobilityModel () : - m_flightParams {{}}, - m_lastUpdate {-1} +ParametricSpeedDroneMobilityModel::ParametricSpeedDroneMobilityModel() + : m_flightParams{{}}, + m_lastUpdate{-1} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ParametricSpeedDroneMobilityModel::~ParametricSpeedDroneMobilityModel () +ParametricSpeedDroneMobilityModel::~ParametricSpeedDroneMobilityModel() { } void -ParametricSpeedDroneMobilityModel::Update () const +ParametricSpeedDroneMobilityModel::Update() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - const Time t = Simulator::Now (); - if (t.Compare (m_lastUpdate) <= 0) + const Time t = Simulator::Now(); + if (t.Compare(m_lastUpdate) <= 0) { - NS_LOG_LOGIC ("Update is being suppressed."); - return; + NS_LOG_LOGIC("Update is being suppressed."); + return; } - m_lastUpdate = t; + m_lastUpdate = t; - m_planner.Update (t); - m_position = m_planner.GetPosition (); - m_velocity = m_planner.GetVelocity (); + m_planner.Update(t); + m_position = m_planner.GetPosition(); + m_velocity = m_planner.GetVelocity(); - NotifyCourseChange (); + NotifyCourseChange(); } Vector -ParametricSpeedDroneMobilityModel::DoGetPosition () const +ParametricSpeedDroneMobilityModel::DoGetPosition() const { - NS_LOG_FUNCTION (this); - NS_LOG_LOGIC ("position: " << m_position); + NS_LOG_FUNCTION(this); + NS_LOG_LOGIC("position: " << m_position); - Update (); - return m_position; + Update(); + return m_position; } void -ParametricSpeedDroneMobilityModel::DoSetPosition (const Vector &position) +ParametricSpeedDroneMobilityModel::DoSetPosition(const Vector& position) { - NS_LOG_FUNCTION (position); + NS_LOG_FUNCTION(position); - m_position = position; + m_position = position; } Vector -ParametricSpeedDroneMobilityModel::DoGetVelocity () const +ParametricSpeedDroneMobilityModel::DoGetVelocity() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - Update (); + Update(); - NS_LOG_LOGIC ("velocity: " << m_velocity); - return m_velocity; + NS_LOG_LOGIC("velocity: " << m_velocity); + return m_velocity; } void -ParametricSpeedDroneMobilityModel::DoInitialize () +ParametricSpeedDroneMobilityModel::DoInitialize() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_planner = Planner - (m_flightPlan, m_flightParams, m_curveStep); + m_planner = Planner(m_flightPlan, + m_flightParams, + m_curveStep); - MobilityModel::DoInitialize (); + MobilityModel::DoInitialize(); } void -ParametricSpeedDroneMobilityModel::DoDispose () +ParametricSpeedDroneMobilityModel::DoDispose() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - MobilityModel::DoDispose (); + MobilityModel::DoDispose(); } void -ParametricSpeedDroneMobilityModel::SetSpeedCoefficients (const DoubleVector &a) +ParametricSpeedDroneMobilityModel::SetSpeedCoefficients(const DoubleVector& a) { - NS_LOG_FUNCTION (this << a); + NS_LOG_FUNCTION(this << a); - for (auto c = a.Begin (); c != a.End (); c++) - m_flightParams.Add (*c); + for (auto c = a.Begin(); c != a.End(); c++) + m_flightParams.Add(*c); } -} // ns3 namespace +} // namespace ns3 diff --git a/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.h b/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.h index 9770b64..715aa29 100644 --- a/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.h +++ b/src/mobility/parametric-speed/parametric-speed-drone-mobility-model.h @@ -18,55 +18,56 @@ #ifndef PARAMETRIC_SPEED_DRONE_MOBILITY_MODEL_H #define PARAMETRIC_SPEED_DRONE_MOBILITY_MODEL_H -#include -#include +#include "parametric-speed-flight.h" +#include "parametric-speed-param.h" #include #include +#include #include #include +#include -#include "parametric-speed-flight.h" -#include "parametric-speed-param.h" - -namespace ns3 { +namespace ns3 +{ class ParametricSpeedDroneMobilityModel : public MobilityModel { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + ParametricSpeedDroneMobilityModel(); + ~ParametricSpeedDroneMobilityModel(); - ParametricSpeedDroneMobilityModel (); - ~ParametricSpeedDroneMobilityModel (); + private: + virtual void DoInitialize(); + virtual void DoDispose(); -private: - virtual void DoInitialize (); - virtual void DoDispose (); + virtual void Update() const; + virtual void DoSetPosition(const Vector& position); + virtual Vector DoGetPosition() const; + virtual Vector DoGetVelocity() const; - virtual void Update () const; - virtual void DoSetPosition (const Vector &position); - virtual Vector DoGetPosition () const; - virtual Vector DoGetVelocity () const; + void SetSpeedCoefficients(const DoubleVector& a); - void SetSpeedCoefficients (const DoubleVector &a); -protected: - mutable Vector m_position; - mutable Vector m_velocity; + protected: + mutable Vector m_position; + mutable Vector m_velocity; - double m_acceleration; - double m_maxSpeed; + double m_acceleration; + double m_maxSpeed; - FlightPlan m_flightPlan; - ParametricSpeedParam m_flightParams; - Planner m_planner; + FlightPlan m_flightPlan; + ParametricSpeedParam m_flightParams; + Planner m_planner; - mutable Time m_lastUpdate; + mutable Time m_lastUpdate; - float m_curveStep; + float m_curveStep; }; } // namespace ns3 diff --git a/src/mobility/parametric-speed/parametric-speed-flight.cc b/src/mobility/parametric-speed/parametric-speed-flight.cc index cc71961..75f0b33 100644 --- a/src/mobility/parametric-speed/parametric-speed-flight.cc +++ b/src/mobility/parametric-speed/parametric-speed-flight.cc @@ -17,315 +17,308 @@ */ #include "parametric-speed-flight.h" -#include - -#include - #include #include +#include #include #include #include #include +#include -namespace ns3 { +namespace ns3 +{ class PrivFuncParams { -public: - PrivFuncParams (std::vector coeffs, - std::vector coeffsDeriv); - PrivFuncParams (std::vector coeffs); - ~PrivFuncParams (); - - std::vector GetCoeffs (); - std::vector GetCoeffsDeriv (); - -private: - std::vector m_coeffs; - std::vector m_coeffsDeriv; + public: + PrivFuncParams(std::vector coeffs, std::vector coeffsDeriv); + PrivFuncParams(std::vector coeffs); + ~PrivFuncParams(); + + std::vector GetCoeffs(); + std::vector GetCoeffsDeriv(); + + private: + std::vector m_coeffs; + std::vector m_coeffsDeriv; }; -NS_LOG_COMPONENT_DEFINE ("ParametricSpeedFlight"); +NS_LOG_COMPONENT_DEFINE("ParametricSpeedFlight"); -ParametricSpeedFlight::ParametricSpeedFlight (FlightPlan flightPlan, - ParametricSpeedParam speedParams, - double step) : - Curve (flightPlan, step), - m_speedParams {speedParams.GetSpeedCoefficients ()}, - m_isHovering {flightPlan.GetN () == 1} +ParametricSpeedFlight::ParametricSpeedFlight(FlightPlan flightPlan, + ParametricSpeedParam speedParams, + double step) + : Curve(flightPlan, step), + m_speedParams{speedParams.GetSpeedCoefficients()}, + m_isHovering{flightPlan.GetN() == 1} { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - Generate (); + Generate(); } -ParametricSpeedFlight::~ParametricSpeedFlight () +ParametricSpeedFlight::~ParametricSpeedFlight() { } void -ParametricSpeedFlight::Generate () +ParametricSpeedFlight::Generate() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - if (m_isHovering) + if (m_isHovering) { - // this is a dummy flight plan to hover on a specific point. - m_length = 0; - m_currentVelocity = Vector3D (); - m_time = m_knots.GetBack ()->GetRestTime (); + // this is a dummy flight plan to hover on a specific point. + m_length = 0; + m_currentVelocity = Vector3D(); + m_time = m_knots.GetBack()->GetRestTime(); } - else + else { - m_length = Curve::Generate (); - m_currentPositionPtr = m_curve.begin (); - m_time = Seconds (FindTime ()); + m_length = Curve::Generate(); + m_currentPositionPtr = m_curve.begin(); + m_time = Seconds(FindTime()); - NS_LOG_LOGIC ("Drone will take " << m_time << " to traverse the path."); + NS_LOG_LOGIC("Drone will take " << m_time << " to traverse the path."); } - m_currentPosition = CurvePoint (m_knots.GetFront ()->GetPosition ()); + m_currentPosition = CurvePoint(m_knots.GetFront()->GetPosition()); } void -ParametricSpeedFlight::Update (const double &t) const +ParametricSpeedFlight::Update(const double& t) const { - NS_LOG_FUNCTION (t); + NS_LOG_FUNCTION(t); - if (!m_isHovering) + if (!m_isHovering) { - UpdateSpeed (t); - UpdateDistance (t); - UpdatePosition (); - UpdateVelocity (); + UpdateSpeed(t); + UpdateDistance(t); + UpdatePosition(); + UpdateVelocity(); - NS_LOG_LOGIC ("t: " << t << " speed: " << m_currentSpeed - << " dist: " << m_currentDistance); + NS_LOG_LOGIC("t: " << t << " speed: " << m_currentSpeed << " dist: " << m_currentDistance); } } Time -ParametricSpeedFlight::GetTime () const +ParametricSpeedFlight::GetTime() const { - return m_time; + return m_time; } Vector -ParametricSpeedFlight::GetPosition () const +ParametricSpeedFlight::GetPosition() const { - return m_currentPosition.GetPosition (); + return m_currentPosition.GetPosition(); } Vector -ParametricSpeedFlight::GetVelocity () const +ParametricSpeedFlight::GetVelocity() const { - return m_currentVelocity; + return m_currentVelocity; } void -ParametricSpeedFlight::UpdateSpeed (const double &t) const +ParametricSpeedFlight::UpdateSpeed(const double& t) const { - double speed = 0.0; - const uint32_t order = m_speedParams.size (); + double speed = 0.0; + const uint32_t order = m_speedParams.size(); - for (uint32_t i = 0; i < order; i++) - speed += m_speedParams[i] * std::pow (t, order - i - 1); + for (uint32_t i = 0; i < order; i++) + speed += m_speedParams[i] * std::pow(t, order - i - 1); - m_currentSpeed = speed; + m_currentSpeed = speed; } void -ParametricSpeedFlight::UpdateDistance (const double &t) const +ParametricSpeedFlight::UpdateDistance(const double& t) const { - // analytic polynomial integration - double distance = 0.0; - const uint32_t orderp1 = m_speedParams.size (); // order of the polynomial, plus 1 + // analytic polynomial integration + double distance = 0.0; + const uint32_t orderp1 = m_speedParams.size(); // order of the polynomial, plus 1 - for (uint32_t i = 0; i < orderp1; i++) - distance += m_speedParams[i] / (i + 1) * std::pow (t, i + 1); + for (uint32_t i = 0; i < orderp1; i++) + distance += m_speedParams[i] / (i + 1) * std::pow(t, i + 1); - m_currentDistance = distance; + m_currentDistance = distance; } void -ParametricSpeedFlight::UpdatePosition () const +ParametricSpeedFlight::UpdatePosition() const { - NS_LOG_FUNCTION_NOARGS (); - NS_LOG_LOGIC ("old pos vector: " << m_currentPosition.GetPosition ()); - m_pastPosition = m_currentPosition; + NS_LOG_FUNCTION_NOARGS(); + NS_LOG_LOGIC("old pos vector: " << m_currentPosition.GetPosition()); + m_pastPosition = m_currentPosition; - for (auto i = m_curve.begin (); i != m_curve.end (); i++) + for (auto i = m_curve.begin(); i != m_curve.end(); i++) { - if ((*i).GetAbsoluteDistance () > m_currentDistance) + if ((*i).GetAbsoluteDistance() > m_currentDistance) { - m_currentPosition = (*i); - m_currentPositionPtr = i; - break; + m_currentPosition = (*i); + m_currentPositionPtr = i; + break; } } - NS_LOG_LOGIC ("new pos vector: " << m_currentPosition.GetPosition ()); + NS_LOG_LOGIC("new pos vector: " << m_currentPosition.GetPosition()); } void -ParametricSpeedFlight::UpdateVelocity () const +ParametricSpeedFlight::UpdateVelocity() const { - NS_LOG_FUNCTION_NOARGS (); - NS_LOG_LOGIC ("old vel: " << m_currentVelocity); + NS_LOG_FUNCTION_NOARGS(); + NS_LOG_LOGIC("old vel: " << m_currentVelocity); - const Vector relativeDistance = m_currentPosition.GetRelativeDistanceVector (m_pastPosition); - const double relativeDistScalar = m_currentPosition.GetRelativeDistance (m_pastPosition); + const Vector relativeDistance = m_currentPosition.GetRelativeDistanceVector(m_pastPosition); + const double relativeDistScalar = m_currentPosition.GetRelativeDistance(m_pastPosition); - if (relativeDistScalar == 0.0) - return; + if (relativeDistScalar == 0.0) + return; - const double velX = (relativeDistance.x != 0) - ? (relativeDistance.x / relativeDistScalar) * m_currentSpeed - : 0; - const double velY = (relativeDistance.y != 0) - ? (relativeDistance.y / relativeDistScalar) * m_currentSpeed - : 0; - const double velZ = (relativeDistance.z != 0) - ? (relativeDistance.z / relativeDistScalar) * m_currentSpeed - : 0; + const double velX = + (relativeDistance.x != 0) ? (relativeDistance.x / relativeDistScalar) * m_currentSpeed : 0; + const double velY = + (relativeDistance.y != 0) ? (relativeDistance.y / relativeDistScalar) * m_currentSpeed : 0; + const double velZ = + (relativeDistance.z != 0) ? (relativeDistance.z / relativeDistScalar) * m_currentSpeed : 0; - NS_LOG_LOGIC ("relative distance: " << relativeDistance - << "; current speed: " << m_currentSpeed); + NS_LOG_LOGIC("relative distance: " << relativeDistance + << "; current speed: " << m_currentSpeed); - m_currentVelocity = {velX, velY, velZ}; + m_currentVelocity = {velX, velY, velZ}; - NS_LOG_LOGIC ("new vel: " << m_currentVelocity); + NS_LOG_LOGIC("new vel: " << m_currentVelocity); } double -Quadratic (double x, void *params) +Quadratic(double x, void* params) { - std::vector coeffs = ((PrivFuncParams *) params)->GetCoeffs (); - uint32_t order = coeffs.size () - 1; - double y = 0; + std::vector coeffs = ((PrivFuncParams*)params)->GetCoeffs(); + uint32_t order = coeffs.size() - 1; + double y = 0; - for (uint32_t i = 0; i < coeffs.size (); i++) - y += coeffs[i] * std::pow (x, order - i); + for (uint32_t i = 0; i < coeffs.size(); i++) + y += coeffs[i] * std::pow(x, order - i); - return y; + return y; } double -QuadraticDeriv (double x, void *params) +QuadraticDeriv(double x, void* params) { - std::vector coeffs = ((PrivFuncParams *) params)->GetCoeffsDeriv (); - uint32_t order = coeffs.size () - 1; - double y = 0; + std::vector coeffs = ((PrivFuncParams*)params)->GetCoeffsDeriv(); + uint32_t order = coeffs.size() - 1; + double y = 0; - for (uint32_t i = 0; i < coeffs.size (); i++) - y += coeffs[i] * std::pow (x, order - i); + for (uint32_t i = 0; i < coeffs.size(); i++) + y += coeffs[i] * std::pow(x, order - i); - return y; + return y; } void -QuadraticFdf (double x, void *params, double *y, double *dy) +QuadraticFdf(double x, void* params, double* y, double* dy) { - *y = Quadratic (x, params); - *dy = QuadraticDeriv (x, params); + *y = Quadratic(x, params); + *dy = QuadraticDeriv(x, params); } const double -ParametricSpeedFlight::FindTime () const +ParametricSpeedFlight::FindTime() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - // skip a rather heavy elaboration if length is zero - if (m_length == 0.0) - return 0.0; + // skip a rather heavy elaboration if length is zero + if (m_length == 0.0) + return 0.0; - uint32_t order = m_speedParams.size (); + uint32_t order = m_speedParams.size(); - // analytic polynomial integration - std::vector coeffs = m_speedParams; - for (uint32_t i = 0; i < order; i++) + // analytic polynomial integration + std::vector coeffs = m_speedParams; + for (uint32_t i = 0; i < order; i++) { - coeffs[i] /= order - i; + coeffs[i] /= order - i; } - coeffs.push_back (-m_length); + coeffs.push_back(-m_length); - NS_LOG_LOGIC ("Length: " << m_length); + NS_LOG_LOGIC("Length: " << m_length); - /* setup GSL */ - int status; - int iter = 0, max_iter = 1000; - const gsl_root_fdfsolver_type *T; - gsl_root_fdfsolver *s; - double x0, x = m_length; // x will be our root - gsl_function_fdf FDF; - PrivFuncParams params (coeffs, m_speedParams); + /* setup GSL */ + int status; + int iter = 0, max_iter = 1000; + const gsl_root_fdfsolver_type* T; + gsl_root_fdfsolver* s; + double x0, x = m_length; // x will be our root + gsl_function_fdf FDF; + PrivFuncParams params(coeffs, m_speedParams); - FDF.f = &Quadratic; - FDF.df = &QuadraticDeriv; - FDF.fdf = &QuadraticFdf; - FDF.params = ¶ms; + FDF.f = &Quadratic; + FDF.df = &QuadraticDeriv; + FDF.fdf = &QuadraticFdf; + FDF.params = ¶ms; - T = gsl_root_fdfsolver_newton; - s = gsl_root_fdfsolver_alloc (T); - gsl_root_fdfsolver_set (s, &FDF, x); + T = gsl_root_fdfsolver_newton; + s = gsl_root_fdfsolver_alloc(T); + gsl_root_fdfsolver_set(s, &FDF, x); - NS_LOG_LOGIC ("Using " << gsl_root_fdfsolver_name (s) << " method."); - NS_LOG_LOGIC ("iter\t root"); + NS_LOG_LOGIC("Using " << gsl_root_fdfsolver_name(s) << " method."); + NS_LOG_LOGIC("iter\t root"); - do + do { - iter++; - status = gsl_root_fdfsolver_iterate (s); - if (status != GSL_SUCCESS) - NS_LOG_ERROR ("GSL Encountered and error when applying the Newton-Raphson method. Error code: " << status); + iter++; + status = gsl_root_fdfsolver_iterate(s); + if (status != GSL_SUCCESS) + NS_LOG_ERROR( + "GSL Encountered and error when applying the Newton-Raphson method. Error code: " + << status); - x0 = x; - x = gsl_root_fdfsolver_root (s); - status = gsl_root_test_delta (x, x0, 0, 1e-3); + x0 = x; + x = gsl_root_fdfsolver_root(s); + status = gsl_root_test_delta(x, x0, 0, 1e-3); - if (status == GSL_SUCCESS) - NS_LOG_LOGIC ("Converged:"); + if (status == GSL_SUCCESS) + NS_LOG_LOGIC("Converged:"); - NS_LOG_LOGIC (std::fixed << std::setw (4) << iter << "\t" - << std::fixed << std::setw (10) << std::setprecision (7) << x); - } - while (status == GSL_CONTINUE && iter < max_iter); + NS_LOG_LOGIC(std::fixed << std::setw(4) << iter << "\t" << std::fixed << std::setw(10) + << std::setprecision(7) << x); + } while (status == GSL_CONTINUE && iter < max_iter); - gsl_root_fdfsolver_free (s); + gsl_root_fdfsolver_free(s); - return std::abs(x); + return std::abs(x); } -PrivFuncParams::PrivFuncParams (std::vector coeffs, - std::vector coeffsDeriv) : - m_coeffs {coeffs}, - m_coeffsDeriv {coeffsDeriv} +PrivFuncParams::PrivFuncParams(std::vector coeffs, std::vector coeffsDeriv) + : m_coeffs{coeffs}, + m_coeffsDeriv{coeffsDeriv} { } - -PrivFuncParams::PrivFuncParams (std::vector coeffs) : - m_coeffs {coeffs}, - m_coeffsDeriv {} +PrivFuncParams::PrivFuncParams(std::vector coeffs) + : m_coeffs{coeffs}, + m_coeffsDeriv{} { } -PrivFuncParams::~PrivFuncParams () +PrivFuncParams::~PrivFuncParams() { } std::vector -PrivFuncParams::GetCoeffs () +PrivFuncParams::GetCoeffs() { - return m_coeffs; + return m_coeffs; } std::vector -PrivFuncParams::GetCoeffsDeriv () +PrivFuncParams::GetCoeffsDeriv() { - return m_coeffsDeriv; + return m_coeffsDeriv; } } // namespace ns3 diff --git a/src/mobility/parametric-speed/parametric-speed-flight.h b/src/mobility/parametric-speed/parametric-speed-flight.h index 6ecc840..b334566 100644 --- a/src/mobility/parametric-speed/parametric-speed-flight.h +++ b/src/mobility/parametric-speed/parametric-speed-flight.h @@ -18,59 +18,59 @@ #ifndef PARAMETRIC_SPEED_FLIGHT_H #define PARAMETRIC_SPEED_FLIGHT_H -#include - #include "parametric-speed-param.h" -namespace ns3 { +#include + +namespace ns3 +{ /** - * Handle a partial curvilinear trajectory between two rest points (i.e., Interest Points with I. Level set to 0). + * Handle a partial curvilinear trajectory between two rest points (i.e., Interest Points with I. + * Level set to 0). */ class ParametricSpeedFlight : public Curve { -public: - /** - * Default constructor - * - * \param flightPlan The Flight Plan to construct the flight path. - * \param speedParameters The coefficients to model the speed of the drone. - */ - ParametricSpeedFlight (FlightPlan flightPlan, - ParametricSpeedParam speedParams, - double step); - /** - * default destructor - */ - virtual ~ParametricSpeedFlight (); + public: + /** + * Default constructor + * + * \param flightPlan The Flight Plan to construct the flight path. + * \param speedParameters The coefficients to model the speed of the drone. + */ + ParametricSpeedFlight(FlightPlan flightPlan, ParametricSpeedParam speedParams, double step); + /** + * default destructor + */ + virtual ~ParametricSpeedFlight(); - void Generate (); - void Update (const double &time) const; + void Generate(); + void Update(const double& time) const; - Time GetTime () const; - Vector GetPosition () const; - Vector GetVelocity () const; + Time GetTime() const; + Vector GetPosition() const; + Vector GetVelocity() const; -protected: - void UpdateDistance (const double &time) const; - void UpdateSpeed (const double &time) const; - void UpdatePosition () const; - void UpdateVelocity () const; - const double FindTime () const; + protected: + void UpdateDistance(const double& time) const; + void UpdateSpeed(const double& time) const; + void UpdatePosition() const; + void UpdateVelocity() const; + const double FindTime() const; - mutable CurvePoint m_currentPosition; - mutable Curve::Iterator m_currentPositionPtr; - mutable CurvePoint m_pastPosition; - mutable double m_currentDistance; + mutable CurvePoint m_currentPosition; + mutable Curve::Iterator m_currentPositionPtr; + mutable CurvePoint m_pastPosition; + mutable double m_currentDistance; - mutable Vector m_currentVelocity; - mutable double m_currentSpeed; + mutable Vector m_currentVelocity; + mutable double m_currentSpeed; - double m_length; /// Total length of the flight path - Time m_time; /// Total time the drone would take to complete it + double m_length; /// Total length of the flight path + Time m_time; /// Total time the drone would take to complete it - std::vector m_speedParams; - bool m_isHovering; + std::vector m_speedParams; + bool m_isHovering; }; } // namespace ns3 diff --git a/src/mobility/parametric-speed/parametric-speed-param.cc b/src/mobility/parametric-speed/parametric-speed-param.cc index dc4c187..2bab9b7 100644 --- a/src/mobility/parametric-speed/parametric-speed-param.cc +++ b/src/mobility/parametric-speed/parametric-speed-param.cc @@ -17,27 +17,28 @@ */ #include "parametric-speed-param.h" -namespace ns3 { +namespace ns3 +{ -ParametricSpeedParam::ParametricSpeedParam (std::vector speedCoefficients) : - m_speedCoefficients {speedCoefficients} +ParametricSpeedParam::ParametricSpeedParam(std::vector speedCoefficients) + : m_speedCoefficients{speedCoefficients} { } -ParametricSpeedParam::~ParametricSpeedParam () +ParametricSpeedParam::~ParametricSpeedParam() { } const std::vector -ParametricSpeedParam::GetSpeedCoefficients () const +ParametricSpeedParam::GetSpeedCoefficients() const { - return m_speedCoefficients; + return m_speedCoefficients; } void -ParametricSpeedParam::Add (double c) +ParametricSpeedParam::Add(double c) { - m_speedCoefficients.push_back (c); + m_speedCoefficients.push_back(c); } } // namespace ns3 diff --git a/src/mobility/parametric-speed/parametric-speed-param.h b/src/mobility/parametric-speed/parametric-speed-param.h index 41921d6..6d2a95e 100644 --- a/src/mobility/parametric-speed/parametric-speed-param.h +++ b/src/mobility/parametric-speed/parametric-speed-param.h @@ -20,20 +20,21 @@ #include -namespace ns3 { +namespace ns3 +{ class ParametricSpeedParam { -public: - ParametricSpeedParam (std::vector speedCoefficients); - virtual ~ParametricSpeedParam (); + public: + ParametricSpeedParam(std::vector speedCoefficients); + virtual ~ParametricSpeedParam(); - const std::vector GetSpeedCoefficients () const; + const std::vector GetSpeedCoefficients() const; - void Add (double coefficient); + void Add(double coefficient); -private: - std::vector m_speedCoefficients; + private: + std::vector m_speedCoefficients; }; } // namespace ns3 diff --git a/src/mobility/planner.cc b/src/mobility/planner.cc index 7bff5b5..a896851 100644 --- a/src/mobility/planner.cc +++ b/src/mobility/planner.cc @@ -17,69 +17,65 @@ */ #include "planner.h" -#include - #include #include +#include #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE_MASK ("Planner", LOG_PREFIX_ALL); +NS_LOG_COMPONENT_DEFINE_MASK("Planner", LOG_PREFIX_ALL); -template -Planner::Planner () +template +Planner::Planner() { } -template -Planner::Planner (FlightPlan flightPlan, - FlightParam flightParam, - float step) : - m_step {step}, - m_flightParams {flightParam} +template +Planner::Planner(FlightPlan flightPlan, + FlightParam flightParam, + float step) + : m_step{step}, + m_flightParams{flightParam} { - for (auto point = flightPlan.Begin (); point != flightPlan.End (); point++) + for (auto point = flightPlan.Begin(); point != flightPlan.End(); point++) { - if ((*point)->GetInterest () == 0) + if ((*point)->GetInterest() == 0) { - if (!m_flightPlans.empty ()) + if (!m_flightPlans.empty()) { - m_flightPlans.back ().Add (*point); + m_flightPlans.back().Add(*point); } - m_flightPlans.push_back (FlightPlan (*point)); // Flight Plan to hover on the point - m_flightPlans.push_back (FlightPlan ()); + m_flightPlans.push_back(FlightPlan(*point)); // Flight Plan to hover on the point + m_flightPlans.push_back(FlightPlan()); } - m_flightPlans.back ().Add (*point); + m_flightPlans.back().Add(*point); } - for (auto flightPlan : m_flightPlans) + for (auto flightPlan : m_flightPlans) { - // push new trajectory - m_flights.push_back (FlightType (flightPlan, - flightParam, - step)); - // estimate timeWindow - const Time time = m_flights.back ().GetTime (); - const Time startTime = (m_timeWindows.size () == 0) - ? Seconds (0) - : m_timeWindows.back ().second; - - m_timeWindows.push_back ({startTime, - startTime + time}); - - NS_LOG_LOGIC ("Added flight " << flightPlan); - NS_LOG_LOGIC ("TimeWindow: start at " << startTime << " for " << time); + // push new trajectory + m_flights.push_back(FlightType(flightPlan, flightParam, step)); + // estimate timeWindow + const Time time = m_flights.back().GetTime(); + const Time startTime = + (m_timeWindows.size() == 0) ? Seconds(0) : m_timeWindows.back().second; + + m_timeWindows.push_back({startTime, startTime + time}); + + NS_LOG_LOGIC("Added flight " << flightPlan); + NS_LOG_LOGIC("TimeWindow: start at " << startTime << " for " << time); } - NS_LOG_LOGIC ("Summary TimeWindow: " << m_timeWindows.size ()); - for (auto tw : m_timeWindows) - NS_LOG_LOGIC (" #: " << tw.first << "; " << tw.second); + NS_LOG_LOGIC("Summary TimeWindow: " << m_timeWindows.size()); + for (auto tw : m_timeWindows) + NS_LOG_LOGIC(" #: " << tw.first << "; " << tw.second); } -template -Planner::~Planner () +template +Planner::~Planner() { } @@ -87,64 +83,63 @@ Planner::~Planner () * Find and update the Trip corresponding to the correct timeWindow, * otherwise do not update **/ -template +template void -Planner::Update (const Time time) const +Planner::Update(const Time time) const { - NS_LOG_FUNCTION (time); + NS_LOG_FUNCTION(time); - const auto flightIndex = GetTimeWindow (time); - if (flightIndex == -1) + const auto flightIndex = GetTimeWindow(time); + if (flightIndex == -1) { - NS_LOG_WARN ("flightIndex got -1 from GetTimeWindow (" << time << ")"); - return; + NS_LOG_WARN("flightIndex got -1 from GetTimeWindow (" << time << ")"); + return; } - const double timeOffset = (time - m_timeWindows[flightIndex].first).GetSeconds (); + const double timeOffset = (time - m_timeWindows[flightIndex].first).GetSeconds(); - NS_LOG_LOGIC ("flightIndex: " << flightIndex << "; timeOffset: " << timeOffset); + NS_LOG_LOGIC("flightIndex: " << flightIndex << "; timeOffset: " << timeOffset); - m_flights[flightIndex].Update (timeOffset); + m_flights[flightIndex].Update(timeOffset); - m_currentPosition = m_flights[flightIndex].GetPosition (); - m_currentVelocity = m_flights[flightIndex].GetVelocity (); + m_currentPosition = m_flights[flightIndex].GetPosition(); + m_currentVelocity = m_flights[flightIndex].GetVelocity(); - NS_LOG_LOGIC ("Drone updated to pos " << m_currentPosition - << "; vel " << m_currentVelocity); + NS_LOG_LOGIC("Drone updated to pos " << m_currentPosition << "; vel " << m_currentVelocity); } -template +template const Vector -Planner::GetPosition () const +Planner::GetPosition() const { - NS_LOG_FUNCTION_NOARGS (); - return m_currentPosition; + NS_LOG_FUNCTION_NOARGS(); + return m_currentPosition; } -template +template const Vector -Planner::GetVelocity () const +Planner::GetVelocity() const { - NS_LOG_FUNCTION_NOARGS (); - return m_currentVelocity; + NS_LOG_FUNCTION_NOARGS(); + return m_currentVelocity; } -template +template const int32_t -Planner::GetTimeWindow (const Time time) const +Planner::GetTimeWindow(const Time time) const { - NS_LOG_FUNCTION (time); + NS_LOG_FUNCTION(time); - for (uint32_t i = 0; i < m_timeWindows.size (); i++) + for (uint32_t i = 0; i < m_timeWindows.size(); i++) { - NS_LOG_LOGIC ("Checking if " << time << " < " << m_timeWindows[i].second); - if (time.Compare(m_timeWindows[i].second) == -1) + NS_LOG_LOGIC("Checking if " << time << " < " << m_timeWindows[i].second); + if (time.Compare(m_timeWindows[i].second) == -1) { - return i; + return i; } } - return -1; + return -1; } template class Planner; diff --git a/src/mobility/planner.h b/src/mobility/planner.h index f50b072..f30c948 100644 --- a/src/mobility/planner.h +++ b/src/mobility/planner.h @@ -18,44 +18,43 @@ #ifndef PLANNER_H #define PLANNER_H -#include -#include +#include "flight-plan.h" #include -#include "flight-plan.h" +#include +#include -namespace ns3 { +namespace ns3 +{ /** * \brief Plan trajectories **/ -template +template class Planner { -public: - Planner (FlightPlan flightPlan, - FlightParam flightParam, - float step); - Planner (); - virtual ~Planner (); + public: + Planner(FlightPlan flightPlan, FlightParam flightParam, float step); + Planner(); + virtual ~Planner(); - void Update (const Time t) const; + void Update(const Time t) const; - const Vector GetPosition () const; - const Vector GetVelocity () const; - const int32_t GetTimeWindow (const Time t) const; + const Vector GetPosition() const; + const Vector GetVelocity() const; + const int32_t GetTimeWindow(const Time t) const; -private: - mutable Vector m_currentVelocity; - mutable Vector m_currentPosition; + private: + mutable Vector m_currentVelocity; + mutable Vector m_currentPosition; - float m_step; + float m_step; - std::vector m_flightParams; - std::vector m_flightPlans; - std::vector m_flights; - std::vector> m_timeWindows; /// Time windows for each flight plan + std::vector m_flightParams; + std::vector m_flightPlans; + std::vector m_flights; + std::vector> m_timeWindows; /// Time windows for each flight plan }; } // namespace ns3 diff --git a/src/mobility/proto-point.cc b/src/mobility/proto-point.cc index 3ed488e..d4dde4c 100644 --- a/src/mobility/proto-point.cc +++ b/src/mobility/proto-point.cc @@ -20,76 +20,80 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_OBJECT_ENSURE_REGISTERED (ProtoPoint); +NS_OBJECT_ENSURE_REGISTERED(ProtoPoint); TypeId -ProtoPoint::GetTypeId () +ProtoPoint::GetTypeId() { - static TypeId tid = TypeId ("ns3::ProtoPoint") - .SetParent () - .SetGroupName ("ProtoTrajectory") - .AddConstructor () - .AddAttribute ("Position", "The current position of the point of interest.", - VectorValue (Vector (0.0, 0.0, 0.0)), - MakeVectorAccessor (&ProtoPoint::m_position), - MakeVectorChecker ()) - .AddAttribute ("Interest", "The grade of interest of this point. 0 for a point of destination.", - IntegerValue (0), - MakeIntegerAccessor (&ProtoPoint::m_interest), - MakeIntegerChecker ()) - .AddAttribute ("RestTime", "The time to rest, if the point is a destination one.", - TimeValue (Seconds (0)), - MakeTimeAccessor (&ProtoPoint::m_restTime), - MakeTimeChecker ()) - ; + static TypeId tid = + TypeId("ns3::ProtoPoint") + .SetParent() + .SetGroupName("ProtoTrajectory") + .AddConstructor() + .AddAttribute("Position", + "The current position of the point of interest.", + VectorValue(Vector(0.0, 0.0, 0.0)), + MakeVectorAccessor(&ProtoPoint::m_position), + MakeVectorChecker()) + .AddAttribute("Interest", + "The grade of interest of this point. 0 for a point of destination.", + IntegerValue(0), + MakeIntegerAccessor(&ProtoPoint::m_interest), + MakeIntegerChecker()) + .AddAttribute("RestTime", + "The time to rest, if the point is a destination one.", + TimeValue(Seconds(0)), + MakeTimeAccessor(&ProtoPoint::m_restTime), + MakeTimeChecker()); - return tid; + return tid; } -ProtoPoint::ProtoPoint () +ProtoPoint::ProtoPoint() { } -ProtoPoint::~ProtoPoint () +ProtoPoint::~ProtoPoint() { } void -ProtoPoint::SetPosition (const Vector &position) +ProtoPoint::SetPosition(const Vector& position) { - m_position = position; + m_position = position; } const Vector -ProtoPoint::GetPosition () const +ProtoPoint::GetPosition() const { - return m_position; + return m_position; } void -ProtoPoint::SetInterest (const uint32_t &interest) +ProtoPoint::SetInterest(const uint32_t& interest) { - m_interest = interest; + m_interest = interest; } const uint32_t -ProtoPoint::GetInterest () const +ProtoPoint::GetInterest() const { - return m_interest; + return m_interest; } void -ProtoPoint::SetRestTime (const Time &seconds) +ProtoPoint::SetRestTime(const Time& seconds) { - m_restTime = seconds; + m_restTime = seconds; } const Time -ProtoPoint::GetRestTime () const +ProtoPoint::GetRestTime() const { - return m_restTime; + return m_restTime; } } // namespace ns3 diff --git a/src/mobility/proto-point.h b/src/mobility/proto-point.h index a22b759..5cc5c4c 100644 --- a/src/mobility/proto-point.h +++ b/src/mobility/proto-point.h @@ -22,7 +22,8 @@ #include #include -namespace ns3 { +namespace ns3 +{ /** * \ingroup mobility @@ -39,72 +40,72 @@ namespace ns3 { */ class ProtoPoint : public Object { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); - /** - * The default constructor. Initialize a point at (0, 0, 0) with interest 0 - * and rest time of 0 seconds. - */ - ProtoPoint (); - /** - * Destruct the object. - */ - virtual ~ProtoPoint (); + /** + * The default constructor. Initialize a point at (0, 0, 0) with interest 0 + * and rest time of 0 seconds. + */ + ProtoPoint(); + /** + * Destruct the object. + */ + virtual ~ProtoPoint(); - /** - * Set the position of the point of interest. - * - * \param position The new position. - */ - void SetPosition (const Vector &position); - /** - * \return The position of the point of interest. - */ - const Vector GetPosition () const; + /** + * Set the position of the point of interest. + * + * \param position The new position. + */ + void SetPosition(const Vector& position); + /** + * \return The position of the point of interest. + */ + const Vector GetPosition() const; - /** - * Set the interest level of the point of interest. - * - * \param value The new level of interest. - */ - void SetInterest (const uint32_t &interest); - /** - * \return The current interest level for the point of interest. - */ - const uint32_t GetInterest () const; + /** + * Set the interest level of the point of interest. + * + * \param value The new level of interest. + */ + void SetInterest(const uint32_t& interest); + /** + * \return The current interest level for the point of interest. + */ + const uint32_t GetInterest() const; - /** - * Set the time to rest at this destination in seconds. - * Note that if the point is not a destination, this property has no effect. - * - * \param seconds The time to rest. - */ - void SetRestTime (const Time &seconds); - /** - * \return The current time to rest applied to this point of interest. - */ - const Time GetRestTime () const; + /** + * Set the time to rest at this destination in seconds. + * Note that if the point is not a destination, this property has no effect. + * + * \param seconds The time to rest. + */ + void SetRestTime(const Time& seconds); + /** + * \return The current time to rest applied to this point of interest. + */ + const Time GetRestTime() const; -private: - /** - * \brief The position of the point of interest. - */ - Vector m_position; - /** - * \brief The interest level of the point of interest. If this level is 0, then this - * point will be used as a destination. - */ - uint32_t m_interest; - /** - * \brief The time, in seconds, that the drone will rest at this point of - * destination. - */ - Time m_restTime; + private: + /** + * \brief The position of the point of interest. + */ + Vector m_position; + /** + * \brief The interest level of the point of interest. If this level is 0, then this + * point will be used as a destination. + */ + uint32_t m_interest; + /** + * \brief The time, in seconds, that the drone will rest at this point of + * destination. + */ + Time m_restTime; }; } // namespace ns3 diff --git a/src/peripheral/drone-peripheral-container.cc b/src/peripheral/drone-peripheral-container.cc index 8fc4b94..db839b4 100644 --- a/src/peripheral/drone-peripheral-container.cc +++ b/src/peripheral/drone-peripheral-container.cc @@ -18,153 +18,157 @@ #include "drone-peripheral-container.h" -#include -#include - #include "drone-peripheral.h" #include "input-peripheral.h" #include "storage-peripheral.h" -namespace ns3 { +#include +#include -NS_LOG_COMPONENT_DEFINE ("DronePeripheralContainer"); +namespace ns3 +{ + +NS_LOG_COMPONENT_DEFINE("DronePeripheralContainer"); -NS_OBJECT_ENSURE_REGISTERED (DronePeripheralContainer); +NS_OBJECT_ENSURE_REGISTERED(DronePeripheralContainer); TypeId -DronePeripheralContainer::GetTypeId (void) +DronePeripheralContainer::GetTypeId(void) { - static TypeId tid = TypeId ("ns3::DronePeripheralContainer") - .SetParent () - .SetGroupName("Network") - .AddConstructor () - ; - return tid; + static TypeId tid = TypeId("ns3::DronePeripheralContainer") + .SetParent() + .SetGroupName("Network") + .AddConstructor(); + return tid; } void -DronePeripheralContainer::Add (const std::string typeId) +DronePeripheralContainer::Add(const std::string typeId) { - m_dronePeripheralFactory.SetTypeId(typeId); + m_dronePeripheralFactory.SetTypeId(typeId); } void -DronePeripheralContainer::Set (std::string name, const AttributeValue &v) +DronePeripheralContainer::Set(std::string name, const AttributeValue& v) { - m_dronePeripheralFactory.Set (name, v); + m_dronePeripheralFactory.Set(name, v); } void -DronePeripheralContainer::SetDrone (Ptr drone) +DronePeripheralContainer::SetDrone(Ptr drone) { - NS_LOG_FUNCTION (this << drone); - NS_ASSERT (drone != NULL); - m_drone = drone; + NS_LOG_FUNCTION(this << drone); + NS_ASSERT(drone != NULL); + m_drone = drone; } Ptr -DronePeripheralContainer::Create () +DronePeripheralContainer::Create() { - auto peripheral = m_dronePeripheralFactory.Create (); - NS_ASSERT (peripheral != nullptr); + auto peripheral = m_dronePeripheralFactory.Create(); + NS_ASSERT(peripheral != nullptr); - peripheral->Initialize (); - //if there are no trigger regions, this peripheral is always ON - if (peripheral->GetNRoI () == 0) - peripheral->SetState (DronePeripheral::PeripheralState::ON); + peripheral->Initialize(); + // if there are no trigger regions, this peripheral is always ON + if (peripheral->GetNRoI() == 0) + peripheral->SetState(DronePeripheral::PeripheralState::ON); - peripheral->SetDrone (m_drone); - m_dronePeripherals.push_back (peripheral); + peripheral->SetDrone(m_drone); + m_dronePeripherals.push_back(peripheral); - return peripheral; + return peripheral; } uint32_t -DronePeripheralContainer::GetN (void) const +DronePeripheralContainer::GetN(void) const { - return m_dronePeripherals.size (); + return m_dronePeripherals.size(); } Ptr -DronePeripheralContainer::Get (uint32_t i) const +DronePeripheralContainer::Get(uint32_t i) const { - return m_dronePeripherals[i]; + return m_dronePeripherals[i]; } DronePeripheralContainer::Iterator -DronePeripheralContainer::Begin (void) const +DronePeripheralContainer::Begin(void) const { - return m_dronePeripherals.begin (); + return m_dronePeripherals.begin(); } DronePeripheralContainer::Iterator -DronePeripheralContainer::End (void) const +DronePeripheralContainer::End(void) const { - return m_dronePeripherals.end (); + return m_dronePeripherals.end(); } void -DronePeripheralContainer::DoInitialize (void) +DronePeripheralContainer::DoInitialize(void) { - Object::DoInitialize(); + Object::DoInitialize(); } void -DronePeripheralContainer::DoDispose (void) +DronePeripheralContainer::DoDispose(void) { - for (std::vector>::iterator i = m_dronePeripherals.begin (); i != m_dronePeripherals.end (); i++) + for (std::vector>::iterator i = m_dronePeripherals.begin(); + i != m_dronePeripherals.end(); + i++) { - Ptr peripheral = *i; - peripheral->Dispose (); - *i = 0; + Ptr peripheral = *i; + peripheral->Dispose(); + *i = 0; } - m_dronePeripherals.clear(); - Object::DoDispose(); + m_dronePeripherals.clear(); + Object::DoDispose(); } void DronePeripheralContainer::InstallAll(Ptr drone) { - PinStorage(); + PinStorage(); - for (auto peripheral: m_dronePeripherals) + for (auto peripheral : m_dronePeripherals) { - //peripheral->SetDrone(drone); - auto value = BooleanValue(false); - if (peripheral->GetAttributeFailSafe("HasStorage", value) && value) + // peripheral->SetDrone(drone); + auto value = BooleanValue(false); + if (peripheral->GetAttributeFailSafe("HasStorage", value) && value) { - auto newperipheral = StaticCast(peripheral); - auto storageperipheral = StaticCast(m_dronePeripherals[0]); - newperipheral->SetStorage(storageperipheral); + auto newperipheral = StaticCast(peripheral); + auto storageperipheral = + StaticCast(m_dronePeripherals[0]); + newperipheral->SetStorage(storageperipheral); } IntegerValue rows; if (peripheral->GetAttributeFailSafe("Rows", rows)) { - auto irs = StaticCast(peripheral); - IrsList::Add(irs); + auto irs = StaticCast(peripheral); + IrsList::Add(irs); } - NS_LOG_DEBUG("DronePeripheralContainer: Peripheral Installed on Drone #"<GetId()<<" with State "<< peripheral->GetState()); + NS_LOG_DEBUG("DronePeripheralContainer: Peripheral Installed on Drone #" + << drone->GetId() << " with State " << peripheral->GetState()); } } void DronePeripheralContainer::PinStorage(void) { - for (uint32_t i=0; iGetInstanceTypeId() == StoragePeripheral::GetTypeId()) + for (uint32_t i = 0; i < GetN(); i++) { - std::swap(m_dronePeripherals[0], m_dronePeripherals[i]); - m_storage = true; - break; + if (m_dronePeripherals[i]->GetInstanceTypeId() == StoragePeripheral::GetTypeId()) + { + std::swap(m_dronePeripherals[0], m_dronePeripherals[i]); + m_storage = true; + break; + } } - } } bool DronePeripheralContainer::thereIsStorage(void) { - return m_storage; + return m_storage; } } // namespace ns3 \ No newline at end of file diff --git a/src/peripheral/drone-peripheral-container.h b/src/peripheral/drone-peripheral-container.h index 750db84..d5e3ec2 100644 --- a/src/peripheral/drone-peripheral-container.h +++ b/src/peripheral/drone-peripheral-container.h @@ -18,15 +18,15 @@ #ifndef DRONE_PERIPHERAL_CONTAINER_H #define DRONE_PERIPHERAL_CONTAINER_H -#include - -#include +#include "drone-peripheral.h" #include +#include -#include "drone-peripheral.h" +#include -namespace ns3 { +namespace ns3 +{ class DronePeripheral; class Drone; @@ -36,108 +36,109 @@ class Drone; */ class DronePeripheralContainer : public Object { -public: - - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); - - DronePeripheralContainer(){} - - /// Drone peripherals container iterator - typedef std::vector >::const_iterator Iterator; - - /** - * \brief Sets the Peripheral TypeId in the ObjectFactory - * - * \param typeId String containing the Peripheral TypeId - */ - void Add (const std::string typeId); - - /** - * \brief Sets Peripheral Attributes in the ObjectFactory. - * - * \param name String containing the Attribute name. - * \param v Value of the Attribute. - */ - void Set (std::string name, const AttributeValue &v); - - /** - * \brief Creates the Peripheral Object and adds it to the container. - * - * \returns Pointer to the DronePeripheral created. - */ - Ptr Create(); - - /** - * \brief Gets an iterator which refers to the first DronePeripheral in the - * container. - * - * \returns an iterator which refers to the first DronePeripheral in the container. - */ - Iterator Begin (void) const; - - /** - * \brief Gets an iterator which indicates past-the-last DronePeripheral in the - * container. - * - * \returns an iterator which indicates an ending condition for a loop. - */ - Iterator End (void) const; - - /** - * \brief Sets the pointer of the drone. - * - * \param drone Pointer of the drone. - */ - void SetDrone (Ptr drone); - - /** - * \brief Get the number of Ptr stored in this container. - * - * \returns the number of Ptr stored in this container. - */ - uint32_t GetN (void) const; - - /** - * \brief Get the Ptr stored in this container at a given - * index. - * - * \param i the index of the requested drone peripheral pointer. - * \returns the requested drone peripheral pointer. - */ - Ptr Get (uint32_t i) const; - - /** - * \brief Installs drone peripherals on a drone and eventually links - * input peripherals to storage peripherals. - * - * \param drone Pointer to the drone. - */ - void InstallAll(Ptr drone); - - /** - * \return the presence of storage peripheral - */ - bool thereIsStorage(); - -protected: - void virtual DoInitialize (void); - void virtual DoDispose (void); - -private: - /** - * \brief Moves the storage peripheral on the top of the container. - */ - void PinStorage(void); - - std::vector > m_dronePeripherals; //!< Drone peripherals smart pointers - ObjectFactory m_dronePeripheralFactory; - Ptr m_drone; - bool m_storage = false; + public: + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); + + DronePeripheralContainer() + { + } + + /// Drone peripherals container iterator + typedef std::vector>::const_iterator Iterator; + + /** + * \brief Sets the Peripheral TypeId in the ObjectFactory + * + * \param typeId String containing the Peripheral TypeId + */ + void Add(const std::string typeId); + + /** + * \brief Sets Peripheral Attributes in the ObjectFactory. + * + * \param name String containing the Attribute name. + * \param v Value of the Attribute. + */ + void Set(std::string name, const AttributeValue& v); + + /** + * \brief Creates the Peripheral Object and adds it to the container. + * + * \returns Pointer to the DronePeripheral created. + */ + Ptr Create(); + + /** + * \brief Gets an iterator which refers to the first DronePeripheral in the + * container. + * + * \returns an iterator which refers to the first DronePeripheral in the container. + */ + Iterator Begin(void) const; + + /** + * \brief Gets an iterator which indicates past-the-last DronePeripheral in the + * container. + * + * \returns an iterator which indicates an ending condition for a loop. + */ + Iterator End(void) const; + + /** + * \brief Sets the pointer of the drone. + * + * \param drone Pointer of the drone. + */ + void SetDrone(Ptr drone); + + /** + * \brief Get the number of Ptr stored in this container. + * + * \returns the number of Ptr stored in this container. + */ + uint32_t GetN(void) const; + + /** + * \brief Get the Ptr stored in this container at a given + * index. + * + * \param i the index of the requested drone peripheral pointer. + * \returns the requested drone peripheral pointer. + */ + Ptr Get(uint32_t i) const; + + /** + * \brief Installs drone peripherals on a drone and eventually links + * input peripherals to storage peripherals. + * + * \param drone Pointer to the drone. + */ + void InstallAll(Ptr drone); + + /** + * \return the presence of storage peripheral + */ + bool thereIsStorage(); + + protected: + void virtual DoInitialize(void); + void virtual DoDispose(void); + + private: + /** + * \brief Moves the storage peripheral on the top of the container. + */ + void PinStorage(void); + + std::vector> m_dronePeripherals; //!< Drone peripherals smart pointers + ObjectFactory m_dronePeripheralFactory; + Ptr m_drone; + bool m_storage = false; }; } // namespace ns3 diff --git a/src/peripheral/drone-peripheral.cc b/src/peripheral/drone-peripheral.cc index 803265d..4629848 100644 --- a/src/peripheral/drone-peripheral.cc +++ b/src/peripheral/drone-peripheral.cc @@ -19,145 +19,150 @@ #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("DronePeripheral"); +NS_LOG_COMPONENT_DEFINE("DronePeripheral"); -NS_OBJECT_ENSURE_REGISTERED (DronePeripheral); +NS_OBJECT_ENSURE_REGISTERED(DronePeripheral); TypeId -DronePeripheral::GetTypeId () +DronePeripheral::GetTypeId() { - static TypeId tid = TypeId ("ns3::DronePeripheral") - .SetParent () - .SetGroupName ("Peripheral") - .AddConstructor () - .AddAttribute ("PowerConsumption", "The power consumption [J/s] of the peripheral, in OFF|IDLE|ON states", - DoubleVectorValue (), - MakeDoubleVectorAccessor (&DronePeripheral::SetPowerConsumptionStates), - MakeDoubleVectorChecker ()) - .AddAttribute ("RoITrigger", "Indexes of Regions of Interest", - IntVectorValue (), - MakeIntVectorAccessor (&DronePeripheral::SetRegionsOfInterest), - MakeIntVectorChecker ()) - ; - return tid; + static TypeId tid = + TypeId("ns3::DronePeripheral") + .SetParent() + .SetGroupName("Peripheral") + .AddConstructor() + .AddAttribute("PowerConsumption", + "The power consumption [J/s] of the peripheral, in OFF|IDLE|ON states", + DoubleVectorValue(), + MakeDoubleVectorAccessor(&DronePeripheral::SetPowerConsumptionStates), + MakeDoubleVectorChecker()) + .AddAttribute("RoITrigger", + "Indexes of Regions of Interest", + IntVectorValue(), + MakeIntVectorAccessor(&DronePeripheral::SetRegionsOfInterest), + MakeIntVectorChecker()); + return tid; } -DronePeripheral::DronePeripheral () +DronePeripheral::DronePeripheral() { - m_state = OFF; - m_powerConsumption = 0; + m_state = OFF; + m_powerConsumption = 0; } void -DronePeripheral::DoDispose () +DronePeripheral::DoDispose() { - NS_LOG_FUNCTION (this); - Object::DoDispose (); + NS_LOG_FUNCTION(this); + Object::DoDispose(); } void -DronePeripheral::DoInitialize (void) +DronePeripheral::DoInitialize(void) { - NS_LOG_FUNCTION (this); - SetState(IDLE); - Object::DoInitialize (); + NS_LOG_FUNCTION(this); + SetState(IDLE); + Object::DoInitialize(); } void -DronePeripheral::SetDrone (Ptr drone) +DronePeripheral::SetDrone(Ptr drone) { - NS_LOG_FUNCTION (this << drone); - NS_ASSERT (drone != NULL); - m_drone = drone; + NS_LOG_FUNCTION(this << drone); + NS_ASSERT(drone != NULL); + m_drone = drone; } Ptr -DronePeripheral::GetDrone (void) +DronePeripheral::GetDrone(void) { - return m_drone; + return m_drone; } double -DronePeripheral::GetPowerConsumption (void) +DronePeripheral::GetPowerConsumption(void) { - NS_LOG_FUNCTION (this); - return m_powerConsumption; + NS_LOG_FUNCTION(this); + return m_powerConsumption; } + void DronePeripheral::SetPowerConsumption(double pc) { - NS_LOG_FUNCTION (this); - m_powerConsumption = pc; + NS_LOG_FUNCTION(this); + m_powerConsumption = pc; } DronePeripheral::PeripheralState DronePeripheral::GetState(void) { - return m_state; + return m_state; } void DronePeripheral::SetState(PeripheralState s) { - m_state = s; - switch (s) + m_state = s; + switch (s) { - case OFF: + case OFF: SetPowerConsumption(GetPowerConsumptionStates()[0]); - break; - case IDLE: + break; + case IDLE: SetPowerConsumption(GetPowerConsumptionStates()[1]); - break; - case ON: + break; + case ON: SetPowerConsumption(GetPowerConsumptionStates()[2]); - break; + break; } - if (GetDrone () != NULL) NS_LOG_DEBUG ("DronePeripheral on Drone #" << GetDrone ()->GetId ()<< ": changing peripheral state to "<GetId() << ": changing peripheral state to " << GetState()); + OnChangeState(s); } void DronePeripheral::OnChangeState(PeripheralState ocs) { - } void -DronePeripheral::SetPowerConsumptionStates (const DoubleVector &a) +DronePeripheral::SetPowerConsumptionStates(const DoubleVector& a) { - for (auto c = a.Begin (); c != a.End (); c++) + for (auto c = a.Begin(); c != a.End(); c++) { - m_powerConsumptionStates.push_back(*c); + m_powerConsumptionStates.push_back(*c); } } std::vector -DronePeripheral::GetPowerConsumptionStates (void) +DronePeripheral::GetPowerConsumptionStates(void) { - return m_powerConsumptionStates; + return m_powerConsumptionStates; } void -DronePeripheral::SetRegionsOfInterest (const IntVector &a) +DronePeripheral::SetRegionsOfInterest(const IntVector& a) { - for (auto c = a.Begin (); c != a.End (); c++) + for (auto c = a.Begin(); c != a.End(); c++) { - m_roi.push_back(*c); + m_roi.push_back(*c); } } std::vector -DronePeripheral::GetRegionsOfInterest (void) +DronePeripheral::GetRegionsOfInterest(void) { - return m_roi; + return m_roi; } int -DronePeripheral::GetNRoI (void) +DronePeripheral::GetNRoI(void) { - return m_roi.size(); + return m_roi.size(); } -} //namespace ns3 +} // namespace ns3 diff --git a/src/peripheral/drone-peripheral.h b/src/peripheral/drone-peripheral.h index d9448d3..03a7ee7 100644 --- a/src/peripheral/drone-peripheral.h +++ b/src/peripheral/drone-peripheral.h @@ -18,15 +18,15 @@ #ifndef DRONE_PERIPHERAL_H #define DRONE_PERIPHERAL_H -#include -#include -#include - #include +#include #include #include +#include +#include -namespace ns3 { +namespace ns3 +{ class Drone; @@ -37,115 +37,114 @@ class Drone; */ class DronePeripheral : public Object { -public: - /** - * \brief the peripheral states - */ - enum - PeripheralState - { - OFF, /// the peripheral is OFF - IDLE, /// the peripheral cannot execute operations - ON /// the peripheral can perform actions - }; - - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); - - DronePeripheral (); - - /** - * \brief Sets the pointer of the drone. - * - * \param drone Pointer of the drone. - */ - void SetDrone (Ptr drone); - - /** - * \brief Returns the pointer of the drone. - * - * \returns Pointer of the drone. - */ - Ptr GetDrone (void); - - /** - * \brief Returns the power consumption of the peripheral. - * - * \returns Power consumption in Watt. - */ - double GetPowerConsumption (void); - - /** - * \brief Returns the current peripheral state. - * - * \returns Peripheral state. - */ - PeripheralState GetState (void); - - /** - * \brief Sets the peripheral state. - * - * \param s state. - */ - void SetState (PeripheralState s); - - /** - * \brief Executes custom operations on state transition. - * - * \param ocs new state. - */ - virtual void OnChangeState (PeripheralState ocs); - - /** - * \return Vector of the regions indexes - */ - std::vector GetRegionsOfInterest (void); - - /** - * \return Number of regions. - */ - int GetNRoI (void); - - /** - * \return Gets the power consumption vector for each state. - */ - std::vector GetPowerConsumptionStates (void); - -protected: - virtual void DoDispose (void); - virtual void DoInitialize (void); - - /** - * \brief Sets the current power consumption. - * - * \param pc power consumption in W. - */ - void SetPowerConsumption(double pc); - - /** - * \brief Sets the power consumption vector for each state. - * - * \param a Structure describing the power consumption for OFF|IDLE|ON state - */ - void SetPowerConsumptionStates (const DoubleVector &a); - - /** - * \brief Sets the trigger regions of interest. - * - * \param a Structure containing indexes of regions - */ - void SetRegionsOfInterest (const IntVector &a); - -private: - Ptr m_drone; //!< Pointer to the drone. - double m_powerConsumption; //!< Constant power consumption in Watt. - PeripheralState m_state; //!< Current peripheral state - std::vector m_powerConsumptionStates; //!< Power consumptions for each state - std::vector m_roi; //!< Regions of interest indexes + public: + /** + * \brief the peripheral states + */ + enum PeripheralState + { + OFF, /// the peripheral is OFF + IDLE, /// the peripheral cannot execute operations + ON /// the peripheral can perform actions + }; + + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); + + DronePeripheral(); + + /** + * \brief Sets the pointer of the drone. + * + * \param drone Pointer of the drone. + */ + void SetDrone(Ptr drone); + + /** + * \brief Returns the pointer of the drone. + * + * \returns Pointer of the drone. + */ + Ptr GetDrone(void); + + /** + * \brief Returns the power consumption of the peripheral. + * + * \returns Power consumption in Watt. + */ + double GetPowerConsumption(void); + + /** + * \brief Returns the current peripheral state. + * + * \returns Peripheral state. + */ + PeripheralState GetState(void); + + /** + * \brief Sets the peripheral state. + * + * \param s state. + */ + void SetState(PeripheralState s); + + /** + * \brief Executes custom operations on state transition. + * + * \param ocs new state. + */ + virtual void OnChangeState(PeripheralState ocs); + + /** + * \return Vector of the regions indexes + */ + std::vector GetRegionsOfInterest(void); + + /** + * \return Number of regions. + */ + int GetNRoI(void); + + /** + * \return Gets the power consumption vector for each state. + */ + std::vector GetPowerConsumptionStates(void); + + protected: + virtual void DoDispose(void); + virtual void DoInitialize(void); + + /** + * \brief Sets the current power consumption. + * + * \param pc power consumption in W. + */ + void SetPowerConsumption(double pc); + + /** + * \brief Sets the power consumption vector for each state. + * + * \param a Structure describing the power consumption for OFF|IDLE|ON state + */ + void SetPowerConsumptionStates(const DoubleVector& a); + + /** + * \brief Sets the trigger regions of interest. + * + * \param a Structure containing indexes of regions + */ + void SetRegionsOfInterest(const IntVector& a); + + private: + Ptr m_drone; //!< Pointer to the drone. + double m_powerConsumption; //!< Constant power consumption in Watt. + PeripheralState m_state; //!< Current peripheral state + std::vector m_powerConsumptionStates; //!< Power consumptions for each state + std::vector m_roi; //!< Regions of interest indexes }; } // namespace ns3 diff --git a/src/peripheral/input-peripheral.cc b/src/peripheral/input-peripheral.cc index 9f9f799..f02139c 100644 --- a/src/peripheral/input-peripheral.cc +++ b/src/peripheral/input-peripheral.cc @@ -17,121 +17,128 @@ */ #include "input-peripheral.h" -#include #include +#include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("InputPeripheral"); -NS_OBJECT_ENSURE_REGISTERED (InputPeripheral); +NS_LOG_COMPONENT_DEFINE("InputPeripheral"); +NS_OBJECT_ENSURE_REGISTERED(InputPeripheral); TypeId -InputPeripheral::GetTypeId () +InputPeripheral::GetTypeId() { - static TypeId tid = TypeId ("ns3::InputPeripheral") - .SetParent () - .SetGroupName ("Peripheral") - .AddConstructor () - .AddAttribute ("DataRate", "The acquisition data rate of the peripheral in bit", - DoubleValue (0), - MakeDoubleAccessor (&InputPeripheral::m_dataRate), - MakeDoubleChecker (0)) - .AddAttribute ("DataAcquisitionTimeInterval", "The time interval occurring between any data acquisition", - TimeValue (Seconds (1.0)), - MakeTimeAccessor (&InputPeripheral::m_acquisitionTimeInterval), - MakeTimeChecker ()) - .AddAttribute ("HasStorage", "Acquired data are offloaded to the StoragePeripheral", - BooleanValue (false), - MakeBooleanAccessor (&InputPeripheral::m_hasStorage), - MakeBooleanChecker ()) - ; - return tid; + static TypeId tid = + TypeId("ns3::InputPeripheral") + .SetParent() + .SetGroupName("Peripheral") + .AddConstructor() + .AddAttribute("DataRate", + "The acquisition data rate of the peripheral in bit", + DoubleValue(0), + MakeDoubleAccessor(&InputPeripheral::m_dataRate), + MakeDoubleChecker(0)) + .AddAttribute("DataAcquisitionTimeInterval", + "The time interval occurring between any data acquisition", + TimeValue(Seconds(1.0)), + MakeTimeAccessor(&InputPeripheral::m_acquisitionTimeInterval), + MakeTimeChecker()) + .AddAttribute("HasStorage", + "Acquired data are offloaded to the StoragePeripheral", + BooleanValue(false), + MakeBooleanAccessor(&InputPeripheral::m_hasStorage), + MakeBooleanChecker()); + return tid; } -InputPeripheral::InputPeripheral () +InputPeripheral::InputPeripheral() { } void -InputPeripheral::DoInitialize (void) +InputPeripheral::DoInitialize(void) { - DronePeripheral::DoInitialize (); + DronePeripheral::DoInitialize(); } void -InputPeripheral::DoDispose (void) +InputPeripheral::DoDispose(void) { - DronePeripheral::DoDispose (); + DronePeripheral::DoDispose(); } void -InputPeripheral::SetStorage (Ptr storage) +InputPeripheral::SetStorage(Ptr storage) { - NS_ASSERT (storage != NULL); - NS_ASSERT (storage->GetDrone () == this->GetDrone ()); - m_storage = storage; + NS_ASSERT(storage != NULL); + NS_ASSERT(storage->GetDrone() == this->GetDrone()); + m_storage = storage; } void -InputPeripheral::Install (Ptr storage, Ptr drone) +InputPeripheral::Install(Ptr storage, Ptr drone) { - SetDrone (drone); - if (storage != NULL) + SetDrone(drone); + if (storage != NULL) { - SetStorage (storage); + SetStorage(storage); } } void -InputPeripheral::AcquireData (void) +InputPeripheral::AcquireData(void) { - if (Simulator::IsFinished ()) - return; + if (Simulator::IsFinished()) + return; - m_dataAcquisitionEvent.Cancel (); + m_dataAcquisitionEvent.Cancel(); - if (Simulator::Now ().GetMilliSeconds () >= m_acquisitionTimeInterval.GetMilliSeconds () && m_storage != NULL) + if (Simulator::Now().GetMilliSeconds() >= m_acquisitionTimeInterval.GetMilliSeconds() && + m_storage != NULL) { - m_storage->Alloc (m_dataRate * m_acquisitionTimeInterval.GetMilliSeconds () / 1000, - StoragePeripheral::bit); + m_storage->Alloc(m_dataRate * m_acquisitionTimeInterval.GetMilliSeconds() / 1000, + StoragePeripheral::bit); } - if (GetState() == PeripheralState::ON) m_dataAcquisitionEvent = Simulator::Schedule (m_acquisitionTimeInterval, &InputPeripheral::AcquireData, this); + if (GetState() == PeripheralState::ON) + m_dataAcquisitionEvent = + Simulator::Schedule(m_acquisitionTimeInterval, &InputPeripheral::AcquireData, this); } void InputPeripheral::OnChangeState(PeripheralState s) { - switch (s) + switch (s) { - case OFF: - break; - case IDLE: + case OFF: break; - case ON: + case IDLE: + break; + case ON: AcquireData(); - break; - default: - break; + break; + default: + break; } } double -InputPeripheral::GetDatarate () +InputPeripheral::GetDatarate() { - return m_dataRate; + return m_dataRate; } Time -InputPeripheral::GetAcquisitionTimeInterval () +InputPeripheral::GetAcquisitionTimeInterval() { - return m_acquisitionTimeInterval; + return m_acquisitionTimeInterval; } bool -InputPeripheral::HasStorage () +InputPeripheral::HasStorage() { - return m_hasStorage; + return m_hasStorage; } } // namespace ns3 diff --git a/src/peripheral/input-peripheral.h b/src/peripheral/input-peripheral.h index 19ae93c..70c095e 100644 --- a/src/peripheral/input-peripheral.h +++ b/src/peripheral/input-peripheral.h @@ -18,13 +18,14 @@ #ifndef INPUT_PERIPHERAL_H #define INPUT_PERIPHERAL_H -#include -#include - #include "drone-peripheral.h" #include "storage-peripheral.h" -namespace ns3 { +#include +#include + +namespace ns3 +{ /** * \brief This class describes a generic input peripheral with a constant @@ -33,67 +34,67 @@ namespace ns3 { */ class InputPeripheral : public DronePeripheral { -public: - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); - - InputPeripheral (); - - /** - * \brief Simulates the data acquisition. - * - * This methods schedules every m_acquisitionTimeInterval an event that allocates - * m_dataRate * m_acquisitionTimeInterval bits to the linked StoragePeripheral. - */ - void AcquireData (void); - - /** - * \brief Sets the pointer to a StoragePeripheral. - * - * \param storage Pointer to a StoragePeripheral. - * - * Input and storage peripherals have to be on the same drone. - */ - void SetStorage (Ptr storage); - - /** - * \brief Installs an InputPeripheral on a Drone and links it to the StoragePeripheral. - * - * This method must be called if the InputPeripheral has the Attribute "HasStorage" - * set to true. - * - * \param storage Pointer to a StoragePeripheral. - * \param drone Pointer to a Drone. - */ - void Install (Ptr storage, Ptr drone); - - /** - * \brief Executes custom operations on state transition. - * - * \param ocs new state. - */ - virtual void OnChangeState(PeripheralState ocs); - - double GetDatarate (); - - Time GetAcquisitionTimeInterval (); - - bool HasStorage (); - -protected: - void DoInitialize (void); - void DoDispose (void); - -private: - Time m_acquisitionTimeInterval; - double m_dataRate; - bool m_hasStorage; - EventId m_dataAcquisitionEvent; - Ptr m_storage; + public: + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); + + InputPeripheral(); + + /** + * \brief Simulates the data acquisition. + * + * This methods schedules every m_acquisitionTimeInterval an event that allocates + * m_dataRate * m_acquisitionTimeInterval bits to the linked StoragePeripheral. + */ + void AcquireData(void); + + /** + * \brief Sets the pointer to a StoragePeripheral. + * + * \param storage Pointer to a StoragePeripheral. + * + * Input and storage peripherals have to be on the same drone. + */ + void SetStorage(Ptr storage); + + /** + * \brief Installs an InputPeripheral on a Drone and links it to the StoragePeripheral. + * + * This method must be called if the InputPeripheral has the Attribute "HasStorage" + * set to true. + * + * \param storage Pointer to a StoragePeripheral. + * \param drone Pointer to a Drone. + */ + void Install(Ptr storage, Ptr drone); + + /** + * \brief Executes custom operations on state transition. + * + * \param ocs new state. + */ + virtual void OnChangeState(PeripheralState ocs); + + double GetDatarate(); + + Time GetAcquisitionTimeInterval(); + + bool HasStorage(); + + protected: + void DoInitialize(void); + void DoDispose(void); + + private: + Time m_acquisitionTimeInterval; + double m_dataRate; + bool m_hasStorage; + EventId m_dataAcquisitionEvent; + Ptr m_storage; }; } // namespace ns3 diff --git a/src/peripheral/storage-peripheral.cc b/src/peripheral/storage-peripheral.cc index a820c6c..97c7d84 100644 --- a/src/peripheral/storage-peripheral.cc +++ b/src/peripheral/storage-peripheral.cc @@ -19,99 +19,113 @@ #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("StoragePeripheral"); +NS_LOG_COMPONENT_DEFINE("StoragePeripheral"); -NS_OBJECT_ENSURE_REGISTERED (StoragePeripheral); +NS_OBJECT_ENSURE_REGISTERED(StoragePeripheral); TypeId -StoragePeripheral::GetTypeId () +StoragePeripheral::GetTypeId() { - static TypeId tid = TypeId ("ns3::StoragePeripheral") - .SetParent () - .SetGroupName ("Peripheral") - .AddConstructor () - .AddAttribute ("Capacity", "The capacity of the disk in bit", - UintegerValue (8000000), //1MByte - MakeUintegerAccessor (&StoragePeripheral::SetCapacity, + static TypeId tid = + TypeId("ns3::StoragePeripheral") + .SetParent() + .SetGroupName("Peripheral") + .AddConstructor() + .AddAttribute("Capacity", + "The capacity of the disk in bit", + UintegerValue(8000000), // 1MByte + MakeUintegerAccessor(&StoragePeripheral::SetCapacity, &StoragePeripheral::GetCapacity), - MakeUintegerChecker ()) - .AddAttribute ("InitialRemainingCapacity", "The initial capacity of the disk in bit", - UintegerValue (8000000), //1MByte - MakeUintegerAccessor (&StoragePeripheral::m_remainingCapacity), - MakeUintegerChecker ()) - .AddTraceSource ("RemainingCapacity", "Remaining Capacity at Storage Peripheral.", - MakeTraceSourceAccessor (&StoragePeripheral::m_remainingCapacity), - "ns3::TracedValueCallback::Uint64") - ; - return tid; + MakeUintegerChecker()) + .AddAttribute("InitialRemainingCapacity", + "The initial capacity of the disk in bit", + UintegerValue(8000000), // 1MByte + MakeUintegerAccessor(&StoragePeripheral::m_remainingCapacity), + MakeUintegerChecker()) + .AddTraceSource("RemainingCapacity", + "Remaining Capacity at Storage Peripheral.", + MakeTraceSourceAccessor(&StoragePeripheral::m_remainingCapacity), + "ns3::TracedValueCallback::Uint64"); + return tid; } -StoragePeripheral::StoragePeripheral () +StoragePeripheral::StoragePeripheral() { } void -StoragePeripheral::SetCapacity (uint64_t cap) +StoragePeripheral::SetCapacity(uint64_t cap) { - m_capacity = cap; - m_remainingCapacity = m_capacity; + m_capacity = cap; + m_remainingCapacity = m_capacity; } uint64_t -StoragePeripheral::GetCapacity () const +StoragePeripheral::GetCapacity() const { - return m_capacity; + return m_capacity; } void -StoragePeripheral::DoInitialize (void) +StoragePeripheral::DoInitialize(void) { - DronePeripheral::DoInitialize (); + DronePeripheral::DoInitialize(); } void -StoragePeripheral::DoDispose () +StoragePeripheral::DoDispose() { - DronePeripheral::DoDispose (); + DronePeripheral::DoDispose(); } bool -StoragePeripheral::Alloc (uint64_t amount, unit amountUnit) +StoragePeripheral::Alloc(uint64_t amount, unit amountUnit) { - if (GetState() != ON) {NS_LOG_DEBUG ("StoragePeripheral: Alloc opeation not possible."); return false;} - NS_LOG_FUNCTION (this << amount * amountUnit); - if (amount * amountUnit <= m_remainingCapacity) + if (GetState() != ON) + { + NS_LOG_DEBUG("StoragePeripheral: Alloc opeation not possible."); + return false; + } + NS_LOG_FUNCTION(this << amount * amountUnit); + if (amount * amountUnit <= m_remainingCapacity) { - m_remainingCapacity -= amount * amountUnit; - NS_LOG_DEBUG ("StoragePeripheral:Stored memory on Drone #" - << GetDrone ()->GetId () << ": " << m_capacity - m_remainingCapacity << " bits"); - return true; + m_remainingCapacity -= amount * amountUnit; + NS_LOG_DEBUG("StoragePeripheral:Stored memory on Drone #" + << GetDrone()->GetId() << ": " << m_capacity - m_remainingCapacity << " bits"); + return true; } - else + else { - NS_LOG_INFO ("StoragePeripheral:Not enough memory on Drone #" << GetDrone ()->GetId ()); - return false; + NS_LOG_INFO("StoragePeripheral:Not enough memory on Drone #" << GetDrone()->GetId()); + return false; } } bool -StoragePeripheral::Free (uint64_t amount, unit amountUnit) +StoragePeripheral::Free(uint64_t amount, unit amountUnit) { - if (GetState() != ON) {NS_LOG_DEBUG ("StoragePeripheral: Free opeation not possible."); return false;} - NS_LOG_FUNCTION (this << amount * amountUnit); - if (amount * amountUnit <= m_capacity - m_remainingCapacity) - { - m_remainingCapacity += amount * amountUnit; - NS_LOG_DEBUG ("StoragePeripheral:Stored memory on Drone #" - << GetDrone ()->GetId () << ": " << m_capacity - m_remainingCapacity << " bits"); - return true; - } else { - NS_LOG_INFO ("StoragePeripheral:Impossible to free more memory than occupied on Drone #" - << GetDrone ()->GetId ()); - return false; - } + if (GetState() != ON) + { + NS_LOG_DEBUG("StoragePeripheral: Free opeation not possible."); + return false; + } + NS_LOG_FUNCTION(this << amount * amountUnit); + if (amount * amountUnit <= m_capacity - m_remainingCapacity) + { + m_remainingCapacity += amount * amountUnit; + NS_LOG_DEBUG("StoragePeripheral:Stored memory on Drone #" + << GetDrone()->GetId() << ": " << m_capacity - m_remainingCapacity << " bits"); + return true; + } + else + { + NS_LOG_INFO("StoragePeripheral:Impossible to free more memory than occupied on Drone #" + << GetDrone()->GetId()); + return false; + } } } // namespace ns3 diff --git a/src/peripheral/storage-peripheral.h b/src/peripheral/storage-peripheral.h index 6541dd7..7b71b10 100644 --- a/src/peripheral/storage-peripheral.h +++ b/src/peripheral/storage-peripheral.h @@ -18,75 +18,77 @@ #ifndef STORAGE_PERIPHERAL_H #define STORAGE_PERIPHERAL_H -#include - #include "drone-peripheral.h" -namespace ns3 { +#include + +namespace ns3 +{ /** * \brief This class describes a generic storage peripheral. */ class StoragePeripheral : public DronePeripheral { -public: - /** - * \brief Multipliers to ease the conversion among units of measure. - */ - enum unit { - bit = 1, - kbit = 1024, - mbit = 1024 * 1024, - byte = 8, - kbyte = 8 * 1024, - mbyte = 8 * 1024 * 1024 - }; + public: + /** + * \brief Multipliers to ease the conversion among units of measure. + */ + enum unit + { + bit = 1, + kbit = 1024, + mbit = 1024 * 1024, + byte = 8, + kbyte = 8 * 1024, + mbyte = 8 * 1024 * 1024 + }; - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); - StoragePeripheral (); + StoragePeripheral(); - /** - * \brief Sets the capacity of the drive. - * - * \param cap Capacity of the drive in bits. - */ - void SetCapacity (uint64_t cap); + /** + * \brief Sets the capacity of the drive. + * + * \param cap Capacity of the drive in bits. + */ + void SetCapacity(uint64_t cap); - /** - * \brief Returns the capacity of the drive. - * - * \returns Capacity of the drive in bits. - */ - uint64_t GetCapacity (void) const; + /** + * \brief Returns the capacity of the drive. + * + * \returns Capacity of the drive in bits. + */ + uint64_t GetCapacity(void) const; - /** - * \brief Allocates a certain amount of data to the drive. - * - * \param amount Amount of data. - * \param amountUnit Unit of measure. - */ - bool Alloc (uint64_t amount, unit amountUnit); + /** + * \brief Allocates a certain amount of data to the drive. + * + * \param amount Amount of data. + * \param amountUnit Unit of measure. + */ + bool Alloc(uint64_t amount, unit amountUnit); - /** - * \brief Frees a certain amount of data from the drive. - * - * \param amount Amount of data. - * \param amountUnit Unit of measure. - */ - bool Free (uint64_t amount, unit amountUnit); + /** + * \brief Frees a certain amount of data from the drive. + * + * \param amount Amount of data. + * \param amountUnit Unit of measure. + */ + bool Free(uint64_t amount, unit amountUnit); -protected: - void DoInitialize (void); - void DoDispose (void); + protected: + void DoInitialize(void); + void DoDispose(void); -private: - uint64_t m_capacity; - TracedValue m_remainingCapacity; + private: + uint64_t m_capacity; + TracedValue m_remainingCapacity; }; } // namespace ns3 diff --git a/src/report/drone-control-layer.cc b/src/report/drone-control-layer.cc index b6feba0..0d41389 100644 --- a/src/report/drone-control-layer.cc +++ b/src/report/drone-control-layer.cc @@ -22,57 +22,59 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("DroneControlLayer"); -NS_OBJECT_ENSURE_REGISTERED (DroneControlLayer); +NS_LOG_COMPONENT_DEFINE("DroneControlLayer"); +NS_OBJECT_ENSURE_REGISTERED(DroneControlLayer); TypeId -DroneControlLayer::GetTypeId () +DroneControlLayer::GetTypeId() { - static TypeId tid = TypeId ("ns3::DroneControlLayer") - .AddConstructor () - .SetParent () - .AddAttribute ("NotImplemented", "This is a placeholder for future developments.", - StringValue (), - MakeStringAccessor (&DroneControlLayer::m_notImplemented), - MakeStringChecker ()) - ; + static TypeId tid = TypeId("ns3::DroneControlLayer") + .AddConstructor() + .SetParent() + .AddAttribute("NotImplemented", + "This is a placeholder for future developments.", + StringValue(), + MakeStringAccessor(&DroneControlLayer::m_notImplemented), + MakeStringChecker()); - return tid; + return tid; } -DroneControlLayer::DroneControlLayer () +DroneControlLayer::DroneControlLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -DroneControlLayer::~DroneControlLayer () +DroneControlLayer::~DroneControlLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -DroneControlLayer::Write (xmlTextWriterPtr h) +DroneControlLayer::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement (h, BAD_CAST "dcl"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "dcl"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "notImplemented", BAD_CAST ""); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "notImplemented", BAD_CAST ""); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/drone-control-layer.h b/src/report/drone-control-layer.h index d3e8472..772359e 100644 --- a/src/report/drone-control-layer.h +++ b/src/report/drone-control-layer.h @@ -19,38 +19,40 @@ */ #ifndef DRONE_CONTROL_LAYER_H #define DRONE_CONTROL_LAYER_H -#include - #include "protocol-layer.h" -namespace ns3 { +#include + +namespace ns3 +{ class DroneControlLayer : public ProtocolLayer { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); - - /** - * Default constructor - */ - DroneControlLayer (); - /** - * Default destructor - */ - ~DroneControlLayer (); - - /** - * Write IPv4 Layer report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - virtual void Write (xmlTextWriterPtr handle); -private: - std::string m_notImplemented; /// coming soon! ;) + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + DroneControlLayer(); + /** + * Default destructor + */ + ~DroneControlLayer(); + + /** + * Write IPv4 Layer report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + virtual void Write(xmlTextWriterPtr handle); + + private: + std::string m_notImplemented; /// coming soon! ;) }; } // namespace ns3 diff --git a/src/report/ipv4-layer.cc b/src/report/ipv4-layer.cc index c59904a..c75f358 100644 --- a/src/report/ipv4-layer.cc +++ b/src/report/ipv4-layer.cc @@ -22,69 +22,68 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Ipv4Layer"); -NS_OBJECT_ENSURE_REGISTERED (Ipv4Layer); +NS_LOG_COMPONENT_DEFINE("Ipv4Layer"); +NS_OBJECT_ENSURE_REGISTERED(Ipv4Layer); TypeId -Ipv4Layer::GetTypeId () +Ipv4Layer::GetTypeId() { - static TypeId tid = TypeId ("ns3::Ipv4Layer") - .AddConstructor () - .SetParent () - .AddAttribute ("Ipv4Address", "The IPv4 Address", - StringValue (), - MakeStringAccessor (&Ipv4Layer::m_address), - MakeStringChecker ()) - .AddAttribute ("SubnetMask", "Subnet Mask", - StringValue (), - MakeStringAccessor (&Ipv4Layer::m_subnetMask), - MakeStringChecker ()) - ; + static TypeId tid = TypeId("ns3::Ipv4Layer") + .AddConstructor() + .SetParent() + .AddAttribute("Ipv4Address", + "The IPv4 Address", + StringValue(), + MakeStringAccessor(&Ipv4Layer::m_address), + MakeStringChecker()) + .AddAttribute("SubnetMask", + "Subnet Mask", + StringValue(), + MakeStringAccessor(&Ipv4Layer::m_subnetMask), + MakeStringChecker()); - return tid; + return tid; } -Ipv4Layer::Ipv4Layer () +Ipv4Layer::Ipv4Layer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -Ipv4Layer::~Ipv4Layer () +Ipv4Layer::~Ipv4Layer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -Ipv4Layer::Write (xmlTextWriterPtr h) +Ipv4Layer::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement(h, BAD_CAST "ipv4"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "ipv4"); + NS_ASSERT(rc >= 0); - /* Nested Elements */ - rc = xmlTextWriterWriteElement(h, - BAD_CAST "address", - BAD_CAST m_address.c_str ()); - NS_ASSERT (rc >= 0); + /* Nested Elements */ + rc = xmlTextWriterWriteElement(h, BAD_CAST "address", BAD_CAST m_address.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, - BAD_CAST "subnetMask", - BAD_CAST m_subnetMask.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "subnetMask", BAD_CAST m_subnetMask.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/ipv4-layer.h b/src/report/ipv4-layer.h index 83db459..e4a4b9f 100644 --- a/src/report/ipv4-layer.h +++ b/src/report/ipv4-layer.h @@ -19,39 +19,41 @@ */ #ifndef IPV4_LAYER_H #define IPV4_LAYER_H -#include - #include "protocol-layer.h" -namespace ns3 { +#include + +namespace ns3 +{ class Ipv4Layer : public ProtocolLayer { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); - - /** - * Default constructor - */ - Ipv4Layer (); - /** - * Default destructor - */ - ~Ipv4Layer (); - - /** - * Write IPv4 Layer report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - virtual void Write (xmlTextWriterPtr handle); -private: - std::string m_address; /// IPv4 Address used - std::string m_subnetMask; /// Network Mask related to the IPv4 address + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + Ipv4Layer(); + /** + * Default destructor + */ + ~Ipv4Layer(); + + /** + * Write IPv4 Layer report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + virtual void Write(xmlTextWriterPtr handle); + + private: + std::string m_address; /// IPv4 Address used + std::string m_subnetMask; /// Network Mask related to the IPv4 address }; } // namespace ns3 diff --git a/src/report/lte-ue-phy-layer.cc b/src/report/lte-ue-phy-layer.cc index 3ba4afd..c1f6159 100644 --- a/src/report/lte-ue-phy-layer.cc +++ b/src/report/lte-ue-phy-layer.cc @@ -22,98 +22,109 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("LteUEPhyLayer"); -NS_OBJECT_ENSURE_REGISTERED (LteUEPhyLayer); +NS_LOG_COMPONENT_DEFINE("LteUEPhyLayer"); +NS_OBJECT_ENSURE_REGISTERED(LteUEPhyLayer); TypeId -LteUEPhyLayer::GetTypeId () +LteUEPhyLayer::GetTypeId() { - static TypeId tid = TypeId ("ns3::LteUEPhyLayer") - .AddConstructor () - .SetParent () - .AddAttribute ("IMSI", "IMSI", - StringValue (), - MakeStringAccessor (&LteUEPhyLayer::m_imsi), - MakeStringChecker ()) - .AddAttribute ("PropagationLossModelDl", "The propagation loss model in downlink", - StringValue (), - MakeStringAccessor (&LteUEPhyLayer::m_pldl), - MakeStringChecker ()) - .AddAttribute ("DlEarfcn", "Downlink E-UTRA Absolute Radio Frequency Channel Number", - StringValue (), - MakeStringAccessor (&LteUEPhyLayer::m_dlearfnc), - MakeStringChecker ()) - .AddAttribute ("DlBandwidth", "Downlink Transmission Bandwidth Configuration in number of Resource Blocks", - StringValue (), - MakeStringAccessor (&LteUEPhyLayer::m_dlband), - MakeStringChecker ()) - .AddAttribute ("PropagationLossModelUl", "The propagation loss model in uplink", - StringValue (), - MakeStringAccessor (&LteUEPhyLayer::m_plul), - MakeStringChecker ()) - .AddAttribute ("UlEarfcn", "Uplink E-UTRA Absolute Radio Frequency Channel Number", - StringValue (), - MakeStringAccessor (&LteUEPhyLayer::m_ulearfnc), - MakeStringChecker ()) - .AddAttribute ("UlBandwidth", "Uplink Transmission Bandwidth Configuration in number of Resource Blocks", - StringValue (), - MakeStringAccessor (&LteUEPhyLayer::m_ulband), - MakeStringChecker ()) - ; - - return tid; + static TypeId tid = + TypeId("ns3::LteUEPhyLayer") + .AddConstructor() + .SetParent() + .AddAttribute("IMSI", + "IMSI", + StringValue(), + MakeStringAccessor(&LteUEPhyLayer::m_imsi), + MakeStringChecker()) + .AddAttribute("PropagationLossModelDl", + "The propagation loss model in downlink", + StringValue(), + MakeStringAccessor(&LteUEPhyLayer::m_pldl), + MakeStringChecker()) + .AddAttribute("DlEarfcn", + "Downlink E-UTRA Absolute Radio Frequency Channel Number", + StringValue(), + MakeStringAccessor(&LteUEPhyLayer::m_dlearfnc), + MakeStringChecker()) + .AddAttribute( + "DlBandwidth", + "Downlink Transmission Bandwidth Configuration in number of Resource Blocks", + StringValue(), + MakeStringAccessor(&LteUEPhyLayer::m_dlband), + MakeStringChecker()) + .AddAttribute("PropagationLossModelUl", + "The propagation loss model in uplink", + StringValue(), + MakeStringAccessor(&LteUEPhyLayer::m_plul), + MakeStringChecker()) + .AddAttribute("UlEarfcn", + "Uplink E-UTRA Absolute Radio Frequency Channel Number", + StringValue(), + MakeStringAccessor(&LteUEPhyLayer::m_ulearfnc), + MakeStringChecker()) + .AddAttribute( + "UlBandwidth", + "Uplink Transmission Bandwidth Configuration in number of Resource Blocks", + StringValue(), + MakeStringAccessor(&LteUEPhyLayer::m_ulband), + MakeStringChecker()); + + return tid; } -LteUEPhyLayer::LteUEPhyLayer () +LteUEPhyLayer::LteUEPhyLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -LteUEPhyLayer::~LteUEPhyLayer () +LteUEPhyLayer::~LteUEPhyLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -LteUEPhyLayer::Write (xmlTextWriterPtr h) +LteUEPhyLayer::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement(h, BAD_CAST "phy"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "phy"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "IMSI", BAD_CAST m_imsi.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "IMSI", BAD_CAST m_imsi.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "PropagationLossModelDl", BAD_CAST m_pldl.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "PropagationLossModelDl", BAD_CAST m_pldl.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "DlEarfcn", BAD_CAST m_dlearfnc.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "DlEarfcn", BAD_CAST m_dlearfnc.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "DlBandwidth", BAD_CAST m_dlband.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "DlBandwidth", BAD_CAST m_dlband.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "PropagationLossModelUl", BAD_CAST m_plul.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "PropagationLossModelUl", BAD_CAST m_plul.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "UlEarfcn", BAD_CAST m_ulearfnc.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "UlEarfcn", BAD_CAST m_ulearfnc.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "UlBandwidth", BAD_CAST m_ulband.c_str ()); + rc = xmlTextWriterWriteElement(h, BAD_CAST "UlBandwidth", BAD_CAST m_ulband.c_str()); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/lte-ue-phy-layer.h b/src/report/lte-ue-phy-layer.h index f10e4e7..a95b84b 100644 --- a/src/report/lte-ue-phy-layer.h +++ b/src/report/lte-ue-phy-layer.h @@ -20,38 +20,40 @@ #ifndef LTE_UE_PHY_LAYER_H #define LTE_UE_PHY_LAYER_H -#include - #include "protocol-layer.h" -namespace ns3 { +#include + +namespace ns3 +{ class LteUEPhyLayer : public ProtocolLayer { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); - - /** - * Default constructor - */ - LteUEPhyLayer (); - /** - * Default destructor - */ - ~LteUEPhyLayer (); - - /** - * Write LTE Phy Layer report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - virtual void Write (xmlTextWriterPtr handle); -private: - std::string m_imsi,m_pldl,m_dlearfnc,m_dlband,m_plul,m_ulearfnc,m_ulband; + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + LteUEPhyLayer(); + /** + * Default destructor + */ + ~LteUEPhyLayer(); + + /** + * Write LTE Phy Layer report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + virtual void Write(xmlTextWriterPtr handle); + + private: + std::string m_imsi, m_pldl, m_dlearfnc, m_dlband, m_plul, m_ulearfnc, m_ulband; }; } // namespace ns3 diff --git a/src/report/protocol-layer.cc b/src/report/protocol-layer.cc index 24cc60f..8977482 100644 --- a/src/report/protocol-layer.cc +++ b/src/report/protocol-layer.cc @@ -22,53 +22,53 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ProtocolLayer"); -NS_OBJECT_ENSURE_REGISTERED (ProtocolLayer); +NS_LOG_COMPONENT_DEFINE("ProtocolLayer"); +NS_OBJECT_ENSURE_REGISTERED(ProtocolLayer); TypeId -ProtocolLayer::GetTypeId () +ProtocolLayer::GetTypeId() { - static TypeId tid = TypeId ("ns3::ProtocolLayer") - .AddConstructor () - .SetParent() - .AddAttribute ("InstanceType", "The InstanceTypeId", - StringValue (), - MakeStringAccessor (&ProtocolLayer::m_instancetypeid), - MakeStringChecker ()) - ; + static TypeId tid = TypeId("ns3::ProtocolLayer") + .AddConstructor() + .SetParent() + .AddAttribute("InstanceType", + "The InstanceTypeId", + StringValue(), + MakeStringAccessor(&ProtocolLayer::m_instancetypeid), + MakeStringChecker()); - return tid; + return tid; } -ProtocolLayer::ProtocolLayer () +ProtocolLayer::ProtocolLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ProtocolLayer::~ProtocolLayer () +ProtocolLayer::~ProtocolLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ProtocolLayer::Write (xmlTextWriterPtr h) +ProtocolLayer::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterWriteElement(h, - BAD_CAST "type", - BAD_CAST m_instancetypeid.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "type", BAD_CAST m_instancetypeid.c_str()); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/protocol-layer.h b/src/report/protocol-layer.h index 22d65e5..068a588 100644 --- a/src/report/protocol-layer.h +++ b/src/report/protocol-layer.h @@ -17,7 +17,6 @@ * * Authors: Giovanni Iacovelli */ - #ifndef PROTOCOL_LAYER_H #define PROTOCOL_LAYER_H @@ -25,11 +24,12 @@ #include -namespace ns3 { +namespace ns3 +{ class ProtocolLayer : public Object { -public: + public: /* * Pure virtual declarations * or very common methods/properties @@ -40,24 +40,29 @@ class ProtocolLayer : public Object * Register the type using ns-3 TypeId System. * \return the object TypeId */ - static TypeId GetTypeId (); + static TypeId GetTypeId(); - ProtocolLayer (); + ProtocolLayer(); - ~ProtocolLayer (); + ~ProtocolLayer(); /** * Write Stack Layer report data to a XML file with a given handler * * \param handle the XML handler to write data on */ - virtual void Write (xmlTextWriterPtr handle); -protected: + virtual void Write(xmlTextWriterPtr handle); + + protected: /** * Object internal initialization */ - virtual void DoInitialize () { Object::DoInitialize (); }; -private: -std::string m_instancetypeid; + virtual void DoInitialize() + { + Object::DoInitialize(); + }; + + private: + std::string m_instancetypeid; }; } // namespace ns3 diff --git a/src/report/report-container.cc b/src/report/report-container.cc index e4892bb..9a60950 100644 --- a/src/report/report-container.cc +++ b/src/report/report-container.cc @@ -23,97 +23,98 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportContainer"); +NS_LOG_COMPONENT_DEFINE("ReportContainer"); template -ReportContainer::ReportContainer (const std::string groupName) : - m_groupName {groupName} +ReportContainer::ReportContainer(const std::string groupName) + : m_groupName{groupName} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } template typename ReportContainer::Iterator -ReportContainer::Begin () const +ReportContainer::Begin() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_entities.begin (); + return m_entities.begin(); } template typename ReportContainer::Iterator -ReportContainer::End () const +ReportContainer::End() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_entities.end (); + return m_entities.end(); } template uint32_t -ReportContainer::GetN () const +ReportContainer::GetN() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_entities.size (); + return m_entities.size(); } template Ptr -ReportContainer::Get (const uint32_t i) const +ReportContainer::Get(const uint32_t i) const { - NS_LOG_FUNCTION (i); + NS_LOG_FUNCTION(i); - return m_entities[i]; + return m_entities[i]; } template void -ReportContainer::Add (Ptr entity) +ReportContainer::Add(Ptr entity) { - NS_LOG_FUNCTION (entity); + NS_LOG_FUNCTION(entity); - m_entities.push_back (entity); + m_entities.push_back(entity); } template void -ReportContainer::Add (uint32_t entityUid) +ReportContainer::Add(uint32_t entityUid) { - NS_LOG_FUNCTION (entityUid); - auto entityReport = CreateObjectWithAttributes - ("Reference", IntegerValue(entityUid)); + NS_LOG_FUNCTION(entityUid); + auto entityReport = CreateObjectWithAttributes("Reference", IntegerValue(entityUid)); - entityReport->Initialize (); - Add (entityReport); + entityReport->Initialize(); + Add(entityReport); } template void -ReportContainer::Write (xmlTextWriterPtr h) const +ReportContainer::Write(xmlTextWriterPtr h) const { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement (h, BAD_CAST m_groupName.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST m_groupName.c_str()); + NS_ASSERT(rc >= 0); - /* Nested Elements */ - for (auto entity = Begin(); entity != End (); entity++) - (*entity)->Write (h); + /* Nested Elements */ + for (auto entity = Begin(); entity != End(); entity++) + (*entity)->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } }; // namespace ns3 diff --git a/src/report/report-container.h b/src/report/report-container.h index 732132a..9b7931e 100644 --- a/src/report/report-container.h +++ b/src/report/report-container.h @@ -20,78 +20,79 @@ #ifndef REPORT_CONTAINER_H #define REPORT_CONTAINER_H -#include -#include +#include "report-drone.h" +#include "report-remote.h" +#include "report-zsp.h" #include #include +#include +#include -#include "report-drone.h" -#include "report-zsp.h" -#include "report-remote.h" - -namespace ns3 { +namespace ns3 +{ /** * A container to easily keep pointers */ -template +template class ReportContainer { -public: - /// Container iterator - typedef typename std::vector>::const_iterator Iterator; - - /** - * Create an empty ReportContainer - * - * \param groupName name of entities group - */ - ReportContainer (const std::string groupName); - - /** - * Get an iterator which refers to the first entity in the container - */ - Iterator Begin () const; - - /** - * Get an iterator which indicates past-the-last entity in the container - */ - Iterator End () const; - - /** - * Get the number of Ptr stored in this container - */ - uint32_t GetN () const; - - /** - * Get the Ptr stored in this container at a given index - */ - Ptr Get (const uint32_t i) const; - - /** - * Append a single Ptr to this container - */ - void Add (Ptr entity); - - /** - * Append a new Ptr to this container initializing with - * an entity UID. - * - * \param entityUid The entity unique identifier - */ - void Add (uint32_t entityUid); - - /** - * Write entity report data to a XML file with a given handler - * - * \param handle the handler to communicate data to the opened XML file - */ - void Write (xmlTextWriterPtr handle) const; -private: - const std::string m_groupName; /// name of entities group - std::vector> m_entities; /// smart pointers + public: + /// Container iterator + typedef typename std::vector>::const_iterator Iterator; + + /** + * Create an empty ReportContainer + * + * \param groupName name of entities group + */ + ReportContainer(const std::string groupName); + + /** + * Get an iterator which refers to the first entity in the container + */ + Iterator Begin() const; + + /** + * Get an iterator which indicates past-the-last entity in the container + */ + Iterator End() const; + + /** + * Get the number of Ptr stored in this container + */ + uint32_t GetN() const; + + /** + * Get the Ptr stored in this container at a given index + */ + Ptr Get(const uint32_t i) const; + + /** + * Append a single Ptr to this container + */ + void Add(Ptr entity); + + /** + * Append a new Ptr to this container initializing with + * an entity UID. + * + * \param entityUid The entity unique identifier + */ + void Add(uint32_t entityUid); + + /** + * Write entity report data to a XML file with a given handler + * + * \param handle the handler to communicate data to the opened XML file + */ + void Write(xmlTextWriterPtr handle) const; + + private: + const std::string m_groupName; /// name of entities group + std::vector> m_entities; /// smart pointers }; /* diff --git a/src/report/report-data-stats.cc b/src/report/report-data-stats.cc index 195abcd..703b76f 100644 --- a/src/report/report-data-stats.cc +++ b/src/report/report-data-stats.cc @@ -22,60 +22,61 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportDataStats"); +NS_LOG_COMPONENT_DEFINE("ReportDataStats"); TypeId -ReportDataStats::GetTypeId () +ReportDataStats::GetTypeId() { - static TypeId tid = TypeId ("ns3::ReportDataStats") - .AddConstructor () - .SetParent () - .AddAttribute ("kind", "Type of data transfer", - PacketTypeValue (), - MakePacketTypeAccessor (&ReportDataStats::m_kind), - MakePacketTypeChecker ()) - .AddAttribute ("amount", "The amount of bytes transferred", - IntegerValue (0), - MakeIntegerAccessor (&ReportDataStats::m_bytes), - MakeIntegerChecker ()) - ; + static TypeId tid = TypeId("ns3::ReportDataStats") + .AddConstructor() + .SetParent() + .AddAttribute("kind", + "Type of data transfer", + PacketTypeValue(), + MakePacketTypeAccessor(&ReportDataStats::m_kind), + MakePacketTypeChecker()) + .AddAttribute("amount", + "The amount of bytes transferred", + IntegerValue(0), + MakeIntegerAccessor(&ReportDataStats::m_bytes), + MakeIntegerChecker()); - return tid; + return tid; } -ReportDataStats::ReportDataStats () : - m_kind {PacketType::UNKNOWN}, - m_bytes {0} +ReportDataStats::ReportDataStats() + : m_kind{PacketType::UNKNOWN}, + m_bytes{0} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportDataStats::~ReportDataStats () +ReportDataStats::~ReportDataStats() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ReportDataStats::Write (xmlTextWriterPtr h) const +ReportDataStats::Write(xmlTextWriterPtr h) const { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - std::ostringstream bBytes; - int rc; + std::ostringstream bBytes; + int rc; - bBytes << m_bytes; - rc = xmlTextWriterWriteElement (h, - BAD_CAST m_kind.ToString (), - BAD_CAST bBytes.str ().c_str ()); - NS_ASSERT (rc >= 0); + bBytes << m_bytes; + rc = xmlTextWriterWriteElement(h, BAD_CAST m_kind.ToString(), BAD_CAST bBytes.str().c_str()); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/report-data-stats.h b/src/report/report-data-stats.h index 49546d3..3eabaf6 100644 --- a/src/report/report-data-stats.h +++ b/src/report/report-data-stats.h @@ -19,45 +19,48 @@ */ #ifndef REPORT_DATA_STATS_H #define REPORT_DATA_STATS_H -#include - +#include #include +#include #include -#include - -namespace ns3 { +namespace ns3 +{ class ReportDataStats : public Object { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + ReportDataStats(); + /** + * Default destructor + */ + ~ReportDataStats(); - /** - * Default constructor - */ - ReportDataStats (); - /** - * Default destructor - */ - ~ReportDataStats (); + constexpr void Add(const uint32_t bytes) + { + m_bytes += bytes; + } - constexpr void Add (const uint32_t bytes) { m_bytes += bytes; } + /** + * Write report data statistics to a XML file with a given handler + * + * \param handle the handler to communicate data to the opened XML file + */ + void Write(xmlTextWriterPtr handle) const; - /** - * Write report data statistics to a XML file with a given handler - * - * \param handle the handler to communicate data to the opened XML file - */ - void Write (xmlTextWriterPtr handle) const; -private: - PacketType m_kind; /// the kind of data packet that is monitored - mutable std::uint32_t m_bytes; /// the amount of bytes transferred + private: + PacketType m_kind; /// the kind of data packet that is monitored + mutable std::uint32_t m_bytes; /// the amount of bytes transferred }; } // namespace ns3 diff --git a/src/report/report-default-iterator.h b/src/report/report-default-iterator.h index 776704e..6cd99f8 100644 --- a/src/report/report-default-iterator.h +++ b/src/report/report-default-iterator.h @@ -1,40 +1,45 @@ #ifndef REPORT_DEFAULT_ITERATOR_H #define REPORT_DEFAULT_ITERATOR_H -#include - #include -namespace ns3 { +#include + +namespace ns3 +{ class ReportDefaultIterator { -public: - virtual ~ReportDefaultIterator () = 0; - /** - * \brief This function will go through all the TypeIds and get only the attributes which are - * explicit values (not vectors or pointer or arrays) and apply StartVisitTypeId - * and VisitAttribute on the attributes in one TypeId. At the end of each TypeId - * EndVisitTypeId is called. - */ - void Iterate (); -private: - /** - * \brief Just an interface that needs to be implemented - */ - virtual void StartVisitTypeId (std::string name); - /** - * \brief Just an interface that needs to be implemented - */ - virtual void EndVisitTypeId (); - /** - * \brief This method can be implemented, otherwise, it will call DoVisitAttribute - */ - virtual void VisitAttribute (TypeId tid, std::string name, std::string defaultValue, uint32_t index); - /** - * \brief This method is just an interface and needs to be implemented - */ - virtual void DoVisitAttribute (std::string name, std::string defaultValue); + public: + virtual ~ReportDefaultIterator() = 0; + /** + * \brief This function will go through all the TypeIds and get only the attributes which are + * explicit values (not vectors or pointer or arrays) and apply StartVisitTypeId + * and VisitAttribute on the attributes in one TypeId. At the end of each TypeId + * EndVisitTypeId is called. + */ + void Iterate(); + + private: + /** + * \brief Just an interface that needs to be implemented + */ + virtual void StartVisitTypeId(std::string name); + /** + * \brief Just an interface that needs to be implemented + */ + virtual void EndVisitTypeId(); + /** + * \brief This method can be implemented, otherwise, it will call DoVisitAttribute + */ + virtual void VisitAttribute(TypeId tid, + std::string name, + std::string defaultValue, + uint32_t index); + /** + * \brief This method is just an interface and needs to be implemented + */ + virtual void DoVisitAttribute(std::string name, std::string defaultValue); }; } // namespace ns3 diff --git a/src/report/report-drone.cc b/src/report/report-drone.cc index 7225229..9cd3c22 100644 --- a/src/report/report-drone.cc +++ b/src/report/report-drone.cc @@ -19,240 +19,254 @@ */ #include "report-drone.h" +#include "drone-control-layer.h" +#include "ipv4-layer.h" +#include "report-helper.h" +#include "wifi-inspector.h" +#include "wifi-mac-layer.h" +#include "wifi-phy-layer.h" + #include +#include +#include +#include +#include #include +#include #include #include -#include #include +#include #include +#include #include #include #include -#include -#include -#include -#include -#include -#include - -#include "drone-control-layer.h" -#include "ipv4-layer.h" -#include "report-helper.h" -#include "wifi-inspector.h" -#include "wifi-mac-layer.h" -#include "wifi-phy-layer.h" - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportDrone"); -NS_OBJECT_ENSURE_REGISTERED (ReportDrone); +NS_LOG_COMPONENT_DEFINE("ReportDrone"); +NS_OBJECT_ENSURE_REGISTERED(ReportDrone); TypeId -ReportDrone::GetTypeId () +ReportDrone::GetTypeId() { - static TypeId tid = TypeId ("ns3::ReportDrone") - .AddConstructor () - .SetParent () - ; + static TypeId tid = + TypeId("ns3::ReportDrone").AddConstructor().SetParent(); - return tid; + return tid; } -ReportDrone::ReportDrone () +ReportDrone::ReportDrone() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportDrone::~ReportDrone () +ReportDrone::~ReportDrone() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -void ReportDrone::DoInitialize() +void +ReportDrone::DoInitialize() { - DoInitializePeripherals(); - ReportEntity::DoInitialize(); + DoInitializePeripherals(); + ReportEntity::DoInitialize(); } void -ReportDrone::DoWrite (xmlTextWriterPtr h) +ReportDrone::DoWrite(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (this << h); - if (h == nullptr) + NS_LOG_FUNCTION(this << h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; - - rc = xmlTextWriterStartElement (h, BAD_CAST "Drone"); - NS_ASSERT (rc >= 0); - - /* Nested Elements */ - rc = xmlTextWriterStartElement (h, BAD_CAST "trajectory"); - NS_ASSERT (rc >= 0); - - for (auto& location : m_trajectory) - location.Write (h); + int rc; - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "Drone"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "Peripherals"); - NS_ASSERT (rc >= 0); + /* Nested Elements */ + rc = xmlTextWriterStartElement(h, BAD_CAST "trajectory"); + NS_ASSERT(rc >= 0); - for (auto p : m_peripherals) - p.Write (h); + for (auto& location : m_trajectory) + location.Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterStartElement (h, BAD_CAST "NetDevices"); - NS_ASSERT (rc >= 0); - - for (int nid = 0; nid < (int) m_networkStacks.size(); nid++) - { - rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevice"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - m_networkStacks[nid].Write (h); + rc = xmlTextWriterStartElement(h, BAD_CAST "Peripherals"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataTx"); - NS_ASSERT (rc >= 0); + for (auto p : m_peripherals) + p.Write(h); - for (auto rid=m_dataTx.begin(); rid !=m_dataTx.end();) - { - if ((*rid)->GetIface() == nid) - { - (*rid)->Write (h); - m_dataTx.erase(rid); - } else { - rid++; - } - } - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataRx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevices"); + NS_ASSERT(rc >= 0); - for (auto rid=m_dataRx.begin(); rid !=m_dataRx.end();) + for (int nid = 0; nid < (int)m_networkStacks.size(); nid++) { - if ((*rid)->GetIface() == nid) - { - (*rid)->Write (h); - m_dataRx.erase(rid); - } else { - rid++; - } + rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevice"); + NS_ASSERT(rc >= 0); + + m_networkStacks[nid].Write(h); + + rc = xmlTextWriterStartElement(h, BAD_CAST "dataTx"); + NS_ASSERT(rc >= 0); + + for (auto rid = m_dataTx.begin(); rid != m_dataTx.end();) + { + if ((*rid)->GetIface() == nid) + { + (*rid)->Write(h); + m_dataTx.erase(rid); + } + else + { + rid++; + } + } + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterStartElement(h, BAD_CAST "dataRx"); + NS_ASSERT(rc >= 0); + + for (auto rid = m_dataRx.begin(); rid != m_dataRx.end();) + { + if ((*rid)->GetIface() == nid) + { + (*rid)->Write(h); + m_dataRx.erase(rid); + } + else + { + rid++; + } + } + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } - - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); - } - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataTx"); - //broadcast - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "dataTx"); + // broadcast + NS_ASSERT(rc >= 0); - for (auto rid=m_dataTx.begin(); rid !=m_dataTx.end();rid++) (*rid)->Write (h); + for (auto rid = m_dataTx.begin(); rid != m_dataTx.end(); rid++) + (*rid)->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataRx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "dataRx"); + NS_ASSERT(rc >= 0); - for (auto rid=m_dataRx.begin(); rid !=m_dataRx.end();rid++) (*rid)->Write (h); + for (auto rid = m_dataRx.begin(); rid != m_dataRx.end(); rid++) + (*rid)->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - ////// + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + ////// - rc = xmlTextWriterStartElement (h, BAD_CAST "cumulativeDataTx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "cumulativeDataTx"); + NS_ASSERT(rc >= 0); - for (auto& dataStatsTx : m_cumulativeDataTx) - dataStatsTx->Write (h); + for (auto& dataStatsTx : m_cumulativeDataTx) + dataStatsTx->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "cumulativeDataRx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "cumulativeDataRx"); + NS_ASSERT(rc >= 0); - for (auto& dataStatsRx : m_cumulativeDataRx) - dataStatsRx->Write (h); + for (auto& dataStatsRx : m_cumulativeDataRx) + dataStatsRx->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } void -ReportDrone::DoInitializeTrajectoryMonitor () +ReportDrone::DoInitializeTrajectoryMonitor() { - NS_LOG_FUNCTION (this); - /* set CourseChange callback using ns-3 XPath addressing system */ - std::stringstream xPathCallback; - - xPathCallback << "/NodeList/" << m_reference - << "/$ns3::MobilityModel/CourseChange"; - Config::ConnectWithoutContext (xPathCallback.str (), - MakeCallback (&ReportDrone::DoMonitorTrajectory, this)); + NS_LOG_FUNCTION(this); + /* set CourseChange callback using ns-3 XPath addressing system */ + std::stringstream xPathCallback; + + xPathCallback << "/NodeList/" << m_reference << "/$ns3::MobilityModel/CourseChange"; + Config::ConnectWithoutContext(xPathCallback.str(), + MakeCallback(&ReportDrone::DoMonitorTrajectory, this)); } void -ReportDrone::DoMonitorTrajectory (const Ptr mobility) +ReportDrone::DoMonitorTrajectory(const Ptr mobility) { - NS_LOG_FUNCTION (this << mobility); - Ptr drone = NodeList::GetNode(m_reference); - Vector position = mobility->GetPosition (); - - if (m_trajectory.size() == 0 || m_trajectory.back().GetPosition() != position) - { - m_trajectory.push_back (ReportLocation (position, Simulator::Now (), irc->IsInRegions(position))); - m_roi.push_back (irc->IsInRegions(position)); - } + NS_LOG_FUNCTION(this << mobility); + Ptr drone = NodeList::GetNode(m_reference); + Vector position = mobility->GetPosition(); + + if (m_trajectory.size() == 0 || m_trajectory.back().GetPosition() != position) + { + m_trajectory.push_back( + ReportLocation(position, Simulator::Now(), irc->IsInRegions(position))); + m_roi.push_back(irc->IsInRegions(position)); + } } void -ReportDrone::DoInitializePeripherals () +ReportDrone::DoInitializePeripherals() { - NS_LOG_FUNCTION (this); - auto nodeRef = NodeList::GetNode (m_reference); - auto drone = StaticCast (nodeRef); - auto percont = drone->getPeripherals (); - - for (auto p = percont->Begin (); p != percont->End (); p++) - { - m_peripherals.push_back (ReportPeripheral ((*p)->GetInstanceTypeId ().GetName (), (*p)->GetPowerConsumptionStates (), (*p)->GetRegionsOfInterest ())); - - auto pName = (*p)->GetInstanceTypeId ().GetName (); - if (pName == "ns3::StoragePeripheral") - { - m_peripherals.back ().AddAttribute ({ "Capacity", std::to_string (StaticCast ((*p))->GetCapacity ()) }); - } - else if (pName == "ns3::InputPeripheral") - { - Ptr inper = StaticCast ((*p)); - m_peripherals.back ().AddAttribute ({ "DataRate", std::to_string (inper->GetDatarate ()) }); - m_peripherals.back ().AddAttribute ({ "DataAcquisitionTimeInterval", std::to_string (inper->GetAcquisitionTimeInterval ().GetSeconds ()) }); - m_peripherals.back ().AddAttribute ({ "HasStorage", inper->HasStorage () ? "true" : "false" }); - } - } + NS_LOG_FUNCTION(this); + auto nodeRef = NodeList::GetNode(m_reference); + auto drone = StaticCast(nodeRef); + auto percont = drone->getPeripherals(); + + for (auto p = percont->Begin(); p != percont->End(); p++) + { + m_peripherals.push_back(ReportPeripheral((*p)->GetInstanceTypeId().GetName(), + (*p)->GetPowerConsumptionStates(), + (*p)->GetRegionsOfInterest())); + + auto pName = (*p)->GetInstanceTypeId().GetName(); + if (pName == "ns3::StoragePeripheral") + { + m_peripherals.back().AddAttribute( + {"Capacity", + std::to_string( + StaticCast((*p))->GetCapacity())}); + } + else if (pName == "ns3::InputPeripheral") + { + Ptr inper = StaticCast((*p)); + m_peripherals.back().AddAttribute({"DataRate", std::to_string(inper->GetDatarate())}); + m_peripherals.back().AddAttribute( + {"DataAcquisitionTimeInterval", + std::to_string(inper->GetAcquisitionTimeInterval().GetSeconds())}); + m_peripherals.back().AddAttribute( + {"HasStorage", inper->HasStorage() ? "true" : "false"}); + } + } } } // namespace ns3 diff --git a/src/report/report-drone.h b/src/report/report-drone.h index c9342e3..68255b9 100644 --- a/src/report/report-drone.h +++ b/src/report/report-drone.h @@ -15,19 +15,12 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , + * Giovanni Iacovelli */ #ifndef REPORT_DRONE_H #define REPORT_DRONE_H -#include - -#include -#include -#include - -#include - #include "report-data-stats.h" #include "report-entity.h" #include "report-location.h" @@ -35,7 +28,15 @@ #include "report-protocol-stack.h" #include "report-transfer.h" -namespace ns3 { +#include +#include +#include + +#include +#include + +namespace ns3 +{ /** * Retrieve and store data about a drone, like its @@ -46,55 +47,54 @@ namespace ns3 { */ class ReportDrone : public ReportEntity { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); - - /** - * Default constructor - */ - ReportDrone (); - /** - * Default destructor - */ - ~ReportDrone (); - -protected: - void DoInitialize(); - -private: - /** - * Write internal interface - * - * \param handle the XML handler to write data on - */ - void DoWrite (xmlTextWriterPtr h); - - /** - * Initialize probe to get trajectory data - */ - void DoInitializeTrajectoryMonitor (); - - /** - * Callback to monitor drone trajectory - * - * \params mobility the mobility model of the drone to inspect - */ - void DoMonitorTrajectory (const Ptr mobility); - - /** - * Initialize Peripherals - */ - void DoInitializePeripherals (); - - - /// drone trajectory - std::vector m_trajectory; - std::vector m_roi; - std::vector m_peripherals; + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + ReportDrone(); + /** + * Default destructor + */ + ~ReportDrone(); + + protected: + void DoInitialize(); + + private: + /** + * Write internal interface + * + * \param handle the XML handler to write data on + */ + void DoWrite(xmlTextWriterPtr h); + + /** + * Initialize probe to get trajectory data + */ + void DoInitializeTrajectoryMonitor(); + + /** + * Callback to monitor drone trajectory + * + * \params mobility the mobility model of the drone to inspect + */ + void DoMonitorTrajectory(const Ptr mobility); + + /** + * Initialize Peripherals + */ + void DoInitializePeripherals(); + + /// drone trajectory + std::vector m_trajectory; + std::vector m_roi; + std::vector m_peripherals; }; } // namespace ns3 diff --git a/src/report/report-entity.cc b/src/report/report-entity.cc index 8438f6b..8fe5d2b 100644 --- a/src/report/report-entity.cc +++ b/src/report/report-entity.cc @@ -17,470 +17,523 @@ */ #include "report-entity.h" +#include "drone-control-layer.h" +#include "ipv4-layer.h" +#include "lte-ue-phy-layer.h" +#include "report-helper.h" +#include "wifi-inspector.h" +#include "wifi-mac-layer.h" +#include "wifi-phy-layer.h" + #include +#include #include #include #include +#include #include #include #include #include #include -#include #include -#include - -#include "drone-control-layer.h" -#include "ipv4-layer.h" -#include "lte-ue-phy-layer.h" -#include "report-helper.h" -#include "wifi-inspector.h" -#include "wifi-mac-layer.h" -#include "wifi-phy-layer.h" - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportEntity"); -NS_OBJECT_ENSURE_REGISTERED (ReportEntity); +NS_LOG_COMPONENT_DEFINE("ReportEntity"); +NS_OBJECT_ENSURE_REGISTERED(ReportEntity); TypeId -ReportEntity::GetTypeId () +ReportEntity::GetTypeId() { - static TypeId tid = TypeId ("ns3::ReportEntity") - .AddConstructor () - .SetParent () - .AddAttribute ("Reference", "UID of reference", - IntegerValue (0), - MakeIntegerAccessor (&ReportEntity::m_reference), - MakeIntegerChecker ()) - ; - - return tid; + static TypeId tid = TypeId("ns3::ReportEntity") + .AddConstructor() + .SetParent() + .AddAttribute("Reference", + "UID of reference", + IntegerValue(0), + MakeIntegerAccessor(&ReportEntity::m_reference), + MakeIntegerChecker()); + + return tid; } -ReportEntity::ReportEntity () +ReportEntity::ReportEntity() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportEntity::~ReportEntity () +ReportEntity::~ReportEntity() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ReportEntity::Write (xmlTextWriterPtr h) +ReportEntity::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); + NS_LOG_FUNCTION(h); - DoWrite (h); + DoWrite(h); } void -ReportEntity::DoWrite (xmlTextWriterPtr handle) +ReportEntity::DoWrite(xmlTextWriterPtr handle) { } void -ReportEntity::DoInitializeTrajectoryMonitor () +ReportEntity::DoInitializeTrajectoryMonitor() { } void -ReportEntity::DoMonitorTrajectory (const Ptr mobility) +ReportEntity::DoMonitorTrajectory(const Ptr mobility) { } void -ReportEntity::DoInitialize () +ReportEntity::DoInitialize() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - DoInitializeTrajectoryMonitor (); - DoInitializeNetworkStacks (); - DoInitializeDataStats (); - DoInitializeTrafficMonitors (); + DoInitializeTrajectoryMonitor(); + DoInitializeNetworkStacks(); + DoInitializeDataStats(); + DoInitializeTrafficMonitors(); } void -ReportEntity::DoInitializeDataStats () +ReportEntity::DoInitializeDataStats() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - for (uint8_t i = 0; i < PacketType::numValues; i++) + for (uint8_t i = 0; i < PacketType::numValues; i++) { - auto objRx = CreateObjectWithAttributes - ("kind", PacketTypeValue (PacketType (i))); - auto objTx = CreateObjectWithAttributes - ("kind", PacketTypeValue (PacketType (i))); + auto objRx = + CreateObjectWithAttributes("kind", PacketTypeValue(PacketType(i))); + auto objTx = + CreateObjectWithAttributes("kind", PacketTypeValue(PacketType(i))); - m_cumulativeDataRx.push_back (objRx); - m_cumulativeDataTx.push_back (objTx); + m_cumulativeDataRx.push_back(objRx); + m_cumulativeDataTx.push_back(objTx); } } void -ReportEntity::DoInitializeTrafficMonitors () +ReportEntity::DoInitializeTrafficMonitors() { - DoInitializeTrafficMonitor (TransferDirection ("Rx")); - DoInitializeTrafficMonitor (TransferDirection ("Tx")); + DoInitializeTrafficMonitor(TransferDirection("Rx")); + DoInitializeTrafficMonitor(TransferDirection("Tx")); } void -ReportEntity::DoInitializeTrafficMonitor (TransferDirection d) +ReportEntity::DoInitializeTrafficMonitor(TransferDirection d) { - NS_LOG_FUNCTION (d); - /* set IPv4 Rx callback using ns-3 XPath addressing system */ - std::stringstream xPathCallback; + NS_LOG_FUNCTION(d); + /* set IPv4 Rx callback using ns-3 XPath addressing system */ + std::stringstream xPathCallback; - xPathCallback << "/NodeList/" << m_reference << "/" - "$ns3::Ipv4L3Protocol/" << d.ToString (); + xPathCallback << "/NodeList/" << m_reference + << "/" + "$ns3::Ipv4L3Protocol/" + << d.ToString(); - auto connectSuccess = false; - switch (d) + auto connectSuccess = false; + switch (d) { - case TransferDirection::Value::Received: - connectSuccess = Config::ConnectWithoutContextFailSafe - (xPathCallback.str (), MakeCallback (&ReportEntity::DoMonitorRxTraffic, - this)); + case TransferDirection::Value::Received: + connectSuccess = Config::ConnectWithoutContextFailSafe( + xPathCallback.str(), + MakeCallback(&ReportEntity::DoMonitorRxTraffic, this)); break; - case TransferDirection::Value::Transmitted: - connectSuccess = Config::ConnectWithoutContextFailSafe - (xPathCallback.str (), MakeCallback (&ReportEntity::DoMonitorTxTraffic, - this)); + case TransferDirection::Value::Transmitted: + connectSuccess = Config::ConnectWithoutContextFailSafe( + xPathCallback.str(), + MakeCallback(&ReportEntity::DoMonitorTxTraffic, this)); break; } - if (!connectSuccess) - NS_LOG_WARN ("Failed to connect callback to " << xPathCallback.str () - << ". Node IPv4L3Protocol is missing."); + if (!connectSuccess) + NS_LOG_WARN("Failed to connect callback to " << xPathCallback.str() + << ". Node IPv4L3Protocol is missing."); } void -ReportEntity::DoMonitorRxTraffic (Ptr packet, - Ptr ipv4, - uint32_t interface) +ReportEntity::DoMonitorRxTraffic(Ptr packet, Ptr ipv4, uint32_t interface) { - NS_LOG_FUNCTION (packet << ipv4 << interface); - constexpr const char *direction = "Rx"; - std::stringstream builderIpv4Src, - builderIpv4Dst; - std::string ipv4Src, - ipv4Dst; - std::uint32_t payloadSize = 0; - std::uint32_t sequenceNumber = 0; - PacketType packetType; - - constexpr const uint8_t bufferLength = 128; - rapidjson::Document d; - auto pCopy = packet->Copy (); - uint8_t *buf = (uint8_t *) calloc (bufferLength, sizeof (uint8_t)); - - if (buf == nullptr) - NS_FATAL_ERROR ("Cannot allocate " << bufferLength << " bytes " - "to manage packet payload."); - - Ipv4Header ipv4Header; - pCopy->RemoveHeader (ipv4Header); - UdpHeader udpHeader; - pCopy->RemoveHeader (udpHeader); - - builderIpv4Src << ipv4Header.GetSource (); - ipv4Src = builderIpv4Src.str (); - - builderIpv4Dst << ipv4Header.GetDestination (); - ipv4Dst = builderIpv4Dst.str (); - - auto i = pCopy->BeginItem (); - while (i.HasNext ()) + NS_LOG_FUNCTION(packet << ipv4 << interface); + constexpr const char* direction = "Rx"; + std::stringstream builderIpv4Src, builderIpv4Dst; + std::string ipv4Src, ipv4Dst; + std::uint32_t payloadSize = 0; + std::uint32_t sequenceNumber = 0; + PacketType packetType; + + constexpr const uint8_t bufferLength = 128; + rapidjson::Document d; + auto pCopy = packet->Copy(); + uint8_t* buf = (uint8_t*)calloc(bufferLength, sizeof(uint8_t)); + + if (buf == nullptr) + NS_FATAL_ERROR("Cannot allocate " << bufferLength + << " bytes " + "to manage packet payload."); + + Ipv4Header ipv4Header; + pCopy->RemoveHeader(ipv4Header); + UdpHeader udpHeader; + pCopy->RemoveHeader(udpHeader); + + builderIpv4Src << ipv4Header.GetSource(); + ipv4Src = builderIpv4Src.str(); + + builderIpv4Dst << ipv4Header.GetDestination(); + ipv4Dst = builderIpv4Dst.str(); + + auto i = pCopy->BeginItem(); + while (i.HasNext()) { - auto item = i.Next (); + auto item = i.Next(); - if (!item.isFragment && item.type == PacketMetadata::Item::PAYLOAD) + if (!item.isFragment && item.type == PacketMetadata::Item::PAYLOAD) { - payloadSize = item.currentSize; + payloadSize = item.currentSize; - pCopy->CopyData (buf, - (item.currentSize > bufferLength) - ? bufferLength - : item.currentSize); + pCopy->CopyData(buf, + (item.currentSize > bufferLength) ? bufferLength : item.currentSize); - d.Parse ((char *) buf); - if (!d.IsObject ()) - return; + d.Parse((char*)buf); + if (!d.IsObject()) + return; - const char *commandStr = d["cmd"].GetString (); - sequenceNumber = d["sn"].GetUint (); + const char* commandStr = d["cmd"].GetString(); + sequenceNumber = d["sn"].GetUint(); - packetType = PacketType (commandStr); + packetType = PacketType(commandStr); - break; + break; } } - const std::string payloadDecoded ((char *) buf); - free (buf); - - if (payloadSize > 0) - { - m_cumulativeDataRx[packetType]->Add (payloadSize); - - Ipv4Address ipv4dstaddr; - ipv4dstaddr.Set(ipv4Dst.c_str()); - auto reportTransfer = CreateObjectWithAttributes - ("EntityID", IntegerValue (m_reference), - "Interface", IntegerValue (ipv4->GetInterfaceForAddress(ipv4dstaddr)), - "PacketType", PacketTypeValue (packetType), - "TransferDirection", TransferDirectionValue (direction), - "Time", TimeValue (Simulator::Now ()), - "SourceAddress", StringValue (ipv4Src), - "DestinationAddress", StringValue (ipv4Dst), - "PacketLength", IntegerValue (payloadSize), - "SequenceNumber", IntegerValue (sequenceNumber), - "Payload", StringValue (payloadDecoded)); - m_dataRx.push_back (reportTransfer); - } + const std::string payloadDecoded((char*)buf); + free(buf); + + if (payloadSize > 0) + { + m_cumulativeDataRx[packetType]->Add(payloadSize); + + Ipv4Address ipv4dstaddr; + ipv4dstaddr.Set(ipv4Dst.c_str()); + auto reportTransfer = CreateObjectWithAttributes( + "EntityID", + IntegerValue(m_reference), + "Interface", + IntegerValue(ipv4->GetInterfaceForAddress(ipv4dstaddr)), + "PacketType", + PacketTypeValue(packetType), + "TransferDirection", + TransferDirectionValue(direction), + "Time", + TimeValue(Simulator::Now()), + "SourceAddress", + StringValue(ipv4Src), + "DestinationAddress", + StringValue(ipv4Dst), + "PacketLength", + IntegerValue(payloadSize), + "SequenceNumber", + IntegerValue(sequenceNumber), + "Payload", + StringValue(payloadDecoded)); + m_dataRx.push_back(reportTransfer); + } } void -ReportEntity::DoMonitorTxTraffic (Ptr packet, - Ptr ipv4, - uint32_t interface) +ReportEntity::DoMonitorTxTraffic(Ptr packet, Ptr ipv4, uint32_t interface) { - NS_LOG_FUNCTION (packet << ipv4 << interface); - constexpr const char *direction = "Tx"; - std::stringstream builderIpv4Src, - builderIpv4Dst; - std::string ipv4Src, - ipv4Dst; - std::uint32_t payloadSize = 0; - std::uint32_t sequenceNumber = 0; - PacketType packetType; - - constexpr const uint8_t bufferLength = 128; - rapidjson::Document d; - auto pCopy = packet->Copy (); - uint8_t *buf = (uint8_t *) calloc (bufferLength, sizeof (uint8_t)); - - if (buf == nullptr) - NS_FATAL_ERROR ("Cannot allocate " << bufferLength << " bytes " - "to manage packet payload."); - - Ipv4Header ipv4Header; - pCopy->RemoveHeader (ipv4Header); - UdpHeader udpHeader; - pCopy->RemoveHeader (udpHeader); - - builderIpv4Src << ipv4Header.GetSource (); - ipv4Src = builderIpv4Src.str (); - - builderIpv4Dst << ipv4Header.GetDestination (); - ipv4Dst = builderIpv4Dst.str (); - - auto i = pCopy->BeginItem (); - while (i.HasNext ()) + NS_LOG_FUNCTION(packet << ipv4 << interface); + constexpr const char* direction = "Tx"; + std::stringstream builderIpv4Src, builderIpv4Dst; + std::string ipv4Src, ipv4Dst; + std::uint32_t payloadSize = 0; + std::uint32_t sequenceNumber = 0; + PacketType packetType; + + constexpr const uint8_t bufferLength = 128; + rapidjson::Document d; + auto pCopy = packet->Copy(); + uint8_t* buf = (uint8_t*)calloc(bufferLength, sizeof(uint8_t)); + + if (buf == nullptr) + NS_FATAL_ERROR("Cannot allocate " << bufferLength + << " bytes " + "to manage packet payload."); + + Ipv4Header ipv4Header; + pCopy->RemoveHeader(ipv4Header); + UdpHeader udpHeader; + pCopy->RemoveHeader(udpHeader); + + builderIpv4Src << ipv4Header.GetSource(); + ipv4Src = builderIpv4Src.str(); + + builderIpv4Dst << ipv4Header.GetDestination(); + ipv4Dst = builderIpv4Dst.str(); + + auto i = pCopy->BeginItem(); + while (i.HasNext()) { - auto item = i.Next (); - if (!item.isFragment && item.type == PacketMetadata::Item::PAYLOAD) + auto item = i.Next(); + if (!item.isFragment && item.type == PacketMetadata::Item::PAYLOAD) { - payloadSize = item.currentSize; + payloadSize = item.currentSize; - pCopy->CopyData (buf, - (item.currentSize > bufferLength) - ? bufferLength - : item.currentSize); + pCopy->CopyData(buf, + (item.currentSize > bufferLength) ? bufferLength : item.currentSize); - d.Parse ((char *) buf); - if (!d.IsObject ()) - return; + d.Parse((char*)buf); + if (!d.IsObject()) + return; - const char *commandStr = d["cmd"].GetString (); - sequenceNumber = d["sn"].GetUint (); + const char* commandStr = d["cmd"].GetString(); + sequenceNumber = d["sn"].GetUint(); - packetType = PacketType (commandStr); + packetType = PacketType(commandStr); - break; + break; } } - const std::string payloadDecoded ((char *) buf); - free (buf); - - if (payloadSize > 0) - { - m_cumulativeDataTx[packetType]->Add (payloadSize); - Ipv4Address ipv4srcaddr; - ipv4srcaddr.Set(ipv4Src.c_str()); - auto reportTransfer = CreateObjectWithAttributes - ("EntityID", IntegerValue (m_reference), - "Interface", IntegerValue (ipv4->GetInterfaceForAddress(ipv4srcaddr)), - "PacketType", PacketTypeValue (packetType), - "TransferDirection", TransferDirectionValue (direction), - "Time", TimeValue (Simulator::Now ()), - "SourceAddress", StringValue (ipv4Src), - "DestinationAddress", StringValue (ipv4Dst), - "PacketLength", IntegerValue (payloadSize), - "SequenceNumber", IntegerValue (sequenceNumber), - "Payload", StringValue (payloadDecoded)); - m_dataTx.push_back (reportTransfer); - } + const std::string payloadDecoded((char*)buf); + free(buf); + + if (payloadSize > 0) + { + m_cumulativeDataTx[packetType]->Add(payloadSize); + Ipv4Address ipv4srcaddr; + ipv4srcaddr.Set(ipv4Src.c_str()); + auto reportTransfer = CreateObjectWithAttributes( + "EntityID", + IntegerValue(m_reference), + "Interface", + IntegerValue(ipv4->GetInterfaceForAddress(ipv4srcaddr)), + "PacketType", + PacketTypeValue(packetType), + "TransferDirection", + TransferDirectionValue(direction), + "Time", + TimeValue(Simulator::Now()), + "SourceAddress", + StringValue(ipv4Src), + "DestinationAddress", + StringValue(ipv4Dst), + "PacketLength", + IntegerValue(payloadSize), + "SequenceNumber", + IntegerValue(sequenceNumber), + "Payload", + StringValue(payloadDecoded)); + m_dataTx.push_back(reportTransfer); + } } bool -ReportEntity::IsWifiNetDevice (Ptr device) +ReportEntity::IsWifiNetDevice(Ptr device) { - return device->GetInstanceTypeId ().GetName () == "ns3::WifiNetDevice"; + return device->GetInstanceTypeId().GetName() == "ns3::WifiNetDevice"; } const std::tuple -ReportEntity::GetIpv4Address (Ptr dev) +ReportEntity::GetIpv4Address(Ptr dev) { - const auto node = NodeList::GetNode (m_reference); - const auto nodeIpv4 = node->GetObject (); - - if (nodeIpv4 == nullptr) - return std::tuple {-2, "", ""}; - - const auto ifid = nodeIpv4->GetInterfaceForDevice(dev); - // FIXME: we should bring all addresses available for all interfaces - if (ifid == -1) return std::tuple {-1, "", ""}; - - const auto firstIpv4Addr = nodeIpv4->GetAddress (ifid, 0); - std::stringstream localIpv4AddrBuilder, netmaskIpv4AddrBuilder; - firstIpv4Addr.GetLocal ().Print (localIpv4AddrBuilder); - firstIpv4Addr.GetBroadcast ().Print (netmaskIpv4AddrBuilder); - - return {ifid, localIpv4AddrBuilder.str (), netmaskIpv4AddrBuilder.str ()}; - - - // REMOVE FROM HERE - // std::stringstream bPath; - - // bPath << "/NodeList/" << m_reference; - // auto matches = Config::LookupMatches (bPath.str ()); - - // for (std::size_t i = 0; i < matches.GetN (); i++) - // { - // auto match = StaticCast (matches.Get (i)); - // const auto matchClassName = match->GetInstanceTypeId (); - - /* - * FIXME: this is not valid anymore! - * Assumption: only one DroneClient is available on a Drone and - * only one DroneServer is available on a ZSP - */ - // if (matchClassName == "ns3::DroneClientApplication" - // || matchClassName == "ns3::DroneServerApplication") - // { - // TypeId::AttributeInformation info; - // Ipv4AddressValue ipv4Address; - // Ipv4MaskValue ipv4NetMask; - // std::stringstream bIpv4Address, - // bIpv4NetMask; - - // match->GetInstanceTypeId ().LookupAttributeByName ("Ipv4Address", - // &info); - // // This method should support Ptr<> type! - // info.accessor->Get (&(*match), ipv4Address); - // match->GetInstanceTypeId ().LookupAttributeByName ("Ipv4SubnetMask", - // &info); - // info.accessor->Get (&(*match), ipv4NetMask); - - // bIpv4Address << ipv4Address.Get (); - // bIpv4NetMask << ipv4NetMask.Get (); - - // return {bIpv4Address.str (), bIpv4NetMask.str ()}; - // } + const auto node = NodeList::GetNode(m_reference); + const auto nodeIpv4 = node->GetObject(); + + if (nodeIpv4 == nullptr) + return std::tuple{-2, "", ""}; + + const auto ifid = nodeIpv4->GetInterfaceForDevice(dev); + // FIXME: we should bring all addresses available for all interfaces + if (ifid == -1) + return std::tuple{-1, "", ""}; + + const auto firstIpv4Addr = nodeIpv4->GetAddress(ifid, 0); + std::stringstream localIpv4AddrBuilder, netmaskIpv4AddrBuilder; + firstIpv4Addr.GetLocal().Print(localIpv4AddrBuilder); + firstIpv4Addr.GetBroadcast().Print(netmaskIpv4AddrBuilder); + + return {ifid, localIpv4AddrBuilder.str(), netmaskIpv4AddrBuilder.str()}; + + // REMOVE FROM HERE + // std::stringstream bPath; + + // bPath << "/NodeList/" << m_reference; + // auto matches = Config::LookupMatches (bPath.str ()); + + // for (std::size_t i = 0; i < matches.GetN (); i++) + // { + // auto match = StaticCast (matches.Get (i)); + // const auto matchClassName = match->GetInstanceTypeId (); + + /* + * FIXME: this is not valid anymore! + * Assumption: only one DroneClient is available on a Drone and + * only one DroneServer is available on a ZSP + */ + // if (matchClassName == "ns3::DroneClientApplication" + // || matchClassName == "ns3::DroneServerApplication") + // { + // TypeId::AttributeInformation info; + // Ipv4AddressValue ipv4Address; + // Ipv4MaskValue ipv4NetMask; + // std::stringstream bIpv4Address, + // bIpv4NetMask; + + // match->GetInstanceTypeId ().LookupAttributeByName ("Ipv4Address", + // &info); + // // This method should support Ptr<> type! + // info.accessor->Get (&(*match), ipv4Address); + // match->GetInstanceTypeId ().LookupAttributeByName ("Ipv4SubnetMask", + // &info); + // info.accessor->Get (&(*match), ipv4NetMask); + + // bIpv4Address << ipv4Address.Get (); + // bIpv4NetMask << ipv4NetMask.Get (); + + // return {bIpv4Address.str (), bIpv4NetMask.str ()}; + // } // } - // NS_FATAL_ERROR ("Expected to find a Client/Server Application on " - // "entity, but it was not there!"); + // NS_FATAL_ERROR ("Expected to find a Client/Server Application on " + // "entity, but it was not there!"); } void -ReportEntity::DoInitializeNetworkStacks () +ReportEntity::DoInitializeNetworkStacks() { - NS_LOG_FUNCTION_NOARGS (); - Ptr node = NodeList::GetNode(m_reference); - std::vector ifaces; // ifaces that needs to be registered - - if (node == nullptr) - NS_FATAL_ERROR ("Report is trying to monitor NodeId " << m_reference << ", " - "but the object is null!"); - uint32_t netdevN = node->GetNDevices (); - for (uint32_t i = 0; i < netdevN; i++) + NS_LOG_FUNCTION_NOARGS(); + Ptr node = NodeList::GetNode(m_reference); + std::vector ifaces; // ifaces that needs to be registered + + if (node == nullptr) + NS_FATAL_ERROR("Report is trying to monitor NodeId " << m_reference + << ", " + "but the object is null!"); + uint32_t netdevN = node->GetNDevices(); + for (uint32_t i = 0; i < netdevN; i++) { - auto dev = node->GetDevice (i); - auto ipv4AddressMask = GetIpv4Address (dev); - auto ifid = std::get<0>(ipv4AddressMask); - if (ifid == -1) continue; - while ((int) m_networkStacks.size()<= (int) ifid) m_networkStacks.push_back ({}); - if (IsWifiNetDevice (dev)) + auto dev = node->GetDevice(i); + auto ipv4AddressMask = GetIpv4Address(dev); + auto ifid = std::get<0>(ipv4AddressMask); + if (ifid == -1) + continue; + while ((int)m_networkStacks.size() <= (int)ifid) + m_networkStacks.push_back({}); + if (IsWifiNetDevice(dev)) + { + auto inspector = WifiInspector(dev); + auto layer = CreateObjectWithAttributes( + "InstanceType", + StringValue(dev->GetInstanceTypeId().GetName())); + auto phyLayer = CreateObjectWithAttributes( + "Frequency", + IntegerValue(inspector.GetCarrierFrequency()), + "Standard", + StringValue(inspector.GetWifiStandard()), + "PropagationDelayModel", + StringValue(inspector.GetPropagationDelayModel()), + "PropagationLossModel", + StringValue(inspector.GetPropagationLossModel()), + "NodeId", + IntegerValue(m_reference), + "NetdevId", + IntegerValue(i)); + auto macLayer = + CreateObjectWithAttributes("Ssid", + StringValue(inspector.GetWifiSsid()), + "Mode", + StringValue(inspector.GetWifiMode())); + auto ipv4Layer = + CreateObjectWithAttributes("Ipv4Address", + StringValue(std::get<1>(ipv4AddressMask)), + "SubnetMask", + StringValue(std::get<2>(ipv4AddressMask))); + auto droneControlLayer = + CreateObjectWithAttributes("NotImplemented", StringValue()); + + phyLayer->Initialize(); + + ifaces.push_back(i); + m_networkStacks[ifid].Add(layer); + m_networkStacks[ifid].Add(phyLayer); + m_networkStacks[ifid].Add(macLayer); + m_networkStacks[ifid].Add(ipv4Layer); + m_networkStacks[ifid].Add(droneControlLayer); + } + else if (dev->GetInstanceTypeId().GetName() == "ns3::LteUeNetDevice") + { + auto lteuenetdev = StaticCast(dev); + NS_ASSERT(lteuenetdev->GetCcMap().begin() != lteuenetdev->GetCcMap().end()); + auto ccmap = (lteuenetdev->GetCcMap().begin())->second; + + auto pldltype = ccmap->GetPhy() + ->GetDlSpectrumPhy() + ->GetChannel() + ->GetPropagationLossModel() + ->GetInstanceTypeId() + .GetName(); + auto plultype = ccmap->GetPhy() + ->GetUlSpectrumPhy() + ->GetChannel() + ->GetPropagationLossModel() + ->GetInstanceTypeId() + .GetName(); + auto layer = CreateObjectWithAttributes( + "InstanceType", + StringValue(dev->GetInstanceTypeId().GetName())); + auto phyLayer = CreateObjectWithAttributes( + "IMSI", + StringValue(std::to_string(lteuenetdev->GetImsi())), + "PropagationLossModelDl", + StringValue(pldltype), + "PropagationLossModelUl", + StringValue(plultype), + "DlEarfcn", + StringValue(std::to_string(ccmap->GetDlEarfcn())), + "DlBandwidth", + StringValue(std::to_string(ccmap->GetDlBandwidth())), + "UlEarfcn", + StringValue(std::to_string(ccmap->GetUlEarfcn())), + "UlBandwidth", + StringValue(std::to_string(ccmap->GetUlBandwidth()))); + + auto ipv4Layer = + CreateObjectWithAttributes("Ipv4Address", + StringValue(std::get<1>(ipv4AddressMask)), + "SubnetMask", + StringValue(std::get<2>(ipv4AddressMask))); + ifaces.push_back(i); + m_networkStacks[ifid].Add(layer); + m_networkStacks[ifid].Add(phyLayer); + m_networkStacks[ifid].Add(ipv4Layer); + } + else { - auto inspector = WifiInspector (dev); - auto layer = CreateObjectWithAttributes - ("InstanceType", StringValue (dev->GetInstanceTypeId ().GetName ())); - auto phyLayer = CreateObjectWithAttributes - ("Frequency", IntegerValue (inspector.GetCarrierFrequency ()), - "Standard", StringValue (inspector.GetWifiStandard ()), - "PropagationDelayModel", StringValue (inspector.GetPropagationDelayModel ()), - "PropagationLossModel", StringValue (inspector.GetPropagationLossModel ()), - "NodeId", IntegerValue (m_reference), - "NetdevId", IntegerValue (i)); - auto macLayer = CreateObjectWithAttributes - ("Ssid", StringValue (inspector.GetWifiSsid ()), - "Mode", StringValue (inspector.GetWifiMode ())); - auto ipv4Layer = CreateObjectWithAttributes - ("Ipv4Address", StringValue (std::get<1>(ipv4AddressMask)), - "SubnetMask", StringValue (std::get<2>(ipv4AddressMask))); - auto droneControlLayer = CreateObjectWithAttributes - ("NotImplemented", StringValue ()); - - phyLayer->Initialize (); - - ifaces.push_back (i); - m_networkStacks[ifid].Add (layer); - m_networkStacks[ifid].Add (phyLayer); - m_networkStacks[ifid].Add (macLayer); - m_networkStacks[ifid].Add (ipv4Layer); - m_networkStacks[ifid].Add (droneControlLayer); - } else if (dev->GetInstanceTypeId ().GetName () == "ns3::LteUeNetDevice") { - auto lteuenetdev = StaticCast (dev); - NS_ASSERT(lteuenetdev->GetCcMap().begin() != lteuenetdev->GetCcMap().end()); - auto ccmap = (lteuenetdev->GetCcMap().begin())->second; - - auto pldltype = ccmap->GetPhy()->GetDlSpectrumPhy ()->GetChannel()->GetPropagationLossModel()->GetInstanceTypeId().GetName(); - auto plultype = ccmap->GetPhy()->GetUlSpectrumPhy ()->GetChannel()->GetPropagationLossModel()->GetInstanceTypeId().GetName(); - auto layer = CreateObjectWithAttributes - ("InstanceType", StringValue (dev->GetInstanceTypeId ().GetName ())); - auto phyLayer = CreateObjectWithAttributes - ("IMSI", StringValue (std::to_string(lteuenetdev->GetImsi())), - "PropagationLossModelDl", StringValue (pldltype), - "PropagationLossModelUl", StringValue (plultype), - "DlEarfcn", StringValue (std::to_string(ccmap->GetDlEarfcn())), - "DlBandwidth", StringValue (std::to_string(ccmap->GetDlBandwidth())), - "UlEarfcn", StringValue (std::to_string(ccmap->GetUlEarfcn())), - "UlBandwidth", StringValue (std::to_string(ccmap->GetUlBandwidth()))); - - auto ipv4Layer = CreateObjectWithAttributes - ("Ipv4Address", StringValue (std::get<1>(ipv4AddressMask)), - "SubnetMask", StringValue (std::get<2>(ipv4AddressMask))); - ifaces.push_back (i); - m_networkStacks[ifid].Add (layer); - m_networkStacks[ifid].Add (phyLayer); - m_networkStacks[ifid].Add (ipv4Layer); - } else { - auto layer = CreateObjectWithAttributes - ("InstanceType", StringValue (dev->GetInstanceTypeId ().GetName ())); - - auto ipv4Layer = CreateObjectWithAttributes - ("Ipv4Address", StringValue (std::get<1>(ipv4AddressMask)), - "SubnetMask", StringValue (std::get<2>(ipv4AddressMask))); - ifaces.push_back (i); - m_networkStacks[ifid].Add (layer); - m_networkStacks[ifid].Add (ipv4Layer); + auto layer = CreateObjectWithAttributes( + "InstanceType", + StringValue(dev->GetInstanceTypeId().GetName())); + + auto ipv4Layer = + CreateObjectWithAttributes("Ipv4Address", + StringValue(std::get<1>(ipv4AddressMask)), + "SubnetMask", + StringValue(std::get<2>(ipv4AddressMask))); + ifaces.push_back(i); + m_networkStacks[ifid].Add(layer); + m_networkStacks[ifid].Add(ipv4Layer); } } } diff --git a/src/report/report-entity.h b/src/report/report-entity.h index 2ceb12d..c56a231 100644 --- a/src/report/report-entity.h +++ b/src/report/report-entity.h @@ -15,11 +15,15 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , + * Giovanni Iacovelli */ #ifndef REPORT_ENTITY_H #define REPORT_ENTITY_H -#include +#include "report-data-stats.h" +#include "report-location.h" +#include "report-protocol-stack.h" +#include "report-transfer.h" #include #include @@ -27,13 +31,10 @@ #include #include +#include -#include "report-data-stats.h" -#include "report-location.h" -#include "report-protocol-stack.h" -#include "report-transfer.h" - -namespace ns3 { +namespace ns3 +{ /** * Generic object to address common report functionalities between IoD_Sim @@ -46,125 +47,123 @@ namespace ns3 { */ class ReportEntity : public Object { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); - - /** - * Default constructor - */ - ReportEntity (); - /** - * Default destructor - */ - ~ReportEntity (); - - /** - * Write Entity report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - void Write (xmlTextWriterPtr handle); -protected: - /** - * Object internal initialization - */ - void DoInitialize (); - - /** - * Write internal interface - * - * \param handle the XML handler to write data on - */ - virtual void DoWrite (xmlTextWriterPtr handle); - - /** - * Initialize probe to get trajectory data - */ - virtual void DoInitializeTrajectoryMonitor (); - - /** - * Callback to monitor entity trajectory - * - * \params mobility the mobility model of the entity to inspect - */ - virtual void DoMonitorTrajectory (const Ptr mobility); - - /** - * Callback to monitor incoming IPv4 packets - * - * \param packet the incoming IPv4 payload - * \param ipv4 the IPv4 header - * \param interface drone interface ID - */ - void DoMonitorRxTraffic (Ptr packet, - Ptr ipv4, - uint32_t interface); - - /** - * Callback to monitor outgoing IPv4 packets - * - * \param packet the incoming IPv4 payload - * \param ipv4 the IPv4 header - * \param interface drone interface ID - */ - void DoMonitorTxTraffic (Ptr packet, - Ptr ipv4, - uint32_t interface); - - /** - * Helper to check if NetDevice is a WifiNetDevice - * - * \param device the network device to inspect - */ - static bool IsWifiNetDevice (Ptr device); - - /** - * Helper to get interface registered IP Address - * - * \param drone the drone to inspect - * \return a tuple with the IPv4 address and its Network Mask - */ - const std::tuple GetIpv4Address (Ptr dev); - - /// cumulative Stats in Rx - std::vector> m_cumulativeDataRx; - /// cumulative Stats in Tx - std::vector> m_cumulativeDataTx; - /// monitored traffix Rx - std::vector> m_dataRx; - /// monitored traffic Tx - std::vector> m_dataTx; - /// abstract representation of the network stacks used - std::vector m_networkStacks; - - uint32_t m_reference; /// Entity UID of reference -private: - /** - * Initialize Data Stats accumulators - */ - void DoInitializeDataStats (); - - /** - * Helper to initialize traffic monitor for both Rx and Tx directions - */ - inline void DoInitializeTrafficMonitors (); - - /** - * Initialize traffic monitor for a given direction relative to the - * observed node - * - * \param direction the direction of the traffic flow - */ - void DoInitializeTrafficMonitor (TransferDirection direction); - - /** - * Build an abstraction of entity's network stacks - */ - void DoInitializeNetworkStacks (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + ReportEntity(); + /** + * Default destructor + */ + ~ReportEntity(); + + /** + * Write Entity report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + void Write(xmlTextWriterPtr handle); + + protected: + /** + * Object internal initialization + */ + void DoInitialize(); + + /** + * Write internal interface + * + * \param handle the XML handler to write data on + */ + virtual void DoWrite(xmlTextWriterPtr handle); + + /** + * Initialize probe to get trajectory data + */ + virtual void DoInitializeTrajectoryMonitor(); + + /** + * Callback to monitor entity trajectory + * + * \params mobility the mobility model of the entity to inspect + */ + virtual void DoMonitorTrajectory(const Ptr mobility); + + /** + * Callback to monitor incoming IPv4 packets + * + * \param packet the incoming IPv4 payload + * \param ipv4 the IPv4 header + * \param interface drone interface ID + */ + void DoMonitorRxTraffic(Ptr packet, Ptr ipv4, uint32_t interface); + + /** + * Callback to monitor outgoing IPv4 packets + * + * \param packet the incoming IPv4 payload + * \param ipv4 the IPv4 header + * \param interface drone interface ID + */ + void DoMonitorTxTraffic(Ptr packet, Ptr ipv4, uint32_t interface); + + /** + * Helper to check if NetDevice is a WifiNetDevice + * + * \param device the network device to inspect + */ + static bool IsWifiNetDevice(Ptr device); + + /** + * Helper to get interface registered IP Address + * + * \param drone the drone to inspect + * \return a tuple with the IPv4 address and its Network Mask + */ + const std::tuple GetIpv4Address( + Ptr dev); + + /// cumulative Stats in Rx + std::vector> m_cumulativeDataRx; + /// cumulative Stats in Tx + std::vector> m_cumulativeDataTx; + /// monitored traffix Rx + std::vector> m_dataRx; + /// monitored traffic Tx + std::vector> m_dataTx; + /// abstract representation of the network stacks used + std::vector m_networkStacks; + + uint32_t m_reference; /// Entity UID of reference + private: + /** + * Initialize Data Stats accumulators + */ + void DoInitializeDataStats(); + + /** + * Helper to initialize traffic monitor for both Rx and Tx directions + */ + inline void DoInitializeTrafficMonitors(); + + /** + * Initialize traffic monitor for a given direction relative to the + * observed node + * + * \param direction the direction of the traffic flow + */ + void DoInitializeTrafficMonitor(TransferDirection direction); + + /** + * Build an abstraction of entity's network stacks + */ + void DoInitializeNetworkStacks(); }; } // namespace ns3 diff --git a/src/report/report-helper.cc b/src/report/report-helper.cc index 57b1c36..61aa951 100644 --- a/src/report/report-helper.cc +++ b/src/report/report-helper.cc @@ -17,12 +17,14 @@ */ #include "report-helper.h" -namespace ns3 { +namespace ns3 +{ -void ReportHelper::SetScenarioName (std::string scenarioName) +void +ReportHelper::SetScenarioName(std::string scenarioName) { - //auto r = ReportSimulation::Get(); - //r->SetScenarioName (scenarioName); + // auto r = ReportSimulation::Get(); + // r->SetScenarioName (scenarioName); } } // namespace ns3 diff --git a/src/report/report-helper.h b/src/report/report-helper.h index 5bf453a..702ce47 100644 --- a/src/report/report-helper.h +++ b/src/report/report-helper.h @@ -20,11 +20,12 @@ #ifndef REPORT_HELPER_H #define REPORT_HELPER_H -namespace ns3 { +namespace ns3 +{ class ReportHelper { - void SetScenarioName (std::string); + void SetScenarioName(std::string); }; } // namespace ns3 diff --git a/src/report/report-location.cc b/src/report/report-location.cc index 0355657..6c4f7f2 100644 --- a/src/report/report-location.cc +++ b/src/report/report-location.cc @@ -21,85 +21,87 @@ #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportLocation"); +NS_LOG_COMPONENT_DEFINE("ReportLocation"); -ReportLocation::ReportLocation (Vector position, Time instant, int roi) : - m_position {position}, - m_instant {instant}, - m_roi {roi} +ReportLocation::ReportLocation(Vector position, Time instant, int roi) + : m_position{position}, + m_instant{instant}, + m_roi{roi} { - NS_LOG_FUNCTION (this << position << instant); + NS_LOG_FUNCTION(this << position << instant); } -ReportLocation::ReportLocation (Vector position, Time instant) : - m_position {position}, - m_instant {instant}, - m_roi {-2} +ReportLocation::ReportLocation(Vector position, Time instant) + : m_position{position}, + m_instant{instant}, + m_roi{-2} { - NS_LOG_FUNCTION (this << position << instant); + NS_LOG_FUNCTION(this << position << instant); } -ReportLocation::ReportLocation () +ReportLocation::ReportLocation() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportLocation::~ReportLocation () +ReportLocation::~ReportLocation() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } Vector ReportLocation::GetPosition() { - return m_position; + return m_position; } void -ReportLocation::Write (xmlTextWriterPtr h) +ReportLocation::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement(h, BAD_CAST "position"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "position"); + NS_ASSERT(rc >= 0); - /* Nested Elements */ - std::stringstream bX, bY, bZ, bT; - bX << m_position.x; - bY << m_position.y; - bZ << m_position.z; - bT << m_instant.GetNanoSeconds (); + /* Nested Elements */ + std::stringstream bX, bY, bZ, bT; + bX << m_position.x; + bY << m_position.y; + bZ << m_position.z; + bT << m_instant.GetNanoSeconds(); - rc = xmlTextWriterWriteElement (h, BAD_CAST "x", BAD_CAST bX.str ().c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "x", BAD_CAST bX.str().c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "y", BAD_CAST bY.str ().c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "y", BAD_CAST bY.str().c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "z", BAD_CAST bZ.str ().c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "z", BAD_CAST bZ.str().c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "t", BAD_CAST bT.str ().c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "t", BAD_CAST bT.str().c_str()); + NS_ASSERT(rc >= 0); - if (m_roi != -2) - { - rc = xmlTextWriterWriteElement (h, BAD_CAST "RoI", BAD_CAST std::to_string(m_roi).c_str ()); - NS_ASSERT (rc >= 0); - } + if (m_roi != -2) + { + rc = xmlTextWriterWriteElement(h, BAD_CAST "RoI", BAD_CAST std::to_string(m_roi).c_str()); + NS_ASSERT(rc >= 0); + } - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/report-location.h b/src/report/report-location.h index be07d89..3140612 100644 --- a/src/report/report-location.h +++ b/src/report/report-location.h @@ -15,7 +15,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , Giovanni Iacovelli + * */ #ifndef REPORT_LOCATION_H #define REPORT_LOCATION_H @@ -24,40 +25,42 @@ #include -namespace ns3 { +namespace ns3 +{ class ReportLocation { -public: + public: /** * Initialize a report location with a given position, instant, and region of interest */ - ReportLocation (Vector position, Time instant, int roi); + ReportLocation(Vector position, Time instant, int roi); /** * Initialize a report location with a given position and instant */ - ReportLocation (Vector position, Time instant); + ReportLocation(Vector position, Time instant); /** * Default constructor for commodity purposes */ - ReportLocation (); + ReportLocation(); /** * Default destructor */ - ~ReportLocation (); + ~ReportLocation(); /** - * \return the position vector - */ + * \return the position vector + */ Vector GetPosition(); /** * Write Zsp report data to a XML file with a given handler * * \param handle the XML handler to write data on */ - void Write (xmlTextWriterPtr handle); -private: - Vector m_position; /// the position descibing the location - Time m_instant; /// the time at which this position is assumed + void Write(xmlTextWriterPtr handle); + + private: + Vector m_position; /// the position descibing the location + Time m_instant; /// the time at which this position is assumed int m_roi; }; diff --git a/src/report/report-peripheral.cc b/src/report/report-peripheral.cc index af7a244..b65dba5 100644 --- a/src/report/report-peripheral.cc +++ b/src/report/report-peripheral.cc @@ -21,82 +21,94 @@ #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportPeripheral"); +NS_LOG_COMPONENT_DEFINE("ReportPeripheral"); -ReportPeripheral::ReportPeripheral (std::string tid, std::vector powerConsumptionStates, std::vector roi) : - m_tid {tid}, - m_powerConsumptionStates {powerConsumptionStates}, - m_roi {roi} +ReportPeripheral::ReportPeripheral(std::string tid, + std::vector powerConsumptionStates, + std::vector roi) + : m_tid{tid}, + m_powerConsumptionStates{powerConsumptionStates}, + m_roi{roi} { - NS_LOG_FUNCTION (this << tid); + NS_LOG_FUNCTION(this << tid); } -ReportPeripheral::~ReportPeripheral () +ReportPeripheral::~ReportPeripheral() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void ReportPeripheral::AddAttribute(std::tuple attr) { - m_otherAttributes.push_back(attr); + m_otherAttributes.push_back(attr); } void -ReportPeripheral::Write (xmlTextWriterPtr h) +ReportPeripheral::Write(xmlTextWriterPtr h) { - std::stringstream roistr; - NS_LOG_FUNCTION (h); - if (h == nullptr) + std::stringstream roistr; + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement(h, BAD_CAST "peripheral"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "peripheral"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "typeID", BAD_CAST m_tid.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "typeID", BAD_CAST m_tid.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement(h, BAD_CAST "PowerConsumptionStates"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "PowerConsumptionStates"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "OFF", BAD_CAST std::to_string(m_powerConsumptionStates[0]).c_str ()); - NS_ASSERT (rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "IDLE", BAD_CAST std::to_string(m_powerConsumptionStates[1]).c_str ()); - NS_ASSERT (rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "ON", BAD_CAST std::to_string(m_powerConsumptionStates[2]).c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, + BAD_CAST "OFF", + BAD_CAST std::to_string(m_powerConsumptionStates[0]).c_str()); + NS_ASSERT(rc >= 0); + rc = xmlTextWriterWriteElement(h, + BAD_CAST "IDLE", + BAD_CAST std::to_string(m_powerConsumptionStates[1]).c_str()); + NS_ASSERT(rc >= 0); + rc = xmlTextWriterWriteElement(h, + BAD_CAST "ON", + BAD_CAST std::to_string(m_powerConsumptionStates[2]).c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - if (m_roi.size () > 0) + if (m_roi.size() > 0) { - for (auto r : m_roi) - roistr << std::to_string (r) << ", "; + for (auto r : m_roi) + roistr << std::to_string(r) << ", "; - std::string roiser = roistr.str (); - roiser.pop_back (); + std::string roiser = roistr.str(); + roiser.pop_back(); - rc = xmlTextWriterWriteElement (h, BAD_CAST "RoITrigger", BAD_CAST roiser.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "RoITrigger", BAD_CAST roiser.c_str()); + NS_ASSERT(rc >= 0); } - for (auto attr : m_otherAttributes) + for (auto attr : m_otherAttributes) { - rc = xmlTextWriterWriteElement (h, BAD_CAST std::get<0> (attr).c_str (), BAD_CAST std::get<1> (attr).c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, + BAD_CAST std::get<0>(attr).c_str(), + BAD_CAST std::get<1>(attr).c_str()); + NS_ASSERT(rc >= 0); } - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/report-peripheral.h b/src/report/report-peripheral.h index 2a1ac6d..d207260 100644 --- a/src/report/report-peripheral.h +++ b/src/report/report-peripheral.h @@ -23,19 +23,20 @@ #include -namespace ns3 { +namespace ns3 +{ class ReportPeripheral { -public: + public: /** * Initialize a report peripheral with a given power consumptions and regions of interest */ - ReportPeripheral (std::string, std::vector, std::vector); + ReportPeripheral(std::string, std::vector, std::vector); /** * Default destructor */ - ~ReportPeripheral (); + ~ReportPeripheral(); /** * \param a tuple containing the name and the value (string) of an additional attribute */ @@ -45,11 +46,12 @@ class ReportPeripheral * * \param handle the XML handler to write data on */ - void Write (xmlTextWriterPtr handle); -private: + void Write(xmlTextWriterPtr handle); + + private: std::string m_tid; std::vector m_powerConsumptionStates; //!< Power consumptions for each state - std::vector m_roi; //!< Regions of interest indexes + std::vector m_roi; //!< Regions of interest indexes std::vector> m_otherAttributes; }; diff --git a/src/report/report-protocol-stack.cc b/src/report/report-protocol-stack.cc index 9b2a540..7f7811b 100644 --- a/src/report/report-protocol-stack.cc +++ b/src/report/report-protocol-stack.cc @@ -21,69 +21,71 @@ #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportProtocolStack"); +NS_LOG_COMPONENT_DEFINE("ReportProtocolStack"); -ReportProtocolStack::ReportProtocolStack () +ReportProtocolStack::ReportProtocolStack() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } ReportProtocolStack::Iterator -ReportProtocolStack::Begin () const +ReportProtocolStack::Begin() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_layers.begin (); + return m_layers.begin(); } ReportProtocolStack::Iterator -ReportProtocolStack::End () const +ReportProtocolStack::End() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_layers.end (); + return m_layers.end(); } uint32_t -ReportProtocolStack::GetN () const +ReportProtocolStack::GetN() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_layers.size (); + return m_layers.size(); } Ptr -ReportProtocolStack::Get (const uint32_t i) const +ReportProtocolStack::Get(const uint32_t i) const { - NS_LOG_FUNCTION (i); + NS_LOG_FUNCTION(i); - return m_layers[i]; + return m_layers[i]; } void -ReportProtocolStack::Add (Ptr layer) +ReportProtocolStack::Add(Ptr layer) { - NS_LOG_FUNCTION (layer); + NS_LOG_FUNCTION(layer); - m_layers.push_back (layer); + m_layers.push_back(layer); } void -ReportProtocolStack::Write (xmlTextWriterPtr h) +ReportProtocolStack::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - /* Nested Elements */ - for (auto& layer : m_layers) - layer->Write (h); + /* Nested Elements */ + for (auto& layer : m_layers) + layer->Write(h); } } // namespace ns3 diff --git a/src/report/report-protocol-stack.h b/src/report/report-protocol-stack.h index 87652c3..9445b84 100644 --- a/src/report/report-protocol-stack.h +++ b/src/report/report-protocol-stack.h @@ -19,56 +19,57 @@ */ #ifndef REPORT_PROTOCOL_STACK_H #define REPORT_PROTOCOL_STACK_H -#include +#include "protocol-layer.h" #include +#include -#include "protocol-layer.h" - -namespace ns3 { +namespace ns3 +{ class ReportProtocolStack { -public: - /// Protocol Layers iterator - typedef std::vector>::const_iterator Iterator; + public: + /// Protocol Layers iterator + typedef std::vector>::const_iterator Iterator; + + /** + * Create an empty ReportProtocolStack + */ + ReportProtocolStack(); - /** - * Create an empty ReportProtocolStack - */ - ReportProtocolStack (); + /** + * Get an iterator which refers to the base Protocol Layer in the stack + */ + Iterator Begin() const; - /** - * Get an iterator which refers to the base Protocol Layer in the stack - */ - Iterator Begin () const; + /** + * Get an iterator which indicates past-the-top Protocol Layer in the stack + */ + Iterator End() const; - /** - * Get an iterator which indicates past-the-top Protocol Layer in the stack - */ - Iterator End () const; + /** + * Get the number of Ptr stored in the stack + */ + uint32_t GetN() const; - /** - * Get the number of Ptr stored in the stack - */ - uint32_t GetN () const; + /** + * Get the Ptr stored in the stack at the given index + */ + Ptr Get(const uint32_t i) const; - /** - * Get the Ptr stored in the stack at the given index - */ - Ptr Get (const uint32_t i) const; + /** + * Place a single Ptr to the top of the stack + */ + void Add(Ptr layer); - /** - * Place a single Ptr to the top of the stack - */ - void Add (Ptr layer); + /** + * Write Protocol Stack report data to a XML file with a given handler + */ + void Write(xmlTextWriterPtr handle); - /** - * Write Protocol Stack report data to a XML file with a given handler - */ - void Write (xmlTextWriterPtr handle); -private: - std::vector> m_layers; /// the stack + private: + std::vector> m_layers; /// the stack }; } // namespace ns3 diff --git a/src/report/report-remote.cc b/src/report/report-remote.cc index d2a8445..7a4adf6 100644 --- a/src/report/report-remote.cc +++ b/src/report/report-remote.cc @@ -15,10 +15,17 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , Giovanni Iacovelli + * */ #include "report-remote.h" +#include "drone-control-layer.h" +#include "ipv4-layer.h" +#include "wifi-inspector.h" +#include "wifi-mac-layer.h" +#include "wifi-phy-layer.h" + #include #include #include @@ -32,141 +39,141 @@ #include -#include "drone-control-layer.h" -#include "ipv4-layer.h" -#include "wifi-inspector.h" -#include "wifi-mac-layer.h" -#include "wifi-phy-layer.h" - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportRemote"); -NS_OBJECT_ENSURE_REGISTERED (ReportRemote); +NS_LOG_COMPONENT_DEFINE("ReportRemote"); +NS_OBJECT_ENSURE_REGISTERED(ReportRemote); TypeId -ReportRemote::GetTypeId () +ReportRemote::GetTypeId() { - static TypeId tid = TypeId ("ns3::ReportRemote") - .AddConstructor () - .SetParent () - ; + static TypeId tid = + TypeId("ns3::ReportRemote").AddConstructor().SetParent(); - return tid; + return tid; } -ReportRemote::ReportRemote () +ReportRemote::ReportRemote() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportRemote::~ReportRemote () +ReportRemote::~ReportRemote() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ReportRemote::DoWrite (xmlTextWriterPtr h) +ReportRemote::DoWrite(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; - - rc = xmlTextWriterStartElement (h, BAD_CAST "Remote"); - NS_ASSERT (rc >= 0); + int rc; - /* Nested Elements */ - rc = xmlTextWriterStartElement (h, BAD_CAST "NetDevices"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "Remote"); + NS_ASSERT(rc >= 0); - for (int nid = 0; nid < (int) m_networkStacks.size(); nid++) - { - rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevice"); - NS_ASSERT (rc >= 0); + /* Nested Elements */ + rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevices"); + NS_ASSERT(rc >= 0); - m_networkStacks[nid].Write (h); - - rc = xmlTextWriterStartElement (h, BAD_CAST "dataTx"); - NS_ASSERT (rc >= 0); - - for (auto rid=m_dataTx.begin(); rid !=m_dataTx.end();) + for (int nid = 0; nid < (int)m_networkStacks.size(); nid++) { - if ((*rid)->GetIface() == nid) - { - (*rid)->Write (h); - m_dataTx.erase(rid); - } else { - rid++; - } + rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevice"); + NS_ASSERT(rc >= 0); + + m_networkStacks[nid].Write(h); + + rc = xmlTextWriterStartElement(h, BAD_CAST "dataTx"); + NS_ASSERT(rc >= 0); + + for (auto rid = m_dataTx.begin(); rid != m_dataTx.end();) + { + if ((*rid)->GetIface() == nid) + { + (*rid)->Write(h); + m_dataTx.erase(rid); + } + else + { + rid++; + } + } + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterStartElement(h, BAD_CAST "dataRx"); + NS_ASSERT(rc >= 0); + + for (auto rid = m_dataRx.begin(); rid != m_dataRx.end();) + { + if ((*rid)->GetIface() == nid) + { + (*rid)->Write(h); + m_dataRx.erase(rid); + } + else + { + rid++; + } + } + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterStartElement (h, BAD_CAST "dataRx"); - NS_ASSERT (rc >= 0); - - for (auto rid=m_dataRx.begin(); rid !=m_dataRx.end();) - { - if ((*rid)->GetIface() == nid) - { - (*rid)->Write (h); - m_dataRx.erase(rid); - } else { - rid++; - } - } - - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); - } - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataTx"); - //broadcast - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "dataTx"); + // broadcast + NS_ASSERT(rc >= 0); - for (auto rid=m_dataTx.begin(); rid !=m_dataTx.end();rid++) (*rid)->Write (h); + for (auto rid = m_dataTx.begin(); rid != m_dataTx.end(); rid++) + (*rid)->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataRx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "dataRx"); + NS_ASSERT(rc >= 0); - for (auto rid=m_dataRx.begin(); rid !=m_dataRx.end();rid++) (*rid)->Write (h); + for (auto rid = m_dataRx.begin(); rid != m_dataRx.end(); rid++) + (*rid)->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - ////// - rc = xmlTextWriterStartElement (h, BAD_CAST "cumulativeDataTx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + ////// + rc = xmlTextWriterStartElement(h, BAD_CAST "cumulativeDataTx"); + NS_ASSERT(rc >= 0); - for (auto& dataStatsTx : m_cumulativeDataTx) - dataStatsTx->Write (h); + for (auto& dataStatsTx : m_cumulativeDataTx) + dataStatsTx->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "cumulativeDataRx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "cumulativeDataRx"); + NS_ASSERT(rc >= 0); - for (auto& dataStatsRx : m_cumulativeDataRx) - dataStatsRx->Write (h); + for (auto& dataStatsRx : m_cumulativeDataRx) + dataStatsRx->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/report-remote.h b/src/report/report-remote.h index c8ec5ae..959790a 100644 --- a/src/report/report-remote.h +++ b/src/report/report-remote.h @@ -20,6 +20,12 @@ #ifndef REPORT_REMOTE_H #define REPORT_REMOTE_H +#include "report-data-stats.h" +#include "report-entity.h" +#include "report-location.h" +#include "report-protocol-stack.h" +#include "report-transfer.h" + #include #include #include @@ -27,13 +33,8 @@ #include -#include "report-data-stats.h" -#include "report-entity.h" -#include "report-location.h" -#include "report-protocol-stack.h" -#include "report-transfer.h" - -namespace ns3 { +namespace ns3 +{ /** * Retrieve and store data about a Remote, like its @@ -43,31 +44,32 @@ namespace ns3 { */ class ReportRemote : public ReportEntity { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + ReportRemote(); + /** + * Default destructor + */ + ~ReportRemote(); - /** - * Default constructor - */ - ReportRemote (); - /** - * Default destructor - */ - ~ReportRemote (); -private: - /** - * Write Remote report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - void DoWrite (xmlTextWriterPtr handle); + private: + /** + * Write Remote report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + void DoWrite(xmlTextWriterPtr handle); - /// abstract representation of the network stack - ReportProtocolStack m_stack; + /// abstract representation of the network stack + ReportProtocolStack m_stack; }; } // namespace ns3 diff --git a/src/report/report-simulation.cc b/src/report/report-simulation.cc index dcf3dcd..8b719ad 100644 --- a/src/report/report-simulation.cc +++ b/src/report/report-simulation.cc @@ -15,7 +15,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , Giovanni Iacovelli + * */ #include "report-simulation.h" @@ -26,119 +27,116 @@ #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportSimulation"); -NS_OBJECT_ENSURE_REGISTERED (ReportSimulation); +NS_LOG_COMPONENT_DEFINE("ReportSimulation"); +NS_OBJECT_ENSURE_REGISTERED(ReportSimulation); TypeId -ReportSimulation::GetTypeId () +ReportSimulation::GetTypeId() { - NS_LOG_FUNCTION_NOARGS (); - - static TypeId tid = TypeId ("ns3::ReportSimulation") - .AddConstructor () - .SetParent () - - /* XML Attributes */ - .AddAttribute ("Scenario", "The name of the scenario", - StringValue ("unnamed"), - MakeStringAccessor (&ReportSimulation::m_scenario), - MakeStringChecker ()) - .AddAttribute ("ExecutedAt", "The datetime of execution", - StringValue (), - MakeStringAccessor (&ReportSimulation::m_executedAt), - MakeStringChecker ()) - ; - - return tid; + NS_LOG_FUNCTION_NOARGS(); + + static TypeId tid = TypeId("ns3::ReportSimulation") + .AddConstructor() + .SetParent() + + /* XML Attributes */ + .AddAttribute("Scenario", + "The name of the scenario", + StringValue("unnamed"), + MakeStringAccessor(&ReportSimulation::m_scenario), + MakeStringChecker()) + .AddAttribute("ExecutedAt", + "The datetime of execution", + StringValue(), + MakeStringAccessor(&ReportSimulation::m_executedAt), + MakeStringChecker()); + + return tid; } -ReportSimulation::ReportSimulation () : - m_drones {"Drones"}, - m_zsps {"ZSPs"}, - m_remotes {"Remotes"} +ReportSimulation::ReportSimulation() + : m_drones{"Drones"}, + m_zsps{"ZSPs"}, + m_remotes{"Remotes"} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportSimulation::~ReportSimulation () +ReportSimulation::~ReportSimulation() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void ReportSimulation::DoInitialize() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - // use schedule now to be sure we are probing during - // an active simulation - Simulator::ScheduleNow (&ReportSimulation::ProbeSimulation, - this); + // use schedule now to be sure we are probing during + // an active simulation + Simulator::ScheduleNow(&ReportSimulation::ProbeSimulation, this); } void -ReportSimulation::Write (xmlTextWriterPtr h) const +ReportSimulation::Write(xmlTextWriterPtr h) const { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement (h, BAD_CAST "simulation"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "simulation"); + NS_ASSERT(rc >= 0); - /* Attributes */ - xmlTextWriterWriteAttribute (h, - BAD_CAST "scenario", - BAD_CAST m_scenario.c_str ()); - xmlTextWriterWriteAttribute (h, - BAD_CAST "executedAt", - BAD_CAST m_executedAt.c_str ()); + /* Attributes */ + xmlTextWriterWriteAttribute(h, BAD_CAST "scenario", BAD_CAST m_scenario.c_str()); + xmlTextWriterWriteAttribute(h, BAD_CAST "executedAt", BAD_CAST m_executedAt.c_str()); - /* Nested Elements */ - m_duration.Write (h); - m_world.Write (h); - m_zsps.Write (h); - m_drones.Write (h); - m_remotes.Write (h); + /* Nested Elements */ + m_duration.Write(h); + m_world.Write(h); + m_zsps.Write(h); + m_drones.Write(h); + m_remotes.Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } void -ReportSimulation::ProbeSimulation () +ReportSimulation::ProbeSimulation() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - PopulateEntities ("/DroneList/*", &m_drones); - PopulateEntities ("/ZspList/*", &m_zsps); - PopulateEntities ("/RemoteList/*", &m_remotes); + PopulateEntities("/DroneList/*", &m_drones); + PopulateEntities("/ZspList/*", &m_zsps); + PopulateEntities("/RemoteList/*", &m_remotes); } template void -ReportSimulation::PopulateEntities (const std::string nodeQuery, - EntityContainer *entities) +ReportSimulation::PopulateEntities(const std::string nodeQuery, EntityContainer* entities) { - NS_LOG_FUNCTION (nodeQuery << entities); - const auto eFound = Config::LookupMatches (nodeQuery); + NS_LOG_FUNCTION(nodeQuery << entities); + const auto eFound = Config::LookupMatches(nodeQuery); - for (auto i = eFound.Begin (); i != eFound.End (); i++) + for (auto i = eFound.Begin(); i != eFound.End(); i++) { - const auto node = DynamicCast (*i); + const auto node = DynamicCast(*i); - if (node != nullptr) + if (node != nullptr) { - const uint32_t uid = node->GetId (); - entities->Add (uid); + const uint32_t uid = node->GetId(); + entities->Add(uid); } } } diff --git a/src/report/report-simulation.h b/src/report/report-simulation.h index 90abf3c..a36e70f 100644 --- a/src/report/report-simulation.h +++ b/src/report/report-simulation.h @@ -15,21 +15,23 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , Giovanni Iacovelli + * */ #ifndef REPORT_SIMULATION_H #define REPORT_SIMULATION_H +#include "report-container.h" +#include "report-world.h" +#include "simulation-duration.h" + #include #include #include -#include "report-container.h" -#include "simulation-duration.h" -#include "report-world.h" - -namespace ns3 { +namespace ns3 +{ /** * Report a simulation by constructing a tree of data during the simulation @@ -41,59 +43,59 @@ namespace ns3 { */ class ReportSimulation : public Object { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + ReportSimulation(); + /** + * Default destructor + */ + ~ReportSimulation(); - /** - * Default constructor - */ - ReportSimulation (); - /** - * Default destructor - */ - ~ReportSimulation (); + /** + * Write Zsp report data to a XML file with a given handler + * + * \param handle the handler to communicate data to the opened XML file + */ + void Write(xmlTextWriterPtr handle) const; - /** - * Write Zsp report data to a XML file with a given handler - * - * \param handle the handler to communicate data to the opened XML file - */ - void Write (xmlTextWriterPtr handle) const; + protected: + /** + * Initialize this Object by acquiring simulation data + */ + virtual void DoInitialize(void); -protected: - /** - * Initialize this Object by acquiring simulation data - */ - virtual void DoInitialize(void); -private: - /** - * Probe Callback to retrieve simulation information - */ - void ProbeSimulation(); + private: + /** + * Probe Callback to retrieve simulation information + */ + void ProbeSimulation(); - /** - * Generic function to populate simulated entities, which can be drones - * or ZSPs - * - * \param nodeQuery the query to perform to find simulated Nodes - * \param entities the container object to be populated - */ - template - void PopulateEntities (const std::string nodeQuery, - EntityContainer *entities); + /** + * Generic function to populate simulated entities, which can be drones + * or ZSPs + * + * \param nodeQuery the query to perform to find simulated Nodes + * \param entities the container object to be populated + */ + template + void PopulateEntities(const std::string nodeQuery, EntityContainer* entities); - std::string m_scenario; /// The name of the scenario - std::string m_executedAt; /// Datetime of execution - SimulationDuration m_duration; /// Duration of the simulation + std::string m_scenario; /// The name of the scenario + std::string m_executedAt; /// Datetime of execution + SimulationDuration m_duration; /// Duration of the simulation - ReportContainer m_drones; /// Report of drones - ReportContainer m_zsps; /// Report of ZSPs - ReportContainer m_remotes; /// Report of Remotes - ReportWorld m_world; /// Report of World + ReportContainer m_drones; /// Report of drones + ReportContainer m_zsps; /// Report of ZSPs + ReportContainer m_remotes; /// Report of Remotes + ReportWorld m_world; /// Report of World }; } // namespace ns3 diff --git a/src/report/report-transfer.cc b/src/report/report-transfer.cc index 565ca7b..72f8f3d 100644 --- a/src/report/report-transfer.cc +++ b/src/report/report-transfer.cc @@ -19,160 +19,157 @@ */ #include "report-transfer.h" -#include +#include "transfer-direction.h" #include #include #include -#include "transfer-direction.h" +#include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportTransfer"); +NS_LOG_COMPONENT_DEFINE("ReportTransfer"); TypeId -ReportTransfer::GetTypeId () +ReportTransfer::GetTypeId() { - static TypeId tid = TypeId ("ns3::ReportTransfer") - .AddConstructor () - .SetParent () - .AddAttribute ("EntityID", "The id of entity", - IntegerValue (), - MakeIntegerAccessor (&ReportTransfer::m_entityid), - MakeIntegerChecker ()) - .AddAttribute ("Interface", "The ipv4 interface number", - IntegerValue (), - MakeIntegerAccessor (&ReportTransfer::m_iface), - MakeIntegerChecker ()) - .AddAttribute ("PacketType", "The Type of the Packet", - PacketTypeValue (), - MakePacketTypeAccessor (&ReportTransfer::m_type), - MakePacketTypeChecker ()) - .AddAttribute ("TransferDirection", "The direction of the transferred data", - TransferDirectionValue (), - MakeTransferDirectionAccessor (&ReportTransfer::m_direction), - MakeTransferDirectionChecker ()) - .AddAttribute ("Time", "The Simulation Time", - TimeValue (), - MakeTimeAccessor (&ReportTransfer::m_time), - MakeTimeChecker ()) - .AddAttribute ("SourceAddress", "The IPv4 Address of the sender", - StringValue (), - MakeStringAccessor (&ReportTransfer::m_sourceAddress), - MakeStringChecker ()) - .AddAttribute ("DestinationAddress", "The IPv4 Address of the target host", - StringValue (), - MakeStringAccessor (&ReportTransfer::m_destinationAddress), - MakeStringChecker ()) - .AddAttribute ("PacketLength", "The length of the payload", - IntegerValue (), - MakeIntegerAccessor (&ReportTransfer::m_length), - MakeIntegerChecker ()) - .AddAttribute ("SequenceNumber", "The sequence number of the DCL packet", - IntegerValue (), - MakeIntegerAccessor (&ReportTransfer::m_sequenceNumber), - MakeIntegerChecker ()) - .AddAttribute ("Payload", "The payload content", - StringValue (), - MakeStringAccessor (&ReportTransfer::m_payload), - MakeStringChecker ()) - ; + static TypeId tid = + TypeId("ns3::ReportTransfer") + .AddConstructor() + .SetParent() + .AddAttribute("EntityID", + "The id of entity", + IntegerValue(), + MakeIntegerAccessor(&ReportTransfer::m_entityid), + MakeIntegerChecker()) + .AddAttribute("Interface", + "The ipv4 interface number", + IntegerValue(), + MakeIntegerAccessor(&ReportTransfer::m_iface), + MakeIntegerChecker()) + .AddAttribute("PacketType", + "The Type of the Packet", + PacketTypeValue(), + MakePacketTypeAccessor(&ReportTransfer::m_type), + MakePacketTypeChecker()) + .AddAttribute("TransferDirection", + "The direction of the transferred data", + TransferDirectionValue(), + MakeTransferDirectionAccessor(&ReportTransfer::m_direction), + MakeTransferDirectionChecker()) + .AddAttribute("Time", + "The Simulation Time", + TimeValue(), + MakeTimeAccessor(&ReportTransfer::m_time), + MakeTimeChecker()) + .AddAttribute("SourceAddress", + "The IPv4 Address of the sender", + StringValue(), + MakeStringAccessor(&ReportTransfer::m_sourceAddress), + MakeStringChecker()) + .AddAttribute("DestinationAddress", + "The IPv4 Address of the target host", + StringValue(), + MakeStringAccessor(&ReportTransfer::m_destinationAddress), + MakeStringChecker()) + .AddAttribute("PacketLength", + "The length of the payload", + IntegerValue(), + MakeIntegerAccessor(&ReportTransfer::m_length), + MakeIntegerChecker()) + .AddAttribute("SequenceNumber", + "The sequence number of the DCL packet", + IntegerValue(), + MakeIntegerAccessor(&ReportTransfer::m_sequenceNumber), + MakeIntegerChecker()) + .AddAttribute("Payload", + "The payload content", + StringValue(), + MakeStringAccessor(&ReportTransfer::m_payload), + MakeStringChecker()); return tid; } -ReportTransfer::ReportTransfer () +ReportTransfer::ReportTransfer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportTransfer::~ReportTransfer () +ReportTransfer::~ReportTransfer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } int32_t -ReportTransfer::GetIface () +ReportTransfer::GetIface() { - return m_iface; + return m_iface; } + void -ReportTransfer::Write (xmlTextWriterPtr h) +ReportTransfer::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - std::ostringstream bLength, - bTime, - bSequenceNumber; - int rc; - - rc = xmlTextWriterStartElement (h, BAD_CAST "transfer"); - NS_ASSERT (rc >= 0); - - /* Attributes */ - rc = xmlTextWriterWriteAttribute (h, - BAD_CAST "type", - BAD_CAST m_type.ToString ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteAttribute (h, - BAD_CAST "entityid", - BAD_CAST std::to_string(m_entityid).c_str()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteAttribute (h, - BAD_CAST "iface", - BAD_CAST std::to_string(m_iface).c_str()); - NS_ASSERT (rc >= 0); - - /* Nested Elements */ - rc = xmlTextWriterWriteElement (h, - BAD_CAST "direction", - BAD_CAST m_direction.ToString ()); - NS_ASSERT (rc >= 0); - - bLength << m_length; - rc = xmlTextWriterWriteElement (h, - BAD_CAST "length", - BAD_CAST bLength.str ().c_str ()); - NS_ASSERT (rc >= 0); - - bTime << m_time.GetNanoSeconds (); - rc = xmlTextWriterWriteElement (h, - BAD_CAST "time", - BAD_CAST bTime.str ().c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteElement (h, - BAD_CAST "sourceAddress", - BAD_CAST m_sourceAddress.c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteElement (h, - BAD_CAST "destinationAddress", - BAD_CAST m_destinationAddress.c_str ()); - NS_ASSERT (rc >= 0); - - bSequenceNumber << m_sequenceNumber; - rc = xmlTextWriterWriteElement (h, - BAD_CAST "sequenceNumber", - BAD_CAST bSequenceNumber.str ().c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteElement (h, - BAD_CAST "payload", - BAD_CAST m_payload.c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + std::ostringstream bLength, bTime, bSequenceNumber; + int rc; + + rc = xmlTextWriterStartElement(h, BAD_CAST "transfer"); + NS_ASSERT(rc >= 0); + + /* Attributes */ + rc = xmlTextWriterWriteAttribute(h, BAD_CAST "type", BAD_CAST m_type.ToString()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteAttribute(h, + BAD_CAST "entityid", + BAD_CAST std::to_string(m_entityid).c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteAttribute(h, BAD_CAST "iface", BAD_CAST std::to_string(m_iface).c_str()); + NS_ASSERT(rc >= 0); + + /* Nested Elements */ + rc = xmlTextWriterWriteElement(h, BAD_CAST "direction", BAD_CAST m_direction.ToString()); + NS_ASSERT(rc >= 0); + + bLength << m_length; + rc = xmlTextWriterWriteElement(h, BAD_CAST "length", BAD_CAST bLength.str().c_str()); + NS_ASSERT(rc >= 0); + + bTime << m_time.GetNanoSeconds(); + rc = xmlTextWriterWriteElement(h, BAD_CAST "time", BAD_CAST bTime.str().c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, BAD_CAST "sourceAddress", BAD_CAST m_sourceAddress.c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "destinationAddress", + BAD_CAST m_destinationAddress.c_str()); + NS_ASSERT(rc >= 0); + + bSequenceNumber << m_sequenceNumber; + rc = xmlTextWriterWriteElement(h, + BAD_CAST "sequenceNumber", + BAD_CAST bSequenceNumber.str().c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, BAD_CAST "payload", BAD_CAST m_payload.c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/report-transfer.h b/src/report/report-transfer.h index b215864..88868a5 100644 --- a/src/report/report-transfer.h +++ b/src/report/report-transfer.h @@ -19,67 +19,66 @@ */ #ifndef REPORT_TRANSFER_H #define REPORT_TRANSFER_H -#include - -#include +#include "transfer-direction.h" +#include #include #include +#include #include +#include -#include - -#include "transfer-direction.h" - -namespace ns3 { +namespace ns3 +{ class ReportTransfer : public Object { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + ReportTransfer(); + /** + * Default destructor + */ + ~ReportTransfer(); - /** - * Default constructor - */ - ReportTransfer (); - /** - * Default destructor - */ - ~ReportTransfer (); + int32_t GetIface(); + /** + * Write Transfer report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + void Write(xmlTextWriterPtr handle); - int32_t GetIface(); - /** - * Write Transfer report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - void Write (xmlTextWriterPtr handle); -private: - /// entityid - uint32_t m_entityid; - /// netdevice id - int32_t m_iface; - /// the type of transfer - PacketType m_type; - /// the direction related to the monitored entity (Tx or Rx?) - TransferDirection m_direction; - /// time of transfer - Time m_time; - /// the sender of the packet - std::string m_sourceAddress; - /// the receiver of the packet - std::string m_destinationAddress; - /// the length of the payload - std::uint32_t m_length; - /// the sequence number of DCL payload - std::uint32_t m_sequenceNumber; - /// the full JSON, DCL payload, decoded in ASCII - std::string m_payload; + private: + /// entityid + uint32_t m_entityid; + /// netdevice id + int32_t m_iface; + /// the type of transfer + PacketType m_type; + /// the direction related to the monitored entity (Tx or Rx?) + TransferDirection m_direction; + /// time of transfer + Time m_time; + /// the sender of the packet + std::string m_sourceAddress; + /// the receiver of the packet + std::string m_destinationAddress; + /// the length of the payload + std::uint32_t m_length; + /// the sequence number of DCL payload + std::uint32_t m_sequenceNumber; + /// the full JSON, DCL payload, decoded in ASCII + std::string m_payload; }; } // namespace ns3 diff --git a/src/report/report-world.cc b/src/report/report-world.cc index 0762d61..b32a8d8 100644 --- a/src/report/report-world.cc +++ b/src/report/report-world.cc @@ -23,99 +23,120 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportWorld"); +NS_LOG_COMPONENT_DEFINE("ReportWorld"); -ReportWorld::ReportWorld () +ReportWorld::ReportWorld() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportWorld::~ReportWorld () +ReportWorld::~ReportWorld() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ReportWorld::Write (xmlTextWriterPtr h) const +ReportWorld::Write(xmlTextWriterPtr h) const { - std::stringstream roistr; - NS_LOG_FUNCTION (h); - if (h == nullptr) + std::stringstream roistr; + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; - - rc = xmlTextWriterStartElement(h, BAD_CAST "World"); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterStartElement(h, BAD_CAST "Buildings"); - NS_ASSERT (rc >= 0); - - for (auto bit = BuildingList::Begin (); bit != BuildingList::End (); ++bit) - { - rc = xmlTextWriterStartElement(h, BAD_CAST "Building"); - NS_ASSERT (rc >= 0); - - xmlTextWriterWriteAttribute (h, BAD_CAST "id", BAD_CAST std::to_string((*bit)->GetId ()).c_str ()); + int rc; - rc = xmlTextWriterWriteElement (h, BAD_CAST "Boundaries", BAD_CAST - ("["+std::to_string((*bit)->GetBoundaries ().xMin)+", " - + std::to_string((*bit)->GetBoundaries ().xMax)+", " - +std::to_string((*bit)->GetBoundaries ().yMin)+", " - + std::to_string((*bit)->GetBoundaries ().yMax)+", " - +std::to_string((*bit)->GetBoundaries ().zMin)+", " - + std::to_string((*bit)->GetBoundaries ().zMax)+"]").c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "World"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "BuildingType", BAD_CAST std::to_string((*bit)->GetBuildingType ()).c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "Buildings"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, BAD_CAST "WallsType", BAD_CAST std::to_string((*bit)->GetExtWallsType ()).c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteElement (h, BAD_CAST "Floors", BAD_CAST std::to_string((*bit)->GetNFloors ()).c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteElement (h, BAD_CAST "Rooms", BAD_CAST - ("["+std::to_string((*bit)->GetNRoomsX ())+","+ std::to_string((*bit)->GetNRoomsX())+"]").c_str ()); - NS_ASSERT (rc >= 0); + for (auto bit = BuildingList::Begin(); bit != BuildingList::End(); ++bit) + { + rc = xmlTextWriterStartElement(h, BAD_CAST "Building"); + NS_ASSERT(rc >= 0); + + xmlTextWriterWriteAttribute(h, + BAD_CAST "id", + BAD_CAST std::to_string((*bit)->GetId()).c_str()); + + rc = xmlTextWriterWriteElement( + h, + BAD_CAST "Boundaries", + BAD_CAST("[" + std::to_string((*bit)->GetBoundaries().xMin) + ", " + + std::to_string((*bit)->GetBoundaries().xMax) + ", " + + std::to_string((*bit)->GetBoundaries().yMin) + ", " + + std::to_string((*bit)->GetBoundaries().yMax) + ", " + + std::to_string((*bit)->GetBoundaries().zMin) + ", " + + std::to_string((*bit)->GetBoundaries().zMax) + "]") + .c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "BuildingType", + BAD_CAST std::to_string((*bit)->GetBuildingType()).c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "WallsType", + BAD_CAST std::to_string((*bit)->GetExtWallsType()).c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "Floors", + BAD_CAST std::to_string((*bit)->GetNFloors()).c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "Rooms", + BAD_CAST("[" + std::to_string((*bit)->GetNRoomsX()) + "," + + std::to_string((*bit)->GetNRoomsX()) + "]") + .c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + } rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); - } + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "InterestRegions"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement(h, BAD_CAST "InterestRegions"); - NS_ASSERT (rc >= 0); - - for (auto ir = irc->Begin (); ir != irc->End (); ir++) - { - xmlTextWriterWriteAttribute (h, BAD_CAST "id", BAD_CAST std::to_string(ir-irc->Begin ()).c_str ()); - - std::string irstr = ""; - DoubleVector coords = (*ir)->GetCoordinates (); - - for (uint32_t c = 0; c < coords.GetN(); c++) irstr+=std::to_string(coords.Get()[c])+", "; - irstr.pop_back(); - irstr.pop_back(); - - rc = xmlTextWriterWriteElement (h, BAD_CAST "Boundaries", BAD_CAST ("["+irstr+"]").c_str ()); - NS_ASSERT (rc >= 0); - } + for (auto ir = irc->Begin(); ir != irc->End(); ir++) + { + xmlTextWriterWriteAttribute(h, + BAD_CAST "id", + BAD_CAST std::to_string(ir - irc->Begin()).c_str()); + + std::string irstr = ""; + DoubleVector coords = (*ir)->GetCoordinates(); + + for (uint32_t c = 0; c < coords.GetN(); c++) + irstr += std::to_string(coords.Get()[c]) + ", "; + irstr.pop_back(); + irstr.pop_back(); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "Boundaries", + BAD_CAST("[" + irstr + "]").c_str()); + NS_ASSERT(rc >= 0); + } - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/report-world.h b/src/report/report-world.h index 9c5d0f2..4b4a235 100644 --- a/src/report/report-world.h +++ b/src/report/report-world.h @@ -19,31 +19,31 @@ */ #ifndef REPORT_WORLD_H #define REPORT_WORLD_H +#include #include #include -#include - -namespace ns3 { +namespace ns3 +{ class ReportWorld { -public: + public: /** * Initialize a world report */ - ReportWorld (); + ReportWorld(); /** * Default destructor */ - ~ReportWorld (); + ~ReportWorld(); /** * Write Zsp report data to a XML file with a given handler * * \param handle the XML handler to write data on */ - void Write (xmlTextWriterPtr handle) const; + void Write(xmlTextWriterPtr handle) const; }; } // namespace ns3 diff --git a/src/report/report-zsp.cc b/src/report/report-zsp.cc index 99d5dda..2d932af 100644 --- a/src/report/report-zsp.cc +++ b/src/report/report-zsp.cc @@ -15,10 +15,17 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , Giovanni Iacovelli + * */ #include "report-zsp.h" +#include "drone-control-layer.h" +#include "ipv4-layer.h" +#include "wifi-inspector.h" +#include "wifi-mac-layer.h" +#include "wifi-phy-layer.h" + #include #include #include @@ -32,165 +39,166 @@ #include -#include "drone-control-layer.h" -#include "ipv4-layer.h" -#include "wifi-inspector.h" -#include "wifi-mac-layer.h" -#include "wifi-phy-layer.h" - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("ReportZsp"); -NS_OBJECT_ENSURE_REGISTERED (ReportZsp); +NS_LOG_COMPONENT_DEFINE("ReportZsp"); +NS_OBJECT_ENSURE_REGISTERED(ReportZsp); TypeId -ReportZsp::GetTypeId () +ReportZsp::GetTypeId() { - static TypeId tid = TypeId ("ns3::ReportZsp") - .AddConstructor () - .SetParent () - ; + static TypeId tid = + TypeId("ns3::ReportZsp").AddConstructor().SetParent(); - return tid; + return tid; } -ReportZsp::ReportZsp () +ReportZsp::ReportZsp() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -ReportZsp::~ReportZsp () +ReportZsp::~ReportZsp() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -ReportZsp::DoWrite (xmlTextWriterPtr h) +ReportZsp::DoWrite(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; - - rc = xmlTextWriterStartElement (h, BAD_CAST "ZSP"); - NS_ASSERT (rc >= 0); + int rc; - /* Nested Elements */ - m_position.Write (h); + rc = xmlTextWriterStartElement(h, BAD_CAST "ZSP"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "NetDevices"); - NS_ASSERT (rc >= 0); + /* Nested Elements */ + m_position.Write(h); - for (int nid = 0; nid < (int) m_networkStacks.size(); nid++) - { - rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevice"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevices"); + NS_ASSERT(rc >= 0); - m_networkStacks[nid].Write (h); - - rc = xmlTextWriterStartElement (h, BAD_CAST "dataTx"); - NS_ASSERT (rc >= 0); - - for (auto rid=m_dataTx.begin(); rid !=m_dataTx.end();) + for (int nid = 0; nid < (int)m_networkStacks.size(); nid++) { - if ((*rid)->GetIface() == nid) - { - (*rid)->Write (h); - m_dataTx.erase(rid); - } else { - rid++; - } + rc = xmlTextWriterStartElement(h, BAD_CAST "NetDevice"); + NS_ASSERT(rc >= 0); + + m_networkStacks[nid].Write(h); + + rc = xmlTextWriterStartElement(h, BAD_CAST "dataTx"); + NS_ASSERT(rc >= 0); + + for (auto rid = m_dataTx.begin(); rid != m_dataTx.end();) + { + if ((*rid)->GetIface() == nid) + { + (*rid)->Write(h); + m_dataTx.erase(rid); + } + else + { + rid++; + } + } + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterStartElement(h, BAD_CAST "dataRx"); + NS_ASSERT(rc >= 0); + + for (auto rid = m_dataRx.begin(); rid != m_dataRx.end();) + { + if ((*rid)->GetIface() == nid) + { + (*rid)->Write(h); + m_dataRx.erase(rid); + } + else + { + rid++; + } + } + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterStartElement (h, BAD_CAST "dataRx"); - NS_ASSERT (rc >= 0); - - for (auto rid=m_dataRx.begin(); rid !=m_dataRx.end();) - { - if ((*rid)->GetIface() == nid) - { - (*rid)->Write (h); - m_dataRx.erase(rid); - } else { - rid++; - } - } - - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); - } - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataTx"); - //broadcast - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "dataTx"); + // broadcast + NS_ASSERT(rc >= 0); - for (auto rid=m_dataTx.begin(); rid !=m_dataTx.end();rid++) (*rid)->Write (h); + for (auto rid = m_dataTx.begin(); rid != m_dataTx.end(); rid++) + (*rid)->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "dataRx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "dataRx"); + NS_ASSERT(rc >= 0); - for (auto rid=m_dataRx.begin(); rid !=m_dataRx.end();rid++) (*rid)->Write (h); + for (auto rid = m_dataRx.begin(); rid != m_dataRx.end(); rid++) + (*rid)->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); - ////// - rc = xmlTextWriterStartElement (h, BAD_CAST "cumulativeDataTx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); + ////// + rc = xmlTextWriterStartElement(h, BAD_CAST "cumulativeDataTx"); + NS_ASSERT(rc >= 0); - for (auto& dataStatsTx : m_cumulativeDataTx) - dataStatsTx->Write (h); + for (auto& dataStatsTx : m_cumulativeDataTx) + dataStatsTx->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterStartElement (h, BAD_CAST "cumulativeDataRx"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "cumulativeDataRx"); + NS_ASSERT(rc >= 0); - for (auto& dataStatsRx : m_cumulativeDataRx) - dataStatsRx->Write (h); + for (auto& dataStatsRx : m_cumulativeDataRx) + dataStatsRx->Write(h); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } void ReportZsp::DoInitializeTrajectoryMonitor() { - NS_LOG_FUNCTION_NOARGS (); - std::stringstream bPath; + NS_LOG_FUNCTION_NOARGS(); + std::stringstream bPath; - bPath << "/NodeList/" << m_reference << "/$ns3::MobilityModel"; - auto matches = Config::LookupMatches (bPath.str ()); - NS_ASSERT (matches.GetN () == 1); + bPath << "/NodeList/" << m_reference << "/$ns3::MobilityModel"; + auto matches = Config::LookupMatches(bPath.str()); + NS_ASSERT(matches.GetN() == 1); - Ptr obj = DynamicCast (matches.Get (0)); - if (obj == nullptr) - NS_FATAL_ERROR ("Expected a MobilityModel on node id " << m_reference << "," - " but none was found!"); + Ptr obj = DynamicCast(matches.Get(0)); + if (obj == nullptr) + NS_FATAL_ERROR("Expected a MobilityModel on node id " << m_reference + << "," + " but none was found!"); - m_position = ReportLocation (obj->GetPosition (), Simulator::Now ()); + m_position = ReportLocation(obj->GetPosition(), Simulator::Now()); } void -ReportZsp::DoMonitorTrajectory (const Ptr mobility) +ReportZsp::DoMonitorTrajectory(const Ptr mobility) { } diff --git a/src/report/report-zsp.h b/src/report/report-zsp.h index ed6fb9a..48be36a 100644 --- a/src/report/report-zsp.h +++ b/src/report/report-zsp.h @@ -15,11 +15,18 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * - * Authors: Giovanni Grieco , Giovanni Iacovelli + * Authors: Giovanni Grieco , Giovanni Iacovelli + * */ #ifndef REPORT_ZSP_H #define REPORT_ZSP_H +#include "report-data-stats.h" +#include "report-entity.h" +#include "report-location.h" +#include "report-protocol-stack.h" +#include "report-transfer.h" + #include #include #include @@ -27,13 +34,8 @@ #include -#include "report-data-stats.h" -#include "report-entity.h" -#include "report-location.h" -#include "report-protocol-stack.h" -#include "report-transfer.h" - -namespace ns3 { +namespace ns3 +{ /** * Retrieve and store data about a ZSP, like its @@ -44,45 +46,46 @@ namespace ns3 { */ class ReportZsp : public ReportEntity { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + ReportZsp(); + /** + * Default destructor + */ + ~ReportZsp(); - /** - * Default constructor - */ - ReportZsp (); - /** - * Default destructor - */ - ~ReportZsp (); -private: - /** - * Write Zsp report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - void DoWrite (xmlTextWriterPtr handle); + private: + /** + * Write Zsp report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + void DoWrite(xmlTextWriterPtr handle); - /** - * Get ZSP position - */ - void DoInitializeTrajectoryMonitor (); + /** + * Get ZSP position + */ + void DoInitializeTrajectoryMonitor(); - /** - * Placeholder, monitor nothing because the ZSP in fixed in space - * - * \params mobility the mobility model of the entity to inspect - */ - void DoMonitorTrajectory (const Ptr mobility); + /** + * Placeholder, monitor nothing because the ZSP in fixed in space + * + * \params mobility the mobility model of the entity to inspect + */ + void DoMonitorTrajectory(const Ptr mobility); - /// ZSP position - ReportLocation m_position; - /// abstract representation of the network stack - ReportProtocolStack m_stack; + /// ZSP position + ReportLocation m_position; + /// abstract representation of the network stack + ReportProtocolStack m_stack; }; } // namespace ns3 diff --git a/src/report/report.cc b/src/report/report.cc index 9d798e7..26955ce 100644 --- a/src/report/report.cc +++ b/src/report/report.cc @@ -19,114 +19,116 @@ */ #include "report.h" +#include "report-simulation.h" + #include #include #include -#include "report-simulation.h" - -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Report"); +NS_LOG_COMPONENT_DEFINE("Report"); void -Report::Initialize (const std::string scenarioName, - const std::string executedAt, - const std::string resultsPath) +Report::Initialize(const std::string scenarioName, + const std::string executedAt, + const std::string resultsPath) { - NS_LOG_FUNCTION (this); - if (m_dataTreeRoot != nullptr) + NS_LOG_FUNCTION(this); + if (m_dataTreeRoot != nullptr) { - NS_LOG_WARN ("Report is already being populated at " << m_dataTreeRoot - << ". There is no need to reinitialize it."); - return; + NS_LOG_WARN("Report is already being populated at " + << m_dataTreeRoot << ". There is no need to reinitialize it."); + return; } - m_resultsPath = resultsPath; + m_resultsPath = resultsPath; - m_dataTreeRoot = CreateObjectWithAttributes - ("Scenario", StringValue (scenarioName), - "ExecutedAt", StringValue (executedAt)); + m_dataTreeRoot = CreateObjectWithAttributes("Scenario", + StringValue(scenarioName), + "ExecutedAt", + StringValue(executedAt)); - m_dataTreeRoot->Initialize (); + m_dataTreeRoot->Initialize(); - /* - * File early opening is to check that a new file can be created and - * written to before starting a simulation that can last minutes, hours, - * days, whatever. - * Lazy opening is discouraged here to not lose data and time. - */ - Open (); + /* + * File early opening is to check that a new file can be created and + * written to before starting a simulation that can last minutes, hours, + * days, whatever. + * Lazy opening is discouraged here to not lose data and time. + */ + Open(); } -Report::~Report () +Report::~Report() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -Report::Save () +Report::Save() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - Write (); - Close (); + Write(); + Close(); } void -Report::Open () +Report::Open() { - NS_LOG_FUNCTION_NOARGS (); - if (m_writer != nullptr) - return; + NS_LOG_FUNCTION_NOARGS(); + if (m_writer != nullptr) + return; - int rc; + int rc; - m_writer = xmlNewTextWriterFilename (GetFilename ().c_str (), 0); - NS_ASSERT (m_writer != nullptr); + m_writer = xmlNewTextWriterFilename(GetFilename().c_str(), 0); + NS_ASSERT(m_writer != nullptr); - rc = xmlTextWriterSetIndent (m_writer, 4); - NS_ASSERT (rc == 0); + rc = xmlTextWriterSetIndent(m_writer, 4); + NS_ASSERT(rc == 0); - rc = xmlTextWriterStartDocument (m_writer, nullptr, "utf-8", nullptr); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartDocument(m_writer, nullptr, "utf-8", nullptr); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteComment (m_writer, BAD_CAST "IoD_Sim Report Summary"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteComment(m_writer, BAD_CAST "IoD_Sim Report Summary"); + NS_ASSERT(rc >= 0); } void -Report::Close () +Report::Close() { - NS_LOG_FUNCTION_NOARGS (); - if (m_writer == nullptr) - return; + NS_LOG_FUNCTION_NOARGS(); + if (m_writer == nullptr) + return; - const int rc = xmlTextWriterEndDocument (m_writer); - NS_ASSERT (rc >= 0); + const int rc = xmlTextWriterEndDocument(m_writer); + NS_ASSERT(rc >= 0); - xmlFreeTextWriter (m_writer); - m_writer = nullptr; + xmlFreeTextWriter(m_writer); + m_writer = nullptr; } void -Report::Write () const +Report::Write() const { - NS_LOG_FUNCTION_NOARGS (); - NS_ASSERT (m_writer != nullptr); + NS_LOG_FUNCTION_NOARGS(); + NS_ASSERT(m_writer != nullptr); - m_dataTreeRoot->Write (m_writer); + m_dataTreeRoot->Write(m_writer); } const std::string -Report::GetFilename () const +Report::GetFilename() const { - NS_LOG_FUNCTION_NOARGS (); - std::ostringstream bFilename; + NS_LOG_FUNCTION_NOARGS(); + std::ostringstream bFilename; - bFilename << m_resultsPath << "summary.xml"; + bFilename << m_resultsPath << "summary.xml"; - return bFilename.str (); + return bFilename.str(); } } // namespace ns3 diff --git a/src/report/report.h b/src/report/report.h index fe42d6d..f777b14 100644 --- a/src/report/report.h +++ b/src/report/report.h @@ -20,15 +20,15 @@ #ifndef REPORT_H #define REPORT_H -#include +#include "report-simulation.h" #include #include +#include -#include "report-simulation.h" - -namespace ns3 { +namespace ns3 +{ /** * The Report module is made to agglomerate useful data and output all of it in @@ -43,57 +43,57 @@ namespace ns3 { */ class Report : public Singleton { -public: - /** - * Initialize Reporting Infrastructure. - * This method should be called only once. It has guards for it and it prints - * a warning message if it is called multiple times. - * - * \param scenarioName Name of the scenario - * \param executedAt Datetime of scenario execution - * \param resultsPath Base path on which the XML file is saved - */ - void Initialize (const std::string scenarioName, - const std::string executedAt, - const std::string resultsPath); + public: + /** + * Initialize Reporting Infrastructure. + * This method should be called only once. It has guards for it and it prints + * a warning message if it is called multiple times. + * + * \param scenarioName Name of the scenario + * \param executedAt Datetime of scenario execution + * \param resultsPath Base path on which the XML file is saved + */ + void Initialize(const std::string scenarioName, + const std::string executedAt, + const std::string resultsPath); - /** - * Base destructor. - * End of simulation, write data to file and clean the environment. - */ - ~Report(); + /** + * Base destructor. + * End of simulation, write data to file and clean the environment. + */ + ~Report(); - /** - * Save all data to the summary file. - */ - void Save (); + /** + * Save all data to the summary file. + */ + void Save(); -private: - /** - * Open the summary file. - */ - void Open (); + private: + /** + * Open the summary file. + */ + void Open(); - /** - * Close the summary file. - */ - void Close (); + /** + * Close the summary file. + */ + void Close(); - /** - * Explore the tree and write on the summary file. - */ - void Write () const; + /** + * Explore the tree and write on the summary file. + */ + void Write() const; - /** - * Generate the destination file name summary.xml - * - * \return Destination file name. - */ - const std::string GetFilename() const; + /** + * Generate the destination file name summary.xml + * + * \return Destination file name. + */ + const std::string GetFilename() const; - std::string m_resultsPath; /// Results directory path - xmlTextWriterPtr m_writer; /// XML file handler - Ptr m_dataTreeRoot; /// Root of accumulated data + std::string m_resultsPath; /// Results directory path + xmlTextWriterPtr m_writer; /// XML file handler + Ptr m_dataTreeRoot; /// Root of accumulated data }; } // namespace ns3 diff --git a/src/report/schema.xsd b/src/report/schema.xsd index 2b29902..fbcd874 100644 --- a/src/report/schema.xsd +++ b/src/report/schema.xsd @@ -171,4 +171,4 @@ - + \ No newline at end of file diff --git a/src/report/simulation-duration.cc b/src/report/simulation-duration.cc index ae85ee7..cfe9be8 100644 --- a/src/report/simulation-duration.cc +++ b/src/report/simulation-duration.cc @@ -19,98 +19,94 @@ */ #include "simulation-duration.h" -#include -#include - #include #include -namespace ns3 { +#include +#include + +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("SimulationDuration"); +NS_LOG_COMPONENT_DEFINE("SimulationDuration"); -SimulationDuration::SimulationDuration (const Time& realDuration, - const Time& virtualDuration) : - m_realDuration {realDuration}, - m_virtualDuration {virtualDuration} +SimulationDuration::SimulationDuration(const Time& realDuration, const Time& virtualDuration) + : m_realDuration{realDuration}, + m_virtualDuration{virtualDuration} { - NS_LOG_FUNCTION (this << m_realDuration << m_virtualDuration); + NS_LOG_FUNCTION(this << m_realDuration << m_virtualDuration); } -SimulationDuration::SimulationDuration () : - m_realDuration {GetRealTime ()}, - m_virtualDuration {GetVirtualTime ()} +SimulationDuration::SimulationDuration() + : m_realDuration{GetRealTime()}, + m_virtualDuration{GetVirtualTime()} { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -SimulationDuration::~SimulationDuration () +SimulationDuration::~SimulationDuration() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -SimulationDuration::Write (xmlTextWriterPtr h) const +SimulationDuration::Write(xmlTextWriterPtr h) const { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; - // use stream facilities to ease output conversion - std::ostringstream bRealDuration, - bVirtualDuration; + int rc; + // use stream facilities to ease output conversion + std::ostringstream bRealDuration, bVirtualDuration; - const Time real = GetRealTime () - m_realDuration; - const Time virt = Simulator::Now () - m_virtualDuration; + const Time real = GetRealTime() - m_realDuration; + const Time virt = Simulator::Now() - m_virtualDuration; - bRealDuration << real.GetSeconds (); - bVirtualDuration << virt.GetSeconds (); + bRealDuration << real.GetSeconds(); + bVirtualDuration << virt.GetSeconds(); - rc = xmlTextWriterStartElement (h, BAD_CAST "duration"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "duration"); + NS_ASSERT(rc >= 0); - /* Nested Elements */ - rc = xmlTextWriterWriteElement (h, - BAD_CAST "real", - BAD_CAST bRealDuration.str ().c_str ()); - NS_ASSERT (rc >= 0); + /* Nested Elements */ + rc = xmlTextWriterWriteElement(h, BAD_CAST "real", BAD_CAST bRealDuration.str().c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement (h, - BAD_CAST "virtual", - BAD_CAST bVirtualDuration.str ().c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "virtual", BAD_CAST bVirtualDuration.str().c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } Time -SimulationDuration::GetRealTime () +SimulationDuration::GetRealTime() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - const auto now = std::chrono::system_clock::now (); - const auto epoch = now.time_since_epoch (); - const auto seconds = std::chrono::duration_cast (epoch); - const uint64_t duration = seconds.count (); + const auto now = std::chrono::system_clock::now(); + const auto epoch = now.time_since_epoch(); + const auto seconds = std::chrono::duration_cast(epoch); + const uint64_t duration = seconds.count(); - std::ostringstream bTime; - bTime << duration << "s"; + std::ostringstream bTime; + bTime << duration << "s"; - return Time (bTime.str ()); + return Time(bTime.str()); } Time -SimulationDuration::GetVirtualTime () +SimulationDuration::GetVirtualTime() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return Simulator::Now (); + return Simulator::Now(); } } // namespace ns3 diff --git a/src/report/simulation-duration.h b/src/report/simulation-duration.h index 95c29f4..f733339 100644 --- a/src/report/simulation-duration.h +++ b/src/report/simulation-duration.h @@ -5,7 +5,8 @@ #include -namespace ns3 { +namespace ns3 +{ /** * Store real and virtual time, useful when it is required to @@ -14,42 +15,43 @@ namespace ns3 { */ class SimulationDuration { -public: - /** - * Construct the object with the given values. - * - * \params realDuration the real time - * \param virtualDuration the virtual time - */ - SimulationDuration (const Time& realDuration, const Time& virtualDuration); - /** - * Default constructor, useful for higher-level object initialization - */ - SimulationDuration (); - /** - * Default destructor - */ - ~SimulationDuration (); - - /** - * Write SimulationDuration report data to a XML file with a given handler - * - * \param handle the handler to communicate data to the opened XML file - */ - void Write (xmlTextWriterPtr handle) const; -private: - /** - * Get current real time - */ - static Time GetRealTime (); - - /** - * Get current virtual time - */ - static Time GetVirtualTime (); - - Time m_realDuration; /// the duration measured by the computer - Time m_virtualDuration; /// the duration relative to the simulator time + public: + /** + * Construct the object with the given values. + * + * \params realDuration the real time + * \param virtualDuration the virtual time + */ + SimulationDuration(const Time& realDuration, const Time& virtualDuration); + /** + * Default constructor, useful for higher-level object initialization + */ + SimulationDuration(); + /** + * Default destructor + */ + ~SimulationDuration(); + + /** + * Write SimulationDuration report data to a XML file with a given handler + * + * \param handle the handler to communicate data to the opened XML file + */ + void Write(xmlTextWriterPtr handle) const; + + private: + /** + * Get current real time + */ + static Time GetRealTime(); + + /** + * Get current virtual time + */ + static Time GetVirtualTime(); + + Time m_realDuration; /// the duration measured by the computer + Time m_virtualDuration; /// the duration relative to the simulator time }; } // namespace ns3 diff --git a/src/report/transfer-direction.cc b/src/report/transfer-direction.cc index e10a9d8..f17f15d 100644 --- a/src/report/transfer-direction.cc +++ b/src/report/transfer-direction.cc @@ -21,40 +21,40 @@ #include -namespace ns3 { +namespace ns3 +{ -ATTRIBUTE_VALUE_IMPLEMENT (TransferDirection); -ATTRIBUTE_CHECKER_IMPLEMENT (TransferDirection); +ATTRIBUTE_VALUE_IMPLEMENT(TransferDirection); +ATTRIBUTE_CHECKER_IMPLEMENT(TransferDirection); -TransferDirection::TransferDirection (const char *a) +TransferDirection::TransferDirection(const char* a) { - for (uint32_t i = 0; i < numValues; i++) + for (uint32_t i = 0; i < numValues; i++) { - if (std::strcmp (a, stringValue[i]) == 0) + if (std::strcmp(a, stringValue[i]) == 0) { - m_value = Value (i); - return; + m_value = Value(i); + return; } } - NS_FATAL_ERROR ("Cannot decode transfer direction correctly: " << a); + NS_FATAL_ERROR("Cannot decode transfer direction correctly: " << a); } -TransferDirection::TransferDirection (const std::string a) : - TransferDirection (a.c_str ()) +TransferDirection::TransferDirection(const std::string a) + : TransferDirection(a.c_str()) { - } -std::istream & -operator >> (std::istream &is, TransferDirection &td) +std::istream& +operator>>(std::istream& is, TransferDirection& td) { - std::string tdString; + std::string tdString; - is >> tdString; - td = TransferDirection (tdString); + is >> tdString; + td = TransferDirection(tdString); - return is; + return is; } } // namespace ns3 diff --git a/src/report/transfer-direction.h b/src/report/transfer-direction.h index 5fdd8c1..48fe5b5 100644 --- a/src/report/transfer-direction.h +++ b/src/report/transfer-direction.h @@ -22,52 +22,69 @@ #include -namespace ns3 { +namespace ns3 +{ class TransferDirection { -public: - enum Value : uint8_t - { - Received, - Transmitted - }; - - constexpr static const uint32_t numValues = 2; - - const char *stringValue[numValues] = { - "Rx", - "Tx" - }; - - TransferDirection () = default; - constexpr TransferDirection (Value aDirection) : m_value {aDirection} {} - /** - * From C String - */ - TransferDirection (const char *a); - /** - * From C++ String - */ - TransferDirection (const std::string a); - - operator Value () const { return m_value; } - explicit operator bool () = delete; - - constexpr bool operator == (Value a) { return m_value == a; } - constexpr bool operator != (Value a) { return m_value == a; } - - constexpr const char * ToString () const { return stringValue[m_value]; } - -private: - Value m_value; + public: + enum Value : uint8_t + { + Received, + Transmitted + }; + + constexpr static const uint32_t numValues = 2; + + const char* stringValue[numValues] = {"Rx", "Tx"}; + + TransferDirection() = default; + + constexpr TransferDirection(Value aDirection) + : m_value{aDirection} + { + } + + /** + * From C String + */ + TransferDirection(const char* a); + /** + * From C++ String + */ + TransferDirection(const std::string a); + + operator Value() const + { + return m_value; + } + + explicit operator bool() = delete; + + constexpr bool operator==(Value a) + { + return m_value == a; + } + + constexpr bool operator!=(Value a) + { + return m_value == a; + } + + constexpr const char* ToString() const + { + return stringValue[m_value]; + } + + private: + Value m_value; }; -ATTRIBUTE_VALUE_DEFINE (TransferDirection); -ATTRIBUTE_ACCESSOR_DEFINE (TransferDirection); -ATTRIBUTE_CHECKER_DEFINE (TransferDirection); +ATTRIBUTE_VALUE_DEFINE(TransferDirection); +ATTRIBUTE_ACCESSOR_DEFINE(TransferDirection); +ATTRIBUTE_CHECKER_DEFINE(TransferDirection); -std::istream & operator >> (std::istream &is, TransferDirection &td); +std::istream& operator>>(std::istream& is, TransferDirection& td); } // namespace ns3 diff --git a/src/report/wifi-inspector.cc b/src/report/wifi-inspector.cc index 5f35e9f..dfa737c 100644 --- a/src/report/wifi-inspector.cc +++ b/src/report/wifi-inspector.cc @@ -24,184 +24,185 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("WifiInspector"); +NS_LOG_COMPONENT_DEFINE("WifiInspector"); -WifiInspector::WifiInspector (Ptr device) : - m_dev {InitializeNetDevice (device)}, - m_phy {InitializePhy (m_dev)}, - m_channel {InitializeChannel (m_dev)}, - m_mac {InitializeMac (m_dev)} +WifiInspector::WifiInspector(Ptr device) + : m_dev{InitializeNetDevice(device)}, + m_phy{InitializePhy(m_dev)}, + m_channel{InitializeChannel(m_dev)}, + m_mac{InitializeMac(m_dev)} { - NS_LOG_FUNCTION (this << device); + NS_LOG_FUNCTION(this << device); } -WifiInspector::~WifiInspector () +WifiInspector::~WifiInspector() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } const char* -WifiInspector::GetWifiStandard () const +WifiInspector::GetWifiStandard() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - const auto standard = m_phy->GetStandard (); + const auto standard = m_phy->GetStandard(); - switch (standard) + switch (standard) { - case WIFI_STANDARD_80211a: + case WIFI_STANDARD_80211a: return "802.11a"; - case WIFI_STANDARD_80211b: + case WIFI_STANDARD_80211b: return "802.11b"; - case WIFI_STANDARD_80211g: + case WIFI_STANDARD_80211g: return "802.11g"; - case WIFI_STANDARD_80211n: + case WIFI_STANDARD_80211n: return "802.11n"; - case WIFI_STANDARD_80211ac: + case WIFI_STANDARD_80211ac: return "802.11ac"; - case WIFI_STANDARD_80211ax: + case WIFI_STANDARD_80211ax: return "802.11ax"; - default: + default: return "UNSUPPORTED"; } } const uint16_t -WifiInspector::GetCarrierFrequency () const +WifiInspector::GetCarrierFrequency() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_phy->GetFrequency (); + return m_phy->GetFrequency(); } const std::string -WifiInspector::GetPropagationLossModel () const +WifiInspector::GetPropagationLossModel() const { - NS_LOG_FUNCTION_NOARGS (); - const TypeId channelTid = m_channel->GetInstanceTypeId (); - TypeId::AttributeInformation info; - PointerValue attribute; + NS_LOG_FUNCTION_NOARGS(); + const TypeId channelTid = m_channel->GetInstanceTypeId(); + TypeId::AttributeInformation info; + PointerValue attribute; - if (!channelTid.LookupAttributeByName ("PropagationLossModel", &info)) - NS_FATAL_ERROR ("Wifi Channel was expected to have PropagationLossModel as " - "attribute, but instead it does not exist!"); + if (!channelTid.LookupAttributeByName("PropagationLossModel", &info)) + NS_FATAL_ERROR("Wifi Channel was expected to have PropagationLossModel as " + "attribute, but instead it does not exist!"); - m_channel->GetAttribute (info.name, attribute); + m_channel->GetAttribute(info.name, attribute); - return attribute.GetObject ()->GetInstanceTypeId ().GetName (); + return attribute.GetObject()->GetInstanceTypeId().GetName(); } const std::string -WifiInspector::GetPropagationDelayModel () const +WifiInspector::GetPropagationDelayModel() const { - NS_LOG_FUNCTION_NOARGS (); - const TypeId channelTid = m_channel->GetInstanceTypeId (); - TypeId::AttributeInformation info; - PointerValue attribute; + NS_LOG_FUNCTION_NOARGS(); + const TypeId channelTid = m_channel->GetInstanceTypeId(); + TypeId::AttributeInformation info; + PointerValue attribute; - if (!channelTid.LookupAttributeByName ("PropagationDelayModel", &info)) - NS_FATAL_ERROR ("Wifi Channel was expected to have PropagationDelayModel as " - "attribute, but instead it does not exist!"); + if (!channelTid.LookupAttributeByName("PropagationDelayModel", &info)) + NS_FATAL_ERROR("Wifi Channel was expected to have PropagationDelayModel as " + "attribute, but instead it does not exist!"); - m_channel->GetAttribute (info.name, attribute); + m_channel->GetAttribute(info.name, attribute); - return attribute.GetObject ()->GetInstanceTypeId ().GetName (); + return attribute.GetObject()->GetInstanceTypeId().GetName(); } const std::string -WifiInspector::GetWifiSsid () const +WifiInspector::GetWifiSsid() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_mac->GetSsid ().PeekString (); + return m_mac->GetSsid().PeekString(); } const std::string -WifiInspector::GetWifiMode () const +WifiInspector::GetWifiMode() const { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - return m_dev->GetRemoteStationManager ()->GetDefaultMode ().GetUniqueName (); + return m_dev->GetRemoteStationManager()->GetDefaultMode().GetUniqueName(); } Ptr -WifiInspector::InitializeNetDevice (Ptr dev) +WifiInspector::InitializeNetDevice(Ptr dev) { - NS_LOG_FUNCTION (dev); - Ptr wifiNetDevice = DynamicCast (dev); + NS_LOG_FUNCTION(dev); + Ptr wifiNetDevice = DynamicCast(dev); - if (wifiNetDevice == nullptr) - NS_FATAL_ERROR ("Cannot inspect an object that is not a WifiNetDevice"); + if (wifiNetDevice == nullptr) + NS_FATAL_ERROR("Cannot inspect an object that is not a WifiNetDevice"); - return wifiNetDevice; + return wifiNetDevice; } Ptr -WifiInspector::InitializePhy (Ptr dev) +WifiInspector::InitializePhy(Ptr dev) { - NS_LOG_FUNCTION_NOARGS (); - const TypeId devTid = dev->GetInstanceTypeId (); - TypeId::AttributeInformation info; - PointerValue attribute; - Ptr phy; - - if (!devTid.LookupAttributeByName ("Phy", &info)) - NS_FATAL_ERROR ("Wifi Device was expected to have Phy as attribute, but " - "instead it does not exist!"); - - dev->GetAttribute (info.name, attribute); - phy = DynamicCast (attribute.GetObject ()); - if (phy == nullptr) - NS_FATAL_ERROR ("Cannot inspect and object that is not a WifiPhy."); - - return phy; + NS_LOG_FUNCTION_NOARGS(); + const TypeId devTid = dev->GetInstanceTypeId(); + TypeId::AttributeInformation info; + PointerValue attribute; + Ptr phy; + + if (!devTid.LookupAttributeByName("Phy", &info)) + NS_FATAL_ERROR("Wifi Device was expected to have Phy as attribute, but " + "instead it does not exist!"); + + dev->GetAttribute(info.name, attribute); + phy = DynamicCast(attribute.GetObject()); + if (phy == nullptr) + NS_FATAL_ERROR("Cannot inspect and object that is not a WifiPhy."); + + return phy; } Ptr -WifiInspector::InitializeChannel (Ptr dev) +WifiInspector::InitializeChannel(Ptr dev) { - NS_LOG_FUNCTION_NOARGS (); - const TypeId devTid = dev->GetInstanceTypeId (); - TypeId channelTid; - TypeId::AttributeInformation info; - PointerValue attribute; - Ptr channelObject; + NS_LOG_FUNCTION_NOARGS(); + const TypeId devTid = dev->GetInstanceTypeId(); + TypeId channelTid; + TypeId::AttributeInformation info; + PointerValue attribute; + Ptr channelObject; - if (!devTid.LookupAttributeByName ("Channel", &info)) - NS_FATAL_ERROR ("Device was expected to have Channel as attribute, but " - "instead it does not exist!"); + if (!devTid.LookupAttributeByName("Channel", &info)) + NS_FATAL_ERROR("Device was expected to have Channel as attribute, but " + "instead it does not exist!"); - dev->GetAttribute (info.name, attribute); - channelObject = attribute.GetObject (); - channelTid = channelObject->GetInstanceTypeId (); + dev->GetAttribute(info.name, attribute); + channelObject = attribute.GetObject(); + channelTid = channelObject->GetInstanceTypeId(); - if (channelTid.GetName () != "ns3::YansWifiChannel") - NS_FATAL_ERROR ("Unsupported channel type " << channelTid.GetName ()); + if (channelTid.GetName() != "ns3::YansWifiChannel") + NS_FATAL_ERROR("Unsupported channel type " << channelTid.GetName()); - return DynamicCast (channelObject); + return DynamicCast(channelObject); } Ptr -WifiInspector::InitializeMac (Ptr dev) +WifiInspector::InitializeMac(Ptr dev) { - NS_LOG_FUNCTION_NOARGS (); - const TypeId devTid = dev->GetInstanceTypeId (); - TypeId::AttributeInformation info; - PointerValue attribute; - Ptr mac; - - if (!devTid.LookupAttributeByName ("Mac", &info)) - NS_FATAL_ERROR ("Wifi Device was expected to have Mac as attribute, but " - "instead it does not exist!"); - - dev->GetAttribute (info.name, attribute); - mac = DynamicCast (attribute.GetObject ()); - if (mac == nullptr) - NS_FATAL_ERROR ("Cannot inspect and object that is not a WifiMac."); - - return mac; + NS_LOG_FUNCTION_NOARGS(); + const TypeId devTid = dev->GetInstanceTypeId(); + TypeId::AttributeInformation info; + PointerValue attribute; + Ptr mac; + + if (!devTid.LookupAttributeByName("Mac", &info)) + NS_FATAL_ERROR("Wifi Device was expected to have Mac as attribute, but " + "instead it does not exist!"); + + dev->GetAttribute(info.name, attribute); + mac = DynamicCast(attribute.GetObject()); + if (mac == nullptr) + NS_FATAL_ERROR("Cannot inspect and object that is not a WifiMac."); + + return mac; } } // namespace ns3 diff --git a/src/report/wifi-inspector.h b/src/report/wifi-inspector.h index 12da953..e141413 100644 --- a/src/report/wifi-inspector.h +++ b/src/report/wifi-inspector.h @@ -19,75 +19,76 @@ */ #ifndef WIFI_INSPECTOR_H #define WIFI_INSPECTOR_H -#include - #include #include #include #include #include -namespace ns3 { +#include + +namespace ns3 +{ class WifiInspector { -public: - /** - * Initialize the inspector with a given Network Device - */ - WifiInspector (Ptr device); - /** - * Default destructor - */ - ~WifiInspector (); + public: + /** + * Initialize the inspector with a given Network Device + */ + WifiInspector(Ptr device); + /** + * Default destructor + */ + ~WifiInspector(); - /** - * Get a string representation of the Wifi Standard in use - */ - const char* GetWifiStandard () const; - /** - * Get the carrier frequency used - */ - const uint16_t GetCarrierFrequency () const; - /** - * Get the propagation loss model that has been set - */ - const std::string GetPropagationLossModel () const; - /** - * Get the propagation delay model that has been set - */ - const std::string GetPropagationDelayModel () const; - /** - * Get the wifi ssid that the device is connected to - */ - const std::string GetWifiSsid () const; - /** - * Get the wifi mode of the device - */ - const std::string GetWifiMode () const; + /** + * Get a string representation of the Wifi Standard in use + */ + const char* GetWifiStandard() const; + /** + * Get the carrier frequency used + */ + const uint16_t GetCarrierFrequency() const; + /** + * Get the propagation loss model that has been set + */ + const std::string GetPropagationLossModel() const; + /** + * Get the propagation delay model that has been set + */ + const std::string GetPropagationDelayModel() const; + /** + * Get the wifi ssid that the device is connected to + */ + const std::string GetWifiSsid() const; + /** + * Get the wifi mode of the device + */ + const std::string GetWifiMode() const; -private: - /** - * Internal helper to treat a NetDevice as a WifiNetDevice - */ - static Ptr InitializeNetDevice (Ptr dev); - /** - * Internal helper to get the Phy Layer of a given WifiNetDevice - */ - static Ptr InitializePhy (Ptr dev); - /** - * Internal helper to get the Wifi Channel of a given WifiNetDevice - */ - static Ptr InitializeChannel (Ptr dev); - /** - * Internal helper to get the MAC Layer of a given WifiNetDevice - */ - static Ptr InitializeMac (Ptr dev); + private: + /** + * Internal helper to treat a NetDevice as a WifiNetDevice + */ + static Ptr InitializeNetDevice(Ptr dev); + /** + * Internal helper to get the Phy Layer of a given WifiNetDevice + */ + static Ptr InitializePhy(Ptr dev); + /** + * Internal helper to get the Wifi Channel of a given WifiNetDevice + */ + static Ptr InitializeChannel(Ptr dev); + /** + * Internal helper to get the MAC Layer of a given WifiNetDevice + */ + static Ptr InitializeMac(Ptr dev); - Ptr m_dev; /// Wifi Network Device to be inspected - Ptr m_phy; /// Wifi Phy Device, as cache - Ptr m_channel; /// Wifi Channel, as cache - Ptr m_mac; /// Wifi Mac, as cache + Ptr m_dev; /// Wifi Network Device to be inspected + Ptr m_phy; /// Wifi Phy Device, as cache + Ptr m_channel; /// Wifi Channel, as cache + Ptr m_mac; /// Wifi Mac, as cache }; } // namespace ns3 diff --git a/src/report/wifi-mac-layer.cc b/src/report/wifi-mac-layer.cc index bfae104..47222a6 100644 --- a/src/report/wifi-mac-layer.cc +++ b/src/report/wifi-mac-layer.cc @@ -22,64 +22,67 @@ #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("WifiMacLayer"); -NS_OBJECT_ENSURE_REGISTERED (WifiMacLayer); +NS_LOG_COMPONENT_DEFINE("WifiMacLayer"); +NS_OBJECT_ENSURE_REGISTERED(WifiMacLayer); TypeId -WifiMacLayer::GetTypeId () +WifiMacLayer::GetTypeId() { - static TypeId tid = TypeId ("ns3::WifiMacLayer") - .AddConstructor () - .SetParent () - .AddAttribute ("Ssid", "The SSID of the BSS", - StringValue (), - MakeStringAccessor (&WifiMacLayer::m_ssid), - MakeStringChecker ()) - .AddAttribute ("Mode", "The mode of the Wifi", - StringValue (), - MakeStringAccessor (&WifiMacLayer::m_mode), - MakeStringChecker ()) - ; + static TypeId tid = TypeId("ns3::WifiMacLayer") + .AddConstructor() + .SetParent() + .AddAttribute("Ssid", + "The SSID of the BSS", + StringValue(), + MakeStringAccessor(&WifiMacLayer::m_ssid), + MakeStringChecker()) + .AddAttribute("Mode", + "The mode of the Wifi", + StringValue(), + MakeStringAccessor(&WifiMacLayer::m_mode), + MakeStringChecker()); - return tid; + return tid; } -WifiMacLayer::WifiMacLayer () +WifiMacLayer::WifiMacLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -WifiMacLayer::~WifiMacLayer () +WifiMacLayer::~WifiMacLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -WifiMacLayer::Write (xmlTextWriterPtr h) +WifiMacLayer::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; + int rc; - rc = xmlTextWriterStartElement(h, BAD_CAST "mac"); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterStartElement(h, BAD_CAST "mac"); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "ssid", BAD_CAST m_ssid.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "ssid", BAD_CAST m_ssid.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterWriteElement(h, BAD_CAST "mode", BAD_CAST m_mode.c_str ()); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterWriteElement(h, BAD_CAST "mode", BAD_CAST m_mode.c_str()); + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement(h); - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } } // namespace ns3 diff --git a/src/report/wifi-mac-layer.h b/src/report/wifi-mac-layer.h index 75ae926..8f44143 100644 --- a/src/report/wifi-mac-layer.h +++ b/src/report/wifi-mac-layer.h @@ -20,39 +20,41 @@ #ifndef WIFI_MAC_LAYER_H #define WIFI_MAC_LAYER_H -#include - #include "protocol-layer.h" -namespace ns3 { +#include + +namespace ns3 +{ class WifiMacLayer : public ProtocolLayer { -public: - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); - - /** - * Default constructor - */ - WifiMacLayer (); - /** - * Default destructor - */ - ~WifiMacLayer (); - - /** - * Write WiFi MAC Layer report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - virtual void Write (xmlTextWriterPtr handle); -private: - std::string m_ssid; /// The connected Wifi SSID - std::string m_mode; /// The used wifi working mode + public: + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + WifiMacLayer(); + /** + * Default destructor + */ + ~WifiMacLayer(); + + /** + * Write WiFi MAC Layer report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + virtual void Write(xmlTextWriterPtr handle); + + private: + std::string m_ssid; /// The connected Wifi SSID + std::string m_mode; /// The used wifi working mode }; } // namespace ns3 diff --git a/src/report/wifi-phy-layer.cc b/src/report/wifi-phy-layer.cc index 155b13b..354b511 100644 --- a/src/report/wifi-phy-layer.cc +++ b/src/report/wifi-phy-layer.cc @@ -19,221 +19,214 @@ */ #include "wifi-phy-layer.h" -#include - #include #include #include #include -#include #include +#include #include #include #include -namespace ns3 { +#include + +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("WifiPhyLayer"); -NS_OBJECT_ENSURE_REGISTERED (WifiPhyLayer); +NS_LOG_COMPONENT_DEFINE("WifiPhyLayer"); +NS_OBJECT_ENSURE_REGISTERED(WifiPhyLayer); TypeId -WifiPhyLayer::GetTypeId () +WifiPhyLayer::GetTypeId() { - static TypeId tid = TypeId ("ns3::WifiPhyLayer") - .AddConstructor () - .SetParent () - .AddAttribute ("Frequency", "Wifi Carrier Frequency in use, in MHz", - IntegerValue (0), - MakeIntegerAccessor (&WifiPhyLayer::m_frequency), - MakeIntegerChecker ()) - .AddAttribute ("Standard", "Wifi Standard in use", - StringValue (), - MakeStringAccessor (&WifiPhyLayer::m_standard), - MakeStringChecker ()) - .AddAttribute ("PropagationDelayModel", "The propagation delay model used", - StringValue (), - MakeStringAccessor (&WifiPhyLayer::m_propagationDelayModel), - MakeStringChecker ()) - .AddAttribute ("PropagationLossModel", "The propagation loss model used", - StringValue (), - MakeStringAccessor (&WifiPhyLayer::m_propagationLossModel), - MakeStringChecker ()) - .AddAttribute ("NodeId", "Global unique identifier of the node", - IntegerValue (), - MakeIntegerAccessor (&WifiPhyLayer::m_droneReference), - MakeIntegerChecker ()) - .AddAttribute ("NetdevId", "ID of the Network Device of the given node", - IntegerValue (), - MakeIntegerAccessor (&WifiPhyLayer::m_netdevReference), - MakeIntegerChecker ()) - ; - - return tid; + static TypeId tid = + TypeId("ns3::WifiPhyLayer") + .AddConstructor() + .SetParent() + .AddAttribute("Frequency", + "Wifi Carrier Frequency in use, in MHz", + IntegerValue(0), + MakeIntegerAccessor(&WifiPhyLayer::m_frequency), + MakeIntegerChecker()) + .AddAttribute("Standard", + "Wifi Standard in use", + StringValue(), + MakeStringAccessor(&WifiPhyLayer::m_standard), + MakeStringChecker()) + .AddAttribute("PropagationDelayModel", + "The propagation delay model used", + StringValue(), + MakeStringAccessor(&WifiPhyLayer::m_propagationDelayModel), + MakeStringChecker()) + .AddAttribute("PropagationLossModel", + "The propagation loss model used", + StringValue(), + MakeStringAccessor(&WifiPhyLayer::m_propagationLossModel), + MakeStringChecker()) + .AddAttribute("NodeId", + "Global unique identifier of the node", + IntegerValue(), + MakeIntegerAccessor(&WifiPhyLayer::m_droneReference), + MakeIntegerChecker()) + .AddAttribute("NetdevId", + "ID of the Network Device of the given node", + IntegerValue(), + MakeIntegerAccessor(&WifiPhyLayer::m_netdevReference), + MakeIntegerChecker()); + + return tid; } -WifiPhyLayer::WifiPhyLayer () +WifiPhyLayer::WifiPhyLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -WifiPhyLayer::~WifiPhyLayer () +WifiPhyLayer::~WifiPhyLayer() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -WifiPhyLayer::Write (xmlTextWriterPtr h) +WifiPhyLayer::Write(xmlTextWriterPtr h) { - NS_LOG_FUNCTION (h); - if (h == nullptr) + NS_LOG_FUNCTION(h); + if (h == nullptr) { - NS_LOG_WARN ("Passed handler is not valid: " << h << ". " - "Data will be discarded."); - return; + NS_LOG_WARN("Passed handler is not valid: " << h + << ". " + "Data will be discarded."); + return; } - int rc; - - rc = xmlTextWriterStartElement(h, BAD_CAST "phy"); - NS_ASSERT (rc >= 0); - - /* Nested Elements */ - rc = xmlTextWriterWriteElement(h, - BAD_CAST "standard", - BAD_CAST m_standard.c_str ()); - NS_ASSERT (rc >= 0); - - std::stringstream bFrequency; - bFrequency << m_frequency; - rc = xmlTextWriterWriteElement (h, - BAD_CAST "frequency", - BAD_CAST bFrequency.str ().c_str ()); - NS_ASSERT (rc >= 0); - - std::stringstream bAddress; - bAddress << m_address; - rc = xmlTextWriterWriteElement (h, - BAD_CAST "address", - BAD_CAST bAddress.str ().c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteElement (h, - BAD_CAST "propagationDelayModel", - BAD_CAST m_propagationDelayModel.c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterWriteElement (h, - BAD_CAST "propagationLossModel", - BAD_CAST m_propagationLossModel.c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterStartElement (h, - BAD_CAST "signal"); - NS_ASSERT (rc >= 0); - - for (auto& sig : m_rssi) + int rc; + + rc = xmlTextWriterStartElement(h, BAD_CAST "phy"); + NS_ASSERT(rc >= 0); + + /* Nested Elements */ + rc = xmlTextWriterWriteElement(h, BAD_CAST "standard", BAD_CAST m_standard.c_str()); + NS_ASSERT(rc >= 0); + + std::stringstream bFrequency; + bFrequency << m_frequency; + rc = xmlTextWriterWriteElement(h, BAD_CAST "frequency", BAD_CAST bFrequency.str().c_str()); + NS_ASSERT(rc >= 0); + + std::stringstream bAddress; + bAddress << m_address; + rc = xmlTextWriterWriteElement(h, BAD_CAST "address", BAD_CAST bAddress.str().c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "propagationDelayModel", + BAD_CAST m_propagationDelayModel.c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterWriteElement(h, + BAD_CAST "propagationLossModel", + BAD_CAST m_propagationLossModel.c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterStartElement(h, BAD_CAST "signal"); + NS_ASSERT(rc >= 0); + + for (auto& sig : m_rssi) { - std::ostringstream bSig, bTx, bTime, bStaId; - - rc = xmlTextWriterStartElement (h, - BAD_CAST "rssi"); - NS_ASSERT (rc >= 0); - - bTime << std::get<0>(sig); - rc = xmlTextWriterWriteAttribute (h, - BAD_CAST "time", - BAD_CAST bTime.str ().c_str ()); - NS_ASSERT (rc >= 0); - - bTx << std::get<1>(sig); - rc = xmlTextWriterWriteAttribute (h, - BAD_CAST "from", - BAD_CAST bTx.str ().c_str ()); - NS_ASSERT (rc >= 0); - - bSig << std::get<2>(sig); - rc = xmlTextWriterWriteAttribute (h, - BAD_CAST "value", - BAD_CAST bSig.str ().c_str ()); - NS_ASSERT (rc >= 0); - - rc = xmlTextWriterEndElement (h); - NS_ASSERT (rc >= 0); + std::ostringstream bSig, bTx, bTime, bStaId; + + rc = xmlTextWriterStartElement(h, BAD_CAST "rssi"); + NS_ASSERT(rc >= 0); + + bTime << std::get<0>(sig); + rc = xmlTextWriterWriteAttribute(h, BAD_CAST "time", BAD_CAST bTime.str().c_str()); + NS_ASSERT(rc >= 0); + + bTx << std::get<1>(sig); + rc = xmlTextWriterWriteAttribute(h, BAD_CAST "from", BAD_CAST bTx.str().c_str()); + NS_ASSERT(rc >= 0); + + bSig << std::get<2>(sig); + rc = xmlTextWriterWriteAttribute(h, BAD_CAST "value", BAD_CAST bSig.str().c_str()); + NS_ASSERT(rc >= 0); + + rc = xmlTextWriterEndElement(h); + NS_ASSERT(rc >= 0); } - rc = xmlTextWriterEndElement(h); // signal - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); // signal + NS_ASSERT(rc >= 0); - rc = xmlTextWriterEndElement(h); // phy - NS_ASSERT (rc >= 0); + rc = xmlTextWriterEndElement(h); // phy + NS_ASSERT(rc >= 0); } void -WifiPhyLayer::DoInitialize () +WifiPhyLayer::DoInitialize() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - m_address = GetDeviceAddress (); // TODO: it would be usedul to report it in the XML file. - DoInitializeRssiMonitor (); + m_address = GetDeviceAddress(); // TODO: it would be usedul to report it in the XML file. + DoInitializeRssiMonitor(); - ProtocolLayer::DoInitialize (); + ProtocolLayer::DoInitialize(); } void -WifiPhyLayer::DoInitializeRssiMonitor () +WifiPhyLayer::DoInitializeRssiMonitor() { - NS_LOG_FUNCTION_NOARGS (); - /* set callback using ns-3 XPath addressing system */ - std::stringstream xPathCallback; - - xPathCallback << "/NodeList/" << m_droneReference - << "/DeviceList/" << m_netdevReference - << "/$ns3::WifiNetDevice/Phy/PhyRxBegin"; - Config::ConnectWithoutContext (xPathCallback.str (), - MakeCallback (&WifiPhyLayer::DoMonitorRssi, this)); + NS_LOG_FUNCTION_NOARGS(); + /* set callback using ns-3 XPath addressing system */ + std::stringstream xPathCallback; + + xPathCallback << "/NodeList/" << m_droneReference << "/DeviceList/" << m_netdevReference + << "/$ns3::WifiNetDevice/Phy/PhyRxBegin"; + Config::ConnectWithoutContext(xPathCallback.str(), + MakeCallback(&WifiPhyLayer::DoMonitorRssi, this)); } Mac48Address -WifiPhyLayer::GetDeviceAddress () +WifiPhyLayer::GetDeviceAddress() { - auto n = NodeList::GetNode (m_droneReference); - auto d = n->GetDevice (m_netdevReference); - auto a = d->GetAddress (); - return Mac48Address::ConvertFrom (a); + auto n = NodeList::GetNode(m_droneReference); + auto d = n->GetDevice(m_netdevReference); + auto a = d->GetAddress(); + return Mac48Address::ConvertFrom(a); } void -WifiPhyLayer::DoMonitorRssi (Ptr packet, RxPowerWattPerChannelBand rxPowersW) +WifiPhyLayer::DoMonitorRssi(Ptr packet, RxPowerWattPerChannelBand rxPowersW) { - //The total RX power corresponds to the maximum over all the bands - auto it = std::max_element (rxPowersW.begin (), rxPowersW.end (), - [] (const std::pair &p1, - const std::pair &p2) { - return p1.second < p2.second; - }); - auto rssi = 10 * log (it->second / 1e-3 /* to mW */); - - WifiMacHeader hdr; - Mac48Address sender; - packet->PeekHeader (hdr); - - // check if packet is for this net device - auto da = (hdr.IsToDs ()) ? hdr.GetAddr3 () : hdr.GetAddr1 (); - if (da != m_address) - return; - - if ((!hdr.IsToDs () && !hdr.IsFromDs ()) || (hdr.IsToDs () && !hdr.IsFromDs ())) - sender = hdr.GetAddr2 (); - else if (!hdr.IsToDs () && hdr.IsFromDs ()) - sender = hdr.GetAddr3 (); - else if (hdr.IsToDs () && hdr.IsFromDs ()) - sender = hdr.GetAddr4 (); - - // filter out any sender, which happens in case of CTL ACK frames - if (sender == Mac48Address()) - return; - - m_rssi.push_back({ Simulator::Now ().GetSeconds (), sender, rssi }); + // The total RX power corresponds to the maximum over all the bands + auto it = std::max_element( + rxPowersW.begin(), + rxPowersW.end(), + [](const std::pair& p1, + const std::pair& p2) { return p1.second < p2.second; }); + auto rssi = 10 * log(it->second / 1e-3 /* to mW */); + + WifiMacHeader hdr; + Mac48Address sender; + packet->PeekHeader(hdr); + + // check if packet is for this net device + auto da = (hdr.IsToDs()) ? hdr.GetAddr3() : hdr.GetAddr1(); + if (da != m_address) + return; + + if ((!hdr.IsToDs() && !hdr.IsFromDs()) || (hdr.IsToDs() && !hdr.IsFromDs())) + sender = hdr.GetAddr2(); + else if (!hdr.IsToDs() && hdr.IsFromDs()) + sender = hdr.GetAddr3(); + else if (hdr.IsToDs() && hdr.IsFromDs()) + sender = hdr.GetAddr4(); + + // filter out any sender, which happens in case of CTL ACK frames + if (sender == Mac48Address()) + return; + + m_rssi.push_back({Simulator::Now().GetSeconds(), sender, rssi}); } } // namespace ns3 diff --git a/src/report/wifi-phy-layer.h b/src/report/wifi-phy-layer.h index 55fc909..84f6dce 100644 --- a/src/report/wifi-phy-layer.h +++ b/src/report/wifi-phy-layer.h @@ -20,76 +20,78 @@ #ifndef WIFI_PHY_LAYER_H #define WIFI_PHY_LAYER_H -#include +#include "protocol-layer.h" #include #include #include #include -#include "protocol-layer.h" +#include -namespace ns3 { +namespace ns3 +{ class WifiPhyLayer : public ProtocolLayer { -public: - typedef std::tuple RssiSample; - - /** - * Register the type using ns-3 TypeId System. - * \return the object TypeId - */ - static TypeId GetTypeId (); - - /** - * Default constructor - */ - WifiPhyLayer (); - /** - * Default destructor - */ - ~WifiPhyLayer (); - - /** - * Write Protocol Stack report data to a XML file with a given handler - * - * \param handle the XML handler to write data on - */ - virtual void Write (xmlTextWriterPtr handle); - -protected: - /** - * Private initialization of the object - */ - virtual void DoInitialize (); - -private: - /** - * Retrieve device MAC Address. - */ - Mac48Address GetDeviceAddress (); - /** - * Initialize RSSI monitor in order to build a history of the RSSI for - * the current entity with the current network device - */ - void DoInitializeRssiMonitor (); - - /** - * Handle the arrival of new RSSI data - */ - void DoMonitorRssi (Ptr packet, RxPowerWattPerChannelBand rxPowersW); - - uint32_t m_droneReference; /// ID of the drone - uint32_t m_netdevReference; /// ID of the network device - - std::vector m_rssi; /// RSSI history of the device - - double m_frequency; /// the carrier frequency set - Mac48Address m_address; /// Device MAC Address - std::string m_standard; /// the wifi standard used - std::string m_propagationDelayModel; /// the prop. delay model set - std::string m_propagationLossModel; /// the prop. loss model set + public: + typedef std::tuple + RssiSample; + + /** + * Register the type using ns-3 TypeId System. + * \return the object TypeId + */ + static TypeId GetTypeId(); + + /** + * Default constructor + */ + WifiPhyLayer(); + /** + * Default destructor + */ + ~WifiPhyLayer(); + + /** + * Write Protocol Stack report data to a XML file with a given handler + * + * \param handle the XML handler to write data on + */ + virtual void Write(xmlTextWriterPtr handle); + + protected: + /** + * Private initialization of the object + */ + virtual void DoInitialize(); + + private: + /** + * Retrieve device MAC Address. + */ + Mac48Address GetDeviceAddress(); + /** + * Initialize RSSI monitor in order to build a history of the RSSI for + * the current entity with the current network device + */ + void DoInitializeRssiMonitor(); + + /** + * Handle the arrival of new RSSI data + */ + void DoMonitorRssi(Ptr packet, RxPowerWattPerChannelBand rxPowersW); + + uint32_t m_droneReference; /// ID of the drone + uint32_t m_netdevReference; /// ID of the network device + + std::vector m_rssi; /// RSSI history of the device + + double m_frequency; /// the carrier frequency set + Mac48Address m_address; /// Device MAC Address + std::string m_standard; /// the wifi standard used + std::string m_propagationDelayModel; /// the prop. delay model set + std::string m_propagationLossModel; /// the prop. loss model set }; } // namespace ns3 diff --git a/src/world/interest-region-container.cc b/src/world/interest-region-container.cc index 1934d61..28a3fb7 100644 --- a/src/world/interest-region-container.cc +++ b/src/world/interest-region-container.cc @@ -18,73 +18,84 @@ #include "interest-region-container.h" -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("InterestRegionContainer"); +NS_LOG_COMPONENT_DEFINE("InterestRegionContainer"); -InterestRegionContainer::InterestRegionContainer(){} +InterestRegionContainer::InterestRegionContainer() +{ +} -InterestRegionContainer::~InterestRegionContainer(){ - for (std::vector>::iterator i = m_interestRegions.begin (); i != m_interestRegions.end (); i++) - { +InterestRegionContainer::~InterestRegionContainer() +{ + for (std::vector>::iterator i = m_interestRegions.begin(); + i != m_interestRegions.end(); + i++) + { Ptr region = *i; - region->Dispose (); + region->Dispose(); *i = 0; - } + } m_interestRegions.clear(); } const Ptr -InterestRegionContainer::Create(const DoubleVector &coords) +InterestRegionContainer::Create(const DoubleVector& coords) { - auto region = CreateObjectWithAttributes("Coordinates",DoubleVectorValue(coords)); - m_interestRegions.push_back(region); - return region; + auto region = + CreateObjectWithAttributes("Coordinates", DoubleVectorValue(coords)); + m_interestRegions.push_back(region); + return region; } uint32_t -InterestRegionContainer::GetN (void) const +InterestRegionContainer::GetN(void) const { - return m_interestRegions.size (); + return m_interestRegions.size(); } Ptr -InterestRegionContainer::GetRoI (uint32_t i) +InterestRegionContainer::GetRoI(uint32_t i) { - return m_interestRegions[i]; + return m_interestRegions[i]; } InterestRegionContainer::Iterator -InterestRegionContainer::Begin (void) const +InterestRegionContainer::Begin(void) const { - return m_interestRegions.begin (); + return m_interestRegions.begin(); } InterestRegionContainer::Iterator -InterestRegionContainer::End (void) const +InterestRegionContainer::End(void) const { - return m_interestRegions.end (); + return m_interestRegions.end(); } int -InterestRegionContainer::IsInRegions(std::vector indexes, Vector &position) +InterestRegionContainer::IsInRegions(std::vector indexes, Vector& position) { - if (m_interestRegions.size() == 0) return -2; - for (auto index : indexes) - { - if (m_interestRegions[index]->IsInside(position)) return index; - } - return -1; + if (m_interestRegions.size() == 0) + return -2; + for (auto index : indexes) + { + if (m_interestRegions[index]->IsInside(position)) + return index; + } + return -1; } int -InterestRegionContainer::IsInRegions(Vector &position) +InterestRegionContainer::IsInRegions(Vector& position) { - if (m_interestRegions.size() == 0) return -2; - for (int index=0;index< (int) m_interestRegions.size();index++) - { - if (m_interestRegions[index]->IsInside(position)) return index; - } - return -1; + if (m_interestRegions.size() == 0) + return -2; + for (int index = 0; index < (int)m_interestRegions.size(); index++) + { + if (m_interestRegions[index]->IsInside(position)) + return index; + } + return -1; } } // namespace ns3 \ No newline at end of file diff --git a/src/world/interest-region-container.h b/src/world/interest-region-container.h index cfd7b71..c66e5da 100644 --- a/src/world/interest-region-container.h +++ b/src/world/interest-region-container.h @@ -18,91 +18,92 @@ #ifndef INTEREST_REGION_CONTAINER_H #define INTEREST_REGION_CONTAINER_H -#include +#include "interest-region.h" #include #include #include -#include "interest-region.h" +#include #define irc InterestRegionContainer::Get() -namespace ns3 { +namespace ns3 +{ /** * \brief Keeps track of a set of region of interest pointers. */ class InterestRegionContainer : public Singleton { -public: - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - // static TypeId GetTypeId (void); - - InterestRegionContainer(); - ~InterestRegionContainer(); - - /// Container iterator - typedef std::vector>::const_iterator Iterator; - - /** - * \brief Creates a RoI and append the pointer to the container - * - * \param coords 3D coordinates of the desired box - * \return The RoI pointer created - */ - const Ptr Create (const DoubleVector &coords); - - /** - * \brief An iterator which refers to the first RoI in the - * container. - * - * \returns an iterator which refers to the first RoI in the container. - */ - Iterator Begin (void) const; - - /** - * \brief An iterator which indicates past-the-last RoI in the - * container. - * - * \returns an iterator which indicates an ending condition for a loop. - */ - Iterator End (void) const; - - /** - * \brief Gets the number of Ptr stored in this container. - * - * \returns the number of Ptr stored in this container. - */ - uint32_t GetN (void) const; - - /** - * \brief Gets the Ptr stored in this container at a given - * index. - * - * \param i the index of the requested RoI pointer. - * \returns the requested RoI pointer. - */ - Ptr GetRoI (uint32_t i); - - /** - * \brief Verifies that a certain point belongs to a set of regions - * - * \param indexes vector of regions' indexes. - * \param position Vector of 3D coordinates describing the point. - * \returns -1 If it does not belong to any region - * -2 If the region vector is empty - * If it does belong to a region - */ - int IsInRegions(std::vector indexes, Vector &position); - int IsInRegions(Vector &position); - -private: - std::vector> m_interestRegions; //!< Regions smart pointers + public: + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + // static TypeId GetTypeId (void); + + InterestRegionContainer(); + ~InterestRegionContainer(); + + /// Container iterator + typedef std::vector>::const_iterator Iterator; + + /** + * \brief Creates a RoI and append the pointer to the container + * + * \param coords 3D coordinates of the desired box + * \return The RoI pointer created + */ + const Ptr Create(const DoubleVector& coords); + + /** + * \brief An iterator which refers to the first RoI in the + * container. + * + * \returns an iterator which refers to the first RoI in the container. + */ + Iterator Begin(void) const; + + /** + * \brief An iterator which indicates past-the-last RoI in the + * container. + * + * \returns an iterator which indicates an ending condition for a loop. + */ + Iterator End(void) const; + + /** + * \brief Gets the number of Ptr stored in this container. + * + * \returns the number of Ptr stored in this container. + */ + uint32_t GetN(void) const; + + /** + * \brief Gets the Ptr stored in this container at a given + * index. + * + * \param i the index of the requested RoI pointer. + * \returns the requested RoI pointer. + */ + Ptr GetRoI(uint32_t i); + + /** + * \brief Verifies that a certain point belongs to a set of regions + * + * \param indexes vector of regions' indexes. + * \param position Vector of 3D coordinates describing the point. + * \returns -1 If it does not belong to any region + * -2 If the region vector is empty + * If it does belong to a region + */ + int IsInRegions(std::vector indexes, Vector& position); + int IsInRegions(Vector& position); + + private: + std::vector> m_interestRegions; //!< Regions smart pointers }; } // namespace ns3 diff --git a/src/world/interest-region.cc b/src/world/interest-region.cc index 66bf9d7..c1960e0 100644 --- a/src/world/interest-region.cc +++ b/src/world/interest-region.cc @@ -17,71 +17,78 @@ */ #include "interest-region.h" -#include - +#include #include #include -#include -namespace ns3 { +#include + +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("InterestRegion"); -NS_OBJECT_ENSURE_REGISTERED (InterestRegion); +NS_LOG_COMPONENT_DEFINE("InterestRegion"); +NS_OBJECT_ENSURE_REGISTERED(InterestRegion); TypeId -InterestRegion::GetTypeId (void) +InterestRegion::GetTypeId(void) { - static TypeId tid = TypeId ("ns3::InterestRegion") - .SetParent () - .SetGroupName ("Scenario") - .AddConstructor () - .AddAttribute ("Coordinates", "Box 3D coordinates, i.e., xMin|xMax|yMin|yMax|zMin|zMax|.", - DoubleVectorValue (), - MakeDoubleVectorAccessor (&InterestRegion::SetCoordinates), - MakeDoubleVectorChecker ()) - ; - return tid; + static TypeId tid = + TypeId("ns3::InterestRegion") + .SetParent() + .SetGroupName("Scenario") + .AddConstructor() + .AddAttribute("Coordinates", + "Box 3D coordinates, i.e., xMin|xMax|yMin|yMax|zMin|zMax|.", + DoubleVectorValue(), + MakeDoubleVectorAccessor(&InterestRegion::SetCoordinates), + MakeDoubleVectorChecker()); + return tid; } -InterestRegion::InterestRegion () +InterestRegion::InterestRegion() { } -InterestRegion::~InterestRegion () +InterestRegion::~InterestRegion() { } void -InterestRegion::DoDispose () +InterestRegion::DoDispose() { - NS_LOG_FUNCTION (this); - Object::DoDispose (); + NS_LOG_FUNCTION(this); + Object::DoDispose(); } void -InterestRegion::DoInitialize (void) +InterestRegion::DoInitialize(void) { - NS_LOG_FUNCTION (this); - Object::DoInitialize (); + NS_LOG_FUNCTION(this); + Object::DoInitialize(); } const DoubleVector -InterestRegion::GetCoordinates () const +InterestRegion::GetCoordinates() const { - return m_coordinates; + return m_coordinates; } void -InterestRegion::SetCoordinates (const DoubleVector &coords) +InterestRegion::SetCoordinates(const DoubleVector& coords) { - m_coordinates = coords; - m_box = Box(m_coordinates.Get(0),m_coordinates.Get(1),m_coordinates.Get(2),m_coordinates.Get(3),m_coordinates.Get(4),m_coordinates.Get(5)); + m_coordinates = coords; + m_box = Box(m_coordinates.Get(0), + m_coordinates.Get(1), + m_coordinates.Get(2), + m_coordinates.Get(3), + m_coordinates.Get(4), + m_coordinates.Get(5)); } bool -InterestRegion::IsInside (const Vector &position) const +InterestRegion::IsInside(const Vector& position) const { - return m_box.IsInside(position); + return m_box.IsInside(position); } } // namespace ns3 diff --git a/src/world/interest-region.h b/src/world/interest-region.h index 33e4ad4..ceffed9 100644 --- a/src/world/interest-region.h +++ b/src/world/interest-region.h @@ -19,53 +19,53 @@ #define INTEREST_REGION_H #include +#include #include #include -#include - -namespace ns3 { +namespace ns3 +{ /** * \brief A 3D region of interest modelled as a box */ class InterestRegion : public Object { -public: - /** - * \brief Get the type ID. - * - * \returns the object TypeId - */ - static TypeId GetTypeId (void); - /** - * \brief default constructor - */ - InterestRegion (); - /** - * \brief default destructor - */ - virtual ~InterestRegion (); - /** - * \return the 3D coordinates of the box - */ - const DoubleVector GetCoordinates () const; - /** - * \brief Sets the 3D coordinates of the box - * - * \param coords DoubleVector containing 3D coordinates of the box - */ - void SetCoordinates (const DoubleVector &coords); + public: + /** + * \brief Get the type ID. + * + * \returns the object TypeId + */ + static TypeId GetTypeId(void); + /** + * \brief default constructor + */ + InterestRegion(); + /** + * \brief default destructor + */ + virtual ~InterestRegion(); + /** + * \return the 3D coordinates of the box + */ + const DoubleVector GetCoordinates() const; + /** + * \brief Sets the 3D coordinates of the box + * + * \param coords DoubleVector containing 3D coordinates of the box + */ + void SetCoordinates(const DoubleVector& coords); - bool IsInside (const Vector &position) const; + bool IsInside(const Vector& position) const; -protected: - virtual void DoDispose (void); - virtual void DoInitialize (void); + protected: + virtual void DoDispose(void); + virtual void DoInitialize(void); -private: - Box m_box; - DoubleVector m_coordinates; + private: + Box m_box; + DoubleVector m_coordinates; }; } // namespace ns3