OscilloscopeConnectionTest.cpp

/**
 * OscilloscopeConnectionTest.cpp
 *
 * This example performs a connection test.
 *
 * Find more information on http://www.tiepie.com/LibTiePie .
 */

#include "PrintInfo.hpp"
#include <iostream>
#include <thread>

#if defined(__linux) || defined(__unix)
#  include <cstdlib>
#  include <unistd.h>
#endif

int main()
{
  int status = EXIT_SUCCESS;

  // Initialize library:
  TiePie::Hardware::Library::init();

  // Print library information:
  printLibraryInfo();

  // Enable network search:
  TiePie::Hardware::Network::setAutoDetectEnabled(true);

  // Update device list:
  TiePie::Hardware::DeviceList::update();

  // Try to open an oscilloscope with connection test support:
  std::unique_ptr<TiePie::Hardware::Oscilloscope> scp;

  for(uint32_t i = 0; !scp && i < TiePie::Hardware::DeviceList::count(); i++)
  {
    const auto item = TiePie::Hardware::DeviceList::getItemByIndex(i);

    if(item->canOpen(TIEPIE_HW_DEVICETYPE_OSCILLOSCOPE) && (scp = item->openOscilloscope()))
    {
      // Check for connection test support:
      if(!scp->hasSureconnect())
        scp = nullptr;
    }
  }

  if(scp)
  {
    try
    {
      // Get the number of channels:
      const uint16_t channelCount = scp->channels.count();

      // Enable all channels that support connection testing:
      for(const auto& channel : scp->channels)
        channel->setEnabled(channel->hasSureconnect());

      // Start connection test on current active channels:
      scp->startSureconnect();

      // Wait for connection test to complete:
      while(!(scp->isSureconnectCompleted()))
      {
        // 10 ms delay, to save CPU time:
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(10ms);
      }

      // Create data buffer:
      std::vector<tiepie_hw_tristate> data(channelCount);

      // Get data:
      scp->sureconnectData(data.data(), channelCount);

      // Print results:
      std::cout << "\nConnection test result: \n";
      for(uint16_t ch = 0; ch < channelCount; ch++)
      {
        std::cout << "Ch" << static_cast<unsigned int>(ch + 1) << " = ";

        switch(data[ch])
        {
          case TIEPIE_HW_TRISTATE_UNDEFINED:
            std::cout << "undefined\n";
            break;

          case TIEPIE_HW_TRISTATE_FALSE:
            std::cout << "false\n";
            break;

          case TIEPIE_HW_TRISTATE_TRUE:
            std::cout << "true\n";
            break;

          default:
            std::cout << "unknown state\n";
        }
      }
    }
    catch(const std::exception& e)
    {
      std::cerr << "Exception: " << e.what() << '\n';
      status = EXIT_FAILURE;
    }

    // Close oscilloscope:
    scp = nullptr;
  }
  else
  {
    std::cerr << "No oscilloscope available with connection test support!\n";
    status = EXIT_FAILURE;
  }

  // Finalize library:
  TiePie::Hardware::Library::fini();

  return status;
}