/**
 * GeneratorGatedBurst.cpp - for LibTiePie 0.5+
 *
 * This example generates a 10 kHz square waveform, 10 Vpp when the external trigger input is active.
 *
 * Find more information on http://www.tiepie.com/LibTiePie .
 */
#include <iostream>
#include <stdexcept>
#include "libtiepie++.h"
#include "PrintInfo.h"
#if defined(__linux) || defined(__unix)
  #include <cstdlib>
#endif
using namespace std;
using namespace LibTiePie;
int main()
{
  int status = EXIT_SUCCESS;
  // Initialize library:
  Library::init();
  // Print library information:
  printLibraryInfo();
  // Update device list:
  DeviceList::update();
  // Try to open a generator with gated burst support:
  Generator* gen = 0;
  for(uint32_t index = 0; index < DeviceList::count(); index++)
  {
    DeviceListItem* item = DeviceList::getItemByIndex(index);
    if(item->canOpen(DEVICETYPE_GENERATOR) && (gen = item->openGenerator()))
    {
      // Check for gated burst support:
      if(!((gen->modes() & GM_GATED_PERIODS) && (gen->triggerInputs.count() > 0)))
      {
        delete gen;
        gen = 0;
      }
    }
    delete item;
    if(gen)
    {
      break;
    }
  }
  if(gen)
  {
    try
    {
      // Set signal type:
      gen->setSignalType(ST_SQUARE);
      // Set frequency:
      gen->setFrequency(10e3); // 10 kHz
      // Set amplitude:
      gen->setAmplitude(5); // 5 V
      // Set offset:
      gen->setOffset(0); // 0 V
      // Set mode:
      gen->setMode(GM_GATED_PERIODS);
      // Locate trigger input:
      TriggerInput* triggerInput = gen->triggerInputs.getById(TIID_EXT1); // EXT 1
      if(!triggerInput)
      {
        throw std::runtime_error("Unknown trigger input!");
      }
      // Enable trigger input:
      triggerInput->setEnabled(true);
      // Enable output:
      gen->setOutputOn(true);
      // Print generator info:
      printDeviceInfo(gen);
      // Start signal generation:
      gen->start();
      // Wait for keystroke:
      cout << "Press Enter to stop signal generation..." << endl;
      while(cin.get() != '\n');
      // Stop generator:
      gen->stop();
      // Disable output:
      gen->setOutputOn(false);
    }
    catch(const exception& e)
    {
      cerr << "Exception: " << e.what() << endl;
      status = EXIT_FAILURE;
    }
    // Close generator:
    delete gen;
  }
  else
  {
    cerr << "No generator available with gated burst support!" << endl;
    status = EXIT_FAILURE;
  }
  // Exit library:
  Library::exit();
  return status;
}
