/*
 * ul_ptx.c
 *
 *  Created on: Oct 25, 2011
 *      Author: qwer1
 */

#include <stddef.h>
#include "ul_ptx.h"
#include "ul_timing.h"

struct ptx ptx_queue[PTX_MAX];
U8 ptx_cnt;

struct ptx *ptx_add( char (*pf)(struct pt *pt, struct ptx *ptx), void *data, U8 flags ) {
	if (ptx_cnt < (PTX_MAX)) {
		struct ptx *ptx = &ptx_queue[ptx_cnt];
		ptx->pf = pf;
		ptx->data = data;
		PT_INIT( &ptx->pt );
		ptx->tmr = 0;
		ptx->flags = flags;
		ptx_cnt++;
		return ptx;
	}
	return NULL;
}

void ptx_dispatch( void ) {
	if (ptx_cnt > 0) {
		struct ptx *ptx = &ptx_queue[0];
		for (U8 cnt=0; cnt<ptx_cnt; cnt++, ptx++) {
			U8 flags = ptx->flags;
			U8 run = 0;
			if (flags & PTX_FLAG_RUN) {
				//decrement millisecond timer
				PTX_TIMER_MS_DEC(ptx->tmr);

				if (flags & PTX_FLAG_SYNC) {
					if (((flags & PTX_FLAG_SYNC_1MS) && (t_1ms)) ||
						((flags & PTX_FLAG_SYNC_10MS) && (t_10ms)) ||
						((flags & PTX_FLAG_SYNC_100MS) && (t_100ms)) ||
						((flags & PTX_FLAG_SYNC_1S) && (t_1s))
					) run = 1;
				} else run = 1;
			}
			//call thread function
			if (run)
				(ptx_queue[cnt].pf)(&ptx->pt, ptx);
		}
	}
}

void ptx_stop(struct ptx *ptx) {
	ptx->flags &= ~PTX_FLAG_RUN;
}

void ptx_start(struct ptx *ptx) {
	ptx->flags |= PTX_FLAG_RUN;
}
