/*
 * Configure.cs
 * 
 * Gocator 2000/2300 C# Sample
 * Copyright (C) 2013 by LMI Technologies Inc.
 * 
 * Licensed under The MIT License.
 * Redistributions of files must retain the above copyright notice.
 *
 * Purpose: Connect to Gocator system and modify parameters
 *
 */

using System;
using System.Runtime.InteropServices;

static class Constants
{
    public const string SENSOR_IP = "192.168.1.10"; // IP of the sensor used for sensor connection GoSystem_FindSensorByIpAddress() call.
#if DEBUG
    public const string GODLLPATH = @"GoSdk.dll";
    public const string KAPIDLLPATH = @"kApi.dll";
#else
    public const string GODLLPATH = @"GoSdk.dll";
    public const string KAPIDLLPATH = @"kApi.dll";
#endif
}

namespace Configure
{
    class Configure
    {
        enum kStatus
        {
            kERROR_STATE = -1000,                                                // Invalid state.
            kERROR_NOT_FOUND = -999,                                             // Item is not found.
            kERROR_COMMAND = -998,                                               // Command not recognized.
            kERROR_PARAMETER = -997,                                             // Parameter is invalid.
            kERROR_UNIMPLEMENTED = -996,                                         // Feature not implemented.
            kERROR_HANDLE = -995,                                                // Handle is invalid.
            kERROR_MEMORY = -994,                                                // Out of memory.
            kERROR_TIMEOUT = -993,                                               // Action timed out.
            kERROR_INCOMPLETE = -992,                                            // Buffer not large enough for data.
            kERROR_STREAM = -991,                                                // Error in stream.
            kERROR_CLOSED = -990,                                                // Resource is no longer avaiable. 
            kERROR_VERSION = -989,                                               // Invalid version number.
            kERROR_ABORT = -988,                                                 // Operation aborted.
            kERROR_ALREADY_EXISTS = -987,                                        // Conflicts with existing item.
            kERROR_NETWORK = -986,                                               // Network setup/resource error.
            kERROR_HEAP = -985,                                                  // Heap error (leak/double-free).
            kERROR_FORMAT = -984,                                                // Data parsing/formatting error. 
            kERROR_READ_ONLY = -983,                                             // Object is read-only (cannot be written).
            kERROR_WRITE_ONLY = -982,                                            // Object is write-only (cannot be read). 
            kERROR_BUSY = -981,                                                  // Agent is busy (cannot service request).
            kERROR_CONFLICT = -980,                                              // State conflicts with another object.
            kERROR_OS = -979,                                                    // Generic error reported by underlying OS.
            kERROR_DEVICE = -978,                                                // Hardware device error.
            kERROR_FULL = -977,                                                  // Resource is already fully utilized.
            kERROR_IN_PROGRESS = -976,                                           // Operation is in progress, but not yet complete.
            kERROR = 0,                                                          // General error. 
            kOK = 1                                                              // Operation successful. 
        }

        enum GoRole
        {
            GO_ROLE_MAIN = 0,                                                    // Sensor is operating as a main sensor.
            GO_ROLE_BUDDY = 1                                                    // Sensor is operating as a buddy sensor.
        }

        public struct address
        {
            public Int32 version;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public byte[] IPaddress;
        }

        // use DLL import to access GoSdkd.dll/GoSdk.dll and kApid.dll/kApi.dll
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSdk_Construct(ref IntPtr assembly);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSystem_Construct(ref IntPtr system, IntPtr allocator);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSystem_FindSensorByIpAddress(IntPtr system, IntPtr addr, ref IntPtr sensor);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSystem_FindSensorById(IntPtr system, UInt32 id, ref IntPtr sensor);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSensor_Connect(IntPtr sensor);
        [DllImport(Constants.GODLLPATH)]
        private static extern IntPtr GoSensor_Setup(IntPtr sensor);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSensor_Flush(IntPtr sensor);
        [DllImport(Constants.GODLLPATH)]
        private static extern double GoSetup_Exposure(IntPtr setup, GoRole role);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSetup_SetExposure(IntPtr setup, GoRole role, double exposure);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSensor_CopyFile(IntPtr sensor, [MarshalAs(UnmanagedType.LPStr)] string sourceName, [MarshalAs(UnmanagedType.LPStr)] string destName);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoSensor_SetDefaultJob(IntPtr sensor, [MarshalAs(UnmanagedType.LPStr)] string fileName);
        [DllImport(Constants.GODLLPATH)]
        private static extern Int32 GoDestroy(IntPtr obj);
        [DllImport(Constants.KAPIDLLPATH)]
        private static extern Int32 kIpAddress_Parse(IntPtr addrPtr, [MarshalAs(UnmanagedType.LPStr)] string text);

