/* -*- c++ -*- */
/*
 * Copyright 2013 Dimitri Stolnikov <horiz0n@gmx.net>
 *
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

/*
 * config.h is generated by configure.  It contains the results
 * of probing for feature_t, options etc.  It should be the first
 * file included in your .cc file.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifndef USE_ASIO
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif

#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <sys/stat.h>
#include <dirent.h>
#include <libgen.h> /* basename */

#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include <cerrno>

#include <boost/assign.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#ifdef USE_ASIO
#include <boost/asio/deadline_timer.hpp>
#endif

#include <gnuradio/io_signature.h>

#include "arg_helpers.h"
#include "rfspace_source_c.h"

using namespace boost::assign;
#ifdef USE_ASIO
using boost::asio::deadline_timer;
#endif

#define DEFAULT_HOST  "127.0.0.1" /* We assume a running "siqs" from CuteSDR project */
#define DEFAULT_PORT  50000

/*
 * Create a new instance of rfspace_source_c and return
 * a boost shared_ptr.  This is effectively the public constructor.
 */
rfspace_source_c_sptr make_rfspace_source_c (const std::string &args)
{
  return gnuradio::get_initial_sptr(new rfspace_source_c (args));
}

/*
 * Specify constraints on number of input and output streams.
 * This info is used to construct the input and output signatures
 * (2nd & 3rd args to gr_block's constructor).  The input and
 * output signatures are used by the runtime system to
 * check that a valid number and type of inputs and outputs
 * are connected to this block.  In this case, we accept
 * only 0 input and 1 output.
 */
static const int MIN_IN = 0;	// mininum number of input streams
static const int MAX_IN = 0;	// maximum number of input streams
static const int MIN_OUT = 1;	// minimum number of output streams
static const int MAX_OUT = 1;	// maximum number of output streams

/*
 * The private constructor
 */
rfspace_source_c::rfspace_source_c (const std::string &args)
  : gr::sync_block ("rfspace_source_c",
                    gr::io_signature::make (MIN_IN, MAX_IN, sizeof (gr_complex)),
                    gr::io_signature::make (MIN_OUT, MAX_OUT, sizeof (gr_complex))),
    _radio(RADIO_UNKNOWN),
#ifdef USE_ASIO
    _io_service(),
    _resolver(_io_service),
    _t(_io_service),
    _u(_io_service),
#else
    _tcp(-1),
    _udp(-1),
