// SPDX-License-Identifier: GPL-3.0-or-later

#include "trydanmodbusmaster.h"
#include <cstring>

TrydanModbusMaster::TrydanModbusMaster(QObject *parent)
    : QObject(parent)
{}

float TrydanModbusMaster::decodeFloat32BB(quint16 high, quint16 low)
{
    // High word is the most-significant 16 bits (Big word order).
    // Within each word bytes are already in big-endian order on the wire.
    // This mirrors pymodbus BinaryPayloadDecoder(byteorder=Endian.Big, wordorder=Endian.Big).
    quint32 raw = (static_cast<quint32>(high) << 16) | static_cast<quint32>(low);
    float result;
    std::memcpy(&result, &raw, sizeof(float));
    return result;
}

int TrydanModbusMaster::decodeIntFromFloat32(quint16 high, quint16 low)
{
    return static_cast<int>(qRound(decodeFloat32BB(high, low)));
}

void TrydanModbusMaster::setReachable(bool reachable)
{
    if (m_reachable == reachable)
        return;
    m_reachable = reachable;
    emit reachableChanged(reachable);
}
