///Copyright Doug Lewis 2018, all rights reserved.
using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.Data;
//using System.Drawing;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Globalization;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using System.Drawing;
using System.ComponentModel;
using DAQ;


namespace WindowsFormsApplication1
{
    public partial class RecordingControl : Form
    {
        private BackgroundWorker recordThread;
        private BackgroundWorker playbackThread;
        public string USBAddress = "192.168.7.2";
        //public string EthAddress = "192.168.1.2";
        public string EthAddress = "10.72.152.2";
        DaqState daqState = new DaqState();
        public double[] ma = new double[8];
        public UInt32[] b = new UInt32[8];

        public double[] sensorM = new double[6];
        public double[] sensorB = new double[6];

        public double[] g1Array = new double[60];
        public double[] g2Array = new double[60];
        public double[] g3Array = new double[60];
        public double[] g4Array = new double[60];
        public double[] g5Array = new double[60];
        public double[] g6Array = new double[60];
        public double[] g7Array = new double[60];
        public double[] g0Array = new double[60];

        

        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();

       
        public void msg(string mesg)
        {
            textBox3.Text = textBox3.Text + Environment.NewLine + " >> " + mesg;
        }
        public string timeString()
        {
            DateTime localDate = DateTime.Now;
            var culture = new CultureInfo("de-DE");
            string dateTimeStr = localDate.ToString(culture);
            return compactDateTime(dateTimeStr);
        }

    public void dispTimeMsg()
        {
            string curTimeString = "time" + timeString();

            textBox3.Text = curTimeString;
        }
        public void sendTimeMsg()
        {
            string curTimeString = "time" + timeString() + "\0";

            textBox3.Text = curTimeString;

            Byte[] data = new Byte[256];
            data = System.Text.Encoding.ASCII.GetBytes(curTimeString);
           
            try
            {
                NetworkStream stream = clientSocket.GetStream();

                // Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length);
            }
            catch (SocketException)
            {
                textBox3.Text = "Recording start failed: SocketException: ";
            }
        }

        public void initSensorCalData(double []sensorM, double [] sensorB)
        {
            sensorM[0] = 0.00001196;  //Pressure Sensor A, Channel 12, Tank Bottom Pressure Sensor 
            sensorB[0] = 0.00098618;
            sensorM[1] = 0.00000993;  //Pressure Sensor B, Channel 11, Engine top pressure sensor 
            sensorB[1] = 0.00067037;
            sensorM[2] = 0.0000108;   //Pressure Sensor C, Channel 10, 
            sensorB[2] = 0.001769202;
            sensorM[3] = 0.003101659562;  // Pressure Sensor D, Channel 13, Tank Top,
            sensorB[3] = 0.4003292;
            sensorM[4] = 0.00000993;      // Raw Load Cell, Channel 14
            sensorB[4] = 0.0003450862;
            sensorM[5] = 0.0022580353;   //Load Cell x 250, Channel 15
            sensorB[5] = 0.0862715513;
        }


        public void initCalDataBoard1(double[] ma, UInt32[] b)
        {
           
            ma[0] = 0.633887;
            ma[1] = 0.854749;
            ma[2] = 0.910143;
            ma[3] = 0.911436;
            ma[4] = 0.904735;
            ma[5] = 0.908236;

            ma[6] = 0.905403;
            ma[7] = 0.909174;


            b[0] = 0x1db49c;
            b[1] = 0x64a56;
            b[2] = 0x133B; 
            b[3] = 0xEFE;
            b[4] = 0x100D;
            b[5] = 0x38D7;
            b[6] = 0x12DE;
            b[7] = 0xDF6;
        }

        //public void initCalDataBoard1(double[] ma, UInt32[] b)
        //{
        //    ///ma[0] = 0;
        //    ma[0] = 0.912216;
        //    ma[1] = 0.912216;
        //    ma[2] = 0.909984;
        //    ma[3] = 0.911557;
        //    ma[4] = 0.904937;
        //    ma[5] = 0.909235;

        //    ma[6] = 0.905309;
        //    ma[7] = 0.909302;

        //    //b[0] = 0;
        //    b[1] = 0xd7;
        //    b[1] = 0xD7;
        //    b[2] = 0x17f9;
        //    b[3] = 0xBF5;
        //    b[4] = 0xA10;
        //    b[5] = 0x1B23;
        //    b[6] = 0x15A7;
        //    b[7] = 0xA2A;
        //}

