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

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


#define AQH_MSG_OFFS_FLASHSTART_UID         0 /* 4 bytes */
#define AQH_MSG_OFFS_FLASHSTART_FWTYPE      4 /* 2 bytes */
#define AQH_MSG_OFFS_FLASHSTART_FWVER       6 /* 2 bytes */

#define AQH_MSG_FLASHSTART_MINSIZE          (AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHSTART_FWVER+2)



GWEN_MSG *AQH_FlashStartMsg_new(uint8_t srcAddr, uint8_t destAddr, uint8_t code,
                                uint32_t uid, uint16_t firmwareType, uint16_t firmwareVersion)
{
  GWEN_MSG *msg;
  uint8_t *ptr;
  int rv;

  msg=AQH_NodeMsg_new(destAddr, srcAddr, code, 8, NULL);
  ptr=GWEN_Msg_GetBuffer(msg)+AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHSTART_UID;

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

  *(ptr++)=firmwareType & 0xff;      /* fw type */
  *(ptr++)=(firmwareType>>8) & 0xff;

  *(ptr++)=firmwareVersion & 0xff;   /* fw ver */
  *(ptr++)=(firmwareVersion>>8) & 0xff;

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



uint16_t AQH_FlashStartMsg_GetFirmwareType(const GWEN_MSG *msg)
{
  return GWEN_Msg_GetUint16At(msg, AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHSTART_FWTYPE, 0);
}



uint16_t AQH_FlashStartMsg_GetFirmwareVersion(const GWEN_MSG *msg)
{
  return GWEN_Msg_GetUint16At(msg, AQH_MSG_OFFS_ALL_DATA_BEGIN+AQH_MSG_OFFS_FLASHSTART_FWVER, 0);
}




void AQH_FlashStartMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText)
{
  if (GWEN_Msg_GetBytesInBuffer(msg)>=AQH_MSG_FLASHSTART_MINSIZE) {
    uint16_t fwVersion;

    fwVersion=AQH_FlashStartMsg_GetFirmwareVersion(msg);
    GWEN_Buffer_AppendArgs(dbuf, "0x%02x->0x%02x: FLASHSTART %s (uid=0x%08x, fw type=%d, fw ver=%d.%d)\n",
                           AQH_NodeMsg_GetSourceAddress(msg),
                           AQH_NodeMsg_GetDestAddress(msg),
                           sText,
                           (unsigned int) AQH_FlashStartMsg_GetUid(msg),
                           AQH_FlashStartMsg_GetFirmwareType(msg),
                           (fwVersion>>8) & 0xff,
                           fwVersion & 0xff);
  }
}







