Date.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using S7.Net.Helper;
  3. namespace S7.Net.Types
  4. {
  5. /// <summary>
  6. /// Contains the conversion methods to convert Words from S7 plc to C#.
  7. /// </summary>
  8. public static class Date
  9. {
  10. /// <summary>
  11. /// Minimum allowed date for the IEC date type
  12. /// </summary>
  13. public static System.DateTime IecMinDate { get; } = new(year: 1990, month: 01, day: 01);
  14. /// <summary>
  15. /// Maximum allowed date for the IEC date type
  16. /// <remarks>
  17. /// Although the spec allows only a max date of 31-12-2168, the PLC IEC date goes up to 06-06-2169 (which is the actual
  18. /// WORD max value - 65535)
  19. /// </remarks>
  20. /// </summary>
  21. public static System.DateTime IecMaxDate { get; } = new(year: 2169, month: 06, day: 06);
  22. private static readonly ushort MaxNumberOfDays = (ushort)(IecMaxDate - IecMinDate).TotalDays;
  23. /// <summary>
  24. /// Converts a word (2 bytes) to IEC date (<see cref="System.DateTime"/>)
  25. /// </summary>
  26. public static System.DateTime FromByteArray(byte[] bytes)
  27. {
  28. if (bytes.Length != 2)
  29. {
  30. throw new ArgumentException("Wrong number of bytes. Bytes array must contain 2 bytes.");
  31. }
  32. var daysSinceDateStart = Word.FromByteArray(bytes);
  33. if (daysSinceDateStart > MaxNumberOfDays)
  34. {
  35. throw new ArgumentException($"Read number exceeded the number of maximum days in the IEC date (read: {daysSinceDateStart}, max: {MaxNumberOfDays})",
  36. nameof(bytes));
  37. }
  38. return IecMinDate.AddDays(daysSinceDateStart);
  39. }
  40. /// <summary>
  41. /// Converts a <see cref="System.DateTime"/> to word (2 bytes)
  42. /// </summary>
  43. public static byte[] ToByteArray(System.DateTime dateTime) => Word.ToByteArray(dateTime.GetDaysSinceIecDateStart());
  44. /// <summary>
  45. /// Converts an array of <see cref="System.DateTime"/>s to an array of bytes
  46. /// </summary>
  47. public static byte[] ToByteArray(System.DateTime[] value)
  48. {
  49. var arr = new ByteArray();
  50. foreach (var date in value)
  51. arr.Add(ToByteArray(date));
  52. return arr.Array;
  53. }
  54. /// <summary>
  55. /// Converts an array of bytes to an array of <see cref="System.DateTime"/>s
  56. /// </summary>
  57. public static System.DateTime[] ToArray(byte[] bytes)
  58. {
  59. var values = new System.DateTime[bytes.Length / sizeof(ushort)];
  60. for (int i = 0; i < values.Length; i++)
  61. {
  62. values[i] = FromByteArray(
  63. new[]
  64. {
  65. bytes[i], bytes[i + 1]
  66. });
  67. }
  68. return values;
  69. }
  70. }
  71. }