Пример #1
0
static void sendMessage(IOTHUB_CLIENT_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size)
{
    static unsigned int messageTrackingId;
    IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
    if (messageHandle == NULL)
    {
        printf("unable to create a new IoTHubMessage\r\n");
    }
    else
    {
        if (IoTHubClient_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK)
        {
            printf("failed to hand over the message to IoTHubClient");
        }
        else
        {
            printf("IoTHubClient accepted the message for delivery\r\n");
        }

        IoTHubMessage_Destroy(messageHandle);
    }
    free((void*)buffer);
    messageTrackingId++;
}
Пример #2
0
void IoTHubClient_LL_Destroy(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle)
{
    /*Codes_SRS_IOTHUBCLIENT_LL_02_009: [IoTHubClient_LL_Destroy shall do nothing if parameter iotHubClientHandle is NULL.]*/
    if (iotHubClientHandle != NULL)
    {
        PDLIST_ENTRY unsend;
        /*Codes_SRS_IOTHUBCLIENT_LL_02_010: [IoTHubClient_LL_Destroy it shall call the underlaying layer's _Destroy function and shall free the resources allocated by IoTHubClient (if any).] */
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;
        handleData->IoTHubTransport_Destroy(handleData->transportHandle);
        /*if any, remove the items currently not send*/
        while ((unsend = DList_RemoveHeadList(&(handleData->waitingToSend))) != &(handleData->waitingToSend))
        {
            IOTHUB_MESSAGE_LIST* temp = containingRecord(unsend, IOTHUB_MESSAGE_LIST, entry);
            /*Codes_SRS_IOTHUBCLIENT_LL_02_033: [Otherwise, IoTHubClient_LL_Destroy shall complete all the event message callbacks that are in the waitingToSend list with the result IOTHUB_CLIENT_CONFIRMATION_BECAUSE_DESTROY.] */
            if (temp->callback != NULL)
            {
                temp->callback(IOTHUB_CLIENT_CONFIRMATION_BECAUSE_DESTROY, temp->context);
            }
            IoTHubMessage_Destroy(temp->messageHandle);
            free(temp);
        }
        free(handleData);
    }
}
Пример #3
0
void simplesample_http_run(void)
{
    if (serializer_init(NULL) != SERIALIZER_OK)
    {
        LogInfo("Failed on serializer_init\r\n");
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);
        srand((unsigned int)time(NULL));
        int avgWindSpeed = 10.0;

        if (iotHubClientHandle == NULL)
        {
            LogInfo("Failed on IoTHubClient_LL_Create\r\n");
        }
        else
        {
            unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/
            if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
            {
                LogInfo("failure to set option \"MinimumPollingTime\"\r\n");
            }

#ifdef MBED_BUILD_TIMESTAMP
            // For mbed add the certificate information
            if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
            {
                LogInfo("failure to set option \"TrustedCerts\"\r\n");
            }
#endif // MBED_BUILD_TIMESTAMP

            ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
            if (myWeather == NULL)
            {
                LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n");
            }
            else
            {
                if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
                {
                    LogInfo("unable to IoTHubClient_SetMessageCallback\r\n");
                }
                else
                {
                    myWeather->DeviceId = "myFirstDevice";
                    myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
                    {
                        unsigned char* destination;
                        size_t destinationSize;
                        if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != IOT_AGENT_OK)
                        {
                            LogInfo("Failed to serialize\r\n");
                        }
                        else
                        {
                            IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize);
                            if (messageHandle == NULL)
                            {
                                LogInfo("unable to create a new IoTHubMessage\r\n");
                            }
                            else
                            {
                                if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
                                {
                                    LogInfo("failed to hand over the message to IoTHubClient\r\n");
                                }
                                else
                                {
                                    LogInfo("IoTHubClient accepted the message for delivery\r\n");
                                }

                                IoTHubMessage_Destroy(messageHandle);
                            }
                            free(destination);
                        }
                    }

                    /* wait for commands */
                    while (1)
                    {
                        IoTHubClient_LL_DoWork(iotHubClientHandle);
                        ThreadAPI_Sleep(100);
                    }
                }

                DESTROY_MODEL_INSTANCE(myWeather);
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        serializer_deinit();
    }
}
void iothub_messaging_ll_sample_run(void)
{
    xlogging_set_log_function(consolelogger_log);

    if (platform_init() != 0)
    {
        (void)printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        (void)printf("Calling IoTHubServiceClientAuth_CreateFromConnectionString with connection string\n");
        iotHubServiceClientHandle = IoTHubServiceClientAuth_CreateFromConnectionString(connectionString);
        if (iotHubServiceClientHandle == NULL)
        {
            (void)printf("IoTHubServiceClientAuth_CreateFromConnectionString failed\n");
        }
        else
        {
            (void)printf("Service Client Authentication handle has been created successfully\n");

            (void)printf("Creating Messaging...\n");
            iotHubMessagingHandle = IoTHubMessaging_LL_Create(iotHubServiceClientHandle);
            if (iotHubMessagingHandle == NULL)
            {
                (void)printf("IoTHubMessaging_LL_Create failed\n");
            }
            else
            {
                (void)printf("Messaging has been created successfully\n");
                (void)printf("Opening Messaging...\n");

                iotHubMessagingResult = IoTHubMessaging_LL_SetFeedbackMessageCallback(iotHubMessagingHandle, feedbackReceivedCallback, "Context string for feedback");
                if (iotHubMessagingResult != IOTHUB_MESSAGING_OK)
                {
                    (void)printf("IoTHubMessaging_LL_SetFeedbackMessageCallback failed\n");
                }
                else
                {
                    iotHubMessagingResult = IoTHubMessaging_LL_Open(iotHubMessagingHandle, openCompleteCallback, "Context string for open");
                    if (iotHubMessagingResult != IOTHUB_MESSAGING_OK)
                    {
                        (void)printf("IoTHubMessaging_LL_Open failed\n");
                    }
                    else
                    {
                        for (int i = 0; i < MESSAGE_COUNT; i++)
                        {
                            double avgWindSpeed = 10.0;
                            static char msgText[1024];
                            sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":%s,\"windSpeed\":%.2f, \"i\":%d}", deviceId, avgWindSpeed + (rand() % 4 + 2), i);
                            IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText));
                            if (messageHandle == NULL)
                            {
                                (void)printf("IoTHubMessage_CreateFromByteArray failed\n");
                                break;
                            }
                            else
                            {
                                iotHubMessagingResult = IoTHubMessaging_LL_Send(iotHubMessagingHandle, deviceId, messageHandle, sendCompleteCallback, NULL);
                                if (iotHubMessagingResult != IOTHUB_MESSAGING_OK)
                                {
                                    (void)printf("IoTHubMessaging_LL_Send failed\n");
                                }
                                else
                                {
                                    (void)printf("IoTHubMessaging_LL_Send accepted data for transmission to IoT Hub.\r\n");
                                }
                            }
                            IoTHubMessage_Destroy(messageHandle);
                        }

                        feedbackCount = 0;
                        while (feedbackCount < MESSAGE_COUNT)
                        {
                            IoTHubMessaging_LL_DoWork(iotHubMessagingHandle);
                            ThreadAPI_Sleep(1);
                        }

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

                        IoTHubMessaging_LL_Close(iotHubMessagingHandle);
                    }
                }
                (void)printf("Calling IoTHubMessaging_LL_Destroy...\n");
                IoTHubMessaging_LL_Destroy(iotHubMessagingHandle);
            }
            (void)printf("Calling IoTHubServiceClientAuth_Destroy...\n");
            IoTHubServiceClientAuth_Destroy(iotHubServiceClientHandle);
        }
        platform_deinit();
    }
}
Пример #5
0
void qaas_mqtt_run(char param[])
{
    int count = 0;
    char macAdrs[18];
    unsigned char* destination;
    size_t destinationSize;
   

    //getMACAddress(0, macAdrs);
     (void)printf("Mac Adress %s.\r\n", macAdrs); 
    if (platform_init() != 0)
    {
        (void)printf("Failed on serializer_init\r\n");
    }
    else
    {
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            (void)printf("Failed on serializer_init\r\n");
        }
        else
        { 
            IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
            srand((unsigned int)time(NULL));
            int avgPrtclSize = 10;

            if (iotHubClientHandle == NULL)
            {
                (void)printf("Failed on IoTHubClient_LL_Create\r\n");
            }
            else
            { 
                CompostClient1* deviceInfo = CREATE_MODEL_INSTANCE(CompostClient, CompostClient1);
                if (deviceInfo == NULL)
                {
                    (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
                }
                else
                {
                    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, deviceInfo) != IOTHUB_CLIENT_OK)
                    {
                        printf("unable to IoTHubClient_SetMessageCallback\r\n");
                    }
                    else
                    {
                        deviceInfo->DeviceId = "CompClnt01";
                                             

                        /* wait for commands */
                        while (1)
                        {
 
                            deviceInfo->Height = measuredHeight;

                            if(count%50 == 0)
                            {
                            if (SERIALIZE(&destination, &destinationSize, deviceInfo->DeviceId, deviceInfo->Height) != IOT_AGENT_OK)
                            {
                                (void)printf("Failed to serialize\r\n");
                            }
                            else
                            {

                                IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize);
                                if (messageHandle == NULL)
                                {
                                    printf("unable to create a new IoTHubMessage\r\n");
                                }
                                else
                                {
                                    if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
                                    {
                                        printf("failed to hand over the message to IoTHubClient");
                                    }
                                    else
                                    {
                                        printf("IoTHubClient accepted the message for delivery\r\n");
                                    }

                                    IoTHubMessage_Destroy(messageHandle);
                                }
                                free(destination);
                            }
                            }
                            IoTHubClient_LL_DoWork(iotHubClientHandle);
                            count++;
                            //ThreadAPI_Sleep(SAMPLES_COUNT * SAMPLING_TIME * 1000);  // secs
							ThreadAPI_Sleep(100);
						}
                    }

                    DESTROY_MODEL_INSTANCE(deviceInfo);
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_deinit();
    }
}
int main(void)
{
    IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = MQTT_Protocol;

    IOTHUB_MESSAGE_HANDLE message_handle;
    float telemetry_temperature;
    float telemetry_humidity;
    const char* telemetry_scale = "Celcius";
    char telemetry_msg_buffer[80];

    int messagecount = 0;

    printf("\r\nThis sample will send messages continuously and accept C2D messages.\r\nPress Ctrl+C to terminate the sample.\r\n\r\n");

    IOTHUB_DEVICE_CLIENT_HANDLE device_handle;

    // Used to initialize IoTHub SDK subsystem
    (void)IoTHub_Init();

    (void)printf("Creating IoTHub handle\r\n");
    // Create the iothub handle here
    device_handle = IoTHubDeviceClient_CreateFromConnectionString(connectionString, protocol);
    if (device_handle == NULL)
    {
        (void)printf("Failure creating Iothub device.  Hint: Check you connection string.\r\n");
    }
    else
    {
#ifdef SET_TRUSTED_CERT_IN_SAMPLES
        // Setting the Trusted Certificate.  This is only necessary on system with without
        // built in certificate stores.
        (void)IoTHubDeviceClient_SetOption(device_handle, OPTION_TRUSTED_CERT, certificates);
#endif // SET_TRUSTED_CERT_IN_SAMPLES

        int i = MESSAGE_COUNT;

        while(i--)
        {
            // Construct the iothub message
            telemetry_temperature = 20.0f + ((float)rand() / RAND_MAX) * 15.0f;
            telemetry_humidity = 60.0f + ((float)rand() / RAND_MAX) * 20.0f;

            sprintf(telemetry_msg_buffer, "{\"temperature\":%.3f,\"humidity\":%.3f,\"scale\":\"%s\"}", 
                telemetry_temperature, telemetry_humidity, telemetry_scale);

            message_handle = IoTHubMessage_CreateFromString(telemetry_msg_buffer);

            (void)printf("\r\nSending message %d to IoTHub\r\nMessage: %s\r\n", (int)(messagecount + 1), telemetry_msg_buffer);
            IoTHubDeviceClient_SendEventAsync(device_handle, message_handle, send_confirm_callback, NULL);

            // The message is copied to the sdk so the we can destroy it
            IoTHubMessage_Destroy(message_handle);
            messagecount = messagecount + 1;

            ThreadAPI_Sleep(g_interval);
        }

        // Clean up the iothub sdk handle
        IoTHubDeviceClient_Destroy(device_handle);
    }
    // Free all the sdk subsystem
    IoTHub_Deinit();

    return 0;
}
static void RecvMessage(IOTHUB_PROVISIONED_DEVICE* deviceToUse)
{
    // arrange
    IOTHUB_CLIENT_HANDLE iotHubClientHandle;

    IOTHUB_SERVICE_CLIENT_AUTH_HANDLE iotHubServiceClientHandle;
    IOTHUB_MESSAGING_CLIENT_HANDLE iotHubMessagingHandle;
    IOTHUB_MESSAGING_RESULT iotHubMessagingResult;
    IOTHUB_MESSAGE_RESULT iotHubMessageResult;

    EXPECTED_RECEIVE_DATA* receiveUserContext;
    IOTHUB_MESSAGE_HANDLE messageHandle;

    // act
    IoTHub_Init();

    // Create Service Client
    iotHubServiceClientHandle = IoTHubServiceClientAuth_CreateFromConnectionString(IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo1));
    ASSERT_IS_NOT_NULL(iotHubServiceClientHandle, "Could not initialize IoTHubServiceClient to send C2D messages to the device");

    iotHubMessagingHandle = IoTHubMessaging_Create(iotHubServiceClientHandle);
    ASSERT_IS_NOT_NULL(iotHubMessagingHandle, "Could not initialize IoTHubMessaging to send C2D messages to the device");

    iotHubMessagingResult = IoTHubMessaging_Open(iotHubMessagingHandle, openCompleteCallback, (void*)"Context string for open");
    ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessagingResult);

    // Create user context and message
    receiveUserContext = ReceiveUserContext_Create();
    ASSERT_IS_NOT_NULL(receiveUserContext, "Could not create receive user context");

    messageHandle = IoTHubMessage_CreateFromString(MSG_CONTENT1);

    ASSERT_IS_NOT_NULL(messageHandle, "Could not create IoTHubMessage to send C2D messages to the device");

    iotHubMessageResult = IoTHubMessage_SetMessageId(messageHandle, MSG_ID1);
    ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessageResult);

    iotHubMessageResult = IoTHubMessage_SetCorrelationId(messageHandle, MSG_CORRELATION_ID1);
    ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessageResult);

    MAP_HANDLE mapHandle = IoTHubMessage_Properties(messageHandle);
    for (size_t i = 0; i < MSG_PROP_COUNT; i++)
    {
        if (Map_AddOrUpdate(mapHandle, MSG_PROP_KEYS[i], MSG_PROP_VALS[i]) != MAP_OK)
        {
            (void)printf("ERROR: Map_AddOrUpdate failed for property %zu!\r\n", i);
        }
    }

    iotHubMessagingResult = IoTHubMessaging_SendAsync(iotHubMessagingHandle, deviceToUse->deviceId, messageHandle, sendCompleteCallback, receiveUserContext);
    ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessagingResult, "IoTHubMessaging_SendAsync failed, could not send C2D message to the device");
    iotHubClientHandle = IoTHubClient_CreateFromConnectionString(deviceToUse->connectionString, HTTP_Protocol);
    ASSERT_IS_NOT_NULL(iotHubClientHandle, "Failure creating Iothub Client");

    if (deviceToUse->howToCreate == IOTHUB_ACCOUNT_AUTH_X509) {
        IOTHUB_CLIENT_RESULT result;
        result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_CERT, deviceToUse->certificate);
        ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 certificate");
        result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_PRIVATE_KEY, deviceToUse->primaryAuthentication);
        ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 privateKey");
    }

    IOTHUB_CLIENT_RESULT result = IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, receiveUserContext);
    ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Failure setting message callback");

    unsigned int minimumPollingTime = 1; /*because it should not wait*/
    if (IoTHubClient_SetOption(iotHubClientHandle, OPTION_MIN_POLLING_TIME, &minimumPollingTime) != IOTHUB_CLIENT_OK)
    {
        printf("failure to set option \"MinimumPollingTime\"\r\n");
    }

    time_t beginOperation, nowTime;
    beginOperation = time(NULL);
    while (
        (
        (nowTime = time(NULL)),
            (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME) //time box
            )
        )
    {
        if (Lock(receiveUserContext->lock) != LOCK_OK)
        {
            ASSERT_FAIL("unable ot lock");
        }
        else
        {
            if (receiveUserContext->wasFound)
            {
                (void)Unlock(receiveUserContext->lock);
                break;
            }
            (void)Unlock(receiveUserContext->lock);
        }
        ThreadAPI_Sleep(100);
    }

    // assert
    ASSERT_IS_TRUE(receiveUserContext->wasFound, "Failure retrieving message that was sent to IotHub."); // was found is written by the callback...

    // cleanup
    IoTHubMessage_Destroy(messageHandle);
    IoTHubMessaging_Close(iotHubMessagingHandle);
    IoTHubMessaging_Destroy(iotHubMessagingHandle);
    IoTHubServiceClientAuth_Destroy(iotHubServiceClientHandle);

    IoTHubClient_Destroy(iotHubClientHandle);
    ReceiveUserContext_Destroy(receiveUserContext);
}
static void SendEvent(IOTHUB_PROVISIONED_DEVICE* deviceToUse)
{
    // arrange
    IOTHUB_CLIENT_HANDLE iotHubClientHandle;
    IOTHUB_MESSAGE_HANDLE msgHandle;

    EXPECTED_SEND_DATA* sendData = EventData_Create();
    ASSERT_IS_NOT_NULL(sendData, "Failure creating data to be sent");

    // Send the Event
    {
        IOTHUB_CLIENT_RESULT result;
        // Create the IoT Hub Data
        iotHubClientHandle = IoTHubClient_CreateFromConnectionString(deviceToUse->connectionString, HTTP_Protocol);
        ASSERT_IS_NOT_NULL(iotHubClientHandle, "Failure creating IothubClient handle");

        msgHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)sendData->expectedString, strlen(sendData->expectedString));
        ASSERT_IS_NOT_NULL(msgHandle, "Failure to create message handle");

        if (deviceToUse->howToCreate == IOTHUB_ACCOUNT_AUTH_X509) {
            result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_CERT, deviceToUse->certificate);
            ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 certificate");
            result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_PRIVATE_KEY, deviceToUse->primaryAuthentication);
            ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 privateKey");
        }

        // act
        result = IoTHubClient_SendEventAsync(iotHubClientHandle, msgHandle, ReceiveConfirmationCallback, sendData);
        ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Failure calling IoTHubClient_SendEventAsync");
    }

    time_t beginOperation, nowTime;
    beginOperation = time(NULL);
    while (
        (nowTime = time(NULL)),
        (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME) // time box
        )
    {
        if (Lock(sendData->lock) != LOCK_OK)
        {
            ASSERT_FAIL("unable to lock");
        }
        else
        {
            if (sendData->dataWasRecv)
            {
                Unlock(sendData->lock);
                break;
            }
            Unlock(sendData->lock);
        }
        ThreadAPI_Sleep(100);
    }

    if (Lock(sendData->lock) != LOCK_OK)
    {
        ASSERT_FAIL("unable to lock");
    }
    else
    {
        ASSERT_IS_TRUE(sendData->dataWasRecv, "Failure sending data to IotHub"); // was found is written by the callback...
        (void)Unlock(sendData->lock);
    }

    {
        IOTHUB_TEST_HANDLE iotHubTestHandle = IoTHubTest_Initialize(IoTHubAccount_GetEventHubConnectionString(g_iothubAcctInfo1), IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo1), deviceToUse->deviceId, IoTHubAccount_GetEventhubListenName(g_iothubAcctInfo1), IoTHubAccount_GetEventhubAccessKey(g_iothubAcctInfo1), IoTHubAccount_GetSharedAccessSignature(g_iothubAcctInfo1), IoTHubAccount_GetEventhubConsumerGroup(g_iothubAcctInfo1));
        ASSERT_IS_NOT_NULL(iotHubTestHandle);

        IOTHUB_TEST_CLIENT_RESULT result = IoTHubTest_ListenForEventForMaxDrainTime(iotHubTestHandle, IoTHubCallback, IoTHubAccount_GetIoTHubPartitionCount(g_iothubAcctInfo1), sendData);
        ASSERT_ARE_EQUAL(IOTHUB_TEST_CLIENT_RESULT, IOTHUB_TEST_CLIENT_OK, result);

        IoTHubTest_Deinit(iotHubTestHandle);
    }

    // assert
    ASSERT_IS_TRUE(sendData->wasFound, "Failure receiving data from eventhub"); // was found is written by the callback...*/

                                                                                         // cleanup
    IoTHubMessage_Destroy(msgHandle);

    IoTHubClient_Destroy(iotHubClientHandle);
    EventData_Destroy(sendData);
}
void simplesample_mqtt_run(void)
{
    if (serializer_init(NULL) != SERIALIZER_OK)
    {
        (void)printf("Failed on serializer_init\r\n");
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
        srand((unsigned int)time(NULL));
        double avgWindSpeed = 10.0;

        if (iotHubClientHandle == NULL)
        {
            (void)printf("Failed on IoTHubClient_LL_Create\r\n");
        }
        else
        {

            ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
            if (myWeather == NULL)
            {
                (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
            }
            else
            {
                if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
                {
                    printf("unable to IoTHubClient_SetMessageCallback\r\n");
                }
                else
                {
                    myWeather->DeviceId = "myFirstDevice";
                    myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
                    {
                        unsigned char* destination;
                        size_t destinationSize;
                        if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != IOT_AGENT_OK)
                        {
                            (void)printf("Failed to serialize\r\n");
                        }
                        else
                        {
                            IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize);
                            if (messageHandle == NULL)
                            {
                                printf("unable to create a new IoTHubMessage\r\n");
                            }
                            else
                            {
                                if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
                                {
                                    printf("failed to hand over the message to IoTHubClient");
                                }
                                else
                                {
                                    printf("IoTHubClient accepted the message for delivery\r\n");
                                }

                                IoTHubMessage_Destroy(messageHandle);
                            }
                            free(destination);
                        }
                    }

                    /* wait for commands */
                    while (1)
                    {
                        IoTHubClient_LL_DoWork(iotHubClientHandle);
                        ThreadAPI_Sleep(100);
                    }
                }

                DESTROY_MODEL_INSTANCE(myWeather);
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        serializer_deinit();
    }
}
int main(void)
{
    IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol;
    IOTHUB_MESSAGE_HANDLE message_handle;
    size_t messages_sent = 0;
    const char* telemetry_msg = "test_message";

    // Select the Protocol to use with the connection
#ifdef SAMPLE_MQTT
    protocol = MQTT_Protocol;
#endif // SAMPLE_MQTT
#ifdef SAMPLE_MQTT_OVER_WEBSOCKETS
    protocol = MQTT_WebSocket_Protocol;
#endif // SAMPLE_MQTT_OVER_WEBSOCKETS
#ifdef SAMPLE_AMQP
    protocol = AMQP_Protocol;
#endif // SAMPLE_AMQP
#ifdef SAMPLE_AMQP_OVER_WEBSOCKETS
    protocol = AMQP_Protocol_over_WebSocketsTls;
#endif // SAMPLE_AMQP_OVER_WEBSOCKETS
#ifdef SAMPLE_HTTP
    protocol = HTTP_Protocol;
#endif // SAMPLE_HTTP

    // Used to initialize IoTHub SDK subsystem
    (void)IoTHub_Init();

    IOTHUB_DEVICE_CLIENT_LL_HANDLE device_ll_handle;

    (void)printf("Creating IoTHub Device handle\r\n");
    // Create the iothub handle here
    device_ll_handle = IoTHubDeviceClient_LL_CreateFromConnectionString(connectionString, protocol);
    if (device_ll_handle == NULL)
    {
        (void)printf("Failure createing Iothub device.  Hint: Check you connection string.\r\n");
    }
    else
    {
        // Set any option that are neccessary.
        // For available options please see the iothub_sdk_options.md documentation

        bool traceOn = true;
        IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_LOG_TRACE, &traceOn);

#ifdef SET_TRUSTED_CERT_IN_SAMPLES
        // Setting the Trusted Certificate.  This is only necessary on system with without
        // built in certificate stores.
            IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_TRUSTED_CERT, certificates);
#endif // SET_TRUSTED_CERT_IN_SAMPLES

#if defined SAMPLE_MQTT || defined SAMPLE_MQTT_WS
        //Setting the auto URL Encoder (recommended for MQTT). Please use this option unless
        //you are URL Encoding inputs yourself.
        //ONLY valid for use with MQTT
        //bool urlEncodeOn = true;
        //IoTHubDeviceClient_LL_SetOption(iothub_ll_handle, OPTION_AUTO_URL_ENCODE_DECODE, &urlEncodeOn);
#endif

        // Setting connection status callback to get indication of connection to iothub
        (void)IoTHubDeviceClient_LL_SetConnectionStatusCallback(device_ll_handle, connection_status_callback, NULL);

        do
        {
            if (messages_sent < MESSAGE_COUNT)
            {
                // Construct the iothub message from a string or a byte array
                message_handle = IoTHubMessage_CreateFromString(telemetry_msg);
                //message_handle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText)));

                // Set Message property
                /*(void)IoTHubMessage_SetMessageId(message_handle, "MSG_ID");
                (void)IoTHubMessage_SetCorrelationId(message_handle, "CORE_ID");
                (void)IoTHubMessage_SetContentTypeSystemProperty(message_handle, "application%2fjson");
                (void)IoTHubMessage_SetContentEncodingSystemProperty(message_handle, "utf-8");*/

                // Add custom properties to message
                (void)IoTHubMessage_SetProperty(message_handle, "property_key", "property_value");

                (void)printf("Sending message %d to IoTHub\r\n", (int)(messages_sent + 1));
                IoTHubDeviceClient_LL_SendEventAsync(device_ll_handle, message_handle, send_confirm_callback, NULL);

                // The message is copied to the sdk so the we can destroy it
                IoTHubMessage_Destroy(message_handle);

                messages_sent++;
            }
            else if (g_message_count_send_confirmations >= MESSAGE_COUNT)
            {
                // After all messages are all received stop running
                g_continueRunning = false;
            }

            IoTHubDeviceClient_LL_DoWork(device_ll_handle);
            ThreadAPI_Sleep(1);

        } while (g_continueRunning);

        // Clean up the iothub sdk handle
        IoTHubDeviceClient_LL_Destroy(device_ll_handle);
    }
    // Free all the sdk subsystem
    IoTHub_Deinit();

    printf("Press any key to continue");
    getchar();

    return 0;
}
int main(void)
{
    IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol;
    IOTHUB_MESSAGE_HANDLE message_handle;
    const char* telemetry_msg = "test_message";
    char *cert_string = NULL;

    printf("This sample will send %d messages and wait for any C2D messages.\r\nPress the enter key to end the sample\r\n\r\n", MESSAGE_COUNT);

    // Select the Protocol to use with the connection
#ifdef SAMPLE_MQTT
    protocol = MQTT_Protocol;
#endif // SAMPLE_MQTT
#ifdef SAMPLE_MQTT_OVER_WEBSOCKETS
    protocol = MQTT_WebSocket_Protocol;
#endif // SAMPLE_MQTT_OVER_WEBSOCKETS
#ifdef SAMPLE_AMQP
    protocol = AMQP_Protocol;
#endif // SAMPLE_AMQP
#ifdef SAMPLE_AMQP_OVER_WEBSOCKETS
    protocol = AMQP_Protocol_over_WebSocketsTls;
#endif // SAMPLE_AMQP_OVER_WEBSOCKETS
#ifdef SAMPLE_HTTP
    protocol = HTTP_Protocol;
#endif // SAMPLE_HTTP

    IOTHUB_DEVICE_CLIENT_HANDLE device_handle;

    // Used to initialize IoTHub SDK subsystem
    (void)IoTHub_Init();

    (void)printf("Creating IoTHub handle\r\n");
    // Create the iothub handle here
    device_handle = IoTHubDeviceClient_CreateFromConnectionString(connectionString, protocol);
    if (device_handle == NULL)
    {
        (void)printf("Failure creating device client handle.  Hint: Check you connection string.\r\n");
    }
    else
    {
        // Setting message callback to get C2D messages
        (void)IoTHubDeviceClient_SetMessageCallback(device_handle, receive_msg_callback, NULL);
        // Setting connection status callback to get indication of connection to iothub
        (void)IoTHubDeviceClient_SetConnectionStatusCallback(device_handle, connection_status_callback, NULL);

        // Set any option that are necessary.
        // For available options please see the iothub_sdk_options.md documentation

        // Turn tracing on/off
        // bool traceOn = true;
        // (void)IoTHubDeviceClient_SetOption(device_handle, OPTION_LOG_TRACE, &traceOn);

        // Provide the Azure IoT device client with the Edge root
        // X509 CA certificate that was used to setup the Edge runtime
        cert_string = obtain_edge_ca_certificate();
        (void)IoTHubDeviceClient_SetOption(device_handle, OPTION_TRUSTED_CERT, cert_string);

#if defined SAMPLE_MQTT || defined SAMPLE_MQTT_OVER_WEBSOCKETS
        //Setting the auto URL Encoder (recommended for MQTT). Please use this option unless
        //you are URL Encoding inputs yourself.
        //ONLY valid for use with MQTT
        //bool urlEncodeOn = true;
        //(void)IoTHubDeviceClient_SetOption(device_handle, OPTION_AUTO_URL_ENCODE_DECODE, &urlEncodeOn);
#endif

        for (size_t index = 0; index < MESSAGE_COUNT; index++)
        {
            // Construct the iothub message from a string
            message_handle = IoTHubMessage_CreateFromString(telemetry_msg);

            // Set Message property
            (void)IoTHubMessage_SetMessageId(message_handle, "MSG_ID");
            (void)IoTHubMessage_SetCorrelationId(message_handle, "CORE_ID");
            (void)IoTHubMessage_SetContentTypeSystemProperty(message_handle, "application%2fjson");
            (void)IoTHubMessage_SetContentEncodingSystemProperty(message_handle, "utf-8");

            // Add custom properties to message
            (void)IoTHubMessage_SetProperty(message_handle, "property_key", "property_value");

            (void)printf("Sending message %d to Edge Hub\r\n", (int)(index + 1));
            IoTHubDeviceClient_SendEventAsync(device_handle, message_handle, send_confirm_callback, NULL);

            // The message is copied to the sdk so the we can destroy it
            IoTHubMessage_Destroy(message_handle);
        }

        printf("\r\nPress any key to continue\r\n");
        (void)getchar();

        // Clean up the iothub sdk handle
        IoTHubDeviceClient_Destroy(device_handle);

        if (cert_string != NULL)
        {
            free(cert_string);
            cert_string = NULL;
        }
    }
    // Free all the sdk subsystem
    IoTHub_Deinit();

    return 0;
}
void iothub_client_sample_amqp_run(void)
{
    TRANSPORT_HANDLE transport_handle;
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle1;
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle2;

    EVENT_INSTANCE messages_device1[MESSAGE_COUNT];
    EVENT_INSTANCE messages_device2[MESSAGE_COUNT];

    g_continueRunning = true;

    //callbackCounter = 0;
    int receiveContext1 = 0;
    int receiveContext2 = 0;

    (void)printf("Starting the IoTHub client sample AMQP...\r\n");

    if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        if ((transport_handle = IoTHubTransport_Create(AMQP_Protocol, hubName, hubSuffix)) == NULL)
        {
            printf("Failed to creating the protocol handle.\r\n");
        }
        else
        {
            IOTHUB_CLIENT_DEVICE_CONFIG config1;
            config1.deviceId = deviceId1;
            config1.deviceKey = deviceKey1;
            config1.deviceSasToken = NULL;
            config1.protocol = AMQP_Protocol;
            config1.transportHandle = IoTHubTransport_GetLLTransport(transport_handle);

            IOTHUB_CLIENT_DEVICE_CONFIG config2;
            config2.deviceId = deviceId2;
            config2.deviceKey = deviceKey2;
            config2.deviceSasToken = NULL;
            config2.protocol = AMQP_Protocol;
            config2.transportHandle = IoTHubTransport_GetLLTransport(transport_handle);

            if ((iotHubClientHandle1 = IoTHubClient_LL_CreateWithTransport(&config1)) == NULL)
            {
                (void)printf("ERROR: iotHubClientHandle1 is NULL!\r\n");
            }
            else if ((iotHubClientHandle2 = IoTHubClient_LL_CreateWithTransport(&config2)) == NULL)
            {
                (void)printf("ERROR: iotHubClientHandle1 is NULL!\r\n");
            }
            else
            {
                bool traceOn = true;
                IoTHubClient_LL_SetOption(iotHubClientHandle1, OPTION_LOG_TRACE, &traceOn);

    #ifdef SET_TRUSTED_CERT_IN_SAMPLES
                // For mbed add the certificate information
                if (IoTHubClient_LL_SetOption(iotHubClientHandle1, OPTION_TRUSTED_CERT, certificates) != IOTHUB_CLIENT_OK)
                {
                    printf("failure to set option \"TrustedCerts\"\r\n");
                }
    #endif // SET_TRUSTED_CERT_IN_SAMPLES

                if (create_events(messages_device1, config1.deviceId) != 0 || create_events(messages_device2, config2.deviceId) != 0)
                {
                    (void)printf("ERROR: failed creating events for the devices..........FAILED!\r\n");
                }
                /* Setting Message call back, so we can receive Commands. */
                else if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle1, ReceiveMessageCallback, &receiveContext1) != IOTHUB_CLIENT_OK)
                {
                    (void)printf("ERROR: IoTHubClient_SetMessageCallback for device 1..........FAILED!\r\n");
                }
                else if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle2, ReceiveMessageCallback, &receiveContext2) != IOTHUB_CLIENT_OK)
                {
                    (void)printf("ERROR: IoTHubClient_SetMessageCallback for device 2..........FAILED!\r\n");
                }
                else
                {
                    (void)printf("IoTHubClient_SetMessageCallback...successful.\r\n");

                    /* Now that we are ready to receive commands, let's send some messages */
                    size_t iterator = 0;
                    do
                    {
                        if (iterator < MESSAGE_COUNT)
                        {
                            if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle1, messages_device1[iterator].messageHandle, SendConfirmationCallback, &messages_device1[iterator]) != IOTHUB_CLIENT_OK)
                            {
                                (void)printf("ERROR: IoTHubClient_SendEventAsync for device 1..........FAILED!\r\n");
                            }
                            else if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle2, messages_device2[iterator].messageHandle, SendConfirmationCallback, &messages_device2[iterator]) != IOTHUB_CLIENT_OK)
                            {
                                (void)printf("ERROR: IoTHubClient_SendEventAsync for device 2..........FAILED!\r\n");
                            }
                            else
                            {
                                (void)printf("IoTHubClient_SendEventAsync accepted data for transmission to IoT Hub.\r\n");
                            }

                            IoTHubMessage_Destroy(messages_device1[iterator].messageHandle);
                            IoTHubMessage_Destroy(messages_device2[iterator].messageHandle);
                        }

                        IoTHubClient_LL_DoWork(iotHubClientHandle1);
                        IoTHubClient_LL_DoWork(iotHubClientHandle2);
                        ThreadAPI_Sleep(1);

                        iterator++;
                    } while (g_continueRunning);

                    (void)printf("iothub_client_sample_mqtt has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM);
                    for (size_t index = 0; index < DOWORK_LOOP_NUM; index++)
                    {
                        IoTHubClient_LL_DoWork(iotHubClientHandle1);
                        ThreadAPI_Sleep(1);
                    }
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle1);
                IoTHubClient_LL_Destroy(iotHubClientHandle2);
            }
            IoTHubTransport_Destroy(transport_handle);
        }
        platform_deinit();
    }
}
static int sendEventLoop(IOTHUB_CLIENT_HANDLE iotHubClientHandle, LONGHAUL_SEND_TEST_STATE* test_state)
{
	int result = 0;

#ifndef MBED_BUILD_TIMESTAMP
	IOTHUB_TEST_HANDLE iotHubTestHandle;

	if ((iotHubTestHandle = IoTHubTest_Initialize(IoTHubAccount_GetEventHubConnectionString(g_iothubAcctInfo), IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo), IoTHubAccount_GetDeviceId(g_iothubAcctInfo), IoTHubAccount_GetDeviceKey(g_iothubAcctInfo), IoTHubAccount_GetEventhubListenName(g_iothubAcctInfo), IoTHubAccount_GetEventhubAccessKey(g_iothubAcctInfo), IoTHubAccount_GetSharedAccessSignature(g_iothubAcctInfo), IoTHubAccount_GetEventhubConsumerGroup(g_iothubAcctInfo))) == NULL)
	{
		LogError("Failed initializing the Event Hub test client.");
		result = __LINE__;
	}
	else
	{
		initializeSendStatistics(&test_state->statistics);
#endif
		time_t testInitialTime;

		if ((testInitialTime = time(NULL)) == INDEFINITE_TIME)
		{
			LogError("Failed setting the initial time of the test (time(NULL) failed).");
			result = __LINE__;
		}
		else
		{
			time_t loopIterationStartTimeInSeconds, loopIterationEndTimeInSeconds;
			double loopIterationTotalTime;
			time_t testCurrentTime;

			while (result == 0)
			{
				if ((testCurrentTime = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the current time of the test (time(NULL) failed)");
					result = __LINE__;
					break;
				}
				else if (difftime(testCurrentTime, testInitialTime) > test_state->profile->totalRunTimeInSeconds)
				{
					LogInfo("Test run for the expected duration (%d seconds)", test_state->profile->totalRunTimeInSeconds);
					break;
				}

				if ((loopIterationStartTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the initial time of the send/receive loop (time(NULL) failed)");
					result = __LINE__;
					break;
				}

				if (test_state->timeUntilNextSendEventInSeconds <= 0.0)
				{
					EXPECTED_SEND_DATA* sendData;
					IOTHUB_MESSAGE_HANDLE msgHandle;

					if ((sendData = EventData_Create()) == NULL)
					{
						LogError("Failed creating EXPECTED_SEND_DATA.");
						result = __LINE__;
					}
					else
					{
						if ((msgHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)sendData->expectedString, strlen(sendData->expectedString))) == NULL)
						{
							LogError("Failed creating IOTHUB_MESSAGE_HANDLE.");
							result = __LINE__;
						}
						else
						{
							if (IoTHubClient_SendEventAsync(iotHubClientHandle, msgHandle, SendConfirmationCallback, sendData) != IOTHUB_CLIENT_OK)
							{
								LogError("Call to IoTHubClient_SendEventAsync failed.");
								result = __LINE__;
							}
							else
							{
								bool dataWasSent = false;
								time_t beginOperation, nowTime;

								if ((beginOperation = time(NULL)) == INDEFINITE_TIME)
								{
									LogError("Failed setting beginOperation (time(NULL) failed).");
									result = __LINE__;
								}
								else
								{
									do
									{
										if (Lock(sendData->lock) != LOCK_OK)
										{
											LogError("Unable to lock to flag event sent.");
											break;
										}
										else
										{
											if (sendData->dataWasSent)
											{
												dataWasSent = true;
												Unlock(sendData->lock);
												break;
											}
											Unlock(sendData->lock);
										}
										ThreadAPI_Sleep(100);

										if ((nowTime = time(NULL)) == INDEFINITE_TIME)
										{
											LogError("Failed setting nowTime (time(NULL) failed).");
											result = __LINE__;
											break;
										}
									} while (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME);

									if (!dataWasSent)
									{
										LogError("Failure sending data to IotHub");
										result = __LINE__;
									}
									else
									{
#ifdef MBED_BUILD_TIMESTAMP
										if (verifyEventReceivedByHub(sendData) != 0)
										{
											result = __LINE__;
										}
										else
										{
#else
										if (verifyEventReceivedByHub(sendData, iotHubTestHandle) != 0)
										{
											result = __LINE__;
										}
										else
										{
											computeSendStatistics(&test_state->statistics, sendData);
#endif
											test_state->timeUntilNextSendEventInSeconds = test_state->profile->eventFrequencyInSecs[test_state->sendFrequencyIndex];

											if ((test_state->sendFrequencyIndex + 1) < test_state->profile->numberOfEventFrequencyVariations) test_state->sendFrequencyIndex++;
										}
									}
								}
							}

							IoTHubMessage_Destroy(msgHandle);
						}

						EventData_Destroy(sendData);
					}
				}

				ThreadAPI_Sleep(500);

				if ((loopIterationEndTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the end time of the send loop iteration (time(NULL) failed)");
					result = __LINE__;
				}
				else
				{
					loopIterationTotalTime = difftime(loopIterationEndTimeInSeconds, loopIterationStartTimeInSeconds);
					test_state->timeUntilNextSendEventInSeconds -= loopIterationTotalTime;
				}
			} // While loop
		}
			
#ifndef MBED_BUILD_TIMESTAMP
		printSendStatistics(&test_state->statistics);

		IoTHubTest_Deinit(iotHubTestHandle);
	}
#endif

	return result;
}

static int receiveMessageLoop(IOTHUB_CLIENT_HANDLE iotHubClientHandle, LONGHAUL_RECEIVE_TEST_STATE* test_state)
{
	int result = 0;

#ifndef MBED_BUILD_TIMESTAMP
	IOTHUB_TEST_HANDLE iotHubTestHandle;

	if ((iotHubTestHandle = IoTHubTest_Initialize(IoTHubAccount_GetEventHubConnectionString(g_iothubAcctInfo), IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo), IoTHubAccount_GetDeviceId(g_iothubAcctInfo), IoTHubAccount_GetDeviceKey(g_iothubAcctInfo), IoTHubAccount_GetEventhubListenName(g_iothubAcctInfo), IoTHubAccount_GetEventhubAccessKey(g_iothubAcctInfo), IoTHubAccount_GetSharedAccessSignature(g_iothubAcctInfo), IoTHubAccount_GetEventhubConsumerGroup(g_iothubAcctInfo))) == NULL)
	{
		LogError("Failed initializing the Event Hub test client.");
		result = __LINE__;
	}
	else
	{
		initializeReceiveStatistics(&test_state->statistics);
#endif
		time_t testInitialTime;

		if ((testInitialTime = time(NULL)) == INDEFINITE_TIME)
		{
			LogError("Failed setting the initial time of the test (time(NULL) failed).");
			result = __LINE__;
		}
		else
		{
			time_t loopIterationStartTimeInSeconds, loopIterationEndTimeInSeconds;
			double loopIterationTotalTime;
			time_t testCurrentTime;

			while (result == 0)
			{
				if ((testCurrentTime = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the current time of the test (time(NULL) failed)");
					result = __LINE__;
					break;
				}
				else if (difftime(testCurrentTime, testInitialTime) > test_state->profile->totalRunTimeInSeconds)
				{
					LogInfo("Test run for the expected duration (%d seconds)", test_state->profile->totalRunTimeInSeconds);
					break;
				}

				if ((loopIterationStartTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the initial time of the receive loop iteration (time(NULL) failed)");
					result = __LINE__;
					break;
				}

				if (test_state->timeUntilNextReceiveMessageInSeconds <= 0.0)
				{
					EXPECTED_RECEIVE_DATA* receiveData;

					if ((receiveData = MessageData_Create()) == NULL)
					{
						LogError("Failed creating EXPECTED_RECEIVE_DATA.");
						result = __LINE__;
					}
					else
					{
						IOTHUB_TEST_CLIENT_RESULT sendResult;

						if (IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, receiveData) != IOTHUB_CLIENT_OK)
						{
							LogError("Call to IoTHubClient_SetMessageCallback failed.");
							result = __LINE__;
						}
						else if ((sendResult = IoTHubTest_SendMessage(iotHubTestHandle, (const unsigned char*)receiveData->data, receiveData->dataSize)) != IOTHUB_TEST_CLIENT_OK)
						{
							LogError("Call to IoTHubTest_SendMessage failed (%i).", sendResult);
							result = __LINE__;
						}
						else
						{
							if ((receiveData->timeSent = time(NULL)) == INDEFINITE_TIME)
							{
								LogError("Failed setting receiveData->timeSent (time(NULL) failed)");
							}

							time_t beginOperation, nowTime;
							
							if ((beginOperation = time(NULL)) == INDEFINITE_TIME)
							{
								LogError("Failed setting beginOperation (time(NULL) failed).");
								result = __LINE__;
							}
							else
							{
								do
								{
									if (Lock(receiveData->lock) != LOCK_OK)
									{
										LogError("Unable to lock to verify if C2D message has been received.");
										result = __LINE__;
										break;
									}
									else
									{
										if (receiveData->receivedByClient)
										{
											(void)Unlock(receiveData->lock);
											break;
										}
										(void)Unlock(receiveData->lock);
									}
									ThreadAPI_Sleep(100);

									if ((nowTime = time(NULL)) == INDEFINITE_TIME)
									{
										LogError("Failed setting nowTime (time(NULL) failed).");
										result = __LINE__;
										break;
									}
								} while (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME);

								if (result == 0)
								{
									if (!receiveData->receivedByClient)
									{
										LogError("Failure retrieving data from C2D");
										result = __LINE__;
									}
									else
									{
#ifndef MBED_BUILD_TIMESTAMP
										computeReceiveStatistics(&test_state->statistics, receiveData);
#endif
										test_state->timeUntilNextReceiveMessageInSeconds = test_state->profile->messageFrequencyInSecs[test_state->receiveFrequencyIndex];

										if ((test_state->receiveFrequencyIndex + 1) < test_state->profile->numberOfMessageFrequencyVariations) test_state->receiveFrequencyIndex++;
									}
								}
							}
						}

						MessageData_Destroy(receiveData);
					}
				}

				ThreadAPI_Sleep(500);

				if ((loopIterationEndTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the end time of the receive loop iteration (time(NULL) failed)");
					result = __LINE__;
				}
				else
				{
					loopIterationTotalTime = difftime(loopIterationEndTimeInSeconds, loopIterationStartTimeInSeconds);
					test_state->timeUntilNextReceiveMessageInSeconds -= loopIterationTotalTime;
				}
			} // While loop
		}

#ifndef MBED_BUILD_TIMESTAMP
		printReceiveStatistics(&test_state->statistics);

		IoTHubTest_Deinit(iotHubTestHandle);
		}
#endif

	return result;
}
void iothub_messaging_ll_sample_run(void)
{
    xlogging_set_log_function(consolelogger_log);

    if (platform_init() != 0)
    {
        (void)printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        (void)printf("Calling IoTHubServiceClientAuth_CreateFromConnectionString with connection string\n");
        iotHubServiceClientHandle = IoTHubServiceClientAuth_CreateFromConnectionString(connectionString);
        if (iotHubServiceClientHandle == NULL)
        {
            (void)printf("IoTHubServiceClientAuth_CreateFromConnectionString failed\n");
        }
        else
        {
            (void)printf("Service Client Authentication handle has been created successfully\n");

            (void)printf("Creating Messaging...\n");
            iotHubMessagingHandle = IoTHubMessaging_LL_Create(iotHubServiceClientHandle);
            if (iotHubMessagingHandle == NULL)
            {
                (void)printf("IoTHubMessaging_LL_Create failed\n");
            }
            else
            {
                (void)printf("Messaging has been created successfully\n");
                (void)printf("Opening Messaging...\n");

                iotHubMessagingResult = IoTHubMessaging_LL_SetFeedbackMessageCallback(iotHubMessagingHandle, feedbackReceivedCallback, "Context string for feedback");
                if (iotHubMessagingResult != IOTHUB_MESSAGING_OK)
                {
                    (void)printf("IoTHubMessaging_LL_SetFeedbackMessageCallback failed\n");
                }
                else
                {
                    iotHubMessagingResult = IoTHubMessaging_LL_Open(iotHubMessagingHandle, openCompleteCallback, "Context string for open");
                    if (iotHubMessagingResult != IOTHUB_MESSAGING_OK)
                    {
                        (void)printf("IoTHubMessaging_LL_Open failed\n");
                    }
                    else
                    {
                        for (int i = 0; i < MESSAGE_COUNT; i++)
                        {
                            double avgWindSpeed = 10.0;
                            static char msgText[1024];
                            sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":%s,\"windSpeed\":%.2f, \"i\":%d}", deviceId, avgWindSpeed + (rand() % 4 + 2), i);
                            IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText));
                            if (messageHandle == NULL)
                            {
                                (void)printf("IoTHubMessage_CreateFromByteArray failed\n");
                                break;
                            }
                            else
                            {
                                IOTHUB_MESSAGE_RESULT iotHubMessageResult;
                                const char* MSG_ID = "Sample_MessageId";
                                const char* MSG_CORRELATION_ID = "Sample_MessageCorrelationId";
                                const char* MSG_PROP_KEYS[3] = { "Sample_Key1", "Sample_Key2", "Sample_Key3" };
                                const char* MSG_PROP_VALS[3] = { "Sample_Val1", "Sample_Val2", "Sample_Val3" };

                                iotHubMessageResult = IoTHubMessage_SetMessageId(messageHandle, MSG_ID);
                                if (iotHubMessageResult != IOTHUB_MESSAGE_OK)
                                {
                                    (void)printf("IoTHubMessage_SetMessageId failed. Exiting...\n");
                                    IoTHubMessage_Destroy(messageHandle);
                                    break;
                                }
                                else
                                {
                                    iotHubMessageResult = IoTHubMessage_SetCorrelationId(messageHandle, MSG_CORRELATION_ID);
                                    if (iotHubMessageResult != IOTHUB_MESSAGE_OK)
                                    {
                                        (void)printf("IoTHubMessage_SetCorrelationId failed. Exiting...\n");
                                        IoTHubMessage_Destroy(messageHandle);
                                        break;
                                    }
                                    else
                                    {
                                        MAP_HANDLE mapHandle = IoTHubMessage_Properties(messageHandle);
                                        for (size_t j = 0; j < 3; j++)
                                        {
                                            if (Map_AddOrUpdate(mapHandle, MSG_PROP_KEYS[j], MSG_PROP_VALS[j]) != MAP_OK)
                                            {
                                                (void)printf("ERROR: Map_AddOrUpdate failed for property %zu!\r\n", j);
                                            }
                                        }

                                        iotHubMessagingResult = IoTHubMessaging_LL_Send(iotHubMessagingHandle, deviceId, messageHandle, sendCompleteCallback, NULL);
                                        if (iotHubMessagingResult != IOTHUB_MESSAGING_OK)
                                        {
                                            (void)printf("IoTHubMessaging_LL_Send failed\n");
                                        }
                                        else
                                        {
                                            (void)printf("IoTHubMessaging_LL_Send accepted data for transmission to IoT Hub.\r\n");
                                        }
                                    }
                                }
                            }
                            IoTHubMessage_Destroy(messageHandle);
                        }

                        feedbackCount = 0;
                        while (feedbackCount < MESSAGE_COUNT)
                        {
                            IoTHubMessaging_LL_DoWork(iotHubMessagingHandle);
                            ThreadAPI_Sleep(1);
                        }

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

                        IoTHubMessaging_LL_Close(iotHubMessagingHandle);
                    }
                }
                (void)printf("Calling IoTHubMessaging_LL_Destroy...\n");
                IoTHubMessaging_LL_Destroy(iotHubMessagingHandle);
            }
            (void)printf("Calling IoTHubServiceClientAuth_Destroy...\n");
            IoTHubServiceClientAuth_Destroy(iotHubServiceClientHandle);
        }
        platform_deinit();
    }
}
int main(void)
{
    TRANSPORT_HANDLE transport_handle;
    IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol;
    IOTHUB_DEVICE_CLIENT_LL_HANDLE device_ll_handle1;
    IOTHUB_DEVICE_CLIENT_LL_HANDLE device_ll_handle2;

#ifdef SAMPLE_AMQP
    protocol = AMQP_Protocol;
#endif // SAMPLE_AMQP
#ifdef SAMPLE_AMQP_OVER_WEBSOCKETS
    protocol = AMQP_Protocol_over_WebSocketsTls;
#endif // SAMPLE_AMQP_OVER_WEBSOCKETS
#ifdef SAMPLE_HTTP
    protocol = HTTP_Protocol;
#endif // SAMPLE_HTTP

    g_continueRunning = true;

    //callbackCounter = 0;
    int receiveContext1 = 0;
    int receiveContext2 = 0;

    (void)printf("Starting the IoTHub client shared sample.  Send `quit` message to either device to close...\r\n");

    // Used to initialize IoTHub SDK subsystem
    (void)IoTHub_Init();

    if ((transport_handle = IoTHubTransport_Create(protocol, hubName, hubSuffix)) == NULL)
    {
        printf("Failed to creating the protocol handle.\r\n");
    }
    else
    {
        EVENT_INSTANCE device1_event;
        EVENT_INSTANCE device2_event;

        device1_event.deviceId = deviceId1;

        IOTHUB_CLIENT_DEVICE_CONFIG config1 = { 0 };
        config1.deviceId = deviceId1;
        config1.deviceKey = deviceKey1;
        config1.deviceSasToken = NULL;
        config1.protocol = protocol;
        config1.transportHandle = IoTHubTransport_GetLLTransport(transport_handle);

        device2_event.deviceId = deviceId2;

        IOTHUB_CLIENT_DEVICE_CONFIG config2 = { 0 };
        config2.deviceId = deviceId2;
        config2.deviceKey = deviceKey2;
        config2.deviceSasToken = NULL;
        config2.protocol = protocol;
        config2.transportHandle = IoTHubTransport_GetLLTransport(transport_handle);

        if ((device_ll_handle1 = IoTHubDeviceClient_LL_CreateWithTransport(&config1)) == NULL)
        {
            (void)printf("ERROR: iotHubClientHandle1 is NULL!\r\n");
        }
        else if ((device_ll_handle2 = IoTHubDeviceClient_LL_CreateWithTransport(&config2)) == NULL)
        {
            (void)printf("ERROR: iotHubClientHandle1 is NULL!\r\n");
        }
        else
        {
            // Set any option that are neccessary.
            // For available options please see the iothub_sdk_options.md documentation
            //bool traceOn = true;
            //IoTHubDeviceClient_LL_SetOption(device_ll_handle1, OPTION_LOG_TRACE, &traceOn);
            //IoTHubDeviceClient_LL_SetOption(device_ll_handle2, OPTION_LOG_TRACE, &traceOn);
#ifdef SET_TRUSTED_CERT_IN_SAMPLES
            // Setting the Trusted Certificate.  This is only necessary on system without
            // built in certificate stores.
            IoTHubDeviceClient_LL_SetOption(device_ll_handle1, OPTION_TRUSTED_CERT, certificates);
            IoTHubDeviceClient_LL_SetOption(device_ll_handle2, OPTION_TRUSTED_CERT, certificates);
#endif // SET_TRUSTED_CERT_IN_SAMPLES

#ifdef SAMPLE_HTTP
            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;
            IoTHubDeviceClient_LL_SetOption(device_ll_handle1, OPTION_MIN_POLLING_TIME, &minimumPollingTime);
            IoTHubDeviceClient_LL_SetOption(device_ll_handle1, OPTION_HTTP_TIMEOUT, &timeout);
            IoTHubDeviceClient_LL_SetOption(device_ll_handle2, OPTION_MIN_POLLING_TIME, &minimumPollingTime);
            IoTHubDeviceClient_LL_SetOption(device_ll_handle2, OPTION_HTTP_TIMEOUT, &timeout);
#endif // SAMPLE_HTTP

            /* Setting Message call back, so we can receive Commands. */
            (void)IoTHubDeviceClient_LL_SetMessageCallback(device_ll_handle1, ReceiveMessageCallback, &receiveContext1);
            (void)IoTHubDeviceClient_LL_SetMessageCallback(device_ll_handle2, ReceiveMessageCallback, &receiveContext2);

            /* Now that we are ready to receive commands, let's send some messages */
            size_t messages_sent = 0;
            IOTHUB_MESSAGE_HANDLE message_handle;
            do
            {
                if (messages_sent < MESSAGE_COUNT)
                {
                    // Create the event hub message
                    message_handle = create_events(&device1_event);
                    (void)IoTHubDeviceClient_LL_SendEventAsync(device_ll_handle1, message_handle, SendConfirmationCallback, &device1_event);
                    // The message is copied to the sdk so the we can destroy it
                    IoTHubMessage_Destroy(message_handle);

                    message_handle = create_events(&device2_event);
                    (void)IoTHubDeviceClient_LL_SendEventAsync(device_ll_handle2, message_handle, SendConfirmationCallback, &device2_event);
                    // The message is copied to the sdk so the we can destroy it
                    IoTHubMessage_Destroy(message_handle);

                    messages_sent++;
                }

                IoTHubDeviceClient_LL_DoWork(device_ll_handle1);
                IoTHubDeviceClient_LL_DoWork(device_ll_handle2);
                ThreadAPI_Sleep(1);
            } while (g_continueRunning);

            (void)printf("client_amqp_shared_sample has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM);
            for (size_t index = 0; index < DOWORK_LOOP_NUM; index++)
            {
                IoTHubDeviceClient_LL_DoWork(device_ll_handle1);
                IoTHubDeviceClient_LL_DoWork(device_ll_handle2);
                ThreadAPI_Sleep(1);
            }

            // Clean up the iothub sdk handle
            IoTHubDeviceClient_LL_Destroy(device_ll_handle1);
            IoTHubDeviceClient_LL_Destroy(device_ll_handle2);
        }
        IoTHubTransport_Destroy(transport_handle);
        // Free all the sdk subsystem
        IoTHub_Deinit();
    }
    return 0;
}
Пример #16
0
void simplesample_http_run(void)
{
    if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            (void)printf("Failed on serializer_init\r\n");
        }
        else
        {
            IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);
            int avgWindSpeed = 10;

            srand((unsigned int)time(NULL));

            if (iotHubClientHandle == NULL)
            {
                (void)printf("Failed on IoTHubClient_LL_Create\r\n");
            }
            else
            {
                // 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;
                ContosoAnemometer* myWeather;

                if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
                {
                    printf("failure to set option \"MinimumPollingTime\"\r\n");
                }

#ifdef MBED_BUILD_TIMESTAMP
                // For mbed add the certificate information
                if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
                {
                    (void)printf("failure to set option \"TrustedCerts\"\r\n");
                }
#endif // MBED_BUILD_TIMESTAMP

                myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
                if (myWeather == NULL)
                {
                    (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
                }
                else
                {
                    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
                    {
                        printf("unable to IoTHubClient_SetMessageCallback\r\n");
                    }
                    else
                    {
                        myWeather->DeviceId = "myFirstDevice";
                        myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
                        {
                            unsigned char* destination;
                            size_t destinationSize;
                            if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != CODEFIRST_OK)
                            {
                                (void)printf("Failed to serialize\r\n");
                            }
                            else
                            {
                                IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize);
                                if (messageHandle == NULL)
                                {
                                    printf("unable to create a new IoTHubMessage\r\n");
                                }
                                else
                                {
                                    if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
                                    {
                                        printf("failed to hand over the message to IoTHubClient");
                                    }
                                    else
                                    {
                                        printf("IoTHubClient accepted the message for delivery\r\n");
                                    }

                                    IoTHubMessage_Destroy(messageHandle);
                                }
                                free(destination);
                            }
                        }

                        /* wait for commands */
                        while (1)
                        {
                            IoTHubClient_LL_DoWork(iotHubClientHandle);
                            ThreadAPI_Sleep(100);
                        }
                    }

                    DESTROY_MODEL_INSTANCE(myWeather);
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_deinit();
    }
}