当前位置: 首页 > article >正文

上位机通讯汇川Plc3U和5U

开发过程中需要调用到汇川官网的两个动态库(ModbusTcpAPI.dll;StandardModbusApi.dll)

解压完成后找到上面的动态库复制到自己项目的根目录下面然后就可以进行下一步操作了

UI界面:

通讯类集成了3U和5U的连接断开以及读写方法:

public class InovancePlc : PLCBase
{
    private InovancePlc _HuiChuan5U;
    #region //标准库
    [DllImport("StandardModbusApi.dll", EntryPoint = "Init_ETH_String", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool Init_ETH_String(string sIpAddr, int nNetId = 0, int IpPort = 502);

    [DllImport("StandardModbusApi.dll", EntryPoint = "Exit_ETH", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool Exit_ETH(int nNetId = 0);

    [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
    public static extern int H5u_Write_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);

    [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
    public static extern int H5u_Read_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);

    [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Device_Block", CallingConvention = CallingConvention.Cdecl)]
    public static extern int H5u_Read_Device_Block(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);

    [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Device_Block", CallingConvention = CallingConvention.Cdecl)]
    public static extern int H5u_Write_Device_Block(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);


    [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Read_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
    public static extern int H3u_Read_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);

    [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Write_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
    public static extern int H3u_Write_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);

    #endregion

    int[] Result = new int[1];
    int nNetId = 1;
    private MyModbusSlave.ErrorMsgEventHandler _ErrorMsgEventHandler;
    public InovancePlc()
        : base()
    {
        if (ECom.Plc5Utype)
        {
            this.PLCVender = PLCType.HuiChuan5U;
        }

        if (ECom.Plc3Utype)
        {
            this.PLCVender = PLCType.HuiChuan3U;
        }
        
    }
    /// <summary>
    /// 连接PLC
    /// </summary>
    /// <returns></returns>
    public override bool Connect()
    {
        try
        {
            if (ECom.Plc5Utype)
            {
                return CreateConnection();
            }
            
            if(ECom.Plc3Utype)
            {
                return CreateConnection1();
            }
            return false;
        }
        catch (Exception ex)
        {
            this.OnTcpClientErrorMsgEnterHead("错误信息:" + ex.Message);
            AddLog.Error("错误信息:" + ex.Message);
            return false;
        }
       
    }

    private bool CreateConnection()
    {
        if(IsConnected)
            return true;
        try
        {
            bool result = Init_ETH_String(IpAddress, 0, Convert.ToInt32(Port));
            if (result == true)
            {
                IsConnected = true;
                AddLog.Info("汇川5U_PlC网口连接成功!");
                return true;
            }
            else
            {
                IsConnected = false;
                AddLog.Info("汇川5U_PlC网口连接失败!");
                return false;
            }
        }
        catch (Exception ex)
        {
            IsConnected = false;
            AddLog.Error("汇川5U_PlC网口连接失败!" + ex.Message);
            return false;
        }
    }
    private bool CreateConnection1()
    {
        if (IsConnected)
            return true;
        try
        {
            bool result = Init_ETH_String(IpAddress, nNetId, Convert.ToInt32(Port));
            if (result == true)
            {
                IsConnected = true;
                AddLog.Info("汇川3U_PlC网口连接成功!");
                return true;
            }
            else
            {
                IsConnected = false;
                AddLog.Info("汇川3U_PlC网口连接失败!");
                return false;
            }
        }
        catch (Exception ex)
        {
            IsConnected = false;
            AddLog.Error("汇川3U_PlC网口连接失败!" + ex.Message);
            return false;
        }
    }
    /// <summary>
    /// 关闭连接
    /// </summary>
    public override void DisConnect()
    {
        if (ECom.Plc5Utype)
        {
            IsConnected = false;
            int nNetId = 0;
            bool result = Exit_ETH(nNetId);
        }
        if (ECom.Plc3Utype)
        {
            IsConnected = false;
            bool result = Exit_ETH(nNetId);
        }

    }
    [Category("ModbusTcp事件")]
    [Description("返回错误消息事件")]
    public event MyModbusSlave.ErrorMsgEventHandler OnErrorMsg
    {
        add
        {
            MyModbusSlave.ErrorMsgEventHandler errorMsgEventHandler = this._ErrorMsgEventHandler;
            MyModbusSlave.ErrorMsgEventHandler temp;
            do
            {
                temp = errorMsgEventHandler;
                MyModbusSlave.ErrorMsgEventHandler value2 = (MyModbusSlave.ErrorMsgEventHandler)Delegate.Combine(temp, value);
                errorMsgEventHandler = Interlocked.CompareExchange<MyModbusSlave.ErrorMsgEventHandler>(ref this._ErrorMsgEventHandler, value2, temp);
            }
            while (errorMsgEventHandler != temp);
        }
        remove
        {
            MyModbusSlave.ErrorMsgEventHandler errorMsgEventHandler = this._ErrorMsgEventHandler;
            MyModbusSlave.ErrorMsgEventHandler temp;
            do
            {
                temp = errorMsgEventHandler;
                MyModbusSlave.ErrorMsgEventHandler value2 = (MyModbusSlave.ErrorMsgEventHandler)Delegate.Remove(temp, value);
                errorMsgEventHandler = Interlocked.CompareExchange<MyModbusSlave.ErrorMsgEventHandler>(ref this._ErrorMsgEventHandler, value2, temp);
            }
            while (errorMsgEventHandler != temp);
        }
    }
    protected virtual void OnTcpClientErrorMsgEnterHead(string msg)
    {
        if (this._ErrorMsgEventHandler != null)
        {
            this._ErrorMsgEventHandler(msg);
        }
    }
    object LockPlc = new object();

    #region 读写方法

    /// <summary>
    /// 重写读值方法
    /// </summary>
    /// <param name="Type">值的类型</param>
    /// <param name="Address">地址</param>
    /// <param name="Length">值的长度</param>
    /// <param name="Value">值</param>
    /// <returns></returns>
    public  bool ReadIn161(string Type, string Address, int Length, out int Value)
    {
        lock (LockPlc)
        {
            Value = -1;
            try
            {
                Result = new int[1] { 0 };
                bool bresult = ReadDInt32(Type, Address, Length, out Result);
                if (bresult)
                {
                    if (Result != null)
                    {
                        Value = Result[0];
                        AddLog.Info("5UPlc读取数据:"+Value);
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                AddLog.Error("读取5UPLC失败:"+ ex.ToString());
                return false;
            }

        }
    }
    /// <summary>
    /// 重写的写值方法
    /// </summary>
    /// <param name="Type">值的类型(D或M)</param>
    /// <param name="Address">地址</param>
    /// <param name="Value">值</param>
    /// <returns></returns>
    public  bool WriteIn16(string Type, string Address, int Value)
    {
        lock (LockPlc)
        {
            try
            {
                bool aaa = WriteDInt32(Type, Address, Value);
                AddLog.Info("5UPlc写入成功:" + aaa);
                return aaa;
            }
            catch (Exception ex)
            {
                MessageBox.Show("5UPLC写值失败" + ex.ToString());
                return false;
            }


        }
    }
    #endregion

    #region 3U读写方法
    /// <summary>
    /// plc3u读
    /// </summary>
    /// <param name="address"></param>
    /// <returns></returns>
    public int ReadSingle32(string address)
    {
        try
        {
            var temp = new short[2];
            ReadBlock16(address, ref temp);
            var tempByte = new List<byte>();
            tempByte.AddRange(BitConverter.GetBytes(temp[0]));
            tempByte.AddRange(BitConverter.GetBytes(temp[1]));
            return BitConverter.ToInt32(tempByte.ToArray(), 0);
        }
        catch (Exception ex)
        {
            MessageBox.Show("PLC Read Fail:" + address);
            return -999;
        }
    }
    /// <summary>
    /// plc3u写
    /// </summary>
    /// <param name="address"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool WriteSingle16(string address, int value)
    {
        try
        {
            var temp = new short[] { (short)value };
            WriteBlock16(address, temp);
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show("PLC Read Fail:" + address);
            return false;
        }
    }




    public void ReadBlock16(string startAddress, ref short[] addressValues)
    {
        var addrType = startAddress.Substring(0, 1);
        var startAddr = Convert.ToInt32(startAddress.Substring(1, startAddress.Length - 1));

        byte[] pBuf = new byte[16000];
        int nCount = addressValues.Length;
        int nRet = H3u_Read_Soft_Elem(GetAddrTypeByte(addrType), startAddr, nCount, pBuf, nNetId);

        for (int i = 0; i < addressValues.Length; i++)
        {
            addressValues[i] = pBuf[i];
        }
    }

    public void WriteBlock16(string startAddress, short[] addressValues)
    {
        var addrType = startAddress.Substring(0, 1);
        var startAddr = Convert.ToInt32(startAddress.Substring(1, startAddress.Length - 1));

        int nCount = addressValues.Length;
        var sendByte = new List<byte>();
        for (int i = 0; i < addressValues.Length; i++)
        {
            sendByte.AddRange(BitConverter.GetBytes(addressValues[i]));
        }
        int nRet = H3u_Write_Soft_Elem(GetAddrTypeByte(addrType), startAddr, nCount, sendByte.ToArray(), nNetId);
    }

    private SoftElemType GetAddrTypeByte(string addrType)
    {
        switch (addrType)
        {
            case "X": return SoftElemType.REGI_H3U_X;
            case "Y": return SoftElemType.REGI_H3U_Y;
            case "M": return SoftElemType.REGI_H3U_M;
            case "D": return SoftElemType.REGI_H3U_DW;
            case "R": return SoftElemType.REGI_H3U_R;
            default: return SoftElemType.REGI_H3U_SM;
        }

    }
    #endregion
  public override bool ReadInt16(string memoryType, string address, int length, out short[] results)
  {
      lock (LockPlc)
      {
          results = new short[] { };
          string _address = memoryType + address;

          //缓冲区。读取整型字元件则一个元件占两个byte,位元件则占一个byte。例如读取D元件500个,则缓冲区大小为1000以上
          byte[] pBuf = new byte[16000];
          int nStartAddr = Convert.ToInt32(address);
          int nCount = Convert.ToInt32(length);
          bool bIsWord = false;//是否字元件

          SoftElemType ElemType = SoftElemType.REGI_H5U_M;
          if (memoryType == "Y")
          {
              ElemType = SoftElemType.REGI_H5U_Y;
          }
          else if (memoryType == "X")
          {
              ElemType = SoftElemType.REGI_H5U_X;
          }
          else if (memoryType == "S")
          {
              ElemType = SoftElemType.REGI_H5U_S;
          }
          else if (memoryType == "M")
          {
              ElemType = SoftElemType.REGI_H5U_M;
          }
          else if (memoryType == "B")
          {
              ElemType = SoftElemType.REGI_H5U_B;
          }
          else if (memoryType == "D")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_D;
          }
          else if (memoryType == "R")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_R;
          }

          int nRet = H5u_Read_Device_Block(ElemType, nStartAddr, nCount, pBuf, 0);

          if (nRet != 1)
          {
              return false;
          }
          List<short> arr = new List<short>();
          string strData = "";
          for (int i = 0; i < nCount; i++)
          {
              if (bIsWord)
              {
                  byte[] databuf = new byte[2] { 0, 0 };
                  databuf[0] = pBuf[i * 2];
                  databuf[1] = pBuf[i * 2 + 1];
                  short iTemp = BitConverter.ToInt16(databuf, 0);
                  arr.Add(iTemp);
              }
              else
              {
                  int nVal = 0;
                  nVal = pBuf[i];
                  strData = strData + nVal.ToString();
                  arr.Add(Convert.ToInt16(strData));
              }
          }

          if (arr != null)
          {
              results = new short[arr.Count];
              for (int i = 0; i < arr.Count; i++)
              {
                  results[i] = arr[i];
              }
              return true;
          }
          else
          {
              return false;
          }

      }

  }
  public override bool ReadDInt32(string memoryType, string address, int length, out int[] results)
  {
      lock (LockPlc)
      {
          results = new int[] { };
          string _address = memoryType + address;

          //缓冲区。读取整型字元件则一个元件占两个byte,位元件则占一个byte。例如读取D元件500个,则缓冲区大小为1000以上
          byte[] pBuf = new byte[16000];
          int nStartAddr = Convert.ToInt32(address);
          int nCount = Convert.ToInt32(length);
          bool bIsWord = false;//是否字元件

          SoftElemType ElemType = SoftElemType.REGI_H5U_M;
          if (memoryType == "Y")
          {
              ElemType = SoftElemType.REGI_H5U_Y;
          }
          else if (memoryType == "X")
          {
              ElemType = SoftElemType.REGI_H5U_X;
          }
          else if (memoryType == "S")
          {
              ElemType = SoftElemType.REGI_H5U_S;
          }
          else if (memoryType == "M")
          {
              ElemType = SoftElemType.REGI_H5U_M;
          }
          else if (memoryType == "B")
          {
              ElemType = SoftElemType.REGI_H5U_B;
          }
          else if (memoryType == "D")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_D;
          }
          else if (memoryType == "R")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_R;
          }

          int nRet = H5u_Read_Device_Block(ElemType, nStartAddr, nCount, pBuf, 0);

          if (nRet != 1)
          {
              return false;
          }
          //     nCount = nCount / 2;
          List<int> arr = new List<int>();
          string strData = "";
          for (int i = 0; i < nCount; i++)
          {
              if (bIsWord)
              {
                  byte[] databuf = new byte[4] { 0, 0, 0, 0 };
                  databuf[0] = pBuf[i * 4];
                  databuf[1] = pBuf[i * 4 + 1];
                  databuf[2] = pBuf[i * 4 + 2];
                  databuf[3] = pBuf[i * 4 + 3];
                  int iTemp = BitConverter.ToInt32(databuf, 0);
                  arr.Add(iTemp);
              }
              else
              {
                  int nVal = 0;
                  nVal = pBuf[i];
                  strData = strData + nVal.ToString();
                  arr.Add(Convert.ToInt16(strData));
              }
          }
          if (arr != null)
          {
              results = new int[arr.Count];
              for (int i = 0; i < arr.Count; i++)
              {
                  results[i] = arr[i];
              }
              return true;
          }
          else
          {
              return false;
          }
      }
  }
  public override bool ReadReal32(string memoryType, string address, int length, out float[] results)
  {
      lock (LockPlc)
      {
          results = new float[] { };
          string _address = memoryType + address;

          //缓冲区。读取整型字元件则一个元件占两个byte,位元件则占一个byte。例如读取D元件500个,则缓冲区大小为1000以上
          byte[] pBuf = new byte[16000];
          int nStartAddr = Convert.ToInt32(address);
          int nCount = Convert.ToInt32(length);
          bool bIsWord = false;//是否字元件

          SoftElemType ElemType = SoftElemType.REGI_H5U_M;
          if (memoryType == "Y")
          {
              ElemType = SoftElemType.REGI_H5U_Y;
          }
          else if (memoryType == "X")
          {
              ElemType = SoftElemType.REGI_H5U_X;
          }
          else if (memoryType == "S")
          {
              ElemType = SoftElemType.REGI_H5U_S;
          }
          else if (memoryType == "M")
          {
              ElemType = SoftElemType.REGI_H5U_M;
          }
          else if (memoryType == "B")
          {
              ElemType = SoftElemType.REGI_H5U_B;
          }
          else if (memoryType == "D")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_D;
          }
          else if (memoryType == "R")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_R;
          }

          int nRet = H5u_Read_Device_Block(ElemType, nStartAddr, nCount, pBuf, 0);

          if (nRet != 1)
          {
              return false;
          }
          List<float> arr = new List<float>();
          string strData = "";
          //      nCount = nCount / 2;
          for (int i = 0; i < nCount; i++)
          {
              if (bIsWord)
              {
                  byte[] databuf = new byte[4] { 0, 0, 0, 0 };
                  databuf[0] = pBuf[i * 4];
                  databuf[1] = pBuf[i * 4 + 1];
                  databuf[2] = pBuf[i * 4 + 2];
                  databuf[3] = pBuf[i * 4 + 3];
                  float iTemp = BitConverter.ToSingle(databuf, 0);
                  arr.Add(iTemp);
              }
              else
              {
                  int nVal = 0;
                  nVal = pBuf[i];
                  strData = strData + nVal.ToString();
                  arr.Add(Convert.ToInt16(strData));
              }
          }
          if (arr != null)
          {
              results = new float[arr.Count];
              for (int i = 0; i < arr.Count; i++)
              {
                  results[i] = arr[i];
              }
              return true;
          }
          else
          {
              return false;
          }

      }

  }
  public override bool WriteDInt32(string memoryType, string address, int val)
  {
      lock (LockPlc)
      {
          string _address = memoryType + address;
          byte[] pBuf = new byte[16000];
          int nStartAddr = Convert.ToInt32(address);
          int nCount = 1;
          bool bIsWord = false;//是否字元件

          SoftElemType ElemType = SoftElemType.REGI_H5U_M;
          if (memoryType == "Y")
          {
              ElemType = SoftElemType.REGI_H5U_Y;
          }
          else if (memoryType == "X")
          {
              ElemType = SoftElemType.REGI_H5U_X;
          }
          else if (memoryType == "S")
          {
              ElemType = SoftElemType.REGI_H5U_S;
          }
          else if (memoryType == "M")
          {
              ElemType = SoftElemType.REGI_H5U_M;
          }
          else if (memoryType == "B")
          {
              ElemType = SoftElemType.REGI_H5U_B;
          }
          else if (memoryType == "D")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_D;
          }
          else if (memoryType == "R")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_R;
          }


          GetDataFromUI(pBuf, val.ToString(), bIsWord, 1);
          int nRet = H5u_Write_Device_Block(ElemType, nStartAddr, nCount, pBuf, 0);

          if (nRet != 1)
          {
              return false;
          }
          else
          {
              return true;
          }
      }

  }

