/*
 * ul_ptx.h
 *
 *  Created on: Sep 30, 2011
 *      Author: qwer1
 *  @brief  Protothreads extensions
 */

#ifndef UL_PTX_H_
#define UL_PTX_H_

#include "ul_other.h"
#include "pt.h"

/** Execute statement cmd and wait until condition becames true */
#define PTX_EXEC_WAIT_UNTIL(cmd, cond) { cmd; }; PT_WAIT_UNTIL(pt, cond)

/** delay, ms using millisecond timer */
#define PTX_DELAY(tmr, time) PTX_EXEC_WAIT_UNTIL((tmr) += (time), (tmr) == 0);

/** delay using thread millisecond timer */
#define PTX_DELAY_MS(time) PTX_DELAY(ptx->tmr, time)

/** decrement timer if flag is set */
#define PTX_TIMER_DEC(flag, tmr) if ((flag) && (tmr)) (tmr)--

/** decrement millisecond timer */
#define PTX_TIMER_MS_DEC(tmr) PTX_TIMER_DEC(t_1ms, tmr)

/** thread structure */
struct ptx {
	struct pt pt; /**< thread context */
	char (*pf)(struct pt *pt, struct ptx *ptx); /**< thread function pointer */
	U16  tmr;     /**< thread timer */
	U8   flags;   /**< thread flags */
	void *data;   /**< pointer to thread data */
};

#define PTX_FLAG_RUN        1
#define PTX_FLAG_SYNC_1MS   2
#define PTX_FLAG_SYNC_10MS  4
#define PTX_FLAG_SYNC_100MS 8
#define PTX_FLAG_SYNC_1S    16
#define PTX_FLAG_SYNC (PTX_FLAG_SYNC_1MS | PTX_FLAG_SYNC_10MS | PTX_FLAG_SYNC_100MS | PTX_FLAG_SYNC_1S)

/** threads queue */
extern struct ptx ptx_queue[PTX_MAX];

/** add new thread to queue */
struct ptx *ptx_add(char (*pf)(struct pt *pt, struct ptx *ptx), void *data, U8 flags);

/** run started threads */
void ptx_dispatch( void );

/** stop thread */
void ptx_stop(struct ptx *ptx);

/** start/resume thread */
void ptx_start(struct ptx *ptx);

#endif /* UL_PTX_H_ */
