internal void WriteStruct(object value, IList <ITcAdsSubItem> subItems, AdsBinaryWriter writer, int writerOffset) { FieldInfo[] fields = value.GetType().GetFields(); if (fields.Length != subItems.Count) { throw new ArgumentException($"Cannot convert data type of symbol to this type.Expected number of fields {subItems.Count}, actual number is {fields.Length}", "type"); } for (int i = 0; i < fields.Length; i++) { ITcAdsSubItem item = subItems[i]; writerOffset += item.Offset; object obj2 = fields[i].GetValue(value); if (((TcAdsDataType)item.BaseType).IsPrimitive) { this.WritePrimitiveValue(item.BaseType.Name, obj2, ((TcAdsDataType)item.BaseType).ManagedType, item.DataTypeId, item.Size, writer, writerOffset); } else if (item.BaseType.Category == DataTypeCategory.Enum) { this.WriteEnumValue(item.BaseType.Name, obj2, (TcAdsDataType)item, writer, writerOffset); } else if (item.BaseType.Category == DataTypeCategory.Struct) { this.WriteStruct(obj2, item.BaseType.SubItems, writer, writerOffset); } else { if (item.BaseType.Category != DataTypeCategory.Array) { throw new ArgumentException($"Cannot convert data type of symbol to this type. ADS Data type '{item.BaseType.Name}' of subitem '{item.SubItemName}' not supported.", "type"); } this.WriteArray(obj2, (TcAdsDataType)item.BaseType, writer, writerOffset); } } }
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); } }
/* * public static string ReadStruct(int varHandle, List<string> types, int[] size, ref TcAdsClient tcClient, out List<List<object>> output) * { * output = new List<List<object>>(); * try * { * string message = ""; * int streamLength = 0; * for (int i = 0; i < size.Length; i++) streamLength += StreamLength(types[i]) * size[i]; * * AdsStream dataStream = new AdsStream(streamLength); * AdsBinaryReader reader = new AdsBinaryReader(dataStream); * for (int i = 0; i < size.Length; i++) * { * List<object> o = new List<object>(); * for (int j = 0; j < size[i]; j++) * { * object obj = new object(); * if (!ReadObject(reader, types[i], out obj)) * message = String.Format("Error while reading " + types[i] + " at struct position (i, j): (" + i + ", " + j + ")"); * o.Add(obj); * } * output.Add(o); * } * * return message; * } * catch (Exception e) * { * return e.ToString(); * } * * } */ public void WriteStruct(string structName, string[] types, object[][] values) { int dataStreamLength = 0; for (int i = 0; i < values.Length; i++) { dataStreamLength += StreamLength(types[i]) * values[i].Length; } using (AdsStream dataStream = new AdsStream(dataStreamLength)) using (AdsBinaryWriter writer = new AdsBinaryWriter(dataStream)) { int varHandle = TcClient.CreateVariableHandle(structName); dataStream.Position = 0; for (int i = 0; i < values.Length; i++) { foreach (object obj in values[i]) { WriteObjectToWriter(writer, types[i], obj); if (types[i] == "string") { dataStream.Position += 81 - obj.ToString().Length; } } } TcClient.Write(varHandle, dataStream); writer.Flush(); } }
private void btnAutoMode_Click(object sender, EventArgs e) { try { //lenght of the stream = length of string + 1 //1,先有adsstream, //2,再有binarywriter.write //3,再有clien.write() //---------把字符串分解成char 在写入plc ------- //modeWrite = new BinaryWriter(modeStream); //modeWrite.Write(strMode.ToCharArray()); //client.Write(hModeUI, modeStream); //---------把字符串分解成char 在写入plc //From version 1.0.0.10 and higher the classes AdsBinaryReader and AdsBinaryWriter // can be used to read and write strings //---------用字符串的方式写入--------------- strMode = "Auto"; modeStream = new AdsStream(30); adsWriter = new AdsBinaryWriter(modeStream); adsWriter.WritePlcString(strMode, 30, Encoding.ASCII); client.Write(hModeUI, modeStream); //-----------可以使用的------------ //---------用字符串的方式写入--------------- } catch (Exception err) { MessageBox.Show("set Auto to PLC: " + err.Message); } btnAutoMode.BackColor = Color.Green; btnCalibMode.BackColor = Color.Empty; btnManualMode.BackColor = Color.Empty; btnSettingMode.BackColor = Color.Empty; }
private void DoWriteTcArgs(AdsBinaryWriter writer) { int i; for (i = 0; i < 8; i++) { writer.Write(inst.Args.Bools[i]); } for (i = 0; i < 8; i++) { writer.Write(inst.Args.Bytes[i]); } for (i = 0; i < 8; i++) { writer.Write(inst.Args.Int16s[i]); } for (i = 0; i < 8; i++) { writer.Write(inst.Args.Int32s[i]); } for (i = 0; i < 8; i++) { writer.Write(inst.Args.Floats[i]); } for (i = 0; i < 8; i++) { writer.Write(inst.Args.Doubles[i]); } }
private void DoWriteTcInstructions(AdsBinaryWriter writer) { writer.Write(inst.Handle); writer.Write(inst.Index); writer.Write(inst.Step); writer.Write(inst.Active); writer.Write(inst.State); }
public static tcFunctionResult tcWriteData(int index, object data) { if (!tcClient.IsConnected) { LogMessage(string.Format("Error\t: {0}", "Attempted to write to PLC when not connected")); return(tcFunctionResult.TC_NOT_CONNECTED); } if (index > tcVarList.Count || index < 0) { LogMessage(string.Format("Error\t: {0}", "Attempted to access a value outside the list")); return(tcFunctionResult.TC_VARLIST_OUTOFBOUND); } AdsStream _DataStrem = new AdsStream(tcVarList[index].DataSize); AdsBinaryWriter tcStreamWriter = new AdsBinaryWriter(_DataStrem); try { switch (tcVarList[index].VariableType.ToLower()) { case "bool": tcStreamWriter.Write((bool)data); tcClient.Write(tcVarList[index].Handle, _DataStrem); break; case "arbool": break; case "int": break; case "arint": break; case "string": break; case "real": break; case "lreal": break; } tcStreamWriter.Close(); } catch (Exception ex) { LogMessage(string.Format("Error at writing data {0}\t: {1}", index.ToString(), ex.Message)); return(tcFunctionResult.TC_FAIL_TO_WRITE_DATA); } finally { tcStreamWriter.Close(); } return(tcFunctionResult.TC_SUCCESS); }
private void button1_Click(object sender, EventArgs e) //Turnon { try { Form1_Load(sender, e); AdsStream adsStream = new AdsStream(30); // AdsBinaryReader reader = new AdsBinaryReader(adsStream); // adsClient.Read(intStart, adsStream); AdsStream adsStream2 = new AdsStream(30); // AdsBinaryReader reader2 = new AdsBinaryReader(adsStream2); // adsClient.Read(intStatus, adsStream2); AdsStream adsStream3 = new AdsStream(30); // blStart = reader.ReadBoolean(); // blStatus = reader2.ReadBoolean(); // if (blStart == false) // { label2.Text = adsClient.ReadAny(intStart, typeof(Boolean)).ToString(); label3.Text = adsClient.ReadAny(intStop, typeof(Boolean)).ToString(); label4.Text = adsClient.ReadAny(intStatus, typeof(Boolean)).ToString(); blStart = true; blStatus = true; blStop = false; AdsBinaryWriter write = new AdsBinaryWriter(adsStream); adsClient.WriteAny(intStart, blStart); AdsBinaryWriter writer2 = new AdsBinaryWriter(adsStream2); adsClient.WriteAny(intStatus, blStatus); AdsBinaryWriter writer3 = new AdsBinaryWriter(adsStream3); adsClient.WriteAny(intStop, blStop); label1.Text = "Đã bật đèn"; label5.Text = adsClient.ReadAny(intStart, typeof(Boolean)).ToString(); label6.Text = adsClient.ReadAny(intStop, typeof(Boolean)).ToString(); label7.Text = adsClient.ReadAny(intStatus, typeof(Boolean)).ToString(); // } // else //blStatus = true; // label1.Text = "TRUE nè"; adsClient.Dispose(); } catch (Exception err) { MessageBox.Show(err.Message); } }
public AdsErrorCode TryGetSymbol(string symbolPath, bool bLookup, out ITcAdsSymbol symbol) { if (string.IsNullOrEmpty(symbolPath)) { throw new ArgumentOutOfRangeException("name"); } symbol = null; SymbolInfoTable table = this; lock (table) { if (bLookup) { TcAdsSymbol symbol2 = null; if (this._symbolTable.TryGetValue(symbolPath, out symbol2)) { symbol = symbol2; return(AdsErrorCode.NoError); } } } AdsErrorCode deviceSymbolNotFound = AdsErrorCode.DeviceSymbolNotFound; AdsStream stream = new AdsStream(symbolPath.Length + 1); using (AdsBinaryWriter writer = new AdsBinaryWriter(stream)) { writer.WritePlcAnsiString(symbolPath, symbolPath.Length + 1); AdsStream rdDataStream = new AdsStream(0xffff); int readBytes = 0; deviceSymbolNotFound = this._adsClient.TryReadWrite(0xf009, 0, rdDataStream, 0, (int)rdDataStream.Length, stream, 0, (int)stream.Length, out readBytes); if (deviceSymbolNotFound == AdsErrorCode.NoError) { using (AdsBinaryReader reader = new AdsBinaryReader(rdDataStream)) { AdsSymbolEntry symbolEntry = new AdsSymbolEntry(-1L, this._encoding, reader); bool flag2 = true; flag2 = StringComparer.OrdinalIgnoreCase.Compare(symbolPath, symbolEntry.name) == 0; symbol = new TcAdsSymbol(symbolEntry, (TcAdsDataType)this._datatypeTable.ResolveDataType(symbolEntry.type)); SymbolInfoTable table2 = this; lock (table2) { this._symbolTable[symbolPath] = (TcAdsSymbol)symbol; if (!flag2 && !this._symbolTable.ContainsKey(symbol.Name)) { this._symbolTable[symbol.Name] = (TcAdsSymbol)symbol; string message = $"InstancePath Ambiguity '{symbolPath}' and '{symbol.Name}'!"; TwinCAT.Ads.Module.Trace.TraceWarning(message); } } } } } return(deviceSymbolNotFound); }
private void adsSendShoulder(double shoulderLevelShift) { //adsReadStream = new AdsStream(40); adsWriteStream = new AdsStream(sizeof(double)); AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(shoulderLevelShift); _tcClient.ReadWrite(0x1, 0x2, null, adsWriteStream); }
private void SendIndexCtr(int indexCtr) //发送控制轴的索引 { try { AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(indexCtr); _tcClient.ReadWrite(0x02, 0x02, adsReadStream, adsWriteStream); byte[] dataBuffer2 = adsReadStream.ToArray(); } catch { MessageBox.Show("索引发送错误!"); } }
private void SendPos(double Pos) { try { AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(Pos); _tcClient.ReadWrite(0x02, 0x03, adsReadStream, adsWriteStream); byte[] dataBuffer3 = adsReadStream.ToArray(); } catch { MessageBox.Show("位置指令发送错误!"); } }
private void SendVelY(double VelY) { try { AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(VelY); _tcClient.ReadWrite(0x02, 0x08, adsReadStream, adsWriteStream); byte[] dataBuffer6 = adsReadStream.ToArray(); } catch { MessageBox.Show("Y速度指令发送错误!"); } }
private void SendAutoInstruct(int instruct) { try { AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(instruct); _tcClient.ReadWrite(0x02, 0x10, adsReadStream, adsWriteStream); byte[] dataBuffer5 = adsReadStream.ToArray(); } catch { MessageBox.Show("指令发送错误!"); } }
private void adsSendData(double shoulderLevelShift, double elbow, double wrist, double hand) { adsReadStream = new AdsStream(40); adsWriteStream = new AdsStream(sizeof(double) * 4); AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(shoulderLevelShift); binWriter.Write(elbow); binWriter.Write(wrist); binWriter.Write(hand); _tcClient.ReadWrite(0x1, 0x1, null, adsWriteStream); }
public void WriteUInt64(string name, UInt64 value) { int handle = GetHandle(name); lock (criticalLock) { using (AdsStream stream = new AdsStream()) { using (AdsBinaryWriter writer = new AdsBinaryWriter(stream)) { writer.Write(value); client.Write(handle, stream); } } } }
private void button2_Click(object sender, EventArgs e) { try { Form1_Load(sender, e); AdsStream adsStream = new AdsStream(30); AdsBinaryWriter writer = new AdsBinaryWriter(adsStream); writer.WritePlcAnsiString(textBox1.Text, 30); adsClient.Write(varHandle, adsStream); adsClient.Dispose(); } catch (Exception err) { MessageBox.Show(err.Message); } }
internal void WriteArray(object value, ITcAdsDataType arrayType, AdsBinaryWriter writer, int writerOffset) { Array array = value as Array; if (array == null) { throw new ArgumentException($"Cannot convert data type of symbol to this type. Expected an array, actual type is {value.GetType()}", "type"); } AdsDatatypeArrayInfo[] arrayInfo = ((TcAdsDataType)arrayType).ArrayInfo; checkArrayDimensions(array, arrayInfo, false); AdsArrayDimensionsInfo info = new AdsArrayDimensionsInfo(arrayInfo); int elements = info.Elements; int byteSize = arrayType.ByteSize / elements; DataTypeCategory category = arrayType.BaseType.Category; int num3 = 0; foreach (int[] numArray in new ArrayIndexIterator(info.LowerBounds, info.UpperBounds, true)) { if ((array.Rank == 1) && (num3 >= array.Length)) { break; } if (category == DataTypeCategory.Primitive) { this.WritePrimitiveValue(arrayType.BaseType.Name, array.GetValue(numArray), ((TcAdsDataType)arrayType.BaseType).ManagedType, arrayType.DataTypeId, byteSize, writer, writerOffset); } else if (category == DataTypeCategory.Enum) { this.WriteEnumValue(arrayType.BaseType.Name, array.GetValue(numArray), (TcAdsDataType)arrayType, writer, writerOffset); } else if (category == DataTypeCategory.Struct) { this.WriteStruct(array.GetValue(numArray), arrayType.BaseType.SubItems, writer, writerOffset); } else { if (category != DataTypeCategory.Array) { throw new ArgumentException("Cannot convert ads array type of symbol to this type.", "type"); } this.WriteArray(array.GetValue(numArray), arrayType.BaseType, writer, writerOffset); } writerOffset += byteSize; num3++; } }
private void Overwrite_Clicked(object sender, RoutedEventArgs e) { try { AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(uint.Parse(Overwrite)); _tcClient.ReadWrite(0x3, 0x1, adsReadStream, adsWriteStream); byte[] dataBuffer = adsReadStream.ToArray(); Box.Text = "Counter overwritten with Value = " + BitConverter.ToUInt32(dataBuffer, 0); } catch (Exception err) { MessageBox.Show(err.Message); } }
private void btOverwrite_Click(object sender, EventArgs e) { try { AdsBinaryWriter binWriter = new AdsBinaryWriter(adsWriteStream); adsWriteStream.Position = 0; binWriter.Write(uint.Parse(tbValue.Text)); _tcClient.ReadWrite(0x3, 0x1, adsReadStream, adsWriteStream); byte[] dataBuffer = adsReadStream.ToArray(); lbOutput.Items.Add("Counter overwritten with Value = " + BitConverter.ToUInt32(dataBuffer, 0)); lbOutput.SelectedIndex = lbOutput.Items.Count - 1; } catch (Exception err) { MessageBox.Show(err.Message); } }
private void btnSettingMode_Click(object sender, EventArgs e) { strMode = "Setting"; modeStream = new AdsStream(30); adsWriter = new AdsBinaryWriter(modeStream); try { adsWriter.WritePlcString(strMode, 30, Encoding.ASCII); client.Write(hModeUI, modeStream); } catch (Exception err) { MessageBox.Show("try to write setting Mode to PLC: " + err.Message); } btnAutoMode.BackColor = Color.Empty; btnCalibMode.BackColor = Color.Empty; btnManualMode.BackColor = Color.Empty; btnSettingMode.BackColor = Color.Green; }
private void btnCalibMode_Click(object sender, EventArgs e) { modeStream = new AdsStream(30); adsWriter = new AdsBinaryWriter(modeStream); strMode = "Calibration"; try { adsWriter.WritePlcAnsiString(strMode, 30); client.Write(hModeUI, modeStream); } catch (Exception err) { MessageBox.Show("Try to write Calibration to PLC: " + err.Message); } btnAutoMode.BackColor = Color.Empty; btnCalibMode.BackColor = Color.Green; btnManualMode.BackColor = Color.Empty; btnSettingMode.BackColor = Color.Empty; }
/// <summary> /// Write item array to TwinCAT Variables /// </summary> /// <param name="name"></param> /// <param name="type"></param> /// <param name="values"></param> public void WriteArray(string name, string type, object[] values) { int arrLength = values.Length; int streamLength = StreamLength(type); using (AdsStream dataStream = new AdsStream(arrLength * streamLength)) using (AdsBinaryWriter writer = new AdsBinaryWriter(dataStream)) { int varHandle = TcClient.CreateVariableHandle(name); dataStream.Position = 0; foreach (object val in values) { WriteObjectToWriter(writer, type, val); } TcClient.Write(varHandle, dataStream); writer.Flush(); } }
public void WriteUInt64(string name, UInt64[] value) { int handle = GetHandle(name); lock (criticalLock) { using (AdsStream stream = new AdsStream()) { using (AdsBinaryWriter writer = new AdsBinaryWriter(stream)) { for (int i = 0; i < value.Length; i++) { writer.Write(value[i]); } client.Write(handle, stream); } } } }
private void lblStop_Click(object sender, EventArgs e) { lblPause.BackColor = Color.Empty; lblStart.BackColor = Color.Empty; lblStop.BackColor = Color.Green; // 用sample03, adsbinaryWriter and adsstream 方法 AdsStream stopStream = new AdsStream(1); AdsBinaryWriter stopWriter = new AdsBinaryWriter(stopStream); try { stopWriter.Write(true); client.Write(hStopUI, stopStream); client.WriteAny(hPauseUI, false); } catch (Exception err) { MessageBox.Show("write stop to PLC: " + err.Message); } }
private void button2_Click(object sender, EventArgs e) //Turnoff --write { try { Form1_Load(sender, e); AdsStream adsStream = new AdsStream(30); AdsStream adsStream2 = new AdsStream(30); AdsStream adsStream3 = new AdsStream(30); label2.Text = adsClient.ReadAny(intStart, typeof(Boolean)).ToString(); label3.Text = adsClient.ReadAny(intStop, typeof(Boolean)).ToString(); label4.Text = adsClient.ReadAny(intStatus, typeof(Boolean)).ToString(); blStart = false; blStatus = false; blStop = true; AdsBinaryWriter write = new AdsBinaryWriter(adsStream); adsClient.WriteAny(intStart, blStart); AdsBinaryWriter writer2 = new AdsBinaryWriter(adsStream2); adsClient.WriteAny(intStatus, blStatus); AdsBinaryWriter writer3 = new AdsBinaryWriter(adsStream3); adsClient.WriteAny(intStop, blStop); label1.Text = "Đã tắt đèn"; label5.Text = adsClient.ReadAny(intStart, typeof(Boolean)).ToString(); label6.Text = adsClient.ReadAny(intStop, typeof(Boolean)).ToString(); label7.Text = adsClient.ReadAny(intStatus, typeof(Boolean)).ToString(); adsClient.Dispose(); } catch (Exception err) { MessageBox.Show(err.Message); } }
protected AdsErrorCode Execute(IList <byte[]> writeData, out IList <byte[]> readData, out int[] readDataSizes, out AdsErrorCode[] returnCodes) { this.executed = false; this.result = AdsErrorCode.NoError; readData = null; readDataSizes = null; this.subResults = null; int length = 0; int num2 = 0; length = this.calcReadLength(); num2 = this.calcWriteLength(); using (AdsBinaryWriter writer = new AdsBinaryWriter(new AdsStream(num2))) { using (AdsBinaryReader reader = new AdsBinaryReader(new AdsStream(length))) { int num3 = 0; foreach (SumDataEntity entity in this.sumEntities) { num3 += this.OnWriteSumEntityData(entity, writer); } if (writeData != null) { num3 += this.OnWriteValueData(writeData, writer); } int readBytes = 0; this.result = this.connection.TryReadWrite((uint)this.ig, (uint)this.sumEntities.Count, (AdsStream)reader.BaseStream, 0, length, (AdsStream)writer.BaseStream, 0, num2, out readBytes); if (this.result == AdsErrorCode.NoError) { reader.BaseStream.Position = 0L; this.OnReadReturnData(reader, out readData, out readDataSizes, out this.subResults); } } } this.executed = true; returnCodes = this.subResults; return(this.result); }
private void BtnWrite_Click(object sender, EventArgs e) { try { AdsStream stream = new AdsStream(4); writer = new AdsBinaryWriter(stream); writer.WritePlcType(TimeSpan.Parse(txtTime.Text)); client.Write(htime1, stream); stream.Position = 0; writer.WritePlcType(DateTime.Parse(txtDate.Text)); client.Write(hdate1, stream); stream.Position = 0; writer.WritePlcType(DateTime.Parse(txtDate2.Text)); client.Write(hdate2, stream); } catch (Exception err) { MessageBox.Show("BtnWrite " + err.Message); } }
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); } } } }
public void Write(string name, TcWriteHandler handler) { int handle = GetHandle(name); lock (criticalLock) { using (AdsStream stream = new AdsStream()) { using (AdsBinaryWriter writer = new AdsBinaryWriter(stream)) { try { handler(writer); client.Write(handle, stream); } catch (Exception e) { string str = string.Format("Occurred exception({0}) in UlTcAdsClient::Write", e.ToString()); throw new Exception(str); } } } } }