  public override bool WriteReal32(string memoryType, string address, float val)
  {
      lock (LockPlc)
      {
          string _address = memoryType + address;
          byte[] pBuf = new byte[16000];
          int nStartAddr = Convert.ToInt32(address);
          int nCount = 1;
          bool bIsWord = false;//是否字元件

          SoftElemType ElemType = SoftElemType.REGI_H5U_M;
          if (memoryType == "Y")
          {
              ElemType = SoftElemType.REGI_H5U_Y;
          }
          else if (memoryType == "X")
          {
              ElemType = SoftElemType.REGI_H5U_X;
          }
          else if (memoryType == "S")
          {
              ElemType = SoftElemType.REGI_H5U_S;
          }
          else if (memoryType == "M")
          {
              ElemType = SoftElemType.REGI_H5U_M;
          }
          else if (memoryType == "B")
          {
              ElemType = SoftElemType.REGI_H5U_B;
          }
          else if (memoryType == "D")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_D;
          }
          else if (memoryType == "R")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_R;
          }


          GetDataFromUI(pBuf, val.ToString(), bIsWord, 2);
          int nRet = H5u_Write_Device_Block(ElemType, nStartAddr, nCount, pBuf, 0);

          if (nRet != 1)
          {
              return false;
          }
          else
          {
              return true;
          }
      }

  }

  public override bool WriteInt16(string memoryType, string address, short val)
  {
      lock (LockPlc)
      {
          string _address = memoryType + address;
          byte[] pBuf = new byte[16000];
          int nStartAddr = Convert.ToInt32(address);
          int nCount = 1;
          bool bIsWord = false;//是否字元件

          SoftElemType ElemType = SoftElemType.REGI_H5U_M;
          if (memoryType == "Y")
          {
              ElemType = SoftElemType.REGI_H5U_Y;
          }
          else if (memoryType == "X")
          {
              ElemType = SoftElemType.REGI_H5U_X;
          }
          else if (memoryType == "S")
          {
              ElemType = SoftElemType.REGI_H5U_S;
          }
          else if (memoryType == "M")
          {
              ElemType = SoftElemType.REGI_H5U_M;
          }
          else if (memoryType == "B")
          {
              ElemType = SoftElemType.REGI_H5U_B;
          }
          else if (memoryType == "D")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_D;
          }
          else if (memoryType == "R")
          {
              bIsWord = true;
              ElemType = SoftElemType.REGI_H5U_R;
          }


          GetDataFromUI(pBuf, val.ToString(), bIsWord, 0);
          int nRet = H5u_Write_Device_Block(ElemType, nStartAddr, nCount, pBuf, 0);

          if (nRet != 1)
          {
              return false;
          }
          else
          {
              return true;
          }
      }

  }
  private void GetDataFromUI(byte[] pBuf, string arr, bool bIsWord, int nDataType)
  {
      for (int i = 0; i < arr.Length; i++)
      {
          if (arr == string.Empty)
          {
              break;
          }
          double nVal = Convert.ToDouble(arr);
          if (bIsWord)
          {
              if (nDataType == 0)//16位整形
              {
                  int idata = Convert.ToInt16(arr);
                  byte[] dataBuf = new byte[2] { 0, 0 };
                  dataBuf = BitConverter.GetBytes(idata);
                  pBuf[2 * i] = dataBuf[0];
                  pBuf[2 * i + 1] = dataBuf[1];
              }
              else if (nDataType == 1)//32位整形
              {
                  int idata = Convert.ToInt32(arr);
                  byte[] dataBuf = new byte[4] { 0, 0, 0, 0 };
                  dataBuf = BitConverter.GetBytes(idata);
                  pBuf[4 * i] = dataBuf[0];
                  pBuf[4 * i + 1] = dataBuf[1];
                  pBuf[4 * i + 2] = dataBuf[2];
                  pBuf[4 * i + 3] = dataBuf[3];
              }
              else if (nDataType == 2)//浮点数
              {
                  float fdata = Convert.ToSingle(arr);
                  byte[] dataBuf = new byte[4] { 0, 0, 0, 0 };
                  dataBuf = BitConverter.GetBytes(fdata);
                  pBuf[4 * i] = dataBuf[0];
                  pBuf[4 * i + 1] = dataBuf[1];
                  pBuf[4 * i + 2] = dataBuf[2];
                  pBuf[4 * i + 3] = dataBuf[3];
              }
          }
          else
          {
              pBuf[i] = (byte)nVal;
          }
      }
  }
  public enum SoftElemType
  {
      //AM600
      ELEM_QX = 0,     //QX元件
      ELEM_MW = 1,     //MW元件
      ELEM_X = 2,      //X元件(对应QX200~QX300)
      ELEM_Y = 3,      //Y元件(对应QX300~QX400)

      //H3U
      REGI_H3U_Y = 0x20,       //Y元件的定义	
      REGI_H3U_X = 0x21,      //X元件的定义							
      REGI_H3U_S = 0x22,      //S元件的定义				
      REGI_H3U_M = 0x23,      //M元件的定义							
      REGI_H3U_TB = 0x24,     //T位元件的定义				
      REGI_H3U_TW = 0x25,     //T字元件的定义				
      REGI_H3U_CB = 0x26,     //C位元件的定义				
      REGI_H3U_CW = 0x27,     //C字元件的定义				
      REGI_H3U_DW = 0x28,     //D字元件的定义				
      REGI_H3U_CW2 = 0x29,        //C双字元件的定义
      REGI_H3U_SM = 0x2a,     //SM
      REGI_H3U_SD = 0x2b,     //
      REGI_H3U_R = 0x2c,      //
                              //H5u
      REGI_H5U_Y = 0x30,       //Y元件的定义	
      REGI_H5U_X = 0x31,      //X元件的定义							
      REGI_H5U_S = 0x32,      //S元件的定义				
      REGI_H5U_M = 0x33,      //M元件的定义	
      REGI_H5U_B = 0x34,       //B元件的定义
      REGI_H5U_D = 0x35,       //D字元件的定义
      REGI_H5U_R = 0x36,       //R字元件的定义

  }

