using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFDeviceNet;

namespace Lasers
{
    public class AR500
    {
        string ComPort;
	int Baud;
	int NetAddress;
	var DevInstance;
	bool Ready;
	int SerialNumber;
	int MeasurementRange;

        public int Open(string ComPort, int Baud, int NetAddress)
        {
	    Ready = false;
	    this->ComPort = ComPort;
	    this->Baud = Baud;
	    this->NetAddress = NetAddress;

	    DevInstance = RF603DeviceNet.CreateRF603Device();
	    DevInstance.BindNetworkAddress(NetAddress);

	    if (DevInstance.OpenPort(ComPort, Baud) == 0)
            {
		// Unable to open serial port
		return 0;
	    }

	    var ps = new _RFCOM_HELLO_ANSWER_Net();
            if (DevInstance.HelloCmd() == 0)
            {
		// Sensor not responding
		return 0;
	    }

	    SerialNumber = ps.DeviceSerial;
	    MeasurementRange = ps.DeviceMaxDistance;

	    Ready = true;

            return 0;
        }
	
	public int Close()
	{
	    DevInstance.ClosePort()
	}

        public double GetReading()
        {
	    if (!Ready)
	    {
		return 0.0;
	    }

	    ushort value;
            if (DevInstance.GetSingleMeasure(ref value) == 0)
            {
		// Unable to read measure
		return 0.0;
	    }

            return ( (double)value * (double)MeasurementRange / 16384.0 );
        }
    }
}
