You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. namespace ModbusDemo.Uitls
  8. {
  9. public static class CheckData
  10. {
  11. /// <summary>
  12. /// 检测返回的数据格式是否正确
  13. /// </summary>
  14. /// <param name="response"></param>
  15. /// <returns></returns>
  16. public static bool CheckResponse(byte[] response)
  17. {
  18. if (response == null || response.Length == 0)
  19. {
  20. MessageBox.Show("返回数据为空", "error", MessageBoxButton.OK, MessageBoxImage.Error);
  21. return false;
  22. }
  23. // 检查数组长度是否足够
  24. if (response.Length > 1)
  25. {
  26. byte secondByte = response[1]; // 获取第二个字节(索引为1)
  27. // 使用掩码0xF0获取高4位,并右移4位
  28. int highNibble = (secondByte & 0xF0) >> 4;
  29. // 判断高4位是否等于8
  30. if (highNibble == 8)
  31. {
  32. MessageBox.Show($"数据错误:错误码为:0x{response[2]:X2}");
  33. return false;
  34. }
  35. }
  36. if (!CRCUitl.ValidateCRC(response))
  37. {
  38. MessageBox.Show("0x14:CRC校验错误");
  39. return false;
  40. }
  41. return true;
  42. }
  43. }
  44. }