/*!
  \file
  \brief SerialDevice のテスト

  \author Satofumi KAMIMURA

  $Id: TestSerialDevice.cpp 1349 2009-09-30 07:00:56Z satofumi $
*/

#include "TestSerialDevice.h"
#include "SerialDevice.h"
#include "ticks.h"
#include "DetectOS.h"
#include <cstring>

#if defined(WINDOWS_OS)
const char device[] = "COM3";
#else
const char device[] = "/dev/usb/ttyUSB0";
#endif


using namespace qrk;
using namespace std;


CPPUNIT_TEST_SUITE_REGISTRATION(TestSerialDevice);
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(TestSerialDevice, "TestSerialDevice");


void TestSerialDevice::connectTest(void)
{
  SerialDevice con;
  bool ret = con.connect(device, 115200);
  CPPUNIT_ASSERT_EQUAL_MESSAGE(device, true, ret);
}


void TestSerialDevice::timeoutTest(void)
{
  enum { Timeout = 100 };
  SerialDevice con;
  bool ret = con.connect(device, 115200);
  CPPUNIT_ASSERT_EQUAL(true, ret);

  char buffer[1024];

  // 1 文字のときのタイムアウト時間の評価
  int first_ticks = ticks();
  char recv_ch;
  int n = con.receive(&recv_ch, 1, Timeout);
  int timeout = ticks() - first_ticks;
  CPPUNIT_ASSERT_EQUAL(0, n);
  snprintf(buffer, 1024, "timeout: %d [msec]", timeout);
  CPPUNIT_ASSERT_MESSAGE(buffer, timeout >= Timeout);
  CPPUNIT_ASSERT_MESSAGE(buffer, timeout < Timeout + 100);

  // n 文字のときのタイムアウト時間の評価
  first_ticks = ticks();
  enum { ReceiveByte = 20 };
  char recv_buffer[ReceiveByte];
  n = con.receive(recv_buffer, ReceiveByte, Timeout);
  timeout = ticks() - first_ticks;
  CPPUNIT_ASSERT_EQUAL(0, n);
  snprintf(buffer, 1024, "timeout: %d [msec]", timeout);
  CPPUNIT_ASSERT_MESSAGE(buffer, timeout >= Timeout);
  CPPUNIT_ASSERT_MESSAGE(buffer, timeout < Timeout + 100);

  // タイムアウト時間がゼロのときの評価
  first_ticks = ticks();
  n = con.receive(recv_buffer, 1, 0);
  timeout = ticks() - first_ticks;
  CPPUNIT_ASSERT_EQUAL(0, n);
  snprintf(buffer, 1024, "timeout: %d [msec]", timeout);
  CPPUNIT_ASSERT_MESSAGE(buffer, timeout < 10);
}
