/*******************************************************************
   swatchdog.c
   Z-Word Inc 2003

	This sample program is for any RabbitNet board.

	Description
	===========
	This program demonstrates setting and hitting the software
   watchdog on a RabbitNet device using costatements.

   This program will first look for a device matching the search
   criteria.  The software watchdog will be set for 2.5 seconds.
   The watchdog will be hit at every increasing time out until
   the time out is past 2.5 seconds.  A software reset will occur
   and the software watchdog will be disabled.

	Connections
	===========
   Connect RabbitNet and power supply cables to the controller
   and RN boards as described in the RabbitNet Manual.

	Instructions
	============
	1. Compile and run this program.

*******************************************************************/
#class auto

#define SWTIMEOUT 2.5	//software watchdog timeout

#define MATCHFLAG  RN_MATCH_PORT|RN_MATCH_PRDID
#define MATCHPORT 0           //port 0 or port 1 on the controller
#define MATCHPID RN1100			//RN1100 DI/0 board; RN1200 for AD board

// screen foreground colors
#define	BLACK		"\x1b[30m"
#define	RED		"\x1b[31m"


main()
{
	auto int device0, tdelay, count;
	auto char statusbyte, timeleft;
	auto char recbyte;
	auto rn_search newdev;

	brdInit();                 //initialize controller
   rn_init(RN_PORTS, 1);      //initialize controller RN ports

   //search for device match
	newdev.flags = MATCHFLAG;
	newdev.ports = MATCHPORT;
	newdev.productid = MATCHPID;
   if ((device0 = rn_find(&newdev)) == -1)
   {
   	printf("\n no device found\n");
      exit(0);
   }

   count = 0;
	tdelay = 1000;

   // first set SW watchdog for timeout
	statusbyte = rn_sw_wdt(device0, SWTIMEOUT);

   // then enable SW watchdog
	statusbyte = rn_enable_wdt(device0, 2);

 	for (;;)
	{
   	costate
      {  //hit software watchdog and increase timeout
			statusbyte = rn_hitwd(device0, &timeleft);
			printf("%s\x1B=%c%cWatchdog timeout count %d  ", BLACK, 0x25, 0x22, timeleft);
      	tdelay+=100;
         printf("%s\x1B=%c%cIncrease delay to %d ms  ", BLACK, 0x25, 0x24, tdelay);
      	waitfor(DelayMs(tdelay));
      }

      costate
      {  // busy count
			printf("%s\x1B=%c%cBusy count %d    ", BLACK, 0x25, 0x26, count++);
      	waitfor(DelayMs(200));
      }

      costate
      {
         if (statusbyte&0x01)		//check WDT bit set
         {
	      	waitfor(DelayMs(1000));
				statusbyte = rn_rst_status(device0, &recbyte);
            if (recbyte&0x40)    //check SW RST bit set
            {
					printf("%s\x1B=%c%cSW reset occured 0x%02x", RED, 0x25, 0x29, recbyte);
            }
         }
      }

	}
}

