Azure / azure-iot-sdk-c

A C99 SDK for connecting devices to Microsoft Azure IoT services
https://azure.github.io/azure-iot-sdk-c
Other
588 stars 737 forks source link

Messages not sending to IoTHub when sending data continuously #383

Closed mrhprasanna closed 6 years ago

mrhprasanna commented 6 years ago

Description of the issue:

I have been using the SDK version 1.1.29 and identified that messages are not sending to IoTHub when sending data continuously though network connection is available.

Code sample exhibiting the issue:

//============================================================================ // Name : AzureSample.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C, Ansi-style //============================================================================

include

include

include

include

include "azure_c_shared_utility/platform.h"

include "azure_c_shared_utility/threadapi.h"

include "azure_c_shared_utility/crt_abstractions.h"

include "azureiot/iothub_client.h"

include "azureiot/iothub_client_options.h"

include "azureiot/iothub_message.h"

include "azureiot/iothubtransportamqp_websockets.h"

include "azureiot/iothubtransporthttp.h"

include

using namespace std;

static const char* connectionString=""; static int callbackCounter;

void init(); void destroy(); int confirmation = 0;

typedef struct EVENT_INSTANCE_TAG { IOTHUB_MESSAGE_HANDLE messageHandle; int messageTrackingId; // For tracking the messages within the user callback. } EVENT_INSTANCE;

static IOTHUBMESSAGE_DISPOSITION_RESULT ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE message, void userContextCallback) { int counter = (int)userContextCallback; const unsigned char buffer = NULL; size_t size = 0; const char messageId; const char correlationId;

// Message properties
if ((messageId = IoTHubMessage_GetMessageId(message)) == NULL)
{
    messageId = "<null>";
}

if ((correlationId = IoTHubMessage_GetCorrelationId(message)) == NULL)
{
    correlationId = "<null>";
}

// Message content
IOTHUBMESSAGE_CONTENT_TYPE contentType = IoTHubMessage_GetContentType(message);

if (contentType == IOTHUBMESSAGE_BYTEARRAY)
{
    if (IoTHubMessage_GetByteArray(message, &buffer, &size) == IOTHUB_MESSAGE_OK)
    {
        (void)printf("Received Message [%d]\r\n Message ID: %s\r\n Correlation ID: %s\r\n BINARY Data: <<<%.*s>>> & Size=%d\r\n", *counter, messageId, correlationId, (int)size, buffer, (int)size);
    }
    else
    {
        (void)printf("Failed getting the BINARY body of the message received.\r\n");
    }
}
else if (contentType == IOTHUBMESSAGE_STRING)
{
    if ((buffer = (const unsigned char*)IoTHubMessage_GetString(message)) != NULL && (size = strlen((const char*)buffer)) > 0)
    {
        (void)printf("Received Message [%d]\r\n Message ID: %s\r\n Correlation ID: %s\r\n STRING Data: <<<%.*s>>> & Size=%d\r\n", *counter, messageId, correlationId, (int)size, buffer, (int)size);
    }
    else
    {
        (void)printf("Failed getting the STRING body of the message received.\r\n");
    }
}
else
{
    (void)printf("Failed getting the body of the message received (type %i).\r\n", contentType);
}

// Retrieve properties from the message
MAP_HANDLE mapProperties = IoTHubMessage_Properties(message);
if (mapProperties != NULL)
{
    const char*const* keys;
    const char*const* values;
    size_t propertyCount = 0;
    if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK)
    {
        if (propertyCount > 0)
        {
            size_t index;

            printf(" Message Properties:\r\n");
            for (index = 0; index < propertyCount; index++)
            {
                printf("\tKey: %s Value: %s\r\n", keys[index], values[index]);
            }
            printf("\r\n");
        }
    }
}

(*counter)++;

/* Some device specific action code goes here... */
return IOTHUBMESSAGE_ACCEPTED;

}

static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void userContextCallback) { EVENT_INSTANCE eventInstance = (EVENT_INSTANCE)userContextCallback; (void)printf("Confirmation[%d] received for message tracking id with result = %s\r\n",callbackCounter,ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); / Some device specific action code goes here... */ callbackCounter++; if(result==IOTHUB_CLIENT_CONFIRMATION_OK) { confirmation = 1; IoTHubMessage_Destroy(eventInstance->messageHandle); eventInstance->messageHandle = NULL; } else { confirmation = -1; }

}