#endif
    _usb(-1),
    _running(false),
    _keep_running(false),
    _sequence(0),
    _nchan(1),
    _sample_rate(NAN),
    _bandwidth(0.0f),
    _fifo(NULL)
{
  std::string host = "";
  unsigned short port = 0;

  dict_t dict = params_to_dict(args);

  if ( dict.count("sdr-iq") )
    dict["rfspace"] = dict["sdr-iq"];

  if ( dict.count("sdr-ip") )
    dict["rfspace"] = dict["sdr-ip"];

  if ( dict.count("netsdr") )
    dict["rfspace"] = dict["netsdr"];

  if ( dict.count("cloudiq") )
    dict["rfspace"] = dict["cloudiq"];

  if ( dict.count("rfspace") )
  {
    std::string value = dict["rfspace"];

    if ( ! value.length() )
    {
      std::vector< std::string > devices = get_devices();

      if ( devices.size() )
      {
        dict_t first = params_to_dict( devices[0] );

        if ( first.count("sdr-iq") )
          value = first["sdr-iq"];

        if ( first.count("sdr-ip") )
          value = first["sdr-ip"];

        if ( first.count("netsdr") )
          value = first["netsdr"];

        if ( first.count("cloudiq") )
          value = first["cloudiq"];

        dict["rfspace"] = value;
        dict["label"] = first["label"];
      }
    }

    std::vector< std::string > tokens;
    boost::algorithm::split( tokens, value, boost::is_any_of(":") );

    if ( tokens[0].length() && (tokens.size() == 1 || tokens.size() == 2 ) )
      host = tokens[0];

    if ( tokens.size() == 2 ) /* port given */
      port = boost::lexical_cast< unsigned short >( tokens[1] );
  }

  if (dict.count("nchan"))
    _nchan = boost::lexical_cast< size_t >( dict["nchan"] );

  if ( _nchan < 1 || _nchan > 2 )
    throw std::runtime_error("Number of channels (nchan) must be 1 or 2");

  if ( ! host.length() )
    host = DEFAULT_HOST;

  if (0 == port)
    port = DEFAULT_PORT;

  std::string port_str = boost::lexical_cast< std::string >( port );

  std::string label = dict["label"];

  if ( label.length() )
    std::cerr << "Using " + label << " ";

  struct stat sb;
  bzero(&sb, sizeof(sb));

  if ( stat(host.c_str(), &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFCHR ) /* is character device */
  {
    _usb = open( host.c_str(), O_RDWR | O_NOCTTY );
    if ( _usb < 0 )
        throw std::runtime_error("Could not open " + host + ": " + std::string(strerror(errno)));

    struct termios tios;

    bzero(&tios, sizeof(tios));
    tios.c_cflag = CS8 | CLOCAL | CREAD;
    tios.c_iflag = IGNPAR;
    tios.c_oflag = 0;
    tios.c_lflag = 0;
    tios.c_cc[VTIME] = 2; /* in units of 0.1 seconds */
    tios.c_cc[VMIN]  = 0;

    cfsetispeed(&tios, B230400);
    cfsetospeed(&tios, B230400);

    tcflush(_usb, TCIFLUSH);
    tcsetattr(_usb, TCSANOW, &tios);

    unsigned char byte;
    while ( read(_usb, &byte, sizeof(byte)) > 0 ); /* flush serial */

    _radio = RFSPACE_SDR_IQ; /* legitimate assumption */

    _fifo = new boost::circular_buffer<gr_complex>( 200000 );
    if ( ! _fifo )
      throw std::runtime_error( "Failed to allocate sample FIFO" );

    _run_usb_read_task = true;

    _thread = gr::thread::thread( boost::bind(&rfspace_source_c::usb_read_task, this) );
  }
  else /* assuming host & port */
  {
    // TODO: make listener host & port dynamic: bind=[host][:port]
    /* SDR-IP 4.4.4 Data Output UDP IP and Port Address */
    /* NETSDR 4.4.3 Data Output UDP IP and Port Address */

#ifdef USE_ASIO

    tcp::resolver::query query(tcp::v4(), host.c_str(), port_str.c_str());
    tcp::resolver::iterator iterator = _resolver.resolve(query);

    boost::system::error_code ec;

    boost::asio::connect(_t, iterator, ec);
    if ( ec )
      throw std::runtime_error(ec.message() + " (" + host + ":" + port_str + ")");

    _u.open(udp::v4(), ec);
    if ( ec )
      throw std::runtime_error(ec.message());

    _u.bind(udp::endpoint(udp::v4(), DEFAULT_PORT), ec);
      if ( ec )
        throw std::runtime_error(ec.message());

    _u.set_option(udp::socket::reuse_address(true));
    _t.set_option(udp::socket::reuse_address(true));

#else

    if ( (_tcp = socket(AF_INET, SOCK_STREAM, 0) ) < 0)
    {
      throw std::runtime_error("Could not create TCP socket");
    }

    int sockoptval = 1;
    setsockopt(_tcp, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(int));
    sockoptval = 1;
    setsockopt(_tcp, IPPROTO_TCP, TCP_NODELAY, &sockoptval, sizeof(int));

    /* don't wait when shutting down */
    linger lngr;
    lngr.l_onoff  = 1;
    lngr.l_linger = 0;
    setsockopt(_tcp, SOL_SOCKET, SO_LINGER, &lngr, sizeof(linger));

    struct hostent *hp;         /* host information */
    struct sockaddr_in host_sa; /* local address */
    struct sockaddr_in peer_sa; /* remote address */

    /* look up the address of the server given its name */
    hp = gethostbyname( host.c_str() );
    if (!hp) {
      close(_tcp);
      throw std::runtime_error(std::string(hstrerror(h_errno)) + " (" + host + ")");
    }

    /* fill in the hosts's address and data */
    memset(&host_sa, 0, sizeof(host_sa));
    host_sa.sin_family = AF_INET;
    host_sa.sin_addr.s_addr = htonl(INADDR_ANY);
    host_sa.sin_port = htons(0);

    if ( bind(_tcp, (struct sockaddr *)&host_sa, sizeof(host_sa)) < 0 )
    {
      close(_tcp);
      throw std::runtime_error("Bind of TCP socket failed: " + std::string(strerror(errno)));
    }

    /* fill in the server's address and data */
    memset(&peer_sa, 0, sizeof(peer_sa));
    peer_sa.sin_family = AF_INET;
    peer_sa.sin_port = htons(port);

    /* put the host's address into the server address structure */
    memcpy((void *)&peer_sa.sin_addr, hp->h_addr_list[0], hp->h_length);

    /* connect to server */
    if ( connect(_tcp, (struct sockaddr *)&peer_sa, sizeof(peer_sa)) < 0 )
    {
      close(_tcp);
      throw std::runtime_error(std::string(strerror(errno)) + " (" + host + ":" + port_str + ")");
    }

    if ( (_udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0 )
    {
      close(_tcp);
      throw std::runtime_error("Could not create UDP socket");
    }

    sockoptval = 1;
    setsockopt(_udp, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(int));

    /* fill in the hosts's address and data */
    memset(&host_sa, 0, sizeof(host_sa));
    host_sa.sin_family = AF_INET;
    host_sa.sin_addr.s_addr = htonl(INADDR_ANY);
    host_sa.sin_port = htons(DEFAULT_PORT);

    if ( bind(_udp, (struct sockaddr *)&host_sa, sizeof(host_sa)) < 0 )
    {
      close(_tcp);
      close(_udp);
      throw std::runtime_error("Bind of UDP socket failed: " + std::string(strerror(errno)));
    }

#endif

  }

  /* Wait 10 ms before sending queries to device (required for networked radios). */
  boost::this_thread::sleep_for(boost::chrono::milliseconds(10));

  /* request & print device information */

  std::vector< unsigned char > response;

  if ( ! label.length() ) /* label is empty, request name & serial from device */
  {
    std::cerr << "Using ";

    unsigned char name[] = { 0x04, 0x20, 0x01, 0x00 }; /* NETSDR 4.1.1 Target Name */
    if ( transaction( name, sizeof(name), response ) )
      std::cerr << "RFSPACE " << &response[sizeof(name)] << " ";

    unsigned char sern[] = { 0x04, 0x20, 0x02, 0x00 }; /* NETSDR 4.1.2 Target Serial Number */
    if ( transaction( sern, sizeof(sern), response ) )
      std::cerr << "SN " << &response[sizeof(sern)] << " ";
  }

  unsigned char prod[] = { 0x04, 0x20, 0x09, 0x00 }; /* NETSDR 4.1.6 Product ID */
  if ( transaction( prod, sizeof(prod), response ) )
  {
    uint32_t product_id = htonl(*((uint32_t *)&response[sizeof(prod)]));
//    std::cerr << std::hex << product_id << std::dec << " ";

    if ( 0x5affa500 == product_id ) /* SDR-IQ 5.1.6 Product ID */
      _radio = RFSPACE_SDR_IQ;
    else if ( 0x53445203 == product_id ) /* SDR-IP 4.1.6 Product ID */
      _radio = RFSPACE_SDR_IP;
    else if ( 0x53445204 == product_id ) /* NETSDR 4.1.6 Product ID */
      _radio = RFSPACE_NETSDR;
    else if ( 0x434C4951 == product_id ) /* CloudIQ Product ID */
      _radio = RFSPACE_CLOUDIQ;
    else
      std::cerr << "UNKNOWN ";
  }

  bool has_X2_option = false;

  if ( RFSPACE_NETSDR == _radio )
  {
    unsigned char opts[] = { 0x04, 0x20, 0x0A, 0x00 }; /* NETSDR 4.1.7 Options */
    if ( transaction( opts, sizeof(opts), response ) )
    {
      if ( response[sizeof(opts)] )
      {
        has_X2_option = (response[sizeof(opts)] & 16 ? true : false);

        std::cerr << "option ";
        std::cerr << (response[sizeof(opts)] & 16 ? "2" : "-"); /* X2 board */
        std::cerr << (response[sizeof(opts)] &  8 ? "U" : "-"); /* Up Converter */
        std::cerr << (response[sizeof(opts)] &  4 ? "D" : "-"); /* Down Converter */
        std::cerr << (response[sizeof(opts)] &  2 ? "R" : "-"); /* Reflock board */
        std::cerr << (response[sizeof(opts)] &  1 ? "S" : "-"); /* Sound Enabled */
        std::cerr << " ";
      }
    }
  }

  /* NETSDR 4.1.4 Hardware/Firmware Versions */

  unsigned char bootver[] = { 0x05, 0x20, 0x04, 0x00, 0x00 };
  if ( transaction( bootver, sizeof(bootver), response ) )
    std::cerr << "BOOT " << *((uint16_t *)&response[sizeof(bootver)]) << " ";

  unsigned char firmver[] = { 0x05, 0x20, 0x04, 0x00, 0x01 };
  if ( transaction( firmver, sizeof(firmver), response ) )
    std::cerr << "FW " << *((uint16_t *)&response[sizeof(firmver)]) << " ";

  if ( RFSPACE_NETSDR == _radio ||
       RFSPACE_SDR_IP == _radio ||
       RFSPACE_CLOUDIQ == _radio)
  {
    unsigned char hardver[] = { 0x05, 0x20, 0x04, 0x00, 0x02 };
    if ( transaction( hardver, sizeof(hardver), response ) )
      std::cerr << "HW " << *((uint16_t *)&response[sizeof(hardver)]) << " ";
  }

  if ( RFSPACE_NETSDR == _radio ||
       RFSPACE_CLOUDIQ == _radio)
  {
    unsigned char fpgaver[] = { 0x05, 0x20, 0x04, 0x00, 0x03 };
    if ( transaction( fpgaver, sizeof(fpgaver), response ) )
      std::cerr << "FPGA " << int(response[sizeof(fpgaver)])
                << "/" << int(response[sizeof(fpgaver)+1]) << " ";
  }

  std::cerr << std::endl;

  if ( RFSPACE_NETSDR == _radio )
  {
    /* NETSDR 4.2.2 Receiver Channel Setup */
    unsigned char rxchan[] = { 0x05, 0x00, 0x19, 0x00, 0x00 };

    unsigned char mode = 0; /* 0 = Single Channel Mode */

    if ( 2 == _nchan )
    {
      if ( has_X2_option )
        mode = 6; /* Dual Channel with dual A/D RF Path (requires X2 option) */
      else
        mode = 4; /* Dual Channel with single A/D RF Path using main A/D. */

      set_output_signature( gr::io_signature::make (2, 2, sizeof (gr_complex)) );
    }

    rxchan[sizeof(rxchan)-1] = mode;
    transaction( rxchan, sizeof(rxchan) );
  }
  else
  {
    if ( 2 == _nchan )
      std::cerr << "NetSDR receiver required for dual channel support." << std::endl;
  }

  /* preset reasonable defaults */

  if ( RFSPACE_SDR_IQ == _radio )
  {
    set_sample_rate( 196078 );
  }
  else if ( RFSPACE_NETSDR == _radio ||
            RFSPACE_SDR_IP == _radio )
  {
    set_sample_rate( 200000 );

    set_bandwidth( 0 ); /* switch to automatic filter selection by default */
  }
  else if ( RFSPACE_CLOUDIQ == _radio)
  {
    set_sample_rate( 240000 );
    set_bandwidth( 0 );
  }

  /* start TCP keepalive thread */
  if ( RFSPACE_NETSDR == _radio ||
       RFSPACE_SDR_IP == _radio ||
       RFSPACE_CLOUDIQ == _radio )
  {
    _run_tcp_keepalive_task = true;
    _thread = gr::thread::thread( boost::bind(&rfspace_source_c::tcp_keepalive_task, this) );
  }

#if 0
  std::cerr << "sample_rates: " << get_sample_rates().to_pp_string() << std::endl;
  std::cerr << "sample rate: " << (uint32_t)get_sample_rate() << std::endl;

  std::cerr << "freq range:  " << get_freq_range().to_pp_string() << std::endl;
  std::cerr << "center freq: " << (uint32_t)get_center_freq() << std::endl;

  std::cerr << "gain range:  " << get_gain_range().to_pp_string() << std::endl;
  std::cerr << "gain:        " << (uint32_t)get_gain() << std::endl;

  std::cerr << "bw range:    " << get_bandwidth_range().to_pp_string() << std::endl;
#endif
}

/*
 * Our virtual destructor.
 */
rfspace_source_c::~rfspace_source_c ()
{
#ifndef USE_ASIO
  close(_tcp);
  close(_udp);
#endif

  if ( RFSPACE_SDR_IQ == _radio )
  {
    _run_usb_read_task = false;

    _thread.join();
  }
  else
  {
    _run_tcp_keepalive_task = false;
    _thread.interrupt();
    _thread.join();
  }

  close(_usb);

  if ( _fifo )
  {
    delete _fifo;
    _fifo = NULL;
  }
}

void rfspace_source_c::apply_channel( unsigned char *cmd, size_t chan )
{
  unsigned char value = 0;

  if ( 0 == chan )
  {
    value = 0;
  }
  else if ( 1 == chan )
  {
    if ( _nchan < 2 )
      throw std::runtime_error("Channel must be 0 only");

    value = 2;
  }
  else
    throw std::runtime_error("Channel must be 0 or 1");

  cmd[4] = value;
}

bool rfspace_source_c::transaction( const unsigned char *cmd, size_t size )
{
  std::vector< unsigned char > response;

  if ( ! transaction( cmd, size, response ) )
    return false;

  /* comparing the contents is not really feasible due to protocol */
  if ( response.size() == size ) /* check response size against request */
    return true;

  return false;
}

//#define VERBOSE

bool rfspace_source_c::transaction( const unsigned char *cmd, size_t size,
                                   std::vector< unsigned char > &response )
{
  size_t rx_bytes = 0;
  unsigned char data[1024*2];

  response.clear();

#ifdef VERBOSE
  printf("< ");
  for (size_t i = 0; i < size; i++)
    printf("%02x ", (unsigned char) cmd[i]);
  printf("\n");
#endif

  if ( RFSPACE_SDR_IQ == _radio )
  {
    if ( write(_usb, cmd, size) != (int)size )
      return false;

    boost::unique_lock<boost::mutex> lock(_resp_lock);
    _resp_avail.wait(lock);

    rx_bytes = _resp.size();
    memcpy( data, _resp.data(), rx_bytes );
  }
  else
  {
    boost::mutex::scoped_lock lock(_tcp_lock);

#ifdef USE_ASIO
    _t.write_some( boost::asio::buffer(cmd, size) );

    rx_bytes = _t.read_some( boost::asio::buffer(data, sizeof(data)) );
#else
    if ( write(_tcp, cmd, size) != (int)size )
      return false;

    int nbytes = read(_tcp, data, 2); /* read header */
    if ( nbytes != 2 )
      return false;

    int length = (data[1] & 0x1f) | data[0];

    if ( (length < 2) || (length > (int)sizeof(data)) )
      return false;

    length -= 2; /* subtract header size */

    nbytes = read(_tcp, &data[2], length); /* read payload */
    if ( nbytes != length )
      return false;

    rx_bytes = 2 + length; /* header + payload */
#endif
  }

  response.resize( rx_bytes );
  memcpy( response.data(), data, rx_bytes );

#ifdef VERBOSE
  printf("> ");
  for (size_t i = 0; i < rx_bytes; i++)
    printf("%02x ", (unsigned char) data[i]);
  printf("\n");
#endif

  return true;
}

static size_t read_bytes( int fd, char *data, size_t size, bool &run )
{
  size_t nbytes = 0;

  while ( nbytes < size && run )
  {
    int nread = read( fd, &data[nbytes], 1 );

    if ( nread == 0 )
      continue;   

    if ( nread < 0 )
      break;

    nbytes++;
  }

  return nbytes;
}

void rfspace_source_c::usb_read_task()
{
  char data[1024*10];
  size_t n_avail, to_copy;

  if ( -1 == _usb )
    return;

  while ( _run_usb_read_task )
  {
    size_t nbytes = read_bytes( _usb, data, 2, _run_usb_read_task );
    if ( nbytes != 2 )
      continue;

    size_t length = ((data[1] << 8) | data[0]) & 0x1fff;

    if ( 0 == length ) /* SDR-IQ 5.4.1 Output Data Item 0 */
      length = 1024*8 + 2;

    if ( length <= 2 )
      continue;

    length -= 2; /* subtract header */

    if ( length > sizeof(data) - 2 )
    {
      _run_usb_read_task = false;

      continue;
    }

    nbytes = read_bytes( _usb, data + 2, length, _run_usb_read_task );
    if ( nbytes != length )
      continue;

    if ( 1024*8 == length )
    {
      /* push samples into the fifo */

      _fifo_lock.lock();

      size_t num_samples = length / 4;
      n_avail = _fifo->capacity() - _fifo->size();
      to_copy = (n_avail < num_samples ? n_avail : num_samples);

      #define SCALE_16  (1.0f/32768.0f)

      int16_t *sample = (int16_t *)(data + 2);

      for ( size_t i = 0; i < to_copy; i++ )
      {
        /* Push sample to the fifo */
        _fifo->push_back( gr_complex( *(sample+0) * SCALE_16,
                                      *(sample+1) * SCALE_16 ) );

        /* offset to the next I+Q sample */
        sample += 2;
      }

      #undef SCALE_16

      _fifo_lock.unlock();

      /* We have made some new samples available to the consumer in work() */
      if (to_copy) {
//        std::cerr << "+" << std::flush;
        _samp_avail.notify_one();
      }

      /* Indicate overrun, if neccesary */
      if (to_copy < num_samples)
        std::cerr << "O" << std::flush;
    }
    else
    {
      /* copy response & signal transaction */

      _resp_lock.lock();

      _resp.clear();
      _resp.resize( length + 2 );
      memcpy( _resp.data(), data, length + 2 );

      _resp_lock.unlock();

      _resp_avail.notify_one();
    }
  }
}

/* send periodic status requests to keep TCP connection alive */
void rfspace_source_c::tcp_keepalive_task()
{
  std::vector< unsigned char > response;
  unsigned char status_pkt[] = { 0x04, 0x20, 0x05, 0x00 };

  if ( -1 == _tcp )
    return;

  while ( _run_tcp_keepalive_task )
  {
    boost::this_thread::sleep_for(boost::chrono::seconds(60));
    transaction( status_pkt, sizeof(status_pkt), response );
  }
}

bool rfspace_source_c::start()
{
  _sequence = 0;
  _running = true;
  _keep_running = false;

  /* SDR-IP 4.2.1 Receiver State */
  /* NETSDR 4.2.1 Receiver State */
  unsigned char start[] = { 0x08, 0x00, 0x18, 0x00, 0x80, 0x02, 0x00, 0x00 };

  /* SDR-IQ 5.2.1 Receiver State */
  if ( RFSPACE_SDR_IQ == _radio )
    start[sizeof(start)-4] = 0x81;

  unsigned char mode = 0; /* 0 = 16 bit Contiguous Mode */

  if ( 0 ) /* TODO: 24 bit Contiguous mode */
    mode |= 0x80;

  if ( 0 ) /* TODO: Hardware Triggered Pulse mode */
    mode |= 0x03;

  start[sizeof(start)-2] = mode;

  return transaction( start, sizeof(start) );
}

bool rfspace_source_c::stop()
{
  if ( ! _keep_running )
    _running = false;
  _keep_running = false;

  if ( _fifo )
    _fifo->clear();

  /* SDR-IP 4.2.1 Receiver State */
  /* NETSDR 4.2.1 Receiver State */
  unsigned char stop[] = { 0x08, 0x00, 0x18, 0x00, 0x00, 0x01, 0x00, 0x00 };

  /* SDR-IQ 5.2.1 Receiver State */
  if ( RFSPACE_SDR_IQ == _radio )
    stop[sizeof(stop)-4] = 0x81;

  return transaction( stop, sizeof(stop) );
}

/* Main work function, pull samples from the socket */
int rfspace_source_c::work( int noutput_items,
                           gr_vector_const_void_star &input_items,
                           gr_vector_void_star &output_items )
{
  unsigned char data[1024*2];

  if ( ! _running )
    return WORK_DONE;

  if ( RFSPACE_SDR_IQ == _radio )
  {
    if ( noutput_items > 0 )
    {
      gr_complex *out = (gr_complex *)output_items[0];

      boost::unique_lock<boost::mutex> lock(_fifo_lock);

      /* Wait until we have the requested number of samples */
      int n_samples_avail = _fifo->size();

      while ( n_samples_avail < noutput_items )
      {
        _samp_avail.wait(lock);
        n_samples_avail = _fifo->size();
      }

      for ( int i = 0; i < noutput_items; ++i )
      {
        out[i] = _fifo->at(0);
        _fifo->pop_front();
      }

//      std::cerr << "-" << std::flush;
    }

    return noutput_items;
  }

#ifdef USE_ASIO
  udp::endpoint ep;
  size_t rx_bytes = _u.receive_from( boost::asio::buffer(data, sizeof(data)), ep );
#else
  struct sockaddr_in sa_in;           /* remote address */
  socklen_t addrlen = sizeof(sa_in);  /* length of addresses */
  ssize_t rx_bytes = recvfrom(_udp, data, sizeof(data), 0, (struct sockaddr *)&sa_in, &addrlen);
  if ( rx_bytes <= 0 )
  {
    std::cerr << "recvfrom returned " << rx_bytes << std::endl;
    return WORK_DONE;
  }
#endif

  #define HEADER_SIZE 2
  #define SEQNUM_SIZE 2

//  bool is_24_bit = false;   // TODO: implement 24 bit sample format

  /* check header */
  if ( (0x04 == data[0] && (0x84 == data[1] || 0x82 == data[1])) )
  {
//    is_24_bit = false;
  }
  else if ( (0xA4 == data[0] && 0x85 == data[1]) ||
            (0x84 == data[0] && 0x81 == data[1]) )
  {
//    is_24_bit = true;
    return 0;
  }
  else
    return 0;

  uint16_t sequence = *((uint16_t *)(data + HEADER_SIZE));

  uint16_t diff = sequence - _sequence;

  if ( diff > 1 )
  {
    std::cerr << "Lost " << diff << " packets from "
#ifdef USE_ASIO
              << ep
#else
              << inet_ntoa(sa_in.sin_addr) << ":" << ntohs(sa_in.sin_port)
#endif
              << std::endl;
  }

  _sequence = (0xffff == sequence) ? 0 : sequence;

  /* get pointer to samples */
  int16_t *sample = (int16_t *)(data + HEADER_SIZE + SEQNUM_SIZE);

  size_t rx_samples = (rx_bytes - HEADER_SIZE - SEQNUM_SIZE) / (sizeof(int16_t) * 2);

  #define SCALE_16  (1.0f/32768.0f)

  if ( 1 == _nchan )
  {
    gr_complex *out = (gr_complex *)output_items[0];
    for ( size_t i = 0; i < rx_samples; i++ )
    {
      out[i] = gr_complex( *(sample+0) * SCALE_16,
                           *(sample+1) * SCALE_16 );

      sample += 2;
    }
  }
  else if ( 2 == _nchan )
  {
    rx_samples /= 2;

    gr_complex *out1 = (gr_complex *)output_items[0];
    gr_complex *out2 = (gr_complex *)output_items[1];
    for ( size_t i = 0; i < rx_samples; i++ )
    {
      out1[i] = gr_complex( *(sample+0) * SCALE_16,
                            *(sample+1) * SCALE_16 );

      out2[i] = gr_complex( *(sample+2) * SCALE_16,
                            *(sample+3) * SCALE_16 );

      sample += 4;
    }
  }

  #undef SCALE_16

  noutput_items = rx_samples;

  return noutput_items;
}

/* discovery protocol internals taken from CuteSDR project */
typedef struct __attribute__ ((__packed__))
{
  /* 56 fixed common byte fields */
  unsigned char length[2]; 	/* length of total message in bytes (little endian byte order) */
  unsigned char key[2];		/* fixed key key[0]==0x5A  key[1]==0xA5 */
  unsigned char op;			/* 0 == Tx_msg(to device), 1 == Rx_msg(from device), 2 == Set(to device) */
  char name[16];				/* Device name string null terminated */
  char sn[16];				/* Serial number string null terminated */
  unsigned char ipaddr[16];	/* device IP address (little endian byte order) */
  unsigned char port[2];		/* device Port number (little endian byte order) */
  unsigned char customfield;	/* Specifies a custom data field for a particular device */
} discover_common_msg_t;

/* UDP port numbers for discovery protocol */
#define DISCOVER_SERVER_PORT 48321	/* PC client Tx port, SDR Server Rx Port */
#define DISCOVER_CLIENT_PORT 48322	/* PC client Rx port, SDR Server Tx Port */

#define KEY0      0x5A
#define KEY1      0xA5
#define MSG_REQ   0
#define MSG_RESP  1
#define MSG_SET   2

typedef struct
{
  std::string name;
  std::string sn;
  std::string addr;
  uint16_t port;
} unit_t;

#ifdef USE_ASIO
static void handle_receive( const boost::system::error_code& ec,
                            std::size_t length,
                            boost::system::error_code* out_ec,
                            std::size_t* out_length )
{
  *out_ec = ec;
  *out_length = length;
}

static void handle_timer( const boost::system::error_code& ec,
                          boost::system::error_code* out_ec )
{
  *out_ec = boost::asio::error::timed_out;
}
#endif

static std::vector < unit_t > discover_netsdr()
{
  std::vector < unit_t > units;

#ifdef USE_ASIO
  boost::system::error_code ec;
  boost::asio::io_service ios;
  udp::socket socket(ios);
  deadline_timer timer(ios);

  timer.expires_at(boost::posix_time::pos_infin);

  socket.open(udp::v4(), ec);

  if ( ec )
    return units;

  socket.bind(udp::endpoint(udp::v4(), DISCOVER_CLIENT_PORT), ec);

  if ( ec )
    return units;

  socket.set_option(udp::socket::reuse_address(true));
  socket.set_option(boost::asio::socket_base::broadcast(true));
#else
  int sock;

  if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0 )
    return units;

  int sockoptval = 1;
  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(int));
  sockoptval = 1;
  setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &sockoptval, sizeof(int));

  struct sockaddr_in host_sa; /* local address */
  struct sockaddr_in peer_sa; /* remote address */

  /* fill in the server's address and data */
  memset((char*)&peer_sa, 0, sizeof(peer_sa));
  peer_sa.sin_family = AF_INET;
  peer_sa.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  peer_sa.sin_port = htons(DISCOVER_SERVER_PORT);

  /* fill in the hosts's address and data */
  memset(&host_sa, 0, sizeof(host_sa));
  host_sa.sin_family = AF_INET;
  host_sa.sin_addr.s_addr = htonl(INADDR_ANY);
  host_sa.sin_port = htons(DISCOVER_CLIENT_PORT);

  if ( bind(sock, (struct sockaddr *)&host_sa, sizeof(host_sa)) < 0 )
  {
    close(sock);
    return units;
  }

  struct timeval tv;
  tv.tv_sec = 0;
  tv.tv_usec = 100000;
  if ( setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0 )
  {
    close(sock);
    return units;
  }
