/****************************************************************************
 * 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.
 ****************************************************************************/

#ifndef AQH_MSG_MQTT_H
#define AQH_MSG_MQTT_H


#include <aqhome/api.h>

#include <gwenhywfar/msg.h>
#include <gwenhywfar/buffer.h>
#include <gwenhywfar/db.h>



#define AQH_MQTTMSG_OFFS_CONTROL           0
#define AQH_MQTTMSG_OFFS_REMAINING_LENGTH  1


/* from https://docs.solace.com/API/MQTT-311-Prtl-Conformance-Spec/MQTT%20Control%20Packet%20format.htm
 */
#define AQH_MQTTMSG_MSGTYPE_CONNECT      0x10u
#define AQH_MQTTMSG_MSGTYPE_CONNACK      0x20u
#define AQH_MQTTMSG_MSGTYPE_PUBLISH      0x30u
#define AQH_MQTTMSG_MSGTYPE_PUBACK       0x40u
#define AQH_MQTTMSG_MSGTYPE_PUBREC       0x50u /* assured delivery part 1 */
#define AQH_MQTTMSG_MSGTYPE_PUBREL       0x62u /* assured delivery part 2 */
#define AQH_MQTTMSG_MSGTYPE_PUBCOMP      0x70u /* assured delivery part 3 */
#define AQH_MQTTMSG_MSGTYPE_SUBSCRIBE    0x82u
#define AQH_MQTTMSG_MSGTYPE_SUBACK       0x90u
#define AQH_MQTTMSG_MSGTYPE_UNSUBSCRIBE  0xa2u
#define AQH_MQTTMSG_MSGTYPE_UNSUBACK     0xb0u
#define AQH_MQTTMSG_MSGTYPE_PINGREQ      0xc0u
#define AQH_MQTTMSG_MSGTYPE_PINGRESP     0xd0u
#define AQH_MQTTMSG_MSGTYPE_DISCONNECT   0xe0u


#define AQH_MQTTMSG_FLAGS_DUP    0x08u
#define AQH_MQTTMSG_FLAGS_QOS2   0x04u
#define AQH_MQTTMSG_FLAGS_QOS1   0x02u
#define AQH_MQTTMSG_FLAGS_RETAIN 0x01u



AQHOME_API GWEN_MSG *GWEN_MqttMsg_new(uint8_t typeAndFlags, uint32_t payloadLen, const uint8_t *payload);

AQHOME_API int AQH_MqttMsg_IsMsgComplete(const GWEN_MSG *msg);
AQHOME_API void AQH_MqttMsg_DumpToBuffer(const GWEN_MSG *msg, GWEN_BUFFER *dbuf, const char *sText);

AQHOME_API const char *AQH_MqttMsg_MsgTypeToString(uint8_t t);

AQHOME_API uint8_t AQH_MqttMsg_GetMsgTypeAndFlags(const GWEN_MSG *msg);


/* helper functions */
AQHOME_API void AQH_MqttMsg_AppendStringWithLen(GWEN_BUFFER *buf, const char *s);
AQHOME_API int AQH_MqttMsg_DumpString(const uint8_t *ptr, uint32_t len, GWEN_BUFFER *buf);

AQHOME_API int AQH_MqttMsg_SkipStringAt(const uint8_t *ptr, uint32_t len);
AQHOME_API char *AQH_MqttMsg_ExtractStringAt(const uint8_t *ptr, uint32_t len);



#endif
