/*!
  \file
  \brief USB-Ethernet 変換プログラムのサンプル

  USB の接続と Ethernet の接続を繋げる

  \author Satofumi KAMIMURA

  $Id: usb2etherSample.cpp 1474 2009-11-01 05:33:08Z satofumi $
*/

#include "SerialDevice.h"
#include "TcpipSocket.h"
#include "TcpipAccepter.h"
#include "delay.h"
#include <iostream>
#include <cstring>

using namespace qrk;
using namespace std;


int main(int argc, char *argv[])
{
  const char* device = "COM3";
  for (int i = 0; i < argc; ++i) {
    if (! strncmp("--port=", argv[i], 7)) {
      device = &argv[i][7];
    }
  }

  SerialDevice serial;
  if (! serial.connect(device, 115200)) {
    cout << "SerialDevice::connect: " << serial.what() << endl;
    return 1;
  }

  TcpipAccepter server;
  server.activate(10940);

  TcpipSocket* socket = server.accept(5000);
  if (! socket) {
    cout << "TcpipSocket::accept: " << server.what() << endl;
    return 1;
  }

  enum { BufferSize = 4096 };
  char buffer[BufferSize];

  while (1) {
    int n = socket->receive(buffer, BufferSize, 0);
    if (n < 0) {
      cout << "TcpipScoket::receive: " << socket->what() << endl;
      break;
    }
    serial.send(buffer, n);

    n = serial.receive(buffer, BufferSize, 0);
    if (n < 0) {
      cout << "TcpipScoket::receive: " << serial.what() << endl;
      break;
    }
    socket->send(buffer, n);
    delay(1);
  }

  return 1;
}
