/*!
  \example reconnectSample.cpp
  \brief 切断の検出と再接続のサンプル

  \author Satofumi KAMIMURA

  $Id: reconnectSample.cpp 1739 2010-03-06 07:43:32Z satofumi $

  \todo 複数台の再接続が出来るように調整する
*/

#include "mUrgDevice.h"
#include "ticks.h"
#include "delay.h"
#include <SDL.h>
#include <iostream>

using namespace qrk;
using namespace std;


namespace
{
  const char device_[] = "/dev/ttyACM0";
  const long baudrate_ = 115200;


  bool reconnect(RangeSensor& urg)
  {
    cout << "disconnected." << endl;

    enum { ReconnectTimes = 5 };
    for (int i = 0; i < ReconnectTimes; ++i) {
      if (urg.connect(device_, baudrate_)) {
        return true;
      }
      delay(1000);
    }
    return false;
  }
}


int main(int argc, char *argv[])
{
  mUrgDevice urg(argc, argv);
  if (! urg.connect(device_)) {
    cout << "UrgDevice::connect: " << urg.what() << endl;
    exit(1);
  }
  long scan_msec = urg.scanMsec();

  enum { DetectMsec = 10 * 1000 }; // [msec]
  long first_ticks = ticks();

  vector<long> data;
  while ((ticks() - first_ticks) < DetectMsec) {
    int n = urg.capture(data);
    if (n < 0) {
      if (! reconnect(urg)) {
        cout << "disconnected!" << endl;
        break;
      }
    }

    cout << "n = " << n << endl;
    delay(scan_msec);
  }

  return 0;
}
