/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2025 Martin Preuss, all rights reserved.
 *
 * The license for this file can be found in the file COPYING which you
 * should have received along with this file.
 ****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif



#include "aqhome/msg/node/m_flashdata.h"
#include "aqhome/msg/node/m_node.h"

#include <gwenhywfar/debug.h>
#include <gwenhywfar/endianfns.h>




#define AQH_MSG_OFFS_FLASHDATA_ADDRESS      0 /* 4 bytes */
#define AQH_MSG_OFFS_FLASHDATA_DATA         4 /* x bytes */

#define AQH_MSG_FLASHDATA_MINSIZE          (AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHDATA_DATA)



AQH_MESSAGE *AQH_FlashDataMessage_new(uint8_t destAddr, uint8_t srcAddr, uint8_t code, uint32_t addr,
                                      const uint8_t *dataPtr, uint32_t dataLen)
{
  AQH_MESSAGE *msg;
  uint8_t *ptr;
  uint32_t i;

  msg=AQH_NodeMessage_prepare(destAddr, srcAddr, code, dataLen+4);

  ptr=AQH_NodeMessage_GetPayloadPointer(msg);
  *(ptr++)=addr & 0xff;
  *(ptr++)=(addr>>8) & 0xff;
  *(ptr++)=(addr>>16) & 0xff;
  *(ptr++)=(addr>>24) & 0xff;

  for (i=0; i<dataLen; i++) {
    *(ptr++)=*(dataPtr++);
  }
  AQH_NodeMessage_AddChecksum(msg);

  return msg;
}



uint32_t AQH_FlashDataMessage_GetAddress(const AQH_MESSAGE *msg)
{
  return AQH_Message_ReadUint32At(msg, AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHDATA_ADDRESS, 0);
}



uint8_t AQH_FlashDataMessage_GetDataLen(const AQH_MESSAGE *msg)
{
  if (msg) {
    uint8_t payloadLen;

    payloadLen=AQH_NodeMessage_GetPayloadLength(msg);
    if (payloadLen>=4)
      return payloadLen-4; /* subtract uid bytes */
  }
  return 0;
}



const uint8_t *AQH_FlashDataMessage_GetDataPtr(const AQH_MESSAGE *msg)
{
  if (msg && AQH_FlashDataMessage_GetDataLen(msg))
    return AQH_NodeMessage_GetPayloadPointer(msg)+4;
  return NULL;
}



void AQH_FlashDataMessage_DumpToBuffer(const AQH_MESSAGE *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  GWEN_Buffer_AppendArgs(dbuf, "0x%02x->0x%02x: FLASHDATA(%s) %s (data address=0x%04x, data length=%d)\n",
                         AQH_NodeMessage_GetSourceAddress(msg),
                         AQH_NodeMessage_GetDestAddress(msg),
                         AQH_NodeMessage_MsgTypeToChar(AQH_NodeMessage_GetMsgType(msg)),
                         sText,
                         AQH_FlashDataMessage_GetAddress(msg),
                         AQH_FlashDataMessage_GetDataLen(msg));
}




