/*****************************************************
event6.c :
  μITRON サンプルプログラム
  Copyright(C) 2002-2003 佐々木芳

イベントの実装

*****************************************************/

#include "hal.h"
#include "itron.h"
#include "event6.h"
#include "debug.h"

void DisplayContext(void)
{
	BOOL ctx = sns_ctx();
	if(ctx)
		CMTRACE("app: handler context.\n");
	else
		CMTRACE("app: task context.\n");

	ctx = sns_loc();
	if(ctx)
		CMTRACE("app: lock context.\n");
	else
		CMTRACE("app: unlock context.\n");

	ctx = sns_dsp();
	if(ctx)
		CMTRACE("app: disable dispatch context.\n");
	else
		CMTRACE("app: enable disptach context.\n");

	ctx = sns_dpn();
	if(ctx)
		CMTRACE("app: disable context.\n");
	else
		CMTRACE("app: enable context.\n");
}


ER kpSendEvent(ID evMbx, EVENT* pEvent)
{
	ER ercd;
	pEvent->evMbx = evMbx;
	ercd = snd_mbx(evMbx, (T_MSG*)pEvent);
	if(ercd != E_OK){
		CMTRACE("event: snd_mbx ercd=%d\n", ercd);
	}
	return ercd;
}

EVENT* kpWaitEvent(ID evMbx)
{
	T_MSG* pMsg;
	EVENT* pEvent = NULL;
	ER ercd = rcv_mbx(evMbx, &pMsg);
	if((ercd == E_OK) && pMsg){
		pEvent = (EVENT*)pMsg;
	}else{
		//CMTRACE("event: rcv_mbx ercd=%d\n", ercd);
		DebugPrintf("event: rcv_mbx ercd=%d\n", ercd);
		if(ercd == E_CTX) DisplayContext();
		FATAL_ERROR("イベント待ちエラー。");
	}
	return pEvent;
}

EVENT* kpWaitEventTimeout(ID evMbx, TMO tmout)
{
	T_MSG* pMsg;
	EVENT* pEvent = NULL;
	ER ercd = trcv_mbx(evMbx, &pMsg, tmout);
	if(ercd == E_OK){
		pEvent = (EVENT*)pMsg;
	}else{
		CMTRACE("event: trcv_mbx ercd=%d\n", ercd);
		if(ercd == E_CTX) DisplayContext();
		FATAL_ERROR("イベント待ちエラー。");
	}
	return pEvent;
}

EVENT* kpCreateEvent(UINT event)
{
	VP p_blk;
	EVENT* pEvent = NULL;
	ER ercd = pget_mpf(MPF_Event, &p_blk);
	if(ercd == E_OK){
		pEvent			= (EVENT*)p_blk;
		pEvent->evMbx	= 0;			//送信先は未設定
		pEvent->event	= event;		//イベントID
		pEvent->header.mpfid = MPF_Event;//このブロックの属すメモリプールID
	}else{
		CMTRACE("event: pget_mpf ercd=%d\n", ercd);
		if(ercd == E_CTX) DisplayContext();
		FATAL_ERROR("イベントインスタンスが作成できません。");
//		DebugPrintf("event: get_mpf ercd=%d\r", ercd);
//		CMTRACE("event: get_mpf ercd=%d\n", ercd);
	}
	return pEvent;
}

EVENT* kpCreateEventTimeout(UINT event, TMO tmout)
{
	VP p_blk;
	EVENT* pEvent = NULL;
	ER ercd = tget_mpf(MPF_Event, &p_blk, tmout);
	if(ercd == E_OK){
		pEvent			= (EVENT*)p_blk;
		pEvent->evMbx	= 0;			//送信先は未設定
		pEvent->event	= event;		//イベントID
		pEvent->header.mpfid = MPF_Event;//このブロックの属すメモリプールID
	}else if(ercd != E_TMOUT){
		CMTRACE("event: tget_mpf ercd=%d\n", ercd);
		if(ercd == E_CTX) DisplayContext();
		FATAL_ERROR("イベントインスタンスが作成できません。");
//		DebugPrintf("event: get_mpf ercd=%d\r", ercd);
//		CMTRACE("event: get_mpf ercd=%d\n", ercd);
	}
	return pEvent;
}

ER kpDeleteEvent(EVENT* pEvent)
{
	ER ercd;
	if(pEvent==NULL) return E_OK;
	ercd = rel_mpf(MPF_Event, (VP)pEvent);
	if(ercd != E_OK){
		CMTRACE("event: rel_mpf ercd=%d\n", ercd);
	}
	return ercd;
}

