Search code examples
c++omnet++veins

How can my RSU call a function at periodic time intervals in Veins?


I am currently working on an algorithm on Veins 4.7.1 where many vehicles and a RSU are sending and receiving messages.

I would like now my RSU to perform periodic calculations regardless if it sended or received a message. The problem is I don't know how and where to implement these periodic calculations in my RSU application.

My first attempt was to implement the calculations in one of the functions provided in BaseWaveApplLayer. I though about adding them in handlePositionUpdate(cObject* obj) with a timer, but I obviously cannot use this function in the RSU application.

Any help would be really appreciated.


Solution

  • Using self messages is typical way of doing periodic task in a module. However, it might be problematic if you need to do several tasks. You need to create all messages first, handle them correctly and remember to cancelAndDelete them in a destructor.

    You can achieve the same result with less code using Veins utility called TimerManager (added in Veins 4.7.). You need to have a member of TimerManager in the module and specify tasks in initialize. The advantage is that if you decide to add new periodic tasks later, it is as simple as adding them in initialize and TimerManager will take care of everything else. It might look like this:

    class TraCIDemoRSU11p : public DemoBaseApplLayer {
    public:
        void initialize(int stage) override;
        // ...
    protected:
        veins::TimerManager timerManager{this};  // define and instantiate the TimerManager
        // ...
    };
    

    And initialize

    void TraCIDemoRSU11p::initialize(int stage) {
        if (stage == 0) {       // Members and pointers initialization       
        }
        else if (stage == 1) {  // Members that require initialized other modules           
            // encode the reaction to the timer firing with a lambda
            auto recurringCallback = [this](){
                //Perform Calculations
            };
            // specify when and how ofthen a timer shall fire
            auto recurringTimerSpec = veins::TimerSpecification(recurringCallback).interval(1);
            // register the timer with the TimerManager instance
            timerManager.create(recurringTimerSpec, "recurring timer");
        }
    }
    

    Read more in the manual on Github: TimerManager manual. The code with comments is taken from there.