#endif
  discover_common_msg_t tx_msg;
  memset( (void *)&tx_msg, 0, sizeof(discover_common_msg_t) );

  tx_msg.length[0] = sizeof(discover_common_msg_t);
  tx_msg.length[1] = sizeof(discover_common_msg_t) >> 8;
  tx_msg.key[0] = KEY0;
  tx_msg.key[1] = KEY1;
  tx_msg.op = MSG_REQ;
#ifdef USE_ASIO
  udp::endpoint ep(boost::asio::ip::address_v4::broadcast(), DISCOVER_SERVER_PORT);
  socket.send_to(boost::asio::buffer(&tx_msg, sizeof(tx_msg)), ep);
#else
  sendto(sock, &tx_msg, sizeof(tx_msg), 0, (struct sockaddr *)&peer_sa, sizeof(peer_sa));
#endif
  while ( true )
  {
    std::size_t rx_bytes = 0;
    unsigned char data[1024*2];

#ifdef USE_ASIO
    // Set up the variables that receive the result of the asynchronous
    // operation. The error code is set to would_block to signal that the
    // operation is incomplete. Asio guarantees that its asynchronous
    // operations will never fail with would_block, so any other value in
    // ec indicates completion.
    ec = boost::asio::error::would_block;

    // Start the asynchronous receive operation. The handle_receive function
    // used as a callback will update the ec and rx_bytes variables.
    socket.async_receive( boost::asio::buffer(data, sizeof(data)),
        boost::bind(handle_receive, _1, _2, &ec, &rx_bytes) );

    // Set a deadline for the asynchronous operation.
    timer.expires_from_now( boost::posix_time::milliseconds(10) );

    // Start an asynchronous wait on the timer. The handle_timer function
    // used as a callback will update the ec variable.
    timer.async_wait( boost::bind(handle_timer, _1, &ec) );

    // Reset the io_service in preparation for a subsequent run_one() invocation.
    ios.reset();

    // Block until at least one asynchronous operation has completed.
    do ios.run_one(); while ( ec == boost::asio::error::would_block );

    if ( boost::asio::error::timed_out == ec ) /* timer was first to complete */
    {
      // Please note that cancel() has portability issues on some versions of
      // Microsoft Windows, and it may be necessary to use close() instead.
      // Consult the documentation for cancel() for further information.
      socket.cancel();

      break;
    }
    else /* socket was first to complete */
    {
      timer.cancel();
    }
#else
    socklen_t addrlen = sizeof(peer_sa);  /* length of addresses */
    int nbytes = recvfrom(sock, data, sizeof(data), 0, (struct sockaddr *)&peer_sa, &addrlen);
    if ( nbytes <= 0 )
      break;

    rx_bytes = nbytes;
#endif

    if ( rx_bytes >= sizeof(discover_common_msg_t) )
    {
      discover_common_msg_t *rx_msg = (discover_common_msg_t *)data;

      if ( KEY0 == rx_msg->key[0] && KEY1 == rx_msg->key[1] &&
           MSG_RESP == rx_msg->op )
      {
        void *temp = rx_msg->port;
        uint16_t port = *((uint16_t *)temp);

        std::string addr = str(boost::format("%d.%d.%d.%d")
            % int(rx_msg->ipaddr[3]) % int(rx_msg->ipaddr[2])
            % int(rx_msg->ipaddr[1]) % int(rx_msg->ipaddr[0]));

        unit_t unit;

        unit.name = rx_msg->name;
        unit.sn = rx_msg->sn;
        unit.addr = addr;
        unit.port = port;

        units.push_back( unit );
      }
    }
  }