Base基础类:

    public class PLCBase
    {
        //走串口通信相关参数
        protected SerialPort _comPort;
        public string ComPortName;
        public int BaudRate;
        public int DataBits;
        public Parity ComParity;
        public StopBits ComStopBits;
        public int StationNo;
        //走网络通信相关参数

        public string IpAddress;

        public string Port;
        //基本参数
        /// <summary>
        /// 是否走网络
        /// </summary>
        public bool IsEthernetType;
        /// <summary>
        /// 描述
        /// </summary>
        public string Description;
        /// <summary>
        /// 是否处于连接状态
        /// </summary>
        public bool IsConnected;
        /// <summary>
        /// 类型
        /// </summary>
        public PLCType PLCVender;

        public PLCBase()
        {

        }

        public virtual bool Connect()
        {
            return false;
        }

        public virtual void DisConnect()
        {

        }

        public virtual bool ReadBit(string memoryType, string address, out bool result)
        {
            result = false;
            return false;
        }

        public virtual bool ReadByte(string memoryType, string address, int length, out byte[] results)
        {
            results = new byte[1] { 0 };
            return false;
        }

        public virtual bool ReadInt16(string memoryType, string address, int length, out short[] results)
        {
            results = new short[1] { 0 };
            return false;
        }

        public virtual bool ReadUInt16(string memoryType, string address, int length, out ushort[] results)
        {
            results = new ushort[1] { 0 };
            return false;
        }

        public virtual bool ReadDInt32(string memoryType, string address, int length, out int[] results)
        {
            results = new int[1] { 0 };
            return false;
        }

        public virtual bool ReadReal32(string memoryType, string address, int length, out float[] results)
        {
            results = new float[1] { 0f };
            return false;
        }

        public virtual bool WriteBit(string memoryType, string address, bool onoff)
        {
            return false;
        }

        public virtual bool WriteInt16(string memoryType, string address, short val)
        {
            return false;
        }

        public virtual bool WriteUInt16(string memoryType, string address, ushort val)
        {
            return false;
        }

        public virtual bool WriteDInt32(string memoryType, string address, int val)
        {
            return false;
        }

        public virtual bool WriteReal32(string memoryType, string address, float val)
        {
            return false;
        }

        public virtual bool WriteBit(string memoryType, string address, bool[] onoff)
        {
            return false;
        }

        public virtual bool WriteInt16(string memoryType, string address, short[] val)
        {
            return false;
        }

        public virtual bool WriteUInt16(string memoryType, string address, ushort[] val)
        {
            return false;
        }

        public virtual bool WriteDInt32(string memoryType, string address, int[] val)
        {
            return false;
        }

        public virtual bool WriteReal32(string memoryType, string address, float[] val)
        {
            return false;
        }

        public virtual void ToXmlNode(out Dictionary<string, object> attributes, out Dictionary<string, object> nodes)
        {
            attributes = new Dictionary<string, object>();
            nodes = new Dictionary<string, object>();
        }
        /// <summary>
        /// 从XML结点获取
        /// </summary>
        public virtual void FromXmlNode(XmlNode node)
        {

        }
    }

    public enum PLCType
    {
        HuiChuan5U,
        HuiChuan3U,
        SimensePLC,
        OmronFinsTcpPLC,
        MelsecPLC,
        MelsecPLC3UModbus,
        MelsecPLC3GAModbus,
        MelsecPLC5UNet,
    }

}

