Overriding function does not execute EV<< command? - overriding

I'm using Omnet++ 4.6 and I created a class to inherit AODVRouting. Now, I created a function in my new class that overrides handleMessage() from the parent class. Compiler indicates that the function is indeed overridden. I typed an EV<< command to print the start of the function to event log, yet it does not print to the event log. What is the problem??
Function in the the parent class is virtual and protected. This is my inherited class.cc:
//
// 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 3 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 http://www.gnu.org/licenses/.
//
#include "MalAODVRouter.h"
#include "IPv4ControlInfo.h"
Define_Module(MalAODVRouter);
MalAODVRouter::MalAODVRouter()
{
AODVRouting::AODVRouting();
}
void MalAODVRouter::initialize(int stage)
{
AODVRouting::initialize(stage);
}
void MalAODVRouter::handleMessage(cMessage *msg)
{
std::cout<<"Mal Host Activity"<<endl;
EV <<"Mal Host Activity \n";
this->bubble("Mal Host Activity");
//capturedMsgs++;
//if (capturedMsgs==1) // One out of every 10 packets (frequency of replay)
//{
cMessage *ReplayMsg = msg->dup();
std::cout<<"Done Duplicating MSG"<<endl;
EV<<"Done Duplicating MSG \n";
/*UDPPacket *udpPacket = dynamic_cast<UDPPacket *>(msg);
AODVControlPacket *ctrlPacket = check_and_cast<AODVControlPacket *>(udpPacket->decapsulate());
IPv4ControlInfo *udpProtocolCtrlInfo = dynamic_cast<IPv4ControlInfo *>(udpPacket->getControlInfo());
ASSERT(udpProtocolCtrlInfo != NULL);
IPv4Address sourceAddr = udpProtocolCtrlInfo->getSrcAddr(); //get Source Address
IPv4Address destinationAddr = udpProtocolCtrlInfo->getDestAddr(); //get Destination Address
IPv4Address addr = getSelfIPAddress();
if (addr != destinationAddr) // if it is not destined for "Eve"
{
UDPPacket *ReplayUDPPacket = udpPacket;
AODVControlPacket *ReplayCtrlPacket = check_and_cast<AODVControlPacket *>(ReplayUDPPacket->decapsulate());
IPv4ControlInfo *ReplayUDPProtocolCtrlInfo = dynamic_cast<IPv4ControlInfo *>(ReplayUDPPacket->getControlInfo());
ASSERT(ReplayUDPProtocolCtrlInfo != NULL);
ReplayUDPProtocolCtrlInfo->setSrcAddr(sourceAddr); //Forge Source
ReplayUDPProtocolCtrlInfo->setDestAddr(destinationAddr); //Keep Destination
*/
//we can add a delay before sending the copy of the message again (10 time units)
scheduleAt(simTime() + 1, ReplayMsg);
//sendDelayed(ReplayMsg, 0.1,"ipOut");
ReplayedMsgs++;
std::cout<<"Launched Replay Packet!\n";
EV<<"Launched Replay Packet!\n";
this->bubble("Attack");
//this->capturedMsgs=0;
// }
//}
AODVRouting::handleMessage(msg);
std::cout<<"Finished handling msg"<<endl;
EV<<"Finished handling msg"<<endl;
}
/*void MalAODVRouter::finish()
{
recordScalar("captured Msgs", capturedMsgs);
recordScalar("Replayed Msgs", ReplayedMsgs);
}*/
MalAODVRouter::~MalAODVRouter()
{
AODVRouting::~AODVRouting();
}
And this is my .h file:
//
// 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 3 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 http://www.gnu.org/licenses/.
//
#ifndef __COPS_MALAODVROUTER_H_
#define __COPS_MALAODVROUTER_H_
#include "AODVRouting.h"
#include <omnetpp.h>
/**
* TODO - Generated class
*/
class MalAODVRouter : public AODVRouting
{
protected:
virtual void initialize(int stage) override;
virtual void handleMessage(cMessage *msg) override;
public:
MalAODVRouter();
//finish();
~MalAODVRouter();
int capturedMsgs=0;
int ReplayedMsgs=0;
};
#endif

In order to view own messages generated by EV you need to switch log viewer to "module output" mode. Start the simulation, and in the bottom right window press the rightmost icon.