        public double convertBinaryToVoltage(UInt32 x)
        {
            // -Vref / 2 ^ (23 - 1)  if MSB = 1;
            // Vref / 2 ^ (23 -1)    if MSB = 0;

            double result = 0;

            UInt32 msb = x & 0x0800000;  //Remember, the sample is 24 bits wide, msb is bit 23.

            if (msb == 0)
            {

                result = ((double)x / Math.Pow(2, 23)) * 5.5;
                return (result);
            }
            else
            {
                  UInt32 temp = (~x + 1) & 0xFFFFFF;
                  result = -1 * ((double)((~x + 1) & 0xFFFFFF) / Math.Pow(2, 23)) * 5.5;

                return (result);
            }
        }
        public double applyCalibration(UInt32 y, double[] ma, UInt32[] b, int channel)
        {
            // y = x * m + b     ma = actual gain
            // x = (y-b) / ma

            double calResult = 0;
            double yVoltage;
            double mChannel;
            double bVoltage;

            yVoltage = convertBinaryToVoltage(y);
            bVoltage = convertBinaryToVoltage(b[channel]);
            mChannel = ma[channel];

            calResult = (yVoltage - bVoltage) / mChannel * 5 / 5.5;
            return (calResult);
        }
        public void bufferHexDump(Byte[] buffer, int lines)
        {
            for (int l = 0; l < lines; l++)
            {
                for (int j = 0; j < 8; j++)
                {

                    int k = (j * 4) + (32 * l);
                    //int k = (j * 4) + (32 * l) + 32;
                    //  Console.WriteLine("j = {0}, k = {1}, l = {2}", j, k, l);
                    Console.Write(" {0} {1} {2} {3}   ",
String.Format("{0:X2}", buffer[k + 3]),
                                                    String.Format("{0:X2}", buffer[k + 2]),
                                                                                                        String.Format("{0:X2}", buffer[k + 1]),
                                                    String.Format("{0:X2}", buffer[k]));

                    //  Console.WriteLine(" {0} {1} {2} {3}     ",
                    //      k + 3, k + 2, k + 1, k);
                }
                Console.WriteLine(" ");
            }
            Console.WriteLine(" ");

        }
        

