#include <softbus_edge/ingress/MockModbusIngress.h>

#include <softbus_core/identity/DeviceIdentity.h>
#include <softbus_core/time/HwClock.h>

namespace softbus::edge {

MockModbusIngress::MockModbusIngress(std::string objectRef, std::string runtimeDeviceId)
    : objectRef_(std::move(objectRef))
    , runtimeDeviceId_(std::move(runtimeDeviceId))
{
}

bool MockModbusIngress::open()
{
    open_ = true;
    return true;
}

void MockModbusIngress::close()
{
    open_ = false;
}

std::vector<uint8_t> MockModbusIngress::buildFrame(uint16_t registerValue) const
{
    // slave=1, func=0x03, byteCount=2, value hi/lo, crc lo/hi (placeholder)
    return {
        0x01, 0x03, 0x02,
        static_cast<uint8_t>((registerValue >> 8) & 0xFF),
        static_cast<uint8_t>(registerValue & 0xFF),
        0x00, 0x00
    };
}

std::vector<softbus::core::RawPacket> MockModbusIngress::poll()
{
    if (!open_) {
        return {};
    }

    const auto traceId = softbus::core::DeviceIdentity::generateTraceId();
    softbus::core::RawPacket packet;
    packet.traceId = traceId;
    packet.timestampNs = softbus::core::HwClock::nowNs();
    packet.runtimeDeviceId = runtimeDeviceId_;
    packet.sourceId = objectRef_;
    packet.protocolTag = "modbus";
    packet.payload = buildFrame(counter_);
    counter_ = static_cast<uint16_t>(counter_ + 1);
    return {packet};
}

} // namespace softbus::edge
