37 lines
1.1 KiB
C
37 lines
1.1 KiB
C
|
|
// 文件名: src/protocol/modbus/modbus_protocol.h
|
||
|
|
#ifndef MODBUS_PROTOCOL_H
|
||
|
|
#define MODBUS_PROTOCOL_H
|
||
|
|
|
||
|
|
#include <vector>
|
||
|
|
#include <cstdint>
|
||
|
|
#include <string>
|
||
|
|
#include <stdexcept>
|
||
|
|
|
||
|
|
namespace modbus::protocol {
|
||
|
|
|
||
|
|
// 自定义异常类型,方便上层捕获
|
||
|
|
class exception : public std::runtime_error {
|
||
|
|
public:
|
||
|
|
explicit exception(const std::string& message) : std::runtime_error(message) {}
|
||
|
|
};
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @brief 创建一个"读保持寄存器" (0x03) 的PDU
|
||
|
|
* @param start_address 起始地址
|
||
|
|
* @param quantity 要读取的寄存器数量
|
||
|
|
* @return 序列化后的PDU字节流 (不含MBAP头)
|
||
|
|
*/
|
||
|
|
std::vector<uint8_t> create_read_holding_registers_pdu(uint16_t start_address, uint16_t quantity);
|
||
|
|
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @brief 解析一个"读保持寄存器"的响应PDU
|
||
|
|
* @param response_pdu 从设备返回的PDU字节流
|
||
|
|
* @return 包含所有寄存器值的向量
|
||
|
|
* @throws modbus::protocol::exception 如果响应无效 (如异常码、长度错误)
|
||
|
|
*/
|
||
|
|
std::vector<uint16_t> parse_read_holding_registers_response(const std::vector<uint8_t>& response_pdu);
|
||
|
|
|
||
|
|
} // namespace modbus::protocol
|
||
|
|
|
||
|
|
#endif // MODBUS_PROTOCOL_H
|