using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

using Acroname.BrainStem2CLI;

namespace BrainStemCLI_MTMLoad_CC
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Creating a MTMLoad1 module");

            // Create an instance of the MTMLoad1 module
            MTMLoad1 stem = new MTMLoad1();
            aErr err = aErr.aErrNone;

            // Connect to the hardware.
            // The only difference for TCP/IP modules is to change "USB" to "TCP";
            // err = stem.discoverAndConnect(USB, 0x40F5849A); // for a known serial number
            err = stem.module.discoverAndConnect(m_linkType.USB, 0);
            if (err != aErr.aErrNone)
            {
                Console.WriteLine("Error \"{0}\" encountered while trying to connect to BrainStem Module", err);
                Thread.Sleep(5000); //Sleep for 1 second.
                System.Environment.Exit(1);

            }
            else
            {
                UInt32 sn = 0;
                err = stem.system.getSerialNumber(ref sn);
                Console.WriteLine("Connected to BrainStem module. SN: {0:X}. Error: {1}", sn, err);
            }

            //Operational modes are defined in aProtocoldefs.h (development/lib/BrainStem2/)
            //Device specific configurations/capabilities can be found in the product datasheet.
            //0x01 = (railOperationalModeConstantCurrent(0x00) | railOperationalModeLinear(0x01))
            stem.rail[0].setOperationalMode(0x00 | 0x01);

            Console.WriteLine("Setting load rail 0 to draw 0.1A");
            stem.rail[0].setCurrentSetpoint(100000);  //Current is in microamps

            Console.WriteLine("Setting load rail 0 max voltage to 5.0V");
            stem.rail[0].setVoltageMaxLimit(5000000);

            Console.WriteLine("Enabling load rail 0");
            stem.rail[0].setEnable(1);

            Console.WriteLine("Allowing time for the rail to stabilize");
            Thread.Sleep(1000); //Sleep for 1 second.

            Int32 voltage = 0;
            err = stem.rail[0].getVoltage(ref voltage);
            Console.WriteLine("Voltage: {0} microvolts, Error: {1}", voltage, err);

            Int32 current = 0;
            err = stem.rail[0].getCurrent( ref current);
            Console.WriteLine("Current: {0} microamps, Error: {1}", current, err);

            Console.WriteLine("Disabling load rail 0");
            stem.rail[0].setEnable(0);

            // Disconnect
            err = stem.module.disconnect();
            if (err == aErr.aErrNone)
            {
                Console.WriteLine("Disconnected from BrainStem module.");
            }

        }
    }
}
