mbap.hpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Modbus/TCP 报文编解码 —— 与 Python 侧 portcv/plc/modbus_pdu.py 行为一致。
  2. //
  3. // 支持的 PDU 功能码:
  4. // 0x03 读保持寄存器(PLC → 视觉的指令区)
  5. // 0x04 读输入寄存器(视觉 → PLC 的结果区,本项目的核心数据)
  6. // 0x06 写单个保持寄存器
  7. // 0x10 写多个保持寄存器
  8. //
  9. // MBAP 头:事务号(2) 协议号(2)=0 长度(2) 单元号(1);length 含单元号 + PDU。
  10. // 注意:Modbus/TCP 的 MBAP 报文本身没有 CRC(CRC 只用于串行 RTU)。
  11. #pragma once
  12. #include <cstddef>
  13. #include <cstdint>
  14. #include <stdexcept>
  15. #include <string>
  16. #include <vector>
  17. #include "portcv/schema.hpp"
  18. namespace portcv {
  19. constexpr int MBAP_HEADER_LEN = 7;
  20. enum : uint8_t {
  21. FC_READ_COILS = 0x01,
  22. FC_READ_DISCRETE_INPUTS = 0x02,
  23. FC_READ_HOLDING_REGISTERS = 0x03,
  24. FC_READ_INPUT_REGISTERS = 0x04,
  25. FC_WRITE_SINGLE_COIL = 0x05,
  26. FC_WRITE_SINGLE_REGISTER = 0x06,
  27. FC_WRITE_MULTIPLE_REGISTERS = 0x10,
  28. };
  29. enum : uint8_t {
  30. EXC_ILLEGAL_FUNCTION = 0x01,
  31. EXC_ILLEGAL_DATA_ADDRESS = 0x02,
  32. EXC_ILLEGAL_DATA_VALUE = 0x03,
  33. EXC_SERVER_DEVICE_FAILURE = 0x04,
  34. EXC_ACKNOWLEDGE = 0x05,
  35. EXC_SERVER_DEVICE_BUSY = 0x06,
  36. };
  37. inline const char* exception_text(uint8_t code) {
  38. switch (code) {
  39. case EXC_ILLEGAL_FUNCTION: return "非法功能码";
  40. case EXC_ILLEGAL_DATA_ADDRESS: return "非法数据地址";
  41. case EXC_ILLEGAL_DATA_VALUE: return "非法数据值";
  42. case EXC_SERVER_DEVICE_FAILURE: return "从站设备故障";
  43. case EXC_ACKNOWLEDGE: return "确认(正在处理)";
  44. case EXC_SERVER_DEVICE_BUSY: return "设备忙";
  45. default: return "未知";
  46. }
  47. }
  48. /// 解析后的 MBAP + PDU。
  49. struct MbapFrame {
  50. uint16_t tx_id = 0;
  51. uint16_t proto_id = 0;
  52. uint16_t length = 0;
  53. uint8_t unit_id = 0;
  54. std::vector<uint8_t> pdu;
  55. };
  56. /// 解析 MBAP + PDU;长度不足或 PDU 不完整会抛异常(调用方应回错误帧或直接断连)。
  57. inline MbapFrame parse_mbap(const uint8_t* data, std::size_t len) {
  58. if (len < static_cast<std::size_t>(MBAP_HEADER_LEN)) {
  59. throw std::invalid_argument("报文长度不足");
  60. }
  61. MbapFrame f;
  62. f.tx_id = static_cast<uint16_t>((static_cast<uint16_t>(data[0]) << 8) | data[1]);
  63. f.proto_id = static_cast<uint16_t>((static_cast<uint16_t>(data[2]) << 8) | data[3]);
  64. f.length = static_cast<uint16_t>((static_cast<uint16_t>(data[4]) << 8) | data[5]);
  65. f.unit_id = data[6];
  66. f.pdu.assign(data + MBAP_HEADER_LEN, data + len);
  67. // 允许 PDU 多带字节(部分网关如此),按 length-1 截断(与 Python 一致)。
  68. const std::size_t want = f.length > 0 ? static_cast<std::size_t>(f.length - 1) : 0;
  69. if (f.pdu.size() > want) { f.pdu.resize(want); }
  70. return f;
  71. }
  72. /// MBAP 封装。
  73. inline std::vector<uint8_t> build_frame(uint16_t tx_id, uint8_t unit_id,
  74. const std::vector<uint8_t>& pdu) {
  75. std::vector<uint8_t> out;
  76. out.reserve(pdu.size() + MBAP_HEADER_LEN);
  77. out.push_back(static_cast<uint8_t>((tx_id >> 8) & 0xFF));
  78. out.push_back(static_cast<uint8_t>(tx_id & 0xFF));
  79. out.push_back(0); // 协议号 = 0
  80. out.push_back(0);
  81. const uint16_t length = static_cast<uint16_t>(pdu.size() + 1);
  82. out.push_back(static_cast<uint8_t>((length >> 8) & 0xFF));
  83. out.push_back(static_cast<uint8_t>(length & 0xFF));
  84. out.push_back(unit_id);
  85. out.insert(out.end(), pdu.begin(), pdu.end());
  86. return out;
  87. }
  88. /// 构造读类/写单个寄存器请求(探测工具与自检用)。
  89. inline std::vector<uint8_t> build_request(uint16_t tx_id, uint8_t unit_id, uint8_t function,
  90. uint16_t address, uint16_t quantity = 1,
  91. uint16_t single_value = 0) {
  92. std::vector<uint8_t> pdu;
  93. switch (function) {
  94. case FC_READ_HOLDING_REGISTERS:
  95. case FC_READ_INPUT_REGISTERS:
  96. case FC_READ_COILS:
  97. case FC_READ_DISCRETE_INPUTS:
  98. pdu = {function, static_cast<uint8_t>((address >> 8) & 0xFF),
  99. static_cast<uint8_t>(address & 0xFF),
  100. static_cast<uint8_t>((quantity >> 8) & 0xFF),
  101. static_cast<uint8_t>(quantity & 0xFF)};
  102. break;
  103. case FC_WRITE_SINGLE_REGISTER:
  104. pdu = {function, static_cast<uint8_t>((address >> 8) & 0xFF),
  105. static_cast<uint8_t>(address & 0xFF),
  106. static_cast<uint8_t>((single_value >> 8) & 0xFF),
  107. static_cast<uint8_t>(single_value & 0xFF)};
  108. break;
  109. default:
  110. throw std::invalid_argument("未支持的请求功能码");
  111. }
  112. return build_frame(tx_id, unit_id, pdu);
  113. }
  114. /// 构造 FC16 写多个保持寄存器请求。
  115. inline std::vector<uint8_t> build_write_multiple_request(uint16_t tx_id, uint8_t unit_id,
  116. uint16_t address,
  117. const std::vector<uint16_t>& values) {
  118. std::vector<uint8_t> pdu = {FC_WRITE_MULTIPLE_REGISTERS,
  119. static_cast<uint8_t>((address >> 8) & 0xFF),
  120. static_cast<uint8_t>(address & 0xFF),
  121. static_cast<uint8_t>((values.size() >> 8) & 0xFF),
  122. static_cast<uint8_t>(values.size() & 0xFF),
  123. static_cast<uint8_t>((values.size() * 2) & 0xFF)};
  124. for (uint16_t w : values) {
  125. pdu.push_back(static_cast<uint8_t>((w >> 8) & 0xFF));
  126. pdu.push_back(static_cast<uint8_t>(w & 0xFF));
  127. }
  128. return build_frame(tx_id, unit_id, pdu);
  129. }
  130. /// 异常响应(功能码最高位置 1)。
  131. inline std::vector<uint8_t> build_exception_response(uint16_t tx_id, uint8_t unit_id,
  132. uint8_t function, uint8_t code) {
  133. std::vector<uint8_t> pdu = {static_cast<uint8_t>(function | 0x80), code};
  134. return build_frame(tx_id, unit_id, pdu);
  135. }
  136. /// 读类响应 PDU(功能码 + 字节数 + 大端字)。
  137. inline std::vector<uint8_t> build_read_response_pdu(uint8_t function,
  138. const std::vector<uint16_t>& words) {
  139. std::vector<uint8_t> pdu;
  140. pdu.push_back(function);
  141. pdu.push_back(static_cast<uint8_t>((words.size() * 2) & 0xFF));
  142. const std::vector<uint8_t> body = words_to_bytes(words);
  143. pdu.insert(pdu.end(), body.begin(), body.end());
  144. return pdu;
  145. }
  146. /// 解析 0x03/0x04 响应 PDU → 寄存器列表;异常响应抛 std::runtime_error(与 Python 一致)。
  147. inline std::vector<uint16_t> parse_read_response(const std::vector<uint8_t>& pdu) {
  148. if (pdu.empty()) { throw std::invalid_argument("空 PDU"); }
  149. const uint8_t function = pdu[0];
  150. if (function & 0x80) {
  151. const uint8_t code = pdu.size() > 1 ? pdu[1] : 0;
  152. throw std::runtime_error(std::string("Modbus 异常响应: ") + exception_text(code));
  153. }
  154. if (function != FC_READ_HOLDING_REGISTERS && function != FC_READ_INPUT_REGISTERS) {
  155. throw std::invalid_argument("不是读寄存器响应");
  156. }
  157. const std::size_t byte_count = pdu.size() > 1 ? pdu[1] : 0;
  158. const std::size_t avail = pdu.size() > 2 ? pdu.size() - 2 : 0;
  159. const std::size_t n = byte_count < avail ? byte_count : avail;
  160. return bytes_to_words(pdu.data() + 2, n);
  161. }
  162. } // namespace portcv