public static int GetOpcServerAllItem(string opcSerHostIp, Guid opcSerGuid, out List <DriveNodeEntity> driveNotes) { int rtc = -1; driveNotes = null; try { OpcServer opcSer = new OpcServer(); rtc = opcSer.Connect(new Host(opcSerHostIp), opcSerGuid); if (!HRESULTS.Succeeded(rtc)) { return(rtc); } //获取组 if (GetOPCServerStatus(opcSer, out rtc)) { return(GetOpcServerAllItem(opcSer, out driveNotes)); } } catch (Exception err) { NLogHelper.ExceptionInfo(err, "GetDriveNodes error :{0}", err.Message); } return(rtc); }
public static int GetOpcServerAllItem(OpcServer opcSer, out List <DriveNodeEntity> driveNodes) { int rtc = -1; driveNodes = null; BrowseTree browseTress = new BrowseTree(opcSer); rtc = browseTress.CreateTree(); if (HRESULTS.Succeeded(rtc)) { TreeNode[] root = browseTress.Root(); if (root != null) { driveNodes = new List <DriveNodeEntity>(); // driveNotes 固定两层 ,没有使用递归 转换 foreach (TreeNode item in root) { DriveNodeEntity driveNodeTemp = CloneDriveNode(item, DriveNodeModel.OPCGroup); foreach (TreeNode itemChild in item.Nodes) { driveNodeTemp.childNode.Add(CloneDriveNode(itemChild, DriveNodeModel.OPCItem)); } driveNodes.Add(driveNodeTemp); } return(0); } } return(rtc); }
/// <summary> /// 启动函数 /// </summary> /// <returns></returns> public IResult init() { OPCItemState rslt; OPCDATASOURCE dsrc = OPCDATASOURCE.OPC_DS_DEVICE; ILE.LEResult res = new LEResult(); ///将所有数据点放进RefreshGroup容器 foreach (ILE.IDataPoint po in this.ItemPoints) { if (po.business_code == "01" | po.business_code == "02") //如果是采集完成数与异常数,要把初始值拿到用于扣减 { int j = mySyncIOGroup.Read(dsrc, po.Item_name, out rslt); po.InitVal = rslt.DataValue.ToString(); } int i = myRefreshGroup.Add(po.Item_name); if (!HRESULTS.Succeeded(i)) { res.Result = false; res.ExtMessage = "新增监测点失败"; this.server.Disconnect(); this.server = null; return(res); } } //Action action = new Action(Monitor); //action.BeginInvoke(null, null); thread.Start(); res.Result = true; return(res); }
// event handler: called if any item in group has changed values protected void theGrp_DataChange(object sender, DataChangeEventArgs e) { Trace.WriteLine("theGrp_DataChange id=" + e.transactionID.ToString() + " me=0x" + e.masterError.ToString("X")); foreach (OPCItemState s in e.sts) { if (s.HandleClient != itmHandleClient) // only one client handle { continue; } Trace.WriteLine(" item error=0x" + s.Error.ToString("X")); if (HRESULTS.Succeeded(s.Error)) { Trace.WriteLine(" val=" + s.DataValue.ToString()); txtItemValue.Text = s.DataValue.ToString(); // update screen txtItemQual.Text = OpcGroup.QualityToString(s.Quality); txtItemTimeSt.Text = DateTime.FromFileTime(s.TimeStamp).ToString(); } else { txtItemValue.Text = "ERROR 0x" + s.Error.ToString("X"); txtItemQual.Text = "error"; txtItemTimeSt.Text = "error"; } } }
public int GetNodeValue(string nodeStrGuid, out object nodeValue) { int rtc = -1; nodeValue = null; try { OPCDATASOURCE opcDataSource = OPCDATASOURCE.OPC_DS_DEVICE; OPCItemState opcItemState = new OPCItemState(); DriveNodeEntity driveNode = allOPCItemNodes.Find(p => nodeStrGuid.Equals(p.nodeId)); ItemDef itemdef = syncIOGroup.Item(driveNode.nodeName); rtc = syncIOGroup.Read(opcDataSource, itemdef, out opcItemState); if (HRESULTS.Succeeded(rtc)) { nodeValue = opcItemState.DataValue; //txtItemQuality.Text = syncIOGroup.GetQualityString(opcItemState.Quality); //txtTimeStamp.Text = DateTime.FromFileTime(opcItemState.TimeStamp).ToString(); } } catch (Exception ex) { NLogHelper.ExceptionInfo(ex, "GetNodeValue param:'{1}' ,exception:{0}", ex.Message, nodeStrGuid); } return(rtc); }
/// <summary> /// 添加状态点到ItemPoints /// </summary> /// <param name="point"></param> public IResult AddItem(ILE.IDataPoint point) { //此处把配置文件中的数据点名拆出来,放进模型 string[] pms = point.parameter.Split(','); point.Item_name = pms[2]; ILE.LEResult res = new LEResult(); try { HaiGrang.Package.OpcNetApiChs.DaNet.RefreshEventHandler reh = new HaiGrang.Package.OpcNetApiChs.DaNet.RefreshEventHandler(this.DataChangeHandler); myRefreshGroup = new RefreshGroup(server, 500, reh); mySyncIOGroup = new SyncIOGroup(this.server); int i = myRefreshGroup.Add(point.Item_name); if (!HRESULTS.Succeeded(i)) { res.Result = false; res.ExtMessage = "新增监测点[" + point.dataPoint_name + "]失败"; this.server.Disconnect(); this.server = null; return(res); } myRefreshGroup.Remove(point.Item_name); //如果成功添加了,说明数据点可用,此时要拿出来,不能直接启动数据点。 this.ItemPoints.Add(point); res.Result = true; } catch (Exception exc) { res.Result = false; res.ExtMessage = "新增监测点失败"; } return(res); }
public bool Start() { try { bool bRet = InitOPCService(); if (!bRet) { return(false); } if (null == opcSerNodes || null == allOPCItemNodes) { NLogHelper.DefalutError("OPCBUSService.Start error,未配置opc服务"); return(false); } opcSer.Connect(host, guid); syncIOGroup = new SyncIOGroup(opcSer); refreshEventHandler = new RefreshEventHandler(RefreshEvent); refreshGroup = new RefreshGroup(opcSer, 10, refreshEventHandler); foreach (DriveNodeEntity item in allOPCItemNodes) { int iRet = refreshGroup.Add(item.nodeName); if (HRESULTS.Succeeded(iRet)) { Console.WriteLine(" true " + iRet); } } return(true); } catch (Exception ex) { NLogHelper.ExceptionInfo(ex, "Start StartOPCService exception: {0}", ex.Message); return(false); } }
public object[] GetItemProperties(string itemID, params int[] propertyIDs) { int count = propertyIDs.Length; if (count < 1) { return(null); } IntPtr ptrDat; IntPtr ptrErr; if (HRESULTS.Succeeded(_opcProp.GetItemProperties(itemID, count, propertyIDs, out ptrDat, out ptrErr))) { object[] propertiesData = new object[count]; for (int i = 0; i < count; i++) { if (Marshal.ReadInt32(ptrErr) == 0) { propertiesData[i] = Marshal.GetObjectForNativeVariant(ptrDat); } ptrErr += 4; ptrDat += 16; } Marshal.FreeCoTaskMem(ptrDat); Marshal.FreeCoTaskMem(ptrErr); return(propertiesData); } return(null); }
public string WriteStringItem(String tagName, String value) { ItemDef ItemData = new ItemDef(); ItemData = readGroup.Item(tagName); OPCItemState state = new OPCItemState(); int rtc = readGroup.Write(ItemData, value); if (HRESULTS.Succeeded(rtc)) // read from OPC server successful { if (state != null) { if (HRESULTS.Succeeded(state.Error)) // item read successful { return("Success"); } else // the item could not be read { // hf.LogException("Item cannot be readable: " + tagName); return("ERROR"); } } else // State not valid { // hf.LogException("Item cannot be readable due to state: " + tagName); return("ERROR"); } } else // OPC server read error { // hf.LogException("Item cannot be readable due to OPC: " + tagName); return("ERROR"); } }
public void AsynchReadListenerForPVL(object sender, OPCDA.NET.RefreshEventArguments arg) { OPCDA.NET.OPCItemState res = arg.items[0].OpcIRslt; try { if (arg.Reason == OPCDA.NET.RefreshEventReason.DataChanged) { // data changes if (HRESULTS.Succeeded(res.Error)) { OPCDA.NET.ItemDef opcItemDef = (OPCDA.NET.ItemDef)arg.items.GetValue(0); string[] iterateItemName = opcItemDef.OpcIDef.ItemID.Split(new Char[] { '.' }); if (iterateItemName.Length == 3) { // string machineCode = iterateItemName[1].ToString(); string command = iterateItemName[2].ToString(); if (command.Equals(OpcTags.PVL_Deck_Pallet_Present)) { bool resValue = bool.Parse(res.DataValue.ToString()); pallet.Dispatcher.BeginInvoke(new InvokeDelegate(SetPalletPresentStatus), resValue); } } } } } catch (Exception errMsg) { Console.WriteLine(errMsg.Message); } }
// ------------------------ IOPCDataCallback --------------- void IOPCDataCallback.OnDataChange( int dwTransid, int hGroup, int hrMasterquality, int hrMastererror, int dwCount, IntPtr phClientItems, IntPtr pvValues, IntPtr pwQualities, IntPtr pftTimeStamps, IntPtr ppErrors) { Trace.WriteLine("OpcGroup.OnDataChange"); if ((dwCount == 0) || (hGroup != state.HandleClient)) { return; } int count = (int)dwCount; int runh = (int)phClientItems; int runv = (int)pvValues; int runq = (int)pwQualities; int runt = (int)pftTimeStamps; int rune = (int)ppErrors; DataChangeEventArgs e = new DataChangeEventArgs(); e.transactionID = dwTransid; e.groupHandleClient = hGroup; e.masterQuality = hrMasterquality; e.masterError = hrMastererror; e.sts = new OPCItemState[count]; for (int i = 0; i < count; i++) { e.sts[i] = new OPCItemState(); e.sts[i].Error = Marshal.ReadInt32((IntPtr)rune); rune += 4; e.sts[i].HandleClient = Marshal.ReadInt32((IntPtr)runh); runh += 4; if (HRESULTS.Succeeded(e.sts[i].Error)) { short vt = Marshal.ReadInt16((IntPtr)runv); if (vt == (short)VarEnum.VT_ERROR) { e.sts[i].Error = Marshal.ReadInt32((IntPtr)(runv + 8)); } e.sts[i].DataValue = Marshal.GetObjectForNativeVariant((IntPtr)runv); e.sts[i].Quality = Marshal.ReadInt16((IntPtr)runq); e.sts[i].TimeStamp = Marshal.ReadInt64((IntPtr)runt); } runv += DUMMY_VARIANT.ConstSize; runq += 2; runt += 8; } if (DataChanged != null) { DataChanged(this, e); } }
// ------------------------ IOPCSyncIO --------------- public bool Read(OPCDATASOURCE src, int[] arrHSrv, out OPCItemState[] arrStat) { arrStat = null; int count = arrHSrv.Length; IntPtr ptrStat; IntPtr ptrErr; int hresult = ifSync.Read(src, count, arrHSrv, out ptrStat, out ptrErr); if (HRESULTS.Failed(hresult)) { Marshal.ThrowExceptionForHR(hresult); } int runErr = (int)ptrErr; int runStat = (int)ptrStat; if ((runErr == 0) || (runStat == 0)) { Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT); } arrStat = new OPCItemState[count]; for (int i = 0; i < count; i++) { // WORKAROUND !!! arrStat[i] = new OPCItemState(); arrStat[i].Error = Marshal.ReadInt32((IntPtr)runErr); runErr += 4; arrStat[i].HandleClient = Marshal.ReadInt32((IntPtr)runStat); if (HRESULTS.Succeeded(arrStat[i].Error)) { short vt = Marshal.ReadInt16((IntPtr)(runStat + 16)); if (vt == (short)VarEnum.VT_ERROR) { arrStat[i].Error = Marshal.ReadInt32((IntPtr)(runStat + 24)); } arrStat[i].TimeStamp = Marshal.ReadInt64((IntPtr)(runStat + 4)); arrStat[i].Quality = Marshal.ReadInt16((IntPtr)(runStat + 12)); arrStat[i].DataValue = Marshal.GetObjectForNativeVariant((IntPtr)(runStat + 16)); DUMMY_VARIANT.VariantClear((IntPtr)(runStat + 16)); } else { arrStat[i].DataValue = null; } runStat += 32; } Marshal.FreeCoTaskMem(ptrStat); Marshal.FreeCoTaskMem(ptrErr); return(hresult == HRESULTS.S_OK); }
//----------------------------------------------------------------- // this function handles data change callbacks due to the periodic refresh request // by the group. // The data is assiociated with the items by the client handle, that is specif(ied // in the add item function call. private void DataChangedHandler(object sender, DataChangeEventArgs e) { try { int i, hnd; // OPC_QUALITY_STATUS qs; // DateTime dt; for (i = 0; i < e.sts.Length; ++i) { if (HRESULTS.Succeeded(e.sts[i].Error)) { hnd = e.sts[i].HandleClient; OPCItemDef tagItemDef = items1[hnd]; // int _tagValue = Convert.ToInt32(e.sts[i].DataValue); if (tagItemDef != null) { if (tagItemDef.ItemID.Contains(TagLPG_WB_RFIDPunched) && Convert.ToInt32(e.sts[i].DataValue) == 1) // Start { String RFIDCardNumber = _OPCB0.ReadStringItem(TagLPG_WB_CardData); if (!string.IsNullOrEmpty(RFIDCardNumber)) { string WBWeight = _OPCB0.ReadStringItem(TagLPG_WB_Val); if (!string.IsNullOrEmpty(WBWeight)) { string cmdexePath = @"C:\Users\Administrator\Documents\visual studio 2013\Projects\TLAS\TLAS.WBconsole\bin\DebugTLAS.WBconsole.exe"; //notice the quotes around the below string... string cmdArguments = String.Format("{0},{1}", RFIDCardNumber, WBWeight); ProcessStartInfo psi = new ProcessStartInfo(cmdexePath, cmdArguments); Process p = new Process(); p.StartInfo = psi; p.Start(); } } } if (tagItemDef.ItemID.Contains(TagLPG_Bay01_RFID_Puched) && Convert.ToInt32(e.sts[i].DataValue) == 1) // Start { } if (tagItemDef.ItemID.Contains(TagLPG_Bay01_LPGBatchComplete) && Convert.ToInt32(e.sts[i].DataValue) == 1) // Start { } } } } } catch (Exception exe) { // DBLogging.InsertLogs("Exception: Line1", false, exe.Message + " " + exe.InnerException, _connStr); } }
/// <summary> /// It is used to subscribe data change notification from OPC server /// </summary> /// <param name="sender">sender</param> /// <param name="e">inlcude all updated OPC data point</param> private void OPCGrp_DataChange(object sender, DataChangeEventArgs e) { string Function_Name = "opcGrp_DataChange"; LogHelper.Trace(CLASS_NAME, Function_Name, "Function_Entered"); try { lock (m_opcDataDicObj) { foreach (OPCItemState s in e.sts) { if (m_opcDataDic.ContainsKey(s.HandleClient)) { if (HRESULTS.Succeeded(s.Error)) { if (s.Quality == OPC_GOODQUALITY) { LogHelper.Debug(CLASS_NAME, Function_Name, "DataValue = " + s.DataValue.ToString()); m_opcDataDic[s.HandleClient].DataValue = s.DataValue; } else { // m_needToReCreateGrp2Srv = true; if (s.Quality == OPC_NOTCONNECTEDQUALITY) // means the datapoint Quality is "NOT_CONNECT" { m_needToReCreateGrp2Srv = true; // next time plotting, will re-create group to OpcSrv1. if (m_opcDataDic[s.HandleClient].DataValue.ToString().CompareTo(OPC_NOTCONNECTED) != 0) //if last value was not "NOTCONNECTED" { LogHelper.Info(CLASS_NAME, Function_Name, "DataPoint:" + m_opcDataDic[s.HandleClient].ID + " is not connected! "); m_opcDataDic[s.HandleClient].DataValue = OPC_NOTCONNECTED; } } else { LogHelper.Info(CLASS_NAME, Function_Name, "For DataPoint: " + m_opcDataDic[s.HandleClient].ID + ", OPCItemState quality not good, Quality = " + s.Quality); m_opcDataDic[s.HandleClient].DataValue = OPC_BLANK_DATAVALUE; } } LogHelper.Debug(CLASS_NAME, Function_Name, "The new value for datapoint[" + m_opcDataDic[s.HandleClient].ID + "] is " + m_opcDataDic[s.HandleClient].DataValue.ToString()); } } } } } catch (Exception localException) { LogHelper.Error(CLASS_NAME, Function_Name, localException); } LogHelper.Trace(CLASS_NAME, Function_Name, "Function_Exited"); }
/// <summary> /// Read values /// </summary> /// <param name="dataSource">Read data source</param> /// <param name="serverHandles">Server handles of OPC items to read</param> /// <param name="itemStates">OPC Item states array</param> /// <returns>Bool</returns> public bool Read(OPCDATASOURCE dataSource, int[] serverHandles, out OpcItemState[] itemStates) { ThrowIfDisposed(); itemStates = null; int hResult = opcSyncIO.Read(dataSource, serverHandles.Length, serverHandles, out IntPtr ptrStat, out IntPtr ptrErr); if (HRESULTS.Failed(hResult)) { Marshal.ThrowExceptionForHR(hResult); } if ((ptrErr == IntPtr.Zero) || (ptrStat == IntPtr.Zero)) { Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT); } try { itemStates = new OpcItemState[serverHandles.Length]; for (int i = 0; i < serverHandles.Length; i++) { itemStates[i] = new OpcItemState { Error = Extensions.ReadInt32(ptrErr, i), HandleClient = Marshal.ReadInt32(ptrStat, i * sizeOPCREADRESULT) }; if (HRESULTS.Succeeded(itemStates[i].Error)) { short vt = Marshal.ReadInt16(ptrStat, i * sizeOPCREADRESULT + 16); if (vt == (short)VarEnum.VT_ERROR) { itemStates[i].Error = Marshal.ReadInt32(ptrStat, i * sizeOPCREADRESULT + 24); } itemStates[i].TimeStamp = Marshal.ReadInt64(ptrStat, i * sizeOPCREADRESULT + 4); itemStates[i].Quality = Marshal.ReadInt16(ptrStat, i * sizeOPCREADRESULT + 12); itemStates[i].DataValue = Marshal.GetObjectForNativeVariant(IntPtr.Add(ptrStat, i * sizeOPCREADRESULT + 16)); Extensions.VariantClear(IntPtr.Add(ptrStat, i * sizeOPCREADRESULT + 16)); } else { itemStates[i].DataValue = null; } } } finally { Marshal.FreeCoTaskMem(ptrStat); Marshal.FreeCoTaskMem(ptrErr); } return(hResult == HRESULTS.S_OK); }
public void TestSucceeded01() { //Test Procedure Call bool b = HRESULTS.Succeeded(HRESULTS.OPC_E_INVALIDITEMID); //Post Condition Check Assert.IsFalse(b); b = HRESULTS.Succeeded(HRESULTS.S_OK); //Post Condition Check Assert.IsTrue(b); }
// event handler: called if any item in group has changed values protected void theGrp_DataChange(object sender, DataChangeEventArgs e) { //Trace.WriteLine("theGrp_DataChange id=" + e.transactionID + " me=0x" + e.masterError.ToString("X")); foreach (OPCItemState s in e.sts.Where(s => s.HandleClient == _itmHandleClient)) { Trace.WriteLine(" item error=0x" + s.Error.ToString("X")); if (HRESULTS.Succeeded(s.Error)) { Trace.WriteLine(" val=" + s.DataValue); } } }
public DCO(string pamater) { this.ItemPoints = new List <IDataPoint>(); thread = new System.Threading.Thread(new System.Threading.ThreadStart(Monitor)); ILE.LEResult res = new LEResult(); //用这个数据点的配置,启动OPC连接,正因如此,此处注意,无法支持一台设备存在两个OPC_server地址 string[] pmts = pamater.Split(','); strMachine = pmts[0]; //服务PC的IP地址 string strServerName = pmts[1]; //服务名 string strPointName = pmts[2]; //数据点地址名 OpcServerBrowser myBrowser = new OpcServerBrowser(strMachine); try { myBrowser.CLSIDFromProgID(strServerName, out SrvGuid); //获取OPC服务组件的注册ID,获取不到会直接报错 } catch { res.ExtMessage = "服务不存在或无法访问!"; res.Result = false; //return res; throw new Exception("服务不存在或无法访问"); } Host host = new Host(strMachine); server = new OpcServer(); host.Domain = strMachine.ToUpper(); host.HostName = strMachine; host.UserName = ""; host.Password = ""; int rtc = server.Connect(strMachine, SrvGuid); try { HRESULTS.Succeeded(rtc); //this.label1.Text = "连接成功!"; //守护线程 } catch (Exception exc) { res.Result = false; res.ExtMessage = exc.Message; this.server.Disconnect(); this.server = null; throw new Exception("服务连接失败"); } }
public void theGrp_WriteComplete(object sender, WriteCompleteEventArgs e) { Console.WriteLine("WriteComplete event: gh={0} id={1} me={2}", e.groupHandleClient, e.transactionID, e.masterError); foreach (OPCWriteResult r in e.res) { if (HRESULTS.Succeeded(r.Error)) { Console.WriteLine(" ih={0} e={1}", r.HandleClient, r.Error); } else { Console.WriteLine(" ih={0} ERROR=0x{1:x} !", r.HandleClient, r.Error); } } }
private static void OpcGroup_DataChanged(object sender, DataChangeEventArgs e) { Console.WriteLine("DataChanged Group:{0} TrID:{1} E:{2} Q:{3}", e.GroupHandleClient, e.TransactionID, e.MasterError, e.MasterQuality); foreach (OpcItemState s in e.ItemStates) { 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); } } }
public void theGrp_ReadComplete(object sender, ReadCompleteEventArgs e) { Console.WriteLine("ReadComplete event: gh={0} id={1} me={2} mq={3}", e.groupHandleClient, e.transactionID, e.masterError, e.masterQuality); foreach (OPCItemState s in e.sts) { if (HRESULTS.Succeeded(s.Error)) { Console.WriteLine(" ih={0} v={1} q={2} t={3}", s.HandleClient, s.DataValue, s.Quality, s.TimeStamp); } else { Console.WriteLine(" ih={0} ERROR=0x{1:x} !", s.HandleClient, s.Error); } } }
public bool Read(OPCDATASOURCE src, int[] arrHSrv, out OPCItemState[] arrStat) { IntPtr ptr; IntPtr ptr2; arrStat = null; int length = arrHSrv.Length; int hresultcode = this.ifSync.Read(src, length, arrHSrv, out ptr, out ptr2); if (HRESULTS.Failed(hresultcode)) { Marshal.ThrowExceptionForHR(hresultcode); } int num3 = (int)ptr2; int num4 = (int)ptr; if ((num3 == 0) || (num4 == 0)) { Marshal.ThrowExceptionForHR(-2147467260); } arrStat = new OPCItemState[length]; for (int i = 0; i < length; i++) { arrStat[i] = new OPCItemState(); arrStat[i].Error = Marshal.ReadInt32((IntPtr)num3); num3 += 4; arrStat[i].HandleClient = Marshal.ReadInt32((IntPtr)num4); if (HRESULTS.Succeeded(arrStat[i].Error)) { if (Marshal.ReadInt16((IntPtr)(num4 + 0x10)) == 10) { arrStat[i].Error = Marshal.ReadInt32((IntPtr)(num4 + 0x18)); } arrStat[i].TimeStamp = Marshal.ReadInt64((IntPtr)(num4 + 4)); arrStat[i].Quality = Marshal.ReadInt16((IntPtr)(num4 + 12)); arrStat[i].DataValue = Marshal.GetObjectForNativeVariant((IntPtr)(num4 + 0x10)); DUMMY_VARIANT.VariantClear((IntPtr)(num4 + 0x10)); } else { arrStat[i].DataValue = null; } num4 += 0x20; } Marshal.FreeCoTaskMem(ptr); Marshal.FreeCoTaskMem(ptr2); return(hresultcode == 0); }
void IOPCDataCallback.OnDataChange( int dwTransid, int hGroup, int hrMasterquality, int hrMastererror, int dwCount, IntPtr phClientItems, IntPtr pvValues, IntPtr pwQualities, IntPtr pftTimeStamps, IntPtr ppErrors) { Trace.WriteLine($"{nameof(OpcGroup)}.{nameof(IOPCDataCallback.OnDataChange)}, transID:{dwTransid}, count:{dwCount}, thread ID:{System.Threading.Thread.CurrentThread.ManagedThreadId}"); if ((dwCount == 0) || (hGroup != stateHandleClient)) { return; } DataChangeEventArgs eventArgs = new DataChangeEventArgs { TransactionID = dwTransid, GroupHandleClient = hGroup, MasterQuality = hrMasterquality, MasterError = hrMastererror, ItemStates = new OpcItemState[dwCount] }; for (int i = 0; i < dwCount; i++) { eventArgs.ItemStates[i] = new OpcItemState { Error = Extensions.ReadInt32(ppErrors, i), HandleClient = Extensions.ReadInt32(phClientItems, i) }; if (HRESULTS.Succeeded(eventArgs.ItemStates[i].Error)) { // Test if native variant is VT_ERROR short vt = Marshal.ReadInt16(pvValues, i * Extensions.NativeVariantSize); if (vt == (short)VarEnum.VT_ERROR) { eventArgs.ItemStates[i].Error = Marshal.ReadInt32(pvValues, (i * Extensions.NativeVariantSize) + 8); } eventArgs.ItemStates[i].DataValue = Extensions.GetObjectForNativeVariant(pvValues, i); eventArgs.ItemStates[i].Quality = Extensions.ReadInt16(pwQualities, i); eventArgs.ItemStates[i].TimeStamp = Extensions.ReadInt64(pftTimeStamps, i); } } dataChanged?.Invoke(this, eventArgs); }
/// <summary> /// This function reads a analog double tag value from OPC, read will be from Device, Return ERROR in case of any error /// </summary> /// <param name="tagName"></param> /// <returns></returns> public int ReadBooleanItem(String tagName) { ItemDef ItemData; ItemData = readGroup.Item(tagName); OPCItemState state = new OPCItemState(); // Read from device OPCDATASOURCE dsrc = OPCDATASOURCE.OPC_DS_DEVICE; int rtc = readGroup.Read(dsrc, ItemData, out state); if (HRESULTS.Succeeded(rtc)) // read from OPC server successful { if (state != null) { if (HRESULTS.Succeeded(state.Error)) // item read successful { if (Convert.ToBoolean(state.DataValue) == true) { return(1); } else { return(0); } } else // the item could not be read { // hf.LogException("Item cannot be readable: " + tagName); return(-10000); } } else // State not valid { // hf.LogException("Item cannot be readable due to State: " + tagName); return(-10000); } } else // OPC server read error { // hf.LogException("Item cannot be readable due to OPC: " + tagName); return(-10000); } }
void IOPCDataCallback.OnReadComplete(int dwTransid, int hGroup, int hrMasterquality, int hrMastererror, int dwCount, IntPtr phClientItems, IntPtr pvValues, IntPtr pwQualities, IntPtr pftTimeStamps, IntPtr ppErrors) { if ((dwCount != 0) && (hGroup == this.state.HandleClient)) { int num = dwCount; int num2 = (int)phClientItems; int num3 = (int)pvValues; int num4 = (int)pwQualities; int num5 = (int)pftTimeStamps; int num6 = (int)ppErrors; ReadCompleteEventArgs e = new ReadCompleteEventArgs(); e.transactionID = dwTransid; e.groupHandleClient = hGroup; e.masterQuality = hrMasterquality; e.masterError = hrMastererror; e.sts = new OPCItemState[num]; for (int i = 0; i < num; i++) { e.sts[i] = new OPCItemState(); e.sts[i].Error = Marshal.ReadInt32((IntPtr)num6); num6 += 4; e.sts[i].HandleClient = Marshal.ReadInt32((IntPtr)num2); num2 += 4; if (HRESULTS.Succeeded(e.sts[i].Error)) { if (Marshal.ReadInt16((IntPtr)num3) == 10) { e.sts[i].Error = Marshal.ReadInt32((IntPtr)(num3 + 8)); } e.sts[i].DataValue = Marshal.GetObjectForNativeVariant((IntPtr)num3); e.sts[i].Quality = Marshal.ReadInt16((IntPtr)num4); e.sts[i].TimeStamp = Marshal.ReadInt64((IntPtr)num5); } num3 += DUMMY_VARIANT.ConstSize; num4 += 2; num5 += 8; } if (this.ReadCompleted != null) { this.ReadCompleted(this, e); } } }
public IGroup AddGroup(string name, short id, int updateRate, float deadBand, bool active) { if (IsClosed) { Connect(); } if (!_metaGroups.Exists(x => x.ID == id)) { _metaGroups.Add(new MetaGroup { ID = id, Name = name, UpdateRate = updateRate, DeadBand = deadBand, Active = active }); } if (_opcServer == null) { return(null); } GCHandle hDeadband, hTimeBias; hDeadband = GCHandle.Alloc(deadBand, GCHandleType.Pinned); hTimeBias = GCHandle.Alloc(0, GCHandleType.Pinned); Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID; int serverId, svrUpdateRate; object grpObj; if (HRESULTS.Succeeded(_opcServer.AddGroup(name, active, updateRate, id, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), 0x0, out serverId, out svrUpdateRate, ref iidRequiredInterface, out grpObj))) { IConnectionPointContainer pIConnectionPointContainer = (IConnectionPointContainer)grpObj; Guid iid = typeof(IOPCDataCallback).GUID; IConnectionPoint pIConnectionPoint; pIConnectionPointContainer.FindConnectionPoint(ref iid, out pIConnectionPoint); int dwCookie; OPCGroup grp = new OPCGroup(name, id, svrUpdateRate, deadBand, active, grpObj, this); _groups.Add(serverId, grp); pIConnectionPoint.Advise(grp, out dwCookie); //OPCGroups.Add(serverId, grp); return(grp); } else { return(null); } }
// event handler: called if any item in group has changed values protected void theGrp_DataChange(object sender, DataChangeEventArgs e) { Trace.WriteLine("theGrp_DataChange id=" + e.transactionID.ToString() + " me=0x" + e.masterError.ToString("X")); string strTemp = ""; string[] name = { "192_168_1_210.Alarm.tmAlarmState", "192_168_1_210.Temperature.tmTemp1_Set" }; int i = 0; string value = ""; foreach (OPCItemState s in e.sts) { if (s.HandleClient != itmHandleClient) // only one client handle { continue; } Trace.WriteLine(" item error=0x" + s.Error.ToString("X")); if (HRESULTS.Succeeded(s.Error)) { Trace.WriteLine(" val=" + s.DataValue.ToString()); // value += name[i]+":" + s.DataValue.ToString()+";\n"; itemsValue[i][1] = s.DataValue.ToString(); i++; // string qulity = OpcGroup.QualityToString(s.Quality); // string timestamp = DateTime.FromFileTime( s.TimeStamp ).ToString(); // SetValue(value); // SetQulity(qulity); // SetTimestamp(timestamp); //txtItemValue.Text = temp; // update screen //txtItemQual.Text = OpcGroup.QualityToString( s.Quality ); //txtItemTimeSt.Text = DateTime.FromFileTime( s.TimeStamp ).ToString(); } else { txtItemValue.Text = "ERROR 0x" + s.Error.ToString("X"); txtItemQual.Text = "error"; txtItemTimeSt.Text = "error"; } } }
public void theGrp_ReadComplete(object sender, ReadCompleteEventArgs e) { //Console.WriteLine("ReadComplete event: gh={0} id={1} me={2} mq={3}", e.groupHandleClient, e.transactionID, e.masterError, e.masterQuality); //AddTotextBox("\r\nReadComplete event: gh = " + e.groupHandleClient + " id = " + e.transactionID + " me = " + e.masterError + " mq = " + e.masterQuality, textBox4); SetText("\r\nReadComplete event: gh = " + e.groupHandleClient + " id = " + e.transactionID + " me = " + e.masterError + " mq = " + e.masterQuality); foreach (OPCItemState s in e.sts) { if (HRESULTS.Succeeded(s.Error)) { //Console.WriteLine(" ih={0} v={1} q={2} t={3}", s.HandleClient, s.DataValue, s.Quality, s.TimeStamp); //AddTotextBox("\r\n ih = " + s.HandleClient + " v = " + s.DataValue + " q = " + s.Quality + " t = " + s.TimeStamp, textBox4); SetText("\r\n ih = " + s.HandleClient + " v = " + s.DataValue + " q = " + s.Quality + " t = " + s.TimeStamp); } else { //Console.WriteLine(" ih={0} ERROR=0x{1:x} !", s.HandleClient, s.Error); //AddTotextBox("\r\n ih = " + s.HandleClient + " ERROR = 0x" + s.Error, textBox4); SetText("\r\n ih = " + s.HandleClient + " ERROR = 0x" + s.Error); } } }
public bool RemoveItems(params ITag[] items) { int count = items.Length; int[] arrSvr = new int[count]; for (int i = 0; i < count; i++) { ITag item = items[i]; //if (item == null) // return false; arrSvr[i] = item.Address.Start; _server.RemoveItemIndex(item.GetTagName()); _items.Remove(item); } IntPtr ptrErr; int result = _itemMgt.RemoveItems(count, arrSvr, out ptrErr); Marshal.FreeCoTaskMem(ptrErr); return(HRESULTS.Succeeded(result)); }
public void theGrp_WriteComplete(object sender, WriteCompleteEventArgs e) { //Console.WriteLine("WriteComplete event: gh={0} id={1} me={2}", e.groupHandleClient, e.transactionID, e.masterError); //AddTotextBox("\r\nWriteComplete event: gh = " + e.groupHandleClient + " id = " + e.transactionID + " me = " + e.masterError, textBox4); SetText("\r\nWriteComplete event: gh = " + e.groupHandleClient + " id = " + e.transactionID + " me = " + e.masterError); foreach (OPCWriteResult r in e.res) { if (HRESULTS.Succeeded(r.Error)) { //Console.WriteLine(" ih={0} e={1}", r.HandleClient, r.Error); //AddTotextBox("\r\n ih = " + r.HandleClient + " e = " + r.Error, textBox4); SetText("\r\n ih = " + r.HandleClient + " e = " + r.Error); } else { //Console.WriteLine(" ih={0} ERROR=0x{1:x} !", r.HandleClient, r.Error); //AddTotextBox("\r\n ih = " + r.HandleClient + " ERROR = 0x" + r.Error, textBox4); SetText("\r\n ih = " + r.HandleClient + " ERROR = 0x" + r.Error); } } }