//*****************************************************************************
//
// File name: CclinkSlave.cs
// Location: See Matrox Example Launcher in the MIL Control Center
// 
//
// Synopsis:  This program allocates a MIL application and system.
//            Then allocate a MIL industrial communication context to a
//            CC-Link IE Field Basic slave instance.
//
// Notes:     This example is only available if you have the MIL Industrial Communication package,
//            or another relevant update installed.
// Copyright (C) Matrox Electronic Systems Ltd., 1992-2020.
// All Rights Reserved
//*****************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Matrox.MatroxImagingLibrary;

namespace McomCclinkSlave
{
    class CclinkSlave
    {
        private MIL_ID _milIdCom = 0;

        public CclinkSlave(MIL_ID milID)
        {
            _milIdCom = milID;
        }
        public bool IsSlaveStopped
        {
            get
            {
                bool state = false;

                MIL.McomInquire(ComId: _milIdCom, InquireType: MIL.M_COM_GET_CONNECTION_STATE, UserVarPtr: ref state);

                return !state;
            }
        }

        public void WriteRegister(MIL_INT deviceNumber, ushort value)
        {
            /* Write in the input register (RWr) as specified in PLC configuration */
            MIL.McomWrite(ComId: _milIdCom, DataObjectEntryName: "RWr", Offset: deviceNumber, Size: 1, UserArrayPtr: BitConverter.GetBytes(value));
        }

        public ushort ReadRegister(MIL_INT deviceNumber)
        {
            byte[] result = { 0, 0 };

            /* Read in the output register (RWw) as specified in PLC configuration */
            MIL.McomRead(ComId: _milIdCom, DataObjectEntryName: "RWw", Offset: deviceNumber, Size: 1, UserArrayPtr: result);
            return BitConverter.ToUInt16(result, 0);
        }

        public void SetFlag(MIL_INT deviceNumber)
        {
            WriteFlag(deviceNumber, state: true);
        }

        public void ClearFlag(MIL_INT deviceNumber)
        {
            WriteFlag(deviceNumber, state: false);
        }

        public void WriteFlag(MIL_INT deviceNumber, bool state)
        {
            /* Write in the input flag (RX) as specified in PLC configuration */
            MIL.McomWrite(ComId: _milIdCom, DataObjectEntryName: "RX", Offset: deviceNumber, Size: 1, UserArrayPtr: BitConverter.GetBytes(state));
        }

        public bool ReadFlag(MIL_INT deviceNumber)
        {
            byte[] status = { 0 };
            /* Read in the output flag (RY) as specified in PLC configuration */
            MIL.McomRead(ComId: _milIdCom, DataObjectEntryName: "RY", Offset: deviceNumber, Size: 1, UserArrayPtr: status);
            return BitConverter.ToBoolean(status, 0);
        }

    }
}