#include <string.h>
#include "mqtt.h"

uint8_t mqtt_readBuffer[MQTT_BUFFER_SIZE];
volatile uint16_t mes_id;

wiz_NetInfo netInfo = { .mac  = {0x00, 0x08, 0xdc, 0xab, 0xcd, 0xf2}, // Mac address
		.ip   = {192, 168, 1, 1},         // IP address
		.sn   = {255, 255, 0, 0},         // Subnet mask
		.dns =  {0,0,0,0},			  // DNS address (google dns)
		.gw   = {192, 168, 0, 1}, // Gateway address
		.dhcp = NETINFO_STATIC};    //Static IP configuration
uint8_t MQTT_targetIP[4] = {192, 168, 5, 2};

//MQTT subscribe call-back is here
void messageArrived(MessageData* md)
{
	char _topic_name[64] = "\0";
	char _message[128] = "\0";

	MQTTMessage* message = md->message;
	MQTTString* topic = md->topicName;
	strncpy(_topic_name, topic->lenstring.data, topic->lenstring.len);
	strncpy(_message, message->payload, message->payloadlen);
	printf("<<MQTT Sub: [%s] %s", _topic_name , _message);

	//md->topicName->
	/*
	  for (uint8_t i = 0; i < md->topicName->lenstring.len; i++)
		putchar(*(md->topicName->lenstring.data + i));

	  printf(" (%.*s)\r\n", (int32_t)message->payloadlen, (char*)message->payload);
	 */
}

void mqtt_pub(Client* mqtt_client, char * mqtt_topic, char * mqtt_msg, int mqtt_msg_len)
{
	static uint32_t mqtt_pub_count = 0;
	static uint8_t mqtt_err_cnt = 0;
	int32_t mqtt_rc;

    //printf(">>MQTT pub msg nr%lu ", ++mqtt_pub_count);
	MQTTMessage pubMessage;
	pubMessage.qos = QOS0;
	pubMessage.id = mes_id++;
	pubMessage.payloadlen = (size_t)mqtt_msg_len;
	pubMessage.payload = mqtt_msg;
	mqtt_rc = MQTTPublish(mqtt_client, mqtt_topic , &pubMessage);
	//Analize MQTT publish result (for MQTT failover mode)
	if (mqtt_rc == SUCCESSS)
	{
		mqtt_err_cnt  = 0;
		//printf(" - OK\r\n");
	}
	else
	{
		//printf(" - ERROR\r\n");
		//Reboot device after 20 continuous errors (~ 20sec)
        //while(1);
		if(mqtt_err_cnt++ > 20)
		{
			printf("Connection with MQTT Broker was lost!!\r\nReboot the board..\r\n");
			while(1);
		}
	}
}
