//
// Extended data example for the Crandun Technologies CTI-AR4000
// software library.
// Copyright (c) 2001, Crandun Technologies Inc.
//
// This example demonstrates how to change the sensor's sample rate,
// and how to acquire extended sample information 
// (ambient light, amplitude and temperature readings) from the sensor.
//
#include "CTI_AR4000.h"	// required header
#include <iostream>		// needed for cout

using namespace std;		// we use cin, cout and cerr
using namespace Crandun;	// all library symbols are in this namespace

// A helper macro for checking return codes
#define CHK_RETURN_VALUE(retCode, fnName) \
if (retCode < 0) { \
		cerr << "ERROR: " #fnName " returned error code: " << rc << endl; \
		my_Sensor.setCommClosed(); \
		cerr << "Please enter any character to exit: "; \
		cin >> c; \
		return (-1); \
} 


int main()
{
	char c;
	long rc;
	const int MAXSAMPLES = 100;
	AR4000_DATA_PT extRangeData[MAXSAMPLES];

	CTI_AR4000 my_Sensor;

	cout << "Crandun Technologies CTI-AR4000 Library extended sample data example." << endl << endl;

	cout << "Opening the serial port..." << endl;
	rc = my_Sensor.setCommOpen("COM1:", 9600);
	if (rc != CTI_SUCCESS) {
		cerr << "ERROR: setCommParams returned error: " << rc << endl;
		cerr << "Please enter any character to exit: ";
		cin >> c;
		return -1;
	}
	cout << "Successfully opened the serial port!" << endl;

	cout << "Setting sample rate to 10 samples/second." << endl;
	rc = my_Sensor.setSamplesPerSec(10);
	CHK_RETURN_VALUE(rc, setSamplesPerSec);
	cout << "Successfully set the sample rate!" << endl;

	cout << "Setting extended outputs on." << endl;
	rc = my_Sensor.setLowLevelOutputOn();
	CHK_RETURN_VALUE(rc, setLowLevelOutputOn);
	cout << "Successfully set extended outputs on!" << endl;

	cout << "Reading samples from sensor..." << endl;
	rc = my_Sensor.getExtSamples(extRangeData, MAXSAMPLES, 3);	// acquire at least 3 samples
	CHK_RETURN_VALUE(rc, getExtSamples);

	cout << "Read " << rc << " range samples from the sensor." << endl;

	for (int i = 0; i < rc; i++) {
		cout << "Range " << i << " is:  " << extRangeData[i].range << " inches."<< endl;
		cout << "     Raw range is:     " << extRangeData[i].rawRange << endl;
		cout << "     Sensor temp. is:  " << extRangeData[i].temperature << " deg. F." << endl;
		cout << "     Ambient light is: " << extRangeData[i].ambient << endl;
		cout << "     Amplitude is:     " << extRangeData[i].amplitude << endl;
	}

	cout << my_Sensor.getNumBytesSkipped() << " bytes of data were skipped." << endl;

	my_Sensor.setCommClosed();

	cout << "Please enter any character to exit: ";
	cin >> c;
	return 0;
}