#ifdef USE_ASIO
  socket.close(ec);
#else
  close(sock);
#endif

  return units;
}

static std::string read_file(const char *filename)
{
  std::ifstream in(filename, std::ios::in | std::ios::binary);
  if (in)
  {
    std::string contents;

    in.seekg(0, std::ios::end);
    contents.resize(in.tellg());
    in.seekg(0, std::ios::beg);
    in.read(&contents[0], contents.size());
    in.close();

    return contents;
  }

  return "";
}

static std::vector < unit_t > discover_sdr_iq()
{
  std::vector < unit_t > units;

  int n;
  struct dirent **namelist;
  char buffer[1024];
  std::vector< std::string > ftdi_sio_devices;

  const char* sys_prefix = "/sys/class/tty/";

  n = scandir( sys_prefix, &namelist, NULL, NULL );
  if ( n > 0 )
  {
    while ( n-- )
    {
      if ( strcmp( namelist[n]->d_name, "." ) &&
           strcmp( namelist[n]->d_name, ".." ) )
      {
        struct stat st;

        std::string device = std::string(sys_prefix) + namelist[n]->d_name;
        std::string device_driver = device + "/device/driver";

        if ( lstat( device_driver.c_str(), &st ) == 0 && S_ISLNK(st.st_mode) )
        {
          memset(buffer, 0, sizeof(buffer));

          if ( readlink( device_driver.c_str(), buffer, sizeof(buffer) ) > 0 )
          {
            const char *base = basename(buffer);
            if ( base && strcmp( base, "ftdi_sio" ) == 0 )
            {
              ftdi_sio_devices.push_back( device );
            }
          }
        }
      }

      free( namelist[n] );
    }

    free( namelist );
  }

  for ( size_t i = 0; i < ftdi_sio_devices.size(); i++ )
  {
    memset(buffer, 0, sizeof(buffer));

    if ( readlink( ftdi_sio_devices[i].c_str(), buffer, sizeof(buffer) ) > 0 )
    {
      std::string path(buffer);

      size_t sep_pos = path.size();
      for ( size_t i = 0; i < 4; i++ )
      {
        if ( sep_pos != std::string::npos )
          sep_pos--;

        sep_pos = path.rfind("/", sep_pos);
      }

      path = path.substr( 0, sep_pos );

      size_t dev_pos = path.find("/devices");
      if ( dev_pos != std::string::npos )
        path = path.substr( dev_pos );

      path = "/sys" + path;

      std::string product = read_file( (path + "/product").c_str() );

      size_t pos = product.find('\n');
      if ( pos != std::string::npos )
        product.erase( pos );

      if ( "SDR-IQ" != product )
        continue;

      std::string serial = read_file( (path + "/serial").c_str() );
      if ( serial.empty() )
        serial = "<none>";

      pos = serial.find('\n');
      if ( pos != std::string::npos )
        serial.erase( pos );

      std::string port = std::string("/dev/");

      const char *base = basename(buffer);
      if ( base )
        port += base;
#if 0
      std::cerr << product << std::endl;
      std::cerr << serial << std::endl;
      std::cerr << port << std::endl;
#endif
      unit_t unit;

      unit.name = product;
      unit.sn = serial;
      unit.addr = port;
      unit.port = 0;

      units.push_back( unit );
    }
  }

  return units;
}

