MQTT Connection
Antwort
25.04.19 12:41

Hi,

I'm a french student in computer science and I need to use a XDK110 in my internship project.

I'm able to recover the data of the sensors and I want to share it on a server with the MQTT Protocol. I succeeded to connect the XDK to the wifi but concerning the MQTT Connection I have the strange error "Error in XDK110 Application package.", what did I do wrong? 

Error :

 INFO | XDK DEVICE 1: WLANPersonalWPA2Connect : Connected to WPA network successfully. 
 INFO | XDK DEVICE 1: MQTT Connection : Failed 
 INFO | XDK DEVICE 1: MqttEventHandler : Event - 2
 INFO | XDK DEVICE 1: MqttEventHandler : Event - 3
 INFO | XDK DEVICE 1: Error in XDK110 Application package.
 INFO | XDK DEVICE 1: 	Package ID: 153
 INFO | XDK DEVICE 1: 	Module ID: 39
 INFO | XDK DEVICE 1: 	Severity code: 2
 INFO | XDK DEVICE 1: 	Error code: 122

 

Code :

/* --------------------------------------------------------------------------- |
 * INCLUDES & DEFINES ******************************************************** |
 * -------------------------------------------------------------------------- */

/* own header files */
#include "XdkAppInfo.h"
#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_APP_CONTROLLER

/* own header files */
#include "AppController.h"

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

/* additional interface header files */
#include "BCDS_BSP_Board.h"
#include "BCDS_CmdProcessor.h"
#include "BCDS_NetworkConfig.h"
#include "BCDS_Assert.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"

/* local variables ********************************************************** */

static WLAN_Setup_T WLANSetupInfo =
        {
                .IsEnterprise = false,
                .IsHostPgmEnabled = false,
				.SSID = "XDK_Hotspot",
				.Password = "FreeWifi",
                .IsStatic = false,
        };/**< WLAN setup parameters */


static MQTT_Setup_T MqttSetupInfo =
        {
                .MqttType = MQTT_TYPE_SERVALSTACK,
                .IsSecure = false,
        };/**< MQTT setup parameters */

static MQTT_Connect_T MqttConnectInfo =
        {
                .ClientId = "lens_g1TzMUhsPq14ehIXP1xO8fvbDps",
                .BrokerURL = "192.168.122.1",
                .BrokerPort = 1883,
                .CleanSession = true,
                .KeepAliveInterval = 100,
        };/**< MQTT connect parameters */

static void AppMQTTSubscribeCB(MQTT_SubscribeCBParam_T param);

static MQTT_Subscribe_T MqttSubscribeInfo =
        {
                .Topic = "mqtt/xdk/test",
                .QoS = 1UL,
                .IncomingPublishNotificationCB = AppMQTTSubscribeCB,
        };/**< MQTT subscribe parameters */

static MQTT_Publish_T MqttPublishInfo =
        {
                .Topic = "mqtt/xdk/test",
                .QoS = 1UL,
                .Payload = NULL,
                .PayloadLength = 0UL,
        };/**< MQTT publish parameters */

static uint32_t AppIncomingMsgCount = 0UL;/**< Incoming message count */

static char AppIncomingMsgTopicBuffer[256];/**< Incoming message topic buffer */

static char AppIncomingMsgPayloadBuffer[256];/**< Incoming message payload buffer */

static CmdProcessor_T * AppCmdProcessor;/**< Handle to store the main Command processor handle to be used by run-time event driven threads */

static xTaskHandle AppControllerHandle = NULL;/**< OS thread handle for Application controller to be used by run-time blocking threads */

/* global variables ********************************************************* */

/* inline functions ********************************************************* */

/* local functions ********************************************************** */

static void AppMQTTSubscribeCB(MQTT_SubscribeCBParam_T param)
{
    AppIncomingMsgCount++;
    memset(AppIncomingMsgTopicBuffer, 0, sizeof(AppIncomingMsgTopicBuffer));
    memset(AppIncomingMsgPayloadBuffer, 0, sizeof(AppIncomingMsgPayloadBuffer));

    if (param.PayloadLength < (int) sizeof(AppIncomingMsgPayloadBuffer))
    {
        strncpy(AppIncomingMsgPayloadBuffer, (const char *) param.Payload, param.PayloadLength);
    }

    if (param.TopicLength < (int) sizeof(AppIncomingMsgTopicBuffer))
    {
        strncpy(AppIncomingMsgTopicBuffer, param.Topic, param.TopicLength);
    }


    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);
}