        public void procBuffer(Byte [] buffer, double[] ma, UInt32[] b)
        {
            //Each 128k buffer has a 256 byte header
            // First 32 bits contains hex BABEFACE
            // Next 32 bits is a buffer counter
            // Next TBD bits will contain a timestamp

             bufferHexDump(buffer, 2);

            UInt32 samplePtr = 32; // We start with the first sample, header is 32 bytes
            Byte[] Temp = new Byte[4];
            UInt32 littleEndianSample;
            UInt32 bufferCount;
            UInt32 result;
            double[] calVoltageChan = new double[8];
            double pressure1;
            double pressure2;
            double pressure3;
            double pressure4;
            double load1;
            double load2;

            bufferCount = (UInt32)buffer[4];
            bufferCount |= ((UInt32)buffer[5] << 8) & 0x0000FF00;
            bufferCount |= ((UInt32)buffer[6] << 16) & 0x00FF0000;
            bufferCount |= ((UInt32)buffer[7] << 24) & 0xFF000000;
        
            //Process a set of 8 samples, 1 per channel

            for (int i = 0; i < 8; i++)
            {

                // The upper byte is the channel number, we don't use it in further processing
                // Time for a little cowboys and endians Gulliver. The buffer is received in network
                // order, which is big endian and needs to be put into little endian.
                littleEndianSample = (UInt32)buffer[samplePtr];
                littleEndianSample |= ((UInt32)buffer[samplePtr + 1] << 8) & 0x00FF00;
                littleEndianSample |= ((UInt32)buffer[samplePtr + 2] << 16) & 0x00FF0000;
                samplePtr += +4;

                // Calculate the calibrated voltage for each channel 
                // This uses the 0 and 5 volt calibration values  
                calVoltageChan[i] = applyCalibration(littleEndianSample, ma, b, i);
            }

            if ((result = bufferCount % 3) == 0)
            {
                //x= (y - b) / m
                pressure1 = (calVoltageChan[3] - sensorB[3]) / sensorM[3]; //DAQ Channel 13
                pressure2 = (calVoltageChan[4] - sensorB[0]) / sensorM[0];  //DAQ Channel 12
                pressure3 = (calVoltageChan[5] - sensorB[1]) / sensorM[1]; //DAQ Channel 11
                pressure4 = (calVoltageChan[6] - sensorB[2]) / sensorM[2]; //DAQ Channel 10
                load1 = (calVoltageChan[1] - sensorB[5]) / sensorM[5];     //DAQ Channel 15 Load Cell x 250
                load2 = (calVoltageChan[2] - sensorB[4]) / sensorM[4];     //DAQ Channel 14 Raw Load  Cell

                updateArray(g7Array, calVoltageChan[7]); //S1 Battery

                updateArray(g6Array, pressure4);  // Engine chamber pressure sensor (differential)
                updateArray(g5Array, pressure3);  // Engine top pressure sensor (differential)
                updateArray(g4Array, pressure2);   // Tank Bottom Pressure Sensor (differential)
                updateArray(g3Array, pressure1);  // Tank top pressure sensor (single ended)
                updateArray(g2Array, calVoltageChan[2]);  // Raw load cell 
                updateArray(g1Array, calVoltageChan[1]);  // Amplified (x250ish) load cell
                updateArray(g0Array, calVoltageChan[0]);

                updateGraph(chart1, g7Array); //Update Battery S1
                updateGraph(chart2, g6Array); //Update engine chamber pressure sensor 
                updateGraph(chart3, g5Array);
                updateGraph(chart4, g4Array);
                updateGraph(chart5, g3Array);
                updateGraph(chart6, g2Array);
                updateGraph(chart7, g1Array);
                updateGraph(chart8, g0Array);

                Invoke(new MethodInvoker(() => label33.Text = Convert.ToString(bufferCount)));

                Invoke(new MethodInvoker(() => label15.Text = string.Format("{0:0.0000000}", calVoltageChan[0])));  //DAQ Channel 16

                

                Invoke(new MethodInvoker(() => label24.Text = string.Format("{0:0.0000000}", calVoltageChan[1])));  //DAQ Channel 15
                Invoke(new MethodInvoker(() => label34.Text = string.Format("{0:0.0000000}", calVoltageChan[2])));  //DAQ Channel 14
                Invoke(new MethodInvoker(() => label37.Text = string.Format("{0:0.0000000}", calVoltageChan[3])));  //DAQ Channel 13

                Invoke(new MethodInvoker(() => label31.Text = string.Format("{0:0.0000000}", calVoltageChan[4])));  //DAQ Channel 12
                Invoke(new MethodInvoker(() => label39.Text = string.Format("{0:0.0000000}", calVoltageChan[5])));  //DAQ Channel 11
                Invoke(new MethodInvoker(() => label41.Text = string.Format("{0:0.0000000}", calVoltageChan[6])));  //DAQ Channel 10
                Invoke(new MethodInvoker(() => label43.Text = string.Format("{0:0.0000000}", calVoltageChan[7])));  //DAQ Channel 9

                Invoke(new MethodInvoker(() => label26.Text = string.Format("{0:0.0}", pressure1))); //DAQ Channel 13
                Invoke(new MethodInvoker(() => label27.Text = string.Format("{0:0.0}", pressure2))); //DAQ Channel 12

                Invoke(new MethodInvoker(() => label29.Text = string.Format("{0:0.0}", pressure3))); //DAQ Channel 11
                Invoke(new MethodInvoker(() => label44.Text = string.Format("{0:0.0}", pressure4))); //DAQ Channel 10

                Invoke(new MethodInvoker(() => label28.Text = string.Format("{0:0.0}", load1)));                
                Invoke(new MethodInvoker(() => label25.Text = string.Format("{0:0.0}", load2)));

                Invoke(new MethodInvoker(() => Refresh()));
            }
        }
        
        public void updateArray(double[] array, double newVal)
        {
            for (int i = array.Length - 1; i > 0; i -- )
            {
                array[i] = array[i - 1]; 
            }
            array[0] = newVal;
           
        }
        public void updateGraph(Chart chart, double[] array)
        {
            Series myS1 = chart.Series.FindByName("S1");
            int removeIndex = myS1.Points.Count;


            Invoke(new MethodInvoker(() => chart.Series["S1"].Points.Clear()));
            Invoke(new MethodInvoker(() => chart.Update()));
            for (int i = 0; i < array.Length - 1; ++i)
            {
                Invoke(new MethodInvoker(() => chart.Series["S1"].Points.AddXY(i, array[i])));
            }
            Invoke(new MethodInvoker(() => chart.Update()));
            Invoke(new MethodInvoker(() => chart.Refresh()));
        }

