/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2023 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/msg_flashdata.h"

#include <gwenhywfar/misc.h>
#include <gwenhywfar/list.h>
#include <gwenhywfar/error.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/text.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)



GWEN_MSG *AQH_FlashDataMsg_new(uint8_t srcAddr, uint8_t destAddr, uint8_t code, uint32_t addr,
                               const uint8_t *dataPtr, uint32_t dataLen)
{
  GWEN_MSG *msg;
  uint8_t *ptr;
  int rv;
  uint32_t i;

  msg=AQH_NodeMsg_new(destAddr, srcAddr, code, dataLen+4, NULL);
  ptr=GWEN_Msg_GetBuffer(msg)+AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHDATA_ADDRESS;

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

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

  rv=AQH_NodeMsg_AddChecksum(msg);
  if (rv<0) {
    DBG_INFO(AQH_LOGDOMAIN, "here (%d)", rv);
    GWEN_Msg_free(msg);
    return NULL;
  }

  return msg;
}



uint32_t AQH_FlashDataMsg_GetAddress(const GWEN_MSG *msg)
{
  return GWEN_Msg_GetUint32At(msg, AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHDATA_ADDRESS, 0);
}



uint8_t AQH_FlashDataMsg_GetDataLen(const GWEN_MSG *msg)
{
  uint8_t msgDataLen;

  msgDataLen=GWEN_Msg_GetUint8At(msg, AQH_MSG_OFFS_ALL_PAYLOAD_LEN, 0);
  if (msgDataLen>AQH_MSG_FLASHDATA_MINSIZE)
    return msgDataLen-6; /* cmd (1), src(1), addr(4) */
  return 0;
}



const uint8_t *AQH_FlashDataMsg_GetDataPtr(const GWEN_MSG *msg)
{
  const uint8_t *ptr;

  ptr=GWEN_Msg_GetConstBuffer(msg);
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSG_FLASHDATA_MINSIZE)
    return ptr+AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHDATA_DATA;
  return NULL;
}



void AQH_FlashDataMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSG_FLASHDATA_MINSIZE) {
    GWEN_Buffer_AppendArgs(dbuf, "0x%02x->0x%02x: FLASHDATA %s (data address=0x%04x, data length=%d)\n",
                           AQH_NodeMsg_GetSourceAddress(msg),
                           AQH_NodeMsg_GetDestAddress(msg),
                           sText,
                           AQH_FlashDataMsg_GetAddress(msg),
                           AQH_FlashDataMsg_GetDataLen(msg));
  }
}







