using System;
using System.Globalization;
using System.Text;
using System.Net;
using RFDeviceNet;

namespace DemoSharp
{
    class Program
    {
        private const string MainMenu = "****************************************************\r\nPress key to select:\r\n" +
                                        "1 - Test 620  device.\r\n" +
                                        "2 - Test 603  device.\r\n" +
                                        "3 - Test 625_Legacy  device.\r\n" +
                                        "4 - Test 656  device.\r\n" +
                                        "5 - Test 625 device.\r\n" +
                                        "Other - Exit.";

        private static PacketWorker _pworker;

        static void Main(string[] args)
        {
            _pworker = new PacketWorker();
           var init= RFDeviceObjectNet.Initialize();
            if (init==0)
            {
                Console.WriteLine("RFDeviceObject initializing failed. Program will exit.");
                Console.Read();
                return;
            }
        //    Console.WriteLine("Library version - " + RFDeviceObjectNet.Get);
            while (true)
            {
                Console.WriteLine(MainMenu);
                var key = Console.ReadKey();
                Console.WriteLine();
                if (key.Key == ConsoleKey.D1 || key.Key == ConsoleKey.NumPad1)
                    Go620Test();
                else if (key.Key == ConsoleKey.D2 || key.Key == ConsoleKey.NumPad2)
                    Go603Test();
                else if (key.Key == ConsoleKey.D3 || key.Key == ConsoleKey.NumPad3)
                    Go625_LegacyTest();
                else if (key.Key == ConsoleKey.D4 || key.Key == ConsoleKey.NumPad4)
                    Go656Test();
                else if (key.Key == ConsoleKey.D5 || key.Key == ConsoleKey.NumPad5)
                    Go625Test();
                else
                {
                    break;
                }
            }
        }



        static void Go625Test()
        {
            Console.WriteLine("625 test...");

            _UDP_DEVINFOBLOCK_PC_Net block;
            try
            {
                block = _pworker.GetUdpPcketFrom620();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }


            var dev = RF625DeviceNet.CreateRF625Device(block);
            var sb = new StringBuilder();
            foreach (var b in block.IP)
            {
                sb.Append(b.ToString(CultureInfo.InvariantCulture) + '.');
            }
            sb.Remove(sb.Length - 1, 1);
            if (dev.Connect() != 0)
            {
                Console.WriteLine("Connected to 625 device " + sb + '.');
                Console.WriteLine(dev.ReadParams() != 0
                                      ? "Parameters reading from 625 device done."
                                      : "Can't read parameters from 625 device.");
                Console.WriteLine(dev.WriteParams() != 0
                                      ? "Parameters writing to 625 device done."
                                      : "Can't write parameters to 625 device.");
                var tcpResultBuffer = new Byte[0];
                if (dev.GetResult(ref tcpResultBuffer)!=0)
                {
                    Console.WriteLine("TCP GetResult operation result:");
                    int i = 0;
                    foreach (var b in tcpResultBuffer)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("TCP GetResult operation error.");
                    Console.WriteLine(dev.Disconnect() != 0 ? "625 device disconnected." : "625 device disconnect error.");
                }
            }
            else
            {
                Console.WriteLine("TCP connecting to 625 device failed.");
            }

            while (true)
            {
                Console.WriteLine("Input local IP for UDP working with 625 device. Use 'Enter' when complete.");
                var ip = Console.ReadLine();
                Console.WriteLine();
                IPAddress ipAddress;
                if (ip == null || IPAddress.TryParse(ip, out ipAddress) == false)
                {
                    Console.WriteLine("Wrong ip.");
                }
                else
                {
                    Console.WriteLine("Current ip: " + ipAddress);
                    if (dev.UDPConnect(6001, ipAddress.ToString()) == 0)
                    {
                        Console.WriteLine("Can't connect with 625 device via UDP.");
                        break;
                    }

                    var tcpResultBuffer = new float[0];
                    var count = new ushort();
                    if (dev.UDPGetNormalizedResult(ref tcpResultBuffer, ref count) == 0)
                    {
                        Console.WriteLine("Can't get result from 625 device via UDP.");
                        break;
                    }
                    int i = 0;
                    foreach (var b in tcpResultBuffer)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    if (dev.Disconnect() == 0)
                    {
                        Console.WriteLine("Can't disconnect from 625 device via UDP.");
                        break;
                    }
                    Console.WriteLine("Disconnected from 625 device via UDP.");
                    break;
                }
            }
        }