        public void initializeChan16S3BatteryGraph(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 2.5;
            chart.ChartAreas[0].AxisY.Maximum = 4.5;
            chart.ChartAreas[0].AxisY.Interval = 1;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }
        public void initializeChan15LoadCellx250(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 0;
            chart.ChartAreas[0].AxisY.Maximum = 1000;
            chart.ChartAreas[0].AxisY.Interval = 250;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }

        public void initializeChan14LoadCellRaw(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 0;
            chart.ChartAreas[0].AxisY.Maximum = 1000;
            chart.ChartAreas[0].AxisY.Interval = 250;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }
        public void initializeChan13TankTopPressureSensor(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 0;
            chart.ChartAreas[0].AxisY.Maximum = 1000;
            chart.ChartAreas[0].AxisY.Interval = 250;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }
        public void initializeChan12TankBottomPressureSensor(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 0;
            chart.ChartAreas[0].AxisY.Maximum = 1000;
            chart.ChartAreas[0].AxisY.Interval = 250;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }
        public void initializeChan11EngineTopPressureSensor(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 0;
            chart.ChartAreas[0].AxisY.Maximum = 1000;
            chart.ChartAreas[0].AxisY.Interval = 250;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }
        public void initializeChan10EngineChamberPressureSensor(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 0;
            chart.ChartAreas[0].AxisY.Maximum = 1000;
            chart.ChartAreas[0].AxisY.Interval = 250;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }

        public void initializeChan9S1BatteryGraph(Chart chart)
        {
            int xMax = 60;

            chart.ChartAreas[0].AxisX.Minimum = 0;
            chart.ChartAreas[0].AxisX.Maximum = xMax;
            chart.ChartAreas[0].AxisY.Minimum = 2.5;
            chart.ChartAreas[0].AxisY.Maximum = 4.5;
            chart.ChartAreas[0].AxisY.Interval = 1;

            Series S1 = new Series();
            S1.ChartType = SeriesChartType.Line;
            S1.Color = Color.Red;
            S1.IsVisibleInLegend = false;
            chart.Series[0].Color = Color.Red;
            chart.Series[0].IsVisibleInLegend = false;
            S1.Name = "S1";

            chart.Series.Add(S1);
            chart.Refresh();
        }
        public RecordingControl()
        {

            InitializeComponent();

            initializeChan9S1BatteryGraph(chart1);

            initializeChan10EngineChamberPressureSensor(chart2);

            initializeChan11EngineTopPressureSensor(chart3);

            initializeChan12TankBottomPressureSensor(chart4);

            initializeChan13TankTopPressureSensor(chart5);

            initializeChan14LoadCellRaw(chart6);

            initializeChan15LoadCellx250(chart7);

            initializeChan16S3BatteryGraph(chart8);

            initCalDataBoard1(ma, b);

            initSensorCalData(sensorM, sensorB);

            daqState.state = daqRecState.OFF;

        }

        void BBBConnect()
        {
            try
            {
                if (daqState.BeagleInterface == BBBInterface.Ethernet)
                {
                    textBox3.Text = "Client Socket Program - Connection Succeeded ...";
                    clientSocket.Connect(EthAddress, 8888);
                    daqState.state = daqRecState.CONNECT;
                }
                else
                {
                    clientSocket.Connect(USBAddress, 8888);
                    textBox3.Text = "Client Socket Program - Connection Succeeded ...";
                    daqState.state = daqRecState.CONNECT;
                }

                dispTimeMsg();

            }
            catch (System.Net.Sockets.SocketException)
            {
                textBox3.Text = "Client Socket Program - Connection Not Established ...";

            }
        }
        private void QuadAEnableCheckbox_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {
            
        }       

     private void recordThread_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            string[] subString = null;
            int result;

            string fileName = @"C:/ERPSData/binrecord";
            // Translate the passed message into ASCII and store it as a byte array.
            string myTimeString = timeString();

            fileName = fileName + myTimeString + ".bin";
            Invoke(new MethodInvoker(() => fileNameLabel.Text = fileName));

            FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            Console.WriteLine("Opening recording file {0}", fileName);
            string messageString = "record" + myTimeString + "\0";
            
            Byte[] data = new Byte[256];
            Byte[] dataIn = new Byte[256];
            string dataInString;
            Byte[] buffer = new Byte[131072]; //128k Recieve Buffer

            data = System.Text.Encoding.ASCII.GetBytes(messageString);


            if  ((recordThread.CancellationPending == false) && (daqState.state == daqRecState.RECORD))
            {

                try
                {
                    NetworkStream stream = clientSocket.GetStream();

                    // Send the message to the connected TcpServer. 
                    Console.WriteLine("Sending record message string {0}", messageString);
                    Console.WriteLine("\0");
                    stream.Write(data, 0, data.Length);
                    Console.WriteLine("Recording Started ...");

                    stream.Read(dataIn, 0, dataIn.Length);

                    dataInString = System.Text.Encoding.ASCII.GetString(dataIn);
                    subString = dataInString.Split(',');
                    result = subString[0].CompareTo("recstart");
                    Console.WriteLine("dataInString = {0}", dataInString);


                    if (result == 0)
                    {
                        uint bufferCount = UInt32.Parse(subString[1]);
                        Console.WriteLine("Buffer Count = {0}", bufferCount);
                        for (int i = 0; i < bufferCount; i++)
                        {
                            int totalRead = 0;
                            int toRead = buffer.Length;
                            try
                            {
                                do
                                {
                                    int inLength = stream.Read(buffer, totalRead, toRead);
                                    totalRead += inLength;
                                    toRead = buffer.Length - totalRead;
                                } while (totalRead < buffer.Length);

                                procBuffer(buffer, ma, b);

                                fileStream.Write(buffer, 0, buffer.Length);
                            }
                            catch (SocketException)
                            {
                                Console.WriteLine("SocketException reading stream: " + e.ToString());
                            }
                            catch (ArgumentException)
                            {
                                Console.WriteLine("Argument Exception reading stream: " + e.ToString());
                            }
                            catch (IOException)
                            {
                                Console.WriteLine("IOException Exception reading stream: " + e.ToString());
                            }
                        }
                    }

                    stream.Read(dataIn, 0, dataIn.Length);
                    dataInString = System.Text.Encoding.ASCII.GetString(dataIn);
                    result = dataInString.CompareTo("recdone");
                    Console.WriteLine("dataInString", dataInString);
                    fileStream.Close();

                }

                catch (SocketException)
                {
                    textBox3.Text = "Recording start failed: SocketException: " + e.ToString();

                    fileStream.Close();
                }
            }
        }
        private void RecordStartButton_Click(object sender, EventArgs e)
        {
            daqState.state = daqRecState.RECORD;
            recordThread = new BackgroundWorker();
            recordThread.WorkerReportsProgress = false;
            recordThread.WorkerSupportsCancellation = true;
            recordThread.DoWork += new DoWorkEventHandler(recordThread_DoWork);
            recordThread.RunWorkerAsync();

        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            string message = "exit\0";
            daqState.state = daqRecState.OFF;
            Byte[] data = new Byte[256];
            data = System.Text.Encoding.ASCII.GetBytes(message);

            daqState.state = daqRecState.OFF;
            try
            {
                NetworkStream stream = clientSocket.GetStream();

                // Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length);
                textBox3.Text = "Recording stopped ...";
            }

            catch (SocketException)
            {
                textBox3.Text = "Recording start failed: SocketException: " + e.ToString();
            }
        }

