arkhipenko / TaskScheduler

Cooperative multitasking for Arduino, ESPx, STM32, nRF and other microcontrollers
http://playground.arduino.cc/Code/TaskScheduler
BSD 3-Clause "New" or "Revised" License
1.33k stars 243 forks source link

TaskScheduler Task Callbacks With OO in Callback #174

Closed tkw722 closed 10 months ago

tkw722 commented 1 year ago

Hello! I love leveraging the TaskScheduler, but I'm hoping to use it in something more advanced that a typical single file sketch. Instead I'm hoping to use it throughout a more object oriented project. That said, I'm running into some challenges. Here's an example sketch that I think highlights what I'm seeing:

#include <Arduino.h>
#include <Wire.h>

#include "TaskScheduler.h"

Scheduler *scheduler;

Task *TestTask;

class TestClass
{
public:
    void doSomething()
    {
        // we do something here
    }
};

void setup()
{
    Wire.begin();
    Serial.begin(115200);

    delay(1000);

    scheduler = new Scheduler();

    TestClass *inst = new TestClass();

    Task *TestTask = new Task(100, TASK_FOREVER, []()
                              { inst->doSomething(); });

    scheduler->addTask(*TestTask);

    TestTask->enable();
}

// the loop function runs over and over again forever
void loop()
{
    scheduler->execute();
}

Understandably, without having inst in the capture list, I get the error:

an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list

If I add it to the capture list such as:

Task *TestTask = new Task(100, TASK_FOREVER, [inst]()
                              { inst->doSomething(); });

Now instead I get an error on Task that says:

no instance of constructor "Task::Task" matches the argument listC/C++(289) test.cpp(29, 30): argument types are: (int, int, lambda []()->void)

I'm struggling to figure out how to be able to use TaskScheduler in an object oriented context where I may want to leverage it in files other than the main sketch file. I want to avoid being forced to have whatever I leverage in a Task callback being global in scope.

Anyone have any experience in using the TaskScheduler in this manner?

tkw722 commented 1 year ago

Aha! I have just discovered:

#define _TASK_STD_FUNCTION

I think that has got me squared away. I'll circle back if not.

arkhipenko commented 10 months ago

assuming you found the solution. reopen if not.