实例调用类

  private void btn_WriteDate_Click(object sender, EventArgs e)
  {
      if (ckPlc5U.Checked)
      {
          try
          {
              if (!string.IsNullOrWhiteSpace(TxtAddress.Text) && !string.IsNullOrWhiteSpace(TxtValue.Text) && !string.IsNullOrWhiteSpace(SltType.Text))
              {
                  try
                  {
                      ECom.Plc5UWrite(SltType.Text, TxtAddress.Text, int.Parse(TxtValue.Text));
                  }
                  catch (Exception ex)
                  {
                      AddLog.Error("Plc写入出错:" + ex.Message);
                      return;
                  }
              }
              else
              {
                  if (form == null)
                  {
                      MessageBox.Show("Plc种类、地址、值不能为空!");
                  }
                  else
                  {
                      AntdUI.Message.error(form, "Plc种类、地址、值不能为空!", Font);
                  }

              }
          }
          catch (Exception ex)
          {

              AddLog.Info("Plc写入出错" + ex.Message);
              return;
          }
      }
      if(ckPlc3U.Checked)
      {
          try
          {
              if (!string.IsNullOrWhiteSpace(TxtAddress.Text) && !string.IsNullOrWhiteSpace(TxtValue.Text))
              {
                  try
                  {
                      ECom.Plc3UWrite(TxtAddress.Text, int.Parse(TxtValue.Text));
                  }
                  catch (Exception ex)
                  {
                      AddLog.Error("Plc3U写入出错:" + ex.Message);
                      return;
                  }
              }
              else
              {
                  if (form == null)
                  {
                      MessageBox.Show("Plc3U地址、值不能为空!");
                  }
                  else
                  {
                      AntdUI.Message.error(form, "Plc3U地址、值不能为空!", Font);
                  }

              }
          }
          catch (Exception ex)
          {

              AddLog.Info("Plc3U写入出错" + ex.Message);
              return;
          }
      }
  }

  private async void btn_ReadDate_Click(object sender, EventArgs e)
  {
      if (ckPlc5U.Checked)
      {
          try
          {
              await Task.Run(() => ECom.Plc5URead(SltType.Text, TxtAddress.Text, int.Parse(TxtLength.Text), int.Parse(TxtValue.Text)));
          }
          catch (Exception ex)
          {

              AddLog.Error("Plc5U读取出错:" + ex.Message);
              return;
          }
      }
      if (ckPlc3U.Checked)
      {
          try
          {
              await Task.Run(() => ECom.Plc3URead(TxtAddress.Text));
          }
          catch (Exception ex)
          {

              AddLog.Error("Plc3U读取出错:" + ex.Message);
              return;
          }
      }
  } #region 汇川plc读写数据
 public static void Plc5URead(string Type, string address ,int Length,int value)
 {
     inovancePlc.ReadIn161(Type, address, Length, out value);
 }
 public static void Plc5UWrite(string Type, string address ,int value)
 {
     inovancePlc.WriteIn16(Type, address, value);
 }
 public static void Plc3URead(string Address)
 {
     inovancePlc.ReadSingle32(Address).ToString();
 }
 public static void Plc3UWrite(string Address,int value)
 {
     inovancePlc.WriteSingle16(Address,value).ToString();
 }
 #endregion