        private void LaunchModeRadioButton_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
        }

       

        public string compactDateTime(string dateTimeStr)
        {
            
            char[] inString = dateTimeStr.ToCharArray();
            string blankString = "                                  ";
            char[] myString = blankString.ToCharArray();
           
            // Convert a string of this form: 19.06.2015 10:03:06
            // To this form: 06192015100306
            myString[0] = inString[3];
            myString[1] = inString[4];
            myString[2] = inString[0];
            myString[3] = inString[1];
            myString[4] = inString[6];
            myString[5] = inString[7];
            myString[6] = inString[8];
            myString[7] = inString[9];
            myString[8] = inString[11];
            myString[9] = inString[12];
            myString[10] = inString[14];
            myString[11] = inString[15];
            myString[12] = inString[17];
            myString[13] = inString[18];

            string outString = new string(myString);
            return outString;
        }

        private void Test_Click(object sender, EventArgs e)
        {
            sendTimeMsg();
        }

        private void TestDataRadioButton1_CheckedChanged(object sender, EventArgs e)
        {
            //testDataEnabled = TRUE;
        }

        private void chart1_Click(object sender, EventArgs e)
        {

        }

        private void chart1_Click_1(object sender, EventArgs e)
        {

        }

        private void chart2_Click(object sender, EventArgs e)
        {

        }

        private void chart6_Click(object sender, EventArgs e)
        {

        }

        private void chart7_Click(object sender, EventArgs e)
        {

        }

        private void chart8_Click(object sender, EventArgs e)
        {

        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void label15_Click(object sender, EventArgs e)
        {

        }

        private void label32_Click(object sender, EventArgs e)
        {
            //Buffer Count Label
        }

        private void label33_Click(object sender, EventArgs e)
        {
            
        }

        private void label23_Click(object sender, EventArgs e)
        {

        }

        private void label24_Click(object sender, EventArgs e)
        {

        }

        private void label25_Click(object sender, EventArgs e)
        {

        }

        private void label26_Click(object sender, EventArgs e)
        {

        }

        private void label27_Click(object sender, EventArgs e)
        {

        }

        private void label29_Click(object sender, EventArgs e)
        {

        }

        private void label28_Click(object sender, EventArgs e)
        {

        }

        private void label30_Click(object sender, EventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label37_Click(object sender, EventArgs e)
        {

        }

        private void label34_Click(object sender, EventArgs e)
        {

        }

        private void label31_Click(object sender, EventArgs e)
        {

        }

        private void label39_Click(object sender, EventArgs e)
        {

        }

        private void label41_Click(object sender, EventArgs e)
        {

        }

        private void label43_Click(object sender, EventArgs e)
        {

        }

        private void label11_Click(object sender, EventArgs e)
        {

        }

        private void label17_Click(object sender, EventArgs e)
        {

        }

        private void chart1_Click_2(object sender, EventArgs e)
        {

        }

        private void label3_Click_1(object sender, EventArgs e)
        {

        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            daqState.BeagleInterface = BBBInterface.Ethernet;
        }

        private void USBRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            daqState.BeagleInterface = BBBInterface.USB;
        }

        private void fileNameLabel_Click(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void numberBuffsTextBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void numBuffs_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            BBBConnect();
        }
        private void playbackThread_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
             //string fileName1 = @"C:\ERPSData\0V_board1_binrecord06302018201157.bin";
            string fileName2 = @"C:\ERPSData\0v_cal_daq1_09062018202431.bin";

            var fileStream = new FileStream(fileName2, FileMode.Open);


            Console.WriteLine("Opening recording file {0}", fileName2);
            Boolean eof = false;
            int inLength;

            Byte[] buffer = new Byte[131072]; //128k Recieve Buffer

            if ((playbackThread.CancellationPending == false) && (daqState.state == daqRecState.PLAYBACK))
            {
                while (eof == false)
                {
                    int totalRead = 0;
                    int toRead = buffer.Length;
                    //try
                    //{
                        do
                        {
                            inLength = fileStream.Read(buffer, totalRead, toRead);
                            System.Threading.Thread.Sleep(100);
                            procBuffer(buffer, ma, b);
                        } while (inLength != 0);      
                        fileStream.Write(buffer, 0, buffer.Length);
                    //}
                }
            }
        }
        private void PlaybackButton_Click(object sender, EventArgs e)
        {
            daqState.state = daqRecState.PLAYBACK;
            playbackThread = new BackgroundWorker();
            playbackThread.WorkerReportsProgress = false;
            playbackThread.WorkerSupportsCancellation = true;
            playbackThread.DoWork += new DoWorkEventHandler(playbackThread_DoWork);
            playbackThread.RunWorkerAsync();
        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void chart2_Click_1(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void label44_Click(object sender, EventArgs e)
        {

        }

        private void chart3_Click(object sender, EventArgs e)
        {

        }

        private void chart4_Click(object sender, EventArgs e)
        {

        }

        private void label14_Click(object sender, EventArgs e)
        {

        }

        private void chart8_Click_1(object sender, EventArgs e)
        {

        }

        private void label15_Click_1(object sender, EventArgs e)
        {

        }
    }
}
