/**
   This is a little CLI program to control the picoscope frequency 
   generator coming with the Pico Labs Picoscope 2206a oscilloscope

   Mark Koennecke, May 2015

 */

#include <sys/types.h>
#include <string.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#include <libps2000a-1.1/ps2000aApi.h>
#ifndef PICO_STATUS
#include <libps2000a-1.1/PicoStatus.h>
#endif


static short handle;

/*--------------------------------------------------------------*/
static void StopPico(void)
{
  ps2000aCloseUnit(handle);
}
/*--------------------------------------------------------------*/
static void SetGenerator(long freq, float ampl)
{
  int status;

  if(freq == 0){
    status = ps2000aSetSigGenBuiltIn(handle,
				     0,
				     0,
				     PS2000A_DC_VOLTAGE,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0);
  } else {
    status = ps2000aSetSigGenBuiltIn(handle,
				     0,
				     (unsigned long)ampl,
				     PS2000A_SINE,
				     (float)freq,
				     (float)freq,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0,
				     0);
  }
  if(status != PICO_OK){
    printf("Failed to configure signal generator with %d\n", status);
  }
}
/*----------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
  int status;
  long int freq = 1000;
  float mult = 1000000, ampl = 1.*mult, tmp;
  char line[80], token[80];

  status = ps2000aOpenUnit(&handle, NULL);
  if(status != PICO_OK){
    printf("Failed to open picoscope with %d\n", status);
    exit(1);
  }

  atexit(StopPico);

  while(1) {
    memset(line,0,sizeof(line));
    fgets(line,sizeof(line),stdin);

    if(strstr(line,"freq") != NULL){
      status = sscanf(line,"%s %f",token, &tmp);
      if(status == 2){
	freq = (unsigned int) tmp;
	SetGenerator(freq,ampl);
	printf("OK\n");
      } else {
	printf("freq  %ld\n", freq); 
      }
    } else if(strstr(line,"ampl") != NULL){
      status = sscanf(line,"%s %f",token, &tmp);
      if(status == 2){
	ampl = tmp*mult;
	SetGenerator(freq,ampl);
	printf("OK\n");
      } else {
	printf("ampl  %f\n", ampl/mult); 
      }
    } else if(strstr(line,"on") != NULL){
      SetGenerator(freq,ampl);
	printf("OK\n");
    }else if(strstr(line,"off") != NULL){
      SetGenerator(0,0);
	printf("OK\n");
    }else if(strstr(line,"exit") != NULL){
        ps2000aCloseUnit(handle);
	break;
    } else {
      printf("Parameter commands: freq (hz), ampl( V), on, off\n");
    }
    fflush(stdout);
  }


}
