diff --git a/jdeeco-simulation-demo/mixim/src/base/modules/BaseModule.h b/jdeeco-simulation-demo/mixim/src/base/modules/BaseModule.h deleted file mode 100644 index 49485f157..000000000 --- a/jdeeco-simulation-demo/mixim/src/base/modules/BaseModule.h +++ /dev/null @@ -1,169 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * file: BaseModule.h - * - * author: Steffen Sroka - * Andreas Koepke - * - * copyright: (C) 2004 Telecommunication Networks Group (TKN) at - * Technische Universitaet Berlin, Germany. - * - * 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. - * For further information see file COPYING - * in the top level directory - *************************************************************************** - * part of: framework implementation developed by tkn - **************************************************************************/ - -#ifndef BASE_MODULE_H -#define BASE_MODULE_H - -#include -#include - -#include "MiXiMDefs.h" -#include "HostState.h" - -#ifndef debugEV -#define debugEV_clear (ev.isDisabled()||!debug) ? ev : ev -#define debugEV (ev.isDisabled()||!debug) ? ev : ev << logName() << "::" << getClassName() << ": " -#endif - -#ifndef coreEV -#define coreEV_clear (ev.isDisabled()||!coreDebug) ? ev : ev -#define coreEV (ev.isDisabled()||!coreDebug) ? ev : ev << logName() << "::" << getClassName() <<": " -#endif - -/** - * @brief Base class for all simple modules of a host. - * - * This method raises - * an error if the host state changes to something else than ACTIVE. - * Therefore that a sub-classing module can be used in a simulation - * where the host state can change it has to override that method - * which forces the author to make sure the module reacts well to - * host state changes. - * Alternatively one can also set a "notAffectedByHostState" parameter - * of the module to true. - * - * The base module additionally provides a function findHost which - * returns a pointer to the host module and a function hostIndex to - * return the index of the host module. The latter one correspondes to - * the index shown in tkenv and comes in very handy for testing and - * debugging using tkenv. It is used e.g. in all the 'print' macros - * used for debugging. - * - * There will never be a stand-alone BaseModule module. - * - * Note: most modules wont derive from BaseModule directly but from - * its sub class "MiximBatteryAccess" which extends BaseModule by several - * methods for accessing the battery module. - * - * @see MiximBatteryAccess - * - * @ingroup baseModules - * - * @author Steffen Sroka - * @author Andreas Koepke - */ -class MIXIM_API BaseModule: public cSimpleModule, public cListener { - protected: - /** @brief Debug switch for all other modules*/ - bool debug; - - /** @brief Stores if this module is affected by changes in the - * hosts state. If not explicitly set this module has to capture - * changes in the host state.*/ - bool notAffectedByHostState; - - /** @brief Stores the category of the HostState*/ - const static simsignalwrap_t catHostStateSignal; -protected: - - /** - * @brief Called whenever the hosts state changes. - * - * Default implementation of this method throws an error whenever the host - * state changes and the "notAffectedbyHostState" variable is not explicitly - * set. This is because every module of a host has to make sure to react - * well to changes in the host state. Or it has to explicitly set its - * parameter "notAffectedbyHostState" to true. - */ - virtual void handleHostState(const HostState& state); - - /** - * @brief Switches the host to the passed state. - * - * If the hosts state is switched to anything else than "ACTIVE" every - * module of the host has to handle this explicitly (see method - * "handleHostState()")! - */ - void switchHostState(HostState::States state); - - /** @brief Function to get a pointer to the host module*/ - cModule* findHost(void); - const cModule* findHost(void) const; - /** @brief Function to get the logging name of id*/ - //std::string getLogName(int); - -private: - /** @brief Copy constructor is not allowed. - */ - BaseModule(const BaseModule&); - /** @brief Assignment operator is not allowed. - */ - BaseModule& operator=(const BaseModule&); - - public: - - BaseModule(); - BaseModule(unsigned stacksize); - - /** @brief Basic initialization for all modules */ - virtual void initialize(int); - - /** - * @brief Divide initialization into two stages - * - * In the first stage (stage==0), modules subscribe to notification. - * The first notifications (e.g. about the initial - * values of some variables such as RadioState) should take place earliest - * in the second stage (stage==1), when everyone interested in them has - * already subscribed. - * Further one should try to keep calls to other modules out of stage 0 to - * assure that the other module had at least once the chance to initialize - * itself in stage 0. - */ - virtual int numInitStages() const { - return 2; - } - - /** - * @brief Function to get the logging name of the host - * - * The logging name is the ned module name of the host (unless the - * host ned variable loggingName is specified). It can be used for - * logging messages to simplify debugging in TKEnv. - */ - std::string logName(void) const ; - - /** - * @brief Get a reference to the local node module - */ - const cModule* getNode() const { - return findHost(); - } - - /** - * @brief Called by the signaling mechanism whenever a change of a category occurs - * to which we have subscribed. - * In this base class just handle the host state switching and - * some debug notifications - */ - virtual void receiveSignal(cComponent *source, simsignal_t signalID, cObject *obj); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/base/phyLayer/BasePhyLayer.cc b/jdeeco-simulation-demo/mixim/src/base/phyLayer/BasePhyLayer.cc deleted file mode 100644 index 01ccea8b7..000000000 --- a/jdeeco-simulation-demo/mixim/src/base/phyLayer/BasePhyLayer.cc +++ /dev/null @@ -1,905 +0,0 @@ -#include "BasePhyLayer.h" - -#include -#include - -#include "MacToPhyControlInfo.h" -#include "PhyToMacControlInfo.h" -#include "FindModule.h" -#include "AnalogueModel.h" -#include "Decider.h" -#include "BaseWorldUtility.h" -#include "BaseConnectionManager.h" - -//introduce BasePhyLayer as module to OMNet -Define_Module(BasePhyLayer); - -short BasePhyLayer::airFramePriority = 10; - -Coord NoMobiltyPos = Coord::ZERO; - -template -static inline bool isFiniteNumber(register _Tp value) { - return value < std::numeric_limits<_Tp>::infinity() && value > -std::numeric_limits<_Tp>::infinity() && value != std::numeric_limits<_Tp>::quiet_NaN(); -} - -//--Initialization---------------------------------- - -BasePhyLayer::BasePhyLayer() - : ConnectionManagerAccess() - , DeciderToPhyInterface() - , MacToPhyInterface() - , protocolId(GENERIC) - , thermalNoise(NULL) - , maxTXPower(0) - , sensitivity(0) - , recordStats(false) - , channelInfo() - , radio(NULL) - , decider(NULL) - , analogueModels() - , upperLayerIn(-1) - , upperLayerOut(-1) - , upperControlOut(-1) - , upperControlIn(-1) - , radioSwitchingOverTimer(NULL) - , txOverTimer(NULL) - , headerLength(-1) - , world(NULL) -{} - -template T BasePhyLayer::readPar(const char* parName, const T defaultValue) const { - if(hasPar(parName)) - return par(parName); - return defaultValue; -} - -// the following line is needed to allow linking when compiled in RELEASE mode. -// Add a declaration for each parameterization of the template used in -// code to be linked, e.g. in modules or in examples, if it is not already -// used in base (double and simtime_t). Needed with (at least): gcc 4.4.1. -template int BasePhyLayer::readPar(const char* parName, const int) const; -template double BasePhyLayer::readPar(const char* parName, const double) const; -template<> simtime_t BasePhyLayer::readPar(const char* parName, const simtime_t defaultValue) const { - if(hasPar(parName)) - return simtime_t( par(parName).doubleValue() ); - return defaultValue; -} -template bool BasePhyLayer::readPar(const char* parName, const bool) const; - -void BasePhyLayer::initialize(int stage) { - - ConnectionManagerAccess::initialize(stage); - - if (stage == 0) { - // if using sendDirect, make sure that messages arrive without delay - gate("radioIn")->setDeliverOnReceptionStart(true); - - //get gate ids - upperLayerIn = findGate("upperLayerIn"); - upperLayerOut = findGate("upperLayerOut"); - upperControlOut = findGate("upperControlOut"); - upperControlIn = findGate("upperControlIn"); - - //read simple ned-parameters - // - initialize basic parameters - if(par("useThermalNoise").boolValue()) { - double thermalNoiseVal = FWMath::dBm2mW(par("thermalNoise").doubleValue()); - thermalNoise = new ConstantSimpleConstMapping(DimensionSet::timeDomain, - thermalNoiseVal); - } else { - thermalNoise = 0; - } - headerLength = par("headerLength").longValue(); - sensitivity = par("sensitivity").doubleValue(); - if (!isFiniteNumber(sensitivity) || sensitivity <= -999999) - sensitivity = 0; // disabled - else - sensitivity = FWMath::dBm2mW(sensitivity); - if (!isFiniteNumber(sensitivity)) - sensitivity = 0; // disabled - maxTXPower = par("maxTXPower").doubleValue(); - - recordStats = par("recordStats").boolValue(); - - // - initialize radio - radio = initializeRadio(); - - // get pointer to the world module - world = FindModule::findGlobalModule(); - if (world == NULL) { - opp_error("Could not find BaseWorldUtility module"); - } - - if(cc->hasPar("sat") - && (sensitivity - FWMath::dBm2mW(cc->par("sat").doubleValue())) < -0.000001) { - opp_error("Sensitivity can't be smaller than the " - "signal attenuation threshold (sat) in ConnectionManager. " - "Please adjust your omnetpp.ini file accordingly."); - } - -// } else if (stage == 1){ - //read complex(xml) ned-parameters - // - analogue model parameters - initializeAnalogueModels(par("analogueModels").xmlValue()); - // - decider parameters - initializeDecider(par("decider").xmlValue()); - - //initialise timer messages - radioSwitchingOverTimer = new cMessage("radio switching over", RADIO_SWITCHING_OVER); - txOverTimer = new cMessage("transmission over", TX_OVER); - - } -} - -MiximRadio* BasePhyLayer::initializeRadio() const { - int initialRadioState = par("initialRadioState").longValue(); - double radioMinAtt = par("radioMinAtt").doubleValue(); - double radioMaxAtt = par("radioMaxAtt").doubleValue(); - int nbRadioChannels = readPar("nbRadioChannels", 1); - int initialRadioChannel = readPar("initialRadioChannel", 0); - - MiximRadio* radio = MiximRadio::createNewRadio(recordStats, initialRadioState, - radioMinAtt, radioMaxAtt, - initialRadioChannel, nbRadioChannels); - - // - switch times to TX - //if no RX to TX defined asume same time as sleep to TX - radio->setSwitchTime(MiximRadio::RX, MiximRadio::TX, (hasPar("timeRXToTX") ? par("timeRXToTX") : par("timeSleepToTX")).doubleValue()); - //if no sleep to TX defined asume same time as RX to TX - radio->setSwitchTime(MiximRadio::SLEEP, MiximRadio::TX, (hasPar("timeSleepToTX") ? par("timeSleepToTX") : par("timeRXToTX")).doubleValue()); - - // - switch times to RX - //if no TX to RX defined asume same time as sleep to RX - radio->setSwitchTime(MiximRadio::TX, MiximRadio::RX, (hasPar("timeTXToRX") ? par("timeTXToRX") : par("timeSleepToRX")).doubleValue()); - //if no sleep to RX defined asume same time as TX to RX - radio->setSwitchTime(MiximRadio::SLEEP, MiximRadio::RX, (hasPar("timeSleepToRX") ? par("timeSleepToRX") : par("timeTXToRX")).doubleValue()); - - // - switch times to sleep - //if no TX to sleep defined asume same time as RX to sleep - radio->setSwitchTime(MiximRadio::TX, MiximRadio::SLEEP, (hasPar("timeTXToSleep") ? par("timeTXToSleep") : par("timeRXToSleep")).doubleValue()); - //if no RX to sleep defined asume same time as TX to sleep - radio->setSwitchTime(MiximRadio::RX, MiximRadio::SLEEP, (hasPar("timeRXToSleep") ? par("timeRXToSleep") : par("timeTXToSleep")).doubleValue()); - - return radio; -} - -void BasePhyLayer::getParametersFromXML(cXMLElement* xmlData, ParameterMap& outputMap) const { - cXMLElementList parameters = xmlData->getElementsByTagName("Parameter"); - - for(cXMLElementList::const_iterator it = parameters.begin(); - it != parameters.end(); it++) { - - const char* name = (*it)->getAttribute("name"); - const char* type = (*it)->getAttribute("type"); - const char* value = (*it)->getAttribute("value"); - if(name == 0 || type == 0 || value == 0) { - ev << "Invalid parameter, could not find name, type or value." << endl; - continue; - } - - std::string sType = type; //needed for easier comparision - std::string sValue = value; //needed for easier comparision - - cMsgPar param(name); - - //parse type of parameter and set value - if (sType == "bool") { - param.setBoolValue(sValue == "true" || sValue == "1"); - - } else if (sType == "double") { - param.setDoubleValue(strtod(value, 0)); - - } else if (sType == "string") { - param.setStringValue(value); - - } else if (sType == "long") { - param.setLongValue(strtol(value, 0, 0)); - - } else { - ev << "Unknown parameter type: \"" << sType << "\"" << endl; - continue; - } - - //add parameter to output map - outputMap[name] = param; - } -} - -void BasePhyLayer::finish(){ - // give decider the chance to do something - decider->finish(); -} - -//-----Decider initialization---------------------- - - -void BasePhyLayer::initializeDecider(cXMLElement* xmlConfig) { - - decider = NULL; - - if(xmlConfig == NULL) { - opp_error("No decider configuration file specified."); - return; - } - - cXMLElementList deciderList = xmlConfig->getElementsByTagName("Decider"); - - if(deciderList.empty()) { - opp_error("No decider configuration found in configuration file."); - return; - } - - if(deciderList.size() > 1) { - opp_error("More than one decider configuration found in configuration file."); - return; - } - - cXMLElement* deciderData = deciderList.front(); - - const char* name = deciderData->getAttribute("type"); - - if(name == NULL) { - opp_error("Could not read type of decider from configuration file."); - return; - } - - ParameterMap params; - getParametersFromXML(deciderData, params); - - decider = getDeciderFromName(name, params); - - if(decider == NULL) { - opp_error("Could not find a decider with the name \"%s\".", name); - return; - } - - coreEV << "Decider \"" << name << "\" loaded." << endl; -} - -Decider* BasePhyLayer::getDeciderFromName(const std::string& /*name*/, ParameterMap& /*params*/) -{ - return NULL; -} - - -//-----AnalogueModels initialization---------------- - -void BasePhyLayer::initializeAnalogueModels(cXMLElement* xmlConfig) { - - /* - * first of all, attach the AnalogueModel that represents the RadioState - * to the AnalogueModelList as first element. - */ - - std::string s("RadioStateAnalogueModel"); - ParameterMap p; - - AnalogueModel* newAnalogueModel = getAnalogueModelFromName(s, p); - - if(newAnalogueModel == 0) - { - opp_warning("Could not find an analogue model with the name \"%s\".", s.c_str()); - } - else - { - analogueModels.push_back(newAnalogueModel); - } - - - if(xmlConfig == 0) { - opp_warning("No analogue models configuration file specified."); - return; - } - - cXMLElementList analogueModelList = xmlConfig->getElementsByTagName("AnalogueModel"); - - if(analogueModelList.empty()) { - opp_warning("No analogue models configuration found in configuration file."); - return; - } - - // iterate over all AnalogueModel-entries, get a new AnalogueModel instance and add - // it to analogueModels - for(cXMLElementList::const_iterator it = analogueModelList.begin(); - it != analogueModelList.end(); it++) { - - - cXMLElement* analogueModelData = *it; - - const char* name = analogueModelData->getAttribute("type"); - - if(name == 0) { - opp_warning("Could not read name of analogue model."); - continue; - } - - ParameterMap params; - getParametersFromXML(analogueModelData, params); - - AnalogueModel* newAnalogueModel = getAnalogueModelFromName(name, params); - - if(newAnalogueModel == 0) { - opp_warning("Could not find an analogue model with the name \"%s\".", name); - continue; - } - - // attach the new AnalogueModel to the AnalogueModelList - analogueModels.push_back(newAnalogueModel); - - coreEV << "AnalogueModel \"" << name << "\" loaded." << endl; - - } // end iterator loop - - -} - -AnalogueModel* BasePhyLayer::getAnalogueModelFromName(const std::string& name, ParameterMap& /*params*/) const { - - // add default analogue models here - - // case "RSAM", pointer is valid as long as the radio exists - if (name == "RadioStateAnalogueModel") { - return radio->getAnalogueModel(); - } - - return NULL; -} - -//--Message handling-------------------------------------- - -void BasePhyLayer::handleMessage(cMessage* msg) { - - //self messages - if(msg->isSelfMessage()) { - handleSelfMessage(msg); - - //MacPkts <- MacToPhyControlInfo - } else if(msg->getArrivalGateId() == upperLayerIn) { - handleUpperMessage(msg); - - //controlmessages - } else if(msg->getArrivalGateId() == upperControlIn) { - handleUpperControlMessage(msg); - - //AirFrames - } else if(msg->getKind() == AIR_FRAME){ - handleAirFrame(static_cast(msg)); - - //unknown message - } else { - ev << "Unknown message received." << endl; - delete msg; - } -} - -void BasePhyLayer::handleAirFrame(airframe_ptr_t frame) { - //TODO: ask jerome to set air frame priority in his UWBIRPhy - //assert(frame->getSchedulingPriority() == airFramePriority); - - switch(frame->getState()) { - case START_RECEIVE: - handleAirFrameStartReceive(frame); - break; - - case RECEIVING: { - handleAirFrameReceiving(frame); - break; - } - case END_RECEIVE: - handleAirFrameEndReceive(frame); - break; - - default: - opp_error( "Unknown AirFrame state: %s", frame->getState()); - break; - } -} - -void BasePhyLayer::handleAirFrameStartReceive(airframe_ptr_t frame) { - coreEV << "Received new AirFrame " << frame << " from channel " << frame->getChannel() << "." << endl; - - if(channelInfo.isChannelEmpty()) { - radio->setTrackingModeTo(true); - } - - channelInfo.addAirFrame(frame, simTime()); - assert(!channelInfo.isChannelEmpty()); - - if(usePropagationDelay) { - Signal& s = frame->getSignal(); - simtime_t delay = simTime() - s.getSendingStart(); - s.setPropagationDelay(delay); - } - assert(frame->getSignal().getReceptionStart() == simTime()); - - frame->getSignal().setReceptionSenderInfo(frame); - filterSignal(frame); - - if(decider && isKnownProtocolId(frame->getProtocolId())) { - frame->setState(RECEIVING); - - //pass the AirFrame the first time to the Decider - handleAirFrameReceiving(frame); - - //if no decider is defined we will schedule the message directly to its end - } else { - Signal& signal = frame->getSignal(); - - simtime_t signalEndTime = signal.getReceptionStart() + frame->getDuration(); - frame->setState(END_RECEIVE); - - sendSelfMessage(frame, signalEndTime); - } -} - -void BasePhyLayer::handleAirFrameReceiving(airframe_ptr_t frame) { - - Signal& FrameSignal = frame->getSignal(); - simtime_t nextHandleTime = decider->processSignal(frame); - simtime_t signalEndTime = FrameSignal.getReceptionEnd(); - - assert(FrameSignal.getDuration() == frame->getDuration()); - - //check if this is the end of the receiving process - if(simTime() >= signalEndTime) { - frame->setState(END_RECEIVE); - handleAirFrameEndReceive(frame); - return; - } - - //smaller zero means don't give it to me again - if(nextHandleTime < SIMTIME_ZERO) { - nextHandleTime = signalEndTime; - frame->setState(END_RECEIVE); - - //invalid point in time - } else if(nextHandleTime < simTime() || nextHandleTime > signalEndTime) { - opp_error("Invalid next handle time returned by Decider. Expected a value between current simulation time (%s) and end of signal (%s) but got %s", - SIMTIME_STR(simTime()), SIMTIME_STR(signalEndTime), SIMTIME_STR(nextHandleTime)); - } - - coreEV << "Handed AirFrame with ID " << frame->getId() << " to Decider. Next handling in " << (nextHandleTime - simTime()) << "s." << endl; - - sendSelfMessage(frame, nextHandleTime); -} - -void BasePhyLayer::handleAirFrameEndReceive(airframe_ptr_t frame) -{ - coreEV << "End of Airframe with ID " << frame->getId() << "." << endl; - - simtime_t earliestInfoPoint = channelInfo.removeAirFrame(frame); - - /* clean information in the radio until earliest time-point - * of information in the ChannelInfo, - * since this time-point might have changed due to removal of - * the AirFrame - */ - if(channelInfo.isChannelEmpty()) { - earliestInfoPoint = simTime(); - radio->setTrackingModeTo(false); - } - - radio->cleanAnalogueModelUntil(earliestInfoPoint); -} - -void BasePhyLayer::handleUpperMessage(cMessage* msg){ - - // check if Radio is in TX state - if (radio->getCurrentState() != MiximRadio::TX) - { - delete msg; - msg = 0; - opp_error("Error: message for sending received, but radio not in state TX"); - } - - // check if not already sending - if(txOverTimer->isScheduled()) - { - delete msg; - msg = 0; - opp_error("Error: message for sending received, but radio already sending"); - } - - // build the AirFrame to send - assert(dynamic_cast(msg) != 0); - - airframe_ptr_t frame = encapsMsg(static_cast(msg)); - - // make sure there is no self message of kind TX_OVER scheduled - // and schedule the actual one - assert (!txOverTimer->isScheduled()); - sendSelfMessage(txOverTimer, simTime() + frame->getDuration()); - - sendMessageDown(frame); -} - -BasePhyLayer::airframe_ptr_t BasePhyLayer::encapsMsg(cPacket *macPkt) -{ - // the cMessage passed must be a MacPacket... but no cast needed here - // MacPkt* pkt = static_cast(msg); - - // ...and must always have a ControlInfo attached (contains Signal) - cObject* ctrlInfo = macPkt->removeControlInfo(); - assert(ctrlInfo); - - // create the new AirFrame - airframe_ptr_t frame = new MiximAirFrame(macPkt->getName(), AIR_FRAME); - - // Retrieve the pointer to the Signal-instance from the ControlInfo-instance. - // We are now the new owner of this instance. - Signal* s = MacToPhyControlInfo::getSignalFromControlInfo(ctrlInfo); - // make sure we really obtained a pointer to an instance - assert(s); - - // set the members - assert(s->getDuration() > 0); - frame->setDuration(s->getDuration()); - // copy the signal into the AirFrame - frame->setSignal(*s); - //set priority of AirFrames above the normal priority to ensure - //channel consistency (before any thing else happens at a time - //point t make sure that the channel has removed every AirFrame - //ended at t and added every AirFrame started at t) - frame->setSchedulingPriority(airFramePriority); - frame->setProtocolId(myProtocolId()); - frame->setBitLength(headerLength); - frame->setId(world->getUniqueAirFrameId()); - frame->setChannel(radio->getCurrentChannel()); - - // pointer and Signal not needed anymore - delete s; - s = 0; - - // delete the Control info - delete ctrlInfo; - ctrlInfo = 0; - - frame->encapsulate(macPkt); - - // --- from here on, the AirFrame is the owner of the MacPacket --- - macPkt = 0; - coreEV <<"AirFrame encapsulated, length: " << frame->getBitLength() << "\n"; - - return frame; -} - -void BasePhyLayer::handleChannelSenseRequest(cMessage* msg) { - ChannelSenseRequest* senseReq = static_cast(msg); - - simtime_t nextHandleTime = decider->handleChannelSenseRequest(senseReq); - - if(nextHandleTime >= simTime()) { //schedule request for next handling - sendSelfMessage(msg, nextHandleTime); - - //don't throw away any AirFrames while ChannelSenseRequest is active - if(!channelInfo.isRecording()) { - channelInfo.startRecording(simTime()); - } - } else if(nextHandleTime >= SIMTIME_ZERO){ - opp_error("Next handle time of ChannelSenseRequest returned by the Decider is smaller then current simulation time: %.2f", - SIMTIME_DBL(nextHandleTime)); - } - - // else, i.e. nextHandleTime < 0.0, the Decider doesn't want to handle - // the request again -} - -void BasePhyLayer::handleUpperControlMessage(cMessage* msg){ - - switch(msg->getKind()) { - case CHANNEL_SENSE_REQUEST: - handleChannelSenseRequest(msg); - break; - default: - ev << "Received unknown control message from upper layer!" << endl; - break; - } -} - -void BasePhyLayer::handleSelfMessage(cMessage* msg) { - - switch(msg->getKind()) { - //transmission over - case TX_OVER: - assert(msg == txOverTimer); - sendControlMsgToMac(new cMessage("Transmission over", TX_OVER)); - break; - - //radio switch over - case RADIO_SWITCHING_OVER: - assert(msg == radioSwitchingOverTimer); - finishRadioSwitching(); - break; - - //AirFrame - case AIR_FRAME: - handleAirFrame(static_cast(msg)); - break; - - //ChannelSenseRequest - case CHANNEL_SENSE_REQUEST: - handleChannelSenseRequest(msg); - break; - - default: - break; - } -} - -//--Send messages------------------------------ - -void BasePhyLayer::sendControlMessageUp(cMessage* msg) { - send(msg, upperControlOut); -} - -void BasePhyLayer::sendMacPktUp(cMessage* pkt) { - send(pkt, upperLayerOut); -} - -void BasePhyLayer::sendMessageDown(airframe_ptr_t msg) { - sendToChannel(msg); -} - -void BasePhyLayer::sendSelfMessage(cMessage* msg, simtime_t_cref time) { - //TODO: maybe delete this method because it doesn't makes much sense, - // or change it to "scheduleIn(msg, timeDelta)" which schedules - // a message to +timeDelta from current time - scheduleAt(time, msg); -} - - -void BasePhyLayer::filterSignal(airframe_ptr_t frame) { - if (analogueModels.empty()) - return; - - ConnectionManagerAccess *const senderModule = dynamic_cast(frame->getSenderModule()); - ConnectionManagerAccess *const receiverModule = dynamic_cast(frame->getArrivalModule()); - //const simtime_t sStart = frame->getSignal().getReceptionStart(); - - assert(senderModule); assert(receiverModule); - - /** claim the Move pattern of the sender from the Signal */ - ChannelMobilityPtrType sendersMobility = senderModule ? senderModule->getMobilityModule() : NULL; - ChannelMobilityPtrType receiverMobility = receiverModule ? receiverModule->getMobilityModule() : NULL; - - const Coord sendersPos = sendersMobility ? sendersMobility->getCurrentPosition(/*sStart*/) : NoMobiltyPos; - const Coord receiverPos = receiverMobility ? receiverMobility->getCurrentPosition(/*sStart*/): NoMobiltyPos; - - for(AnalogueModelList::const_iterator it = analogueModels.begin(); it != analogueModels.end(); ++it) - (*it)->filterSignal(frame, sendersPos, receiverPos); -} - -//--Destruction-------------------------------- - -BasePhyLayer::~BasePhyLayer() { - //get AirFrames from ChannelInfo and delete - //(although ChannelInfo normally owns the AirFrames it - //is not able to cancel and delete them itself - AirFrameVector channel; - channelInfo.getAirFrames(0, simTime(), channel); - - for(AirFrameVector::iterator it = channel.begin(); - it != channel.end(); ++it) - { - cancelAndDelete(*it); - } - - //free timer messages - if(txOverTimer) { - cancelAndDelete(txOverTimer); - } - if(radioSwitchingOverTimer) { - cancelAndDelete(radioSwitchingOverTimer); - } - - //free thermal noise mapping - if(thermalNoise) { - delete thermalNoise; - } - - //free Decider - if(decider != 0) { - delete decider; - } - - /* - * get a pointer to the radios RSAM again to avoid deleting it, - * it is not created by calling new (BasePhyLayer is not the owner)! - */ - AnalogueModel* rsamPointer = radio ? radio->getAnalogueModel() : NULL; - - //free AnalogueModels - for(AnalogueModelList::const_iterator it = analogueModels.begin(); - it != analogueModels.end(); ++it) { - - AnalogueModelList::value_type tmp = *it; - - // do not delete the RSAM, it's not allocated by new! - if (tmp == rsamPointer) { - rsamPointer = 0; - continue; - } - - if(tmp != 0) { - delete tmp; - } - } - - - // free radio - if(radio != 0) { - delete radio; - } -} - -//--MacToPhyInterface implementation----------------------- - -int BasePhyLayer::getRadioState() const { - Enter_Method_Silent(); - assert(radio); - return radio->getCurrentState(); -} - -/** - * @brief Returns the true if the radio is in RX state. - */ -bool BasePhyLayer::isRadioInRX() const { - return getRadioState() == MiximRadio::RX; -} - -void BasePhyLayer::finishRadioSwitching(bool bSendCtrlMsg /*= true*/) -{ - radio->endSwitch(simTime()); - if (bSendCtrlMsg) { - sendControlMsgToMac(new cMessage("Radio switching over", RADIO_SWITCHING_OVER)); - } -} - -simtime_t BasePhyLayer::setRadioState(int rs) { - Enter_Method_Silent(); - assert(radio); - - if(txOverTimer && txOverTimer->isScheduled()) { - opp_warning("Switched radio while sending an AirFrame. The effects this would have on the transmission are not simulated by the BasePhyLayer!"); - } - - simtime_t switchTime = radio->switchTo(rs, simTime()); - - //invalid switch time, we are probably already switching - if(switchTime < SIMTIME_ZERO) - return switchTime; - - // if switching is done in exactly zero-time no extra self-message is scheduled - if (switchTime == SIMTIME_ZERO) { - // In case of zero-time-switch, send no control-message to MAC! - finishRadioSwitching(false); - } - else { - sendSelfMessage(radioSwitchingOverTimer, simTime() + switchTime); - } - - return switchTime; -} - -ChannelState BasePhyLayer::getChannelState() const { - Enter_Method_Silent(); - assert(decider); - return decider->getChannelState(); -} - -long BasePhyLayer::getPhyHeaderLength() const { - Enter_Method_Silent(); - if (headerLength < 0) - return par("headerLength").longValue(); - return headerLength; -} - -void BasePhyLayer::setCurrentRadioChannel(int newRadioChannel) { - if (newRadioChannel == getCurrentRadioChannel()) - return; - - if(txOverTimer && txOverTimer->isScheduled()) { - opp_warning("Switched channel while sending an AirFrame. The effects this would have on the transmission are not simulated by the BasePhyLayer!"); - } - - radio->setCurrentChannel(newRadioChannel); - decider->channelChanged(newRadioChannel); - coreEV << "Switched radio to channel " << newRadioChannel << endl; -} - -int BasePhyLayer::getCurrentRadioChannel() const { - return radio->getCurrentChannel(); -} - -int BasePhyLayer::getNbRadioChannels() const { - return radio->getNbChannels(); -} - -//--DeciderToPhyInterface implementation------------ - -void BasePhyLayer::getChannelInfo(simtime_t_cref from, simtime_t_cref to, AirFrameVector& out) const { - if (getNbRadioChannels() < 2) { - channelInfo.getAirFrames(from, to, out); - } - else { - // here we filter out all air frames which are not on current channel - struct airframe_filter_channel_fctr : public ChannelInfo::airframe_filter_fctr { - int iChNum; - - airframe_filter_channel_fctr(int chNum) : ChannelInfo::airframe_filter_fctr(), iChNum(chNum) - {} - - virtual bool pass(const ChannelInfo::airframe_ptr_t& a) const { - return a->getChannel() == iChNum; - } - }; - - airframe_filter_channel_fctr fctrFilterChannel(getCurrentRadioChannel()); - channelInfo.getAirFrames(from, to, out, &fctrFilterChannel); - } -} - -ConstMapping* BasePhyLayer::getThermalNoise(simtime_t_cref from, simtime_t_cref /*to*/) { - if(thermalNoise) - thermalNoise->initializeArguments(Argument(from)); - - return thermalNoise; -} - -void BasePhyLayer::sendControlMsgToMac(cMessage* msg) { - if(msg->getKind() == CHANNEL_SENSE_REQUEST) { - if(channelInfo.isRecording()) { - channelInfo.stopRecording(); - } - } - sendControlMessageUp(msg); -} - -void BasePhyLayer::sendUp(airframe_ptr_t frame, DeciderResult* result) { - - coreEV << "Decapsulating MacPacket from Airframe with ID " << frame->getId() << " and sending it up to MAC." << endl; - - cMessage* packet = frame->decapsulate(); - - assert(packet); - - setUpControlInfo(packet, result); - - sendMacPktUp(packet); -} - -simtime_t BasePhyLayer::getSimTime() const { - - return simTime(); -} - -void BasePhyLayer::cancelScheduledMessage(cMessage* msg) { - if(msg->isScheduled()){ - cancelEvent(msg); - } else { - EV << "Warning: Decider wanted to cancel a scheduled message but message" - << " wasn't actually scheduled. Message is: " << msg << endl; - } -} - -void BasePhyLayer::rescheduleMessage(cMessage* msg, simtime_t_cref t) { - cancelScheduledMessage(msg); - scheduleAt(t, msg); -} - -void BasePhyLayer::drawCurrent(double amount, int activity) { - MiximBatteryAccess::drawCurrent(amount, activity); -} - -void BasePhyLayer::recordScalar(const char *name, double value, const char *unit) { - ConnectionManagerAccess::recordScalar(name, value, unit); -} - -/** - * Attaches a "control info" (PhyToMac) structure (object) to the message pMsg. - */ -cObject* BasePhyLayer::setUpControlInfo(cMessage *const pMsg, DeciderResult *const pDeciderResult) -{ - return PhyToMacControlInfo::setControlInfo(pMsg, pDeciderResult); -} diff --git a/jdeeco-simulation-demo/mixim/src/base/phyLayer/BasePhyLayer.h b/jdeeco-simulation-demo/mixim/src/base/phyLayer/BasePhyLayer.h deleted file mode 100644 index e0bcbf134..000000000 --- a/jdeeco-simulation-demo/mixim/src/base/phyLayer/BasePhyLayer.h +++ /dev/null @@ -1,604 +0,0 @@ -#ifndef BASEPHYLAYER_ -#define BASEPHYLAYER_ - -#include -#include -#include - -#include "MiXiMDefs.h" -#include "connectionManager/ConnectionManagerAccess.h" -#include "DeciderToPhyInterface.h" -#include "MacToPhyInterface.h" - -#include "ChannelInfo.h" - -class AnalogueModel; -class Decider; -class BaseWorldUtility; -class cXMLElement; - -/** - * @brief The BasePhyLayer represents the physical layer of a nic. - * - * The BasePhyLayer is directly connected to the mac layer via - * OMNeT channels and is able to send messages to other physical - * layers through sub-classing from ChannelAcces. - * - * The BasePhyLayer encapsulates two sub modules. - * The AnalogueModels, which are responsible for simulating - * the attenuation of received signals and the Decider which - * provides the main functionality of the physical layer like - * signal classification (noise or not noise) and demodulation - * (calculating transmission errors). - * - * The BasePhyLayer itself is responsible for the OMNeT - * depended parts of the physical layer which are the following: - * - * Module initialization: - * - read ned-parameters and initialize module, Decider and - * AnalogueModels. - * - * Message handling: - * - receive messages from mac layer and hand them to the Decider - * or directly send them to the channel - * - receive AirFrames from the channel, hand them to the - * AnalogueModels for filtering, simulate delay and transmission - * duration, hand it to the Decider for evaluation and send - * received packets to the mac layer - * - keep track of currently active AirFrames on the channel - * (see ChannelInfo) - * - * The actual evaluation of incoming signals is done by the - * Decider. - * - * base class ConnectionManagerAccess: - * - provides access to the channel via the ConnectionManager - * - * base class DeciderToPhyInterface: - * - interface for the Decider - * - * base class MacToPhyInterface: - * - interface for the Mac - * - * @ingroup phyLayer - * @ingroup baseModules - */ -class MIXIM_API BasePhyLayer: public ConnectionManagerAccess, - public DeciderToPhyInterface, - public MacToPhyInterface { - -protected: - - enum ProtocolIds { - GENERIC = 0, - }; - - int protocolId; - - /** @brief Defines the scheduling priority of AirFrames. - * - * AirFrames use a slightly higher priority than normal to ensure - * channel consistency. This means that before anything else happens - * at a time point t every AirFrame which ended at t has been removed and - * every AirFrame started at t has been added to the channel. - * - * An example where this matters is a ChannelSenseRequest which ends at - * the same time as an AirFrame starts (or ends). Depending on which message - * is handled first the result of ChannelSenseRequest would differ. - */ - static short airFramePriority; - - /** @brief Defines the strength of the thermal noise.*/ - ConstantSimpleConstMapping* thermalNoise; - - /** @brief The maximum transmission power a message can be send with */ - double maxTXPower; - - /** @brief The sensitivity describes the minimum strength a signal must have to be received.*/ - double sensitivity; - - /** @brief Stores if tracking of statistics (esp. cOutvectors) is enabled.*/ - bool recordStats; - - /** - * @brief Channel info keeps track of received AirFrames and provides information about - * currently active AirFrames at the channel. - */ - ChannelInfo channelInfo; - - /** @brief The state machine storing the current radio state (TX, RX, SLEEP).*/ - MiximRadio* radio; - - /** @brief Pointer to the decider module. */ - Decider* decider; - - /** @brief Used to store the AnalogueModels to be used as filters.*/ - typedef std::vector AnalogueModelList; - - /** @brief List of the analogue models to use.*/ - AnalogueModelList analogueModels; - - /** @brief The id of the in-data gate from the Mac layer */ - int upperLayerIn; - /** @brief The id of the out-data gate to the Mac layer */ - int upperLayerOut; - /** @brief The id of the out-control gate to the Mac layer */ - int upperControlOut; - /** @brief The id of the in-control gate from the Mac layer */ - int upperControlIn; - - /** - * @brief Self message scheduled to the point in time when the - * switching process of the radio is over. - */ - cMessage* radioSwitchingOverTimer; - - /** - * @brief Self message scheduled to the point in time when the - * transmission of an AirFrame is over. - */ - cMessage* txOverTimer; - - /** @brief The states of the receiving process for AirFrames.*/ - enum eAirFrameStates { - /** @brief Start of actual receiving process of the AirFrame. */ - START_RECEIVE = 1, - /** @brief AirFrame is being received. */ - RECEIVING, - /** @brief Receiving process over */ - END_RECEIVE - }; - - /** @brief Stores the length of the phy header in bits. */ - long headerLength; - - /** @brief Pointer to the World Utility, to obtain some global information*/ - BaseWorldUtility* world; - -private: - - /** - * @brief Utility function. Reads the parameters of a XML element - * and stores them in the passed ParameterMap reference. - */ - void getParametersFromXML(cXMLElement* xmlData, ParameterMap& outputMap) const; - - /** - * @brief Initializes the AnalogueModels with the data from the - * passed XML-config data. - */ - void initializeAnalogueModels(cXMLElement* xmlConfig); - - /** - * @brief Initializes the Decider with the data from the - * passed XML-config data. - */ - void initializeDecider(cXMLElement* xmlConfig); - -protected: - - /** - * @brief Reads and returns the parameter with the passed name. - * - * If the parameter couldn't be found the value of defaultValue - * is returned. - * - * @param parName - the name of the ned-parameter - * @param defaultValue - the value to be returned if the parameter - * couldn't be found - */ - template T readPar(const char* parName, const T defaultValue) const; - - /** - * @brief OMNeT++ initialization function. - * - * Read simple parameters. - * Read and parse xml file for decider and analogue models - * configuration. - */ - virtual void initialize(int stage); - - /** - * @brief OMNeT++ handle message function. - * - * Classify and forward message to subroutines. - * - AirFrames from channel - * - self scheduled AirFrames - * - MacPackets from MAC layer - * - ControllMesasges from MAC layer - * - self messages like TX_OVER and RADIO_SWITCHED - */ - virtual void handleMessage(cMessage* msg); - - /** - * @brief Initializes and returns the radio class to use. - * - * Can be overridden by sub-classing phy layers to use their - * own Radio implementations. - */ - virtual MiximRadio* initializeRadio() const; - - /** - * @brief Creates and returns an instance of the AnalogueModel with the - * specified name. - * - * The returned AnalogueModel has to be - * generated with the "new" command. The BasePhyLayer - * keeps the ownership of the returned AnalogueModel. - * - * This method is used by the BasePhyLayer during - * initialization to load the AnalogueModels which - * has been specified in the ned file. - * - * This method has to be overridden if you want to be - * able to load your own AnalogueModels. - * - * Is able to initialize the following AnalogueModels: - * - RadioStateAnalogueModel - */ - virtual AnalogueModel* getAnalogueModelFromName(const std::string& name, ParameterMap& params) const; - - /** - * @brief Creates and returns an instance of the analogue model with the specified - * _AMODEL_CLASS_. - * - * The returned Decider has to be generated with - * the "new" command. - * - * @return Instance of the Decider with the specified class type. - */ - template - _AMODEL_CLASS_* createAnalogueModel(const ParameterMap& params) const { - _AMODEL_CLASS_ *const pAnalogueModel = new _AMODEL_CLASS_(); - if (pAnalogueModel != NULL && !pAnalogueModel->initFromMap(params)) { - opp_warning("Analog model from config.xml could not be initialized correctly!"); - } - return pAnalogueModel; - } - - /** - * @brief Creates and returns an instance of the Decider with the specified - * name. - * - * The returned Decider has to be generated with - * the "new" command. The BasePhyLayer keeps the ownership - * of the returned Decider. - * - * This method is used by the BasePhyLayer during - * Initialization to load the decider which has been - * specified in the config.xml file. - * - * This method has to be overridden if you want to be - * able to load your own decider. - * - * @return Instance of the decider with the specified name. - */ - virtual Decider* getDeciderFromName(const std::string& name, ParameterMap& params); - - /** - * @brief Creates and returns an instance of the Decider with the specified - * _DECIDER_CLASS_. - * - * The returned Decider has to be generated with - * the "new" command. - * - * @return Instance of the Decider with the specified class type. - */ - template - _DECIDER_CLASS_* createDecider(const ParameterMap& params) { - _DECIDER_CLASS_ *const pDecider = new _DECIDER_CLASS_(this, sensitivity, findHost()->getIndex(), coreDebug); - if (pDecider != NULL && !pDecider->initFromMap(params)) { - opp_warning("Decider from config.xml could not be initialized correctly!"); - } - return pDecider; - } - - /** - * @name Handle Messages - **/ - /*@{ */ - /** - * @brief Handles messages received from the channel (probably AirFrames). - */ - virtual void handleAirFrame(airframe_ptr_t frame); - - /** - * @brief Handles messages received from the upper layer through the - * data gate. - */ - virtual void handleUpperMessage(cMessage* msg); - - /** - * @brief Handles messages received from the upper layer through the - * control gate. - */ - virtual void handleUpperControlMessage(cMessage* msg); - - /** - * @brief Handles self scheduled messages. - */ - virtual void handleSelfMessage(cMessage* msg); - - /** - * @brief Handles reception of a ChannelSenseRequest by forwarding it - * to the decider and scheduling it to the point in time - * returned by the decider. - */ - virtual void handleChannelSenseRequest(cMessage* msg); - - /** - * @brief Handles incoming AirFrames with the state FIRST_RECEIVE. - */ - void handleAirFrameFirstReceive(airframe_ptr_t msg); - - /** - * @brief Handles incoming AirFrames with the state START_RECEIVE. - */ - virtual void handleAirFrameStartReceive(airframe_ptr_t msg); - - /** - * @brief Handles incoming AirFrames with the state RECEIVING. - */ - virtual void handleAirFrameReceiving(airframe_ptr_t msg); - - /** - * @brief Handles incoming AirFrames with the state END_RECEIVE. - */ - virtual void handleAirFrameEndReceive(airframe_ptr_t msg); - - /*@}*/ - - /** - * @name Send Messages - **/ - /*@{ */ - - /** - * @brief Sends the passed control message to the upper layer. - */ - void sendControlMessageUp(cMessage* msg); - - /** - * @brief Sends the passed MacPkt to the upper layer. - */ - void sendMacPktUp(cMessage* pkt); - - /** - * @brief Sends the passed AirFrame to the channel - */ - void sendMessageDown(airframe_ptr_t pkt); - - /** - * @brief Schedule self message to passed point in time. - */ - void sendSelfMessage(cMessage* msg, simtime_t_cref time); - - /*@}*/ - - /** - * @brief This function encapsulates messages from the upper layer into an - * AirFrame and sets all necessary attributes. - */ - virtual airframe_ptr_t encapsMsg(cPacket *msg); - - /** - * @brief Filters the passed AirFrame's Signal by every registered AnalogueModel. - */ - virtual void filterSignal(airframe_ptr_t frame); - - /** - * @brief Called the moment the simulated switching process of the MiximRadio is finished. - * - * The Radio is set the new RadioState and the MAC Layer is sent - * a confirmation message. - * - * @param bSendCtrlMsg Flag for sending control message to MAC (in case of zero switch time - * this flag maybe false). - */ - virtual void finishRadioSwitching(bool bSendCtrlMsg = true); - - /** - * @brief Returns the identifier of the protocol this phy uses to send - * messages. - * - * @return An integer representing the identifier of the used protocol. - */ - virtual int myProtocolId() const { return protocolId; } - - /** - * @brief Returns true if the protocol with the passed identifier is - * decodeable by the decider. - * - * If the protocol with the passed id is not understood by this phy layers - * decider the according AirFrame is not passed to the it but only is added - * to channel info to be available as interference to the decider. - * - * Default implementation checks only if the passed id is the same as the - * one returned by "myProtocolId()". - * - * @param id The identifier of the protocol of an AirFrame. - * @return Returns true if the passed protocol id is supported by this phy- - * layer. - */ - virtual bool isKnownProtocolId(int id) const { return id == myProtocolId(); } - -private: - /** @brief Copy constructor is not allowed. - */ - BasePhyLayer(const BasePhyLayer&); - /** @brief Assignment operator is not allowed. - */ - BasePhyLayer& operator=(const BasePhyLayer&); - -public: - BasePhyLayer(); - - /** - * Free the pointer to the decider and the AnalogueModels and the Radio. - */ - virtual ~BasePhyLayer(); - - /** @brief Only calls the deciders finish method.*/ - virtual void finish(); - - //---------MacToPhyInterface implementation----------- - /** - * @name MacToPhyInterface implementation - * @brief These methods implement the MacToPhyInterface. - **/ - /*@{ */ - - /** - * @brief Returns the current state the radio is in. - * - * See RadioState for possible values. - * - * This method is mainly used by the mac layer. - */ - virtual int getRadioState() const; - - /** - * @brief Returns the true if the radio is in RX state. - */ - virtual bool isRadioInRX() const; - - /** - * @brief Tells the BasePhyLayer to switch to the specified - * radio state. - * - * The switching process can take some time depending on the - * specified switching times in the ned file. - * - * @return Decider::notAgain: Error code if the Radio is currently switching - * else: switching time from the current RadioState to the new RadioState - */ - virtual simtime_t setRadioState(int rs); - - /** - * @brief Returns the current state of the channel. - * - * See ChannelState for details. - */ - virtual ChannelState getChannelState() const; - - /** - * @brief Returns the length of the phy header in bits. - * - * Both the MAC and the PHY needs the header length. - */ - virtual long getPhyHeaderLength() const; - - /** @brief Sets the channel currently used by the radio. */ - virtual void setCurrentRadioChannel(int newRadioChannel); - - /** @brief Returns the channel currently used by the radio. */ - virtual int getCurrentRadioChannel() const; - - /** @brief Returns the number of channels available on this radio. */ - virtual int getNbRadioChannels() const; - - /*@}*/ - - //---------DeciderToPhyInterface implementation----------- - /** - * @name DeciderToPhyInterface implementation - * @brief These methods implement the DeciderToPhyInterface. - **/ - /*@{ */ - - /** - * @brief Fills the passed AirFrameVector with all AirFrames that intersect - * with the time interval [from, to] - */ - virtual void getChannelInfo(simtime_t_cref from, simtime_t_cref to, AirFrameVector& out) const; - - /** - * @brief Returns a Mapping which defines the thermal noise in - * the passed time frame (in mW). - * - * The implementing class of this method keeps ownership of the - * Mapping. - * - * This implementation returns a constant mapping with the value - * of the "thermalNoise" module parameter - * - * Override this method if you want to define a more complex - * thermal noise. - */ - virtual ConstMapping* getThermalNoise(simtime_t_cref from, simtime_t_cref to); - - /** - * @brief Called by the Decider to send a control message to the MACLayer - * - * This function can be used to answer a ChannelSenseRequest to the MACLayer - * - */ - virtual void sendControlMsgToMac(cMessage* msg); - - /** - * @brief Called to send an AirFrame with DeciderResult to the MACLayer - * - * When a packet is completely received and not noise, the Decider - * call this function to send the packet together with - * the corresponding DeciderResult up to MACLayer - * - */ - virtual void sendUp(airframe_ptr_t packet, DeciderResult* result); - - /** - * @brief Returns the current simulation time - */ - virtual simtime_t getSimTime() const; - - /** - * @brief Tells the PhyLayer to cancel a scheduled message (AirFrame or - * ControlMessage). - * - * Used by the Decider if it doesn't need to handle an AirFrame or - * ControlMessage again anymore. - */ - virtual void cancelScheduledMessage(cMessage* msg); - - /** - * @brief Tells the PhyLayer to reschedule a message (AirFrame or - * ControlMessage). - * - * Used by the Decider if it has to handle an AirFrame or an control message - * earlier than it has returned to the PhyLayer the last time the Decider - * handled that message. - */ - virtual void rescheduleMessage(cMessage* msg, simtime_t_cref t); - - /** - * @brief Does nothing. For an actual power supporting - * phy see "PhyLayerBattery". - */ - virtual void drawCurrent(double amount, int activity); - - /** - * @brief Records a double into the scalar result file. - * - * Implements the method from DeciderToPhyInterface, method-calls are forwarded - * to OMNeT-method 'recordScalar'. - */ - void recordScalar(const char *name, double value, const char *unit=NULL); - - /*@}*/ - - /** - * @brief Attaches a "control info" (PhyToMac) structure (object) to the message pMsg. - * - * This is most useful when passing packets between protocol layers - * of a protocol stack, the control info will contain the decider result. - * - * The "control info" object will be deleted when the message is deleted. - * Only one "control info" structure can be attached (the second - * setL3ToL2ControlInfo() call throws an error). - * - * @param pMsg The message where the "control info" shall be attached. - * @param pSrcAddr The MAC address of the message receiver. - */ - virtual cObject* setUpControlInfo(cMessage *const pMsg, DeciderResult *const pDeciderResult); -}; - -#endif /*BASEPHYLAYER_*/ diff --git a/jdeeco-simulation-demo/mixim/src/base/phyLayer/MacToPhyInterface.h b/jdeeco-simulation-demo/mixim/src/base/phyLayer/MacToPhyInterface.h deleted file mode 100644 index 856936d3e..000000000 --- a/jdeeco-simulation-demo/mixim/src/base/phyLayer/MacToPhyInterface.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef MACTOPHYINTERFACE_H_ -#define MACTOPHYINTERFACE_H_ - -#include - -#include "MiXiMDefs.h" -#include "Signal_.h" -#include "ChannelState.h" -#include "PhyUtils.h" - -/** - * @brief Defines the methods provided by the phy to the mac layer. - * - * @ingroup macLayer - * @ingroup phyLayer - */ -class MIXIM_API MacToPhyInterface -{ -public: - /** - * @brief Message kinds used by every phy layer. - * - * Physical layers should begin their additional kinds - * at the value of LAST_BASE_PHY_KIND. - */ - enum BasePhyMessageKinds { - /** @brief Indicates the end of a send transmission. */ - TX_OVER = 22000, - /** @brief Indicates the end of a radio switch. */ - RADIO_SWITCHING_OVER, - /** @brief Channel sense control message between Mac and Phy.*/ - CHANNEL_SENSE_REQUEST, - /** @brief AirFrame kind */ - AIR_FRAME, - /** @brief Stores the id on which classes extending BasePhy should - * continue their own kinds.*/ - LAST_BASE_PHY_KIND, - }; - -public: - - virtual ~MacToPhyInterface() {} - /** - * @brief Returns the current state the radio is in. See RadioState - * for possible values. - * - * NOTE: Radio state information is not available until - * initialization-stage 1. - * - * This method is mainly used by the mac layer. - */ - virtual int getRadioState() const = 0; - - /** - * @brief Tells the BasePhyLayer to switch to the specified - * radio state. - * - * NOTE: Radio state can't be changed until initialization-stage 1. - * - * The switching process can take some time depending on the - * specified switching times in the ned file. - * The return value is the time needed to switch to the - * specified state, or smaller zero if the radio could - * not be switched (propably because it is already switching. - */ - virtual simtime_t setRadioState(int rs) = 0; - - /** - * @brief Returns the current state of the channel. See ChannelState - * for details. - * - * NOTE: Channel state information is not available until initialization - * is over and the simulation has started. - */ - virtual ChannelState getChannelState() const = 0; - - /** - * @brief Returns the length of the phy header in bits. - * - * Since the MAC layer has to create the signal for - * a transmission it has to know the total length of - * the packet and therefore needs the length of the - * phy header. - */ - virtual long getPhyHeaderLength() const = 0; - - /** @brief Sets the channel currently used by the radio. */ - virtual void setCurrentRadioChannel(int newRadioChannel) = 0; - - /** @brief Returns the channel currently used by the radio. */ - virtual int getCurrentRadioChannel() const = 0; - - /** @brief Returns the number of channels available on this radio. */ - virtual int getNbRadioChannels() const = 0; -}; - -#endif /*MACTOPHYINTERFACE_H_*/ diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/base/BasicModule.h b/jdeeco-simulation-demo/mixim/src/inet_stub/base/BasicModule.h deleted file mode 100644 index 2d7e31127..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/base/BasicModule.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * file: BasicModule.h - * - * author: Steffen Sroka - * Andreas Koepke - * - * copyright: (C) 2004 Telecommunication Networks Group (TKN) at - * Technische Universitaet Berlin, Germany. - * - * 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. - * For further information see file COPYING - * in the top level directory - *************************************************************************** - * part of: framework implementation developed by tkn - **************************************************************************/ - - -#ifndef BASIC_MODULE_H -#define BASIC_MODULE_H - -#include "INETDefs.h" - -#include "NotificationBoard.h" -#include "NotifierConsts.h" - -#ifndef EV -#define EV (ev.isDisabled()||!debug) ? (std::ostream&)ev : ev << logName() << "::" << getClassName() << ": " -#endif - - -/** - * @brief Base class for all simple modules of a host that want to have - * access to the NotificationBoard module. - * - * The basic module additionally provides a function findHost() which - * returns a pointer to the host module. - * - * There is no Define_Module() for this class because we use - * BasicModule only as a base class to derive all other - * module. There will never be a stand-alone BasicModule module - * (and that is why there is no Define_Module() and no .ned file for - * BasicModule). - * - * @see NotificationBoard - * @ingroup basicModules - * - * @author Steffen Sroka - * @author Andreas Koepke - */ -class INET_API BasicModule: public cSimpleModule, public INotifiable -{ - protected: - /** @brief Debug switch for the core modules*/ - bool coreDebug; - - /** @brief Debug switch for all other modules*/ - bool debug; - - /** @brief Log name of the host module*/ - std::string loggingName; - - protected: - /** @brief Function to get a pointer to the host module*/ - virtual cModule *findHost(bool errorIfNotFound = true) const; - - /** @brief Function to get the logging name of id*/ - const char* getLogName(int); - - protected: - /** @brief Basic initialization for all modules */ - virtual void initialize(int); - - /** - * @brief Divide initialization into two stages - * - * In the first stage (stage==0), modules subscribe to notification - * categories at NotificationBoard. The first notifications - * (e.g. about the initial values of some variables such as RadioState) - * should take place earliest in the second stage (stage==1), - * when everyone interested in them has already subscribed. - */ - virtual int numInitStages() const {return 2;} - - /** - * @brief Function to get the logging name of the host - * - * The logging name is the ned module name of the host (unless the - * host ned variable loggingName is specified). It can be used for - * logging messages to simplify debugging in TKEnv. - */ - const char* logName(void) const - { - return loggingName.c_str(); - }; - - /** - * @brief Called by the NotificationBoard whenever a change of a category occurs - * to which we have subscribed. Redefined from INotifiable. - */ - virtual void receiveChangeNotification(int category, const cObject *details) {} -}; - -#endif - - diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/base/NotificationBoard.h b/jdeeco-simulation-demo/mixim/src/inet_stub/base/NotificationBoard.h deleted file mode 100644 index a69001c30..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/base/NotificationBoard.h +++ /dev/null @@ -1,156 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, see . -// - - -#ifndef __INET_NOTIFICATIONBOARD_H -#define __INET_NOTIFICATIONBOARD_H - -#include -#include - -#include "INETDefs.h" - -#include "ModuleAccess.h" -#include "INotifiable.h" -#include "NotifierConsts.h" - -/** - * Acts as a intermediary between module where state changes can occur and - * modules which are interested in learning about those changes; - * "Notification Broker". - * - * Notification events are grouped into "categories." Examples of categories - * are: NF_RADIOSTATE_CHANGED, NF_PP_TX_BEGIN, NF_PP_TX_END, NF_IPv4_ROUTE_ADDED, - * NF_BEACON_LOST, NF_NODE_FAILURE, NF_NODE_RECOVERY, etc. Each category is - * identified by an integer (right now it's assigned in the source code via an enum, - * in the future we'll convert to dynamic category registration). - * - * To trigger a notification, the client must obtain a pointer to the - * NotificationBoard of the given host or router (explained later), and - * call its fireChangeNotification() method. The notification will be - * delivered to all subscribed clients immediately, inside the - * fireChangeNotification() call. - * - * Clients that wish to receive notifications should implement (subclass from) - * the INotifiable interface, obtain a pointer to the NotificationBoard, - * and subscribe to the categories they are interested in by calling the - * subscribe() method of the NotificationBoard. Notifications will be - * delivered to the receiveChangeNotification() method of the client - * (redefined from INotifiable). - * - * In cases when the category itself (an int) does not carry enough information - * about the notification event, one can pass additional information - * in a data class. There is no restriction on what the data class may contain, - * except that it has to be subclassed from cObject, and of course - * producers and consumers of notifications should agree on its contents. - * If no extra info is needed, one can pass a NULL pointer in the - * fireChangeNotification() method. - * - * A module which implements INotifiable looks like this: - * - *
- * class Foo : public cSimpleModule, public INotifiable {
- *     ...
- *     virtual void receiveChangeNotification(int category, const cObject *details) {..}
- *     ...
- * };
- * 
- * - * Obtaining a pointer to the NotificationBoard module of that host/router: - * - *
- * NotificationBoard *nb; // this is best made a module class member
- * nb = NotificationBoardAccess().get();  // best done in initialize()
- * 
- * - * - * See NED file for additional info. - * - * @see INotifiable - * @author Andras Varga - */ -class INET_API NotificationBoard : public cSimpleModule -{ - public: // should be protected - typedef std::vector NotifiableVector; - typedef std::map ClientMap; - friend std::ostream& operator<<(std::ostream&, const NotifiableVector&); // doesn't work in MSVC 6.0 - - protected: - ClientMap clientMap; - - protected: - /** - * Initialize. - */ - virtual void initialize(); - - /** - * Does nothing. - */ - virtual void handleMessage(cMessage *msg); - - public: - /** @name Methods for consumers of change notifications */ - //@{ - /** - * Subscribe to changes of the given category - */ - virtual void subscribe(INotifiable *client, int category); - - /** - * Unsubscribe from changes of the given category - */ - virtual void unsubscribe(INotifiable *client, int category); - - /** - * Returns true if any client has subscribed to the given category. - * This, by using a local boolean 'hasSubscriber' flag, allows - * performance-critical clients to leave out calls to - * fireChangeNotification() if there's no one subscribed anyway. - * The flag should be refreshed on each NF_SUBSCRIBERLIST_CHANGED - * notification. - */ - virtual bool hasSubscribers(int category); - //@} - - /** @name Methods for producers of change notifications */ - //@{ - /** - * Tells NotificationBoard that a change of the given category has - * taken place. The optional details object may carry more specific - * information about the change (e.g. exact location, specific attribute - * that changed, old value, new value, etc). - */ - virtual void fireChangeNotification(int category, const cObject *details = NULL); - //@} -}; - -/** - * Gives access to the NotificationBoard instance within the host/router. - */ -class INET_API NotificationBoardAccess : public ModuleAccess -{ - public: - NotificationBoardAccess() : ModuleAccess("notificationBoard") {} -}; - -#endif - - - - diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/ANSimMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/ANSimMobility.h deleted file mode 100644 index 397e12658..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/ANSimMobility.h +++ /dev/null @@ -1,65 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// 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, see . -// - - -#ifndef AN_SIM_MOBILITY_H -#define AN_SIM_MOBILITY_H - -#include "INETDefs.h" - -#include "LineSegmentsMobilityBase.h" - - -/** - * @brief Uses the \ elements of the ANSim tool's trace file. - * See NED file for more info. - * - * @ingroup mobility - * @author Andras Varga - */ -class ANSimMobility : public LineSegmentsMobilityBase -{ - protected: - // config - int nodeId; ///< we'll have to compare this to the \ elements - // state - cXMLElement *nextPositionChange; ///< points to the next \ element - - protected: - /** @brief Initializes mobility model parameters. */ - virtual void initialize(int stage); - - /** @brief Initializes the position according to the mobility model. */ - virtual void initializePosition(); - - /** @brief Overridden from LineSegmentsMobilityBase. */ - virtual void setTargetPosition(); - - /** @brief Overridden from LineSegmentsMobilityBase. */ - virtual void move(); - - /** @brief Finds the next \ element. */ - virtual cXMLElement *findNextPositionChange(cXMLElement *positionChange); - - /** @brief Utility: extract data from given \ element. */ - virtual void extractDataFrom(cXMLElement *node); - - public: - ANSimMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/BonnMotionMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/BonnMotionMobility.h deleted file mode 100644 index 8a11f926a..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/BonnMotionMobility.h +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// 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, see . -// - -#ifndef BONN_MOTION_MOBILITY_H -#define BONN_MOTION_MOBILITY_H - -#include "INETDefs.h" - -#include "LineSegmentsMobilityBase.h" -#include "BonnMotionFileCache.h" - - -/** - * @brief Uses the BonnMotion native file format. See NED file for more info. - * - * @ingroup mobility - * @author Andras Varga - */ -class INET_API BonnMotionMobility : public LineSegmentsMobilityBase -{ - protected: - // state - bool is3D; - const BonnMotionFile::Line *lines; - int currentLine; - - protected: - /** @brief Initializes mobility model parameters. */ - virtual void initialize(int stage); - - /** @brief Initializes the position according to the mobility model. */ - virtual void initializePosition(); - - /** @brief Overridden from LineSegmentsMobilityBase. */ - virtual void setTargetPosition(); - - /** @brief Overridden from LineSegmentsMobilityBase. */ - virtual void move(); - - public: - BonnMotionMobility(); - - virtual ~BonnMotionMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/ChiangMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/ChiangMobility.h deleted file mode 100644 index 7101c255e..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/ChiangMobility.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Author: Marcin Kosiba -// -// 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, see . -// - - -#ifndef CHIANG_MOBILITY_H -#define CHIANG_MOBILITY_H - -#include "INETDefs.h" - -#include - - -/** - * @brief Chiang's random walk movement model. See NED file for more info. - * - * @author Marcin Kosiba - */ -class INET_API ChiangMobility : public LineSegmentsMobilityBase -{ - protected: - double speed; ///< speed of the host - double stateTransitionUpdateInterval; ///< how often to calculate the new state - int xState; ///< 0 = negative direction, 1 = no move, 2 = positive direction - int yState; ///< 0 = negative direction, 1 = no move, 2 = positive direction - - protected: - /** @brief Initializes mobility model parameters.*/ - virtual void initialize(int stage); - - /** @brief Gets the next state based on the current state. */ - int getNextStateIndex(int currentState); - - /** @brief Calculate a new target position to move to. */ - void setTargetPosition(); - - /** @brief Move the host according to the current simulation time. */ - virtual void move(); - - public: - ChiangMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/CircleMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/CircleMobility.h deleted file mode 100644 index 65273209d..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/CircleMobility.h +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, see . -// - - -#ifndef CIRCLE_MOBILITY_H -#define CIRCLE_MOBILITY_H - -#include "INETDefs.h" - -#include "MovingMobilityBase.h" - - -/** - * @brief Circle movement model. See NED file for more info. - * - * @ingroup mobility - * @author Andras Varga - */ -class INET_API CircleMobility : public MovingMobilityBase -{ - protected: - double cx; - double cy; - double cz; - double r; - double startAngle; - double speed; - /** @brief angular velocity [rad/s], derived from speed and radius. */ - double omega; - - /** @brief Direction from the center of the circle. */ - double angle; - - protected: - /** @brief Initializes mobility model parameters.*/ - virtual void initialize(int stage); - - /** @brief Initializes the position according to the mobility model. */ - virtual void initializePosition(); - - /** @brief Move the host according to the current simulation time. */ - virtual void move(); - - public: - CircleMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/GaussMarkovMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/GaussMarkovMobility.h deleted file mode 100644 index 3bb731c9d..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/GaussMarkovMobility.h +++ /dev/null @@ -1,60 +0,0 @@ -// -// Author: Marcin Kosiba -// -// 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, see . -// - - -#ifndef GAUSS_MARKOV_MOBILITY_H -#define GAUSS_MARKOV_MOBILITY_H - -#include "INETDefs.h" - -#include "LineSegmentsMobilityBase.h" - - -/** - * @brief Gauss Markov movement model. See NED file for more info. - * - * @author Marcin Kosiba - */ -class INET_API GaussMarkovMobility : public LineSegmentsMobilityBase -{ - protected: - double speed; ///< speed of the host - double angle; ///< angle of linear motion - double alpha; ///< alpha parameter - int margin; ///< margin at which the host gets repelled from the border - double speedMean; ///< speed mean - double angleMean; ///< angle mean - double variance; ///< variance - - protected: - /** @brief Initializes mobility model parameters.*/ - virtual void initialize(int stage); - - /** @brief If the host is too close to the border it is repelled */ - void preventBorderHugging(); - - /** @brief Move the host*/ - virtual void move(); - - /** @brief Calculate a new target position to move to. */ - virtual void setTargetPosition(); - - public: - GaussMarkovMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/LinearMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/LinearMobility.h deleted file mode 100644 index a3f8bf84a..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/LinearMobility.h +++ /dev/null @@ -1,52 +0,0 @@ -// -// Author: Emin Ilker Cetinbas (niw3_at_yahoo_d0t_com) -// Copyright (C) 2005 Emin Ilker Cetinbas -// -// 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, see . -// - - -#ifndef LINEAR_MOBILITY_H -#define LINEAR_MOBILITY_H - -#include "INETDefs.h" - -#include "MovingMobilityBase.h" - - -/** - * @brief Linear movement model. See NED file for more info. - * - * @ingroup mobility - * @author Emin Ilker Cetinbas - */ -class INET_API LinearMobility : public MovingMobilityBase -{ - protected: - double speed; ///< speed of the host - double angle; ///< angle of linear motion - double acceleration; ///< acceleration of linear motion - - protected: - /** @brief Initializes mobility model parameters.*/ - virtual void initialize(int stage); - - /** @brief Move the host*/ - virtual void move(); - - public: - LinearMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/MassMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/MassMobility.h deleted file mode 100644 index a8a0f832b..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/MassMobility.h +++ /dev/null @@ -1,61 +0,0 @@ -// -// Author: Emin Ilker Cetinbas (niw3_at_yahoo_d0t_com) -// Generalization: Andras Varga -// Copyright (C) 2005 Emin Ilker Cetinbas, Andras Varga -// -// 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, see . -// - - -#ifndef MASS_MOBILITY_H -#define MASS_MOBILITY_H - -#include "INETDefs.h" - -#include "LineSegmentsMobilityBase.h" - - -/** - * @brief Models the mobility of with mass, making random motions. - * See NED file for more info. - * - * @ingroup mobility - * @author Emin Ilker Cetinbas, Andras Varga - */ -class INET_API MassMobility : public LineSegmentsMobilityBase -{ - protected: - // config (see NED file for explanation) - cPar *changeIntervalParameter; - cPar *changeAngleByParameter; - cPar *speedParameter; - - // current state - double angle; ///< angle of linear motion - - protected: - /** @brief Initializes mobility model parameters. */ - virtual void initialize(int stage); - - /** @brief Move the host according to the current simulation time. */ - virtual void move(); - - /** @brief Calculate a new target position to move to. */ - virtual void setTargetPosition(); - - public: - MassMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/MoBANLocal.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/MoBANLocal.h deleted file mode 100644 index 61c73a778..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/MoBANLocal.h +++ /dev/null @@ -1,97 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * file: MoBANLocal.h - * - * author: Majid Nabi - * - * http://www.es.ele.tue.nl/nes - * - * copyright: (C) 2010 Electronic Systems group(ES), - * Eindhoven University of Technology (TU/e), the Netherlands. - * - * - * 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. - * For further information see file COPYING - * in the top level directory - *************************************************************************** - * part of: MoBAN (Mobility Model for wireless Body Area Networks) - * description: Implementation of the local module of the MoBAN mobility model - *************************************************************************** - * Citation of the following publication is appreciated if you use MoBAN for - * a publication of your own. - * - * M. Nabi, M. Geilen, T. Basten. MoBAN: A Configurable Mobility Model for Wireless Body Area Networks. - * In Proc. of the 4th Int'l Conf. on Simulation Tools and Techniques, SIMUTools 2011, Barcelona, Spain, 2011. - * - * BibTeX: - * @inproceedings{MoBAN, - * author = "M. Nabi and M. Geilen and T. Basten.", - * title = "{MoBAN}: A Configurable Mobility Model for Wireless Body Area Networks.", - * booktitle = "Proceedings of the 4th Int'l Conf. on Simulation Tools and Techniques.", - * series = {SIMUTools '11}, - * isbn = {978-963-9799-41-7}, - * year = {2011}, - * location = {Barcelona, Spain}, - * publisher = {ICST} } - * - **************************************************************************/ - - -#ifndef MO_BAN_LOCAL_H -#define MO_BAN_LOCAL_H - -#include -#include - - -/** - * @brief This is the local mobility module of MoBAN. It should be instantiated in each node that belongs to a WBAN. - * The NED parameter "coordinatorIndex" determines to which WBAN (MoBANCoordinator) it belongs. - * The current implementation uses the Random Walk Mobility Model (RWMM) for individual (local) movement within a sphere around the node, with given speed - * and sphere radius of the current posture. The reference point of the node in the current posture, the sphere radius, and the speed is given by the - * corresponding coordinator. RWMM determines the location of the node at any time relative to the given reference point. - * - * @ingroup mobility - * @ingroup MoBAN - * @author Majid Nabi - */ -class MoBANLocal : public LineSegmentsMobilityBase -{ - protected: - /** @brief The coordinator of the WBAN. */ - MoBANCoordinator *coordinator; - - /** @brief Reference position of the node in the current posture. */ - Coord referencePosition; - - /** @brief The radius of local mobility of the node in the current posture. */ - double radius; - - /** @brief The speed of local mobility of the node in the current posture. */ - double speed; - - protected: - virtual void initialize(int); - - virtual void initializePosition(); - - virtual void setTargetPosition(); - - virtual void updateVisualRepresentation(); - - public: - MoBANLocal(); - - virtual Coord getCurrentPosition(); - - virtual Coord getCurrentSpeed(); - - void setCoordinator(MoBANCoordinator *coordinator) { this->coordinator = coordinator; } - - void setMoBANParameters(Coord referencePoint, double radius, double speed); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/Ns2MotionMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/Ns2MotionMobility.h deleted file mode 100644 index f18a2cfba..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/Ns2MotionMobility.h +++ /dev/null @@ -1,83 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// Copyright (C) 2008 Alfonso Ariza -// -// 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. -// - - -#ifndef NS2_MOTION_MOBILITY_H -#define NS2_MOTION_MOBILITY_H - -#include "INETDefs.h" - -#include "LineSegmentsMobilityBase.h" - - -/** - * @brief Uses the ns2 motion native file format. See NED file for more info. - * - * @ingroup mobility - * @author Alfonso Ariza - */ - -class Ns2MotionMobility; - -/** - * Represents a ns2 motion file's contents. - */ -class INET_API Ns2MotionFile -{ - public: - typedef std::vector Line; - double initial[3]; - protected: - friend class Ns2MotionMobility; - typedef std::vector LineList; - LineList lines; -}; - -class INET_API Ns2MotionMobility : public LineSegmentsMobilityBase -{ - protected: - // state - unsigned int vecpos; - Ns2MotionFile *ns2File; - int nodeId; - double scrollX; - double scrollY; - - protected: - void parseFile(const char *filename); - - /** @brief Initializes mobility model parameters.*/ - virtual void initialize(int stage); - - /** @brief Initializes the position according to the mobility model. */ - virtual void initializePosition(); - - /** @brief Overridden from LineSegmentsMobilityBase.*/ - virtual void setTargetPosition(); - - /** @brief Overridden from LineSegmentsMobilityBase.*/ - virtual void move(); - - public: - Ns2MotionMobility(); - - virtual ~Ns2MotionMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/RandomWPMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/RandomWPMobility.h deleted file mode 100644 index 4f0bc9e83..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/RandomWPMobility.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright (C) 2005 Georg Lutz, Institut fuer Telematik, University of Karlsruhe -// Copyright (C) 2005 Andras Varga -// -// 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, see . -// - - -#ifndef RANDOM_WP_MOBILITY_H -#define RANDOM_WP_MOBILITY_H - -#include "INETDefs.h" - -#include "LineSegmentsMobilityBase.h" - - -/** - * Random Waypoint mobility model. See NED file for more info. - * - * @author Georg Lutz (georglutz AT gmx DOT de), Institut fuer Telematik, - * Universitaet Karlsruhe, http://www.tm.uka.de, 2004-2005 - * @author Andras Varga (generalized, ported to LineSegmentsMobilityBase) - */ -class INET_API RandomWPMobility : public LineSegmentsMobilityBase -{ - protected: - bool nextMoveIsWait; - - protected: - /** @brief Initializes mobility model parameters.*/ - virtual void initialize(int stage); - - /** @brief Overridden from LineSegmentsMobilityBase.*/ - virtual void setTargetPosition(); - - /** @brief Overridden from LineSegmentsMobilityBase.*/ - virtual void move(); - - public: - RandomWPMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/RectangleMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/RectangleMobility.h deleted file mode 100644 index 8b73ab4b2..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/RectangleMobility.h +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, see . -// - - -#ifndef RECTANGLE_MOBILITY_H -#define RECTANGLE_MOBILITY_H - -#include "INETDefs.h" - -#include "MovingMobilityBase.h" - - -/** - * @brief Rectangle movement model. See NED file for more info. - * - * @ingroup mobility - * @author Andras Varga - */ -class INET_API RectangleMobility : public MovingMobilityBase -{ - protected: - // configuration - double speed; ///< speed of the host - - // state - double d; ///< distance from (x1,y1), measured clockwise on the perimeter - double corner1, corner2, corner3, corner4; - - protected: - /** @brief Initializes mobility model parameters. - * - * If the host is not stationary it calculates a random position on the rectangle. - */ - virtual void initialize(int stage); - - /** @brief Initializes the position according to the mobility model. */ - virtual void initializePosition(); - - /** @brief Move the host */ - virtual void move(); - - public: - RectangleMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/TractorMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/TractorMobility.h deleted file mode 100644 index 239f67f73..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/TractorMobility.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -*- mode:c++ -*- ********************************************************/ -// -// Copyright (C) 2007 Peterpaul Klein Haneveld -// -// 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. -// - -#ifndef RECTANGLE_MOBILITY_H -#define RECTANGLE_MOBILITY_H - - -#include - - -/** - * @brief Tractor movement model. See NED file for more info. - * - * NOTE: Does not yet support 3-dimensional movement. - * @ingroup mobility - * @author Peterpaul Klein Haneveld - */ -class TractorMobility : public LineSegmentsMobilityBase -{ - protected: - double speed; //< speed along the trajectory - double x1, y1, x2, y2; ///< rectangle bounds of the field - int rowCount; ///< the number of rows that the tractor must take - int step; - - protected: - /** @brief Initializes mobility model parameters. */ - virtual void initialize(int); - - /** @brief Initializes the position according to the mobility model. */ - virtual void initializePosition(); - - /** @brief Calculate a new target position to move to. */ - void setTargetPosition(); - - public: - TractorMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/TurtleMobility.h b/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/TurtleMobility.h deleted file mode 100644 index 679a05339..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/mobility/models/TurtleMobility.h +++ /dev/null @@ -1,78 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, see . -// - - -#ifndef TURTLE_MOBILITY_H -#define TURTLE_MOBILITY_H - -#include - -#include "INETDefs.h" - -#include "LineSegmentsMobilityBase.h" - - -/** - * @brief LOGO-style movement model, with the script coming from XML. - * See NED file for more info. - * - * @ingroup mobility - * @author Andras Varga - */ -class INET_API TurtleMobility : public LineSegmentsMobilityBase -{ - protected: - // config - cXMLElement *turtleScript; - - // state - cXMLElement *nextStatement; - double speed; - double angle; - BorderPolicy borderPolicy; - std::stack loopVars; // for - - protected: - /** @brief Initializes mobility model parameters.*/ - virtual void initialize(int stage); - - /** @brief Initializes the position according to the mobility model. */ - virtual void initializePosition(); - - /** @brief Overridden from LineSegmentsMobilityBase. Invokes resumeScript().*/ - virtual void setTargetPosition(); - - /** @brief Overridden from LineSegmentsMobilityBase.*/ - virtual void move(); - - /** @brief Process next statements from script */ - virtual void resumeScript(); - - /** @brief Execute the given statement*/ - virtual void executeStatement(cXMLElement *nextStatement); - - /** @brief Parse attrs in the script -- accepts things like "uniform(10,50) as well */ - virtual double getValue(const char *s); - - /** @brief Advance nextStatement pointer */ - virtual void gotoNextStatement(); - - public: - TurtleMobility(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/networklayer/common/InterfaceTable.cc b/jdeeco-simulation-demo/mixim/src/inet_stub/networklayer/common/InterfaceTable.cc deleted file mode 100644 index 6d626febd..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/networklayer/common/InterfaceTable.cc +++ /dev/null @@ -1,372 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 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 Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this program; if not, see . -// - - -#include -#include -#include -#include -#include -#include - -#include "InterfaceTable.h" -#include "NotifierConsts.h" - -#ifdef WITH_IPv4 -#include "IPv4InterfaceData.h" -#endif - -#ifdef WITH_IPv6 -#include "IPv6InterfaceData.h" -#endif - -Define_Module( InterfaceTable ); - -#define INTERFACEIDS_START 100 - -std::ostream& operator<<(std::ostream& os, const InterfaceEntry& e) -{ - os << e.info(); - return os; -}; - - -InterfaceTable::InterfaceTable() -{ - nb = NULL; - tmpNumInterfaces = -1; - tmpInterfaceList = NULL; -} - -InterfaceTable::~InterfaceTable() -{ - for (int i=0; i < (int)idToInterface.size(); i++) - delete idToInterface[i]; - delete [] tmpInterfaceList; -} - -void InterfaceTable::initialize(int stage) -{ - if (stage==0) - { - // get a pointer to the NotificationBoard module - nb = NotificationBoardAccess().get(); - - // register a loopback interface - InterfaceEntry *ie = new InterfaceEntry(NULL); - ie->setName("lo0"); - ie->setMtu(3924); - ie->setLoopback(true); - addInterface(ie); - } - else if (stage==1) - { - WATCH_PTRVECTOR(idToInterface); - updateDisplayString(); - } -} - -void InterfaceTable::updateDisplayString() -{ - if (!ev.isGUI()) - return; - - char buf[80]; - sprintf(buf, "%d interfaces", getNumInterfaces()); - getDisplayString().setTagArg("t", 0, buf); -} - -void InterfaceTable::handleMessage(cMessage *msg) -{ - throw cRuntimeError("This module doesn't process messages"); -} - -void InterfaceTable::receiveChangeNotification(int category, const cObject *details) -{ - // nothing needed here at the moment - Enter_Method_Silent(); - printNotificationBanner(category, details); -} - -//--- - -cModule *InterfaceTable::getHostModule() -{ - return findContainingNode(this); -} - -int InterfaceTable::getNumInterfaces() -{ - if (tmpNumInterfaces == -1) - { - // count non-NULL elements - int n = 0; - int maxId = idToInterface.size(); - for (int i=0; i=n) - throw cRuntimeError("getInterface(): interface index %d out of range 0..%d", pos, n-1); - - if (!tmpInterfaceList) - { - // collect non-NULL elements into tmpInterfaceList[] - tmpInterfaceList = new InterfaceEntry *[n]; - int k = 0; - int maxId = idToInterface.size(); - for (int i=0; i=(int)idToInterface.size()) ? NULL : idToInterface[id]; -} - -void InterfaceTable::addInterface(InterfaceEntry *entry) -{ - if (!nb) - throw cRuntimeError("InterfaceTable must precede all network interface modules in the node's NED definition"); - // check name is unique - if (getInterfaceByName(entry->getName())!=NULL) - throw cRuntimeError("addInterface(): interface '%s' already registered", entry->getName()); - - // insert - entry->setInterfaceId(INTERFACEIDS_START + idToInterface.size()); - entry->setInterfaceTable(this); - idToInterface.push_back(entry); - invalidateTmpInterfaceList(); - - // fill in networkLayerGateIndex, nodeOutputGateId, nodeInputGateId - discoverConnectingGates(entry); - - nb->fireChangeNotification(NF_INTERFACE_CREATED, entry); -} - -void InterfaceTable::discoverConnectingGates(InterfaceEntry *entry) -{ - cModule *ifmod = entry->getInterfaceModule(); - if (!ifmod) - return; // virtual interface - - // ifmod is something like "host.eth[1].mac"; climb up to find "host.eth[1]" from it - cModule *host = getParentModule(); - while (ifmod && ifmod->getParentModule()!=host) - ifmod = ifmod->getParentModule(); - if (!ifmod) - throw cRuntimeError("addInterface(): specified module is not in this host/router"); - - // find gates connected to host / network layer - cGate *nwlayerInGate = NULL, *nwlayerOutGate = NULL; - for (GateIterator i(ifmod); !i.end(); i++) - { - cGate *g = i(); - if (!g) continue; - - // find the host/router's gates that internally connect to this interface - if (g->getType()==cGate::OUTPUT && g->getNextGate() && g->getNextGate()->getOwnerModule()==host) - entry->setNodeOutputGateId(g->getNextGate()->getId()); - if (g->getType()==cGate::INPUT && g->getPreviousGate() && g->getPreviousGate()->getOwnerModule()==host) - entry->setNodeInputGateId(g->getPreviousGate()->getId()); - - // find the gate index of networkLayer/networkLayer6/mpls that connects to this interface - if (g->getType()==cGate::OUTPUT && g->getNextGate() && g->isName("upperLayerOut")) - nwlayerInGate = g->getNextGate(); - if (g->getType()==cGate::INPUT && g->getPreviousGate() && g->isName("upperLayerIn")) - nwlayerOutGate = g->getPreviousGate(); - } - - // consistency checks - // note: we don't check nodeOutputGateId/nodeInputGateId, because wireless interfaces - // are not connected to the host - if (!nwlayerInGate && !nwlayerOutGate) // Accesspoint does not have a network layer so the NIC is not connected - return; - if (!nwlayerInGate || !nwlayerOutGate || nwlayerInGate->getOwnerModule()!=nwlayerOutGate->getOwnerModule() || nwlayerInGate->getIndex()!=nwlayerOutGate->getIndex()) - throw cRuntimeError("addInterface(): interface must be connected to network layer's in/out gates using the same gate index"); - - entry->setNetworkLayerGateIndex(nwlayerInGate->getIndex()); -} - -void InterfaceTable::deleteInterface(InterfaceEntry *entry) -{ - int id = entry->getInterfaceId(); - if (entry != getInterfaceById(id)) - throw cRuntimeError("deleteInterface(): interface '%s' not found in interface table", entry->getName()); - - nb->fireChangeNotification(NF_INTERFACE_DELETED, entry); // actually, only going to be deleted - - idToInterface[id - INTERFACEIDS_START] = NULL; - delete entry; - invalidateTmpInterfaceList(); -} - -void InterfaceTable::invalidateTmpInterfaceList() -{ - tmpNumInterfaces = -1; - delete [] tmpInterfaceList; - tmpInterfaceList = NULL; -} - -void InterfaceTable::interfaceChanged(InterfaceEntry *entry, int category) -{ - nb->fireChangeNotification(category, entry); - - if (ev.isGUI() && par("displayAddresses").boolValue()) - updateLinkDisplayString(entry); -} - -void InterfaceTable::updateLinkDisplayString(InterfaceEntry *entry) -{ - int outputGateId = entry->getNodeOutputGateId(); - if (outputGateId != -1) - { - cModule *host = getParentModule(); - cGate *outputGate = host->gate(outputGateId); - if (!outputGate->getChannel()) - return; -#if defined(WITH_IPv4) or defined(WITH_IPv6) - cDisplayString& displayString = outputGate->getDisplayString(); - char buf[128]; -#endif -#ifdef WITH_IPv4 - if (entry->ipv4Data()) { - sprintf(buf, "%s\n%s/%d", entry->getFullName(), entry->ipv4Data()->getIPAddress().str().c_str(), entry->ipv4Data()->getNetmask().getNetmaskLength()); - displayString.setTagArg("t", 0, buf); - displayString.setTagArg("t", 1, "l"); - } -#endif -#ifdef WITH_IPv6 - if (entry->ipv6Data() && entry->ipv6Data()->getNumAddresses() > 0) { - sprintf(buf, "%s\n%s", entry->getFullName(), entry->ipv6Data()->getPreferredAddress().str().c_str()); - displayString.setTagArg("t", 0, buf); - displayString.setTagArg("t", 1, "l"); - } -#endif - } -} - -InterfaceEntry *InterfaceTable::getInterfaceByNodeOutputGateId(int id) -{ - // linear search is OK because normally we have don't have many interfaces and this func is rarely called - Enter_Method_Silent(); - int n = idToInterface.size(); - for (int i=0; igetNodeOutputGateId()==id) - return idToInterface[i]; - return NULL; -} - -InterfaceEntry *InterfaceTable::getInterfaceByNodeInputGateId(int id) -{ - // linear search is OK because normally we have don't have many interfaces and this func is rarely called - Enter_Method_Silent(); - int n = idToInterface.size(); - for (int i=0; igetNodeInputGateId()==id) - return idToInterface[i]; - return NULL; -} - -InterfaceEntry *InterfaceTable::getInterfaceByNetworkLayerGateIndex(int index) -{ - // linear search is OK because normally we have don't have many interfaces and this func is rarely called - Enter_Method_Silent(); - int n = idToInterface.size(); - for (int i=0; igetNetworkLayerGateIndex()==index) - return idToInterface[i]; - return NULL; -} - -InterfaceEntry *InterfaceTable::getInterfaceByInterfaceModule(cModule *ifmod) -{ - // ifmod is something like "host.eth[1].mac"; climb up to find "host.eth[1]" from it - cModule *host = getParentModule(); - while (ifmod && ifmod->getParentModule()!=host) - ifmod = ifmod->getParentModule(); - if (!ifmod) - throw cRuntimeError("addInterface(): specified module is not in this host/router"); - - int nodeInputGateId = -1, nodeOutputGateId = -1; - for (GateIterator i(ifmod); !i.end(); i++) - { - cGate *g = i(); - if (!g) continue; - - // find the host/router's gates that internally connect to this interface - if (g->getType()==cGate::OUTPUT && g->getNextGate() && g->getNextGate()->getOwnerModule()==host) - nodeOutputGateId = g->getNextGate()->getId(); - if (g->getType()==cGate::INPUT && g->getPreviousGate() && g->getPreviousGate()->getOwnerModule()==host) - nodeInputGateId = g->getPreviousGate()->getId(); - } - - InterfaceEntry *ie = NULL; - if (nodeInputGateId >= 0) - ie = getInterfaceByNodeInputGateId(nodeInputGateId); - if (!ie && nodeOutputGateId >= 0) - ie = getInterfaceByNodeOutputGateId(nodeOutputGateId); - - ASSERT(!ie || (ie->getNodeInputGateId() == nodeInputGateId && ie->getNodeOutputGateId() == nodeOutputGateId)); - return ie; -} - -InterfaceEntry *InterfaceTable::getInterfaceByName(const char *name) -{ - Enter_Method_Silent(); - if (!name) - return NULL; - int n = idToInterface.size(); - for (int i=0; igetName())) - return idToInterface[i]; - return NULL; -} - -InterfaceEntry *InterfaceTable::getFirstLoopbackInterface() -{ - Enter_Method_Silent(); - int n = idToInterface.size(); - for (int i=0; iisLoopback()) - return idToInterface[i]; - return NULL; -} - -InterfaceEntry *InterfaceTable::getFirstMulticastInterface() -{ - Enter_Method_Silent(); - int n = idToInterface.size(); - for (int i=0; iisMulticast() && !idToInterface[i]->isLoopback()) - return idToInterface[i]; - return NULL; -} - diff --git a/jdeeco-simulation-demo/mixim/src/inet_stub/networklayer/common/InterfaceTable.h b/jdeeco-simulation-demo/mixim/src/inet_stub/networklayer/common/InterfaceTable.h deleted file mode 100644 index 4dd4d1933..000000000 --- a/jdeeco-simulation-demo/mixim/src/inet_stub/networklayer/common/InterfaceTable.h +++ /dev/null @@ -1,207 +0,0 @@ -// -// Copyright (C) 2005 Andras Varga -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 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 Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this program; if not, see . -// - -#ifndef __INET_INTERFACETABLE_H -#define __INET_INTERFACETABLE_H - -#include - -#include "INETDefs.h" - -#include "IInterfaceTable.h" -#include "InterfaceEntry.h" -#include "NotificationBoard.h" - - -/** - * Represents the interface table. This object has one instance per host - * or router. It has methods to manage the interface table, - * so one can access functionality similar to the "ifconfig" command. - * - * See the NED documentation for general overview. - * - * This is a simple module without gates, it requires function calls to it - * (message handling does nothing). Methods are provided for reading and - * updating the interface table. - * - * Interfaces are dynamically registered: at the start of the simulation, - * every L2 module adds its own InterfaceEntry to the table; after that, - * IPv4's IRoutingTable and IPv6's RoutingTable6 (an possibly, further - * L3 protocols) add protocol-specific data on each InterfaceEntry - * (see IPv4InterfaceData, IPv6InterfaceData, and InterfaceEntry::setIPv4Data(), - * InterfaceEntry::setIPv6Data()) - * - * Interfaces are represented by InterfaceEntry objects. - * - * When interfaces need to be reliably and efficiently identified from other - * modules, interfaceIds should be used. They are better suited than pointers - * because when an interface gets removed (see deleteInterface()), it is - * often impossible/impractical to invalidate all pointers to it, and also - * because pointers are not necessarily unique (a new InterfaceEntry may get - * allocated exactly at the address of a previously deleted one). - * Interface Ids are unique (Ids of removed interfaces are not issued again), - * stale Ids can be detected, and they are also invariant to insertion/deletion. - * - * Clients can get notified about interface changes by subscribing to - * the following notifications in NotificationBoard: NF_INTERFACE_CREATED, - * NF_INTERFACE_DELETED, NF_INTERFACE_STATE_CHANGED, NF_INTERFACE_CONFIG_CHANGED. - * State change gets fired for up/down events; all other changes fire as - * config change. - * - * @see InterfaceEntry - */ -class INET_API InterfaceTable : public cSimpleModule, public IInterfaceTable, protected INotifiable -{ - protected: - NotificationBoard *nb; // cached pointer - - // primary storage for interfaces: vector indexed by id; may contain NULLs; - // slots are never reused to ensure id uniqueness - typedef std::vector InterfaceVector; - InterfaceVector idToInterface; - - // fields to support getNumInterfaces() and getInterface(pos) - int tmpNumInterfaces; // caches number of non-NULL elements of idToInterface; -1 if invalid - InterfaceEntry **tmpInterfaceList; // caches non-NULL elements of idToInterface; NULL if invalid - - protected: - // displays summary above the icon - virtual void updateDisplayString(); - - // displays the interface IPv4/IPv6 address on the outgoing link that corresponds to the interface - virtual void updateLinkDisplayString(InterfaceEntry *entry); - - // discover and store which nwlayer/host gates connect to this interface - virtual void discoverConnectingGates(InterfaceEntry *entry); - - // called from InterfaceEntry - virtual void interfaceChanged(InterfaceEntry *entry, int category); - - // internal - virtual void invalidateTmpInterfaceList(); - - public: - InterfaceTable(); - virtual ~InterfaceTable(); - virtual std::string getFullPath() const {return cSimpleModule::getFullPath();} - - protected: - virtual int numInitStages() const {return 2;} - virtual void initialize(int stage); - - /** - * Raises an error. - */ - virtual void handleMessage(cMessage *); - - public: - /** - * Called by the NotificationBoard whenever a change of a category - * occurs to which this client has subscribed. - */ - virtual void receiveChangeNotification(int category, const cObject *details); - - /** - * Returns the host or router this interface table lives in. - */ - virtual cModule *getHostModule(); - - /** - * Adds an interface. The entry->getInterfaceModule() will be used - * to discover and fill in getNetworkLayerGateIndex(), getNodeOutputGateId(), - * and getNodeInputGateId() in InterfaceEntry. It should be NULL if this is - * a virtual interface (e.g. loopback). - */ - virtual void addInterface(InterfaceEntry *entry); - - /** - * Deletes the given interface from the table. Indices of existing - * interfaces (see getInterface(int)) may change. It is an error if - * the given interface is not in the table. - */ - virtual void deleteInterface(InterfaceEntry *entry); - - /** - * Returns the number of interfaces. - */ - virtual int getNumInterfaces(); - - /** - * Returns the InterfaceEntry specified by an index 0..numInterfaces-1. - * Throws an error if index is out of range. - * - * Note that this index is NOT the same as interfaceId! Indices are - * not guaranteed to stay the same after interface addition/deletion, - * so cannot be used to reliably identify the interface. Use interfaceId - * to refer to interfaces from other modules or from messages/packets. - */ - virtual InterfaceEntry *getInterface(int pos); - - /** - * Returns an interface by its Id. Ids are guaranteed to be invariant - * to interface deletions/additions. Returns NULL if there is no such - * interface (This allows detecting stale IDs without raising an error.) - */ - virtual InterfaceEntry *getInterfaceById(int id); - - /** - * Returns an interface given by its getNodeOutputGateId(). - * Returns NULL if not found. - */ - virtual InterfaceEntry *getInterfaceByNodeOutputGateId(int id); - - /** - * Returns an interface given by its getNodeInputGateId(). - * Returns NULL if not found. - */ - virtual InterfaceEntry *getInterfaceByNodeInputGateId(int id); - - /** - * Returns an interface given by its getNetworkLayerGateIndex(). - * Returns NULL if not found. - */ - virtual InterfaceEntry *getInterfaceByNetworkLayerGateIndex(int index); - - /** - * Returns an interface by one of its component module (e.g. PPP). - * Returns NULL if not found. - */ - virtual InterfaceEntry *getInterfaceByInterfaceModule(cModule *ifmod); - - - /** - * Returns an interface given by its name. Returns NULL if not found. - */ - virtual InterfaceEntry *getInterfaceByName(const char *name); - - /** - * Returns the first interface with the isLoopback flag set. - * (If there's no loopback, it returns NULL -- but this - * should never happen because InterfaceTable itself registers a - * loopback interface on startup.) - */ - virtual InterfaceEntry *getFirstLoopbackInterface(); - - /** - * Returns the first multicast capable interface. - * If there is no such interface, then returns NULL. - */ - virtual InterfaceEntry *getFirstMulticastInterface(); -}; - -#endif - diff --git a/jdeeco-simulation-demo/mixim/src/modules/connectionManager/UnitDisk.h b/jdeeco-simulation-demo/mixim/src/modules/connectionManager/UnitDisk.h deleted file mode 100644 index 203ca47dc..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/connectionManager/UnitDisk.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * file: UnitDisk.h - * - * author: Tom Parker - * - * copyright: (C) 2006 Parallel and Distributed Systems Group (PDS) at - * Technische Universiteit Delft, The Netherlands. - * - * 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. - * For further information see file COPYING - * in the top level directory - *************************************************************************** - * description: propagation layer: unit disk model - ***************************************************************************/ -#ifndef UNIT_DISK_H -#define UNIT_DISK_H 1 - -#include "MiXiMDefs.h" -#include "ConnectionManager.h" - -//TODO: clean up UnitDisk code, maybe extends its ned file from baseConnectionManager -class MIXIM_API UnitDisk : public ConnectionManager -{ - protected: - /** @brief Holds the maximum interference range.*/ - double radioRange; - - public: - UnitDisk() : - ConnectionManager(), radioRange(0) - { - } - - /** @brief Called by Omnet++ during initialisation.*/ - void initialize(int stage); - - /** @brief Returns a constant value as maximum interference range.*/ - virtual double calcInterfDist() - { - return par("radioRange").doubleValue(); - } -}; - -#endif - diff --git a/jdeeco-simulation-demo/mixim/src/modules/mac/Mac80211.h b/jdeeco-simulation-demo/mixim/src/modules/mac/Mac80211.h deleted file mode 100644 index 55790095b..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/mac/Mac80211.h +++ /dev/null @@ -1,344 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * file: Mac80211.h - * - * author: David Raguin/Marc L�bbers - * - * copyright: (C) 2004 Telecommunication Networks Group (TKN) at - * Technische Universitaet Berlin, Germany. - * - * 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. - * For further information see file COPYING - * in the top level directory - *************************************************************************** - * part of: framework implementation developed by tkn - **************************************************************************/ - -#ifndef MAC_80211_H -#define MAC_80211_H - -#include - -#include "MiXiMDefs.h" -#include "BaseMacLayer.h" -#include "Consts80211.h" -#include "Mac80211Pkt_m.h" - -class ChannelSenseRequest; - -/** - * @brief An implementation of the 802.11b MAC. - * - * For more info, see the NED file. - * - * @ingroup macLayer - * @ingroup ieee80211 - * @author David Raguin, Karl Wessel (port for MiXiM) - */ -class MIXIM_API Mac80211 : public BaseMacLayer -{ -private: - /** @brief Copy constructor is not allowed. - */ - Mac80211(const Mac80211&); - /** @brief Assignment operator is not allowed. - */ - Mac80211& operator=(const Mac80211&); - -public: - - /** @brief frame kinds */ - enum Mac80211MessageKinds { - //between MAC layers of two nodes - RTS = LAST_BASE_MAC_MESSAGE_KIND, // request to send - CTS, // clear to send - ACK, // acknowledgement - DATA, - BROADCAST, - LAST_MAC_80211_MESSAGE_KIND - }; -protected: - /** @brief Type for a queue of Mac80211Pkts.*/ - typedef std::list MacPktList; - - /** Definition of the timer types */ - enum timerType { - TIMEOUT, - NAV - }; - - /** Definition of the states*/ - enum State { - WFDATA = 0, // waiting for data packet - QUIET = 1, // waiting for the communication between two other nodes to end - IDLE = 2, // no packet to send, no packet receiving - CONTEND = 3,// contention state (battle for the channel) - WFCTS = 4, // RTS sent, waiting for CTS - WFACK = 5, // DATA packet sent, waiting for ACK - BUSY = 6 // during transmission of an ACK or a BROADCAST packet - }; - - /** @brief Data about a neighbor host.*/ - struct NeighborEntry { - /** @brief The neighbors address.*/ - LAddress::L2Type address; - int fsc; - simtime_t age; - double bitrate; - - NeighborEntry() : address(), fsc(0), age(), bitrate(0) {} - }; - - /** @brief Type for a list of NeighborEntries.*/ - typedef std::list NeighborList; - - public: - Mac80211(); - virtual ~Mac80211(); - - virtual void initialize(int); - virtual void finish(); - - protected: - - /** @brief Handle self messages such as timer... */ - virtual void handleSelfMsg(cMessage*); - - /** @brief Handle messages from upper layer */ - virtual void handleUpperMsg(cMessage* msg); - - /** @brief Handle messages from lower layer */ - virtual void handleLowerMsg(cMessage*); - - /** @brief Handle messages from lower layer */ - virtual void handleLowerControl(cMessage*); - - - /** @brief handle end of contention */ - virtual void handleEndContentionTimer(); - - /** @brief handle a message that is not for me or errornous*/ - void handleMsgNotForMe(cMessage *af, simtime_t_cref duration); - /** @brief handle a message that was meant for me*/ - void handleMsgForMe(Mac80211Pkt*); - // ** @brief handle a Broadcast message*/ - void handleBroadcastMsg(Mac80211Pkt*); - - /** @brief handle the end of a transmission...*/ - void handleEndTransmission(); - - /** @brief handle end of SIFS*/ - void handleEndSifsTimer(); - /** @brief handle time out*/ - void handleTimeoutTimer(); - /** @brief NAV timer expired, the exchange of messages of other - stations is done*/ - void handleNavTimer(); - - void handleRTSframe(Mac80211Pkt*); - - void handleDATAframe(Mac80211Pkt*); - - void handleACKframe(Mac80211Pkt*); - - void handleCTSframe(Mac80211Pkt*); - - void dataTransmissionFailed(); - - void rtsTransmissionFailed(); - - /** @brief send data frame */ - virtual void sendDATAframe(Mac80211Pkt*); - - /** @brief send Acknoledgement */ - void sendACKframe(Mac80211Pkt*); - - /** @brief send CTS frame */ - void sendCTSframe(Mac80211Pkt*); - - /** @brief send RTS frame */ - virtual void sendRTSframe(); - - /** @brief send broadcast frame */ - void sendBROADCASTframe(); - - /** @brief encapsulate packet */ - virtual macpkt_ptr_t encapsMsg(cPacket *netw); - - /** @brief decapsulate packet */ - virtual cPacket* decapsMsg(macpkt_ptr_t frame); - - /** @brief start a new contention period */ - virtual void beginNewCycle(); - - /** @brief Compute a backoff value */ - simtime_t backoff(bool rtscts = true); - - /** @brief Test if maximum number of retries to transmit is exceeded */ - void testMaxAttempts(); - - /** @brief return a timeOut value for a certain type of frame*/ - simtime_t timeOut(Mac80211MessageKinds type, double br); - - /** @brief computes the duration of a transmission over the physical channel, given a certain bitrate */ - simtime_t packetDuration(double bits, double br); - - /** @brief Produce a readable name of the given state */ - const char *stateName(State state); - - /** @brief Sets the state, and produces a log message in between */ - void setState(State state); - - /** @brief Check whether the next packet should be send with RTS/CTS */ - bool rtsCts(Mac80211Pkt* m) { - return m->getBitLength() - MAC80211_HEADER_LENGTH > rtsCtsThreshold; - } - - /** @brief suspend an ongoing contention, pick it up again when the channel becomes idle */ - void suspendContention(); - - /** @brief figure out at which bitrate to send to this particular destination */ - double retrieveBitrate(const LAddress::L2Type& destAddress); - - /** @brief add a new entry to the neighbor list */ - void addNeighbor(Mac80211Pkt *af); - - /** @brief find a neighbor based on his address */ - NeighborList::iterator findNeighbor(const LAddress::L2Type& address) { - NeighborList::iterator it; - for(it = neighbors.begin(); it != neighbors.end(); ++it) { - if(it->address == address) break; - } - return it; - } - - /** @brief find the oldest neighbor -- usually in order to overwrite this entry */ - NeighborList::iterator findOldestNeighbor() { - NeighborList::iterator it = neighbors.begin(); - NeighborList::iterator oldIt = neighbors.begin(); - simtime_t age = it->age; - for(; it != neighbors.end(); ++it) { - if(it->age < age) { - age = it->age; - oldIt = it; - } - } - return oldIt; - } - - - /** - * @brief Starts a channel sense request which sense the channel for the - * passed duration or until the channel is busy. - * - * Used during contend state to check if the channel is free. - */ - void senseChannelWhileIdle(simtime_t_cref duration); - - /** - * @brief Creates the signal to be used for a packet to be sent. - */ - Signal* createSignal(simtime_t_cref start, simtime_t_cref length, double power, double bitrate); - -protected: - - // TIMERS: - - /** @brief Timer used for time-outs after the transmission of a RTS, - a CTS, or a DATA packet*/ - cMessage* timeout; - - /** @brief Timer used for the defer time of a node. Also called NAV : - networks allocation vector*/ - cMessage* nav; - - /** @brief Used to sense if the channel is idle for contention periods*/ - ChannelSenseRequest* contention; - - /** @brief Timer used to indicate the end of a SIFS*/ - ChannelSenseRequest* endSifs; - - /** @brief Stores the the time a channel sensing started. - * Used to calculate the quiet-time of the channel if the sensing was - * aborted. */ - simtime_t chSenseStart; - - /** @brief Current state of the MAC*/ - State state; - - /** @brief Default bitrate - * - * The default bitrate must be set in the omnetpp.ini. It is used - * whenever an auto bitrate is not appropriate, like broadcasts. - */ - double defaultBitrate; - - /** @brief The power at which data is transmitted */ - double txPower; - - /** @brief Stores the center frequency the Mac uses. */ - double centerFreq; - - /** @brief Current bit rate at which data is transmitted */ - double bitrate; - /** @brief Auto bit rate adaptation -- switch */ - bool autoBitrate; - /** @brief Hold RSSI thresholds at which to change the bitrates */ - std::vector snrThresholds; - - /** @brief Maximal number of packets in the queue; should be set in - the omnetpp.ini*/ - unsigned queueLength; - - /** @brief Boolean used to know if the next packet is a broadcast packet.*/ - bool nextIsBroadcast; - - /** @brief Buffering of messages from upper layer*/ - MacPktList fromUpperLayer; - - /** @brief Number of frame transmission attempt - * - * Incremented when the SHORT_RETRY_LIMIT is hit, or when an ACK - * or CTS is missing. - */ - unsigned longRetryCounter; - - /** @brief Number of frame transmission attempt*/ - unsigned shortRetryCounter; - - /** @brief remaining backoff time. - * If the backoff timer is interrupted, - * this variable holds the remaining backoff time. */ - simtime_t remainingBackoff; - - /** @brief current IFS value (DIFS or EIFS) - * If an error has been detected, the next backoff requires EIFS, - * once a valid frame has been received, resets to DIFS. */ - simtime_t currentIFS; - - /** @brief Number of bits in a packet before RTS/CTS is used */ - int rtsCtsThreshold; - - /** @brief Very small value used in timer scheduling in order to avoid - multiple changements of state in the same simulation time.*/ - simtime_t delta; - - /** @brief Keep information for this many neighbors */ - unsigned neighborhoodCacheSize; - /** @brief Consider information in cache outdate if it is older than this */ - simtime_t neighborhoodCacheMaxAge; - - /** @brief A list of this hosts neighbors.*/ - NeighborList neighbors; - - /** take care of switchover times */ - bool switching; - - /** sequence control -- to detect duplicates*/ - int fsc; -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/modules/netw/WiseRoute.cc b/jdeeco-simulation-demo/mixim/src/modules/netw/WiseRoute.cc deleted file mode 100644 index b66dfc193..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/netw/WiseRoute.cc +++ /dev/null @@ -1,400 +0,0 @@ -/*************************************************************************** - * file: WiseRoute.cc - * - * author: Damien Piguet, Jerome Rousselot - * - * copyright: (C) 2007-2008 CSEM SA, Neuchatel, Switzerland. - * - * description: Implementation of the routing protocol of WiseStack. - * - * 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. - * For further information see file COPYING - * in the top level directory - * - * - * Funding: This work was partially financed by the European Commission under the - * Framework 6 IST Project "Wirelessly Accessible Sensor Populations" - * (WASP) under contract IST-034963. - *************************************************************************** - * ported to Mixim 2.0.1 by Theodoros Kapourniotis - * last modification: 06/02/11 - **************************************************************************/ -#include "WiseRoute.h" - -#include -#include -#include - -#include "NetwControlInfo.h" -#include "MacToNetwControlInfo.h" -#include "ArpInterface.h" -#include "FindModule.h" -#include "WiseRoutePkt_m.h" -#include "SimTracer.h" -#include "connectionManager/ConnectionManagerAccess.h" - -using std::make_pair; - -Define_Module(WiseRoute); - -void WiseRoute::initialize(int stage) -{ - BaseNetwLayer::initialize(stage); - - if(stage == 1) { - - EV << "Host index=" << findHost()->getIndex() << ", Id=" - << findHost()->getId() << endl; - - - EV << " host IP address=" << myNetwAddr << endl; - EV << " host macaddress=" << arp->getMacAddr(myNetwAddr) << endl; - macaddress = arp->getMacAddr(myNetwAddr); - - sinkAddress = LAddress::L3Type( par("sinkAddress").longValue() ); // 0 - headerLength = par ("headerLength"); - rssiThreshold = par("rssiThreshold").doubleValue(); - rssiThreshold = FWMath::dBm2mW(rssiThreshold); - routeFloodsInterval = par("routeFloodsInterval"); - - stats = par("stats"); - trace = par("trace"); - debug = par("debug"); - useSimTracer = par("useSimTracer"); - floodSeqNumber = 0; - - nbDataPacketsForwarded = 0; - nbDataPacketsReceived = 0; - nbDataPacketsSent = 0; - nbDuplicatedFloodsReceived = 0; - nbFloodsSent = 0; - nbPureUnicastSent = 0; - nbRouteFloodsSent = 0; - nbRouteFloodsReceived = 0; - nbUnicastFloodForwarded = 0; - nbPureUnicastForwarded = 0; - nbGetRouteFailures = 0; - nbRoutesRecorded = 0; - nbHops = 0; - receivedRSSI.setName("receivedRSSI"); - routeRSSI.setName("routeRSSI"); - allReceivedRSSI.setName("allReceivedRSSI"); - receivedBER.setName("receivedBER"); - routeBER.setName("routeBER"); - allReceivedBER.setName("allReceivedBER"); - nextHopSelectionForSink.setName("nextHopSelectionForSink"); - - routeFloodTimer = new cMessage("route-flood-timer", SEND_ROUTE_FLOOD_TIMER); - // only schedule a flood of the node is a sink!! - if (routeFloodsInterval > 0 && myNetwAddr==sinkAddress) - scheduleAt(simTime() + uniform(0.5, 1.5), routeFloodTimer); - - if(useSimTracer) { - // Get a handle to the tracer module - tracer = FindModule::findGlobalModule(); - //const char *tracerModulePath = "sim.simTracer"; - //cModule *modp = simulation.getModuleByPath(tracerModulePath); - //tracer = check_and_cast(modp); - if (!tracer) { - error("No SimTracer module found, please check your ned configuration."); - } - // log node position - ChannelMobilityPtrType ptrMobility = ChannelMobilityAccessType().get(); - if (ptrMobility) { - Coord pos = ptrMobility->getCurrentPosition(); - tracer->logPosition(myNetwAddr, pos.x, pos.y, pos.z); - } - } - } -} - -WiseRoute::~WiseRoute() -{ - cancelAndDelete(routeFloodTimer); -} - -void WiseRoute::handleSelfMsg(cMessage* msg) -{ - if (msg->getKind() == SEND_ROUTE_FLOOD_TIMER) { - // Send route flood packet and restart the timer - WiseRoutePkt* pkt = new WiseRoutePkt("route-flood", ROUTE_FLOOD); - pkt->setByteLength(headerLength); - pkt->setInitialSrcAddr(myNetwAddr); - pkt->setFinalDestAddr(LAddress::L3BROADCAST); - pkt->setSrcAddr(myNetwAddr); - pkt->setDestAddr(LAddress::L3BROADCAST); - pkt->setNbHops(0); - floodTable.insert(make_pair(myNetwAddr, floodSeqNumber)); - pkt->setSeqNum(floodSeqNumber); - floodSeqNumber++; - pkt->setIsFlood(1); - setDownControlInfo(pkt, LAddress::L2BROADCAST); - sendDown(pkt); - nbFloodsSent++; - nbRouteFloodsSent++; - scheduleAt(simTime() + routeFloodsInterval + uniform(0, 1), routeFloodTimer); - } - else { - EV << "WiseRoute - handleSelfMessage: got unexpected message of kind " << msg->getKind() << endl; - delete msg; - } -} - - -void WiseRoute::handleLowerMsg(cMessage* msg) -{ - WiseRoutePkt* netwMsg = check_and_cast(msg); - const LAddress::L3Type& finalDestAddr = netwMsg->getFinalDestAddr(); - const LAddress::L3Type& initialSrcAddr = netwMsg->getInitialSrcAddr(); - const LAddress::L3Type& srcAddr = netwMsg->getSrcAddr(); - double rssi = static_cast(netwMsg->getControlInfo())->getRSSI(); - double ber = static_cast(netwMsg->getControlInfo())->getBitErrorRate(); - // Check whether the message is a flood and if it has to be forwarded. - floodTypes floodType = updateFloodTable(netwMsg->getIsFlood(), initialSrcAddr, finalDestAddr, - netwMsg->getSeqNum()); - if(trace) { - allReceivedRSSI.record(rssi); - allReceivedBER.record(ber); - } - if (floodType == DUPLICATE) { - nbDuplicatedFloodsReceived++; - delete netwMsg; - } - else { - const cObject* pCtrlInfo = NULL; - // If the message is a route flood, update the routing table. - if (netwMsg->getKind() == ROUTE_FLOOD) - updateRouteTable(initialSrcAddr, srcAddr, rssi, ber); - - if (finalDestAddr == myNetwAddr || LAddress::isL3Broadcast(finalDestAddr)) { - WiseRoutePkt* msgCopy; - if (floodType == FORWARD) { - // it's a flood. copy for delivery, forward original. - // if we are here (see updateFloodTable()), finalDestAddr == IP Broadcast. Hence finalDestAddr, - // initialSrcAddr, and destAddr have already been correctly set - // at origin, as well as the MAC control info. Hence only update - // local hop source address. - msgCopy = check_and_cast(netwMsg->dup()); - netwMsg->setSrcAddr(myNetwAddr); - pCtrlInfo = netwMsg->removeControlInfo(); - setDownControlInfo(netwMsg, LAddress::L2BROADCAST); - netwMsg->setNbHops(netwMsg->getNbHops()+1); - sendDown(netwMsg); - nbDataPacketsForwarded++; - } - else - msgCopy = netwMsg; - if (msgCopy->getKind() == DATA) { - sendUp(decapsMsg(msgCopy)); - nbDataPacketsReceived++; - } - else { - nbRouteFloodsReceived++; - delete msgCopy; - } - } - else { - // not for me. if flood, forward as flood. else select a route - if (floodType == FORWARD) { - netwMsg->setSrcAddr(myNetwAddr); - pCtrlInfo = netwMsg->removeControlInfo(); - setDownControlInfo(netwMsg, LAddress::L2BROADCAST); - netwMsg->setNbHops(netwMsg->getNbHops()+1); - sendDown(netwMsg); - nbDataPacketsForwarded++; - nbUnicastFloodForwarded++; - } - else { - LAddress::L3Type nextHop = getRoute(finalDestAddr); - if (LAddress::isL3Broadcast(nextHop)) { - // no route exist to destination, attempt to send to final destination - nextHop = finalDestAddr; - nbGetRouteFailures++; - } - netwMsg->setSrcAddr(myNetwAddr); - netwMsg->setDestAddr(nextHop); - pCtrlInfo = netwMsg->removeControlInfo(); - setDownControlInfo(netwMsg, arp->getMacAddr(nextHop)); - netwMsg->setNbHops(netwMsg->getNbHops()+1); - sendDown(netwMsg); - nbDataPacketsForwarded++; - nbPureUnicastForwarded++; - } - } - if (pCtrlInfo != NULL) - delete pCtrlInfo; - } -} - -void WiseRoute::handleLowerControl(cMessage *msg) -{ - delete msg; -} - -void WiseRoute::handleUpperMsg(cMessage* msg) -{ - LAddress::L3Type finalDestAddr; - LAddress::L3Type nextHopAddr; - LAddress::L2Type nextHopMacAddr; - WiseRoutePkt* pkt = new WiseRoutePkt(msg->getName(), DATA); - cObject* cInfo = msg->removeControlInfo(); - - pkt->setByteLength(headerLength); - - if ( cInfo == NULL ) { - EV << "WiseRoute warning: Application layer did not specifiy a destination L3 address\n" - << "\tusing broadcast address instead\n"; - finalDestAddr = LAddress::L3BROADCAST; - } - else { - EV <<"WiseRoute: CInfo removed, netw addr="<< NetwControlInfo::getAddressFromControlInfo( cInfo ) <setFinalDestAddr(finalDestAddr); - pkt->setInitialSrcAddr(myNetwAddr); - pkt->setSrcAddr(myNetwAddr); - pkt->setNbHops(0); - - if (LAddress::isL3Broadcast(finalDestAddr)) - nextHopAddr = LAddress::L3BROADCAST; - else - nextHopAddr = getRoute(finalDestAddr, true); - pkt->setDestAddr(nextHopAddr); - if (LAddress::isL3Broadcast(nextHopAddr)) { - // it's a flood. - nextHopMacAddr = LAddress::L2BROADCAST; - pkt->setIsFlood(1); - nbFloodsSent++; - // record flood in flood table - floodTable.insert(make_pair(myNetwAddr, floodSeqNumber)); - pkt->setSeqNum(floodSeqNumber); - floodSeqNumber++; - nbGetRouteFailures++; - } - else { - pkt->setIsFlood(0); - nbPureUnicastSent++; - nextHopMacAddr = arp->getMacAddr(nextHopAddr); - } - setDownControlInfo(pkt, nextHopMacAddr); - assert(static_cast(msg)); - pkt->encapsulate(static_cast(msg)); - sendDown(pkt); - nbDataPacketsSent++; -} - -void WiseRoute::finish() -{ - if (stats) { - recordScalar("nbDataPacketsForwarded", nbDataPacketsForwarded); - recordScalar("nbDataPacketsReceived", nbDataPacketsReceived); - recordScalar("nbDataPacketsSent", nbDataPacketsSent); - recordScalar("nbDuplicatedFloodsReceived", nbDuplicatedFloodsReceived); - recordScalar("nbFloodsSent", nbFloodsSent); - recordScalar("nbPureUnicastSent", nbPureUnicastSent); - recordScalar("nbRouteFloodsSent", nbRouteFloodsSent); - recordScalar("nbRouteFloodsReceived", nbRouteFloodsReceived); - recordScalar("nbUnicastFloodForwarded", nbUnicastFloodForwarded); - recordScalar("nbPureUnicastForwarded", nbPureUnicastForwarded); - recordScalar("nbGetRouteFailures", nbGetRouteFailures); - recordScalar("nbRoutesRecorded", nbRoutesRecorded); - recordScalar("meanNbHops", (double) nbHops / (double) nbDataPacketsReceived); - } - BaseNetwLayer::finish(); -} - -void WiseRoute::updateRouteTable(const LAddress::L3Type& origin, const LAddress::L3Type& lastHop, double rssi, double ber) -{ - tRouteTable::iterator pos; - - pos = routeTable.find(origin); - if(trace) { - receivedRSSI.record(rssi); - receivedBER.record(ber); - } - if (pos == routeTable.end()) { - // A route towards origin does not exist yet. Insert the currently discovered one - // only if the received RSSI is above the threshold. - if (rssi > rssiThreshold) { - tRouteTableEntry newEntry; - - // last hop from origin means next hop towards origin. - newEntry.nextHop = lastHop; - newEntry.rssi = rssi; - if(trace) { - routeRSSI.record(rssi); - routeBER.record(ber); - } - routeTable.insert(make_pair(origin, newEntry)); - if(useSimTracer) { - tracer->logLink(myNetwAddr, lastHop); - } - nbRoutesRecorded++; - if (origin == LAddress::L3NULL && trace) { - nextHopSelectionForSink.record(static_cast(lastHop)); - } - } - } - else { - // A route towards the node which originated the received packet already exists. - // Replace its entry only if the route proposal that we just received has a stronger - // RSSI. -// tRouteTableEntry entry = pos->second; -// if (entry.rssi > rssiThreshold) { -// entry.nextHop = lastHop; -// entry.rssi = rssi; -// if (origin == 0) -// nextHopSelectionForSink.record(lastHop); -// } - } -} - -cMessage* WiseRoute::decapsMsg(WiseRoutePkt *msg) -{ - cMessage *m = msg->decapsulate(); - setUpControlInfo(m, msg->getSrcAddr()); - nbHops = nbHops + msg->getNbHops(); - // delete the netw packet - delete msg; - return m; -} - -WiseRoute::floodTypes WiseRoute::updateFloodTable(bool isFlood, const tFloodTable::key_type& srcAddr, const tFloodTable::key_type& destAddr, unsigned long seqNum) -{ - if (isFlood) { - tFloodTable::iterator pos = floodTable.lower_bound(srcAddr); - tFloodTable::iterator posEnd = floodTable.upper_bound(srcAddr); - - while (pos != posEnd) { - if (seqNum == pos->second) - return DUPLICATE; // this flood is known, don't forward it. - ++pos; - } - floodTable.insert(make_pair(srcAddr, seqNum)); - if (destAddr == myNetwAddr) - return FORME; - else - return FORWARD; - } - else - return NOTAFLOOD; -} - -WiseRoute::tFloodTable::key_type WiseRoute::getRoute(const tFloodTable::key_type& destAddr, bool /*iAmOrigin*/) const -{ - // Find a route to dest address. As in the embedded code, if no route exists, indicate - // final destination as next hop. If we'are lucky, final destination is one hop away... - // If I am the origin of the packet and no route exists, use flood, hence return broadcast - // address for next hop. - tRouteTable::const_iterator pos = routeTable.find(destAddr); - if (pos != routeTable.end()) - return pos->second.nextHop; - else - return LAddress::L3BROADCAST; -} diff --git a/jdeeco-simulation-demo/mixim/src/modules/phy/PhyLayerUWBIR.cc b/jdeeco-simulation-demo/mixim/src/modules/phy/PhyLayerUWBIR.cc deleted file mode 100644 index 964bc949b..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/phy/PhyLayerUWBIR.cc +++ /dev/null @@ -1,217 +0,0 @@ -#include "PhyLayerUWBIR.h" - -#include - -#include "DeciderUWBIREDSyncOnAddress.h" -#include "DeciderUWBIREDSync.h" -#include "MacToUWBIRPhyControlInfo.h" -#include "AirFrameUWBIR_m.h" -#include "BaseWorldUtility.h" -#include "UWBIRStochasticPathlossModel.h" -#include "UWBIRIEEE802154APathlossModel.h" - -Define_Module(PhyLayerUWBIR); - -//t_dynamic_expression_value (PhyLayerUWBIR::*ghassemzadehNLOSFPtr) (cComponent *context, t_dynamic_expression_value argv[], int argc) = &ghassemzadehNLOSFunc; -PhyLayerUWBIR::fptr ghassemzadehNLOSFPtr = &PhyLayerUWBIR::ghassemzadehNLOSFunc; -Define_NED_Function(ghassemzadehNLOSFPtr, "xml ghassemzadehNLOS()"); - -void PhyLayerUWBIR::initialize(int stage) { - PhyLayerBattery::initialize(stage); - if (stage == 0) { - /* parameters belong to the NIC, not just phy layer - * - * if/when variable transmit power is supported, txCurrent - * should be specified as an xml table of available transmit - * power levels and corresponding txCurrent */ - syncCurrent = getNic()->par( "syncCurrent" ); // assume instantaneous transitions between rx and sync - uwbradio = dynamic_cast(radio); - } -} - -MiximRadio* PhyLayerUWBIR::initializeRadio() const { - int initialRadioState = par("initialRadioState"); //readPar("initalRadioState", (int) RadioUWBIR::SYNC); - double radioMinAtt = readPar("radioMinAtt", 1.0); - double radioMaxAtt = readPar("radioMaxAtt", 0.0); - - RadioUWBIR* uwbradio = RadioUWBIR::createNewUWBIRRadio(recordStats, initialRadioState, radioMinAtt, radioMaxAtt); - - // Radio timers - // From Sleep mode - uwbradio->setSwitchTime(RadioUWBIR::SLEEP, RadioUWBIR::RX, (hasPar("timeSleepToRX") ? par("timeSleepToRX") : par("timeTXToRX")).doubleValue()); - uwbradio->setSwitchTime(RadioUWBIR::SLEEP, RadioUWBIR::TX, (hasPar("timeSleepToTX") ? par("timeSleepToTX") : par("timeRXToTX")).doubleValue()); - - // From TX mode - uwbradio->setSwitchTime(RadioUWBIR::TX, RadioUWBIR::SYNC, (hasPar("timeTXToRX") ? par("timeTXToRX") : par("timeSleepToRX")).doubleValue()); - uwbradio->setSwitchTime(RadioUWBIR::TX, RadioUWBIR::RX, (hasPar("timeTXToRX") ? par("timeTXToRX") : par("timeSleepToRX")).doubleValue()); - - // From RX mode - uwbradio->setSwitchTime(RadioUWBIR::RX, RadioUWBIR::TX, (hasPar("timeRXToTX") ? par("timeRXToTX") : par("timeSleepToTX")).doubleValue()); - uwbradio->setSwitchTime(RadioUWBIR::RX, RadioUWBIR::SYNC, (readPar("timeRXToSYNC", readPar("timeSYNCToRX", 0.000000001)))); - uwbradio->setSwitchTime(RadioUWBIR::SYNC, RadioUWBIR::TX, (hasPar("timeRXToTX") ? par("timeRXToTX") : par("timeSleepToTX")).doubleValue()); - - // From SYNC mode - uwbradio->setSwitchTime(RadioUWBIR::SYNC, RadioUWBIR::RX, (readPar("timeSYNCToRX", readPar("timeRXToSYNC", 0.000000001)))); - - return uwbradio; -} - -AnalogueModel* PhyLayerUWBIR::getAnalogueModelFromName(const std::string& name, ParameterMap& params) const { - if (name == "UWBIRStochasticPathlossModel") - return createAnalogueModel(params); - - if (name == "UWBIRIEEE802154APathlossModel") - return createAnalogueModel(params); - - return PhyLayerBattery::getAnalogueModelFromName(name, params); -} - -Decider* PhyLayerUWBIR::getDeciderFromName(const std::string& name, ParameterMap& params) { - if (name == "DeciderUWBIREDSyncOnAddress") { - protocolId = IEEE_802154_UWB; - return createDecider(params);; - } - if (name == "DeciderUWBIREDSync") { - protocolId = IEEE_802154_UWB; - return createDecider(params); - } - if (name=="DeciderUWBIRED") { - protocolId = IEEE_802154_UWB; - return createDecider(params); - } - - return PhyLayerBattery::getDeciderFromName(name, params); -} - -void PhyLayerUWBIR::setSwitchingCurrent(int from, int to) { - int act = SWITCHING_ACCT; - double current = 0; - - if (from != to && (from == RadioUWBIR::SYNC || to == RadioUWBIR::SYNC)) { - if (from == RadioUWBIR::SYNC) { - switch(to) { - case RadioUWBIR::RX: - case RadioUWBIR::SLEEP: - current = syncCurrent; - break; - case RadioUWBIR::TX: - current = rxTxCurrent; - break; - // ! transitions between rx and sync should be immediate - default: - opp_error("Unknown radio switch! From SYNC to %d", to); - break; - } - } - else { - switch(from) { - case RadioUWBIR::RX: - current = syncCurrent; - break; - case RadioUWBIR::SLEEP: - current = setupRxCurrent; - break; - case RadioUWBIR::TX: - current = txRxCurrent; - break; - // ! transitions between rx and sync should be immediate - default: - opp_error("Unknown radio switch! From %d to SYNC", from); - break; - } - } - } - else { - PhyLayerBattery::setSwitchingCurrent(from, to); - return; - } - - MiximBatteryAccess::drawCurrent(current, act); -} - -void PhyLayerUWBIR::setRadioCurrent(int rs) { - switch(rs) { - case RadioUWBIR::SYNC: - MiximBatteryAccess::drawCurrent(syncCurrent, SYNC_ACCT); - break; - case RadioUWBIR::SWITCHING: - // do nothing here - break; - default: - PhyLayerBattery::setRadioCurrent(rs); - break; - } -} - -simtime_t PhyLayerUWBIR::setRadioState(int rs) { - int prevState = radio->getCurrentState(); - - if(prevState == RadioUWBIR::RX && rs != RadioUWBIR::RX && rs != RadioUWBIR::SYNC) { - decider->cancelProcessSignal(); - } - - return PhyLayerBattery::setRadioState(rs); -} - -bool PhyLayerUWBIR::isRadioInRX() const { - const int iCurRS = getRadioState(); - - return iCurRS == RadioUWBIR::RX || iCurRS == RadioUWBIR::SYNC; -} - -PhyLayerUWBIR::airframe_ptr_t PhyLayerUWBIR::encapsMsg(cPacket *macPkt) -{ - // the cMessage passed must be a MacPacket... but no cast needed here - // MacPkt* pkt = static_cast(msg); - - // ...and must always have a ControlInfo attached (contains Signal) - cObject* ctrlInfo = macPkt->removeControlInfo(); - assert(ctrlInfo); - - // create the new AirFrame - AirFrameUWBIR* frame = new AirFrameUWBIR("airframe", AIR_FRAME); - - // Retrieve the pointer to the Signal-instance from the ControlInfo-instance. - // We are now the new owner of this instance. - Signal* s = MacToUWBIRPhyControlInfo::getSignalFromControlInfo(ctrlInfo); - // make sure we really obtained a pointer to an instance - assert(s); - - // set the members - assert(s->getDuration() > 0); - frame->setDuration(s->getDuration()); - // copy the signal into the AirFrame - frame->setSignal(*s); - //set priority of AirFrames above the normal priority to ensure - //channel consistency (before any thing else happens at a time - //point t make sure that the channel has removed every AirFrame - //ended at t and added every AirFrame started at t) - frame->setSchedulingPriority(airFramePriority); - frame->setProtocolId(myProtocolId()); - frame->setBitLength(headerLength); - frame->setId(world->getUniqueAirFrameId()); - frame->setChannel(radio->getCurrentChannel()); - frame->setCfg(MacToUWBIRPhyControlInfo::getConfigFromControlInfo(ctrlInfo)); - - // pointer and Signal not needed anymore - delete s; - s = 0; - - // delete the Control info - delete ctrlInfo; - ctrlInfo = 0; - - frame->encapsulate(macPkt); - - // --- from here on, the AirFrame is the owner of the MacPacket --- - macPkt = 0; - coreEV <<"AirFrame encapsulated, length: " << frame->getBitLength() << "\n"; - - return frame; -} - - -void PhyLayerUWBIR::finish() { - PhyLayerBattery::finish(); -} - diff --git a/jdeeco-simulation-demo/mixim/src/modules/phy/PhyLayerUWBIR.h b/jdeeco-simulation-demo/mixim/src/modules/phy/PhyLayerUWBIR.h deleted file mode 100644 index 9647a9528..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/phy/PhyLayerUWBIR.h +++ /dev/null @@ -1,240 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * file: PhyLayerUWBIR.h - * - * author: Jerome Rousselot - * - * copyright: (C) 2008 Centre Suisse d'Electronique et Microtechnique (CSEM) SA - * Systems Engineering - * Wireless Embedded Systems - * Jaquet-Droz 1, CH-2002 Neuchatel, Switzerland. - * - * - * 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. - * For further information see file COPYING - * in the top level directory - * description: this physical layer models an ultra wideband impulse radio channel. - * acknowledgment: this work was supported (in part) by the National Competence - * Center in Research on Mobile Information and Communication Systems - * NCCR-MICS, a center supported by the Swiss National Science - * Foundation under grant number 5005-67322. - ***************************************************************************/ -// -// A physical layer that models an Ultra Wideband Impulse Radio wireless communication system. -// -// This class loads channel models and delivers frames to an UWB Decider. It is independent of the modulation technique, -// as long as the frames are represented using the same approach as in IEEE802154A.h (Maximum Pulse Amplitude Estimation). -// -// Several channel models are possible: Ghassemzadeh-LOS, Ghassemadeh-NLOS (see UWBIRStochasticPathlossModel.h) -// and the IEEE 802.15.4A UWB channel models that use the default power delay profile (see UWBIRIEEE802154APathlossModel.h). -// -// Currently, an energy detection receiver is modeled in UWBIRED.h. -// Several synchronization logics have been implemented in derived classes: -// see DeciderUWBIREDSync.h and and DeciderUWBIREDSyncOnAddress.h. -// -// To add a novel receiver (e.g. coherent demodulation), either derive UWBIRED or write a new one, -// then add functionality in this module to load the new decider. -// The same procedure applies for new channel models. -// -// To change the modulation, see UWBIRMac.h, IEEE802154A.h and UWBIRED.h. -// -// To implement optional modes of IEEE802154A, see IEEE802154A.h. -// -// Citation of the following publication is appreciated if you use the MiXiM UWB PHY model -// for a publication of your own. -// J. Rousselot, J.-D. Decotignie, An ultra-wideband impulse radio PHY -// layer model for network simulation. SIMULATION January 2011 vol. 87 no. 1-2 82-112. -// -// For more information, see also: -// -// [1] J. Rousselot, J.-D. Decotignie, An ultra-wideband impulse radio PHY -// layer model for network simulation. SIMULATION January 2011 vol. 87 no. -// 1-2 82-112. http://dx.doi.org/10.1177/0037549710377767 -// [2] J. Rousselot, Ultra Low Power Communication Protocols for UWB -// Impulse Radio Wireless Sensor Networks. EPFL Thesis 4720, 2010. -// http://infoscience.epfl.ch/record/147987 -// [3] A High-Precision Ultra Wideband Impulse Radio Physical Layer Model -// for Network Simulation, Jérôme Rousselot, Jean-Dominique Decotignie, -// Second International Omnet++ Workshop,Simu'TOOLS, Rome, 6 Mar 09. -// http://portal.acm.org/citation.cfm?id=1537714 -// -#ifndef UWBIR_PHY_LAYER_H -#define UWBIR_PHY_LAYER_H - -#include "MiXiMDefs.h" -#include "PhyLayerBattery.h" -#include "RadioUWBIR.h" -#include "HostState.h" - -class DeciderUWBIREDSyncOnAddress; -class DeciderUWBIREDSync; - -#include "DeciderUWBIRED.h" - -#if (OMNETPP_VERSION >= 0x0402) - typedef cNEDValue t_dynamic_expression_value; -#else - typedef cDynamicExpression::Value t_dynamic_expression_value; -#endif - -/** - * @brief Physical layer that models an Ultra Wideband Impulse Radio wireless communication system. - * - * This class loads channel models and deliver frames to an UWB Decider. It is independent of the modulation technique, - * as long as the frames are represented using the same approach as in IEEE802154A.h (Maximum Pulse Amplitude Estimation). - * - * Several channel models are possible: Ghassemzadeh-LOS, Ghassemadeh-NLOS (see UWBIRStochasticPathlossModel.h) - * and the IEEE 802.15.4A UWB channel models that use the default power delay profile (see UWBIRIEEE802154APathlossModel.h). - * - * Currently, an energy detection receiver is modeled in UWBIRED.h. - * Several synchronization logics have been implemented in derived classes: - * see DeciderUWBIREDSync.h and and DeciderUWBIREDSyncOnAddress.h. - * - * If you want to add a novel receiver (e.g. coherent demodulation), either derive UWBIRED or write your own, - * then add functionality in this module to load your decider. - * The same apply for new channel models. - * - * To change the modulation, refer to UWBIRMac.h, IEEE802154A.h and UWBIRED.h. - * To implement optional modes of IEEE802154A, refer to IEEE802154A.h. - * - * Refer to the following publications for more information: - * [1] An Ultra Wideband Impulse Radio PHY Layer Model for Network Simulation, - * J. Rousselot, J.-D. Decotignie, Simulation: Transactions of the Society - * for Computer Simulation, 2010 (to appear). - * [2] A High-Precision Ultra Wideband Impulse Radio Physical Layer Model - * for Network Simulation, Jérôme Rousselot, Jean-Dominique Decotignie, - * Second International Omnet++ Workshop,Simu'TOOLS, Rome, 6 Mar 09. - * http://portal.acm.org/citation.cfm?id=1537714 - * - * @ingroup ieee802154a - * @ingroup phyLayer - * @ingroup power - */ -class MIXIM_API PhyLayerUWBIR : public PhyLayerBattery -{ - friend class DeciderUWBIRED; -private: - /** @brief Copy constructor is not allowed. - */ - PhyLayerUWBIR(const PhyLayerUWBIR&); - /** @brief Assignment operator is not allowed. - */ - PhyLayerUWBIR& operator=(const PhyLayerUWBIR&); - -public: - PhyLayerUWBIR() - : PhyLayerBattery() - , uwbradio(NULL) - , syncCurrent(0) - {} - - virtual void finish(); - - // this function allows to include common xml documents for ned parameters as ned functions - static t_dynamic_expression_value ghassemzadehNLOSFunc(cComponent */*context*/, t_dynamic_expression_value argv[] __attribute__((unused)), int /*argc*/) { - const char * ghassemzadehnlosxml = - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - ""; - cXMLParImpl xmlParser; - xmlParser.parse(ghassemzadehnlosxml); // from char* to xml - t_dynamic_expression_value parameters(xmlParser.xmlValue(NULL)); // from xml to Value - return parameters; - } - typedef t_dynamic_expression_value (*fptr) (cComponent *context, t_dynamic_expression_value argv[], int argc); - static fptr ghassemzadehNLOSFPtr; - //static t_dynamic_expression_value (*ghassemzadehNLOSFPtr) (cComponent *context, t_dynamic_expression_value argv[], int argc); - -protected: - virtual airframe_ptr_t encapsMsg(cPacket *msg); - - /** - * @brief Creates and returns an instance of the AnalogueModel with the - * specified name. - * - * Is able to initialize the following AnalogueModels: - * - UWBIRStochasticPathlossModel - * - UWBIRIEEE802154APathlossModel - */ - virtual AnalogueModel* getAnalogueModelFromName(const std::string& name, ParameterMap& params) const; - - /** - * @brief Creates and returns an instance of the decider with the specified - * name. - * - * Is able to initialize directly the following decider: - * - DeciderUWBIREDSyncOnAddress - * - DeciderUWBIREDSync - * - DeciderUWBIRED - */ - virtual Decider* getDeciderFromName(const std::string& name, ParameterMap& params); - virtual MiximRadio* initializeRadio() const; - - RadioUWBIR* uwbradio; - - virtual void switchRadioToRX() { - Enter_Method_Silent(); - uwbradio->startReceivingFrame(simTime()); - setRadioCurrent(radio->getCurrentState()); - } - - virtual void switchRadioToSync() { - Enter_Method_Silent(); - uwbradio->finishReceivingFrame(simTime()); - setRadioCurrent(radio->getCurrentState()); - } - - /** @brief The different currents in mA.*/ - double syncCurrent; - - /** - * @brief Defines the power consuming activities (accounts) of - * the NIC. Should be the same as defined in the decider. - */ - enum Activities { - SLEEP_ACCT=0, - RX_ACCT, //1 - TX_ACCT, //2 - SWITCHING_ACCT, //3 - SYNC_ACCT, //4 - }; - - enum ProtocolIds { - IEEE_802154_UWB = 3200, - }; - - /** @brief Updates the actual current drawn for the passed state.*/ - virtual void setRadioCurrent(int rs); - - /** @brief Updates the actual current drawn for switching between - * the passed states.*/ - virtual void setSwitchingCurrent(int from, int to); - -public: - virtual void initialize(int stage); - - /** - * @brief Captures radio switches to adjust power consumption. - */ - virtual simtime_t setRadioState(int rs); - - /** - * @brief Returns the true if the radio is in RX state. - */ - virtual bool isRadioInRX() const; -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/modules/power/battery/BatteryStats.h b/jdeeco-simulation-demo/mixim/src/modules/power/battery/BatteryStats.h deleted file mode 100644 index 77e8fb428..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/power/battery/BatteryStats.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * Energy Framework for Omnet++, version 0.9 - * - * Author: Laura Marie Feeney - * - * Copyright 2009 Swedish Institute of Computer Science. - * - * This software is provided `as is' and without any express or implied - * warranties, including, but not limited to, the implied warranties of - * merchantability and fitness for a particular purpose. - * - ***************************************************************************/ -#ifndef BATTERYSTATS_H -#define BATTERYSTATS_H - -#include - -#include "MiXiMDefs.h" -#include "BaseModule.h" -#include "BaseBattery.h" - -class DeviceEntry; - -/** - * @brief collects and formates statistical data from the battery - * - * See BatteryStats.ned for parameters - * - * Generates time series information from BatteryState information - * published by the battery and by reading its s-o-c information - * (currently not interesting). Also generates summary statistics - * when the Battery module passes its DeviceEntry table at finish(). - * Note: only BatteryStats modules should access BatteryState - * information, other modules should use Battery's estimateResidual - * method. - * - * @ingroup power - */ -class MIXIM_API BatteryStats : public BaseModule -{ - private: - /** @brief Copy constructor is not allowed. - */ - BatteryStats(const BatteryStats&); - /** @brief Assignment operator is not allowed. - */ - BatteryStats& operator=(const BatteryStats&); - - public: - BatteryStats() - : BaseModule() - , doDetail(0) - , doTimeSeries(0) - , residualVec() - , relativeVec() - , estimateVec() - , estimateRelVec() - {} - - /** @brief Signal for the BatteryStats.*/ - const static simsignalwrap_t catBatteryStateSignal; - - virtual void initialize(int); - virtual void handleMessage(cMessage*); - virtual void receiveSignal(cComponent *source, simsignal_t signalID, cObject *obj); - virtual void finish(); - - /** @brief invoked by the Battery Module's finish() - * - * (should not rely on BatteryStats::finish() to clean up resources - */ - virtual void summary(double, double, simtime_t_cref); - /** @brief invoked by the Battery Module's at finish() - * - * (should not rely on BatteryStats::finish() to clean up resources - */ - virtual void detail(const DeviceEntry *, int); - - protected: - int doDetail; - /** @brief Enable tracking of output vectors?*/ - int doTimeSeries; - - /** @name Tracked statistic values.*/ - /*@{*/ - cOutVector residualVec; - cOutVector relativeVec; - cOutVector estimateVec; - cOutVector estimateRelVec; - /*@}*/ -}; -#endif diff --git a/jdeeco-simulation-demo/mixim/src/modules/power/battery/SimpleBattery.h b/jdeeco-simulation-demo/mixim/src/modules/power/battery/SimpleBattery.h deleted file mode 100644 index 97731f30e..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/power/battery/SimpleBattery.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * Energy Framework for Omnet++, version 0.9 - * - * Author: Laura Marie Feeney - * - * Copyright 2009 Swedish Institute of Computer Science. - * - * This software is provided `as is' and without any express or implied - * warranties, including, but not limited to, the implied warranties of - * merchantability and fitness for a particular purpose. - * - ***************************************************************************/ -#ifndef BATTERY_H -#define BATTERY_H - -#include - -#include "MiXiMDefs.h" -#include "BaseBattery.h" - -#include "BatteryState.h" -#include "HostState.h" - -#include "DeviceEntry.h" - -/** - * @brief A simple linear model of battery consumption. - * - * See SimpleBattery.ned for parameters - * - * Simple Battery receives DrawMsg's from one or more devices, updates - * residual capacity (total current * voltage * time), publishes - * HostState notification on battery depletion, and provides time - * series and summary information to Battery Stats module. - * - * @ingroup power - * @author Laura Marie Feeney - * @author Karl Wessel (port for MiXiM) - */ - -class MIXIM_API SimpleBattery: public BaseBattery { -private: - /** @brief Copy constructor is not allowed. - */ - SimpleBattery(const SimpleBattery&); - /** @brief Assignment operator is not allowed. - */ - SimpleBattery& operator=(const SimpleBattery&); - -public: - SimpleBattery(); - virtual ~SimpleBattery(); - virtual void initialize(int); - virtual void handleMessage(cMessage*); - virtual void handleHostState(const HostState& state); - virtual void finish(); - - /** - * @name State-of-charge interface - * - * @brief Other host modules should use these interfaces to obtain - * the state-of-charge of the battery. Do NOT use BatteryState - * interfaces, which should be used only by Battery Stats modules. - */ - /*@{*/ - /** @brief get voltage (future support for non-voltage regulated h/w */ - double getVoltage() const; - /** @brief current state of charge of the battery, relative to its - * rated nominal capacity [0..1] - */ - double estimateResidualRelative() const; - /** @brief current state of charge of the battery (mW-s) */ - double estimateResidualAbs() const; - /*@}*/ - - /** - * @brief Registers a power device by creating a new DeviceEntry for it. - */ - virtual int registerDevice(const std::string& name, int numAccounts); - - /** - * @brief Draws either a certain amount of energy in mWs or - * a defined current in mA over time, depending on passed DrawAmount. - */ - virtual void draw(int drainID, DrawAmount& amount, int activity); - - virtual HostState::States getState() const { - return hostState.get(); - } - -protected: - - /** @brief The maximum amount of different power drawing devices.*/ - int numDevices; - - /** @name battery parameters*/ - /*@{*/ - /** @brief Actual capacity.*/ - double capmAh; - /** @brief Nominal capacity.*/ - double nominalCapmAh; - /** @brief Voltage*/ - double voltage; - /*@}*/ - - /** @brief Debit battery at least once every resolution seconds.*/ - simtime_t resolution; - cMessage *timeout; - - /** @name publishing of capacity to BatteryStats via the BB. */ - /*@{*/ - cMessage *publish; - double publishDelta; - simtime_t publishTime; - - /** @brief Holds the state of the battery.*/ - BatteryState *batteryState; - /*@}*/ - - /** @name publish of host failure notification - * @brief everyone should subscribe to this*/ - /*@{*/ - HostState hostState; - /*@}*/ - - /** @name INTERNAL state*/ - /*@{*/ - double capacity; - double nominalCapacity; - double residualCapacity; - double lastPublishCapacity; - simtime_t lifetime; - /*@}*/ - - /** @brief Ouput vector tracking the residual capacity.*/ - cOutVector residualVec; - - /** @brief Array of different power consuming devices.*/ - DeviceEntry *devices; - /** @brief Amount of currently registered devices.*/ - int registeredDevices; - - /** @brief Self message kinds used by the battery.*/ - enum msgType { - AUTO_UPDATE, - PUBLISH, - }; - - simtime_t lastUpdateTime; - /** @brief Pointer to host module */ - cModule* host; - virtual void deductAndCheck(); -}; - -#endif diff --git a/jdeeco-simulation-demo/mixim/src/modules/utility/SimTracer.cc b/jdeeco-simulation-demo/mixim/src/modules/utility/SimTracer.cc deleted file mode 100644 index 01cd93957..000000000 --- a/jdeeco-simulation-demo/mixim/src/modules/utility/SimTracer.cc +++ /dev/null @@ -1,175 +0,0 @@ -/* -*- mode:c++ -*- ******************************************************** - * file: SimTracer.cc - * - * author: Jerome Rousselot - * - * copyright: (C) 2007-2009 CSEM SA, Neuchatel, Switzerland - * - * 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. - * For further information see file COPYING - * in the top level directory - * - * Funding: This work was partially financed by the European Commission under the - * Framework 6 IST Project "Wirelessly Accessible Sensor Populations" - * (WASP) under contract IST-034963. - *************************************************************************** - * part of: Modifications to the MF-2 framework by CSEM - **************************************************************************/ -#include "SimTracer.h" - -#include "FindModule.h" -#include "BaseLayer.h" - -using std::map; -using std::string; - -Define_Module(SimTracer); - -/* - * Open some log files and write some static initializations stuff. - */ -void SimTracer::initialize(int stage) -{ - cSimpleModule::initialize(stage); - if (stage == 0) { - char treeName[250]; - /*int n; - n =*/ sprintf(treeName, "results/tree-%d.txt", - cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getActiveRunNumber()); - treeFile.open(treeName); - if (!treeFile) { - EV << "Error opening output stream for routing tree statistics." - << endl; - } else { - treeFile << "graph aRoutingTree " << endl << "{" << endl; - } - goodputVec.setName("goodput"); - pSinkVec.setName("sinkPowerConsumption"); - pSensorVec.setName("sensorPowerConsumption"); - nbApplPacketsSent = 0; - nbApplPacketsReceived = 0; - - // retrieve pointer to BaseWorldUtility module - world = FindModule::findGlobalModule(); - //world = check_and_cast(cSimulation::getActiveSimulation()->getModuleByPath("sim.world")); - if (world) { - world->subscribe(BaseLayer::catPacketSignal.initialize(), this); - } - else { - error("No BaseWorldUtility module found, please check your ned configuration."); - } - -// } else if(stage == 1) { // it seems that we are initialized only once. Why ? - } -} - -// compute current average sensor power consumption -double SimTracer::getAvgSensorPowerConsumption() const { - double sensorAvgP = 0; - int nbSensors = 0; - - map < unsigned long, double >::const_iterator iter = powerConsumptions.begin(); // address, powerConsumption - for (; iter != powerConsumptions.end(); ++iter) { // iterate over all nodes power consumptions - if(iter->first == 0) - continue; - - double eval = iter->second; - eval = eval + SIMTIME_DBL(simTime() - lastUpdates.at(iter->first)) * currPower.at(iter->first); - eval = eval * 1000 / SIMTIME_DBL(simTime()); - - ++nbSensors; - sensorAvgP += eval; - } - if (nbSensors) { - sensorAvgP = sensorAvgP / nbSensors; - } - return sensorAvgP; -} - -double SimTracer::getSinkPowerConsumption() const { - map < unsigned long, double >::const_iterator iter = powerConsumptions.find(0); - if (iter == powerConsumptions.end()) - return 0.0; - double sinkP = iter->second; - sinkP = sinkP + SIMTIME_DBL(simTime() - lastUpdates.at(iter->first)) * currPower.at(iter->first); - sinkP = sinkP * 1000 / SIMTIME_DBL(simTime()); - return sinkP; -} - -/* - * Close the nam log file. - */ -void SimTracer::finish() -{ - double goodput = 0; - if(nbApplPacketsSent > 0) { - goodput = ((double) nbApplPacketsReceived)/nbApplPacketsSent; - } else { - goodput = 0; - } - recordScalar("Application Packet Success Rate", goodput); - recordScalar("Application packets received", nbApplPacketsReceived); - recordScalar("Application packets sent", nbApplPacketsSent); - recordScalar("Sink power consumption", getSinkPowerConsumption()); - recordScalar("Sensor average power consumption", getAvgSensorPowerConsumption()); - if (treeFile) { - treeFile << "}" << endl; - treeFile.close(); - } - -} - -/* - * Record a line into the nam log file. - */ -void SimTracer::namLog(string /*namString*/) -{ - //Enter_Method_Silent(); - //namFile << namString << endl; -} - -void SimTracer::radioEnergyLog(unsigned long mac, int /*state*/, - simtime_t_cref duration, double power, double newPower) -{ - Enter_Method_Silent(); - /* - radioEnergyFile << mac << "\t" << state << "\t" << duration << "\t" << power - << endl; - */ - if (powerConsumptions.count(mac) == 0) { - powerConsumptions[mac] = 0; - } - powerConsumptions[mac] = powerConsumptions[mac] + power * SIMTIME_DBL(duration); - currPower[mac] = newPower; - lastUpdates[mac] = simTime(); - if(mac != 0) { - pSensorVec.record(getAvgSensorPowerConsumption()); - } else { - pSinkVec.record(getSinkPowerConsumption()); - } -} - -void SimTracer::logPosition(int node, double x, double y, double /*z*/) -{ - treeFile << node << "[pos=\""<< x << ", " << y << "!\"];" << endl; -} - -void SimTracer::receiveSignal(cComponent */*source*/, simsignal_t signalID, cObject *obj) -{ - if (signalID == BaseLayer::catPacketSignal) { - packet = *(static_cast(obj)); - // nbApplPacketsSent = nbApplPacketsSent + packet.getNbPacketsSent(); - // nbApplPacketsReceived = nbApplPacketsReceived + packet.getNbPacketsReceived(); - if(packet.isSent()) { - nbApplPacketsSent = nbApplPacketsSent + 1; - } else { - nbApplPacketsReceived = nbApplPacketsReceived + 1; - } - goodputVec.record(((double) nbApplPacketsReceived)/nbApplPacketsSent); - } -} -