OPC通訊實例(C#通過OPC連接PLC讀寫數據)(目前最解決我問題的文章之一,特此收藏)


using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OPCAutomation;
using System.Diagnostics;
 
namespace OPC_Client
{
    public partial class Form1 : Form
    {
        OPCServer objServer;
        OPCGroups objGroups;
        OPCGroup objGroup;
        OPCItems objItems;
        Array strItemIDs;
        Array lClientHandles;
        Array lserverhandles;
        Array lErrors;
      //  int ltransID_Rd = 1;
       // int lCancelID_Rd;
       object RequestedDataTypes = null;
        object AccessPaths = null;
     //   Array lerrors_Rd;
        Array lErrors_Wt;
        int lTransID_Wt = 2;
        int lCancelID_Wt;
        public Form1()
        {
            InitializeComponent();
        }
 
 
        //連接opc server
        private void button1_Click(object sender, EventArgs e)
        {
            //(1)創建opc server對象
            objServer = new OPCServer();
            //連接opc server
            objServer.Connect("KEPware.KEPServerEx.V4", null);
            //(2)建立一個opc組集合
            objGroups = objServer.OPCGroups;
            //(3)建立一個opc組
            objGroup = objGroups.Add(null); //Group組名字可有可無
            //(4)添加opc標籤
            objGroup.IsActive = true; //設置該組爲活動狀態,連接PLC時,設置爲非活動狀態也一樣
            objGroup.IsSubscribed = true; //設置異步通知
            objGroup.UpdateRate = 250;
            objServer.OPCGroups.DefaultGroupDeadband = 0;
            objGroup.DataChange  = new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
           // objGroup.AsyncReadComplete  = new DIOPCGroupEvent_AsyncReadCompleteEventHandler(AsyncReadComplete);
            objGroup.AsyncWriteComplete  = new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(AsyncWriteComplete);
            objItems = objGroup.OPCItems; //建立opc標籤集合
            string[] tmpIDs = new string[7];
            int[] tmpCHandles = new int[7];
            for (int i = 1; i < 7; i  )
            {
                tmpCHandles[i] = i;
            }
            tmpIDs[1] = "西門子S7-300.PLC.系統啓動開關";
            tmpIDs[2] = "西門子S7-300.PLC.機械手啓動開關";
            tmpIDs[3] = "西門子S7-300.PLC.M1電動機";
            tmpIDs[4] = "西門子S7-300.PLC.機械手";
            tmpIDs[5] = "西門子S7-300.PLC.溫度";
            tmpIDs[6] = "西門子S7-300.PLC.溼度";
            strItemIDs = (Array)tmpIDs;//必須轉成Array型,否則不能調用AddItems方法
            lClientHandles = (Array)tmpCHandles;
            // 添加opc標籤
            objItems.AddItems(6, ref strItemIDs, ref lClientHandles, out lserverhandles, out lErrors, RequestedDataTypes, AccessPaths);
        }
 
 
        //結束並斷開opc server
        private void button4_Click(object sender, EventArgs e)
        {
            objServer.Disconnect();
            //關閉kepserver進程,這個跟OPC操作無關
            /*
            foreach ( Process oneProcess in Process.GetProcesses())
            {
            if (oneProcess.ProcessName == "ServerMain")
            oneProcess.Kill();
            }
            */
        }
 
        //每當項數據有變化時執行的事件,採用訂閱方式
 
 
        void KepGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {
            //爲了測試,所以加了控制檯的輸出,來查看事物ID號
            //Console.WriteLine("********" TransactionID.ToString() "*********");
 
            for (int i = 0; i < NumItems; i  )
            {
 
 
                if (Convert.ToInt32(ClientHandles.GetValue(i   1)) == 1)
                {
                    if (ItemValues.GetValue(i   1) != null)
                    {
                        this.Data1.Text = ItemValues.GetValue(i   1).ToString();
                    }
                }
                if (Convert.ToInt32(ClientHandles.GetValue(i   1)) == 2)
                {
                    if (ItemValues.GetValue(i   1) != null)
                    {
                        this.Data2.Text = ItemValues.GetValue(i   1).ToString();
                    }
                }
                if (Convert.ToInt32(ClientHandles.GetValue(i   1)) == 3)
                {
                    if (ItemValues.GetValue(i   1) != null)
                    {
                        this.Data3.Text = ItemValues.GetValue(i   1).ToString();
                    }
                }
                if (Convert.ToInt32(ClientHandles.GetValue(i   1)) == 4)
                {
                    if (ItemValues.GetValue(i   1) != null)
                    {
                        this.Data4.Text = ItemValues.GetValue(i   1).ToString();
                    }
                }
                if (Convert.ToInt32(ClientHandles.GetValue(i   1)) == 5)
                {
                    if (ItemValues.GetValue(i   1) != null)
                    {
                        this.Data5.Text = ItemValues.GetValue(i   1).ToString();
                    }
                }
                if (Convert.ToInt32(ClientHandles.GetValue(i   1)) == 6)
                {
                    if (ItemValues.GetValue(i   1) != null)
                    {
                        this.Data6.Text = ItemValues.GetValue(i   1).ToString();
                    }
                }
            }
 
 
        }
 
        
 
            
          
        //發送異步寫數據指令
        private void button3_Click(object sender, EventArgs e)
        {
            Array AsyncValue_Wt;
            Array SerHandles;
            object[] tmpWtData = new object[3];//寫入的數據必須是object型的,否則會報錯
            int[] tmpSerHdles = new int[3];
            //將輸入數據賦給數組,然後再轉成Array型送給AsyncValue_Wt
            tmpWtData[1] = (object)textBox1.Text;
            tmpWtData[2] = (object)textBox2.Text;
            AsyncValue_Wt = (Array)tmpWtData;
            //將輸入數據送給的Item對應服務器句柄賦給數組,然後再轉成Array型送給SerHandles
            tmpSerHdles[1] = Convert.ToInt32(lserverhandles.GetValue(1));
            tmpSerHdles[2] = Convert.ToInt32(lserverhandles.GetValue(2));
            SerHandles = (Array)tmpSerHdles;
            objGroup.AsyncWrite(2, ref SerHandles, ref AsyncValue_Wt, out lErrors_Wt, lTransID_Wt, out lCancelID_Wt);
 
        }
        //異步寫入成功
        private void AsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors)
        {
            MessageBox.Show("數據寫入成功!");
        }
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章