准备事项

1.Microsoft Visual Studio2010开发工具
2.KepServerEx4,OPC服务器软件,切记,用4.0版本。自行百度下载
3.OPCAutomation动态链接库下载地址:点我下载

封装类库

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using OPCAutomation; //引入OPC服务器动态链接库

namespace ComObj
{
    public class PLC
    {
        //KepServerEx服务器名称
        private const string S_OPCSvrName = "KEPware.KEPServerEx.V4";

        private string mRoot = string.Empty;
        private string mDirLog = string.Empty;
        private static bool mCommunicateInited = false;
        private OPCServer mOpcSvr = null;
        private OPCGroups mOpcGrps = null;
        private OPCGroup mOpcGrp = null;
        private OPCItem[] mOpcItems = null;
        private object[] mItemVals = null;
        
        //添加索引集合到OPC服务器中
        private string[] mItems = {"M126","D483" };

        private static PLC mInstance = null;
        private PLC()
        {
            mRoot = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            mDirLog = Path.Combine(mRoot, "logs");
            if (!Directory.Exists(mDirLog)) Directory.CreateDirectory(mDirLog);
            mOpcItems = new OPCItem[mItems.Length];
            mItemVals = new object[mItems.Length];
            mCommunicateInited = iniCommunicate();
        }
        private static string mLastErrInfo = string.Empty;

        public static string getLastErrInfo()
        {
            return mLastErrInfo;
        }

        public static PLC getInstance()
        {
            if (mInstance == null) mInstance = new PLC();
            if (!mCommunicateInited) mInstance = null;
            return mInstance;
        }

        private void mOpcGrp_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {
            for (int i = 1; i <= NumItems; i++)
            {
                int h = int.Parse(ClientHandles.GetValue(i).ToString());
                h -= 1;
                if (h >= 0 && h < mItemVals.Length) mItemVals[h] = ItemValues.GetValue(i);
            }
        }

        private void writeLog(string info)
        {
            DateTime now = DateTime.Now;
            string fname = Path.Combine(mDirLog, string.Format("log_{0}.log", now.ToString("yyMMdd")));
            StreamWriter sw = File.AppendText(fname);
            sw.Write(string.Format("{0}##{1}\r\n", now.ToString("yyMMdd HH:mm:ss"), info));
            sw.Flush();
            sw.Close();
        }

        private bool connect()
        {
            try
            {
                mOpcSvr.Connect(S_OPCSvrName);
                if (mOpcSvr.ServerState != (int)OPCServerState.OPCRunning)
                {
                    mLastErrInfo = "OPC连接异常";
                    writeLog("OPC连接异常," + mOpcSvr.ServerState.ToString());
                    return false;
                }
            }
            catch (Exception e)
            {
                mLastErrInfo = "OPC连接异常";
                writeLog("OPC连接异常:" + e.ToString());
                return false;
            }
            return true;
        }

        private bool iniGroup()
        {
            try
            {
                mOpcGrps = mOpcSvr.OPCGroups;
                mOpcGrp = mOpcGrps.Add("Single");
                mOpcGrp.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(mOpcGrp_DataChange);
                mOpcGrps.DefaultGroupIsActive = true;
                mOpcGrps.DefaultGroupDeadband = 50;
                mOpcGrp.UpdateRate = 50;
                mOpcGrp.IsActive = true;
                mOpcGrp.IsSubscribed = true;
                for (int i = 0; i < mItems.Length; i++)
                {
                    mOpcItems[i] = mOpcGrp.OPCItems.AddItem(string.Format("single.dev.{0}", mItems[i]), i + 1);
                }
            }
            catch (Exception e)
            {
                mLastErrInfo = "OPC错误:组初始化失败";
                writeLog(mLastErrInfo + "," + e.ToString());
                return false;
            }
            return true;
        }

        private bool iniCommunicate()
        {
            if (mCommunicateInited) return true;
            mLastErrInfo = string.Empty;
            try
            {
                mOpcSvr = new OPCServer();
                object progIds = mOpcSvr.GetOPCServers();
                bool bTmp = false;
                foreach (string progId in (Array)progIds)
                {
                    bTmp = progId.Equals(S_OPCSvrName);
                    if (bTmp) break;
                }
                if (!bTmp)
                {
                    mLastErrInfo = "连接失败,可能OPC服务未安装";
                    writeLog("OPC连接失败:可能OPC服务未安装");
                    return false;
                }
                if (!connect()) return false;
                if (!iniGroup())
                {
                    mOpcSvr.Disconnect();
                    return false;
                }
                return true;
            }
            catch (Exception e)
            {
                writeLog("OPC连接失败:" + e.ToString());
                return false;
            }
        }

        private int findItem(string item)
        {
            item = item.ToUpper();
            for (int i = 0; i < mItems.Length; i++)
            {
                if (mItems[i].Equals(item)) return i;
            }
            return -1;
        }

        private object getValue(string item)
        {
            int i = findItem(item);
            return i == -1 ? null : mItemVals[i];
        }

        private bool getValueBool(string item)
        {
            object val = getValue(item);
            if (val == null) return false;
            bool res;
            if (!bool.TryParse(val.ToString(), out res))
            {
                int i;
                if (int.TryParse(val.ToString(), out i))
                {
                    res = i != 0;
                }
            }
            return res;
        }

        private int getValueInt(string item)
        {
            object val = getValue(item);
            return val == null ? 0 : (int)val;
        }

        private bool setValue(string item, string val)
        {
            int i = findItem(item);
            if (i == -1)
            {
                mLastErrInfo = "Item不存在";
                return false;
            }
            try
            {
                mOpcItems[i].Write(val);
            }
            catch (Exception e)
            {
                mLastErrInfo = "OPC写错误";
                writeLog("OPC写错误," + e.ToString());
                return false;
            }
            return true;
        }

        private bool setValueBool(string item, bool val)
        {
            return setValue(item, val ? "1" : "0");
        }

        private bool setValueInt(string item, int val)
        {
            return setValue(item, val.ToString());
        }

        #region 属性
        public static void disConnect()
        {
            if (mInstance != null)
            {
                if (mInstance.mOpcSvr != null)
                    try
                    {
                        mInstance.mOpcSvr.Disconnect();
                    }
                    catch
                    {
                    }
            }
        }
        //
        public int D483
        {
            get { return getValueInt("D483"); }
            set { setValueInt("D483", value); }
        }
        public bool M126
        {
            get { return getValueBool("M126"); }
            set { setValueBool("M126", value); }
        }
        #endregion
    }
}

调用

读:

using ComObj;
private ComObj.PLC mPlc;

//此时我们放一个计时器
private void tmState_Tick(object sender, EventArgs e)
        {
            tmState.Enabled = false;
            //机
            lblJ1.Text = string.Format("{0}.{1}", mPlc.D483 / 10, mPlc.D483 % 10);
        }

 private void FormDcTest_Load(object sender, EventArgs e)
        {
            mPlc = ComObj.PLC.getInstance();
            if (mPlc == null)
            {
                MessageBox.Show(ComObj.PLC.getLastErrInfo(), "PLC通讯失败,请确保已打开KepServerEx4.0软件", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tmState.Enabled = true;
            }
        }

给PLC指令:

                  mPlc.M124 = true;
Last modification:April 6th, 2020 at 08:47 am
If you think my article is useful to you, please feel free to appreciate