下载动态库可参考本文链接:C#汇川PLC通讯_c#与汇川plc通信-CSDN博客


http://www.kler.cn/a/322934.html

相关文章:

  • 函数指针示例
  • 《C语言程序设计现代方法》note-5 数组
  • 如何编译 Cesium 源码
  • transformers 操作篇
  • C++map和set(二)
  • c++ 类和对象(中)
  • vue防止数据过滤,污染原数据
  • Unity 的 UI Event System 是一个重要的框架
  • (done) 声音信号处理基础知识(4) (Understanding Audio Signals for ML)
  • 机器学习查漏补缺(4)
  • 基于python+django+vue的旅游景点数据分析系统
  • iOS--RunLoop原理
  • Python 3 字典
  • 尚庭公寓-接口定义
  • 变种水仙花数 - Lily Number
  • 【Python】Flask-Admin:构建强大、灵活的后台管理界面
  • SpringBootWeb响应
  • java Nio的应用
  • Spring Boot入门指南
  • Angular与Vue的全方位对比分析
  • 实例讲解电动汽车故障限功限速控制策略及Simulink建模方法
  • 快速创建第一个Spring Boot 项目
  • K8s Calico替换为Cilium,以及安装Cilium过程(鲁莽版)
  • linux命令之git用法
  • 智能手机取证: 专家如何从被锁定设备中提取数据?
  • SSH连接提示秘钥无效