/**
 * @brief Responsible for controlling the send data over MQTT application control flow.
 *
 * - Synchronize SNTP time stamp for the system if MQTT communication is secure
 * - Connect to MQTT broker
 * - Subscribe to MQTT topic
 * - Read environmental sensor data
 * - Publish data periodically for a MQTT topic
 *
 * @param[in] pvParameters
 * Unused
 */
static void AppControllerFire(void* pvParameters)
{
    BCDS_UNUSED(pvParameters);

    Retcode_T retcode = RETCODE_OK;

    const char * publishBuffer = "Hello World";
    MqttPublishInfo.Payload = publishBuffer;
    MqttPublishInfo.PayloadLength = strlen(publishBuffer);

    if (RETCODE_OK == retcode)
    {
        printf("MQTT Connection : Failed \r\n");
        retcode = MQTT_ConnectToBroker(&MqttConnectInfo, UINT32_C(60000));
    }

    if (RETCODE_OK == retcode)
    {
        printf("MQTT Subscription : Failed \r\n");
        retcode = MQTT_SubsribeToTopic(&MqttSubscribeInfo, UINT32_C(5000));
    }

    if (RETCODE_OK != retcode)
    {
        /* We raise error and still proceed to publish data periodically */
        Retcode_RaiseError(retcode);
    }

    /* A function that implements a task must not exit or attempt to return to
     its caller function as there is nothing to return to. */
    while (1)
    {
        MQTT_PublishToTopic(&MqttPublishInfo, UINT32_C(5000));
        vTaskDelay(UINT32_C(5000));
    }
}

/**
 * @brief To enable the necessary modules for the application
 * - WLAN
 * - ServalPAL
 * - SNTP (if secure communication)
 * - MQTT
 * - Sensor
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerEnable(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);

    Retcode_T retcode = WLAN_Enable();
    if (RETCODE_OK == retcode)
    {
        retcode = ServalPAL_Enable();
    }

    if (RETCODE_OK == retcode)
    {
        if (pdPASS != xTaskCreate(AppControllerFire, (const char * const ) "AppController", TASK_STACK_SIZE_APP_CONTROLLER, NULL, TASK_PRIO_APP_CONTROLLER, &AppControllerHandle))
        {
            retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_OUT_OF_RESOURCES);
        }
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerEnable : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

/**
 * @brief To setup the necessary modules for the application
 * - WLAN
 * - ServalPAL
 * - SNTP (if secure communication)
 * - MQTT
 * - Sensor
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerSetup(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);

    Retcode_T retcode = WLAN_Setup(&WLANSetupInfo);
    if (RETCODE_OK == retcode)
    {
        retcode = ServalPAL_Setup(AppCmdProcessor);
    }
    if (RETCODE_OK == retcode)
    {
        retcode = MQTT_Setup(&MqttSetupInfo);
    }
    if (RETCODE_OK == retcode)
    {
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerEnable, NULL, UINT32_C(0));
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerSetup : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

/* global functions ********************************************************* */