        static int Main(string[] args)
        {
            kStatus status;
            IntPtr api = IntPtr.Zero;
            IntPtr system = IntPtr.Zero;
            IntPtr sensor = IntPtr.Zero;
            IntPtr setup = IntPtr.Zero;
            IntPtr addrPtr = IntPtr.Zero;
            address addr = new address();
            double currentExposure;
            double newExposure;
            IntPtr mainSensor = IntPtr.Zero;

            if ((status = (kStatus)GoSdk_Construct(ref api)) != kStatus.kOK)
            {
                Console.WriteLine("GoSdk_Construct Error:{0}", (int)status);
                return (int)status;
            }

            if ((status = (kStatus)GoSystem_Construct(ref system, IntPtr.Zero)) != kStatus.kOK)
            {
                Console.WriteLine("GoSystem_Construct Error:{0}", (int)status);
                return (int)status;
            }

            addrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(addr));
            Marshal.StructureToPtr(addr, addrPtr, false);
            
            if ((status = (kStatus)kIpAddress_Parse(addrPtr, Constants.SENSOR_IP)) != kStatus.kOK)
            {
                Console.WriteLine("kIpAddress_Parse Error:{0}", (int)status);
                return (int)status;
            }

            if ((status = (kStatus)GoSystem_FindSensorByIpAddress(system, addrPtr, ref sensor)) != kStatus.kOK)
            {
                Console.WriteLine("GoSystem_FindSensorByIpAddress Error:{0}", (int)status);
                return (int)status;
            }

            if ((status = (kStatus)GoSensor_Connect(sensor)) != kStatus.kOK)
            {
                Console.WriteLine("GoSensor_Connect Error:{0}", (int)status);
                return (int)status;
            }

            //retrieve setup handle
            setup = GoSensor_Setup(sensor);

            //read current parameters
            currentExposure = GoSetup_Exposure(setup, GoRole.GO_ROLE_MAIN);

            Console.WriteLine("Current Parameters:");
            Console.WriteLine("-------------------");
            Console.WriteLine("Exposure: {0}", currentExposure);

            //modify parameter in main sensor
            if ((status = (kStatus)GoSetup_SetExposure(setup, GoRole.GO_ROLE_MAIN, currentExposure + 200)) != kStatus.kOK)
            {
                Console.WriteLine("GoSetup_SetExposure Error:{0}", (int)status);
                return (int)status;
            }

            // GoSensorFlush() - immediately synchronizes configuration changes to the sensor
            // *The changes will be shown on the web browser GUI after the browser has been refreshed.
            // NOTE: Sensor is not automatically synchronized with every call to function that modifies a setting.
            // This allows for rapid configuring sensors without delay caused by synchronization after every call.
            // Generally functions that retreieve setting values causes automatic synchronization while functions that set values don't.
            // Synchronization is also always guranteed prior to sensor entering running state. The GoSensor_Flush() function
            // should only be used when configuration changes are needed to be seen immediately.
            if ((status = (kStatus)GoSensor_Flush(sensor)) != kStatus.kOK)
            {
                Console.WriteLine("GoSensor_Flush Error:{0}", (int)status);
                return (int)status;
            }

            newExposure = GoSetup_Exposure(setup, GoRole.GO_ROLE_MAIN);
            Console.WriteLine("New Parameters:");
            Console.WriteLine("-------------------");
            Console.WriteLine("Exposure: {0}", newExposure);

            // Save the configuration into a new file set. This is the same behavior
            // as if the user clicks the save button in the toolbar.
            if ((status = (kStatus)GoSensor_CopyFile(sensor, "_live.job", "newExposure.job")) != kStatus.kOK)
            {
                Console.WriteLine("GoSensor_CopyFile Error:{0}", (int)status);
                return (int)status;
            }

	        // Set the saved configuration as default file. This makes it the active configuration when the sensor powers up.
            if ((status = (kStatus)GoSensor_SetDefaultJob(sensor, "newExposure.job")) != kStatus.kOK)
            {
                Console.WriteLine("GoSensor_SetDefaultJob Error:{0}", (int)status);
                return (int)status;
            }


            //restore previous parameter setting
            if ((status = (kStatus)GoSetup_SetExposure(setup, GoRole.GO_ROLE_MAIN, currentExposure)) != kStatus.kOK)
            {
                Console.WriteLine("GoSetup_SetExposure Error:{0}", (int)status);
                return (int)status;
            }

            // destroy handles
            GoDestroy(system);
            GoDestroy(api);

            // wait for Enter key
            Console.WriteLine("\nPress ENTER to continue");
            do
            {
                System.Threading.Thread.Sleep(100);

            } while (Console.Read() != (int)ConsoleKey.Enter);
            return (int)kStatus.kOK;
        }
    }
}