std::vector<std::string> rfspace_source_c::get_devices( bool fake )
{
  std::vector<std::string> devices;

  std::vector < unit_t > units = discover_netsdr();

  BOOST_FOREACH( unit_t u, units )
  {
//    std::cerr << u.name << " " << u.sn << " " << u.addr <<  ":" << u.port
//              << std::endl;

    std::string type = u.name;
    std::transform(type.begin(), type.end(), type.begin(), ::tolower);

    devices += str(boost::format("%s=%s:%d,label='RFSPACE %s SN %s'")
                   % type % u.addr % u.port % u.name % u.sn);
  }

  units = discover_sdr_iq();

  BOOST_FOREACH( unit_t u, units )
  {
//    std::cerr << u.name << " " << u.sn << " " << u.addr <<  ":" << u.port
//              << std::endl;

    std::string type = u.name;
    std::transform(type.begin(), type.end(), type.begin(), ::tolower);

    devices += str(boost::format("%s=%s,label='RFSPACE %s SN %s'")
                   % type % u.addr % u.name % u.sn);
  }

  if ( devices.empty() && fake )
  {
    devices += str(boost::format("sdr-iq=%s,label='RFSPACE SDR-IQ Receiver'")
                   % "/dev/ttyUSB0");

    devices += str(boost::format("sdr-ip=%s:%d,label='RFSPACE SDR-IP Receiver'")
                   % DEFAULT_HOST % DEFAULT_PORT);

    devices += str(boost::format("netsdr=%s:%d,label='RFSPACE NetSDR Receiver'")
                   % DEFAULT_HOST % DEFAULT_PORT);

    devices += str(boost::format("cloudiq=%s:%d,label='RFSPACE Cloud-IQ Receiver'")
                   % DEFAULT_HOST % DEFAULT_PORT);
  }

  return devices;
}

