/*
 * task.h
 *
 *  Created on: Oct 29, 2021
 *      Author: compi
 */

#ifndef FSL_TASK_H_
#define FSL_TASK_H_

#include <FreeRTOS.h>
#include <task.h>	// FreeRTOS
#include <semphr.h>	// FreeRTOS

namespace fsl {

template<typename T, uint32_t stackSize> class Task {
public:
	Task(UBaseType_t priority, void (T::*fp)()) : m_priority(priority), m_fp(fp) {}
	void Start() {
		m_handle = xTaskCreateStatic(taskStaticBridge, getName(), sizeof(m_stack)/sizeof(m_stack[0]),
				this, m_priority, m_stack, &m_tcb);
	}
	virtual ~Task() {};
	virtual char const * getName() = 0;

private:
    static void taskStaticBridge(void *_this) {
        (static_cast<T*>(reinterpret_cast<Task<T, stackSize>*>(_this))->*(reinterpret_cast<Task<T, stackSize>*>(_this)->m_fp))();
    }

	TaskHandle_t m_handle;
	UBaseType_t m_priority;
    void (T::*m_fp)();
	StaticTask_t m_tcb;
	StackType_t m_stack[stackSize];
};

} /* namespace fsl */

#endif /* FSL_TASK_H_ */
