using Modbus.Device;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ModbusMKSDemo
{
    class Program
    {
        public static float DecodeFloat(ushort[] input)
        {
            return DecodeFloat(input[1], input[0]);
        }

        public static float DecodeFloat(ushort first, ushort second)
        {
            var a = BitConverter.GetBytes(first);
            var b = BitConverter.GetBytes(second);

            byte[] f = new byte[4];
            Buffer.BlockCopy(a, 0, f, 0, 2);
            Buffer.BlockCopy(b, 0, f, 2, 2);

            return BitConverter.ToSingle(f, 0);
        }

        public static void ModbusTcpMasterReadInputsFromModbusSlave()
        {
            int port = 502;
            IPAddress address = new IPAddress(new byte[] { 192, 168, 0, 199 });

            // create the master
            TcpClient masterTcpClient = new TcpClient(address.ToString(), port);
            ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTcpClient);

            ushort numInputs = 2;
            ushort startAddress = 0x4000;

            // read five register values
            
            for (int i = 0; i < 100; ++i)
            {
                ushort[] inputs = master.ReadInputRegisters(startAddress, numInputs);
                Console.WriteLine("{1}: Flow: {0}", DecodeFloat(inputs), i);
                Thread.Sleep(1000);
            }
            
            // clean up
            masterTcpClient.Close();

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }

        static void Main(string[] args)
        {
            ModbusTcpMasterReadInputsFromModbusSlave();
        }
    }
}
