using System;
using System.Threading;
using System.IO.Ports;
using System.Text;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace CPF
{
    class PositionSensor
    {
        public delegate void    ReportPosition(double positionIn_MM);
        private AutoResetEvent  _done;
        private Channel         _ADUCM360;
        private double          _positionInMM;
        private bool            _synced;

        private void PositionResponse(byte[] buffer)
        {
            if (_synced == true)
            {
                for (int i = 0; i < buffer.Length; i++)
                {
                    if (buffer[i] == 0x20)
                    {
                        buffer[i] = 0;  // Trim, off the SP-m-m-CR-LF"
                        string s = new string(System.Text.Encoding.UTF8.GetChars(buffer));
                        if (NumberParser.TryParseDouble(s, out _positionInMM))
                            Debug.Print(_positionInMM.ToString("F2"));
                        else
                            Debug.Print("Error, string: " + s + " is not a valid number.");
                        break;
                    }
                }
            }
            else
            {
                // Ignore the first message received
                _synced = true;
            }
        }

        public PositionSensor()
        {
            _done = new AutoResetEvent(false);
            _synced = false;
            _ADUCM360 = new Channel("com2", 9600);
            _ADUCM360.Callback = PositionResponse;
            _ADUCM360.Terminator = 0x0A;
        }

        public void Go()
        {
            _ADUCM360.Start();
        }

        public void Halt()
        {
            _ADUCM360.Stop();
            _ADUCM360.Dispose();
            _synced = false;
        }
    }
}
