public void TestErr_AddItems01() { //Testing --- OPCItemDef[] opcitems = new OPCItemDef[1]; OPCItemDef opcitem = new OPCItemDef("DP1", true, 1, System.Runtime.InteropServices.VarEnum.VT_EMPTY); opcitems[0] = opcitem; OPCItemResult[] result; //Test Procedure Call bool b = group.AddItems(opcitems, out result); }
public bool ViewItem(string opcid) { try { RemoveItem(); // first remove previous item if any itmHandleClient = 1234; OPCItemDef[] aD = new OPCItemDef[1]; aD[0] = new OPCItemDef(opcid, true, itmHandleClient, VarEnum.VT_EMPTY); OPCItemResult[] arrRes; theGrp.AddItems(aD, out arrRes); if (arrRes == null) { return(false); } if (arrRes[0].Error != HRESULTS.S_OK) { return(false); } btnItemMore.Enabled = true; itmHandleServer = arrRes[0].HandleServer; itmAccessRights = arrRes[0].AccessRights; itmTypeCode = VT2TypeCode(arrRes[0].CanonicalDataType); txtItemID.Text = opcid; txtItemDataType.Text = DUMMY_VARIANT.VarEnumToString(arrRes[0].CanonicalDataType); if ((itmAccessRights & OPCACCESSRIGHTS.OPC_READABLE) != 0) { int cancelID; theGrp.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE, 7788, out cancelID); } else { txtItemValue.Text = "no read access"; } if (itmTypeCode != TypeCode.Object) // Object=failed! { // check if write is premitted if ((itmAccessRights & OPCACCESSRIGHTS.OPC_WRITEABLE) != 0) { btnItemWrite.Enabled = true; } } } catch (COMException) { MessageBox.Show(this, "AddItem OPC error!", "ViewItem", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } return(true); }
private void cmdAddItem_Click(object sender, EventArgs e) { ItemDefs[0] = new OPCItemDef(txtItem1.Text, true, 1234, VarEnum.VT_EMPTY); ItemDefs[1] = new OPCItemDef(txtItem2.Text, true, 5678, VarEnum.VT_EMPTY); theGroup.AddItems(ItemDefs, out itemResults); if (itemResults[0].Error != 0 || itemResults[1].Error != 0) { MessageBox.Show("AddItems - some failed"); cmdConnect.Enabled = false; cmdDisconnect.Enabled = true; cmdAddGroup.Enabled = false; cmdRemGroup.Enabled = true; cmdAddItem.Enabled = true; cmdRemItem.Enabled = false; } HandlesServer[0] = itemResults[0].HandleServer; HandlesServer[1] = itemResults[1].HandleServer; cmdAddItem.Enabled = false; cmdRemGroup.Enabled = false; cmdRemItem.Enabled = true; cmdWriteSync.Enabled = true; cmdWriteAsync.Enabled = true; cmdReadSync.Enabled = true; cmdReadAsync.Enabled = true; }
public void AddOPCItem(OpcGroup grp, string valueAddress, Guid guid) { if (grp == null) { return; } try { results = grp.AddItems(new [] { valueAddress }, new Guid[] { guid }); for (int i = 0; i < results.Count(); i++) { //ValList[i].OPCItemResult = results[i]; if (results[i].ResultID.Failed()) { string message = "Failed to add item \'" + results[i].ItemName + "\'" + " Error: " + results[i].ResultID.Name; Console.WriteLine(message); //RadWindow.Alert(message); } else { //success } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void AddItems(List <string> p_ItemIds) { int l_ItemClientHandle = 0; OpcItemDef[] l_ItemDef = new OpcItemDef[p_ItemIds.Count]; OpcItemResult[] l_AddRes; foreach (string l_ItemName in p_ItemIds) { l_ItemDef[l_ItemClientHandle] = new OpcItemDef(l_ItemName, false, l_ItemClientHandle, VarEnum.VT_BSTR); l_ItemClientHandle++; } _group.AddItems(l_ItemDef, out l_AddRes); l_ItemClientHandle = 0; foreach (string l_ItemName in p_ItemIds) { if (l_AddRes[l_ItemClientHandle].Error == HResults.S_OK) { Dictionary <string, string> l_ItemProps = new Dictionary <string, string>(); l_ItemProps.Add(CModel.ServerModel.ItemPropIdKey, _server.GetItemID(l_ItemName)); l_ItemProps.Add(CModel.ServerModel.ItemPropTypeKey, OpcUtility.TypeToString((int)l_AddRes[l_ItemClientHandle].CanonicalDataType)); _serverModel.AddItem(l_ItemClientHandle, l_AddRes[l_ItemClientHandle].HandleServer, l_ItemProps); } l_ItemClientHandle++; } }
public void ViewItems(List <string> opcids) { // first remove previous item if any _itmHandleClient = 1234; //или RemoveItems(); List <OPCItemDef> aD = new List <OPCItemDef>(); int i = 1; foreach (string opcid in opcids) { i++; aD.Add(new OPCItemDef(opcid, true, _itmHandleClient + i, VarEnum.VT_EMPTY)); } OPCItemResult[] arrRes; _theGrp.AddItems(aD.ToArray(), out arrRes); if (arrRes == null) { return; } if (arrRes.Any(ar => ar.Error != HRESULTS.S_OK)) { throw new Exception("arrRes[0].Error != HRESULTS.S_OK"); } _itmHandlerListServer = new List <int>(); foreach (var item in arrRes) { _itmHandlerListServer.Add(Convert.ToInt32(item.HandleServer)); } //_itmHandlerListServer = arrRes.OfType<int>().ToList(); int cancelId; _theGrp.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE, 7788, out cancelId); }
/// <summary> /// 同步读 /// </summary> /// <param name="dataAddress"></param> /// <returns></returns> public OperateResult <string> SyncReadData(string dataAddress) { #region 检验 if (string.IsNullOrEmpty(dataAddress)) { return(new OperateResult <string>("传入的参数都不能为空")); } if (_opcServer == null) { return(new OperateResult <string>("OPCServer未能正确初始化!")); } if (!_opcServer.IsConnected) { return(new OperateResult <string>("OPCServer连接错误!")); } #endregion string groupName = "AsyncWriteData"; OpcGroup group = _opcServer.FindGroupByName(groupName); if (group != null) { _opcServer.RemoveGroup(group); } group = _opcServer.AddGroup(groupName, 1, false); //1.添加组 IRequest request; #region 添加Item及写入Item if ((dataAddress.Contains(',')) && (OPCServerName == _RSLinxOPC)) //RSLinx 数组的写入 { //地址前缀,类型,起始位置,长度 } else //正常类型 { Guid[] handel = new[] { Guid.NewGuid() }; ItemResult[] itemResults = group.AddItems(new[] { dataAddress }, handel); //2.添加Items object[] objhandel = new object[] { handel[0] }; object _requestHandle = Guid.NewGuid().ToString("N"); //group.(objhandel, _requestHandle, ) } #endregion return(OperateResult.CreateSuccessResult("测试")); //没有获取到结果++++++++++++++++++++++++++ }
private bool CreateGroup() { try { // add our only working group _theGrp = _theSrv.AddGroup("OPCdotNET-Group", true, 500); //При создании группы тут читаем данные по всем тегам с сервера. OPCItemDef[] i = new OPCItemDef[12]; i[0] = new OPCItemDef(); i[1] = new OPCItemDef(); i[2] = new OPCItemDef(); i[3] = new OPCItemDef(); i[4] = new OPCItemDef(); i[5] = new OPCItemDef(); i[6] = new OPCItemDef(); i[7] = new OPCItemDef(); i[8] = new OPCItemDef(); i[9] = new OPCItemDef(); i[10] = new OPCItemDef(); i[11] = new OPCItemDef(); i[0].ItemID = OpcConsts.DispPress; i[1].ItemID = OpcConsts.DlinaSopr; i[2].ItemID = OpcConsts.Bits; i[3].ItemID = OpcConsts.PosadkaKol; i[4].ItemID = OpcConsts.SpeedPress; i[5].ItemID = OpcConsts.Instrument; i[6].ItemID = OpcConsts.BlinL; i[7].ItemID = OpcConsts.BlinR; i[8].ItemID = OpcConsts.DispPress1; i[9].ItemID = OpcConsts.DispPress2; i[10].ItemID = OpcConsts.DispPress3; i[11].ItemID = OpcConsts.ShowGraph; OPCItemResult[] resI = new OPCItemResult[4]; _theGrp.AddItems(i, out resI); // add event handler for data changes _theGrp.DataChanged += theGrp_DataChange; _theGrp.WriteCompleted += theGrp_WriteComplete; } catch (COMException e) { throw e; } return(true); }
private bool SetOneOPCTag(IOPCTag opcTag, VarEnum dataType) { var items = new OPCItemDef[1]; items[0] = new OPCItemDef(opcTag.FullName, true, 0, dataType); OPCItemResult[] addRslt; int rtc = OPCWriteGroup.AddItems(items, out addRslt); if (HRESULTS.Failed(rtc)) { return(false);// "Error at AddItem"; } var iHnd = new Int32[addRslt.Length]; for (int i = 0; i < addRslt.Length; ++i) { iHnd[i] = addRslt[i].HandleServer; } int[] err; var val = new object[addRslt.Length]; val[0] = opcTag.ObjectValue; rtc = OPCWriteGroup.Write(iHnd, val, out err); //string errTxt = "OK"; if (HRESULTS.Failed(rtc)) { return(false); //errTxt = srv.GetErrorString(rtc, 0); } // succeeded // check item error codes if (err.Any(HRESULTS.Failed)) { return(false); } OPCWriteGroup.RemoveItems(iHnd, out err); return(true); // return errTxt; }
private PLCCommand() { try { _opcSrv.Connect(StrSrvName); for (int i = 0; i < _arrGrps.Length; i++) { string strGrp = _arrGrps[i]; OpcGroup grp = _opcSrv.AddGroup(strGrp, true, 9600); grp.UpdateRate = 100; grp.Active = true; grp.PercentDeadband = 0; _opcGrpsDic.Add(strGrp, grp); string[] arrCurrentItems = _arrItems[i].Split(','); OPCItemDef[] opcItems = new OPCItemDef[arrCurrentItems.Length]; OPCItemResult[] opcResults = new OPCItemResult[arrCurrentItems.Length]; for (int j = 0; j < arrCurrentItems.Length; j++) { string strItemName = $"{StrItemId}.{strGrp}.{arrCurrentItems[j]}"; OPCItemDef item = new OPCItemDef(strItemName, true, opcResults.Length, System.Runtime.InteropServices.VarEnum.VT_BOOL); opcItems[j] = item; } Dictionary <string, OPCItemResult> oDic = new Dictionary <string, OPCItemResult>(); grp.AddItems(opcItems, out opcResults); for (int k = 0; k < opcResults.Length; k++) { oDic.Add(arrCurrentItems[k], opcResults[k]); } _opcResultsDic.Add(strGrp, oDic); } } catch (Exception ee) { LogImpl.Debug("错误" + ee.ToString()); } }
private string AddMyRefreshGroup1(OpcServer OpcSrv) { float deadBand = 90.0F; try { // create group with 2 sec update rate oGrp = OpcSrv.AddGroup("Line1", true, UpdateRate, ref deadBand, 0, 0); } catch { DBLogging.InsertLogs("Exception: AddMyRefreshGroup1", false, "Group could not be added", _connStr); return("Group could not be added"); } oGrp.DataChanged += new DataChangeEventHandler(DataChangedHandler); oGrp.AdviseIOPCDataCallback(); //client handle as item index items1[0] = new OPCItemDef(TagLPG_Bay01_RFID_Puched, true, 0, VarEnum.VT_BOOL); items1[1] = new OPCItemDef(TagLPG_WB_RFIDPunched, true, 1, VarEnum.VT_BOOL); items1[2] = new OPCItemDef(TagLPG_Bay01_LPGBatchComplete, true, 2, VarEnum.VT_BOOL); int rtc; rtc = oGrp.AddItems(items1, out addRslt1); if (HRESULTS.Failed(rtc)) { return("Error at AddItem"); } for (int i = 0; i < addRslt1.Length; ++i) { ItemValues1[i] = new OPCItemState(); } return(""); }
public void addItemToGrp() { try { if (TheGrp != null) { //String[] Items = new String[30]; for (int i = 0; i < ArryAdress.Length; i++) { if (ArryAdress[i] != "") { String stritem = ItemConfig + "," + ArryAdress[i] + "," + dataType + "," + ReadWriteType; ItemDefs[i] = new OPCItemDef(stritem, true, i + 1, System.Runtime.InteropServices.VarEnum.VT_EMPTY); } } TheGrp.AddItems(ItemDefs, out rItm); } } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.ToString()); } }
/// <summary> /// lov level function which creates an opc tag of specific COM type /// </summary> /// <param name="opcTag"></param> /// <param name="dataType"></param> /// <returns></returns> private bool CreateReadOPCTag(string opcTag, VarEnum dataType) { numberOfReadOPCTags++; opcReadTags.Add(opcTag); var items = new OPCItemDef[1]; items[0] = new OPCItemDef(opcTag, true, 0, dataType); OPCItemResult[] readResults; int rtc2 = OPCReadGroup.AddItems(items, out readResults); listOfOpcResults.Add(readResults); if (HRESULTS.Failed(rtc2)) { //srv.Disconnect(); { return(false); } } return(true); }
private PLCCommand2() { try { opcSrv.Connect(strSrvName); for (int i = 0; i < arrGrps.Length; i++) { string strGrp = arrGrps[i]; OpcGroup grp = opcSrv.AddGroup(strGrp, true, 9600); opcGrpsDic.Add(strGrp, grp); string[] arrCurrentItems = arrItems[i].Split(','); OPCItemDef[] opcItems = new OPCItemDef[arrCurrentItems.Length]; OPCItemResult[] opcResults = new OPCItemResult[arrCurrentItems.Length]; for (int j = 0; j < arrCurrentItems.Length; j++) { string strItemName = string.Format("{0}.{1}.{2}", strItemID, strGrp, arrCurrentItems[j]); OPCItemDef item = new OPCItemDef(strItemName, true, opcResults.Length, System.Runtime.InteropServices.VarEnum.VT_BOOL); opcItems[j] = item; } Dictionary <string, OPCItemResult> oDic = new Dictionary <string, OPCItemResult>(); grp.AddItems(opcItems, out opcResults); for (int k = 0; k < opcResults.Length; k++) { oDic.Add(arrCurrentItems[k], opcResults[k]); } opcResultsDic.Add(strGrp, oDic); } } catch (Exception ee) { LogImpl.Error("plc初始化:" + ee.StackTrace); } }
static void Main(string[] args) { string progID = args.Length > 0 ? args[0] : "Kepware.KEPServerEX.V5"; OpcServer opcServer = new OpcServer(); opcServer.Connect(progID); System.Threading.Thread.Sleep(500); // we are faster than some servers! OpcGroup opcGroup = opcServer.AddGroup("SampleGroup", false, 900); List <string> itemNames = new List <string>(); if (args.Length > 1) { for (int i = 1; i < args.Length; i++) { itemNames.Add(args[i]); } } else { itemNames.Add("Simulation Examples.Functions.Ramp1"); itemNames.Add("Simulation Examples.Functions.Random1"); } OpcItemDefinition[] opcItemDefs = new OpcItemDefinition[itemNames.Count]; for (int i = 0; i < opcItemDefs.Length; i++) { opcItemDefs[i] = new OpcItemDefinition(itemNames[i], true, i, VarEnum.VT_EMPTY); } opcGroup.AddItems(opcItemDefs, out OpcItemResult[] opcItemResult); if (opcItemResult == null) { Console.WriteLine("Error add items - null value returned"); return; } int[] serverHandles = new int[opcItemResult.Length]; for (int i = 0; i < opcItemResult.Length; i++) { if (HRESULTS.Failed(opcItemResult[i].Error)) { Console.WriteLine("AddItems - failed {0}", itemNames[i]); opcGroup.Remove(true); opcServer.Disconnect(); return; } else { serverHandles[i] = opcItemResult[i].HandleServer; } } opcGroup.DataChanged += OpcGroup_DataChanged; opcGroup.SetEnable(true); opcGroup.Active = true; Console.WriteLine("********** Press <Enter> to close **********"); Console.ReadLine(); opcGroup.DataChanged -= OpcGroup_DataChanged; opcGroup.Remove(true); opcServer.Disconnect(); }
/// <summary> /// Add unique OPC item to group /// </summary> /// <param name="opcID">OPC Item name</param> /// <returns>false - not added to OPC group, true - added successfully</returns> public bool AddOPCItem(string opcID) { string Function_Name = "AddOPCItem"; LogHelper.Trace(CLASS_NAME, Function_Name, string.Format("Function_Entered for datapoint {0}", opcID)); if (opcID.Trim() == "") { LogHelper.Debug(CLASS_NAME, Function_Name, "New Datapoint name is empty.Function_Exited with return value false."); return(false); } int currentSeq = 0; OPCDataItem opcDataItemVar = null; lock (m_opcDataDicObj) { if (m_opcDataIndexDic.ContainsKey(opcID)) { LogHelper.Info(CLASS_NAME, Function_Name, "Already the datapoint is added.Function_Exited"); return(true); } currentSeq = m_OPCDataSeqNum++; opcDataItemVar = new OPCDataItem(opcID, currentSeq); //add to internal map m_opcDataIndexDic.Add(opcID, currentSeq); m_opcDataDic.Add(currentSeq, opcDataItemVar); } if (!IsOPCServerConnected()) { LogHelper.Debug(CLASS_NAME, Function_Name, "OPC Server is not connect. Reconnect before adding datapoints."); return(false); } try { LogHelper.Trace(CLASS_NAME, Function_Name, "Connect to OPC Group"); //connect to OPC Group OPCItemDef[] aD = new OPCItemDef[1]; aD[0] = new OPCItemDef(opcID, true, currentSeq, VarEnum.VT_EMPTY); OPCItemResult[] arrRes; { lock (m_opcDataDicObj) { m_OPCGroup.AddItems(aD, out arrRes); } } if (arrRes == null) { LogHelper.Info(CLASS_NAME, Function_Name, "OPC Group AddItems() return null(cant not find handle server). Function Exited with return value false."); return(false); } if (arrRes[0].Error != HRESULTS.S_OK) { LogHelper.Info(CLASS_NAME, Function_Name, string.Format("OPC Group AddItems() return Error code({0}, not OK) for DataPoint = {1}. Function Exited with return value false.", arrRes[0].Error, opcID)); lock (m_opcDataDicObj) { m_OPCDataSeqNum--; m_opcDataIndexDic.Remove(opcID); m_opcDataDic.Remove(currentSeq); m_TotryQuene.Add(opcID); } return(false); } opcDataItemVar.HandleServer = arrRes[0].HandleServer; OPCACCESSRIGHTS itmAccessRights = arrRes[0].AccessRights; TypeCode itmTypeCode = VT2TypeCode(arrRes[0].CanonicalDataType); if ((itmAccessRights & OPCACCESSRIGHTS.OPC_READABLE) != 0) { int cancelID; lock (m_opcDataDicObj) { m_OPCGroup.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE, 7788, out cancelID); } } else { LogHelper.Info(CLASS_NAME, Function_Name, "Can find a handle server, but not have access right.Function Exited with return value false."); return(false); } } catch (COMException localException) { LogHelper.Error(CLASS_NAME, Function_Name, string.Format("{0} for DataPoint - {1}", localException.ToString(), opcID)); // if (localException.Message.Contains("The RPC server is unavailable.")) // Fixed issue - related to System Language, to avoid it used Error code if (localException.Message.Contains("0x800706BA")) { lock (m_opcDataDicObj) { m_opcSrvConnectFlag = false; } } return(false); } catch (Exception exception) { LogHelper.Error(CLASS_NAME, Function_Name, string.Format("{0} for DataPoint - {1}", exception.ToString(), opcID)); return(false); } LogHelper.Trace(CLASS_NAME, Function_Name, "Function_Exited"); return(true); }
public int Connect(string Servername) { Debug.WriteLine("Try to connect to : " + Servername); if (OpcSrv != null) { Debug.WriteLine("Already connected"); return(-1); } try { OpcSrv = new OpcServer(); OpcSrv.Connect(Servername); Debug.WriteLine("Connected to the server"); } catch (Exception ex) { Debug.WriteLine("Error connecting to the server"); OpcSrv = null; return(-2); } /* add the items here */ Items = new OPCItemDef[2]; // onlyone node can be selected Items[0] = new OPCItemDef("PLC1:PLC_PRG.doorbell", true, 0, typeof(void)); Items[1] = new OPCItemDef("PLC1:.DO_CARDS", true, 0, typeof(void)); Debug.WriteLine("Creating OPC group"); ItemHandles = null; errors = null; int updRate = 500; int clientHandle = 1; int rtc; OpcGrp = OpcSrv.AddGroup("", true, updRate, clientHandle, out rtc); if (HRESULTS.Failed(rtc)) { Debug.WriteLine("Error creating group"); return(rtc); } OPCItemResult[] rslt; rtc = OpcGrp.AddItems(Items, out rslt); if (HRESULTS.Failed(rtc)) { Debug.WriteLine("Error adding items to the OPC group"); return(rtc); } ItemHandles = new int[rslt.Length]; errors = new int[Items.Length]; Debug.WriteLine("Items added"); for (int i = 0; i < Items.Length; ++i) { ItemHandles[i] = rslt[i].HandleServer; errors[i] = rslt[i].Error; } return(0); }
public void Work() { theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! // add our only working group theGrp = theSrv.AddGroup("Group", false, 900); theTargGrp = theSrv.AddGroup("Target", false, 900); // add two items and save server handles itemDefs[0] = new OPCItemDef(itemA, true, 1, VarEnum.VT_EMPTY); itemDefs[1] = new OPCItemDef(itemB, true, 2, VarEnum.VT_EMPTY); // itemTarget[0] = new OPCItemDef(itemC, true, 1, VarEnum.VT_EMPTY); OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { AddTotextBox("OPC Tester: AddItems - some failed", textBox4); theGrp.Remove(true); theSrv.Disconnect(); return; } ; handlesSrv[0] = rItm[0].HandleServer; handlesSrv[1] = rItm[1].HandleServer; OPCItemResult[] rItmTarg; theTargGrp.AddItems(itemTarget, out rItmTarg); if (rItmTarg == null) { return; } if (HRESULTS.Failed(rItmTarg[0].Error)) { AddTotextBox("OPC Tester: AddItems - some failed", textBox4); theGrp.Remove(true); theSrv.Disconnect(); return; } ; handlesTargetSrv[0] = rItmTarg[0].HandleServer; //---------------------------------------------------------------------------------- // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; theGrp.Read(handlesSrv, 55667788, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); // asynch write theTargGrp.SetEnable(true); theTargGrp.Active = true; object[] itemValues = new object[1]; itemValues[0] = (int)450; theTargGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete); theTargGrp.Write(handlesTargetSrv, itemValues, 99887766, out CancelID, out aE); // some delay for asynch write-complete callback (simplification) Thread.Sleep(500); theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); }
public void PLCWrite() { try { theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! //add our only working group theGrp = theSrv.AddGroup("Group", false, 900); //add two items and save server handles itemDefs[0] = new OPCItemDef(itemA, true, 1, VarEnum.VT_EMPTY); itemDefs[1] = new OPCItemDef(itemB, true, 2, VarEnum.VT_EMPTY); OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { AddTotextBox("OPC Tester: AddItems - some failed", textBox4); theGrp.Remove(true); theSrv.Disconnect(); return; } ; if (handlesSrv[0] == 0) { handlesSrv[0] = rItm[0].HandleServer; handlesSrv[1] = rItm[1].HandleServer; } // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; Random rnd = new Random(); int transactionID = rnd.Next(1, 55667788); theGrp.Read(handlesSrv, transactionID, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); //theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); //theGrp.RemoveItems(handlesSrv, out aE); //теперь здесь //theGrp.Remove(false); } catch (Exception e) { SetText("Unexpected Error:" + e.Message); return; } }
public void Work() { /* try // disabled for debugging * { */ theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! // add our only working group theGrp = theSrv.AddGroup("OPCCSharp-Group", false, 900); // add two items and save server handles itemDefs[0] = new OPCItemDef(itemA, true, 1234, VarEnum.VT_EMPTY); itemDefs[1] = new OPCItemDef(itemB, true, 5678, VarEnum.VT_EMPTY); OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { Console.WriteLine("OPC Tester: AddItems - some failed"); theGrp.Remove(true); theSrv.Disconnect(); return; } ; handlesSrv[0] = rItm[0].HandleServer; handlesSrv[1] = rItm[1].HandleServer; // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; theGrp.Read(handlesSrv, 55667788, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); // asynch write object[] itemValues = new object[2]; itemValues[0] = (int)1111111; itemValues[1] = (double)2222.2222; theGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete); theGrp.Write(handlesSrv, itemValues, 99887766, out CancelID, out aE); // some delay for asynch write-complete callback (simplification) Thread.Sleep(500); // disconnect and close Console.WriteLine("************************************** hit to close..."); Console.ReadLine(); theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); theGrp.RemoveItems(handlesSrv, out aE); theGrp.Remove(false); theSrv.Disconnect(); theGrp = null; theSrv = null; /* } * catch( Exception e ) * { * Console.WriteLine( "EXCEPTION : OPC Tester " + e.ToString() ); * return; * } */ }
static void Main(string[] args) { string progID = args.Length > 0 ? args[0] : "Kepware.KEPServerEX.V5"; OpcServer opcServer = new OpcServer(); opcServer.Connect(progID); System.Threading.Thread.Sleep(500); // we are faster than some servers! OpcGroup opcGroup = opcServer.AddGroup("SampleGroup", false, 900); List <string> itemNames = new List <string>(); if (args.Length > 1) { for (int i = 1; i < args.Length; i++) { itemNames.Add(args[i]); } } else { itemNames.Add("Simulation Examples.Functions.Ramp1"); itemNames.Add("Simulation Examples.Functions.Random1"); } OpcItemDefinition[] opcItemDefs = new OpcItemDefinition[itemNames.Count]; for (int i = 0; i < opcItemDefs.Length; i++) { opcItemDefs[i] = new OpcItemDefinition(itemNames[i], true, i, VarEnum.VT_EMPTY); } opcGroup.AddItems(opcItemDefs, out OpcItemResult[] opcItemResult); if (opcItemResult == null) { Console.WriteLine("Error add items - null value returned"); return; } int[] serverHandles = new int[opcItemResult.Length]; for (int i = 0; i < opcItemResult.Length; i++) { if (HRESULTS.Failed(opcItemResult[i].Error)) { Console.WriteLine("AddItems - failed {0}", itemNames[i]); opcGroup.Remove(true); opcServer.Disconnect(); return; } else { serverHandles[i] = opcItemResult[i].HandleServer; } } opcGroup.SetEnable(true); opcGroup.Active = true; bool result = opcGroup.Read(OPCDATASOURCE.OPC_DS_CACHE, serverHandles, out OpcItemState[] states); foreach (OpcItemState s in states) { if (HRESULTS.Succeeded(s.Error)) { Console.WriteLine(" {0}: {1} (Q:{2} T:{3})", s.HandleClient, s.DataValue, s.Quality, DateTime.FromFileTime(s.TimeStamp)); } else { Console.WriteLine(" {0}: ERROR = 0x{1:x} !", s.HandleClient, s.Error); } } opcGroup.Remove(true); opcServer.Disconnect(); }
//[MethodImplAttribute(MethodImplOptions.Synchronized)]//Синхронизировать метод private bool Connect() { lock (lockConn) { DateTime dt1 = DateTime.Now; try { bool result; //создадим соединение с БД SERVERSTATUS status; _opcsrv.GetStatus(out status); if (_cntconn == 0 || status == null || status.eServerState != OPCSERVERSTATE.OPC_STATUS_RUNNING) { _opcsrv.Connect(_progid, _host); _opcsrv.GetStatus(out status); if (status != null && status.eServerState == OPCSERVERSTATE.OPC_STATUS_RUNNING) { try { _opcgrp = _opcsrv.AddGroup(_grpname, false, _interval); _opcgrp.HandleClient = 0; int _cnt = _maps.GetLength(0); _serverhandles = new int[_cnt]; _vals = new object[_cnt]; _errs = new object[_cnt]; OPCItemDef[] _opcitmsdef = new OPCItemDef[_cnt]; for (int i = 0; i < _cnt; i++) { _opcitmsdef[i] = new OPCItemDef(_maps[i, 1], true, i, VarEnum.VT_EMPTY); } _opcgrp.AddItems(_opcitmsdef, out _opcitms); for (int i = 0; i < _cnt; i++) { _serverhandles[i] = _opcitms[i].HandleServer; } _opcgrp.SetEnable(true); _opcgrp.Active = true; _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : T(сек)=" + (DateTime.Now - dt1).Seconds + ", нап. груп. - " + _maps.GetLength(0)); _cntconn++; //Увеличим счётчик активных соединений _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : Connect - Активных соединений: " + _cntconn); result = true; } catch (Exception e) { _server.LogWrite(LogType.ERROR, e.Message); result = false; } } else { result = false; } } else { _cntconn++; //Увеличим счётчик активных соединений result = true; } return(result); } finally { _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : T(сек)=" + (DateTime.Now - dt1).Seconds + ", время на откытие соединения"); } } }
public void Work() { /* try // disabled for debugging * { */ theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! // add our only working group theGrp = theSrv.AddGroup("OPCCSharp-Group", false, timeref); if (sendtags > tags.Length) { sendtags = tags.Length; } var itemDefs = new OPCItemDef[tags.Length]; for (var i = 0; i < tags.Length; i++) { itemDefs[i] = new OPCItemDef(tags[i], true, i, VarEnum.VT_EMPTY); } OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { Console.WriteLine("OPC Tester: AddItems - some failed"); theGrp.Remove(true); theSrv.Disconnect(); return; } ; var handlesSrv = new int[itemDefs.Length]; for (var i = 0; i < itemDefs.Length; i++) { handlesSrv[i] = rItm[i].HandleServer; } currentValues = new Single[itemDefs.Length]; // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; theGrp.Read(handlesSrv, 55667788, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); while (webSend == "yes") { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; context.Response.AddHeader("Access-Control-Allow-Origin", "*"); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseStringG); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); } // disconnect and close Console.WriteLine("************************************** hit <return> to close..."); Console.ReadLine(); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); theGrp.RemoveItems(handlesSrv, out aE); theGrp.Remove(false); theSrv.Disconnect(); theGrp = null; theSrv = null; /* } * catch( Exception e ) * { * Console.WriteLine( "EXCEPTION : OPC Tester " + e.ToString() ); * return; * } */ }
static void Main(string[] args) { /*create array of readable Tags*/ var Tags = new List <OPCClientItem>(); Tags.Add(new OPCClientItem() { Name = ".test", ClientHanle = 1 }); OpcServer server = new OpcServer(); try { int transactionID = new Random().Next(1024, 65535); int cancelID = 0; int updateRate = 1000; /*connect to the OPC Server and check it's state*/ server.Connect("Matrikon.OPC.Simulation.1"); var serverStatus = new SERVERSTATUS(); server.GetStatus(out serverStatus); if (serverStatus.eServerState == OPCSERVERSTATE.OPC_STATUS_RUNNING) { /*create group of items*/ OpcGroup group = server.AddGroup("Group1", true, updateRate); group.ReadCompleted += group_ReadCompleted; List <OPCItemDef> items = new List <OPCItemDef>(); Tags.ToList() .ForEach(x => items.Add(new OPCItemDef(x.Name, true, x.ClientHanle, VarEnum.VT_EMPTY))); /* add items and collect their attributes*/ OPCItemResult[] itemAddResults = null; group.AddItems(items.ToArray(), out itemAddResults); for (int i = 0; i < itemAddResults.Length; i++) { OPCItemResult itemResult = itemAddResults[i]; OPCClientItem tag = Tags[i]; tag.ServerHandle = itemResult.HandleServer; tag.AccessRight = (itemResult.AccessRights == OPCACCESSRIGHTS.OPC_READABLE) ? OPCClientItem.EAccessRight.ReadOnly : OPCClientItem.EAccessRight.ReadAndWrite; } ; /*Refresh items in group*/ // group.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE, transactionID, out cancelID); /*Async read data for the group items*/ int[] serverHandles = new int[Tags.Count]; for (int i = 0; i < Tags.Count; i++) { serverHandles[i] = Tags[i].ServerHandle; } ; OPCItemState[] itemsStateResult = null; /*sync read*/ group.Read(OPCDATASOURCE.OPC_DS_DEVICE, serverHandles, out itemsStateResult); Console.WriteLine("Sync read:"); for (int i = 0; i < itemsStateResult.Length; i++) { OPCItemState itemResult = itemsStateResult[i]; Console.WriteLine(" -> item:{0}; value:{1}; timestamp{2}; qualituy:{3}", Tags[i].Name, itemResult.DataValue.ToString(), itemResult.TimeStamp, itemResult.Quality); } ; /*sync write*/ object[] values = new object[Tags.Count]; int[] resultErrors = new int[Tags.Count]; values[0] = (object)256; group.Write(serverHandles, values, out resultErrors); /*async read*/ group.Read(serverHandles, transactionID, out cancelID, out resultErrors); /*wait for a while befor remove group to process async event*/ System.Threading.Thread.Sleep(3000); /*the group must be removed !!! */ group.Remove(true); } ; } finally { server.Disconnect(); server = null; GC.Collect(); }; Console.ReadKey(); }
/// <summary> /// 初始化 /// </summary> /// <param name="serverPKID"></param> /// <param name="address"></param> /// <param name="updateRate"></param> /// <param name="deviceTagParams"></param> /// <param name="callback"></param> private void Initial(Int64 serverPKID, string address, int updateRate, List <DeviceTagParam> deviceTagParams, DataChangeEventHandler callback) { pkid = serverPKID; #region 初始化参数 string ip = (address == "") ? CBaseData.LocalIP : address; string serverName = address; string[] addes = address.Split('|', ';'); //分号隔开,前面是IP地址,后面是OPCServer名称 if (addes.Length > 1) { ip = addes[0]; if ((ip.ToLower() == "local") || (ip.ToLower() == "localhost") || (ip.ToLower() == ".")) { ip = CBaseData.LocalIP; //本机IP } serverName = addes[1]; } else //默认为本机 { ip = CBaseData.LocalIP; } IPAddress remote; IPAddress.TryParse(ip, out remote); ServerIP = remote; OPCServerName = serverName; Callback = callback; //设置回调函数 #endregion DeviceTags = deviceTagParams; //标签 #region 自定义协议 CustomProtocol = (addes.Length >= 3) ? addes[2] : ""; //自定义协议 ProtocolVariable = (addes.Length >= 4) ? addes[3] : ""; //自定义协议 #endregion #region OPC 设定 string error = String.Empty; _opcServer = OpcServers.FirstOrDefault(c => c.PKID == serverPKID); if ((_opcServer == null) || (!_opcServer.IsConnected)) { _opcServer = OPCConnector.ConnectOPCServer(serverPKID, ip, serverName, ref error); } else { EventLogger.Log($"【{serverPKID}】OPC服务器已连接"); } if (_opcServer != null && _opcServer.IsConnected) { List <Guid> subHandels = new List <Guid>(); //Handel List <string> subItemIds = new List <string>(); //标签地址 List <Guid> normalHandels = new List <Guid>(); //Handel List <string> normalItemIds = new List <string>(); //标签地址 if (subHandels.Count > 0) //添加订阅 { OpcGroup subGroup = _opcServer.AddGroup("GP" + serverPKID + "S", updateRate, true); //订阅的Group subGroup.AddItems(subItemIds.ToArray(), subHandels.ToArray()); subGroup.DataChanged -= OPCDataChanged; subGroup.DataChanged += OPCDataChanged; } if (normalHandels.Count > 0) //添加正常 { OpcGroup normalGroup = _opcServer.AddGroup("GP" + serverPKID + "N", updateRate, false); //正常的Group normalGroup.AddItems(normalItemIds.ToArray(), normalHandels.ToArray()); } EventLogger.Log($"【{serverPKID}】OPC服务器连接成功。"); } else { error = $"【{serverPKID}】OPC服务器连接失败,具体为:" + error; EventLogger.Log(error); } OpcServers.Add(_opcServer); //将OPCServer添加到系统中 #endregion }
/// <summary> /// 异步写数据 /// </summary> /// <param name="dataAddress"></param> /// <param name="dataValue"></param> /// <returns></returns> public OperateResult AsyncWriteData(string dataAddress, string dataValue) { #region 检验 if (string.IsNullOrEmpty(dataAddress) || string.IsNullOrEmpty(dataValue)) { return(new OperateResult("传入的参数都不能为空")); } if (_opcServer == null) { return(new OperateResult("OPCServer未能正确初始化!")); } if (!_opcServer.IsConnected) { return(new OperateResult("OPCServer连接错误!")); } #endregion string groupName = "AsyncWriteData"; OpcGroup group = _opcServer.FindGroupByName(groupName); if (group != null) { _opcServer.RemoveGroup(group); } group = _opcServer.AddGroup(groupName, 1, false); //添加组 string datavalue = dataValue.Split('|')[0]; WriteCompleteEventHandler writeFinishHandler = WriteFinishHandler; IRequest request; #region 添加Item及写入Item if ((dataAddress.Contains(',')) && (OPCServerName == _RSLinxOPC)) //RSLinx 数组的写入 { //地址前缀,类型,起始位置,长度 #region RSLinx 数组及地址串 string[] tags = dataAddress.Split(','); if (tags.Length < 3) { return(new OperateResult("RSLinx 地址错误")); } string mainAddress = tags[0]; //主地址 string type = tags[1]; //类型 int beginIndex = SafeConverter.SafeToInt(tags[2]); //开始索引 int length = SafeConverter.SafeToInt(tags[3]); //长度 string endStr = (tags.Length > 4) ? tags[4] : ""; Guid[] handels = new Guid[length]; string[] address = new string[length]; string[] values = new string[length]; for (int i = 0; i < length; i++) { handels[i] = Guid.NewGuid(); values[i] = datavalue.Length > i ? datavalue[i].ToString() : "0"; //默认为0 if (type.ToLower() == "array") //数组型 { address[i] = mainAddress + "[" + (i + beginIndex).ToString() + "]"; } else //连续地址 { address[i] = mainAddress + type + (i + beginIndex).ToString() + endStr; } } ItemResult[] itemResults = group.AddItems(address, handels); ItemValue[] itemValues = new ItemValue[length]; for (int i = 0; i < length; i++) { itemValues[i] = new ItemValue(itemResults[i]) { Value = values[i] }; } group.AsyncWrite(itemValues, handels, writeFinishHandler, out request); #endregion } else //正常类型 { Guid[] handel = new[] { Guid.NewGuid() }; ItemResult[] itemResults = group.AddItems(new[] { dataAddress }, handel); ItemValue itemValue = new ItemValue(itemResults[0]) { Value = datavalue, }; group.AsyncWrite(new ItemValue[] { itemValue }, handel, writeFinishHandler, out request); } #endregion return(OperateResult.CreateSuccessResult()); }
private void button2_Click_1(object sender, EventArgs e) { lerTag = false; rtc = 0; oGrp = null; OpcServer srv2 = new OpcServer(); srv.Connect("Localhost", servidorOpc); //Cadastra os subcampos da lista na tela com as variáveis do array de resultados itensValor = new string[tags.Count]; for (int i = 0; i < tags.Count; i++) { itensValor[i] = i.ToString(); lv_tagList.Items[i].SubItems.Add(itensValor[i]); } if (servidorOpc == "") { MessageBox.Show("Nenhum servidor OPC cadastrado"); return; } float deadBand = 0.0F; try { //Adicionar um grupo (pasta em que o tag será lido): oGrp = srv.AddGroup("Grp1", true, 500, ref deadBand, 0, 0); } catch { MessageBox.Show("Erro ao tentar adicionar grupo OPC.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } //Configurar item para leitura (array) items = new OPCItemDef[tags.Count]; //string tagsArray[55] = tags.ToArray; for (int i = 0; i < tags.Count; i++) { items[i] = new OPCItemDef(tags[i], true, 0, System.Runtime.InteropServices.VarEnum.VT_BSTR); } addRslt = new OPCItemResult[tags.Count]; //Adicionar este(s) ite(ns) ao grupo criado anteriormente: rtc = oGrp.AddItems(items, out addRslt); if (rtc != 0) { //Se desse erro, o valor de RTC será diferente de 0, aqui dentro poderia ter algum tratamento } iHnd = new Int32[tags.Count]; for (int i = 0; i < tags.Count; i++) { iHnd[i] = addRslt[i].HandleServer; } //Esse aqui é o evento em paralelo a execução do botão, que faz a leitura contínua do tag:] //O seu código está no método logo abaixo, chamado bwLer_DoWork lerTag = true; if (bwLer.IsBusy == false) { bwLer.RunWorkerAsync(); } else { bwLer.CancelAsync(); bwLer.RunWorkerAsync(); } }