Developer Portal Community

    cancel
    Showing results for 
    Search instead for 
    Did you mean: 

    XDK MQTT Connection Problems

    Narmak
    Member

    XDK MQTT Connection Problems

    Hi,

    I have written some code to send sensor data over wifi using mqtt to my laptop.

    Most of the time everything works just fine, but sometimes I get errors I can't figure out.

     

    1. Sometimes the wifi connection fails when the connection is being established after reboot... I get the following message: "Error in WLAN package. Package ID: 10, Module ID: 3, Severity code: 2, Error code: 1". I know there was a topic in the old forum explaning the error codes, but since I can't access that topic I can't figure out the issue here.

    2. If I increase the measuring and sending frequency to a value higher than 6Hz, it works just fine for a while, but then I either receive the following error "HardFault_Occured_going to reset the processor" and the XDK restarts or the XDK just stops doing anything and I have to manually restart it.

    3. Even before the XDK crashes at a high frequency, the sending intervals become inconsistent. E.g. I set the frequency to 10Hz and some timestamps (internal clock of XDK) are more than a second apart, others only 2ms.

    Thanks in Advance

    Ps: Since I could neither attach a textfile nor add my entire code here (exceeded 20.000 characters), I only post the most relevant parts:

     

     

    #include "XdkAppInfo.h"
    #undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
    #define BCDS_MODULE_ID XDK_APP_MODULE_ID_APP_CONTROLLER
    
    #include "AppController.h"
    
    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    
    #include "BCDS_CmdProcessor.h"
    #include "FreeRTOS.h"
    #include "XDK_Utils.h"
    #include "task.h"
    
    #include "Serval_Mqtt.h"
    #include "BCDS_NetworkConfig.h"
    #include "BCDS_WlanConnect.h"
    
    #include "XdkSensorHandle.h"
    #include "timers.h"
    
    #include "PAL_initialize_ih.h"
    #include "PAL_socketMonitor_ih.h"
    
    #include "BCDS_ServalPal.h"
    #include "BCDS_ServalPalWifi.h"
    #include "XDK_LED.h"
    #include "XDK_Button.h"
    #include "XDK_WLAN.h"
    #include "Serval_Clock.h"
    
    #include "arm_math.h"
    
    #define MQTT_BROKER_HOST "broker.mqttdashboard.com"
    //#define MQTT_BROKER_HOST "192.168.137.1"
    #define MQTT_BROKER_PORT 1883
    #define TIMER_AUTO_RELOAD_ON pdTRUE
    #define TIMERBLOCKTIME UINT32_C(0Xfffff)
    #define SECONDS(x) ((portTickType) (x) / portTICK_RATE_MS)
    
    #define  XDK_APP_DELAY      UINT32_C(1000)
    static MqttSession_T session;
    static MqttSession_T *session_ptr = &session;
    
    static CmdProcessor_T * AppCmdProcessor;
    CmdProcessor_T ServalCmdProcessor;
    
    xTimerHandle measurementTimer;
    
    static xTaskHandle AppControllerHandle = NULL;
    static WLAN_Setup_T WLANSetupInfo = {
                    .IsEnterprise = false,
                    .IsHostPgmEnabled = false,
                    .SSID = "*******",
                    .Password = "*******",
                    .IsStatic = false,
    };
    
    void publishAccValues(uint32_t type){
    	static char *pub_message;
    	static char *pub_topic;
    	static StringDescr_T pub_topic_descr;
    
             //Reading values from sensor and converting the floats to one string happens here
    
             pub_message = message;
             pub_topic = "XDK1";
    	StringDescr_wrap(&pub_topic_descr, pub_topic);
    	Mqtt_publish(session_ptr, pub_topic_descr, pub_message
    			,strlen(pub_message), MQTT_QOS_AT_MOST_ONE, false);
    }
    
    static void readAccelerometer(void)
    {
    	 Retcode_T returnValue =
             Accelerometer_readXyzGValue(xdkAccelerometers_BMA280_Handle,&bma280);
    	 LightSensor_readLuxData(xdkLightSensor_MAX44009_Handle, &max44009);
    
    	 if (RETCODE_OK == returnValue) {
    		 publishAccValues(1);
    	 }
    }
    
    void AccelerationFunction(xTimerHandle pxTimer){
    	BCDS_UNUSED(pxTimer);
    	readAccelerometer();
    }
    
    retcode_t init(void){
    	retcode_t rc_initialize = Mqtt_initialize();
    	if(rc_initialize == RC_OK) {
    		session_ptr = &session;
    		Mqtt_initializeInternalSession(session_ptr);
    	}
    	return rc_initialize;
    }
    
    void servalPalSetup(void) {
    	CmdProcessor_Initialize(&ServalCmdProcessor, "ServalCmdPrc", 3,1000,10);
    	ServalPal_Initialize(&ServalCmdProcessor);
    	ServalPalWiFi_Init();
    	ServalPalWiFi_StateChangeInfo_T stateChangeInfo = {
    			SERVALPALWIFI_OPEN, INT16_C(0) };
    	ServalPalWiFi_NotifyWiFiEvent(SERVALPALWIFI_STATE_CHANGE, &stateChangeInfo);
    }
    
    void config_set_connect_data(void){
    	static char *device_name = "XDK1";
    	session_ptr->MQTTVersion = 3;
    	session_ptr->keepAliveInterval = 100;
    	session_ptr->cleanSession = true;
    	session_ptr->will.haveWill = false;
    	StringDescr_T device_name_descr;
    	StringDescr_wrap(&device_name_descr, device_name);
    	session_ptr->clientID=device_name_descr;
    }
    
    void config_set_target(void){
    	static char mqtt_broker[64];
    		const char *mqtt_broker_format = "mqtt://%s:%d";
    
    		char server_ip_buffer[13];
    
    		Ip_Address_T ip;
    		PAL_getIpaddress((uint8_t *) MQTT_BROKER_HOST, &ip);
    
    
    		char ip[15] = {'1','9','2','.','1','6','8','.','1','2','8','.','0','0','1'};
    
    		//Ip_convertAddrToString(&ip, ip);
    		sprintf(mqtt_broker, mqtt_broker_format,
    				test, MQTT_BROKER_PORT);
    		SupportedUrl_fromString(mqtt_broker,
    				(uint16_t) strlen(mqtt_broker), &session_ptr->target);
    }
    
    static void AppControllerSetup(void * param1, uint32_t param2){
        BCDS_UNUSED(param1);
        BCDS_UNUSED(param2);
        Retcode_T retcode = RETCODE_OK;
    
        WLAN_Setup(&WLANSetupInfo);
        PAL_initialize();
        PAL_socketMonitorInit();
    
    
        initLightSensor();
        initAccelerometer();
        initEnvironmental();
    
        retcode = LED_Setup();
        if (RETCODE_OK == retcode){
        	ButtonSetup.CmdProcessorHandle = AppCmdProcessor;
        	retcode = Button_Setup(&ButtonSetup);
        }
    
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerEnable, NULL, UINT32_C(0));
        if (RETCODE_OK != retcode)
        {
            printf("AppControllerSetup : Failed \r\n");
            Retcode_RaiseError(retcode);
            assert(0);
        }
    }
    static void AppControllerEnable(void * param1, uint32_t param2){
        BCDS_UNUSED(param1);
        BCDS_UNUSED(param2);
        Retcode_T retcode = RETCODE_OK;
    
        retcode = WLAN_Enable();
        if(retcode == RETCODE_OK) {
        	LED_On(LED_INBUILT_YELLOW);
        }
        retcode = init();
        if(retcode == RC_OK){
        	config_set_target();
        	config_set_connect_data();
            config_set_event_handler();
            not_connect();
            LED_On(LED_INBUILT_RED);
        }
        else {
        	printf("Initialize Failed\n\r");
        }
        retcode = LED_Enable();
        if (RETCODE_OK == retcode){
        	retcode  = Button_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);
        }
        Utils_PrintResetCause();
    }
    
    
    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);
        }
        measurementTimer = xTimerCreate((char* const) "",
    	   			SECONDS(10),
    				TIMER_AUTO_RELOAD_ON,
    				NULL,
    				AccelerationFunction);
    }

     

     

     

     

    10 REPLIES 10
    Grocamora
    Community Manager

    Re: XDK MQTT Connection Problems

    Hello @Narmak,

     

    Thanks a lot for your question in our community 😎

    Our XDK experts will have a look and we will get back to you as soon as possible!
    Thanks a lot and stay tuned!

     

    Roca

    Tags (4)
    Padmapriya
    Long-established Member

    Re: XDK MQTT Connection Problems

    Hello,

    1. The error code corresponds to WiFi connectivity failure. Package id: SDK\xdk110\Platform\Wlan, Error code: FAILURE.
      1. Also under what circumstance are you rebooting the device ?
    2. How are you sending sensor data to MQTT server ?
      1. What sensors?
      2. sensor setup : sampling freq
    Narmak
    Member

    Re: XDK MQTT Connection Problems

    Hi,

    thanks for your reply, see my answers/further questions:

     

    1. What could be the reason for the failure? Is there a way to avoid this?
      1. Either when I am starting a new measurement or the transmission fails and I am forced to reboot
    2. I added the code snippet of one of my publish functions
      1. Currently I am using the acceleration, environmental and ambient light sensor. So far I am either combining acceleration and ambient light or environmental and ambient light.
      2. I simply call the Accelerometer_init(xdkAccelerometers_BMA280_Handle) function to set up the sensor

     

    I hope I could answer all your questions

    void publishAccValues(void){
    	static char *pub_message;
    	static char *pub_topic;
    	static StringDescr_T pub_topic_descr;
    	float x = (float) bma280.xAxisData;
    	float y = (float) bma280.yAxisData;
    	float z = (float) bma280.zAxisData;
    
    	uint64_t time = getCurrentTime();
    
    	char str[100];
    
    	int tmpInt1 = (float) time;                 
    
    	sprintf (str, "%d", tmpInt1);
    
    	char xS[10];
    	char yS[10];
    	char zS[10];
    	char light[10];
    
    	char semi[2] = {';'};
    	char timesplit[2] = {'%'};
    	snprintf(xS, sizeof xS, "%f", x);
    	snprintf(yS, sizeof yS, "%f", y);
    	snprintf(zS, sizeof zS, "%f", z);
    	snprintf(light, sizeof light, "%lu", max44009);
    
    	pub_topic = "XDK1";
    	char message[100] = {'A','c','c',':', ' '};
    	strcat(message,xS);
    	strcat(message, semi);
    	strcat(message,yS);
    	strcat(message, semi);
    	strcat(message, zS);
    	strcat(message, semi);
    	strcat(message, light);
    	strcat(message, timesplit);
    	strcat(message, str);
    	strcat(message, semi);
    
    	pub_message = message;
    
    	StringDescr_wrap(&pub_topic_descr, pub_topic);
    	Mqtt_publish(session_ptr, pub_topic_descr, pub_message
    			,strlen(pub_message), MQTT_QOS_AT_MOST_ONE, false);
    }

     

    Padmapriya
    Long-established Member

    Re: XDK MQTT Connection Problems

    Hello,

    Reg: WiFi failure

    It is uncertian to explain why wifi initialization fail, without knowing the exact code execution flow. What type reboot is done, hard/soft ? If done soft reset, please make sure to disable the WiFi connection and close the wifi/mqtt session.

    Reg: Data over MQTT

    I am quite suspicious about the usage of StringDescr_wrap(). Can you simplify your code by using snprintf as below,

    const char *publishDataFormat = "Environmental Data -\n"
                "\r\tHumidity : %ld\n"
                "\r\tPressure : %ld\n"
                "\r\tTemperature : %f\xf8\n";
    Sensor_Value_T sensorValue;
    char publishBuffer[APP_MQTT_DATA_BUFFER_SIZE];
    
    int32_t length = snprintf((char *) publishBuffer, 256, publishDataFormat,
    					(long int) sensorValue.RH, (long int) sensorValue.Pressure,
    					(sensorValue.Temp /= 1000));
    
    MqttPublishInfo.Payload = publishBuffer;
    MqttPublishInfo.PayloadLength = length;
    MQTT_PublishToTopic(&MqttPublishInfo, 20000);

    You can refer SendDataOverMQTT application provided in XDK workbench for further reference.

    Icon--AD-black-48x48Icon--address-consumer-data-black-48x48Icon--appointment-black-48x48Icon--back-left-black-48x48Icon--calendar-black-48x48Icon--center-alignedIcon--Checkbox-checkIcon--clock-black-48x48Icon--close-black-48x48Icon--compare-black-48x48Icon--confirmation-black-48x48Icon--dealer-details-black-48x48Icon--delete-black-48x48Icon--delivery-black-48x48Icon--down-black-48x48Icon--download-black-48x48Ic-OverlayAlertIcon--externallink-black-48x48Icon-Filledforward-right_adjustedIcon--grid-view-black-48x48IC_gd_Check-Circle170821_Icons_Community170823_Bosch_Icons170823_Bosch_Icons170821_Icons_CommunityIC-logout170821_Icons_Community170825_Bosch_Icons170821_Icons_CommunityIC-shopping-cart2170821_Icons_CommunityIC-upIC_UserIcon--imageIcon--info-i-black-48x48Icon--left-alignedIcon--Less-minimize-black-48x48Icon-FilledIcon--List-Check-grennIcon--List-Check-blackIcon--List-Cross-blackIcon--list-view-mobile-black-48x48Icon--list-view-black-48x48Icon--More-Maximize-black-48x48Icon--my-product-black-48x48Icon--newsletter-black-48x48Icon--payment-black-48x48Icon--print-black-48x48Icon--promotion-black-48x48Icon--registration-black-48x48Icon--Reset-black-48x48Icon--right-alignedshare-circle1Icon--share-black-48x48Icon--shopping-bag-black-48x48Icon-shopping-cartIcon--start-play-black-48x48Icon--store-locator-black-48x48Ic-OverlayAlertIcon--summary-black-48x48tumblrIcon-FilledvineIc-OverlayAlertwhishlist