//
//   C++ Language example for the 
//   Crandun Technologies CTI-AR4000 software library.
//   Copyright (c) 2001, Crandun Technologies Inc.
//
//   This example shows how to retrieve the sensor's
//   firmware version, and how to change the sensor's baud rate.
//

#include "CTI_AR4000.h"	// required header
#include <iostream>		// needed for cout, cerr, cin

using namespace std;		// we use cout, cerr, cin, string
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 i;
	long rc;
	const int MAXSAMPLES=20;
	float rangeData[MAXSAMPLES];
	char sFirmwareVersion[40];
	CTI_AR4000 my_Sensor;

	cout << "Crandun Technologies CTI-AR4000 Baud Rate change sample program." << endl;;
	
	cout << "Opening the serial port..." << endl;
	rc = my_Sensor.setCommOpen("COM1:", 9600);
	CHK_RETURN_VALUE(rc, setCommOpen)
	cout << "Successfully opened the serial port!" << endl;

	// Query the sensor's firmware version 
	cout << "Querying the sensor firmware version..." << endl;
	rc = my_Sensor.getFirmwareVersion(sFirmwareVersion, sizeof(sFirmwareVersion));
	CHK_RETURN_VALUE(rc, setCommOpen)
	cout << "The sensor firmware version is '" << sFirmwareVersion << "'" << endl;


	// Now change the baud rate
	cout << "Changing baud rate to 19200" << endl;
	rc = my_Sensor.setBaudRate(19200);
	CHK_RETURN_VALUE(rc, setBaudRate)
	cout << "Successfully changed baud rate to 19200" << endl;

	cout << "Reading samples from sensor..." << endl;
	rc = my_Sensor.getSamples(rangeData, MAXSAMPLES, 5);
	CHK_RETURN_VALUE(rc, getSamples)

	cout << "Read " << rc << " range samples from the sensor." << endl;
	for (i = 0; i < rc; i++)
		cout << "Range " << i << " is " << rangeData[i] << " inches." << endl;

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


	// Now change the baud rate to 38400 
	cout << "Changing baud rate to 38400" << endl;
	rc = my_Sensor.setBaudRate(38400);
	CHK_RETURN_VALUE(rc, setBaudRate)
	cout << "Successfully changed baud rate to 38400" << endl;

	cout << "Reading samples from sensor..." << endl;
	rc = my_Sensor.getSamples(rangeData, MAXSAMPLES, 5);
	CHK_RETURN_VALUE(rc, getSamples)

	cout << "Read " << rc << " range samples from the sensor." << endl;
	for (i = 0; i < rc; i++)
		cout << "Range " << i << " is " << rangeData[i] << " inches." << endl;

	cout << my_Sensor.getNumBytesSkipped() << " bytes of data were skipped." << endl;;
	
	
	// closing the comm port changes the baud rate back to factory default of 9600 
	my_Sensor.setCommClosed();

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