repo
stringlengths
1
152
file
stringlengths
15
205
code
stringlengths
0
41.6M
file_length
int64
0
41.6M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringlengths
1
100
null
AICP-main/veins/src/veins/modules/analogueModel/TwoRayInterferenceModel.cc
// // Copyright (C) 2011 Stefan Joerer <stefan.joerer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/analogueModel/TwoRayInterferenceModel.h" #include "veins/base/messages/AirFrame_m.h" using namespace veins; void TwoRayInterferenceModel::filterSignal(Signal* signal) { auto senderPos = signal->getSenderPoa().pos.getPositionAt(); auto receiverPos = signal->getReceiverPoa().pos.getPositionAt(); const Coord senderPos2D(senderPos.x, senderPos.y); const Coord receiverPos2D(receiverPos.x, receiverPos.y); ASSERT(senderPos.z > 0); // make sure send antenna is above ground ASSERT(receiverPos.z > 0); // make sure receive antenna is above ground double d = senderPos2D.distance(receiverPos2D); double ht = senderPos.z, hr = receiverPos.z; EV_TRACE << "(ht, hr) = (" << ht << ", " << hr << ")" << endl; double d_dir = sqrt(pow(d, 2) + pow((ht - hr), 2)); // direct distance double d_ref = sqrt(pow(d, 2) + pow((ht + hr), 2)); // distance via ground reflection double sin_theta = (ht + hr) / d_ref; double cos_theta = d / d_ref; double gamma = (sin_theta - sqrt(epsilon_r - pow(cos_theta, 2))) / (sin_theta + sqrt(epsilon_r - pow(cos_theta, 2))); Signal attenuation(signal->getSpectrum()); for (uint16_t i = 0; i < signal->getNumValues(); i++) { double freq = signal->getSpectrum().freqAt(i); double lambda = BaseWorldUtility::speedOfLight() / freq; double phi = (2 * M_PI / lambda * (d_dir - d_ref)); double att = pow(4 * M_PI * (d / lambda) * 1 / (sqrt((pow((1 + gamma * cos(phi)), 2) + pow(gamma, 2) * pow(sin(phi), 2)))), 2); EV_TRACE << "Add attenuation for (freq, lambda, phi, gamma, att) = (" << freq << ", " << lambda << ", " << phi << ", " << gamma << ", " << (1 / att) << ", " << FWMath::mW2dBm(att) << ")" << endl; attenuation.at(i) = 1 / att; } *signal *= attenuation; }
2,734
41.734375
203
cc
null
AICP-main/veins/src/veins/modules/analogueModel/TwoRayInterferenceModel.h
// // Copyright (C) 2011 Stefan Joerer <stefan.joerer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/base/phyLayer/AnalogueModel.h" #include "veins/base/modules/BaseWorldUtility.h" namespace veins { using veins::AirFrame; /** * @brief * Extended version of Two-Ray Ground path loss model. * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * An in-depth description of the model is available at: * Christoph Sommer and Falko Dressler, "Using the Right Two-Ray Model? A Measurement based Evaluation of PHY Models in VANETs," Proceedings of 17th ACM International Conference on Mobile Computing and Networking (MobiCom 2011), Poster Session, Las Vegas, NV, September 2011. * * @author Stefan Joerer * * @ingroup analogueModels */ class VEINS_API TwoRayInterferenceModel : public AnalogueModel { public: TwoRayInterferenceModel(cComponent* owner, double dielectricConstant) : AnalogueModel(owner) , epsilon_r(dielectricConstant) { } ~TwoRayInterferenceModel() override { } void filterSignal(Signal* signal) override; protected: /** @brief stores the dielectric constant used for calculation */ double epsilon_r; }; } // namespace veins
2,102
30.863636
275
h
null
AICP-main/veins/src/veins/modules/analogueModel/VehicleObstacleShadowing.cc
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/analogueModel/VehicleObstacleShadowing.h" using namespace veins; VehicleObstacleShadowing::VehicleObstacleShadowing(cComponent* owner, VehicleObstacleControl& vehicleObstacleControl, bool useTorus, const Coord& playgroundSize) : AnalogueModel(owner) , vehicleObstacleControl(vehicleObstacleControl) , useTorus(useTorus) , playgroundSize(playgroundSize) { if (useTorus) throw cRuntimeError("VehicleObstacleShadowing does not work on torus-shaped playgrounds"); } void VehicleObstacleShadowing::filterSignal(Signal* signal) { auto senderPos = signal->getSenderPoa().pos.getPositionAt(); auto receiverPos = signal->getReceiverPoa().pos.getPositionAt(); auto potentialObstacles = vehicleObstacleControl.getPotentialObstacles(signal->getSenderPoa().pos, signal->getReceiverPoa().pos, *signal); if (potentialObstacles.size() < 1) return; double senderHeight = senderPos.z; double receiverHeight = receiverPos.z; potentialObstacles.insert(potentialObstacles.begin(), std::make_pair(0, senderHeight)); potentialObstacles.emplace_back(senderPos.distance(receiverPos), receiverHeight); auto attenuationDB = VehicleObstacleControl::getVehicleAttenuationDZ(potentialObstacles, Signal(signal->getSpectrum())); EV_TRACE << "t=" << simTime() << ": Attenuation by vehicles is " << attenuationDB << std::endl; // convert from "dB loss" to a multiplicative factor Signal attenuation(attenuationDB.getSpectrum()); for (uint16_t i = 0; i < attenuation.getNumValues(); i++) { attenuation.at(i) = pow(10.0, -attenuationDB.at(i) / 10.0); } *signal *= attenuation; }
2,570
40.467742
161
cc
null
AICP-main/veins/src/veins/modules/analogueModel/VehicleObstacleShadowing.h
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/base/phyLayer/AnalogueModel.h" #include "veins/base/modules/BaseWorldUtility.h" #include "veins/modules/obstacle/VehicleObstacleControl.h" #include "veins/base/utils/Move.h" #include "veins/base/messages/AirFrame_m.h" using veins::AirFrame; using veins::VehicleObstacleControl; #include <cstdlib> namespace veins { /** * @brief Basic implementation of a VehicleObstacleShadowing that uses * SimplePathlossConstMapping (that is subclassed from SimpleConstMapping) as attenuation-Mapping. * * @ingroup analogueModels */ class VEINS_API VehicleObstacleShadowing : public AnalogueModel { protected: /** @brief reference to global VehicleObstacleControl instance */ VehicleObstacleControl& vehicleObstacleControl; /** @brief Information needed about the playground */ const bool useTorus; /** @brief The size of the playground.*/ const Coord& playgroundSize; public: /** * @brief Initializes the analogue model. myMove and playgroundSize * need to be valid as long as this instance exists. * * The constructor needs some specific knowledge in order to create * its mapping properly: * * @param owner pointer to the cComponent that owns this AnalogueModel * @param vehicleObstacleControl reference to global VehicleObstacleControl module * @param useTorus information about the playground the host is moving in * @param playgroundSize information about the playground the host is moving in */ VehicleObstacleShadowing(cComponent* owner, VehicleObstacleControl& vehicleObstacleControl, bool useTorus, const Coord& playgroundSize); /** * @brief Filters a specified Signal by adding an attenuation * over time to the Signal. */ void filterSignal(Signal* signal) override; bool neverIncreasesPower() override { return true; } }; } // namespace veins
2,820
32.987952
140
h
null
AICP-main/veins/src/veins/modules/application/ieee80211p/DemoBaseApplLayer.cc
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/application/ieee80211p/DemoBaseApplLayer.h" using namespace veins; void DemoBaseApplLayer::initialize(int stage) { BaseApplLayer::initialize(stage); if (stage == 0) { // initialize pointers to other modules if (FindModule<TraCIMobility*>::findSubModule(getParentModule())) { mobility = TraCIMobilityAccess().get(getParentModule()); traci = mobility->getCommandInterface(); traciVehicle = mobility->getVehicleCommandInterface(); } else { traci = nullptr; mobility = nullptr; traciVehicle = nullptr; } annotations = AnnotationManagerAccess().getIfExists(); ASSERT(annotations); mac = FindModule<DemoBaseApplLayerToMac1609_4Interface*>::findSubModule(getParentModule()); ASSERT(mac); // read parameters headerLength = par("headerLength"); sendBeacons = par("sendBeacons").boolValue(); beaconLengthBits = par("beaconLengthBits"); beaconUserPriority = par("beaconUserPriority"); beaconInterval = par("beaconInterval"); dataLengthBits = par("dataLengthBits"); dataOnSch = par("dataOnSch").boolValue(); dataUserPriority = par("dataUserPriority"); wsaInterval = par("wsaInterval").doubleValue(); currentOfferedServiceId = -1; isParked = false; findHost()->subscribe(BaseMobility::mobilityStateChangedSignal, this); findHost()->subscribe(TraCIMobility::parkingStateChangedSignal, this); sendBeaconEvt = new cMessage("beacon evt", SEND_BEACON_EVT); sendWSAEvt = new cMessage("wsa evt", SEND_WSA_EVT); generatedBSMs = 0; generatedWSAs = 0; generatedWSMs = 0; receivedBSMs = 0; receivedWSAs = 0; receivedWSMs = 0; } else if (stage == 1) { // store MAC address for quick access myId = mac->getMACAddress(); // simulate asynchronous channel access if (dataOnSch == true && !mac->isChannelSwitchingActive()) { dataOnSch = false; EV_ERROR << "App wants to send data on SCH but MAC doesn't use any SCH. Sending all data on CCH" << std::endl; } simtime_t firstBeacon = simTime(); if (par("avoidBeaconSynchronization").boolValue() == true) { simtime_t randomOffset = dblrand() * beaconInterval; firstBeacon = simTime() + randomOffset; if (mac->isChannelSwitchingActive() == true) { if (beaconInterval.raw() % (mac->getSwitchingInterval().raw() * 2)) { EV_ERROR << "The beacon interval (" << beaconInterval << ") is smaller than or not a multiple of one synchronization interval (" << 2 * mac->getSwitchingInterval() << "). This means that beacons are generated during SCH intervals" << std::endl; } firstBeacon = computeAsynchronousSendingTime(beaconInterval, ChannelType::control); } if (sendBeacons) { scheduleAt(firstBeacon, sendBeaconEvt); } } } } simtime_t DemoBaseApplLayer::computeAsynchronousSendingTime(simtime_t interval, ChannelType chan) { /* * avoid that periodic messages for one channel type are scheduled in the other channel interval * when alternate access is enabled in the MAC */ simtime_t randomOffset = dblrand() * beaconInterval; simtime_t firstEvent; simtime_t switchingInterval = mac->getSwitchingInterval(); // usually 0.050s simtime_t nextCCH; /* * start event earliest in next CCH (or SCH) interval. For alignment, first find the next CCH interval * To find out next CCH, go back to start of current interval and add two or one intervals * depending on type of current interval */ if (mac->isCurrentChannelCCH()) { nextCCH = simTime() - SimTime().setRaw(simTime().raw() % switchingInterval.raw()) + switchingInterval * 2; } else { nextCCH = simTime() - SimTime().setRaw(simTime().raw() % switchingInterval.raw()) + switchingInterval; } firstEvent = nextCCH + randomOffset; // check if firstEvent lies within the correct interval and, if not, move to previous interval if (firstEvent.raw() % (2 * switchingInterval.raw()) > switchingInterval.raw()) { // firstEvent is within a sch interval if (chan == ChannelType::control) firstEvent -= switchingInterval; } else { // firstEvent is within a cch interval, so adjust for SCH messages if (chan == ChannelType::service) firstEvent += switchingInterval; } return firstEvent; } void DemoBaseApplLayer::populateWSM(BaseFrame1609_4* wsm, LAddress::L2Type rcvId, int serial) { wsm->setRecipientAddress(rcvId); wsm->setBitLength(headerLength); if (DemoSafetyMessage* bsm = dynamic_cast<DemoSafetyMessage*>(wsm)) { bsm->setSenderPos(curPosition); bsm->setAngle(mobility->getHeading().getRad()); bsm->setSenderSpeed(curSpeed); bsm->setPsid(-1); bsm->setChannelNumber(static_cast<int>(Channel::cch)); bsm->addBitLength(beaconLengthBits); wsm->setUserPriority(beaconUserPriority); } else if (DemoServiceAdvertisment* wsa = dynamic_cast<DemoServiceAdvertisment*>(wsm)) { wsa->setChannelNumber(static_cast<int>(Channel::cch)); wsa->setTargetChannel(static_cast<int>(currentServiceChannel)); wsa->setPsid(currentOfferedServiceId); wsa->setServiceDescription(currentServiceDescription.c_str()); } else { if (dataOnSch) wsm->setChannelNumber(static_cast<int>(Channel::sch1)); // will be rewritten at Mac1609_4 to actual Service Channel. This is just so no controlInfo is needed else wsm->setChannelNumber(static_cast<int>(Channel::cch)); wsm->addBitLength(dataLengthBits); wsm->setUserPriority(dataUserPriority); } } void DemoBaseApplLayer::receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details) { Enter_Method_Silent(); if (signalID == BaseMobility::mobilityStateChangedSignal) { handlePositionUpdate(obj); } else if (signalID == TraCIMobility::parkingStateChangedSignal) { handleParkingUpdate(obj); } } void DemoBaseApplLayer::handlePositionUpdate(cObject* obj) { ChannelMobilityPtrType const mobility = check_and_cast<ChannelMobilityPtrType>(obj); curPosition = mobility->getPositionAt(simTime()); curSpeed = mobility->getCurrentSpeed(); } void DemoBaseApplLayer::handleParkingUpdate(cObject* obj) { isParked = mobility->getParkingState(); } void DemoBaseApplLayer::handleLowerMsg(cMessage* msg) { BaseFrame1609_4* wsm = dynamic_cast<BaseFrame1609_4*>(msg); ASSERT(wsm); if (DemoSafetyMessage* bsm = dynamic_cast<DemoSafetyMessage*>(wsm)) { receivedBSMs++; onBSM(bsm); } else if (DemoServiceAdvertisment* wsa = dynamic_cast<DemoServiceAdvertisment*>(wsm)) { receivedWSAs++; onWSA(wsa); } else { receivedWSMs++; onWSM(wsm); } delete (msg); } void DemoBaseApplLayer::handleSelfMsg(cMessage* msg) { switch (msg->getKind()) { case SEND_BEACON_EVT: { DemoSafetyMessage* bsm = new DemoSafetyMessage(); populateWSM(bsm); sendDown(bsm); scheduleAt(simTime() + beaconInterval, sendBeaconEvt); break; } case SEND_WSA_EVT: { DemoServiceAdvertisment* wsa = new DemoServiceAdvertisment(); populateWSM(wsa); sendDown(wsa); scheduleAt(simTime() + wsaInterval, sendWSAEvt); break; } default: { if (msg) EV_WARN << "APP: Error: Got Self Message of unknown kind! Name: " << msg->getName() << endl; break; } } } void DemoBaseApplLayer::finish() { recordScalar("generatedWSMs", generatedWSMs); recordScalar("receivedWSMs", receivedWSMs); recordScalar("generatedBSMs", generatedBSMs); recordScalar("receivedBSMs", receivedBSMs); recordScalar("generatedWSAs", generatedWSAs); recordScalar("receivedWSAs", receivedWSAs); } DemoBaseApplLayer::~DemoBaseApplLayer() { cancelAndDelete(sendBeaconEvt); cancelAndDelete(sendWSAEvt); findHost()->unsubscribe(BaseMobility::mobilityStateChangedSignal, this); } void DemoBaseApplLayer::startService(Channel channel, int serviceId, std::string serviceDescription) { if (sendWSAEvt->isScheduled()) { throw cRuntimeError("Starting service although another service was already started"); } mac->changeServiceChannel(channel); currentOfferedServiceId = serviceId; currentServiceChannel = channel; currentServiceDescription = serviceDescription; simtime_t wsaTime = computeAsynchronousSendingTime(wsaInterval, ChannelType::control); scheduleAt(wsaTime, sendWSAEvt); } void DemoBaseApplLayer::stopService() { cancelEvent(sendWSAEvt); currentOfferedServiceId = -1; } void DemoBaseApplLayer::sendDown(cMessage* msg) { checkAndTrackPacket(msg); BaseApplLayer::sendDown(msg); } void DemoBaseApplLayer::sendDelayedDown(cMessage* msg, simtime_t delay) { checkAndTrackPacket(msg); BaseApplLayer::sendDelayedDown(msg, delay); } void DemoBaseApplLayer::checkAndTrackPacket(cMessage* msg) { if (dynamic_cast<DemoSafetyMessage*>(msg)) { EV_TRACE << "sending down a BSM" << std::endl; generatedBSMs++; } else if (dynamic_cast<DemoServiceAdvertisment*>(msg)) { EV_TRACE << "sending down a WSA" << std::endl; generatedWSAs++; } else if (dynamic_cast<BaseFrame1609_4*>(msg)) { EV_TRACE << "sending down a wsm" << std::endl; generatedWSMs++; } }
10,732
32.540625
265
cc
null
AICP-main/veins/src/veins/modules/application/ieee80211p/DemoBaseApplLayer.h
// // Copyright (C) 2016 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <map> #include "veins/base/modules/BaseApplLayer.h" #include "veins/modules/utility/Consts80211p.h" #include "veins/modules/messages/BaseFrame1609_4_m.h" #include "veins/modules/messages/DemoServiceAdvertisement_m.h" #include "veins/modules/messages/DemoSafetyMessage_m.h" #include "veins/base/connectionManager/ChannelAccess.h" #include "veins/modules/mac/ieee80211p/DemoBaseApplLayerToMac1609_4Interface.h" #include "veins/modules/mobility/traci/TraCIMobility.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" namespace veins { using veins::AnnotationManager; using veins::AnnotationManagerAccess; using veins::TraCICommandInterface; using veins::TraCIMobility; using veins::TraCIMobilityAccess; /** * @brief * Demo application layer base class. * * @author David Eckhoff * * @ingroup applLayer * * @see DemoBaseApplLayer * @see Mac1609_4 * @see PhyLayer80211p * @see Decider80211p */ class VEINS_API DemoBaseApplLayer : public BaseApplLayer { public: ~DemoBaseApplLayer() override; void initialize(int stage) override; void finish() override; void receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details) override; enum DemoApplMessageKinds { SEND_BEACON_EVT, SEND_WSA_EVT }; protected: /** @brief handle messages from below and calls the onWSM, onBSM, and onWSA functions accordingly */ void handleLowerMsg(cMessage* msg) override; /** @brief handle self messages */ void handleSelfMsg(cMessage* msg) override; /** @brief sets all the necessary fields in the WSM, BSM, or WSA. */ virtual void populateWSM(BaseFrame1609_4* wsm, LAddress::L2Type rcvId = LAddress::L2BROADCAST(), int serial = 0); /** @brief this function is called upon receiving a BaseFrame1609_4 */ virtual void onWSM(BaseFrame1609_4* wsm){}; /** @brief this function is called upon receiving a DemoSafetyMessage, also referred to as a beacon */ virtual void onBSM(DemoSafetyMessage* bsm){}; /** @brief this function is called upon receiving a DemoServiceAdvertisement */ virtual void onWSA(DemoServiceAdvertisment* wsa){}; /** @brief this function is called every time the vehicle receives a position update signal */ virtual void handlePositionUpdate(cObject* obj); /** @brief this function is called every time the vehicle parks or starts moving again */ virtual void handleParkingUpdate(cObject* obj); /** @brief This will start the periodic advertising of the new service on the CCH * * @param channel the channel on which the service is provided * @param serviceId a service ID to be used with the service * @param serviceDescription a literal description of the service */ virtual void startService(Channel channel, int serviceId, std::string serviceDescription); /** @brief stopping the service and advertising for it */ virtual void stopService(); /** @brief compute a point in time that is guaranteed to be in the correct channel interval plus a random offset * * @param interval the interval length of the periodic message * @param chantype the type of channel, either type_CCH or type_SCH */ virtual simtime_t computeAsynchronousSendingTime(simtime_t interval, ChannelType chantype); /** * @brief overloaded for error handling and stats recording purposes * * @param msg the message to be sent. Must be a WSM/BSM/WSA */ virtual void sendDown(cMessage* msg); /** * @brief overloaded for error handling and stats recording purposes * * @param msg the message to be sent. Must be a WSM/BSM/WSA * @param delay the delay for the message */ virtual void sendDelayedDown(cMessage* msg, simtime_t delay); /** * @brief helper function for error handling and stats recording purposes * * @param msg the message to be checked and tracked */ virtual void checkAndTrackPacket(cMessage* msg); protected: /* pointers ill be set when used with TraCIMobility */ TraCIMobility* mobility; TraCICommandInterface* traci; TraCICommandInterface::Vehicle* traciVehicle; AnnotationManager* annotations; DemoBaseApplLayerToMac1609_4Interface* mac; /* support for parking currently only works with TraCI */ bool isParked; /* BSM (beacon) settings */ uint32_t beaconLengthBits; uint32_t beaconUserPriority; simtime_t beaconInterval; bool sendBeacons; /* WSM (data) settings */ uint32_t dataLengthBits; uint32_t dataUserPriority; bool dataOnSch; /* WSA settings */ int currentOfferedServiceId; std::string currentServiceDescription; Channel currentServiceChannel; simtime_t wsaInterval; /* state of the vehicle */ Coord curPosition; Coord curSpeed; LAddress::L2Type myId = 0; int mySCH; /* stats */ uint32_t generatedWSMs; uint32_t generatedWSAs; uint32_t generatedBSMs; uint32_t receivedWSMs; uint32_t receivedWSAs; uint32_t receivedBSMs; /* messages for periodic events such as beacon and WSA transmissions */ cMessage* sendBeaconEvt; cMessage* sendWSAEvt; }; } // namespace veins
6,159
32.11828
117
h
null
AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11p.cc
// // Copyright (C) 2006-2011 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/application/traci/TraCIDemo11p.h" #include "veins/modules/application/traci/TraCIDemo11pMessage_m.h" using namespace veins; Define_Module(veins::TraCIDemo11p); void TraCIDemo11p::initialize(int stage) { DemoBaseApplLayer::initialize(stage); if (stage == 0) { sentMessage = false; lastDroveAt = simTime(); currentSubscribedServiceId = -1; } } void TraCIDemo11p::onBSM(DemoSafetyMessage* bsm){ //if (!sentMessage) { //sentMessage = true; // repeat the received traffic update once in 2 seconds plus some random delay bsm->setSerial(0); scheduleAt(simTime() + 0.1 + uniform(0.01, 0.2), bsm->dup()); //} } void TraCIDemo11p::onWSA(DemoServiceAdvertisment* wsa) { if (currentSubscribedServiceId == -1) { mac->changeServiceChannel(static_cast<Channel>(wsa->getTargetChannel())); currentSubscribedServiceId = wsa->getPsid(); if (currentOfferedServiceId != wsa->getPsid()) { stopService(); startService(static_cast<Channel>(wsa->getTargetChannel()), wsa->getPsid(), "Mirrored Traffic Service"); } } } void TraCIDemo11p::onWSM(BaseFrame1609_4* frame) { TraCIDemo11pMessage* wsm = check_and_cast<TraCIDemo11pMessage*>(frame); findHost()->getDisplayString().setTagArg("i", 1, "green"); if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getDemoData(), 9999); if (!sentMessage) { sentMessage = true; // repeat the received traffic update once in 2 seconds plus some random delay wsm->setSenderAddress(myId); wsm->setSerial(3); scheduleAt(simTime() + 0.01 + uniform(0.01, 0.2), wsm->dup()); } } void TraCIDemo11p::handleSelfMsg(cMessage* msg) { if (TraCIDemo11pMessage* wsm = dynamic_cast<TraCIDemo11pMessage*>(msg)) { // send this message on the service channel until the counter is 3 or higher. // this code only runs when channel switching is enabled sendDown(wsm->dup()); wsm->setSerial(wsm->getSerial() + 1); if (wsm->getSerial() >= 3) { // stop service advertisements stopService(); delete (wsm); } else { scheduleAt(simTime() + 1, wsm); } } else if (DemoSafetyMessage* bsm = dynamic_cast<DemoSafetyMessage*>(msg)){ bsm->setSerial(bsm->getSerial() + 1); // hop limit = 2, distance limit = 100, heading direction diff limit = 30" if (bsm->getSerial() >= 3|| bsm->getSenderPos().distance(curPosition) >= 100 || std::abs(bsm->getAngle()-mobility->getHeading().getRad())>=0.52) { //if (bsm->getSerial() >= 3 || bsm->getSenderPos().distance(curPosition) >= 100){ // stop service advertisements stopService(); delete (bsm); } else { sendDown(bsm->dup()); } } else { DemoBaseApplLayer::handleSelfMsg(msg); } } void TraCIDemo11p::handlePositionUpdate(cObject* obj) { DemoBaseApplLayer::handlePositionUpdate(obj); // stopped for for at least 10s? if (mobility->getSpeed() < 1) { if (simTime() - lastDroveAt >= 10 && sentMessage == false) { findHost()->getDisplayString().setTagArg("i", 1, "red"); sentMessage = true; TraCIDemo11pMessage* wsm = new TraCIDemo11pMessage(); populateWSM(wsm); wsm->setDemoData(mobility->getRoadId().c_str()); // host is standing still due to crash if (dataOnSch) { startService(Channel::sch2, 42, "Traffic Information Service"); // started service and server advertising, schedule message to self to send later scheduleAt(computeAsynchronousSendingTime(1, ChannelType::service), wsm); } else { // send right away on CCH, because channel switching is disabled sendDown(wsm); } } } else { lastDroveAt = simTime(); } }
4,994
33.93007
154
cc
null
AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11p.h
// // Copyright (C) 2006-2011 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/modules/application/ieee80211p/DemoBaseApplLayer.h" namespace veins { /** * @brief * A tutorial demo for TraCI. When the car is stopped for longer than 10 seconds * it will send a message out to other cars containing the blocked road id. * Receiving cars will then trigger a reroute via TraCI. * When channel switching between SCH and CCH is enabled on the MAC, the message is * instead send out on a service channel following a Service Advertisement * on the CCH. * * @author Christoph Sommer : initial DemoApp * @author David Eckhoff : rewriting, moving functionality to DemoBaseApplLayer, adding WSA * */ class VEINS_API TraCIDemo11p : public DemoBaseApplLayer { public: void initialize(int stage) override; protected: simtime_t lastDroveAt; bool sentMessage; int currentSubscribedServiceId; protected: void onBSM(DemoSafetyMessage* bsm) override; void onWSM(BaseFrame1609_4* wsm) override; void onWSA(DemoServiceAdvertisment* wsa) override; void handleSelfMsg(cMessage* msg) override; void handlePositionUpdate(cObject* obj) override; }; } // namespace veins
2,061
32.258065
91
h
null
AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11pMessage_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/application/traci/TraCIDemo11pMessage.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "TraCIDemo11pMessage_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(TraCIDemo11pMessage) TraCIDemo11pMessage::TraCIDemo11pMessage(const char *name, short kind) : ::veins::BaseFrame1609_4(name,kind) { this->senderAddress = -1; this->serial = 0; } TraCIDemo11pMessage::TraCIDemo11pMessage(const TraCIDemo11pMessage& other) : ::veins::BaseFrame1609_4(other) { copy(other); } TraCIDemo11pMessage::~TraCIDemo11pMessage() { } TraCIDemo11pMessage& TraCIDemo11pMessage::operator=(const TraCIDemo11pMessage& other) { if (this==&other) return *this; ::veins::BaseFrame1609_4::operator=(other); copy(other); return *this; } void TraCIDemo11pMessage::copy(const TraCIDemo11pMessage& other) { this->demoData = other.demoData; this->senderAddress = other.senderAddress; this->serial = other.serial; } void TraCIDemo11pMessage::parsimPack(omnetpp::cCommBuffer *b) const { ::veins::BaseFrame1609_4::parsimPack(b); doParsimPacking(b,this->demoData); doParsimPacking(b,this->senderAddress); doParsimPacking(b,this->serial); } void TraCIDemo11pMessage::parsimUnpack(omnetpp::cCommBuffer *b) { ::veins::BaseFrame1609_4::parsimUnpack(b); doParsimUnpacking(b,this->demoData); doParsimUnpacking(b,this->senderAddress); doParsimUnpacking(b,this->serial); } const char * TraCIDemo11pMessage::getDemoData() const { return this->demoData.c_str(); } void TraCIDemo11pMessage::setDemoData(const char * demoData) { this->demoData = demoData; } LAddress::L2Type& TraCIDemo11pMessage::getSenderAddress() { return this->senderAddress; } void TraCIDemo11pMessage::setSenderAddress(const LAddress::L2Type& senderAddress) { this->senderAddress = senderAddress; } int TraCIDemo11pMessage::getSerial() const { return this->serial; } void TraCIDemo11pMessage::setSerial(int serial) { this->serial = serial; } class TraCIDemo11pMessageDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: TraCIDemo11pMessageDescriptor(); virtual ~TraCIDemo11pMessageDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(TraCIDemo11pMessageDescriptor) TraCIDemo11pMessageDescriptor::TraCIDemo11pMessageDescriptor() : omnetpp::cClassDescriptor("veins::TraCIDemo11pMessage", "veins::BaseFrame1609_4") { propertynames = nullptr; } TraCIDemo11pMessageDescriptor::~TraCIDemo11pMessageDescriptor() { delete[] propertynames; } bool TraCIDemo11pMessageDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<TraCIDemo11pMessage *>(obj)!=nullptr; } const char **TraCIDemo11pMessageDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *TraCIDemo11pMessageDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int TraCIDemo11pMessageDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 3+basedesc->getFieldCount() : 3; } unsigned int TraCIDemo11pMessageDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISCOMPOUND, FD_ISEDITABLE, }; return (field>=0 && field<3) ? fieldTypeFlags[field] : 0; } const char *TraCIDemo11pMessageDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "demoData", "senderAddress", "serial", }; return (field>=0 && field<3) ? fieldNames[field] : nullptr; } int TraCIDemo11pMessageDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='d' && strcmp(fieldName, "demoData")==0) return base+0; if (fieldName[0]=='s' && strcmp(fieldName, "senderAddress")==0) return base+1; if (fieldName[0]=='s' && strcmp(fieldName, "serial")==0) return base+2; return basedesc ? basedesc->findField(fieldName) : -1; } const char *TraCIDemo11pMessageDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "LAddress::L2Type", "int", }; return (field>=0 && field<3) ? fieldTypeStrings[field] : nullptr; } const char **TraCIDemo11pMessageDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *TraCIDemo11pMessageDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int TraCIDemo11pMessageDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp; switch (field) { default: return 0; } } const char *TraCIDemo11pMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp; switch (field) { default: return nullptr; } } std::string TraCIDemo11pMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getDemoData()); case 1: {std::stringstream out; out << pp->getSenderAddress(); return out.str();} case 2: return long2string(pp->getSerial()); default: return ""; } } bool TraCIDemo11pMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp; switch (field) { case 0: pp->setDemoData((value)); return true; case 2: pp->setSerial(string2long(value)); return true; default: return false; } } const char *TraCIDemo11pMessageDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { case 1: return omnetpp::opp_typename(typeid(LAddress::L2Type)); default: return nullptr; }; } void *TraCIDemo11pMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp; switch (field) { case 1: return (void *)(&pp->getSenderAddress()); break; default: return nullptr; } } } // namespace veins
16,188
31.184891
146
cc
null
AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11pMessage_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/application/traci/TraCIDemo11pMessage.msg. // #ifndef __VEINS_TRACIDEMO11PMESSAGE_M_H #define __VEINS_TRACIDEMO11PMESSAGE_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif // cplusplus {{ #include "veins/base/utils/Coord.h" #include "veins/modules/messages/BaseFrame1609_4_m.h" #include "veins/base/utils/SimpleAddress.h" // }} namespace veins { /** * Class generated from <tt>veins/modules/application/traci/TraCIDemo11pMessage.msg:35</tt> by nedtool. * <pre> * packet TraCIDemo11pMessage extends BaseFrame1609_4 * { * string demoData; * LAddress::L2Type senderAddress = -1; * int serial = 0; * } * </pre> */ class VEINS_API TraCIDemo11pMessage : public ::veins::BaseFrame1609_4 { protected: ::omnetpp::opp_string demoData; LAddress::L2Type senderAddress; int serial; private: void copy(const TraCIDemo11pMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const TraCIDemo11pMessage&); public: TraCIDemo11pMessage(const char *name=nullptr, short kind=0); TraCIDemo11pMessage(const TraCIDemo11pMessage& other); virtual ~TraCIDemo11pMessage(); TraCIDemo11pMessage& operator=(const TraCIDemo11pMessage& other); virtual TraCIDemo11pMessage *dup() const override {return new TraCIDemo11pMessage(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual const char * getDemoData() const; virtual void setDemoData(const char * demoData); virtual LAddress::L2Type& getSenderAddress(); virtual const LAddress::L2Type& getSenderAddress() const {return const_cast<TraCIDemo11pMessage*>(this)->getSenderAddress();} virtual void setSenderAddress(const LAddress::L2Type& senderAddress); virtual int getSerial() const; virtual void setSerial(int serial); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const TraCIDemo11pMessage& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, TraCIDemo11pMessage& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_TRACIDEMO11PMESSAGE_M_H
2,809
30.222222
129
h
null
AICP-main/veins/src/veins/modules/application/traci/TraCIDemoRSU11p.cc
// // Copyright (C) 2016 David Eckhoff <david.eckhoff@fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/application/traci/TraCIDemoRSU11p.h" #include "veins/modules/application/traci/TraCIDemo11pMessage_m.h" using namespace veins; Define_Module(veins::TraCIDemoRSU11p); void TraCIDemoRSU11p::onWSA(DemoServiceAdvertisment* wsa) { // if this RSU receives a WSA for service 42, it will tune to the chan if (wsa->getPsid() == 42) { mac->changeServiceChannel(static_cast<Channel>(wsa->getTargetChannel())); } } void TraCIDemoRSU11p::onWSM(BaseFrame1609_4* frame) { TraCIDemo11pMessage* wsm = check_and_cast<TraCIDemo11pMessage*>(frame); // this rsu repeats the received traffic update in 2 seconds plus some random delay sendDelayedDown(wsm->dup(), 2 + uniform(0.01, 0.2)); }
1,628
34.413043
87
cc
null
AICP-main/veins/src/veins/modules/application/traci/TraCIDemoRSU11p.h
// // Copyright (C) 2016 David Eckhoff <david.eckhoff@fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/modules/application/ieee80211p/DemoBaseApplLayer.h" namespace veins { /** * Small RSU Demo using 11p */ class VEINS_API TraCIDemoRSU11p : public DemoBaseApplLayer { protected: void onWSM(BaseFrame1609_4* wsm) override; void onWSA(DemoServiceAdvertisment* wsa) override; }; } // namespace veins
1,235
30.692308
76
h
null
AICP-main/veins/src/veins/modules/mac/ieee80211p/DemoBaseApplLayerToMac1609_4Interface.h
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/base/utils/NetwToMacControlInfo.h" #include "veins/modules/utility/Consts80211p.h" namespace veins { /** * @brief * Interface between DemoBaseApplLayer Layer and Mac1609_4 * * @author David Eckhoff * * @ingroup macLayer */ class VEINS_API DemoBaseApplLayerToMac1609_4Interface { public: virtual bool isChannelSwitchingActive() = 0; virtual simtime_t getSwitchingInterval() = 0; virtual bool isCurrentChannelCCH() = 0; virtual void changeServiceChannel(Channel channelNumber) = 0; virtual ~DemoBaseApplLayerToMac1609_4Interface(){}; /** * @brief Returns the MAC address of this MAC module. */ virtual const LAddress::L2Type& getMACAddress() = 0; }; } // namespace veins
1,647
27.912281
76
h
null
AICP-main/veins/src/veins/modules/mac/ieee80211p/Mac1609_4.cc
// // Copyright (C) 2016 David Eckhoff <david.eckhoff@fau.de> // Copyright (C) 2018 Fabian Bronner <fabian.bronner@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/mac/ieee80211p/Mac1609_4.h" #include <iterator> #include "veins/modules/phy/DeciderResult80211.h" #include "veins/base/phyLayer/PhyToMacControlInfo.h" #include "veins/modules/messages/PhyControlMessage_m.h" #include "veins/modules/messages/AckTimeOutMessage_m.h" using namespace veins; using std::unique_ptr; Define_Module(veins::Mac1609_4); const simsignal_t Mac1609_4::sigChannelBusy = registerSignal("org_car2x_veins_modules_mac_sigChannelBusy"); const simsignal_t Mac1609_4::sigCollision = registerSignal("org_car2x_veins_modules_mac_sigCollision"); void Mac1609_4::initialize(int stage) { BaseMacLayer::initialize(stage); if (stage == 0) { phy11p = FindModule<Mac80211pToPhy11pInterface*>::findSubModule(getParentModule()); ASSERT(phy11p); // this is required to circumvent double precision issues with constants from CONST80211p.h ASSERT(simTime().getScaleExp() == -12); txPower = par("txPower").doubleValue(); setParametersForBitrate(par("bitrate")); // unicast parameters dot11RTSThreshold = par("dot11RTSThreshold"); dot11ShortRetryLimit = par("dot11ShortRetryLimit"); dot11LongRetryLimit = par("dot11LongRetryLimit"); ackLength = par("ackLength"); useAcks = par("useAcks").boolValue(); ackErrorRate = par("ackErrorRate").doubleValue(); rxStartIndication = false; ignoreChannelState = false; waitUntilAckRXorTimeout = false; stopIgnoreChannelStateMsg = new cMessage("ChannelStateMsg"); myId = getParentModule()->getParentModule()->getFullPath(); // create two edca systems myEDCA[ChannelType::control] = make_unique<EDCA>(this, ChannelType::control, par("queueSize")); myEDCA[ChannelType::control]->myId = myId; myEDCA[ChannelType::control]->myId.append(" CCH"); myEDCA[ChannelType::control]->createQueue(2, (((CWMIN_11P + 1) / 4) - 1), (((CWMIN_11P + 1) / 2) - 1), AC_VO); myEDCA[ChannelType::control]->createQueue(3, (((CWMIN_11P + 1) / 2) - 1), CWMIN_11P, AC_VI); myEDCA[ChannelType::control]->createQueue(6, CWMIN_11P, CWMAX_11P, AC_BE); myEDCA[ChannelType::control]->createQueue(9, CWMIN_11P, CWMAX_11P, AC_BK); myEDCA[ChannelType::service] = make_unique<EDCA>(this, ChannelType::service, par("queueSize")); myEDCA[ChannelType::service]->myId = myId; myEDCA[ChannelType::service]->myId.append(" SCH"); myEDCA[ChannelType::service]->createQueue(2, (((CWMIN_11P + 1) / 4) - 1), (((CWMIN_11P + 1) / 2) - 1), AC_VO); myEDCA[ChannelType::service]->createQueue(3, (((CWMIN_11P + 1) / 2) - 1), CWMIN_11P, AC_VI); myEDCA[ChannelType::service]->createQueue(6, CWMIN_11P, CWMAX_11P, AC_BE); myEDCA[ChannelType::service]->createQueue(9, CWMIN_11P, CWMAX_11P, AC_BK); useSCH = par("useServiceChannel").boolValue(); if (useSCH) { if (useAcks) throw cRuntimeError("Unicast model does not support channel switching"); // set the initial service channel int serviceChannel = par("serviceChannel"); switch (serviceChannel) { case 1: mySCH = Channel::sch1; break; case 2: mySCH = Channel::sch2; break; case 3: mySCH = Channel::sch3; break; case 4: mySCH = Channel::sch4; break; default: throw cRuntimeError("Service Channel must be between 1 and 4"); break; } } headerLength = par("headerLength"); nextMacEvent = new cMessage("next Mac Event"); if (useSCH) { uint64_t currenTime = simTime().raw(); uint64_t switchingTime = SWITCHING_INTERVAL_11P.raw(); double timeToNextSwitch = (double) (switchingTime - (currenTime % switchingTime)) / simTime().getScale(); if ((currenTime / switchingTime) % 2 == 0) { setActiveChannel(ChannelType::control); } else { setActiveChannel(ChannelType::service); } // channel switching active nextChannelSwitch = new cMessage("Channel Switch"); // add a little bit of offset between all vehicles, but no more than syncOffset simtime_t offset = dblrand() * par("syncOffset").doubleValue(); scheduleAt(simTime() + offset + timeToNextSwitch, nextChannelSwitch); } else { // no channel switching nextChannelSwitch = nullptr; setActiveChannel(ChannelType::control); } // stats statsReceivedPackets = 0; statsReceivedBroadcasts = 0; statsSentPackets = 0; statsSentAcks = 0; statsTXRXLostPackets = 0; statsSNIRLostPackets = 0; statsDroppedPackets = 0; statsNumTooLittleTime = 0; statsNumInternalContention = 0; statsNumBackoff = 0; statsSlotsBackoff = 0; statsTotalBusyTime = 0; idleChannel = true; lastBusy = simTime(); channelIdle(true); } } void Mac1609_4::handleSelfMsg(cMessage* msg) { if (msg == stopIgnoreChannelStateMsg) { ignoreChannelState = false; return; } if (AckTimeOutMessage* ackTimeOutMsg = dynamic_cast<AckTimeOutMessage*>(msg)) { handleAckTimeOut(ackTimeOutMsg); return; } if (msg == nextChannelSwitch) { ASSERT(useSCH); scheduleAt(simTime() + SWITCHING_INTERVAL_11P, nextChannelSwitch); switch (activeChannel) { case ChannelType::control: EV_TRACE << "CCH --> SCH" << std::endl; channelBusySelf(false); setActiveChannel(ChannelType::service); channelIdle(true); phy11p->changeListeningChannel(mySCH); break; case ChannelType::service: EV_TRACE << "SCH --> CCH" << std::endl; channelBusySelf(false); setActiveChannel(ChannelType::control); channelIdle(true); phy11p->changeListeningChannel(Channel::cch); break; } // schedule next channel switch in 50ms } else if (msg == nextMacEvent) { // we actually came to the point where we can send a packet channelBusySelf(true); BaseFrame1609_4* pktToSend = myEDCA[activeChannel]->initiateTransmit(lastIdle); ASSERT(pktToSend); lastAC = mapUserPriority(pktToSend->getUserPriority()); lastWSM = pktToSend; EV_TRACE << "MacEvent received. Trying to send packet with priority" << lastAC << std::endl; // send the packet Mac80211Pkt* mac = new Mac80211Pkt(pktToSend->getName(), pktToSend->getKind()); if (pktToSend->getRecipientAddress() != LAddress::L2BROADCAST()) { mac->setDestAddr(pktToSend->getRecipientAddress()); } else { mac->setDestAddr(LAddress::L2BROADCAST()); } mac->setSrcAddr(myMacAddr); mac->encapsulate(pktToSend->dup()); MCS usedMcs = mcs; double txPower_mW; PhyControlMessage* controlInfo = dynamic_cast<PhyControlMessage*>(pktToSend->getControlInfo()); if (controlInfo) { // if MCS is not specified, just use the default one MCS explicitMcs = static_cast<MCS>(controlInfo->getMcs()); if (explicitMcs != MCS::undefined) { usedMcs = explicitMcs; } // apply the same principle to tx power txPower_mW = controlInfo->getTxPower_mW(); if (txPower_mW < 0) { txPower_mW = txPower; } } else { txPower_mW = txPower; } simtime_t sendingDuration = RADIODELAY_11P + phy11p->getFrameDuration(mac->getBitLength(), usedMcs); EV_TRACE << "Sending duration will be" << sendingDuration << std::endl; if ((!useSCH) || (timeLeftInSlot() > sendingDuration)) { if (useSCH) EV_TRACE << " Time in this slot left: " << timeLeftInSlot() << std::endl; Channel channelNr = (activeChannel == ChannelType::control) ? Channel::cch : mySCH; double freq = IEEE80211ChannelFrequencies.at(channelNr); EV_TRACE << "Sending a Packet. Frequency " << freq << " Priority" << lastAC << std::endl; sendFrame(mac, RADIODELAY_11P, channelNr, usedMcs, txPower_mW); // schedule ack timeout for unicast packets if (pktToSend->getRecipientAddress() != LAddress::L2BROADCAST() && useAcks) { waitUntilAckRXorTimeout = true; // PHY-RXSTART.indication should be received within ackWaitTime // sifs + slot + rx_delay: see 802.11-2012 9.3.2.8 (32us + 13us + 49us = 94us) simtime_t ackWaitTime(94, SIMTIME_US); // update id in the retransmit timer myEDCA[activeChannel]->myQueues[lastAC].ackTimeOut->setWsmId(pktToSend->getTreeId()); simtime_t timeOut = sendingDuration + ackWaitTime; scheduleAt(simTime() + timeOut, myEDCA[activeChannel]->myQueues[lastAC].ackTimeOut); } } else { // not enough time left now EV_TRACE << "Too little Time left. This packet cannot be send in this slot." << std::endl; statsNumTooLittleTime++; // revoke TXOP myEDCA[activeChannel]->revokeTxOPs(); delete mac; channelIdle(); // do nothing. contention will automatically start after channel switch } } } void Mac1609_4::handleUpperControl(cMessage* msg) { ASSERT(false); } void Mac1609_4::handleUpperMsg(cMessage* msg) { BaseFrame1609_4* thisMsg = check_and_cast<BaseFrame1609_4*>(msg); t_access_category ac = mapUserPriority(thisMsg->getUserPriority()); EV_TRACE << "Received a message from upper layer for channel " << thisMsg->getChannelNumber() << " Access Category (Priority): " << ac << std::endl; ChannelType chan; if (static_cast<Channel>(thisMsg->getChannelNumber()) == Channel::cch) { chan = ChannelType::control; } else { ASSERT(useSCH); thisMsg->setChannelNumber(static_cast<int>(mySCH)); chan = ChannelType::service; } int num = myEDCA[chan]->queuePacket(ac, thisMsg); // packet was dropped in Mac if (num == -1) { statsDroppedPackets++; return; } // if this packet is not at the front of a new queue we dont have to reevaluate times EV_TRACE << "sorted packet into queue of EDCA " << static_cast<int>(chan) << " this packet is now at position: " << num << std::endl; if (chan == activeChannel) { EV_TRACE << "this packet is for the currently active channel" << std::endl; } else { EV_TRACE << "this packet is NOT for the currently active channel" << std::endl; } if (num == 1 && idleChannel == true && chan == activeChannel) { simtime_t nextEvent = myEDCA[chan]->startContent(lastIdle, guardActive()); if (nextEvent != -1) { if ((!useSCH) || (nextEvent <= nextChannelSwitch->getArrivalTime())) { if (nextMacEvent->isScheduled()) { cancelEvent(nextMacEvent); } scheduleAt(nextEvent, nextMacEvent); EV_TRACE << "Updated nextMacEvent:" << nextMacEvent->getArrivalTime().raw() << std::endl; } else { EV_TRACE << "Too little time in this interval. Will not schedule nextMacEvent" << std::endl; // it is possible that this queue has an txop. we have to revoke it myEDCA[activeChannel]->revokeTxOPs(); statsNumTooLittleTime++; } } else { cancelEvent(nextMacEvent); } } if (num == 1 && idleChannel == false && myEDCA[chan]->myQueues[ac].currentBackoff == 0 && chan == activeChannel) { myEDCA[chan]->backoff(ac); } } void Mac1609_4::handleLowerControl(cMessage* msg) { if (msg->getKind() == MacToPhyInterface::PHY_RX_START) { rxStartIndication = true; } else if (msg->getKind() == MacToPhyInterface::PHY_RX_END_WITH_SUCCESS) { // PHY_RX_END_WITH_SUCCESS will get packet soon! Nothing to do here } else if (msg->getKind() == MacToPhyInterface::PHY_RX_END_WITH_FAILURE) { // RX failed at phy. Time to retransmit phy11p->notifyMacAboutRxStart(false); rxStartIndication = false; handleRetransmit(lastAC); } else if (msg->getKind() == MacToPhyInterface::TX_OVER) { EV_TRACE << "Successfully transmitted a packet on " << lastAC << std::endl; phy->setRadioState(Radio::RX); if (!dynamic_cast<Mac80211Ack*>(lastMac.get())) { // message was sent // update EDCA queue. go into post-transmit backoff and set cwCur to cwMin myEDCA[activeChannel]->postTransmit(lastAC, lastWSM, useAcks); } // channel just turned idle. // don't set the chan to idle. the PHY layer decides, not us. if (guardActive()) { throw cRuntimeError("We shouldnt have sent a packet in guard!"); } } else if (msg->getKind() == Mac80211pToPhy11pInterface::CHANNEL_BUSY) { channelBusy(); } else if (msg->getKind() == Mac80211pToPhy11pInterface::CHANNEL_IDLE) { // Decider80211p::processSignalEnd() sends up the received packet to MAC followed by control message CHANNEL_IDLE in the same timestamp. // If we received a unicast frame (first event scheduled by Decider), MAC immediately schedules an ACK message and wants to switch the radio to TX mode. // So, the notification for channel idle from phy is undesirable and we skip it here. // After ACK TX is over, PHY will inform the channel status again. if (ignoreChannelState) { // Skipping channelidle because we are about to send an ack regardless of the channel state } else { channelIdle(); } } else if (msg->getKind() == Decider80211p::BITERROR || msg->getKind() == Decider80211p::COLLISION) { statsSNIRLostPackets++; EV_TRACE << "A packet was not received due to biterrors" << std::endl; } else if (msg->getKind() == Decider80211p::RECWHILESEND) { statsTXRXLostPackets++; EV_TRACE << "A packet was not received because we were sending while receiving" << std::endl; } else if (msg->getKind() == MacToPhyInterface::RADIO_SWITCHING_OVER) { EV_TRACE << "Phylayer said radio switching is done" << std::endl; } else if (msg->getKind() == BaseDecider::PACKET_DROPPED) { phy->setRadioState(Radio::RX); EV_TRACE << "Phylayer said packet was dropped" << std::endl; } else { EV_WARN << "Invalid control message type (type=NOTHING) : name=" << msg->getName() << " modulesrc=" << msg->getSenderModule()->getFullPath() << "." << std::endl; ASSERT(false); } if (msg->getKind() == Decider80211p::COLLISION) { emit(sigCollision, true); } delete msg; } void Mac1609_4::setActiveChannel(ChannelType state) { activeChannel = state; ASSERT(state == ChannelType::control || (useSCH && state == ChannelType::service)); } void Mac1609_4::finish() { for (auto&& p : myEDCA) { statsNumInternalContention += p.second->statsNumInternalContention; statsNumBackoff += p.second->statsNumBackoff; statsSlotsBackoff += p.second->statsSlotsBackoff; } recordScalar("ReceivedUnicastPackets", statsReceivedPackets); recordScalar("ReceivedBroadcasts", statsReceivedBroadcasts); recordScalar("SentPackets", statsSentPackets); recordScalar("SentAcknowledgements", statsSentAcks); recordScalar("SNIRLostPackets", statsSNIRLostPackets); recordScalar("RXTXLostPackets", statsTXRXLostPackets); recordScalar("TotalLostPackets", statsSNIRLostPackets + statsTXRXLostPackets); recordScalar("DroppedPacketsInMac", statsDroppedPackets); recordScalar("TooLittleTime", statsNumTooLittleTime); recordScalar("TimesIntoBackoff", statsNumBackoff); recordScalar("SlotsBackoff", statsSlotsBackoff); recordScalar("NumInternalContention", statsNumInternalContention); recordScalar("totalBusyTime", statsTotalBusyTime.dbl()); } Mac1609_4::~Mac1609_4() { if (nextMacEvent) { cancelAndDelete(nextMacEvent); nextMacEvent = nullptr; } if (nextChannelSwitch) { cancelAndDelete(nextChannelSwitch); nextChannelSwitch = nullptr; } if (stopIgnoreChannelStateMsg) { cancelAndDelete(stopIgnoreChannelStateMsg); stopIgnoreChannelStateMsg = nullptr; } }; void Mac1609_4::sendFrame(Mac80211Pkt* frame, simtime_t delay, Channel channelNr, MCS mcs, double txPower_mW) { phy->setRadioState(Radio::TX); // give time for the radio to be in Tx state before transmitting delay = std::max(delay, RADIODELAY_11P); // wait at least for the radio to switch attachControlInfo(frame, channelNr, mcs, txPower_mW); check_and_cast<MacToPhyControlInfo11p*>(frame->getControlInfo()); lastMac.reset(frame->dup()); sendDelayed(frame, delay, lowerLayerOut); if (dynamic_cast<Mac80211Ack*>(frame)) { statsSentAcks += 1; } else { statsSentPackets += 1; } } void Mac1609_4::attachControlInfo(Mac80211Pkt* mac, Channel channelNr, MCS mcs, double txPower_mW) { auto cinfo = new MacToPhyControlInfo11p(channelNr, mcs, txPower_mW); mac->setControlInfo(cinfo); } /* checks if guard is active */ bool Mac1609_4::guardActive() const { if (!useSCH) return false; if (simTime().dbl() - nextChannelSwitch->getSendingTime() <= GUARD_INTERVAL_11P) return true; return false; } /* returns the time until the guard is over */ simtime_t Mac1609_4::timeLeftTillGuardOver() const { ASSERT(useSCH); simtime_t sTime = simTime(); if (sTime - nextChannelSwitch->getSendingTime() <= GUARD_INTERVAL_11P) { return GUARD_INTERVAL_11P - (sTime - nextChannelSwitch->getSendingTime()); } else return 0; } /* returns the time left in this channel window */ simtime_t Mac1609_4::timeLeftInSlot() const { ASSERT(useSCH); return nextChannelSwitch->getArrivalTime() - simTime(); } /* Will change the Service Channel on which the mac layer is listening and sending */ void Mac1609_4::changeServiceChannel(Channel cN) { ASSERT(useSCH); mySCH = static_cast<Channel>(cN); if (mySCH != Channel::sch1 && mySCH != Channel::sch2 && mySCH != Channel::sch3 && mySCH != Channel::sch4) { throw cRuntimeError("This Service Channel doesnt exit: %d", cN); } if (activeChannel == ChannelType::service) { // change to new chan immediately if we are in a SCH slot, // otherwise it will switch to the new SCH upon next channel switch phy11p->changeListeningChannel(mySCH); } } void Mac1609_4::setTxPower(double txPower_mW) { txPower = txPower_mW; } void Mac1609_4::setMCS(MCS mcs) { ASSERT2(mcs != MCS::undefined, "invalid MCS selected"); this->mcs = mcs; } void Mac1609_4::setCCAThreshold(double ccaThreshold_dBm) { phy11p->setCCAThreshold(ccaThreshold_dBm); } void Mac1609_4::handleBroadcast(Mac80211Pkt* macPkt, DeciderResult80211* res) { statsReceivedBroadcasts++; unique_ptr<BaseFrame1609_4> wsm(check_and_cast<BaseFrame1609_4*>(macPkt->decapsulate())); wsm->setControlInfo(new PhyToMacControlInfo(res)); sendUp(wsm.release()); } void Mac1609_4::handleLowerMsg(cMessage* msg) { Mac80211Pkt* macPkt = check_and_cast<Mac80211Pkt*>(msg); // pass information about received frame to the upper layers DeciderResult80211* macRes = check_and_cast<DeciderResult80211*>(PhyToMacControlInfo::getDeciderResult(msg)); DeciderResult80211* res = new DeciderResult80211(*macRes); long dest = macPkt->getDestAddr(); EV_TRACE << "Received frame name= " << macPkt->getName() << ", myState= src=" << macPkt->getSrcAddr() << " dst=" << macPkt->getDestAddr() << " myAddr=" << myMacAddr << std::endl; if (dest == myMacAddr) { if (auto* ack = dynamic_cast<Mac80211Ack*>(macPkt)) { ASSERT(useAcks); handleAck(ack); delete res; } else { unique_ptr<BaseFrame1609_4> wsm(check_and_cast<BaseFrame1609_4*>(macPkt->decapsulate())); wsm->setControlInfo(new PhyToMacControlInfo(res)); handleUnicast(macPkt->getSrcAddr(), std::move(wsm)); } } else if (dest == LAddress::L2BROADCAST()) { handleBroadcast(macPkt, res); } else { EV_TRACE << "Packet not for me" << std::endl; delete res; } delete macPkt; if (rxStartIndication) { // We have handled/processed the incoming packet // Since we reached here, we were expecting an ack but we didnt get it, so retransmission should take place phy11p->notifyMacAboutRxStart(false); rxStartIndication = false; handleRetransmit(lastAC); } } int Mac1609_4::EDCA::queuePacket(t_access_category ac, BaseFrame1609_4* msg) { if (maxQueueSize && myQueues[ac].queue.size() >= maxQueueSize) { delete msg; return -1; } myQueues[ac].queue.push(msg); return myQueues[ac].queue.size(); } void Mac1609_4::EDCA::createQueue(int aifsn, int cwMin, int cwMax, t_access_category ac) { if (myQueues.find(ac) != myQueues.end()) { throw cRuntimeError("You can only add one queue per Access Category per EDCA subsystem"); } EDCAQueue newQueue(aifsn, cwMin, cwMax, ac); myQueues[ac] = newQueue; } Mac1609_4::t_access_category Mac1609_4::mapUserPriority(int prio) { // Map user priority to access category, based on IEEE Std 802.11-2012, Table 9-1 switch (prio) { case 1: return AC_BK; case 2: return AC_BK; case 0: return AC_BE; case 3: return AC_BE; case 4: return AC_VI; case 5: return AC_VI; case 6: return AC_VO; case 7: return AC_VO; default: throw cRuntimeError("MacLayer received a packet with unknown priority"); break; } return AC_VO; } BaseFrame1609_4* Mac1609_4::EDCA::initiateTransmit(simtime_t lastIdle) { // iterate through the queues to return the packet we want to send BaseFrame1609_4* pktToSend = nullptr; simtime_t idleTime = simTime() - lastIdle; EV_TRACE << "Initiating transmit at " << simTime() << ". I've been idle since " << idleTime << std::endl; // As t_access_category is sorted by priority, we iterate back to front. // This realizes the behavior documented in IEEE Std 802.11-2012 Section 9.2.4.2; that is, "data frames from the higher priority AC" win an internal collision. // The phrase "EDCAF of higher UP" of IEEE Std 802.11-2012 Section 9.19.2.3 is assumed to be meaningless. for (auto iter = myQueues.rbegin(); iter != myQueues.rend(); iter++) { if (iter->second.queue.size() != 0 && !iter->second.waitForAck) { if (idleTime >= iter->second.aifsn * SLOTLENGTH_11P + SIFS_11P && iter->second.txOP == true) { EV_TRACE << "Queue " << iter->first << " is ready to send!" << std::endl; iter->second.txOP = false; // this queue is ready to send if (pktToSend == nullptr) { pktToSend = iter->second.queue.front(); } else { // there was already another packet ready. we have to go increase cw and go into backoff. It's called internal contention and its wonderful statsNumInternalContention++; iter->second.cwCur = std::min(iter->second.cwMax, (iter->second.cwCur + 1) * 2 - 1); iter->second.currentBackoff = owner->intuniform(0, iter->second.cwCur); EV_TRACE << "Internal contention for queue " << iter->first << " : " << iter->second.currentBackoff << ". Increase cwCur to " << iter->second.cwCur << std::endl; } } } } if (pktToSend == nullptr) { throw cRuntimeError("No packet was ready"); } return pktToSend; } simtime_t Mac1609_4::EDCA::startContent(simtime_t idleSince, bool guardActive) { EV_TRACE << "Restarting contention." << std::endl; simtime_t nextEvent = -1; simtime_t idleTime = SimTime().setRaw(std::max((int64_t) 0, (simTime() - idleSince).raw())); ; lastStart = idleSince; EV_TRACE << "Channel is already idle for:" << idleTime << " since " << idleSince << std::endl; // this returns the nearest possible event in this EDCA subsystem after a busy channel for (auto&& p : myQueues) { auto& accessCategory = p.first; auto& edcaQueue = p.second; if (edcaQueue.queue.size() != 0 && !edcaQueue.waitForAck) { /* 1609_4 says that when attempting to send (backoff == 0) when guard is active, a random backoff is invoked */ if (guardActive == true && edcaQueue.currentBackoff == 0) { // cw is not increased edcaQueue.currentBackoff = owner->intuniform(0, edcaQueue.cwCur); statsNumBackoff++; } simtime_t DIFS = edcaQueue.aifsn * SLOTLENGTH_11P + SIFS_11P; // the next possible time to send can be in the past if the channel was idle for a long time, meaning we COULD have sent earlier if we had a packet simtime_t possibleNextEvent = DIFS + edcaQueue.currentBackoff * SLOTLENGTH_11P; EV_TRACE << "Waiting Time for Queue " << accessCategory << ":" << possibleNextEvent << "=" << edcaQueue.aifsn << " * " << SLOTLENGTH_11P << " + " << SIFS_11P << "+" << edcaQueue.currentBackoff << "*" << SLOTLENGTH_11P << "; Idle time: " << idleTime << std::endl; if (idleTime > possibleNextEvent) { EV_TRACE << "Could have already send if we had it earlier" << std::endl; // we could have already sent. round up to next boundary simtime_t base = idleSince + DIFS; possibleNextEvent = simTime() - simtime_t().setRaw((simTime() - base).raw() % SLOTLENGTH_11P.raw()) + SLOTLENGTH_11P; } else { // we are gonna send in the future EV_TRACE << "Sending in the future" << std::endl; possibleNextEvent = idleSince + possibleNextEvent; } nextEvent == -1 ? nextEvent = possibleNextEvent : nextEvent = std::min(nextEvent, possibleNextEvent); } } return nextEvent; } void Mac1609_4::EDCA::stopContent(bool allowBackoff, bool generateTxOp) { // update all Queues EV_TRACE << "Stopping Contention at " << simTime().raw() << std::endl; simtime_t passedTime = simTime() - lastStart; EV_TRACE << "Channel was idle for " << passedTime << std::endl; lastStart = -1; // indicate that there was no last start for (auto&& p : myQueues) { auto& accessCategory = p.first; auto& edcaQueue = p.second; if ((edcaQueue.currentBackoff != 0 || edcaQueue.queue.size() != 0) && !edcaQueue.waitForAck) { // check how many slots we already waited until the chan became busy int64_t oldBackoff = edcaQueue.currentBackoff; std::string info; if (passedTime < edcaQueue.aifsn * SLOTLENGTH_11P + SIFS_11P) { // we didnt even make it one DIFS :( info.append(" No DIFS"); } else { // decrease the backoff by one because we made it longer than one DIFS edcaQueue.currentBackoff -= 1; // check how many slots we waited after the first DIFS int64_t passedSlots = (int64_t)((passedTime - SimTime(edcaQueue.aifsn * SLOTLENGTH_11P + SIFS_11P)) / SLOTLENGTH_11P); EV_TRACE << "Passed slots after DIFS: " << passedSlots << std::endl; if (edcaQueue.queue.size() == 0) { // this can be below 0 because of post transmit backoff -> backoff on empty queues will not generate macevents, // we dont want to generate a txOP for empty queues edcaQueue.currentBackoff -= std::min(edcaQueue.currentBackoff, passedSlots); info.append(" PostCommit Over"); } else { edcaQueue.currentBackoff -= passedSlots; if (edcaQueue.currentBackoff <= -1) { if (generateTxOp) { edcaQueue.txOP = true; info.append(" TXOP"); } // else: this packet couldnt be sent because there was too little time. we could have generated a txop, but the channel switched edcaQueue.currentBackoff = 0; } } } EV_TRACE << "Updating backoff for Queue " << accessCategory << ": " << oldBackoff << " -> " << edcaQueue.currentBackoff << info << std::endl; } } } void Mac1609_4::EDCA::backoff(t_access_category ac) { myQueues[ac].currentBackoff = owner->intuniform(0, myQueues[ac].cwCur); statsSlotsBackoff += myQueues[ac].currentBackoff; statsNumBackoff++; EV_TRACE << "Going into Backoff because channel was busy when new packet arrived from upperLayer" << std::endl; } void Mac1609_4::EDCA::postTransmit(t_access_category ac, BaseFrame1609_4* wsm, bool useAcks) { bool holBlocking = (wsm->getRecipientAddress() != LAddress::L2BROADCAST()) && useAcks; if (holBlocking) { // mac->waitUntilAckRXorTimeout = true; // set in handleselfmsg() // Head of line blocking, wait until ack timeout myQueues[ac].waitForAck = true; myQueues[ac].waitOnUnicastID = wsm->getTreeId(); ((Mac1609_4*) owner)->phy11p->notifyMacAboutRxStart(true); } else { myQueues[ac].waitForAck = false; delete myQueues[ac].queue.front(); myQueues[ac].queue.pop(); myQueues[ac].cwCur = myQueues[ac].cwMin; // post transmit backoff myQueues[ac].currentBackoff = owner->intuniform(0, myQueues[ac].cwCur); statsSlotsBackoff += myQueues[ac].currentBackoff; statsNumBackoff++; EV_TRACE << "Queue " << ac << " will go into post-transmit backoff for " << myQueues[ac].currentBackoff << " slots" << std::endl; } } Mac1609_4::EDCA::EDCA(cSimpleModule* owner, ChannelType channelType, int maxQueueLength) : HasLogProxy(owner) , owner(owner) , maxQueueSize(maxQueueLength) , channelType(channelType) , statsNumInternalContention(0) , statsNumBackoff(0) , statsSlotsBackoff(0) { } Mac1609_4::EDCA::~EDCA() { for (auto& q : myQueues) { auto& ackTimeout = q.second.ackTimeOut; if (ackTimeout) { owner->cancelAndDelete(ackTimeout); ackTimeout = nullptr; } } } void Mac1609_4::EDCA::revokeTxOPs() { for (auto&& p : myQueues) { auto& edcaQueue = p.second; if (edcaQueue.txOP == true) { edcaQueue.txOP = false; edcaQueue.currentBackoff = 0; } } } void Mac1609_4::channelBusySelf(bool generateTxOp) { // the channel turned busy because we're sending. we don't want our queues to go into backoff // internal contention is already handled in initiateTransmission if (!idleChannel) return; idleChannel = false; EV_TRACE << "Channel turned busy: Switch or Self-Send" << std::endl; lastBusy = simTime(); // channel turned busy if (nextMacEvent->isScheduled() == true) { cancelEvent(nextMacEvent); } else { // the edca subsystem was not doing anything anyway. } myEDCA[activeChannel]->stopContent(false, generateTxOp); emit(sigChannelBusy, true); } void Mac1609_4::channelBusy() { if (!idleChannel) return; // the channel turned busy because someone else is sending idleChannel = false; EV_TRACE << "Channel turned busy: External sender" << std::endl; lastBusy = simTime(); // channel turned busy if (nextMacEvent->isScheduled() == true) { cancelEvent(nextMacEvent); } else { // the edca subsystem was not doing anything anyway. } myEDCA[activeChannel]->stopContent(true, false); emit(sigChannelBusy, true); } void Mac1609_4::channelIdle(bool afterSwitch) { EV_TRACE << "Channel turned idle: Switch: " << afterSwitch << std::endl; if (waitUntilAckRXorTimeout) { return; } if (nextMacEvent->isScheduled() == true) { // this rare case can happen when another node's time has such a big offset that the node sent a packet although we already changed the channel // the workaround is not trivial and requires a lot of changes to the phy and decider return; // throw cRuntimeError("channel turned idle but contention timer was scheduled!"); } idleChannel = true; simtime_t delay = 0; // account for 1609.4 guards if (afterSwitch) { // delay = GUARD_INTERVAL_11P; } if (useSCH) { delay += timeLeftTillGuardOver(); } // channel turned idle! lets start contention! lastIdle = delay + simTime(); statsTotalBusyTime += simTime() - lastBusy; // get next Event from current EDCA subsystem simtime_t nextEvent = myEDCA[activeChannel]->startContent(lastIdle, guardActive()); if (nextEvent != -1) { if ((!useSCH) || (nextEvent < nextChannelSwitch->getArrivalTime())) { scheduleAt(nextEvent, nextMacEvent); EV_TRACE << "next Event is at " << nextMacEvent->getArrivalTime().raw() << std::endl; } else { EV_TRACE << "Too little time in this interval. will not schedule macEvent" << std::endl; statsNumTooLittleTime++; myEDCA[activeChannel]->revokeTxOPs(); } } else { EV_TRACE << "I don't have any new events in this EDCA sub system" << std::endl; } emit(sigChannelBusy, false); } void Mac1609_4::setParametersForBitrate(uint64_t bitrate) { mcs = getMCS(bitrate, BANDWIDTH_11P); if (mcs == MCS::undefined) { throw cRuntimeError("Chosen Bitrate is not valid for 802.11p: Valid rates are: 3Mbps, 4.5Mbps, 6Mbps, 9Mbps, 12Mbps, 18Mbps, 24Mbps and 27Mbps. Please adjust your omnetpp.ini file accordingly."); } } bool Mac1609_4::isChannelSwitchingActive() { return useSCH; } simtime_t Mac1609_4::getSwitchingInterval() { return SWITCHING_INTERVAL_11P; } bool Mac1609_4::isCurrentChannelCCH() { return (activeChannel == ChannelType::control); } // Unicast void Mac1609_4::sendAck(LAddress::L2Type recpAddress, unsigned long wsmId) { ASSERT(useAcks); // 802.11-2012 9.3.2.8 // send an ACK after SIFS without regard of busy/ idle state of channel ignoreChannelState = true; channelBusySelf(true); // send the packet auto* mac = new Mac80211Ack("ACK"); mac->setDestAddr(recpAddress); mac->setSrcAddr(myMacAddr); mac->setMessageId(wsmId); mac->setBitLength(ackLength); simtime_t sendingDuration = RADIODELAY_11P + phy11p->getFrameDuration(mac->getBitLength(), mcs); EV_TRACE << "Ack sending duration will be " << sendingDuration << std::endl; // TODO: check ack procedure when channel switching is allowed // double freq = (activeChannel == ChannelType::control) ? IEEE80211ChannelFrequencies.at(Channel::cch) : IEEE80211ChannelFrequencies.at(mySCH); double freq = IEEE80211ChannelFrequencies.at(Channel::cch); EV_TRACE << "Sending an ack. Frequency " << freq << " at time : " << simTime() + SIFS_11P << std::endl; sendFrame(mac, SIFS_11P, Channel::cch, mcs, txPower); scheduleAt(simTime() + SIFS_11P, stopIgnoreChannelStateMsg); } void Mac1609_4::handleUnicast(LAddress::L2Type srcAddr, unique_ptr<BaseFrame1609_4> wsm) { if (useAcks) { sendAck(srcAddr, wsm->getTreeId()); } if (handledUnicastToApp.find(wsm->getTreeId()) == handledUnicastToApp.end()) { handledUnicastToApp.insert(wsm->getTreeId()); EV_TRACE << "Received a data packet addressed to me." << std::endl; statsReceivedPackets++; sendUp(wsm.release()); } } void Mac1609_4::handleAck(const Mac80211Ack* ack) { ASSERT2(rxStartIndication, "Not expecting ack"); phy11p->notifyMacAboutRxStart(false); rxStartIndication = false; ChannelType chan = ChannelType::control; bool queueUnblocked = false; for (auto&& p : myEDCA[chan]->myQueues) { auto& accessCategory = p.first; auto& edcaQueue = p.second; if (edcaQueue.queue.size() > 0 && edcaQueue.waitForAck && (edcaQueue.waitOnUnicastID == ack->getMessageId())) { BaseFrame1609_4* wsm = edcaQueue.queue.front(); edcaQueue.queue.pop(); delete wsm; myEDCA[chan]->myQueues[accessCategory].cwCur = myEDCA[chan]->myQueues[accessCategory].cwMin; myEDCA[chan]->backoff(accessCategory); edcaQueue.ssrc = 0; edcaQueue.slrc = 0; edcaQueue.waitForAck = false; edcaQueue.waitOnUnicastID = -1; if (myEDCA[chan]->myQueues[accessCategory].ackTimeOut->isScheduled()) { cancelEvent(myEDCA[chan]->myQueues[accessCategory].ackTimeOut); } queueUnblocked = true; } } if (!queueUnblocked) { throw cRuntimeError("Could not find WSM in EDCA queues with WSM ID received in ACK"); } else { waitUntilAckRXorTimeout = false; } } void Mac1609_4::handleAckTimeOut(AckTimeOutMessage* ackTimeOutMsg) { if (rxStartIndication) { // Rx is already in process. Wait for it to complete. // In case it is not an ack, we will retransmit // This assigning might be redundant as it was set already in handleSelfMsg but no harm in reassigning here. lastAC = (t_access_category)(ackTimeOutMsg->getKind()); return; } // We did not start receiving any packet. // stop receiving notification for rx start as we will retransmit phy11p->notifyMacAboutRxStart(false); // back off and try retransmission again handleRetransmit((t_access_category)(ackTimeOutMsg->getKind())); // Phy was requested not to send channel idle status on TX_OVER // So request the channel status now. For the case when we receive ACK, decider updates channel status itself after ACK RX phy11p->requestChannelStatusIfIdle(); } void Mac1609_4::handleRetransmit(t_access_category ac) { // cancel the acktime out if (myEDCA[ChannelType::control]->myQueues[ac].ackTimeOut->isScheduled()) { // This case is possible if we received PHY_RX_END_WITH_SUCCESS or FAILURE even before ack timeout cancelEvent(myEDCA[ChannelType::control]->myQueues[ac].ackTimeOut); } if (myEDCA[ChannelType::control]->myQueues[ac].queue.size() == 0) { throw cRuntimeError("Trying retransmission on empty queue..."); } BaseFrame1609_4* appPkt = myEDCA[ChannelType::control]->myQueues[ac].queue.front(); bool contend = false; bool retriesExceeded = false; // page 879 of IEEE 802.11-2012 if (appPkt->getBitLength() <= dot11RTSThreshold) { myEDCA[ChannelType::control]->myQueues[ac].ssrc++; if (myEDCA[ChannelType::control]->myQueues[ac].ssrc <= dot11ShortRetryLimit) { retriesExceeded = false; } else { retriesExceeded = true; } } else { myEDCA[ChannelType::control]->myQueues[ac].slrc++; if (myEDCA[ChannelType::control]->myQueues[ac].slrc <= dot11LongRetryLimit) { retriesExceeded = false; } else { retriesExceeded = true; } } if (!retriesExceeded) { // try again! myEDCA[ChannelType::control]->myQueues[ac].cwCur = std::min(myEDCA[ChannelType::control]->myQueues[ac].cwMax, (myEDCA[ChannelType::control]->myQueues[ac].cwCur * 2) + 1); myEDCA[ChannelType::control]->backoff(ac); contend = true; // no need to reset wait on id here as we are still retransmitting same packet myEDCA[ChannelType::control]->myQueues[ac].waitForAck = false; } else { // enough tries! myEDCA[ChannelType::control]->myQueues[ac].queue.pop(); if (myEDCA[ChannelType::control]->myQueues[ac].queue.size() > 0) { // start contention only if there are more packets in the queue contend = true; } delete appPkt; myEDCA[ChannelType::control]->myQueues[ac].cwCur = myEDCA[ChannelType::control]->myQueues[ac].cwMin; myEDCA[ChannelType::control]->backoff(ac); myEDCA[ChannelType::control]->myQueues[ac].waitForAck = false; myEDCA[ChannelType::control]->myQueues[ac].waitOnUnicastID = -1; myEDCA[ChannelType::control]->myQueues[ac].ssrc = 0; myEDCA[ChannelType::control]->myQueues[ac].slrc = 0; } waitUntilAckRXorTimeout = false; if (contend && idleChannel && !ignoreChannelState) { // reevaluate times -- if channel is not idle, then contention would start automatically cancelEvent(nextMacEvent); simtime_t nextEvent = myEDCA[ChannelType::control]->startContent(lastIdle, guardActive()); scheduleAt(nextEvent, nextMacEvent); } } Mac1609_4::EDCA::EDCAQueue::EDCAQueue(int aifsn, int cwMin, int cwMax, t_access_category ac) : aifsn(aifsn) , cwMin(cwMin) , cwMax(cwMax) , cwCur(cwMin) , currentBackoff(0) , txOP(false) , ssrc(0) , slrc(0) , waitForAck(false) , waitOnUnicastID(-1) , ackTimeOut(new AckTimeOutMessage("AckTimeOut")) { ackTimeOut->setKind(ac); } Mac1609_4::EDCA::EDCAQueue::~EDCAQueue() { while (!queue.empty()) { delete queue.front(); queue.pop(); } // ackTimeOut needs to be deleted in EDCA }
43,487
36.392949
274
cc
null
AICP-main/veins/src/veins/modules/mac/ieee80211p/Mac1609_4.h
// // Copyright (C) 2012 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <queue> #include <memory> #include <stdint.h> #include "veins/veins.h" #include "veins/base/modules/BaseLayer.h" #include "veins/modules/phy/PhyLayer80211p.h" #include "veins/modules/mac/ieee80211p/DemoBaseApplLayerToMac1609_4Interface.h" #include "veins/modules/utility/Consts80211p.h" #include "veins/modules/utility/MacToPhyControlInfo11p.h" #include "veins/base/utils/FindModule.h" #include "veins/modules/messages/Mac80211Pkt_m.h" #include "veins/modules/messages/BaseFrame1609_4_m.h" #include "veins/modules/messages/AckTimeOutMessage_m.h" #include "veins/modules/messages/Mac80211Ack_m.h" #include "veins/base/modules/BaseMacLayer.h" #include "veins/modules/utility/ConstsPhy.h" #include "veins/modules/utility/HasLogProxy.h" namespace veins { /** * @brief * Manages timeslots for CCH and SCH listening and sending. * * @author David Eckhoff : rewrote complete model * @author Christoph Sommer : features and bug fixes * @author Michele Segata : features and bug fixes * @author Stefan Joerer : features and bug fixes * @author Gurjashan Pannu: features (unicast model) * @author Christopher Saloman: initial version * * @ingroup macLayer * * @see DemoBaseApplLayer * @see Mac1609_4 * @see PhyLayer80211p * @see Decider80211p */ class DeciderResult80211; class VEINS_API Mac1609_4 : public BaseMacLayer, public DemoBaseApplLayerToMac1609_4Interface { public: // tell to anybody which is interested when the channel turns busy or idle static const simsignal_t sigChannelBusy; // tell to anybody which is interested when a collision occurred static const simsignal_t sigCollision; // Access categories in increasing order of priority (see IEEE Std 802.11-2012, Table 9-1) enum t_access_category { AC_BK = 0, AC_BE = 1, AC_VI = 2, AC_VO = 3 }; class VEINS_API EDCA : HasLogProxy { public: class VEINS_API EDCAQueue { public: std::queue<BaseFrame1609_4*> queue; int aifsn; // number of aifs slots for this queue int cwMin; // minimum contention window int cwMax; // maximum contention size int cwCur; // current contention window int64_t currentBackoff; // current Backoff value for this queue bool txOP; int ssrc; // station short retry count int slrc; // station long retry count bool waitForAck; // true if the queue is waiting for an acknowledgment for unicast unsigned long waitOnUnicastID; // unique id of unicast on which station is waiting AckTimeOutMessage* ackTimeOut; // timer for retransmission on receiving no ACK EDCAQueue() { } EDCAQueue(int aifsn, int cwMin, int cwMax, t_access_category ac); ~EDCAQueue(); }; EDCA(cSimpleModule* owner, ChannelType channelType, int maxQueueLength = 0); ~EDCA(); void createQueue(int aifsn, int cwMin, int cwMax, t_access_category); int queuePacket(t_access_category AC, BaseFrame1609_4* cmsg); void backoff(t_access_category ac); simtime_t startContent(simtime_t idleSince, bool guardActive); void stopContent(bool allowBackoff, bool generateTxOp); void postTransmit(t_access_category, BaseFrame1609_4* wsm, bool useAcks); void revokeTxOPs(); /** @brief return the next packet to send, send all lower Queues into backoff */ BaseFrame1609_4* initiateTransmit(simtime_t idleSince); public: cSimpleModule* owner; std::map<t_access_category, EDCAQueue> myQueues; uint32_t maxQueueSize; simtime_t lastStart; // when we started the last contention; ChannelType channelType; /** @brief Stats */ long statsNumInternalContention; long statsNumBackoff; long statsSlotsBackoff; /** @brief Id for debug messages */ std::string myId; }; public: Mac1609_4() : nextChannelSwitch(nullptr) , nextMacEvent(nullptr) { } ~Mac1609_4() override; /** * @brief return true if alternate access is enabled */ bool isChannelSwitchingActive() override; simtime_t getSwitchingInterval() override; bool isCurrentChannelCCH() override; void changeServiceChannel(Channel channelNumber) override; /** * @brief Change the default tx power the NIC card is using * * @param txPower_mW the tx power to be set in mW */ void setTxPower(double txPower_mW); /** * @brief Change the default MCS the NIC card is using * * @param mcs the default modulation and coding scheme * to use */ void setMCS(MCS mcs); /** * @brief Change the phy layer carrier sense threshold. * * @param ccaThreshold_dBm the cca threshold in dBm */ void setCCAThreshold(double ccaThreshold_dBm); protected: /** @brief States of the channel selecting operation.*/ protected: /** @brief Initialization of the module and some variables.*/ void initialize(int) override; /** @brief Delete all dynamically allocated objects of the module.*/ void finish() override; /** @brief Handle messages from lower layer.*/ void handleLowerMsg(cMessage*) override; /** @brief Handle messages from upper layer.*/ void handleUpperMsg(cMessage*) override; /** @brief Handle control messages from upper layer.*/ void handleUpperControl(cMessage* msg) override; /** @brief Handle self messages such as timers.*/ void handleSelfMsg(cMessage*) override; /** @brief Handle control messages from lower layer.*/ void handleLowerControl(cMessage* msg) override; /** @brief Handle received broadcast */ virtual void handleBroadcast(Mac80211Pkt* macPkt, DeciderResult80211* res); /** @brief Set a state for the channel selecting operation.*/ void setActiveChannel(ChannelType state); void sendFrame(Mac80211Pkt* frame, omnetpp::simtime_t delay, Channel channelNr, MCS mcs, double txPower_mW); simtime_t timeLeftInSlot() const; simtime_t timeLeftTillGuardOver() const; bool guardActive() const; void attachControlInfo(Mac80211Pkt* mac, Channel channelNr, MCS mcs, double txPower_mW); /** @brief maps a application layer priority (up) to an EDCA access category. */ t_access_category mapUserPriority(int prio); void channelBusy(); void channelBusySelf(bool generateTxOp); void channelIdle(bool afterSwitch = false); void setParametersForBitrate(uint64_t bitrate); void sendAck(LAddress::L2Type recpAddress, unsigned long wsmId); void handleUnicast(LAddress::L2Type srcAddr, std::unique_ptr<BaseFrame1609_4> wsm); void handleAck(const Mac80211Ack* ack); void handleAckTimeOut(AckTimeOutMessage* ackTimeOutMsg); void handleRetransmit(t_access_category ac); const LAddress::L2Type& getMACAddress() override { ASSERT(myMacAddr != LAddress::L2NULL()); return BaseMacLayer::getMACAddress(); } protected: /** @brief Self message to indicate that the current channel shall be switched.*/ cMessage* nextChannelSwitch; /** @brief Self message to wake up at next MacEvent */ cMessage* nextMacEvent; /** @brief Last time the channel went idle */ simtime_t lastIdle; simtime_t lastBusy; /** @brief Current state of the channel selecting operation.*/ ChannelType activeChannel; /** @brief access category of last sent packet */ t_access_category lastAC; /** @brief pointer to last sent packet */ BaseFrame1609_4* lastWSM; /** @brief pointer to last sent mac frame */ std::unique_ptr<Mac80211Pkt> lastMac; int headerLength; bool useSCH; Channel mySCH; std::map<ChannelType, std::unique_ptr<EDCA>> myEDCA; bool idleChannel; /** @brief stats */ long statsReceivedPackets; long statsReceivedBroadcasts; long statsSentPackets; long statsSentAcks; long statsTXRXLostPackets; long statsSNIRLostPackets; long statsDroppedPackets; long statsNumTooLittleTime; long statsNumInternalContention; long statsNumBackoff; long statsSlotsBackoff; simtime_t statsTotalBusyTime; /** @brief The power (in mW) to transmit with.*/ double txPower; MCS mcs; ///< Modulation and coding scheme to use unless explicitly specified. /** @brief Id for debug messages */ std::string myId; bool useAcks; double ackErrorRate; int dot11RTSThreshold; int dot11ShortRetryLimit; int dot11LongRetryLimit; int ackLength; // indicates rx start within the period of ACK timeout bool rxStartIndication; // An ack is sent after SIFS irrespective of the channel state cMessage* stopIgnoreChannelStateMsg; bool ignoreChannelState; // Dont start contention immediately after finishing unicast TX. Wait until ack timeout/ ack Rx bool waitUntilAckRXorTimeout; std::set<unsigned long> handledUnicastToApp; Mac80211pToPhy11pInterface* phy11p; }; } // namespace veins
10,064
30.851266
112
h
null
AICP-main/veins/src/veins/modules/mac/ieee80211p/Mac80211pToPhy11pInterface.h
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/base/phyLayer/MacToPhyInterface.h" #include "veins/modules/utility/ConstsPhy.h" #include "veins/modules/utility/Consts80211p.h" namespace veins { /** * @brief * Interface of PhyLayer80211p exposed to Mac1609_4. * * @author Christopher Saloman * @author David Eckhoff * * @ingroup phyLayer */ class VEINS_API Mac80211pToPhy11pInterface { public: enum BasePhyMessageKinds { CHANNEL_IDLE, CHANNEL_BUSY, }; virtual ~Mac80211pToPhy11pInterface() = default; virtual void changeListeningChannel(Channel channel) = 0; virtual void setCCAThreshold(double ccaThreshold_dBm) = 0; virtual void notifyMacAboutRxStart(bool enable) = 0; virtual void requestChannelStatusIfIdle() = 0; virtual simtime_t getFrameDuration(int payloadLengthBits, MCS mcs) const = 0; }; } // namespace veins
1,757
29.842105
81
h
null
AICP-main/veins/src/veins/modules/messages/AckTimeOutMessage_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AckTimeOutMessage.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "AckTimeOutMessage_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(AckTimeOutMessage) AckTimeOutMessage::AckTimeOutMessage(const char *name, short kind) : ::omnetpp::cMessage(name,kind) { this->wsmId = -1; this->ac = -1; } AckTimeOutMessage::AckTimeOutMessage(const AckTimeOutMessage& other) : ::omnetpp::cMessage(other) { copy(other); } AckTimeOutMessage::~AckTimeOutMessage() { } AckTimeOutMessage& AckTimeOutMessage::operator=(const AckTimeOutMessage& other) { if (this==&other) return *this; ::omnetpp::cMessage::operator=(other); copy(other); return *this; } void AckTimeOutMessage::copy(const AckTimeOutMessage& other) { this->wsmId = other.wsmId; this->ac = other.ac; } void AckTimeOutMessage::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cMessage::parsimPack(b); doParsimPacking(b,this->wsmId); doParsimPacking(b,this->ac); } void AckTimeOutMessage::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cMessage::parsimUnpack(b); doParsimUnpacking(b,this->wsmId); doParsimUnpacking(b,this->ac); } unsigned long AckTimeOutMessage::getWsmId() const { return this->wsmId; } void AckTimeOutMessage::setWsmId(unsigned long wsmId) { this->wsmId = wsmId; } int AckTimeOutMessage::getAc() const { return this->ac; } void AckTimeOutMessage::setAc(int ac) { this->ac = ac; } class AckTimeOutMessageDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: AckTimeOutMessageDescriptor(); virtual ~AckTimeOutMessageDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(AckTimeOutMessageDescriptor) AckTimeOutMessageDescriptor::AckTimeOutMessageDescriptor() : omnetpp::cClassDescriptor("veins::AckTimeOutMessage", "omnetpp::cMessage") { propertynames = nullptr; } AckTimeOutMessageDescriptor::~AckTimeOutMessageDescriptor() { delete[] propertynames; } bool AckTimeOutMessageDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<AckTimeOutMessage *>(obj)!=nullptr; } const char **AckTimeOutMessageDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *AckTimeOutMessageDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int AckTimeOutMessageDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 2+basedesc->getFieldCount() : 2; } unsigned int AckTimeOutMessageDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<2) ? fieldTypeFlags[field] : 0; } const char *AckTimeOutMessageDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "wsmId", "ac", }; return (field>=0 && field<2) ? fieldNames[field] : nullptr; } int AckTimeOutMessageDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='w' && strcmp(fieldName, "wsmId")==0) return base+0; if (fieldName[0]=='a' && strcmp(fieldName, "ac")==0) return base+1; return basedesc ? basedesc->findField(fieldName) : -1; } const char *AckTimeOutMessageDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "unsigned long", "int", }; return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr; } const char **AckTimeOutMessageDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *AckTimeOutMessageDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int AckTimeOutMessageDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp; switch (field) { default: return 0; } } const char *AckTimeOutMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp; switch (field) { default: return nullptr; } } std::string AckTimeOutMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp; switch (field) { case 0: return ulong2string(pp->getWsmId()); case 1: return long2string(pp->getAc()); default: return ""; } } bool AckTimeOutMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp; switch (field) { case 0: pp->setWsmId(string2ulong(value)); return true; case 1: pp->setAc(string2long(value)); return true; default: return false; } } const char *AckTimeOutMessageDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *AckTimeOutMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace veins
15,189
30.449275
135
cc
null
AICP-main/veins/src/veins/modules/messages/AckTimeOutMessage_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AckTimeOutMessage.msg. // #ifndef __VEINS_ACKTIMEOUTMESSAGE_M_H #define __VEINS_ACKTIMEOUTMESSAGE_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif namespace veins { /** * Class generated from <tt>veins/modules/messages/AckTimeOutMessage.msg:25</tt> by nedtool. * <pre> * message AckTimeOutMessage * { * // The corresponding WSM's tree id * unsigned long wsmId = -1; * // Access category on which the AckTimer is set * int ac = -1; * } * </pre> */ class VEINS_API AckTimeOutMessage : public ::omnetpp::cMessage { protected: unsigned long wsmId; int ac; private: void copy(const AckTimeOutMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const AckTimeOutMessage&); public: AckTimeOutMessage(const char *name=nullptr, short kind=0); AckTimeOutMessage(const AckTimeOutMessage& other); virtual ~AckTimeOutMessage(); AckTimeOutMessage& operator=(const AckTimeOutMessage& other); virtual AckTimeOutMessage *dup() const override {return new AckTimeOutMessage(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual unsigned long getWsmId() const; virtual void setWsmId(unsigned long wsmId); virtual int getAc() const; virtual void setAc(int ac); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const AckTimeOutMessage& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, AckTimeOutMessage& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_ACKTIMEOUTMESSAGE_M_H
2,303
27.444444
121
h
null
AICP-main/veins/src/veins/modules/messages/AirFrame11p_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AirFrame11p.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "AirFrame11p_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(AirFrame11p) AirFrame11p::AirFrame11p(const char *name, short kind) : ::veins::AirFrame(name,kind) { this->underMinPowerLevel = false; this->wasTransmitting = false; } AirFrame11p::AirFrame11p(const AirFrame11p& other) : ::veins::AirFrame(other) { copy(other); } AirFrame11p::~AirFrame11p() { } AirFrame11p& AirFrame11p::operator=(const AirFrame11p& other) { if (this==&other) return *this; ::veins::AirFrame::operator=(other); copy(other); return *this; } void AirFrame11p::copy(const AirFrame11p& other) { this->underMinPowerLevel = other.underMinPowerLevel; this->wasTransmitting = other.wasTransmitting; } void AirFrame11p::parsimPack(omnetpp::cCommBuffer *b) const { ::veins::AirFrame::parsimPack(b); doParsimPacking(b,this->underMinPowerLevel); doParsimPacking(b,this->wasTransmitting); } void AirFrame11p::parsimUnpack(omnetpp::cCommBuffer *b) { ::veins::AirFrame::parsimUnpack(b); doParsimUnpacking(b,this->underMinPowerLevel); doParsimUnpacking(b,this->wasTransmitting); } bool AirFrame11p::getUnderMinPowerLevel() const { return this->underMinPowerLevel; } void AirFrame11p::setUnderMinPowerLevel(bool underMinPowerLevel) { this->underMinPowerLevel = underMinPowerLevel; } bool AirFrame11p::getWasTransmitting() const { return this->wasTransmitting; } void AirFrame11p::setWasTransmitting(bool wasTransmitting) { this->wasTransmitting = wasTransmitting; } class AirFrame11pDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: AirFrame11pDescriptor(); virtual ~AirFrame11pDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(AirFrame11pDescriptor) AirFrame11pDescriptor::AirFrame11pDescriptor() : omnetpp::cClassDescriptor("veins::AirFrame11p", "veins::AirFrame") { propertynames = nullptr; } AirFrame11pDescriptor::~AirFrame11pDescriptor() { delete[] propertynames; } bool AirFrame11pDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<AirFrame11p *>(obj)!=nullptr; } const char **AirFrame11pDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *AirFrame11pDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int AirFrame11pDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 2+basedesc->getFieldCount() : 2; } unsigned int AirFrame11pDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<2) ? fieldTypeFlags[field] : 0; } const char *AirFrame11pDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "underMinPowerLevel", "wasTransmitting", }; return (field>=0 && field<2) ? fieldNames[field] : nullptr; } int AirFrame11pDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='u' && strcmp(fieldName, "underMinPowerLevel")==0) return base+0; if (fieldName[0]=='w' && strcmp(fieldName, "wasTransmitting")==0) return base+1; return basedesc ? basedesc->findField(fieldName) : -1; } const char *AirFrame11pDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "bool", "bool", }; return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr; } const char **AirFrame11pDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *AirFrame11pDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int AirFrame11pDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } AirFrame11p *pp = (AirFrame11p *)object; (void)pp; switch (field) { default: return 0; } } const char *AirFrame11pDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } AirFrame11p *pp = (AirFrame11p *)object; (void)pp; switch (field) { default: return nullptr; } } std::string AirFrame11pDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } AirFrame11p *pp = (AirFrame11p *)object; (void)pp; switch (field) { case 0: return bool2string(pp->getUnderMinPowerLevel()); case 1: return bool2string(pp->getWasTransmitting()); default: return ""; } } bool AirFrame11pDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } AirFrame11p *pp = (AirFrame11p *)object; (void)pp; switch (field) { case 0: pp->setUnderMinPowerLevel(string2bool(value)); return true; case 1: pp->setWasTransmitting(string2bool(value)); return true; default: return false; } } const char *AirFrame11pDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *AirFrame11pDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } AirFrame11p *pp = (AirFrame11p *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace veins
15,205
30.482402
128
cc
null
AICP-main/veins/src/veins/modules/messages/AirFrame11p_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AirFrame11p.msg. // #ifndef __VEINS_AIRFRAME11P_M_H #define __VEINS_AIRFRAME11P_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif // cplusplus {{ #include "veins/base/messages/AirFrame_m.h" using veins::AirFrame; // }} namespace veins { /** * Class generated from <tt>veins/modules/messages/AirFrame11p.msg:35</tt> by nedtool. * <pre> * // * // Extension of base AirFrame message to have the underMinPowerLevel field * // * message AirFrame11p extends AirFrame * { * bool underMinPowerLevel = false; * bool wasTransmitting = false; * } * </pre> */ class VEINS_API AirFrame11p : public ::veins::AirFrame { protected: bool underMinPowerLevel; bool wasTransmitting; private: void copy(const AirFrame11p& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const AirFrame11p&); public: AirFrame11p(const char *name=nullptr, short kind=0); AirFrame11p(const AirFrame11p& other); virtual ~AirFrame11p(); AirFrame11p& operator=(const AirFrame11p& other); virtual AirFrame11p *dup() const override {return new AirFrame11p(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual bool getUnderMinPowerLevel() const; virtual void setUnderMinPowerLevel(bool underMinPowerLevel); virtual bool getWasTransmitting() const; virtual void setWasTransmitting(bool wasTransmitting); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const AirFrame11p& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, AirFrame11p& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_AIRFRAME11P_M_H
2,391
26.494253
121
h
null
AICP-main/veins/src/veins/modules/messages/BaseFrame1609_4_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/BaseFrame1609_4.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "BaseFrame1609_4_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(BaseFrame1609_4) BaseFrame1609_4::BaseFrame1609_4(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->channelNumber = 0; this->userPriority = 7; this->psid = 0; this->recipientAddress = -1; } BaseFrame1609_4::BaseFrame1609_4(const BaseFrame1609_4& other) : ::omnetpp::cPacket(other) { copy(other); } BaseFrame1609_4::~BaseFrame1609_4() { } BaseFrame1609_4& BaseFrame1609_4::operator=(const BaseFrame1609_4& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void BaseFrame1609_4::copy(const BaseFrame1609_4& other) { this->channelNumber = other.channelNumber; this->userPriority = other.userPriority; this->psid = other.psid; this->recipientAddress = other.recipientAddress; } void BaseFrame1609_4::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->channelNumber); doParsimPacking(b,this->userPriority); doParsimPacking(b,this->psid); doParsimPacking(b,this->recipientAddress); } void BaseFrame1609_4::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->channelNumber); doParsimUnpacking(b,this->userPriority); doParsimUnpacking(b,this->psid); doParsimUnpacking(b,this->recipientAddress); } int BaseFrame1609_4::getChannelNumber() const { return this->channelNumber; } void BaseFrame1609_4::setChannelNumber(int channelNumber) { this->channelNumber = channelNumber; } int BaseFrame1609_4::getUserPriority() const { return this->userPriority; } void BaseFrame1609_4::setUserPriority(int userPriority) { this->userPriority = userPriority; } int BaseFrame1609_4::getPsid() const { return this->psid; } void BaseFrame1609_4::setPsid(int psid) { this->psid = psid; } LAddress::L2Type& BaseFrame1609_4::getRecipientAddress() { return this->recipientAddress; } void BaseFrame1609_4::setRecipientAddress(const LAddress::L2Type& recipientAddress) { this->recipientAddress = recipientAddress; } class BaseFrame1609_4Descriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: BaseFrame1609_4Descriptor(); virtual ~BaseFrame1609_4Descriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(BaseFrame1609_4Descriptor) BaseFrame1609_4Descriptor::BaseFrame1609_4Descriptor() : omnetpp::cClassDescriptor("veins::BaseFrame1609_4", "omnetpp::cPacket") { propertynames = nullptr; } BaseFrame1609_4Descriptor::~BaseFrame1609_4Descriptor() { delete[] propertynames; } bool BaseFrame1609_4Descriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<BaseFrame1609_4 *>(obj)!=nullptr; } const char **BaseFrame1609_4Descriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *BaseFrame1609_4Descriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int BaseFrame1609_4Descriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 4+basedesc->getFieldCount() : 4; } unsigned int BaseFrame1609_4Descriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISCOMPOUND, }; return (field>=0 && field<4) ? fieldTypeFlags[field] : 0; } const char *BaseFrame1609_4Descriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "channelNumber", "userPriority", "psid", "recipientAddress", }; return (field>=0 && field<4) ? fieldNames[field] : nullptr; } int BaseFrame1609_4Descriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='c' && strcmp(fieldName, "channelNumber")==0) return base+0; if (fieldName[0]=='u' && strcmp(fieldName, "userPriority")==0) return base+1; if (fieldName[0]=='p' && strcmp(fieldName, "psid")==0) return base+2; if (fieldName[0]=='r' && strcmp(fieldName, "recipientAddress")==0) return base+3; return basedesc ? basedesc->findField(fieldName) : -1; } const char *BaseFrame1609_4Descriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "int", "int", "int", "LAddress::L2Type", }; return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr; } const char **BaseFrame1609_4Descriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *BaseFrame1609_4Descriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int BaseFrame1609_4Descriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp; switch (field) { default: return 0; } } const char *BaseFrame1609_4Descriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp; switch (field) { default: return nullptr; } } std::string BaseFrame1609_4Descriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp; switch (field) { case 0: return long2string(pp->getChannelNumber()); case 1: return long2string(pp->getUserPriority()); case 2: return long2string(pp->getPsid()); case 3: {std::stringstream out; out << pp->getRecipientAddress(); return out.str();} default: return ""; } } bool BaseFrame1609_4Descriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp; switch (field) { case 0: pp->setChannelNumber(string2long(value)); return true; case 1: pp->setUserPriority(string2long(value)); return true; case 2: pp->setPsid(string2long(value)); return true; default: return false; } } const char *BaseFrame1609_4Descriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { case 3: return omnetpp::opp_typename(typeid(LAddress::L2Type)); default: return nullptr; }; } void *BaseFrame1609_4Descriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp; switch (field) { case 3: return (void *)(&pp->getRecipientAddress()); break; default: return nullptr; } } } // namespace veins
16,613
30.706107
128
cc
null
AICP-main/veins/src/veins/modules/messages/BaseFrame1609_4_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/BaseFrame1609_4.msg. // #ifndef __VEINS_BASEFRAME1609_4_M_H #define __VEINS_BASEFRAME1609_4_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif // cplusplus {{ #include "veins/base/utils/SimpleAddress.h" // }} namespace veins { /** * Class generated from <tt>veins/modules/messages/BaseFrame1609_4.msg:31</tt> by nedtool. * <pre> * packet BaseFrame1609_4 * { * //Channel Number on which this packet was sent * int channelNumber; * //User priority with which this packet was sent (note the AC mapping rules in Mac1609_4::mapUserPriority) * int userPriority = 7; * //Unique number to identify the service * int psid = 0; * //Recipient of frame (-1 for any) * LAddress::L2Type recipientAddress = -1; * } * </pre> */ class VEINS_API BaseFrame1609_4 : public ::omnetpp::cPacket { protected: int channelNumber; int userPriority; int psid; LAddress::L2Type recipientAddress; private: void copy(const BaseFrame1609_4& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const BaseFrame1609_4&); public: BaseFrame1609_4(const char *name=nullptr, short kind=0); BaseFrame1609_4(const BaseFrame1609_4& other); virtual ~BaseFrame1609_4(); BaseFrame1609_4& operator=(const BaseFrame1609_4& other); virtual BaseFrame1609_4 *dup() const override {return new BaseFrame1609_4(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual int getChannelNumber() const; virtual void setChannelNumber(int channelNumber); virtual int getUserPriority() const; virtual void setUserPriority(int userPriority); virtual int getPsid() const; virtual void setPsid(int psid); virtual LAddress::L2Type& getRecipientAddress(); virtual const LAddress::L2Type& getRecipientAddress() const {return const_cast<BaseFrame1609_4*>(this)->getRecipientAddress();} virtual void setRecipientAddress(const LAddress::L2Type& recipientAddress); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const BaseFrame1609_4& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, BaseFrame1609_4& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_BASEFRAME1609_4_M_H
2,987
30.125
131
h
null
AICP-main/veins/src/veins/modules/messages/DemoSafetyMessage_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoSafetyMessage.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "DemoSafetyMessage_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(DemoSafetyMessage) DemoSafetyMessage::DemoSafetyMessage(const char *name, short kind) : ::veins::BaseFrame1609_4(name,kind) { this->serial = 0; this->angle = 0; } DemoSafetyMessage::DemoSafetyMessage(const DemoSafetyMessage& other) : ::veins::BaseFrame1609_4(other) { copy(other); } DemoSafetyMessage::~DemoSafetyMessage() { } DemoSafetyMessage& DemoSafetyMessage::operator=(const DemoSafetyMessage& other) { if (this==&other) return *this; ::veins::BaseFrame1609_4::operator=(other); copy(other); return *this; } void DemoSafetyMessage::copy(const DemoSafetyMessage& other) { this->senderPos = other.senderPos; this->senderSpeed = other.senderSpeed; this->serial = other.serial; this->angle = other.angle; } void DemoSafetyMessage::parsimPack(omnetpp::cCommBuffer *b) const { ::veins::BaseFrame1609_4::parsimPack(b); doParsimPacking(b,this->senderPos); doParsimPacking(b,this->senderSpeed); doParsimPacking(b,this->serial); doParsimPacking(b,this->angle); } void DemoSafetyMessage::parsimUnpack(omnetpp::cCommBuffer *b) { ::veins::BaseFrame1609_4::parsimUnpack(b); doParsimUnpacking(b,this->senderPos); doParsimUnpacking(b,this->senderSpeed); doParsimUnpacking(b,this->serial); doParsimUnpacking(b,this->angle); } Coord& DemoSafetyMessage::getSenderPos() { return this->senderPos; } void DemoSafetyMessage::setSenderPos(const Coord& senderPos) { this->senderPos = senderPos; } Coord& DemoSafetyMessage::getSenderSpeed() { return this->senderSpeed; } void DemoSafetyMessage::setSenderSpeed(const Coord& senderSpeed) { this->senderSpeed = senderSpeed; } int DemoSafetyMessage::getSerial() const { return this->serial; } void DemoSafetyMessage::setSerial(int serial) { this->serial = serial; } double DemoSafetyMessage::getAngle() const { return this->angle; } void DemoSafetyMessage::setAngle(double angle) { this->angle = angle; } class DemoSafetyMessageDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: DemoSafetyMessageDescriptor(); virtual ~DemoSafetyMessageDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(DemoSafetyMessageDescriptor) DemoSafetyMessageDescriptor::DemoSafetyMessageDescriptor() : omnetpp::cClassDescriptor("veins::DemoSafetyMessage", "veins::BaseFrame1609_4") { propertynames = nullptr; } DemoSafetyMessageDescriptor::~DemoSafetyMessageDescriptor() { delete[] propertynames; } bool DemoSafetyMessageDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<DemoSafetyMessage *>(obj)!=nullptr; } const char **DemoSafetyMessageDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *DemoSafetyMessageDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int DemoSafetyMessageDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 4+basedesc->getFieldCount() : 4; } unsigned int DemoSafetyMessageDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISCOMPOUND, FD_ISCOMPOUND, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<4) ? fieldTypeFlags[field] : 0; } const char *DemoSafetyMessageDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "senderPos", "senderSpeed", "serial", "angle", }; return (field>=0 && field<4) ? fieldNames[field] : nullptr; } int DemoSafetyMessageDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "senderPos")==0) return base+0; if (fieldName[0]=='s' && strcmp(fieldName, "senderSpeed")==0) return base+1; if (fieldName[0]=='s' && strcmp(fieldName, "serial")==0) return base+2; if (fieldName[0]=='a' && strcmp(fieldName, "angle")==0) return base+3; return basedesc ? basedesc->findField(fieldName) : -1; } const char *DemoSafetyMessageDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "Coord", "Coord", "int", "float", }; return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr; } const char **DemoSafetyMessageDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *DemoSafetyMessageDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int DemoSafetyMessageDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp; switch (field) { default: return 0; } } const char *DemoSafetyMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp; switch (field) { default: return nullptr; } } std::string DemoSafetyMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp; switch (field) { case 0: {std::stringstream out; out << pp->getSenderPos(); return out.str();} case 1: {std::stringstream out; out << pp->getSenderSpeed(); return out.str();} case 2: return long2string(pp->getSerial()); case 3: return double2string(pp->getAngle()); default: return ""; } } bool DemoSafetyMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp; switch (field) { case 2: pp->setSerial(string2long(value)); return true; case 3: pp->setAngle(string2double(value)); return true; default: return false; } } const char *DemoSafetyMessageDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { case 0: return omnetpp::opp_typename(typeid(Coord)); case 1: return omnetpp::opp_typename(typeid(Coord)); default: return nullptr; }; } void *DemoSafetyMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp; switch (field) { case 0: return (void *)(&pp->getSenderPos()); break; case 1: return (void *)(&pp->getSenderSpeed()); break; default: return nullptr; } } } // namespace veins
16,569
30.6826
140
cc
null
AICP-main/veins/src/veins/modules/messages/DemoSafetyMessage_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoSafetyMessage.msg. // #ifndef __VEINS_DEMOSAFETYMESSAGE_M_H #define __VEINS_DEMOSAFETYMESSAGE_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif // cplusplus {{ #include "veins/base/utils/Coord.h" #include "veins/modules/messages/BaseFrame1609_4_m.h" #include "veins/base/utils/SimpleAddress.h" // }} namespace veins { /** * Class generated from <tt>veins/modules/messages/DemoSafetyMessage.msg:35</tt> by nedtool. * <pre> * packet DemoSafetyMessage extends BaseFrame1609_4 * { * Coord senderPos; * Coord senderSpeed; * int serial = 0; * double angle = 0; * } * </pre> */ class VEINS_API DemoSafetyMessage : public ::veins::BaseFrame1609_4 { protected: Coord senderPos; Coord senderSpeed; int serial; double angle; private: void copy(const DemoSafetyMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const DemoSafetyMessage&); public: DemoSafetyMessage(const char *name=nullptr, short kind=0); DemoSafetyMessage(const DemoSafetyMessage& other); virtual ~DemoSafetyMessage(); DemoSafetyMessage& operator=(const DemoSafetyMessage& other); virtual DemoSafetyMessage *dup() const override {return new DemoSafetyMessage(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual Coord& getSenderPos(); virtual const Coord& getSenderPos() const {return const_cast<DemoSafetyMessage*>(this)->getSenderPos();} virtual void setSenderPos(const Coord& senderPos); virtual Coord& getSenderSpeed(); virtual const Coord& getSenderSpeed() const {return const_cast<DemoSafetyMessage*>(this)->getSenderSpeed();} virtual void setSenderSpeed(const Coord& senderSpeed); virtual int getSerial() const; virtual void setSerial(int serial); virtual double getAngle() const; virtual void setAngle(double angle); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const DemoSafetyMessage& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, DemoSafetyMessage& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_DEMOSAFETYMESSAGE_M_H
2,883
29.357895
121
h
null
AICP-main/veins/src/veins/modules/messages/DemoServiceAdvertisement_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoServiceAdvertisement.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "DemoServiceAdvertisement_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(DemoServiceAdvertisment) DemoServiceAdvertisment::DemoServiceAdvertisment(const char *name, short kind) : ::veins::BaseFrame1609_4(name,kind) { this->targetChannel = 0; } DemoServiceAdvertisment::DemoServiceAdvertisment(const DemoServiceAdvertisment& other) : ::veins::BaseFrame1609_4(other) { copy(other); } DemoServiceAdvertisment::~DemoServiceAdvertisment() { } DemoServiceAdvertisment& DemoServiceAdvertisment::operator=(const DemoServiceAdvertisment& other) { if (this==&other) return *this; ::veins::BaseFrame1609_4::operator=(other); copy(other); return *this; } void DemoServiceAdvertisment::copy(const DemoServiceAdvertisment& other) { this->targetChannel = other.targetChannel; this->serviceDescription = other.serviceDescription; } void DemoServiceAdvertisment::parsimPack(omnetpp::cCommBuffer *b) const { ::veins::BaseFrame1609_4::parsimPack(b); doParsimPacking(b,this->targetChannel); doParsimPacking(b,this->serviceDescription); } void DemoServiceAdvertisment::parsimUnpack(omnetpp::cCommBuffer *b) { ::veins::BaseFrame1609_4::parsimUnpack(b); doParsimUnpacking(b,this->targetChannel); doParsimUnpacking(b,this->serviceDescription); } int DemoServiceAdvertisment::getTargetChannel() const { return this->targetChannel; } void DemoServiceAdvertisment::setTargetChannel(int targetChannel) { this->targetChannel = targetChannel; } const char * DemoServiceAdvertisment::getServiceDescription() const { return this->serviceDescription.c_str(); } void DemoServiceAdvertisment::setServiceDescription(const char * serviceDescription) { this->serviceDescription = serviceDescription; } class DemoServiceAdvertismentDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: DemoServiceAdvertismentDescriptor(); virtual ~DemoServiceAdvertismentDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(DemoServiceAdvertismentDescriptor) DemoServiceAdvertismentDescriptor::DemoServiceAdvertismentDescriptor() : omnetpp::cClassDescriptor("veins::DemoServiceAdvertisment", "veins::BaseFrame1609_4") { propertynames = nullptr; } DemoServiceAdvertismentDescriptor::~DemoServiceAdvertismentDescriptor() { delete[] propertynames; } bool DemoServiceAdvertismentDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<DemoServiceAdvertisment *>(obj)!=nullptr; } const char **DemoServiceAdvertismentDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *DemoServiceAdvertismentDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int DemoServiceAdvertismentDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 2+basedesc->getFieldCount() : 2; } unsigned int DemoServiceAdvertismentDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<2) ? fieldTypeFlags[field] : 0; } const char *DemoServiceAdvertismentDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "targetChannel", "serviceDescription", }; return (field>=0 && field<2) ? fieldNames[field] : nullptr; } int DemoServiceAdvertismentDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='t' && strcmp(fieldName, "targetChannel")==0) return base+0; if (fieldName[0]=='s' && strcmp(fieldName, "serviceDescription")==0) return base+1; return basedesc ? basedesc->findField(fieldName) : -1; } const char *DemoServiceAdvertismentDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "int", "string", }; return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr; } const char **DemoServiceAdvertismentDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *DemoServiceAdvertismentDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int DemoServiceAdvertismentDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp; switch (field) { default: return 0; } } const char *DemoServiceAdvertismentDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp; switch (field) { default: return nullptr; } } std::string DemoServiceAdvertismentDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp; switch (field) { case 0: return long2string(pp->getTargetChannel()); case 1: return oppstring2string(pp->getServiceDescription()); default: return ""; } } bool DemoServiceAdvertismentDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp; switch (field) { case 0: pp->setTargetChannel(string2long(value)); return true; case 1: pp->setServiceDescription((value)); return true; default: return false; } } const char *DemoServiceAdvertismentDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *DemoServiceAdvertismentDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace veins
15,878
31.943983
158
cc
null
AICP-main/veins/src/veins/modules/messages/DemoServiceAdvertisement_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoServiceAdvertisement.msg. // #ifndef __VEINS_DEMOSERVICEADVERTISEMENT_M_H #define __VEINS_DEMOSERVICEADVERTISEMENT_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif // cplusplus {{ #include "veins/base/utils/Coord.h" #include "veins/modules/messages/BaseFrame1609_4_m.h" // }} namespace veins { /** * Class generated from <tt>veins/modules/messages/DemoServiceAdvertisement.msg:33</tt> by nedtool. * <pre> * packet DemoServiceAdvertisment extends BaseFrame1609_4 * { * int targetChannel; * string serviceDescription; * } * </pre> */ class VEINS_API DemoServiceAdvertisment : public ::veins::BaseFrame1609_4 { protected: int targetChannel; ::omnetpp::opp_string serviceDescription; private: void copy(const DemoServiceAdvertisment& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const DemoServiceAdvertisment&); public: DemoServiceAdvertisment(const char *name=nullptr, short kind=0); DemoServiceAdvertisment(const DemoServiceAdvertisment& other); virtual ~DemoServiceAdvertisment(); DemoServiceAdvertisment& operator=(const DemoServiceAdvertisment& other); virtual DemoServiceAdvertisment *dup() const override {return new DemoServiceAdvertisment(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual int getTargetChannel() const; virtual void setTargetChannel(int targetChannel); virtual const char * getServiceDescription() const; virtual void setServiceDescription(const char * serviceDescription); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const DemoServiceAdvertisment& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, DemoServiceAdvertisment& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_DEMOSERVICEADVERTISEMENT_M_H
2,575
29.666667
121
h
null
AICP-main/veins/src/veins/modules/messages/Mac80211Ack_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Ack.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "Mac80211Ack_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(Mac80211Ack) Mac80211Ack::Mac80211Ack(const char *name, short kind) : ::veins::Mac80211Pkt(name,kind) { this->messageId = 0; } Mac80211Ack::Mac80211Ack(const Mac80211Ack& other) : ::veins::Mac80211Pkt(other) { copy(other); } Mac80211Ack::~Mac80211Ack() { } Mac80211Ack& Mac80211Ack::operator=(const Mac80211Ack& other) { if (this==&other) return *this; ::veins::Mac80211Pkt::operator=(other); copy(other); return *this; } void Mac80211Ack::copy(const Mac80211Ack& other) { this->messageId = other.messageId; } void Mac80211Ack::parsimPack(omnetpp::cCommBuffer *b) const { ::veins::Mac80211Pkt::parsimPack(b); doParsimPacking(b,this->messageId); } void Mac80211Ack::parsimUnpack(omnetpp::cCommBuffer *b) { ::veins::Mac80211Pkt::parsimUnpack(b); doParsimUnpacking(b,this->messageId); } unsigned long Mac80211Ack::getMessageId() const { return this->messageId; } void Mac80211Ack::setMessageId(unsigned long messageId) { this->messageId = messageId; } class Mac80211AckDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: Mac80211AckDescriptor(); virtual ~Mac80211AckDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(Mac80211AckDescriptor) Mac80211AckDescriptor::Mac80211AckDescriptor() : omnetpp::cClassDescriptor("veins::Mac80211Ack", "veins::Mac80211Pkt") { propertynames = nullptr; } Mac80211AckDescriptor::~Mac80211AckDescriptor() { delete[] propertynames; } bool Mac80211AckDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<Mac80211Ack *>(obj)!=nullptr; } const char **Mac80211AckDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *Mac80211AckDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int Mac80211AckDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 1+basedesc->getFieldCount() : 1; } unsigned int Mac80211AckDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, }; return (field>=0 && field<1) ? fieldTypeFlags[field] : 0; } const char *Mac80211AckDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "messageId", }; return (field>=0 && field<1) ? fieldNames[field] : nullptr; } int Mac80211AckDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='m' && strcmp(fieldName, "messageId")==0) return base+0; return basedesc ? basedesc->findField(fieldName) : -1; } const char *Mac80211AckDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "unsigned long", }; return (field>=0 && field<1) ? fieldTypeStrings[field] : nullptr; } const char **Mac80211AckDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *Mac80211AckDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int Mac80211AckDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp; switch (field) { default: return 0; } } const char *Mac80211AckDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp; switch (field) { default: return nullptr; } } std::string Mac80211AckDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp; switch (field) { case 0: return ulong2string(pp->getMessageId()); default: return ""; } } bool Mac80211AckDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp; switch (field) { case 0: pp->setMessageId(string2ulong(value)); return true; default: return false; } } const char *Mac80211AckDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *Mac80211AckDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace veins
14,454
30.220302
128
cc
null
AICP-main/veins/src/veins/modules/messages/Mac80211Ack_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Ack.msg. // #ifndef __VEINS_MAC80211ACK_M_H #define __VEINS_MAC80211ACK_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif // cplusplus {{ #include "veins/modules/messages/Mac80211Pkt_m.h" // }} namespace veins { /** * Class generated from <tt>veins/modules/messages/Mac80211Ack.msg:31</tt> by nedtool. * <pre> * packet Mac80211Ack extends Mac80211Pkt * { * unsigned long messageId; // The ID of the aknowledged packet * } * </pre> */ class VEINS_API Mac80211Ack : public ::veins::Mac80211Pkt { protected: unsigned long messageId; private: void copy(const Mac80211Ack& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const Mac80211Ack&); public: Mac80211Ack(const char *name=nullptr, short kind=0); Mac80211Ack(const Mac80211Ack& other); virtual ~Mac80211Ack(); Mac80211Ack& operator=(const Mac80211Ack& other); virtual Mac80211Ack *dup() const override {return new Mac80211Ack(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual unsigned long getMessageId() const; virtual void setMessageId(unsigned long messageId); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const Mac80211Ack& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, Mac80211Ack& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_MAC80211ACK_M_H
2,145
26.164557
121
h
null
AICP-main/veins/src/veins/modules/messages/Mac80211Pkt_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Pkt.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "Mac80211Pkt_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(Mac80211Pkt) Mac80211Pkt::Mac80211Pkt(const char *name, short kind) : ::veins::MacPkt(name,kind) { this->address3 = 0; this->address4 = 0; this->fragmentation = 0; this->informationDS = 0; this->sequenceControl = 0; this->retry = false; this->duration = 0; } Mac80211Pkt::Mac80211Pkt(const Mac80211Pkt& other) : ::veins::MacPkt(other) { copy(other); } Mac80211Pkt::~Mac80211Pkt() { } Mac80211Pkt& Mac80211Pkt::operator=(const Mac80211Pkt& other) { if (this==&other) return *this; ::veins::MacPkt::operator=(other); copy(other); return *this; } void Mac80211Pkt::copy(const Mac80211Pkt& other) { this->address3 = other.address3; this->address4 = other.address4; this->fragmentation = other.fragmentation; this->informationDS = other.informationDS; this->sequenceControl = other.sequenceControl; this->retry = other.retry; this->duration = other.duration; } void Mac80211Pkt::parsimPack(omnetpp::cCommBuffer *b) const { ::veins::MacPkt::parsimPack(b); doParsimPacking(b,this->address3); doParsimPacking(b,this->address4); doParsimPacking(b,this->fragmentation); doParsimPacking(b,this->informationDS); doParsimPacking(b,this->sequenceControl); doParsimPacking(b,this->retry); doParsimPacking(b,this->duration); } void Mac80211Pkt::parsimUnpack(omnetpp::cCommBuffer *b) { ::veins::MacPkt::parsimUnpack(b); doParsimUnpacking(b,this->address3); doParsimUnpacking(b,this->address4); doParsimUnpacking(b,this->fragmentation); doParsimUnpacking(b,this->informationDS); doParsimUnpacking(b,this->sequenceControl); doParsimUnpacking(b,this->retry); doParsimUnpacking(b,this->duration); } int Mac80211Pkt::getAddress3() const { return this->address3; } void Mac80211Pkt::setAddress3(int address3) { this->address3 = address3; } int Mac80211Pkt::getAddress4() const { return this->address4; } void Mac80211Pkt::setAddress4(int address4) { this->address4 = address4; } int Mac80211Pkt::getFragmentation() const { return this->fragmentation; } void Mac80211Pkt::setFragmentation(int fragmentation) { this->fragmentation = fragmentation; } int Mac80211Pkt::getInformationDS() const { return this->informationDS; } void Mac80211Pkt::setInformationDS(int informationDS) { this->informationDS = informationDS; } int Mac80211Pkt::getSequenceControl() const { return this->sequenceControl; } void Mac80211Pkt::setSequenceControl(int sequenceControl) { this->sequenceControl = sequenceControl; } bool Mac80211Pkt::getRetry() const { return this->retry; } void Mac80211Pkt::setRetry(bool retry) { this->retry = retry; } ::omnetpp::simtime_t Mac80211Pkt::getDuration() const { return this->duration; } void Mac80211Pkt::setDuration(::omnetpp::simtime_t duration) { this->duration = duration; } class Mac80211PktDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: Mac80211PktDescriptor(); virtual ~Mac80211PktDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(Mac80211PktDescriptor) Mac80211PktDescriptor::Mac80211PktDescriptor() : omnetpp::cClassDescriptor("veins::Mac80211Pkt", "veins::MacPkt") { propertynames = nullptr; } Mac80211PktDescriptor::~Mac80211PktDescriptor() { delete[] propertynames; } bool Mac80211PktDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<Mac80211Pkt *>(obj)!=nullptr; } const char **Mac80211PktDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *Mac80211PktDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int Mac80211PktDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 7+basedesc->getFieldCount() : 7; } unsigned int Mac80211PktDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<7) ? fieldTypeFlags[field] : 0; } const char *Mac80211PktDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "address3", "address4", "fragmentation", "informationDS", "sequenceControl", "retry", "duration", }; return (field>=0 && field<7) ? fieldNames[field] : nullptr; } int Mac80211PktDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='a' && strcmp(fieldName, "address3")==0) return base+0; if (fieldName[0]=='a' && strcmp(fieldName, "address4")==0) return base+1; if (fieldName[0]=='f' && strcmp(fieldName, "fragmentation")==0) return base+2; if (fieldName[0]=='i' && strcmp(fieldName, "informationDS")==0) return base+3; if (fieldName[0]=='s' && strcmp(fieldName, "sequenceControl")==0) return base+4; if (fieldName[0]=='r' && strcmp(fieldName, "retry")==0) return base+5; if (fieldName[0]=='d' && strcmp(fieldName, "duration")==0) return base+6; return basedesc ? basedesc->findField(fieldName) : -1; } const char *Mac80211PktDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "int", "int", "int", "int", "int", "bool", "simtime_t", }; return (field>=0 && field<7) ? fieldTypeStrings[field] : nullptr; } const char **Mac80211PktDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *Mac80211PktDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int Mac80211PktDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp; switch (field) { default: return 0; } } const char *Mac80211PktDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp; switch (field) { default: return nullptr; } } std::string Mac80211PktDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp; switch (field) { case 0: return long2string(pp->getAddress3()); case 1: return long2string(pp->getAddress4()); case 2: return long2string(pp->getFragmentation()); case 3: return long2string(pp->getInformationDS()); case 4: return long2string(pp->getSequenceControl()); case 5: return bool2string(pp->getRetry()); case 6: return simtime2string(pp->getDuration()); default: return ""; } } bool Mac80211PktDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp; switch (field) { case 0: pp->setAddress3(string2long(value)); return true; case 1: pp->setAddress4(string2long(value)); return true; case 2: pp->setFragmentation(string2long(value)); return true; case 3: pp->setInformationDS(string2long(value)); return true; case 4: pp->setSequenceControl(string2long(value)); return true; case 5: pp->setRetry(string2bool(value)); return true; case 6: pp->setDuration(string2simtime(value)); return true; default: return false; } } const char *Mac80211PktDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *Mac80211PktDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace veins
17,922
29.74271
128
cc
null
AICP-main/veins/src/veins/modules/messages/Mac80211Pkt_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Pkt.msg. // #ifndef __VEINS_MAC80211PKT_M_H #define __VEINS_MAC80211PKT_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif // cplusplus {{ #include "veins/base/messages/MacPkt_m.h" // }} namespace veins { /** * Class generated from <tt>veins/modules/messages/Mac80211Pkt.msg:39</tt> by nedtool. * <pre> * // * // Defines all fields of an 802.11 MAC frame * // * packet Mac80211Pkt extends MacPkt * { * int address3; * int address4; * int fragmentation; //part of the Frame Control field * int informationDS; //part of the Frame Control field * int sequenceControl; * bool retry; * simtime_t duration; //the expected remaining duration the current transaction * } * </pre> */ class VEINS_API Mac80211Pkt : public ::veins::MacPkt { protected: int address3; int address4; int fragmentation; int informationDS; int sequenceControl; bool retry; ::omnetpp::simtime_t duration; private: void copy(const Mac80211Pkt& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const Mac80211Pkt&); public: Mac80211Pkt(const char *name=nullptr, short kind=0); Mac80211Pkt(const Mac80211Pkt& other); virtual ~Mac80211Pkt(); Mac80211Pkt& operator=(const Mac80211Pkt& other); virtual Mac80211Pkt *dup() const override {return new Mac80211Pkt(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual int getAddress3() const; virtual void setAddress3(int address3); virtual int getAddress4() const; virtual void setAddress4(int address4); virtual int getFragmentation() const; virtual void setFragmentation(int fragmentation); virtual int getInformationDS() const; virtual void setInformationDS(int informationDS); virtual int getSequenceControl() const; virtual void setSequenceControl(int sequenceControl); virtual bool getRetry() const; virtual void setRetry(bool retry); virtual ::omnetpp::simtime_t getDuration() const; virtual void setDuration(::omnetpp::simtime_t duration); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const Mac80211Pkt& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, Mac80211Pkt& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_MAC80211PKT_M_H
3,084
28.103774
121
h
null
AICP-main/veins/src/veins/modules/messages/PhyControlMessage_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/PhyControlMessage.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "PhyControlMessage_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(PhyControlMessage) PhyControlMessage::PhyControlMessage(const char *name, short kind) : ::omnetpp::cMessage(name,kind) { this->mcs = -1; this->txPower_mW = -1; } PhyControlMessage::PhyControlMessage(const PhyControlMessage& other) : ::omnetpp::cMessage(other) { copy(other); } PhyControlMessage::~PhyControlMessage() { } PhyControlMessage& PhyControlMessage::operator=(const PhyControlMessage& other) { if (this==&other) return *this; ::omnetpp::cMessage::operator=(other); copy(other); return *this; } void PhyControlMessage::copy(const PhyControlMessage& other) { this->mcs = other.mcs; this->txPower_mW = other.txPower_mW; } void PhyControlMessage::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cMessage::parsimPack(b); doParsimPacking(b,this->mcs); doParsimPacking(b,this->txPower_mW); } void PhyControlMessage::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cMessage::parsimUnpack(b); doParsimUnpacking(b,this->mcs); doParsimUnpacking(b,this->txPower_mW); } int PhyControlMessage::getMcs() const { return this->mcs; } void PhyControlMessage::setMcs(int mcs) { this->mcs = mcs; } double PhyControlMessage::getTxPower_mW() const { return this->txPower_mW; } void PhyControlMessage::setTxPower_mW(double txPower_mW) { this->txPower_mW = txPower_mW; } class PhyControlMessageDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: PhyControlMessageDescriptor(); virtual ~PhyControlMessageDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(PhyControlMessageDescriptor) PhyControlMessageDescriptor::PhyControlMessageDescriptor() : omnetpp::cClassDescriptor("veins::PhyControlMessage", "omnetpp::cMessage") { propertynames = nullptr; } PhyControlMessageDescriptor::~PhyControlMessageDescriptor() { delete[] propertynames; } bool PhyControlMessageDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<PhyControlMessage *>(obj)!=nullptr; } const char **PhyControlMessageDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *PhyControlMessageDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int PhyControlMessageDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 2+basedesc->getFieldCount() : 2; } unsigned int PhyControlMessageDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<2) ? fieldTypeFlags[field] : 0; } const char *PhyControlMessageDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "mcs", "txPower_mW", }; return (field>=0 && field<2) ? fieldNames[field] : nullptr; } int PhyControlMessageDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='m' && strcmp(fieldName, "mcs")==0) return base+0; if (fieldName[0]=='t' && strcmp(fieldName, "txPower_mW")==0) return base+1; return basedesc ? basedesc->findField(fieldName) : -1; } const char *PhyControlMessageDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "int", "double", }; return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr; } const char **PhyControlMessageDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *PhyControlMessageDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int PhyControlMessageDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp; switch (field) { default: return 0; } } const char *PhyControlMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp; switch (field) { default: return nullptr; } } std::string PhyControlMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp; switch (field) { case 0: return long2string(pp->getMcs()); case 1: return double2string(pp->getTxPower_mW()); default: return ""; } } bool PhyControlMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp; switch (field) { case 0: pp->setMcs(string2long(value)); return true; case 1: pp->setTxPower_mW(string2double(value)); return true; default: return false; } } const char *PhyControlMessageDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *PhyControlMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace veins
15,260
30.596273
135
cc
null
AICP-main/veins/src/veins/modules/messages/PhyControlMessage_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/PhyControlMessage.msg. // #ifndef __VEINS_PHYCONTROLMESSAGE_M_H #define __VEINS_PHYCONTROLMESSAGE_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif namespace veins { /** * Class generated from <tt>veins/modules/messages/PhyControlMessage.msg:29</tt> by nedtool. * <pre> * // * // Defines a control message that can be associated with a MAC frame to set * // transmission power and datarate on a per packet basis * // * message PhyControlMessage * { * //modulation and coding scheme to be used (see enum TxMCS in ConstsPhy.h) * int mcs = -1; * //transmission power to be used in mW * double txPower_mW = -1; * } * </pre> */ class VEINS_API PhyControlMessage : public ::omnetpp::cMessage { protected: int mcs; double txPower_mW; private: void copy(const PhyControlMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const PhyControlMessage&); public: PhyControlMessage(const char *name=nullptr, short kind=0); PhyControlMessage(const PhyControlMessage& other); virtual ~PhyControlMessage(); PhyControlMessage& operator=(const PhyControlMessage& other); virtual PhyControlMessage *dup() const override {return new PhyControlMessage(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual int getMcs() const; virtual void setMcs(int mcs); virtual double getTxPower_mW() const; virtual void setTxPower_mW(double txPower_mW); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const PhyControlMessage& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, PhyControlMessage& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_PHYCONTROLMESSAGE_M_H
2,485
28.247059
121
h
null
AICP-main/veins/src/veins/modules/messages/TraCITrafficLightMessage_m.cc
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/TraCITrafficLightMessage.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "TraCITrafficLightMessage_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace veins { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } EXECUTE_ON_STARTUP( omnetpp::cEnum *e = omnetpp::cEnum::find("veins::TrafficLightAtrributeType"); if (!e) omnetpp::enums.getInstance()->add(e = new omnetpp::cEnum("veins::TrafficLightAtrributeType")); e->insert(NONE, "NONE"); e->insert(LOGICID, "LOGICID"); e->insert(PHASEID, "PHASEID"); e->insert(SWITCHTIME, "SWITCHTIME"); e->insert(STATE, "STATE"); ) EXECUTE_ON_STARTUP( omnetpp::cEnum *e = omnetpp::cEnum::find("veins::TrafficLightChangeSource"); if (!e) omnetpp::enums.getInstance()->add(e = new omnetpp::cEnum("veins::TrafficLightChangeSource")); e->insert(UNKNOWN, "UNKNOWN"); e->insert(SUMO, "SUMO"); e->insert(LOGIC, "LOGIC"); e->insert(RSU, "RSU"); ) Register_Class(TraCITrafficLightMessage) TraCITrafficLightMessage::TraCITrafficLightMessage(const char *name, short kind) : ::omnetpp::cMessage(name,kind) { this->changedAttribute = 0; this->changeSource = 0; } TraCITrafficLightMessage::TraCITrafficLightMessage(const TraCITrafficLightMessage& other) : ::omnetpp::cMessage(other) { copy(other); } TraCITrafficLightMessage::~TraCITrafficLightMessage() { } TraCITrafficLightMessage& TraCITrafficLightMessage::operator=(const TraCITrafficLightMessage& other) { if (this==&other) return *this; ::omnetpp::cMessage::operator=(other); copy(other); return *this; } void TraCITrafficLightMessage::copy(const TraCITrafficLightMessage& other) { this->tlId = other.tlId; this->changedAttribute = other.changedAttribute; this->oldValue = other.oldValue; this->newValue = other.newValue; this->changeSource = other.changeSource; } void TraCITrafficLightMessage::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cMessage::parsimPack(b); doParsimPacking(b,this->tlId); doParsimPacking(b,this->changedAttribute); doParsimPacking(b,this->oldValue); doParsimPacking(b,this->newValue); doParsimPacking(b,this->changeSource); } void TraCITrafficLightMessage::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cMessage::parsimUnpack(b); doParsimUnpacking(b,this->tlId); doParsimUnpacking(b,this->changedAttribute); doParsimUnpacking(b,this->oldValue); doParsimUnpacking(b,this->newValue); doParsimUnpacking(b,this->changeSource); } const char * TraCITrafficLightMessage::getTlId() const { return this->tlId.c_str(); } void TraCITrafficLightMessage::setTlId(const char * tlId) { this->tlId = tlId; } int TraCITrafficLightMessage::getChangedAttribute() const { return this->changedAttribute; } void TraCITrafficLightMessage::setChangedAttribute(int changedAttribute) { this->changedAttribute = changedAttribute; } const char * TraCITrafficLightMessage::getOldValue() const { return this->oldValue.c_str(); } void TraCITrafficLightMessage::setOldValue(const char * oldValue) { this->oldValue = oldValue; } const char * TraCITrafficLightMessage::getNewValue() const { return this->newValue.c_str(); } void TraCITrafficLightMessage::setNewValue(const char * newValue) { this->newValue = newValue; } int TraCITrafficLightMessage::getChangeSource() const { return this->changeSource; } void TraCITrafficLightMessage::setChangeSource(int changeSource) { this->changeSource = changeSource; } class TraCITrafficLightMessageDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: TraCITrafficLightMessageDescriptor(); virtual ~TraCITrafficLightMessageDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(TraCITrafficLightMessageDescriptor) TraCITrafficLightMessageDescriptor::TraCITrafficLightMessageDescriptor() : omnetpp::cClassDescriptor("veins::TraCITrafficLightMessage", "omnetpp::cMessage") { propertynames = nullptr; } TraCITrafficLightMessageDescriptor::~TraCITrafficLightMessageDescriptor() { delete[] propertynames; } bool TraCITrafficLightMessageDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<TraCITrafficLightMessage *>(obj)!=nullptr; } const char **TraCITrafficLightMessageDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *TraCITrafficLightMessageDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int TraCITrafficLightMessageDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 5+basedesc->getFieldCount() : 5; } unsigned int TraCITrafficLightMessageDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<5) ? fieldTypeFlags[field] : 0; } const char *TraCITrafficLightMessageDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "tlId", "changedAttribute", "oldValue", "newValue", "changeSource", }; return (field>=0 && field<5) ? fieldNames[field] : nullptr; } int TraCITrafficLightMessageDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='t' && strcmp(fieldName, "tlId")==0) return base+0; if (fieldName[0]=='c' && strcmp(fieldName, "changedAttribute")==0) return base+1; if (fieldName[0]=='o' && strcmp(fieldName, "oldValue")==0) return base+2; if (fieldName[0]=='n' && strcmp(fieldName, "newValue")==0) return base+3; if (fieldName[0]=='c' && strcmp(fieldName, "changeSource")==0) return base+4; return basedesc ? basedesc->findField(fieldName) : -1; } const char *TraCITrafficLightMessageDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "int", "string", "string", "int", }; return (field>=0 && field<5) ? fieldTypeStrings[field] : nullptr; } const char **TraCITrafficLightMessageDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { case 1: { static const char *names[] = { "enum", nullptr }; return names; } case 4: { static const char *names[] = { "enum", nullptr }; return names; } default: return nullptr; } } const char *TraCITrafficLightMessageDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { case 1: if (!strcmp(propertyname,"enum")) return "veins::TrafficLightAtrributeType"; return nullptr; case 4: if (!strcmp(propertyname,"enum")) return "veins::TrafficLightChangeSource"; return nullptr; default: return nullptr; } } int TraCITrafficLightMessageDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp; switch (field) { default: return 0; } } const char *TraCITrafficLightMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp; switch (field) { default: return nullptr; } } std::string TraCITrafficLightMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getTlId()); case 1: return enum2string(pp->getChangedAttribute(), "veins::TrafficLightAtrributeType"); case 2: return oppstring2string(pp->getOldValue()); case 3: return oppstring2string(pp->getNewValue()); case 4: return enum2string(pp->getChangeSource(), "veins::TrafficLightChangeSource"); default: return ""; } } bool TraCITrafficLightMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp; switch (field) { case 0: pp->setTlId((value)); return true; case 1: pp->setChangedAttribute((veins::TrafficLightAtrributeType)string2enum(value, "veins::TrafficLightAtrributeType")); return true; case 2: pp->setOldValue((value)); return true; case 3: pp->setNewValue((value)); return true; case 4: pp->setChangeSource((veins::TrafficLightChangeSource)string2enum(value, "veins::TrafficLightChangeSource")); return true; default: return false; } } const char *TraCITrafficLightMessageDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *TraCITrafficLightMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp; switch (field) { default: return nullptr; } } } // namespace veins
18,952
32.076789
156
cc
null
AICP-main/veins/src/veins/modules/messages/TraCITrafficLightMessage_m.h
// // Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/TraCITrafficLightMessage.msg. // #ifndef __VEINS_TRACITRAFFICLIGHTMESSAGE_M_H #define __VEINS_TRACITRAFFICLIGHTMESSAGE_M_H #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0505 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef VEINS_API # if defined(VEINS_EXPORT) # define VEINS_API OPP_DLLEXPORT # elif defined(VEINS_IMPORT) # define VEINS_API OPP_DLLIMPORT # else # define VEINS_API # endif #endif namespace veins { /** * Enum generated from <tt>veins/modules/messages/TraCITrafficLightMessage.msg:26</tt> by nedtool. * <pre> * enum TrafficLightAtrributeType * { * NONE = 0; * LOGICID = 1; * PHASEID = 2; * SWITCHTIME = 3; * STATE = 4; * } * </pre> */ enum TrafficLightAtrributeType { NONE = 0, LOGICID = 1, PHASEID = 2, SWITCHTIME = 3, STATE = 4 }; /** * Enum generated from <tt>veins/modules/messages/TraCITrafficLightMessage.msg:34</tt> by nedtool. * <pre> * enum TrafficLightChangeSource * { * UNKNOWN = 0; * SUMO = 1; * LOGIC = 2; * RSU = 3;//If an RSU tries to change the values * } * </pre> */ enum TrafficLightChangeSource { UNKNOWN = 0, SUMO = 1, LOGIC = 2, RSU = 3 }; /** * Class generated from <tt>veins/modules/messages/TraCITrafficLightMessage.msg:42</tt> by nedtool. * <pre> * // NOTE: Currently only supports changes of the IDs (due to variation in field types) * message TraCITrafficLightMessage * { * // traffic light id * string tlId; * // what field/attrbute of the traffic light changed? * int changedAttribute \@enum(TrafficLightAtrributeType); * // value before the change * string oldValue; * // value that is to be set / was newly set * string newValue; * // where did the change originate * int changeSource \@enum(TrafficLightChangeSource); * } * </pre> */ class VEINS_API TraCITrafficLightMessage : public ::omnetpp::cMessage { protected: ::omnetpp::opp_string tlId; int changedAttribute; ::omnetpp::opp_string oldValue; ::omnetpp::opp_string newValue; int changeSource; private: void copy(const TraCITrafficLightMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const TraCITrafficLightMessage&); public: TraCITrafficLightMessage(const char *name=nullptr, short kind=0); TraCITrafficLightMessage(const TraCITrafficLightMessage& other); virtual ~TraCITrafficLightMessage(); TraCITrafficLightMessage& operator=(const TraCITrafficLightMessage& other); virtual TraCITrafficLightMessage *dup() const override {return new TraCITrafficLightMessage(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual const char * getTlId() const; virtual void setTlId(const char * tlId); virtual int getChangedAttribute() const; virtual void setChangedAttribute(int changedAttribute); virtual const char * getOldValue() const; virtual void setOldValue(const char * oldValue); virtual const char * getNewValue() const; virtual void setNewValue(const char * newValue); virtual int getChangeSource() const; virtual void setChangeSource(int changeSource); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const TraCITrafficLightMessage& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, TraCITrafficLightMessage& obj) {obj.parsimUnpack(b);} } // namespace veins #endif // ifndef __VEINS_TRACITRAFFICLIGHTMESSAGE_M_H
3,978
28.043796
121
h
null
AICP-main/veins/src/veins/modules/mobility/LinearMobility.cc
// // Copyright (C) 2005 Emin Ilker Cetinbas // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: Emin Ilker Cetinbas (niw3_at_yahoo_d0t_com) #include "veins/modules/mobility/LinearMobility.h" #include "veins/veins.h" using namespace veins; Define_Module(veins::LinearMobility); void LinearMobility::initialize(int stage) { BaseMobility::initialize(stage); EV_TRACE << "initializing LinearMobility stage " << stage << endl; if (stage == 0) { move.setSpeed(par("speed").doubleValue()); acceleration = par("acceleration"); angle = par("angle"); angle = fmod(angle, 360); } else if (stage == 1) { stepTarget = move.getStartPos(); } } void LinearMobility::fixIfHostGetsOutside() { Coord dummy = Coord::ZERO; handleIfOutside(WRAP, stepTarget, dummy, dummy, angle); } /** * Move the host if the destination is not reached yet. Otherwise * calculate a new random position */ void LinearMobility::makeMove() { EV_TRACE << "start makeMove " << move.info() << endl; move.setStart(stepTarget, simTime()); stepTarget.x = (move.getStartPos().x + move.getSpeed() * cos(M_PI * angle / 180) * SIMTIME_DBL(updateInterval)); stepTarget.y = (move.getStartPos().y + move.getSpeed() * sin(M_PI * angle / 180) * SIMTIME_DBL(updateInterval)); move.setDirectionByTarget(stepTarget); EV_TRACE << "new stepTarget: " << stepTarget.info() << endl; // accelerate move.setSpeed(move.getSpeed() + acceleration * SIMTIME_DBL(updateInterval)); fixIfHostGetsOutside(); }
2,357
29.230769
116
cc
null
AICP-main/veins/src/veins/modules/mobility/LinearMobility.h
// // Copyright (C) 2005 Emin Ilker Cetinbas // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // author: Emin Ilker Cetinbas (niw3_at_yahoo_d0t_com) // part of: framework implementation developed by tkn #pragma once #include "veins/base/modules/BaseMobility.h" namespace veins { /** * @brief Linear movement model. See NED file for more info. * * This mobility module expects a torus as playground ("useTorus" * Parameter of BaseWorldUtility module). * * NOTE: Does not yet support 3-dimensional movement. * @ingroup mobility * @author Emin Ilker Cetinbas */ class VEINS_API LinearMobility : public BaseMobility { protected: double angle; ///< angle of linear motion double acceleration; ///< acceleration of linear motion /** @brief always stores the last step for position display update */ Coord stepTarget; public: /** @brief Initializes mobility model parameters.*/ void initialize(int) override; protected: /** @brief Move the host*/ void makeMove() override; void fixIfHostGetsOutside() override; }; } // namespace veins
1,878
29.306452
76
h
null
AICP-main/veins/src/veins/modules/mobility/traci/ParBuffer.h
// // Copyright (C) 2019 Michele Segata <segata@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <cstddef> #include <string> #include <sstream> namespace veins { class VEINS_API ParBuffer { public: ParBuffer() : SEP(':') { } ParBuffer(std::string buf) : SEP(':') { inBuffer = buf; } template <typename T> ParBuffer& operator<<(const T& v) { if (outBuffer.str().length() == 0) outBuffer << v; else outBuffer << SEP << v; return *this; } std::string next() { std::string value; size_t sep; if (inBuffer.size() == 0) return ""; sep = inBuffer.find(SEP); if (sep == std::string::npos) { value = inBuffer; inBuffer = ""; } else { value = inBuffer.substr(0, sep); inBuffer = inBuffer.substr(sep + 1); } return value; } ParBuffer& operator>>(double& v) { std::string value = next(); sscanf(value.c_str(), "%lf", &v); return *this; } ParBuffer& operator>>(int& v) { std::string value = next(); sscanf(value.c_str(), "%d", &v); return *this; } ParBuffer& operator>>(std::string& v) { v = next(); return *this; } void set(std::string buf) { inBuffer = buf; } void clear() { outBuffer.clear(); } std::string str() const { return outBuffer.str(); } private: const char SEP; std::stringstream outBuffer; std::string inBuffer; }; } // namespace veins
2,488
21.423423
76
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIBuffer.cc
// // Copyright (C) 2006 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/mobility/traci/TraCIBuffer.h" #include "veins/modules/mobility/traci/TraCIConstants.h" #include "veins/modules/mobility/traci/TraCICoord.h" #include <iomanip> #include <sstream> using namespace veins::TraCIConstants; namespace veins { bool TraCIBuffer::timeAsDouble = true; TraCIBuffer::TraCIBuffer() : buf() { buf_index = 0; } TraCIBuffer::TraCIBuffer(std::string buf) : buf(buf) { buf_index = 0; } bool TraCIBuffer::eof() const { return buf_index == buf.length(); } void TraCIBuffer::set(std::string buf) { this->buf = buf; buf_index = 0; } void TraCIBuffer::clear() { set(""); } std::string TraCIBuffer::str() const { return buf; } template <> std::vector<std::string> TraCIBuffer::readTypeChecked(int expectedTraCIType) { ASSERT(read<uint8_t>() == static_cast<uint8_t>(expectedTraCIType)); int32_t nrOfElements = read<uint8_t>(); std::vector<std::string> result; result.reserve(nrOfElements); for (int32_t i = 0; i < nrOfElements; ++i) { result.emplace_back(read<std::string>()); } return result; } std::string TraCIBuffer::hexStr() const { std::stringstream ss; for (std::string::const_iterator i = buf.begin() + buf_index; i != buf.end(); ++i) { if (i != buf.begin()) ss << " "; ss << std::hex << std::setw(2) << std::setfill('0') << (int) (uint8_t) *i; } return ss.str(); } template <> void TraCIBuffer::write(std::string inv) { uint32_t length = inv.length(); write<uint32_t>(length); for (size_t i = 0; i < length; ++i) write<char>(inv[i]); } template <> std::string TraCIBuffer::read() { uint32_t length = read<uint32_t>(); if (length == 0) return std::string(); char obuf[length + 1]; for (size_t i = 0; i < length; ++i) read<char>(obuf[i]); obuf[length] = 0; return std::string(obuf, length); } template <> void TraCIBuffer::write(TraCICoord inv) { write<uint8_t>(POSITION_2D); write<double>(inv.x); write<double>(inv.y); } template <> TraCICoord TraCIBuffer::read() { uint8_t posType = read<uint8_t>(); ASSERT(posType == POSITION_2D); TraCICoord p; p.x = read<double>(); p.y = read<double>(); return p; } template <> void TraCIBuffer::write(simtime_t o) { if (timeAsDouble) { double d = o.dbl(); write<double>(d); } else { uint32_t i = o.inUnit(SIMTIME_MS); write<uint32_t>(i); } } template <> simtime_t TraCIBuffer::read() { if (timeAsDouble) { double d = read<double>(); simtime_t o = d; return o; } else { uint32_t i = read<uint32_t>(); simtime_t o = SimTime(i, SIMTIME_MS); return o; } } bool VEINS_API isBigEndian() { short a = 0x0102; unsigned char* p_a = reinterpret_cast<unsigned char*>(&a); return (p_a[0] == 0x01); } } // namespace veins
3,810
21.28655
88
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIBuffer.h
// // Copyright (C) 2006 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <cstddef> #include <string> #include "veins/veins.h" #include "veins/modules/mobility/traci/TraCIConstants.h" namespace veins { struct TraCICoord; bool VEINS_API isBigEndian(); /** * Byte-buffer that stores values in TraCI byte-order */ class VEINS_API TraCIBuffer { public: TraCIBuffer(); TraCIBuffer(std::string buf); template <typename T> T read() { T buf_to_return; unsigned char* p_buf_to_return = reinterpret_cast<unsigned char*>(&buf_to_return); if (isBigEndian()) { for (size_t i = 0; i < sizeof(buf_to_return); ++i) { if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer"); p_buf_to_return[i] = buf[buf_index++]; } } else { for (size_t i = 0; i < sizeof(buf_to_return); ++i) { if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer"); p_buf_to_return[sizeof(buf_to_return) - 1 - i] = buf[buf_index++]; } } return buf_to_return; } template <typename T> void write(T inv) { unsigned char* p_buf_to_send = reinterpret_cast<unsigned char*>(&inv); if (isBigEndian()) { for (size_t i = 0; i < sizeof(inv); ++i) { buf += p_buf_to_send[i]; } } else { for (size_t i = 0; i < sizeof(inv); ++i) { buf += p_buf_to_send[sizeof(inv) - 1 - i]; } } } void readBuffer(unsigned char* buffer, size_t size) { if (isBigEndian()) { for (size_t i = 0; i < size; ++i) { if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer"); buffer[i] = buf[buf_index++]; } } else { for (size_t i = 0; i < size; ++i) { if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer"); buffer[size - 1 - i] = buf[buf_index++]; } } } template <typename T> T read(T& out) { out = read<T>(); return out; } template <typename T> TraCIBuffer& operator>>(T& out) { out = read<T>(); return *this; } template <typename T> TraCIBuffer& operator<<(const T& inv) { write(inv); return *this; } /** * @brief * read and check type, then read and return an item from the buffer */ template <typename T> T readTypeChecked(int expectedTraCIType) { uint8_t read_type(read<uint8_t>()); ASSERT(read_type == static_cast<uint8_t>(expectedTraCIType)); return read<T>(); } bool eof() const; void set(std::string buf); void clear(); std::string str() const; std::string hexStr() const; static void setTimeType(uint8_t val) { if (val != TraCIConstants::TYPE_INTEGER && val != TraCIConstants::TYPE_DOUBLE) { throw cRuntimeError("Invalid time data type"); } timeAsDouble = val == TraCIConstants::TYPE_DOUBLE; } private: std::string buf; size_t buf_index; static bool timeAsDouble; }; template <> std::vector<std::string> TraCIBuffer::readTypeChecked(int expectedTraCIType); template <> void VEINS_API TraCIBuffer::write(std::string inv); template <> void TraCIBuffer::write(TraCICoord inv); template <> std::string VEINS_API TraCIBuffer::read(); template <> TraCICoord TraCIBuffer::read(); template <> void TraCIBuffer::write(simtime_t o); template <> simtime_t TraCIBuffer::read(); } // namespace veins
4,581
25.952941
92
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIColor.cc
// // Copyright (C) 2006-2011 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/mobility/traci/TraCIColor.h" using veins::TraCIColor; TraCIColor::TraCIColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) : red(red) , green(green) , blue(blue) , alpha(alpha) { } TraCIColor TraCIColor::fromTkColor(std::string tkColorName) { if (tkColorName == "alice blue") return TraCIColor(240, 248, 255, 255); if (tkColorName == "AliceBlue") return TraCIColor(240, 248, 255, 255); if (tkColorName == "antique white") return TraCIColor(250, 235, 215, 255); if (tkColorName == "AntiqueWhite") return TraCIColor(250, 235, 215, 255); if (tkColorName == "AntiqueWhite1") return TraCIColor(255, 239, 219, 255); if (tkColorName == "AntiqueWhite2") return TraCIColor(238, 223, 204, 255); if (tkColorName == "AntiqueWhite3") return TraCIColor(205, 192, 176, 255); if (tkColorName == "AntiqueWhite4") return TraCIColor(139, 131, 120, 255); if (tkColorName == "aquamarine") return TraCIColor(127, 255, 212, 255); if (tkColorName == "aquamarine1") return TraCIColor(127, 255, 212, 255); if (tkColorName == "aquamarine2") return TraCIColor(118, 238, 198, 255); if (tkColorName == "aquamarine3") return TraCIColor(102, 205, 170, 255); if (tkColorName == "aquamarine4") return TraCIColor(69, 139, 116, 255); if (tkColorName == "azure") return TraCIColor(240, 255, 255, 255); if (tkColorName == "azure1") return TraCIColor(240, 255, 255, 255); if (tkColorName == "azure2") return TraCIColor(224, 238, 238, 255); if (tkColorName == "azure3") return TraCIColor(193, 205, 205, 255); if (tkColorName == "azure4") return TraCIColor(131, 139, 139, 255); if (tkColorName == "beige") return TraCIColor(245, 245, 220, 255); if (tkColorName == "bisque") return TraCIColor(255, 228, 196, 255); if (tkColorName == "bisque1") return TraCIColor(255, 228, 196, 255); if (tkColorName == "bisque2") return TraCIColor(238, 213, 183, 255); if (tkColorName == "bisque3") return TraCIColor(205, 183, 158, 255); if (tkColorName == "bisque4") return TraCIColor(139, 125, 107, 255); if (tkColorName == "black") return TraCIColor(0, 0, 0, 255); if (tkColorName == "blanched almond") return TraCIColor(255, 235, 205, 255); if (tkColorName == "BlanchedAlmond") return TraCIColor(255, 235, 205, 255); if (tkColorName == "blue") return TraCIColor(0, 0, 255, 255); if (tkColorName == "blue violet") return TraCIColor(138, 43, 226, 255); if (tkColorName == "blue1") return TraCIColor(0, 0, 255, 255); if (tkColorName == "blue2") return TraCIColor(0, 0, 238, 255); if (tkColorName == "blue3") return TraCIColor(0, 0, 205, 255); if (tkColorName == "blue4") return TraCIColor(0, 0, 139, 255); if (tkColorName == "BlueViolet") return TraCIColor(138, 43, 226, 255); if (tkColorName == "brown") return TraCIColor(165, 42, 42, 255); if (tkColorName == "brown1") return TraCIColor(255, 64, 64, 255); if (tkColorName == "brown2") return TraCIColor(238, 59, 59, 255); if (tkColorName == "brown3") return TraCIColor(205, 51, 51, 255); if (tkColorName == "brown4") return TraCIColor(139, 35, 35, 255); if (tkColorName == "burlywood") return TraCIColor(222, 184, 135, 255); if (tkColorName == "burlywood1") return TraCIColor(255, 211, 155, 255); if (tkColorName == "burlywood2") return TraCIColor(238, 197, 145, 255); if (tkColorName == "burlywood3") return TraCIColor(205, 170, 125, 255); if (tkColorName == "burlywood4") return TraCIColor(139, 115, 85, 255); if (tkColorName == "cadet blue") return TraCIColor(95, 158, 160, 255); if (tkColorName == "CadetBlue") return TraCIColor(95, 158, 160, 255); if (tkColorName == "CadetBlue1") return TraCIColor(152, 245, 255, 255); if (tkColorName == "CadetBlue2") return TraCIColor(142, 229, 238, 255); if (tkColorName == "CadetBlue3") return TraCIColor(122, 197, 205, 255); if (tkColorName == "CadetBlue4") return TraCIColor(83, 134, 139, 255); if (tkColorName == "chartreuse") return TraCIColor(127, 255, 0, 255); if (tkColorName == "chartreuse1") return TraCIColor(127, 255, 0, 255); if (tkColorName == "chartreuse2") return TraCIColor(118, 238, 0, 255); if (tkColorName == "chartreuse3") return TraCIColor(102, 205, 0, 255); if (tkColorName == "chartreuse4") return TraCIColor(69, 139, 0, 255); if (tkColorName == "chocolate") return TraCIColor(210, 105, 30, 255); if (tkColorName == "chocolate1") return TraCIColor(255, 127, 36, 255); if (tkColorName == "chocolate2") return TraCIColor(238, 118, 33, 255); if (tkColorName == "chocolate3") return TraCIColor(205, 102, 29, 255); if (tkColorName == "chocolate4") return TraCIColor(139, 69, 19, 255); if (tkColorName == "coral") return TraCIColor(255, 127, 80, 255); if (tkColorName == "coral1") return TraCIColor(255, 114, 86, 255); if (tkColorName == "coral2") return TraCIColor(238, 106, 80, 255); if (tkColorName == "coral3") return TraCIColor(205, 91, 69, 255); if (tkColorName == "coral4") return TraCIColor(139, 62, 47, 255); if (tkColorName == "cornflower blue") return TraCIColor(100, 149, 237, 255); if (tkColorName == "CornflowerBlue") return TraCIColor(100, 149, 237, 255); if (tkColorName == "cornsilk") return TraCIColor(255, 248, 220, 255); if (tkColorName == "cornsilk1") return TraCIColor(255, 248, 220, 255); if (tkColorName == "cornsilk2") return TraCIColor(238, 232, 205, 255); if (tkColorName == "cornsilk3") return TraCIColor(205, 200, 177, 255); if (tkColorName == "cornsilk4") return TraCIColor(139, 136, 120, 255); if (tkColorName == "cyan") return TraCIColor(0, 255, 255, 255); if (tkColorName == "cyan1") return TraCIColor(0, 255, 255, 255); if (tkColorName == "cyan2") return TraCIColor(0, 238, 238, 255); if (tkColorName == "cyan3") return TraCIColor(0, 205, 205, 255); if (tkColorName == "cyan4") return TraCIColor(0, 139, 139, 255); if (tkColorName == "dark blue") return TraCIColor(0, 0, 139, 255); if (tkColorName == "dark cyan") return TraCIColor(0, 139, 139, 255); if (tkColorName == "dark goldenrod") return TraCIColor(184, 134, 11, 255); if (tkColorName == "dark gray") return TraCIColor(169, 169, 169, 255); if (tkColorName == "dark green") return TraCIColor(0, 100, 0, 255); if (tkColorName == "dark grey") return TraCIColor(169, 169, 169, 255); if (tkColorName == "dark khaki") return TraCIColor(189, 183, 107, 255); if (tkColorName == "dark magenta") return TraCIColor(139, 0, 139, 255); if (tkColorName == "dark olive green") return TraCIColor(85, 107, 47, 255); if (tkColorName == "dark orange") return TraCIColor(255, 140, 0, 255); if (tkColorName == "dark orchid") return TraCIColor(153, 50, 204, 255); if (tkColorName == "dark red") return TraCIColor(139, 0, 0, 255); if (tkColorName == "dark salmon") return TraCIColor(233, 150, 122, 255); if (tkColorName == "dark sea green") return TraCIColor(143, 188, 143, 255); if (tkColorName == "dark slate blue") return TraCIColor(72, 61, 139, 255); if (tkColorName == "dark slate gray") return TraCIColor(47, 79, 79, 255); if (tkColorName == "dark slate grey") return TraCIColor(47, 79, 79, 255); if (tkColorName == "dark turquoise") return TraCIColor(0, 206, 209, 255); if (tkColorName == "dark violet") return TraCIColor(148, 0, 211, 255); if (tkColorName == "DarkBlue") return TraCIColor(0, 0, 139, 255); if (tkColorName == "DarkCyan") return TraCIColor(0, 139, 139, 255); if (tkColorName == "DarkGoldenrod") return TraCIColor(184, 134, 11, 255); if (tkColorName == "DarkGoldenrod1") return TraCIColor(255, 185, 15, 255); if (tkColorName == "DarkGoldenrod2") return TraCIColor(238, 173, 14, 255); if (tkColorName == "DarkGoldenrod3") return TraCIColor(205, 149, 12, 255); if (tkColorName == "DarkGoldenrod4") return TraCIColor(139, 101, 8, 255); if (tkColorName == "DarkGray") return TraCIColor(169, 169, 169, 255); if (tkColorName == "DarkGreen") return TraCIColor(0, 100, 0, 255); if (tkColorName == "DarkGrey") return TraCIColor(169, 169, 169, 255); if (tkColorName == "DarkKhaki") return TraCIColor(189, 183, 107, 255); if (tkColorName == "DarkMagenta") return TraCIColor(139, 0, 139, 255); if (tkColorName == "DarkOliveGreen") return TraCIColor(85, 107, 47, 255); if (tkColorName == "DarkOliveGreen1") return TraCIColor(202, 255, 112, 255); if (tkColorName == "DarkOliveGreen2") return TraCIColor(188, 238, 104, 255); if (tkColorName == "DarkOliveGreen3") return TraCIColor(162, 205, 90, 255); if (tkColorName == "DarkOliveGreen4") return TraCIColor(110, 139, 61, 255); if (tkColorName == "DarkOrange") return TraCIColor(255, 140, 0, 255); if (tkColorName == "DarkOrange1") return TraCIColor(255, 127, 0, 255); if (tkColorName == "DarkOrange2") return TraCIColor(238, 118, 0, 255); if (tkColorName == "DarkOrange3") return TraCIColor(205, 102, 0, 255); if (tkColorName == "DarkOrange4") return TraCIColor(139, 69, 0, 255); if (tkColorName == "DarkOrchid") return TraCIColor(153, 50, 204, 255); if (tkColorName == "DarkOrchid1") return TraCIColor(191, 62, 255, 255); if (tkColorName == "DarkOrchid2") return TraCIColor(178, 58, 238, 255); if (tkColorName == "DarkOrchid3") return TraCIColor(154, 50, 205, 255); if (tkColorName == "DarkOrchid4") return TraCIColor(104, 34, 139, 255); if (tkColorName == "DarkRed") return TraCIColor(139, 0, 0, 255); if (tkColorName == "DarkSalmon") return TraCIColor(233, 150, 122, 255); if (tkColorName == "DarkSeaGreen") return TraCIColor(143, 188, 143, 255); if (tkColorName == "DarkSeaGreen1") return TraCIColor(193, 255, 193, 255); if (tkColorName == "DarkSeaGreen2") return TraCIColor(180, 238, 180, 255); if (tkColorName == "DarkSeaGreen3") return TraCIColor(155, 205, 155, 255); if (tkColorName == "DarkSeaGreen4") return TraCIColor(105, 139, 105, 255); if (tkColorName == "DarkSlateBlue") return TraCIColor(72, 61, 139, 255); if (tkColorName == "DarkSlateGray") return TraCIColor(47, 79, 79, 255); if (tkColorName == "DarkSlateGray1") return TraCIColor(151, 255, 255, 255); if (tkColorName == "DarkSlateGray2") return TraCIColor(141, 238, 238, 255); if (tkColorName == "DarkSlateGray3") return TraCIColor(121, 205, 205, 255); if (tkColorName == "DarkSlateGray4") return TraCIColor(82, 139, 139, 255); if (tkColorName == "DarkSlateGrey") return TraCIColor(47, 79, 79, 255); if (tkColorName == "DarkTurquoise") return TraCIColor(0, 206, 209, 255); if (tkColorName == "DarkViolet") return TraCIColor(148, 0, 211, 255); if (tkColorName == "deep pink") return TraCIColor(255, 20, 147, 255); if (tkColorName == "deep sky blue") return TraCIColor(0, 191, 255, 255); if (tkColorName == "DeepPink") return TraCIColor(255, 20, 147, 255); if (tkColorName == "DeepPink1") return TraCIColor(255, 20, 147, 255); if (tkColorName == "DeepPink2") return TraCIColor(238, 18, 137, 255); if (tkColorName == "DeepPink3") return TraCIColor(205, 16, 118, 255); if (tkColorName == "DeepPink4") return TraCIColor(139, 10, 80, 255); if (tkColorName == "DeepSkyBlue") return TraCIColor(0, 191, 255, 255); if (tkColorName == "DeepSkyBlue1") return TraCIColor(0, 191, 255, 255); if (tkColorName == "DeepSkyBlue2") return TraCIColor(0, 178, 238, 255); if (tkColorName == "DeepSkyBlue3") return TraCIColor(0, 154, 205, 255); if (tkColorName == "DeepSkyBlue4") return TraCIColor(0, 104, 139, 255); if (tkColorName == "dim gray") return TraCIColor(105, 105, 105, 255); if (tkColorName == "dim grey") return TraCIColor(105, 105, 105, 255); if (tkColorName == "DimGray") return TraCIColor(105, 105, 105, 255); if (tkColorName == "DimGrey") return TraCIColor(105, 105, 105, 255); if (tkColorName == "dodger blue") return TraCIColor(30, 144, 255, 255); if (tkColorName == "DodgerBlue") return TraCIColor(30, 144, 255, 255); if (tkColorName == "DodgerBlue1") return TraCIColor(30, 144, 255, 255); if (tkColorName == "DodgerBlue2") return TraCIColor(28, 134, 238, 255); if (tkColorName == "DodgerBlue3") return TraCIColor(24, 116, 205, 255); if (tkColorName == "DodgerBlue4") return TraCIColor(16, 78, 139, 255); if (tkColorName == "firebrick") return TraCIColor(178, 34, 34, 255); if (tkColorName == "firebrick1") return TraCIColor(255, 48, 48, 255); if (tkColorName == "firebrick2") return TraCIColor(238, 44, 44, 255); if (tkColorName == "firebrick3") return TraCIColor(205, 38, 38, 255); if (tkColorName == "firebrick4") return TraCIColor(139, 26, 26, 255); if (tkColorName == "floral white") return TraCIColor(255, 250, 240, 255); if (tkColorName == "FloralWhite") return TraCIColor(255, 250, 240, 255); if (tkColorName == "forest green") return TraCIColor(34, 139, 34, 255); if (tkColorName == "ForestGreen") return TraCIColor(34, 139, 34, 255); if (tkColorName == "gainsboro") return TraCIColor(220, 220, 220, 255); if (tkColorName == "ghost white") return TraCIColor(248, 248, 255, 255); if (tkColorName == "GhostWhite") return TraCIColor(248, 248, 255, 255); if (tkColorName == "gold") return TraCIColor(255, 215, 0, 255); if (tkColorName == "gold1") return TraCIColor(255, 215, 0, 255); if (tkColorName == "gold2") return TraCIColor(238, 201, 0, 255); if (tkColorName == "gold3") return TraCIColor(205, 173, 0, 255); if (tkColorName == "gold4") return TraCIColor(139, 117, 0, 255); if (tkColorName == "goldenrod") return TraCIColor(218, 165, 32, 255); if (tkColorName == "goldenrod1") return TraCIColor(255, 193, 37, 255); if (tkColorName == "goldenrod2") return TraCIColor(238, 180, 34, 255); if (tkColorName == "goldenrod3") return TraCIColor(205, 155, 29, 255); if (tkColorName == "goldenrod4") return TraCIColor(139, 105, 20, 255); if (tkColorName == "gray") return TraCIColor(190, 190, 190, 255); if (tkColorName == "gray0") return TraCIColor(0, 0, 0, 255); if (tkColorName == "gray1") return TraCIColor(3, 3, 3, 255); if (tkColorName == "gray2") return TraCIColor(5, 5, 5, 255); if (tkColorName == "gray3") return TraCIColor(8, 8, 8, 255); if (tkColorName == "gray4") return TraCIColor(10, 10, 10, 255); if (tkColorName == "gray5") return TraCIColor(13, 13, 13, 255); if (tkColorName == "gray6") return TraCIColor(15, 15, 15, 255); if (tkColorName == "gray7") return TraCIColor(18, 18, 18, 255); if (tkColorName == "gray8") return TraCIColor(20, 20, 20, 255); if (tkColorName == "gray9") return TraCIColor(23, 23, 23, 255); if (tkColorName == "gray10") return TraCIColor(26, 26, 26, 255); if (tkColorName == "gray11") return TraCIColor(28, 28, 28, 255); if (tkColorName == "gray12") return TraCIColor(31, 31, 31, 255); if (tkColorName == "gray13") return TraCIColor(33, 33, 33, 255); if (tkColorName == "gray14") return TraCIColor(36, 36, 36, 255); if (tkColorName == "gray15") return TraCIColor(38, 38, 38, 255); if (tkColorName == "gray16") return TraCIColor(41, 41, 41, 255); if (tkColorName == "gray17") return TraCIColor(43, 43, 43, 255); if (tkColorName == "gray18") return TraCIColor(46, 46, 46, 255); if (tkColorName == "gray19") return TraCIColor(48, 48, 48, 255); if (tkColorName == "gray20") return TraCIColor(51, 51, 51, 255); if (tkColorName == "gray21") return TraCIColor(54, 54, 54, 255); if (tkColorName == "gray22") return TraCIColor(56, 56, 56, 255); if (tkColorName == "gray23") return TraCIColor(59, 59, 59, 255); if (tkColorName == "gray24") return TraCIColor(61, 61, 61, 255); if (tkColorName == "gray25") return TraCIColor(64, 64, 64, 255); if (tkColorName == "gray26") return TraCIColor(66, 66, 66, 255); if (tkColorName == "gray27") return TraCIColor(69, 69, 69, 255); if (tkColorName == "gray28") return TraCIColor(71, 71, 71, 255); if (tkColorName == "gray29") return TraCIColor(74, 74, 74, 255); if (tkColorName == "gray30") return TraCIColor(77, 77, 77, 255); if (tkColorName == "gray31") return TraCIColor(79, 79, 79, 255); if (tkColorName == "gray32") return TraCIColor(82, 82, 82, 255); if (tkColorName == "gray33") return TraCIColor(84, 84, 84, 255); if (tkColorName == "gray34") return TraCIColor(87, 87, 87, 255); if (tkColorName == "gray35") return TraCIColor(89, 89, 89, 255); if (tkColorName == "gray36") return TraCIColor(92, 92, 92, 255); if (tkColorName == "gray37") return TraCIColor(94, 94, 94, 255); if (tkColorName == "gray38") return TraCIColor(97, 97, 97, 255); if (tkColorName == "gray39") return TraCIColor(99, 99, 99, 255); if (tkColorName == "gray40") return TraCIColor(102, 102, 102, 255); if (tkColorName == "gray41") return TraCIColor(105, 105, 105, 255); if (tkColorName == "gray42") return TraCIColor(107, 107, 107, 255); if (tkColorName == "gray43") return TraCIColor(110, 110, 110, 255); if (tkColorName == "gray44") return TraCIColor(112, 112, 112, 255); if (tkColorName == "gray45") return TraCIColor(115, 115, 115, 255); if (tkColorName == "gray46") return TraCIColor(117, 117, 117, 255); if (tkColorName == "gray47") return TraCIColor(120, 120, 120, 255); if (tkColorName == "gray48") return TraCIColor(122, 122, 122, 255); if (tkColorName == "gray49") return TraCIColor(125, 125, 125, 255); if (tkColorName == "gray50") return TraCIColor(127, 127, 127, 255); if (tkColorName == "gray51") return TraCIColor(130, 130, 130, 255); if (tkColorName == "gray52") return TraCIColor(133, 133, 133, 255); if (tkColorName == "gray53") return TraCIColor(135, 135, 135, 255); if (tkColorName == "gray54") return TraCIColor(138, 138, 138, 255); if (tkColorName == "gray55") return TraCIColor(140, 140, 140, 255); if (tkColorName == "gray56") return TraCIColor(143, 143, 143, 255); if (tkColorName == "gray57") return TraCIColor(145, 145, 145, 255); if (tkColorName == "gray58") return TraCIColor(148, 148, 148, 255); if (tkColorName == "gray59") return TraCIColor(150, 150, 150, 255); if (tkColorName == "gray60") return TraCIColor(153, 153, 153, 255); if (tkColorName == "gray61") return TraCIColor(156, 156, 156, 255); if (tkColorName == "gray62") return TraCIColor(158, 158, 158, 255); if (tkColorName == "gray63") return TraCIColor(161, 161, 161, 255); if (tkColorName == "gray64") return TraCIColor(163, 163, 163, 255); if (tkColorName == "gray65") return TraCIColor(166, 166, 166, 255); if (tkColorName == "gray66") return TraCIColor(168, 168, 168, 255); if (tkColorName == "gray67") return TraCIColor(171, 171, 171, 255); if (tkColorName == "gray68") return TraCIColor(173, 173, 173, 255); if (tkColorName == "gray69") return TraCIColor(176, 176, 176, 255); if (tkColorName == "gray70") return TraCIColor(179, 179, 179, 255); if (tkColorName == "gray71") return TraCIColor(181, 181, 181, 255); if (tkColorName == "gray72") return TraCIColor(184, 184, 184, 255); if (tkColorName == "gray73") return TraCIColor(186, 186, 186, 255); if (tkColorName == "gray74") return TraCIColor(189, 189, 189, 255); if (tkColorName == "gray75") return TraCIColor(191, 191, 191, 255); if (tkColorName == "gray76") return TraCIColor(194, 194, 194, 255); if (tkColorName == "gray77") return TraCIColor(196, 196, 196, 255); if (tkColorName == "gray78") return TraCIColor(199, 199, 199, 255); if (tkColorName == "gray79") return TraCIColor(201, 201, 201, 255); if (tkColorName == "gray80") return TraCIColor(204, 204, 204, 255); if (tkColorName == "gray81") return TraCIColor(207, 207, 207, 255); if (tkColorName == "gray82") return TraCIColor(209, 209, 209, 255); if (tkColorName == "gray83") return TraCIColor(212, 212, 212, 255); if (tkColorName == "gray84") return TraCIColor(214, 214, 214, 255); if (tkColorName == "gray85") return TraCIColor(217, 217, 217, 255); if (tkColorName == "gray86") return TraCIColor(219, 219, 219, 255); if (tkColorName == "gray87") return TraCIColor(222, 222, 222, 255); if (tkColorName == "gray88") return TraCIColor(224, 224, 224, 255); if (tkColorName == "gray89") return TraCIColor(227, 227, 227, 255); if (tkColorName == "gray90") return TraCIColor(229, 229, 229, 255); if (tkColorName == "gray91") return TraCIColor(232, 232, 232, 255); if (tkColorName == "gray92") return TraCIColor(235, 235, 235, 255); if (tkColorName == "gray93") return TraCIColor(237, 237, 237, 255); if (tkColorName == "gray94") return TraCIColor(240, 240, 240, 255); if (tkColorName == "gray95") return TraCIColor(242, 242, 242, 255); if (tkColorName == "gray96") return TraCIColor(245, 245, 245, 255); if (tkColorName == "gray97") return TraCIColor(247, 247, 247, 255); if (tkColorName == "gray98") return TraCIColor(250, 250, 250, 255); if (tkColorName == "gray99") return TraCIColor(252, 252, 252, 255); if (tkColorName == "gray100") return TraCIColor(255, 255, 255, 255); if (tkColorName == "green") return TraCIColor(0, 255, 0, 255); if (tkColorName == "green yellow") return TraCIColor(173, 255, 47, 255); if (tkColorName == "green1") return TraCIColor(0, 255, 0, 255); if (tkColorName == "green2") return TraCIColor(0, 238, 0, 255); if (tkColorName == "green3") return TraCIColor(0, 205, 0, 255); if (tkColorName == "green4") return TraCIColor(0, 139, 0, 255); if (tkColorName == "GreenYellow") return TraCIColor(173, 255, 47, 255); if (tkColorName == "grey") return TraCIColor(190, 190, 190, 255); if (tkColorName == "grey0") return TraCIColor(0, 0, 0, 255); if (tkColorName == "grey1") return TraCIColor(3, 3, 3, 255); if (tkColorName == "grey2") return TraCIColor(5, 5, 5, 255); if (tkColorName == "grey3") return TraCIColor(8, 8, 8, 255); if (tkColorName == "grey4") return TraCIColor(10, 10, 10, 255); if (tkColorName == "grey5") return TraCIColor(13, 13, 13, 255); if (tkColorName == "grey6") return TraCIColor(15, 15, 15, 255); if (tkColorName == "grey7") return TraCIColor(18, 18, 18, 255); if (tkColorName == "grey8") return TraCIColor(20, 20, 20, 255); if (tkColorName == "grey9") return TraCIColor(23, 23, 23, 255); if (tkColorName == "grey10") return TraCIColor(26, 26, 26, 255); if (tkColorName == "grey11") return TraCIColor(28, 28, 28, 255); if (tkColorName == "grey12") return TraCIColor(31, 31, 31, 255); if (tkColorName == "grey13") return TraCIColor(33, 33, 33, 255); if (tkColorName == "grey14") return TraCIColor(36, 36, 36, 255); if (tkColorName == "grey15") return TraCIColor(38, 38, 38, 255); if (tkColorName == "grey16") return TraCIColor(41, 41, 41, 255); if (tkColorName == "grey17") return TraCIColor(43, 43, 43, 255); if (tkColorName == "grey18") return TraCIColor(46, 46, 46, 255); if (tkColorName == "grey19") return TraCIColor(48, 48, 48, 255); if (tkColorName == "grey20") return TraCIColor(51, 51, 51, 255); if (tkColorName == "grey21") return TraCIColor(54, 54, 54, 255); if (tkColorName == "grey22") return TraCIColor(56, 56, 56, 255); if (tkColorName == "grey23") return TraCIColor(59, 59, 59, 255); if (tkColorName == "grey24") return TraCIColor(61, 61, 61, 255); if (tkColorName == "grey25") return TraCIColor(64, 64, 64, 255); if (tkColorName == "grey26") return TraCIColor(66, 66, 66, 255); if (tkColorName == "grey27") return TraCIColor(69, 69, 69, 255); if (tkColorName == "grey28") return TraCIColor(71, 71, 71, 255); if (tkColorName == "grey29") return TraCIColor(74, 74, 74, 255); if (tkColorName == "grey30") return TraCIColor(77, 77, 77, 255); if (tkColorName == "grey31") return TraCIColor(79, 79, 79, 255); if (tkColorName == "grey32") return TraCIColor(82, 82, 82, 255); if (tkColorName == "grey33") return TraCIColor(84, 84, 84, 255); if (tkColorName == "grey34") return TraCIColor(87, 87, 87, 255); if (tkColorName == "grey35") return TraCIColor(89, 89, 89, 255); if (tkColorName == "grey36") return TraCIColor(92, 92, 92, 255); if (tkColorName == "grey37") return TraCIColor(94, 94, 94, 255); if (tkColorName == "grey38") return TraCIColor(97, 97, 97, 255); if (tkColorName == "grey39") return TraCIColor(99, 99, 99, 255); if (tkColorName == "grey40") return TraCIColor(102, 102, 102, 255); if (tkColorName == "grey41") return TraCIColor(105, 105, 105, 255); if (tkColorName == "grey42") return TraCIColor(107, 107, 107, 255); if (tkColorName == "grey43") return TraCIColor(110, 110, 110, 255); if (tkColorName == "grey44") return TraCIColor(112, 112, 112, 255); if (tkColorName == "grey45") return TraCIColor(115, 115, 115, 255); if (tkColorName == "grey46") return TraCIColor(117, 117, 117, 255); if (tkColorName == "grey47") return TraCIColor(120, 120, 120, 255); if (tkColorName == "grey48") return TraCIColor(122, 122, 122, 255); if (tkColorName == "grey49") return TraCIColor(125, 125, 125, 255); if (tkColorName == "grey50") return TraCIColor(127, 127, 127, 255); if (tkColorName == "grey51") return TraCIColor(130, 130, 130, 255); if (tkColorName == "grey52") return TraCIColor(133, 133, 133, 255); if (tkColorName == "grey53") return TraCIColor(135, 135, 135, 255); if (tkColorName == "grey54") return TraCIColor(138, 138, 138, 255); if (tkColorName == "grey55") return TraCIColor(140, 140, 140, 255); if (tkColorName == "grey56") return TraCIColor(143, 143, 143, 255); if (tkColorName == "grey57") return TraCIColor(145, 145, 145, 255); if (tkColorName == "grey58") return TraCIColor(148, 148, 148, 255); if (tkColorName == "grey59") return TraCIColor(150, 150, 150, 255); if (tkColorName == "grey60") return TraCIColor(153, 153, 153, 255); if (tkColorName == "grey61") return TraCIColor(156, 156, 156, 255); if (tkColorName == "grey62") return TraCIColor(158, 158, 158, 255); if (tkColorName == "grey63") return TraCIColor(161, 161, 161, 255); if (tkColorName == "grey64") return TraCIColor(163, 163, 163, 255); if (tkColorName == "grey65") return TraCIColor(166, 166, 166, 255); if (tkColorName == "grey66") return TraCIColor(168, 168, 168, 255); if (tkColorName == "grey67") return TraCIColor(171, 171, 171, 255); if (tkColorName == "grey68") return TraCIColor(173, 173, 173, 255); if (tkColorName == "grey69") return TraCIColor(176, 176, 176, 255); if (tkColorName == "grey70") return TraCIColor(179, 179, 179, 255); if (tkColorName == "grey71") return TraCIColor(181, 181, 181, 255); if (tkColorName == "grey72") return TraCIColor(184, 184, 184, 255); if (tkColorName == "grey73") return TraCIColor(186, 186, 186, 255); if (tkColorName == "grey74") return TraCIColor(189, 189, 189, 255); if (tkColorName == "grey75") return TraCIColor(191, 191, 191, 255); if (tkColorName == "grey76") return TraCIColor(194, 194, 194, 255); if (tkColorName == "grey77") return TraCIColor(196, 196, 196, 255); if (tkColorName == "grey78") return TraCIColor(199, 199, 199, 255); if (tkColorName == "grey79") return TraCIColor(201, 201, 201, 255); if (tkColorName == "grey80") return TraCIColor(204, 204, 204, 255); if (tkColorName == "grey81") return TraCIColor(207, 207, 207, 255); if (tkColorName == "grey82") return TraCIColor(209, 209, 209, 255); if (tkColorName == "grey83") return TraCIColor(212, 212, 212, 255); if (tkColorName == "grey84") return TraCIColor(214, 214, 214, 255); if (tkColorName == "grey85") return TraCIColor(217, 217, 217, 255); if (tkColorName == "grey86") return TraCIColor(219, 219, 219, 255); if (tkColorName == "grey87") return TraCIColor(222, 222, 222, 255); if (tkColorName == "grey88") return TraCIColor(224, 224, 224, 255); if (tkColorName == "grey89") return TraCIColor(227, 227, 227, 255); if (tkColorName == "grey90") return TraCIColor(229, 229, 229, 255); if (tkColorName == "grey91") return TraCIColor(232, 232, 232, 255); if (tkColorName == "grey92") return TraCIColor(235, 235, 235, 255); if (tkColorName == "grey93") return TraCIColor(237, 237, 237, 255); if (tkColorName == "grey94") return TraCIColor(240, 240, 240, 255); if (tkColorName == "grey95") return TraCIColor(242, 242, 242, 255); if (tkColorName == "grey96") return TraCIColor(245, 245, 245, 255); if (tkColorName == "grey97") return TraCIColor(247, 247, 247, 255); if (tkColorName == "grey98") return TraCIColor(250, 250, 250, 255); if (tkColorName == "grey99") return TraCIColor(252, 252, 252, 255); if (tkColorName == "grey100") return TraCIColor(255, 255, 255, 255); if (tkColorName == "honeydew") return TraCIColor(240, 255, 240, 255); if (tkColorName == "honeydew1") return TraCIColor(240, 255, 240, 255); if (tkColorName == "honeydew2") return TraCIColor(224, 238, 224, 255); if (tkColorName == "honeydew3") return TraCIColor(193, 205, 193, 255); if (tkColorName == "honeydew4") return TraCIColor(131, 139, 131, 255); if (tkColorName == "hot pink") return TraCIColor(255, 105, 180, 255); if (tkColorName == "HotPink") return TraCIColor(255, 105, 180, 255); if (tkColorName == "HotPink1") return TraCIColor(255, 110, 180, 255); if (tkColorName == "HotPink2") return TraCIColor(238, 106, 167, 255); if (tkColorName == "HotPink3") return TraCIColor(205, 96, 144, 255); if (tkColorName == "HotPink4") return TraCIColor(139, 58, 98, 255); if (tkColorName == "indian red") return TraCIColor(205, 92, 92, 255); if (tkColorName == "IndianRed") return TraCIColor(205, 92, 92, 255); if (tkColorName == "IndianRed1") return TraCIColor(255, 106, 106, 255); if (tkColorName == "IndianRed2") return TraCIColor(238, 99, 99, 255); if (tkColorName == "IndianRed3") return TraCIColor(205, 85, 85, 255); if (tkColorName == "IndianRed4") return TraCIColor(139, 58, 58, 255); if (tkColorName == "ivory") return TraCIColor(255, 255, 240, 255); if (tkColorName == "ivory1") return TraCIColor(255, 255, 240, 255); if (tkColorName == "ivory2") return TraCIColor(238, 238, 224, 255); if (tkColorName == "ivory3") return TraCIColor(205, 205, 193, 255); if (tkColorName == "ivory4") return TraCIColor(139, 139, 131, 255); if (tkColorName == "khaki") return TraCIColor(240, 230, 140, 255); if (tkColorName == "khaki1") return TraCIColor(255, 246, 143, 255); if (tkColorName == "khaki2") return TraCIColor(238, 230, 133, 255); if (tkColorName == "khaki3") return TraCIColor(205, 198, 115, 255); if (tkColorName == "khaki4") return TraCIColor(139, 134, 78, 255); if (tkColorName == "lavender") return TraCIColor(230, 230, 250, 255); if (tkColorName == "lavender blush") return TraCIColor(255, 240, 245, 255); if (tkColorName == "LavenderBlush") return TraCIColor(255, 240, 245, 255); if (tkColorName == "LavenderBlush1") return TraCIColor(255, 240, 245, 255); if (tkColorName == "LavenderBlush2") return TraCIColor(238, 224, 229, 255); if (tkColorName == "LavenderBlush3") return TraCIColor(205, 193, 197, 255); if (tkColorName == "LavenderBlush4") return TraCIColor(139, 131, 134, 255); if (tkColorName == "lawn green") return TraCIColor(124, 252, 0, 255); if (tkColorName == "LawnGreen") return TraCIColor(124, 252, 0, 255); if (tkColorName == "lemon chiffon") return TraCIColor(255, 250, 205, 255); if (tkColorName == "LemonChiffon") return TraCIColor(255, 250, 205, 255); if (tkColorName == "LemonChiffon1") return TraCIColor(255, 250, 205, 255); if (tkColorName == "LemonChiffon2") return TraCIColor(238, 233, 191, 255); if (tkColorName == "LemonChiffon3") return TraCIColor(205, 201, 165, 255); if (tkColorName == "LemonChiffon4") return TraCIColor(139, 137, 112, 255); if (tkColorName == "light blue") return TraCIColor(173, 216, 230, 255); if (tkColorName == "light coral") return TraCIColor(240, 128, 128, 255); if (tkColorName == "light cyan") return TraCIColor(224, 255, 255, 255); if (tkColorName == "light goldenrod") return TraCIColor(238, 221, 130, 255); if (tkColorName == "light goldenrod yellow") return TraCIColor(250, 250, 210, 255); if (tkColorName == "light gray") return TraCIColor(211, 211, 211, 255); if (tkColorName == "light green") return TraCIColor(144, 238, 144, 255); if (tkColorName == "light grey") return TraCIColor(211, 211, 211, 255); if (tkColorName == "light pink") return TraCIColor(255, 182, 193, 255); if (tkColorName == "light salmon") return TraCIColor(255, 160, 122, 255); if (tkColorName == "light sea green") return TraCIColor(32, 178, 170, 255); if (tkColorName == "light sky blue") return TraCIColor(135, 206, 250, 255); if (tkColorName == "light slate blue") return TraCIColor(132, 112, 255, 255); if (tkColorName == "light slate gray") return TraCIColor(119, 136, 153, 255); if (tkColorName == "light slate grey") return TraCIColor(119, 136, 153, 255); if (tkColorName == "light steel blue") return TraCIColor(176, 196, 222, 255); if (tkColorName == "light yellow") return TraCIColor(255, 255, 224, 255); if (tkColorName == "LightBlue") return TraCIColor(173, 216, 230, 255); if (tkColorName == "LightBlue1") return TraCIColor(191, 239, 255, 255); if (tkColorName == "LightBlue2") return TraCIColor(178, 223, 238, 255); if (tkColorName == "LightBlue3") return TraCIColor(154, 192, 205, 255); if (tkColorName == "LightBlue4") return TraCIColor(104, 131, 139, 255); if (tkColorName == "LightCoral") return TraCIColor(240, 128, 128, 255); if (tkColorName == "LightCyan") return TraCIColor(224, 255, 255, 255); if (tkColorName == "LightCyan1") return TraCIColor(224, 255, 255, 255); if (tkColorName == "LightCyan2") return TraCIColor(209, 238, 238, 255); if (tkColorName == "LightCyan3") return TraCIColor(180, 205, 205, 255); if (tkColorName == "LightCyan4") return TraCIColor(122, 139, 139, 255); if (tkColorName == "LightGoldenrod") return TraCIColor(238, 221, 130, 255); if (tkColorName == "LightGoldenrod1") return TraCIColor(255, 236, 139, 255); if (tkColorName == "LightGoldenrod2") return TraCIColor(238, 220, 130, 255); if (tkColorName == "LightGoldenrod3") return TraCIColor(205, 190, 112, 255); if (tkColorName == "LightGoldenrod4") return TraCIColor(139, 129, 76, 255); if (tkColorName == "LightGoldenrodYellow") return TraCIColor(250, 250, 210, 255); if (tkColorName == "LightGray") return TraCIColor(211, 211, 211, 255); if (tkColorName == "LightGreen") return TraCIColor(144, 238, 144, 255); if (tkColorName == "LightGrey") return TraCIColor(211, 211, 211, 255); if (tkColorName == "LightPink") return TraCIColor(255, 182, 193, 255); if (tkColorName == "LightPink1") return TraCIColor(255, 174, 185, 255); if (tkColorName == "LightPink2") return TraCIColor(238, 162, 173, 255); if (tkColorName == "LightPink3") return TraCIColor(205, 140, 149, 255); if (tkColorName == "LightPink4") return TraCIColor(139, 95, 101, 255); if (tkColorName == "LightSalmon") return TraCIColor(255, 160, 122, 255); if (tkColorName == "LightSalmon1") return TraCIColor(255, 160, 122, 255); if (tkColorName == "LightSalmon2") return TraCIColor(238, 149, 114, 255); if (tkColorName == "LightSalmon3") return TraCIColor(205, 129, 98, 255); if (tkColorName == "LightSalmon4") return TraCIColor(139, 87, 66, 255); if (tkColorName == "LightSeaGreen") return TraCIColor(32, 178, 170, 255); if (tkColorName == "LightSkyBlue") return TraCIColor(135, 206, 250, 255); if (tkColorName == "LightSkyBlue1") return TraCIColor(176, 226, 255, 255); if (tkColorName == "LightSkyBlue2") return TraCIColor(164, 211, 238, 255); if (tkColorName == "LightSkyBlue3") return TraCIColor(141, 182, 205, 255); if (tkColorName == "LightSkyBlue4") return TraCIColor(96, 123, 139, 255); if (tkColorName == "LightSlateBlue") return TraCIColor(132, 112, 255, 255); if (tkColorName == "LightSlateGray") return TraCIColor(119, 136, 153, 255); if (tkColorName == "LightSlateGrey") return TraCIColor(119, 136, 153, 255); if (tkColorName == "LightSteelBlue") return TraCIColor(176, 196, 222, 255); if (tkColorName == "LightSteelBlue1") return TraCIColor(202, 225, 255, 255); if (tkColorName == "LightSteelBlue2") return TraCIColor(188, 210, 238, 255); if (tkColorName == "LightSteelBlue3") return TraCIColor(162, 181, 205, 255); if (tkColorName == "LightSteelBlue4") return TraCIColor(110, 123, 139, 255); if (tkColorName == "LightYellow") return TraCIColor(255, 255, 224, 255); if (tkColorName == "LightYellow1") return TraCIColor(255, 255, 224, 255); if (tkColorName == "LightYellow2") return TraCIColor(238, 238, 209, 255); if (tkColorName == "LightYellow3") return TraCIColor(205, 205, 180, 255); if (tkColorName == "LightYellow4") return TraCIColor(139, 139, 122, 255); if (tkColorName == "lime green") return TraCIColor(50, 205, 50, 255); if (tkColorName == "LimeGreen") return TraCIColor(50, 205, 50, 255); if (tkColorName == "linen") return TraCIColor(250, 240, 230, 255); if (tkColorName == "magenta") return TraCIColor(255, 0, 255, 255); if (tkColorName == "magenta1") return TraCIColor(255, 0, 255, 255); if (tkColorName == "magenta2") return TraCIColor(238, 0, 238, 255); if (tkColorName == "magenta3") return TraCIColor(205, 0, 205, 255); if (tkColorName == "magenta4") return TraCIColor(139, 0, 139, 255); if (tkColorName == "maroon") return TraCIColor(176, 48, 96, 255); if (tkColorName == "maroon1") return TraCIColor(255, 52, 179, 255); if (tkColorName == "maroon2") return TraCIColor(238, 48, 167, 255); if (tkColorName == "maroon3") return TraCIColor(205, 41, 144, 255); if (tkColorName == "maroon4") return TraCIColor(139, 28, 98, 255); if (tkColorName == "medium aquamarine") return TraCIColor(102, 205, 170, 255); if (tkColorName == "medium blue") return TraCIColor(0, 0, 205, 255); if (tkColorName == "medium orchid") return TraCIColor(186, 85, 211, 255); if (tkColorName == "medium purple") return TraCIColor(147, 112, 219, 255); if (tkColorName == "medium sea green") return TraCIColor(60, 179, 113, 255); if (tkColorName == "medium slate blue") return TraCIColor(123, 104, 238, 255); if (tkColorName == "medium spring green") return TraCIColor(0, 250, 154, 255); if (tkColorName == "medium turquoise") return TraCIColor(72, 209, 204, 255); if (tkColorName == "medium violet red") return TraCIColor(199, 21, 133, 255); if (tkColorName == "MediumAquamarine") return TraCIColor(102, 205, 170, 255); if (tkColorName == "MediumBlue") return TraCIColor(0, 0, 205, 255); if (tkColorName == "MediumOrchid") return TraCIColor(186, 85, 211, 255); if (tkColorName == "MediumOrchid1") return TraCIColor(224, 102, 255, 255); if (tkColorName == "MediumOrchid2") return TraCIColor(209, 95, 238, 255); if (tkColorName == "MediumOrchid3") return TraCIColor(180, 82, 205, 255); if (tkColorName == "MediumOrchid4") return TraCIColor(122, 55, 139, 255); if (tkColorName == "MediumPurple") return TraCIColor(147, 112, 219, 255); if (tkColorName == "MediumPurple1") return TraCIColor(171, 130, 255, 255); if (tkColorName == "MediumPurple2") return TraCIColor(159, 121, 238, 255); if (tkColorName == "MediumPurple3") return TraCIColor(137, 104, 205, 255); if (tkColorName == "MediumPurple4") return TraCIColor(93, 71, 139, 255); if (tkColorName == "MediumSeaGreen") return TraCIColor(60, 179, 113, 255); if (tkColorName == "MediumSlateBlue") return TraCIColor(123, 104, 238, 255); if (tkColorName == "MediumSpringGreen") return TraCIColor(0, 250, 154, 255); if (tkColorName == "MediumTurquoise") return TraCIColor(72, 209, 204, 255); if (tkColorName == "MediumVioletRed") return TraCIColor(199, 21, 133, 255); if (tkColorName == "midnight blue") return TraCIColor(25, 25, 112, 255); if (tkColorName == "MidnightBlue") return TraCIColor(25, 25, 112, 255); if (tkColorName == "mint cream") return TraCIColor(245, 255, 250, 255); if (tkColorName == "MintCream") return TraCIColor(245, 255, 250, 255); if (tkColorName == "misty rose") return TraCIColor(255, 228, 225, 255); if (tkColorName == "MistyRose") return TraCIColor(255, 228, 225, 255); if (tkColorName == "MistyRose1") return TraCIColor(255, 228, 225, 255); if (tkColorName == "MistyRose2") return TraCIColor(238, 213, 210, 255); if (tkColorName == "MistyRose3") return TraCIColor(205, 183, 181, 255); if (tkColorName == "MistyRose4") return TraCIColor(139, 125, 123, 255); if (tkColorName == "moccasin") return TraCIColor(255, 228, 181, 255); if (tkColorName == "navajo white") return TraCIColor(255, 222, 173, 255); if (tkColorName == "NavajoWhite") return TraCIColor(255, 222, 173, 255); if (tkColorName == "NavajoWhite1") return TraCIColor(255, 222, 173, 255); if (tkColorName == "NavajoWhite2") return TraCIColor(238, 207, 161, 255); if (tkColorName == "NavajoWhite3") return TraCIColor(205, 179, 139, 255); if (tkColorName == "NavajoWhite4") return TraCIColor(139, 121, 94, 255); if (tkColorName == "navy") return TraCIColor(0, 0, 128, 255); if (tkColorName == "navy blue") return TraCIColor(0, 0, 128, 255); if (tkColorName == "NavyBlue") return TraCIColor(0, 0, 128, 255); if (tkColorName == "old lace") return TraCIColor(253, 245, 230, 255); if (tkColorName == "OldLace") return TraCIColor(253, 245, 230, 255); if (tkColorName == "olive drab") return TraCIColor(107, 142, 35, 255); if (tkColorName == "OliveDrab") return TraCIColor(107, 142, 35, 255); if (tkColorName == "OliveDrab1") return TraCIColor(192, 255, 62, 255); if (tkColorName == "OliveDrab2") return TraCIColor(179, 238, 58, 255); if (tkColorName == "OliveDrab3") return TraCIColor(154, 205, 50, 255); if (tkColorName == "OliveDrab4") return TraCIColor(105, 139, 34, 255); if (tkColorName == "orange") return TraCIColor(255, 165, 0, 255); if (tkColorName == "orange red") return TraCIColor(255, 69, 0, 255); if (tkColorName == "orange1") return TraCIColor(255, 165, 0, 255); if (tkColorName == "orange2") return TraCIColor(238, 154, 0, 255); if (tkColorName == "orange3") return TraCIColor(205, 133, 0, 255); if (tkColorName == "orange4") return TraCIColor(139, 90, 0, 255); if (tkColorName == "OrangeRed") return TraCIColor(255, 69, 0, 255); if (tkColorName == "OrangeRed1") return TraCIColor(255, 69, 0, 255); if (tkColorName == "OrangeRed2") return TraCIColor(238, 64, 0, 255); if (tkColorName == "OrangeRed3") return TraCIColor(205, 55, 0, 255); if (tkColorName == "OrangeRed4") return TraCIColor(139, 37, 0, 255); if (tkColorName == "orchid") return TraCIColor(218, 112, 214, 255); if (tkColorName == "orchid1") return TraCIColor(255, 131, 250, 255); if (tkColorName == "orchid2") return TraCIColor(238, 122, 233, 255); if (tkColorName == "orchid3") return TraCIColor(205, 105, 201, 255); if (tkColorName == "orchid4") return TraCIColor(139, 71, 137, 255); if (tkColorName == "pale goldenrod") return TraCIColor(238, 232, 170, 255); if (tkColorName == "pale green") return TraCIColor(152, 251, 152, 255); if (tkColorName == "pale turquoise") return TraCIColor(175, 238, 238, 255); if (tkColorName == "pale violet red") return TraCIColor(219, 112, 147, 255); if (tkColorName == "PaleGoldenrod") return TraCIColor(238, 232, 170, 255); if (tkColorName == "PaleGreen") return TraCIColor(152, 251, 152, 255); if (tkColorName == "PaleGreen1") return TraCIColor(154, 255, 154, 255); if (tkColorName == "PaleGreen2") return TraCIColor(144, 238, 144, 255); if (tkColorName == "PaleGreen3") return TraCIColor(124, 205, 124, 255); if (tkColorName == "PaleGreen4") return TraCIColor(84, 139, 84, 255); if (tkColorName == "PaleTurquoise") return TraCIColor(175, 238, 238, 255); if (tkColorName == "PaleTurquoise1") return TraCIColor(187, 255, 255, 255); if (tkColorName == "PaleTurquoise2") return TraCIColor(174, 238, 238, 255); if (tkColorName == "PaleTurquoise3") return TraCIColor(150, 205, 205, 255); if (tkColorName == "PaleTurquoise4") return TraCIColor(102, 139, 139, 255); if (tkColorName == "PaleVioletRed") return TraCIColor(219, 112, 147, 255); if (tkColorName == "PaleVioletRed1") return TraCIColor(255, 130, 171, 255); if (tkColorName == "PaleVioletRed2") return TraCIColor(238, 121, 159, 255); if (tkColorName == "PaleVioletRed3") return TraCIColor(205, 104, 127, 255); if (tkColorName == "PaleVioletRed4") return TraCIColor(139, 71, 93, 255); if (tkColorName == "papaya whip") return TraCIColor(255, 239, 213, 255); if (tkColorName == "PapayaWhip") return TraCIColor(255, 239, 213, 255); if (tkColorName == "peach puff") return TraCIColor(255, 218, 185, 255); if (tkColorName == "PeachPuff") return TraCIColor(255, 218, 185, 255); if (tkColorName == "PeachPuff1") return TraCIColor(255, 218, 185, 255); if (tkColorName == "PeachPuff2") return TraCIColor(238, 203, 173, 255); if (tkColorName == "PeachPuff3") return TraCIColor(205, 175, 149, 255); if (tkColorName == "PeachPuff4") return TraCIColor(139, 119, 101, 255); if (tkColorName == "peru") return TraCIColor(205, 133, 63, 255); if (tkColorName == "pink") return TraCIColor(255, 192, 203, 255); if (tkColorName == "pink1") return TraCIColor(255, 181, 197, 255); if (tkColorName == "pink2") return TraCIColor(238, 169, 184, 255); if (tkColorName == "pink3") return TraCIColor(205, 145, 158, 255); if (tkColorName == "pink4") return TraCIColor(139, 99, 108, 255); if (tkColorName == "plum") return TraCIColor(221, 160, 221, 255); if (tkColorName == "plum1") return TraCIColor(255, 187, 255, 255); if (tkColorName == "plum2") return TraCIColor(238, 174, 238, 255); if (tkColorName == "plum3") return TraCIColor(205, 150, 205, 255); if (tkColorName == "plum4") return TraCIColor(139, 102, 139, 255); if (tkColorName == "powder blue") return TraCIColor(176, 224, 230, 255); if (tkColorName == "PowderBlue") return TraCIColor(176, 224, 230, 255); if (tkColorName == "purple") return TraCIColor(160, 32, 240, 255); if (tkColorName == "purple1") return TraCIColor(155, 48, 255, 255); if (tkColorName == "purple2") return TraCIColor(145, 44, 238, 255); if (tkColorName == "purple3") return TraCIColor(125, 38, 205, 255); if (tkColorName == "purple4") return TraCIColor(85, 26, 139, 255); if (tkColorName == "red") return TraCIColor(255, 0, 0, 255); if (tkColorName == "red1") return TraCIColor(255, 0, 0, 255); if (tkColorName == "red2") return TraCIColor(238, 0, 0, 255); if (tkColorName == "red3") return TraCIColor(205, 0, 0, 255); if (tkColorName == "red4") return TraCIColor(139, 0, 0, 255); if (tkColorName == "rosy brown") return TraCIColor(188, 143, 143, 255); if (tkColorName == "RosyBrown") return TraCIColor(188, 143, 143, 255); if (tkColorName == "RosyBrown1") return TraCIColor(255, 193, 193, 255); if (tkColorName == "RosyBrown2") return TraCIColor(238, 180, 180, 255); if (tkColorName == "RosyBrown3") return TraCIColor(205, 155, 155, 255); if (tkColorName == "RosyBrown4") return TraCIColor(139, 105, 105, 255); if (tkColorName == "royal blue") return TraCIColor(65, 105, 225, 255); if (tkColorName == "RoyalBlue") return TraCIColor(65, 105, 225, 255); if (tkColorName == "RoyalBlue1") return TraCIColor(72, 118, 255, 255); if (tkColorName == "RoyalBlue2") return TraCIColor(67, 110, 238, 255); if (tkColorName == "RoyalBlue3") return TraCIColor(58, 95, 205, 255); if (tkColorName == "RoyalBlue4") return TraCIColor(39, 64, 139, 255); if (tkColorName == "saddle brown") return TraCIColor(139, 69, 19, 255); if (tkColorName == "SaddleBrown") return TraCIColor(139, 69, 19, 255); if (tkColorName == "salmon") return TraCIColor(250, 128, 114, 255); if (tkColorName == "salmon1") return TraCIColor(255, 140, 105, 255); if (tkColorName == "salmon2") return TraCIColor(238, 130, 98, 255); if (tkColorName == "salmon3") return TraCIColor(205, 112, 84, 255); if (tkColorName == "salmon4") return TraCIColor(139, 76, 57, 255); if (tkColorName == "sandy brown") return TraCIColor(244, 164, 96, 255); if (tkColorName == "SandyBrown") return TraCIColor(244, 164, 96, 255); if (tkColorName == "sea green") return TraCIColor(46, 139, 87, 255); if (tkColorName == "SeaGreen") return TraCIColor(46, 139, 87, 255); if (tkColorName == "SeaGreen1") return TraCIColor(84, 255, 159, 255); if (tkColorName == "SeaGreen2") return TraCIColor(78, 238, 148, 255); if (tkColorName == "SeaGreen3") return TraCIColor(67, 205, 128, 255); if (tkColorName == "SeaGreen4") return TraCIColor(46, 139, 87, 255); if (tkColorName == "seashell") return TraCIColor(255, 245, 238, 255); if (tkColorName == "seashell1") return TraCIColor(255, 245, 238, 255); if (tkColorName == "seashell2") return TraCIColor(238, 229, 222, 255); if (tkColorName == "seashell3") return TraCIColor(205, 197, 191, 255); if (tkColorName == "seashell4") return TraCIColor(139, 134, 130, 255); if (tkColorName == "sienna") return TraCIColor(160, 82, 45, 255); if (tkColorName == "sienna1") return TraCIColor(255, 130, 71, 255); if (tkColorName == "sienna2") return TraCIColor(238, 121, 66, 255); if (tkColorName == "sienna3") return TraCIColor(205, 104, 57, 255); if (tkColorName == "sienna4") return TraCIColor(139, 71, 38, 255); if (tkColorName == "sky blue") return TraCIColor(135, 206, 235, 255); if (tkColorName == "SkyBlue") return TraCIColor(135, 206, 235, 255); if (tkColorName == "SkyBlue1") return TraCIColor(135, 206, 255, 255); if (tkColorName == "SkyBlue2") return TraCIColor(126, 192, 238, 255); if (tkColorName == "SkyBlue3") return TraCIColor(108, 166, 205, 255); if (tkColorName == "SkyBlue4") return TraCIColor(74, 112, 139, 255); if (tkColorName == "slate blue") return TraCIColor(106, 90, 205, 255); if (tkColorName == "slate gray") return TraCIColor(112, 128, 144, 255); if (tkColorName == "slate grey") return TraCIColor(112, 128, 144, 255); if (tkColorName == "SlateBlue") return TraCIColor(106, 90, 205, 255); if (tkColorName == "SlateBlue1") return TraCIColor(131, 111, 255, 255); if (tkColorName == "SlateBlue2") return TraCIColor(122, 103, 238, 255); if (tkColorName == "SlateBlue3") return TraCIColor(105, 89, 205, 255); if (tkColorName == "SlateBlue4") return TraCIColor(71, 60, 139, 255); if (tkColorName == "SlateGray") return TraCIColor(112, 128, 144, 255); if (tkColorName == "SlateGray1") return TraCIColor(198, 226, 255, 255); if (tkColorName == "SlateGray2") return TraCIColor(185, 211, 238, 255); if (tkColorName == "SlateGray3") return TraCIColor(159, 182, 205, 255); if (tkColorName == "SlateGray4") return TraCIColor(108, 123, 139, 255); if (tkColorName == "SlateGrey") return TraCIColor(112, 128, 144, 255); if (tkColorName == "snow") return TraCIColor(255, 250, 250, 255); if (tkColorName == "snow1") return TraCIColor(255, 250, 250, 255); if (tkColorName == "snow2") return TraCIColor(238, 233, 233, 255); if (tkColorName == "snow3") return TraCIColor(205, 201, 201, 255); if (tkColorName == "snow4") return TraCIColor(139, 137, 137, 255); if (tkColorName == "spring green") return TraCIColor(0, 255, 127, 255); if (tkColorName == "SpringGreen") return TraCIColor(0, 255, 127, 255); if (tkColorName == "SpringGreen1") return TraCIColor(0, 255, 127, 255); if (tkColorName == "SpringGreen2") return TraCIColor(0, 238, 118, 255); if (tkColorName == "SpringGreen3") return TraCIColor(0, 205, 102, 255); if (tkColorName == "SpringGreen4") return TraCIColor(0, 139, 69, 255); if (tkColorName == "steel blue") return TraCIColor(70, 130, 180, 255); if (tkColorName == "SteelBlue") return TraCIColor(70, 130, 180, 255); if (tkColorName == "SteelBlue1") return TraCIColor(99, 184, 255, 255); if (tkColorName == "SteelBlue2") return TraCIColor(92, 172, 238, 255); if (tkColorName == "SteelBlue3") return TraCIColor(79, 148, 205, 255); if (tkColorName == "SteelBlue4") return TraCIColor(54, 100, 139, 255); if (tkColorName == "tan") return TraCIColor(210, 180, 140, 255); if (tkColorName == "tan1") return TraCIColor(255, 165, 79, 255); if (tkColorName == "tan2") return TraCIColor(238, 154, 73, 255); if (tkColorName == "tan3") return TraCIColor(205, 133, 63, 255); if (tkColorName == "tan4") return TraCIColor(139, 90, 43, 255); if (tkColorName == "thistle") return TraCIColor(216, 191, 216, 255); if (tkColorName == "thistle1") return TraCIColor(255, 225, 255, 255); if (tkColorName == "thistle2") return TraCIColor(238, 210, 238, 255); if (tkColorName == "thistle3") return TraCIColor(205, 181, 205, 255); if (tkColorName == "thistle4") return TraCIColor(139, 123, 139, 255); if (tkColorName == "tomato") return TraCIColor(255, 99, 71, 255); if (tkColorName == "tomato1") return TraCIColor(255, 99, 71, 255); if (tkColorName == "tomato2") return TraCIColor(238, 92, 66, 255); if (tkColorName == "tomato3") return TraCIColor(205, 79, 57, 255); if (tkColorName == "tomato4") return TraCIColor(139, 54, 38, 255); if (tkColorName == "turquoise") return TraCIColor(64, 224, 208, 255); if (tkColorName == "turquoise1") return TraCIColor(0, 245, 255, 255); if (tkColorName == "turquoise2") return TraCIColor(0, 229, 238, 255); if (tkColorName == "turquoise3") return TraCIColor(0, 197, 205, 255); if (tkColorName == "turquoise4") return TraCIColor(0, 134, 139, 255); if (tkColorName == "violet") return TraCIColor(238, 130, 238, 255); if (tkColorName == "violet red") return TraCIColor(208, 32, 144, 255); if (tkColorName == "VioletRed") return TraCIColor(208, 32, 144, 255); if (tkColorName == "VioletRed1") return TraCIColor(255, 62, 150, 255); if (tkColorName == "VioletRed2") return TraCIColor(238, 58, 140, 255); if (tkColorName == "VioletRed3") return TraCIColor(205, 50, 120, 255); if (tkColorName == "VioletRed4") return TraCIColor(139, 34, 82, 255); if (tkColorName == "wheat") return TraCIColor(245, 222, 179, 255); if (tkColorName == "wheat1") return TraCIColor(255, 231, 186, 255); if (tkColorName == "wheat2") return TraCIColor(238, 216, 174, 255); if (tkColorName == "wheat3") return TraCIColor(205, 186, 150, 255); if (tkColorName == "wheat4") return TraCIColor(139, 126, 102, 255); if (tkColorName == "white") return TraCIColor(255, 255, 255, 255); if (tkColorName == "white smoke") return TraCIColor(245, 245, 245, 255); if (tkColorName == "WhiteSmoke") return TraCIColor(245, 245, 245, 255); if (tkColorName == "yellow") return TraCIColor(255, 255, 0, 255); if (tkColorName == "yellow green") return TraCIColor(154, 205, 50, 255); if (tkColorName == "yellow1") return TraCIColor(255, 255, 0, 255); if (tkColorName == "yellow2") return TraCIColor(238, 238, 0, 255); if (tkColorName == "yellow3") return TraCIColor(205, 205, 0, 255); if (tkColorName == "yellow4") return TraCIColor(139, 139, 0, 255); if (tkColorName == "YellowGreen") return TraCIColor(154, 205, 50, 255); throw cRuntimeError("unknown color name: %s", tkColorName.c_str()); }
56,742
70.735777
87
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIColor.h
// // Copyright (C) 2006-2011 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" namespace veins { /** * TraCI compatible color container */ class VEINS_API TraCIColor { public: TraCIColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha); static TraCIColor fromTkColor(std::string tkColorName); public: uint8_t red; uint8_t green; uint8_t blue; uint8_t alpha; }; } // namespace veins
1,293
27.755556
76
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCICommandInterface.cc
// // Copyright (C) 2006 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <stdlib.h> #include "veins/modules/mobility/traci/TraCIBuffer.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/mobility/traci/TraCIConnection.h" #include "veins/modules/mobility/traci/TraCIConstants.h" #include "veins/modules/mobility/traci/ParBuffer.h" #ifdef _WIN32 #define realpath(N, R) _fullpath((R), (N), _MAX_PATH) #endif /* _WIN32 */ using namespace veins::TraCIConstants; namespace veins { const std::map<uint32_t, TraCICommandInterface::VersionConfig> TraCICommandInterface::versionConfigs = { {20, {20, TYPE_DOUBLE, TYPE_POLYGON, VAR_TIME}}, {19, {19, TYPE_DOUBLE, TYPE_POLYGON, VAR_TIME}}, {18, {18, TYPE_DOUBLE, TYPE_POLYGON, VAR_TIME}}, {17, {17, TYPE_INTEGER, TYPE_BOUNDINGBOX, VAR_TIME_STEP}}, {16, {16, TYPE_INTEGER, TYPE_BOUNDINGBOX, VAR_TIME_STEP}}, {15, {15, TYPE_INTEGER, TYPE_BOUNDINGBOX, VAR_TIME_STEP}}, }; TraCICommandInterface::TraCICommandInterface(cComponent* owner, TraCIConnection& c, bool ignoreGuiCommands) : HasLogProxy(owner) , connection(c) , ignoreGuiCommands(ignoreGuiCommands) { } bool TraCICommandInterface::isIgnoringGuiCommands() { return ignoreGuiCommands; } std::pair<uint32_t, std::string> TraCICommandInterface::getVersion() { TraCIConnection::Result result; TraCIBuffer buf = connection.query(CMD_GETVERSION, TraCIBuffer(), &result); if (!result.success) { ASSERT(buf.eof()); return std::pair<uint32_t, std::string>(0, "(unknown)"); } uint8_t cmdLength; buf >> cmdLength; uint8_t commandResp; buf >> commandResp; ASSERT(commandResp == CMD_GETVERSION); uint32_t apiVersion; buf >> apiVersion; std::string serverVersion; buf >> serverVersion; ASSERT(buf.eof()); return std::pair<uint32_t, std::string>(apiVersion, serverVersion); } void TraCICommandInterface::setApiVersion(uint32_t apiVersion) { try { versionConfig = versionConfigs.at(apiVersion); TraCIBuffer::setTimeType(versionConfig.timeType); } catch (std::out_of_range const& exc) { throw cRuntimeError(std::string("TraCI server reports unsupported TraCI API version: " + std::to_string(apiVersion) + ". We recommend using Sumo version 1.0.1 or 0.32.0").c_str()); } } std::pair<TraCICoord, TraCICoord> TraCICommandInterface::initNetworkBoundaries(int margin) { // query road network boundaries TraCIBuffer buf = connection.query(CMD_GET_SIM_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_NET_BOUNDING_BOX) << std::string("sim0")); uint8_t cmdLength_resp; buf >> cmdLength_resp; uint8_t commandId_resp; buf >> commandId_resp; ASSERT(commandId_resp == RESPONSE_GET_SIM_VARIABLE); uint8_t variableId_resp; buf >> variableId_resp; ASSERT(variableId_resp == VAR_NET_BOUNDING_BOX); std::string simId; buf >> simId; uint8_t typeId_resp; buf >> typeId_resp; ASSERT(typeId_resp == getNetBoundaryType()); if (getNetBoundaryType() == TYPE_POLYGON) { // Polygons can have an arbitrary number of tuples, so check that it is actually 2 uint8_t npoints; buf >> npoints; ASSERT(npoints == 2); } double x1; buf >> x1; double y1; buf >> y1; double x2; buf >> x2; double y2; buf >> y2; ASSERT(buf.eof()); EV_DEBUG << "TraCI reports network boundaries (" << x1 << ", " << y1 << ")-(" << x2 << ", " << y2 << ")" << endl; TraCICoord nb1(x1, y1); TraCICoord nb2(x2, y2); connection.setNetbounds(nb1, nb2, margin); return {nb1, nb2}; } void TraCICommandInterface::Vehicle::setSpeedMode(int32_t bitset) { uint8_t variableId = VAR_SPEEDSETMODE; uint8_t variableType = TYPE_INTEGER; TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << bitset); ASSERT(buf.eof()); } void TraCICommandInterface::Vehicle::setSpeed(double speed) { uint8_t variableId = VAR_SPEED; uint8_t variableType = TYPE_DOUBLE; TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << speed); ASSERT(buf.eof()); } void TraCICommandInterface::Vehicle::setMaxSpeed(double speed) { uint8_t variableId = VAR_MAXSPEED; uint8_t variableType = TYPE_DOUBLE; TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << speed); ASSERT(buf.eof()); } TraCIColor TraCICommandInterface::Vehicle::getColor() { TraCIColor res(0, 0, 0, 0); TraCIBuffer p; p << static_cast<uint8_t>(VAR_COLOR); p << nodeId; TraCIBuffer buf = connection->query(CMD_GET_VEHICLE_VARIABLE, p); uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; uint8_t responseId = RESPONSE_GET_VEHICLE_VARIABLE; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; uint8_t variableId = VAR_COLOR; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; std::string objectId = nodeId; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; uint8_t resultTypeId = TYPE_COLOR; ASSERT(resType_r == resultTypeId); buf >> res.red; buf >> res.green; buf >> res.blue; buf >> res.alpha; ASSERT(buf.eof()); return res; } void TraCICommandInterface::Vehicle::setColor(const TraCIColor& color) { TraCIBuffer p; p << static_cast<uint8_t>(VAR_COLOR); p << nodeId; p << static_cast<uint8_t>(TYPE_COLOR) << color.red << color.green << color.blue << color.alpha; TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, p); ASSERT(buf.eof()); } void TraCICommandInterface::Vehicle::slowDown(double speed, simtime_t time) { uint8_t variableId = CMD_SLOWDOWN; uint8_t variableType = TYPE_COMPOUND; int32_t count = 2; uint8_t speedType = TYPE_DOUBLE; uint8_t durationType = traci->getTimeType(); TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << speedType << speed << durationType << time); ASSERT(buf.eof()); } void TraCICommandInterface::Vehicle::newRoute(std::string roadId) { uint8_t variableId = LANE_EDGE_ID; uint8_t variableType = TYPE_STRING; TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << roadId); ASSERT(buf.eof()); } void TraCICommandInterface::Vehicle::setParking() { throw cRuntimeError("TraCICommandInterface::Vehicle::setParking is non-functional as of SUMO 1.0.0"); } std::list<std::string> TraCICommandInterface::getVehicleTypeIds() { return genericGetStringList(CMD_GET_VEHICLETYPE_VARIABLE, "", ID_LIST, RESPONSE_GET_VEHICLETYPE_VARIABLE); } std::list<std::string> TraCICommandInterface::getRouteIds() { return genericGetStringList(CMD_GET_ROUTE_VARIABLE, "", ID_LIST, RESPONSE_GET_ROUTE_VARIABLE); } std::list<std::string> TraCICommandInterface::getRoadIds() { return genericGetStringList(CMD_GET_EDGE_VARIABLE, "", ID_LIST, RESPONSE_GET_EDGE_VARIABLE); } double TraCICommandInterface::Road::getCurrentTravelTime() { return traci->genericGetDouble(CMD_GET_EDGE_VARIABLE, roadId, VAR_CURRENT_TRAVELTIME, RESPONSE_GET_EDGE_VARIABLE); } double TraCICommandInterface::Road::getMeanSpeed() { return traci->genericGetDouble(CMD_GET_EDGE_VARIABLE, roadId, LAST_STEP_MEAN_SPEED, RESPONSE_GET_EDGE_VARIABLE); } std::string TraCICommandInterface::Vehicle::getRoadId() { return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ROAD_ID, RESPONSE_GET_VEHICLE_VARIABLE); } std::string TraCICommandInterface::Vehicle::getLaneId() { return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LANE_ID, RESPONSE_GET_VEHICLE_VARIABLE); } int32_t TraCICommandInterface::Vehicle::getLaneIndex() { return traci->genericGetInt(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LANE_INDEX, RESPONSE_GET_VEHICLE_VARIABLE); } std::string TraCICommandInterface::Vehicle::getTypeId() { return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_TYPE, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getMaxSpeed() { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_MAXSPEED, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getLanePosition() { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LANEPOSITION, RESPONSE_GET_VEHICLE_VARIABLE); } std::list<std::string> TraCICommandInterface::Vehicle::getPlannedRoadIds() { return traci->genericGetStringList(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_EDGES, RESPONSE_GET_VEHICLE_VARIABLE); } std::string TraCICommandInterface::Vehicle::getRouteId() { return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ROUTE_ID, RESPONSE_GET_VEHICLE_VARIABLE); } std::list<std::string> TraCICommandInterface::Route::getRoadIds() { return traci->genericGetStringList(CMD_GET_ROUTE_VARIABLE, routeId, VAR_EDGES, RESPONSE_GET_ROUTE_VARIABLE); } void TraCICommandInterface::Vehicle::changeRoute(std::string roadId, simtime_t travelTime) { if (travelTime >= 0) { uint8_t variableId = VAR_EDGE_TRAVELTIME; uint8_t variableType = TYPE_COMPOUND; int32_t count = 2; uint8_t edgeIdT = TYPE_STRING; std::string edgeId = roadId; uint8_t newTimeT = TYPE_DOUBLE; // has always been seconds as double double newTime = travelTime.dbl(); TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << edgeIdT << edgeId << newTimeT << newTime); ASSERT(buf.eof()); } else { uint8_t variableId = VAR_EDGE_TRAVELTIME; uint8_t variableType = TYPE_COMPOUND; int32_t count = 1; uint8_t edgeIdT = TYPE_STRING; std::string edgeId = roadId; TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << edgeIdT << edgeId); ASSERT(buf.eof()); } { uint8_t variableId = CMD_REROUTE_TRAVELTIME; uint8_t variableType = TYPE_COMPOUND; int32_t count = 0; TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count); ASSERT(buf.eof()); } } double TraCICommandInterface::Vehicle::getLength() { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LENGTH, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getWidth() { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_WIDTH, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getHeight() { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_HEIGHT, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getAccel() { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ACCEL, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getDeccel() { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_DECEL, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getCO2Emissions() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_CO2EMISSION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getCOEmissions() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_COEMISSION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getHCEmissions() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_HCEMISSION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getPMxEmissions() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_PMXEMISSION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getNOxEmissions() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_NOXEMISSION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getFuelConsumption() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_FUELCONSUMPTION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getNoiseEmission() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_NOISEEMISSION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getElectricityConsumption() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ELECTRICITYCONSUMPTION, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getWaitingTime() const { return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_WAITING_TIME, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::Vehicle::getAccumulatedWaitingTime() const { const auto apiVersion = traci->versionConfig.version; if (apiVersion <= 15) { throw cRuntimeError("TraCICommandInterface::Vehicle::getAccumulatedWaitingTime requires SUMO 0.31.0 or newer"); } return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_WAITING_TIME_ACCUMULATED, RESPONSE_GET_VEHICLE_VARIABLE); } double TraCICommandInterface::getDistance(const Coord& p1, const Coord& p2, bool returnDrivingDistance) { uint8_t variable = DISTANCE_REQUEST; std::string simId = "sim0"; uint8_t variableType = TYPE_COMPOUND; int32_t count = 3; uint8_t dType = static_cast<uint8_t>(returnDrivingDistance ? REQUEST_DRIVINGDIST : REQUEST_AIRDIST); // query road network boundaries TraCIBuffer buf = connection.query(CMD_GET_SIM_VARIABLE, TraCIBuffer() << variable << simId << variableType << count << connection.omnet2traci(p1) << connection.omnet2traci(p2) << dType); uint8_t cmdLength_resp; buf >> cmdLength_resp; uint8_t commandId_resp; buf >> commandId_resp; ASSERT(commandId_resp == RESPONSE_GET_SIM_VARIABLE); uint8_t variableId_resp; buf >> variableId_resp; ASSERT(variableId_resp == variable); std::string simId_resp; buf >> simId_resp; ASSERT(simId_resp == simId); uint8_t typeId_resp; buf >> typeId_resp; ASSERT(typeId_resp == TYPE_DOUBLE); double distance; buf >> distance; ASSERT(buf.eof()); return distance; } void TraCICommandInterface::Vehicle::stopAt(std::string roadId, double pos, uint8_t laneid, double radius, simtime_t waittime) { uint8_t variableId = CMD_STOP; uint8_t variableType = TYPE_COMPOUND; int32_t count = 4; uint8_t edgeIdT = TYPE_STRING; std::string edgeId = roadId; uint8_t stopPosT = TYPE_DOUBLE; double stopPos = pos; uint8_t stopLaneT = TYPE_BYTE; uint8_t stopLane = laneid; uint8_t durationT = traci->getTimeType(); simtime_t duration = waittime; TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << edgeIdT << edgeId << stopPosT << stopPos << stopLaneT << stopLane << durationT << duration); ASSERT(buf.eof()); } std::list<std::string> TraCICommandInterface::getTrafficlightIds() { return genericGetStringList(CMD_GET_TL_VARIABLE, "", ID_LIST, RESPONSE_GET_TL_VARIABLE); } std::string TraCICommandInterface::Trafficlight::getCurrentState() const { return traci->genericGetString(CMD_GET_TL_VARIABLE, trafficLightId, TL_RED_YELLOW_GREEN_STATE, RESPONSE_GET_TL_VARIABLE); } simtime_t TraCICommandInterface::Trafficlight::getDefaultCurrentPhaseDuration() const { return traci->genericGetTime(CMD_GET_TL_VARIABLE, trafficLightId, TL_PHASE_DURATION, RESPONSE_GET_TL_VARIABLE); } std::list<std::string> TraCICommandInterface::Trafficlight::getControlledLanes() const { return traci->genericGetStringList(CMD_GET_TL_VARIABLE, trafficLightId, TL_CONTROLLED_LANES, RESPONSE_GET_TL_VARIABLE); } std::list<std::list<TraCITrafficLightLink>> TraCICommandInterface::Trafficlight::getControlledLinks() const { uint8_t resultTypeId = TYPE_COMPOUND; uint8_t commandId = CMD_GET_TL_VARIABLE; uint8_t variableId = TL_CONTROLLED_LINKS; std::string objectId = trafficLightId; uint8_t responseId = RESPONSE_GET_TL_VARIABLE; TraCIBuffer buf = connection->query(commandId, TraCIBuffer() << variableId << objectId); // generic header uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); int32_t compoundSize; buf >> compoundSize; // nr of fields in the compound int32_t nrOfSignals = buf.readTypeChecked<int32_t>(TYPE_INTEGER); std::list<std::list<TraCITrafficLightLink>> controlledLinks; for (int32_t i = 0; i < nrOfSignals; ++i) { int32_t nrOfLinks = buf.readTypeChecked<int32_t>(TYPE_INTEGER); std::list<TraCITrafficLightLink> linksOfSignal; uint8_t stringListType; buf >> stringListType; ASSERT(stringListType == static_cast<uint8_t>(TYPE_STRINGLIST)); for (int32_t j = 0; j < nrOfLinks; ++j) { int32_t stringCount; buf >> stringCount; ASSERT(stringCount == 3); TraCITrafficLightLink link; buf >> link.incoming; buf >> link.outgoing; buf >> link.internal; linksOfSignal.push_back(link); } controlledLinks.push_back(linksOfSignal); } return controlledLinks; } int32_t TraCICommandInterface::Trafficlight::getCurrentPhaseIndex() const { return traci->genericGetInt(CMD_GET_TL_VARIABLE, trafficLightId, TL_CURRENT_PHASE, RESPONSE_GET_TL_VARIABLE); } std::string TraCICommandInterface::Trafficlight::getCurrentProgramID() const { return traci->genericGetString(CMD_GET_TL_VARIABLE, trafficLightId, TL_CURRENT_PROGRAM, RESPONSE_GET_TL_VARIABLE); } TraCITrafficLightProgram TraCICommandInterface::Trafficlight::getProgramDefinition() const { uint8_t resultTypeId = TYPE_COMPOUND; TraCITrafficLightProgram program(trafficLightId); const auto apiVersion = traci->versionConfig.version; if (apiVersion == 15 || apiVersion == 16 || apiVersion == 17 || apiVersion == 18) { uint8_t commandId = CMD_GET_TL_VARIABLE; uint8_t variableId = TL_COMPLETE_DEFINITION_RYG; std::string objectId = trafficLightId; uint8_t responseId = RESPONSE_GET_TL_VARIABLE; TraCIBuffer buf = connection->query(commandId, TraCIBuffer() << variableId << objectId); // generic header uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); int32_t compoundSize; buf >> compoundSize; // nr of fields in the compound int32_t nrOfLogics = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // nr of logics in the compound for (int32_t i = 0; i < nrOfLogics; ++i) { TraCITrafficLightProgram::Logic logic; logic.id = buf.readTypeChecked<std::string>(TYPE_STRING); // program ID logic.type = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // (sub)type - currently just a 0 logic.parameter = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // (sub)parameter - currently just a 0 logic.currentPhase = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // phase index int32_t nrOfPhases = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // number of phases in this program for (int32_t j = 0; j < nrOfPhases; ++j) { TraCITrafficLightProgram::Phase phase; phase.duration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // default duration of phase phase.minDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // minimum duration of phase phase.maxDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // maximum duration of phase phase.state = buf.readTypeChecked<std::string>(TYPE_STRING); // phase definition (like "[ryg]*") logic.phases.push_back(phase); } program.addLogic(logic); } } else if (apiVersion == 19 || apiVersion == 20) { uint8_t commandId = CMD_GET_TL_VARIABLE; uint8_t variableId = TL_COMPLETE_DEFINITION_RYG; std::string objectId = trafficLightId; uint8_t responseId = RESPONSE_GET_TL_VARIABLE; TraCIBuffer buf = connection->query(commandId, TraCIBuffer() << variableId << objectId); // generic header uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); int32_t nrOfLogics = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // nr of logics in the compound for (int32_t i = 0; i < nrOfLogics; ++i) { int32_t nrOfComps = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); ASSERT(nrOfComps == 5); TraCITrafficLightProgram::Logic logic; logic.id = buf.readTypeChecked<std::string>(TYPE_STRING); // program ID logic.type = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // (sub)type - currently just a 0 logic.currentPhase = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // phase index int32_t nrOfPhases = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // number of phases in this program for (int32_t j = 0; j < nrOfPhases; ++j) { TraCITrafficLightProgram::Phase phase; int32_t nrOfComps = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); ASSERT((apiVersion == 19 && nrOfComps == 5) || (apiVersion == 20 && nrOfComps == 6)); phase.duration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // default duration of phase phase.state = buf.readTypeChecked<std::string>(TYPE_STRING); // phase definition (like "[ryg]*") phase.minDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // minimum duration of phase phase.maxDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // maximum duration of phase if (apiVersion <= 19) { phase.next = {buf.readTypeChecked<int32_t>(TYPE_INTEGER)}; } else { int32_t nextCount = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); phase.next = {}; for (int32_t k = 0; k < nextCount; ++k) { phase.next.push_back(buf.readTypeChecked<int32_t>(TYPE_INTEGER)); } } if (apiVersion == 20) { phase.name = buf.readTypeChecked<std::string>(TYPE_STRING); } logic.phases.push_back(phase); } int32_t nrOfSubpars = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // nr of subparameters for (int32_t j = 0; j < nrOfSubpars; ++j) { uint8_t stringListType; buf >> stringListType; ASSERT(stringListType == static_cast<uint8_t>(TYPE_STRINGLIST)); std::string s1; buf >> s1; // discard std::string s2; buf >> s2; // discard } program.addLogic(logic); } } else { throw cRuntimeError("Invalid API version used, check your code."); } return program; } simtime_t TraCICommandInterface::Trafficlight::getAssumedNextSwitchTime() const { return traci->genericGetTime(CMD_GET_TL_VARIABLE, trafficLightId, TL_NEXT_SWITCH, RESPONSE_GET_TL_VARIABLE); } void TraCICommandInterface::Trafficlight::setState(std::string state) { TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_RED_YELLOW_GREEN_STATE) << trafficLightId << static_cast<uint8_t>(TYPE_STRING) << state); ASSERT(buf.eof()); } void TraCICommandInterface::Trafficlight::setPhaseDuration(simtime_t duration) { TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_PHASE_DURATION) << trafficLightId << static_cast<uint8_t>(traci->getTimeType()) << duration); ASSERT(buf.eof()); } void TraCICommandInterface::Trafficlight::setProgramDefinition(TraCITrafficLightProgram::Logic logic, int32_t logicNr) { TraCIBuffer inbuf; const auto apiVersion = traci->versionConfig.version; if (apiVersion == 15 || apiVersion == 16 || apiVersion == 17 || apiVersion == 18) { inbuf << static_cast<uint8_t>(TL_COMPLETE_PROGRAM_RYG); inbuf << trafficLightId; inbuf << static_cast<uint8_t>(TYPE_COMPOUND); inbuf << logicNr; inbuf << static_cast<uint8_t>(TYPE_STRING); inbuf << logic.id; inbuf << static_cast<uint8_t>(TYPE_INTEGER); // (sub)type - currently unused inbuf << logic.type; inbuf << static_cast<uint8_t>(TYPE_COMPOUND); // (sub)parameter - currently unused inbuf << logic.parameter; inbuf << static_cast<uint8_t>(TYPE_INTEGER); inbuf << logic.currentPhase; inbuf << static_cast<uint8_t>(TYPE_INTEGER); inbuf << static_cast<int32_t>(logic.phases.size()); for (uint32_t i = 0; i < logic.phases.size(); ++i) { TraCITrafficLightProgram::Phase& phase = logic.phases[i]; inbuf << static_cast<uint8_t>(traci->getTimeType()); inbuf << phase.duration; inbuf << static_cast<uint8_t>(traci->getTimeType()); inbuf << phase.minDuration; inbuf << static_cast<uint8_t>(traci->getTimeType()); inbuf << phase.maxDuration; inbuf << static_cast<uint8_t>(TYPE_STRING); inbuf << phase.state; } } else if (apiVersion == 19 || apiVersion == 20) { inbuf << static_cast<uint8_t>(TL_COMPLETE_PROGRAM_RYG); inbuf << trafficLightId; inbuf << static_cast<uint8_t>(TYPE_COMPOUND); inbuf << 5; inbuf << static_cast<uint8_t>(TYPE_STRING); inbuf << logic.id; inbuf << static_cast<uint8_t>(TYPE_INTEGER); // (sub)type - currently unused inbuf << logic.type; inbuf << static_cast<uint8_t>(TYPE_INTEGER); inbuf << logic.currentPhase; inbuf << static_cast<uint8_t>(TYPE_COMPOUND); inbuf << static_cast<int32_t>(logic.phases.size()); for (uint32_t i = 0; i < logic.phases.size(); ++i) { TraCITrafficLightProgram::Phase& phase = logic.phases[i]; inbuf << static_cast<uint8_t>(TYPE_COMPOUND); inbuf << int32_t((apiVersion == 19) ? 5 : 6); inbuf << static_cast<uint8_t>(traci->getTimeType()); inbuf << phase.duration; inbuf << static_cast<uint8_t>(TYPE_STRING); inbuf << phase.state; inbuf << static_cast<uint8_t>(traci->getTimeType()); inbuf << phase.minDuration; inbuf << static_cast<uint8_t>(traci->getTimeType()); inbuf << phase.maxDuration; if (apiVersion <= 19) { inbuf << static_cast<uint8_t>(TYPE_INTEGER); if (phase.next.size() == 0) { inbuf << static_cast<int32_t>(0); } else if (phase.next.size() == 1) { inbuf << static_cast<int32_t>(phase.next[0]); } else { throw cRuntimeError("Setting multiple phase.next requires a newer version of SUMO"); } } else { inbuf << static_cast<uint8_t>(TYPE_COMPOUND); inbuf << static_cast<int32_t>(phase.next.size()); for (int32_t next : phase.next) { inbuf << static_cast<uint8_t>(TYPE_INTEGER); inbuf << next; } } if (apiVersion == 20) { inbuf << static_cast<uint8_t>(TYPE_STRING); inbuf << phase.name; } } // no subparameters inbuf << static_cast<uint8_t>(TYPE_COMPOUND); inbuf << int32_t(0); } else { throw cRuntimeError("Invalid API version used, check your code."); } TraCIBuffer obuf = connection->query(CMD_SET_TL_VARIABLE, inbuf); ASSERT(obuf.eof()); } void TraCICommandInterface::Trafficlight::setProgram(std::string program) { TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_PROGRAM) << trafficLightId << static_cast<uint8_t>(TYPE_STRING) << program); ASSERT(buf.eof()); } void TraCICommandInterface::Trafficlight::setPhaseIndex(int32_t index) { TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_PHASE_INDEX) << trafficLightId << static_cast<uint8_t>(TYPE_INTEGER) << index); ASSERT(buf.eof()); } std::list<std::string> TraCICommandInterface::getPolygonIds() { return genericGetStringList(CMD_GET_POLYGON_VARIABLE, "", ID_LIST, RESPONSE_GET_POLYGON_VARIABLE); } std::string TraCICommandInterface::Polygon::getTypeId() { return traci->genericGetString(CMD_GET_POLYGON_VARIABLE, polyId, VAR_TYPE, RESPONSE_GET_POLYGON_VARIABLE); } std::list<Coord> TraCICommandInterface::Polygon::getShape() { return traci->genericGetCoordList(CMD_GET_POLYGON_VARIABLE, polyId, VAR_SHAPE, RESPONSE_GET_POLYGON_VARIABLE); } void TraCICommandInterface::Polygon::setShape(const std::list<Coord>& points) { TraCIBuffer buf; uint8_t count = static_cast<uint8_t>(points.size()); buf << static_cast<uint8_t>(VAR_SHAPE) << polyId << static_cast<uint8_t>(TYPE_POLYGON) << count; for (std::list<Coord>::const_iterator i = points.begin(); i != points.end(); ++i) { const TraCICoord& pos = connection->omnet2traci(*i); buf << static_cast<double>(pos.x) << static_cast<double>(pos.y); } TraCIBuffer obuf = connection->query(CMD_SET_POLYGON_VARIABLE, buf); ASSERT(obuf.eof()); } void TraCICommandInterface::addPolygon(std::string polyId, std::string polyType, const TraCIColor& color, bool filled, int32_t layer, const std::list<Coord>& points) { TraCIBuffer p; p << static_cast<uint8_t>(ADD) << polyId; p << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(5); p << static_cast<uint8_t>(TYPE_STRING) << polyType; p << static_cast<uint8_t>(TYPE_COLOR) << color.red << color.green << color.blue << color.alpha; p << static_cast<uint8_t>(TYPE_UBYTE) << static_cast<uint8_t>(filled); p << static_cast<uint8_t>(TYPE_INTEGER) << layer; p << static_cast<uint8_t>(TYPE_POLYGON) << static_cast<uint8_t>(points.size()); for (std::list<Coord>::const_iterator i = points.begin(); i != points.end(); ++i) { const TraCICoord& pos = connection.omnet2traci(*i); p << static_cast<double>(pos.x) << static_cast<double>(pos.y); } TraCIBuffer buf = connection.query(CMD_SET_POLYGON_VARIABLE, p); ASSERT(buf.eof()); } void TraCICommandInterface::Polygon::remove(int32_t layer) { TraCIBuffer p; p << static_cast<uint8_t>(REMOVE) << polyId; p << static_cast<uint8_t>(TYPE_INTEGER) << layer; TraCIBuffer buf = connection->query(CMD_SET_POLYGON_VARIABLE, p); ASSERT(buf.eof()); } std::list<std::string> TraCICommandInterface::getPoiIds() { return genericGetStringList(CMD_GET_POI_VARIABLE, "", ID_LIST, RESPONSE_GET_POI_VARIABLE); } void TraCICommandInterface::addPoi(std::string poiId, std::string poiType, const TraCIColor& color, int32_t layer, const Coord& pos_) { TraCIBuffer p; TraCICoord pos = connection.omnet2traci(pos_); p << static_cast<uint8_t>(ADD) << poiId; p << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(4); p << static_cast<uint8_t>(TYPE_STRING) << poiType; p << static_cast<uint8_t>(TYPE_COLOR) << color.red << color.green << color.blue << color.alpha; p << static_cast<uint8_t>(TYPE_INTEGER) << layer; p << pos; TraCIBuffer buf = connection.query(CMD_SET_POI_VARIABLE, p); ASSERT(buf.eof()); } void TraCICommandInterface::Poi::remove(int32_t layer) { TraCIBuffer p; p << static_cast<uint8_t>(REMOVE) << poiId; p << static_cast<uint8_t>(TYPE_INTEGER) << layer; TraCIBuffer buf = connection->query(CMD_SET_POI_VARIABLE, p); ASSERT(buf.eof()); } std::list<std::string> TraCICommandInterface::getLaneIds() { return genericGetStringList(CMD_GET_LANE_VARIABLE, "", ID_LIST, RESPONSE_GET_LANE_VARIABLE); } std::list<Coord> TraCICommandInterface::Lane::getShape() { return traci->genericGetCoordList(CMD_GET_LANE_VARIABLE, laneId, VAR_SHAPE, RESPONSE_GET_LANE_VARIABLE); } std::string TraCICommandInterface::Lane::getRoadId() { return traci->genericGetString(CMD_GET_LANE_VARIABLE, laneId, LANE_EDGE_ID, RESPONSE_GET_LANE_VARIABLE); } double TraCICommandInterface::Lane::getLength() { return traci->genericGetDouble(CMD_GET_LANE_VARIABLE, laneId, VAR_LENGTH, RESPONSE_GET_LANE_VARIABLE); } double TraCICommandInterface::Lane::getMaxSpeed() { return traci->genericGetDouble(CMD_GET_LANE_VARIABLE, laneId, VAR_MAXSPEED, RESPONSE_GET_LANE_VARIABLE); } double TraCICommandInterface::Lane::getMeanSpeed() { return traci->genericGetDouble(CMD_GET_LANE_VARIABLE, laneId, LAST_STEP_MEAN_SPEED, RESPONSE_GET_LANE_VARIABLE); } std::list<std::string> TraCICommandInterface::getLaneAreaDetectorIds() { return genericGetStringList(CMD_GET_LANEAREA_VARIABLE, "", ID_LIST, RESPONSE_GET_LANEAREA_VARIABLE); } int TraCICommandInterface::LaneAreaDetector::getLastStepVehicleNumber() { return traci->genericGetInt(CMD_GET_LANEAREA_VARIABLE, laneAreaDetectorId, LAST_STEP_VEHICLE_NUMBER, RESPONSE_GET_LANEAREA_VARIABLE); } std::list<std::string> TraCICommandInterface::getJunctionIds() { return genericGetStringList(CMD_GET_JUNCTION_VARIABLE, "", ID_LIST, RESPONSE_GET_JUNCTION_VARIABLE); } Coord TraCICommandInterface::Junction::getPosition() { return traci->genericGetCoord(CMD_GET_JUNCTION_VARIABLE, junctionId, VAR_POSITION, RESPONSE_GET_JUNCTION_VARIABLE); } bool TraCICommandInterface::addVehicle(std::string vehicleId, std::string vehicleTypeId, std::string routeId, simtime_t emitTime_st, double emitPosition, double emitSpeed, int8_t emitLane) { TraCIConnection::Result result; uint8_t variableId = ADD; uint8_t variableType = TYPE_COMPOUND; int32_t count = 6; int32_t emitTime = (emitTime_st < 0) ? round(emitTime_st.dbl()) : (floor(emitTime_st.dbl() * 1000)); TraCIBuffer buf = connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << vehicleId << variableType << count << (uint8_t) TYPE_STRING << vehicleTypeId << (uint8_t) TYPE_STRING << routeId << (uint8_t) TYPE_INTEGER << emitTime << (uint8_t) TYPE_DOUBLE << emitPosition << (uint8_t) TYPE_DOUBLE << emitSpeed << (uint8_t) TYPE_BYTE << emitLane, &result); ASSERT(buf.eof()); return result.success; } bool TraCICommandInterface::Vehicle::changeVehicleRoute(const std::list<std::string>& edges) { if (getRoadId().find(':') != std::string::npos) return false; if (edges.front().compare(getRoadId()) != 0) return false; uint8_t variableId = VAR_ROUTE; uint8_t variableType = TYPE_STRINGLIST; TraCIBuffer buf; buf << variableId << nodeId << variableType; int32_t numElem = edges.size(); buf << numElem; for (std::list<std::string>::const_iterator i = edges.begin(); i != edges.end(); ++i) { buf << static_cast<std::string>(*i); } TraCIBuffer obuf = connection->query(CMD_SET_VEHICLE_VARIABLE, buf); ASSERT(obuf.eof()); return true; } void TraCICommandInterface::Vehicle::setParameter(const std::string& parameter, int value) { std::stringstream strValue; strValue << value; setParameter(parameter, strValue.str()); } void TraCICommandInterface::Vehicle::setParameter(const std::string& parameter, double value) { std::stringstream strValue; strValue << value; setParameter(parameter, strValue.str()); } void TraCICommandInterface::Vehicle::setParameter(const std::string& parameter, const std::string& value) { static int32_t nParameters = 2; TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_PARAMETER) << nodeId << static_cast<uint8_t>(TYPE_COMPOUND) << nParameters << static_cast<uint8_t>(TYPE_STRING) << parameter << static_cast<uint8_t>(TYPE_STRING) << value); ASSERT(buf.eof()); } void TraCICommandInterface::Vehicle::getParameter(const std::string& parameter, int& value) { std::string v; getParameter(parameter, v); ParBuffer buf(v); buf >> value; } void TraCICommandInterface::Vehicle::getParameter(const std::string& parameter, double& value) { std::string v; getParameter(parameter, v); ParBuffer buf(v); buf >> value; } void TraCICommandInterface::Vehicle::getParameter(const std::string& parameter, std::string& value) { TraCIBuffer response = traci->connection.query(CMD_GET_VEHICLE_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_PARAMETER) << nodeId << static_cast<uint8_t>(TYPE_STRING) << parameter); uint8_t cmdLength; response >> cmdLength; uint8_t responseId; response >> responseId; ASSERT(responseId == RESPONSE_GET_VEHICLE_VARIABLE); uint8_t variable; response >> variable; ASSERT(variable == VAR_PARAMETER); std::string id; response >> id; ASSERT(id == nodeId); uint8_t type; response >> type; ASSERT(type == TYPE_STRING); response >> value; } std::pair<double, double> TraCICommandInterface::getLonLat(const Coord& coord) { TraCIBuffer request; request << static_cast<uint8_t>(POSITION_CONVERSION) << std::string("sim0") << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(2) << connection.omnet2traci(coord) << static_cast<uint8_t>(TYPE_UBYTE) << static_cast<uint8_t>(POSITION_LON_LAT); TraCIBuffer response = connection.query(CMD_GET_SIM_VARIABLE, request); uint8_t cmdLength; response >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; response >> cmdLengthX; } uint8_t responseId; response >> responseId; ASSERT(responseId == RESPONSE_GET_SIM_VARIABLE); uint8_t variable; response >> variable; ASSERT(variable == POSITION_CONVERSION); std::string id; response >> id; uint8_t convPosType; response >> convPosType; ASSERT(convPosType == POSITION_LON_LAT); double convPosLon; response >> convPosLon; double convPosLat; response >> convPosLat; return std::make_pair(convPosLon, convPosLat); } std::tuple<std::string, double, uint8_t> TraCICommandInterface::getRoadMapPos(const Coord& coord) { TraCIBuffer request; request << static_cast<uint8_t>(POSITION_CONVERSION) << std::string("sim0") << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(2) << connection.omnet2traci(coord) << static_cast<uint8_t>(TYPE_UBYTE) << static_cast<uint8_t>(POSITION_ROADMAP); TraCIBuffer response = connection.query(CMD_GET_SIM_VARIABLE, request); uint8_t cmdLength; response >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; response >> cmdLengthX; } uint8_t responseId; response >> responseId; ASSERT(responseId == RESPONSE_GET_SIM_VARIABLE); uint8_t variable; response >> variable; ASSERT(variable == POSITION_CONVERSION); std::string id; response >> id; uint8_t convPosType; response >> convPosType; ASSERT(convPosType == POSITION_ROADMAP); std::string convRoadId; response >> convRoadId; double convPos; response >> convPos; uint8_t convLaneId; response >> convLaneId; return std::make_tuple(convRoadId, convPos, convLaneId); } std::list<std::string> TraCICommandInterface::getGuiViewIds() { if (ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return std::list<std::string>(); } return genericGetStringList(CMD_GET_GUI_VARIABLE, "", ID_LIST, RESPONSE_GET_GUI_VARIABLE); } std::string TraCICommandInterface::GuiView::getScheme() { if (traci->ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return std::string(); } return traci->genericGetString(CMD_GET_GUI_VARIABLE, viewId, VAR_VIEW_SCHEMA, RESPONSE_GET_GUI_VARIABLE); } void TraCICommandInterface::GuiView::setScheme(std::string name) { if (traci->ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return; } TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_SCHEMA) << viewId << static_cast<uint8_t>(TYPE_STRING) << name); ASSERT(buf.eof()); } double TraCICommandInterface::GuiView::getZoom() { if (traci->ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return 0; } return traci->genericGetDouble(CMD_GET_GUI_VARIABLE, viewId, VAR_VIEW_ZOOM, RESPONSE_GET_GUI_VARIABLE); } void TraCICommandInterface::GuiView::setZoom(double zoom) { if (traci->ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return; } TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_ZOOM) << viewId << static_cast<uint8_t>(TYPE_DOUBLE) << zoom); ASSERT(buf.eof()); } void TraCICommandInterface::GuiView::setBoundary(Coord p1_, Coord p2_) { if (traci->ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return; } TraCICoord p1 = connection->omnet2traci(p1_); TraCICoord p2 = connection->omnet2traci(p2_); if (traci->getNetBoundaryType() == TYPE_POLYGON) { uint8_t count = 2; TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_BOUNDARY) << viewId << static_cast<uint8_t>(TYPE_POLYGON) << count << p1.x << p1.y << p2.x << p2.y); ASSERT(buf.eof()); } else { TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_BOUNDARY) << viewId << static_cast<uint8_t>(TYPE_BOUNDINGBOX) << p1.x << p1.y << p2.x << p2.y); ASSERT(buf.eof()); } } void TraCICommandInterface::GuiView::takeScreenshot(std::string filename, int32_t width, int32_t height) { if (traci->ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return; } if (filename == "") { // get absolute path of results/ directory const char* myResultsDir = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RESULTDIR); char* s = realpath(myResultsDir, nullptr); std::string absolutePath = s; free(s); // get run id const char* myRunID = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNID); // build filename from this char ss[512]; snprintf(ss, sizeof(ss), "%s/screenshot-%s-@%08.2f.png", absolutePath.c_str(), myRunID, simTime().dbl()); filename = ss; } const auto apiVersion = traci->versionConfig.version; if (apiVersion == 15 || apiVersion == 16 || apiVersion == 17) { uint8_t variableType = TYPE_COMPOUND; int32_t count = 3; uint8_t filenameType = TYPE_STRING; uint8_t widthType = TYPE_INTEGER; uint8_t heightType = TYPE_INTEGER; TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_SCREENSHOT) << viewId << variableType << count << filenameType << filename << widthType << width << heightType << height); ASSERT(buf.eof()); } else if (apiVersion == 18 || apiVersion == 19 || apiVersion == 20) { uint8_t filenameType = TYPE_STRING; TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_SCREENSHOT) << viewId << filenameType << filename); ASSERT(buf.eof()); } else { throw cRuntimeError("Invalid API version used, check your code."); } } void TraCICommandInterface::GuiView::trackVehicle(std::string vehicleId) { if (traci->ignoreGuiCommands) { EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl; return; } TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_TRACK_VEHICLE) << viewId << static_cast<uint8_t>(TYPE_STRING) << vehicleId); ASSERT(buf.eof()); } std::string TraCICommandInterface::genericGetString(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result) { uint8_t resultTypeId = TYPE_STRING; std::string res; TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result); if ((result != nullptr) && (!result->success)) { return res; } uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); buf >> res; ASSERT(buf.eof()); return res; } Coord TraCICommandInterface::genericGetCoord(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result) { uint8_t resultTypeId = POSITION_2D; double x; double y; TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result); if ((result != nullptr) && (!result->success)) { return Coord(); } uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); buf >> x; buf >> y; ASSERT(buf.eof()); return connection.traci2omnet(TraCICoord(x, y)); } double TraCICommandInterface::genericGetDouble(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result) { uint8_t resultTypeId = TYPE_DOUBLE; double res; TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result); if ((result != nullptr) && (!result->success)) { return 0; } uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); buf >> res; ASSERT(buf.eof()); return res; } simtime_t TraCICommandInterface::genericGetTime(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result) { uint8_t resultTypeId = getTimeType(); simtime_t res; TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result); if ((result != nullptr) && (!result->success)) { return res; } uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); buf >> res; ASSERT(buf.eof()); return res; } int32_t TraCICommandInterface::genericGetInt(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result) { uint8_t resultTypeId = TYPE_INTEGER; int32_t res; TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result); if ((result != nullptr) && (!result->success)) { return 0; } uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); buf >> res; ASSERT(buf.eof()); return res; } std::list<std::string> TraCICommandInterface::genericGetStringList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result) { uint8_t resultTypeId = TYPE_STRINGLIST; std::list<std::string> res; TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result); if ((result != nullptr) && (!result->success)) { return res; } uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); uint32_t count; buf >> count; for (uint32_t i = 0; i < count; i++) { std::string id; buf >> id; res.push_back(id); } ASSERT(buf.eof()); return res; } std::list<Coord> TraCICommandInterface::genericGetCoordList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result) { uint8_t resultTypeId = TYPE_POLYGON; std::list<Coord> res; TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result); if ((result != nullptr) && (!result->success)) { return res; } uint8_t cmdLength; buf >> cmdLength; if (cmdLength == 0) { uint32_t cmdLengthX; buf >> cmdLengthX; } uint8_t commandId_r; buf >> commandId_r; ASSERT(commandId_r == responseId); uint8_t varId; buf >> varId; ASSERT(varId == variableId); std::string objectId_r; buf >> objectId_r; ASSERT(objectId_r == objectId); uint8_t resType_r; buf >> resType_r; ASSERT(resType_r == resultTypeId); uint8_t count; buf >> count; for (uint32_t i = 0; i < count; i++) { double x; buf >> x; double y; buf >> y; res.push_back(connection.traci2omnet(TraCICoord(x, y))); } ASSERT(buf.eof()); return res; } std::string TraCICommandInterface::Vehicle::getVType() { return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_TYPE, RESPONSE_GET_VEHICLE_VARIABLE); } } // namespace veins
54,381
35.254667
371
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCICommandInterface.h
// // Copyright (C) 2006 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <list> #include <string> #include <stdint.h> #include "veins/modules/mobility/traci/TraCIColor.h" #include "veins/base/utils/Coord.h" #include "veins/modules/mobility/traci/TraCICoord.h" #include "veins/modules/mobility/traci/TraCIConnection.h" #include "veins/modules/world/traci/trafficLight/TraCITrafficLightProgram.h" #include "veins/modules/utility/HasLogProxy.h" namespace veins { class VEINS_API TraCICommandInterface : public HasLogProxy { public: TraCICommandInterface(cComponent* owner, TraCIConnection& c, bool ignoreGuiCommands); bool isIgnoringGuiCommands(); enum DepartTime { DEPART_TIME_TRIGGERED = -1, DEPART_TIME_CONTAINER_TRIGGERED = -2, DEPART_TIME_NOW = -3, // Not yet documented and fully implemented (Sumo 0.30.0) }; enum DepartSpeed { DEPART_SPEED_RANDOM = -2, DEPART_SPEED_MAX = -3, }; enum DepartPosition { DEPART_POSITION_RANDOM = -2, DEPART_POSITION_FREE = -3, DEPART_POSITION_BASE = -4, DEPART_POSITION_LAST = -5, DEPART_POSITION_RANDOM_FREE = -6, }; enum DepartLane { DEPART_LANE_RANDOM = -2, // A random lane DEPART_LANE_FREE = -3, // The least occupied lane DEPART_LANE_ALLOWED = -4, // The least occupied lane which allows continuation DEPART_LANE_BEST = -5, // The least occupied of the best lanes DEPART_LANE_FIRST = -6, // The rightmost valid }; // General methods that do not deal with a particular object in the simulation std::pair<uint32_t, std::string> getVersion(); void setApiVersion(uint32_t apiVersion); std::pair<double, double> getLonLat(const Coord&); unsigned getApiVersion() const { return versionConfig.version; } uint8_t getTimeType() const { return versionConfig.timeType; } uint8_t getNetBoundaryType() const { return versionConfig.netBoundaryType; } uint8_t getTimeStepCmd() const { return versionConfig.timeStepCmd; } std::pair<TraCICoord, TraCICoord> initNetworkBoundaries(int margin); /** * Convert Cartesian coordination to road map position * @param coord Cartesian coordination * @return a tuple of <RoadId, Pos, LaneId> where: * RoadId identifies a road segment (edge) * Pos describes the position of the node in longitudinal direction (ranging from 0 to the road's length) * LaneId identifies the driving lane on the edge. */ std::tuple<std::string, double, uint8_t> getRoadMapPos(const Coord& coord); /** * Get the distance between two arbitrary positions. * * @param position1 OMNeT coordinate of first position * @param position2 OMNeT coordinate of second position * @param returnDrivingDistance whether to return the driving distance or the air distance * @return the distance between the two positions */ double getDistance(const Coord& position1, const Coord& position2, bool returnDrivingDistance); // Vehicle methods /** * @brief Adds a vehicle to the simulation. * * @param vehicleId The new vehicle's ID. * @param vehicleTypeId The new vehicle's type identifier. * @param routeId Identifier of the new vehicle's route. * @param emitTime_st Time at which to spawn the new vehicle or a value from DepartTime. * @param emitPosition Position of the new vehicle on its lane. Valid values are between 0 and 1 (start and * end of edge) and special values from DepartPosition. * @param emitSpeed Speed in meters per second of the new vehicle. Also accepts special values from DepartSpeed. * @param emitLane The new vehicle's lane. Special Also accepts special values from DepartLane. * @return Success indication */ bool addVehicle(std::string vehicleId, std::string vehicleTypeId, std::string routeId, simtime_t emitTime_st = DEPART_TIME_TRIGGERED, double emitPosition = DEPART_POSITION_BASE, double emitSpeed = DEPART_SPEED_MAX, int8_t emitLane = DEPART_LANE_BEST); class VEINS_API Vehicle { public: Vehicle(TraCICommandInterface* traci, std::string nodeId) : traci(traci) , nodeId(nodeId) { connection = &traci->connection; } void setSpeedMode(int32_t bitset); void setSpeed(double speed); void setMaxSpeed(double speed); TraCIColor getColor(); void setColor(const TraCIColor& color); void slowDown(double speed, simtime_t time); void newRoute(std::string roadId); void setParking(); std::string getRoadId(); std::string getLaneId(); double getMaxSpeed(); double getLanePosition(); std::list<std::string> getPlannedRoadIds(); std::string getRouteId(); void changeRoute(std::string roadId, simtime_t travelTime); void stopAt(std::string roadId, double pos, uint8_t laneid, double radius, simtime_t waittime); int32_t getLaneIndex(); std::string getTypeId(); bool changeVehicleRoute(const std::list<std::string>& roads); double getLength(); double getWidth(); double getHeight(); double getAccel(); double getDeccel(); void setParameter(const std::string& parameter, int value); void setParameter(const std::string& parameter, double value); void setParameter(const std::string& parameter, const std::string& value); void getParameter(const std::string& parameter, int& value); void getParameter(const std::string& parameter, double& value); void getParameter(const std::string& parameter, std::string& value); /** * Returns the vehicle type of a vehicle */ std::string getVType(); /** * Get the vehicle's CO2 emissions in mg during this time step. * * @return the vehicle's CO2 emissions, -1001 in case of error */ double getCO2Emissions() const; /** * Get the vehicle's CO emissions in mg during this time step. * * @return the vehicle's CO emissions, -1001 in case of error */ double getCOEmissions() const; /** * Get the vehicle's HC emissions in mg during this time step. * * @return the vehicle's HC emissions, -1001 in case of error */ double getHCEmissions() const; /** * Get the vehicle's PMx emissions in mg during this time step. * * @return the vehicle's PMx emissions, -1001 in case of error */ double getPMxEmissions() const; /** * Get the vehicle's NOx emissions in mg during this time step. * * @return the vehicle's NOx emissions, -1001 in case of error */ double getNOxEmissions() const; /** * Get the vehicle's fuel consumption in ml during this time step. * * @return the vehicle's fuel consumption, -1001 in case of error */ double getFuelConsumption() const; /** * Get the noise generated by the vehicle's in dbA during this time step. * * @return the noise, -1001 in case of error */ double getNoiseEmission() const; /** * Get the vehicle's electricity consumption in kWh during this time step. * * @return the vehicle's electricity consumption, -1001 in case of error */ double getElectricityConsumption() const; /** * Get the vehicle's waiting time in s. * The waiting time of a vehicle is defined as the time (in seconds) spent with a speed below 0.1m/s since the last time it was faster than 0.1m/s. * (basically, the waiting time of a vehicle is reset to 0 every time it moves). * A vehicle that is stopping intentionally with a "stop" command does not accumulate waiting time. * * @return the vehicle's waiting time */ double getWaitingTime() const; /** * Get the vehicle's accumulated waiting time in s within the previous time interval. * The length of the interval is configurable and 100s per default. * * @return the accumulated waiting time */ double getAccumulatedWaitingTime() const; protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string nodeId; }; Vehicle vehicle(std::string nodeId) { return Vehicle(this, nodeId); } // Road methods std::list<std::string> getRoadIds(); class VEINS_API Road { public: Road(TraCICommandInterface* traci, std::string roadId) : traci(traci) , roadId(roadId) { connection = &traci->connection; } double getCurrentTravelTime(); double getMeanSpeed(); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string roadId; }; Road road(std::string roadId) { return Road(this, roadId); } // Lane methods std::list<std::string> getLaneIds(); class VEINS_API Lane { public: Lane(TraCICommandInterface* traci, std::string laneId) : traci(traci) , laneId(laneId) { connection = &traci->connection; } std::list<Coord> getShape(); std::string getRoadId(); double getLength(); double getMaxSpeed(); double getMeanSpeed(); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string laneId; }; Lane lane(std::string laneId) { return Lane(this, laneId); } // Trafficlight methods std::list<std::string> getTrafficlightIds(); class VEINS_API Trafficlight { public: Trafficlight(TraCICommandInterface* traci, std::string trafficLightId) : traci(traci) , trafficLightId(trafficLightId) { connection = &traci->connection; } std::string getCurrentState() const; simtime_t getDefaultCurrentPhaseDuration() const; std::list<std::string> getControlledLanes() const; std::list<std::list<TraCITrafficLightLink>> getControlledLinks() const; int32_t getCurrentPhaseIndex() const; std::string getCurrentProgramID() const; TraCITrafficLightProgram getProgramDefinition() const; simtime_t getAssumedNextSwitchTime() const; void setProgram(std::string program); /**< set/switch to different program */ void setPhaseIndex(int32_t index); /**< set/switch to different phase within the program */ void setState(std::string state); void setPhaseDuration(simtime_t duration); /**< set remaining duration of current phase */ void setProgramDefinition(TraCITrafficLightProgram::Logic program, int32_t programNr); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string trafficLightId; }; Trafficlight trafficlight(std::string trafficLightId) { return Trafficlight(this, trafficLightId); } // LaneAreaDetector methods std::list<std::string> getLaneAreaDetectorIds(); class VEINS_API LaneAreaDetector { public: LaneAreaDetector(TraCICommandInterface* traci, std::string laneAreaDetectorId) : traci(traci) , laneAreaDetectorId(laneAreaDetectorId) { connection = &traci->connection; } int getLastStepVehicleNumber(); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string laneAreaDetectorId; }; LaneAreaDetector laneAreaDetector(std::string laneAreaDetectorId) { return LaneAreaDetector(this, laneAreaDetectorId); } // Polygon methods std::list<std::string> getPolygonIds(); void addPolygon(std::string polyId, std::string polyType, const TraCIColor& color, bool filled, int32_t layer, const std::list<Coord>& points); class VEINS_API Polygon { public: Polygon(TraCICommandInterface* traci, std::string polyId) : traci(traci) , polyId(polyId) { connection = &traci->connection; } std::string getTypeId(); std::list<Coord> getShape(); void setShape(const std::list<Coord>& points); void remove(int32_t layer); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string polyId; }; Polygon polygon(std::string polyId) { return Polygon(this, polyId); } // Poi methods std::list<std::string> getPoiIds(); void addPoi(std::string poiId, std::string poiType, const TraCIColor& color, int32_t layer, const Coord& pos); class VEINS_API Poi { public: Poi(TraCICommandInterface* traci, std::string poiId) : traci(traci) , poiId(poiId) { connection = &traci->connection; } void remove(int32_t layer); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string poiId; }; Poi poi(std::string poiId) { return Poi(this, poiId); } // Junction methods std::list<std::string> getJunctionIds(); class VEINS_API Junction { public: Junction(TraCICommandInterface* traci, std::string junctionId) : traci(traci) , junctionId(junctionId) { connection = &traci->connection; } Coord getPosition(); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string junctionId; }; Junction junction(std::string junctionId) { return Junction(this, junctionId); } // Route methods std::list<std::string> getRouteIds(); class VEINS_API Route { public: Route(TraCICommandInterface* traci, std::string routeId) : traci(traci) , routeId(routeId) { connection = &traci->connection; } std::list<std::string> getRoadIds(); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string routeId; }; Route route(std::string routeId) { return Route(this, routeId); } // Vehicletype methods std::list<std::string> getVehicleTypeIds(); // GuiView methods std::list<std::string> getGuiViewIds(); class VEINS_API GuiView : public HasLogProxy { public: GuiView(TraCICommandInterface* traci, std::string viewId) : HasLogProxy(traci->owner) , traci(traci) , viewId(viewId) { connection = &traci->connection; } std::string getScheme(); void setScheme(std::string name); double getZoom(); void setZoom(double zoom); void setBoundary(Coord p1, Coord p2); void takeScreenshot(std::string filename = "", int32_t width = -1, int32_t height = -1); /** * Track the vehicle identified by vehicleId in the Sumo GUI. */ void trackVehicle(std::string vehicleId); protected: TraCICommandInterface* traci; TraCIConnection* connection; std::string viewId; }; GuiView guiView(std::string viewId) { return GuiView(this, viewId); } private: struct VersionConfig { unsigned version; uint8_t timeType; uint8_t netBoundaryType; uint8_t timeStepCmd; }; TraCIConnection& connection; bool ignoreGuiCommands; static const std::map<uint32_t, VersionConfig> versionConfigs; VersionConfig versionConfig; std::string genericGetString(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr); Coord genericGetCoord(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr); double genericGetDouble(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr); simtime_t genericGetTime(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr); int32_t genericGetInt(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr); std::list<std::string> genericGetStringList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr); std::list<Coord> genericGetCoordList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr); }; } // namespace veins
18,086
33.385932
255
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIConnection.cc
// // Copyright (C) 2006 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #define WANT_WINSOCK2 #include <platdep/sockets.h> #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64) #include <ws2tcpip.h> #else #include <netinet/tcp.h> #include <netdb.h> #include <arpa/inet.h> #endif #include <algorithm> #include <functional> #include "veins/modules/mobility/traci/TraCIConnection.h" #include "veins/modules/mobility/traci/TraCIConstants.h" using namespace veins::TraCIConstants; namespace veins { struct traci2omnet_functor : public std::unary_function<TraCICoord, Coord> { traci2omnet_functor(const TraCIConnection& owner) : owner(owner) { } Coord operator()(const TraCICoord& coord) const { return owner.traci2omnet(coord); } const TraCIConnection& owner; }; SOCKET socket(void* ptr) { ASSERT(ptr); return *static_cast<SOCKET*>(ptr); } TraCIConnection::Result::Result() : success(false) , not_impl(false) , message() { } TraCIConnection::Result::Result(bool success, bool not_impl, std::string message) : success(success) , not_impl(false) , message(message) { } TraCIConnection::TraCIConnection(cComponent* owner, void* ptr) : HasLogProxy(owner) , socketPtr(ptr) { ASSERT(socketPtr); } TraCIConnection::~TraCIConnection() { if (socketPtr) { closesocket(socket(socketPtr)); delete static_cast<SOCKET*>(socketPtr); } } TraCIConnection* TraCIConnection::connect(cComponent* owner, const char* host, int port) { EV_STATICCONTEXT; EV_INFO << "TraCIScenarioManager connecting to TraCI server" << endl; if (initsocketlibonce() != 0) throw cRuntimeError("Could not init socketlib"); in_addr addr; struct hostent* host_ent; struct in_addr saddr; saddr.s_addr = inet_addr(host); if (saddr.s_addr != static_cast<unsigned int>(-1)) { addr = saddr; } else if ((host_ent = gethostbyname(host))) { addr = *((struct in_addr*) host_ent->h_addr_list[0]); } else { throw cRuntimeError("Invalid TraCI server address: %s", host); return nullptr; } sockaddr_in address; sockaddr* address_p = (sockaddr*) &address; memset(address_p, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = addr.s_addr; SOCKET* socketPtr = new SOCKET(); if (*socketPtr < 0) throw cRuntimeError("Could not create socket to connect to TraCI server"); for (int tries = 1; tries <= 10; ++tries) { *socketPtr = ::socket(AF_INET, SOCK_STREAM, 0); if (::connect(*socketPtr, address_p, sizeof(address)) >= 0) break; closesocket(socket(socketPtr)); std::stringstream ss; ss << "Could not connect to TraCI server; error message: " << sock_errno() << ": " << strerror(sock_errno()); std::string msg = ss.str(); int sleepDuration = tries * .25 + 1; if (tries >= 10) { throw cRuntimeError(msg.c_str()); } else if (tries == 3) { EV_WARN << msg << " -- Will retry in " << sleepDuration << " second(s)." << std::endl; } sleep(sleepDuration); } { int x = 1; ::setsockopt(*socketPtr, IPPROTO_TCP, TCP_NODELAY, (const char*) &x, sizeof(x)); } return new TraCIConnection(owner, socketPtr); } TraCIBuffer TraCIConnection::query(uint8_t commandId, const TraCIBuffer& buf, Result* result) { sendMessage(makeTraCICommand(commandId, buf)); TraCIBuffer obuf(receiveMessage()); uint8_t cmdLength; obuf >> cmdLength; uint8_t commandResp; obuf >> commandResp; ASSERT(commandResp == commandId); uint8_t resultCode; obuf >> resultCode; std::string description; obuf >> description; if (result != nullptr) { result->success = (resultCode == RTYPE_OK); result->not_impl = (resultCode == RTYPE_NOTIMPLEMENTED); result->message = description; } else { if (resultCode == RTYPE_NOTIMPLEMENTED) throw cRuntimeError("TraCI server reported command 0x%2x not implemented (\"%s\"). Might need newer version.", commandId, description.c_str()); if (resultCode != RTYPE_OK) throw cRuntimeError("TraCI server reported status %d executing command 0x%2x (\"%s\").", (int) resultCode, commandId, description.c_str()); } return obuf; } std::string TraCIConnection::receiveMessage() { if (!socketPtr) throw cRuntimeError("Not connected to TraCI server"); uint32_t msgLength; { char buf2[sizeof(uint32_t)]; uint32_t bytesRead = 0; while (bytesRead < sizeof(uint32_t)) { int receivedBytes = ::recv(socket(socketPtr), reinterpret_cast<char*>(&buf2) + bytesRead, sizeof(uint32_t) - bytesRead, 0); if (receivedBytes > 0) { bytesRead += receivedBytes; } else if (receivedBytes == 0) { throw cRuntimeError("Connection to TraCI server closed unexpectedly. Check your server's log"); } else { if (sock_errno() == EINTR) continue; if (sock_errno() == EAGAIN) continue; throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno())); } } TraCIBuffer(std::string(buf2, sizeof(uint32_t))) >> msgLength; } uint32_t bufLength = msgLength - sizeof(msgLength); char buf[bufLength]; { EV_TRACE << "Reading TraCI message of " << bufLength << " bytes" << endl; uint32_t bytesRead = 0; while (bytesRead < bufLength) { int receivedBytes = ::recv(socket(socketPtr), reinterpret_cast<char*>(&buf) + bytesRead, bufLength - bytesRead, 0); if (receivedBytes > 0) { bytesRead += receivedBytes; } else if (receivedBytes == 0) { throw cRuntimeError("Connection to TraCI server closed unexpectedly. Check your server's log"); } else { if (sock_errno() == EINTR) continue; if (sock_errno() == EAGAIN) continue; throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno())); } } } return std::string(buf, bufLength); } void TraCIConnection::sendMessage(std::string buf) { if (!socketPtr) throw cRuntimeError("Not connected to TraCI server"); { uint32_t msgLength = sizeof(uint32_t) + buf.length(); TraCIBuffer buf2 = TraCIBuffer(); buf2 << msgLength; uint32_t bytesWritten = 0; while (bytesWritten < sizeof(uint32_t)) { ssize_t sentBytes = ::send(socket(socketPtr), buf2.str().c_str() + bytesWritten, sizeof(uint32_t) - bytesWritten, 0); if (sentBytes > 0) { bytesWritten += sentBytes; } else { if (sock_errno() == EINTR) continue; if (sock_errno() == EAGAIN) continue; throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno())); } } } { EV_TRACE << "Writing TraCI message of " << buf.length() << " bytes" << endl; uint32_t bytesWritten = 0; while (bytesWritten < buf.length()) { ssize_t sentBytes = ::send(socket(socketPtr), buf.c_str() + bytesWritten, buf.length() - bytesWritten, 0); if (sentBytes > 0) { bytesWritten += sentBytes; } else { if (sock_errno() == EINTR) continue; if (sock_errno() == EAGAIN) continue; throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno())); } } } } std::string makeTraCICommand(uint8_t commandId, const TraCIBuffer& buf) { if (sizeof(uint8_t) + sizeof(uint8_t) + buf.str().length() > 0xFF) { uint32_t len = sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) + buf.str().length(); return (TraCIBuffer() << static_cast<uint8_t>(0) << len << commandId).str() + buf.str(); } uint8_t len = sizeof(uint8_t) + sizeof(uint8_t) + buf.str().length(); return (TraCIBuffer() << len << commandId).str() + buf.str(); } void TraCIConnection::setNetbounds(TraCICoord netbounds1, TraCICoord netbounds2, int margin) { coordinateTransformation.reset(new TraCICoordinateTransformation(netbounds1, netbounds2, margin)); } Coord TraCIConnection::traci2omnet(TraCICoord coord) const { ASSERT(coordinateTransformation.get()); return coordinateTransformation->traci2omnet(coord); } std::list<Coord> TraCIConnection::traci2omnet(const std::list<TraCICoord>& list) const { ASSERT(coordinateTransformation.get()); return coordinateTransformation->traci2omnet(list); } TraCICoord TraCIConnection::omnet2traci(Coord coord) const { ASSERT(coordinateTransformation.get()); return coordinateTransformation->omnet2traci(coord); } std::list<TraCICoord> TraCIConnection::omnet2traci(const std::list<Coord>& list) const { ASSERT(coordinateTransformation.get()); return coordinateTransformation->omnet2traci(list); } Heading TraCIConnection::traci2omnetHeading(double heading) const { ASSERT(coordinateTransformation.get()); return coordinateTransformation->traci2omnetHeading(heading); } double TraCIConnection::omnet2traciHeading(Heading heading) const { ASSERT(coordinateTransformation.get()); return coordinateTransformation->omnet2traciHeading(heading); } } // namespace veins
10,707
32.567398
191
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIConnection.h
// // Copyright (C) 2006 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <stdint.h> #include <memory> #include "veins/modules/mobility/traci/TraCIBuffer.h" #include "veins/modules/mobility/traci/TraCICoord.h" #include "veins/modules/mobility/traci/TraCICoordinateTransformation.h" #include "veins/base/utils/Coord.h" #include "veins/base/utils/Heading.h" #include "veins/modules/utility/HasLogProxy.h" namespace veins { class VEINS_API TraCIConnection : public HasLogProxy { public: class VEINS_API Result { public: Result(); Result(bool success, bool not_impl, std::string message); bool success; bool not_impl; std::string message; }; static TraCIConnection* connect(cComponent* owner, const char* host, int port); void setNetbounds(TraCICoord netbounds1, TraCICoord netbounds2, int margin); ~TraCIConnection(); /** * sends a single command via TraCI, checks status response, returns additional responses. * @param commandId: command to send * @param buf: additional parameters to send * @param result: where to store return value (if set to nullptr, any return value other than RTYPE_OK will trigger an exception). */ TraCIBuffer query(uint8_t commandId, const TraCIBuffer& buf = TraCIBuffer(), Result* result = nullptr); /** * sends a message via TraCI (after adding the header) */ void sendMessage(std::string buf); /** * receives a message via TraCI (and strips the header) */ std::string receiveMessage(); /** * convert TraCI heading to OMNeT++ heading (in rad) */ Heading traci2omnetHeading(double heading) const; /** * convert OMNeT++ heading (in rad) to TraCI heading */ double omnet2traciHeading(Heading heading) const; /** * convert TraCI coordinates to OMNeT++ coordinates */ Coord traci2omnet(TraCICoord coord) const; std::list<Coord> traci2omnet(const std::list<TraCICoord>&) const; /** * convert OMNeT++ coordinates to TraCI coordinates */ TraCICoord omnet2traci(Coord coord) const; std::list<TraCICoord> omnet2traci(const std::list<Coord>&) const; private: TraCIConnection(cComponent* owner, void* ptr); void* socketPtr; std::unique_ptr<TraCICoordinateTransformation> coordinateTransformation; }; /** * returns byte-buffer containing a TraCI command with optional parameters */ std::string makeTraCICommand(uint8_t commandId, const TraCIBuffer& buf = TraCIBuffer()); } // namespace veins
3,398
31.066038
134
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIConstants.h
// // Copyright (C) 2019 Universidad Nacional de Colombia, Politecnico Jaime Isaza Cadavid. // Copyright (C) 2019 Andres Acosta, Jorge Espinosa, Jairo Espinosa // Copyright (C) 2009 Rodney Thomson // Copyright (C) 2008 Rodney Thomson // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: BSD-3-Clause // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution // * Neither the name of Universidad Nacional de Colombia, Politécnico Jaime Isaza Cadavid nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // TraCI4Matlab 3.0.0.0 // $Id: constants.m 53 2019-01-03 15:18:31Z afacostag $ // The SUMO hexadecimal constants. // Authors: Andres Acosta, Jairo Espinosa, Jorge Espinosa. #pragma once namespace veins { namespace TraCIConstants { const uint32_t TRACI_VERSION = 19; const double INVALID_DOUBLE_VALUE = -1073741824; const int32_t INVALID_INT_VALUE = -1073741824; const uint8_t ADD = 0x80; const uint8_t ADD_FULL = 0x85; const uint8_t APPEND_STAGE = 0xc4; const int8_t ARRIVALFLAG_LANE_CURRENT = -0x02; const int8_t ARRIVALFLAG_POS_MAX = -0x03; const int8_t ARRIVALFLAG_POS_RANDOM = -0x02; const int8_t ARRIVALFLAG_SPEED_CURRENT = -0x02; const uint8_t AUTOMATIC_CONTEXT_SUBSCRIPTION = 0x03; const uint8_t AUTOMATIC_VARIABLES_SUBSCRIPTION = 0x02; const uint8_t CMD_ADD_SUBSCRIPTION_FILTER = 0x7e; const uint8_t CMD_CHANGELANE = 0x13; const uint8_t CMD_CHANGESUBLANE = 0x15; const uint8_t CMD_CHANGETARGET = 0x31; const uint8_t CMD_CLEAR_PENDING_VEHICLES = 0x94; const uint8_t CMD_CLOSE = 0x7F; const uint8_t CMD_GETVERSION = 0x00; const uint8_t CMD_GET_EDGE_VARIABLE = 0xaa; const uint8_t CMD_GET_GUI_VARIABLE = 0xac; const uint8_t CMD_GET_INDUCTIONLOOP_VARIABLE = 0xa0; const uint8_t CMD_GET_JUNCTION_VARIABLE = 0xa9; const uint8_t CMD_GET_LANEAREA_VARIABLE = 0xad; const uint8_t CMD_GET_LANE_VARIABLE = 0xa3; const uint8_t CMD_GET_MULTIENTRYEXIT_VARIABLE = 0xa1; // renamed for compatibility const uint8_t CMD_GET_PERSON_VARIABLE = 0xae; const uint8_t CMD_GET_POI_VARIABLE = 0xa7; const uint8_t CMD_GET_POLYGON_VARIABLE = 0xa8; const uint8_t CMD_GET_ROUTE_VARIABLE = 0xa6; const uint8_t CMD_GET_SIM_VARIABLE = 0xab; const uint8_t CMD_GET_TL_VARIABLE = 0xa2; const uint8_t CMD_GET_VEHICLETYPE_VARIABLE = 0xa5; const uint8_t CMD_GET_VEHICLE_VARIABLE = 0xa4; const uint8_t CMD_LOAD = 0x01; const uint8_t CMD_OPENGAP = 0x16; const uint8_t CMD_REROUTE_EFFORT = 0x91; const uint8_t CMD_REROUTE_TO_PARKING = 0xc2; const uint8_t CMD_REROUTE_TRAVELTIME = 0x90; const uint8_t CMD_RESUME = 0x19; const uint8_t CMD_SAVE_SIMSTATE = 0x95; const uint8_t CMD_SETORDER = 0x03; const uint8_t CMD_SET_EDGE_VARIABLE = 0xca; const uint8_t CMD_SET_GUI_VARIABLE = 0xcc; const uint8_t CMD_SET_JUNCTION_VARIABLE = 0xc9; const uint8_t CMD_SET_LANE_VARIABLE = 0xc3; const uint8_t CMD_SET_PERSON_VARIABLE = 0xce; const uint8_t CMD_SET_POI_VARIABLE = 0xc7; const uint8_t CMD_SET_POLYGON_VARIABLE = 0xc8; const uint8_t CMD_SET_ROUTE_VARIABLE = 0xc6; const uint8_t CMD_SET_SIM_VARIABLE = 0xcb; const uint8_t CMD_SET_TL_VARIABLE = 0xc2; const uint8_t CMD_SET_VEHICLETYPE_VARIABLE = 0xc5; const uint8_t CMD_SET_VEHICLE_VARIABLE = 0xc4; const uint8_t CMD_SIMSTEP = 0x02; const uint8_t CMD_SIMSTEP2 = 0x02; // Veins specific (called CMD_SIMSTEP in TraCI) const uint8_t CMD_SLOWDOWN = 0x14; const uint8_t CMD_STOP = 0x12; const uint8_t CMD_SUBSCRIBE_EDGE_CONTEXT = 0x8a; const uint8_t CMD_SUBSCRIBE_EDGE_VARIABLE = 0xda; const uint8_t CMD_SUBSCRIBE_GUI_CONTEXT = 0x8c; const uint8_t CMD_SUBSCRIBE_GUI_VARIABLE = 0xdc; const uint8_t CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x80; const uint8_t CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xd0; const uint8_t CMD_SUBSCRIBE_JUNCTION_CONTEXT = 0x89; const uint8_t CMD_SUBSCRIBE_JUNCTION_VARIABLE = 0xd9; const uint8_t CMD_SUBSCRIBE_LANEAREA_CONTEXT = 0x8d; const uint8_t CMD_SUBSCRIBE_LANEAREA_VARIABLE = 0xdd; const uint8_t CMD_SUBSCRIBE_LANE_CONTEXT = 0x83; const uint8_t CMD_SUBSCRIBE_LANE_VARIABLE = 0xd3; const uint8_t CMD_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x81; // renamed for compatibility const uint8_t CMD_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xd1; // renamed for compatibility const uint8_t CMD_SUBSCRIBE_PERSON_CONTEXT = 0x8e; const uint8_t CMD_SUBSCRIBE_PERSON_VARIABLE = 0xde; const uint8_t CMD_SUBSCRIBE_POI_CONTEXT = 0x87; const uint8_t CMD_SUBSCRIBE_POI_VARIABLE = 0xd7; const uint8_t CMD_SUBSCRIBE_POLYGON_CONTEXT = 0x88; const uint8_t CMD_SUBSCRIBE_POLYGON_VARIABLE = 0xd8; const uint8_t CMD_SUBSCRIBE_ROUTE_CONTEXT = 0x86; const uint8_t CMD_SUBSCRIBE_ROUTE_VARIABLE = 0xd6; const uint8_t CMD_SUBSCRIBE_SIM_CONTEXT = 0x8b; const uint8_t CMD_SUBSCRIBE_SIM_VARIABLE = 0xdb; const uint8_t CMD_SUBSCRIBE_TL_CONTEXT = 0x82; const uint8_t CMD_SUBSCRIBE_TL_VARIABLE = 0xd2; const uint8_t CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x85; const uint8_t CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xd5; const uint8_t CMD_SUBSCRIBE_VEHICLE_CONTEXT = 0x84; const uint8_t CMD_SUBSCRIBE_VEHICLE_VARIABLE = 0xd4; const uint8_t COPY = 0x88; const int8_t DEPARTFLAG_CONTAINER_TRIGGERED = -0x02; const int8_t DEPARTFLAG_LANE_ALLOWED_FREE = -0x04; const int8_t DEPARTFLAG_LANE_BEST_FREE = -0x05; const int8_t DEPARTFLAG_LANE_FIRST_ALLOWED = -0x06; const int8_t DEPARTFLAG_LANE_FREE = -0x03; const int8_t DEPARTFLAG_LANE_RANDOM = -0x02; const int8_t DEPARTFLAG_NOW = -0x03; const int8_t DEPARTFLAG_POS_BASE = -0x04; const int8_t DEPARTFLAG_POS_FREE = -0x03; const int8_t DEPARTFLAG_POS_LAST = -0x05; const int8_t DEPARTFLAG_POS_RANDOM = -0x02; const int8_t DEPARTFLAG_POS_RANDOM_FREE = -0x06; const int8_t DEPARTFLAG_SPEED_MAX = -0x03; const int8_t DEPARTFLAG_SPEED_RANDOM = -0x02; const int8_t DEPARTFLAG_TRIGGERED = -0x01; const uint8_t DISTANCE_REQUEST = 0x83; const uint8_t FILTER_TYPE_DOWNSTREAM_DIST = 0x03; const uint8_t FILTER_TYPE_LANES = 0x01; const uint8_t FILTER_TYPE_LEAD_FOLLOW = 0x05; const uint8_t FILTER_TYPE_NONE = 0x00; const uint8_t FILTER_TYPE_NOOPPOSITE = 0x02; const uint8_t FILTER_TYPE_TURN = 0x07; const uint8_t FILTER_TYPE_UPSTREAM_DIST = 0x04; const uint8_t FILTER_TYPE_VCLASS = 0x08; const uint8_t FILTER_TYPE_VTYPE = 0x09; const uint8_t FIND_INTERMODAL_ROUTE = 0x87; const uint8_t FIND_ROUTE = 0x86; const uint8_t GENERIC_ATTRIBUTE = 0x03; const uint8_t ID_COUNT = 0x01; const uint8_t ID_LIST = 0x00; const uint8_t JAM_LENGTH_METERS = 0x19; const uint8_t JAM_LENGTH_VEHICLE = 0x18; const uint8_t LANE_ALLOWED = 0x34; const uint8_t LANE_DISALLOWED = 0x35; const uint8_t LANE_EDGE_ID = 0x31; const uint8_t LANE_LINKS = 0x33; const uint8_t LANE_LINK_NUMBER = 0x30; const uint8_t LAST_STEP_LENGTH = 0x15; const uint8_t LAST_STEP_MEAN_SPEED = 0x11; const uint8_t LAST_STEP_OCCUPANCY = 0x13; const uint8_t LAST_STEP_PERSON_ID_LIST = 0x1a; const uint8_t LAST_STEP_TIME_SINCE_DETECTION = 0x16; const uint8_t LAST_STEP_VEHICLE_DATA = 0x17; const uint8_t LAST_STEP_VEHICLE_HALTING_NUMBER = 0x14; const uint8_t LAST_STEP_VEHICLE_ID_LIST = 0x12; const uint8_t LAST_STEP_VEHICLE_NUMBER = 0x10; const int32_t MAX_ORDER = 1073741824; const uint8_t MOVE_TO_XY = 0xb4; const uint8_t OBJECT_VARIABLES_SUBSCRIPTION = 0x02; // Veins specific (called AUTOMATIC_VARIABLES_SUBSCRIPTION in TraCI) const uint8_t POSITION_2D = 0x01; const uint8_t POSITION_3D = 0x03; const uint8_t POSITION_CONVERSION = 0x82; const uint8_t POSITION_LON_LAT = 0x00; const uint8_t POSITION_LON_LAT_ALT = 0x02; const uint8_t POSITION_ROADMAP = 0x04; const uint8_t REMOVE = 0x81; const uint8_t REMOVE_ARRIVED = 0x02; const uint8_t REMOVE_PARKING = 0x01; const uint8_t REMOVE_STAGE = 0xc5; const uint8_t REMOVE_TELEPORT = 0x00; const uint8_t REMOVE_TELEPORT_ARRIVED = 0x04; const uint8_t REMOVE_VAPORIZED = 0x03; const uint8_t REQUEST_AIRDIST = 0x00; const uint8_t REQUEST_DRIVINGDIST = 0x01; const uint8_t RESPONSE_GET_EDGE_VARIABLE = 0xba; const uint8_t RESPONSE_GET_GUI_VARIABLE = 0xbc; const uint8_t RESPONSE_GET_INDUCTIONLOOP_VARIABLE = 0xb0; const uint8_t RESPONSE_GET_JUNCTION_VARIABLE = 0xb9; const uint8_t RESPONSE_GET_LANEAREA_VARIABLE = 0xbd; const uint8_t RESPONSE_GET_LANE_VARIABLE = 0xb3; const uint8_t RESPONSE_GET_MULTIENTRYEXIT_VARIABLE = 0xb1; // renamed for compatibility const uint8_t RESPONSE_GET_PERSON_VARIABLE = 0xbe; const uint8_t RESPONSE_GET_POI_VARIABLE = 0xb7; const uint8_t RESPONSE_GET_POLYGON_VARIABLE = 0xb8; const uint8_t RESPONSE_GET_ROUTE_VARIABLE = 0xb6; const uint8_t RESPONSE_GET_SIM_VARIABLE = 0xbb; const uint8_t RESPONSE_GET_TL_VARIABLE = 0xb2; const uint8_t RESPONSE_GET_VEHICLETYPE_VARIABLE = 0xb5; const uint8_t RESPONSE_GET_VEHICLE_VARIABLE = 0xb4; const uint8_t RESPONSE_SUBSCRIBE_EDGE_CONTEXT = 0x9a; const uint8_t RESPONSE_SUBSCRIBE_EDGE_VARIABLE = 0xea; const uint8_t RESPONSE_SUBSCRIBE_GUI_CONTEXT = 0x9c; const uint8_t RESPONSE_SUBSCRIBE_GUI_VARIABLE = 0xec; const uint8_t RESPONSE_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x90; const uint8_t RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xe0; const uint8_t RESPONSE_SUBSCRIBE_JUNCTION_CONTEXT = 0x99; const uint8_t RESPONSE_SUBSCRIBE_JUNCTION_VARIABLE = 0xe9; const uint8_t RESPONSE_SUBSCRIBE_LANEAREA_CONTEXT = 0x9d; const uint8_t RESPONSE_SUBSCRIBE_LANEAREA_VARIABLE = 0xed; const uint8_t RESPONSE_SUBSCRIBE_LANE_CONTEXT = 0x93; const uint8_t RESPONSE_SUBSCRIBE_LANE_VARIABLE = 0xe3; const uint8_t RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x91; // renamed for compatibility const uint8_t RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xe1; // renamed for compatibility const uint8_t RESPONSE_SUBSCRIBE_PERSON_CONTEXT = 0x9e; const uint8_t RESPONSE_SUBSCRIBE_PERSON_VARIABLE = 0xee; const uint8_t RESPONSE_SUBSCRIBE_POI_CONTEXT = 0x97; const uint8_t RESPONSE_SUBSCRIBE_POI_VARIABLE = 0xe7; const uint8_t RESPONSE_SUBSCRIBE_POLYGON_CONTEXT = 0x98; const uint8_t RESPONSE_SUBSCRIBE_POLYGON_VARIABLE = 0xe8; const uint8_t RESPONSE_SUBSCRIBE_ROUTE_CONTEXT = 0x96; const uint8_t RESPONSE_SUBSCRIBE_ROUTE_VARIABLE = 0xe6; const uint8_t RESPONSE_SUBSCRIBE_SIM_CONTEXT = 0x9b; const uint8_t RESPONSE_SUBSCRIBE_SIM_VARIABLE = 0xeb; const uint8_t RESPONSE_SUBSCRIBE_TL_CONTEXT = 0x92; const uint8_t RESPONSE_SUBSCRIBE_TL_VARIABLE = 0xe2; const uint8_t RESPONSE_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x95; const uint8_t RESPONSE_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xe5; const uint8_t RESPONSE_SUBSCRIBE_VEHICLE_CONTEXT = 0x94; const uint8_t RESPONSE_SUBSCRIBE_VEHICLE_VARIABLE = 0xe4; const uint8_t ROUTING_MODE_AGGREGATED = 0x01; const uint8_t ROUTING_MODE_COMBINED = 0x03; const uint8_t ROUTING_MODE_DEFAULT = 0x00; const uint8_t ROUTING_MODE_EFFORT = 0x02; const uint8_t RTYPE_ERR = 0xFF; const uint8_t RTYPE_NOTIMPLEMENTED = 0x01; const uint8_t RTYPE_OK = 0x00; const uint8_t STAGE_DRIVING = 0x03; const uint8_t STAGE_WAITING = 0x01; const uint8_t STAGE_WAITING_FOR_DEPART = 0x00; const uint8_t STAGE_WALKING = 0x02; const uint8_t STOP_BUS_STOP = 0x08; const uint8_t STOP_CHARGING_STATION = 0x20; const uint8_t STOP_CONTAINER_STOP = 0x10; const uint8_t STOP_CONTAINER_TRIGGERED = 0x04; const uint8_t STOP_DEFAULT = 0x00; const uint8_t STOP_PARKING = 0x01; const uint8_t STOP_PARKING_AREA = 0x40; const uint8_t STOP_TRIGGERED = 0x02; const uint8_t SURROUNDING_VARIABLES_SUBSCRIPTION = 0x03; // Veins specific (called AUTOMATIC_CONTEXT_SUBSCRIPTION in TraCI) const uint8_t TL_COMPLETE_DEFINITION_RYG = 0x2b; const uint8_t TL_COMPLETE_PROGRAM_RYG = 0x2c; const uint8_t TL_CONTROLLED_JUNCTIONS = 0x2a; const uint8_t TL_CONTROLLED_LANES = 0x26; const uint8_t TL_CONTROLLED_LINKS = 0x27; const uint8_t TL_CURRENT_PHASE = 0x28; const uint8_t TL_CURRENT_PROGRAM = 0x29; const uint8_t TL_EXTERNAL_STATE = 0x2e; const uint8_t TL_NEXT_SWITCH = 0x2d; const uint8_t TL_PHASE_DURATION = 0x24; const uint8_t TL_PHASE_INDEX = 0x22; const uint8_t TL_PROGRAM = 0x23; const uint8_t TL_RED_YELLOW_GREEN_STATE = 0x20; const uint8_t TYPE_BOUNDINGBOX = 0x05; // Retained for backwards compatibility const uint8_t TYPE_BYTE = 0x08; const uint8_t TYPE_COLOR = 0x11; const uint8_t TYPE_COMPOUND = 0x0F; const uint8_t TYPE_DOUBLE = 0x0B; const uint8_t TYPE_INTEGER = 0x09; const uint8_t TYPE_POLYGON = 0x06; const uint8_t TYPE_STRING = 0x0C; const uint8_t TYPE_STRINGLIST = 0x0E; const uint8_t TYPE_UBYTE = 0x07; const uint8_t VAR_ACCEL = 0x46; const uint8_t VAR_ACCELERATION = 0x72; const uint8_t VAR_ACCUMULATED_WAITING_TIME = 0x87; const uint8_t VAR_ACTIONSTEPLENGTH = 0x7d; const uint8_t VAR_ALLOWED_SPEED = 0xb7; const uint8_t VAR_ANGLE = 0x43; const uint8_t VAR_APPARENT_DECEL = 0x7c; const uint8_t VAR_ARRIVED_VEHICLES_IDS = 0x7a; const uint8_t VAR_ARRIVED_VEHICLES_NUMBER = 0x79; const uint8_t VAR_BEST_LANES = 0xb2; const uint8_t VAR_BUS_STOP_WAITING = 0x67; const uint8_t VAR_CO2EMISSION = 0x60; const uint8_t VAR_COEMISSION = 0x61; const uint8_t VAR_COLLIDING_VEHICLES_IDS = 0x81; const uint8_t VAR_COLLIDING_VEHICLES_NUMBER = 0x80; const uint8_t VAR_COLOR = 0x45; const uint8_t VAR_CURRENT_TRAVELTIME = 0x5a; const uint8_t VAR_DECEL = 0x47; const uint8_t VAR_DELTA_T = 0x7b; const uint8_t VAR_DEPARTED_VEHICLES_IDS = 0x74; const uint8_t VAR_DEPARTED_VEHICLES_NUMBER = 0x73; const uint8_t VAR_DISTANCE = 0x84; const uint8_t VAR_EDGES = 0x54; const uint8_t VAR_EDGE_EFFORT = 0x59; const uint8_t VAR_EDGE_TRAVELTIME = 0x58; const uint8_t VAR_ELECTRICITYCONSUMPTION = 0x71; const uint8_t VAR_EMERGENCYSTOPPING_VEHICLES_IDS = 0x8a; const uint8_t VAR_EMERGENCYSTOPPING_VEHICLES_NUMBER = 0x89; const uint8_t VAR_EMERGENCY_DECEL = 0x7b; const uint8_t VAR_EMISSIONCLASS = 0x4a; const uint8_t VAR_FILL = 0x55; const uint8_t VAR_FOES = 0x37; const uint8_t VAR_FUELCONSUMPTION = 0x65; const uint8_t VAR_HAS_VIEW = 0xa7; const uint8_t VAR_HCEMISSION = 0x62; const uint8_t VAR_HEIGHT = 0xbc; const uint8_t VAR_IMPERFECTION = 0x5d; const uint8_t VAR_LANECHANGE_MODE = 0xb6; const uint8_t VAR_LANEPOSITION = 0x56; const uint8_t VAR_LANEPOSITION_LAT = 0xb8; const uint8_t VAR_LANE_ID = 0x51; const uint8_t VAR_LANE_INDEX = 0x52; const uint8_t VAR_LASTACTIONTIME = 0x7f; const uint8_t VAR_LATALIGNMENT = 0xb9; const uint8_t VAR_LEADER = 0x68; const uint8_t VAR_LENGTH = 0x44; const uint8_t VAR_LINE = 0xbd; const uint8_t VAR_LOADED_VEHICLES_IDS = 0x72; const uint8_t VAR_LOADED_VEHICLES_NUMBER = 0x71; const uint8_t VAR_MAXSPEED = 0x41; const uint8_t VAR_MAXSPEED_LAT = 0xba; const uint8_t VAR_MINGAP = 0x4c; const uint8_t VAR_MINGAP_LAT = 0xbb; const uint8_t VAR_MIN_EXPECTED_VEHICLES = 0x7d; const uint8_t VAR_MOVE_TO = 0x5c; const uint8_t VAR_MOVE_TO_VTD = 0xb4; // Veins specific (called MOVE_TO_XY in TraCI) const uint8_t VAR_NAME = 0x1b; const uint8_t VAR_NET_BOUNDING_BOX = 0x7c; const uint8_t VAR_NEXT_EDGE = 0xc1; const uint8_t VAR_NEXT_STOPS = 0x73; const uint8_t VAR_NEXT_TLS = 0x70; const uint8_t VAR_NOISEEMISSION = 0x66; const uint8_t VAR_NOXEMISSION = 0x64; const uint8_t VAR_PARAMETER = 0x7e; const uint8_t VAR_PARKING_ENDING_VEHICLES_IDS = 0x6f; const uint8_t VAR_PARKING_ENDING_VEHICLES_NUMBER = 0x6e; const uint8_t VAR_PARKING_STARTING_VEHICLES_IDS = 0x6d; const uint8_t VAR_PARKING_STARTING_VEHICLES_NUMBER = 0x6c; const uint8_t VAR_PERSON_NUMBER = 0x67; const uint8_t VAR_PMXEMISSION = 0x63; const uint8_t VAR_POSITION = 0x42; const uint8_t VAR_POSITION3D = 0x39; const uint8_t VAR_ROAD_ID = 0x50; const uint8_t VAR_ROUTE = 0x57; const uint8_t VAR_ROUTE_ID = 0x53; const uint8_t VAR_ROUTE_INDEX = 0x69; const uint8_t VAR_ROUTE_VALID = 0x92; const uint8_t VAR_ROUTING_MODE = 0x89; const uint8_t VAR_SCREENSHOT = 0xa5; const uint8_t VAR_SHAPE = 0x4e; const uint8_t VAR_SHAPECLASS = 0x4b; const uint8_t VAR_SIGNALS = 0x5b; const uint8_t VAR_SLOPE = 0x36; const uint8_t VAR_SPEED = 0x40; const uint8_t VAR_SPEEDSETMODE = 0xb3; const uint8_t VAR_SPEED_DEVIATION = 0x5f; const uint8_t VAR_SPEED_FACTOR = 0x5e; const uint8_t VAR_SPEED_WITHOUT_TRACI = 0xb1; const uint8_t VAR_STAGE = 0xc0; const uint8_t VAR_STAGES_REMAINING = 0xc2; const uint8_t VAR_STOPSTATE = 0xb5; const uint8_t VAR_STOP_ENDING_VEHICLES_IDS = 0x6b; const uint8_t VAR_STOP_ENDING_VEHICLES_NUMBER = 0x6a; const uint8_t VAR_STOP_STARTING_VEHICLES_IDS = 0x69; const uint8_t VAR_STOP_STARTING_VEHICLES_NUMBER = 0x68; const uint8_t VAR_TAU = 0x48; const uint8_t VAR_TELEPORT_ENDING_VEHICLES_IDS = 0x78; const uint8_t VAR_TELEPORT_ENDING_VEHICLES_NUMBER = 0x77; const uint8_t VAR_TELEPORT_STARTING_VEHICLES_IDS = 0x76; const uint8_t VAR_TELEPORT_STARTING_VEHICLES_NUMBER = 0x75; const uint8_t VAR_TIME = 0x66; const uint8_t VAR_TIME_STEP = 0x70; const uint8_t VAR_TRACK_VEHICLE = 0xa6; const uint8_t VAR_TYPE = 0x4f; const uint8_t VAR_UPDATE_BESTLANES = 0x6a; const uint8_t VAR_VEHICLE = 0xc3; const uint8_t VAR_VEHICLECLASS = 0x49; const uint8_t VAR_VIA = 0xbe; const uint8_t VAR_VIEW_BOUNDARY = 0xa3; const uint8_t VAR_VIEW_OFFSET = 0xa1; const uint8_t VAR_VIEW_SCHEMA = 0xa2; const uint8_t VAR_VIEW_ZOOM = 0xa0; const uint8_t VAR_WAITING_TIME = 0x7a; const uint8_t VAR_WAITING_TIME_ACCUMULATED = 0x87; // Veins specific (called VAR_ACCUMULATED_WAITING_TIME in TraCI) const uint8_t VAR_WIDTH = 0x4d; } // namespace TraCIConstants } // namespace veins
18,274
43.791667
123
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCICoord.h
// // Copyright (C) 2006 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" namespace veins { /** * Coord equivalent for storing TraCI coordinates */ struct VEINS_API TraCICoord { TraCICoord() : x(0.0) , y(0.0) { } TraCICoord(double x, double y) : x(x) , y(y) { } double x; double y; }; } // namespace veins
1,240
24.854167
76
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCICoordinateTransformation.cc
// // Copyright (C) 2018 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/mobility/traci/TraCICoordinateTransformation.h" namespace veins { using OmnetCoord = TraCICoordinateTransformation::OmnetCoord; using OmnetCoordList = TraCICoordinateTransformation::OmnetCoordList; using TraCICoordList = TraCICoordinateTransformation::TraCICoordList; using OmnetHeading = TraCICoordinateTransformation::OmnetHeading; using TraCIHeading = TraCICoordinateTransformation::TraCIHeading; TraCICoordinateTransformation::TraCICoordinateTransformation(TraCICoord topleft, TraCICoord bottomright, float margin) : dimensions({bottomright.x - topleft.x, bottomright.y - topleft.y}) , topleft(topleft) , bottomright(bottomright) , margin(margin) { } TraCICoord TraCICoordinateTransformation::omnet2traci(const OmnetCoord& coord) const { return {coord.x + topleft.x - margin, dimensions.y - (coord.y - topleft.y) + margin}; } TraCICoordList TraCICoordinateTransformation::omnet2traci(const OmnetCoordList& coords) const { TraCICoordList result; for (auto&& coord : coords) { result.push_back(omnet2traci(coord)); } return result; } TraCIHeading TraCICoordinateTransformation::omnet2traciHeading(OmnetHeading o) const { // convert to degrees auto angle = o.getRad() * 180 / M_PI; // rotate angle angle = 90 - angle; // normalize angle to -180 <= angle < 180 while (angle < -180) { angle += 360; } while (angle >= 180) { angle -= 360; } return angle; } OmnetCoord TraCICoordinateTransformation::traci2omnet(const TraCICoord& coord) const { return {coord.x - topleft.x + margin, dimensions.y - (coord.y - topleft.y) + margin}; } OmnetCoordList TraCICoordinateTransformation::traci2omnet(const TraCICoordList& coords) const { OmnetCoordList result; for (auto&& coord : coords) { result.push_back(traci2omnet(coord)); } return result; } OmnetHeading TraCICoordinateTransformation::traci2omnetHeading(TraCIHeading o) const { // rotate angle auto angle = 90 - o; // convert to rad angle = angle * M_PI / 180.0; // normalize angle to -M_PI <= angle < M_PI while (angle < -M_PI) { angle += 2 * M_PI; } while (angle >= M_PI) { angle -= 2 * M_PI; } return OmnetHeading(angle); } } // end namespace veins
3,218
28.805556
118
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCICoordinateTransformation.h
// // Copyright (C) 2018 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/modules/mobility/traci/TraCICoord.h" #include "veins/base/utils/Coord.h" #include "veins/base/utils/Heading.h" #include <list> namespace veins { /** * Helper class for converting SUMO coordinates to OMNeT++ Coordinates for a given network. */ class VEINS_API TraCICoordinateTransformation { public: using OmnetCoord = Coord; using OmnetCoordList = std::list<OmnetCoord>; using TraCICoordList = std::list<TraCICoord>; using TraCIHeading = double; using OmnetHeading = Heading; TraCICoordinateTransformation(TraCICoord topleft, TraCICoord bottomright, float margin); TraCICoord omnet2traci(const OmnetCoord& coord) const; TraCICoordList omnet2traci(const OmnetCoordList& coords) const; TraCIHeading omnet2traciHeading(OmnetHeading heading) const; /**< TraCI's heading interpretation: 0 is north, 90 is east */ OmnetCoord traci2omnet(const TraCICoord& coord) const; OmnetCoordList traci2omnet(const TraCICoordList& coords) const; OmnetHeading traci2omnetHeading(TraCIHeading heading) const; /**< OMNeT++'s heading interpretation: 0 is east, pi/2 is north */ private: TraCICoord dimensions; TraCICoord topleft; TraCICoord bottomright; float margin; }; // end class NetworkCoordinateTranslator } // end namespace veins
2,214
35.916667
132
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCILauncher.cc
// // Copyright (C) 2006-2016 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/veins.h" #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64) #else #include <sys/wait.h> #endif #include "veins/modules/mobility/traci/TraCILauncher.h" using veins::TraCILauncher; TraCILauncher::TraCILauncher(std::string commandLine) { #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64) STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFOA); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); char cmdline[32768]; strncpy(cmdline, commandLine.c_str(), sizeof(cmdline)); bool bSuccess = CreateProcess(0, cmdline, 0, 0, 1, NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE, 0, 0, &si, &pi); if (!bSuccess) { std::string msg = "undefined error"; DWORD errorMessageID = ::GetLastError(); if (errorMessageID != 0) { LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &messageBuffer, 0, NULL); std::string message(messageBuffer, size); LocalFree(messageBuffer); msg = message; } msg = std::string() + "Error launching TraCI server (\"" + commandLine + "\"): " + msg + ". Make sure you have set $PATH correctly."; throw cRuntimeError(msg.c_str()); } else { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } #else pid = fork(); if (pid == 0) { signal(SIGINT, SIG_IGN); int r = system(commandLine.c_str()); if (r == -1) { throw cRuntimeError("Running \"%s\" failed during system()", commandLine.c_str()); } if (WEXITSTATUS(r) != 0) { throw cRuntimeError("Error launching TraCI server (\"%s\"): exited with code %d. Make sure you have set $PATH correctly.", commandLine.c_str(), WEXITSTATUS(r)); } exit(1); } #endif } TraCILauncher::~TraCILauncher() { #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64) #else if (pid) { // send SIGINT kill(pid, 15); } #endif }
3,252
32.885417
232
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCILauncher.h
// // Copyright (C) 2006-2016 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once namespace veins { /** * @brief * Launches a program (the TraCI server) when instantiated. * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * @author Christoph Sommer * * @see TraCIMobility * @see TraCIScenarioManager * */ class VEINS_API TraCILauncher { public: TraCILauncher(std::string commandLine); ~TraCILauncher(); protected: #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64) #else pid_t pid; #endif }; } // namespace veins
1,502
27.903846
113
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIMobility.cc
// // Copyright (C) 2006-2012 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <limits> #include <iostream> #include <sstream> #include "veins/modules/mobility/traci/TraCIMobility.h" using namespace veins; using veins::TraCIMobility; Define_Module(veins::TraCIMobility); const simsignal_t TraCIMobility::parkingStateChangedSignal = registerSignal("org_car2x_veins_modules_mobility_parkingStateChanged"); namespace { const double MY_INFINITY = (std::numeric_limits<double>::has_infinity ? std::numeric_limits<double>::infinity() : std::numeric_limits<double>::max()); } void TraCIMobility::Statistics::initialize() { firstRoadNumber = MY_INFINITY; startTime = simTime(); totalTime = 0; stopTime = 0; minSpeed = MY_INFINITY; maxSpeed = -MY_INFINITY; totalDistance = 0; totalCO2Emission = 0; } void TraCIMobility::Statistics::watch(cSimpleModule&) { } void TraCIMobility::Statistics::recordScalars(cSimpleModule& module) { if (firstRoadNumber != MY_INFINITY) module.recordScalar("firstRoadNumber", firstRoadNumber); module.recordScalar("startTime", startTime); module.recordScalar("totalTime", totalTime); module.recordScalar("stopTime", stopTime); if (minSpeed != MY_INFINITY) module.recordScalar("minSpeed", minSpeed); if (maxSpeed != -MY_INFINITY) module.recordScalar("maxSpeed", maxSpeed); module.recordScalar("totalDistance", totalDistance); module.recordScalar("totalCO2Emission", totalCO2Emission); } void TraCIMobility::initialize(int stage) { if (stage == 0) { BaseMobility::initialize(stage); hostPositionOffset = par("hostPositionOffset"); setHostSpeed = par("setHostSpeed"); accidentCount = par("accidentCount"); currentPosXVec.setName("posx"); currentPosYVec.setName("posy"); currentSpeedVec.setName("speed"); currentAccelerationVec.setName("acceleration"); currentCO2EmissionVec.setName("co2emission"); statistics.initialize(); statistics.watch(*this); ASSERT(isPreInitialized); isPreInitialized = false; Coord nextPos = calculateHostPosition(roadPosition); nextPos.z = move.getStartPosition().z; move.setStart(nextPos); move.setDirectionByVector(heading.toCoord()); move.setOrientationByVector(heading.toCoord()); if (this->setHostSpeed) { move.setSpeed(speed); } isParking = false; startAccidentMsg = nullptr; stopAccidentMsg = nullptr; manager = nullptr; last_speed = -1; if (accidentCount > 0) { simtime_t accidentStart = par("accidentStart"); startAccidentMsg = new cMessage("scheduledAccident"); stopAccidentMsg = new cMessage("scheduledAccidentResolved"); scheduleAt(simTime() + accidentStart, startAccidentMsg); } } else if (stage == 1) { // don't call BaseMobility::initialize(stage) -- our parent will take care to call changePosition later } else { BaseMobility::initialize(stage); } } void TraCIMobility::finish() { statistics.stopTime = simTime(); statistics.recordScalars(*this); cancelAndDelete(startAccidentMsg); cancelAndDelete(stopAccidentMsg); isPreInitialized = false; } void TraCIMobility::handleSelfMsg(cMessage* msg) { if (msg == startAccidentMsg) { getVehicleCommandInterface()->setSpeed(0); simtime_t accidentDuration = par("accidentDuration"); scheduleAt(simTime() + accidentDuration, stopAccidentMsg); accidentCount--; } else if (msg == stopAccidentMsg) { getVehicleCommandInterface()->setSpeed(-1); if (accidentCount > 0) { simtime_t accidentInterval = par("accidentInterval"); scheduleAt(simTime() + accidentInterval, startAccidentMsg); } } } void TraCIMobility::preInitialize(std::string external_id, const Coord& position, std::string road_id, double speed, Heading heading) { this->external_id = external_id; this->lastUpdate = 0; this->roadPosition = position; this->road_id = road_id; this->speed = speed; this->heading = heading; this->hostPositionOffset = par("hostPositionOffset"); this->setHostSpeed = par("setHostSpeed"); Coord nextPos = calculateHostPosition(roadPosition); nextPos.z = move.getStartPosition().z; move.setStart(nextPos); move.setDirectionByVector(heading.toCoord()); move.setOrientationByVector(heading.toCoord()); if (this->setHostSpeed) { move.setSpeed(speed); } isPreInitialized = true; } void TraCIMobility::nextPosition(const Coord& position, std::string road_id, double speed, Heading heading, VehicleSignalSet signals) { EV_DEBUG << "nextPosition " << position.x << " " << position.y << " " << road_id << " " << speed << " " << heading << std::endl; isPreInitialized = false; this->roadPosition = position; this->road_id = road_id; this->speed = speed; this->heading = heading; this->signals = signals; changePosition(); ASSERT(getCurrentDirection() == heading.toCoord() and getCurrentDirection() == getCurrentOrientation()); } void TraCIMobility::changePosition() { // ensure we're not called twice in one time step ASSERT(lastUpdate != simTime()); // keep statistics (for current step) currentPosXVec.record(move.getStartPos().x); currentPosYVec.record(move.getStartPos().y); Coord nextPos = calculateHostPosition(roadPosition); nextPos.z = move.getStartPosition().z; // keep statistics (relative to last step) if (statistics.startTime != simTime()) { simtime_t updateInterval = simTime() - this->lastUpdate; double distance = move.getStartPos().distance(nextPos); statistics.totalDistance += distance; statistics.totalTime += updateInterval; if (speed != -1) { statistics.minSpeed = std::min(statistics.minSpeed, speed); statistics.maxSpeed = std::max(statistics.maxSpeed, speed); currentSpeedVec.record(speed); if (last_speed != -1) { double acceleration = (speed - last_speed) / updateInterval; double co2emission = calculateCO2emission(speed, acceleration); currentAccelerationVec.record(acceleration); currentCO2EmissionVec.record(co2emission); statistics.totalCO2Emission += co2emission * updateInterval.dbl(); } last_speed = speed; } else { last_speed = -1; speed = -1; } } this->lastUpdate = simTime(); // Update display string to show node is getting updates auto hostMod = getParentModule(); if (std::string(hostMod->getDisplayString().getTagArg("veins", 0)) == ". ") { hostMod->getDisplayString().setTagArg("veins", 0, " ."); } else { hostMod->getDisplayString().setTagArg("veins", 0, ". "); } move.setStart(Coord(nextPos.x, nextPos.y, move.getStartPosition().z)); // keep z position move.setDirectionByVector(heading.toCoord()); move.setOrientationByVector(heading.toCoord()); if (this->setHostSpeed) { move.setSpeed(speed); } fixIfHostGetsOutside(); updatePosition(); } void TraCIMobility::changeParkingState(bool newState) { Enter_Method_Silent(); isParking = newState; emit(parkingStateChangedSignal, this); } void TraCIMobility::fixIfHostGetsOutside() { Coord pos = move.getStartPos(); Coord dummy = Coord::ZERO; double dum; bool outsideX = (pos.x < 0) || (pos.x >= playgroundSizeX()); bool outsideY = (pos.y < 0) || (pos.y >= playgroundSizeY()); bool outsideZ = (!world->use2D()) && ((pos.z < 0) || (pos.z >= playgroundSizeZ())); if (outsideX || outsideY || outsideZ) { throw cRuntimeError("Tried moving host to (%f, %f) which is outside the playground", pos.x, pos.y); } handleIfOutside(RAISEERROR, pos, dummy, dummy, dum); } double TraCIMobility::calculateCO2emission(double v, double a) const { // Calculate CO2 emission parameters according to: // Cappiello, A. and Chabini, I. and Nam, E.K. and Lue, A. and Abou Zeid, M., "A statistical model of vehicle emissions and fuel consumption," IEEE 5th International Conference on Intelligent Transportation Systems (IEEE ITSC), pp. 801-809, 2002 double A = 1000 * 0.1326; // W/m/s double B = 1000 * 2.7384e-03; // W/(m/s)^2 double C = 1000 * 1.0843e-03; // W/(m/s)^3 double M = 1325.0; // kg // power in W double P_tract = A * v + B * v * v + C * v * v * v + M * a * v; // for sloped roads: +M*g*sin_theta*v /* // "Category 7 vehicle" (e.g. a '92 Suzuki Swift) double alpha = 1.01; double beta = 0.0162; double delta = 1.90e-06; double zeta = 0.252; double alpha1 = 0.985; */ // "Category 9 vehicle" (e.g. a '94 Dodge Spirit) double alpha = 1.11; double beta = 0.0134; double delta = 1.98e-06; double zeta = 0.241; double alpha1 = 0.973; if (P_tract <= 0) return alpha1; return alpha + beta * v * 3.6 + delta * v * v * v * (3.6 * 3.6 * 3.6) + zeta * a * v; } Coord TraCIMobility::calculateHostPosition(const Coord& vehiclePos) const { Coord corPos; if (hostPositionOffset >= 0.001) { // calculate antenna position of vehicle according to antenna offset corPos = vehiclePos - (heading.toCoord() * hostPositionOffset); } else { corPos = vehiclePos; } return corPos; }
10,482
32.279365
249
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIMobility.h
// // Copyright (C) 2006-2012 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <string> #include <fstream> #include <list> #include <stdexcept> #include "veins/base/modules/BaseMobility.h" #include "veins/base/utils/FindModule.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/mobility/traci/VehicleSignal.h" #include "veins/base/utils/Heading.h" namespace veins { /** * @brief * Used in modules created by the TraCIScenarioManager. * * This module relies on the TraCIScenarioManager for state updates * and can not be used on its own. * * TraCI server implementations do not differentiate between the orientation and direction of a vehicle. * Thus, TraCIMobility::updatePosition sets the BaseMobility's orientation and direction to the same value. * Said value is equivalent to the heading of the vehicle. * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * @author Christoph Sommer, David Eckhoff, Luca Bedogni, Bastian Halmos, Stefan Joerer * * @see TraCIScenarioManager * @see TraCIScenarioManagerLaunchd * * @ingroup mobility */ class VEINS_API TraCIMobility : public BaseMobility { public: class VEINS_API Statistics { public: double firstRoadNumber; /**< for statistics: number of first road we encountered (if road id can be expressed as a number) */ simtime_t startTime; /**< for statistics: start time */ simtime_t totalTime; /**< for statistics: total time travelled */ simtime_t stopTime; /**< for statistics: stop time */ double minSpeed; /**< for statistics: minimum value of currentSpeed */ double maxSpeed; /**< for statistics: maximum value of currentSpeed */ double totalDistance; /**< for statistics: total distance travelled */ double totalCO2Emission; /**< for statistics: total CO2 emission */ void initialize(); void watch(cSimpleModule& module); void recordScalars(cSimpleModule& module); }; const static simsignal_t parkingStateChangedSignal; TraCIMobility() : BaseMobility() , isPreInitialized(false) , manager(nullptr) , commandInterface(nullptr) , vehicleCommandInterface(nullptr) { } ~TraCIMobility() override { delete vehicleCommandInterface; } void initialize(int) override; void finish() override; void handleSelfMsg(cMessage* msg) override; virtual void preInitialize(std::string external_id, const Coord& position, std::string road_id = "", double speed = -1, Heading heading = Heading::nan); virtual void nextPosition(const Coord& position, std::string road_id = "", double speed = -1, Heading heading = Heading::nan, VehicleSignalSet signals = {VehicleSignal::undefined}); virtual void changePosition(); virtual void changeParkingState(bool); virtual void setExternalId(std::string external_id) { this->external_id = external_id; } virtual std::string getExternalId() const { if (external_id == "") throw cRuntimeError("TraCIMobility::getExternalId called with no external_id set yet"); return external_id; } virtual double getHostPositionOffset() const { return hostPositionOffset; } virtual bool getParkingState() const { return isParking; } virtual std::string getRoadId() const { if (road_id == "") throw cRuntimeError("TraCIMobility::getRoadId called with no road_id set yet"); return road_id; } virtual double getSpeed() const { if (speed == -1) throw cRuntimeError("TraCIMobility::getSpeed called with no speed set yet"); return speed; } virtual VehicleSignalSet getSignals() const { if (signals.test(VehicleSignal::undefined)) throw cRuntimeError("TraCIMobility::getSignals called with no signals set yet"); return signals; } /** * returns heading. */ virtual Heading getHeading() const { if (heading.isNan()) throw cRuntimeError("TraCIMobility::getHeading called with no heading set yet"); return heading; } virtual TraCIScenarioManager* getManager() const { if (!manager) manager = TraCIScenarioManagerAccess().get(); return manager; } virtual TraCICommandInterface* getCommandInterface() const { if (!commandInterface) commandInterface = getManager()->getCommandInterface(); return commandInterface; } virtual TraCICommandInterface::Vehicle* getVehicleCommandInterface() const { if (!vehicleCommandInterface) vehicleCommandInterface = new TraCICommandInterface::Vehicle(getCommandInterface()->vehicle(getExternalId())); return vehicleCommandInterface; } /** * Returns the speed of the host (likely 0 if setHostSpeed==false) */ Coord getHostSpeed() const { return BaseMobility::getCurrentSpeed(); } protected: int accidentCount; /**< number of accidents */ cOutVector currentPosXVec; /**< vector plotting posx */ cOutVector currentPosYVec; /**< vector plotting posy */ cOutVector currentSpeedVec; /**< vector plotting speed */ cOutVector currentAccelerationVec; /**< vector plotting acceleration */ cOutVector currentCO2EmissionVec; /**< vector plotting current CO2 emission */ Statistics statistics; /**< everything statistics-related */ bool isPreInitialized; /**< true if preInitialize() has been called immediately before initialize() */ std::string external_id; /**< updated by setExternalId() */ double hostPositionOffset; /**< front offset for the antenna on this car */ bool setHostSpeed; /**< whether to update the speed of the host (along with its position) */ simtime_t lastUpdate; /**< updated by nextPosition() */ Coord roadPosition; /**< position of front bumper, updated by nextPosition() */ std::string road_id; /**< updated by nextPosition() */ double speed; /**< updated by nextPosition() */ Heading heading; /**< updated by nextPosition() */ VehicleSignalSet signals; /**<updated by nextPosition() */ cMessage* startAccidentMsg; cMessage* stopAccidentMsg; mutable TraCIScenarioManager* manager; mutable TraCICommandInterface* commandInterface; mutable TraCICommandInterface::Vehicle* vehicleCommandInterface; double last_speed; bool isParking; void fixIfHostGetsOutside() override; /**< called after each read to check for (and handle) invalid positions */ /** * Returns the amount of CO2 emissions in grams/second, calculated for an average Car * @param v speed in m/s * @param a acceleration in m/s^2 * @returns emission in g/s */ double calculateCO2emission(double v, double a) const; /** * Calculates where the OMNeT++ module position of this car should be, given its front bumper position */ Coord calculateHostPosition(const Coord& vehiclePos) const; /** * Calling this method on pointers of type TraCIMobility is deprecated in favor of calling either getHostSpeed or getSpeed. */ Coord getCurrentSpeed() const override { return BaseMobility::getCurrentSpeed(); } }; class VEINS_API TraCIMobilityAccess { public: TraCIMobility* get(cModule* host) { TraCIMobility* traci = FindModule<TraCIMobility*>::findSubModule(host); ASSERT(traci); return traci; }; }; } // namespace veins
8,475
35.692641
185
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIRegionOfInterest.cc
// // Copyright (C) 2015 Raphael Riebl <raphael.riebl@thi.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <algorithm> #include <sstream> #include "veins/veins.h" #include "veins/modules/mobility/traci/TraCIRegionOfInterest.h" namespace veins { TraCIRegionOfInterest::TraCIRegionOfInterest() { } void TraCIRegionOfInterest::addRoads(const std::string& roads) { std::istringstream roadsStream(roads); std::string road; while (std::getline(roadsStream, road, ' ')) { roiRoads.insert(road); } } void TraCIRegionOfInterest::addRectangles(const std::string& rects) { std::istringstream rectsStream(rects); std::string rect; while (std::getline(rectsStream, rect, ' ')) { std::istringstream rectStream(rect); double x1; rectStream >> x1; char c1; rectStream >> c1; double y1; rectStream >> y1; char c2; rectStream >> c2; double x2; rectStream >> x2; char c3; rectStream >> c3; double y2; rectStream >> y2; if (rectStream.good()) { throw cRuntimeError("Parsing ROI rectangle failed"); } roiRects.push_back(std::pair<TraCICoord, TraCICoord>(TraCICoord(x1, y1), TraCICoord(x2, y2))); } } void TraCIRegionOfInterest::clear() { roiRoads.clear(); roiRects.clear(); } bool TraCIRegionOfInterest::onAnyRectangle(const TraCICoord& position) const { struct RectangleTest { RectangleTest(const TraCICoord& position_) : position(position_) { } bool operator()(const std::pair<TraCICoord, TraCICoord>& rect) const { return (position.x >= rect.first.x && position.y >= rect.first.y) && (position.x <= rect.second.x && position.y <= rect.second.y); } const TraCICoord& position; }; std::list<std::pair<TraCICoord, TraCICoord>>::const_iterator found = std::find_if(roiRects.begin(), roiRects.end(), RectangleTest(position)); return found != roiRects.end(); } bool TraCIRegionOfInterest::partOfRoads(const std::string& road) const { return roiRoads.count(road) > 0; } bool TraCIRegionOfInterest::hasConstraints() const { return !roiRoads.empty() || !roiRects.empty(); } const std::list<std::pair<TraCICoord, TraCICoord>>& TraCIRegionOfInterest::getRectangles() const { return roiRects; } } // namespace veins
3,213
27.192982
145
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIRegionOfInterest.h
// // Copyright (C) 2015 Raphael Riebl <raphael.riebl@thi.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <list> #include <set> #include <string> #include <utility> #include "veins/modules/mobility/traci/TraCICoord.h" namespace veins { /** * Can return whether a given position lies within the simulation's region of interest. * Modules are destroyed and re-created as managed vehicles leave and re-enter the ROI */ class VEINS_API TraCIRegionOfInterest { public: enum ConstraintResult { NONE, // when no constraints exist SATISFY, BREAK }; TraCIRegionOfInterest(); /** * Add roads to contraints * @param roads given as road ids separated by spaces */ void addRoads(const std::string& roads); /** * Add rectangles to constraints * @param rects given as x1,y1-x2,y2 pairs separated by spaces */ void addRectangles(const std::string& rects); /** * Remove all constraints */ void clear(); /** * Check if position lies on any ROI rectangle * @param pos Position to check * @return true if on any rectangle */ bool onAnyRectangle(const TraCICoord& pos) const; /** * Check if a given road is part of interest roads * @param road_id * @return true if part of ROI roads */ bool partOfRoads(const std::string& road_id) const; /** * Check if any constraints are defined * @return true if constraints exist */ bool hasConstraints() const; const std::list<std::pair<TraCICoord, TraCICoord>>& getRectangles() const; private: std::set<std::string> roiRoads; /**< which roads (e.g. "hwy1 hwy2") are considered to consitute the region of interest, if not empty */ std::list<std::pair<TraCICoord, TraCICoord>> roiRects; /**< which rectangles (e.g. "0,0-10,10 20,20-30,30) are considered to consitute the region of interest, if not empty */ }; } // namespace veins
2,769
28.784946
178
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManager.cc
// // Copyright (C) 2006-2017 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <fstream> #include <vector> #include <algorithm> #include <stdexcept> #include <iterator> #include <cstdlib> #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/base/connectionManager/ChannelAccess.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/mobility/traci/TraCIConstants.h" #include "veins/modules/mobility/traci/TraCIMobility.h" #include "veins/modules/obstacle/ObstacleControl.h" #include "veins/modules/world/traci/trafficLight/TraCITrafficLightInterface.h" using namespace veins::TraCIConstants; using veins::AnnotationManagerAccess; using veins::TraCIBuffer; using veins::TraCICoord; using veins::TraCIScenarioManager; using veins::TraCITrafficLightInterface; Define_Module(veins::TraCIScenarioManager); const simsignal_t TraCIScenarioManager::traciInitializedSignal = registerSignal("org_car2x_veins_modules_mobility_traciInitialized"); const simsignal_t TraCIScenarioManager::traciModuleAddedSignal = registerSignal("org_car2x_veins_modules_mobility_traciModuleAdded"); const simsignal_t TraCIScenarioManager::traciModuleRemovedSignal = registerSignal("org_car2x_veins_modules_mobility_traciModuleRemoved"); const simsignal_t TraCIScenarioManager::traciTimestepBeginSignal = registerSignal("org_car2x_veins_modules_mobility_traciTimestepBegin"); const simsignal_t TraCIScenarioManager::traciTimestepEndSignal = registerSignal("org_car2x_veins_modules_mobility_traciTimestepEnd"); TraCIScenarioManager::TraCIScenarioManager() : connection(nullptr) , commandIfc(nullptr) , connectAndStartTrigger(nullptr) , executeOneTimestepTrigger(nullptr) , world(nullptr) { } TraCIScenarioManager::~TraCIScenarioManager() { if (connection) { TraCIBuffer buf = connection->query(CMD_CLOSE, TraCIBuffer()); } cancelAndDelete(connectAndStartTrigger); cancelAndDelete(executeOneTimestepTrigger); } namespace { std::vector<std::string> getMapping(std::string el) { // search for string protection characters ' char protection = '\''; size_t first = el.find(protection); size_t second; size_t eq; std::string type, value; std::vector<std::string> mapping; if (first == std::string::npos) { // there's no string protection, simply split by '=' cStringTokenizer stk(el.c_str(), "="); mapping = stk.asVector(); } else { // if there's string protection, we need to find a matching delimiter second = el.find(protection, first + 1); // ensure that a matching delimiter exists, and that it is at the end if (second == std::string::npos || second != el.size() - 1) throw cRuntimeError("invalid syntax for mapping \"%s\"", el.c_str()); // take the value of the mapping as the text within the quotes value = el.substr(first + 1, second - first - 1); if (first == 0) { // if the string starts with a quote, there's only the value mapping.push_back(value); } else { // search for the equal sign eq = el.find('='); // this must be the character before the quote if (eq == std::string::npos || eq != first - 1) { throw cRuntimeError("invalid syntax for mapping \"%s\"", el.c_str()); } else { type = el.substr(0, eq); } mapping.push_back(type); mapping.push_back(value); } } return mapping; } } // namespace TraCIScenarioManager::TypeMapping TraCIScenarioManager::parseMappings(std::string parameter, std::string parameterName, bool allowEmpty) { /** * possible syntaxes * * "a" : assign module type "a" to all nodes (for backward compatibility) * "a=b" : assign module type "b" to vehicle type "a". the presence of any other vehicle type in the simulation will cause the simulation to stop * "a=b c=d" : assign module type "b" to vehicle type "a" and "d" to "c". the presence of any other vehicle type in the simulation will cause the simulation to stop * "a=b c=d *=e": everything which is not of vehicle type "a" or "b", assign module type "e" * "a=b c=0" : for vehicle type "c" no module should be instantiated * "a=b c=d *=0": everything which is not of vehicle type a or c should not be instantiated * * For display strings key-value pairs needs to be protected with single quotes, as they use an = sign as the type mappings. For example * *.manager.moduleDisplayString = "'i=block/process'" * *.manager.moduleDisplayString = "a='i=block/process' b='i=misc/sun'" * * moduleDisplayString can also be left empty: * *.manager.moduleDisplayString = "" */ unsigned int i; TypeMapping map; // tokenizer to split into mappings ("a=b c=d", -> ["a=b", "c=d"]) cStringTokenizer typesTz(parameter.c_str(), " "); // get all mappings std::vector<std::string> typeMappings = typesTz.asVector(); // and check that there exists at least one if (typeMappings.size() == 0) { if (!allowEmpty) throw cRuntimeError("parameter \"%s\" is empty", parameterName.c_str()); else return map; } // loop through all mappings for (i = 0; i < typeMappings.size(); i++) { // tokenizer to find the mapping from vehicle type to module type std::string typeMapping = typeMappings[i]; std::vector<std::string> mapping = getMapping(typeMapping); if (mapping.size() == 1) { // we are where there is no actual assignment // "a": this is good // "a b=c": this is not if (typeMappings.size() != 1) // stop simulation with an error throw cRuntimeError("parameter \"%s\" includes multiple mappings, but \"%s\" is not mapped to any vehicle type", parameterName.c_str(), mapping[0].c_str()); else // all vehicle types should be instantiated with this module type map["*"] = mapping[0]; } else { // check that mapping is valid (a=b and not like a=b=c) if (mapping.size() != 2) throw cRuntimeError("invalid syntax for mapping \"%s\" for parameter \"%s\"", typeMapping.c_str(), parameterName.c_str()); // check that the mapping does not already exist if (map.find(mapping[0]) != map.end()) throw cRuntimeError("duplicated mapping for vehicle type \"%s\" for parameter \"%s\"", mapping[0].c_str(), parameterName.c_str()); // finally save the mapping map[mapping[0]] = mapping[1]; } } return map; } void TraCIScenarioManager::parseModuleTypes() { TypeMapping::iterator i; std::vector<std::string> typeKeys, nameKeys, displayStringKeys; std::string moduleTypes = par("moduleType").stdstringValue(); std::string moduleNames = par("moduleName").stdstringValue(); std::string moduleDisplayStrings = par("moduleDisplayString").stdstringValue(); moduleType = parseMappings(moduleTypes, "moduleType", false); moduleName = parseMappings(moduleNames, "moduleName", false); moduleDisplayString = parseMappings(moduleDisplayStrings, "moduleDisplayString", true); // perform consistency check. for each vehicle type in moduleType there must be a vehicle type // in moduleName (and in moduleDisplayString if moduleDisplayString is not empty) // get all the keys for (i = moduleType.begin(); i != moduleType.end(); i++) typeKeys.push_back(i->first); for (i = moduleName.begin(); i != moduleName.end(); i++) nameKeys.push_back(i->first); for (i = moduleDisplayString.begin(); i != moduleDisplayString.end(); i++) displayStringKeys.push_back(i->first); // sort them (needed for intersection) std::sort(typeKeys.begin(), typeKeys.end()); std::sort(nameKeys.begin(), nameKeys.end()); std::sort(displayStringKeys.begin(), displayStringKeys.end()); std::vector<std::string> intersection; // perform set intersection std::set_intersection(typeKeys.begin(), typeKeys.end(), nameKeys.begin(), nameKeys.end(), std::back_inserter(intersection)); if (intersection.size() != typeKeys.size() || intersection.size() != nameKeys.size()) throw cRuntimeError("keys of mappings of moduleType and moduleName are not the same"); if (displayStringKeys.size() == 0) return; intersection.clear(); std::set_intersection(typeKeys.begin(), typeKeys.end(), displayStringKeys.begin(), displayStringKeys.end(), std::back_inserter(intersection)); if (intersection.size() != displayStringKeys.size()) throw cRuntimeError("keys of mappings of moduleType and moduleName are not the same"); } void TraCIScenarioManager::initialize(int stage) { cSimpleModule::initialize(stage); if (stage != 1) { return; } trafficLightModuleType = par("trafficLightModuleType").stdstringValue(); trafficLightModuleName = par("trafficLightModuleName").stdstringValue(); trafficLightModuleDisplayString = par("trafficLightModuleDisplayString").stdstringValue(); trafficLightModuleIds.clear(); std::istringstream filterstream(par("trafficLightFilter").stdstringValue()); std::copy(std::istream_iterator<std::string>(filterstream), std::istream_iterator<std::string>(), std::back_inserter(trafficLightModuleIds)); connectAt = par("connectAt"); firstStepAt = par("firstStepAt"); updateInterval = par("updateInterval"); if (firstStepAt == -1) firstStepAt = connectAt + updateInterval; parseModuleTypes(); penetrationRate = par("penetrationRate").doubleValue(); ignoreGuiCommands = par("ignoreGuiCommands"); host = par("host").stdstringValue(); port = getPortNumber(); if (port == -1) { throw cRuntimeError("TraCI Port autoconfiguration failed, set 'port' != -1 in omnetpp.ini or provide VEINS_TRACI_PORT environment variable."); } autoShutdown = par("autoShutdown"); annotations = AnnotationManagerAccess().getIfExists(); roi.clear(); roi.addRoads(par("roiRoads")); roi.addRectangles(par("roiRects")); areaSum = 0; nextNodeVectorIndex = 0; hosts.clear(); subscribedVehicles.clear(); trafficLights.clear(); activeVehicleCount = 0; parkingVehicleCount = 0; drivingVehicleCount = 0; autoShutdownTriggered = false; world = FindModule<BaseWorldUtility*>::findGlobalModule(); vehicleObstacleControl = FindModule<VehicleObstacleControl*>::findGlobalModule(); ASSERT(firstStepAt > connectAt); connectAndStartTrigger = new cMessage("connect"); scheduleAt(connectAt, connectAndStartTrigger); executeOneTimestepTrigger = new cMessage("step"); scheduleAt(firstStepAt, executeOneTimestepTrigger); EV_DEBUG << "initialized TraCIScenarioManager" << endl; } void TraCIScenarioManager::init_traci() { auto* commandInterface = getCommandInterface(); { auto apiVersion = commandInterface->getVersion(); EV_DEBUG << "TraCI server \"" << apiVersion.second << "\" reports API version " << apiVersion.first << endl; commandInterface->setApiVersion(apiVersion.first); } { // query and set road network boundaries auto networkBoundaries = commandInterface->initNetworkBoundaries(par("margin")); if (world != nullptr && ((connection->traci2omnet(networkBoundaries.second).x > world->getPgs()->x) || (connection->traci2omnet(networkBoundaries.first).y > world->getPgs()->y))) { EV_DEBUG << "WARNING: Playground size (" << world->getPgs()->x << ", " << world->getPgs()->y << ") might be too small for vehicle at network bounds (" << connection->traci2omnet(networkBoundaries.second).x << ", " << connection->traci2omnet(networkBoundaries.first).y << ")" << endl; } } { // subscribe to list of departed and arrived vehicles, as well as simulation time simtime_t beginTime = 0; simtime_t endTime = SimTime::getMaxTime(); std::string objectId = ""; uint8_t variableNumber = 7; uint8_t variable1 = VAR_DEPARTED_VEHICLES_IDS; uint8_t variable2 = VAR_ARRIVED_VEHICLES_IDS; uint8_t variable3 = commandInterface->getTimeStepCmd(); uint8_t variable4 = VAR_TELEPORT_STARTING_VEHICLES_IDS; uint8_t variable5 = VAR_TELEPORT_ENDING_VEHICLES_IDS; uint8_t variable6 = VAR_PARKING_STARTING_VEHICLES_IDS; uint8_t variable7 = VAR_PARKING_ENDING_VEHICLES_IDS; TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_SIM_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1 << variable2 << variable3 << variable4 << variable5 << variable6 << variable7); processSubcriptionResult(buf); ASSERT(buf.eof()); } { // subscribe to list of vehicle ids simtime_t beginTime = 0; simtime_t endTime = SimTime::getMaxTime(); std::string objectId = ""; uint8_t variableNumber = 1; uint8_t variable1 = ID_LIST; TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_VEHICLE_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1); processSubcriptionResult(buf); ASSERT(buf.eof()); } if (!trafficLightModuleType.empty() && !trafficLightModuleIds.empty()) { // initialize traffic lights cModule* parentmod = getParentModule(); if (!parentmod) { throw cRuntimeError("Parent Module not found (for traffic light creation)"); } cModuleType* tlModuleType = cModuleType::get(trafficLightModuleType.c_str()); // query traffic lights via TraCI std::list<std::string> trafficLightIds = commandInterface->getTrafficlightIds(); size_t nrOfTrafficLights = trafficLightIds.size(); int cnt = 0; for (std::list<std::string>::iterator i = trafficLightIds.begin(); i != trafficLightIds.end(); ++i) { std::string tlId = *i; if (std::find(trafficLightModuleIds.begin(), trafficLightModuleIds.end(), tlId) == trafficLightModuleIds.end()) { continue; // filter only selected elements } Coord position = commandInterface->junction(tlId).getPosition(); cModule* module = tlModuleType->create(trafficLightModuleName.c_str(), parentmod, nrOfTrafficLights, cnt); module->par("externalId") = tlId; module->finalizeParameters(); module->getDisplayString().parse(trafficLightModuleDisplayString.c_str()); module->buildInside(); module->scheduleStart(simTime() + updateInterval); cModule* tlIfSubmodule = module->getSubmodule("tlInterface"); // initialize traffic light interface with current program TraCITrafficLightInterface* tlIfModule = dynamic_cast<TraCITrafficLightInterface*>(tlIfSubmodule); tlIfModule->preInitialize(tlId, position, updateInterval); // initialize mobility for positioning cModule* mobiSubmodule = module->getSubmodule("mobility"); mobiSubmodule->par("x") = position.x; mobiSubmodule->par("y") = position.y; mobiSubmodule->par("z") = position.z; module->callInitialize(); trafficLights[tlId] = module; subscribeToTrafficLightVariables(tlId); // subscribe after module is in trafficLights cnt++; } } ObstacleControl* obstacles = ObstacleControlAccess().getIfExists(); if (obstacles) { { // get list of polygons std::list<std::string> ids = commandInterface->getPolygonIds(); for (std::list<std::string>::iterator i = ids.begin(); i != ids.end(); ++i) { std::string id = *i; std::string typeId = commandInterface->polygon(id).getTypeId(); if (!obstacles->isTypeSupported(typeId)) continue; std::list<Coord> coords = commandInterface->polygon(id).getShape(); std::vector<Coord> shape; std::copy(coords.begin(), coords.end(), std::back_inserter(shape)); obstacles->addFromTypeAndShape(id, typeId, shape); } } } traciInitialized = true; emit(traciInitializedSignal, true); // draw and calculate area of rois for (std::list<std::pair<TraCICoord, TraCICoord>>::const_iterator r = roi.getRectangles().begin(), end = roi.getRectangles().end(); r != end; ++r) { TraCICoord first = r->first; TraCICoord second = r->second; std::list<Coord> pol; Coord a = connection->traci2omnet(first); Coord b = connection->traci2omnet(TraCICoord(first.x, second.y)); Coord c = connection->traci2omnet(second); Coord d = connection->traci2omnet(TraCICoord(second.x, first.y)); pol.push_back(a); pol.push_back(b); pol.push_back(c); pol.push_back(d); // draw polygon for region of interest if (annotations) { annotations->drawPolygon(pol, "black"); } // calculate region area double ab = a.distance(b); double ad = a.distance(d); double area = ab * ad; areaSum += area; } } void TraCIScenarioManager::finish() { while (hosts.begin() != hosts.end()) { deleteManagedModule(hosts.begin()->first); } recordScalar("roiArea", areaSum); } void TraCIScenarioManager::handleMessage(cMessage* msg) { if (msg->isSelfMessage()) { handleSelfMsg(msg); return; } throw cRuntimeError("TraCIScenarioManager doesn't handle messages from other modules"); } void TraCIScenarioManager::handleSelfMsg(cMessage* msg) { if (msg == connectAndStartTrigger) { connection.reset(TraCIConnection::connect(this, host.c_str(), port)); commandIfc.reset(new TraCICommandInterface(this, *connection, ignoreGuiCommands)); init_traci(); return; } if (msg == executeOneTimestepTrigger) { executeOneTimestep(); return; } throw cRuntimeError("TraCIScenarioManager received unknown self-message"); } void TraCIScenarioManager::preInitializeModule(cModule* mod, const std::string& nodeId, const Coord& position, const std::string& road_id, double speed, Heading heading, VehicleSignalSet signals) { // pre-initialize TraCIMobility auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod); for (auto mm : mobilityModules) { mm->preInitialize(nodeId, position, road_id, speed, heading); } } void TraCIScenarioManager::updateModulePosition(cModule* mod, const Coord& p, const std::string& edge, double speed, Heading heading, VehicleSignalSet signals) { // update position in TraCIMobility auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod); for (auto mm : mobilityModules) { mm->nextPosition(p, edge, speed, heading, signals); } } // name: host;Car;i=vehicle.gif void TraCIScenarioManager::addModule(std::string nodeId, std::string type, std::string name, std::string displayString, const Coord& position, std::string road_id, double speed, Heading heading, VehicleSignalSet signals, double length, double height, double width) { if (hosts.find(nodeId) != hosts.end()) throw cRuntimeError("tried adding duplicate module"); double option1 = hosts.size() / (hosts.size() + unEquippedHosts.size() + 1.0); double option2 = (hosts.size() + 1) / (hosts.size() + unEquippedHosts.size() + 1.0); if (fabs(option1 - penetrationRate) < fabs(option2 - penetrationRate)) { unEquippedHosts.insert(nodeId); return; } int32_t nodeVectorIndex = nextNodeVectorIndex++; cModule* parentmod = getParentModule(); if (!parentmod) throw cRuntimeError("Parent Module not found"); cModuleType* nodeType = cModuleType::get(type.c_str()); if (!nodeType) throw cRuntimeError("Module Type \"%s\" not found", type.c_str()); // TODO: this trashes the vectsize member of the cModule, although nobody seems to use it cModule* mod = nodeType->create(name.c_str(), parentmod, nodeVectorIndex, nodeVectorIndex); mod->finalizeParameters(); if (displayString.length() > 0) { mod->getDisplayString().parse(displayString.c_str()); } mod->buildInside(); mod->scheduleStart(simTime() + updateInterval); preInitializeModule(mod, nodeId, position, road_id, speed, heading, signals); mod->callInitialize(); hosts[nodeId] = mod; // post-initialize TraCIMobility auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod); for (auto mm : mobilityModules) { mm->changePosition(); } if (vehicleObstacleControl) { std::vector<AntennaPosition> initialAntennaPositions; for (auto& caModule : getSubmodulesOfType<ChannelAccess>(mod, true)) { initialAntennaPositions.push_back(caModule->getAntennaPosition()); } ASSERT(mobilityModules.size() == 1); auto mm = mobilityModules[0]; double offset = mm->getHostPositionOffset(); const MobileHostObstacle* vo = vehicleObstacleControl->add(MobileHostObstacle(initialAntennaPositions, mm, length, offset, width, height)); vehicleObstacles[mm] = vo; } emit(traciModuleAddedSignal, mod); } cModule* TraCIScenarioManager::getManagedModule(std::string nodeId) { if (hosts.find(nodeId) == hosts.end()) return nullptr; return hosts[nodeId]; } bool TraCIScenarioManager::isModuleUnequipped(std::string nodeId) { if (unEquippedHosts.find(nodeId) == unEquippedHosts.end()) return false; return true; } void TraCIScenarioManager::deleteManagedModule(std::string nodeId) { cModule* mod = getManagedModule(nodeId); if (!mod) throw cRuntimeError("no vehicle with Id \"%s\" found", nodeId.c_str()); emit(traciModuleRemovedSignal, mod); auto cas = getSubmodulesOfType<ChannelAccess>(mod, true); for (auto ca : cas) { cModule* nic = ca->getParentModule(); auto connectionManager = ChannelAccess::getConnectionManager(nic); connectionManager->unregisterNic(nic); } if (vehicleObstacleControl) { for (cModule::SubmoduleIterator iter(mod); !iter.end(); iter++) { cModule* submod = *iter; TraCIMobility* mm = dynamic_cast<TraCIMobility*>(submod); if (!mm) continue; auto vo = vehicleObstacles.find(mm); ASSERT(vo != vehicleObstacles.end()); vehicleObstacleControl->erase(vo->second); } } hosts.erase(nodeId); mod->callFinish(); mod->deleteModule(); } void TraCIScenarioManager::executeOneTimestep() { EV_DEBUG << "Triggering TraCI server simulation advance to t=" << simTime() << endl; simtime_t targetTime = simTime(); emit(traciTimestepBeginSignal, targetTime); if (isConnected()) { TraCIBuffer buf = connection->query(CMD_SIMSTEP2, TraCIBuffer() << targetTime); uint32_t count; buf >> count; EV_DEBUG << "Getting " << count << " subscription results" << endl; for (uint32_t i = 0; i < count; ++i) { processSubcriptionResult(buf); } } emit(traciTimestepEndSignal, targetTime); if (!autoShutdownTriggered) scheduleAt(simTime() + updateInterval, executeOneTimestepTrigger); } void TraCIScenarioManager::subscribeToVehicleVariables(std::string vehicleId) { // subscribe to some attributes of the vehicle simtime_t beginTime = 0; simtime_t endTime = SimTime::getMaxTime(); std::string objectId = vehicleId; uint8_t variableNumber = 8; uint8_t variable1 = VAR_POSITION; uint8_t variable2 = VAR_ROAD_ID; uint8_t variable3 = VAR_SPEED; uint8_t variable4 = VAR_ANGLE; uint8_t variable5 = VAR_SIGNALS; uint8_t variable6 = VAR_LENGTH; uint8_t variable7 = VAR_HEIGHT; uint8_t variable8 = VAR_WIDTH; TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_VEHICLE_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1 << variable2 << variable3 << variable4 << variable5 << variable6 << variable7 << variable8); processSubcriptionResult(buf); ASSERT(buf.eof()); } void TraCIScenarioManager::unsubscribeFromVehicleVariables(std::string vehicleId) { // subscribe to some attributes of the vehicle simtime_t beginTime = 0; simtime_t endTime = SimTime::getMaxTime(); std::string objectId = vehicleId; uint8_t variableNumber = 0; TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_VEHICLE_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber); ASSERT(buf.eof()); } void TraCIScenarioManager::subscribeToTrafficLightVariables(std::string tlId) { // subscribe to some attributes of the traffic light system simtime_t beginTime = 0; simtime_t endTime = SimTime::getMaxTime(); std::string objectId = tlId; uint8_t variableNumber = 4; uint8_t variable1 = TL_CURRENT_PHASE; uint8_t variable2 = TL_CURRENT_PROGRAM; uint8_t variable3 = TL_NEXT_SWITCH; uint8_t variable4 = TL_RED_YELLOW_GREEN_STATE; TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_TL_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1 << variable2 << variable3 << variable4); processSubcriptionResult(buf); ASSERT(buf.eof()); } void TraCIScenarioManager::unsubscribeFromTrafficLightVariables(std::string tlId) { // unsubscribe from some attributes of the traffic light system // this method is mainly for completeness as traffic lights are not supposed to be removed at runtime simtime_t beginTime = 0; simtime_t endTime = SimTime::getMaxTime(); std::string objectId = tlId; uint8_t variableNumber = 0; TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_TL_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber); ASSERT(buf.eof()); } void TraCIScenarioManager::processTrafficLightSubscription(std::string objectId, TraCIBuffer& buf) { cModule* tlIfSubmodule = trafficLights[objectId]->getSubmodule("tlInterface"); TraCITrafficLightInterface* tlIfModule = dynamic_cast<TraCITrafficLightInterface*>(tlIfSubmodule); if (!tlIfModule) { throw cRuntimeError("Could not find traffic light module %s", objectId.c_str()); } uint8_t variableNumber_resp; buf >> variableNumber_resp; for (uint8_t j = 0; j < variableNumber_resp; ++j) { uint8_t response_type; buf >> response_type; uint8_t isokay; buf >> isokay; if (isokay != RTYPE_OK) { std::string description = buf.readTypeChecked<std::string>(TYPE_STRING); if (isokay == RTYPE_NOTIMPLEMENTED) { throw cRuntimeError("TraCI server reported subscribing to 0x%2x not implemented (\"%s\"). Might need newer version.", response_type, description.c_str()); } else { throw cRuntimeError("TraCI server reported error subscribing to variable 0x%2x (\"%s\").", response_type, description.c_str()); } } switch (response_type) { case TL_CURRENT_PHASE: tlIfModule->setCurrentPhaseByNr(buf.readTypeChecked<int32_t>(TYPE_INTEGER), false); break; case TL_CURRENT_PROGRAM: tlIfModule->setCurrentLogicById(buf.readTypeChecked<std::string>(TYPE_STRING), false); break; case TL_NEXT_SWITCH: tlIfModule->setNextSwitch(buf.readTypeChecked<simtime_t>(getCommandInterface()->getTimeType()), false); break; case TL_RED_YELLOW_GREEN_STATE: tlIfModule->setCurrentState(buf.readTypeChecked<std::string>(TYPE_STRING), false); break; default: throw cRuntimeError("Received unhandled traffic light subscription result; type: 0x%02x", response_type); break; } } } void TraCIScenarioManager::processSimSubscription(std::string objectId, TraCIBuffer& buf) { uint8_t variableNumber_resp; buf >> variableNumber_resp; for (uint8_t j = 0; j < variableNumber_resp; ++j) { uint8_t variable1_resp; buf >> variable1_resp; uint8_t isokay; buf >> isokay; if (isokay != RTYPE_OK) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRING); std::string description; buf >> description; if (isokay == RTYPE_NOTIMPLEMENTED) throw cRuntimeError("TraCI server reported subscribing to variable 0x%2x not implemented (\"%s\"). Might need newer version.", variable1_resp, description.c_str()); throw cRuntimeError("TraCI server reported error subscribing to variable 0x%2x (\"%s\").", variable1_resp, description.c_str()); } if (variable1_resp == VAR_DEPARTED_VEHICLES_IDS) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRINGLIST); uint32_t count; buf >> count; EV_DEBUG << "TraCI reports " << count << " departed vehicles." << endl; for (uint32_t i = 0; i < count; ++i) { std::string idstring; buf >> idstring; // adding modules is handled on the fly when entering/leaving the ROI } activeVehicleCount += count; drivingVehicleCount += count; } else if (variable1_resp == VAR_ARRIVED_VEHICLES_IDS) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRINGLIST); uint32_t count; buf >> count; EV_DEBUG << "TraCI reports " << count << " arrived vehicles." << endl; for (uint32_t i = 0; i < count; ++i) { std::string idstring; buf >> idstring; if (subscribedVehicles.find(idstring) != subscribedVehicles.end()) { subscribedVehicles.erase(idstring); // no unsubscription via TraCI possible/necessary as of SUMO 1.0.0 (the vehicle has arrived) } // check if this object has been deleted already (e.g. because it was outside the ROI) cModule* mod = getManagedModule(idstring); if (mod) deleteManagedModule(idstring); if (unEquippedHosts.find(idstring) != unEquippedHosts.end()) { unEquippedHosts.erase(idstring); } } if ((count > 0) && (count >= activeVehicleCount) && autoShutdown) autoShutdownTriggered = true; activeVehicleCount -= count; drivingVehicleCount -= count; } else if (variable1_resp == VAR_TELEPORT_STARTING_VEHICLES_IDS) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRINGLIST); uint32_t count; buf >> count; EV_DEBUG << "TraCI reports " << count << " vehicles starting to teleport." << endl; for (uint32_t i = 0; i < count; ++i) { std::string idstring; buf >> idstring; // check if this object has been deleted already (e.g. because it was outside the ROI) cModule* mod = getManagedModule(idstring); if (mod) deleteManagedModule(idstring); if (unEquippedHosts.find(idstring) != unEquippedHosts.end()) { unEquippedHosts.erase(idstring); } } activeVehicleCount -= count; drivingVehicleCount -= count; } else if (variable1_resp == VAR_TELEPORT_ENDING_VEHICLES_IDS) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRINGLIST); uint32_t count; buf >> count; EV_DEBUG << "TraCI reports " << count << " vehicles ending teleport." << endl; for (uint32_t i = 0; i < count; ++i) { std::string idstring; buf >> idstring; // adding modules is handled on the fly when entering/leaving the ROI } activeVehicleCount += count; drivingVehicleCount += count; } else if (variable1_resp == VAR_PARKING_STARTING_VEHICLES_IDS) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRINGLIST); uint32_t count; buf >> count; EV_DEBUG << "TraCI reports " << count << " vehicles starting to park." << endl; for (uint32_t i = 0; i < count; ++i) { std::string idstring; buf >> idstring; cModule* mod = getManagedModule(idstring); auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod); for (auto mm : mobilityModules) { mm->changeParkingState(true); } } parkingVehicleCount += count; drivingVehicleCount -= count; } else if (variable1_resp == VAR_PARKING_ENDING_VEHICLES_IDS) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRINGLIST); uint32_t count; buf >> count; EV_DEBUG << "TraCI reports " << count << " vehicles ending to park." << endl; for (uint32_t i = 0; i < count; ++i) { std::string idstring; buf >> idstring; cModule* mod = getManagedModule(idstring); auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod); for (auto mm : mobilityModules) { mm->changeParkingState(false); } } parkingVehicleCount -= count; drivingVehicleCount += count; } else if (variable1_resp == getCommandInterface()->getTimeStepCmd()) { uint8_t varType; buf >> varType; ASSERT(varType == getCommandInterface()->getTimeType()); simtime_t serverTimestep; buf >> serverTimestep; EV_DEBUG << "TraCI reports current time step as " << serverTimestep << "ms." << endl; simtime_t omnetTimestep = simTime(); ASSERT(omnetTimestep == serverTimestep); } else { throw cRuntimeError("Received unhandled sim subscription result"); } } } void TraCIScenarioManager::processVehicleSubscription(std::string objectId, TraCIBuffer& buf) { bool isSubscribed = (subscribedVehicles.find(objectId) != subscribedVehicles.end()); double px; double py; std::string edge; double speed; double angle_traci; int signals; double length; double height; double width; int numRead = 0; uint8_t variableNumber_resp; buf >> variableNumber_resp; for (uint8_t j = 0; j < variableNumber_resp; ++j) { uint8_t variable1_resp; buf >> variable1_resp; uint8_t isokay; buf >> isokay; if (isokay != RTYPE_OK) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRING); std::string errormsg; buf >> errormsg; if (isSubscribed) { if (isokay == RTYPE_NOTIMPLEMENTED) throw cRuntimeError("TraCI server reported subscribing to vehicle variable 0x%2x not implemented (\"%s\"). Might need newer version.", variable1_resp, errormsg.c_str()); throw cRuntimeError("TraCI server reported error subscribing to vehicle variable 0x%2x (\"%s\").", variable1_resp, errormsg.c_str()); } } else if (variable1_resp == ID_LIST) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRINGLIST); uint32_t count; buf >> count; EV_DEBUG << "TraCI reports " << count << " active vehicles." << endl; ASSERT(count == activeVehicleCount); std::set<std::string> drivingVehicles; for (uint32_t i = 0; i < count; ++i) { std::string idstring; buf >> idstring; drivingVehicles.insert(idstring); } // check for vehicles that need subscribing to std::set<std::string> needSubscribe; std::set_difference(drivingVehicles.begin(), drivingVehicles.end(), subscribedVehicles.begin(), subscribedVehicles.end(), std::inserter(needSubscribe, needSubscribe.begin())); for (std::set<std::string>::const_iterator i = needSubscribe.begin(); i != needSubscribe.end(); ++i) { subscribedVehicles.insert(*i); subscribeToVehicleVariables(*i); } // check for vehicles that need unsubscribing from std::set<std::string> needUnsubscribe; std::set_difference(subscribedVehicles.begin(), subscribedVehicles.end(), drivingVehicles.begin(), drivingVehicles.end(), std::inserter(needUnsubscribe, needUnsubscribe.begin())); for (std::set<std::string>::const_iterator i = needUnsubscribe.begin(); i != needUnsubscribe.end(); ++i) { subscribedVehicles.erase(*i); unsubscribeFromVehicleVariables(*i); } } else if (variable1_resp == VAR_POSITION) { uint8_t varType; buf >> varType; ASSERT(varType == POSITION_2D); buf >> px; buf >> py; numRead++; } else if (variable1_resp == VAR_ROAD_ID) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_STRING); buf >> edge; numRead++; } else if (variable1_resp == VAR_SPEED) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_DOUBLE); buf >> speed; numRead++; } else if (variable1_resp == VAR_ANGLE) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_DOUBLE); buf >> angle_traci; numRead++; } else if (variable1_resp == VAR_SIGNALS) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_INTEGER); buf >> signals; numRead++; } else if (variable1_resp == VAR_LENGTH) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_DOUBLE); buf >> length; numRead++; } else if (variable1_resp == VAR_HEIGHT) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_DOUBLE); buf >> height; numRead++; } else if (variable1_resp == VAR_WIDTH) { uint8_t varType; buf >> varType; ASSERT(varType == TYPE_DOUBLE); buf >> width; numRead++; } else { throw cRuntimeError("Received unhandled vehicle subscription result"); } } // bail out if we didn't want to receive these subscription results if (!isSubscribed) return; // make sure we got updates for all attributes if (numRead != 8) return; Coord p = connection->traci2omnet(TraCICoord(px, py)); if ((p.x < 0) || (p.y < 0)) throw cRuntimeError("received bad node position (%.2f, %.2f), translated to (%.2f, %.2f)", px, py, p.x, p.y); Heading heading = connection->traci2omnetHeading(angle_traci); cModule* mod = getManagedModule(objectId); // is it in the ROI? bool inRoi = !roi.hasConstraints() ? true : (roi.onAnyRectangle(TraCICoord(px, py)) || roi.partOfRoads(edge)); if (!inRoi) { if (mod) { deleteManagedModule(objectId); EV_DEBUG << "Vehicle #" << objectId << " left region of interest" << endl; } else if (unEquippedHosts.find(objectId) != unEquippedHosts.end()) { unEquippedHosts.erase(objectId); EV_DEBUG << "Vehicle (unequipped) # " << objectId << " left region of interest" << endl; } return; } if (isModuleUnequipped(objectId)) { return; } if (!mod) { // no such module - need to create std::string vType = commandIfc->vehicle(objectId).getTypeId(); std::string mType, mName, mDisplayString; TypeMapping::iterator iType, iName, iDisplayString; TypeMapping::iterator i; iType = moduleType.find(vType); if (iType == moduleType.end()) { iType = moduleType.find("*"); if (iType == moduleType.end()) throw cRuntimeError("cannot find a module type for vehicle type \"%s\"", vType.c_str()); } mType = iType->second; // search for module name iName = moduleName.find(vType); if (iName == moduleName.end()) { iName = moduleName.find(std::string("*")); if (iName == moduleName.end()) throw cRuntimeError("cannot find a module name for vehicle type \"%s\"", vType.c_str()); } mName = iName->second; if (moduleDisplayString.size() != 0) { iDisplayString = moduleDisplayString.find(vType); if (iDisplayString == moduleDisplayString.end()) { iDisplayString = moduleDisplayString.find("*"); if (iDisplayString == moduleDisplayString.end()) throw cRuntimeError("cannot find a module display string for vehicle type \"%s\"", vType.c_str()); } mDisplayString = iDisplayString->second; } else { mDisplayString = ""; } if (mType != "0") { addModule(objectId, mType, mName, mDisplayString, p, edge, speed, heading, VehicleSignalSet(signals), length, height, width); EV_DEBUG << "Added vehicle #" << objectId << endl; } } else { // module existed - update position EV_DEBUG << "module " << objectId << " moving to " << p.x << "," << p.y << endl; updateModulePosition(mod, p, edge, speed, heading, VehicleSignalSet(signals)); } } void TraCIScenarioManager::processSubcriptionResult(TraCIBuffer& buf) { uint8_t cmdLength_resp; buf >> cmdLength_resp; uint32_t cmdLengthExt_resp; buf >> cmdLengthExt_resp; uint8_t commandId_resp; buf >> commandId_resp; std::string objectId_resp; buf >> objectId_resp; if (commandId_resp == RESPONSE_SUBSCRIBE_VEHICLE_VARIABLE) processVehicleSubscription(objectId_resp, buf); else if (commandId_resp == RESPONSE_SUBSCRIBE_SIM_VARIABLE) processSimSubscription(objectId_resp, buf); else if (commandId_resp == RESPONSE_SUBSCRIBE_TL_VARIABLE) processTrafficLightSubscription(objectId_resp, buf); else { throw cRuntimeError("Received unhandled subscription result"); } } int TraCIScenarioManager::getPortNumber() const { int port = par("port"); if (port != -1) { return port; } // search for externally configured traci port const char* env_port = std::getenv("VEINS_TRACI_PORT"); if (env_port != nullptr) { port = std::atoi(env_port); } return port; }
44,467
38.953279
295
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManager.h
// // Copyright (C) 2006-2017 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <map> #include <memory> #include <list> #include <queue> #include "veins/veins.h" #include "veins/base/utils/Coord.h" #include "veins/base/modules/BaseWorldUtility.h" #include "veins/base/connectionManager/BaseConnectionManager.h" #include "veins/base/utils/FindModule.h" #include "veins/modules/obstacle/ObstacleControl.h" #include "veins/modules/obstacle/VehicleObstacleControl.h" #include "veins/modules/mobility/traci/TraCIBuffer.h" #include "veins/modules/mobility/traci/TraCIColor.h" #include "veins/modules/mobility/traci/TraCIConnection.h" #include "veins/modules/mobility/traci/TraCICoord.h" #include "veins/modules/mobility/traci/VehicleSignal.h" #include "veins/modules/mobility/traci/TraCIRegionOfInterest.h" namespace veins { class TraCICommandInterface; class MobileHostObstacle; /** * @brief * Creates and moves nodes controlled by a TraCI server. * * If the server is a SUMO road traffic simulation, you can use the * TraCIScenarioManagerLaunchd module and sumo-launchd.py script instead. * * All nodes created thus must have a TraCIMobility submodule. * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * @author Christoph Sommer, David Eckhoff, Falko Dressler, Zheng Yao, Tobias Mayer, Alvaro Torres Cortes, Luca Bedogni * * @see TraCIMobility * @see TraCIScenarioManagerLaunchd * */ class VEINS_API TraCIScenarioManager : public cSimpleModule { public: static const simsignal_t traciInitializedSignal; static const simsignal_t traciModuleAddedSignal; static const simsignal_t traciModuleRemovedSignal; static const simsignal_t traciTimestepBeginSignal; static const simsignal_t traciTimestepEndSignal; TraCIScenarioManager(); ~TraCIScenarioManager() override; int numInitStages() const override { return std::max(cSimpleModule::numInitStages(), 2); } void initialize(int stage) override; void finish() override; void handleMessage(cMessage* msg) override; virtual void handleSelfMsg(cMessage* msg); bool isConnected() const { return static_cast<bool>(connection); } TraCICommandInterface* getCommandInterface() const { return commandIfc.get(); } TraCIConnection* getConnection() const { return connection.get(); } bool getAutoShutdownTriggered() { return autoShutdownTriggered; } const std::map<std::string, cModule*>& getManagedHosts() { return hosts; } /** * Predicate indicating a successful connection to the TraCI server. * * @note Once the connection has been established, this will return true even when the connection has been torn down again. */ bool isUsable() const { return traciInitialized; } protected: bool traciInitialized = false; /**< Flag indicating whether the init_traci routine has been run. Note that it will change to false again once set, even during shutdown. */ simtime_t connectAt; /**< when to connect to TraCI server (must be the initial timestep of the server) */ simtime_t firstStepAt; /**< when to start synchronizing with the TraCI server (-1: immediately after connecting) */ simtime_t updateInterval; /**< time interval of hosts' position updates */ // maps from vehicle type to moduleType, moduleName, and moduleDisplayString typedef std::map<std::string, std::string> TypeMapping; TypeMapping moduleType; /**< module type to be used in the simulation for each managed vehicle */ TypeMapping moduleName; /**< module name to be used in the simulation for each managed vehicle */ TypeMapping moduleDisplayString; /**< module displayString to be used in the simulation for each managed vehicle */ std::string host; int port; std::string trafficLightModuleType; /**< module type to be used in the simulation for each managed traffic light */ std::string trafficLightModuleName; /**< module name to be used in the simulation for each managed traffic light */ std::string trafficLightModuleDisplayString; /**< module displayString to be used in the simulation for each managed vehicle */ std::vector<std::string> trafficLightModuleIds; /**< list of traffic light module ids that is subscribed to (whitelist) */ bool autoShutdown; /**< Shutdown module as soon as no more vehicles are in the simulation */ double penetrationRate; bool ignoreGuiCommands; /**< whether to ignore all TraCI commands that only make sense when the server has a graphical user interface */ TraCIRegionOfInterest roi; /**< Can return whether a given position lies within the simulation's region of interest. Modules are destroyed and re-created as managed vehicles leave and re-enter the ROI */ double areaSum; AnnotationManager* annotations; std::unique_ptr<TraCIConnection> connection; std::unique_ptr<TraCICommandInterface> commandIfc; size_t nextNodeVectorIndex; /**< next OMNeT++ module vector index to use */ std::map<std::string, cModule*> hosts; /**< vector of all hosts managed by us */ std::set<std::string> unEquippedHosts; std::set<std::string> subscribedVehicles; /**< all vehicles we have already subscribed to */ std::map<std::string, cModule*> trafficLights; /**< vector of all traffic lights managed by us */ uint32_t activeVehicleCount; /**< number of vehicles, be it parking or driving **/ uint32_t parkingVehicleCount; /**< number of parking vehicles, derived from parking start/end events */ uint32_t drivingVehicleCount; /**< number of driving, as reported by sumo */ bool autoShutdownTriggered; cMessage* connectAndStartTrigger; /**< self-message scheduled for when to connect to TraCI server and start running */ cMessage* executeOneTimestepTrigger; /**< self-message scheduled for when to next call executeOneTimestep */ BaseWorldUtility* world; std::map<const BaseMobility*, const MobileHostObstacle*> vehicleObstacles; VehicleObstacleControl* vehicleObstacleControl; void executeOneTimestep(); /**< read and execute all commands for the next timestep */ virtual void init_traci(); virtual void preInitializeModule(cModule* mod, const std::string& nodeId, const Coord& position, const std::string& road_id, double speed, Heading heading, VehicleSignalSet signals); virtual void updateModulePosition(cModule* mod, const Coord& p, const std::string& edge, double speed, Heading heading, VehicleSignalSet signals); void addModule(std::string nodeId, std::string type, std::string name, std::string displayString, const Coord& position, std::string road_id = "", double speed = -1, Heading heading = Heading::nan, VehicleSignalSet signals = {VehicleSignal::undefined}, double length = 0, double height = 0, double width = 0); cModule* getManagedModule(std::string nodeId); /**< returns a pointer to the managed module named moduleName, or 0 if no module can be found */ void deleteManagedModule(std::string nodeId); bool isModuleUnequipped(std::string nodeId); /**< returns true if this vehicle is Unequipped */ void subscribeToVehicleVariables(std::string vehicleId); void unsubscribeFromVehicleVariables(std::string vehicleId); void processSimSubscription(std::string objectId, TraCIBuffer& buf); void processVehicleSubscription(std::string objectId, TraCIBuffer& buf); void processSubcriptionResult(TraCIBuffer& buf); void subscribeToTrafficLightVariables(std::string tlId); void unsubscribeFromTrafficLightVariables(std::string tlId); void processTrafficLightSubscription(std::string objectId, TraCIBuffer& buf); /** * parses the vector of module types in ini file * * in case of inconsistencies the function kills the simulation */ void parseModuleTypes(); /** * transforms a list of mappings of an omnetpp.ini parameter in a list */ TypeMapping parseMappings(std::string parameter, std::string parameterName, bool allowEmpty = false); virtual int getPortNumber() const; }; class VEINS_API TraCIScenarioManagerAccess { public: TraCIScenarioManager* get() { return FindModule<TraCIScenarioManager*>::findGlobalModule(); }; }; } // namespace veins
9,225
42.933333
313
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerForker.cc
// // Copyright (C) 2006-2016 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #define WANT_WINSOCK2 #include <platdep/sockets.h> #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64) #include <ws2tcpip.h> #else #include <netinet/tcp.h> #include <netdb.h> #include <arpa/inet.h> #endif #include <sstream> #include <iostream> #include <fstream> #include "veins/modules/mobility/traci/TraCIScenarioManagerForker.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/mobility/traci/TraCIConstants.h" #include "veins/modules/mobility/traci/TraCILauncher.h" using veins::TraCILauncher; using veins::TraCIScenarioManagerForker; Define_Module(veins::TraCIScenarioManagerForker); namespace { template <typename T> inline std::string replace(std::string haystack, std::string needle, T newValue) { size_t i = haystack.find(needle, 0); if (i == std::string::npos) return haystack; std::ostringstream os; os << newValue; haystack.replace(i, needle.length(), os.str()); return haystack; } } // namespace TraCIScenarioManagerForker::TraCIScenarioManagerForker() { server = nullptr; } TraCIScenarioManagerForker::~TraCIScenarioManagerForker() { killServer(); } void TraCIScenarioManagerForker::initialize(int stage) { if (stage == 1) { commandLine = par("commandLine").stringValue(); command = par("command").stringValue(); configFile = par("configFile").stringValue(); seed = par("seed"); killServer(); } TraCIScenarioManager::initialize(stage); if (stage == 1) { startServer(); } } void TraCIScenarioManagerForker::finish() { TraCIScenarioManager::finish(); killServer(); } void TraCIScenarioManagerForker::startServer() { // autoset seed, if requested if (seed == -1) { const char* seed_s = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNNUMBER); seed = atoi(seed_s); } // assemble commandLine commandLine = replace(commandLine, "$command", command); commandLine = replace(commandLine, "$configFile", configFile); commandLine = replace(commandLine, "$seed", seed); commandLine = replace(commandLine, "$port", port); server = new TraCILauncher(commandLine); } void TraCIScenarioManagerForker::killServer() { if (server) { delete server; server = nullptr; } } int TraCIScenarioManagerForker::getPortNumber() const { int port = TraCIScenarioManager::getPortNumber(); if (port != -1) { return port; } // find a free port for the forker if port is still -1 if (initsocketlibonce() != 0) throw cRuntimeError("Could not init socketlib"); SOCKET sock = ::socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { throw cRuntimeError("Failed to create socket: %s", strerror(errno)); } struct sockaddr_in serv_addr; struct sockaddr* serv_addr_p = (struct sockaddr*) &serv_addr; memset(serv_addr_p, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = 0; if (::bind(sock, serv_addr_p, sizeof(serv_addr)) < 0) { throw cRuntimeError("Failed to bind socket: %s", strerror(errno)); } socklen_t len = sizeof(serv_addr); if (getsockname(sock, serv_addr_p, &len) < 0) { throw cRuntimeError("Failed to get hostname: %s", strerror(errno)); } port = ntohs(serv_addr.sin_port); closesocket(sock); return port; }
4,425
27.554839
122
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerForker.h
// // Copyright (C) 2006-2016 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/modules/mobility/traci/TraCILauncher.h" namespace veins { /** * @brief * * Extends the TraCIScenarioManager to automatically fork an instance of SUMO when needed. * * All other functionality is provided by the TraCIScenarioManager. * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * @author Christoph Sommer, Florian Hagenauer * * @see TraCIMobility * @see TraCIScenarioManager * */ class VEINS_API TraCIScenarioManagerForker : public TraCIScenarioManager { public: TraCIScenarioManagerForker(); ~TraCIScenarioManagerForker() override; void initialize(int stage) override; void finish() override; protected: std::string commandLine; /**< command line for running TraCI server (substituting $configFile, $seed, $port) */ std::string command; /**< substitution for $command parameter */ std::string configFile; /**< substitution for $configFile parameter */ int seed; /**< substitution for $seed parameter (-1: current run number) */ TraCILauncher* server; virtual void startServer(); virtual void killServer(); int getPortNumber() const override; }; class VEINS_API TraCIScenarioManagerForkerAccess { public: TraCIScenarioManagerForker* get() { return FindModule<TraCIScenarioManagerForker*>::findGlobalModule(); }; }; } // namespace veins
2,427
31.373333
115
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerLaunchd.cc
// // Copyright (C) 2006-2012 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/mobility/traci/TraCIScenarioManagerLaunchd.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/mobility/traci/TraCIConstants.h" #include <sstream> #include <iostream> #include <fstream> namespace veins { namespace TraCIConstants { const uint8_t CMD_FILE_SEND = 0x75; } // namespace TraCIConstants } // namespace veins using namespace veins::TraCIConstants; using veins::TraCIScenarioManagerLaunchd; Define_Module(veins::TraCIScenarioManagerLaunchd); TraCIScenarioManagerLaunchd::~TraCIScenarioManagerLaunchd() { } void TraCIScenarioManagerLaunchd::initialize(int stage) { if (stage != 1) { TraCIScenarioManager::initialize(stage); return; } launchConfig = par("launchConfig").xmlValue(); seed = par("seed"); cXMLElementList basedir_nodes = launchConfig->getElementsByTagName("basedir"); if (basedir_nodes.size() == 0) { // default basedir is where current network file was loaded from std::string basedir = cSimulation::getActiveSimulation()->getEnvir()->getConfig()->getConfigEntry("network").getBaseDirectory(); cXMLElement* basedir_node = new cXMLElement("basedir", __FILE__, launchConfig); basedir_node->setAttribute("path", basedir.c_str()); launchConfig->appendChild(basedir_node); } cXMLElementList seed_nodes = launchConfig->getElementsByTagName("seed"); if (seed_nodes.size() == 0) { if (seed == -1) { // default seed is current repetition const char* seed_s = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNNUMBER); seed = atoi(seed_s); } std::stringstream ss; ss << seed; cXMLElement* seed_node = new cXMLElement("seed", __FILE__, launchConfig); seed_node->setAttribute("value", ss.str().c_str()); launchConfig->appendChild(seed_node); } TraCIScenarioManager::initialize(stage); } void TraCIScenarioManagerLaunchd::finish() { TraCIScenarioManager::finish(); } void TraCIScenarioManagerLaunchd::init_traci() { { std::pair<uint32_t, std::string> version = getCommandInterface()->getVersion(); uint32_t apiVersion = version.first; std::string serverVersion = version.second; if (apiVersion == 1) { EV_DEBUG << "TraCI server \"" << serverVersion << "\" reports API version " << apiVersion << endl; } else { throw cRuntimeError("TraCI server \"%s\" reports API version %d, which is unsupported. We recommend using the version of sumo-launchd that ships with Veins.", serverVersion.c_str(), apiVersion); } } #if OMNETPP_VERSION <= 0x500 std::string contents = launchConfig->tostr(0); #else std::string contents = launchConfig->getXML(); #endif TraCIBuffer buf; buf << std::string("sumo-launchd.launch.xml") << contents; connection->sendMessage(makeTraCICommand(CMD_FILE_SEND, buf)); TraCIBuffer obuf(connection->receiveMessage()); uint8_t cmdLength; obuf >> cmdLength; uint8_t commandResp; obuf >> commandResp; if (commandResp != CMD_FILE_SEND) throw cRuntimeError("Expected response to command %d, but got one for command %d", CMD_FILE_SEND, commandResp); uint8_t result; obuf >> result; std::string description; obuf >> description; if (result != RTYPE_OK) { EV << "Warning: Received non-OK response from TraCI server to command " << CMD_FILE_SEND << ":" << description.c_str() << std::endl; } TraCIScenarioManager::init_traci(); }
4,535
34.162791
206
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerLaunchd.h
// // Copyright (C) 2006-2012 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" namespace veins { /** * @brief * Extends the TraCIScenarioManager for use with sumo-launchd.py and SUMO. * * Connects to a running instance of the sumo-launchd.py script * to automatically launch/kill SUMO when the simulation starts/ends. * * All other functionality is provided by the TraCIScenarioManager. * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * @author Christoph Sommer, David Eckhoff * * @see TraCIMobility * @see TraCIScenarioManager * */ class VEINS_API TraCIScenarioManagerLaunchd : public TraCIScenarioManager { public: ~TraCIScenarioManagerLaunchd() override; void initialize(int stage) override; void finish() override; protected: cXMLElement* launchConfig; /**< launch configuration to send to sumo-launchd */ int seed; /**< seed value to set in launch configuration, if missing (-1: current run number) */ void init_traci() override; }; class VEINS_API TraCIScenarioManagerLaunchdAccess { public: TraCIScenarioManagerLaunchd* get() { return FindModule<TraCIScenarioManagerLaunchd*>::findGlobalModule(); }; }; } // namespace veins
2,203
30.485714
113
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScreenRecorder.cc
// // Copyright (C) 2006-2014 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/mobility/traci/TraCIScreenRecorder.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #ifdef _WIN32 #define realpath(N, R) _fullpath((R), (N), _MAX_PATH) #endif /* _WIN32 */ using veins::TraCIScreenRecorder; Define_Module(veins::TraCIScreenRecorder); void TraCIScreenRecorder::initialize(int stage) { if (stage == 0) { takeScreenshot = new cMessage("take screenshot"); takeScreenshot->setSchedulingPriority(1); // this schedules screenshots after TraCI timesteps scheduleAt(par("start"), takeScreenshot); return; } } void TraCIScreenRecorder::handleMessage(cMessage* msg) { ASSERT(msg == takeScreenshot); // get dirname const char* dirname = par("dirname").stringValue(); if (std::string(dirname) == "") { dirname = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RESULTDIR); } // get absolute path of dirname (the TraCI server might be running in a different directory than OMNeT++) std::string dirname_abs; { char* s = realpath(dirname, nullptr); if (!s) { perror("cannot open output directory"); throw cRuntimeError("cannot open output directory '%s'", dirname); } dirname_abs = s; free(s); } // get filename template std::string filenameTemplate = par("filenameTemplate").stdstringValue(); if (filenameTemplate == "") { const char* myRunID = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNID); filenameTemplate = "screenshot-" + std::string(myRunID) + "-@%08.2f.png"; #ifdef _WIN32 // replace ':' with '-' for (std::string::iterator i = filenameTemplate.begin(); i != filenameTemplate.end(); ++i) if (*i == ':') *i = '-'; #endif /* _WIN32 */ } // assemble filename std::string filename; { std::string tmpl = dirname_abs + "/" + filenameTemplate; char buf[1024]; snprintf(buf, 1024, tmpl.c_str(), simTime().dbl()); buf[1023] = 0; filename = buf; } // take screenshot TraCIScenarioManager* manager = TraCIScenarioManagerAccess().get(); ASSERT(manager); TraCICommandInterface* traci = manager->getCommandInterface(); if (!traci) { throw cRuntimeError("Cannot create screenshot: TraCI is not connected yet"); } TraCICommandInterface::GuiView view = traci->guiView(par("viewName")); view.takeScreenshot(filename); // schedule next screenshot simtime_t stop = par("stop"); if ((stop == -1) || (simTime() < stop)) { scheduleAt(simTime() + par("interval"), takeScreenshot); } } void TraCIScreenRecorder::finish() { cancelAndDelete(takeScreenshot); }
3,770
33.281818
119
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIScreenRecorder.h
// // Copyright (C) 2006-2014 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" namespace veins { /** * @brief * Simple support module to take (a series of) screenshots of a simulation running in the TraCI server. * * Note that the TraCI server needs to be run in GUI mode and support taking screenshots for this to work. * * The screenshots can then be converted to a video using something along the lines of * mencoder 'mf://results/screenshot-*.png' -mf w=800:h=600:fps=25:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * @author Christoph Sommer * * @see TraCIScenarioManager * */ class VEINS_API TraCIScreenRecorder : public cSimpleModule { public: void initialize(int stage) override; void handleMessage(cMessage* msg) override; void finish() override; protected: cMessage* takeScreenshot; }; } // namespace veins
1,867
32.357143
144
h
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIVehicleInserter.cc
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/mobility/traci/TraCIVehicleInserter.h" #include <vector> #include <algorithm> #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/mobility/traci/TraCIMobility.h" #include "veins/base/utils/FindModule.h" Define_Module(veins::TraCIVehicleInserter); using namespace veins; TraCIVehicleInserter::TraCIVehicleInserter() : mobRng(nullptr) { } TraCIVehicleInserter::~TraCIVehicleInserter() { } int TraCIVehicleInserter::numInitStages() const { return std::max(cSimpleModule::numInitStages(), 2); } void TraCIVehicleInserter::initialize(int stage) { cSimpleModule::initialize(stage); if (stage != 1) { return; } // internal 1 manager = TraCIScenarioManagerAccess().get(); // signals manager->subscribe(TraCIScenarioManager::traciModuleAddedSignal, this); manager->subscribe(TraCIScenarioManager::traciTimestepBeginSignal, this); // parameters vehicleRngIndex = par("vehicleRngIndex"); numVehicles = par("numVehicles"); // internal 2 vehicleNameCounter = 0; mobRng = getRNG(vehicleRngIndex); } void TraCIVehicleInserter::finish() { unsubscribe(TraCIScenarioManager::traciModuleAddedSignal, this); unsubscribe(TraCIScenarioManager::traciTimestepBeginSignal, this); } void TraCIVehicleInserter::finish(cComponent* component, simsignal_t signalID) { cListener::finish(component, signalID); } void TraCIVehicleInserter::handleMessage(cMessage* msg) { } void TraCIVehicleInserter::receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details) { if (signalID == TraCIScenarioManager::traciModuleAddedSignal) { ASSERT(manager->isConnected()); cModule* mod = check_and_cast<cModule*>(obj); auto* mob = FindModule<TraCIMobility*>::findSubModule(mod); ASSERT(mob != nullptr); std::string nodeId = mob->getExternalId(); if (queuedVehicles.find(nodeId) != queuedVehicles.end()) { queuedVehicles.erase(nodeId); } } } void TraCIVehicleInserter::receiveSignal(cComponent* source, simsignal_t signalID, const SimTime& t, cObject* details) { if (signalID == TraCIScenarioManager::traciTimestepBeginSignal) { ASSERT(manager->isConnected()); if (simTime() > 1) { if (vehicleTypeIds.size() == 0) { std::list<std::string> vehTypes = manager->getCommandInterface()->getVehicleTypeIds(); for (std::list<std::string>::const_iterator i = vehTypes.begin(); i != vehTypes.end(); ++i) { if (i->substr(0, 8).compare("DEFAULT_") != 0) { EV_DEBUG << *i << std::endl; vehicleTypeIds.push_back(*i); } } } if (routeIds.size() == 0) { std::list<std::string> routes = manager->getCommandInterface()->getRouteIds(); for (std::list<std::string>::const_iterator i = routes.begin(); i != routes.end(); ++i) { std::string routeId = *i; if (par("useRouteDistributions").boolValue() == true) { if (std::count(routeId.begin(), routeId.end(), '#') >= 1) { EV_DEBUG << "Omitting route " << routeId << " as it seems to be a member of a route distribution (found '#' in name)" << std::endl; continue; } } EV_DEBUG << "Adding " << routeId << " to list of possible routes" << std::endl; routeIds.push_back(routeId); } } for (int i = manager->getManagedHosts().size() + queuedVehicles.size(); i < numVehicles; i++) { insertNewVehicle(); } } insertVehicles(); } } void TraCIVehicleInserter::insertNewVehicle() { std::string type; if (vehicleTypeIds.size()) { int vehTypeId = mobRng->intRand(vehicleTypeIds.size()); type = vehicleTypeIds[vehTypeId]; } else { type = "DEFAULT_VEHTYPE"; } int routeId = mobRng->intRand(routeIds.size()); vehicleInsertQueue[routeId].push(type); } void TraCIVehicleInserter::insertVehicles() { for (std::map<int, std::queue<std::string>>::iterator i = vehicleInsertQueue.begin(); i != vehicleInsertQueue.end();) { std::string route = routeIds[i->first]; EV_DEBUG << "process " << route << std::endl; std::queue<std::string> vehicles = i->second; while (!i->second.empty()) { bool suc = false; std::string type = i->second.front(); std::stringstream veh; veh << type << "_" << vehicleNameCounter; EV_DEBUG << "trying to add " << veh.str() << " with " << route << " vehicle type " << type << std::endl; suc = manager->getCommandInterface()->addVehicle(veh.str(), type, route, simTime()); if (!suc) { i->second.pop(); } else { EV_DEBUG << "successful inserted " << veh.str() << std::endl; queuedVehicles.insert(veh.str()); i->second.pop(); vehicleNameCounter++; } } std::map<int, std::queue<std::string>>::iterator tmp = i; ++tmp; vehicleInsertQueue.erase(i); i = tmp; } }
6,422
33.532258
159
cc
null
AICP-main/veins/src/veins/modules/mobility/traci/TraCIVehicleInserter.h
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <queue> #include "veins/veins.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" namespace veins { /** * @brief * Uses the TraCIScenarioManager to programmatically insert new vehicles at the TraCI server. * * This is done whenever the total number of active vehicles drops below a given number. * * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>. * * @author Christoph Sommer, David Eckhoff, Falko Dressler, Zheng Yao, Tobias Mayer, Alvaro Torres Cortes, Luca Bedogni * * @see TraCIScenarioManager * */ class VEINS_API TraCIVehicleInserter : public cSimpleModule, public cListener { public: TraCIVehicleInserter(); ~TraCIVehicleInserter() override; int numInitStages() const override; void initialize(int stage) override; void finish() override; void finish(cComponent* component, simsignal_t signalID) override; void handleMessage(cMessage* msg) override; void receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details) override; void receiveSignal(cComponent* source, simsignal_t signalID, const SimTime& t, cObject* details) override; protected: /** * adds a new vehicle to the queue which are tried to be inserted at the next SUMO time step; */ void insertNewVehicle(); /** * tries to add all vehicles in the vehicle queue to SUMO; */ void insertVehicles(); // parameters int vehicleRngIndex; int numVehicles; // internal TraCIScenarioManager* manager; cRNG* mobRng; std::map<int, std::queue<std::string>> vehicleInsertQueue; std::set<std::string> queuedVehicles; std::vector<std::string> routeIds; uint32_t vehicleNameCounter; std::vector<std::string> vehicleTypeIds; }; } // namespace veins
2,768
32.361446
119
h
null
AICP-main/veins/src/veins/modules/mobility/traci/VehicleSignal.h
// // Copyright (C) 2018 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/base/utils/EnumBitset.h" namespace veins { enum class VehicleSignal : uint32_t { blinker_right, blinker_left, blinker_emergency, brakelight, frontlight, foglight, highbeam, backdrive, wiper, door_open_left, door_open_right, emergency_blue, emergency_red, emergency_yellow, undefined }; template <> struct VEINS_API EnumTraits<VehicleSignal> { static const VehicleSignal max = VehicleSignal::undefined; }; using VehicleSignalSet = EnumBitset<VehicleSignal>; } // namespace veins
1,500
25.333333
76
h
null
AICP-main/veins/src/veins/modules/obstacle/MobileHostObstacle.cc
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <set> #include <limits> #include "veins/modules/obstacle/MobileHostObstacle.h" #include "veins/base/modules/BaseMobility.h" #include "veins/base/utils/Heading.h" using veins::Coord; using veins::MobileHostObstacle; namespace { bool isPointInObstacle(Coord point, const MobileHostObstacle::Coords& shape) { bool isInside = false; auto i = shape.begin(); auto j = (shape.rbegin() + 1).base(); for (; i != shape.end(); j = i++) { bool inYRangeUp = (point.y >= i->y) && (point.y < j->y); bool inYRangeDown = (point.y >= j->y) && (point.y < i->y); bool inYRange = inYRangeUp || inYRangeDown; if (!inYRange) continue; bool intersects = point.x < (i->x + ((point.y - i->y) * (j->x - i->x) / (j->y - i->y))); if (!intersects) continue; isInside = !isInside; } return isInside; } double segmentsIntersectAt(Coord p1From, Coord p1To, Coord p2From, Coord p2To) { Coord p1Vec = p1To - p1From; Coord p2Vec = p2To - p2From; Coord p1p2 = p1From - p2From; double D = (p1Vec.x * p2Vec.y - p1Vec.y * p2Vec.x); double p1Frac = (p2Vec.x * p1p2.y - p2Vec.y * p1p2.x) / D; if (p1Frac < 0 || p1Frac > 1) return -1; double p2Frac = (p1Vec.x * p1p2.y - p1Vec.y * p1p2.x) / D; if (p2Frac < 0 || p2Frac > 1) return -1; return p1Frac; } } // namespace MobileHostObstacle::Coords MobileHostObstacle::getShape(simtime_t t) const { double l = getLength(); double o = getHostPositionOffset(); // this is the shift we have to undo in order to (given the OMNeT++ host position) get the car's front bumper position double w = getWidth() / 2; const BaseMobility* m = getMobility(); Coord p = m->getPositionAt(t); double a = Heading::fromCoord(m->getCurrentOrientation()).getRad(); Coords shape; shape.push_back(p + Coord(-(l - o), -w).rotatedYaw(-a)); shape.push_back(p + Coord(+o, -w).rotatedYaw(-a)); shape.push_back(p + Coord(+o, +w).rotatedYaw(-a)); shape.push_back(p + Coord(-(l - o), +w).rotatedYaw(-a)); return shape; } bool MobileHostObstacle::maybeInBounds(double x1, double y1, double x2, double y2, simtime_t t) const { double l = getLength(); double o = getHostPositionOffset(); // this is the shift we have to undo in order to (given the OMNeT++ host position) get the car's front bumper position double w = getWidth() / 2; const BaseMobility* m = getMobility(); Coord p = m->getPositionAt(t); double lw = std::max(l, w); double xx1 = p.x - std::abs(o) - lw; double xx2 = p.x + std::abs(o) + lw; double yy1 = p.y - std::abs(o) - lw; double yy2 = p.y + std::abs(o) + lw; if (xx2 < x1) return false; if (xx1 > x2) return false; if (yy2 < y1) return false; if (yy1 > y2) return false; return true; } double MobileHostObstacle::getIntersectionPoint(const Coord& senderPos, const Coord& receiverPos, simtime_t t) const { const double not_a_number = std::numeric_limits<double>::quiet_NaN(); MobileHostObstacle::Coords shape = getShape(t); // shortcut if sender is inside bool senderInside = isPointInObstacle(senderPos, shape); if (senderInside) return 0; // get a list of points (in [0, 1]) along the line between sender and receiver where the beam intersects with this obstacle std::multiset<double> intersectAt; bool doesIntersect = false; MobileHostObstacle::Coords::const_iterator i = shape.begin(); MobileHostObstacle::Coords::const_iterator j = (shape.rbegin() + 1).base(); for (; i != shape.end(); j = i++) { Coord c1 = *i; Coord c2 = *j; double inter = segmentsIntersectAt(senderPos, receiverPos, c1, c2); if (inter != -1) { doesIntersect = true; EV << "intersect: " << inter << endl; intersectAt.insert(inter); } } // shortcut if no intersections if (!doesIntersect) { bool receiverInside = isPointInObstacle(receiverPos, shape); if (receiverInside) return senderPos.distance(receiverPos); return not_a_number; } return (*intersectAt.begin() * senderPos.distance(receiverPos)); }
5,088
33.619048
158
cc
null
AICP-main/veins/src/veins/modules/obstacle/MobileHostObstacle.h
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <vector> #include "veins/base/utils/Coord.h" #include "veins/base/utils/AntennaPosition.h" namespace veins { class BaseMobility; /** * Obstacle for radio waves derived from a mobile host's body. * * Primarily used for VehicleObstacleShadowing. */ class VEINS_API MobileHostObstacle { public: using Coords = std::vector<Coord>; MobileHostObstacle(std::vector<AntennaPosition> initialAntennaPositions, BaseMobility* mobility, double length, double hostPositionOffset, double width, double height) : initialAntennaPositions(std::move(initialAntennaPositions)) , mobility(mobility) , length(length) , hostPositionOffset(hostPositionOffset) , width(width) , height(height) { } void setMobility(BaseMobility* mobility) { this->mobility = mobility; } void setLength(double d) { this->length = d; } void setHostPositionOffset(double d) { this->hostPositionOffset = d; } void setWidth(double d) { this->width = d; } void setHeight(double d) { this->height = d; } const std::vector<AntennaPosition>& getInitialAntennaPositions() const { return initialAntennaPositions; } const BaseMobility* getMobility() const { return mobility; } double getLength() const { return length; } double getHostPositionOffset() const { return hostPositionOffset; } double getWidth() const { return width; } double getHeight() const { return height; } Coords getShape(simtime_t t) const; bool maybeInBounds(double x1, double y1, double x2, double y2, simtime_t t) const; /** * return closest point (in meters) along (senderPos--receiverPos) where this obstacle overlaps, or NAN if it doesn't */ double getIntersectionPoint(const Coord& senderPos, const Coord& receiverPos, simtime_t t) const; protected: /** * Positions with identiers for all antennas connected to the host of this obstacle. * * Used to identify which host this obstacle belongs to. * Even works after the host has been destroyed (as AntennaPosition only stores the comonnent id). */ std::vector<AntennaPosition> initialAntennaPositions; BaseMobility* mobility; double length; double hostPositionOffset; double width; double height; }; } // namespace veins
3,398
26.634146
171
h
null
AICP-main/veins/src/veins/modules/obstacle/Obstacle.cc
// // Copyright (C) 2010-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <algorithm> #include "veins/modules/obstacle/Obstacle.h" using namespace veins; using veins::Obstacle; Obstacle::Obstacle(std::string id, std::string type, double attenuationPerCut, double attenuationPerMeter) : visualRepresentation(nullptr) , id(id) , type(type) , attenuationPerCut(attenuationPerCut) , attenuationPerMeter(attenuationPerMeter) { } void Obstacle::setShape(Coords shape) { coords = shape; bboxP1 = Coord(1e7, 1e7); bboxP2 = Coord(-1e7, -1e7); for (Coords::const_iterator i = coords.begin(); i != coords.end(); ++i) { bboxP1.x = std::min(i->x, bboxP1.x); bboxP1.y = std::min(i->y, bboxP1.y); bboxP2.x = std::max(i->x, bboxP2.x); bboxP2.y = std::max(i->y, bboxP2.y); } } const Obstacle::Coords& Obstacle::getShape() const { return coords; } const Coord Obstacle::getBboxP1() const { return bboxP1; } const Coord Obstacle::getBboxP2() const { return bboxP2; } bool Obstacle::containsPoint(Coord point) const { bool isInside = false; const Obstacle::Coords& shape = getShape(); Obstacle::Coords::const_iterator i = shape.begin(); Obstacle::Coords::const_iterator j = (shape.rbegin() + 1).base(); for (; i != shape.end(); j = i++) { bool inYRangeUp = (point.y >= i->y) && (point.y < j->y); bool inYRangeDown = (point.y >= j->y) && (point.y < i->y); bool inYRange = inYRangeUp || inYRangeDown; if (!inYRange) continue; bool intersects = point.x < (i->x + ((point.y - i->y) * (j->x - i->x) / (j->y - i->y))); if (!intersects) continue; isInside = !isInside; } return isInside; } namespace { double segmentsIntersectAt(const Coord& p1From, const Coord& p1To, const Coord& p2From, const Coord& p2To) { double p1x = p1To.x - p1From.x; double p1y = p1To.y - p1From.y; double p2x = p2To.x - p2From.x; double p2y = p2To.y - p2From.y; double p1p2x = p1From.x - p2From.x; double p1p2y = p1From.y - p2From.y; double D = (p1x * p2y - p1y * p2x); double p1Frac = (p2x * p1p2y - p2y * p1p2x) / D; if (p1Frac < 0 || p1Frac > 1) return -1; double p2Frac = (p1x * p1p2y - p1y * p1p2x) / D; if (p2Frac < 0 || p2Frac > 1) return -1; return p1Frac; } } // namespace std::vector<double> Obstacle::getIntersections(const Coord& senderPos, const Coord& receiverPos) const { std::vector<double> intersectAt; const Obstacle::Coords& shape = getShape(); Obstacle::Coords::const_iterator i = shape.begin(); Obstacle::Coords::const_iterator j = (shape.rbegin() + 1).base(); for (; i != shape.end(); j = i++) { const Coord& c1 = *i; const Coord& c2 = *j; double i = segmentsIntersectAt(senderPos, receiverPos, c1, c2); if (i != -1) { intersectAt.push_back(i); } } std::sort(intersectAt.begin(), intersectAt.end()); return intersectAt; } std::string Obstacle::getType() const { return type; } std::string Obstacle::getId() const { return id; } double Obstacle::getAttenuationPerCut() const { return attenuationPerCut; } double Obstacle::getAttenuationPerMeter() const { return attenuationPerMeter; }
4,132
27.308219
106
cc
null
AICP-main/veins/src/veins/modules/obstacle/Obstacle.h
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <vector> #include "veins/veins.h" #include "veins/base/utils/Coord.h" #include "veins/modules/world/annotations/AnnotationManager.h" namespace veins { /** * stores information about an Obstacle for ObstacleControl */ class VEINS_API Obstacle { public: using Coords = std::vector<Coord>; Obstacle(std::string id, std::string type, double attenuationPerCut, double attenuationPerMeter); void setShape(Coords shape); const Coords& getShape() const; const Coord getBboxP1() const; const Coord getBboxP2() const; bool containsPoint(Coord Point) const; std::string getType() const; std::string getId() const; double getAttenuationPerCut() const; double getAttenuationPerMeter() const; /** * get a list of points (in [0, 1]) along the line between sender and receiver where the beam intersects with this obstacle */ std::vector<double> getIntersections(const Coord& senderPos, const Coord& receiverPos) const; AnnotationManager::Annotation* visualRepresentation; protected: std::string id; std::string type; double attenuationPerCut; /**< in dB. attenuation per exterior border of obstacle */ double attenuationPerMeter; /**< in dB / m. to account for attenuation caused by interior of obstacle */ Coords coords; Coord bboxP1; Coord bboxP2; }; } // namespace veins
2,293
30.861111
127
h
null
AICP-main/veins/src/veins/modules/obstacle/ObstacleControl.cc
// // Copyright (C) 2010-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <sstream> #include <map> #include <set> #include "veins/modules/obstacle/ObstacleControl.h" #include "veins/base/modules/BaseWorldUtility.h" using veins::ObstacleControl; Define_Module(veins::ObstacleControl); namespace { veins::BBoxLookup rebuildBBoxLookup(const std::vector<std::unique_ptr<veins::Obstacle>>& obstacleOwner, int gridCellSize = 250) { std::vector<veins::Obstacle*> obstaclePointers; obstaclePointers.reserve(obstacleOwner.size()); std::transform(obstacleOwner.begin(), obstacleOwner.end(), std::back_inserter(obstaclePointers), [](const std::unique_ptr<veins::Obstacle>& obstacle) { return obstacle.get(); }); auto playgroundSize = veins::FindModule<veins::BaseWorldUtility*>::findGlobalModule()->getPgs(); auto bboxFunction = [](veins::Obstacle* o) { return veins::BBoxLookup::Box{{o->getBboxP1().x, o->getBboxP1().y}, {o->getBboxP2().x, o->getBboxP2().y}}; }; return veins::BBoxLookup(obstaclePointers, bboxFunction, playgroundSize->x, playgroundSize->y, gridCellSize); } } // anonymous namespace ObstacleControl::~ObstacleControl() { } void ObstacleControl::initialize(int stage) { if (stage == 1) { obstacleOwner.clear(); cacheEntries.clear(); isBboxLookupDirty = true; annotations = AnnotationManagerAccess().getIfExists(); if (annotations) annotationGroup = annotations->createGroup("obstacles"); obstaclesXml = par("obstacles"); gridCellSize = par("gridCellSize"); if (gridCellSize < 1) { throw cRuntimeError("gridCellSize was %d, but must be a positive integer number", gridCellSize); } addFromXml(obstaclesXml); } } void ObstacleControl::finish() { obstacleOwner.clear(); } void ObstacleControl::handleMessage(cMessage* msg) { if (msg->isSelfMessage()) { handleSelfMsg(msg); return; } throw cRuntimeError("ObstacleControl doesn't handle messages from other modules"); } void ObstacleControl::handleSelfMsg(cMessage* msg) { throw cRuntimeError("ObstacleControl doesn't handle self-messages"); } void ObstacleControl::addFromXml(cXMLElement* xml) { std::string rootTag = xml->getTagName(); if (rootTag != "obstacles") { throw cRuntimeError("Obstacle definition root tag was \"%s\", but expected \"obstacles\"", rootTag.c_str()); } cXMLElementList list = xml->getChildren(); for (cXMLElementList::const_iterator i = list.begin(); i != list.end(); ++i) { cXMLElement* e = *i; std::string tag = e->getTagName(); if (tag == "type") { // <type id="building" db-per-cut="9" db-per-meter="0.4" /> ASSERT(e->getAttribute("id")); std::string id = e->getAttribute("id"); ASSERT(e->getAttribute("db-per-cut")); std::string perCutParS = e->getAttribute("db-per-cut"); double perCutPar = strtod(perCutParS.c_str(), nullptr); ASSERT(e->getAttribute("db-per-meter")); std::string perMeterParS = e->getAttribute("db-per-meter"); double perMeterPar = strtod(perMeterParS.c_str(), nullptr); perCut[id] = perCutPar; perMeter[id] = perMeterPar; } else if (tag == "poly") { // <poly id="building#0" type="building" color="#F00" shape="16,0 8,13.8564 -8,13.8564 -16,0 -8,-13.8564 8,-13.8564" /> ASSERT(e->getAttribute("id")); std::string id = e->getAttribute("id"); ASSERT(e->getAttribute("type")); std::string type = e->getAttribute("type"); ASSERT(e->getAttribute("color")); std::string color = e->getAttribute("color"); ASSERT(e->getAttribute("shape")); std::string shape = e->getAttribute("shape"); Obstacle obs(id, type, getAttenuationPerCut(type), getAttenuationPerMeter(type)); std::vector<Coord> sh; cStringTokenizer st(shape.c_str()); while (st.hasMoreTokens()) { std::string xy = st.nextToken(); std::vector<double> xya = cStringTokenizer(xy.c_str(), ",").asDoubleVector(); ASSERT(xya.size() == 2); sh.push_back(Coord(xya[0], xya[1])); } obs.setShape(sh); add(obs); } else { throw cRuntimeError("Found unknown tag in obstacle definition: \"%s\"", tag.c_str()); } } } void ObstacleControl::addFromTypeAndShape(std::string id, std::string typeId, std::vector<Coord> shape) { if (!isTypeSupported(typeId)) { throw cRuntimeError("Unsupported obstacle type: \"%s\"", typeId.c_str()); } Obstacle obs(id, typeId, getAttenuationPerCut(typeId), getAttenuationPerMeter(typeId)); obs.setShape(shape); add(obs); } void ObstacleControl::add(Obstacle obstacle) { Obstacle* o = new Obstacle(obstacle); obstacleOwner.emplace_back(o); // visualize using AnnotationManager if (annotations) o->visualRepresentation = annotations->drawPolygon(o->getShape(), "red", annotationGroup); cacheEntries.clear(); isBboxLookupDirty = true; } void ObstacleControl::erase(const Obstacle* obstacle) { if (annotations && obstacle->visualRepresentation) annotations->erase(obstacle->visualRepresentation); for (auto itOwner = obstacleOwner.begin(); itOwner != obstacleOwner.end(); ++itOwner) { // find owning pointer and remove it to deallocate obstacle if (itOwner->get() == obstacle) { obstacleOwner.erase(itOwner); break; } } cacheEntries.clear(); isBboxLookupDirty = true; } std::vector<std::pair<veins::Obstacle*, std::vector<double>>> ObstacleControl::getIntersections(const Coord& senderPos, const Coord& receiverPos) const { std::vector<std::pair<Obstacle*, std::vector<double>>> allIntersections; // rebuild bounding box lookup structure if dirty (new obstacles added recently) if (isBboxLookupDirty) { bboxLookup = rebuildBBoxLookup(obstacleOwner); isBboxLookupDirty = false; } auto candidateObstacles = bboxLookup.findOverlapping({senderPos.x, senderPos.y}, {receiverPos.x, receiverPos.y}); // remove duplicates sort(candidateObstacles.begin(), candidateObstacles.end()); candidateObstacles.erase(unique(candidateObstacles.begin(), candidateObstacles.end()), candidateObstacles.end()); for (Obstacle* o : candidateObstacles) { // if obstacles has neither borders nor matter: bail. if (o->getShape().size() < 2) continue; auto foundIntersections = o->getIntersections(senderPos, receiverPos); if (!foundIntersections.empty() || o->containsPoint(senderPos) || o->containsPoint(receiverPos)) { allIntersections.emplace_back(o, foundIntersections); } } return allIntersections; } double ObstacleControl::calculateAttenuation(const Coord& senderPos, const Coord& receiverPos) const { Enter_Method_Silent(); if ((perCut.size() == 0) || (perMeter.size() == 0)) { throw cRuntimeError("Unable to use SimpleObstacleShadowing: No obstacle types have been configured"); } if (obstacleOwner.size() == 0) { throw cRuntimeError("Unable to use SimpleObstacleShadowing: No obstacles have been added"); } // return cached result, if available CacheKey cacheKey(senderPos, receiverPos); CacheEntries::const_iterator cacheEntryIter = cacheEntries.find(cacheKey); if (cacheEntryIter != cacheEntries.end()) { return cacheEntryIter->second; } // get intersections auto intersections = getIntersections(senderPos, receiverPos); double factor = 1; for (auto i = intersections.begin(); i != intersections.end(); ++i) { auto o = i->first; auto intersectAt = i->second; // if beam interacts with neither borders nor matter: bail. bool senderInside = o->containsPoint(senderPos); bool receiverInside = o->containsPoint(receiverPos); if ((intersectAt.size() == 0) && !senderInside && !receiverInside) continue; // remember number of cuts before messing with intersection points double numCuts = intersectAt.size(); // for distance calculation, make sure every other pair of points marks transition through matter and void, respectively. if (senderInside) intersectAt.insert(intersectAt.begin(), 0); if (receiverInside) intersectAt.push_back(1); ASSERT((intersectAt.size() % 2) == 0); // sum up distances in matter. double fractionInObstacle = 0; for (auto i = intersectAt.begin(); i != intersectAt.end();) { double p1 = *(i++); double p2 = *(i++); fractionInObstacle += (p2 - p1); } // calculate attenuation double totalDistance = senderPos.distance(receiverPos); double attenuation = (o->getAttenuationPerCut() * numCuts) + (o->getAttenuationPerMeter() * fractionInObstacle * totalDistance); factor *= pow(10.0, -attenuation / 10.0); // bail if attenuation is already extremely high if (factor < 1e-30) break; } // cache result if (cacheEntries.size() >= 1000) cacheEntries.clear(); cacheEntries[cacheKey] = factor; return factor; } double ObstacleControl::getAttenuationPerCut(std::string type) { if (perCut.find(type) != perCut.end()) return perCut[type]; else { throw cRuntimeError("Obstacle type %s unknown", type.c_str()); return -1; } } double ObstacleControl::getAttenuationPerMeter(std::string type) { if (perMeter.find(type) != perMeter.end()) return perMeter[type]; else { throw cRuntimeError("Obstacle type %s unknown", type.c_str()); return -1; } } bool ObstacleControl::isTypeSupported(std::string type) { // the type of obstacle is supported if there are attenuation values for borders and interior return (perCut.find(type) != perCut.end()) && (perMeter.find(type) != perMeter.end()); }
11,005
35.564784
182
cc
null
AICP-main/veins/src/veins/modules/obstacle/ObstacleControl.h
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <memory> #include "veins/veins.h" #include "veins/base/utils/Coord.h" #include "veins/modules/obstacle/Obstacle.h" #include "veins/modules/world/annotations/AnnotationManager.h" #include "veins/modules/utility/BBoxLookup.h" namespace veins { /** * ObstacleControl models obstacles that block radio transmissions. * * Each Obstacle is a polygon. * Transmissions that cross one of the polygon's lines will have * their receive power set to zero. */ class VEINS_API ObstacleControl : public cSimpleModule { public: ~ObstacleControl() override; void initialize(int stage) override; int numInitStages() const override { return 2; } void finish() override; void handleMessage(cMessage* msg) override; void handleSelfMsg(cMessage* msg); void addFromXml(cXMLElement* xml); void addFromTypeAndShape(std::string id, std::string typeId, std::vector<Coord> shape); void add(Obstacle obstacle); void erase(const Obstacle* obstacle); bool isTypeSupported(std::string type); double getAttenuationPerCut(std::string type); double getAttenuationPerMeter(std::string type); /** * get hit obstacles (along with a list of points (in [0, 1]) along the line between sender and receiver where the beam intersects with the respective obstacle) as well as any obstacle that contains the sender or receiver (with a list of potentially 0 points) */ std::vector<std::pair<Obstacle*, std::vector<double>>> getIntersections(const Coord& senderPos, const Coord& receiverPos) const; /** * calculate additional attenuation by obstacles, return multiplicative factor */ double calculateAttenuation(const Coord& senderPos, const Coord& receiverPos) const; protected: struct CacheKey { const Coord senderPos; const Coord receiverPos; CacheKey(const Coord& senderPos, const Coord& receiverPos) : senderPos(senderPos) , receiverPos(receiverPos) { } bool operator<(const CacheKey& o) const { if (senderPos.x < o.senderPos.x) return true; if (senderPos.x > o.senderPos.x) return false; if (senderPos.y < o.senderPos.y) return true; if (senderPos.y > o.senderPos.y) return false; if (receiverPos.x < o.receiverPos.x) return true; if (receiverPos.x > o.receiverPos.x) return false; if (receiverPos.y < o.receiverPos.y) return true; if (receiverPos.y > o.receiverPos.y) return false; return false; } }; typedef std::map<CacheKey, double> CacheEntries; cXMLElement* obstaclesXml; /**< obstacles to add at startup */ int gridCellSize = 250; /**< size of square grid tiles for obstacle store */ std::vector<std::unique_ptr<Obstacle>> obstacleOwner; AnnotationManager* annotations; AnnotationManager::Group* annotationGroup; std::map<std::string, double> perCut; std::map<std::string, double> perMeter; mutable CacheEntries cacheEntries; mutable BBoxLookup bboxLookup; mutable bool isBboxLookupDirty = true; }; class VEINS_API ObstacleControlAccess { public: ObstacleControlAccess() { } ObstacleControl* getIfExists() { return dynamic_cast<ObstacleControl*>(getSimulation()->getModuleByPath("obstacles")); } }; } // namespace veins
4,319
33.285714
263
h
null
AICP-main/veins/src/veins/modules/obstacle/VehicleObstacleControl.cc
// // Copyright (C) 2010-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <sstream> #include <map> #include <set> #include <limits> #include <cmath> #include "veins/modules/obstacle/VehicleObstacleControl.h" #include "veins/base/modules/BaseMobility.h" #include "veins/base/connectionManager/ChannelAccess.h" #include "veins/base/toolbox/Signal.h" using veins::MobileHostObstacle; using veins::Signal; using veins::VehicleObstacleControl; Define_Module(veins::VehicleObstacleControl); VehicleObstacleControl::~VehicleObstacleControl() = default; void VehicleObstacleControl::initialize(int stage) { if (stage == 1) { annotations = AnnotationManagerAccess().getIfExists(); if (annotations) { vehicleAnnotationGroup = annotations->createGroup("vehicleObstacles"); } } } void VehicleObstacleControl::finish() { } void VehicleObstacleControl::handleMessage(cMessage* msg) { if (msg->isSelfMessage()) { handleSelfMsg(msg); return; } throw cRuntimeError("VehicleObstacleControl doesn't handle messages from other modules"); } void VehicleObstacleControl::handleSelfMsg(cMessage* msg) { throw cRuntimeError("VehicleObstacleControl doesn't handle self-messages"); } const MobileHostObstacle* VehicleObstacleControl::add(MobileHostObstacle obstacle) { auto* o = new MobileHostObstacle(obstacle); vehicleObstacles.push_back(o); return o; } void VehicleObstacleControl::erase(const MobileHostObstacle* obstacle) { bool erasedOne = false; for (auto k = vehicleObstacles.begin(); k != vehicleObstacles.end();) { MobileHostObstacle* o = *k; if (o == obstacle) { erasedOne = true; k = vehicleObstacles.erase(k); } else { ++k; } } ASSERT(erasedOne); delete obstacle; } Signal VehicleObstacleControl::getVehicleAttenuationSingle(double h1, double h2, double h, double d, double d1, Signal attenuationPrototype) { Signal attenuation = Signal(attenuationPrototype.getSpectrum()); for (uint16_t i = 0; i < attenuation.getNumValues(); i++) { double freq = attenuation.getSpectrum().freqAt(i); double lambda = BaseWorldUtility::speedOfLight() / freq; double d2 = d - d1; double y = (h2 - h1) / d * d1 + h1; double H = h - y; double r1 = sqrt(lambda * d1 * d2 / d); double V0 = sqrt(2) * H / r1; if (V0 <= -0.7) { attenuation.at(i) = 0; } else { attenuation.at(i) = 6.9 + 20 * log10(sqrt(pow((V0 - 0.1), 2) + 1) + V0 - 0.1); } } return attenuation; } Signal VehicleObstacleControl::getVehicleAttenuationDZ(const std::vector<std::pair<double, double>>& dz_vec, Signal attenuationPrototype) { // basic sanity check ASSERT(dz_vec.size() >= 2); // make sure the list of x coordinates is sorted for (size_t i = 0; i < dz_vec.size() - 1; i++) { ASSERT(dz_vec[i].first < dz_vec[i + 1].first); } // find "major obstacles" (MOs) between sender and receiver via rope-stretching algorithm /* * | * | | * | : | * | | : : | | * mo0 mo1 mo2 mo3 * snd rcv */ std::vector<size_t> mo; ///< indices of MOs (this includes the sender and receiver) mo.push_back(0); for (size_t i = 0;;) { double max_slope = -std::numeric_limits<double>::infinity(); size_t max_slope_index; bool have_max_slope_index = false; for (size_t j = i + 1; j < dz_vec.size(); ++j) { double slope = (dz_vec[j].second - dz_vec[i].second) / (dz_vec[j].first - dz_vec[i].first); if (slope > max_slope) { max_slope = slope; max_slope_index = j; have_max_slope_index = true; } } // Sanity check ASSERT(have_max_slope_index); if (max_slope_index >= dz_vec.size() - 1) break; mo.push_back(max_slope_index); i = max_slope_index; } mo.push_back(dz_vec.size() - 1); // calculate attenuation due to MOs Signal attenuation_mo(attenuationPrototype.getSpectrum()); for (size_t mm = 0; mm < mo.size() - 2; ++mm) { size_t tx = mo[mm]; size_t ob = mo[mm + 1]; size_t rx = mo[mm + 2]; double h1 = dz_vec[tx].second; double h2 = dz_vec[rx].second; double d = dz_vec[rx].first - dz_vec[tx].first; double d1 = dz_vec[ob].first - dz_vec[tx].first; double h = dz_vec[ob].second; Signal ad_mo = getVehicleAttenuationSingle(h1, h2, h, d, d1, attenuationPrototype); attenuation_mo += ad_mo; } // calculate attenuation due to "small obstacles" (i.e. the ones in-between MOs) Signal attenuation_so(attenuationPrototype.getSpectrum()); for (size_t i = 0; i < mo.size() - 1; ++i) { size_t delta = mo[i + 1] - mo[i]; if (delta == 1) { // no obstacle in-between these two MOs } else if (delta == 2) { // one obstacle in-between these two MOs size_t tx = mo[i]; size_t ob = mo[i] + 1; size_t rx = mo[i + 1]; double h1 = dz_vec[tx].second; double h2 = dz_vec[rx].second; double d = dz_vec[rx].first - dz_vec[tx].first; double d1 = dz_vec[ob].first - dz_vec[tx].first; double h = dz_vec[ob].second; Signal ad_mo = getVehicleAttenuationSingle(h1, h2, h, d, d1, attenuationPrototype); attenuation_so += ad_mo; } else { // multiple obstacles in-between these two MOs -- use the one closest to their line of sight double x1 = dz_vec[mo[i]].first; double y1 = dz_vec[mo[i]].second; double x2 = dz_vec[mo[i + 1]].first; double y2 = dz_vec[mo[i + 1]].second; double min_delta_h = std::numeric_limits<float>::infinity(); size_t min_delta_h_index; bool have_min_delta_h_index = false; for (size_t j = mo[i] + 1; j < mo[i + 1]; ++j) { double h = (y2 - y1) / (x2 - x1) * (dz_vec[j].first - x1) + y1; double delta_h = h - dz_vec[j].second; if (delta_h < min_delta_h) { min_delta_h = delta_h; min_delta_h_index = j; have_min_delta_h_index = true; } } // Sanity check ASSERT(have_min_delta_h_index); size_t tx = mo[i]; size_t ob = min_delta_h_index; size_t rx = mo[i + 1]; double h1 = dz_vec[tx].second; double h2 = dz_vec[rx].second; double d = dz_vec[rx].first - dz_vec[tx].first; double d1 = dz_vec[ob].first - dz_vec[tx].first; double h = dz_vec[ob].second; Signal ad_mo = getVehicleAttenuationSingle(h1, h2, h, d, d1, attenuationPrototype); attenuation_so += ad_mo; } } double c; { double prodS = 1; double sumS = 0; double prodSsum = 1; double firstS = 0; double lastS = 0; double s_old = 0; for (size_t jj = 0; jj < mo.size() - 1; ++jj) { double s = dz_vec[mo[jj + 1]].first - dz_vec[mo[jj]].first; ///< distance between two MOs prodS *= s; sumS += s; if (jj == 0) firstS = s; else if (jj > 0) prodSsum *= (s + s_old); if (jj == mo.size() - 2) lastS = s; s_old = s; } c = -10 * log10((prodS * sumS) / (prodSsum * firstS * lastS)); } return attenuation_mo + attenuation_so + c; } std::vector<std::pair<double, double>> VehicleObstacleControl::getPotentialObstacles(const AntennaPosition& senderPos_, const AntennaPosition& receiverPos_, const Signal& s) const { Enter_Method_Silent(); auto senderPos = senderPos_.getPositionAt(); auto receiverPos = receiverPos_.getPositionAt(); double senderHeight = senderPos.z; double receiverHeight = receiverPos.z; ASSERT(senderHeight > 0); ASSERT(receiverHeight > 0); std::vector<std::pair<double, double>> potentialObstacles; /**< linear position of each obstructing vehicle along (senderPos--receiverPos) */ simtime_t sStart = s.getSendingStart(); EV << "searching candidates for transmission from " << senderPos.info() << " -> " << receiverPos.info() << " (" << senderPos.distance(receiverPos) << "meters total)" << std::endl; if (hasGUI() && annotations) { annotations->eraseAll(vehicleAnnotationGroup); drawVehicleObstacles(sStart); annotations->drawLine(senderPos, receiverPos, "blue", vehicleAnnotationGroup); } double x1 = std::min(senderPos.x, receiverPos.x); double x2 = std::max(senderPos.x, receiverPos.x); double y1 = std::min(senderPos.y, receiverPos.y); double y2 = std::max(senderPos.y, receiverPos.y); for (auto o : vehicleObstacles) { auto obstacleAntennaPositions = o->getInitialAntennaPositions(); double l = o->getLength(); double w = o->getWidth(); double h = o->getHeight(); auto hp_approx = o->getMobility()->getPositionAt(simTime()); EV << "checking vehicle in proximity of " << hp_approx.info() << " with height: " << h << " width: " << w << " length: " << l << endl; if (!o->maybeInBounds(x1, y1, x2, y2, sStart)) { EV_TRACE << "bounding boxes don't overlap: ignore" << std::endl; continue; } // check if this is either the sender or the receiver bool ignoreMe = false; for (auto obstacleAntenna : obstacleAntennaPositions) { if (obstacleAntenna.isSameAntenna(senderPos_)) { EV_TRACE << "...this is the sender: ignore" << std::endl; ignoreMe = true; } if (obstacleAntenna.isSameAntenna(receiverPos_)) { EV_TRACE << "...this is the receiver: ignore" << std::endl; ignoreMe = true; } } if (ignoreMe) continue; // this is a potential obstacle double p1d = o->getIntersectionPoint(senderPos, receiverPos, sStart); double maxd = senderPos.distance(receiverPos); if (!std::isnan(p1d) && p1d > 0 && p1d < maxd) { auto it = potentialObstacles.begin(); while (true) { if (it == potentialObstacles.end()) { potentialObstacles.emplace_back(p1d, h); break; } if (it->first == p1d) { // omit double entries EV << "two obstacles at same distance " << it->first << " == " << p1d << " height: " << it->second << " =? " << h << std::endl; break; } if (it->first > p1d) { potentialObstacles.insert(it, std::make_pair(p1d, h)); break; } ++it; } EV << "\tgot obstacle in 2d-LOS, " << p1d << " meters away from sender" << std::endl; Coord hitPos = senderPos + (receiverPos - senderPos) / senderPos.distance(receiverPos) * p1d; if (hasGUI() && annotations) { annotations->drawLine(senderPos, hitPos, "red", vehicleAnnotationGroup); } } } return potentialObstacles; } void VehicleObstacleControl::drawVehicleObstacles(const simtime_t& t) const { for (auto o : vehicleObstacles) { annotations->drawPolygon(o->getShape(t), "black", vehicleAnnotationGroup); } }
12,651
33.010753
183
cc
null
AICP-main/veins/src/veins/modules/obstacle/VehicleObstacleControl.h
// // Copyright (C) 2006-2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <list> #include "veins/veins.h" #include "veins/base/utils/AntennaPosition.h" #include "veins/base/utils/Coord.h" #include "veins/modules/obstacle/Obstacle.h" #include "veins/modules/world/annotations/AnnotationManager.h" #include "veins/base/utils/Move.h" #include "veins/modules/obstacle/MobileHostObstacle.h" namespace veins { class Signal; /** * VehicleObstacleControl models moving obstacles that block radio transmissions. * * Each Obstacle is a polygon. * Transmissions that cross one of the polygon's lines will have * their receive power set to zero. */ class VEINS_API VehicleObstacleControl : public cSimpleModule { public: ~VehicleObstacleControl() override; void initialize(int stage) override; int numInitStages() const override { return 2; } void finish() override; void handleMessage(cMessage* msg) override; void handleSelfMsg(cMessage* msg); const MobileHostObstacle* add(MobileHostObstacle obstacle); void erase(const MobileHostObstacle* obstacle); /** * get distance and height of potential obstacles */ std::vector<std::pair<double, double>> getPotentialObstacles(const AntennaPosition& senderPos, const AntennaPosition& receiverPos, const Signal& s) const; /** * compute attenuation due to (single) vehicle. * Calculate impact of vehicles as obstacles according to: * M. Boban, T. T. V. Vinhoza, M. Ferreira, J. Barros, and O. K. Tonguz: 'Impact of Vehicles as Obstacles in Vehicular Ad Hoc Networks', IEEE JSAC, Vol. 29, No. 1, January 2011 * * @param h1: height of sender * @param h2: height of receiver * @param h: height of obstacle * @param d: distance between sender and receiver * @param d1: distance between sender and obstacle * @param attenuationPrototype: a prototype Signal for constructing a Signal containing the attenuation factors for each frequency */ static Signal getVehicleAttenuationSingle(double h1, double h2, double h, double d, double d1, Signal attenuationPrototype); /** * compute attenuation due to vehicles. * Calculate impact of vehicles as obstacles according to: * M. Boban, T. T. V. Vinhoza, M. Ferreira, J. Barros, and O. K. Tonguz: 'Impact of Vehicles as Obstacles in Vehicular Ad Hoc Networks', IEEE JSAC, Vol. 29, No. 1, January 2011 * * @param dz_vec: a vector of (distance, height) referring to potential obstacles along the line of sight, starting with the sender and ending with the receiver * @param attenuationPrototype: a prototype Signal for constructing a Signal containing the attenuation factors for each frequency */ static Signal getVehicleAttenuationDZ(const std::vector<std::pair<double, double>>& dz_vec, Signal attenuationPrototype); protected: AnnotationManager* annotations; using VehicleObstacles = std::list<MobileHostObstacle*>; VehicleObstacles vehicleObstacles; AnnotationManager::Group* vehicleAnnotationGroup; void drawVehicleObstacles(const simtime_t& t) const; }; class VEINS_API VehicleObstacleControlAccess { public: VehicleObstacleControlAccess() { } VehicleObstacleControl* getIfExists() { return dynamic_cast<VehicleObstacleControl*>(getSimulation()->getModuleByPath("vehicleObstacles")); } }; } // namespace veins
4,279
36.876106
180
h
null
AICP-main/veins/src/veins/modules/phy/Decider80211p.cc
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // Copyright (C) 2012 Bastian Bloessl, Stefan Joerer, Michele Segata <{bloessl,joerer,segata}@ccs-labs.org> // Copyright (C) 2018 Fabian Bronner <fabian.bronner@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /* * Based on Decider80211.cc from Karl Wessel * and modifications by Christopher Saloman */ #include "veins/modules/phy/Decider80211p.h" #include "veins/modules/phy/DeciderResult80211.h" #include "veins/modules/messages/Mac80211Pkt_m.h" #include "veins/base/toolbox/Signal.h" #include "veins/modules/messages/AirFrame11p_m.h" #include "veins/modules/phy/NistErrorRate.h" #include "veins/modules/utility/ConstsPhy.h" #include "veins/base/toolbox/SignalUtils.h" using namespace veins; simtime_t Decider80211p::processNewSignal(AirFrame* msg) { AirFrame11p* frame = check_and_cast<AirFrame11p*>(msg); // get the receiving power of the Signal at start-time and center frequency Signal& signal = frame->getSignal(); signalStates[frame] = EXPECT_END; if (signal.smallerAtCenterFrequency(minPowerLevel)) { // annotate the frame, so that we won't try decoding it at its end frame->setUnderMinPowerLevel(true); // check channel busy status. a superposition of low power frames might turn channel status to busy if (cca(simTime(), nullptr) == false) { setChannelIdleStatus(false); } return signal.getReceptionEnd(); } else { // This value might be just an intermediate result (due to short circuiting) double recvPower = signal.getAtCenterFrequency(); setChannelIdleStatus(false); if (phy11p->getRadioState() == Radio::TX) { frame->setBitError(true); frame->setWasTransmitting(true); EV_TRACE << "AirFrame: " << frame->getId() << " (" << recvPower << ") received, while already sending. Setting BitErrors to true" << std::endl; } else { if (!currentSignal.first) { // NIC is not yet synced to any frame, so lock and try to decode this frame currentSignal.first = frame; EV_TRACE << "AirFrame: " << frame->getId() << " with (" << recvPower << " > " << minPowerLevel << ") -> Trying to receive AirFrame." << std::endl; if (notifyRxStart) { phy->sendControlMsgToMac(new cMessage("RxStartStatus", MacToPhyInterface::PHY_RX_START)); } } else { // NIC is currently trying to decode another frame. this frame will be simply treated as interference EV_TRACE << "AirFrame: " << frame->getId() << " with (" << recvPower << " > " << minPowerLevel << ") -> Already synced to another AirFrame. Treating AirFrame as interference." << std::endl; } // channel turned busy // measure communication density myBusyTime += signal.getDuration().dbl(); } return signal.getReceptionEnd(); } } int Decider80211p::getSignalState(AirFrame* frame) { if (signalStates.find(frame) == signalStates.end()) { return NEW; } else { return signalStates[frame]; } } DeciderResult* Decider80211p::checkIfSignalOk(AirFrame* frame) { auto frame11p = check_and_cast<AirFrame11p*>(frame); Signal& s = frame->getSignal(); simtime_t start = s.getReceptionStart(); simtime_t end = s.getReceptionEnd(); // compute receive power double recvPower_dBm = 10 * log10(s.getAtCenterFrequency()); start = start + PHY_HDR_PREAMBLE_DURATION; // its ok if something in the training phase is broken AirFrameVector airFrames; getChannelInfo(start, end, airFrames); double noise = phy->getNoiseFloorValue(); // Make sure to use the adjusted starting-point (which ignores the preamble) double sinrMin = SignalUtils::getMinSINR(start, end, frame, airFrames, noise); double snrMin; if (collectCollisionStats) { // snrMin = SignalUtils::getMinSNR(start, end, frame, noise); snrMin = s.getDataMin() / noise; } else { // just set to any value. if collectCollisionStats != true // it will be ignored by packetOk snrMin = 1e200; } double payloadBitrate = getOfdmDatarate(static_cast<MCS>(frame11p->getMcs()), BANDWIDTH_11P); DeciderResult80211* result = nullptr; switch (packetOk(sinrMin, snrMin, frame->getBitLength(), payloadBitrate)) { case DECODED: EV_TRACE << "Packet is fine! We can decode it" << std::endl; result = new DeciderResult80211(true, payloadBitrate, sinrMin, recvPower_dBm, false); break; case NOT_DECODED: if (!collectCollisionStats) { EV_TRACE << "Packet has bit Errors. Lost " << std::endl; } else { EV_TRACE << "Packet has bit Errors due to low power. Lost " << std::endl; } result = new DeciderResult80211(false, payloadBitrate, sinrMin, recvPower_dBm, false); break; case COLLISION: EV_TRACE << "Packet has bit Errors due to collision. Lost " << std::endl; collisions++; result = new DeciderResult80211(false, payloadBitrate, sinrMin, recvPower_dBm, true); break; default: ASSERT2(false, "Impossible packet result returned by packetOk(). Check the code."); break; } return result; } enum Decider80211p::PACKET_OK_RESULT Decider80211p::packetOk(double sinrMin, double snrMin, int lengthMPDU, double bitrate) { double packetOkSinr; double packetOkSnr; // compute success rate depending on mcs and bw packetOkSinr = NistErrorRate::getChunkSuccessRate(bitrate, BANDWIDTH_11P, sinrMin, PHY_HDR_SERVICE_LENGTH + lengthMPDU + PHY_TAIL_LENGTH); // check if header is broken double headerNoError = NistErrorRate::getChunkSuccessRate(PHY_HDR_BITRATE, BANDWIDTH_11P, sinrMin, PHY_HDR_PLCPSIGNAL_LENGTH); double headerNoErrorSnr; // compute PER also for SNR only if (collectCollisionStats) { packetOkSnr = NistErrorRate::getChunkSuccessRate(bitrate, BANDWIDTH_11P, snrMin, PHY_HDR_SERVICE_LENGTH + lengthMPDU + PHY_TAIL_LENGTH); headerNoErrorSnr = NistErrorRate::getChunkSuccessRate(PHY_HDR_BITRATE, BANDWIDTH_11P, snrMin, PHY_HDR_PLCPSIGNAL_LENGTH); // the probability of correct reception without considering the interference // MUST be greater or equal than when consider it ASSERT(packetOkSnr >= packetOkSinr); ASSERT(headerNoErrorSnr >= headerNoError); } // probability of no bit error in the PLCP header double rand = RNGCONTEXT dblrand(); if (!collectCollisionStats) { if (rand > headerNoError) return NOT_DECODED; } else { if (rand > headerNoError) { // ups, we have a header error. is that due to interference? if (rand > headerNoErrorSnr) { // no. we would have not been able to receive that even // without interference return NOT_DECODED; } else { // yes. we would have decoded that without interference return COLLISION; } } } // probability of no bit error in the rest of the packet rand = RNGCONTEXT dblrand(); if (!collectCollisionStats) { if (rand > packetOkSinr) { return NOT_DECODED; } else { return DECODED; } } else { if (rand > packetOkSinr) { // ups, we have an error in the payload. is that due to interference? if (rand > packetOkSnr) { // no. we would have not been able to receive that even // without interference return NOT_DECODED; } else { // yes. we would have decoded that without interference return COLLISION; } } else { return DECODED; } } } bool Decider80211p::cca(simtime_t_cref time, AirFrame* exclude) { AirFrameVector airFrames; // collect all AirFrames that intersect with [start, end] getChannelInfo(time, time, airFrames); // In the reference implementation only centerFrequenvy - 5e6 (half bandwidth) is checked! // Although this is wrong, the same is done here to reproduce original results double minPower = phy->getNoiseFloorValue(); bool isChannelIdle = minPower < ccaThreshold; if (airFrames.size() > 0) { size_t usedFreqIndex = airFrames.front()->getSignal().getSpectrum().indexOf(centerFrequency - 5e6); isChannelIdle = SignalUtils::isChannelPowerBelowThreshold(time, airFrames, usedFreqIndex, ccaThreshold - minPower, exclude); } return isChannelIdle; } simtime_t Decider80211p::processSignalEnd(AirFrame* msg) { AirFrame11p* frame = check_and_cast<AirFrame11p*>(msg); // here the Signal is finally processed Signal& signal = frame->getSignal(); double recvPower_dBm = 10 * log10(signal.getMax()); bool whileSending = false; // remove this frame from our current signals signalStates.erase(frame); DeciderResult* result; if (frame->getUnderMinPowerLevel()) { // this frame was not even detected by the radio card result = new DeciderResult80211(false, 0, 0, recvPower_dBm); } else if (frame->getWasTransmitting() || phy11p->getRadioState() == Radio::TX) { // this frame was received while sending whileSending = true; result = new DeciderResult80211(false, 0, 0, recvPower_dBm); } else { // first check whether this is the frame NIC is currently synced on if (frame == currentSignal.first) { // check if the snr is above the Decider's specific threshold, // i.e. the Decider has received it correctly result = checkIfSignalOk(frame); // after having tried to decode the frame, the NIC is no more synced to the frame // and it is ready for syncing on a new one currentSignal.first = 0; } else { // if this is not the frame we are synced on, we cannot receive it result = new DeciderResult80211(false, 0, 0, recvPower_dBm); } } if (result->isSignalCorrect()) { EV_TRACE << "packet was received correctly, it is now handed to upper layer...\n"; // go on with processing this AirFrame, send it to the Mac-Layer if (notifyRxStart) { phy->sendControlMsgToMac(new cMessage("RxStartStatus", MacToPhyInterface::PHY_RX_END_WITH_SUCCESS)); } phy->sendUp(frame, result); } else { if (frame->getUnderMinPowerLevel()) { EV_TRACE << "packet was not detected by the card. power was under minPowerLevel threshold\n"; } else if (whileSending) { EV_TRACE << "packet was received while sending, sending it as control message to upper layer\n"; phy->sendControlMsgToMac(new cMessage("Error", RECWHILESEND)); } else { EV_TRACE << "packet was not received correctly, sending it as control message to upper layer\n"; if (notifyRxStart) { phy->sendControlMsgToMac(new cMessage("RxStartStatus", MacToPhyInterface::PHY_RX_END_WITH_FAILURE)); } if (((DeciderResult80211*) result)->isCollision()) { phy->sendControlMsgToMac(new cMessage("Error", Decider80211p::COLLISION)); } else { phy->sendControlMsgToMac(new cMessage("Error", BITERROR)); } } delete result; } if (phy11p->getRadioState() == Radio::TX) { EV_TRACE << "I'm currently sending\n"; } // check if channel is idle now // we declare channel busy if CCA tells us so, or if we are currently // decoding a frame else if (cca(simTime(), frame) == false || currentSignal.first != 0) { EV_TRACE << "Channel not yet idle!\n"; } else { // might have been idle before (when the packet rxpower was below sens) if (isChannelIdle != true) { EV_TRACE << "Channel idle now!\n"; setChannelIdleStatus(true); } } return notAgain; } void Decider80211p::setChannelIdleStatus(bool isIdle) { isChannelIdle = isIdle; if (isIdle) phy->sendControlMsgToMac(new cMessage("ChannelStatus", Mac80211pToPhy11pInterface::CHANNEL_IDLE)); else phy->sendControlMsgToMac(new cMessage("ChannelStatus", Mac80211pToPhy11pInterface::CHANNEL_BUSY)); } void Decider80211p::changeFrequency(double freq) { centerFrequency = freq; } double Decider80211p::getCCAThreshold() { return 10 * log10(ccaThreshold); } void Decider80211p::setCCAThreshold(double ccaThreshold_dBm) { ccaThreshold = pow(10, ccaThreshold_dBm / 10); } void Decider80211p::setNotifyRxStart(bool enable) { notifyRxStart = enable; } void Decider80211p::switchToTx() { if (currentSignal.first != 0) { // we are currently trying to receive a frame. if (allowTxDuringRx) { // if the above layer decides to transmit anyhow, we need to abort reception AirFrame11p* currentFrame = dynamic_cast<AirFrame11p*>(currentSignal.first); ASSERT(currentFrame); // flag the frame as "while transmitting" currentFrame->setWasTransmitting(true); currentFrame->setBitError(true); // forget about the signal currentSignal.first = 0; } else { throw cRuntimeError("Decider80211p: mac layer requested phy to transmit a frame while currently receiving another"); } } } void Decider80211p::finish() { simtime_t totalTime = simTime() - myStartTime; phy->recordScalar("busyTime", myBusyTime / totalTime.dbl()); if (collectCollisionStats) { phy->recordScalar("ncollisions", collisions); } } Decider80211p::~Decider80211p(){};
14,961
34.122066
205
cc
null
AICP-main/veins/src/veins/modules/phy/Decider80211p.h
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // Copyright (C) 2012 Bastian Bloessl, Stefan Joerer, Michele Segata <{bloessl,joerer,segata}@ccs-labs.org> // Copyright (C) 2018 Fabian Bronner <fabian.bronner@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/base/phyLayer/BaseDecider.h" #include "veins/modules/utility/Consts80211p.h" #include "veins/modules/mac/ieee80211p/Mac80211pToPhy11pInterface.h" #include "veins/modules/phy/Decider80211pToPhy80211pInterface.h" namespace veins { using veins::AirFrame; /** * @brief * Based on Decider80211.h from Karl Wessel * and modifications by Christopher Saloman * * @author David Eckhoff * * @ingroup decider * * @see DemoBaseApplLayer * @see Mac1609_4 * @see PhyLayer80211p * @see Decider80211p */ class VEINS_API Decider80211p : public BaseDecider { public: enum Decider80211ControlKinds { NOTHING = 22100, BITERROR, // the phy has recognized a bit error in the packet LAST_DECIDER_80211_CONTROL_KIND, RECWHILESEND }; /** * @brief tell the outcome of a packetOk() call, which might be * correctly decoded, discarded due to low SNR or discarder due * to low SINR (i.e. collision) */ enum PACKET_OK_RESULT { DECODED, NOT_DECODED, COLLISION }; protected: // threshold value for checking a SNR-map (SNR-threshold) double snrThreshold; /** @brief Power level threshold used to declare channel busy if * preamble portion is missed (802.11-2012 18.3.10.6 * CCA requirements). Notice that in 18.3.10.6, the mandatory CCA threshold * for a 10 MHz channel is -65 dBm. However, there is another threshold * called CCA-ED which requirements are defined in D.2.5. For a 10 MHz * channel, CCA-ED threshold shall be -75 dBm. CCA-ED is required for * certain operating classes that shall implement CCA-ED behavior. * According to Table E-4 however, 802.11p channels should not implement * it, so the correct threshold is -65 dBm. * When considering ETSI ITS G5 (ETSI TS 102 687) things change again. * Indeed, the DCC Sensitivity Control (DSC) part of the DCC algorithm * changes the CCA threshold depending on the state. Values are listed * in Table A.3: minimum value is -95 dBm, maximum value is -65 dBm, * and default value is -85 dBm. */ double ccaThreshold; /** @brief allows/disallows interruption of current reception for txing * * For a standard 802.11 MAC, starting a transmission while currently * receiving a frame is forbidden, as the channel is in a BUSY state. * For research purposes, however, one might use a custom MAC layer on * top of an 802.11p OFDM PHY, and decide to interrupt an ongoing * reception to start a transmission, whatever the reason. If the * following variable is set to false, simulation will be terminated * if this occurs. If not, simulation will continue, aborting current * reception. */ bool allowTxDuringRx; /** @brief The center frequency on which the decider listens for signals */ double centerFrequency; double myBusyTime; double myStartTime; std::string myPath; Decider80211pToPhy80211pInterface* phy11p; std::map<AirFrame*, int> signalStates; /** @brief enable/disable statistics collection for collisions * * For collecting statistics about collisions, we compute the Packet * Error Rate for both SNR and SINR values. This might increase the * simulation time, so if statistics about collisions are not needed, * this variable should be set to false */ bool collectCollisionStats; /** @brief count the number of collisions */ unsigned int collisions; /** @brief notify PHY-RXSTART.indication */ bool notifyRxStart; protected: /** * @brief Checks a mapping against a specific threshold (element-wise). * * @return true , if every entry of the mapping is above threshold * false , otherwise * * */ virtual DeciderResult* checkIfSignalOk(AirFrame* frame); simtime_t processNewSignal(AirFrame* frame) override; /** * @brief Processes a received AirFrame. * * The SNR-mapping for the Signal is created and checked against the Deciders * SNR-threshold. Depending on that the received AirFrame is either sent up * to the MAC-Layer or dropped. * * @return usually return a value for: 'do not pass it again' */ simtime_t processSignalEnd(AirFrame* frame) override; /** @brief computes if packet is ok or has errors*/ enum PACKET_OK_RESULT packetOk(double snirMin, double snrMin, int lengthMPDU, double bitrate); public: /** * @brief Initializes the Decider with a pointer to its PhyLayer and * specific values for threshold and minPowerLevel */ Decider80211p(cComponent* owner, DeciderToPhyInterface* phy, double minPowerLevel, double ccaThreshold, bool allowTxDuringRx, double centerFrequency, int myIndex = -1, bool collectCollisionStatistics = false) : BaseDecider(owner, phy, minPowerLevel, myIndex) , ccaThreshold(ccaThreshold) , allowTxDuringRx(allowTxDuringRx) , centerFrequency(centerFrequency) , myBusyTime(0) , myStartTime(simTime().dbl()) , collectCollisionStats(collectCollisionStatistics) , collisions(0) , notifyRxStart(false) { phy11p = dynamic_cast<Decider80211pToPhy80211pInterface*>(phy); ASSERT(phy11p); } void setPath(std::string myPath) { this->myPath = myPath; } bool cca(simtime_t_cref, AirFrame*); int getSignalState(AirFrame* frame) override; ~Decider80211p() override; void changeFrequency(double freq); /** * @brief returns the CCA threshold in dBm */ double getCCAThreshold(); /** * @brief sets the CCA threshold */ void setCCAThreshold(double ccaThreshold_dBm); void setChannelIdleStatus(bool isIdle) override; /** * @brief invoke this method when the phy layer is also finalized, * so that statistics recorded by the decider can be written to * the output file */ void finish() override; /** * @brief Notifies the decider that phy layer is starting a transmission. * * This helps the decider interrupting a current reception. In a standard * 802.11 MAC, this should never happen, but in other MAC layers you might * decide to interrupt an ongoing reception and start transmitting. Thank * to this method, the decider can flag the ongoing frame as non received * because of the transmission. */ void switchToTx() override; /** * @brief notify PHY-RXSTART.indication */ void setNotifyRxStart(bool enable); }; } // namespace veins
7,753
33.7713
212
h
null
AICP-main/veins/src/veins/modules/phy/Decider80211pToPhy80211pInterface.h
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once namespace veins { /** * @brief * Interface of PhyLayer80211p exposed to Decider80211p. * * @author David Eckhoff * * @ingroup phyLayer */ class VEINS_API Decider80211pToPhy80211pInterface { public: virtual ~Decider80211pToPhy80211pInterface(){}; virtual int getRadioState() = 0; }; } // namespace veins
1,229
28.285714
76
h
null
AICP-main/veins/src/veins/modules/phy/DeciderResult80211.h
// // Copyright (C) 2007 Technische Universitaet Berlin (TUB), Germany, Telecommunication Networks Group // Copyright (C) 2007 Technische Universiteit Delft (TUD), Netherlands // Copyright (C) 2007 Universitaet Paderborn (UPB), Germany // Copyright (C) 2014 Michele Segata <segata@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /* * DeciderResult80211.h * * Created on: 04.02.2009 * Author: karl * * Modified by Michele Segata (segata@ccs-labs.org) */ #pragma once #include "veins/veins.h" #include "veins/base/phyLayer/Decider.h" namespace veins { /** * @brief Defines an extended DeciderResult for the 80211 protocol * which stores the bit-rate of the transmission. * * @ingroup decider * @ingroup ieee80211 */ class VEINS_API DeciderResult80211 : public DeciderResult { protected: /** @brief Stores the bit-rate of the transmission of the packet */ double bitrate; /** @brief Stores the signal to noise ratio of the transmission */ double snr; /** @brief Stores the received power in dBm * Please note that this is NOT the RSSI. The RSSI is an indicator * of the quality of the signal which is not standardized, and * different vendors can define different indicators. This value * indicates the power that the frame had when received by the * NIC card, WITHOUT noise floor and WITHOUT interference */ double recvPower_dBm; /** @brief Stores whether the uncorrect decoding was due to low power or collision */ bool collision; public: /** * @brief Initialises with the passed values. * * "bitrate" defines the bit-rate of the transmission of the packet. */ DeciderResult80211(bool isCorrect, double bitrate, double snr, double recvPower_dBm = 0, bool collision = false) : DeciderResult(isCorrect) , bitrate(bitrate) , snr(snr) , recvPower_dBm(recvPower_dBm) , collision(collision) { } /** * @brief Returns the bit-rate of the transmission of the packet. */ double getBitrate() const { return bitrate; } /** * @brief Returns the signal to noise ratio of the transmission. */ double getSnr() const { return snr; } /** * @brief Returns whether drop was due to collision, if isCorrect is false */ bool isCollision() const { return collision; } /** * @brief Returns the signal power in dBm. */ double getRecvPower_dBm() const { return recvPower_dBm; } }; } // namespace veins
3,384
27.445378
116
h
null
AICP-main/veins/src/veins/modules/phy/NistErrorRate.cc
/* * Copyright (c) 2010 The Boeing Company * Copyright (c) 2014 Michele Segata <segata@ccs-labs.org> * * SPDX-License-Identifier: GPL-2.0-only * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Gary Pei <guangyu.pei@boeing.com> */ #include "veins/veins.h" #include "veins/modules/phy/NistErrorRate.h" using veins::NistErrorRate; NistErrorRate::NistErrorRate() { } double NistErrorRate::getBpskBer(double snr) { double z = std::sqrt(snr); double ber = 0.5 * erfc(z); return ber; } double NistErrorRate::getQpskBer(double snr) { double z = std::sqrt(snr / 2.0); double ber = 0.5 * erfc(z); return ber; } double NistErrorRate::get16QamBer(double snr) { double z = std::sqrt(snr / (5.0 * 2.0)); double ber = 0.75 * 0.5 * erfc(z); return ber; } double NistErrorRate::get64QamBer(double snr) { double z = std::sqrt(snr / (21.0 * 2.0)); double ber = 7.0 / 12.0 * 0.5 * erfc(z); return ber; } double NistErrorRate::getFecBpskBer(double snr, uint32_t nbits, uint32_t bValue) { double ber = getBpskBer(snr); if (ber == 0.0) { return 1.0; } double pe = calculatePe(ber, bValue); pe = std::min(pe, 1.0); double pms = std::pow(1 - pe, (double) nbits); return pms; } double NistErrorRate::getFecQpskBer(double snr, uint32_t nbits, uint32_t bValue) { double ber = getQpskBer(snr); if (ber == 0.0) { return 1.0; } double pe = calculatePe(ber, bValue); pe = std::min(pe, 1.0); double pms = std::pow(1 - pe, (double) nbits); return pms; } double NistErrorRate::calculatePe(double p, uint32_t bValue) { double D = std::sqrt(4.0 * p * (1.0 - p)); double pe = 1.0; if (bValue == 1) { // code rate 1/2, use table 3.1.1 pe = 0.5 * (36.0 * std::pow(D, 10) + 211.0 * std::pow(D, 12) + 1404.0 * std::pow(D, 14) + 11633.0 * std::pow(D, 16) + 77433.0 * std::pow(D, 18) + 502690.0 * std::pow(D, 20) + 3322763.0 * std::pow(D, 22) + 21292910.0 * std::pow(D, 24) + 134365911.0 * std::pow(D, 26)); } else if (bValue == 2) { // code rate 2/3, use table 3.1.2 pe = 1.0 / (2.0 * bValue) * (3.0 * std::pow(D, 6) + 70.0 * std::pow(D, 7) + 285.0 * std::pow(D, 8) + 1276.0 * std::pow(D, 9) + 6160.0 * std::pow(D, 10) + 27128.0 * std::pow(D, 11) + 117019.0 * std::pow(D, 12) + 498860.0 * std::pow(D, 13) + 2103891.0 * std::pow(D, 14) + 8784123.0 * std::pow(D, 15)); } else if (bValue == 3) { // code rate 3/4, use table 3.1.2 pe = 1.0 / (2.0 * bValue) * (42.0 * std::pow(D, 5) + 201.0 * std::pow(D, 6) + 1492.0 * std::pow(D, 7) + 10469.0 * std::pow(D, 8) + 62935.0 * std::pow(D, 9) + 379644.0 * std::pow(D, 10) + 2253373.0 * std::pow(D, 11) + 13073811.0 * std::pow(D, 12) + 75152755.0 * std::pow(D, 13) + 428005675.0 * std::pow(D, 14)); } else { ASSERT(false); } return pe; } double NistErrorRate::getFec16QamBer(double snr, uint32_t nbits, uint32_t bValue) { double ber = get16QamBer(snr); if (ber == 0.0) { return 1.0; } double pe = calculatePe(ber, bValue); pe = std::min(pe, 1.0); double pms = std::pow(1 - pe, static_cast<double>(nbits)); return pms; } double NistErrorRate::getFec64QamBer(double snr, uint32_t nbits, uint32_t bValue) { double ber = get64QamBer(snr); if (ber == 0.0) { return 1.0; } double pe = calculatePe(ber, bValue); pe = std::min(pe, 1.0); double pms = std::pow(1 - pe, static_cast<double>(nbits)); return pms; } double NistErrorRate::getChunkSuccessRate(unsigned int datarate, enum Bandwidth bw, double snr_mW, uint32_t nbits) { // get mcs from datarate and bw MCS mcs = getMCS(datarate, bw); // compute success rate depending on mcs switch (mcs) { case MCS::ofdm_bpsk_r_1_2: return getFecBpskBer(snr_mW, nbits, 1); break; case MCS::ofdm_bpsk_r_3_4: return getFecBpskBer(snr_mW, nbits, 3); break; case MCS::ofdm_qpsk_r_1_2: return getFecQpskBer(snr_mW, nbits, 1); break; case MCS::ofdm_qpsk_r_3_4: return getFecQpskBer(snr_mW, nbits, 3); break; case MCS::ofdm_qam16_r_1_2: return getFec16QamBer(snr_mW, nbits, 1); break; case MCS::ofdm_qam16_r_3_4: return getFec16QamBer(snr_mW, nbits, 3); break; case MCS::ofdm_qam64_r_2_3: return getFec64QamBer(snr_mW, nbits, 2); break; case MCS::ofdm_qam64_r_3_4: return getFec64QamBer(snr_mW, nbits, 3); break; default: ASSERT2(false, "Invalid MCS chosen"); break; } return 0; }
5,228
31.277778
318
cc
null
AICP-main/veins/src/veins/modules/phy/NistErrorRate.h
/* * Copyright (c) 2010 The Boeing Company * Copyright (c) 2014 Michele Segata <segata@ccs-labs.org> * * SPDX-License-Identifier: GPL-2.0-only * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Gary Pei <guangyu.pei@boeing.com> */ #pragma once #include <stdint.h> #include <cmath> #include "veins/modules/utility/ConstsPhy.h" namespace veins { /** * Model the error rate for different modulations and coding schemes. * Taken from the nist wifi model of ns-3 */ class VEINS_API NistErrorRate { public: NistErrorRate(); static double getChunkSuccessRate(unsigned int datarate, enum Bandwidth bw, double snr_mW, uint32_t nbits); private: /** * Return the coded BER for the given p and b. * * \param p * \param bValue * \return BER */ static double calculatePe(double p, uint32_t bValue); /** * Return BER of BPSK at the given SNR. * * \param snr snr value * \return BER of BPSK at the given SNR */ static double getBpskBer(double snr); /** * Return BER of QPSK at the given SNR. * * \param snr snr value * \return BER of QPSK at the given SNR */ static double getQpskBer(double snr); /** * Return BER of QAM16 at the given SNR. * * \param snr snr value * \return BER of QAM16 at the given SNR */ static double get16QamBer(double snr); /** * Return BER of QAM64 at the given SNR. * * \param snr snr value * \return BER of QAM64 at the given SNR */ static double get64QamBer(double snr); /** * Return BER of BPSK at the given SNR after applying FEC. * * \param snr snr value * \param nbits the number of bits in the chunk * \param bValue * \return BER of BPSK at the given SNR after applying FEC */ static double getFecBpskBer(double snr, uint32_t nbits, uint32_t bValue); /** * Return BER of QPSK at the given SNR after applying FEC. * * \param snr snr value * \param nbits the number of bits in the chunk * \param bValue * \return BER of QPSK at the given SNR after applying FEC */ static double getFecQpskBer(double snr, uint32_t nbits, uint32_t bValue); /** * Return BER of QAM16 at the given SNR after applying FEC. * * \param snr snr value * \param nbits the number of bits in the chunk * \param bValue * \return BER of QAM16 at the given SNR after applying FEC */ static double getFec16QamBer(double snr, uint32_t nbits, uint32_t bValue); /** * Return BER of QAM64 at the given SNR after applying FEC. * * \param snr snr value * \param nbits the number of bits in the chunk * \param bValue * \return BER of QAM64 at the given SNR after applying FEC */ static double getFec64QamBer(double snr, uint32_t nbits, uint32_t bValue); }; } // namespace veins
3,531
29.448276
111
h
null
AICP-main/veins/src/veins/modules/phy/PhyLayer80211p.cc
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /* * Based on PhyLayer.cc from Karl Wessel * and modifications by Christopher Saloman */ #include "veins/modules/phy/PhyLayer80211p.h" #include "veins/modules/phy/Decider80211p.h" #include "veins/modules/analogueModel/SimplePathlossModel.h" #include "veins/modules/analogueModel/BreakpointPathlossModel.h" #include "veins/modules/analogueModel/PERModel.h" #include "veins/modules/analogueModel/SimpleObstacleShadowing.h" #include "veins/modules/analogueModel/VehicleObstacleShadowing.h" #include "veins/modules/analogueModel/TwoRayInterferenceModel.h" #include "veins/modules/analogueModel/NakagamiFading.h" #include "veins/base/connectionManager/BaseConnectionManager.h" #include "veins/modules/utility/Consts80211p.h" #include "veins/modules/messages/AirFrame11p_m.h" #include "veins/modules/utility/MacToPhyControlInfo11p.h" using namespace veins; using std::unique_ptr; Define_Module(veins::PhyLayer80211p); void PhyLayer80211p::initialize(int stage) { if (stage == 0) { // get ccaThreshold before calling BasePhyLayer::initialize() which instantiates the deciders ccaThreshold = pow(10, par("ccaThreshold").doubleValue() / 10); allowTxDuringRx = par("allowTxDuringRx").boolValue(); collectCollisionStatistics = par("collectCollisionStatistics").boolValue(); // Create frequency mappings and initialize spectrum for signal representation Spectrum::Frequencies freqs; for (auto& channel : IEEE80211ChannelFrequencies) { freqs.push_back(channel.second - 5e6); freqs.push_back(channel.second); freqs.push_back(channel.second + 5e6); } overallSpectrum = Spectrum(freqs); } BasePhyLayer::initialize(stage); } unique_ptr<AnalogueModel> PhyLayer80211p::getAnalogueModelFromName(std::string name, ParameterMap& params) { if (name == "SimplePathlossModel") { return initializeSimplePathlossModel(params); } else if (name == "BreakpointPathlossModel") { return initializeBreakpointPathlossModel(params); } else if (name == "PERModel") { return initializePERModel(params); } else if (name == "SimpleObstacleShadowing") { return initializeSimpleObstacleShadowing(params); } else if (name == "VehicleObstacleShadowing") { return initializeVehicleObstacleShadowing(params); } else if (name == "TwoRayInterferenceModel") { if (world->use2D()) throw cRuntimeError("The TwoRayInterferenceModel uses nodes' z-position as the antenna height over ground. Refusing to work in a 2D world"); return initializeTwoRayInterferenceModel(params); } else if (name == "NakagamiFading") { return initializeNakagamiFading(params); } return BasePhyLayer::getAnalogueModelFromName(name, params); } unique_ptr<AnalogueModel> PhyLayer80211p::initializeBreakpointPathlossModel(ParameterMap& params) { double alpha1 = -1, alpha2 = -1, breakpointDistance = -1; double L01 = -1, L02 = -1; bool useTorus = world->useTorus(); const Coord& playgroundSize = *(world->getPgs()); ParameterMap::iterator it; it = params.find("alpha1"); if (it != params.end()) { // parameter alpha1 has been specified in config.xml // set alpha1 alpha1 = it->second.doubleValue(); EV_TRACE << "createPathLossModel(): alpha1 set from config.xml to " << alpha1 << endl; // check whether alpha is not smaller than specified in ConnectionManager if (cc->hasPar("alpha") && alpha1 < cc->par("alpha").doubleValue()) { // throw error throw cRuntimeError("TestPhyLayer::createPathLossModel(): alpha can't be smaller than specified in \ ConnectionManager. Please adjust your config.xml file accordingly"); } } it = params.find("L01"); if (it != params.end()) { L01 = it->second.doubleValue(); } it = params.find("L02"); if (it != params.end()) { L02 = it->second.doubleValue(); } it = params.find("alpha2"); if (it != params.end()) { // parameter alpha1 has been specified in config.xml // set alpha2 alpha2 = it->second.doubleValue(); EV_TRACE << "createPathLossModel(): alpha2 set from config.xml to " << alpha2 << endl; // check whether alpha is not smaller than specified in ConnectionManager if (cc->hasPar("alpha") && alpha2 < cc->par("alpha").doubleValue()) { // throw error throw cRuntimeError("TestPhyLayer::createPathLossModel(): alpha can't be smaller than specified in \ ConnectionManager. Please adjust your config.xml file accordingly"); } } it = params.find("breakpointDistance"); if (it != params.end()) { // parameter alpha1 has been specified in config.xml breakpointDistance = it->second.doubleValue(); EV_TRACE << "createPathLossModel(): breakpointDistance set from config.xml to " << alpha2 << endl; // check whether alpha is not smaller than specified in ConnectionManager } if (alpha1 == -1 || alpha2 == -1 || breakpointDistance == -1 || L01 == -1 || L02 == -1) { throw cRuntimeError("Undefined parameters for breakpointPathlossModel. Please check your configuration."); } return make_unique<BreakpointPathlossModel>(this, L01, L02, alpha1, alpha2, breakpointDistance, useTorus, playgroundSize); } unique_ptr<AnalogueModel> PhyLayer80211p::initializeTwoRayInterferenceModel(ParameterMap& params) { ASSERT(params.count("DielectricConstant") == 1); double dielectricConstant = params["DielectricConstant"].doubleValue(); return make_unique<TwoRayInterferenceModel>(this, dielectricConstant); } unique_ptr<AnalogueModel> PhyLayer80211p::initializeNakagamiFading(ParameterMap& params) { bool constM = params["constM"].boolValue(); double m = 0; if (constM) { m = params["m"].doubleValue(); } return make_unique<NakagamiFading>(this, constM, m); } unique_ptr<AnalogueModel> PhyLayer80211p::initializeSimplePathlossModel(ParameterMap& params) { // init with default value double alpha = 2.0; bool useTorus = world->useTorus(); const Coord& playgroundSize = *(world->getPgs()); // get alpha-coefficient from config ParameterMap::iterator it = params.find("alpha"); if (it != params.end()) { // parameter alpha has been specified in config.xml // set alpha alpha = it->second.doubleValue(); EV_TRACE << "createPathLossModel(): alpha set from config.xml to " << alpha << endl; // check whether alpha is not smaller than specified in ConnectionManager if (cc->hasPar("alpha") && alpha < cc->par("alpha").doubleValue()) { // throw error throw cRuntimeError("TestPhyLayer::createPathLossModel(): alpha can't be smaller than specified in \ ConnectionManager. Please adjust your config.xml file accordingly"); } } else // alpha has not been specified in config.xml { if (cc->hasPar("alpha")) { // parameter alpha has been specified in ConnectionManager // set alpha according to ConnectionManager alpha = cc->par("alpha").doubleValue(); EV_TRACE << "createPathLossModel(): alpha set from ConnectionManager to " << alpha << endl; } else // alpha has not been specified in ConnectionManager { // keep alpha at default value EV_TRACE << "createPathLossModel(): alpha set from default value to " << alpha << endl; } } return make_unique<SimplePathlossModel>(this, alpha, useTorus, playgroundSize); } unique_ptr<AnalogueModel> PhyLayer80211p::initializePERModel(ParameterMap& params) { double per = params["packetErrorRate"].doubleValue(); return make_unique<PERModel>(this, per); } unique_ptr<Decider> PhyLayer80211p::getDeciderFromName(std::string name, ParameterMap& params) { if (name == "Decider80211p") { protocolId = IEEE_80211; return initializeDecider80211p(params); } return BasePhyLayer::getDeciderFromName(name, params); } unique_ptr<AnalogueModel> PhyLayer80211p::initializeSimpleObstacleShadowing(ParameterMap& params) { // init with default value bool useTorus = world->useTorus(); const Coord& playgroundSize = *(world->getPgs()); ParameterMap::iterator it; ObstacleControl* obstacleControlP = ObstacleControlAccess().getIfExists(); if (!obstacleControlP) throw cRuntimeError("initializeSimpleObstacleShadowing(): cannot find ObstacleControl module"); return make_unique<SimpleObstacleShadowing>(this, *obstacleControlP, useTorus, playgroundSize); } unique_ptr<AnalogueModel> PhyLayer80211p::initializeVehicleObstacleShadowing(ParameterMap& params) { // init with default value bool useTorus = world->useTorus(); const Coord& playgroundSize = *(world->getPgs()); ParameterMap::iterator it; VehicleObstacleControl* vehicleObstacleControlP = VehicleObstacleControlAccess().getIfExists(); if (!vehicleObstacleControlP) throw cRuntimeError("initializeVehicleObstacleShadowing(): cannot find VehicleObstacleControl module"); return make_unique<VehicleObstacleShadowing>(this, *vehicleObstacleControlP, useTorus, playgroundSize); } unique_ptr<Decider> PhyLayer80211p::initializeDecider80211p(ParameterMap& params) { double centerFreq = params["centerFrequency"]; auto dec = make_unique<Decider80211p>(this, this, minPowerLevel, ccaThreshold, allowTxDuringRx, centerFreq, findHost()->getIndex(), collectCollisionStatistics); dec->setPath(getParentModule()->getFullPath()); return unique_ptr<Decider>(std::move(dec)); } void PhyLayer80211p::changeListeningChannel(Channel channel) { Decider80211p* dec = dynamic_cast<Decider80211p*>(decider.get()); ASSERT(dec); double freq = IEEE80211ChannelFrequencies.at(channel); dec->changeFrequency(freq); } void PhyLayer80211p::handleSelfMessage(cMessage* msg) { switch (msg->getKind()) { // transmission overBasePhyLayer:: case TX_OVER: { ASSERT(msg == txOverTimer); sendControlMsgToMac(new cMessage("Transmission over", TX_OVER)); // check if there is another packet on the chan, and change the chan-state to idle Decider80211p* dec = dynamic_cast<Decider80211p*>(decider.get()); ASSERT(dec); if (dec->cca(simTime(), nullptr)) { // chan is idle EV_TRACE << "Channel idle after transmit!\n"; dec->setChannelIdleStatus(true); } else { EV_TRACE << "Channel not yet idle after transmit!\n"; } break; } // radio switch over case RADIO_SWITCHING_OVER: ASSERT(msg == radioSwitchingOverTimer); BasePhyLayer::finishRadioSwitching(); break; // AirFrame case AIR_FRAME: BasePhyLayer::handleAirFrame(static_cast<AirFrame*>(msg)); break; default: break; } } unique_ptr<AirFrame> PhyLayer80211p::createAirFrame(cPacket* macPkt) { return make_unique<AirFrame11p>(macPkt->getName(), AIR_FRAME); } void PhyLayer80211p::attachSignal(AirFrame* airFrame, cObject* ctrlInfo) { const auto ctrlInfo11p = check_and_cast<MacToPhyControlInfo11p*>(ctrlInfo); const auto duration = getFrameDuration(airFrame->getEncapsulatedPacket()->getBitLength(), ctrlInfo11p->mcs); ASSERT(duration > 0); Signal signal(overallSpectrum, simTime(), duration); auto freqIndex = overallSpectrum.indexOf(IEEE80211ChannelFrequencies.at(ctrlInfo11p->channelNr)); signal.at(freqIndex - 1) = ctrlInfo11p->txPower_mW; signal.at(freqIndex) = ctrlInfo11p->txPower_mW; signal.at(freqIndex + 1) = ctrlInfo11p->txPower_mW; signal.setDataStart(freqIndex - 1); signal.setDataEnd(freqIndex + 1); signal.setCenterFrequencyIndex(freqIndex); // copy the signal into the AirFrame airFrame->setSignal(signal); airFrame->setDuration(signal.getDuration()); airFrame->setMcs(static_cast<int>(ctrlInfo11p->mcs)); } int PhyLayer80211p::getRadioState() { return BasePhyLayer::getRadioState(); }; simtime_t PhyLayer80211p::setRadioState(int rs) { if (rs == Radio::TX) decider->switchToTx(); return BasePhyLayer::setRadioState(rs); } void PhyLayer80211p::setCCAThreshold(double ccaThreshold_dBm) { ccaThreshold = pow(10, ccaThreshold_dBm / 10); Decider80211p* dec = dynamic_cast<Decider80211p*>(decider.get()); ASSERT(dec); dec->setCCAThreshold(ccaThreshold_dBm); } double PhyLayer80211p::getCCAThreshold() { return 10 * log10(ccaThreshold); } void PhyLayer80211p::notifyMacAboutRxStart(bool enable) { Decider80211p* dec = dynamic_cast<Decider80211p*>(decider.get()); ASSERT(dec); dec->setNotifyRxStart(enable); } void PhyLayer80211p::requestChannelStatusIfIdle() { Enter_Method_Silent(); Decider80211p* dec = dynamic_cast<Decider80211p*>(decider.get()); ASSERT(dec); if (dec->cca(simTime(), nullptr)) { // chan is idle EV_TRACE << "Request channel status: channel idle!\n"; dec->setChannelIdleStatus(true); } } simtime_t PhyLayer80211p::getFrameDuration(int payloadLengthBits, MCS mcs) const { Enter_Method_Silent(); ASSERT(mcs != MCS::undefined); auto ndbps = getNDBPS(mcs); // calculate frame duration according to Equation (17-29) of the IEEE 802.11-2007 standard return PHY_HDR_PREAMBLE_DURATION + PHY_HDR_PLCPSIGNAL_DURATION + T_SYM_80211P * ceil(static_cast<double>(16 + payloadLengthBits + 6) / (ndbps)); }
14,532
36.94517
168
cc
null
AICP-main/veins/src/veins/modules/phy/PhyLayer80211p.h
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/base/phyLayer/BasePhyLayer.h" #include "veins/base/toolbox/Spectrum.h" #include "veins/modules/mac/ieee80211p/Mac80211pToPhy11pInterface.h" #include "veins/modules/phy/Decider80211p.h" #include "veins/modules/analogueModel/SimplePathlossModel.h" #include "veins/base/connectionManager/BaseConnectionManager.h" #include "veins/modules/phy/Decider80211pToPhy80211pInterface.h" #include "veins/base/utils/Move.h" namespace veins { /** * @brief * Adaptation of the PhyLayer class for 802.11p. * * @ingroup phyLayer * * @see DemoBaseApplLayer * @see Mac1609_4 * @see PhyLayer80211p * @see Decider80211p */ class VEINS_API PhyLayer80211p : public BasePhyLayer, public Mac80211pToPhy11pInterface, public Decider80211pToPhy80211pInterface { public: void initialize(int stage) override; /** * @brief Set the carrier sense threshold * @param ccaThreshold_dBm the cca threshold in dBm */ void setCCAThreshold(double ccaThreshold_dBm) override; /** * @brief Return the cca threshold in dBm */ double getCCAThreshold(); /** * @brief Enable notifications about PHY-RXSTART.indication in MAC * @param enable true if Mac needs to be notified about it */ void notifyMacAboutRxStart(bool enable) override; /** * @brief Explicit request to PHY for the channel status */ void requestChannelStatusIfIdle() override; protected: /** @brief CCA threshold. See Decider80211p for details */ double ccaThreshold; /** @brief enable/disable detection of packet collisions */ bool collectCollisionStatistics; /** @brief allows/disallows interruption of current reception for txing * * See detailed description in Decider80211p */ bool allowTxDuringRx; enum ProtocolIds { IEEE_80211 = 12123 }; /** * @brief Creates and returns an instance of the AnalogueModel with the * specified name. * * Is able to initialize the following AnalogueModels: */ virtual std::unique_ptr<AnalogueModel> getAnalogueModelFromName(std::string name, ParameterMap& params) override; /** * @brief Creates and initializes a SimplePathlossModel with the * passed parameter values. */ std::unique_ptr<AnalogueModel> initializeSimplePathlossModel(ParameterMap& params); /** * @brief Creates and initializes an AntennaModel with the * passed parameter values. */ std::unique_ptr<AnalogueModel> initializeAntennaModel(ParameterMap& params); /** * @brief Creates and initializes a BreakpointPathlossModel with the * passed parameter values. */ virtual std::unique_ptr<AnalogueModel> initializeBreakpointPathlossModel(ParameterMap& params); /** * @brief Creates and initializes a SimpleObstacleShadowing with the * passed parameter values. */ std::unique_ptr<AnalogueModel> initializeSimpleObstacleShadowing(ParameterMap& params); /** * @brief Creates and initializes a VehicleObstacleShadowing with the * passed parameter values. */ std::unique_ptr<AnalogueModel> initializeVehicleObstacleShadowing(ParameterMap& params); /** * @brief Creates a simple Packet Error Rate model that attenuates a percentage * of the packets to zero, and does not attenuate the other packets. * */ virtual std::unique_ptr<AnalogueModel> initializePERModel(ParameterMap& params); /** * @brief Creates and initializes a TwoRayInterferenceModel with the * passed parameter values. */ std::unique_ptr<AnalogueModel> initializeTwoRayInterferenceModel(ParameterMap& params); /** * @brief Creates and initializes a NakagamiFading with the * passed parameter values. */ std::unique_ptr<AnalogueModel> initializeNakagamiFading(ParameterMap& params); /** * @brief Creates and returns an instance of the Decider with the specified * name. * * Is able to initialize the following Deciders: * * - Decider80211p */ virtual std::unique_ptr<Decider> getDeciderFromName(std::string name, ParameterMap& params) override; /** * @brief Initializes a new Decider80211 from the passed parameter map. */ virtual std::unique_ptr<Decider> initializeDecider80211p(ParameterMap& params); /** * Create a protocol-specific AirFrame * Overloaded to create a specialize AirFrame11p. */ std::unique_ptr<AirFrame> createAirFrame(cPacket* macPkt) override; /** * Attach a signal to the given AirFrame. * * The attached Signal corresponds to the IEEE 802.11p standard. * Parameters for the signal are passed in the control info. * The indicated power levels are set up on the specified center frequency, as well as the neighboring 5MHz. * * @note The control info must be of type MacToPhyControlInfo11p */ void attachSignal(AirFrame* airFrame, cObject* ctrlInfo) override; void changeListeningChannel(Channel channel) override; virtual simtime_t getFrameDuration(int payloadLengthBits, MCS mcs) const override; void handleSelfMessage(cMessage* msg) override; int getRadioState() override; simtime_t setRadioState(int rs) override; }; } // namespace veins
6,210
32.755435
131
h
null
AICP-main/veins/src/veins/modules/phy/SampledAntenna1D.cc
// // Copyright (C) 2016 Alexander Brummer <alexander.brummer@fau.de> // Copyright (C) 2018 Fabian Bronner <fabian.bronner@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/phy/SampledAntenna1D.h" #include "veins/base/utils/FWMath.h" using namespace veins; SampledAntenna1D::SampledAntenna1D(std::vector<double>& values, std::string offsetType, std::vector<double>& offsetParams, std::string rotationType, std::vector<double>& rotationParams, cRNG* rng) : antennaGains(values.size() + 1) { distance = (2 * M_PI) / values.size(); // instantiate a random number generator for sample offsets if one is specified cRandom* offsetGen = nullptr; if (offsetType == "uniform") { if (!math::almost_equal(offsetParams[0], -offsetParams[1])) { throw cRuntimeError("SampledAntenna1D::SampledAntenna1D(): The mean of the random distribution for the samples' offsets has to be 0."); } offsetGen = new cUniform(rng, offsetParams[0], offsetParams[1]); } else if (offsetType == "normal") { if (!math::almost_equal<double>(offsetParams[0], 0)) { throw cRuntimeError("SampledAntenna1D::SampledAntenna1D(): The mean of the random distribution for the samples' offsets has to be 0."); } offsetGen = new cNormal(rng, offsetParams[0], offsetParams[1]); } else if (offsetType == "triang") { if (!math::almost_equal<double>((offsetParams[0] + offsetParams[1] + offsetParams[2]) / 3, 0)) { throw cRuntimeError("SampledAntenna1D::SampledAntenna1D(): The mean of the random distribution for the samples' offsets has to be 0."); } offsetGen = new cTriang(rng, offsetParams[0], offsetParams[1], offsetParams[2]); } // determine random rotation of the antenna if specified cRandom* rotationGen = nullptr; if (rotationType == "uniform") { rotationGen = new cUniform(rng, rotationParams[0], rotationParams[1]); } else if (rotationType == "normal") { rotationGen = new cNormal(rng, rotationParams[0], rotationParams[1]); } else if (rotationType == "triang") { rotationGen = new cTriang(rng, rotationParams[0], rotationParams[1], rotationParams[2]); } rotation = (rotationGen == nullptr) ? 0 : rotationGen->draw(); if (rotationGen != nullptr) delete rotationGen; // transform to rad rotation *= (M_PI / 180); // copy values and apply offset for (unsigned int i = 0; i < values.size(); i++) { double offset = 0; if (offsetGen != nullptr) { offset = offsetGen->draw(); // transform to rad offset *= (M_PI / 180); } antennaGains[i] = values[i] + offset; } if (offsetGen != nullptr) delete offsetGen; // assign the value of 0 degrees to 360 degrees as well to assure correct interpolation (size allocated already before) antennaGains[values.size()] = antennaGains[0]; } SampledAntenna1D::~SampledAntenna1D() { } double SampledAntenna1D::getGain(Coord ownPos, Coord ownOrient, Coord otherPos) { // get the line of sight vector Coord los = otherPos - ownPos; // calculate angle using atan2 double angle = atan2(los.y, los.x) - atan2(ownOrient.y, ownOrient.x); // apply possible rotation angle -= rotation; // make sure angle is within [0, 2*M_PI) angle = fmod(angle, 2 * M_PI); if (angle < 0) angle += 2 * M_PI; // calculate antennaGain size_t baseElement = angle / distance; double offset = (angle - (baseElement * distance)) / distance; // make sure to not address an element out of antennaGains (baseElement == lastElement implies that offset is zero) ASSERT((baseElement < antennaGains.size()) && (baseElement != antennaGains.size() - 1 || offset == 0)); double gainValue = antennaGains[baseElement]; if (offset > 0) { gainValue += offset * (antennaGains[baseElement + 1] - antennaGains[baseElement]); } return FWMath::dBm2mW(gainValue); } double SampledAntenna1D::getLastAngle() { return lastAngle / M_PI * 180.0; }
4,915
38.328
196
cc
null
AICP-main/veins/src/veins/modules/phy/SampledAntenna1D.h
// // Copyright (C) 2016 Alexander Brummer <alexander.brummer@fau.de> // Copyright (C) 2018 Fabian Bronner <fabian.bronner@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/base/phyLayer/Antenna.h" #include <vector> namespace veins { /** * @brief * This class represents an antenna whose gain is calculated from given samples in the horizontal plane. * The respective gain is therefore dependent on the azimuth angle. * The user has to provide the samples, which are assumed to be distributed equidistantly. * As the power is assumed to be relative to an isotropic radiator, the values have to be given in dBi. * The values are stored in a mapping automatically supporting linear interpolation between samples. * Optional randomness in terms of sample offsets and antenna rotation is supported. * * * An example antenna.xml for this Antenna can be the following: * @verbatim <?xml version="1.0" encoding="UTF-8"?> <root> <Antenna type="SampledAntenna1D" id="antenna1"> <!-- Write the samples in the value attribute, separated by spaces. The values will be --> <!-- distributed equidistantly, e.g. 4 values will be placed at 0°, 90°, 180° and 270° --> <parameter name="samples" type="string" value="3 -3 3 -3"/> <!-- Options for random offsets are as follows. --> <!-- The mean of the given distribution has to be 0 (so that the overall offset is close to 0dBi) --> <!-- <parameter name="random-offsets" type="string" value="uniform a b"/> --> <!-- <parameter name="random-offsets" type="string" value="normal mean stddev"/> --> <!-- <parameter name="random-offsets" type="string" value="triang a b c"/> --> <parameter name="random-offsets" type="string" value="uniform -0.01 0.01"/> <!-- Options for random rotation of the antennas are the same, but mean doesn't have to be 0. --> <parameter name="random-rotation" type="string" value="uniform -1 1"/> </Antenna> </root> @endverbatim * * * @author Alexander Brummer * * * @see Antenna * @see BasePhyLayer */ class VEINS_API SampledAntenna1D : public Antenna { public: /** * @brief Constructor for the sampled antenna. * * @param values - contains the samples representing the antenna * @param offsetType - name of random distribution to use for the random offset of the samples * @param offsetParams - contains the parameters for the offset random distribution * @param rotationType - name of random distribution to use for the random rotation of the whole antenna * @param rotationParams - contains the parameters for the rotation random distribution * @param rng - pointer to the random number generator to use */ SampledAntenna1D(std::vector<double>& values, std::string offsetType, std::vector<double>& offsetParams, std::string rotationType, std::vector<double>& rotationParams, cRNG* rng); /** * @brief Destructor of the sampled antenna. * * Deletes the mapping used for storing the antenna samples. */ ~SampledAntenna1D() override; /** * @brief Calculates this antenna's gain based on the direction the signal is coming from/sent in. * * @param ownPos - coordinates of this antenna * @param ownOrient - states the direction the antenna (i.e. the car) is pointing at * @param otherPos - coordinates of the other antenna which this antenna is currently communicating with * @return Returns the gain this antenna achieves depending on the computed direction. * If the angle is within two samples, linear interpolation is applied. */ double getGain(Coord ownPos, Coord ownOrient, Coord otherPos) override; double getLastAngle() override; private: /** * @brief Used to store the antenna's samples. */ std::vector<double> antennaGains; double distance; /** * @brief An optional random rotation of the antenna is stored in this field and applied every time * the gain has to be calculated. */ double rotation; double lastAngle; }; } // namespace veins
5,067
41.233333
183
h
null
AICP-main/veins/src/veins/modules/utility/BBoxLookup.cc
// // Copyright (C) 2019 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <cmath> #include "veins/modules/utility/BBoxLookup.h" namespace { using Point = veins::BBoxLookup::Point; using Box = veins::BBoxLookup::Box; /** * Helper structure representing a wireless ray from a sender to a receiver. * * Contains pre-computed values to speed up calls to intersect with the same ray but different boxes. */ struct Ray { Point origin; Point destination; Point direction; Point invDirection; struct { size_t x; size_t y; } sign; double length; }; /** * Return a Ray struct for fast intersection tests from sender to receiver. */ Ray makeRay(const Point& sender, const Point& receiver) { const double dir_x = receiver.x - sender.x; const double dir_y = receiver.y - sender.y; Ray ray; ray.origin = sender; ray.destination = receiver; ray.length = std::sqrt(dir_x * dir_x + dir_y * dir_y); ray.direction.x = dir_x / ray.length; ray.direction.y = dir_y / ray.length; ray.invDirection.x = 1.0 / ray.direction.x; ray.invDirection.y = 1.0 / ray.direction.y; ray.sign.x = ray.invDirection.x < 0; ray.sign.y = ray.invDirection.y < 0; return ray; } /** * Return whether ray intersects with box. * * Based on: * Amy Williams, Steve Barrus, R. Keith Morley & Peter Shirley (2005) An Efficient and Robust Ray-Box Intersection Algorithm, Journal of Graphics Tools, 10:1, 49-54, DOI: 10.1080/2151237X.2005.10129188 */ bool intersects(const Ray& ray, const Box& box) { const double x[2]{box.p1.x, box.p2.x}; const double y[2]{box.p1.y, box.p2.y}; double tmin = (x[ray.sign.x] - ray.origin.x) * ray.invDirection.x; double tmax = (x[1 - ray.sign.x] - ray.origin.x) * ray.invDirection.x; double tymin = (y[ray.sign.y] - ray.origin.y) * ray.invDirection.y; double tymax = (y[1 - ray.sign.y] - ray.origin.y) * ray.invDirection.y; if ((tmin > tymax) || (tymin > tmax)) return false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; return (tmin < ray.length) && (tmax > 0); } } // anonymous namespace namespace veins { BBoxLookup::BBoxLookup(const std::vector<Obstacle*>& obstacles, std::function<BBoxLookup::Box(Obstacle*)> makeBBox, double scenarioX, double scenarioY, int cellSize) : bboxes() , obstacleLookup() , bboxCells() , cellSize(cellSize) , numCols(std::floor(scenarioX / cellSize) + 1) , numRows(std::floor(scenarioY / cellSize) + 1) { // phase 1: build unordered collection of cells // initialize proto-cells (cells in non-contiguos memory) ASSERT(scenarioX > 0); ASSERT(scenarioY > 0); ASSERT(numCols * cellSize >= scenarioX); ASSERT(numRows * cellSize >= scenarioY); const size_t numCells = numCols * numRows; std::vector<std::vector<BBoxLookup::Box>> protoCells(numCells); std::vector<std::vector<Obstacle*>> protoLookup(numCells); // fill protoCells with boundingBoxes size_t numEntries = 0; for (const auto obstaclePtr : obstacles) { auto bbox = makeBBox(obstaclePtr); const size_t fromCol = std::max(0, int(bbox.p1.x / cellSize)); const size_t toCol = std::max(0, int(bbox.p2.x / cellSize)); const size_t fromRow = std::max(0, int(bbox.p1.y / cellSize)); const size_t toRow = std::max(0, int(bbox.p2.y / cellSize)); for (size_t row = fromRow; row <= toRow; ++row) { for (size_t col = fromCol; col <= toCol; ++col) { const size_t cellIndex = col + row * numCols; protoCells[cellIndex].push_back(bbox); protoLookup[cellIndex].push_back(obstaclePtr); ++numEntries; ASSERT(protoCells[cellIndex].size() == protoLookup[cellIndex].size()); } } } // phase 2: derive read-only data structure with fast lookup bboxes.reserve(numEntries); obstacleLookup.reserve(numEntries); bboxCells.reserve(numCells); size_t index = 0; for (size_t row = 0; row < numRows; ++row) { for (size_t col = 0; col < numCols; ++col) { const size_t cellIndex = col + row * numCols; auto& currentCell = protoCells.at(cellIndex); auto& currentLookup = protoLookup.at(cellIndex); ASSERT(currentCell.size() == currentLookup.size()); const size_t count = currentCell.size(); // copy over bboxes and obstacle lookups (in strict order) for (size_t entryIndex = 0; entryIndex < count; ++entryIndex) { bboxes.push_back(currentCell.at(entryIndex)); obstacleLookup.push_back(currentLookup.at(entryIndex)); } // create lookup table for this cell bboxCells.push_back({index, count}); // forward index to begin of next cell index += count; ASSERT(bboxes.size() == index); } } ASSERT(bboxes.size() == numEntries); ASSERT(bboxes.size() == obstacleLookup.size()); } std::vector<Obstacle*> BBoxLookup::findOverlapping(Point sender, Point receiver) const { std::vector<Obstacle*> overlappingObstacles; const Box bbox{ {std::min(sender.x, receiver.x), std::min(sender.y, receiver.y)}, {std::max(sender.x, receiver.x), std::max(sender.y, receiver.y)}, }; // determine coordinates for all cells touched by bbox const size_t firstCol = std::max(0, int(bbox.p1.x / cellSize)); const size_t lastCol = std::max(0, int(bbox.p2.x / cellSize)); const size_t firstRow = std::max(0, int(bbox.p1.y / cellSize)); const size_t lastRow = std::max(0, int(bbox.p2.y / cellSize)); ASSERT(lastCol < numCols && lastRow < numRows); // precompute transmission ray properties const Ray ray = makeRay(sender, receiver); // iterate over cells for (size_t row = firstRow; row <= lastRow; ++row) { for (size_t col = firstCol; col <= lastCol; ++col) { // skip cell if ray does not intersect with the cell. const Box cellBox = {{static_cast<double>(col * cellSize), static_cast<double>(row * cellSize)}, {static_cast<double>((col + 1) * cellSize), static_cast<double>((row + 1) * cellSize)}}; if (!intersects(ray, cellBox)) continue; // derive cell for current cell coordinates const size_t cellIndex = col + row * numCols; const BBoxCell& cell = bboxCells.at(cellIndex); // iterate over bboxes in each cell for (size_t bboxIndex = cell.index; bboxIndex < cell.index + cell.count; ++bboxIndex) { const Box& current = bboxes.at(bboxIndex); // check for overlap with bbox (fast rejection) if (current.p2.x < bbox.p1.x) continue; if (current.p1.x > bbox.p2.x) continue; if (current.p2.y < bbox.p1.y) continue; if (current.p1.y > bbox.p2.y) continue; // derive corresponding obstacle if (!intersects(ray, current)) continue; overlappingObstacles.push_back(obstacleLookup.at(bboxIndex)); } } } return overlappingObstacles; } } // namespace veins
8,075
39.38
201
cc
null
AICP-main/veins/src/veins/modules/utility/BBoxLookup.h
// // Copyright (C) 2019 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <algorithm> #include <functional> #include <vector> #include "veins/veins.h" namespace veins { class Obstacle; /** * Fast grid-based spatial datastructure to find obstacles (geometric shapes) in a bounding box. * * Stores bounding boxes for a set of obstacles and allows searching for them via another bounding box. * * Only considers a 2-dimensional plane (x and y coordinates). * * In principle, any kind (or implementation) of a obstacle/shape/polygon is possible. * There only has to be a function to derive a bounding box for a given obstacle. * Obstacle instances are stored as pointers, so the lifetime of the obstacle instances is not managed by this class. */ class VEINS_API BBoxLookup { public: struct Point { double x; double y; }; // array of stucts approach // cache line size: 64byte = 8 x 8-byte double = 2 bboxes per line // bbox coordinates are inherently local, if i check x1, i likely also check the other struct Box { Point p1; Point p2; }; struct BBoxCell { size_t index; /**< index of the first element of this cell in bboxes */ size_t count; /**< number of elements in this cell; index + number = index of last element */ }; BBoxLookup() = default; BBoxLookup(const std::vector<Obstacle*>& obstacles, std::function<BBoxLookup::Box(Obstacle*)> makeBBox, double scenarioX, double scenarioY, int cellSize = 250); /** * Return all obstacles which have their bounding box touched by the transmission from sender to receiver. * * The obstacles itself may not actually overlap with transmission (false positives are possible). */ std::vector<Obstacle*> findOverlapping(Point sender, Point receiver) const; private: // NOTE: obstacles may occur multiple times in bboxes/obstacleLookup (if they are in multiple cells) std::vector<Box> bboxes; /**< ALL bboxes in one chunck of contiguos memory, ordered by cells */ std::vector<Obstacle*> obstacleLookup; /**< bboxes[i] belongs to instance in obstacleLookup[i] */ std::vector<BBoxCell> bboxCells; /**< flattened matrix of X * Y BBoxCell instances */ int cellSize = 0; size_t numCols = 0; /**< X BBoxCell instances in a row */ size_t numRows = 0; /**< Y BBoxCell instances in a column */ }; } // namespace veins
3,260
37.364706
164
h
null
AICP-main/veins/src/veins/modules/utility/Consts80211p.h
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <stdint.h> #include "veins/veins.h" #include "veins/modules/utility/ConstsPhy.h" using omnetpp::SimTime; namespace veins { /** @brief Bit rates for 802.11p * * as defined in Table 17-14 MIB attribute default values/ranges in the IEEE 802.11-2007 standard */ const uint64_t NUM_BITRATES_80211P = 8; const uint64_t BITRATES_80211P[] = {3000000, 4500000, 6000000, 9000000, 12000000, 18000000, 24000000, 27000000}; /** @brief Number of Data Bits Per Symbol (N_NBPS) corresponding to bitrates in BITRATES_80211P * * as defined in Table 17-3 in the IEEE 802.11-2007 standard */ const uint32_t N_DBPS_80211P[] = {24, 36, 48, 72, 96, 144, 192, 216}; /** @brief Symbol interval * * as defined in Table 17-4 in the IEEE 802.11-2007 standard */ const double T_SYM_80211P = 8e-6; /** @brief Length (in bits) of SERVICE field in PHY HEADER * * as defined in 17.3.2 PLCP frame format in the IEEE 802.11-2007 standard */ const int PHY_HDR_SERVICE_LENGTH = 16; /** @brief Length (in bits) of Tail field in PHY PPDU * * as defined in 17.3.2 PLCP frame format in the IEEE 802.11-2007 standard */ const int PHY_TAIL_LENGTH = 6; /** @brief Duration of the PLCP Preamble * * as defined in Table 17.4 Timing-related parameters in the IEEE 802.11-2007 standard */ const double PHY_HDR_PREAMBLE_DURATION = 32e-6; /** @brief Duration of the PLCP Signal * * as defined in Table 17.4 Timing-related parameters in the IEEE 802.11-2007 standard */ const double PHY_HDR_PLCPSIGNAL_DURATION = 8e-6; /** @brief Length of the PLCP Signal * * as defined in Figure 17.1 PPDU frame format in the IEEE 802.11-2007 standard */ const int PHY_HDR_PLCPSIGNAL_LENGTH = 24; /** @brief Bitrate of the PLCP Signal * * as defined in Table 17.4 Timing-related parameters in the IEEE 802.11-2007 standard * 24 bits in 8e-6 seconds */ const uint64_t PHY_HDR_BITRATE = 3000000; /** @brief Slot Time for 10 MHz channel spacing * * as defined in Table 17-15 OFDM PHY characteristics in the IEEE 802.11-2007 standard */ const SimTime SLOTLENGTH_11P = SimTime().setRaw(13000000UL); /** @brief Short interframe space * * as defined in Table 17-15 OFDM PHY characteristics in the IEEE 802.11-2007 standard */ const SimTime SIFS_11P = SimTime().setRaw(32000000UL); /** @brief Time it takes to switch from Rx to Tx Mode * * as defined in Table 17-15 OFDM PHY characteristics in the IEEE 802.11-2007 standard */ const SimTime RADIODELAY_11P = SimTime().setRaw(1000000UL); /** @brief Contention Window minimal size * * as defined in Table 17-15 OFDM PHY characteristics in the IEEE 802.11-2007 standard */ const unsigned CWMIN_11P = 15; /** @brief Contention Window maximal size * * as defined in Table 17-15 OFDM PHY characteristics in the IEEE 802.11-2007 standard */ const unsigned CWMAX_11P = 1023; /** @brief 1609.4 slot length * * as defined in Table H.1 in the IEEE 1609.4-2010 standard */ const SimTime SWITCHING_INTERVAL_11P = SimTime().setRaw(50000000000UL); /** @brief 1609.4 slot length * * as defined in Table H.1 in the IEEE 1609.4-2010 standard * It is the sum of SyncTolerance and MaxChSwitchTime as defined in 6.2.5 in the IEEE 1609.4-2010 Standard */ const SimTime GUARD_INTERVAL_11P = SimTime().setRaw(4000000000UL); const Bandwidth BANDWIDTH_11P = Bandwidth::ofdm_10_mhz; /** @brief Channels as reserved by the FCC * */ enum class Channel { crit_sol = 172, sch1 = 174, sch2 = 176, cch = 178, sch3 = 180, sch4 = 182, hpps = 184 }; /** * Maps channel identifier to the corresponding center frequency. * * @note Not all entries are defined. */ const std::map<Channel, double> IEEE80211ChannelFrequencies = { {Channel::crit_sol, 5.86e9}, {Channel::sch1, 5.87e9}, {Channel::sch2, 5.88e9}, {Channel::cch, 5.89e9}, {Channel::sch3, 5.90e9}, {Channel::sch4, 5.91e9}, {Channel::hpps, 5.92e9}, }; enum class ChannelType { control = 0, service, }; } // namespace veins
4,879
27.87574
112
h
null
AICP-main/veins/src/veins/modules/utility/ConstsPhy.h
// // Copyright (C) 2014 Michele Segata <segata@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <cmath> #include <stdint.h> #include "veins/veins.h" namespace veins { /** @brief Modulation and coding scheme to be used for transmission */ enum class MCS { // use the default MCS undefined = -1, ofdm_bpsk_r_1_2, ofdm_bpsk_r_3_4, ofdm_qpsk_r_1_2, ofdm_qpsk_r_3_4, ofdm_qam16_r_1_2, ofdm_qam16_r_3_4, ofdm_qam64_r_2_3, ofdm_qam64_r_3_4 }; /** @brief Available bandwidths */ enum class Bandwidth { ofdm_5_mhz, ofdm_10_mhz, ofdm_20_mhz }; /** @brief Given bandwidth and MCS returns datarate in bits per second */ inline uint64_t getOfdmDatarate(MCS mcs, Bandwidth bw) { // divide datarate by div, depending on bandwidth uint64_t div; // datarate to be returned uint64_t dr; switch (bw) { case Bandwidth::ofdm_5_mhz: div = 4; break; case Bandwidth::ofdm_10_mhz: div = 2; break; case Bandwidth::ofdm_20_mhz: default: div = 1; break; } switch (mcs) { case MCS::ofdm_bpsk_r_1_2: dr = 6000000; break; case MCS::ofdm_bpsk_r_3_4: dr = 9000000; break; case MCS::ofdm_qpsk_r_1_2: dr = 12000000; break; case MCS::ofdm_qpsk_r_3_4: dr = 18000000; break; case MCS::ofdm_qam16_r_1_2: dr = 24000000; break; case MCS::ofdm_qam16_r_3_4: dr = 36000000; break; case MCS::ofdm_qam64_r_2_3: dr = 48000000; break; case MCS::ofdm_qam64_r_3_4: dr = 54000000; break; default: dr = 6000000; break; } return (dr / div); } /** @brief returns the number of databits per ofdm symbol */ inline uint32_t getNDBPS(MCS mcs) { uint32_t ndbps; switch (mcs) { case MCS::ofdm_bpsk_r_1_2: ndbps = 24; break; case MCS::ofdm_bpsk_r_3_4: ndbps = 36; break; case MCS::ofdm_qpsk_r_1_2: ndbps = 48; break; case MCS::ofdm_qpsk_r_3_4: ndbps = 72; break; case MCS::ofdm_qam16_r_1_2: ndbps = 96; break; case MCS::ofdm_qam16_r_3_4: ndbps = 144; break; case MCS::ofdm_qam64_r_2_3: ndbps = 192; break; case MCS::ofdm_qam64_r_3_4: ndbps = 216; break; default: ndbps = 24; break; } return ndbps; } /** @brief returns the bandwidth in Hz */ inline uint64_t getBandwidth(Bandwidth bw) { switch (bw) { case Bandwidth::ofdm_5_mhz: return 5000000; break; case Bandwidth::ofdm_10_mhz: return 10000000; break; case Bandwidth::ofdm_20_mhz: return 20000000; break; default: ASSERT2(false, "Invalid datarate for required bandwidth"); return -1; } } /** @brief returns encoding given datarate */ inline MCS getMCS(uint64_t datarate, Bandwidth bw) { if (bw == Bandwidth::ofdm_10_mhz) { if (datarate == 3000000) { return MCS::ofdm_bpsk_r_1_2; } if (datarate == 4500000) { return MCS::ofdm_bpsk_r_3_4; } if (datarate == 6000000) { return MCS::ofdm_qpsk_r_1_2; } if (datarate == 9000000) { return MCS::ofdm_qpsk_r_3_4; } if (datarate == 12000000) { return MCS::ofdm_qam16_r_1_2; } if (datarate == 18000000) { return MCS::ofdm_qam16_r_3_4; } if (datarate == 24000000) { return MCS::ofdm_qam64_r_2_3; } if (datarate == 27000000) { return MCS::ofdm_qam64_r_3_4; } } if (bw == Bandwidth::ofdm_20_mhz) { if (datarate == 6000000) { return MCS::ofdm_bpsk_r_1_2; } if (datarate == 9000000) { return MCS::ofdm_bpsk_r_3_4; } if (datarate == 12000000) { return MCS::ofdm_qpsk_r_1_2; } if (datarate == 18000000) { return MCS::ofdm_qpsk_r_3_4; } if (datarate == 24000000) { return MCS::ofdm_qam16_r_1_2; } if (datarate == 36000000) { return MCS::ofdm_qam16_r_3_4; } if (datarate == 48000000) { return MCS::ofdm_qam64_r_2_3; } if (datarate == 54000000) { return MCS::ofdm_qam64_r_3_4; } } if (bw == Bandwidth::ofdm_5_mhz) { if (datarate == 1500000) { return MCS::ofdm_bpsk_r_1_2; } if (datarate == 2250000) { return MCS::ofdm_bpsk_r_3_4; } if (datarate == 3000000) { return MCS::ofdm_qpsk_r_1_2; } if (datarate == 4500000) { return MCS::ofdm_qpsk_r_3_4; } if (datarate == 6000000) { return MCS::ofdm_qam16_r_1_2; } if (datarate == 9000000) { return MCS::ofdm_qam16_r_3_4; } if (datarate == 12000000) { return MCS::ofdm_qam64_r_2_3; } if (datarate == 13500000) { return MCS::ofdm_qam64_r_3_4; } } ASSERT2(false, "Invalid datarate for required bandwidth"); return MCS::undefined; } } // namespace veins
6,167
24.17551
76
h
null
AICP-main/veins/src/veins/modules/utility/HasLogProxy.cc
// // Copyright (C) 2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/utility/HasLogProxy.h" namespace veins { HasLogProxy::HasLogProxy(cComponent* owner) : owner(owner) { } const cComponent* HasLogProxy::getThisPtr() const { return owner; } } // namespace veins
1,129
28.736842
76
cc
null
AICP-main/veins/src/veins/modules/utility/HasLogProxy.h
// // Copyright (C) 2018 Christoph Sommer <sommer@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <string> #include "veins/veins.h" namespace veins { /** * Helper class for logging from classes not derived from cComponent */ class VEINS_API HasLogProxy { public: HasLogProxy(cComponent* owner); const cComponent* getThisPtr() const; protected: cComponent* owner; }; } // namespace veins
1,230
27.627907
76
h
null
AICP-main/veins/src/veins/modules/utility/MacToPhyControlInfo11p.h
// // Copyright (C) 2018-2019 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/modules/utility/ConstsPhy.h" #include "veins/modules/utility/Consts80211p.h" namespace veins { /** * Stores information which is needed by the physical layer * when sending a MacPkt. * * @ingroup phyLayer * @ingroup macLayer */ struct VEINS_API MacToPhyControlInfo11p : public cObject { Channel channelNr; ///< Channel number/index used to select frequency. MCS mcs; ///< The modulation and coding scheme to employ for the associated frame. double txPower_mW; ///< Transmission power in milliwatts. MacToPhyControlInfo11p(Channel channelNr, MCS mcs, double txPower_mW) : channelNr(channelNr) , mcs(mcs) , txPower_mW(txPower_mW) { } }; } // namespace veins
1,672
30.566038
86
h
null
AICP-main/veins/src/veins/modules/utility/SignalManager.h
// // Copyright (C) 2019-2019 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include <functional> #include <memory> namespace veins { template <typename Payload> struct VEINS_API SignalPayload { cComponent* source; simsignal_t signalID; Payload p; cObject* details; }; template <typename Payload> class VEINS_API SignalCallbackListener : public cListener { public: using Callback = std::function<void (SignalPayload<Payload>)>; SignalCallbackListener(Callback callback, cModule* receptor, simsignal_t signal) : callback(callback) , receptor(receptor) , signal(signal) { receptor->subscribe(signal, this); } ~SignalCallbackListener() { if (getSubscribeCount() > 0) { receptor->unsubscribe(signal, this); } } void receiveSignal(cComponent* source, simsignal_t signalID, Payload p, cObject* details) override { ASSERT(signalID == signal); callback({source, signalID, p, details}); } private: const Callback callback; cModule* const receptor; const simsignal_t signal; }; class VEINS_API SignalManager { public: void subscribeCallback(cModule* receptor, simsignal_t signal, const std::function<void(SignalPayload<bool>)> callback) { auto callbackListener = make_unique<SignalCallbackListener<bool>>(callback, receptor, signal); callbacks.emplace_back(std::move(callbackListener)); } void subscribeCallback(cModule* receptor, simsignal_t signal, const std::function<void(SignalPayload<long>)> callback) { auto callbackListener = make_unique<SignalCallbackListener<long>>(callback, receptor, signal); callbacks.emplace_back(std::move(callbackListener)); } void subscribeCallback(cModule* receptor, simsignal_t signal, const std::function<void(SignalPayload<unsigned long>)> callback) { auto callbackListener = make_unique<SignalCallbackListener<unsigned long>>(callback, receptor, signal); callbacks.emplace_back(std::move(callbackListener)); } void subscribeCallback(cModule* receptor, simsignal_t signal, const std::function<void(SignalPayload<double>)> callback) { auto callbackListener = make_unique<SignalCallbackListener<double>>(callback, receptor, signal); callbacks.emplace_back(std::move(callbackListener)); } void subscribeCallback(cModule* receptor, simsignal_t signal, const std::function<void(SignalPayload<const SimTime&>)> callback) { auto callbackListener = make_unique<SignalCallbackListener<const SimTime&>>(callback, receptor, signal); callbacks.emplace_back(std::move(callbackListener)); } void subscribeCallback(cModule* receptor, simsignal_t signal, const std::function<void(SignalPayload<const char*>)> callback) { auto callbackListener = make_unique<SignalCallbackListener<const char*>>(callback, receptor, signal); callbacks.emplace_back(std::move(callbackListener)); } void subscribeCallback(cModule* receptor, simsignal_t signal, const std::function<void(SignalPayload<cObject*>)> callback) { auto callbackListener = make_unique<SignalCallbackListener<cObject*>>(callback, receptor, signal); callbacks.emplace_back(std::move(callbackListener)); } private: std::vector<std::unique_ptr<cListener>> callbacks; }; } // namespace veins
4,271
36.80531
132
h
null
AICP-main/veins/src/veins/modules/utility/TimerManager.cc
// // Copyright (C) 2018-2018 Max Schettler <max.schettler@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "veins/modules/utility/TimerManager.h" #include <algorithm> using omnetpp::simTime; using omnetpp::simtime_t; using veins::TimerManager; using veins::TimerMessage; using veins::TimerSpecification; struct veins::TimerMessage : public omnetpp::cMessage { TimerMessage(const std::string& name) : omnetpp::cMessage(name.c_str()) { } }; TimerSpecification::TimerSpecification(std::function<void()> callback) : start_mode_(StartMode::immediate) , end_mode_(EndMode::open) , period_(-1) , callback_(callback) { } TimerSpecification& TimerSpecification::interval(simtime_t interval) { ASSERT(interval > 0); period_ = interval; return *this; } TimerSpecification& TimerSpecification::relativeStart(simtime_t start) { start_mode_ = StartMode::relative; start_ = start; return *this; } TimerSpecification& TimerSpecification::absoluteStart(simtime_t start) { start_mode_ = StartMode::absolute; start_ = start; return *this; } TimerSpecification& TimerSpecification::relativeEnd(simtime_t end) { end_mode_ = EndMode::relative; end_time_ = end; return *this; } TimerSpecification& TimerSpecification::absoluteEnd(simtime_t end) { end_mode_ = EndMode::absolute; end_time_ = end; return *this; } TimerSpecification& TimerSpecification::repetitions(size_t n) { end_mode_ = EndMode::repetition; end_count_ = n; return *this; } TimerSpecification& TimerSpecification::openEnd() { end_mode_ = EndMode::open; return *this; } TimerSpecification& TimerSpecification::oneshotIn(omnetpp::simtime_t in) { return this->relativeStart(in).interval(1).repetitions(1); } TimerSpecification& TimerSpecification::oneshotAt(omnetpp::simtime_t at) { return this->absoluteStart(at).interval(1).repetitions(1); } void TimerSpecification::finalize() { switch (start_mode_) { case StartMode::relative: start_ += simTime(); start_mode_ = StartMode::absolute; break; case StartMode::absolute: break; case StartMode::immediate: start_ = simTime() + period_; break; } switch (end_mode_) { case EndMode::relative: end_time_ += simTime(); end_mode_ = EndMode::absolute; break; case EndMode::absolute: break; case EndMode::repetition: end_time_ = start_ + ((end_count_ - 1) * period_); end_mode_ = EndMode::absolute; break; case EndMode::open: break; } } bool TimerSpecification::validOccurence(simtime_t time) const { const bool afterStart = time >= start_; const bool beforeEnd = time <= end_time_; const bool atPeriod = omnetpp::fmod(time - start_, period_) == 0; return afterStart && (beforeEnd || end_mode_ == EndMode::open) && atPeriod; } TimerManager::TimerManager(omnetpp::cSimpleModule* parent) : parent_(parent) { ASSERT(parent_); } TimerManager::~TimerManager() { for (const auto& timer : timers_) { parent_->cancelAndDelete(timer.first); } } bool TimerManager::handleMessage(omnetpp::cMessage* message) { auto* timerMessage = dynamic_cast<TimerMessage*>(message); if (!timerMessage) { return false; } ASSERT(timerMessage->isSelfMessage()); std::string s = timerMessage->getName(); auto timer = timers_.find(timerMessage); if (timer == timers_.end()) { return false; } ASSERT(timer->second.valid() && timer->second.validOccurence(simTime())); timer->second.callback_(); if (timers_.find(timerMessage) != timers_.end()) { // confirm that the timer has not been cancelled during the callback const auto next_event = simTime() + timer->second.period_; if (timer->second.validOccurence(next_event)) { parent_->scheduleAt(next_event, timer->first); } else { parent_->cancelAndDelete(timer->first); timers_.erase(timer); } } return true; } TimerManager::TimerHandle TimerManager::create(TimerSpecification timerSpecification, const std::string name) { ASSERT(timerSpecification.valid()); timerSpecification.finalize(); const auto ret = timers_.insert(std::make_pair(new TimerMessage(name), std::move(timerSpecification))); ASSERT(ret.second); parent_->scheduleAt(ret.first->second.start_, ret.first->first); return ret.first->first->getId(); } void TimerManager::cancel(TimerManager::TimerHandle handle) { const auto entryMatchesHandle = [handle](const std::pair<TimerMessage*, TimerSpecification>& entry) { return entry.first->getId() == handle; }; auto timer = std::find_if(timers_.begin(), timers_.end(), entryMatchesHandle); if (timer != timers_.end()) { parent_->cancelAndDelete(timer->first); timers_.erase(timer); } }
5,749
26.644231
147
cc
null
AICP-main/veins/src/veins/modules/utility/TimerManager.h
// // Copyright (C) 2018-2018 Max Schettler <max.schettler@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <functional> #include <map> #include <string> #include "veins/veins.h" namespace veins { /** * Abstraction for (recurring) Timers for cSimpleModule. * * This abstraction takes care of managing the required self-messages to (repeatedly) execute a piece of code after a certain time. * To use, instantiate one TimerManager per cSimpleModule, then call its handleMessage method from that of the cSimpleModule. * * In order to schedule a timer, create a TimerSpecification object using the corresponding methods. * After configuration, use the create function from the TimerManager to actually schedule the configured timer. */ class TimerManager; /** * A message which is used for triggering Timers. * * Its implementation is empty as it is only used to differentiate from other * messages. */ struct TimerMessage; /** * A class which specifies a Timer. * * This includes timing information as well as its callback. */ struct VEINS_API TimerSpecification { public: /** * Create a new TimerSpecification. * * The created timer is invalid, an interval is missing for it to be usable. * By default, the timer starts running immediately and triggers first after the first time after the interval. * After that, it will continue to run until the simulation ends, calling the callback after the interval has elapsed. * In order to create a timer, this needs to be passed to TimerManager::create. * * @param callback The callback which is executed when the timer is triggered. * * @see TimerManager */ TimerSpecification(std::function<void()> callback); /** * Set the period between two timer occurences. */ TimerSpecification& interval(omnetpp::simtime_t interval); /** * Set the number of repetitions. * * @note You cannot use both this and absoluteEnd or relativeEnd. */ TimerSpecification& repetitions(size_t n); /** * Set the timer's start time. * * Any previously set start time will be overwritten. * * @param start Time of first execution relative to the current simulation time. E.g., passing simtime_t(1, SIMTIME_S) will execute the timer in one second. * * @note You cannot use this in conjunction with repetition(). */ TimerSpecification& relativeStart(omnetpp::simtime_t start); /** * Set the timer's start time. * * Any previously set start time will be overwritten. * * @param start The absolute start time. The first occurence will be exactly at this time. Passing a value earlier than the current simtime will result in an error. * * @note You cannot use this in conjunction with repetition(). */ TimerSpecification& absoluteStart(omnetpp::simtime_t start); /** * Set the timer's end time. * * Any previously set end time will be overwritten. * * @param end Time after which this timer will no longer be executed, relative to the current simulation time. E.g., passing simtime_t(1, SIMTIME_S) will stop the execution of the time after one second has passed. */ TimerSpecification& relativeEnd(omnetpp::simtime_t end); /** * Set the timer's end time. * * Any previously set end time will be overwritten. * * @param end The absolute end time. The latest possible occurence is at this time. Values before the current start time will prevent any executions. */ TimerSpecification& absoluteEnd(omnetpp::simtime_t end); /** * Set the timer to be open ended. * * Any previously set end time will be overwritten. */ TimerSpecification& openEnd(); /** * Set the timer to execute once in a given time. * * Any previously set start time, end time, and interval will be overwritten. */ TimerSpecification& oneshotIn(omnetpp::simtime_t in); /** * Set the timer to execute once at a given time. * * Any previously set start time, end time, and interval will be overwritten. */ TimerSpecification& oneshotAt(omnetpp::simtime_t at); private: friend TimerManager; enum class StartMode { relative, absolute, immediate }; enum class EndMode { relative, absolute, repetition, open }; /** * Finalizes this instance such that its values are independent of current simulation time. * * After calling this function, start_mode_ is guaranteed to be StartMode::absolute and end_mode_ to be EndMode::absolute or EndMode::open. */ void finalize(); /** * Checks validity of this specification, i.e., whether all necessary information is set. */ bool valid() const { return period_ != -1; } /** * Check that the given time is a valid occurence for this timer. */ bool validOccurence(omnetpp::simtime_t time) const; StartMode start_mode_; ///< Interpretation of start time._ omnetpp::simtime_t start_; ///< Time of the Timer's first occurence. Interpretation depends on start_mode_. EndMode end_mode_; ///< Interpretation of end time._ unsigned end_count_; ///< Number of repetitions of the timer. Only valid when end_mode_ == repetition. omnetpp::simtime_t end_time_; ///< Last possible occurence of the timer. Only valid when end_mode_ != repetition. omnetpp::simtime_t period_; ///< Time between events. std::function<void()> callback_; ///< The function to be called when the Timer is triggered. }; class VEINS_API TimerManager { private: public: using TimerHandle = long; using TimerList = std::map<TimerMessage*, const TimerSpecification>; TimerManager(omnetpp::cSimpleModule* parent); /** * Destroy this module. * * All associated events will be cancelled and the corresponding messages deleted. */ ~TimerManager(); /** * Handle the given message and, if applicable, trigger the associated timer. * * @param message The received message. * @return true, if the message was meant for this TimerManager. In this case, the passed message might be invalidated. */ bool handleMessage(omnetpp::cMessage* message); /** * Create a new timer. * * @param timerSpecification Parameters for the new timer * @param name The timer's name * @return A handle for the timer. * * @see cancel * @see TimerSpecification */ TimerHandle create(TimerSpecification timerSpecification, std::string name = ""); /** * Cancel a timer. * * Prevents any future executions of the given timer. Expired timers are silently ignored. * * @param handle A handle which identifies the timer. */ void cancel(TimerHandle handle); private: TimerList timers_; ///< List of all active Timers. omnetpp::cSimpleModule* const parent_; ///< A pointer to the module which owns this TimerManager. }; } // namespace veins
7,952
32.276151
217
h
null
AICP-main/veins/src/veins/modules/world/annotations/AnnotationDummy.cc
// // Copyright (C) 2010 Christoph Sommer <christoph.sommer@informatik.uni-erlangen.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // AnnotationDummy - workaround to visualize annotations #include "veins/modules/world/annotations/AnnotationDummy.h" using veins::AnnotationDummy; Define_Module(veins::AnnotationDummy); AnnotationDummy::~AnnotationDummy() { }
1,155
33
84
cc
null
AICP-main/veins/src/veins/modules/world/annotations/AnnotationDummy.h
// // Copyright (C) 2010 Christoph Sommer <christoph.sommer@informatik.uni-erlangen.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // AnnotationDummy - workaround to visualize annotations #pragma once #include "veins/veins.h" namespace veins { /** * AnnotationDummy is just a workaround to visualize annotations * * @author Christoph Sommer */ class VEINS_API AnnotationDummy : public cSimpleModule { public: ~AnnotationDummy() override; protected: }; } // namespace veins
1,280
28.113636
84
h
null
AICP-main/veins/src/veins/modules/world/annotations/AnnotationManager.cc
// // Copyright (C) 2010 Christoph Sommer <christoph.sommer@informatik.uni-erlangen.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // AnnotationManager - manages annotations on the OMNeT++ canvas #include <sstream> #include <cmath> #include "veins/modules/world/annotations/AnnotationManager.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" Define_Module(veins::AnnotationManager); using veins::AnnotationManager; using veins::TraCIScenarioManager; using veins::TraCIScenarioManagerAccess; namespace { const short EVT_SCHEDULED_ERASE = 3; } void AnnotationManager::initialize() { scheduledEraseEvts.clear(); annotations.clear(); groups.clear(); annotationLayer = new cGroupFigure(); cCanvas* canvas = getParentModule()->getCanvas(); canvas->addFigure(annotationLayer, canvas->findFigure("submodules")); annotationsXml = par("annotations"); addFromXml(annotationsXml); } void AnnotationManager::finish() { hideAll(); } AnnotationManager::~AnnotationManager() { while (scheduledEraseEvts.begin() != scheduledEraseEvts.end()) { cancelAndDelete(*scheduledEraseEvts.begin()); scheduledEraseEvts.erase(scheduledEraseEvts.begin()); } scheduledEraseEvts.clear(); while (annotations.begin() != annotations.end()) { delete *annotations.begin(); annotations.erase(annotations.begin()); } annotations.clear(); while (groups.begin() != groups.end()) { delete *groups.begin(); groups.erase(groups.begin()); } groups.clear(); } void AnnotationManager::handleMessage(cMessage* msg) { if (msg->isSelfMessage()) { handleSelfMsg(msg); return; } throw cRuntimeError("AnnotationManager doesn't handle messages from other modules"); } void AnnotationManager::handleSelfMsg(cMessage* msg) { if (msg->getKind() == EVT_SCHEDULED_ERASE) { Annotation* a = static_cast<Annotation*>(msg->getContextPointer()); ASSERT(a); erase(a); scheduledEraseEvts.remove(msg); delete msg; return; } throw cRuntimeError("unknown self message type"); } void AnnotationManager::handleParameterChange(const char* parname) { if (parname && (std::string(parname) == "draw")) { if (par("draw")) { showAll(); } else { hideAll(); } } } /** * adds Annotations from an XML document; example below. * * ``` * <annotations> * <line color="#F00" shape="16,0 8,13.8564" /> * <poly color="#0F0" shape="16,64 8,77.8564 -8,77.8564 -16,64 -8,50.1436 8,50.1436" /> * </annotations> * ``` */ void AnnotationManager::addFromXml(cXMLElement* xml) { std::string rootTag = xml->getTagName(); ASSERT(rootTag == "annotations"); cXMLElementList list = xml->getChildren(); for (cXMLElementList::const_iterator i = list.begin(); i != list.end(); ++i) { cXMLElement* e = *i; std::string tag = e->getTagName(); if (tag == "point") { ASSERT(e->getAttribute("text")); std::string text = e->getAttribute("text"); ASSERT(e->getAttribute("color")); std::string color = e->getAttribute("color"); ASSERT(e->getAttribute("shape")); std::string shape = e->getAttribute("shape"); std::vector<std::string> points = cStringTokenizer(shape.c_str(), " ").asVector(); ASSERT(points.size() == 2); std::vector<double> p1a = cStringTokenizer(points[0].c_str(), ",").asDoubleVector(); ASSERT(p1a.size() == 2); drawPoint(Coord(p1a[0], p1a[1]), color, text); } else if (tag == "line") { ASSERT(e->getAttribute("color")); std::string color = e->getAttribute("color"); ASSERT(e->getAttribute("shape")); std::string shape = e->getAttribute("shape"); std::vector<std::string> points = cStringTokenizer(shape.c_str(), " ").asVector(); ASSERT(points.size() == 2); std::vector<double> p1a = cStringTokenizer(points[0].c_str(), ",").asDoubleVector(); ASSERT(p1a.size() == 2); std::vector<double> p2a = cStringTokenizer(points[1].c_str(), ",").asDoubleVector(); ASSERT(p2a.size() == 2); drawLine(Coord(p1a[0], p1a[1]), Coord(p2a[0], p2a[1]), color); } else if (tag == "poly") { ASSERT(e->getAttribute("color")); std::string color = e->getAttribute("color"); ASSERT(e->getAttribute("shape")); std::string shape = e->getAttribute("shape"); std::vector<std::string> points = cStringTokenizer(shape.c_str(), " ").asVector(); ASSERT(points.size() >= 2); std::vector<Coord> coords; for (std::vector<std::string>::const_iterator i = points.begin(); i != points.end(); ++i) { std::vector<double> pa = cStringTokenizer(i->c_str(), ",").asDoubleVector(); ASSERT(pa.size() == 2); coords.push_back(Coord(pa[0], pa[1])); } drawPolygon(coords, color); } else { throw cRuntimeError("while reading annotations xml: expected 'line' or 'poly', but got '%s'", tag.c_str()); } } } AnnotationManager::Group* AnnotationManager::createGroup(std::string title) { Group* group = new Group(title); groups.push_back(group); return group; } AnnotationManager::Point* AnnotationManager::drawPoint(Coord p, std::string color, std::string text, Group* group) { Point* o = new Point(p, color, text); o->group = group; annotations.push_back(o); if (par("draw")) show(o); return o; } AnnotationManager::Line* AnnotationManager::drawLine(Coord p1, Coord p2, std::string color, Group* group) { Line* l = new Line(p1, p2, color); l->group = group; annotations.push_back(l); if (par("draw")) show(l); return l; } AnnotationManager::Polygon* AnnotationManager::drawPolygon(std::list<Coord> coords, std::string color, Group* group) { Polygon* p = new Polygon(coords, color); p->group = group; annotations.push_back(p); if (par("draw")) show(p); return p; } AnnotationManager::Polygon* AnnotationManager::drawPolygon(std::vector<Coord> coords, std::string color, Group* group) { return drawPolygon(std::list<Coord>(coords.begin(), coords.end()), color, group); } void AnnotationManager::drawBubble(Coord p1, std::string text) { std::string pxOld = getDisplayString().getTagArg("p", 0); std::string pyOld = getDisplayString().getTagArg("p", 1); std::string px; { std::stringstream ss; ss << p1.x; px = ss.str(); } std::string py; { std::stringstream ss; ss << p1.x; py = ss.str(); } getDisplayString().setTagArg("p", 0, px.c_str()); getDisplayString().setTagArg("p", 1, py.c_str()); bubble(text.c_str()); getDisplayString().setTagArg("p", 0, pxOld.c_str()); getDisplayString().setTagArg("p", 1, pyOld.c_str()); } void AnnotationManager::erase(const Annotation* annotation) { hide(annotation); annotations.remove(const_cast<Annotation*>(annotation)); delete annotation; } void AnnotationManager::eraseAll(Group* group) { for (Annotations::iterator i = annotations.begin(); i != annotations.end();) { if ((!group) || ((*i)->group == group)) { erase(*i++); } else { i++; } } } void AnnotationManager::scheduleErase(simtime_t deltaT, Annotation* annotation) { Enter_Method_Silent(); cMessage* evt = new cMessage("erase", EVT_SCHEDULED_ERASE); evt->setContextPointer(annotation); scheduleAt(simTime() + deltaT, evt); scheduledEraseEvts.push_back(evt); } void AnnotationManager::show(const Annotation* annotation) { if (annotation->figure) return; if (const Point* o = dynamic_cast<const Point*>(annotation)) { if (hasGUI()) { // no corresponding TkEnv representation } TraCIScenarioManager* traci = TraCIScenarioManagerAccess().get(); if (traci && traci->isConnected()) { std::stringstream nameBuilder; nameBuilder << o->text << " " << getEnvir()->getUniqueNumber(); traci->getCommandInterface()->addPoi(nameBuilder.str(), "Annotation", TraCIColor::fromTkColor(o->color), 6, o->pos); annotation->traciPoiIds.push_back(nameBuilder.str()); } } else if (const Line* l = dynamic_cast<const Line*>(annotation)) { if (hasGUI()) { cLineFigure* figure = new cLineFigure(); figure->setStart(cFigure::Point(l->p1.x, l->p1.y)); figure->setEnd(cFigure::Point(l->p2.x, l->p2.y)); figure->setLineColor(cFigure::Color(l->color.c_str())); annotation->figure = figure; annotationLayer->addFigure(annotation->figure); } TraCIScenarioManager* traci = TraCIScenarioManagerAccess().get(); if (traci && traci->isConnected()) { std::list<Coord> coords; coords.push_back(l->p1); coords.push_back(l->p2); std::stringstream nameBuilder; nameBuilder << "Annotation" << getEnvir()->getUniqueNumber(); traci->getCommandInterface()->addPolygon(nameBuilder.str(), "Annotation", TraCIColor::fromTkColor(l->color), false, 5, coords); annotation->traciLineIds.push_back(nameBuilder.str()); } } else if (const Polygon* p = dynamic_cast<const Polygon*>(annotation)) { ASSERT(p->coords.size() >= 2); if (hasGUI()) { cPolygonFigure* figure = new cPolygonFigure(); std::vector<cFigure::Point> points; for (std::list<Coord>::const_iterator i = p->coords.begin(); i != p->coords.end(); ++i) { points.push_back(cFigure::Point(i->x, i->y)); } figure->setPoints(points); figure->setLineColor(cFigure::Color(p->color.c_str())); figure->setFilled(false); annotation->figure = figure; annotationLayer->addFigure(annotation->figure); } TraCIScenarioManager* traci = TraCIScenarioManagerAccess().get(); if (traci && traci->isConnected()) { std::stringstream nameBuilder; nameBuilder << "Annotation" << getEnvir()->getUniqueNumber(); traci->getCommandInterface()->addPolygon(nameBuilder.str(), "Annotation", TraCIColor::fromTkColor(p->color), false, 4, p->coords); annotation->traciPolygonsIds.push_back(nameBuilder.str()); } } else { throw cRuntimeError("unknown Annotation type"); } } void AnnotationManager::hide(const Annotation* annotation) { if (annotation->figure) { delete annotationLayer->removeFigure(annotation->figure); annotation->figure = nullptr; } TraCIScenarioManager* traci = TraCIScenarioManagerAccess().get(); if (traci && traci->isConnected()) { for (std::list<std::string>::const_iterator i = annotation->traciPolygonsIds.begin(); i != annotation->traciPolygonsIds.end(); ++i) { std::string id = *i; traci->getCommandInterface()->polygon(id).remove(3); } annotation->traciPolygonsIds.clear(); for (std::list<std::string>::const_iterator i = annotation->traciLineIds.begin(); i != annotation->traciLineIds.end(); ++i) { std::string id = *i; traci->getCommandInterface()->polygon(id).remove(4); } annotation->traciLineIds.clear(); for (std::list<std::string>::const_iterator i = annotation->traciPoiIds.begin(); i != annotation->traciPoiIds.end(); ++i) { std::string id = *i; traci->getCommandInterface()->poi(id).remove(5); } annotation->traciPoiIds.clear(); } } void AnnotationManager::showAll(Group* group) { for (Annotations::const_iterator i = annotations.begin(); i != annotations.end(); ++i) { if ((!group) || ((*i)->group == group)) show(*i); } } void AnnotationManager::hideAll(Group* group) { for (Annotations::const_iterator i = annotations.begin(); i != annotations.end(); ++i) { if ((!group) || ((*i)->group == group)) hide(*i); } }
13,280
31.235437
142
cc
null
AICP-main/veins/src/veins/modules/world/annotations/AnnotationManager.h
// // Copyright (C) 2010 Christoph Sommer <christoph.sommer@informatik.uni-erlangen.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // AnnotationManager - manages annotations on the OMNeT++ canvas #pragma once #include <list> #include "veins/veins.h" #include "veins/base/utils/FindModule.h" #include "veins/base/utils/Coord.h" namespace veins { /** * manages annotations on the OMNeT++ canvas. */ class VEINS_API AnnotationManager : public cSimpleModule { public: class VEINS_API Group; class VEINS_API Annotation { public: Annotation() : group(nullptr) , figure(nullptr) { } virtual ~Annotation() { } protected: friend class AnnotationManager; Group* group; mutable cFigure* figure; mutable std::list<std::string> traciPoiIds; mutable std::list<std::string> traciLineIds; mutable std::list<std::string> traciPolygonsIds; }; class VEINS_API Point : public Annotation { public: Point(Coord pos, std::string color, std::string text) : pos(pos) , color(color) , text(text) { } ~Point() override { } protected: friend class AnnotationManager; Coord pos; std::string color; std::string text; }; class VEINS_API Line : public Annotation { public: Line(Coord p1, Coord p2, std::string color) : p1(p1) , p2(p2) , color(color) { } ~Line() override { } protected: friend class AnnotationManager; Coord p1; Coord p2; std::string color; }; class VEINS_API Polygon : public Annotation { public: Polygon(std::list<Coord> coords, std::string color) : coords(coords) , color(color) { } ~Polygon() override { } protected: friend class AnnotationManager; std::list<Coord> coords; std::string color; }; class VEINS_API Group { public: Group(std::string title) : title(title) { } virtual ~Group() { } protected: friend class AnnotationManager; std::string title; }; ~AnnotationManager() override; void initialize() override; void finish() override; void handleMessage(cMessage* msg) override; void handleSelfMsg(cMessage* msg); void handleParameterChange(const char* parname) override; void addFromXml(cXMLElement* xml); Group* createGroup(std::string title = "untitled"); Point* drawPoint(Coord p, std::string color, std::string text, Group* group = nullptr); Line* drawLine(Coord p1, Coord p2, std::string color, Group* group = nullptr); Polygon* drawPolygon(std::list<Coord> coords, std::string color, Group* group = nullptr); Polygon* drawPolygon(std::vector<Coord> coords, std::string color, Group* group = nullptr); void drawBubble(Coord p1, std::string text); void erase(const Annotation* annotation); void eraseAll(Group* group = nullptr); void scheduleErase(simtime_t deltaT, Annotation* annotation); void show(const Annotation* annotation); void hide(const Annotation* annotation); void showAll(Group* group = nullptr); void hideAll(Group* group = nullptr); protected: using Annotations = std::list<Annotation*>; using Groups = std::list<Group*>; cXMLElement* annotationsXml; /**< annotations to add at startup */ std::list<cMessage*> scheduledEraseEvts; Annotations annotations; Groups groups; cGroupFigure* annotationLayer; }; class VEINS_API AnnotationManagerAccess { public: AnnotationManager* getIfExists() { return FindModule<AnnotationManager*>::findGlobalModule(); }; }; } // namespace veins
4,754
24.564516
95
h
null
AICP-main/veins/src/veins/modules/world/traci/trafficLight/TraCITrafficLightInterface.cc
// // Copyright (C) 2015-2018 Dominik Buse <dbuse@mail.uni-paderborn.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <string> #include "veins/modules/world/traci/trafficLight/TraCITrafficLightInterface.h" #include "veins/modules/messages/TraCITrafficLightMessage_m.h" using namespace veins; using veins::TraCITrafficLightInterface; using veins::TraCITrafficLightLink; using veins::TraCITrafficLightProgram; Define_Module(veins::TraCITrafficLightInterface); TraCITrafficLightInterface::TraCITrafficLightInterface() : cSimpleModule() , isPreInitialized(false) , updateInterval() , manager(nullptr) , commandInterface(nullptr) , tlCommandInterface(nullptr) , external_id("") , position() , programDefinition() , currentLogicId("") , currentPhaseNr(-1) , nextSwitchTime() , inOnlineSignalState(false) { } TraCITrafficLightInterface::~TraCITrafficLightInterface() { delete tlCommandInterface; } void TraCITrafficLightInterface::preInitialize(const std::string& external_id, const Coord& position, const simtime_t& updateInterval) { isPreInitialized = true; this->updateInterval = updateInterval; setExternalId(external_id); this->position = position; } Coord TraCITrafficLightInterface::getPosition() const { return this->position; } std::list<std::list<TraCITrafficLightLink>> TraCITrafficLightInterface::getControlledLinks() { return controlledLinks; } TraCITrafficLightProgram::Logic TraCITrafficLightInterface::getCurrentLogic() const { return programDefinition.getLogic(currentLogicId); } std::string TraCITrafficLightInterface::getCurrentLogicId() const { return currentLogicId; } int TraCITrafficLightInterface::getCurrentPhaseId() const { return currentPhaseNr; } TraCITrafficLightProgram::Phase TraCITrafficLightInterface::getCurrentPhase() const { return getCurrentLogic().phases[currentPhaseNr]; } simtime_t TraCITrafficLightInterface::getAssumedNextSwitch() const { return nextSwitchTime; } simtime_t TraCITrafficLightInterface::getRemainingDuration() const { return nextSwitchTime - simTime(); } std::string TraCITrafficLightInterface::getCurrentState() const { if (isInOnlineSignalState()) { return currentSignalState; } else { return getCurrentPhase().state; } } bool TraCITrafficLightInterface::isInOnlineSignalState() const { return inOnlineSignalState; } void TraCITrafficLightInterface::setProgramDefinition(const TraCITrafficLightProgram& programDefinition) { this->programDefinition = programDefinition; } void TraCITrafficLightInterface::setControlledLinks(const std::list<std::list<TraCITrafficLightLink>>& controlledLinks) { this->controlledLinks = controlledLinks; } void TraCITrafficLightInterface::setCurrentLogicById(const std::string& logicId, bool setSumo) { if (setSumo) { ASSERT(logicId != "online"); if (!programDefinition.hasLogic(logicId)) { throw cRuntimeError("Logic '%s' not found in program of TraCITrafficLightInterface %s", logicId.c_str(), external_id.c_str()); } tlCommandInterface->setProgram(logicId); const std::string newValueInSumo = tlCommandInterface->getCurrentProgramID(); ASSERT(newValueInSumo == logicId); } if (currentLogicId != logicId || (isInOnlineSignalState() && logicId != "online")) { sendChangeMsg(TrafficLightAtrributeType::LOGICID, logicId, currentLogicId); } if (logicId != "online") { inOnlineSignalState = false; this->currentLogicId = logicId; } } void TraCITrafficLightInterface::setCurrentPhaseByNr(const unsigned int phaseNr, bool setSumo) { if (setSumo) { if (phaseNr >= getCurrentLogic().phases.size()) { throw cRuntimeError("Cannot set current phase to %d: current logic has only %d Phases (TraCITrafficLightInterface %s)", phaseNr, getCurrentLogic().phases.size(), external_id.c_str()); } tlCommandInterface->setPhaseIndex(phaseNr); const unsigned int newValueInSumo = tlCommandInterface->getCurrentPhaseIndex(); ASSERT(newValueInSumo == phaseNr); } if (currentPhaseNr != static_cast<int>(phaseNr) || isInOnlineSignalState()) { sendChangeMsg(TrafficLightAtrributeType::PHASEID, std::to_string(phaseNr), std::to_string(currentPhaseNr)); } inOnlineSignalState = false; currentPhaseNr = phaseNr; } void TraCITrafficLightInterface::setCurrentState(const std::string& state, bool setSumo) { if (setSumo) { tlCommandInterface->setState(state); const std::string newValueInSumo = tlCommandInterface->getCurrentState(); ASSERT(newValueInSumo == state); } if (currentSignalState != state) { sendChangeMsg(TrafficLightAtrributeType::STATE, state, currentSignalState); } inOnlineSignalState = true; currentSignalState = state; } void TraCITrafficLightInterface::setNextSwitch(const simtime_t& newNextSwitch, bool setSumo) { // FIXME: not working reliably - use setRemainingDuration instead! // round to be feasible for SUMO simtime_t nextSwitch = ceil(newNextSwitch, updateInterval, 0); if (setSumo) { simtime_t remainingDuration = ceil(nextSwitch - simTime(), updateInterval, 0); if (remainingDuration < 0) { EV << "Warning: remaining duration for switch below 0: " << remainingDuration << std::endl; // maybe issue even an error if this occurs remainingDuration = 0; } getTlCommandInterface()->setPhaseDuration(remainingDuration); simtime_t newValueInSumo = tlCommandInterface->getAssumedNextSwitchTime(); ASSERT(newValueInSumo == nextSwitch); } if (nextSwitchTime != nextSwitch) { sendChangeMsg(TrafficLightAtrributeType::SWITCHTIME, std::to_string(nextSwitch.inUnit(SIMTIME_MS)), std::to_string(nextSwitchTime.inUnit(SIMTIME_MS))); } nextSwitchTime = nextSwitch; } void TraCITrafficLightInterface::setRemainingDuration(const simtime_t& rawRemainingDuration, bool setSumo) { ASSERT(rawRemainingDuration >= 0); // round (up) to match sumo time steps simtime_t veinsTimeNow(simTime()); simtime_t sumoTimeNow(ceil(veinsTimeNow, updateInterval) - updateInterval); simtime_t roundedRemainingDuration = ceil(rawRemainingDuration, updateInterval, 0); // simtime_t nextSwitchInVeins = floor(simTime() + roundedRemainingDuration, updateInterval, 0) - updateInterval; simtime_t nextSwitchInVeins = sumoTimeNow + roundedRemainingDuration; if (setSumo) { // set value to sumo getTlCommandInterface()->setPhaseDuration(roundedRemainingDuration); // check that everything is consistent simtime_t nextSwitchInSumo = tlCommandInterface->getAssumedNextSwitchTime(); ASSERT(nextSwitchInSumo == nextSwitchInVeins); } if (nextSwitchTime != nextSwitchInVeins) { sendChangeMsg(TrafficLightAtrributeType::SWITCHTIME, std::to_string(nextSwitchInVeins.inUnit(SIMTIME_MS)), std::to_string(nextSwitchTime.inUnit(SIMTIME_MS))); } nextSwitchTime = nextSwitchInVeins; } void TraCITrafficLightInterface::initialize() { ASSERT(isPreInitialized); isPreInitialized = false; setProgramDefinition(getTlCommandInterface()->getProgramDefinition()); setControlledLinks(getTlCommandInterface()->getControlledLinks()); currentLogicId = getTlCommandInterface()->getCurrentProgramID(); currentPhaseNr = getTlCommandInterface()->getCurrentPhaseIndex(); nextSwitchTime = getTlCommandInterface()->getAssumedNextSwitchTime(); currentSignalState = getTlCommandInterface()->getCurrentState(); } void TraCITrafficLightInterface::handleMessage(cMessage* msg) { if (msg->isSelfMessage()) { // not in use (yet) } else if (msg->arrivedOn("logic$i")) { handleChangeCommandMessage(msg); } delete msg; } void TraCITrafficLightInterface::handleChangeCommandMessage(cMessage* msg) { TraCITrafficLightMessage* tmMsg = check_and_cast<TraCITrafficLightMessage*>(msg); switch (tmMsg->getChangedAttribute()) { case TrafficLightAtrributeType::LOGICID: setCurrentLogicById(tmMsg->getNewValue(), true); break; case TrafficLightAtrributeType::PHASEID: setCurrentPhaseByNr(std::stoi(tmMsg->getNewValue()), true); break; case TrafficLightAtrributeType::SWITCHTIME: setNextSwitch(SimTime(std::stoi(tmMsg->getNewValue()), SIMTIME_MS), true); break; case TrafficLightAtrributeType::STATE: setCurrentState(tmMsg->getNewValue(), true); break; } } void TraCITrafficLightInterface::sendChangeMsg(int changedAttribute, const std::string newValue, const std::string oldValue) { Enter_Method_Silent(); TraCITrafficLightMessage* pMsg = new TraCITrafficLightMessage("TrafficLightChangeMessage"); pMsg->setTlId(external_id.c_str()); pMsg->setChangedAttribute(changedAttribute); pMsg->setChangeSource(TrafficLightChangeSource::SUMO); pMsg->setOldValue(oldValue.c_str()); pMsg->setNewValue(newValue.c_str()); send(pMsg, "logic$o"); }
9,949
34.663082
195
cc
null
AICP-main/veins/src/veins/modules/world/traci/trafficLight/TraCITrafficLightInterface.h
// // Copyright (C) 2015-2018 Dominik Buse <dbuse@mail.uni-paderborn.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/world/traci/trafficLight/TraCITrafficLightProgram.h" namespace veins { class VEINS_API TraCITrafficLightInterface : public cSimpleModule { public: TraCITrafficLightInterface(); ~TraCITrafficLightInterface() override; /** Set parameters for connection to TraCI */ virtual void preInitialize(const std::string& external_id, const Coord& position, const simtime_t& updateInterval); virtual void setExternalId(const std::string& external_id) { this->external_id = external_id; } virtual std::string getExternalId() const { if (external_id == "") throw cRuntimeError("TraCITrafficLightInterface::getExternalId called with no external_id set yet"); return external_id; } virtual TraCIScenarioManager* getManager() const { if (!manager) { manager = TraCIScenarioManagerAccess().get(); } return manager; } virtual TraCICommandInterface* getCommandInterface() const { if (!commandInterface) { commandInterface = getManager()->getCommandInterface(); } return commandInterface; } virtual TraCICommandInterface::Trafficlight* getTlCommandInterface() const { if (!tlCommandInterface) { tlCommandInterface = new TraCICommandInterface::Trafficlight(getCommandInterface(), external_id); } return tlCommandInterface; } virtual std::list<std::list<TraCITrafficLightLink>> getControlledLinks(); virtual Coord getPosition() const; virtual TraCITrafficLightProgram::Logic getCurrentLogic() const; virtual std::string getCurrentLogicId() const; virtual int getCurrentPhaseId() const; virtual TraCITrafficLightProgram::Phase getCurrentPhase() const; virtual simtime_t getAssumedNextSwitch() const; virtual simtime_t getRemainingDuration() const; virtual std::string getCurrentState() const; virtual bool isInOnlineSignalState() const; virtual void setProgramDefinition(const TraCITrafficLightProgram& programDefinition); virtual void setControlledLinks(const std::list<std::list<TraCITrafficLightLink>>& controlledLinks); virtual void setCurrentLogicById(const std::string& logicId, bool setSumo = true); virtual void setCurrentPhaseByNr(const unsigned int phaseNr, bool setSumo = true); virtual void setCurrentState(const std::string& state, bool setSumo = true); virtual void setNextSwitch(const simtime_t& newNextSwitch, bool setSumo = true); virtual void setRemainingDuration(const simtime_t& timeTillSwitch, bool setSumo = true); protected: void initialize() override; void handleMessage(cMessage* msg) override; virtual void handleChangeCommandMessage(cMessage* msg); virtual void sendChangeMsg(int changedAttribute, const std::string newValue, const std::string oldValue); bool isPreInitialized; /**< true if preInitialize() has been called immediately before initialize() */ simtime_t updateInterval; /**< ScenarioManager's update interval */ /** reference to the simulations ScenarioManager */ mutable TraCIScenarioManager* manager; /** reference to the simulations traffic light-specific TraCI command interface */ mutable TraCICommandInterface* commandInterface; /** reference to the simulations traffic light-specific TraCI command interface */ mutable TraCICommandInterface::Trafficlight* tlCommandInterface; std::string external_id; /**< id used on the other end of TraCI */ Coord position; /**< position of the traffic light */ TraCITrafficLightProgram programDefinition; /**< full definition of program (all logics) */ std::list<std::list<TraCITrafficLightLink>> controlledLinks; /**< controlledLinks[signal][link] */ // std::list< std::list<TraCITrafficLightLink> > controlledLanes; /**< controlledLanes[signal][link] */ std::string currentLogicId; /**< id of the currently active logic */ int currentPhaseNr; /**< current phase of the current program */ simtime_t nextSwitchTime; /**< predicted next phase switch time (absolute timestamp) */ std::string currentSignalState; /**< current state of the signals (rRgGyY-String) */ bool inOnlineSignalState; /**< whether the TLS is currently set to a manual (i.e. online) phase state */ }; } // namespace veins namespace veins { class VEINS_API TraCITrafficLightInterfaceAccess { public: TraCITrafficLightInterface* get(cModule* host) { TraCITrafficLightInterface* traci = FindModule<TraCITrafficLightInterface*>::findSubModule(host); ASSERT(traci); return traci; }; }; } // namespace veins
5,743
42.515152
131
h