private void OPCUAStart_Click(object sender, EventArgs e){
//KepServer = new OPCServer();
_OpcTaskEnd = false;
try{
KepServer.Connect("Techmation.OPC.Server.V1"); //需要修改设置OPCDA服务器名 //KEPware.KEPServerEx.V4
if (KepServer.ServerState == (int)OPCServerState.OPCRunning){
//海天OPC初始化,需要 KepServer连接上服务器才能初始化
InitializeOPC();
OPCUAStatusTxt.Text = "已连接上";
OPUDAStartBt.Enabled = false;
OPCUAStopBt.Enabled = true;
Task.Run(() =>{
while (_OpcTaskEnd == false){
try{
//读OPC变量
//批量读
KepGroup.SyncRead((short)OPCAutomation.OPCDataSource.OPCCache, 27, ServerHandles, out Values, out Errors, out Qualities, out TimeStamps);
//更新HMI界面
Invoke(new Action(() =>{
..................
..................
..............
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message );
if (_OpcTaskEnd == true) return;
}
}));
Thread.Sleep(500);
}
catch (Exception)
{
}
}
});
}
else
{
OPCUAStatusTxt.Text = "未连接";
OPUDAStartBt.Enabled = true;
OPCUAStopBt.Enabled = false;
}
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
private void InitializeOPC(){
KepGroups = KepServer.OPCGroups;
KepGroup = KepGroups.Add("Group1"); //需要修改设置组名
KepGroup.UpdateRate = 250;
KepGroup.IsActive = true;
KepGroup.IsSubscribed = false;
KepItems = KepGroup.OPCItems;
//string OpcDaPath = System.Configuration.ConfigurationManager.AppSettings["HT_OPC_IP"]; //"192_168_100_1."; //需要修改变量前的路径名 // "Channel1.Device1.Group1.";
ServerHandles[1] = KepItems.AddItem(OpcDaPath + "tmTemp1_Current", 1).ServerHandle; //需要修改设置变量名
ServerHandles[2] = KepItems.AddItem(OpcDaPath + "tmTemp2_Current", 2).ServerHandle;
//设置的变量名要和设备的一样的 OpcDaPath 是IP地址 这样获取对应设备下的数据
ServerHandles[3] = KepItems.AddItem(OpcDaPath + "tmTemp3_Current", 3).ServerHandle;
ServerHandles[4] = KepItems.AddItem(OpcDaPath + "tmTemp4_Current", 4).ServerHandle;
ServerHandles[5] = KepItems.AddItem(OpcDaPath + "tmTemp5_Current", 5).ServerHandle;
ServerHandles[6] = KepItems.AddItem(OpcDaPath + "tmChargePress1", 6).ServerHandle;
...................
.....................
.............................
}