/****************************************************************************
 * 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_ping.h"
#include "aqhome/msg/msg_node.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_PING_TIMESTAMP   0

#define AQH_MSG_PING_MINSIZE          (AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_PING_TIMESTAMP+4+1)




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

  msg=AQH_NodeMsg_new(destAddr, srcAddr, code, 4, NULL);
  ptr=GWEN_Msg_GetBuffer(msg)+AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_PING_TIMESTAMP;
  *(ptr++)=0; /* timestamp */
  *(ptr++)=0;
  *(ptr++)=0;
  *ptr=0;

  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_PingMsg_GetTimestamp(const GWEN_MSG *msg)
{
  return GWEN_Msg_GetUint32At(msg, AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_PING_TIMESTAMP, 0);
}



void AQH_PingMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if ((AQH_NodeMsg_GetMsgType(msg)==AQH_MSG_TYPE_PING) &&
      (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSG_PING_MINSIZE)) {
    GWEN_Buffer_AppendArgs(dbuf,
                           "0x%02x->0x%02x: PING %s (timestamp=0x%08x)\n",
                           AQH_NodeMsg_GetSourceAddress(msg),
                           AQH_NodeMsg_GetDestAddress(msg),
                           sText,
                           (unsigned int) AQH_PingMsg_GetTimestamp(msg));
  }
}






