public void PLCRead() { try { // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; Random rnd = new Random(); int transactionID = rnd.Next(1, 55667788); theGrp.Read(handlesSrv, transactionID, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); //theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); //theGrp.RemoveItems(handlesSrv, out aE); //теперь здесь //theGrp.Remove(false); } catch (Exception e) { SetText("Unexpected Error:" + e.Message); return; } }
public void TestErr_Read01() { //Testing --- out parameters are null int[] arrHSrv = new int[1]; OPCItemState[] arrStat = null; //Test Procedure Call bool b = group.Read(OPCDATASOURCE.OPC_DS_CACHE, arrHSrv, out arrStat); }
public override void RunOnce() { _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : RunOnce вход"); //Создадим соединение if (!Connect()) { throw new Exception("[" + this._name + "] : Ошибка подключения! "); } //Синхронный режим прямой вызов OPCItemState[] _opcitmstate; //--Тестовая секция-- lock (lockThis) { _opcgrp.Read(_opcds, _serverhandles, out _opcitmstate); } for (int i = 0; i < _maps.GetLength(0); i++) { Tag tag = _server.GetTag(_maps[i, 0]); if (_opcitmstate[i].Error == HRESULTS.S_OK) { if (_opcitmstate[i].DataValue is byte[]) { _opcitmstate[i].DataValue = ByteArrayToString((byte[])_opcitmstate[i].DataValue); } else { tag.Value = _opcitmstate[i].DataValue; } tag.Timestamp = new DateTime(_opcitmstate[i].TimeStamp); tag.Quality = (QualityType)Convert.ToByte(_opcitmstate[i].Quality); _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : " + _maps[i, 1] + "=" + tag.Value); } else { tag.Quality = QualityType.BAD; _server.LogWrite(LogType.ERROR, "[" + this._name + "] : tag=" + _maps[i, 0] + ", opctag=" + _maps[i, 1] + ", ошибка: " + _opcitmstate[i].Error); } _server.SetTag(tag); } //--Тестовая секция-- //Отключим соединение если не требуется хранить его Disconnect(); _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : RunOnce выход"); }
public void ReadItems() { _itemAccessMutex.WaitOne(); try { int l_Index = 0; OpcItemState[] l_ItemStateArray; List <int> l_ServerHandleList = _serverModel.GetServerHandleList(); _group.Read(OpcDataSource.OPC_DS_DEVICE, l_ServerHandleList.ToArray(), out l_ItemStateArray); foreach (int l_ServerHandle in l_ServerHandleList) { if (l_ItemStateArray[l_Index].Error == HResults.S_OK) { int l_ClientHandle = _serverModel.GetClientHandleFromServerHandle(l_ServerHandle); Dictionary <string, string> l_ItemProps = new Dictionary <string, string>(); IOPCItem l_Item = _serverModel.GetItemFromClientHandle(l_ClientHandle); l_ItemProps.Add(CModel.ServerModel.ItemPropValueKey, OpcUtility.ValueToString(l_Item.Type, l_ItemStateArray[l_Index].DataValue)); l_ItemProps.Add(CModel.ServerModel.ItemPropQualityKey, OpcUtility.QualityToString(l_ItemStateArray[l_Index].Quality)); l_ItemProps.Add(CModel.ServerModel.ItemPropTimestampKey, OpcUtility.TimeStampToString(l_ItemStateArray[l_Index].Timestamp)); _serverModel.UpdateItem(l_ClientHandle, l_ItemProps); } l_Index++; } } catch (Exception l_Ex) { Disconnect(); throw l_Ex; } finally { _itemAccessMutex.ReleaseMutex(); } }
public void updateItems() { if (OpcSrv == null) { Debug.WriteLine("Not connected"); return; } if (OpcGrp == null) { Debug.WriteLine("OPC group not created"); return; } int rtc = OpcGrp.Read(OPCDATASOURCE.OPC_DS_CACHE, ItemHandles, out result); if (HRESULTS.Failed(rtc)) { Debug.WriteLine("Read error 0x" + rtc.ToString("X")); } else // display the read values { string txt = ""; for (int i = 0; i < result.Length; ++i) { if (i > 0) { txt += "\r\n"; } if (HRESULTS.Failed(result[i].Error)) { txt += "Error 0x" + result[i].Error.ToString("X"); } else { txt += result[i].DataValue.ToString(); } } } }
private void bwLer_DoWork(object sender, DoWorkEventArgs e) { //Esse loop fica em verdadeiro (rodando sempre) quando clico no botão de leitura: while (lerTag) { //Esse método abaixo faz a leitura OPC de todos os tags que eu tiver cadastrado rtc = oGrp.Read(OPCDA.OPCDATASOURCE.OPC_DS_CACHE, iHnd, out rslt); for (int i = 0; i < tags.Count; i++) { //Isso aqui é só um tratamento para ver se não veio dado vazio, se vier, escrever erro na tela: if (rslt[i].DataValue == null) { //Condição de erro de leitura this.Invoke(new MethodInvoker(delegate { })); } else { //Se estiver OK o valor, escreve seu valor lido na tela: this.Invoke(new MethodInvoker(delegate { lv_tagList.Items[i].SubItems[1].Text = rslt[i].DataValue.ToString(); itensValor[i] = rslt[i].DataValue.ToString(); string nomeTag = tags[i].Substring(shortcut.Length); insertDb(buscaTagId(nomeTag), rslt[i].DataValue.ToString()); })); } System.Threading.Thread.Sleep(tempoScan); } } //Esse método abaixo faz a desconexão com o OPC Server. srv.Disconnect(); }
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 Work() { /* try // disabled for debugging * { */ theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! // add our only working group theGrp = theSrv.AddGroup("OPCCSharp-Group", false, 900); // add two items and save server handles itemDefs[0] = new OPCItemDef(itemA, true, 1234, VarEnum.VT_EMPTY); itemDefs[1] = new OPCItemDef(itemB, true, 5678, VarEnum.VT_EMPTY); OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { Console.WriteLine("OPC Tester: AddItems - some failed"); theGrp.Remove(true); theSrv.Disconnect(); return; } ; handlesSrv[0] = rItm[0].HandleServer; handlesSrv[1] = rItm[1].HandleServer; // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; theGrp.Read(handlesSrv, 55667788, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); // asynch write object[] itemValues = new object[2]; itemValues[0] = (int)1111111; itemValues[1] = (double)2222.2222; theGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete); theGrp.Write(handlesSrv, itemValues, 99887766, out CancelID, out aE); // some delay for asynch write-complete callback (simplification) Thread.Sleep(500); // disconnect and close Console.WriteLine("************************************** hit to close..."); Console.ReadLine(); theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); theGrp.RemoveItems(handlesSrv, out aE); theGrp.Remove(false); theSrv.Disconnect(); theGrp = null; theSrv = null; /* } * catch( Exception e ) * { * Console.WriteLine( "EXCEPTION : OPC Tester " + e.ToString() ); * return; * } */ }
static void Main(string[] args) { /*create array of readable Tags*/ var Tags = new List <OPCClientItem>(); Tags.Add(new OPCClientItem() { Name = ".test", ClientHanle = 1 }); OpcServer server = new OpcServer(); try { int transactionID = new Random().Next(1024, 65535); int cancelID = 0; int updateRate = 1000; /*connect to the OPC Server and check it's state*/ server.Connect("Matrikon.OPC.Simulation.1"); var serverStatus = new SERVERSTATUS(); server.GetStatus(out serverStatus); if (serverStatus.eServerState == OPCSERVERSTATE.OPC_STATUS_RUNNING) { /*create group of items*/ OpcGroup group = server.AddGroup("Group1", true, updateRate); group.ReadCompleted += group_ReadCompleted; List <OPCItemDef> items = new List <OPCItemDef>(); Tags.ToList() .ForEach(x => items.Add(new OPCItemDef(x.Name, true, x.ClientHanle, VarEnum.VT_EMPTY))); /* add items and collect their attributes*/ OPCItemResult[] itemAddResults = null; group.AddItems(items.ToArray(), out itemAddResults); for (int i = 0; i < itemAddResults.Length; i++) { OPCItemResult itemResult = itemAddResults[i]; OPCClientItem tag = Tags[i]; tag.ServerHandle = itemResult.HandleServer; tag.AccessRight = (itemResult.AccessRights == OPCACCESSRIGHTS.OPC_READABLE) ? OPCClientItem.EAccessRight.ReadOnly : OPCClientItem.EAccessRight.ReadAndWrite; } ; /*Refresh items in group*/ // group.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE, transactionID, out cancelID); /*Async read data for the group items*/ int[] serverHandles = new int[Tags.Count]; for (int i = 0; i < Tags.Count; i++) { serverHandles[i] = Tags[i].ServerHandle; } ; OPCItemState[] itemsStateResult = null; /*sync read*/ group.Read(OPCDATASOURCE.OPC_DS_DEVICE, serverHandles, out itemsStateResult); Console.WriteLine("Sync read:"); for (int i = 0; i < itemsStateResult.Length; i++) { OPCItemState itemResult = itemsStateResult[i]; Console.WriteLine(" -> item:{0}; value:{1}; timestamp{2}; qualituy:{3}", Tags[i].Name, itemResult.DataValue.ToString(), itemResult.TimeStamp, itemResult.Quality); } ; /*sync write*/ object[] values = new object[Tags.Count]; int[] resultErrors = new int[Tags.Count]; values[0] = (object)256; group.Write(serverHandles, values, out resultErrors); /*async read*/ group.Read(serverHandles, transactionID, out cancelID, out resultErrors); /*wait for a while befor remove group to process async event*/ System.Threading.Thread.Sleep(3000); /*the group must be removed !!! */ group.Remove(true); } ; } finally { server.Disconnect(); server = null; GC.Collect(); }; Console.ReadKey(); }
public void Work() { /* try // disabled for debugging * { */ theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! // add our only working group theGrp = theSrv.AddGroup("OPCCSharp-Group", false, timeref); if (sendtags > tags.Length) { sendtags = tags.Length; } var itemDefs = new OPCItemDef[tags.Length]; for (var i = 0; i < tags.Length; i++) { itemDefs[i] = new OPCItemDef(tags[i], true, i, VarEnum.VT_EMPTY); } OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { Console.WriteLine("OPC Tester: AddItems - some failed"); theGrp.Remove(true); theSrv.Disconnect(); return; } ; var handlesSrv = new int[itemDefs.Length]; for (var i = 0; i < itemDefs.Length; i++) { handlesSrv[i] = rItm[i].HandleServer; } currentValues = new Single[itemDefs.Length]; // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; theGrp.Read(handlesSrv, 55667788, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); while (webSend == "yes") { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; context.Response.AddHeader("Access-Control-Allow-Origin", "*"); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseStringG); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); } // disconnect and close Console.WriteLine("************************************** hit <return> to close..."); Console.ReadLine(); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); theGrp.RemoveItems(handlesSrv, out aE); theGrp.Remove(false); theSrv.Disconnect(); theGrp = null; theSrv = null; /* } * catch( Exception e ) * { * Console.WriteLine( "EXCEPTION : OPC Tester " + e.ToString() ); * return; * } */ }
static void Main(string[] args) { string progID = args.Length > 0 ? args[0] : "Kepware.KEPServerEX.V5"; OpcServer opcServer = new OpcServer(); opcServer.Connect(progID); System.Threading.Thread.Sleep(500); // we are faster than some servers! OpcGroup opcGroup = opcServer.AddGroup("SampleGroup", false, 900); List <string> itemNames = new List <string>(); if (args.Length > 1) { for (int i = 1; i < args.Length; i++) { itemNames.Add(args[i]); } } else { itemNames.Add("Simulation Examples.Functions.Ramp1"); itemNames.Add("Simulation Examples.Functions.Random1"); } OpcItemDefinition[] opcItemDefs = new OpcItemDefinition[itemNames.Count]; for (int i = 0; i < opcItemDefs.Length; i++) { opcItemDefs[i] = new OpcItemDefinition(itemNames[i], true, i, VarEnum.VT_EMPTY); } opcGroup.AddItems(opcItemDefs, out OpcItemResult[] opcItemResult); if (opcItemResult == null) { Console.WriteLine("Error add items - null value returned"); return; } int[] serverHandles = new int[opcItemResult.Length]; for (int i = 0; i < opcItemResult.Length; i++) { if (HRESULTS.Failed(opcItemResult[i].Error)) { Console.WriteLine("AddItems - failed {0}", itemNames[i]); opcGroup.Remove(true); opcServer.Disconnect(); return; } else { serverHandles[i] = opcItemResult[i].HandleServer; } } opcGroup.SetEnable(true); opcGroup.Active = true; bool result = opcGroup.Read(OPCDATASOURCE.OPC_DS_CACHE, serverHandles, out OpcItemState[] states); foreach (OpcItemState s in states) { if (HRESULTS.Succeeded(s.Error)) { Console.WriteLine(" {0}: {1} (Q:{2} T:{3})", s.HandleClient, s.DataValue, s.Quality, DateTime.FromFileTime(s.TimeStamp)); } else { Console.WriteLine(" {0}: ERROR = 0x{1:x} !", s.HandleClient, s.Error); } } opcGroup.Remove(true); opcServer.Disconnect(); }
public void Work() { theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! // add our only working group theGrp = theSrv.AddGroup("Group", false, 900); theTargGrp = theSrv.AddGroup("Target", false, 900); // add two items and save server handles itemDefs[0] = new OPCItemDef(itemA, true, 1, VarEnum.VT_EMPTY); itemDefs[1] = new OPCItemDef(itemB, true, 2, VarEnum.VT_EMPTY); // itemTarget[0] = new OPCItemDef(itemC, true, 1, VarEnum.VT_EMPTY); OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { AddTotextBox("OPC Tester: AddItems - some failed", textBox4); theGrp.Remove(true); theSrv.Disconnect(); return; } ; handlesSrv[0] = rItm[0].HandleServer; handlesSrv[1] = rItm[1].HandleServer; OPCItemResult[] rItmTarg; theTargGrp.AddItems(itemTarget, out rItmTarg); if (rItmTarg == null) { return; } if (HRESULTS.Failed(rItmTarg[0].Error)) { AddTotextBox("OPC Tester: AddItems - some failed", textBox4); theGrp.Remove(true); theSrv.Disconnect(); return; } ; handlesTargetSrv[0] = rItmTarg[0].HandleServer; //---------------------------------------------------------------------------------- // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; theGrp.Read(handlesSrv, 55667788, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); // asynch write theTargGrp.SetEnable(true); theTargGrp.Active = true; object[] itemValues = new object[1]; itemValues[0] = (int)450; theTargGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete); theTargGrp.Write(handlesTargetSrv, itemValues, 99887766, out CancelID, out aE); // some delay for asynch write-complete callback (simplification) Thread.Sleep(500); theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); }
public void PLCWrite() { try { theSrv = new OpcServer(); theSrv.Connect(serverProgID); Thread.Sleep(500); // we are faster then some servers! //add our only working group theGrp = theSrv.AddGroup("Group", false, 900); //add two items and save server handles itemDefs[0] = new OPCItemDef(itemA, true, 1, VarEnum.VT_EMPTY); itemDefs[1] = new OPCItemDef(itemB, true, 2, VarEnum.VT_EMPTY); OPCItemResult[] rItm; theGrp.AddItems(itemDefs, out rItm); if (rItm == null) { return; } if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { AddTotextBox("OPC Tester: AddItems - some failed", textBox4); theGrp.Remove(true); theSrv.Disconnect(); return; } ; if (handlesSrv[0] == 0) { handlesSrv[0] = rItm[0].HandleServer; handlesSrv[1] = rItm[1].HandleServer; } // asynch read our two items theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete); int CancelID; int[] aE; Random rnd = new Random(); int transactionID = rnd.Next(1, 55667788); theGrp.Read(handlesSrv, transactionID, out CancelID, out aE); // some delay for asynch read-complete callback (simplification) Thread.Sleep(500); theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete); //theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); //theGrp.RemoveItems(handlesSrv, out aE); //теперь здесь //theGrp.Remove(false); } catch (Exception e) { SetText("Unexpected Error:" + e.Message); return; } }