size_t rfspace_source_c::get_num_channels()
{
  return _nchan;
}

#define NETSDR_MAX_RATE  2e6  /* same for SDR-IP & NETSDR */
#define NETSDR_ADC_CLOCK 80e6 /* same for SDR-IP & NETSDR */
#define SDR_IQ_ADC_CLOCK 66666667 /* SDR-IQ 5.2.4 I/Q Data Output Sample Rate */

osmosdr::meta_range_t rfspace_source_c::get_sample_rates()
{
  osmosdr::meta_range_t range;

  if ( RFSPACE_SDR_IQ == _radio )
  {
    /* Populate fixed sample rates as per SDR-IQ 5.2.4 I/Q Data Output Sample Rate */
    range += osmosdr::range_t( 8138 );
    range += osmosdr::range_t( 16276 );
    range += osmosdr::range_t( 37793 );
    range += osmosdr::range_t( 55556 );
    range += osmosdr::range_t( 111111 );
    range += osmosdr::range_t( 158730 );
    range += osmosdr::range_t( 196078 );
  }
  else if ( RFSPACE_SDR_IP == _radio )
  {
    /* Calculate SDR-IP sample rates as per SDR-IP 4.2.8 DDC Output Sample Rate */
    for ( size_t decimation = 2560; decimation >= 40; decimation -= 10 )
    {
      double rate = NETSDR_ADC_CLOCK / decimation;

      if ( rate > (NETSDR_MAX_RATE / _nchan) )
        break;

      if ( floor(rate) == rate )
        range += osmosdr::range_t( rate );
    }
  }
  else if ( RFSPACE_NETSDR == _radio )
  {
    /* Calculate NetSDR sample rates as per NETSDR 4.2.9 I/Q Output Data Sample Rate */
    for ( size_t decimation = 2500; decimation >= 40; decimation -= 4 )
    {
      double rate = NETSDR_ADC_CLOCK / decimation;

      if ( rate > (NETSDR_MAX_RATE / _nchan) )
        break;

      if ( floor(rate) == rate )
        range += osmosdr::range_t( rate );
    }
  }
  else if ( RFSPACE_CLOUDIQ == _radio )
  {
    /* CloudIQ supports 122.88 MHz / 4*N for N = 17 ... 3072, but lets limit
     * ourselves to the ones available in SpectraVue (plus a few)
     */
    range += osmosdr::range_t( 48000 );
    range += osmosdr::range_t( 61440 );
    range += osmosdr::range_t( 96000 );
    range += osmosdr::range_t( 122880 );
    range += osmosdr::range_t( 240000 );
    range += osmosdr::range_t( 256000 );
    range += osmosdr::range_t( 370120 );
    range += osmosdr::range_t( 495483 );
    range += osmosdr::range_t( 512000 );
    range += osmosdr::range_t( 614400 );
    range += osmosdr::range_t( 1024000 );
    range += osmosdr::range_t( 1228800 );
    range += osmosdr::range_t( 1807058 );
  }

  return range;
}

