/*------------------------------------------------------- 
 * コンソール
 *   com インターフェースと通信
 *-------------------------------------------------------*/
#include <xc.h>
#include <stdint.h>
#include "cons.h"
#include "com.h"

/* 前回に受信しした文字 (CRLF -> CR 変換用) */
static char cons_ch_prev = 0;

/* 1文字受信 (受信文字がなければ-1) : CRLF -> CR 変換*/
/*   注意: ノンブロッキング動作 */
int16_t cons_getc(void)
{
  int16_t ch = com_rx_get();
  if (ch >= 0) {
    /* 受信文字あり */
    if ((cons_ch_prev == CHAR_CR) &&
        (ch == CHAR_LF)) { /* CRLFのLFは捨てる */
      ch = com_rx_get(); 
    }
    if (ch >= 0) {
      cons_ch_prev = (char)ch;
    }
  } else {
    /* 受信文字なし */
    ch = -1;
  }
  return ch;
}

/* 受信バッファに文字があるか否かを検査 */
int8_t cons_get_ready(void)
{
  int16_t n = com_rx_nchars();
  if ((cons_ch_prev == CHAR_CR) &&
      (n > 0) && (com_rx_peek() == CHAR_LF)) {
    /* CRLFのLFは捨てるので勘定外 */
    return (n > 1);
  }
  return (n > 0);
}

/* 1文字送信 */
void cons_putc(char ch)
{
  while (com_tx_busy()) {
    CLRWDT();
  }
  com_tx_put(ch);
}

/* 送信中を検査 */
int8_t cons_put_busy(void)
{
  return com_tx_busy();
}

/* 改行(CR+LF) */
void cons_print_newline(void)
{
  cons_putc(CHAR_CR);
  cons_putc(CHAR_LF);
}

/* 8ビットを16進数２ケタで表示 */
void cons_print_hex(uint8_t d)
{
  const char hexchars[] = "0123456789ABCDEF";
  cons_putc(hexchars[(unsigned)(d >> 4) & 0x0F]);
  cons_putc(hexchars[(unsigned) d       & 0x0F]);
}

/* 文字列表示（文字列はデータ領域） */
void cons_print(char *s)
{
  for (; *s != '\0'; s++) {
    cons_putc(*s);
  }
}

/* 文字列表示（文字列はプログラムコード領域） */
void cons_print_pgm(const char *s)
{
  for (; *s != '\0'; s++) {
    cons_putc(*s);
  }
}
