/**
 * @file tcpsimple.cs
 *
 * A simple console based example using FieldTalk in Modbus/TCP
 * master mode
 *
 * @if NOTICE
 *
 * Copyright (c) proconX Pty Ltd. All rights reserved.
 *
 * THIS IS PROPRIETARY SOFTWARE AND YOU NEED A LICENSE TO USE OR REDISTRIBUTE.
 *
 * THIS SOFTWARE IS PROVIDED BY PROCONX AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PROCONX OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @endif
 */


using System;
using System.Threading;
using FieldTalk.Modbus.Master;


/**
 * A simple console based example using FieldTalk in Modbus/TCP
 * master mode
 */
class TcpSimpleApp
{

    MbusTcpMasterProtocol mbusProtocol = new MbusTcpMasterProtocol();


    /**
     * Opens protocol
     */
    void openProtocol()
    {
        int result;

        result = mbusProtocol.openProtocol("127.0.0.1");
        if (result != BusProtocolErrors.FTALK_SUCCESS)
        {
            Console.WriteLine("Error opening protocol: " + BusProtocolErrors.getBusProtocolErrorText(result));
            Environment.Exit(result);
        }
    }


    /**
     * Closes protocol
     */
    void closeProtocol()
    {
        mbusProtocol.closeProtocol();
    }


    /**
     * Cyclic loop which polls every one second 10 registers starting at
     * reference 100 from slave # 1
     */
    void runPollLoop()
    {
        Int16[] dataArr = new Int16[10];

        for (;;)
        {
            int result;

            result = mbusProtocol.readMultipleRegisters(1, 100, dataArr);
            if (result == BusProtocolErrors.FTALK_SUCCESS)
            {
                  for (int i = 0; i < dataArr.Length; i++)
                     Console.WriteLine("[" + (100 + i) + "]: " + dataArr[i]);
            }
            else
            {
                Console.WriteLine(BusProtocolErrors.getBusProtocolErrorText(result) + "!");
                // Stop for fatal errors
                if ((result & BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS) != BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS)
                    return;
            }
            Thread.Sleep(1000);
        }
    }


    /**
     * Main function.
     */
    public static void Main()
    {
        TcpSimpleApp app = new TcpSimpleApp();

        app.openProtocol();
        app.runPollLoop();
        app.closeProtocol();
    }
}