static char msgText[1024]; static char propText[1024]; IOTHUB_CLIENT_HANDLE iotHubClientHandle; size_t retryTimeSeconds=0;

static void connectionStatusCallback(IOTHUB_CLIENT_CONNECTION_STATUS callback, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void *userContext) {

printf("Reason [%d]", reason);
if (reason == IOTHUB_CLIENT_CONNECTION_EXPIRED_SAS_TOKEN)
{
    std::cout<<"IOTHUB_CLIENT_CONNECTION_EXPIRED_SAS_TOKEN"<<std::endl;
}
else if (reason == IOTHUB_CLIENT_CONNECTION_BAD_CREDENTIAL)
{
    std::cout<<"IOTHUB_CLIENT_CONNECTION_BAD_CREDENTIAL"<<std::endl;
}
if(reason==IOTHUB_CLIENT_CONNECTION_NO_NETWORK)
{
    printf("connection is not available\n");
}
else if(reason==IOTHUB_CLIENT_CONNECTION_OK)
{
    printf("connection is available\n");
}

}

void init() { int receiveContext = 0; if (platform_init() != 0) { (void)printf("ERROR: failed initializing the platform.\r\n"); } //AMQP_Protocol_over_WebSocketsTls HTTP_Protocol else if ((iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString,AMQP_Protocol_over_WebSocketsTls)) == NULL) { (void)printf("ERROR: iotHubClientHandle is NULL!\r\n"); platform_deinit(); } else { / unsigned int timeout = 241000; // Because it can poll "after 9 seconds" polls will happen effectively // at ~10 seconds. // Note that for scalabilty, the default value of minimumPollingTime // is 25 minutes. For more information, see: // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging unsigned int minimumPollingTime = 9; if (IoTHubClient_SetOption(iotHubClientHandle, "timeout", &timeout) != IOTHUB_CLIENT_OK) { printf("failure to set option \"timeout\"\r\n"); } if (IoTHubClient_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) { printf("failure to set option \"MinimumPollingTime\"\r\n");/ // For mbed add the certificate information if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) { printf("failure to set option \"TrustedCerts\"\r\n"); }

        /*Setting Message call back, so we can receive Commands. */
        if (IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
        {
            (void)printf("ERROR: IoTHubClient_SetMessageCallback..........FAILED!\r\n");
        }
        if(IoTHubClient_SetRetryPolicy(iotHubClientHandle,IOTHUB_CLIENT_RETRY_POLICY::IOTHUB_CLIENT_RETRY_INTERVAL,retryTimeSeconds)!=IOTHUB_CLIENT_OK)
        {
            printf("Error:Iothubclient_SetRetryPolicy failed..\n");
        }
        void *p = NULL;
        IoTHubClient_SetConnectionStatusCallback(iotHubClientHandle,connectionStatusCallback,p);
    size_t keepAliveFrequencySecs = 60;
    IoTHubClient_SetOption(iotHubClientHandle,OPTION_SERVICE_SIDE_KEEP_ALIVE_FREQ_SECS,&keepAliveFrequencySecs);
    }

}

void destroy() { IoTHubClient_Destroy(iotHubClientHandle); platform_deinit(); }

