private void DateTimeSample_FormClosing(object sender, FormClosingEventArgs e) { client.DeleteVariableHandle(hdate1); client.DeleteVariableHandle(htime1); client.DeleteVariableHandle(hdate2); client.Dispose(); }
public bool ReadBool(string pou, string variableName) { try { var hVar = _tcClient.CreateVariableHandle(pou + "." + variableName); var readVariable = _tcClient.ReadAny(hVar, typeof(bool)); _tcClient.DeleteVariableHandle(hVar); return(bool.Parse(readVariable.ToString())); } catch (AdsErrorException) { Debug.LogError("TC Read Error - Bool" + pou + "." + variableName); return(false); } }
public bool writeToPLCString(string sName, string sValue) { bool bret = true; TcAdsClient tcClient = new TcAdsClient(); AdsStream dataStream = new AdsStream(100); AdsBinaryReader binReader = new AdsBinaryReader(dataStream); int iHandle = 0; tcClient.Connect(851); iHandle = tcClient.CreateVariableHandle(sName); try { tcClient.WriteAnyString(iHandle, sValue, sValue.Length, Encoding.Default); } catch (Exception ex) { Console.WriteLine(ex.Message); bret = false; } finally { tcClient.DeleteVariableHandle(iHandle); tcClient.Dispose(); } return(bret); }
public static void WriteBusQueue(List <string> list) { try { WriteTwincat("GVL.EraseTable", true); TcAdsClient client = new TcAdsClient(); client.Connect(amsnetid, Convert.ToInt32(amsnetport)); int handle = client.CreateVariableHandle("GVL.DataFromBus"); foreach (string el in list) { AdsStream stream = new AdsStream(500); AdsBinaryWriter writer = new AdsBinaryWriter(stream); writer.WritePlcString(el, 500, Encoding.Unicode); client.Write(handle, stream); stream.Dispose(); writer.Dispose(); Thread.Sleep(10); } client.DeleteVariableHandle(handle); client.Dispose(); } catch (Exception ex) { Console.WriteLine("BusWrite: " + ex.Message); } }
/** * Reads one variable from the PLC. The variable must be declared as a REAL. * * Input: * tcAds - TwinCat ADS client object * var - The variable name (as a string) to be read from the PLC. E.g "MAIN.var1" * vartype - The variable type as declared in the PLC. REAL is the only supported variable type. * More types can be added by making changes where appropriate. * * Output: Floating value representing the value in the PLC. * **/ static float readByString(TcAdsClient tcAds, string var, string vartype) { int hVar = 0; try { hVar = tcAds.CreateVariableHandle(var); } catch (Exception err) { Console.WriteLine(err); } if (vartype == "REAL") { // creates a stream with a length of 4 byte AdsStream ds = new AdsStream(4); BinaryReader br = new BinaryReader(ds); tcAds.Read(hVar, ds); try { tcAds.DeleteVariableHandle(hVar); } catch (Exception err) { Console.WriteLine(err); } return(br.ReadSingle()); } else { Console.WriteLine("Error: Variable type not implemented!"); return(0.0F); } }
//TcAdsClient tcClient = new TcAdsClient(); //AdsStream dataStream = new AdsStream(4); //AdsBinaryReader binReader = new AdsBinaryReader(dataStream); public bool writeToPLCInt(string sName, int iValue) { TcAdsClient tcClient = new TcAdsClient(); AdsStream dataStream = new AdsStream(4); AdsBinaryReader binReader = new AdsBinaryReader(dataStream); int iHandle = 0; tcClient.Connect(851); iHandle = tcClient.CreateVariableHandle(sName); try { tcClient.WriteAny(iHandle, iValue); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { tcClient.DeleteVariableHandle(iHandle); tcClient.Dispose(); } return(true); }
private void OnExit(object sender, EventArgs e) { //enable resources try { adsClient.DeleteVariableHandle(hTemperature); adsClient.DeleteVariableHandle(hProducedPieces); adsClient.DeleteVariableHandle(hIsRunning); } catch (Exception err) { Console.WriteLine(err.Message); Console.ReadLine(); } adsClient.Dispose(); }
static void Main(string[] args) { TcAdsClient tcClient = new TcAdsClient(); AdsStream dataStream = new AdsStream(4); AdsBinaryReader binReader = new AdsBinaryReader(dataStream); int handle = 0; int iValue = 0; int exValue = 0; string variable, adres; DateTime now = DateTime.Now; Console.WriteLine("Podaj adres serwera ADS: "); adres = Console.ReadLine(); Console.WriteLine("Podaj nazwe zmienna do zapysywania w bazie danych: "); variable = Console.ReadLine(); FileStream File = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter writer = new StreamWriter(File); writer.WriteLine(adres + " 801 " + variable + " " + now.ToString("F")); try { tcClient.Connect(adres, 801); handle = tcClient.CreateVariableHandle(variable); Console.WriteLine("Czekam na znak"); do { tcClient.Read(handle, dataStream); iValue = binReader.ReadInt32(); dataStream.Position = 0; if (iValue != exValue) { writer.WriteLine(iValue + " " + now.ToString("F")); } Console.WriteLine("Aktualna wartosc wynosi: " + iValue); exValue = iValue; } while (Console.ReadKey().Key.Equals(ConsoleKey.Enter)); } catch (Exception ex) { Console.WriteLine(ex.Message + " xdddd"); } finally { writer.Close(); tcClient.DeleteVariableHandle(handle); tcClient.Dispose(); } Console.ReadKey(); }
private void DataUpdate(object sender, ElapsedEventArgs e) { double[] ActualAngle = new double[7]; //double[] ActualPos = new double[3]; int hvar = new int(); //定义句柄变量 for (int i = 0; i < 6; i++) { string str = $"GVL.OutActPos[{i}]"; hvar = tcclient.CreateVariableHandle(str); ActualAngle[i] = (double)(tcclient.ReadAny(hvar, typeof(double))); tcclient.DeleteVariableHandle(hvar); } string str1 = "MAIN.EcdPos"; hvar = tcclient.CreateVariableHandle(str1); ActualAngle[6] = (int)(tcclient.ReadAny(hvar, typeof(int))); tcclient.DeleteVariableHandle(hvar); //for (int i = 0; i < 3; i++) //{ // string str = $"GVL.Pos_Now[{i}]"; // hvar = tcclient.CreateVariableHandle(str); // ActualPos[i] = (double)(tcclient.ReadAny(hvar, typeof(double))); // tcclient.DeleteVariableHandle(hvar); //} Application.Current.Dispatcher.Invoke(new Action(() => { string anglestr = null; for (int i = 0; i < 7; i++) { anglestr += ActualAngle[i].ToString("F4") + Environment.NewLine; } //anglestr += Environment.NewLine; //for (int i = 0; i < 3; i++) // anglestr += ActualPos[i].ToString("F4") + Environment.NewLine; DataFromPLC.Text = anglestr; //发到ros Publish("/joint_states_real", anglestr); })); }
public async Task <T[]> ReadArray <T>(string PLCName, int size) { string plcname = "." + PLCName; return(await Task.Run(() => { try { int handle = Tcads.CreateVariableHandle(plcname); T[] returnData = (T[])Tcads.ReadAny(handle, typeof(T[]), new int[] { size }); Tcads.DeleteVariableHandle(handle); return returnData; } catch (Exception ex) { ErrorFile.ErrorLog(ex.Message, ADS.Logfilepath); return default; } })); }
public void WriteValue(X parameterName, object value, bool selfVerify = false) { var att = parameterName.GetAttribute <TypeAttribute>(); if (att.RWStatus == TypeAttribute.RW.ReadOnly) { return; } var pName = $"{att.SourceFunction}.{parameterName}"; var writeId = _tcClient.CreateVariableHandle(pName); _tcClient.WriteAny(writeId, value); _tcClient.DeleteVariableHandle(writeId); if (selfVerify) { OnChange(parameterName); } }
/// <summary> /// Subscribe to an observable and write the emitted values to a PLC variable /// /// Use this method to regularly write values to PLC variable. For one-off writes, use the Write() method /// </summary> /// <typeparam name="T"></typeparam> /// <param name="variableName">Name of the PLC variable</param> /// <param name="observable">Observable that emits values to write</param> /// <param name="scheduler">Scheduler to execute the subscription on. By default uses the scheduler the Observable runs on</param> /// <returns>An IDisposable that can be disposed when it's no longer desired to write the values in the observable</returns> public IDisposable StreamTo <T>(string variableName, IObservable <T> observable, IScheduler scheduler = null) { scheduler = scheduler ?? Scheduler.Immediate; int variableHandle = _client.CreateVariableHandle(variableName); var subscription = observable.ObserveOn(scheduler).Subscribe(value => WriteWithHandle(variableHandle, value)); // Return an IDisposable that, when disposed, stops listening to the Observable but also deletes the variable handle return(new CompositeDisposable(subscription, Disposable.Create(() => _client.DeleteVariableHandle(variableHandle)))); }
private void Sample02_FormClosing(object sender, FormClosingEventArgs e) { try { client.DeleteVariableHandle(hPLCVar); } catch (Exception err) { MessageBox.Show(err.Message); } client.Dispose(); }
/// <summary> /// Reads the element from the specified <paramref name="elementPath"/> and returns it. /// </summary> /// <param name="elementPath">The path to read from.</param> /// <param name="typeOfElement">The type of the desired element.</param> /// <returns>The read value.</returns> public object ReadElement(string elementPath, Type typeOfElement) { int handle = -1; try { handle = _twinCatClient.CreateVariableHandle(elementPath); return(_twinCatClient.ReadAny(handle, typeOfElement)); } catch (AdsErrorException e) { var exception = new PlcCommunicationException("Can't read tag " + elementPath, _path, _port.ToString(CultureInfo.InvariantCulture), string.Empty, e); throw exception; } finally { if (handle != -1) { _twinCatClient.DeleteVariableHandle(handle); } } }
//readlreal private void button_Click(object sender, EventArgs e) { TwinCAT_ADS_LOAD(); try { hvar = tcclient.CreateVariableHandle("MAIN.adsstru.KL3068_Value_Ch1"); } catch (Exception err) { MessageBox.Show("get hvar error \n" + err.ToString()); } AdsStream datastream = new AdsStream(8); BinaryReader binread = new BinaryReader(datastream); datastream.Position = 0; try { tcclient.Read(hvar, datastream); readlreal = binread.ReadDouble(); textBox1.Text = readlreal.ToString("0.00"); textBox6.Text = Calc_temper(readlreal).ToString("0.00") + "度"; } catch (Exception err) { MessageBox.Show("read value error"); } try { tcclient.DeleteVariableHandle(hvar); } catch (Exception err) { MessageBox.Show("read delect hvar error"); } }
/// <summary> /// Parses an PLC array of type T. Supports pointered arrays (POINTER TO ...). /// In case of pointered array it will skipp NULL pointers and import only valid instances. /// </summary> /// <typeparam name="T"> /// Marshall type representation in .NET. See Beckhoff TwinCat 3 manual for an example. /// </typeparam> /// <param name="plcPath">The path in PLC to the array.</param> /// <param name="symbolLoader">The symbol loader instance.</param> /// <param name="twinCatClient">The adsClient instance.</param> /// <returns> /// Dictionary of imported and converted (.NET type) array elements and their pathes. /// </returns> public static IDictionary <string, T> GetArrayElementsWithPathes <T>(this TcAdsClient twinCatClient, TcAdsSymbolInfoLoader symbolLoader, string plcPath) { IDictionary <string, T> array = new Dictionary <string, T>(); TcAdsSymbolInfo arraySymbol = symbolLoader.FindSymbol(plcPath); if (arraySymbol == null) { return(array); } var stream = new AdsStream(8); var reader = new AdsBinaryReader(stream); TcAdsSymbolInfo elementSymbol = arraySymbol.FirstSubSymbol; while (elementSymbol != null) { stream.Position = 0; twinCatClient.Read(elementSymbol.IndexGroup, elementSymbol.IndexOffset, stream); var pointerValue = PlcSystem.IsX64Mode ? reader.ReadInt64() : reader.ReadInt32(); if (pointerValue != 0) { string plcArrayElementPath = elementSymbol.Name; if (elementSymbol.IsPointer) { plcArrayElementPath = string.Format("{0}^", plcArrayElementPath); } var handle = twinCatClient.CreateVariableHandle(plcArrayElementPath); try { var element = (T)twinCatClient.ReadAny(handle, typeof(T)); array.Add(plcArrayElementPath, element); } finally { twinCatClient.DeleteVariableHandle(handle); } } elementSymbol = elementSymbol.NextSymbol; } return(array); }
/// <summary> /// Parses an PLC array of type T. Supports pointered arrays (POINTER TO ...). /// In case of pointered array it will skipp NULL pointers and import only valid instances. /// </summary> /// <param name="plcPath">The path in PLC to the array.</param> /// <param name="twinCatClient">The adsClient instance.</param> /// <param name="typeOfElements">Marshall type representation in .NET. See Beckhoff TwinCat 3 manual for an example.</param> /// <returns> /// Dictionary of imported and converted (.NET type) array elements and their pathes. /// </returns> public static IEnumerable GetArrayElements(this TcAdsClient twinCatClient, string plcPath, Type typeOfElements) { var elements = new ArrayList(); TcAdsSymbolInfoLoader symbolLoader = twinCatClient.CreateSymbolInfoLoader(); TcAdsSymbolInfo arraySymbol = symbolLoader.FindSymbol(plcPath); if (arraySymbol == null) { return(elements); } var stream = new AdsStream(8); var reader = new AdsBinaryReader(stream); TcAdsSymbolInfo elementSymbol = arraySymbol.FirstSubSymbol; while (elementSymbol != null) { stream.Position = 0; twinCatClient.Read(elementSymbol.IndexGroup, elementSymbol.IndexOffset, stream); var pointerValue = PlcSystem.IsX64Mode ? reader.ReadInt64() : reader.ReadInt32(); if (pointerValue != 0) { string plcArrayElementPath = elementSymbol.Name; if (elementSymbol.IsPointer) { plcArrayElementPath = string.Format("{0}^", plcArrayElementPath); } var handle = twinCatClient.CreateVariableHandle(plcArrayElementPath); try { object element = twinCatClient.ReadAny(handle, typeOfElements); elements.Add(element); } finally { twinCatClient.DeleteVariableHandle(handle); } } elementSymbol = elementSymbol.NextSymbol; } return(elements); }
public void beat() { try { while (true) { beatVal = !beatVal; tcClient.WriteAny(iHandle, beatVal); Thread.Sleep(1000); } } catch (ThreadAbortException ex) { tcClient.DeleteVariableHandle(iHandle); } }
void DisposeTcADSClient() { try { tcClient.DeleteVariableHandle(hVarTcADS_Write_Enable); tcClient.DeleteVariableHandle(hVarTcADS_Write_Disable); tcClient.DeleteVariableHandle(hVarTcADS_Write_StateRequest); tcClient.DeleteVariableHandle(hVarTcADS_Read_Errors); tcClient.DeleteVariableHandle(hVarTcADS_Read_SystemStates); tcClient.DeleteVariableHandle(hVarTcADS_Read_OpsEnabled); tcClient.DeleteVariableHandle(hVarTcADS_Read_LoggerPaused); tcClient.DeleteVariableHandle(hVarTcADS_Read_DataToADS); } catch (Exception err) { MessageBox.Show(err.Message); } tcClient.Dispose(); }
public static int ReadInt(string VarAdress) { int result = 0; try { hVar = TwinCat3Client.CreateVariableHandle(VarAdress); AdsStream ADSdataStream = new AdsStream(4); BinaryReader binRead = new BinaryReader(ADSdataStream); TwinCat3Client.Read(hVar, ADSdataStream); ADSdataStream.Position = 0; result = binRead.ReadInt32(); TwinCat3Client.DeleteVariableHandle(hVar); hVar = 0; ADSdataStream.Dispose(); binRead.Dispose(); } catch (Exception err) { MessageBox.Show(err.Message); } return(result); }
private void WriteViaVariableHandle() { try { if (currentSymbol != null) { int varHdl = adsClient.CreateVariableHandle(currentSymbol.Name); if (varHdl != 0) { adsClient.WriteAny(varHdl, GetObjectForTypeId(currentSymbol.Datatype, tbWriteWatch.Text)); adsClient.DeleteVariableHandle(varHdl); } } } catch (Exception err) { MessageBox.Show("Failed to write with variable handle. " + err.Message); } }
public void Disconnect() { lock (criticalLock) { try { foreach (KeyValuePair <string, int> dic in handles) { client.DeleteVariableHandle(dic.Value); } handles.Clear(); } catch (Exception e) { string str = string.Format("Occurred exception({0}) in UlTcAdsClient::Disconnect", e.ToString()); throw new Exception(str); } } }
/// <summary> /// Reads a pointer value of the specified <paramref name="typeOfValue"/>. /// </summary> /// <param name="twinCatClient">The twin cat client to read from.</param> /// <param name="plcPath">The path in the PC to the element.</param> /// <param name="typeOfValue">The expected type of the value.</param> /// <returns> /// The value of the element at the specified <paramref name="plcPath"/>. /// </returns> public static object GetPointerValue(this TcAdsClient twinCatClient, string plcPath, Type typeOfValue) { TcAdsSymbolInfoLoader symbolLoader = twinCatClient.CreateSymbolInfoLoader(); TcAdsSymbolInfo symbol = symbolLoader.FindSymbol(plcPath); if (symbol == null) { return(null); } var stream = new AdsStream(8); var reader = new AdsBinaryReader(stream); stream.Position = 0; twinCatClient.Read(symbol.IndexGroup, symbol.IndexOffset, stream); var pointerValue = PlcSystem.IsX64Mode ? reader.ReadInt64() : reader.ReadInt32(); if (pointerValue != 0) { string plcArrayElementPath = symbol.Name; if (symbol.IsPointer) { plcArrayElementPath = string.Format("{0}^", plcArrayElementPath); } var handle = twinCatClient.CreateVariableHandle(plcArrayElementPath); try { return(twinCatClient.ReadAny(handle, typeOfValue)); } finally { twinCatClient.DeleteVariableHandle(handle); } } return(null); }
//------------------------------------------------------ // wird beim Beenden des Programms aufgerufen // is activated when ending the program //------------------------------------------------------ private void Close(object sender, EventArgs e) { try { // Löschen der Notifications und Handles // Deleting of the notifications and handles tcClient.DeleteDeviceNotification(hEngine); tcClient.DeleteDeviceNotification(hDeviceUp); tcClient.DeleteDeviceNotification(hDeviceDown); tcClient.DeleteDeviceNotification(hSteps); tcClient.DeleteDeviceNotification(hCount); tcClient.DeleteDeviceNotification(hSwitchNotify); tcClient.DeleteVariableHandle(hSwitchWrite); } catch (Exception ex) { MessageBox.Show(ex.Message); } tcClient.Dispose(); }
/// <summary> /// Parses an PLC array of type T. Supports pointered arrays (POINTER TO ...). /// </summary> /// <param name="twinCatClient">The adsClient instance.</param> /// <param name="plcPath">The path in PLC to the array.</param> /// <param name="arraySize">Size of the array.</param> /// <param name="type">Marshall type representation in .NET. See Beckhoff TwinCat 3 manual for an example.</param> /// <param name="array">the new instance where the values will be stored in</param> /// <param name="stopReadingPositions">Whether it should continue to read additional values.</param> /// <returns> /// List of imported and converted (.NET type) array elements. /// </returns> /// <remarks> /// This implementation does not use an AdsSymbol loader and fixes some pointer dereferencing issues (11.11.2013). /// It seems the AdsSymbol loader cannot resolve complicated paths using .^ character. /// </remarks> public static IEnumerable ParseArray(this TcAdsClient twinCatClient, string plcPath, int arraySize, Type type, IList array, Func <object, bool> stopReadingPositions = null) { for (int i = 0; i < arraySize; i++) { var handle = twinCatClient.CreateVariableHandle(plcPath + "[" + i + "]"); try { var value = twinCatClient.ReadAny(handle, type); if (stopReadingPositions != null && stopReadingPositions(value)) { break; } array.Add(value); } finally { twinCatClient.DeleteVariableHandle(handle); } } return(array); }
/// <summary> /// Read item array from TwinCAT Variables /// </summary> /// <param name="name"></param> /// <param name="type"></param> /// <param name="arrLength"></param> /// <returns></returns> public object[] ReadArray(string name, string type, int arrLength) { object[] values = new object[arrLength]; int streamLength = StreamLength(type); using (AdsStream dataStream = new AdsStream(arrLength * streamLength)) using (AdsBinaryReader reader = new AdsBinaryReader(dataStream)) { int varHandle = TcClient.CreateVariableHandle(name); TcClient.Read(varHandle, dataStream); dataStream.Position = 0; for (int i = 0; i < arrLength; i++) { values[i] = ReadObjectFromReader(reader, type); } TcClient.DeleteVariableHandle(varHandle); } return(values); }
public static void WriteTwincat(string comando, object valore) { if (!(valore is null)) { using (TcAdsClient client = new TcAdsClient()) { try { client.Connect(amsnetid, Convert.ToInt32(amsnetport)); int handle = client.CreateVariableHandle(comando); if (valore.GetType().FullName.Contains("String")) { string el = valore.ToString(); AdsStream stream = new AdsStream(500); AdsBinaryWriter writer = new AdsBinaryWriter(stream); writer.WritePlcString(el, 500, Encoding.Unicode); client.Write(handle, stream); stream.Dispose(); writer.Dispose(); } else { client.WriteAny(handle, valore); } //client.Dispose(); client.DeleteVariableHandle(handle); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
/** * Reads one variable from the PLC. The variable must be declared as a REAL. * * Input: * tcAds - TwinCat ADS client object * var - The variable name (as a string) to be read from the PLC. E.g "MAIN.var1" * vartype - The variable type as declared in the PLC. REAL is the only supported variable type. * More types can be added by making changes where appropriate. * * Output: Floating value representing the value in the PLC. * **/ static float readByString(TcAdsClient tcAds,string var,string vartype) { int hVar = 0; try { hVar = tcAds.CreateVariableHandle(var); } catch (Exception err) { Console.WriteLine(err); } if (vartype == "REAL") { // creates a stream with a length of 4 byte AdsStream ds = new AdsStream(4); BinaryReader br = new BinaryReader(ds); tcAds.Read(hVar, ds); try { tcAds.DeleteVariableHandle(hVar); } catch (Exception err) { Console.WriteLine(err); } return br.ReadSingle(); } else { Console.WriteLine("Error: Variable type not implemented!"); return 0.0F; } }
public Task WriteTag(Tag tag, object value) { if (tag.Value == null && value == null) { return(Task.FromResult(true)); } var task = _writeTaskScheduler.Schedule(() => { tag.LockValue(); try { tag.DetectDataTypeForValue(value); if (!IsConnected) { throw new PlcCommunicationException( "BeckhoffTagController can't write tag because there is no connection established!", _adsAddress, _adsPort.ToString(CultureInfo.InvariantCulture), string.Empty); } var address = GetPlcAddress(tag); var dataStream = new AdsStream(tag.BitSize == 0 ? 81 : tag.BitSize / 8); try { if (address == null) { int handle = _twinCatClient.CreateVariableHandle(tag.FullName()); var isDataStream = WriteToStream(dataStream, tag, value); try { if (isDataStream) { _twinCatClient.Write(handle, dataStream); } else { _twinCatClient.WriteAny(handle, value); } } finally { _twinCatClient.DeleteVariableHandle(handle); } } else { var isDataStream = WriteToStream(dataStream, tag, value); if (isDataStream) { _twinCatClient.Write(address.IndexGroup, address.IndexOffset, dataStream); } else { _twinCatClient.WriteAny(address.IndexGroup, address.IndexOffset, value); } } } catch (AdsErrorException ex) { if (_logger != null) { _logger.Warn("Couldn't write " + tag.FullName() + " because " + ex.ErrorCode.ToString() + " will try again..."); } try { // try again if (address == null) { int handle = _twinCatClient.CreateVariableHandle(tag.FullName()); var isDataStream = WriteToStream(dataStream, tag, value); try { if (isDataStream) { _twinCatClient.Write(handle, dataStream); } else { _twinCatClient.WriteAny(handle, value); } } finally { _twinCatClient.DeleteVariableHandle(handle); } } else { var isDataStream = WriteToStream(dataStream, tag, value); if (isDataStream) { _twinCatClient.Write(address.IndexGroup, address.IndexOffset, dataStream); } else { _twinCatClient.WriteAny(address.IndexGroup, address.IndexOffset, value); } } } catch (AdsErrorException e) { throw new PlcCommunicationException("Can't write tag " + tag.FullName() + " on port " + _adsPort.ToString(CultureInfo.InvariantCulture), _adsPort.ToString(CultureInfo.InvariantCulture), _adsPort.ToString(CultureInfo.InvariantCulture), string.Empty, e); } } } finally { tag.ReleaseValue(); } // at this point we assume the value was written successfully to the PLC Type type; if (IEC61131_3_DataTypes.NetDataTypes.TryGetValue(tag.DataType, out type)) { tag.Value = Convert.ChangeType(value, type); } else { tag.Value = value; } }); return(task); }
public void ADS_dataget(string sid, int num, Real_status real_data, Data_Env_info env_info) { //if (num == 4) //{ try { hvar = tcclient.CreateVariableHandle("MAIN.adsstru"); } catch (Exception err) { MessageBox.Show("ADS get hvar error"); } AdsStream datastream = new AdsStream(40); // ads 字节流 5*8+1个bool BinaryReader binread = new BinaryReader(datastream); datastream.Position = 0; try { tcclient.Read(hvar, datastream); structtest.tmp = binread.ReadDouble(); //获取的5个信号量,由于电压传感器还未接入 structtest.humi = binread.ReadDouble(); structtest.u = binread.ReadDouble(); structtest.v = binread.ReadDouble(); structtest.w = binread.ReadDouble(); //structtest.smokeflag = binread.ReadBoolean(); real_data.douTemperature = Calc_temper(structtest.tmp); real_data.douHumidity = Calc_humid(structtest.humi); real_data.douVoltage_1ch = Calc_voge(structtest.u); real_data.douVoltage_2ch = Calc_voge(structtest.v); real_data.douVoltage_3ch = Calc_voge(structtest.w); env_info.hmi = (float)real_data.douHumidity; env_info.tep = (float)real_data.douTemperature; env_info.u = (float)real_data.douVoltage_1ch; env_info.v = (float)real_data.douVoltage_2ch; env_info.w = (float)real_data.douVoltage_3ch; env_info.id = sid; env_info.time = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss.ffff"); //获得系统时间,当作时间戳 if (num == 4) { FormMain.queue_env.Enqueue(env_info); } //Console.WriteLine(env_info.hmi+" "+env_info.tep+" "+env_info.u); } catch (Exception err) { MessageBox.Show("ADS read value error"); } try { tcclient.DeleteVariableHandle(hvar); } catch (Exception err) { MessageBox.Show("ADS delect hvar error"); } //} }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="PLCName">用nameof(属性名),"前提是属性名和PLC变量名一致"</param> /// <param name="value"></param> /// <param name="AutoReset">是否自动复位,只对bool量有效</param> public bool WriteSingle <T>(string PLCName, T value, bool AutoReset = false) { string plcname = "." + PLCName; try { ITcAdsSymbol5 info = (ITcAdsSymbol5)Tcads.ReadSymbolInfo(plcname); int handle = Tcads.CreateVariableHandle(plcname); if (typeof(T) != typeof(string)) { Tcads.WriteAny(handle, value); } else { switch (info.TypeName) { case "SINT": sbyte sbdata = Convert.ToSByte(value); Tcads.WriteAny(handle, sbdata); break; case "BYTE": byte bydata = Convert.ToByte(value); Tcads.WriteAny(handle, bydata); break; case "BOOL": bool bdata = Convert.ToBoolean(value); Tcads.WriteAny(handle, bdata); if (AutoReset) { TobeResetList.Add(plcname); } break; case "INT": short int16data = Convert.ToInt16(value); Tcads.WriteAny(handle, int16data); break; case "UINT": ushort uint16data = Convert.ToUInt16(value); Tcads.WriteAny(handle, uint16data); break; case "REAL": float floatdata = Convert.ToSingle(value); Tcads.WriteAny(handle, floatdata); break; case "DINT": int intdata = Convert.ToInt32(value); Tcads.WriteAny(handle, intdata); break; case "UDINT": uint uintdata = Convert.ToUInt32(value); Tcads.WriteAny(handle, uintdata); break; case "LINT": long longdata = Convert.ToInt64(value); Tcads.WriteAny(handle, longdata); break; case "ULINT": ulong ulongdata = Convert.ToUInt64(value); Tcads.WriteAny(handle, ulongdata); break; case "LREAL": double doubledata = Convert.ToDouble(value); Tcads.WriteAny(handle, doubledata); break; } } Tcads.DeleteVariableHandle(handle); return(true); } catch (Exception ex) { ErrorFile.ErrorLog(ex.Message, ADS.Logfilepath); return(false); } }