using S7.Net;
using System;

namespace SSWMS.Server
{
    public class S7Net
    {
        private const int count1 = 1;
        private static Plc plc1 = null;
        private static byte[] bytesRead1 = new byte[count1];

        public static void Read()
        {
            if (plc1 == null || !plc1.IsConnected)
            {
                if (plc1 == null)
                {
                    plc1 = new Plc(CpuType.S71500, "192.168.0.1", 0, 1);
                }
                plc1.Open();
            }
            byte[] bytes1 = plc1.ReadBytes(DataType.DataBlock, 1, 0, count1);
            //byte[] bytesA = new byte[count1];
            //Array.Copy(bytes1, 0, bytesA, 0, count1);
            Array.Copy(bytes1, bytesRead1, count1);
        }

        public static void Close()
        {
            if (plc1 != null)
            {
                if (plc1.IsConnected)
                {
                    plc1.Close();
                }
                plc1 = null;
            }
        }

        public static bool Write1(int startByteAdr, byte[] value, out string sResult)
        {
            sResult = string.Empty;
            if (plc1 == null || !plc1.IsConnected)
            {
                sResult = "未连接PLC";
                return false;
            }
            ErrorCode errorCode = plc1.WriteBytes(DataType.DataBlock, 1, startByteAdr, value);
            sResult = $"错误代码 {errorCode}";
            return errorCode == ErrorCode.NoError;
        }
    }
}