/*********************************************************************************
 * PROJECT: MiMic
 * --------------------------------------------------------------------------------
 *
 * This file is part of MiMic
 * Copyright (C)2011 Ryo Iizuka
 *
 * MiMic 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 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/>.
 *
 * For further information please contact.
 *	http://nyatla.jp/
 *	<airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp>
 *
 *********************************************************************************/
#include "NyLPC_cThread.h"
#include "FreeRTOS.h"

#include "task.h"
#include "semphr.h"




static void _task(void *pvParameters);

void NyLPC_cThread_initialize(NyLPC_TcThread_t* i_inst,NyLPC_TInt32 i_stack)
{
	i_inst->_sbit=NyLPC_TcThread_BIT_IS_TERMINATED;
	NyLPC_AbortIfNot(pdPASS==xTaskCreate(
		_task,
		(const portCHAR*)"th",
		i_stack<1?NyLPC_TcThread_DEFAULT_STACKSIZE:i_stack,
		( void * ) i_inst,
		tskIDLE_PRIORITY,
		&(i_inst->_taskid)));
}

void NyLPC_cThread_start(NyLPC_TcThread_t* i_inst,NyLPC_TcThread_ThreadFunc i_func,void* i_param)
{
	NyLPC_ArgAssert(i_inst!=NULL);
	NyLPC_ArgAssert(i_func!=NULL);
	i_inst->_func=i_func;
	i_inst->_param=i_param;
	i_inst->_sbit=0;
	vTaskResume(i_inst->_taskid);
	return;
}
void NyLPC_cThread_join(NyLPC_TcThread_t* i_inst)
{
	NyLPC_TUInt32_setBit(i_inst->_sbit,NyLPC_TcThread_BIT_IS_JOIN_REQ);
	while(!NyLPC_TUInt32_isBitOn(i_inst->_sbit,NyLPC_TcThread_BIT_IS_TERMINATED))
	{
		vTaskDelay(2);//少し待つ。
	}
	//終了
	return;
}

static void _task(void *pvParameters)
{
	NyLPC_TcThread_t* inst=(NyLPC_TcThread_t*)pvParameters;
	vTaskSuspend(inst->_taskid);
	for(;;){
		inst->_func(inst->_param);
		NyLPC_TUInt32_setBit(inst->_sbit,NyLPC_TcThread_BIT_IS_TERMINATED);
		vTaskSuspend(inst->_taskid);
	}
}

