using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace MoveTest
{
    /// <summary>
    /// This class provides methods to send and recieve data over a serial port
    /// </summary>
    class SerialCommunications : IDisposable
    {
        /// <summary>Base class for serial communications, shouldn't really be public</summary>
        public SerialPort serialPort;

        //public event SerialDataReceivedEventHandler DataReceived;
        //public delegate string dataReceived();

        /// <summary>Creates the serial port and sets it up</summary>
        /// <param name="portName">Text name of the serial port, for example COM17</param>
        public SerialCommunications(string portName)
        {
            serialPort = new SerialPort(portName, 128000,       //Creates serial port with given
                Parity.None, 8, StopBits.One);                  //name and some default values
            serialPort.Handshake = Handshake.RequestToSend;     //Sets up basic handshaking

            if (serialPort.IsOpen)          //Check if serial port already open
            {
                serialPort.Close();         //If so, close it, shouldn't really happen
                System.Windows.Forms.MessageBox.Show
                    ("Serial port already open");
            }

            serialPort.Open();              //Open the serial port
        }

        /// <summary>Sends data to the serial port</summary>
        /// <param name="message">Text string to send</param>
        public void Send(string message)
        {
            serialPort.Write(message);
        }

        /// <summary>Sends data to the serial port</summary>
        /// <param name="buffer">Byte array to send</param>
        public void Send(byte[] buffer)
        {
            serialPort.Write(buffer, 0, buffer.Length);
        }

        /// <summary>Sends data to the serial port</summary>
        /// <param name="buffer">Byte array to send</param>
        /// <param name="offset">The offset into the array to write from</param>
        /// <param name="count">Number of bytes to send</param>
        public void Send(byte[] buffer, int offset, int count)
        {
            serialPort.Write(buffer, offset, count);
        }

        /// <summary>Disposes the serial port</summary>
        public void Dispose()
        {
            serialPort.Dispose();
        }

    }
}