/** Refer interface header for description */
void AppController_Init(void * cmdProcessorHandle, uint32_t param2)
{
    BCDS_UNUSED(param2);

    Retcode_T retcode = RETCODE_OK;

    if (cmdProcessorHandle == NULL)
    {
        printf("AppController_Init : Command processor handle is NULL \r\n");
        retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_NULL_POINTER);
    }
    else
    {
        AppCmdProcessor = (CmdProcessor_T *) cmdProcessorHandle;
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerSetup, NULL, UINT32_C(0));
    }

    if (RETCODE_OK != retcode)
    {
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

 

Thanks for your help.

0 (0 Stimmen)
RE: MQTT Connection
Antwort
25.04.19 14:17 als Antwort auf Elie BOURY.

Hello Elie,

I am not sure what exactly is going wrong here but i have some assumptions.

First of all, this code snippet does not make sense.

    if (RETCODE_OK == retcode)
    {
        printf("MQTT Connection : Failed \r\n");
        retcode = MQTT_ConnectToBroker(&MqttConnectInfo, UINT32_C(60000));
    }

    if (RETCODE_OK == retcode)
    {
        printf("MQTT Subscription : Failed \r\n");
        retcode = MQTT_SubsribeToTopic(&MqttSubscribeInfo, UINT32_C(5000));
    }

You print "MQTT Connection: Failed" before you even execute the function. Furthermore the return code RETCODE_OK signals that an operation succeed.

I noticed that the second print "MQTT Subscription: Failed" is not shown in your console. So i would assume that the function MQTT_ConnectToBroker returns a value different from RETCODE_OK. The reason why the function does not work is not obvious for me. But maybe there are some problems with your MQTT broker.

I would recommend to test you code with this free online broker: broker.hivemq.com

I hope this was helpfull. If you have any further questions do not hesitate to ask.

Best regards,

Christian

 

0 (0 Stimmen)
RE: MQTT Connection
Antwort
26.04.19 11:06 als Antwort auf Christian Köhler.

Before all, thank you for your help.

First, the free online broker you gave me is working much better than my IP address so now I'm going to use it.

Secondly, concerning the strange code you highlighted, I found it weird too but it's the code given by the XDK Workbench ... 

However, I took another piece of code and now I succeed to connect the XDK to the broker, but now the problem is that every message that I want to send is a fail.

If you can help me again it would be really nice. Thanks again.

Error : 

 INFO | XDK DEVICE 1: Connected to WPA network successfully
 INFO | XDK DEVICE 1: IP address of device  192.168.43.135
 INFO | XDK DEVICE 1:               Mask    255.255.255.0
 INFO | XDK DEVICE 1:               Gateway 192.168.43.9
 INFO | XDK DEVICE 1:               DNS     192.168.43.9
 INFO | XDK DEVICE 1: WLANPersonalWPA2Connect : Connected to WPA network successfully. 
 INFO | XDK DEVICE 1: MqttEventHandler : Event - 0
 INFO | XDK DEVICE 1: MQTT_SubsribeToTopic : Subscribing to topic: mqtt/xdk/#, Qos: 1
 INFO | XDK DEVICE 1: MqttEventHandler : Event - 8
 INFO | XDK DEVICE 1: MqttEventHandler : Event - 15
 INFO | XDK DEVICE 1: MqttEventHandler : Event - 4
 INFO | XDK DEVICE 1: Error in XDK110 Application package.
 INFO | XDK DEVICE 1: 	Package ID: 153
 INFO | XDK DEVICE 1: 	Module ID: 39
 INFO | XDK DEVICE 1: 	Severity code: 2
 INFO | XDK DEVICE 1: 	Error code: 123
 INFO | XDK DEVICE 1: AppControllerFire : MQTT publish failed 
 INFO | XDK DEVICE 1: Error in XDK110 Application package.
 INFO | XDK DEVICE 1: 	Package ID: 153
 INFO | XDK DEVICE 1: 	Module ID: 39
 INFO | XDK DEVICE 1: 	Severity code: 2
 INFO | XDK DEVICE 1: 	Error code: 130
 INFO | XDK DEVICE 1: AppControllerFire : MQTT publish failed 
 INFO | XDK DEVICE 1: Error in XDK110 Application package.
 INFO | XDK DEVICE 1: 	Package ID: 153
 INFO | XDK DEVICE 1: 	Module ID: 39
 INFO | XDK DEVICE 1: 	Severity code: 2
 INFO | XDK DEVICE 1: 	Error code: 130
 INFO | XDK DEVICE 1: AppControllerFire : MQTT publish failed 
 INFO | XDK DEVICE 1: Error in XDK110 Application package.
 INFO | XDK DEVICE 1: 	Package ID: 153
 INFO | XDK DEVICE 1: 	Module ID: 39
 INFO | XDK DEVICE 1: 	Severity code: 2
 INFO | XDK DEVICE 1: 	Error code: 130
etc...

 

And here is my new code : 

 

/* own header files */
#include "XdkAppInfo.h"
#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_APP_CONTROLLER

/* own header files */
#include "AppController.h"

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

/* constant definitions ***************************************************** */

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

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

#define APP_TEMPERATURE_OFFSET_CORRECTION               (-3459)/**< Macro for static temperature offset correction. Self heating, temperature correction factor */
#define APP_MQTT_DATA_BUFFER_SIZE                   UINT32_C(256)/**< macro for data size of incoming subscribed and published messages */

#if APP_MQTT_SECURE_ENABLE
#define APP_RESPONSE_FROM_SNTP_SERVER_TIMEOUT       UINT32_C(10000)/**< Timeout for SNTP server time sync */
#endif /* APP_MQTT_SECURE_ENABLE */

/* local variables ********************************************************** */

static WLAN_Setup_T WLANSetupInfo =
        {
                .IsEnterprise = false,
                .IsHostPgmEnabled = false,
				.SSID = "XDK_Hotspot",
				.Password = "FreeWifi",
				.IsStatic = false
        };/**< WLAN setup parameters */

static Sensor_Setup_T SensorSetup =
        {
                .CmdProcessorHandle = NULL,
                .Enable =
                        {
                                .Accel = false,
                                .Mag = false,
                                .Gyro = false,
                                .Humidity = true,
                                .Temp = true,
                                .Pressure = true,
                                .Light = false,
                                .Noise = false,
                        },
                .Config =
                        {
                                .Accel =
                                        {
                                                .Type = SENSOR_ACCEL_BMA280,
                                                .IsRawData = false,
                                                .IsInteruptEnabled = false,
                                                .Callback = NULL,
                                        },
                                .Gyro =
                                        {
                                                .Type = SENSOR_GYRO_BMG160,
                                                .IsRawData = false,
                                        },
                                .Mag =
                                        {
                                                .IsRawData = false
                                        },
                                .Light =
                                        {
                                                .IsInteruptEnabled = false,
                                                .Callback = NULL,
                                        },
                                .Temp =
                                        {
                                                .OffsetCorrection = APP_TEMPERATURE_OFFSET_CORRECTION,
                                        },
                        },
        };/**< Sensor setup parameters */

#if APP_MQTT_SECURE_ENABLE
static SNTP_Setup_T SNTPSetupInfo =
        {
                .ServerUrl = SNTP_SERVER_URL,
                .ServerPort = SNTP_SERVER_PORT,
        };/**< SNTP setup parameters */
#endif /* APP_MQTT_SECURE_ENABLE */

static MQTT_Setup_T MqttSetupInfo =
        {
                .MqttType = MQTT_TYPE_SERVALSTACK,
                .IsSecure = APP_MQTT_SECURE_ENABLE,
        };/**< MQTT setup parameters */

static MQTT_Connect_T MqttConnectInfo =
        {
                .ClientId = "XDK_Sunderland",
                .BrokerURL = "broker.hivemq.com",
                .BrokerPort = 1883,
                .CleanSession = true,
                .KeepAliveInterval = 100,
        };/**< MQTT connect parameters */

static void AppMQTTSubscribeCB(MQTT_SubscribeCBParam_T param);

static MQTT_Subscribe_T MqttSubscribeInfo =
        {
                .Topic = "mqtt/xdk/#",
                .QoS = 1UL,
                .IncomingPublishNotificationCB = AppMQTTSubscribeCB,
        };/**< MQTT subscribe parameters */

static MQTT_Publish_T MqttPublishInfo =
        {
                .Topic = "mqtt/xdl/test",
                .QoS = 1UL,
                .Payload = NULL,
                .PayloadLength = 0UL,
        };/**< MQTT publish parameters */

static uint32_t AppIncomingMsgCount = 0UL;/**< Incoming message count */

static char AppIncomingMsgTopicBuffer[APP_MQTT_DATA_BUFFER_SIZE];/**< Incoming message topic buffer */

static char AppIncomingMsgPayloadBuffer[APP_MQTT_DATA_BUFFER_SIZE];/**< Incoming message payload buffer */

static CmdProcessor_T * AppCmdProcessor;/**< Handle to store the main Command processor handle to be used by run-time event driven threads */

static xTaskHandle AppControllerHandle = NULL;/**< OS thread handle for Application controller to be used by run-time blocking threads */

/* global variables ********************************************************* */

/* inline functions ********************************************************* */

/* local functions ********************************************************** */

static void AppMQTTSubscribeCB(MQTT_SubscribeCBParam_T param)
{
    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);
}

