最近在搞到一個OPC動態庫OPCAutomation.dll,該動態庫在http://www.kepware.com/可下載,下面介紹如何用C#進行OPC Client開發。
1.新建C#應用程序,命名為OPC Client,將OPCAutomation.dll引用,如圖。
using OPCAutomation;
2. 定義OPC的三個接口類OPCServer類、OPCGroup類和OPCItem類;
OPCServer KepServer;
OPCGroups KepGroups;
OPCGroup KepGroup;
OPCItems KepItems;
OPCItem KepItem;
3. 枚舉網絡OPC服務器
枚舉OPC服務器用到GetOPCServers()函數
//獲取計算機IP,計算機名稱
IPHostEntry IPHost = Dns.Resolve(Environment.MachineName);
if (IPHost.AddressList.Length > 0)
{
strHostIP = IPHost.AddressList[0].ToString();
}
else
{
return;
}
//通過IP來獲取計算機名稱,可用在局域網內
IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP);
strHostName = ipHostEntry.HostName.ToString();//獲取本地計算機上的OPCServerName
try
{
KepServer = new OPCServer();
object serverList = KepServer.GetOPCServers(strHostName);
//枚舉網絡所有OPC服務器並寫入ComboBox控件
foreach (string turn in (Array)serverList)
{
cmbServerName.Items.Add(turn);
}
cmbServerName.SelectedIndex = 0;
btnConnServer.Enabled = true;
}
catch (Exception err)
{
MessageBox.Show("枚舉本地OPC服務器出錯:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
4. 連接OPC服務器
try
{
KepServer.Connect(remoteServerName, remoteServerIP);
if (KepServer.ServerState == (int)OPCServerState.OPCRunning)
{
tsslServerState.Text = "已連接到-" + KepServer.ServerName + " ";
}
else
{
//這里你可以根據返回的狀態來自定義顯示信息,請查看自動化接口API文檔
tsslServerState.Text = "狀態:" + KepServer.ServerState.ToString() + " ";
}
}
catch (Exception err)
{
MessageBox.Show("連接遠程服務器出現錯誤:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
5. 創建組和列出OPC服務器中所有節點
//創建組
try
{
KepGroups = KepServer.OPCGroups;
KepGroup = KepGroups.Add("OPCDOTNETGROUP");
SetGroupProperty();
KepGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
KepGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete);
KepItems = KepGroup.OPCItems;
}
catch (Exception err)
{
MessageBox.Show("創建組出現錯誤:"+err.Message,"提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);
return false;
}
//列出OPC服務器中所有節點
//展開分支
oPCBrowser.ShowBranches();
//展開葉子
oPCBrowser.ShowLeafs(true);
foreach (object turn in oPCBrowser)
{
listBox1.Items.Add(turn.ToString());
}