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

  \author Satofumi KAMIMURA

  $Id: reconnectSample.cpp 1053 2009-06-20 22:52:51Z satofumi $

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

#include "mUrgCtrl.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[])
{
  mUrgCtrl urg(argc, argv);
  if (! urg.connect(device_)) {
    cout << "UrgCtrl::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;
}
