using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;

namespace ET_2217H_AI_Log
{
    class Program
    {

        public static bool IsIP(string ip)  //Check the IP format
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }


        static void Main(string[] args)
        {

            string IP = "";
            bool ret = false;
            bool quitIP = false;
            bool quit = false;

            IntPtr hHS;

            short ChCnt = 8;
            int Ch_EN = 1;//0=disable,1=Enable
            int Ch_Type = 4;//Gain
            short Gain = 3;//Ch_Type
            /*---------------------------------
             * 0 = +/- 2.5V          
             * 1 = 0 ~ 5V
             * 2 = +/- 5V
             * 3 = 0 ~ 10V
             * 4 = +/- 10V
             * 5 = 0 ~ 20mA
             * 6 = +/- 20mA
             * 7 = 4 ~ 20mA
            ---------------------------------*/
            ushort BufferStatus = 0;
            uint LoggerStatus = 0;
            UInt32 readsize = 0;
            int FileType = 1;

            string FilePath = Directory.GetCurrentDirectory();

            short TrigMode = 0;
            UInt32 targetCnt = 0;
            int sampleRate = 1000;

            short DataTransMethod = 0;
            short AutoRun = 0;

            Console.WriteLine("This example program is only applicable to the ET-2217H !!");

            while (quitIP == false)
            {
                Console.WriteLine("Please Enter IP!!");
                IP = Console.ReadLine();
                ret = IsIP(IP);
                if (ret == false)
                {
                    Console.WriteLine("Please enter the correct IP");
                }
                else
                {
                    quitIP = true;
                    Thread.Sleep(100);
                }
            }


            hHS = HSDAQNet.Sys.HS_Device_Create(IP);

            if (hHS != IntPtr.Zero)
            {
                //----------------------------------------------------------------------------------------------------------------------
                //The API HS_SetConfig() is used to configure individual channels. 
                //This section demonstrates how to use HS_SetConfig() to individually configure which channels to enable and set the channel type. 
                //The example enables all channels and sets the same channel type for each.
                //Choose either HS_SetAIScanParam() or the HS_SetConfig() described in the section below, but only one can be used.
                //It is recommended to use HS_SetConfig(), as this method is more flexible.
                for (int i = 0; i < ChCnt; i++)
                {
                    HSDAQNet.Config.HS_SetConfig(hHS, (int)HSDAQNet.ConfigCode.EACH_CH_ENABLE, i, Ch_EN);
                    Thread.Sleep(100);
                    HSDAQNet.Config.HS_GetConfig(hHS, (int)HSDAQNet.ConfigCode.EACH_CH_ENABLE, i, ref Ch_EN);
                    Thread.Sleep(100);
                    HSDAQNet.Config.HS_SetConfig(hHS, (int)HSDAQNet.ConfigCode.EACH_CH_TYPE, i, Ch_Type);
                    Thread.Sleep(100);
                    HSDAQNet.Config.HS_GetConfig(hHS, (int)HSDAQNet.ConfigCode.EACH_CH_TYPE, i, ref Ch_Type);
                    Console.WriteLine("[ch{0}] Enable = {1} , Type = {2}", i, Ch_EN, Ch_Type);
                }
                //----------------------------------------------------------------------------------------------------------------------




                //----------------------------------------------------------------------------------------------------------------------
                //HS_SetAIScanParam() allows you to configure the number of channels to enable, 
                //but it does not let you specify exactly which channels. For example, 
                //if you set it to enable 2 channels, it will automatically enable ch0 and ch1; 
                //if you set it to enable 4 channels, it will enable ch0, ch1, ch2, and ch3. 
                //Additionally, the channel type can only be set uniformly, and individual configuration for each channel is not possible.
                //In the HS_SetAIScanParam() API, you only need to configure 'ChCnt' and 'Gain'; other parameters can be set to 0.
                /*
                HSDAQNet.HSIO.HS_SetAIScanParam(hHS, ChCnt, Gain, 0, 0, 0, 0, 0);
                Thread.Sleep(10);
                HSDAQNet.HSIO.HS_GetAIScanParam(hHS, ref ChCnt, ref Gain, ref TrigMode, ref sampleRate, ref targetCnt, ref DataTransMethod, ref AutoRun);
                //HS_GetAIScanParam() can read the enabled/disabled status and channel types for all channels.
                //However, if the channels are not enabled in sequence (e.g., ch0 enabled, ch1 disabled, ch2 enabled), or if the channel types are inconsistent, an error message will be logged.
                //Therefore, using the HS_SetAIScanParam() and HS_GetAIScanParam() APIs is not recommended, and it is suggested to use HS_SetConfig() and HS_GetConfig() instead.
                Console.WriteLine("Ch=" + ChCnt + ",Gain=" + Gain);
                */
                //----------------------------------------------------------------------------------------------------------------------



                ret = true;
                if (!ret)
                {
                    Console.WriteLine("Error code1 0x" + HSDAQNet.ErrHandling.GetLastError().ToString("x8"));
                }
                else
                {
                    Console.WriteLine(System.DateTime.Now);
                    ret = HSDAQNet.DATALOG.HS_StartLogger(hHS, FilePath, 1, FileType);//Parameter 2 is the interval time for switching files, in minutes.Parameter 3 is the file format: 0 = bin, 1 = txt.

                    if (ret == false)
                    {
                        Console.WriteLine("Error code2 0x" + HSDAQNet.ErrHandling.GetLastError().ToString("x8"));
                    }
                    Console.WriteLine("Press 'Q' to stop capturing data");

                    while (quit == false)
                    {
                        ret = HSDAQNet.HSIO.HS_GetTotalSamplingStatus(hHS, ref readsize, ref LoggerStatus);
                        Console.Write(readsize + "\r");

                        if (ret == false)
                        {
                            Console.WriteLine("Error code3 0x" + HSDAQNet.ErrHandling.GetLastError().ToString("x8"));
                        }
                        else
                        {
                            if ((LoggerStatus & 0x02) == 0x02 || (LoggerStatus & 0x04) == 0x04 || (LoggerStatus & 0x08) == 0x08)
                            {

                                //  2:  AD_BUF_OVERFLOW	
                                //  4:  AD_SCAN_STOP
                                //  8:  AD_DATA_SAMPLING_TIMEOUT

                                Console.WriteLine("BufferStatus Error<" + BufferStatus + ">," + readsize);
                                break;
                            }
                        }

                        if (readsize >= 8000)//The ET-2217H does not support N-Sample Mode, so if you only want to collect a fixed number of data points, please make a similar check as in this line.
                        {
                            quit = true;
                        }
                        if (readsize > 0)
                        {
                            if (Console.KeyAvailable)
                            {
                                if (Console.ReadKey(true).Key == ConsoleKey.Q)
                                {
                                    quit = true;
                                }
                            }
                        }

                    }

                    HSDAQNet.DATALOG.HS_StopLogger(hHS);
                    Thread.Sleep(10);
                    HSDAQNet.Sys.HS_Device_Release(hHS);
                    Console.WriteLine("\r\nAP total read = " + readsize + "\r\n");
                }

                /******************************How to get log file****************************/
                int fileNum = 0;
                string STARTtime = "";
                string STARTdate = "";
                uint logcount = 0;
                string logpath = "";
                Thread.Sleep(10);
                fileNum = HSDAQNet.DATALOG.HS_GetAllLogFiles(FilePath, FileType);
                Console.WriteLine("fileNum : {0}", fileNum);
                for (int i = 0; i < fileNum; i++)
                {
                    IntPtr loghandle = HSDAQNet.DATALOG.HS_LogFile_Open_byIndex(i, ref logpath);
                    HSDAQNet.DATALOG.HS_GetLogFile_AIScanSampleInfo(loghandle, ref logcount, ref STARTdate, ref STARTtime);
                    Console.WriteLine("Open file : " + logpath);
                    float[] fdatabuffer = new float[logcount]; Console.WriteLine(logcount);
                    HSDAQNet.DATALOG.HS_GetLogFile_AIData(loghandle, 0, logcount, fdatabuffer);
                    for (int y = 0; y < 40; y++)
                    {
                        if (y % ChCnt == ChCnt - 1)
                            Console.Write(fdatabuffer[y].ToString("F4") + "\r\n");
                        else
                            Console.Write(fdatabuffer[y].ToString("F4") + ",");

                    }
                    HSDAQNet.DATALOG.HS_LogFile_Close(loghandle);
                }

                Console.WriteLine("Press 'Q' to quit program");

                
                while (Console.ReadKey(true).Key != ConsoleKey.Q) ;
            }
        }
    }
}
