public bool AddGroup(object Form_Main) //返回值false为失败,true为成功 { Int32 dwRequestedUpdateRate = 2000; Int32 hClientGroup = 1; Int32 pRevUpdaterate; float deadband = 0; int TimeBias = 0; GCHandle hTimeBias, hDeadband; hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned); hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID; if (!isConnected) { if (!Connect()) { return(false); //如果还没有没有建立连接,先建立连接 } } try { //ServerObj.AddGroup的返回值类型为void ServerObj.AddGroup("OPCGroup", 0, dwRequestedUpdateRate, hClientGroup, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), LOCALE_ID, out pSvrGroupHandle, out pRevUpdaterate, ref iidRequiredInterface, out GroupObj); IOPCAsyncIO2Obj = (IOPCAsyncIO2)GroupObj;//为组异步读写定义句柄 //Query interface for Async calls on group object IOPCGroupStateMgtObj = (IOPCGroupStateMgt)GroupObj; pIConnectionPointContainer = (IConnectionPointContainer)GroupObj; //定义特定组的异步调用连接 Guid iid = typeof(IOPCDataCallback).GUID; // Establish Callback for all async operations pIConnectionPointContainer.FindConnectionPoint(ref iid, out pIConnectionPoint); // Creates a connection between the OPC servers's connection point and this client's sink (the callback object) pIConnectionPoint.Advise(Form_Main, out dwCookie); isAddGroup = true; } catch (System.Exception error) { isAddGroup = false; MessageBox.Show(string.Format("创建组对象时出错:-{0}", error.Message), "建组出错", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (hDeadband.IsAllocated) { hDeadband.Free(); } if (hTimeBias.IsAllocated) { hTimeBias.Free(); } } return(isAddGroup); }
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; } }
internal void InternalAdd(int[] p_BiasTime, float[] p_PercentDeadband, int p_LocaleID) { Type l_TypGrpMgt = typeof(IOPCGroupStateMgt); Guid l_GuidGrpTst = l_TypGrpMgt.GUID; object l_ObjTemp; if (m_State.Public) { IOPCServerPublicGroups l_IfPubGrps = null; l_IfPubGrps = (IOPCServerPublicGroups)m_IfServer; if (l_IfPubGrps == null) { Marshal.ThrowExceptionForHR(HResults.E_NOINTERFACE); } l_IfPubGrps.GetPublicGroupByName(m_State.Name, ref l_GuidGrpTst, out l_ObjTemp); l_IfPubGrps = null; } else { m_IfServer.AddGroup(m_State.Name, m_State.Active, m_State.UpdateRate, m_State.HandleClient, p_BiasTime, p_PercentDeadband, m_State.LocaleID, out m_State.HandleServer, out m_State.UpdateRate, ref l_GuidGrpTst, out l_ObjTemp); } if (l_ObjTemp == null) { Marshal.ThrowExceptionForHR(HResults.E_NOINTERFACE); } m_IfMgt = (IOPCGroupStateMgt)l_ObjTemp; l_ObjTemp = null; GetStates(); GetInterfaces(); AdviseIOPCDataCallback(); }
private void AddGroup() { /* 2. Add a new group * Add a group object and querry for interface IOPCItemMgt * Parameter as following: * [in] not active, so no OnDataChange callback * [in] Request this Update Rate from Server * [in] Client Handle, not necessary in this sample * [in] No time interval to system UTC time * [in] No Deadband, so all data changes are reported * [in] Server uses english language to for text values * [out] Server handle to identify this group in later calls * [out] The answer from Server to the requested Update Rate * [in] requested interface type of the group object * [out] pointer to the requested interface */ pIOPCServer.AddGroup(GROUP_NAME, 0, dwRequestedUpdateRate, hClientGroup, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), LOCALE_ID, out pSvrGroupHandle, out pRevUpdateRate, ref iidRequiredInterface, out pobjGroup1); }
/// <summary> /// 添加Opc项 /// </summary> /// <param name="opcGroup"></param> private void AddOpcGroup(OpcDaCustomGroup opcGroup) { try { //添加OPC组 iOpcServer.AddGroup(opcGroup.GroupName, opcGroup.IsActive, opcGroup.RequestedUpdateRate, opcGroup.ClientGroupHandle, opcGroup.TimeBias.AddrOfPinnedObject(), opcGroup.PercendDeadBand.AddrOfPinnedObject(), opcGroup.LCID, out opcGroup.ServerGroupHandle, out opcGroup.RevisedUpdateRate, ref opcGroup.Riid, out opcGroup.Group); InitIoInterfaces(opcGroup); if (opcGroup.OpcDataCustomItems.Length > 0) { //添加OPC项 AddOpcItem(opcGroup); //激活订阅回调事件 ActiveDataChanged(IOPCGroupStateMgt); } } catch (COMException ex) { throw ex; } finally { if (opcGroup.TimeBias.IsAllocated) { opcGroup.TimeBias.Free(); } if (opcGroup.PercendDeadBand.IsAllocated) { opcGroup.PercendDeadBand.Free(); } } }
public Group(IOPCServer server, int cliengGroup, string groupName, int isActive, int LOCALE_ID) { try { pIOPCServer = server; hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned); hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); pIOPCServer.AddGroup(groupName, isActive, dwRequestedUpdateRate, cliengGroup, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), LOCALE_ID, out pSvrGroupHandle, out pRevUpdateRate, ref iidRequiredInterface, out pobjGroup1); InitReqIOInterfaces(); } catch (Exception ex) { throw ex; } }
/// <summary> /// Create OPC Group /// </summary> /// <param name="opcServer">If server link</param> /// <param name="isPublic">Is public</param> /// <param name="groupName">Group name</param> /// <param name="setActive">Set active</param> /// <param name="requestedUpdateRate">Requested update rate</param> /// <param name="biasTime">Bias time</param> /// <param name="percentDeadband">Percent deadband</param> /// <param name="localeID">Locale ID</param> internal OpcGroup(IOPCServer opcServer, bool isPublic, string groupName, bool setActive, int requestedUpdateRate, int?biasTime, float?percentDeadband, int localeID) { IsDisposed = false; parentServer = opcServer; stateName = groupName; statePublic = isPublic; stateUpdateRate = requestedUpdateRate; stateActive = setActive; stateTimeBias = 0; statePercentDeadband = 0.0f; stateLocaleID = 0; stateHandleClient = this.GetHashCode(); stateHandleServer = 0; Type typGrpMgt = typeof(IOPCGroupStateMgt); Guid guidGrpTst = typGrpMgt.GUID; if (statePublic) { IOPCServerPublicGroups ifPubGrps = null; ifPubGrps = (IOPCServerPublicGroups)parentServer; if (ifPubGrps == null) { Marshal.ThrowExceptionForHR(HRESULTS.E_NOINTERFACE); } ifPubGrps.GetPublicGroupByName(stateName, ref guidGrpTst, out opcGroupObject); ifPubGrps = null; } else { int[] biasTimeArray = biasTime == null ? null : new int[1] { biasTime.Value }; float[] percentDeadbandArray = percentDeadband == null ? null : new float[1] { percentDeadband.Value }; parentServer.AddGroup(stateName, stateActive, stateUpdateRate, stateHandleClient, biasTimeArray, percentDeadbandArray, stateLocaleID, out stateHandleServer, out stateUpdateRate, ref guidGrpTst, out opcGroupObject); } if (opcGroupObject == null) { Marshal.ThrowExceptionForHR(HRESULTS.E_NOINTERFACE); } RefreshState(); // Advise callback Guid sinkGuid = typeof(IOPCDataCallback).GUID; connectionPointContainer.FindConnectionPoint(ref sinkGuid, out callbackConnectionPoint); if (callbackConnectionPoint != null) { callbackConnectionPoint.Advise(this, out callbackCookie); } }
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); }
/// <summary> /// 增加一个group /// </summary> /// <param name="Form_Main"></param> /// <returns></returns> public string PLCGroupAdd(object Form_Main) { string errText = string.Empty; Int32 dwRequestedUpdateRate = 250; Int32 pRevUpdateRate; float deadband = 0; int TimeBias = 0; GCHandle hTimeBias, hDeadband; hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned); hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID; try { ServerObj.AddGroup("MyOPCGroup1",//组对象 0, dwRequestedUpdateRate, hClientGroup, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), LOCALE_ID, out pSvrGroupHandle, out pRevUpdateRate, ref iidRequiredInterface, out MyobjGroup1); IOPCAsyncIO2Obj = (IOPCAsyncIO2)MyobjGroup1; //Query interface for Async calls on group object IOPCGroupStateMgtObj = (IOPCGroupStateMgt)MyobjGroup1; pIConnectionPointContainer = (IConnectionPointContainer)MyobjGroup1; //定义特定组的异步调用连接 Guid iid = typeof(IOPCDataCallback).GUID; // Establish Callback for all async operations pIConnectionPointContainer.FindConnectionPoint(ref iid, out pIConnectionPoint); // Creates a connection between the OPC servers's connection point and this client's sink (the callback object) pIConnectionPoint.Advise(Form_Main, out dwCookie); } catch (Exception ex) { errText = ex.Message.ToString(); } return(errText); }
/// <summary> /// Creates a group. /// </summary> public object CreateGroup( int groupId, int samplingInterval, float deadband, out int groupHandle, out int revisedSamplingInterval) { groupHandle = 0; revisedSamplingInterval = 0; GCHandle hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); string methodName = "IOPCServer.AddGroup"; try { IOPCServer server = BeginComCall <IOPCServer>(methodName, true); object group = null; Guid iid = typeof(OpcRcw.Da.IOPCItemMgt).GUID; server.AddGroup( String.Empty, 1, samplingInterval, 0, IntPtr.Zero, hDeadband.AddrOfPinnedObject(), ComUtils.LOCALE_SYSTEM_DEFAULT, out groupHandle, out revisedSamplingInterval, ref iid, out group); return(group); } catch (Exception e) { ComUtils.TraceComError(e, methodName); return(null); } finally { EndComCall(methodName); hDeadband.Free(); } }
/// <summary> /// 添加组 /// </summary> /// <param name="opcGroup"></param> public void AddGroup(OpcGroup opcGroup) { GCHandle hTimeBias = GCHandle.Alloc(0, GCHandleType.Pinned);//为指定的对象分配句柄。 GCHandle hPercendDeadBand = GCHandle.Alloc(0, GCHandleType.Pinned); int updateRate; Guid riid = typeof(IOPCItemMgt).GUID; if (string.IsNullOrEmpty(opcGroup.GroupName))//组名称为空,给个默认的组名 { opcGroup.GroupName = _defaultGroupName; _defaultGroupName = "Group" + (Convert.ToInt32(_defaultGroupName.Remove(0, 5)) + 1); } //if (opcGroup.ClientGroupHandle == 0) //{ // opcGroup.ClientGroupHandle = _defaultClientGroupHandle; // _defaultClientGroupHandle++; //} try { opcServer.AddGroup(opcGroup.GroupName, opcGroup.IsActive, opcGroup.RequestedUpdateRate, opcGroup.ClientGroupHandle, hTimeBias.AddrOfPinnedObject(), hPercendDeadBand.AddrOfPinnedObject(), opcGroup.LocalId, out opcGroup.ServerGroupHandle, out updateRate, ref riid, out opcGroup.ObjGroup); // _lstOpcGroup.Add(opcGroup); OpcGroups.Add(opcGroup.ClientGroupHandle, opcGroup); Guid iid = typeof(IOPCDataCallback).GUID; //为所有的异步调用创建回调 opcGroup.ConnectionPointContainer.FindConnectionPoint(ref iid, out opcGroup.ConnectionPoint); //为OPCServer的连接点与客户端接收点之间建立连接 opcGroup.ConnectionPoint.Advise(opcGroup, out opcGroup.dwCookie); } catch (Exception ex) { throw ex; } finally { if (hTimeBias.IsAllocated) { hTimeBias.Free(); } if (hPercendDeadBand.IsAllocated) { hPercendDeadBand.Free(); } } }
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); } }
/// <summary> /// 增加group /// </summary> /// <param name="Form_Main"></param> /// <returns></returns> public string PLCGroupAdd() { string errText = string.Empty; Int32 dwRequestedUpdateRate = 1000; //Int32 hClientGroup; Int32 pRevUpdateRate; float deadband = 0; int TimeBias = 0; GCHandle hTimeBias, hDeadband; hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned); hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID; try { ServerObj.AddGroup("ShearerInfoGroup", //组对象 1, dwRequestedUpdateRate, 1, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), 0, out pSvrGroupHandle, out pRevUpdateRate, ref iidRequiredInterface, out MyobjGroup1); IOPCSyncIO2Obj = (IOPCSyncIO)MyobjGroup1; //Query interface for Async calls on group object IOPCGroupStateMgtObj = (IOPCGroupStateMgt)MyobjGroup1; } catch (Exception ex) { errText = ex.Message.ToString(); } return(errText); }
/// <summary>adds a IOPCGroupStateMgt-object to the OPC-server</summary> /// <param name="commonInterface">the common interface</param> /// <returns> the revisedUpdateRate for further use </returns> /// <exception cref="Exception">throws and forwards any exception (with short error description)</exception> public int addOPCGroup(IOPCCommon commonInterface) { // initialize arguments. Guid iid = Guid.Empty; object objGroup = null; IntPtr pTimeBias = IntPtr.Zero; IntPtr pDeadband = IntPtr.Zero; if (m_disposed) { throw new NullReferenceException("This object has been disposed!"); } m_revUpdateRate = 0; try { // get the default locale for the server. commonInterface.GetLocaleID(out m_LocaleID); iid = typeof(IOPCGroupStateMgt).GUID; if (iid == Guid.Empty) { throw new Exception("Could not get the interface 'IOPCGroupStateMgt'!"); } // Add a group object "m_OPCGroup" and query for interface IOPCItemMgt // Parameter as following: // [in] active, so do OnDataChange callback // [in] Request this Update Rate from Server // [in] Client Handle, not necessary in this sample // [in] No time interval to system UTC time // [in] No Deadband, so all data changes are reported // [in] Server uses english language to for text values // [out] Server handle to identify this group in later calls // [out] The answer from Server to the requested Update Rate // [in] requested interface type of the group object // [out] pointer to the requested interface m_OPCServer.AddGroup(m_grpName, Convert.ToInt32(m_isActive), m_reqUpdateRate, m_grpClntHndl, pTimeBias, pDeadband, m_LocaleID, out m_grpSrvHndl, out m_revUpdateRate, ref iid, out objGroup); if (objGroup == null) { string strMsg = "Couldn't add the group '" + m_grpName + "' to the server!"; throw new Exception(strMsg); } // Get our reference from the created group m_OPCGroupStateMgt = (IOPCGroupStateMgt)objGroup; if (m_OPCGroupStateMgt == null) { throw new Exception("Could not get the interface 'IOPCGroupStateMgt'!"); } } catch (Exception) { throw; } return(m_revUpdateRate); }
/// <summary> /// Creates a new subscription. /// </summary> /// <param name="state">The initial state of the subscription.</param> /// <returns>The new subscription object.</returns> public ITsCDaSubscription CreateSubscription(TsCDaSubscriptionState state) { if (state == null) { throw new ArgumentNullException(nameof(state)); } lock (this) { if (m_server == null) { throw new NotConnectedException(); } string methodName = "IOPCServer.AddGroup"; // copy the subscription state. TsCDaSubscriptionState result = (TsCDaSubscriptionState)state.Clone(); // initialize arguments. Guid iid = typeof(IOPCItemMgt).GUID; object group = null; int serverHandle = 0; int revisedUpdateRate = 0; GCHandle hDeadband = GCHandle.Alloc(result.Deadband, GCHandleType.Pinned); // invoke COM method. try { IOPCServer server = BeginComCall <IOPCServer>(methodName, true); server.AddGroup( (result.Name != null) ? result.Name : "", (result.Active) ? 1 : 0, result.UpdateRate, 0, IntPtr.Zero, hDeadband.AddrOfPinnedObject(), Technosoftware.DaAeHdaClient.Com.Interop.GetLocale(result.Locale), out serverHandle, out revisedUpdateRate, ref iid, out group); } catch (Exception e) { ComCallError(methodName, e); throw Technosoftware.DaAeHdaClient.Utilities.Interop.CreateException(methodName, e); } finally { if (hDeadband.IsAllocated) { hDeadband.Free(); } EndComCall(methodName); } if (group == null) { throw new OpcResultException(OpcResult.E_FAIL, "The subscription was not created."); } methodName = "IOPCGroupStateMgt2.SetKeepAlive"; // set the keep alive rate if requested. try { int keepAlive = 0; IOPCGroupStateMgt2 comObject = BeginComCall <IOPCGroupStateMgt2>(group, methodName, true); comObject.SetKeepAlive(result.KeepAlive, out keepAlive); result.KeepAlive = keepAlive; } catch (Exception e1) { result.KeepAlive = 0; ComCallError(methodName, e1); } finally { EndComCall(methodName); } // save server handle. result.ServerHandle = serverHandle; // set the revised update rate. if (revisedUpdateRate > result.UpdateRate) { result.UpdateRate = revisedUpdateRate; } // create the subscription object. Technosoftware.DaAeHdaClient.Com.Da.Subscription subscription = CreateSubscription(group, result, filters_); // index by server handle. subscriptions_[serverHandle] = subscription; // return subscription. return(subscription); } }
public override void Init() { // Local variables Type svrComponenttyp; OPCITEMDEF[] ItemDefArray; // Initialise Group properties int bActive = 0; int dwRequestedUpdateRate = 250; int hClientGroup = 0; int dwLCID = LOCALE_ID; int pRevUpdateRate; int TimeBias = 0; float deadband = 0; // Access unmanaged COM memory GCHandle hTimeBias, hDeadband; hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned); hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); // 1. Connect to the local server. // Get the Type from the progID and create instance of the OPC Server COM // component Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID; svrComponenttyp = Type.GetTypeFromProgID(SERVER_NAME); try { pIOPCServer = (IOPCServer)Activator.CreateInstance(svrComponenttyp); try { /* 2. Add a new group * Add a group object and querry for interface IOPCItemMgt * Parameter as following: * [in] not active, so no OnDataChange callback * [in] Request this Update Rate from Server * [in] Client Handle, not necessary in this sample * [in] No time interval to system UTC time * [in] No Deadband, so all data changes are reported * [in] Server uses english language to for text values * [out] Server handle to identify this group in later calls * [out] The answer from Server to the requested Update Rate * [in] requested interface type of the group object * [out] pointer to the requested interface */ pIOPCServer.AddGroup(GROUP_NAME, bActive, dwRequestedUpdateRate, hClientGroup, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), dwLCID, out nSvrGroupID, out pRevUpdateRate, ref iidRequiredInterface, out pobjGroup1); // Get the IOPOCSyncIO interface pointer from the group pointer. // pIOPCSyncIO also needs to be released when not in use. pIOPCSyncIO = (IOPCSyncIO)pobjGroup1; /* 3. Add items to the group */ // This example shows adding of only one item in the group ItemDefArray = new OPCITEMDEF[1]; ItemDefArray[0].szAccessPath = ""; // Accesspath not needed for this sample ItemDefArray[0].szItemID = ITEM_NAME_Prefix + OPCTag; // ItemID, see above ItemDefArray[0].bActive = 1; // item is active ItemDefArray[0].hClient = 1; // client handle ItemDefArray[0].dwBlobSize = 0; // blob size ItemDefArray[0].pBlob = IntPtr.Zero; // pointer to blob ItemDefArray[0].vtRequestedDataType = 2; // return values in native (cannonical) datatype // initialize output parameters. IntPtr pResults = IntPtr.Zero; IntPtr pErrors = IntPtr.Zero; try { // Add items to group ((IOPCItemMgt)pobjGroup1).AddItems(1, ItemDefArray, out pResults, out pErrors); // Unmarshal to get the server handles out fom the m_pItemResult // after checking the errors int[] errors = new int[1]; Marshal.Copy(pErrors, errors, 0, 1); if (errors[0] == 0) { OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pResults, typeof(OPCITEMRESULT)); // Allocate integer array nItemSvrID = new int[1]; nItemSvrID[0] = result.hServer; } else { string pstrError; pIOPCServer.GetErrorString(errors[0], LOCALE_ID, out pstrError); MessageBox.Show(pstrError, "Result - Adding Items", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Free indirect structure elements Marshal.DestroyStructure(pResults, typeof(OPCITEMRESULT)); } catch (Exception error) // catch for error in adding items. { MessageBox.Show(error.Message, "Result - Adding Items", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // Free the unmanaged COM memory if (pResults != IntPtr.Zero) { Marshal.FreeCoTaskMem(pResults); pResults = IntPtr.Zero; } if (pErrors != IntPtr.Zero) { Marshal.FreeCoTaskMem(pErrors); pErrors = IntPtr.Zero; } } } catch (Exception error) // catch for error in creation group { MessageBox.Show(string.Format("Error while creating group object:-{0}", error.Message), "Result-Add Group", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (hDeadband.IsAllocated) { hDeadband.Free(); } if (hTimeBias.IsAllocated) { hTimeBias.Free(); } } } catch (Exception error) // catch for error in creating server { MessageBox.Show(string.Format("Error while creating server object:-{0}", error.Message), "Result - Create Server Instance", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/*------------------------------------------------------ * Add OPC Group * * (ret) True OK * False NG * ------------------------------------------------------*/ public bool AddGroup(string sGrpName, int iUpdateRate) { if (m_OPCServer == null) { return(false); } if (m_OPCGroup != null || m_iServerGroup != 0) { return(false); } object group = null; bool bActive = true; int iClientGroup = 0; //1234; IntPtr ptrTimeBias = IntPtr.Zero; IntPtr ptrDeadBand = IntPtr.Zero; int iLCID = 0; Guid guidGroupStateMgt; Guid guidDataCallback; int iRevisedUpdateRate; int iKeepAliveTime = 10000; try { switch (m_OpcdaVer) { case DEF_OPCDA.VER_30: guidGroupStateMgt = Marshal.GenerateGuidForType(typeof(IOPCGroupStateMgt2)); m_OPCServer.AddGroup(sGrpName, (bActive) ? 1 : 0, iUpdateRate, iClientGroup, ptrTimeBias, ptrDeadBand, iLCID, out m_iServerGroup, out iRevisedUpdateRate, ref guidGroupStateMgt, out group); m_OPCGroup2 = (IOPCGroupStateMgt2)group; m_OPCGroup2.SetKeepAlive(iKeepAliveTime, out iKeepAliveTime); m_OPCConnPointCntnr = (IConnectionPointContainer)m_OPCGroup2; guidDataCallback = Marshal.GenerateGuidForType(typeof(IOPCDataCallback)); m_OPCConnPointCntnr.FindConnectionPoint(ref guidDataCallback, out m_OPCConnPoint); break; case DEF_OPCDA.VER_10: case DEF_OPCDA.VER_20: default: guidGroupStateMgt = Marshal.GenerateGuidForType(typeof(IOPCGroupStateMgt)); m_OPCServer.AddGroup(sGrpName, (bActive) ? 1 : 0, iUpdateRate, iClientGroup, ptrTimeBias, ptrDeadBand, iLCID, out m_iServerGroup, out iRevisedUpdateRate, ref guidGroupStateMgt, out group); m_OPCGroup = (IOPCGroupStateMgt)group; m_OPCConnPointCntnr = (IConnectionPointContainer)m_OPCGroup; guidDataCallback = Marshal.GenerateGuidForType(typeof(IOPCDataCallback)); m_OPCConnPointCntnr.FindConnectionPoint(ref guidDataCallback, out m_OPCConnPoint); break; } return(true); } catch (Exception exc) { MessageBox.Show(exc.ToString(), "AddGroup"); return(false); } }
private void LoadOPC() { try { // OPC server variables. Type svrComponenttyp; OPCITEMDEF[] ItemDefArray; // Initialise Group properties int bActive = 0; int dwRequestedUpdateRate = 250; int hClientGroup = 0; int dwLCID = LOCALE_ID; int pRevUpdateRate; int TimeBias = 0; float deadband = 0; int vNo_OF_Tags = 1;//341; ItemDefArray = new OPCITEMDEF[vNo_OF_Tags]; // Access unmanaged COM memory GCHandle hTimeBias, hDeadband; hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned); hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); string[] itemIds = new string[vNo_OF_Tags]; string[] datas = new string[vNo_OF_Tags]; itemIds[S7_STR1_S_Send_STR1_Receive_TCM_HandshakingwithMIS_ID] = "S7:[S7 CONNECTION_1]MREAL100";//"S7:[STR1]S_Send.STR1.TataMis_Receive.TCM.L2_Cut_Length_S1";// // 1. Connect to Simens OPC DA local server. ( IP Address = 127.0.0.1 ) ( External Ip Address as = 192.168.1.145) Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID; svrComponenttyp = System.Type.GetTypeFromProgID(SERVER_NAME); pIOPCServer = (IOPCServer)System.Activator.CreateInstance(svrComponenttyp); // MessageBox.Show("Connected"); //2. CC#3 add group function pIOPCServer.AddGroup(GROUP_NAME, bActive, dwRequestedUpdateRate, hClientGroup, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), dwLCID, out nSvrGroupID, out pRevUpdateRate, ref iidRequiredInterface, out pobjGroup1); pIOPCSyncIO = (IOPCSyncIO)pobjGroup1; // nItemSvrID = new int[1]; // nItemSvrID[0] = 1;// result.hServer; //3.CC#3 add item function for (int i = 0; i < vNo_OF_Tags; i++) { ItemDefArray[i].szItemID = itemIds[i]; } ((IOPCItemMgt)pobjGroup1).AddItems(NUMBER_OF_TAGS, ItemDefArray, out pResults, out pErrors); for (int i = 0; i < vNo_OF_Tags; i++) { nItemSvrID[i] = i + 1; } //4. CC#3 Read item function IntPtr pItemValues = new IntPtr(); pIOPCSyncIO.Read(OPCDATASOURCE.OPC_DS_DEVICE, NUMBER_OF_TAGS, nItemSvrID, out pItemValues, out pErrors); IntPtr position = pItemValues; OPCITEMSTATE[] result = new OPCITEMSTATE[vNo_OF_Tags]; for (int i = 0; i < vNo_OF_Tags; i++) { result[i] = (OPCITEMSTATE)Marshal.PtrToStructure(position, typeof(OPCITEMSTATE)); double a = Convert.ToDouble(result[i].vDataValue.ToString()); MessageBox.Show("here " + result[i].vDataValue.ToString()); datas[i] = Convert.ToString(result[i].vDataValue); position = (IntPtr)(position.ToInt32() + Marshal.SizeOf(typeof(OPCITEMSTATE)));/*********************************/ } FuncFreeMemory(); unloadcomobjects(); // now as current data is available , proceed with the further functions. // tranfering the data to the previous variable of the TATA OPC Programe. output = new string[vNo_OF_Tags]; // TATA OPC Variable assigned to previous programe. for (int i = 0; i < vNo_OF_Tags; i++) { output[i] = datas[i]; } // Handle Strand Communication Faliure. // Added on 12th August 2011 - for (int i = 0; i < vNo_OF_Tags; i++) { if ((output[i] == null) || (output[i] == "")) { output[i] = Convert.ToString(0); string vDate = DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year; string vDate1 = DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second; objWriteFile = new StreamWriter(FilePath + "CC3_ACS_Errors_" + vDate + ".txt", true); objWriteFile.WriteLine("Communicaiton Error:-" + itemIds[i] + "\tDate :-\t" + vDate1); // Log The Tag and associated PLC For the Communication Errors objWriteFile.Close(); } } for (int i = 0; i < vNo_OF_Tags; i++) { datas[i] = null; } // disconnecting Server. Marshal.ReleaseComObject(pIOPCServer); pIOPCServer = null; } catch (Exception ex) { //MessageBox.Show(ex.Message); string vDate = DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year; //objWriteFile = new StreamWriter(FilePath + "CC3_ACS_Errors_" + vDate + ".txt", true); //objWriteFile.WriteLine("Load OPC Error:-" + ex.Message + "\tDate :-\t" + vDate); //objWriteFile.Close(); } }