public void Remove(bool p_Force) { if (m_CallbackPoint != null) { if (m_CallbackCookie != 0) { m_CallbackPoint.Unadvise(m_CallbackCookie); m_CallbackCookie = 0; } Marshal.ReleaseComObject(m_CallbackPoint); m_CallbackPoint = null; } m_PointContainer = null; m_IfItems = null; m_IfSync = null; m_IfAsync = null; if (m_IfMgt != null) { Marshal.ReleaseComObject(m_IfMgt); m_IfMgt = null; } if (m_IfServer != null) { if (!m_State.Public) { m_IfServer.RemoveGroup(m_State.HandleServer, p_Force); } m_IfServer = null; } m_State.HandleServer = 0; }
internal Group(DaServer server, int clientId, int serverId, string name, int updateRate, IOPCItemMgt group) { _server = server; ClientId = clientId; ServerId = serverId; Name = name; _group = group; UpdateRate = updateRate; _syncIo = (IOPCSyncIO)group; _groupManagement = (IOPCGroupStateMgt)group; try { _asyncIo = (IOPCAsyncIO2)group; } catch (InvalidCastException) { } try { _connectionPointContainer = (IConnectionPointContainer)group; } catch (InvalidCastException) { } }
/*------------------------------------------------------ * Add OPC Item * * (ret) True OK * False NG * ------------------------------------------------------*/ public bool AddItem(string[] ItemName, int[] ClientHd, int[] ServerHd) { int iItemCount = ItemName.Length; OPCITEMDEF[] itemDef = new OPCITEMDEF[iItemCount]; OPCITEMRESULT itemResult; IntPtr ppResult; IntPtr ppErrors; IntPtr posRes; int[] errors = new int[iItemCount]; int i; for (i = 0; i < iItemCount; i++) { itemDef[i].szItemID = ItemName[i]; itemDef[i].bActive = 1; itemDef[i].hClient = ClientHd[i]; } try { switch (m_OpcdaVer) { case DEF_OPCDA.VER_30: m_OPCItem = (IOPCItemMgt)m_OPCGroup2; break; case DEF_OPCDA.VER_10: case DEF_OPCDA.VER_20: default: m_OPCItem = (IOPCItemMgt)m_OPCGroup; break; } m_OPCItem.AddItems(iItemCount, itemDef, out ppResult, out ppErrors); Marshal.Copy(ppErrors, errors, 0, iItemCount); posRes = ppResult; for (i = 0; i < iItemCount; i++) { itemResult = (OPCITEMRESULT)Marshal.PtrToStructure(posRes, typeof(OPCITEMRESULT)); if (errors[i] == 0) { ServerHd[i] = itemResult.hServer; } Marshal.DestroyStructure(posRes, typeof(OPCITEMRESULT)); // 06/09/20 for VS2005 posRes = (IntPtr)(posRes.ToInt32() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMRESULT))); // 06/09/20 for VS2005 //posRes = new IntPtr(posRes.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT))); } Marshal.FreeCoTaskMem(ppResult); Marshal.FreeCoTaskMem(ppErrors); } catch (Exception exc) { MessageBox.Show(exc.ToString(), "AddItem"); return(false); } // erase itemDef; // erase errors; return(true); }
public void internalAdd(int[] biasTime, float[] percentDeadband, int localeID) { Type typGrpMgt = typeof(IOPCGroupStateMgt); Guid guidGrpTst = typGrpMgt.GUID; object objtemp; try { ifServer.AddGroup(state.Name, state.Active, state.UpdateRate, state.HandleClient, null, null, 0, out state.HandleServer, out state.UpdateRate, ref guidGrpTst, out objtemp); if (objtemp == null) { Marshal.ThrowExceptionForHR(HRESULTS.E_NOINTERFACE); } ifMgt = (IOPCGroupStateMgt)objtemp; ifItems = (IOPCItemMgt)ifMgt; ifSync = (IOPCSyncIO)ifMgt; } catch (Exception e) { System.Diagnostics.Debug.Print(e.Message); throw e; } }
public void Dispose() { int count = _items.Count; int[] arrSvr = new int[count]; for (int i = 0; i < count; i++) { arrSvr[i] = _items[i].Address.Start; } _items.Clear(); IntPtr ptrErr; try { int result = _itemMgt.RemoveItems(count, arrSvr, out ptrErr); Marshal.FreeCoTaskMem(ptrErr); if (_grpObj != null) { Marshal.ReleaseComObject(_grpObj); } } catch (Exception err) { } _grpObj = null; _itemMgt = null; _grpState = null; _async = null; _sync = null; }
private void getinterfaces() { this.ifItems = (IOPCItemMgt)this.ifMgt; this.ifSync = (IOPCSyncIO)this.ifMgt; this.ifAsync = (IOPCAsyncIO2)this.ifMgt; this.cpointcontainer = (IConnectionPointContainer)this.ifMgt; }
public void RegInServer(OPCServer server) { //this.server = server; int TimeBias = 0; Guid riid = typeof(IOPCItemMgt).GUID; uint hClientGroup = 1; uint dwLCID = 2; object pUnknown; try { server.Server.AddGroup(this.Name, System.Convert.ToInt32(this.Enabled), this.UpdateRate, hClientGroup, ref TimeBias, ref this.fDeadband, dwLCID, out m_hGroup, out fUpdateRate, riid, out pUnknown); m_pItemMgt = (IOPCItemMgt)pUnknown; } catch (System.Exception ex) { Console.Out.WriteLine(ex.Message); } try { RegItemsInServer(); } catch (ServerException ex) { string msg; //Запрашиваем у сервера текст ошибки, соответствующий текущему HRESULT server.Server.GetErrorString(ex.HResult, 2, out msg); Console.Out.WriteLine(msg, "Ошибка"); } }
private void GetInterfaces() { m_IfItems = (IOPCItemMgt)m_IfMgt; m_IfSync = (IOPCSyncIO)m_IfMgt; m_IfAsync = (IOPCAsyncIO2)m_IfMgt; m_PointContainer = (System.Runtime.InteropServices.ComTypes.IConnectionPointContainer)m_IfMgt; }
public ConnectionGroup(string opcServer, string opcHost, List <OPCBaseChannel> channels) { Type t; if (opcHost.ToLowerInvariant() == "localhost") { t = Type.GetTypeFromProgID(opcServer); } else { t = Type.GetTypeFromProgID(opcServer, opcHost); } server = (IOPCServer)Activator.CreateInstance(t); int groupClientId = 1; int groupId; int updateRate = 0; object group_obj; Guid tmp_guid = typeof(IOPCItemMgt).GUID; server.AddGroup("fscdg", 1, updateRate, groupClientId, new IntPtr(), new IntPtr(), 0, out groupId, out updateRate, ref tmp_guid, out group_obj); group = (IOPCItemMgt)group_obj; IntPtr addResult = new IntPtr(); IntPtr addErrors = new IntPtr(); OPCITEMDEF[] items = new OPCITEMDEF[2]; for (int i = 0; i < channels.Count; i++) { items[0].bActive = 1; items[0].szItemID = channels[i].OpcChannel; items[0].hClient = channels[i].GetHashCode(); group.AddItems(1, items, out addResult, out addErrors); } for (int i = 0; i < channels.Count; i++) { IntPtr pos = new IntPtr(addResult.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)) * i); OPCITEMRESULT res = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT)); bool readOnly = (res.dwAccessRights & OPC_WRITEABLE) != OPC_WRITEABLE; channels[i].Connect(this, res.hServer, readOnly); } Marshal.FreeCoTaskMem(addResult); Marshal.FreeCoTaskMem(addErrors); addResult = IntPtr.Zero; addErrors = IntPtr.Zero; IConnectionPointContainer cpc = (IConnectionPointContainer)group_obj; IConnectionPoint cp; Guid dataCallbackGuid = typeof(IOPCDataCallback).GUID; cpc.FindConnectionPoint(ref dataCallbackGuid, out cp); callback = new OPCDataCallback(channels); cp.Advise(callback, out callbackCookie); }
public OPCGroup(string name, short Id, int updateRate, float deadband, bool active, object grpObj, OPCReader reader) { _name = name; _Id = Id; _updateRate = updateRate; _deadBand = deadband; _isActive = active; _grpObj = grpObj; _plcReader = reader; _server = reader.Parent; _itemMgt = (IOPCItemMgt)_grpObj; //_grpState = (IOPCGroupStateMgt2)_grpObj; _async = (IOPCAsyncIO3)_grpObj; _sync = (IOPCSyncIO2)_grpObj; }
/// <summary> /// 释放对象 /// </summary> public void Dispose() { try { if (dwCookie != 0) { ConnectionPoint.Unadvise(dwCookie); dwCookie = 0; } } catch (Exception) { dwCookie = 0; } Marshal.ReleaseComObject(ConnectionPoint); ConnectionPoint = null; Marshal.ReleaseComObject(connectionPointContainer); connectionPointContainer = null; if (oPCSyncIO != null) { Marshal.ReleaseComObject(oPCSyncIO);//减与指定的 COM 对象关联的运行时可调用包装器 (RCW) 的引用计数。 oPCSyncIO = null; } if (oPCAsyncIO != null) { Marshal.ReleaseComObject(oPCAsyncIO);//减与指定的 COM 对象关联的运行时可调用包装器 (RCW) 的引用计数。 oPCAsyncIO = null; } if (oPCGroupStateMgt != null) { Marshal.ReleaseComObject(oPCGroupStateMgt); oPCGroupStateMgt = null; } if (oPCItemMgt != null) { Marshal.ReleaseComObject(oPCItemMgt); oPCItemMgt = null; } if (ObjGroup != null) { Marshal.ReleaseComObject(ObjGroup); ObjGroup = null; } }
public void DeleteItems(string[] id, int[] ItemHANDLES) { int m_Res = 0; try { int dwCount = ItemHANDLES.Length; IntPtr pErrors; IOPCItemMgt m_pIItemMgt = (IOPCItemMgt)pUnknown; //add item m_Res = m_pIItemMgt.RemoveItems(dwCount, ItemHANDLES, out pErrors); if (m_Res < 0) { throw new Exception("Server: Delete Items failed hr= " + m_Res.ToString()); } int runErr = (int)pErrors; if (runErr == 0) { throw new Exception("Server: Delete Items failed hr= " + unchecked ((int)0x80004004).ToString()); } int error; for (int i = 0; i < dwCount; i++) { error = Marshal.ReadInt32((IntPtr)runErr); if (error < 0) { //parent.PrintMessage("Server: Delete Item " + id[i] + " is failed hr =" + error.ToString(), MessageStyl.error); runErr += 4; } } Marshal.FreeCoTaskMem(pErrors); } catch (Exception e) { //parent.PrintMessage(e.Message, MessageStyl.error); throw e; } }
public void Remove(bool bForce) { try { int num; if (this.callbackcpoint != null) { if (this.callbackcookie != 0) { this.callbackcpoint.Unadvise(this.callbackcookie); this.callbackcookie = 0; } num = Marshal.ReleaseComObject(this.callbackcpoint); this.callbackcpoint = null; } this.cpointcontainer = null; this.ifItems = null; this.ifSync = null; this.ifAsync = null; if (this.ifMgt != null) { num = Marshal.ReleaseComObject(this.ifMgt); this.ifMgt = null; } if (this.ifServer != null) { if (!this.state.Public) { this.ifServer.RemoveGroup(this.state.HandleServer, bForce); } this.ifServer = null; } this.state.HandleServer = 0; } catch (Exception exception) { LogHelper.Error("OPCTrendLib.OPCData.OpcGroup", "Remove", exception); Console.WriteLine(exception.ToString()); } }
public void Remove(bool bForce) { ifItems = null; ifSync = null; if (!(ifMgt == null)) { int rc = Marshal.ReleaseComObject(ifMgt); ifMgt = null; } if (!(ifServer == null)) { if (!state.Public) { ifServer.RemoveGroup(state.HandleServer, bForce); } ifServer = null; } state.HandleServer = 0; }
internal Group(DAServer server, int clientId, int serverId, string name, int updateRate, IOPCItemMgt @group) { this.server = server; ClientId = clientId; ServerId = serverId; Name = name; this.@group = @group; UpdateRate = updateRate; syncIO = (IOPCSyncIO) @group; groupManagement = (IOPCGroupStateMgt) @group; try { asyncIO = (IOPCAsyncIO2) @group; } catch (InvalidCastException) { } try { connectionPointContainer = (IConnectionPointContainer) @group; } catch (InvalidCastException) { } }
// -------------------------- private --------------------- private void getinterfaces() { ifItems = (IOPCItemMgt) ifMgt; ifSync = (IOPCSyncIO) ifMgt; ifAsync = (IOPCAsyncIO2) ifMgt; cpointcontainer = (UCOMIConnectionPointContainer) ifMgt; }
/// <summary> adds an IOPCItemStateMgt-object to given group </summary> /// <param name="itemsActive"> determines which item is active </param> /// <param name="itemIDs"> determines the itemIDs </param> /// <param name="itemTypes"> the datatypes of the items </param> /// <param name="itmClntHndls"> the clientHandles of the items </param> /// <param name="itmSrvHndls"> the serverHandles given from the opc-server </param> /// <exception cref="Exception">throws and forwards any exception (with short error description)</exception> public void addOPCItems(bool[] itemsActive, // 激活 string[] itemIDs, // item id short[] itemTypes, // item的数据类型 int[] itmClntHndls, // item的client句柄数组 out int[] itmSrvHndls) // item的server句柄数组 { // initialize arguments. Guid iid = Guid.Empty; //number of elements we can add int numberOfItems = itmClntHndls.Length; OPCITEMDEF[] Itemdefs = new OPCITEMDEF[numberOfItems]; IntPtr ppResults = IntPtr.Zero; IntPtr ppErrors = IntPtr.Zero; string strDummy = ""; if (m_disposed) { throw new NullReferenceException("This object has been disposed!"); } // Init item server handles itmSrvHndls = new int[numberOfItems]; try { // Get Item interface m_OPCItem = (IOPCItemMgt)m_OPCGroupStateMgt; if (m_OPCItem == null) { strDummy = "Could not get the interface 'IOPCItemMgt'!"; throw new Exception(strDummy); } // Now add the items for (int i = 0; i < numberOfItems; i++) { // Accesspath not needed Itemdefs[i].szAccessPath = ""; // AddItem Active, so OnDataChange will come in an active group for this item Itemdefs[i].bActive = Convert.ToInt32(itemsActive[i]); // We want to get the items as string Itemdefs[i].vtRequestedDataType = itemTypes[i]; // "BinaryLargeOBject" not needed by SimaticNet OPC Server Itemdefs[i].dwBlobSize = 0; // no blob Itemdefs[i].pBlob = IntPtr.Zero; Itemdefs[i].hClient = itmClntHndls[i]; Itemdefs[i].szItemID = itemIDs[i]; } // Adding items to the Group m_OPCItem.AddItems(numberOfItems, Itemdefs, out ppResults, out ppErrors); if (ppResults == IntPtr.Zero) { strDummy = "The server did not return a result array."; throw new Exception(strDummy); } if (ppErrors == IntPtr.Zero) { strDummy = "The server did not return an arror array."; throw new Exception(strDummy); } //Evaluate return ErrorCodes to exclude possible Errors int[] errors = new int[numberOfItems]; Marshal.Copy(ppErrors, errors, 0, numberOfItems); OPCITEMRESULT[] result = new OPCITEMRESULT[numberOfItems]; IntPtr pos = ppResults; for (int dwCount = 0; dwCount < numberOfItems; dwCount++) { try { if (errors[dwCount] != 0) { strDummy = "At least one item is not added."; throw new Exception(strDummy); // 抛出异常 } // Item was added succesfully result[dwCount] = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT)); itmSrvHndls[dwCount] = result[dwCount].hServer; } catch (Exception) { // Item was not added throw; } pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT))); } m_itmServerHandles = new int[numberOfItems]; m_itmServerHandles = itmSrvHndls; // Free allocated COM-ressouces Marshal.FreeCoTaskMem(ppResults); Marshal.FreeCoTaskMem(ppErrors); } catch (Exception) { // Free allocated COM-ressouces Marshal.FreeCoTaskMem(ppResults); Marshal.FreeCoTaskMem(ppErrors); throw; } }
public void Remove(bool bForce) { ifItems = null; ifSync = null; if (!(ifMgt == null)) { int rc = Marshal.ReleaseComObject(ifMgt); ifMgt = null; } if (!(ifServer == null)) { if (!state.Public) ifServer.RemoveGroup(state.HandleServer, bForce); ifServer = null; } state.HandleServer = 0; }
public void internalAdd(int[] biasTime, float[] percentDeadband, int localeID) { Type typGrpMgt = typeof(IOPCGroupStateMgt); Guid guidGrpTst = typGrpMgt.GUID; object objtemp; try { ifServer.AddGroup(state.Name, state.Active, state.UpdateRate, state.HandleClient, null, null, 0, out state.HandleServer, out state.UpdateRate, ref guidGrpTst, out objtemp); if (objtemp == null) Marshal.ThrowExceptionForHR(HRESULTS.E_NOINTERFACE); ifMgt = (IOPCGroupStateMgt)objtemp; ifItems = (IOPCItemMgt)ifMgt; ifSync = (IOPCSyncIO)ifMgt; } catch (Exception e) { System.Diagnostics.Debug.Print(e.Message); throw e; } }
public void Remove( bool bForce ) { if( ! (callbackcpoint == null) ) { if( callbackcookie != 0 ) { callbackcpoint.Unadvise( callbackcookie ); callbackcookie = 0; } int rc = Marshal.ReleaseComObject( callbackcpoint ); callbackcpoint = null; } cpointcontainer = null; ifItems = null; ifSync = null; ifAsync = null; if( ! (ifMgt == null) ) { int rc = Marshal.ReleaseComObject( ifMgt ); ifMgt = null; } if( ! (ifServer == null) ) { if( ! state.Public ) ifServer.RemoveGroup( state.HandleServer, bForce ); ifServer = null; } state.HandleServer = 0; }
/// <summary> /// Removes the items from the group that have been marked as deleted. /// </summary> public void RemoveItems() { // count the number of items to remove. List <GroupItem> itemsToRemove = new List <GroupItem>(); lock (Lock) { List <GroupItem> itemsToKeep = new List <GroupItem>(); for (int ii = 0; ii < m_items.Count; ii++) { if (m_items[ii].Deleted && m_items[ii].Created) { itemsToRemove.Add(m_items[ii]); continue; } itemsToKeep.Add(m_items[ii]); } m_items = itemsToKeep; } // check if nothing to do. if (itemsToRemove.Count == 0) { return; } // build list of items to remove. int count = itemsToRemove.Count; int[] serverHandles = new int[count]; for (int ii = 0; ii < itemsToRemove.Count; ii++) { serverHandles[ii] = itemsToRemove[ii].ServerHandle; // remove the associated monitored items. if (m_monitoredItems != null) { lock (m_monitoredItems) { m_monitoredItems.Remove(itemsToRemove[ii].ClientHandle); } } } IntPtr pErrors = IntPtr.Zero; string methodName = "IOPCItemMgt.RemoveItems"; try { IOPCItemMgt server = BeginComCall <IOPCItemMgt>(methodName, true); // remove items. server.RemoveItems( count, serverHandles, out pErrors); } catch (Exception e) { ComUtils.TraceComError(e, methodName); for (int ii = 0; ii < itemsToRemove.Count; ii++) { itemsToRemove[ii].Created = false; itemsToRemove[ii].ErrorId = Marshal.GetHRForException(e); } return; } finally { EndComCall(methodName); } // free returned error array. int[] errors = ComUtils.GetInt32s(ref pErrors, count, true); // save error codes. for (int ii = 0; ii < count; ii++) { itemsToRemove[ii].Created = false; itemsToRemove[ii].ErrorId = errors[ii]; } /* * Utils.Trace( * "Group {0} RemoveItems({4}/{5}) {1}/{2}ms {3}%", * m_clientHandle, * m_samplingInterval, * m_actualSamplingInterval, * m_deadband, * itemsToRemove.Count, * m_items.Count); */ }
/// <summary> /// Sets the active state for a set of items in a group. /// </summary> public void ActivateItems(bool active) { // count the number of items to activate. List <GroupItem> itemsToActivate = new List <GroupItem>(); lock (Lock) { for (int ii = 0; ii < m_items.Count; ii++) { if (m_items[ii].ActiveChanged && m_items[ii].Active == active && m_items[ii].Created) { itemsToActivate.Add(m_items[ii]); } } } // check if nothing to do. if (itemsToActivate.Count == 0) { return; } // build list of items to remove. int count = itemsToActivate.Count; int[] serverHandles = new int[count]; for (int ii = 0; ii < itemsToActivate.Count; ii++) { serverHandles[ii] = itemsToActivate[ii].ServerHandle; } // initialize output parameters. IntPtr pErrors = IntPtr.Zero; string methodName = "IOPCItemMgt.SetActiveState"; try { IOPCItemMgt server = BeginComCall <IOPCItemMgt>(methodName, true); server.SetActiveState( count, serverHandles, (active) ? 1 : 0, out pErrors); } catch (Exception e) { ComUtils.TraceComError(e, methodName); for (int ii = 0; ii < itemsToActivate.Count; ii++) { itemsToActivate[ii].ActiveChanged = false; itemsToActivate[ii].ErrorId = Marshal.GetHRForException(e); } } finally { EndComCall(methodName); } // free returned error array. int[] errors = ComUtils.GetInt32s(ref pErrors, count, true); // save error codes. for (int ii = 0; ii < count; ii++) { itemsToActivate[ii].ActiveChanged = false; itemsToActivate[ii].ErrorId = errors[ii]; } /* * Utils.Trace( * "Group {0} ActivateItems({4}/{5}) {1}/{2}ms {3}%", * m_clientHandle, * m_samplingInterval, * m_actualSamplingInterval, * m_deadband, * active, * itemsToActivate.Count); */ }
/// <summary> /// Adds all items to the group that have not already been added. /// </summary> public void AddItems() { // count the number of items to add. List <GroupItem> itemsToAdd = new List <GroupItem>(); lock (Lock) { for (int ii = 0; ii < m_items.Count; ii++) { if (!m_items[ii].Created) { itemsToAdd.Add(m_items[ii]); } } } // check if nothing to do. if (itemsToAdd.Count == 0) { return; } // create item definitions. int count = itemsToAdd.Count; OpcRcw.Da.OPCITEMDEF[] definitions = new OpcRcw.Da.OPCITEMDEF[count]; for (int ii = 0; ii < count; ii++) { definitions[ii] = new OpcRcw.Da.OPCITEMDEF(); definitions[ii].szItemID = itemsToAdd[ii].ItemId; definitions[ii].bActive = (itemsToAdd[ii].Active) ? 1 : 0; definitions[ii].szAccessPath = String.Empty; definitions[ii].vtRequestedDataType = (short)VarEnum.VT_EMPTY; definitions[ii].hClient = itemsToAdd[ii].ClientHandle; } // initialize output parameters. IntPtr pResults = IntPtr.Zero; IntPtr pErrors = IntPtr.Zero; // add items to group. string methodName = "IOPCItemMgt.AddItems"; try { IOPCItemMgt server = BeginComCall <IOPCItemMgt>(methodName, true); server.AddItems( count, definitions, out pResults, out pErrors); } catch (Exception e) { ComUtils.TraceComError(e, methodName); for (int ii = 0; ii < itemsToAdd.Count; ii++) { itemsToAdd[ii].ErrorId = Marshal.GetHRForException(e); } return; } finally { EndComCall(methodName); } // unmarshal output parameters. int[] serverHandles = GetItemResults(ref pResults, count, true); int[] errors = ComUtils.GetInt32s(ref pErrors, count, true); // save handles and error codes. for (int ii = 0; ii < count; ii++) { GroupItem item = itemsToAdd[ii]; item.ServerHandle = serverHandles[ii]; item.ErrorId = errors[ii]; if (item.ErrorId >= 0) { itemsToAdd[ii].Created = true; } } /* * Utils.Trace( * "Group {0} AddItems({4}/{5}) {1}/{2}ms {3}%", * m_clientHandle, * m_samplingInterval, * m_actualSamplingInterval, * m_deadband, * itemsToAdd.Count, * m_items.Count); */ }
static void Main(string[] args) { Server server = new Server(); int TimeBias = 0; float DeadBand = 0.0f; uint phServerGroup; uint UpdateRate; var id = typeof(IOPCItemMgt).GUID; object p; server.AddGroup("Group1", 1, 10, 1, ref TimeBias, ref DeadBand, 0, out phServerGroup, out UpdateRate, ref id, out p); IOPCItemMgt pOPCItemMgt = (IOPCItemMgt)p; Item[] items = new Item[3]; items[0].Active = false; items[0].AccessPath = null; items[0].ClientId=1; items[0].ItemId="ItemY1"; items[0].RequestedDataSubType = VarEnum.VT_R8; items[0].RequestedDataType=VarEnum.VT_EMPTY; items[1].Active = false; items[1].AccessPath = null; items[1].ClientId = 2; items[1].ItemId = "ItemY2"; items[1].RequestedDataSubType = VarEnum.VT_R8; items[1].RequestedDataType = VarEnum.VT_EMPTY; items[2].Active = false; items[2].AccessPath = null; items[2].ClientId = 3; items[2].ItemId = "ItemY3"; items[2].RequestedDataSubType = VarEnum.VT_R8; items[2].RequestedDataType = VarEnum.VT_EMPTY; IntPtr itemPtr = OPCHelper.GetIntPtrfromItemArray(items); IntPtr dataPtr; IntPtr errorsPtr; pOPCItemMgt.AddItems(3, itemPtr, out dataPtr, out errorsPtr); IOPCSyncIO syncIO = (IOPCSyncIO)p; int[] serverIds = { 0, 1, 2 }; IntPtr dataPtr1; IntPtr errorsPtr1; Console.WriteLine("Y1 Y2 Y3"); for (int i = 0; i < 100; ++i) { syncIO.Read(DataSource.Cache, 3, serverIds, out dataPtr1, out errorsPtr1); ItemValue[] temItem = OPCHelper.GetSignalsState(3, dataPtr1, errorsPtr1); for (int k = 0; k < 3; ++k) { if (temItem[k].Error < 0) { Console.WriteLine("Error!"); return; } } double signal_Y1=(double)temItem[0].Value; double signal_Y2=(double)temItem[1].Value; double signal_Y3=(double)temItem[2].Value; Console.WriteLine("{0} {1} {2}", signal_Y1, signal_Y2, signal_Y3); System.Threading.Thread.Sleep(100); } }
internal Group(DAServer server, int clientId, int serverId, string name, int updateRate, IOPCItemMgt @group) { this.server = server; ClientId = clientId; ServerId = serverId; Name = name; this.@group = @group; UpdateRate = updateRate; syncIO = (IOPCSyncIO)@group; groupManagement = (IOPCGroupStateMgt)@group; try { asyncIO = (IOPCAsyncIO2)@group; } catch (InvalidCastException) { } try { connectionPointContainer = (IConnectionPointContainer)@group; } catch (InvalidCastException) { } }
public void AddItems(string[] itemID, out int[] ItemHANDLES, out VarEnum[] arrayType) { int m_Res = 0; try { int dwCount = itemID.Length; IntPtr pErrors; IntPtr pResults; IOPCItemMgt m_pIItemMgt = (IOPCItemMgt)pUnknown; //ItemMgt: OK OPCITEMDEF pItem = new OPCITEMDEF(); //set pItem int temp = 0; pItem.bActive = true; pItem.szAccessPath = null; pItem.hClient = temp; pItem.dwBlobSize = 0; // no blob support pItem.pBlob = IntPtr.Zero; pItem.vtRequestedDataType = (int)VarEnum.VT_EMPTY; pItem.wReserved = 0; //alloc memory IntPtr ptrDef = Marshal.AllocCoTaskMem(dwCount * Marshal.SizeOf(pItem)); int runDef = (int)ptrDef; for (int i = 0; i < dwCount; i++) { pItem.szItemID = itemID[i]; Marshal.StructureToPtr(pItem, (IntPtr)runDef, false); runDef += Marshal.SizeOf(pItem); } //add item m_Res = m_pIItemMgt.AddItems(dwCount, ptrDef, out pResults, out pErrors); //dealoc memory runDef = (int)ptrDef; for (int i = 0; i < dwCount; i++) { Marshal.DestroyStructure((IntPtr)runDef, pItem.GetType()); runDef += Marshal.SizeOf(pItem); } Marshal.FreeCoTaskMem(ptrDef); if (m_Res < 0) { throw new Exception("Server: Add Items failed hr= " + m_Res.ToString()); } //read result int runRes = (int)pResults; int runErr = (int)pErrors; if ((runRes == 0) || (runErr == 0)) { throw new Exception("Server: Add Items failed hr= " + unchecked ((int)0x80004004).ToString()); } //init output arry ItemHANDLES = new int[dwCount]; arrayType = new VarEnum [dwCount]; int error; for (int i = 0; i < dwCount; i++) { error = Marshal.ReadInt32((IntPtr)runErr); if (error < 0) { //parent.PrintMessage("Server: Add Item " + itemID[i] + " is failed hr =" + error.ToString(), MessageStyl.error); ItemHANDLES[i] = 0; arrayType[i] = VarEnum.VT_EMPTY; } else { ItemHANDLES[i] = Marshal.ReadInt32((IntPtr)runRes); arrayType[i] = (VarEnum)(int)Marshal.ReadInt16((IntPtr)(runRes + 4)); //set server handle same as client handle int[] tempHandle = new int[1]; tempHandle[0] = ItemHANDLES[i]; IntPtr setClientError; m_pIItemMgt.SetClientHandles(1, tempHandle, tempHandle, out setClientError); int s_err = Marshal.ReadInt32(setClientError); //if (s_err < 0) parent.PrintMessage("Server: Add Item " + itemID[i] + " : Set the client handle is failed hr =" + s_err.ToString(), MessageStyl.error); } runRes += Marshal.SizeOf(new OPCITEMRESULT()); runErr += 4; } Marshal.FreeCoTaskMem(pResults); Marshal.FreeCoTaskMem(pErrors); } catch (Exception e) { //parent.PrintMessage(e.Message, MessageStyl.error); throw e; } }