/**
 * @brief This will validate the WLAN network connectivity
 *
 * If there is no connectivity then it will scan for the given network and try to reconnect
 *
 * @return  RETCODE_OK on success, or an error code otherwise.
 */
static Retcode_T AppControllerValidateWLANConnectivity(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 /* APP_MQTT_SECURE_ENABLE */

        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_SubsribeToTopic(&MqttSubscribeInfo, MQTT_SUBSCRIBE_TIMEOUT_IN_MS);
            if (RETCODE_OK != retcode)
            {
                printf("AppControllerFire : MQTT subscribe failed \n\r");
            }
        }
    }
    return retcode;
}

/**
 * @brief Responsible for controlling the send data over MQTT application control flow.
 *
 * - Synchronize SNTP time stamp for the system if MQTT communication is secure
 * - Connect to MQTT broker
 * - Subscribe to MQTT topic
 * - Read environmental sensor data
 * - Publish data periodically for a MQTT topic
 *
 * @param[in] pvParameters
 * Unused
 */
static void AppControllerFire(void* pvParameters)
{
    BCDS_UNUSED(pvParameters);

    Retcode_T retcode = RETCODE_OK;
    Sensor_Value_T sensorValue;
    char publishBuffer[APP_MQTT_DATA_BUFFER_SIZE];
    const char *publishDataFormat = "Environmental Data -\n"
            "\r\tHumidity : %ld\n"
            "\r\tPressure : %ld\n"
            "\r\tTemperature : %f\xf8\n";

    memset(&sensorValue, 0x00, sizeof(sensorValue));
#if APP_MQTT_SECURE_ENABLE

    uint64_t sntpTimeStampFromServer = 0UL;

    /* We Synchronize the node with the SNTP server for time-stamp.
     * Since there is no point in doing a HTTPS communication without a valid time */
    do
    {
        retcode = SNTP_GetTimeFromServer(&sntpTimeStampFromServer, APP_RESPONSE_FROM_SNTP_SERVER_TIMEOUT);
        if ((RETCODE_OK != retcode) || (0UL == sntpTimeStampFromServer))
        {
            printf("AppControllerFire : SNTP server time was not synchronized. Retrying...\r\n");
        }
    } while (0UL == sntpTimeStampFromServer);

    BCDS_UNUSED(sntpTimeStampFromServer); /* Copy of sntpTimeStampFromServer will be used be HTTPS for TLS handshake */
#endif /* APP_MQTT_SECURE_ENABLE */

    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_SubsribeToTopic(&MqttSubscribeInfo, MQTT_SUBSCRIBE_TIMEOUT_IN_MS);
        if (RETCODE_OK != retcode)
        {
            printf("AppControllerFire : MQTT subscribe failed \n\r");
        }
    }

    if (RETCODE_OK != retcode)
    {
        /* We raise error and still proceed to publish data periodically */
        Retcode_RaiseError(retcode);
        vTaskSuspend(NULL);
    }

    /* A function that implements a task must not exit or attempt to return to
     its caller function as there is nothing to return to. */
    while (1)
    {
        /* Resetting / clearing the necessary buffers / variables for re-use */
        retcode = RETCODE_OK;

        /* Check whether the WLAN network connection is available */
        retcode = AppControllerValidateWLANConnectivity();
        if (RETCODE_OK == retcode)
        {
            retcode = Sensor_GetData(&sensorValue);
        }
        if (RETCODE_OK == retcode)
        {
            int32_t length = snprintf((char *) publishBuffer, APP_MQTT_DATA_BUFFER_SIZE, publishDataFormat,
                    (long int) sensorValue.RH, (long int) sensorValue.Pressure,
                    (sensorValue.Temp /= 1000));

            MqttPublishInfo.Payload = publishBuffer;
            MqttPublishInfo.PayloadLength = length;

            retcode = MQTT_PublishToTopic(&MqttPublishInfo, MQTT_PUBLISH_TIMEOUT_IN_MS);
            if (RETCODE_OK != retcode)
            {
                printf("AppControllerFire : MQTT publish failed \n\r");
            }
        }
        if (RETCODE_OK != retcode)
        {
            Retcode_RaiseError(retcode);
        }
        vTaskDelay(APP_MQTT_DATA_PUBLISH_PERIODICITY);
    }
}

