CrcExtensions.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Linq;
  3. using NModbus.Utility;
  4. namespace NModbus.Extensions
  5. {
  6. public static class CrcExtensions
  7. {
  8. /// <summary>
  9. /// Determines whether the crc stored in the message matches the calculated crc.
  10. /// </summary>
  11. /// <param name="message"></param>
  12. /// <returns></returns>
  13. public static bool DoesCrcMatch(this byte[] message)
  14. {
  15. var messageFrame = message.Take(message.Length - 2).ToArray();
  16. //Calculate the CRC with the given set of bytes
  17. var calculatedCrc = BitConverter.ToUInt16(ModbusUtility.CalculateCrc(messageFrame), 0);
  18. //Get the crc that is stored in the message
  19. var messageCrc = message.GetCRC();
  20. //Determine if they match
  21. return calculatedCrc == messageCrc;
  22. }
  23. /// <summary>
  24. /// Gets the CRC of the message
  25. /// </summary>
  26. /// <param name="message"></param>
  27. /// <returns></returns>
  28. public static ushort GetCRC(this byte[] message)
  29. {
  30. if (message == null)
  31. throw new ArgumentNullException(nameof(message));
  32. if (message.Length < 4)
  33. throw new ArgumentException("message must be at least four bytes long");
  34. return BitConverter.ToUInt16(message, message.Length - 2);
  35. }
  36. }
  37. }