/*!
  \file
  \brief シリアル通信

  \author Satofumi KAMIMURA

  $Id: serial_connection.cpp 1687 2010-02-11 05:26:50Z satofumi $

  \todo 複数の走行コントローラが動作できるようにする
*/

#include "serial_connection.h"
#include "TcpipAccepter.h"
#include "TcpipSocket.h"

//#include <cstdio>
//#include <cctype>

using namespace qrk;


namespace
{
  TcpipSocket* connection_ = NULL;
  TcpipAccepter* tcpip_accepter_ = NULL;
}


bool serial_setPort(long port)
{
  static TcpipAccepter tcpip_accepter;
  tcpip_accepter_ = &tcpip_accepter;
  return tcpip_accepter_->activate(port);
}


void serial_send(const char *data, int count)
{
  if ((! connection_) || (! connection_->isConnected())) {
    return;
  }
#if 0
  if (count > 0) {
    fprintf(stderr, "send: n = %d: ", count);
    for (int i = 0; i < count; ++i) {
      char ch = data[i];
      if (isprint(ch)) {
        fprintf(stderr, "%c", ch);
      } else {
        fprintf(stderr, "[%02x]", (unsigned char)ch);
      }
    }
    fprintf(stderr, "\n");
  }
#endif
  connection_->send(data, count);
}


int serial_receive(char *data, int max_count)
{
  if (! connection_) {
    // 接続待ち
    connection_ = tcpip_accepter_->accept(1);
    if (! connection_) {
      return 0;
    }

  } else if (! connection_->isConnected()) {
    // 切断の検出
    delete connection_;
    connection_ = NULL;
    return -1;
  }

  return connection_->receive(data, max_count, 0);
#if 0
  int n = connection_->receive(data, max_count, 0);
  if (n > 0) {
    fprintf(stderr, "receive: n = %d: ", n);
    for (int i = 0; i < n; ++i) {
      char ch = data[i];
      if (isprint(ch)) {
        fprintf(stderr, "%c", ch);
      } else {
        fprintf(stderr, "[%02x]", (unsigned char)ch);
      }
    }
    fprintf(stderr, "\n");
  }
  return n;
#endif
}
