using System; using System.Collections.Generic; namespace S7.Net.Types { /// /// Contains the methods to convert between and S7 representation of TIME values. /// public static class TimeSpan { /// /// The minimum value supported by the specification. /// public static readonly System.TimeSpan SpecMinimumTimeSpan = System.TimeSpan.FromMilliseconds(int.MinValue); /// /// The maximum value supported by the specification. /// public static readonly System.TimeSpan SpecMaximumTimeSpan = System.TimeSpan.FromMilliseconds(int.MaxValue); /// /// Parses a value from bytes. /// /// Input bytes read from PLC. /// A object representing the value read from PLC. /// Thrown when the length of /// is not 4 or any value in /// is outside the valid range of values. public static System.TimeSpan FromByteArray(byte[] bytes) { var milliseconds = DInt.FromByteArray(bytes); return System.TimeSpan.FromMilliseconds(milliseconds); } /// /// Parses an array of values from bytes. /// /// Input bytes read from PLC. /// An array of objects representing the values read from PLC. /// Thrown when the length of /// is not a multiple of 4 or any value in /// is outside the valid range of values. public static System.TimeSpan[] ToArray(byte[] bytes) { const int singleTimeSpanLength = 4; if (bytes.Length % singleTimeSpanLength != 0) throw new ArgumentOutOfRangeException(nameof(bytes), bytes.Length, $"Parsing an array of {nameof(System.TimeSpan)} requires a multiple of {singleTimeSpanLength} bytes of input data, input data is '{bytes.Length}' long."); var result = new System.TimeSpan[bytes.Length / singleTimeSpanLength]; var milliseconds = DInt.ToArray(bytes); for (var i = 0; i < milliseconds.Length; i++) result[i] = System.TimeSpan.FromMilliseconds(milliseconds[i]); return result; } /// /// Converts a value to a byte array. /// /// The TimeSpan value to convert. /// A byte array containing the S7 date time representation of . /// Thrown when the value of /// is before /// or after . public static byte[] ToByteArray(System.TimeSpan timeSpan) { if (timeSpan < SpecMinimumTimeSpan) throw new ArgumentOutOfRangeException(nameof(timeSpan), timeSpan, $"Time span '{timeSpan}' is before the minimum '{SpecMinimumTimeSpan}' supported in S7 time representation."); if (timeSpan > SpecMaximumTimeSpan) throw new ArgumentOutOfRangeException(nameof(timeSpan), timeSpan, $"Time span '{timeSpan}' is after the maximum '{SpecMaximumTimeSpan}' supported in S7 time representation."); return DInt.ToByteArray(Convert.ToInt32(timeSpan.TotalMilliseconds)); } /// /// Converts an array of values to a byte array. /// /// The TimeSpan values to convert. /// A byte array containing the S7 date time representations of . /// Thrown when any value of /// is before /// or after . public static byte[] ToByteArray(System.TimeSpan[] timeSpans) { var bytes = new List(timeSpans.Length * 4); foreach (var timeSpan in timeSpans) bytes.AddRange(ToByteArray(timeSpan)); return bytes.ToArray(); } } }