/*
 * cToMita.c
 *
 *  Created on: 16. 2. 2022
 *      Author: filip
 */

/* system header files */
#include <stdio.h>

/* additional interface header files */
#include "BCDS_BSP_Board.h"
#include "BCDS_CmdProcessor.h"
#include "BCDS_WlanNetworkConfig.h"
#include "BCDS_WlanNetworkConnect.h"
#include "BCDS_Assert.h"
#include "XDK_Utils.h"
#include "XDK_WLAN.h"
#include "XDK_MQTT.h"
#include "XDK_Sensor.h"
#include "XDK_SNTP.h"
#include "XDK_ServalPAL.h"
#include "FreeRTOS.h"
#include "task.h"
#include "cToMita.h"


#define MQTT_CONNECT_TIMEOUT_IN_MS                  UINT32_C(60000)/**< Macro for MQTT connection timeout in milli-second */

#define MQTT_SUBSCRIBE_TIMEOUT_IN_MS                UINT32_C(20000)/**< Macro for MQTT subscription timeout in milli-second */

void AppMQTTSubscribeCB(MQTT_SubscribeCBParam_T param);

uint8_t change(int32_t Data){
	return(unsigned int(Data));
}

MQTT_Subscribe_T MqttSubscribeInfo =
        {
                .Topic = APP_MQTT_TOPIC,
                .QoS = 1UL,
                .IncomingPublishNotificationCB = AppMQTTSubscribeCB,
        };

static MQTT_Setup_T MqttSetupInfo =
        {
                .MqttType = MQTT_TYPE_SERVALSTACK,
                .IsSecure = APP_MQTT_SECURE_ENABLE,
        };

static MQTT_Connect_T MqttConnectInfo =
        {
                .ClientId = APP_MQTT_CLIENT_ID,
				.Username = APP_MQTT_USERNAME,
				.Password = APP_MQTT_PASSWORD,
                .BrokerURL = APP_MQTT_BROKER_HOST_URL,
                .BrokerPort = APP_MQTT_BROKER_HOST_PORT,
                .CleanSession = true,
                .KeepAliveInterval = 100,
        };

static uint32_t AppIncomingMsgCount = 0UL;

static char AppIncomingMsgTopicBuffer[APP_MQTT_DATA_BUFFER_SIZE];

static char AppIncomingMsgPayloadBuffer[APP_MQTT_DATA_BUFFER_SIZE];

void Delay_1s(void){
	wait(1000);
}

void AppMQTTSubscribeCB(MQTT_SubscribeCBParam_T param)
{
	printf("AppMQTTSubscribeCB \n\r");
    AppIncomingMsgCount++;
    memset(AppIncomingMsgTopicBuffer, 0, sizeof(AppIncomingMsgTopicBuffer));
    memset(AppIncomingMsgPayloadBuffer, 0, sizeof(AppIncomingMsgPayloadBuffer));

    if (param.PayloadLength < sizeof(AppIncomingMsgPayloadBuffer))
    {
        strncpy(AppIncomingMsgPayloadBuffer, (const char *) param.Payload, param.PayloadLength);
    }
    else
    {
        strncpy(AppIncomingMsgPayloadBuffer, (const char *) param.Payload, (sizeof(AppIncomingMsgPayloadBuffer) - 1U));
    }
    if (param.TopicLength < (int) sizeof(AppIncomingMsgTopicBuffer))
    {
        strncpy(AppIncomingMsgTopicBuffer, param.Topic, param.TopicLength);
    }
    else
    {
        strncpy(AppIncomingMsgTopicBuffer, param.Topic, (sizeof(AppIncomingMsgTopicBuffer) - 1U));
    }

    printf("AppMQTTSubscribeCB : #%d, Incoming Message:\r\n"
            "\tTopic: %s\r\n"
            "\tPayload: \r\n\"\"\"\r\n%s\r\n\"\"\"\r\n", (int) AppIncomingMsgCount,
            AppIncomingMsgTopicBuffer, AppIncomingMsgPayloadBuffer);
}

static Retcode_T InspectAndActOnWlanNetworkStatus(void)
{
    Retcode_T retcode = RETCODE_OK;
    WlanNetworkConnect_IpStatus_T nwStatus;

    nwStatus = WlanNetworkConnect_GetIpStatus();
    if (WLANNWCT_IPSTATUS_CT_AQRD != nwStatus)
    {
#if APP_MQTT_SECURE_ENABLE
        static bool isSntpDisabled = false;
        if (false == isSntpDisabled)
        {
            retcode = SNTP_Disable();
        }
        if (RETCODE_OK == retcode)
        {
            isSntpDisabled = true;
            retcode = WLAN_Reconnect();
        }
        if (RETCODE_OK == retcode)
        {
            retcode = SNTP_Enable();
        }
#else
        retcode = WLAN_Reconnect();
#endif
    }
    return retcode;
}

int mqttSub(int param){

	Retcode_T retcode = RETCODE_OK;
	        /* Resetting / clearing the necessary buffers / variables for re-use */
	retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_FAILURE);

	retcode = MQTT_Enable();
    if (RETCODE_OK == retcode)
    {
        printf("MQTT Enabled\r\n");
    }

    /*MQTT_Setup(&MqttSetupInfo);
    if (RETCODE_OK == retcode)
    {
        printf("MQTT Setup done\r\n");
    }*/

	        /** @note It is recommended to ensure valid WLAN and MQTT connection is maintained
	         *  before any MQTT transactions between device and the server. */
	        /* WLAN status check */
	retcode = InspectAndActOnWlanNetworkStatus();
	if (RETCODE_OK == retcode)
	{
		printf("WLAN OK \n\r");
			//{
		        /* MQTT broker connectivity check */
		       retcode = MQTT_IsConnected();
		      if (RETCODE_OK != retcode)
		      {
		        printf("MQTT reconecting \n\r");
				// if (RETCODE_OK == retcode)
				//	{
						retcode = MQTT_ConnectToBroker(&MqttConnectInfo, MQTT_CONNECT_TIMEOUT_IN_MS);
						if (RETCODE_OK != retcode)
						{
							printf("AppControllerFire : MQTT connection to the broker failed \n\r");
						}
				//	}
				 if (RETCODE_OK == retcode)
				 	{
		    			retcode = MQTT_SubscribeToTopic(&MqttSubscribeInfo, MQTT_SUBSCRIBE_TIMEOUT_IN_MS);
		    			   if (RETCODE_OK != retcode)
		    			    {
		    			        printf("MQTT Subscription : Failed \r\n");
		    			        Retcode_RaiseError(retcode);
		    			    }
		    		}
		       }
	}
			return (1);
}