/**
 * @brief To enable the necessary modules for the application
 * - WLAN
 * - ServalPAL
 * - SNTP (if secure communication)
 * - MQTT
 * - Sensor
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerEnable(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);

    Retcode_T retcode = WLAN_Enable();
    if (RETCODE_OK == retcode)
    {
        retcode = ServalPAL_Enable();
    }
#if APP_MQTT_SECURE_ENABLE
    if (RETCODE_OK == retcode)
    {
        retcode = SNTP_Enable();
    }
#endif /* APP_MQTT_SECURE_ENABLE */
    if (RETCODE_OK == retcode)
    {
        retcode = MQTT_Enable();
    }
    if (RETCODE_OK == retcode)
    {
        retcode = Sensor_Enable();
    }
    if (RETCODE_OK == retcode)
    {
        if (pdPASS != xTaskCreate(AppControllerFire, (const char * const ) "AppController", TASK_STACK_SIZE_APP_CONTROLLER, NULL, TASK_PRIO_APP_CONTROLLER, &AppControllerHandle))
        {
            retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_OUT_OF_RESOURCES);
        }
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerEnable : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
    Utils_PrintResetCause();
}

/**
 * @brief To setup the necessary modules for the application
 * - WLAN
 * - ServalPAL
 * - SNTP (if secure communication)
 * - MQTT
 * - Sensor
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerSetup(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);

    Retcode_T retcode = WLAN_Setup(&WLANSetupInfo);
    if (RETCODE_OK == retcode)
    {
        retcode = ServalPAL_Setup(AppCmdProcessor);
    }
#if APP_MQTT_SECURE_ENABLE
    if (RETCODE_OK == retcode)
    {
        retcode = SNTP_Setup(&SNTPSetupInfo);
    }
#endif /* APP_MQTT_SECURE_ENABLE */
    if (RETCODE_OK == retcode)
    {
        retcode = MQTT_Setup(&MqttSetupInfo);
    }
    if (RETCODE_OK == retcode)
    {
        SensorSetup.CmdProcessorHandle = AppCmdProcessor;
        retcode = Sensor_Setup(&SensorSetup);
    }
    if (RETCODE_OK == retcode)
    {
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerEnable, NULL, UINT32_C(0));
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerSetup : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

