/// <summary> /// Converts an array of ushort (UInt16) to an array of bytes /// </summary> public static byte[] ToByteArray(UInt16[] value) { ByteArray arr = new ByteArray(); foreach (UInt16 val in value) arr.Add(ToByteArray(val)); var result= arr.Array; arr.Clear(); arr = null; return result; }
/// <summary> /// Converts an array of uint (UInt32) to an array of S7 DWord (4 bytes) /// </summary> public static byte[] ToByteArray(UInt32[] value) { ByteArray arr = new ByteArray(); foreach (UInt32 val in value) { arr.Add(ToByteArray(val)); } var result = arr.Array; arr.Clear(); arr = null; return(result); }
private async Task WriteBitWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, int bitAdr, bool bitValue) { byte[] bReceive = new byte[513]; int varCount = 0; try { var value = new[] { bitValue ? (byte)1 : (byte)0 }; varCount = value.Length; // first create the header int packageSize = 35 + value.Length; ByteArray package = new Types.ByteArray(packageSize); package.Add(new byte[] { 3, 0, 0 }); package.Add((byte)packageSize); package.Add(new byte[] { 2, 0xf0, 0x80, 0x32, 1, 0, 0 }); package.Add(Word.ToByteArray((ushort)(varCount - 1))); package.Add(new byte[] { 0, 0x0e }); package.Add(Word.ToByteArray((ushort)(varCount + 4))); package.Add(new byte[] { 0x05, 0x01, 0x12, 0x0a, 0x10, 0x01 }); //ending 0x01 is used for writing a sinlge bit package.Add(Word.ToByteArray((ushort)varCount)); package.Add(Word.ToByteArray((ushort)(db))); package.Add((byte)dataType); int overflow = (int)(startByteAdr * 8 / 0xffffU); // handles words with address bigger than 8191 package.Add((byte)overflow); package.Add(Word.ToByteArray((ushort)(startByteAdr * 8 + bitAdr))); package.Add(new byte[] { 0, 0x03 }); //ending 0x03 is used for writing a sinlge bit package.Add(Word.ToByteArray((ushort)(varCount))); // now join the header and the data package.Add(value); await stream.WriteAsync(package.Array, 0, package.Array.Length); package.Clear(); package = null; var s7data = await COTP.TSDU.ReadAsync(stream); if (s7data == null || s7data[14] != 0xff) { throw new PlcException(ErrorCode.WrongNumberReceivedBytes); } } catch (Exception exc) { throw new PlcException(ErrorCode.WriteData, exc); } }