/// <summary> /// Connect to opc server /// </summary> /// <param name="serverName"></param> /// <param name="requestedUpdateRate">In case of use of LinkMaster and Kepserver simulation, this value should match the LinkMaster value</param> /// <returns></returns> public bool Connect(string serverName, int requestedUpdateRate = 250) { srv = new OpcServer(); int rtc = srv.Connect(serverName); if (HRESULTS.Failed(rtc)) { srv.GetErrorString(rtc, 0);//MBR added 0 return Srv.GetErrorString( rtc); return(false); } float deadBand = 0.0F; //Get data start try { OPCGetData.OPCReadGroup = srv.AddGroup("Group1GetData", true, requestedUpdateRate, ref deadBand, 0, 0); } catch (Exception) { srv.Disconnect(); return(false); //return ex.Message; } //Get data end //Set data start try { OPCSetData.OPCWriteGroup = srv.AddGroup("Group1SetData", true, requestedUpdateRate, ref deadBand, 0, 0); } catch (Exception) { srv.Disconnect(); return(false);//return ex.Message; } return(true); //ok }
private string[] IEnumStringToArray(IEnumString enumerator) { List <string> lst = new List <string>(); if (enumerator != null) { int cft; string[] strF = new string[100]; int hresult; IntPtr intPtr = Marshal.AllocCoTaskMem(sizeof(int)); try { do { hresult = enumerator.Next(100, strF, intPtr); if (HRESULTS.Failed(hresult)) { Marshal.ThrowExceptionForHR(hresult); } cft = Marshal.ReadInt32(intPtr); if (cft > 0) { for (int i = 0; i < cft; i++) { lst.Add(strF[i]); } } }while (hresult == HRESULTS.S_OK); } finally { if (intPtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(intPtr); } } } return(lst.ToArray()); }
public IGroup AddGroup(string name, short id, int updateRate, float deadBand, bool active) { 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); } }
public bool SetActiveState(bool active, params short[] items) { int count = items.Length; int[] arrSvr = new int[count]; for (int i = 0; i < count; i++) { ITag item = GetItemByID(items[i]); if (item != null) { arrSvr[i] = item.Address.Start; } } IntPtr ptrErr; if (HRESULTS.Succeeded(_itemMgt.SetActiveState(count, arrSvr, active, out ptrErr))) { Marshal.FreeCoTaskMem(ptrErr); return(true); } return(false); }
public bool SetClientHandles(int[] arrHSrv, int[] arrHClt, out int[] arrErr) { IntPtr ptr; arrErr = null; int length = arrHSrv.Length; if (length != arrHClt.Length) { Marshal.ThrowExceptionForHR(-2147467260); } int hresultcode = this.ifItems.SetClientHandles(length, arrHSrv, arrHClt, out ptr); if (HRESULTS.Failed(hresultcode)) { Marshal.ThrowExceptionForHR(hresultcode); } arrErr = new int[length]; Marshal.Copy(ptr, arrErr, 0, length); Marshal.FreeCoTaskMem(ptr); return(hresultcode == 0); }
public bool Write(int[] arrHSrv, object[] arrVal, out int[] arrErr) { IntPtr ptr; arrErr = null; int length = arrHSrv.Length; if (length != arrVal.Length) { Marshal.ThrowExceptionForHR(-2147467260); } int hresultcode = this.ifSync.Write(length, arrHSrv, arrVal, out ptr); if (HRESULTS.Failed(hresultcode)) { Marshal.ThrowExceptionForHR(hresultcode); } arrErr = new int[length]; Marshal.Copy(ptr, arrErr, 0, length); Marshal.FreeCoTaskMem(ptr); return(hresultcode == 0); }
public OPCItemState GetValue() { int[] handler = new int[1] { this.HandleServer }; OPC.Data.OPCItemState[] itemValues = this.Group.Read(handler); if (itemValues == null || itemValues.Length == 0) { return(null); } OPC.Data.OPCItemState s = itemValues[0]; if (HRESULTS.Succeeded(s.Error)) { return(s); } else { throw (new Exception("ERROR 0x" + s.Error.ToString("X"))); } }
/// <summary> /// Set datatypes /// </summary> /// <param name="serverHandles">Arr h srv</param> /// <param name="dataTypes">Arr VT</param> /// <param name="errors">Arr err</param> /// <returns>Bool</returns> public bool SetDatatypes(int[] serverHandles, VarEnum[] dataTypes, out int[] errors) { ThrowIfDisposed(); errors = null; if (serverHandles.Length != dataTypes.Length) { Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT); } int hResult; IntPtr ptrErr = IntPtr.Zero; IntPtr ptrVT = Marshal.AllocCoTaskMem(serverHandles.Length * sizeof(short)); try { for (int i = 0; i < dataTypes.Length; i++) { Extensions.WriteInt16(ptrVT, i, (short)dataTypes[i]); } hResult = opcItemMgt.SetDataTypes(serverHandles.Length, serverHandles, ptrVT, out ptrErr); } finally { Marshal.FreeCoTaskMem(ptrVT); } if (HRESULTS.Failed(hResult)) { Marshal.ThrowExceptionForHR(hResult); } errors = new int[serverHandles.Length]; Marshal.Copy(ptrErr, errors, 0, errors.Length); Marshal.FreeCoTaskMem(ptrErr); return(hResult == HRESULTS.S_OK); }
public static bool StartOPCServer(out string errorMessage) { int rtc = 0; errorMessage = ""; try { opcServer = new OpcServer(); //opcMachineHost = ConfigurationManager.AppSettings["OPCSHostMachine"]; //opcServerName = ConfigurationManager.AppSettings["OPCServer"]; Connection dbpm = new Connection(); //for main l2 server //opcMachineHost = dbpm.GetConfigValue("HostServer", "", "Name"); //opcServerName = dbpm.GetConfigValue("OpcServerName", "", "Name"); //opcMachineHost = "NISAR"; //opcServerName = "Matrikon.OPC.Simulation.1"; //for working machine opcMachineHost = ConfigurationManager.AppSettings["OPCSHostMachine"]; opcServerName = ConfigurationManager.AppSettings["OPCServer"]; if (opcServer.isConnectedDA == false) { rtc = opcServer.Connect(opcMachineHost, opcServerName); } SrvAccess = new OpcThread(opcServer); } catch (Exception errMsg) { errorMessage = errMsg.Message; throw errMsg; } return(HRESULTS.Succeeded(rtc)); }
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 bool Write(int[] arrHSrv, object[] arrVal, out int[] arrErr) { arrErr = null; int count = arrHSrv.Length; if (count != arrVal.Length) { Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT); } IntPtr ptrErr; int hresult = ifSync.Write(count, arrHSrv, arrVal, out ptrErr); if (HRESULTS.Failed(hresult)) { Marshal.ThrowExceptionForHR(hresult); } arrErr = new int[count]; Marshal.Copy(ptrErr, arrErr, 0, count); Marshal.FreeCoTaskMem(ptrErr); return(hresult == HRESULTS.S_OK); }
// ----------------------------------------------------------------------------------- public bool SetClientHandles(int[] arrHSrv, int[] arrHClt, out int[] arrErr) { arrErr = null; int count = arrHSrv.Length; if (count != arrHClt.Length) { Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT); } IntPtr ptrErr; int hresult = ifItems.SetClientHandles(count, arrHSrv, arrHClt, out ptrErr); if (HRESULTS.Failed(hresult)) { Marshal.ThrowExceptionForHR(hresult); } arrErr = new int[count]; Marshal.Copy(ptrErr, arrErr, 0, count); Marshal.FreeCoTaskMem(ptrErr); return(hresult == HRESULTS.S_OK); }
public static bool GetOPCServerStatus(OpcServer opcSer, out int opcSerStatus) { bool theGetServerStatusSucceed = false; opcSerStatus = -1; SERVERSTATUS theServerStatus; try { opcSerStatus = opcSer.GetStatus(out theServerStatus); if (HRESULTS.Succeeded(opcSerStatus)) { theGetServerStatusSucceed = true; } } catch (Exception err) { NLogHelper.ExceptionInfo(err, "GetOPCServerStatus error :{0}", err.Message); } return(theGetServerStatusSucceed); }
/// <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 double ReadAnalogDoubleItem(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 { return(Convert.ToDouble(state.DataValue.ToString())); } 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); } }
/// <summary> /// This function reads a tag value from OPC, read will be from Device, Return ERROR in case of any error /// </summary> /// <param name="tagName"></param> /// <returns></returns> public string ReadStringItem(String tagName) { ItemDef ItemData = new ItemDef(); ItemData = readGroup.Item(tagName); OPCItemState state = new OPCItemState(); // Read from device OPCDATASOURCE dsrc = OPCDATASOURCE.OPC_DS_CACHE; //?????????? 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 { return(state.DataValue.ToString()); } 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 ReadAllOPCData() { var iHnd = new Int32[numberOfReadOPCTags]; for (int i = 0; i < numberOfReadOPCTags; i++) { iHnd[i] = listOfOpcResults[i][0].HandleServer; } OPCItemState[] readState; int rtc = OPCReadGroup.Read( OPCDATASOURCE.OPC_DS_DEVICE, iHnd, out readState); if (HRESULTS.Failed(rtc)) { for (int i = 0; i < numberOfReadOPCTags; i++) { if (iHnd[i] == 0) { throw new ArgumentException( "Could not read " + opcReadTags[i]); } } } int mmIIopcTagIndex = 0; for (int i = 0; i < numberOfReadOPCTags; i++) { if (opcTags.OPCTags[mmIIopcTagIndex].FullName == "Nova Server.GetSample.RawValue01.Value") { mmIIopcTagIndex++; } opcTags.OPCTags[mmIIopcTagIndex].ObjectValue = readState[i].DataValue; mmIIopcTagIndex++; } }
public void AsynchReadListenerForPS(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[] { '.' }); string channel = ""; string machineName = ""; string tag_Name = ""; if (iterateItemName.Length == 3) { channel = iterateItemName[0].ToString(); machineName = iterateItemName[1].ToString(); tag_Name = iterateItemName[2].ToString(); updateDataFromOpcListener = new Thread(delegate() { UpdateMachineTagValueToDBFromListener(machineName, tag_Name, res.DataValue); }); updateDataFromOpcListener.IsBackground = true; updateDataFromOpcListener.Start(); } } } } catch (Exception errMsg) { } }
/// <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); }
public void QueryAvailableLocaleIDs(out int[] lcids) { lcids = null; int count; IntPtr ptrIds; int hresult = ifCommon.QueryAvailableLocaleIDs(out count, out ptrIds); if (HRESULTS.Failed(hresult)) { Marshal.ThrowExceptionForHR(hresult); } if (((int)ptrIds) == 0) { return; } if (count < 1) { Marshal.FreeCoTaskMem(ptrIds); return; } lcids = new int[count]; Marshal.Copy(ptrIds, lcids, 0, count); Marshal.FreeCoTaskMem(ptrIds); }
private void FireDataChange(int dwTransid, int hGroup, int hrMasterquality, int hrMastererror, int dwCount, IntPtr phClientItems, IntPtr pvValues, IntPtr pwQualities, IntPtr pftTimeStamps, IntPtr ppErrors) { HistoryData[] clents = new HistoryData[dwCount]; for (int i = 0; i < dwCount; i++) { ITag item = GetItemByID(Marshal.ReadInt16(phClientItems)); if (item == null) { continue; } if (HRESULTS.Succeeded(Marshal.ReadInt32(ppErrors))) { Storage value = Storage.Empty; VarEnum vt = (VarEnum)Marshal.ReadInt32(pvValues); switch (item.Address.VarType) { case DataType.BOOL: value.Boolean = Marshal.ReadByte(pvValues + 8) > 0; break; case DataType.BYTE: value.Byte = Marshal.ReadByte(pvValues + 8); break; case DataType.WORD: value.Word = (ushort)Marshal.ReadInt16(pvValues + 8); break; case DataType.SHORT: value.Int16 = Marshal.ReadInt16(pvValues + 8); break; case DataType.DWORD: value.DWord = (uint)Marshal.ReadInt32(pvValues + 8); break; case DataType.INT: value.Int32 = Marshal.ReadInt32(pvValues + 8); break; case DataType.FLOAT: if (vt == VarEnum.VT_UI2) { ushort us = (ushort)Marshal.ReadInt16(pvValues + 8); value.Single = Convert.ToSingle(us); } else { float[] x = new float[1]; Marshal.Copy(pvValues + 8, x, 0, 1); value.Single = x[0]; } break; case DataType.SYS: case DataType.STR: string str = Marshal.PtrToStringUni(Marshal.ReadIntPtr(pvValues + 8)); StringTag tag = item as StringTag; if (tag != null) { tag.String = str; } break; default: value.Boolean = Marshal.ReadByte(pvValues + 8) > 0; break; } DateTime time = DateTime.FromFileTime(Marshal.ReadInt64(pftTimeStamps)); QUALITIES quality = (QUALITIES)Marshal.ReadInt16(pwQualities); clents[i].ID = item.ID; clents[i].Quality = quality; clents[i].Value = value; clents[i].TimeStamp = time; item.Update(value, time, quality); } ppErrors += 4; phClientItems += 4; pvValues += 16; pwQualities += 2; pftTimeStamps += 8; } DataChange(this, new DataChangeEventArgs(1, clents)); }
public HistoryData[] BatchRead(DataSource source, bool isSync, params ITag[] itemArray) { IntPtr pErrors; int len = itemArray.Length; int result = 0; int[] arrHSrv = Array.ConvertAll(itemArray, c => c.Address.Start); HistoryData[] values = new HistoryData[len]; if (isSync) { IntPtr pItemValues; result = _sync.Read((OPCDATASOURCE)source, len, arrHSrv, out pItemValues, out pErrors); if (HRESULTS.Succeeded(result)) { for (int i = 0; i < len; i++) { var item = itemArray[i]; if (Marshal.ReadInt32(pErrors) == 0) { switch (item.Address.VarType) { case DataType.BOOL: values[i].Value.Boolean = Marshal.ReadByte(pItemValues + 16) > 0; break; case DataType.BYTE: values[i].Value.Byte = Marshal.ReadByte(pItemValues + 16); break; case DataType.WORD: values[i].Value.Word = (ushort)Marshal.ReadInt16(pItemValues + 16); break; case DataType.SHORT: values[i].Value.Int16 = Marshal.ReadInt16(pItemValues + 16); break; case DataType.DWORD: values[i].Value.DWord = (uint)Marshal.ReadInt32(pItemValues + 16); break; case DataType.INT: values[i].Value.Int32 = Marshal.ReadInt32(pItemValues + 16); break; case DataType.FLOAT: float[] x = new float[1]; Marshal.Copy(pItemValues + 16, x, 0, 1); values[i].Value.Single = x[0]; break; case DataType.STR: string str = Marshal.PtrToStringUni(Marshal.ReadIntPtr(pItemValues + 16)); StringTag tag = item as StringTag; if (tag != null) { tag.String = str; } break; } values[i].ID = item.ID; values[i].Quality = (QUALITIES)Marshal.ReadInt16(pItemValues + 12); values[i].TimeStamp = Marshal.ReadInt64(pItemValues + 4).ToDateTime(); item.Update(values[i].Value, values[i].TimeStamp, values[i].Quality); } pItemValues += 32; pErrors += 4; } Marshal.FreeCoTaskMem(pItemValues); } else { Marshal.FreeCoTaskMem(pItemValues); return(null); } } else { int cancelID = 0; result = _async.Read(len, arrHSrv, 1, out cancelID, out pErrors); } Marshal.FreeCoTaskMem(pErrors); return(values); }
public bool AddItems(IList <TagMetaData> items) { int count = items.Count; if (_items == null) { _items = new List <ITag>(count); mapping = new Dictionary <short, ITag>(count); } List <OPCITEMDEF> itemArray = new List <OPCITEMDEF>(count); for (int i = 0; i < count; i++) { if (items[i].GroupID == this._Id) { itemArray.Add(new OPCITEMDEF { hClient = items[i].ID, szItemID = items[i].Address, bActive = true, wReserved = (short)i }); } } IntPtr pAddResults; IntPtr pErrors; if (!HRESULTS.Succeeded(_itemMgt.AddItems(itemArray.Count, itemArray.ToArray(), out pAddResults, out pErrors))) { return(false); } int iStructSize = Marshal.SizeOf(typeof(OPCITEMRESULT)); lock (_server.SyncRoot) { for (int i = 0; i < itemArray.Count; i++) { try { if (Marshal.ReadInt32(pErrors) == 0) { ITag dataItem = null; var itemDef = itemArray[i]; //string addr = string.Concat(_serverId, ',', Marshal.ReadInt32(pAddResults)); DataType type = items[itemDef.wReserved].DataType; switch (type) { case DataType.BOOL: dataItem = new BoolTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 1, 0, DataType.BOOL), this); break; case DataType.BYTE: dataItem = new ByteTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 1, 0, DataType.BYTE), this); break; case DataType.WORD: dataItem = new UShortTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 2, 0, DataType.WORD), this); break; case DataType.SHORT: dataItem = new ShortTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 2, 0, DataType.SHORT), this); break; case DataType.INT: dataItem = new IntTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 4, 0, DataType.INT), this); break; case DataType.DWORD: dataItem = new UIntTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 4, 0, DataType.DWORD), this); break; case DataType.FLOAT: dataItem = new FloatTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 4, 0, DataType.FLOAT), this); break; case DataType.SYS: case DataType.STR: dataItem = new StringTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 64, 0, DataType.STR), this); break; default: break; //case VarEnum.VT_ARRAY: // dataItem = new ArrayTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), (byte)Marshal.ReadInt16(pAddResults + 18), 0, DataType.ARRAY), this); // break; } if (dataItem != null) { _items.Add(dataItem); mapping.Add((short)itemDef.hClient, dataItem); _server.AddItemIndex(items[itemDef.wReserved].Name, dataItem); } pAddResults += iStructSize; pErrors += 4; } } catch (Exception err) { if (err.Message != null) { } } } //Marshal.FreeCoTaskMem(pAddResults); //Marshal.FreeCoTaskMem(pErrors); _items.TrimExcess(); return(true); } }
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; * } */ }
/// <summary> /// Get a list of <see cref="OpcPropertyItem"/> for the specified item ID. /// </summary> /// <param name="itemID">The item ID to get the list of properties</param> /// <param name="propertyIDs">An array of requested property IDs, <see cref="QueryAvailableProperties"/>.</param> /// <returns></returns> public OpcPropertyItem[] LookupItemIDs(string itemID, int[] propertyIDs) { ThrowIfDisposed(); int count = propertyIDs.Length; if (count < 1) { return(new OpcPropertyItem[0]); } IntPtr ptrErr = IntPtr.Zero; IntPtr ptrIds = IntPtr.Zero; try { int hresult = opcItemProperties.LookupItemIDs(itemID, count, propertyIDs, out ptrIds, out ptrErr); if (HRESULTS.Failed(hresult)) { Marshal.ThrowExceptionForHR(hresult); } if ((ptrIds == IntPtr.Zero) || (ptrErr == IntPtr.Zero)) { Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT); } OpcPropertyItem[] propertyItems = new OpcPropertyItem[count]; IntPtr ptrString; for (int i = 0; i < count; i++) { propertyItems[i] = new OpcPropertyItem { PropertyID = propertyIDs[i], Error = Extensions.ReadInt32(ptrErr, i) }; if (propertyItems[i].Error == HRESULTS.S_OK) { ptrString = (IntPtr)Extensions.ReadInt32(ptrIds, i); propertyItems[i].NewItemID = Marshal.PtrToStringUni(ptrString); Marshal.FreeCoTaskMem(ptrString); } else { propertyItems[i].NewItemID = null; } } return(propertyItems); } finally { if (ptrIds != IntPtr.Zero) { Marshal.FreeCoTaskMem(ptrIds); } if (ptrErr != IntPtr.Zero) { Marshal.FreeCoTaskMem(ptrErr); } } }
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; * } */ }
// ------------------------------ events ----------------------------- public void theGrp_DataChange(object sender, DataChangeEventArgs e) { foreach (OPCItemState s in e.sts) { if (HRESULTS.Succeeded(s.Error)) { if (consoleOut == "yes") { Console.WriteLine(" ih={0} v={1} q={2} t={3}", s.HandleClient, s.DataValue, s.Quality, s.TimeStamp); } try { currentValues[s.HandleClient] = Convert.ToSingle(s.DataValue) * Single.Parse(ratios[s.HandleClient]) + Single.Parse(offsets[s.HandleClient]); } catch (FormatException fex) { Console.WriteLine("Неверный формат числа. Используй запятую вместо точки. {0} ", fex); File.WriteAllText("error" + DateTime.Now.ToString("HHmmss") + ".txt", "Неверный формат числа. Используй запятую вместо точки." + "\n " + fex.ToString() + "\n " + fex.Message); theSrv.Disconnect(); } } else { Console.WriteLine(" ih={0} ERROR=0x{1:x} !", s.HandleClient, s.Error); } } string responseString = "{"; for (int i = 0; i < currentValues.Length - 1; i++) { string value = ""; if ((isbool[i] == "b" && currentValues[i] == 1) || (isbool[i] == "!b" && currentValues[i] == 0)) { value = "true"; } else if ((isbool[i] == "b" && currentValues[i] == 0) || (isbool[i] == "!b" && currentValues[i] == 1)) { value = "false"; } else { value = currentValues[i].ToString(); } responseString = responseString + "\"tag" + i + "\":\"" + value + "\", "; } string valuelast = ""; int lasti = currentValues.Length - 1; if ((isbool[lasti] == "b" && currentValues[lasti] == 1) || (isbool[lasti] == "!b" && currentValues[lasti] == 0)) { valuelast = "true"; } else if ((isbool[lasti] == "b" && currentValues[lasti] == 0) || (isbool[lasti] == "!b" && currentValues[lasti] == 1)) { valuelast = "false"; } else { valuelast = currentValues[lasti].ToString(); } responseString = responseString + "\"tag" + (lasti) + "\":\"" + valuelast + "\"}"; responseStringG = responseString; byte[] byteArray = new byte[sendtags * 4]; Buffer.BlockCopy(currentValues, 0, byteArray, 0, byteArray.Length); if (udpSend == "yes") { UDPsend(byteArray); } }
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(); }
public HRESULT(HRESULTS value) : this((int)value) { }
public static HRESULT FromHRESULTS(HRESULTS result) => new HRESULT(result);
public void TestCreateHRESULTS01() { HRESULTS hRESULTS = CreateHRESULTS01(); Assert.IsNotNull(hRESULTS); }