double rfspace_source_c::set_sample_rate( double rate )
{
  if ( RFSPACE_SDR_IQ == _radio )
  {
    /* does not support arbitrary rates, pick closest from hardcoded values above */

    double closest_rate = get_sample_rates().clip( rate, true );

    if ( closest_rate != rate )
      std::cerr << "Picked closest supported sample rate of " << (uint32_t)closest_rate << " Hz"
                << std::endl;

    rate = closest_rate; /* override */
  }

  /* SDR-IQ 5.2.4 I/Q Data Output Sample Rate */
  /* SDR-IP 4.2.8 DDC Output Sample Rate */
  /* NETSDR 4.2.9 I/Q Output Data Sample Rate */
  unsigned char samprate[] = { 0x09, 0x00, 0xB8, 0x00, 0x00, 0x20, 0xA1, 0x07, 0x00 };

  uint32_t u32_rate = rate;
  samprate[sizeof(samprate)-4] = u32_rate >>  0;
  samprate[sizeof(samprate)-3] = u32_rate >>  8;
  samprate[sizeof(samprate)-2] = u32_rate >> 16;
  samprate[sizeof(samprate)-1] = u32_rate >> 24;

  std::vector< unsigned char > response;

  if ( _running )
  {
    _keep_running = true;

    stop();
  }

  if ( ! transaction( samprate, sizeof(samprate), response ) )
    throw std::runtime_error("set_sample_rate failed");

  if ( _running )
  {
    start();
  }

  u32_rate = 0;
  u32_rate |= response[sizeof(samprate)-4] <<  0;
  u32_rate |= response[sizeof(samprate)-3] <<  8;
  u32_rate |= response[sizeof(samprate)-2] << 16;
  u32_rate |= response[sizeof(samprate)-1] << 24;

  _sample_rate = u32_rate;

  if ( rate != _sample_rate )
    std::cerr << "Radio reported a sample rate of " << (uint32_t)_sample_rate << " Hz"
              << std::endl;

  return get_sample_rate();
}

double rfspace_source_c::get_sample_rate()
{
  return _sample_rate;
}

osmosdr::freq_range_t rfspace_source_c::get_freq_range( size_t chan )
{
  osmosdr::freq_range_t range;

  if ( RFSPACE_SDR_IQ == _radio )
  {
    /* does not support range query, use hardcoded values */
    range += osmosdr::range_t(0, SDR_IQ_ADC_CLOCK / 2.0f);

    return range;
  }

  /* query freq range(s) of the radio */

  /* SDR-IP 4.2.2 Receiver Frequency */
  /* NETSDR 4.2.3 Receiver Frequency */
  unsigned char frange[] = { 0x05, 0x40, 0x20, 0x00, 0x00 };

  apply_channel( frange, chan );

  std::vector< unsigned char > response;

  transaction( frange, sizeof(frange), response );

  if ( response.size() >= sizeof(frange) + 1 )
  {
    for ( size_t i = 0; i < response[sizeof(frange)]; i++ )
    {
      uint32_t min = *((uint32_t *)&response[sizeof(frange)+1+i*15]);
      uint32_t max = *((uint32_t *)&response[sizeof(frange)+1+5+i*15]);
      //uint32_t vco = *((uint32_t *)&response[sizeof(frange)+1+10+i*15]);

      //std::cerr << min << " " << max << " " << vco << std::endl;

      range += osmosdr::range_t(min, max); /* must be monotonic */
    }
  }

  if ( range.empty() ) /* assume reasonable default */
    range += osmosdr::range_t(0, NETSDR_ADC_CLOCK / 2.0f);

  return range;
}

