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

	This sample program is for any RabbitNet board.

	Description
	===========
	This program demonstrates setting the hardware watchdog on a
   RabbitNet device.

   This program will first look for a device matching the search
   criteria.  The hardware watchdog will be set and a hardware
   reset should occur in approximately 1.5 seconds.  The hardware
   watchdog will be disabled after reset.

	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"


//////
// This function for this demonstration only by leaving device
// select asserted to force a hardware watchdog timeout
//////
int demo_read(int handle, int regno, char *recdata, int datalen)
{
	auto rn_devstruct *devaddr;
   auto rnDataSend ds;
   auto rnDataRec dr;

	devaddr = (rn_devstruct *)handle;

	//assemble data
   ds.cmd = RCMD|regno;
   memset(ds.mosi, ds.cmd, datalen);
   datalen++;

	rn_sp_enable(devaddr->portnum);
 	_mosi_driver(datalen, &ds, &dr, &devaddr->cmdtiming, &rn_spi[devaddr->portnum]);

   return (dr.statusbyte);
}


main()
{
	auto int device0, count;
	auto char statusbyte;
	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;

   // then enable HW watchdog
	statusbyte = rn_enable_wdt(device0, 1);

   // force watchdog timeout
 	statusbyte = demo_read(device0, 0000, &recbyte, 1);

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

      costate
      {
      	waitfor(DelayMs(5000));			//wait for hard reset to finish
			rn_sp_disable(MATCHPORT);     //make sure device select is deasserted
			statusbyte = rn_rst_status(device0, &recbyte);
//			printf("%s\x1B=%c%cStatus 0x%02x    ", BLACK, 0x25, 0x24, statusbyte);
         if (recbyte&0x80)    //check HW RST bit set
         {
				printf("%s\x1B=%c%cHW reset occured 0x%02x", RED, 0x25, 0x27, recbyte);
         }
      }

	}
}

