rtuhelper.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "rtuhelper.h"
  2. #ifdef _MSC_VER
  3. #pragma execution_character_set("utf-8")
  4. #endif
  5. namespace UtilsFun {
  6. RTUHelper::RTUHelper():
  7. readType(SubAddress),toReadlen(0),_checkSubAddress(false)
  8. {
  9. }
  10. RTUHelper::~RTUHelper(){}
  11. void RTUHelper::readed(const QByteArray &data)
  12. {
  13. int index = 0;
  14. while (index < data.length())
  15. {
  16. const char ch = data.at(index);
  17. // qDebug()<<"ch"<<ch;
  18. // qDebug()<<data.at(index);
  19. switch (readType)
  20. {
  21. case SubAddress:
  22. {
  23. ++ index;
  24. if (!_checkSubAddress || _subAddress.contains(ch))
  25. {
  26. if(!buffer.isEmpty()) buffer.clear();
  27. buffer.append(ch);
  28. readType = GetType;
  29. }
  30. continue;
  31. }
  32. case GetType:
  33. {
  34. buffer.append(ch);
  35. ++ index;
  36. readType = NumLength;
  37. continue;
  38. }
  39. case NumLength: //需要读数据
  40. {
  41. ++ index;
  42. toReadlen = static_cast<uchar>(ch);
  43. buffer.append(ch);
  44. readType = ReadData;
  45. continue;
  46. }
  47. case ReadData: //需要读数据
  48. {
  49. const int canread = data.length() - index;
  50. if (canread >= toReadlen)
  51. {
  52. buffer.append(data.mid(index, toReadlen));
  53. index += toReadlen;
  54. toReadlen = 0;
  55. readType = CRCUL;
  56. }
  57. else
  58. {
  59. buffer.append(data.mid(index, canread));
  60. index += canread;
  61. toReadlen -= canread;
  62. }
  63. continue;
  64. }
  65. case CRCUL: //需要读数据
  66. {
  67. buffer.append(ch);
  68. index ++;
  69. readType = CRCUH;
  70. continue;
  71. }
  72. case CRCUH: //需要读数据
  73. {
  74. buffer.append(ch);
  75. index ++;
  76. readType = SubAddress;
  77. doHandle(this->buffer);
  78. buffer.clear();
  79. }
  80. break;
  81. default:
  82. {
  83. readType = SubAddress;
  84. continue;
  85. }
  86. }
  87. }
  88. }
  89. }