double rfspace_source_c::set_center_freq( double freq, size_t chan )
{
  uint32_t u32_freq = freq;

  /* SDR-IQ 5.2.2 Receiver Frequency */
  /* SDR-IP 4.2.2 Receiver Frequency */
  /* NETSDR 4.2.3 Receiver Frequency */
  unsigned char tune[] = { 0x0A, 0x00, 0x20, 0x00, 0x00, 0xb0, 0x19, 0x6d, 0x00, 0x00 };

  apply_channel( tune, chan );

  tune[sizeof(tune)-5] = u32_freq >>  0;
  tune[sizeof(tune)-4] = u32_freq >>  8;
  tune[sizeof(tune)-3] = u32_freq >> 16;
  tune[sizeof(tune)-2] = u32_freq >> 24;
  tune[sizeof(tune)-1] = 0;

  transaction( tune, sizeof(tune) );

  return get_center_freq( chan );
}

double rfspace_source_c::get_center_freq( size_t chan )
{
  /* SDR-IQ 5.2.2 Receiver Frequency */
  /* SDR-IP 4.2.2 Receiver Frequency */
  /* NETSDR 4.2.3 Receiver Frequency */
  unsigned char freq[] = { 0x05, 0x20, 0x20, 0x00, 0x00 };

  apply_channel( freq, chan );

  std::vector< unsigned char > response;

  if ( ! transaction( freq, sizeof(freq), response ) )
    throw std::runtime_error("get_center_freq failed");

  uint32_t frequency = 0;
  frequency |= response[response.size()-5] <<  0;
  frequency |= response[response.size()-4] <<  8;
  frequency |= response[response.size()-3] << 16;
  frequency |= response[response.size()-2] << 24;

  return frequency;
}

double rfspace_source_c::set_freq_corr( double ppm, size_t chan )
{
  return get_freq_corr( chan );
}

double rfspace_source_c::get_freq_corr( size_t chan )
{
  return 0;
}

std::vector<std::string> rfspace_source_c::get_gain_names( size_t chan )
{
  std::vector< std::string > names;

  names += "ATT";

  return names;
}

osmosdr::gain_range_t rfspace_source_c::get_gain_range( size_t chan )
{
  if ( RFSPACE_SDR_IQ == _radio )
    return osmosdr::gain_range_t(-20, 10, 10);
  else /* SDR-IP, NETSDR and Cloud-IQ */
    return osmosdr::gain_range_t(-30, 0, 10);
}

osmosdr::gain_range_t rfspace_source_c::get_gain_range( const std::string & name, size_t chan )
{
  return get_gain_range( chan );
}

bool rfspace_source_c::set_gain_mode( bool automatic, size_t chan )
{
  return false;
}

bool rfspace_source_c::get_gain_mode( size_t chan )
{
  return false;
}

double rfspace_source_c::set_gain( double gain, size_t chan )
{
  /* SDR-IQ 5.2.5 RF Gain */
  /* SDR-IP 4.2.3 RF Gain */
  /* NETSDR 4.2.6 RF Gain */
  unsigned char atten[] = { 0x06, 0x00, 0x38, 0x00, 0x00, 0x00 };

  apply_channel( atten, chan );

  if ( RFSPACE_SDR_IQ == _radio )
  {
    if ( gain <= -20 )
      atten[sizeof(atten)-1] = 0xE2;
    else if ( gain <= -10 )
      atten[sizeof(atten)-1] = 0xEC;
    else if ( gain <= 0 )
      atten[sizeof(atten)-1] = 0xF6;
    else /* +10 dB */
      atten[sizeof(atten)-1] = 0x00;
  }
  else /* SDR-IP & NETSDR */
  {
    if ( gain <= -30 )
      atten[sizeof(atten)-1] = 0xE2;
    else if ( gain <= -20 )
      atten[sizeof(atten)-1] = 0xEC;
    else if ( gain <= -10 )
      atten[sizeof(atten)-1] = 0xF6;
    else /* 0 dB */
      atten[sizeof(atten)-1] = 0x00;
  }

  transaction( atten, sizeof(atten) );

  return get_gain( chan );
}

double rfspace_source_c::set_gain( double gain, const std::string & name, size_t chan )
{
  return set_gain( gain, chan );
}

double rfspace_source_c::get_gain( size_t chan )
{
  /* SDR-IQ 5.2.5 RF Gain */
  /* SDR-IP 4.2.3 RF Gain */
  /* NETSDR 4.2.6 RF Gain */
  unsigned char atten[] = { 0x05, 0x20, 0x38, 0x00, 0x00 };

  apply_channel( atten, chan );

  std::vector< unsigned char > response;

  if ( ! transaction( atten, sizeof(atten), response ) )
    throw std::runtime_error("get_gain failed");

  unsigned char code = response[response.size()-1];

  double gain = code;

  if( code & 0x80 )
    gain = (code & 0x7f) - 0x80;

  if ( RFSPACE_SDR_IQ == _radio )
    gain += 10;

  return gain;
}

double rfspace_source_c::get_gain( const std::string & name, size_t chan )
{
  return get_gain( chan );
}

std::vector< std::string > rfspace_source_c::get_antennas( size_t chan )
{
  std::vector< std::string > antennas;

  antennas += get_antenna( chan );

  return antennas;
}

std::string rfspace_source_c::set_antenna( const std::string & antenna, size_t chan )
{
  return get_antenna( chan );
}

std::string rfspace_source_c::get_antenna( size_t chan )
{
  /* We only have a single receive antenna here */
  return "RX";
}

#define BANDWIDTH 34e6

double rfspace_source_c::set_bandwidth( double bandwidth, size_t chan )
{
  if ( RFSPACE_SDR_IQ == _radio ||
       RFSPACE_CLOUDIQ == _radio) /* not supported by SDR-IQ or Cloud-IQ */
    return 0.0f;

  /* SDR-IP 4.2.5 RF Filter Selection */
  /* NETSDR 4.2.7 RF Filter Selection */
  unsigned char filter[] = { 0x06, 0x00, 0x44, 0x00, 0x00, 0x00 };

  apply_channel( filter, chan );

  if ( 0.0f == bandwidth )
  {
    _bandwidth = 0.0f;
    filter[sizeof(filter)-1] = 0x00; /* Select bandpass filter based on NCO frequency */
  }
  else if ( BANDWIDTH == bandwidth )
  {
    _bandwidth = BANDWIDTH;
    filter[sizeof(filter)-1] = 0x0B; /* Bypass bandpass filter, use only antialiasing */
  }

  transaction( filter, sizeof(filter) );

  return get_bandwidth();
}

double rfspace_source_c::get_bandwidth( size_t chan )
{
  return _bandwidth;
}

osmosdr::freq_range_t rfspace_source_c::get_bandwidth_range( size_t chan )
{
  osmosdr::freq_range_t bandwidths;

  bandwidths += osmosdr::range_t( BANDWIDTH );

  return bandwidths;
}