Make sure Class is registered has the macro >> Define_Module(....);
(seems done)
Make sure Class is linked >> you should be able to get a full list of
all registered classes in your simulation by running it with the "-h
classes" option
Verify that the name in the ned file is the same as the configuration file cc
try this right click on the folder of the project
Properties >> Omnet++ >> Makemake >> Apply

Related

Can't figure out how or why this code solves an error. ESP32 arduino IDE with platform dot io

I am fairly new to coding and especially to C++ but usually with enough googling and breaking problems down to simpler blocks I can figure things out. This issue makes no sense to me though and the solution I just happened to come up with on accident makes even less sense to me.
I am writing a program for ESP32-S in vscode with platformio and broke this down to isolate what was causing the error and found this issue with class/object declaration:
This code will compile but I get a link error twice that says
undefined reference to `point::point()'
#include <Arduino.h>
class point {
public:
point();
point(uint day){
this->_day = day;
}
uint _day;
};
class channel {
public:
channel(String _color, byte _pin){
}
point _points[64];
};
channel red("red", 0);
void setup() {}
void loop() {}
Meanwhile this code with one seemingly unrelated change compiles and links without issue:
#include <Arduino.h>
class point {
public:
point();
point(uint day){
this->_day = day;
}
uint _day;
};
class channel {
public:
channel(){ // <--- Removing the arguments from channel constructor fixes it?
}
point _points[64];
};
channel red(); // <--- And here of course
void setup() {}
void loop() {}
I don't know why that fixes it, and I have a workaround for now if this is what I have to do, but I want to understand. Thanks.
You've declared a constructor point::point(), but not defined it (i.e. it has no body). This is not OK with the linker and that's what you're being told.
There are three ways to fix this.
Don't declare the constructor (compiler generates a default constructor which may or may not initialize the member _day to 0, depending on compiler and platform). Note that you also have the interesting alternative of deleting the default constructor.
Declare and define it to do whatever you consider appropriate.
Give your constructor point::point(uint day) a default argument value, e.g.: point::point(uint day = 0).
Side note on C style arrays of C++ objects like here:
point _points[64];
This is a dangerous combination, unless you know exactly what you're doing. See the C++ FAQ

How to handle user interaction with new Bluetooth prompt in iOS13?

"There’s a new key for the Info.plist file: NSBluetoothAlwaysUsageDescription, which you can use to explain how and why your app uses Bluetooth. In contrast to the existing NSBluetoothPeripheralUsageDescription, the new description will be shown as part of the new pop-up, and also in the Settings app on the Bluetooth Privacy screens."
After updating to iOS 13, our app experienced crashes, as I'm sure many did. Our problem was due to not including the newly required bluetooth key in the Xamarin.iOS projects Info.plist file.
However after adding this upon loading the first "action" that occurs is presenting the user with the new Bluetooth access prompt.
We aren't clearly seeing how to capture the response to this prompt. In-fact after this prompt is interacted with the app has no "return" point as it were. Can't quite find a break-point for the prompt interaction / result handling and our app never returns from the prompt. It's running but the next "action" to occur never happens.
So- how to capture/handle user's interaction with the new Bluetooth prompt in iOS 13?
NOTE*: To be absolutely transparent - our application doesn't initialize any instance of CBCentralManager rather it takes advantage of a native framework that itself utilizes Bluetooth LE internally (out of our control).
Our case might be quite unique but for those experiencing this implement CBCentralManager and utilize its UpdatedState method to capture user interaction with the newly presented Bluetooth dialogue.
Initialization called in page creation of our Apps MainPage
BleManager = new BluetoothManager();
Class
using System;
using CoreBluetooth;
namespace MyApp.iOS.Classes
{
public class BluetoothManager
{
public CBCentralManager CentralBleManager
{
get { return this.bleCntrlMgr; }
}
protected CBCentralManager bleCntrlMgr;
protected CBCentralManagerDelegate bleMgrDel;
public BluetoothManager()
{
this.bleCntrlMgr = new CoreBluetooth.CBCentralManager();
this.bleCntrlMgr.UpdatedState += BleMgr_UpdatedState;
}
private void BleMgr_UpdatedState(object sender, EventArgs e)
{
Console.WriteLine("UpdatedState: {0}", bleCntrlMgr.State);
if (bleCntrlMgr.State == CBCentralManagerState.PoweredOn
|| bleCntrlMgr.State == CBCentralManagerState.PoweredOff
|| bleCntrlMgr.State == CBCentralManagerState.Resetting
|| bleCntrlMgr.State == CBCentralManagerState.Unauthorized
|| bleCntrlMgr.State == CBCentralManagerState.Unsupported)
{
/* return point */
// i.e.: CallMethod();
}
else if (bleCntrlMgr.State == CBCentralManagerState.Unknown)
{
/* <-- request access --> */
}
}
}
}

Unexpected behavior when using freeRTOS with two tasks

I am using MPU9250-breakout board with Arduino Uno.
The library I used is from here.
Below is my code.
#include <Arduino_FreeRTOS.h>
#include "mpu9250.h"
MPU9250 IMU(Wire,0x68);
int status;
void task_1(void *pvParameters)
{
(void) pvParameters;
for (;;)
{
}
}
void task_2(void *pvParameters)
{
(void) pvParameters;
for (;;)
{
}
}
void setup() {
Serial.begin(115200);
while(!Serial) {}
status = IMU.begin();
if (status < 0) {
Serial.println("IMU initialization unsuccessful");
Serial.println("Check IMU wiring or try cycling power");
Serial.print("Status: ");
Serial.println(status);
while(1) {}
}
xTaskCreate(
task_2,
(const portCHAR *)"task2", // A name just for humans
128, // Stack size
NULL,
1, // priority
NULL);
xTaskCreate(
task_1,
(const portCHAR *)"task1", // A name just for humans
128, // Stack size
NULL,
1, // priority
NULL);
}
void loop()
{
}
The problem is that when there are two tasks defined, the program will be restarted automatically. But when I comment out task_1, the program works fine. The result value of xTaskCreate is correct.
I guess the problem might be the stack or heap size is too small, but I've increased stack and heap size and it's still doesn't work.
Can anyone tell me where the problem might be from?
At the end of your setup(), you need to start the scheduler:
// Now the task scheduler, which takes over control of scheduling individual tasks, //is automatically started.
vTaskStartScheduler();
That is all I see different between my project which works and yours.
Once you have created your tasks, you have to start scheduler.
Call vTaskStartScheduler() before exiting setup function and after you have created your tasks.
https://www.freertos.org/a00132.html
Just for the info, Arduino-UNO (with ATMega-328P) has very limited RAM and it may happen some tasks won't be created. Check return value of xTaskCreate functions.
When I run into this problem, it's usually been that my interrupt vectors weren't pointing to appropriate handlers. So when the RTOS needed to do a context switch, for example, it jumped off into la-la land. Since you say that taking out the tasks allows it to run to the library call, but fails in the same way, it is possible none of your handlers are setup correctly.
The FreeRTOS website has an FAQ about getting new projects to run that I would suggest reading through to help troubleshoot this kind of problem:
https://www.freertos.org/FAQHelp.html#faq
You might also look at some of the other AVR examples included with FreeRTOS to see how they have interrupts setup: https://www.freertos.org/a00090.html#ATMEL

C++ Game - Should I initialize game states more than once?

I have a bare bones game state system worked out however I need some advice on how to improve it. I have a GameState.h that all the game states inherit from. Therefore to manage the game states I have a class that stores a vector of game states
std::vector<GameState *> gameStates;
This handles the game states but using function like pop/push(_back).
At the moment I am creating my game states like this:
.h
GameState *mainMenu = nullptr;
GameState *inGame = nullptr;
.cpp
mainMenu = new MainMenuState();
inGame = new InGameState();
then initializing them like so:
mainMenu->initialize(this, camera);
inGame->initialize(this, camera);
then adding them to the vector like this:
setCurrentGameState(mainMenu);
should I do it like I am already doing it or like this:
setCurrentGameState(new MainMenuState(this, camera));
Should I initialize all of the game states at the start of the game or should I initialize them when they are pushed into the vector then delete them again whey they are popped? In the past I have tried to initialize them when they are pushed however it makes handling the memory much harder. However would initializing all of the game states a the start of the game hinder performance?
What i can say from my experience is: It depends on how big is your game.
A little suggestion. You can split your game in multiple FSM. One for main menu/options/credits part and one for the "real" game part. In this way you can instantiate all the states for the current FSM in use and call the related methods to activate them.
One little architecture example:
class State
{
public:
virtual void OnEnter() = 0;
virtual void OnUpdate(float i_fTime) = 0;
virtual void OnExit() = 0;
};
class FSM
{
public:
/*
here you call onenter for the state where you want
to go and onexit for the current state
*/
virtual void GoToState( const std::string& state_name ) = 0;
/*
here you call OnUpdate method on m_pCurrentState
*/
virtual void Update( float i_fTime ) = 0;
private:
State* m_pCurrentState;
std::map<std::string, State*> m_mStates;
};
class FSMSystem
{
public:
void SetCurrentFSM( FSM* i_pFSM );
void Update( float i_fTime );
private:
FSM* m_pCurrentFSM;
};
For each of your custom fsm, you have to implement from FSM interface. For each of your custom state, you have to implement State class.
Initialize your state inside constructor ( or an init method ) during the creation of your FSM. Leave the heavy stuff ( like texture loading/complex algorithm or similar request to the OnEnter method ).

Qt can not respond key Press event immediately

Environment: Ubuntu, Qt Creator
In my Qt app, I found that sometimes Qt doesn't respond to my key press event immediately, but if I wait a while, it eventually responds.
I think something is blocking the UI.
As I know, if a Qt's component (QWidget etc.) is being destroyed, the Qt UI will be blocked. I have checked my code, there is no component being destroyed at the time I'm pressing the up/down key.
I really want to know is there any other things can block Qt UI.
{
...
connect(webViewWidget, SIGNAL(loadfinished()), this, SLOT(addItem()));
...
}
void addItem()
{
delete webViewWidget; // will this delete block UI?
mListWidget = new ScrollWidget();
mScrollArea = new ScrollArea(this);
for(int i=0; i<Datalen; i++)
{
mListWidget->addSubItem(itemWidget);
}
}
void keyPressEvent(QKeyEvent *event)
{
switch(event->key)
{
case UP_KEY:
scroll up;
break;
case DOWN_KEY:
scroll down;
break;
default:
break;
}
}
In general, your key press event will not be processed before all other events which were put into the application's event queue before pressing your key are processed.
Therefore it could be any kind of event which has not finished processing. Maybe you can figure out if there are any events, e.g. by using QApplication::hasPendingEvents or by inheriting from QApplication and adding debug output whenever an event is added or fully processed.
Destruction of objects is usually not a concern, unless you are doing a lot of work in the destructor. Destroying a webview may take long. You probably should not be destroying it like you do. Instrument that delete (see code below) and see how long it takes.
Your own code may be calling APIs that block. Are you calling any third party libraries? Are you calling any wait... methods in Qt's own API?
If you're unsure, you can instrument every slot and every reimplemented virtual method like xxxEvent(...). You'd need to instrument only slots and reimplemented QObject/QWidget methods, not every method in your code.
You may be producing an event storm, perhaps by posting lots of events in a loop, or by sending a lot of signals that are hooked up to slots connected via a Qt::QueuedConnection. Make sure you're not calling repaint() from within paintEvent() for example.
The instrumentation example below uses RAII and is very easy to apply. Alternatively, you can use a profiler.
#include <QElapsedTimer>
#define INSTRUMENT() Instrument instr__ument(__FUNCTION__)
#define INSTRUMENTLIM(lim) Instrument instr__ument(__FUNCTION__, (lim))
class Instrument {
QElapsedTimer timer;
int limit;
const char * function;
public:
Instrument(const char * name, int timeLimitMs = 20) :
function(name), limit(timeLimitMs) { timer.start(); }
~Instrument() {
if (timer.elapsed() > limit) {
qDebug("%s was slow, took %d ms", function, timer.elapsed());
}
}
}
void slot(...)
{
INSTRUMENT();
...
}
void addItem()
{
INSTRUMENT();
delete webViewWidget; // will this delete block UI?
mListWidget = new ScrollWidget();
mScrollArea = new ScrollArea(this);
for(int i=0; i<Datalen; i++)
{
mListWidget->addSubItem(itemWidget);
}
}

Resources