/* global functions ********************************************************* */

/** Refer interface header for description */
void AppController_Init(void * cmdProcessorHandle, uint32_t param2)
{
    BCDS_UNUSED(param2);

    Retcode_T retcode = RETCODE_OK;

    if (cmdProcessorHandle == NULL)
    {
        printf("AppController_Init : Command processor handle is NULL \r\n");
        retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_NULL_POINTER);
    }
    else
    {
        AppCmdProcessor = (CmdProcessor_T *) cmdProcessorHandle;
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerSetup, NULL, UINT32_C(0));
    }

    if (RETCODE_OK != retcode)
    {
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

/**@} */

 

0 (0 Stimmen)
RE: MQTT Connection
Antwort
02.05.19 07:48 als Antwort auf Elie BOURY.

Hello Elie,

I am sorry I know its been a while since my last answer.

First I will list all events you get from your code. Maybe this will already help you with your problem.

Event - 0: MQTT_CONNECTION_ESTABLISHED

Event - 8: MQTT_SUBSCRIPTION_ACKNOWLEDGED

Event -15: MQTT_PUBLISHED_DATA

Event -4: MQTT_CONNECTION_CLOSED

So it looks like you are able to connect properly to the broker and succeed to subscribe your topic. For some reason the MQTT connection get closed after your first published message.

The Error Codes have the following meaning:

Error Code 123: RETCODE_SENSOR_NONE_IS_ENABLED

Error Code 130: RETCODE_STORAGE_ERROR_IN_FILE_CLOSE_WIFI_MEDIA

For some reason none of the internal sensors are enabled. The results in the first error code. I am not really sure so far where the second error comes from, but it looks like the WiFi connection get closed. That would explain all the following errors.

I would recommend to check your sensor configuration and maybe do some "debugging". Like to check the retcode value after each of the called sensor functions.

Last thing i noticed: I was not able to locate the definition of your define APP_MQTT_SECURE_ENABLE. Please be aware that the define must contain a 0 or a 1 as value.

I hope this was a little bit helpfull. If you have any further questions dont hesitate to ask. I will answer as soon as possible.

Best regards,

Christian

0 (0 Stimmen)