public void Run()
            {
                // Prints the version of the application and the CAS BACnet stack.
                Console.WriteLine("Starting Modbus RTU Master Example version {0}.{1}", APPLICATION_VERSION, CIBuildVersion.CIBUILDNUMBER);
                Console.WriteLine("https://github.com/chipkin/ModbusTCPMasterExampleCSharp");
                Console.WriteLine("FYI: CAS Modbus Stack version: {0}.{1}.{2}.{3}",
                                  CASModbusAdapter.GetAPIMajorVersion(),
                                  CASModbusAdapter.GetAPIMinorVersion(),
                                  CASModbusAdapter.GetAPIPatchVersion(),
                                  CASModbusAdapter.GetAPIBuildVersion());

                // Set up the API and callbacks.
                uint returnCode = CASModbusAdapter.Init(CASModbusAdapter.TYPE_RTU, SendMessage, RecvMessage, CurrentTime);

                if (returnCode != CASModbusAdapter.STATUS_SUCCESS)
                {
                    Console.WriteLine("Error: Could not init the Modbus Stack, returnCode={0}", returnCode);
                    return;
                }

                // All done with the Modbus setup.
                Console.WriteLine("FYI: CAS Modbus Stack Setup, successfuly");

                // Create a new SerialPort object with default settings.
                _serialPort = new SerialPort();

                // Allow the user to set the appropriate properties.
                _serialPort.PortName  = SetPortName(_serialPort.PortName);
                _serialPort.BaudRate  = SetPortBaudRate(_serialPort.BaudRate);
                _serialPort.Parity    = SetPortParity(_serialPort.Parity);
                _serialPort.DataBits  = SetPortDataBits(_serialPort.DataBits);
                _serialPort.StopBits  = SetPortStopBits(_serialPort.StopBits);
                _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

                // Set the read/write timeouts
                _serialPort.ReadTimeout  = 10;
                _serialPort.WriteTimeout = 10;

                _serialPort.Open();

                // Program loop.
                while (true)
                {
                    // Check for user input
                    this.DoUserInput();

                    // Run the Modbus loop proccessing incoming messages.
                    CASModbusAdapter.Loop();

                    // Give some time to other applications.
                    System.Threading.Thread.Sleep(1);
                }
            }
            public void ReadExample()
            {
                Console.WriteLine("FYI: ReadExample");

                // Create the connection
                IPAddress iPAddress = new IPAddress(SETTING_MODBUS_SERVER_TCP_IP);

                this.tcpClient = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                // Attempt to connect to the Modbus slave.
                this.tcpClient.Connect(new IPEndPoint(iPAddress, SETTING_MODBUS_SERVER_TCP_PORT));
                // We are connected.
                Console.WriteLine("FYI: Connected to IP address=[{0}]", this.tcpClient.RemoteEndPoint.ToString());

                System.UInt16[] data = new System.UInt16[SETTING_MODBUS_CLIENT_LENGTH];
                System.Byte     exceptionCode;
                unsafe
                {
                    // Set some unmanaged memory up.
                    IntPtr unmanagedPointer = Marshal.AllocHGlobal(SETTING_MODBUS_CLIENT_LENGTH);

                    // Send the message
                    Console.WriteLine("FYI: Sending ReadRegisters message");
                    uint resultReadRegisters = CASModbusAdapter.ReadRegisters(1, SETTING_MODBUS_CLIENT_DEVICE_ID, CASModbusAdapter.FUNCTION_03_READ_HOLDING_REGISTERS, SETTING_MODBUS_CLIENT_ADDRESS, SETTING_MODBUS_CLIENT_LENGTH, unmanagedPointer, (ushort)(data.Length * sizeof(System.UInt16)), &exceptionCode);

                    // 1 success
                    if (resultReadRegisters == CASModbusAdapter.STATUS_SUCCESS)
                    {
                        // Extract the data from the unmannged memory into a managed buffer.
                        CopyBytesIntoPointer(unmanagedPointer, data, 0, SETTING_MODBUS_CLIENT_LENGTH);
                        Marshal.FreeHGlobal(unmanagedPointer);
                        this.tcpClient.Close();

                        // Print the data to the screen.
                        Console.Write("FYI: Data: ");
                        foreach (System.UInt16 value in data)
                        {
                            Console.Write(value);
                            Console.Write(", ");
                        }
                        Console.WriteLine("");
                    }
                    else if (resultReadRegisters == CASModbusAdapter.STATUS_ERROR_MODBUS_EXCEPTION)
                    {
                        Console.WriteLine("Modbus.Exception={0}", exceptionCode);
                    }
                    else
                    {
                        Console.WriteLine("ModbusStack.Error={0}", resultReadRegisters);
                    }
                }
            }
            public void PrintHelp()
            {
                Console.WriteLine("FYI: Modbus Stack version: {0}.{1}.{2}.{3}",
                                  CASModbusAdapter.GetAPIMajorVersion(),
                                  CASModbusAdapter.GetAPIMinorVersion(),
                                  CASModbusAdapter.GetAPIPatchVersion(),
                                  CASModbusAdapter.GetAPIBuildVersion());

                Console.WriteLine("Help:");
                Console.WriteLine(" Q          - Quit");
                Console.WriteLine(" UP Arror   - Increase 40,001 by 1 ");
                Console.WriteLine(" Down Arror - Decrease 40,001 by 1 ");
                Console.WriteLine("\n");
            }
            public void PrintHelp()
            {
                Console.WriteLine("FYI: Modbus Stack version: {0}.{1}.{2}.{3}",
                                  CASModbusAdapter.GetAPIMajorVersion(),
                                  CASModbusAdapter.GetAPIMinorVersion(),
                                  CASModbusAdapter.GetAPIPatchVersion(),
                                  CASModbusAdapter.GetAPIBuildVersion());

                Console.WriteLine("Help:");
                Console.WriteLine("   q   - Quit");
                Console.WriteLine("   w   - Write values to a Modbus Slave.");
                Console.WriteLine("   r   - Read values from a Modbus Slave.");
                Console.WriteLine("\n");
            }
            public void PrintHelp()
            {
                Console.WriteLine("FYI: Modbus Stack version: {0}.{1}.{2}.{3}",
                                  CASModbusAdapter.GetAPIMajorVersion(),
                                  CASModbusAdapter.GetAPIMinorVersion(),
                                  CASModbusAdapter.GetAPIPatchVersion(),
                                  CASModbusAdapter.GetAPIBuildVersion());

                Console.WriteLine("Help:");
                Console.WriteLine(" Q - Quit");
                Console.WriteLine(" R - Read {0}, fnk={1}, add={2}, count={3}", 40001 + SETTING_MODBUS_CLIENT_OFFSET, CASModbusAdapter.FUNCTION_03_READ_HOLDING_REGISTERS, SETTING_MODBUS_CLIENT_DEVICE_ID, SETTING_MODBUS_CLIENT_LENGTH);
                Console.WriteLine(" W - Write {0}, fnk={1}, add={2}, count={3}", 40001 + SETTING_MODBUS_CLIENT_OFFSET, CASModbusAdapter.FUNCTION_10_FORCE_MULTIPLE_REGISTERS, SETTING_MODBUS_CLIENT_DEVICE_ID, SETTING_MODBUS_CLIENT_LENGTH);
                Console.WriteLine("\n");
            }
            public void WriteExample()
            {
                Console.WriteLine("FYI: WriteExample");

                // Create the connection
                IPAddress iPAddress = new IPAddress(SETTING_MODBUS_SERVER_TCP_IP);

                this.tcpClient = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                // Attempt to connect to the Modbus slave.
                this.tcpClient.Connect(new IPEndPoint(iPAddress, SETTING_MODBUS_SERVER_TCP_PORT));
                // We are connected.
                Console.WriteLine("FYI: Connected to IP address=[{0}]", this.tcpClient.RemoteEndPoint.ToString());

                System.UInt16[] data = new System.UInt16[SETTING_MODBUS_CLIENT_LENGTH];
                data[0] = 99;
                data[1] = 150;
                data[2] = 306;

                System.Byte exceptionCode;
                unsafe
                {
                    // Set some unmanaged memory up.
                    IntPtr unmanagedPointer = Marshal.AllocHGlobal(SETTING_MODBUS_CLIENT_LENGTH);
                    CopyBytesIntoPointer(data, unmanagedPointer);


                    // Send the message
                    Console.WriteLine("FYI: Sending WriteRegisters message");
                    uint resultWriteRegisters = CASModbusAdapter.WriteRegisters(1, SETTING_MODBUS_CLIENT_DEVICE_ID, CASModbusAdapter.FUNCTION_10_FORCE_MULTIPLE_REGISTERS, SETTING_MODBUS_CLIENT_ADDRESS, unmanagedPointer, (ushort)(data.Length * sizeof(System.UInt16)), &exceptionCode);
                    Marshal.FreeHGlobal(unmanagedPointer);
                    this.tcpClient.Close();

                    // Print the results.
                    if (resultWriteRegisters == CASModbusAdapter.STATUS_SUCCESS)
                    {
                        Console.WriteLine("Write was successful.");
                    }
                    else if (resultWriteRegisters == CASModbusAdapter.STATUS_ERROR_MODBUS_EXCEPTION)
                    {
                        Console.WriteLine("Modbus.Exception={0}", exceptionCode);
                    }
                    else
                    {
                        Console.WriteLine("ModbusStack.Error={0}", resultWriteRegisters);
                    }
                }
            }
            public void ReadExample()
            {
                Console.WriteLine("FYI: ReadExample");

                System.UInt16[] data = new System.UInt16[SETTING_MODBUS_CLIENT_LENGTH];
                System.Byte     exceptionCode;
                unsafe
                {
                    // Set some unmanaged memory up.
                    IntPtr unmanagedPointer = Marshal.AllocHGlobal(SETTING_MODBUS_CLIENT_LENGTH);

                    // Send the message
                    Console.WriteLine("FYI: Sending ReadRegisters message");
                    uint resultReadRegisters = CASModbusAdapter.ReadRegisters(1, SETTING_MODBUS_CLIENT_DEVICE_ID, CASModbusAdapter.FUNCTION_03_READ_HOLDING_REGISTERS, SETTING_MODBUS_CLIENT_ADDRESS, SETTING_MODBUS_CLIENT_LENGTH, unmanagedPointer, (ushort)(data.Length * sizeof(System.UInt16)), &exceptionCode);

                    // 1 success
                    if (resultReadRegisters == CASModbusAdapter.STATUS_SUCCESS)
                    {
                        // Extract the data from the unmannged memory into a managed buffer.
                        CopyBytesIntoPointer(unmanagedPointer, data, 0, SETTING_MODBUS_CLIENT_LENGTH);
                        Marshal.FreeHGlobal(unmanagedPointer);

                        // Print the data to the screen.
                        Console.Write("FYI: Data: ");
                        foreach (System.UInt16 value in data)
                        {
                            Console.Write(value);
                            Console.Write(", ");
                        }
                        Console.WriteLine("");
                    }
                    else if (resultReadRegisters == CASModbusAdapter.STATUS_ERROR_MODBUS_EXCEPTION)
                    {
                        Console.WriteLine("Modbus.Exception={0}", exceptionCode);
                    }
                    else
                    {
                        Console.WriteLine("ModbusStack.Error={0}", resultReadRegisters);
                    }
                }
            }
            public void WriteExample()
            {
                Console.WriteLine("FYI: WriteExample");


                System.UInt16[] data = new System.UInt16[SETTING_MODBUS_CLIENT_LENGTH];
                data[0] = 99;
                data[1] = 150;
                data[2] = 306;

                System.Byte exceptionCode;
                unsafe
                {
                    // Set some unmanaged memory up.
                    IntPtr unmanagedPointer = Marshal.AllocHGlobal(SETTING_MODBUS_CLIENT_LENGTH);
                    CopyBytesIntoPointer(data, unmanagedPointer);

                    // Send the message
                    Console.WriteLine("FYI: Sending WriteRegisters message");
                    uint resultWriteRegisters = CASModbusAdapter.WriteRegisters(1, SETTING_MODBUS_CLIENT_DEVICE_ID, CASModbusAdapter.FUNCTION_10_FORCE_MULTIPLE_REGISTERS, SETTING_MODBUS_CLIENT_ADDRESS, unmanagedPointer, (ushort)(data.Length * sizeof(System.UInt16)), &exceptionCode);
                    Marshal.FreeHGlobal(unmanagedPointer);

                    // Print the results.
                    if (resultWriteRegisters == CASModbusAdapter.STATUS_SUCCESS)
                    {
                        Console.WriteLine("Write was successful.");
                    }
                    else if (resultWriteRegisters == CASModbusAdapter.STATUS_ERROR_MODBUS_EXCEPTION)
                    {
                        Console.WriteLine("Modbus.Exception={0}", exceptionCode);
                    }
                    else
                    {
                        Console.WriteLine("ModbusStack.Error={0}", resultWriteRegisters);
                    }
                }
            }
            public void Run()
            {
                // Prints the version of the application and the CAS BACnet stack.
                Console.WriteLine("Starting Modbus TCP Slave Example  version {0}.{1}", APPLICATION_VERSION, CIBuildVersion.CIBUILDNUMBER);
                Console.WriteLine("https://github.com/chipkin/ModbusTCPMasterExampleCSharp");
                Console.WriteLine("FYI: CAS Modbus Stack version: {0}.{1}.{2}.{3}",
                                  CASModbusAdapter.GetAPIMajorVersion(),
                                  CASModbusAdapter.GetAPIMinorVersion(),
                                  CASModbusAdapter.GetAPIPatchVersion(),
                                  CASModbusAdapter.GetAPIBuildVersion());

                // Set up the API and callbacks.
                uint returnCode = CASModbusAdapter.Init(CASModbusAdapter.TYPE_TCP, SendMessage, RecvMessage, CurrentTime);

                if (returnCode != CASModbusAdapter.STATUS_SUCCESS)
                {
                    Console.WriteLine("Error: Could not init the Modbus Stack, returnCode={0}", returnCode);
                    return;
                }

                // Set the modbus slave address. For Modbus TCP 0 and 255 are the only valid slave address.
                CASModbusAdapter.SetSlaveId(ModbusSlave.SETTING_MODBUS_SERVER_SLAVE_ADDRESS);

                // Set up the call back functions for data.
                CASModbusAdapter.RegisterGetValue(GetModbusValue);
                CASModbusAdapter.RegisterSetValue(SetModbusValue);

                // All done with the Modbus setup.
                Console.WriteLine("FYI: CAS Modbus Stack Setup, successfuly");

                // Create the database and fill it with default data
                this.database = new UInt16[SETTING_MODBUS_DATABASE_MAX_SIZE];
                for (UInt16 offset = 0; offset < SETTING_MODBUS_DATABASE_MAX_SIZE; offset++)
                {
                    this.database[offset] = SETTING_MODBUS_DATABASE_DEFAULT_VALUE;
                }

                // Configure the TCP Listen class.
                // https://docs.microsoft.com/en-us/dotnet/framework/network-programming/synchronous-server-socket-example
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, SETTING_MODBUS_SERVER_TCP_PORT);

                this.tcpListener = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                // Bind the socket to the local endpoint and
                // listen for incoming connections.
                try
                {
                    Console.WriteLine("FYI: Binding tcp port. port=[{0}]...", SETTING_MODBUS_SERVER_TCP_PORT);
                    this.tcpListener.Bind(localEndPoint);
                    this.tcpListener.Listen(1);
                    Console.WriteLine("FYI: Waiting on TCP connection TCP port=[{0}]...", SETTING_MODBUS_SERVER_TCP_PORT);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }

                // Program loop.
                while (true)
                {
                    try
                    {
                        // Program is suspended while waiting for an incoming connection.
                        this.tcpClient = this.tcpListener.Accept();
                        Console.WriteLine("FYI: Got a connection from IP address=[{0}]", this.tcpClient.RemoteEndPoint.ToString());

                        // Do loop
                        while (IsSocketConnected(this.tcpClient))
                        {
                            // Check for user input
                            this.DoUserInput();

                            // Run the Modbus loop proccessing incoming messages.
                            CASModbusAdapter.Loop();

                            // Finally flush the buffer
                            CASModbusAdapter.Flush();

                            // Give some time to other applications.
                            System.Threading.Thread.Sleep(1);
                        } // Client connected loop.
                        Console.WriteLine("FYI: TCP Connection disconnected");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                } // Main program loop
            }
            public void Run()
            {
                // Prints the version of the application and the CAS BACnet stack.
                Console.WriteLine("Starting Modbus RTU Slave Example  version {0}.{1}", APPLICATION_VERSION, CIBuildVersion.CIBUILDNUMBER);
                Console.WriteLine("https://github.com/chipkin/ModbusTCPMasterExampleCSharp");
                Console.WriteLine("FYI: CAS Modbus Stack version: {0}.{1}.{2}.{3}",
                                  CASModbusAdapter.GetAPIMajorVersion(),
                                  CASModbusAdapter.GetAPIMinorVersion(),
                                  CASModbusAdapter.GetAPIPatchVersion(),
                                  CASModbusAdapter.GetAPIBuildVersion());

                // Set up the API and callbacks.
                uint returnCode = CASModbusAdapter.Init(CASModbusAdapter.TYPE_RTU, SendMessage, RecvMessage, CurrentTime);

                if (returnCode != CASModbusAdapter.STATUS_SUCCESS)
                {
                    Console.WriteLine("Error: Could not init the Modbus Stack, returnCode={0}", returnCode);
                    return;
                }

                // Set the modbus slave address. For Modbus TCP 0 and 255 are the only valid slave address.
                CASModbusAdapter.SetSlaveId(ModbusSlave.SETTING_MODBUS_SERVER_SLAVE_ADDRESS);

                // Set up the call back functions for data.
                CASModbusAdapter.RegisterGetValue(GetModbusValue);
                CASModbusAdapter.RegisterSetValue(SetModbusValue);


                // All done with the Modbus setup.
                Console.WriteLine("FYI: CAS Modbus Stack Setup, successfuly");

                // Create the database and fill it with default data
                this.database = new UInt16[SETTING_MODBUS_DATABASE_MAX_SIZE];
                for (UInt16 offset = 0; offset < SETTING_MODBUS_DATABASE_MAX_SIZE; offset++)
                {
                    this.database[offset] = SETTING_MODBUS_DATABASE_DEFAULT_VALUE;
                }

                // Connect and set up the serial ports

                // Create a new SerialPort object with default settings.
                _serialPort = new SerialPort();

                // Allow the user to set the appropriate properties.
                _serialPort.PortName  = SetPortName(_serialPort.PortName);
                _serialPort.BaudRate  = SetPortBaudRate(_serialPort.BaudRate);
                _serialPort.Parity    = SetPortParity(_serialPort.Parity);
                _serialPort.DataBits  = SetPortDataBits(_serialPort.DataBits);
                _serialPort.StopBits  = SetPortStopBits(_serialPort.StopBits);
                _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

                // Set the read/write timeouts
                _serialPort.ReadTimeout  = 10;
                _serialPort.WriteTimeout = 10;

                _serialPort.Open();

                // Program loop.
                while (true)
                {
                    // Check for user input
                    this.DoUserInput();

                    // Run the Modbus loop proccessing incoming messages.
                    CASModbusAdapter.Loop();

                    // Give some time to other applications.
                    System.Threading.Thread.Sleep(1);
                }
            }
            public void Run()
            {
                // Prints the version of the application and the CAS BACnet stack.
                Console.WriteLine("Starting Modbus TCP Master Example  version {0}.{1}", APPLICATION_VERSION, CIBuildVersion.CIBUILDNUMBER);
                Console.WriteLine("https://github.com/chipkin/ModbusTCPMasterExampleCSharp");
                Console.WriteLine("FYI: CAS Modbus Stack version: {0}.{1}.{2}.{3}",
                                  CASModbusAdapter.GetAPIMajorVersion(),
                                  CASModbusAdapter.GetAPIMinorVersion(),
                                  CASModbusAdapter.GetAPIPatchVersion(),
                                  CASModbusAdapter.GetAPIBuildVersion());


                // Set up the API and callbacks.
                uint returnCode = CASModbusAdapter.Init(CASModbusAdapter.TYPE_TCP, SendMessage, RecvMessage, CurrentTime);

                if (returnCode != CASModbusAdapter.STATUS_SUCCESS)
                {
                    Console.WriteLine("Error: Could not init the Modbus Stack, returnCode={0}", returnCode);
                    return;
                }

                // All done with the Modbus setup.
                Console.WriteLine("FYI: CAS Modbus Stack Setup, successfuly");


                // Configure the TCP Listen class.
                // https://docs.microsoft.com/en-us/dotnet/framework/network-programming/synchronous-server-socket-example
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, SETTING_MODBUS_SERVER_TCP_PORT);

                this.tcpListener = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                // Program loop.
                while (true)
                {
                    try
                    {
                        // Check for user input
                        DoUserInput();

                        // Run the Modbus loop proccessing incoming messages.
                        CASModbusAdapter.Loop();

                        // Give some time to other applications.
                        System.Threading.Thread.Sleep(1);

                        // If we are connected to a Modbus Slave device. proccess incoming message.
                        if (this.tcpClient != null && this.tcpClient.Connected)
                        {
                            // Finally flush the buffer
                            CASModbusAdapter.Flush();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        if (this.tcpClient != null && this.tcpClient.Connected)
                        {
                            this.tcpClient.Disconnect(true);
                        }
                    }
                } // Main program loop
            }