/*!
  \example multiMdScanSample.cpp

  \brief 複数 URG を用いてデータ取得を行うサンプル

  ２台の URG を用いて、それぞれの前方データを表示する

  \author Satofumi KAMIMURA

  $Id: multiMdScanSample.cpp 1052 2009-06-20 17:40:45Z satofumi $
*/

#include "mUrgCtrl.h"
#include "delay.h"
#include <SDL.h>

using namespace qrk;
using namespace std;


namespace
{
  void urg_exit(int i, mUrgCtrl* urg, const char *message)
  {
    printf("%d: %s: %s\n", i, message, urg->what());
    urg->disconnect();

    exit(1);
  }
}


//! main
int main(int argc, char *argv[]) {

  enum {
    Times = 10,
    Devices = 2,
  };

  //const char *connect_devices[] = { "COM36", "COM34" };
  const char *connect_devices[] = { "/dev/ttyACM0", "/dev/ttyACM1" };

  // 接続
  mUrgCtrl urg_0(argc, argv);
  mUrgCtrl urg_1(argc, argv);
  mUrgCtrl* urg[Devices];
  urg[0] = &urg_0;
  urg[1] = &urg_1;

  for (int i = 0; i < Devices; ++i) {
    if (! urg[i]->connect(connect_devices[i])) {
      urg_exit(i, urg[i], "UrgCtrl::connect()");
    }

    // データを間引くと、連続転送が容易になる
    // 間引き指定が 2 だと、データ転送量は半分になる
    //urg[i]->setCaptureSkipLines(2);
    urg[i]->setCaptureTimes(Times);
    urg[i]->setCaptureMode(AutoCapture);
  }

  long pre_timestamp[Devices] = { 0, 0 };
  string error_messages[Devices];
  int remain_times[Devices] = { Times, Times };
  for (int i = 0; i < 2; ++i) {
    pre_timestamp[i] = 0;
    remain_times[i] = Times;
  }
  while ((remain_times[0] > 0) || (remain_times[1] > 0)) {

    delay(1);

    for (int i = 0; i < Devices; ++i) {
      if (remain_times[i] <= 0) {
        continue;
      }

      /* データ取得 */
      vector<long> data;
      long timestamp = 0;
      int n = urg[i]->capture(data, &timestamp);
      if (n < 0) {
        // 次回に受信できるかもしれないので、処理を続ける
        string error = urg[i]->what();
        if (error_messages[i].compare(error)) {
          // 前回と違うメッセージのときのみ、表示する
          printf("    %d: %s: %s\n", i, "capture()", error.c_str());
          error_messages[i] = error;
        }
        continue;

      } else if (n == 0) {
        continue;
      }
      --remain_times[i];

      printf("    %d: ", i);
      /* データ取得が完了していたら、終了 */
      remain_times[i] = min(static_cast<int>(urg[i]->remainCaptureTimes()),
                            remain_times[i]);
      printf("(%03d/%03d): ", remain_times[i], Times);

      /* 表示 */
      printf("timestamp: %ld (%ld)", timestamp, (timestamp - pre_timestamp[i]));
      printf("\n");
      pre_timestamp[i] = timestamp;

#if 0
      for (j = 0; j < n; ++j) {
        printf("%d:%ld, ", j, data[i][j]);
      }
      printf("\n\n");
#endif
    }
  }

  return 0;
}