        static void Go625_LegacyTest()
        {
            Console.WriteLine("625_Legacy test...");

            _UDP_DEVINFOBLOCK_PC_Net block;
            try
            {
                block = _pworker.GetUdpPcketFrom620();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            var dev = RF625DeviceNet_Legacy.CreateRF625Device_Legacy(block);
            var sb = new StringBuilder();
            foreach (var b in block.IP)
            {
                sb.Append(b.ToString(CultureInfo.InvariantCulture) + '.');
            }
            sb.Remove(sb.Length - 1, 1);
            if (dev.Connect()!=0)
            {
                Console.WriteLine("Connected to 625_Legacy device " + sb + '.');
                Console.WriteLine(dev.ReadParams()!=0
                                      ? "Parameters reading from 625_Legacy device done."
                                      : "Can't read parameters from 625_Legacy device.");
                Console.WriteLine(dev.WriteParams()!=0
                                      ? "Parameters writing to 625_Legacy device done."
                                      : "Can't write parameters to 625_Legacy device.");
                var tcpResultBuffer = new Byte[0];
                if (dev.GetResult(ref tcpResultBuffer)!=0)
                {
                    Console.WriteLine("TCP GetResult operation result:");
                    int i = 0;
                    foreach (var b in tcpResultBuffer)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("TCP GetResult operation error.");
                }
                Console.WriteLine(dev.Disconnect() != 0 ? "625_Legacy device disconnected." : "625_Legacy device disconnect error.");
            }
            else
            {
                Console.WriteLine("TCP connecting to 625_Legacy device failed.");
            }

            while (true)
            {
                Console.WriteLine("Input local IP for UDP working with 625_Legacy device. Use 'Enter' when complete.");
                var ip = Console.ReadLine();
                Console.WriteLine();
                IPAddress ipAddress;
                if (ip == null || IPAddress.TryParse(ip, out ipAddress) == false)
                {
                    Console.WriteLine("Wrong ip.");
                }
                else
                {
                    Console.WriteLine("Current ip: " + ipAddress);
                    if (dev.UDPConnect(6001, ipAddress.ToString())==0)
                    {
                        Console.WriteLine("Can't connect with 625_Legacy device via UDP.");
                        break;
                    }
                    var udpBuf = new byte[0];
                    if (dev.UDPGetResult(ref udpBuf)==0)
                    {
                        Console.WriteLine("Can't get result from 625_Legacy device via UDP.");
                        break;
                    }
                    int i = 0;
                    foreach (var b in udpBuf)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    if (dev.Disconnect()==0)
                    {
                        Console.WriteLine("Can't disconnect from 625_Legacy device via UDP.");
                        break;
                    }
                    Console.WriteLine("Disconnected from 625_Legacy device via UDP.");
                    break;
                }
            }
        }

        static void Go620Test()
        {
            Console.WriteLine("620 test...");
            
            _UDP_DEVINFOBLOCK_PC_Net block;
            try
            {
                block = _pworker.GetUdpPcketFrom620();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            var dev = RF620DeviceNet.CreateRF620Device(block);
            var sb = new StringBuilder();
            foreach (var b in block.IP)
            {
                sb.Append(b.ToString(CultureInfo.InvariantCulture) + '.');
            }
            sb.Remove(sb.Length - 1, 1);
            if (dev.Connect()!=0)
            {
                Console.WriteLine("Connected to 620 device " + sb + '.');
                Console.WriteLine(dev.ReadParams()!=0
                                      ? "Parameters reading from 620 device done."
                                      : "Can't read parameters from 602 device.");
                Console.WriteLine(dev.WriteParams()!=0
                                      ? "Parameters writing to 620 device done."
                                      : "Can't write parameters to 602 device.");
                var tcpResultBuffer = new Byte[0];
                if (dev.GetResult(ref tcpResultBuffer)!=0)
                {
                    Console.WriteLine("TCP GetResult operation result:");
                    int i = 0;
                    foreach (var b in tcpResultBuffer)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("TCP GetResult operation error.");
                }
                Console.WriteLine(dev.Disconnect()!=0 ? "620 device disconnected." : "620 device disconnect error.");
            }
            else
            {
                Console.WriteLine("TCP connecting to 620 device failed.");
            }

            while (true)
            {
                Console.WriteLine("Input local IP for UDP working with 620 device. Use 'Enter' on complete.");
                var ip = Console.ReadLine();
                Console.WriteLine();
                IPAddress ipAddress;
                if (ip == null || IPAddress.TryParse(ip, out ipAddress) == false)
                {
                    Console.WriteLine("Wrong ip.");
                }
                else
                {
                    Console.WriteLine("Current ip: " + ipAddress);
                    if (dev.UDPConnect(6001, ipAddress.ToString())==0)
                    {
                        Console.WriteLine("Can't connect with 620 device via UDP.");
                        break;
                    }
                    var udpBuf = new byte[0];
                    if (dev.UDPGetResult(ref udpBuf)==0)
                    {
                        Console.WriteLine("Can't get result from 620 device via UDP.");
                        break;
                    }
                    int i = 0;
                    foreach (var b in udpBuf)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    if (dev.Disconnect()==0)
                    {
                        Console.WriteLine("Can't disconnect from 620 device via UDP.");
                        break;
                    }
                    Console.WriteLine("Disconnected from 620 device via UDP.");
                    break;
                }
            }
        }

        static void Go603Test()
        {
            Console.WriteLine("603 test...");
            var dev = RF603DeviceNet.CreateRF603Device();
            dev.BindNetworkAddress(1);
            int comNum;
            while (true)
            {
                Console.WriteLine("Input COM port number for 603 device connection. Press 'Enter' to complete.");
                var comNumStr = Console.ReadLine();
                if (string.IsNullOrEmpty(comNumStr) || !int.TryParse(comNumStr, out comNum))
                {
                    Console.WriteLine("Wrong number.");
                }
                else
                {
                    break;
                }
            }
            if (dev.OpenPort("COM" + comNum.ToString(CultureInfo.InvariantCulture), 921600)==0)
            {
                Console.WriteLine("OpenPort operation error.");
                return;                                       
            }
            var ps = new _RFCOM_HELLO_ANSWER_Net();
            if (dev.HelloCmd() == 0)
            {
                Console.WriteLine("HelloCmd opearion error.");
            }
            else
            {

                Console.WriteLine("Device serial: " + ps.DeviceSerial);
                Console.WriteLine("Device max distance: " + ps.DeviceMaxDistance);

            }
          
            ushort value = 0;
 

            if (dev.StartStream(1)==0)
            {
                Console.WriteLine("Can't start stream from 603 device.");
            }
            else
            {
                Console.Write("GetStreamMeasure: ");
                for (int i = 0; i < 10; i++)
                {  
                    if (dev.GetStreamMeasure(ref value) != 0)
                    {
                       
                        Console.Write((value * 50) / 16384 + " mm, ");
                    }
                    else
                    {
                        Console.Write("GetStreamMeasureError.");
                        break;
                    }
                }
                Console.WriteLine();
                Console.WriteLine(dev.StopStream(1)==0 ? "StopStream operation error." : "StopStream operation complete.");
                Console.WriteLine(dev.ClosePort()==0 ? "ClosePort operation error." : "ClosePort operation complete.");
            }

        }





        static void Go656Test()
        {
            Console.WriteLine("656 test...");
            var dev = RF656DeviceNet.CreateRF656Device();
             dev.BindNetworkAddress(1);
            int comNum;
            while (true)
            {
                Console.WriteLine("Input COM port number for 656 device connection. Press 'Enter' to complete.");
                var comNumStr = Console.ReadLine();
                if (string.IsNullOrEmpty(comNumStr) || !int.TryParse(comNumStr, out comNum))
                {
                    Console.WriteLine("Wrong number.");
                }
                else
                {
                    break;
                }
            }
            if (dev.OpenPort("COM" + comNum.ToString(CultureInfo.InvariantCulture), 115200)==0)
            {
                Console.WriteLine("OpenPort operation error.");
                return;
            }
            var ps  = new _RFCOM_HELLO_ANSWER_Net();
            if (dev.HelloCmd()==0)
            {
                Console.WriteLine("HelloCmd opearion error.");
            }
            else
            {
                Console.WriteLine("Device serial: " + ps.DeviceSerial);
                Console.WriteLine("Device max distance: " + ps.DeviceMaxDistance);
            }
            ushort value = 0;
          /*  if (!dev.Measure(1, ref value))
            {
                Console.WriteLine("Can't get measure from 656 device.");
            }
            Console.WriteLine("Read measure value: " + value.ToString(CultureInfo.InvariantCulture));*/

            if (dev.StartStream(1)==0)
            {
                Console.WriteLine("Can't start stream from 656 device.");
            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    if (dev.GetStreamMeasure(ref value)!=0)
                        Console.Write(value + " ");
                    else
                    {
                        Console.Write("GetStreamMeasureError.");
                        break;
                    }
                }
                Console.WriteLine();
                Console.WriteLine(dev.StopStream(1)==0 ? "StopStream operation error." : "StopStream operation complete.");
                Console.WriteLine(dev.ClosePort()==0 ? "ClosePort operation error." : "ClosePort operation complete.");
            }

        }
    }
}
