#include <modbus/ModbusParser.h>

namespace modbus {

ModbusParser::ModbusParser(std::string defaultObjectRef)
    : defaultObjectRef_(std::move(defaultObjectRef))
{
}

softbus::core::ParseResult ModbusParser::parseFrame(const uint8_t* data, std::size_t size,
                                                     const std::string& sourceId)
{
    softbus::core::ParseResult result;
    if (size < 7 || data[1] != 0x03) {
        return result;
    }

    const std::size_t byteCount = data[2];
    if (byteCount < 2 || size < 3 + byteCount + 2) {
        return result;
    }

    const uint16_t registerValue =
        (static_cast<uint16_t>(data[3]) << 8) | static_cast<uint16_t>(data[4]);

    result.success = true;
    result.message.sourceId = sourceId;
    result.message.id = sourceId.empty() ? defaultObjectRef_ : sourceId;
    result.message.domain = softbus::core::DomDomain::Process;
    result.message.quality = softbus::core::QualityCode::Good;
    result.message.value = {
        {"protocol", "modbus"},
        {"function", 0x03},
        {"register", 40001},
        {"registerValue", registerValue},
        {"value", static_cast<double>(registerValue) * 0.1}
    };
    return result;
}

} // namespace modbus
