/*
 * task6 - task for os
 *
 * $Id: cli.c,v 1.8 2002/08/03 17:52:57 tomdean Exp $
 */

#include <sys/ports_def.h>
#include <os.h>
#include <lcd.h>
#include <libeeprom.h>

unsigned char cli_stack[STACK_SIZE];

void cli() {
  register unsigned short loop_count = 0;
  register unsigned char task;
  register msg_t *msg, *ptr;
  register unsigned short idx;
  register unsigned char *c;
  
  while (1) {
	hex_to_ascii_4(++loop_count, TASK6_COUNT);
	SYS_RECV_WAIT(msg);
	/*
	 * do we have a message?
	 *
	 * XXX fix me - cannot get here is msg is null
	 */
	if (msg != NULL) {
	  switch(msg->buf[0]) {
	  case '4':
		/* 4800 baud */
		_io_ports[M6811_BAUD] = M6811_SCP1 | M6811_SCP0 | M6811_SCR0;
		msg->empty = 1;
		break;
	  case '9':
		/* 9600 baud */
		_io_ports[M6811_BAUD] = M6811_SCP1 | M6811_SCP0;
		msg->empty = 1;
		break;
	  case 'b':
		/* show sci_buf  in error 3 */
		error3_in_use = 1;
		idx = msg->buf[1] - '0';
		ptr = &sci_buf[idx];
		for (idx=0; idx<40; idx++) error3[idx] = ' ';
		error3[0] = ptr->task + '0';
		error3[2] = ptr->empty + '0';
		hex_to_ascii_4((unsigned short)ptr->next, error3+4);
		c = ptr->buf;
		for (idx=9; idx<40; idx++) error3[idx] = *c++;
		error3[40] = 0;  /* null termination */
		lcd_write_row_3(error3);
		msg->empty = 1;
		break;		
	  case 'c':
		/* release error3 */
		error3_in_use = 0;
		for (idx=0; idx<40; idx++) error3[idx] = ' ';
		msg->empty = 1;
		break;
	  case 'e':
		/* empty sci_buf */
		idx = msg->buf[1] - '0';
		sci_buf[idx].empty = 1;
		msg->empty = 1;
		break;
	  case 'm':
		/* mesage to task n */
		task = msg->buf[1] - '0';
#if 0
		hex_to_ascii_2(cur_task, error1+11);
		hex_to_ascii_4((unsigned short)msg, error1+14);
#endif
		/* XXX fix me - what to do if cli sends a message to itself? */
		/* note: the macros generate several statements, so need braces */
		if (task != CLI_TASK) { SYS_SEND(task, msg); }
		else msg->empty = 1;
		break;
	  case 'q':
		/* write a task's message queue to error3 */
		task = msg->buf[1] - '0';
		ptr = msg_queue[task];
		error3_in_use = 1;
		for (idx=0; idx<40; idx++) error3[idx] = ' ';
		idx=0; /* error1 buffer position */
		if (ptr == NULL) hex_to_ascii_4(0, error3+idx);
		else while ((ptr != NULL) && (idx<37)) {
		  hex_to_ascii_4((unsigned short)ptr, error3+idx);
		  ptr = ptr->next;
		  idx+=5;
		}
		error3[40] = 0;  /* null termination */
		lcd_write_row_3(error3);
		msg->empty = 1;
		break;
	  case 'r':
		/* restart task n */
		task = msg->buf[1] - '0';
		SYS_START(task);
		msg->empty = 1;
		break;
	  case 's':
		/* stop task n */
		task = msg->buf[1] - '0';
		SYS_STOP(task);
		msg->empty = 1;
		break;
	  default:
		/*
		 * XXX fix me - Do something other than drop the buffer
		 * when it is not recognized
		 */
		msg->empty = 1;
	  }
	}
  }
}

