using Modbus.Device; // NModbus namespace
using System.Net.Sockets;

internal class Program
{
    // Configuration
    private const string hostname = "127.0.0.1"; // Replace with your Watlow F4 IP

    private const int port = 502;
    private const byte slaveId = 0;

    // Register 100 should be the first read-only input on the F4
    // Value 99 or 100 should work depending on zero indexing
    private const ushort loadRegister = 99;

    private static void Main(string[] args)
    {
        TcpClient tcpClient = null;
        ModbusIpMaster master = null;

        try
        {
            // Initialize connection
            tcpClient = new TcpClient(hostname, port);
            master = ModbusIpMaster.CreateIp(tcpClient);

            // Monitor continuously
            while (true)
            {
                // Check for Escape key press
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.Escape)
                    {
                        Console.WriteLine("Escape pressed. Exiting...");
                        break;
                    }
                }

                try
                {
                    // Read load value (holding register)
                    ushort[] registers = master.ReadHoldingRegisters(slaveId, loadRegister, 1);
                    int load = registers[0];

                    // Display load info
                    DisplayLoadInfo(load);

                    // Pause before next read
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Initialization error: {ex.Message}");
        }
        finally
        {
            // Clean up
            master?.Dispose();
            tcpClient?.Close();
        }
    }

    private static void DisplayLoadInfo(int load)
    {
        Console.Clear(); // Clears the console

        // Assume load is 0-65535 for 0.00-100.00% (16-bit range)
        int percent = (int)load / 65535 * 100;
        int barLength = (int)(percent / 2); // Scale to 50 chars for console

        Console.WriteLine($"Load Value: {load}");
        Console.WriteLine($"Load Percentage: {percent:F2}%");
        Console.Write("Bar Graph: [");
        Console.Write(new string('=', barLength));
        Console.Write(new string(' ', 50 - barLength));
        Console.WriteLine("]");
        Console.WriteLine("\nHold ESC to exit.");
    }
}