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

	log100.c
	Copyright (C) Z-World, 2001

 	Demonstrate use of DeviceMate to perform logging.
	The \samples\dmunit\logxtc.c program must be running on the
	DeviceMate processor.

	This sends 100 "random" log messages to alternating destinations.
	Assuming that you are running devmate=logxtc.c without any
	reconfiguration, then messages will alternate between being
	saved in the filesystem, and being printed to the stdio window.
	
******************************************************/


/* Request use of log services */
#define USE_TC_LOG

/*
 * 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

int main()
{
	int rc;
	uint16 timer;
	int i;
	char buf[116];
#define NUM_TEST_MESSAGES 3
	static const char * test_messages[NUM_TEST_MESSAGES] =
	{
		"Z-World",
		"Rabbit Semiconductor",
		"Talk Async Serial!"
	};
#define NUM_TEST_INTERVALS 5
	static const uint16 test_intervals[NUM_TEST_INTERVALS] =
	{
		// interval between messages, in milliseconds
		400, 100, 100, 300, 200
	};

	printf("Initializing target communications...\n");
	devmate_init();

reopen_log:
	printf("Waiting for log services...\n");
	devmate_log_init();
	while (!devmate_log_status()) devmate_tick();
	if (devmate_log_status() < 0) {
		printf("Log services not available.\n");
		exit(21);
	}
	printf("OK!  Sending test messages...\n");

	for (i = 0; i < 100; i++) {
		sprintf(buf, "Log message %d.  %s", i, test_messages[i%NUM_TEST_MESSAGES]);
		printf("Sending '%s'...\n", buf);
		// alternate between facility 0 and 1
		rc = devmate_log_put((i&1)<<3, buf, strlen(buf));
		printf("...rc = %d\n", rc);
		switch (rc) {
			case 0:		// normal
				break;
			case 1:
				printf("  Not buffered, trying again in 400ms\n");
				timer = (uint16)MS_TIMER + 400;
				while ((int16)((uint16)MS_TIMER - timer) < 0)
					devmate_tick();
				i--;
				continue;
			case -2:
				printf("  Message too long!\n");
				break;
			default:
				printf("  Logging unavailable - re-establishing...\n");
				goto reopen_log;
		}
		timer = (uint16)MS_TIMER + test_intervals[i%NUM_TEST_INTERVALS];
		while ((int16)((uint16)MS_TIMER - timer) < 0)
			devmate_tick();
	}
	

	printf("All done.\n");

	while (1)
		devmate_tick();

	return 0;
}