/*!
  \file
  \brief tiny_sci のホスト実装

  \author Satofumi KAMIMURA

  $Id: sci_host.cpp 1111 2009-07-05 21:06:28Z satofumi $
*/

#include "tiny_sci.h"
#include "Connection.h"
#include <iostream>
#include <cstring>

using namespace qrk;
using namespace std;


namespace
{
  enum {
    NoTimeout = -1,
  };
  Connection* connection_ = NULL;
}


void sci_initialize(Connection* connection)
{
  connection_ = connection;
}


void sci_initialize(long baudrate)
{
  (void)baudrate;

  // 初期化は終了しているはずので、実装しなくてよい
}


int sci_setBaudrate(long baudrate)
{
  static_cast<void>(baudrate);

  cerr << "sci_setBaudrate: " << baudrate << endl;

  // 常に成功として扱う
  return 0;
}


char sci_getch(void)
{
  char recv_ch = '\0';
  int n = connection_->receive(&recv_ch, 1, NoTimeout);
  if (n != 1) {
    cerr << "sci_getch: " << connection_->what() << endl;
    exit(0);
  }

  return recv_ch;
}


void sci_gets(char *buffer, int len)
{
  int n = connection_->receive(buffer, len, NoTimeout);
  if (n != len) {
    cerr << "sci_getch: " << connection_->what() << endl;
    exit(1);
  }
}


void sci_flush(void)
{
  // 実装しない
}


void sci_putch(char ch)
{
  connection_->send(&ch, 1);
}


void sci_puts(const char* str)
{
  int n = strlen(str);
  connection_->send(str, n);
}
