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

	wd.c
	Z-World, 2001
 
	This program is intended to be run on a target processor.  It sets
	up a number of watchdogs on the DeviceMate and keeps hitting them.
 
	See \samples\dmunit\wd.c for the DeviceMate program intended to be run
	with this program.
  
*****************************************************************************/

/* Request use of watchdog services */
#define USE_TC_WD

/*
 * Uncomment this line if this program will be loaded over ethernet. This will
 * force the DevMate communication to use serial port A, re-using the programming
 * link that was used to download the program.
 */
//#define USE_TC_LOADER

#ifdef CC_VER
	/* Dynamic C */
	#memmap xmem
	#use "tc_conf.lib"
#else
	/* Non-Rabbit */
	#include "tc_conf.h"
	#include <stdio.h>	
#endif

/* Change these items if desired... */
#define RESPONSE_TIMEOUT	3000	/* Expect responses within this many ms */
#define WD_TIMEOUT			4000	/* Minimum watchdog timeout in ms */
#define NUM_WD					10		/* Number of watchdogs to set */
#define NUM_HITS				40		/* Max hits of the 1st (fastest) watchdog */



uint16 wdto[NUM_WD];		/* watchdog timeout, ms */
uint16 hitrate[NUM_WD];	/* ms between hits, per wd */
uint16 nexthit[NUM_WD];	/* next hit timestamp */

int main(void)
{
	auto int i, rc, hitcount;
	auto char wdname[20];
	
	/* initialize hit rates etc. */
	for (i = 0; i < NUM_WD; i++) {
		wdto[i] = WD_TIMEOUT + i * 300;
		hitrate[i] = wdto[i] / 3;
	}
		
	devmate_init();
	
	if ((rc = devmate_wd_init(RESPONSE_TIMEOUT)) != DEVMATE_WD_ACKED) {
		printf("devmate_wd_init: failed %d\n", rc);
		exit(19);
	}
	
	for (i = 0; i < NUM_WD; i++) {
		sprintf(wdname, "test%d", i+1);
		rc = devmate_wd_add(wdname, wdto[i], RESPONSE_TIMEOUT);
		switch (rc) {
			case DEVMATE_WD_TIMEOUT:
				printf("devmate_wd_add: %s timed out\n", wdname);
				exit(21);
			case DEVMATE_WD_NAKED:
				printf("devmate_wd_add: %s NAK\n", wdname);
				exit(22);
			case DEVMATE_WD_ACKED:
				break;
			default:
				printf("devmate_wd_add: %s unexpected response %d\n", wdname, rc);
				exit(20);
		}
	}

	for (i = 0; i < NUM_WD; i++)
		nexthit[i] = (uint16)MS_TIMER + hitrate[i];
	hitcount = 0;

	for(;;) {
		devmate_tick();
		
		if (hitcount >= NUM_HITS) {
			if (hitcount == NUM_HITS) {
				hitcount++;
				printf("Done.  Waiting for reset...\n");
			}
			// Stop hitting when 1st watchdog reaches limit count.
			continue;
		}
			
		for (i = 0; i < NUM_WD; i++) {
			if ((int16)((uint16)MS_TIMER - nexthit[i]) > 0) {
				sprintf(wdname, "test%d", i+1);
				printf("hitting %s\n", wdname);
				devmate_wd_hit(wdname);
				nexthit[i] = (uint16)MS_TIMER + hitrate[i];
				if (!i)
					hitcount++;
			}
		}
	}
}
