void OMNeTBattery::draw(int deviceID, DrawAmount& amount, int activity) { if (amount.getType() == DrawAmount::CURRENT) { double current = amount.getValue(); if (activity < 0 && current != 0) { error("Invalid parameters for OMNeTBattery::draw"); } EV << simTime() << " device " << deviceID << " drew current " << current << "mA, activity = " << activity << endl; // update the residual capacity (finish previous current draw) updateResidualEnergy(); // set the new current draw in the device vector deviceEntryVector[deviceID]->currentEnergyDraw = current; deviceEntryVector[deviceID]->currentActivity = activity; } else if (amount.getType() == DrawAmount::ENERGY) { double energy = amount.getValue(); if (!(activity >= 0 && activity < deviceEntryVector[deviceID]->numberOfActivities)) { error("Invalid activity specified"); } EV << simTime() << " device " << deviceID << " deduct " << energy << " mW-s, activity = " << activity << endl; // deduct a fixed energy cost deviceEntryVector[deviceID]->accts[activity] += energy; residualCapacityInMilliWattSeconds -= energy; // update the residual capacity (ongoing current draw) updateResidualEnergy(); } else { error("Unknown power type!"); } }
virtual void handleMessage(cMessage *msg) override { delete msg; messageCount++; interarrivalTimeAccumulated += simTime().dbl() - lastArrivalTime; lastArrivalTime = simTime().dbl(); //emit(arrivalSignal, interarrivalTimeAccumulated); //Trigger signal to save data //emit(arrivalSignal, lastArrivalTime); //Trigger signal to save data double currentInterarrival = interarrivalTimeAccumulated/messageCount; emit(arrivalSignal, currentInterarrival); //Trigger signal to save data EV << "Recieved message. Current interarrival time is: " << interarrivalTimeAccumulated / messageCount << "s" << endl; }
void HTokenBucket::activity(){ while(true){ EV<<"TokenQsize: "<<queue_size<<" simTime:"<< simTime() <<" last_token:"<< last_sent <<std::endl; cMessage* msg = receive(); if(msg != NULL && (queue_size < max_queue_size)){ Packet* packet = check_and_cast<Packet*>(msg); for(unsigned i = 0; i<queue.size(); i++){//wrzuca w odpowiednie miejsce kolejki w zaleznosci od priorytetu if(packet->getPriority() > queue[i]->getPriority() && queue_size > 0){ queue.insert(queue.begin()+i, packet); break; } } if(queue.size()==queue_size)//Jak nie znalazl sobie miejsca, to dorzuca pakiet na koncu queue.push_back(packet); EV<<"Token packet queued"<<std::endl; queued++; }else{ EV<<"Token packet rejected"<<std::endl; rejected++; } if((simTime()-last_sent) > interval && tokens_size < max_tokens_size){ tokens.push_back(true); last_sent = simTime(); EV<<"Token added"<<std::endl; } if(tokens_size>0){ Packet* packet = queue.front(); queue.erase(queue.begin()); send(packet, "out"); sent++; tokens.erase(tokens.begin()); EV<<"Token packet sent"<<std::endl; } for(unsigned i=0; i<tokens.size(); i++){ if((simTime() - queue[i]->getCreationTime()) > max_ttl) queue.erase(queue.begin()+i); } tokens_size = tokens.size(); queue_size = queue.size(); } }
void OMNeTBattery::initialize(int stage) { if(stage == 0) { notificationBoard = NotificationBoardAccess().get(); checkCompatibilityToRadioState(); voltageInVolts = par("voltage"); double capacityInMilliAmpereHours = par("capacity"); capacityInMilliWattSeconds = capacityInMilliAmpereHours * 60 * 60 * voltageInVolts; residualCapacityInMilliWattSeconds = capacityInMilliWattSeconds; energyVectorDelta = par("energyVectorDelta"); lastStoredResidualEnergyInMilliWattSeconds = residualCapacityInMilliWattSeconds; updateInterval = par("updateInterval"); if (updateInterval > 0) { lastUpdateTime = simTime(); publishMessage = new cMessage("Update energy"); publishMessage->setSchedulingPriority(2000); scheduleAt(updateInterval, publishMessage); } else { EV << "Warning: Battery is disabled (updateInterval is <= 0)" << std::endl; } residualEnergyOutVector.setName("energyLevel"); residualEnergyOutVector.record(residualCapacityInMilliWattSeconds); WATCH(residualCapacityInMilliWattSeconds); updateBatteryIcon(); } }
void HostUtility::create_junction_host(int aid) { AimsunWorldUtility *world = NULL; world = FindModule<AimsunWorldUtility*>::findGlobalModule(); if(!world) { throw cRuntimeError("Cannot get Aimsun World Utility!"); } int vector_size = world->get_vehicles() + world->get_junctions(); try { const unsigned short *attr_name = NULL; attr_name = AKIConvertFromAsciiString("GKNode:omnetpp_module"); void *attr = ANGConnGetAttribute(attr_name); const unsigned short *name = NULL; name = ANGConnGetAttributeValueString(attr, aid); bool anyNonAsciiChar = false; std::string module_name = AKIConvertToAsciiString(name, false, &anyNonAsciiChar); const unsigned short *attr_x_name = AKIConvertFromAsciiString("GKNode:x"); void *attr_x = ANGConnGetAttribute(attr_x_name); double x = ANGConnGetAttributeValueDouble(attr_x, aid); const unsigned short *attr_y_name = AKIConvertFromAsciiString("GKNode:y"); void *attr_y = ANGConnGetAttribute(attr_y_name); double y = ANGConnGetAttributeValueDouble(attr_y, aid); const unsigned short *attr_z_name = AKIConvertFromAsciiString("GKNode:z"); void *attr_z = ANGConnGetAttribute(attr_z_name); double z = ANGConnGetAttributeValueDouble(attr_z, aid); if (module_name != "") { cModuleType *moduleType = cModuleType::get(module_name.c_str()); cModule *module = moduleType->create("hosts", this->getParentModule(), vector_size, index); index++; // set up parameters and gate sizes before we set up itsubmodules module->par("aid") = aid; module->par("x") = x; module->par("y") = y; module->par("z") = z; module->finalizeParameters(); // create internals, and schedule it module->buildInside(); module->scheduleStart(simTime()); module->callInitialize(); junctions->insert(std::pair<int, cModule*>(aid, module)); } } catch (std::exception& e) { AimsunPrint(std::string(e.what())); } }
Packet* SimpleGen::generateMessage() { char name[20]; int src = getId(); int dest = 31337; int priority = intrand(5) + 1; int Payload = 1; int ByteLength = intuniform(0, 1000); int ds = intrand(2); packetId += 1; // Generate simple message name sprintf(name, "msg-%d", packetId); //Create new packet Packet* packet = new Packet(name); // Set properties packet->setSessionID(sessionId); packet->setPacketID(packetId); packet->setSrc(src); packet->setDst(dest); packet->setSessionID(sessionId); packet->setPacketID(packetId); packet->setPriority(priority); packet->setPayload(Payload); packet->setByteLength(ByteLength); packet->setDs(ds); packet->setCreationTime(simTime().dbl()); return packet; }
/* * Draw info strings on screen, like FPS */ void CLGLWindowDrawInfo(void) { if(CLGLWindow::showInfo == true){ std::stringstream fps(std::stringstream::in | std::stringstream::out); std::stringstream simTime(std::stringstream::in | std::stringstream::out); static std::stringstream pause(std::stringstream::in | std::stringstream::out); static std::stringstream kernel(std::stringstream::in | std::stringstream::out); pause.seekp(std::ios::beg); kernel.seekp(std::ios::beg); // Draw FPS fps << "FPS: " << CLGLWindow::fps; CLGLWindowDrawString(fps.str().c_str(), 1, CLGLWindow::window_height-CLGLWindow::fontSize, CLGLWindow::stringColor, CLGLWindow::font); // Draw How many particles are beeing simulated and if it is paused if(CLGLWindow::play == ON){ pause << "Simulating " << CLGLWindow::NumParticles << " Particles"; CLGLWindowDrawString(pause.str().c_str(), 1, 33, CLGLWindow::stringColor, CLGLWindow::font); } else{ CLGLWindowDrawString("Paused", 1, 33, CLGLWindow::stringColor, CLGLWindow::font); } // Draw Current Kernel in Use kernel << "Kernel: Gravity with Runge Kutta " << CLGLSim::curKernel << std::endl; CLGLWindowDrawString(kernel.str().c_str(), 1, 7, CLGLWindow::stringColor, CLGLWindow::font); } }
void Context::start() { mSignalHandler = Signal::registerHandler( std::tr1::bind(&Context::handleSignal, this, std::tr1::placeholders::_1) ); if (mSimDuration == Duration::zero()) return; Time t_now = simTime(); Time t_end = simTime(mSimDuration); Duration wait_dur = t_end - t_now; mFinishedTimer->wait( wait_dur, mainStrand->wrap( std::tr1::bind(&Context::shutdown, this) ) ); }
void OMNeTBattery::handleMessage(cMessage* message) { if (message->isSelfMessage() == false) { error("Can not handle any external messages"); } updateResidualEnergy(); if(residualCapacityInMilliWattSeconds > 0) { scheduleAt(simTime() + updateInterval, publishMessage); } }
virtual void initialize() override { // Get delay time as random value from exponential distribution as set in omnetpp.ini. //simtime_t delay = par("delayTime"); currentNumber=1; currentNumber=randGenerator.generateNumber(currentNumber); currentUniformValue= Dist.uniformValue(0,1,currentNumber); //Map random number into uniform function simtime_t delay = expDist.expValue(1,currentUniformValue); //Get x where exponential cumulative function is the random value scheduleAt(simTime() + delay, new cMessage("selfmsg")); }
void HostUtility::enter_vehicle(int aid, int sid) { AimsunWorldUtility *world = NULL; int vector_size; const unsigned short *attr_name = NULL; const unsigned short *name = NULL; bool anyNonAsciiChar = false; int obj_id; std::string module_name = ""; world = FindModule<AimsunWorldUtility*>::findGlobalModule(); vector_size = world->get_vehicles() + world->get_junctions(); try { StaticInfVeh info = AKIVehGetStaticInf(aid); name = AKIVehGetVehTypeName(info.type); obj_id = ANGConnGetObjectId(name, false); attr_name = AKIConvertFromAsciiString("GKVehicle::omnetpp_module"); name = ANGConnGetAttributeValueString(ANGConnGetAttribute(attr_name), obj_id); if (name == NULL) { throw cRuntimeError("Cannot get ANG Object Attribute."); } module_name = AKIConvertToAsciiString(name, false, &anyNonAsciiChar); if (module_name != "") { cModuleType *moduleType = cModuleType::get(module_name.c_str()); cModule *module = moduleType->create("hosts", this->getParentModule(), vector_size, index); index++; // set up parameters and gate sizes before we set up itsubmodules module->par("aid") = aid; module->par("section") = sid; module->finalizeParameters(); // create internals, and schedule it module->buildInside(); module->scheduleStart(simTime()); module->callInitialize(); vehicles->insert(std::pair<int, cModule*>(aid, module)); } } catch (std::exception& e) { AimsunPrint(std::string(e.what())); } }
void OMNeTBattery::calculateConsumedEnergy() { calculateConsumedEnergyOfStandardDevices(); calculateConsumedEnergyOfWirelessDevices(); if (residualCapacityInMilliWattSeconds <= 0.0 ) { handleDepletedEnergy(); } else { EV << "[BATTERY]: residual capacity = " << residualCapacityInMilliWattSeconds << "\n"; } lastUpdateTime = simTime(); }
void OMNeTBattery::calculateConsumedEnergyOfStandardDevices() { SimTime now = simTime(); for (unsigned int i = 0; i < deviceEntryVector.size(); i++) { int currentActivity = deviceEntryVector[i]->currentActivity; if (currentActivity != NO_ACTIVITY) { double usedEnergy = deviceEntryVector[i]->currentEnergyDraw * voltageInVolts * (now - lastUpdateTime).dbl(); if (usedEnergy > 0) { deviceEntryVector[i]->accts[currentActivity] += usedEnergy; residualCapacityInMilliWattSeconds -= usedEnergy; } } } }
virtual void handleMessage(cMessage *msg) override { delete msg; //simtime_t delay = par("delayTime"); currentNumber=randGenerator.generateNumber(currentNumber); currentUniformValue= Dist.uniformValue(0,1,currentNumber); //Map random number into cumulative function simtime_t delay = expDist.expValue(1,currentUniformValue); //Get x where exponential cumulative function is the random value EV << "Delay expired, sending another message. New delay is: " << delay << endl; // Send out a message to the reciever. send(new cMessage("msg"), "out"); // Schedule a self message after delay. scheduleAt(simTime() + delay, new cMessage("selfmsg")); }
void OMNeTBattery::calculateConsumedEnergyOfWirelessDevices() { SimTime now = simTime(); for (DeviceEntryMap::iterator it = deviceEntryMap.begin(); it!=deviceEntryMap.end(); it++) { DeviceEntry* deviceEntry = it->second; int currentActivity = deviceEntry->currentActivity; if (currentActivity != NO_ACTIVITY) { double usedEnergy = deviceEntry->currentEnergyDraw * voltageInVolts * (now - lastUpdateTime).dbl(); if (usedEnergy > 0) { deviceEntry->accts[currentActivity] += usedEnergy; residualCapacityInMilliWattSeconds -= usedEnergy; } } } }
void Detector::handleMessage(cMessage *msg) { if (msg->arrivedOn("clock")) { // Schedule evaluation just a bit later, so that we have all sketches scheduleAt( simTime() + simtime_t(getParentModule()->par("interval")) * .8, msg); } else if (msg->isSelfMessage()) { evaluateCores(); delete msg; clearReports(); } else if (msg->arrivedOn("graphServerIn")) { updateCores(check_and_cast<CoresUpdate*>(msg)); } else if (msg->arrivedOn("reportsIn")) { updateReports(check_and_cast<Report*>(msg)); } else { delete msg; } }
void SimpleGen::handleMessage(cMessage* msg) { if (msg == event) { // Calculate delay double delay = getDelay(); emit(eventSignal, delay); if (canSendMessage()) { // It's time to send message, so prepare new one and send send(generateMessage(), "out"); } // Send next message after delay scheduleAt(simTime() + delay, event); } else { // This should never happen, but for sure delete delete msg; } }
void Clock::handleMessage(cMessage *msg) { for (int i = 0; i < gateSize("out"); i++) send(msg->dup(), "out",i); scheduleAt(simTime()+ interval, msg); }
void Clock::finish(){ cancelAndDelete(timer); recordScalar("Interval", interval); recordScalar("StartTime", par("waitTime").doubleValue()); recordScalar("EndTime", simTime()); }
/** In a few, rare cases, you'll need the *actual* time representation * rather than an offset since the start of simulation. In those cases, * this method gives you the real time, in UTC. Note that this is still in * relation to a "global" epoch, so it is still not convertible directly * to, e.g. a Unix time. For that you'll need to use * Timer::getSpecifiedDate to get a relative offset. * * NOTE: Only use these methods if you absolutely have to. */ Time realTime() const { return simTime() + (mEpoch.read()-Time::null()) + Timer::getUTCOffset(); }
void OMNeTBattery::handleDepletedEnergy() { EV << "[BATTERY]: " << getParentModule()->getFullName() <<" 's battery exhausted" << std::endl; residualCapacityInMilliWattSeconds = 0; deactivateAllRegisteredDevices(); recordScalar("nodeEnergyDepletionTimestamp", simTime()); }