void iothub_client_sample_amqp_websockets_run(EVENT_INSTANCE* messages) {

srand((unsigned int)time(NULL));
double avgWindSpeed = 10.0;
double minTemperature = 20.0;
double minHumidity = 60.0;
double temperature = 0;
double humidity = 0;

callbackCounter = 0;

            temperature = minTemperature + (rand() % 10);
            humidity = minHumidity +  (rand() % 20);
    sprintf_s(msgText, sizeof(msgText), "{\"Sample\":[{\"Sample_1\":\"Sample_1_Value\",\"Sample_2\":\"Sample_2_Value\",\"Sample_3\":\"Sample_3_value\",\"Sample_4\":\"Sample-Value_4\",\"Sample_5\":\"Sample_Value_5\",\"Sample_6\":\"Sample_Value_6\",\"Sample_7\":\"Sample_value_7\",\"Sample_8\":\"Sample_Value_8\",\"Sample_9\":{\"Sample_value_9_1\":\"Sample_Value_9_2\",\"Sample_10\":\"Sample_Vlaue_10\",\"Sample_11\":\"Sample_value_11\"},\"Sample_12\":[{\"Sample_Value_12_1\":\"Sample_value_12_2\",\"Sample_13\":\"Sample_Value_13\"}],\"Sample_14\":\"Sample_value_14\",\"Sample_15\":\"Sample_Value_15\"}]}");
            if ((messages->messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText))) == NULL)
            {
                (void)printf("ERROR: iotHubMessageHandle is NULL!\r\n");
            }
            else
            {
                messages->messageTrackingId = 1;

                MAP_HANDLE propMap = IoTHubMessage_Properties(messages->messageHandle);
                (void)sprintf_s(propText, sizeof(propText), temperature > 28 ? "true" : "false");
                if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK)
                {
                    (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
                }

       int a =10;
                if (IoTHubClient_SendEventAsync(iotHubClientHandle, messages->messageHandle, SendConfirmationCallback, messages) != IOTHUB_CLIENT_OK)
                {
                    (void)printf("ERROR: IoTHubClient_SendEventAsync..........FAILED!\r\n");
                }
                else
                {
                    (void)printf("IoTHubClient_SendEventAsync accepted data for transmission to IoT Hub.\r\n");
                }
             }

        /* Wait for Commands. */
       //(void)printf("Press any key to exit the application. \r\n");
        //(void)getchar();
}

int main(void) { init(); EVENT_INSTANCE message[1000]; int i=0; while(true) { std::cout<<"Slot ID:"<<i<<std::endl; iothub_client_sample_amqp_websockets_run(&message[i]); i=i+1; sleep(1); if(i == 1000) { i= 0; } } return EXIT_SUCCESS; }

Console log of the issue:

Info: Preparing transport for re-connection Error: Time:Mon Feb 19 17:07:02 2018 File:/build/azure-iot-sdk-c-o2dV7s/azure-iot-sdk-c-0.1.0/iothub_client/src/iothubtransportamqp_methods.c Func:iothubtransportamqp_methods_unsubscribe Line:817 unsubscribe called while not subscribed Error: Time:Mon Feb 19 17:07:02 2018 File:/home/administrator/azure-iot-sdk-c/uamqp/src/saslclientio.c Func:saslclientio_send_async Line:1173 send called while not open Error: Time:Mon Feb 19 17:07:02 2018 File:/home/administrator/azure-iot-sdk-c/uamqp/src/connection.c Func:on_bytes_encoded Line:253 Cannot send encoded bytes Error: Time:Mon Feb 19 17:07:02 2018 File:/home/administrator/azure-iot-sdk-c/uamqp/src/saslclientio.c Func:saslclientio_close_async Line:1122 saslclientio_close called while not open Error: Time:Mon Feb 19 17:07:02 2018 File:/home/administrator/azure-iot-sdk-c/uamqp/src/connection.c Func:on_bytes_encoded Line:257 xio_close failed Error: Time:Mon Feb 19 17:07:02 2018 File:/home/administrator/azure-iot-sdk-c/uamqp/src/saslclientio.c Func:saslclientio_close_async Line:1122 saslclientio_close called while not open Error: Time:Mon Feb 19 17:07:02 2018 File:/home/administrator/azure-iot-sdk-c/uamqp/src/connection.c Func:connection_close Line:1358 xio_close failed Reason [4]connection is not available Slot ID:246 IoTHubClient_SendEventAsync accepted data for transmission to IoT Hub.

jspaith commented 6 years ago

Could you try upgrading your SDK before we investigate deeper? In particular...

Info: Preparing transport for re-connection

We've fixed a bunch of reconnection issues in 1.1.30 in particular so this issue may just resolve.

mrhprasanna commented 6 years ago

@jspaith I will upgrade the SDK and update the result.

mrhprasanna commented 6 years ago

@jspaith I have tested with latest release and still facing the same issue.

jspaith commented 6 years ago

@mrhprasanna - I've been assuming this is the issue being discussed offline with Ewerton but if this is a separate issue please set me straight.

I know there's still loose ends to tie up on the reconnect over slow network issue so I'm not trying to close this, but I want to make sure we're not sweeping a separate issue under the rug.

jspaith commented 6 years ago

I'm closing out since it's been quiet a while and I think some off other discussions around this are a bit different than initial thread. By all means re-open or create new issues if there's further concerns.

tameraw commented 6 years ago

@mrhprasanna thank you for your contribution to our open-sourced project!  Please help us improve by filling out this 2-minute customer satisfaction survey.