/// <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(); } }
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 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); } }
//往TwinCAT写入数值 private void mTwinCATCoil_CoilUpdate(object sender, EventArgs e) { try { TwinCATCoil temp = sender as TwinCATCoil; if (temp.CoilHandle == 0) { temp.CoilHandle = adsClient.CreateVariableHandle(temp.CoilName); } if (temp.CoilGroup != 0)//如果是数组~ { //adsClient.WriteAny(temp.CoilHandle, a, new int[] { temp.CoilGroup });//这样不行~ dynamic dynamicObj = Convert.ChangeType(temp.CoilValue, temp.CoilType); int size = 0; if (dynamicObj is bool[])//否则得出结果是4字节 { size = 1; } else { size = Marshal.SizeOf(dynamicObj[0]); } AdsStream datastream = new AdsStream(size * temp.CoilGroup); //每个元素占用位 System.IO.BinaryWriter binwrite = new System.IO.BinaryWriter(datastream); datastream.Position = 0; for (int i = 0; i < temp.CoilGroup; i++) { binwrite.Write(dynamicObj[i]); } adsClient.Write(temp.CoilHandle, datastream); } else { adsClient.WriteAny(temp.CoilHandle, Convert.ChangeType(temp.CoilValue, temp.CoilType)); } } catch (Exception ex) { if (sender is TwinCATCoil) { Trace.Write(ex, "Update:" + (sender as TwinCATCoil).CoilName); } else { Trace.Write(ex, "Update"); } } }
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); } }
private void AdsWrite() { AdsStream wdStream = new AdsStream(wdLength); BinaryWriter Writer = new BinaryWriter(new AdsStream(wdLength)); //Axis1 Writer.Write(Controlword_axis1); Writer.Write(ModesOfOperation_axis1); Writer.Write(TargetPosition_axis1); Writer.Write(Polarity_axis1); Writer.Write(ProfileVelocity_axis1); Writer.Write(ProfileAcceleration_axis1); Writer.Write(ProfileDeceleration_axis1); Writer.Write(TargetVelocity_axis1); //Axix2 Writer.Write(HomingMethod_axix2); Writer.Write(HomeSpeed_axix2[0]); Writer.Write(HomeSpeed_axix2[1]); Writer.Write(HomingAcceleration_axix2); tcClient.Write(Group, objControlWord_axis1, (AdsStream)Writer.BaseStream); }
private void btnWrite_Click(object sender, EventArgs e) { stream = new AdsStream(32); writer = new BinaryWriter(stream); stream.Position = 0; try { writer.Write(short.Parse(txtINT.Text)); stream.Position = 4; writer.Write(int.Parse(txtDINT.Text)); stream.Position = 8; writer.Write(byte.Parse(txtByte.Text)); stream.Position = 16; writer.Write(double.Parse(txtLreal.Text)); stream.Position = 24; writer.Write(float.Parse(txtReal.Text)); client.Write(hPLCVar, 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); } } } } }
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); }
static void Main(string[] args) { TcAdsClient tcAds = new TcAdsClient(); AdsStream ds = new AdsStream(16); bool scan = false; double input1 = 0; double input2 = 0; double freq = 0.2; double startFreq = 0.05; double endFreq = 0.2; double steps = 4; double periodNumber = 20; double time = 0; double amp = 2.5; double offset = 2.5; double deltaF = 1; double lastTime = 0; tcAds.Connect(851); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); if (scan == true) { freq = startFreq; deltaF = (endFreq - startFreq) / steps; Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt")); Console.WriteLine(freq); while (freq <= endFreq) { time = stopWatch.ElapsedMilliseconds / 1000f; if ((time - lastTime) >= periodNumber / freq) { lastTime = time; freq += deltaF; Console.WriteLine(time); Console.WriteLine(freq); } else { ds = new AdsStream(8); BinaryWriter bw = new BinaryWriter(ds); input1 = (amp * Math.Sin(2 * Math.PI * freq * time) + offset) * 3276.8; input2 = (-amp / 2 * Math.Sin(2 * Math.PI * freq * time) + offset) * 3276.8; bw.Write((int)input1); bw.Write((int)input2); tcAds.Write(0x4020, 0, ds); } } Console.WriteLine("Done!"); Console.ReadLine(); } else { while (true) { ds = new AdsStream(8); BinaryWriter bw = new BinaryWriter(ds); time = stopWatch.ElapsedMilliseconds / 1000f; input1 = (amp * Math.Sin(2 * Math.PI * freq * time) + offset) * 3276.8; input2 = (-amp / 2 * Math.Sin(2 * Math.PI * freq * time) + offset) * 3276.8; input1 = 1; bw.Write((int)input1); bw.Write((int)input2); tcAds.Write(0x4020, 0, ds); Console.WriteLine(input1); } } }
public void WriteAdsValue(IWoopsaProperty property, IWoopsaValue value) { WoopsaAdsProperty adsProperty = (WoopsaAdsProperty)property; AdsStream stream = new AdsStream(); switch (property.Type) { case WoopsaValueType.Integer: if (adsProperty.AdsInfo.Type == BeckhoffValueType.WORD || adsProperty.AdsInfo.Type == BeckhoffValueType.UINT) { stream = new AdsStream(BitConverter.GetBytes(value.ToUInt16())); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.DWORD || adsProperty.AdsInfo.Type == BeckhoffValueType.UDINT) { stream = new AdsStream(BitConverter.GetBytes(value.ToUInt32())); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.SINT) { stream = new AdsStream(BitConverter.GetBytes(value.ToSByte())); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.INT) { stream = new AdsStream(BitConverter.GetBytes(value.ToInt16())); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.DINT) { stream = new AdsStream(BitConverter.GetBytes(value.ToInt32())); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.LINT) { stream = new AdsStream(BitConverter.GetBytes(value.ToInt64())); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.USINT || adsProperty.AdsInfo.Type == BeckhoffValueType.BYTE) { stream = new AdsStream(1); stream.WriteByte(value.ToByte()); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.ULINT) { stream = new AdsStream(BitConverter.GetBytes(value.ToUInt64())); } else { throw new WoopsaException("Ads type not compatible with Woopsa Integer"); } break; case WoopsaValueType.Logical: stream = new AdsStream(BitConverter.GetBytes(value.ToBool())); break; case WoopsaValueType.Real: if (adsProperty.AdsInfo.Type == BeckhoffValueType.REAL) { stream = new AdsStream(BitConverter.GetBytes(value.ToFloat())); } else if (adsProperty.AdsInfo.Type == BeckhoffValueType.LREAL) { stream = new AdsStream(BitConverter.GetBytes(value.ToDouble())); } else { throw new WoopsaException("Ads type not compatible with Woopsa Real"); } break; case WoopsaValueType.Text: stream = new AdsStream(80); byte[] byteString = System.Text.Encoding.ASCII.GetBytes(value.ToString()); stream.Write(byteString, 0, byteString.Length); break; case WoopsaValueType.TimeSpan: stream = new AdsStream(BitConverter.GetBytes((uint)(value.ToTimeSpan().Ticks / TimeSpan.TicksPerMillisecond))); break; case WoopsaValueType.DateTime: TimeSpan timeSp; DateTime dateTime; if (adsProperty.AdsInfo.Type == BeckhoffValueType.TIME_OF_DAY) { dateTime = value.ToDateTime(); uint timeOfDay = (uint)dateTime.Millisecond + ((uint)dateTime.Second + ((uint)dateTime.Minute + ((uint)dateTime.Hour * 60)) * 60) * 1000; stream = new AdsStream(BitConverter.GetBytes(timeOfDay)); } else { timeSp = value.ToDateTime() - BeckhoffPlcReferenceDateTime; stream = new AdsStream(BitConverter.GetBytes((uint)timeSp.TotalSeconds)); } break; default: stream = new AdsStream(1); break; } _tcAds.Write(adsProperty.AdsInfo.IndexGroup, adsProperty.AdsInfo.IndexOffset, stream); }