using System;
using Sensirion.SHDLC;
using Sensirion.SHDLC.SFC5xxx;

namespace SFC5xxxDemoCLI
{
  class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      // define local variables
      ShdlcConnection connection = null;
      SFC5xxxDevice device = null;

      // print out header
      Console.WriteLine("SFC5xxx Demo CLI");
      Console.WriteLine("================");
      Console.WriteLine("Please connect the SFC5xxx device and enter the connection parameters.");
      Console.WriteLine("Just press [Enter] to use the values in brackets." + Environment.NewLine);

      // read COM-port
      Console.Write("COM-Port [COM1]: ");
      string port = Console.ReadLine().ToUpper().Trim();
      if (string.IsNullOrEmpty(port)) port = "COM1"; // use default value
      if (!port.StartsWith("COM")) port = "COM" + port;

      // read baudrate
      Console.Write("Baudrate [115200]: ");
      string baudrate = Console.ReadLine().Trim();
      if (string.IsNullOrEmpty(baudrate)) baudrate = "115200"; // use default value

      // read device address
      Console.Write("Device Address [0]: ");
      string address = Console.ReadLine().Trim();
      if (string.IsNullOrEmpty(address)) address = "0"; // use default value

      try
      {
        // create connection string
        string conStr = port + ", " + int.Parse(baudrate) + ", " + "ECHOOFF";

        // connect to device
        connection = new ShdlcConnection();
        connection.OpenPort(PortType.Serial, conStr);
        device = new SFC5xxxDevice(connection, int.Parse(address));

        // print out connection parameters
        Console.WriteLine(Environment.NewLine + "Connected successfully to device '" + device.ProductName
                          + "' on port '" + port + "' at address '" + address + "'.");
        Console.WriteLine("Press [Enter] to read the measured flow. To set a new setpoint is optional.");
        Console.WriteLine("Enter any character as setpoint to abort." + Environment.NewLine);

        // set setpoint and read measured flow in a loop
        float inputSetpoint = 0.0f;
        float currentSetpoint = device.GetSetpoint(DataScaling.Normalized); // normalized (0..1)
        while (true)
        {
          // set new setpoint and read measured flow
          float flow = device.SetSetpointAndReadMeasuredValue(currentSetpoint, DataScaling.Normalized);
          Console.Write("Measured flow: " + string.Format("{0,6:##0.00}", flow * 100.0f) + "%\t\t");
          Console.Write("Set Setpoint [" + string.Format("{0,6:##0.00}", currentSetpoint * 100.0f) + "%]: ");

          // read next setpoint or abort loop
          string input = Console.ReadLine().Replace("%", "").Trim();
          if (float.TryParse(input, out inputSetpoint))
            currentSetpoint = inputSetpoint / 100.0f; // normalize the setpoint to 0..1
          else if (!string.IsNullOrEmpty(input))
            break; // abort loop
        }
      }
      catch (Exception ex)
      {
        // print out exception message
        Console.WriteLine(Environment.NewLine + "Error: " + ex.Message);
      }

      // try to close the port if it is still open
      if (connection != null)
      {
        try 
        {
          connection.ClosePort();
        }
        catch { }
      }

      // wait for the enter key to exit the application
      Console.WriteLine("\nPress [Enter] to exit the program.");
      Console.ReadLine();
    }
  }
}
