/****************************************************************************
 * 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_flashend.h"

#include <gwenhywfar/misc.h>
#include <gwenhywfar/list.h>
#include <gwenhywfar/error.h>
#include <gwenhywfar/debug.h>


#define AQH_MSG_OFFS_FLASHEND_REASON      0 /* 1 byte */

#define AQH_MSG_FLASHEND_MINSIZE          (AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHEND_REASON+1)



GWEN_MSG *AQH_FlashEndMsg_new(uint8_t srcAddr, uint8_t destAddr, uint8_t code, uint8_t reason)
{
  GWEN_MSG *msg;
  uint8_t *ptr;
  int rv;

  msg=AQH_NodeMsg_new(destAddr, srcAddr, code, 5, NULL);
  ptr=GWEN_Msg_GetBuffer(msg)+AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHEND_REASON;

  *(ptr++)=reason & 0xff;               /* reason */
  GWEN_Msg_IncCurrentPos(msg, 5);

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

  return msg;

}



uint8_t AQH_FlashEndMsg_GetReason(const GWEN_MSG *msg)
{
  return GWEN_Msg_GetUint32At(msg, AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHEND_REASON, 0);
}



void AQH_FlashEndMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSG_FLASHEND_MINSIZE) {
    GWEN_Buffer_AppendArgs(dbuf, "0x%02x->0x%02x: FLASHEND %s (reason=%d)\n",
                           AQH_NodeMsg_GetSourceAddress(msg),
                           AQH_NodeMsg_GetDestAddress(msg),
                           sText,
                           AQH_FlashEndMsg_GetReason(msg));
  }
}







