Beispiel #1
0
        /// <summary>
        /// Get correct bytes according to a given <see cref="Endianness"/>
        /// </summary>
        /// <param name="shorts">Array of <see cref="ushort">shorts</see></param>
        /// <param name="endianness"><see cref="Endianness"/> expected in the shorts</param>
        /// <returns>Array of <see cref="byte"/> with correct endian for current CPU</returns>
        public static byte[] GetBytes(this ushort[] shorts, Endianness endianness)
        {
            ushort[] targetShorts = new ushort[shorts.Length];
            Array.Copy(shorts, targetShorts, shorts.Length);

            if (endianness.ShouldSwapWords())
            {
                Array.Reverse(targetShorts);
            }

            var bytes     = new byte[targetShorts.Length * 2];
            var byteIndex = 0;

            for (var i = 0; i < targetShorts.Length; i++)
            {
                var resultBytes = BitConverter.GetBytes(targetShorts[i]);

                if (endianness.ShouldSwapBytes())
                {
                    Array.Reverse(resultBytes);
                }

                Array.Copy(resultBytes, 0, bytes, byteIndex, resultBytes.Length);

                byteIndex += resultBytes.Length;
            }

            return(bytes);
        }
        /// <summary>
        /// Extension function to get the bytes of the payload, with corrected endianness.
        /// </summary>
        /// <param name="shorts">the collection of shorts to get the individual bytes from</param>
        /// <param name="endianness">the endianness to use</param>
        /// <param name="dataType">the Modbus data type</param>
        /// <returns>a collection of endianness corrected bytes</returns>
        public static IEnumerable <byte> GetBytes(this IEnumerable <ushort> shorts, Endianness endianness, DataType dataType)
        {
            var shortsInDataPoint = dataType switch
            {
                DataType.Float or DataType.Int32 or DataType.Uint32 => 2,
                _ => 1
            };
            var bytesInDataPoint = shortsInDataPoint * 2;
            var numBytes         = shorts.Count() * 2;

            if (numBytes % bytesInDataPoint != 0)
            {
                throw new ElementsNotPerfectlyDivisableIntoChunksException(numBytes, bytesInDataPoint);
            }

            shorts = (endianness.ShouldSwapWords()) ? shorts.ChunkwiseReverse(shortsInDataPoint) : shorts;
            var bytes = shorts.SelectMany(sh => BitConverter.GetBytes(sh)).ToList();

            bytes = (endianness.ShouldSwapBytesInWords()) ? bytes.ChunkwiseReverse(2).ToList() : bytes;

            return(bytes);
        }