static void remote_monitoring_run(void)
{
    if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            printf("Failed on serializer_init\r\n");
        }
        else
        {
            IOTHUB_CLIENT_CONFIG config;
            IOTHUB_CLIENT_HANDLE iotHubClientHandle;

            config.deviceSasToken = NULL;
            config.deviceId = deviceId;
            config.deviceKey = deviceKey;
            config.iotHubName = hubName;
            config.iotHubSuffix = hubSuffix;
#ifndef WINCE
            config.protocol = AMQP_Protocol;
#else
            config.protocol = HTTP_Protocol;
#endif
            iotHubClientHandle = IoTHubClient_Create(&config);
            if (iotHubClientHandle == NULL)
            {
                (void)printf("Failed on IoTHubClient_CreateFromConnectionString\r\n");
            }
            else
            {
#ifdef MBED_BUILD_TIMESTAMP
                // For mbed add the certificate information
                if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
                {
                    printf("failure to set option \"TrustedCerts\"\r\n");
                }
#endif // MBED_BUILD_TIMESTAMP

                Thermostat* thermostat = CREATE_MODEL_INSTANCE(Contoso, Thermostat);
                if (thermostat == NULL)
                {
                    (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
                }
                else
                {
                    STRING_HANDLE commandsMetadata;

                    if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, thermostat) != IOTHUB_CLIENT_OK)
                    {
                        printf("unable to IoTHubClient_SetMessageCallback\r\n");
                    }
                    else
                    {

                        /* send the device info upon startup so that the cloud app knows
                        what commands are available and the fact that the device is up */
                        thermostat->ObjectType = "DeviceInfo";
                        thermostat->IsSimulatedDevice = false;
                        thermostat->Version = "1.0";
                        thermostat->DeviceProperties.HubEnabledState = true;
                        thermostat->DeviceProperties.DeviceID = (char*)deviceId;

                        commandsMetadata = STRING_new();
                        if (commandsMetadata == NULL)
                        {
                            (void)printf("Failed on creating string for commands metadata\r\n");
                        }
                        else
                        {
                            /* Serialize the commands metadata as a JSON string before sending */
                            if (SchemaSerializer_SerializeCommandMetadata(GET_MODEL_HANDLE(Contoso, Thermostat), commandsMetadata) != SCHEMA_SERIALIZER_OK)
                            {
                                (void)printf("Failed serializing commands metadata\r\n");
                            }
                            else
                            {
                                unsigned char* buffer;
                                size_t bufferSize;
                                thermostat->Commands = (char*)STRING_c_str(commandsMetadata);

                                /* Here is the actual send of the Device Info */
                                if (SERIALIZE(&buffer, &bufferSize, thermostat->ObjectType, thermostat->Version, thermostat->IsSimulatedDevice, thermostat->DeviceProperties, thermostat->Commands) != IOT_AGENT_OK)
                                {
                                    (void)printf("Failed serializing\r\n");
                                }
                                else
                                {
                                    sendMessage(iotHubClientHandle, buffer, bufferSize);
                                }

                            }

                            STRING_delete(commandsMetadata);
                        }

                        thermostat->Temperature = 50;
                        thermostat->ExternalTemperature = 55;
                        thermostat->Humidity = 50;
                        thermostat->DeviceId = (char*)deviceId;

                        while (1)
                        {
                            unsigned char*buffer;
                            size_t bufferSize;

                            float tempC = -300.0;
                            float pressurePa = -300;
                            float humidityPct = -300;

                            int sensorResult = bme280_read_sensors(&tempC, &pressurePa, &humidityPct);

                            if (sensorResult == 1)
                            {
                                thermostat->Temperature = tempC;
                                thermostat->Humidity = humidityPct;
                                printf("Humidity = %.1f%% Temperature = %.1f*C \n",
                                    humidityPct, tempC);
                                pinMode(Grn_led_pin, OUTPUT);
                            }
                            else
                            {
                                thermostat->Temperature = 404.0;
                                thermostat->Humidity = 404.0;
                                printf("Unable to read BME280 on pin %i\n", Spi_channel);
                                pinMode(Red_led_pin, OUTPUT);
                            }

                            (void)printf("Sending sensor value Temperature = %.1f*C, Humidity = %.1f%%\r\n", thermostat->Temperature, thermostat->Humidity);

                            if (SERIALIZE(&buffer, &bufferSize, thermostat->DeviceId, thermostat->Temperature, thermostat->Humidity, thermostat->ExternalTemperature) != IOT_AGENT_OK)
                            {
                                (void)printf("Failed sending sensor value\r\n");
                            }
                            else
                            {
                                sendMessage(iotHubClientHandle, buffer, bufferSize);
                            }

                            ThreadAPI_Sleep(1000);
                        }
                    }
                    close_lockfile(Lock_fd);
                    DESTROY_MODEL_INSTANCE(thermostat);
                }
                IoTHubClient_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_deinit();
    }
}
예제 #2
0
void simplesample_amqp_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
        {
            /* Setup IoTHub client configuration */
            IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, AMQP_Protocol);
            srand((unsigned int)time(NULL));
            int avgWindSpeed = 10;

            // Turn on Log 
            bool trace = true;
            (void)IoTHubClient_SetOption(iotHubClientHandle, "logtrace", &trace);

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

                ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
                if (myWeather == NULL)
                {
                    (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
                }
                else
                {
                    unsigned char* destination;
                    size_t destinationSize;

                    if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
                    {
                        printf("unable to IoTHubClient_SetMessageCallback\r\n");
                    }
                    else
                    {
                        myWeather->DeviceId = "myFirstDevice";
                        myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);

                        if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != CODEFIRST_OK)
                        {
                            (void)printf("Failed to serialize\r\n");
                        }
                        else
                        {
                            sendMessage(iotHubClientHandle, destination, destinationSize);
                        }

                        /* wait for commands */
                        (void)getchar();
                    }
                    DESTROY_MODEL_INSTANCE(myWeather);
                }
                IoTHubClient_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_deinit();
    }
}
예제 #3
0
void remote_monitoring_run(void)
{
    if (serializer_init(NULL) != SERIALIZER_OK)
    {
        printf("Failed on serializer_init\r\n");
    }
    else
    {
		IOTHUB_CLIENT_CONFIG config;

		config.deviceId = deviceId;
		config.deviceKey = deviceKey;
		config.iotHubName = hubName;
		config.iotHubSuffix = hubSuffix;
		config.protocol = AMQP_Protocol;

		IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_Create(&config);
        if (iotHubClientHandle == NULL)
        {
            (void)printf("Failed on IoTHubClient_CreateFromConnectionString\r\n");
        }
        else
        {
            unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/
            if (IoTHubClient_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_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
            {
                printf("failure to set option \"TrustedCerts\"\r\n");
            }
#endif // MBED_BUILD_TIMESTAMP

            Thermostat* thermostat = CREATE_MODEL_INSTANCE(Contoso, Thermostat);
            if (thermostat == NULL)
            {
                (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
            }
            else
            {
                STRING_HANDLE commandsMetadata;

                if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, thermostat) != IOTHUB_CLIENT_OK)
                {
                    printf("unable to IoTHubClient_SetMessageCallback\r\n");
                }
                else
                {

                    /* send the device info upon startup so that the cloud app knows
                    what commands are available and the fact that the device is up */
                    thermostat->ObjectType = "DeviceInfo";
					thermostat->IsSimulatedDevice = false;
					thermostat->Version = "1.0";
					thermostat->DeviceProperties.HubEnabledState = true;
                    thermostat->DeviceProperties.DeviceID = (char*)deviceId;

                    commandsMetadata = STRING_new();
                    if (commandsMetadata == NULL)
                    {
                        (void)printf("Failed on creating string for commands metadata\r\n");
                    }
                    else
                    {
                        /* Serialize the commands metadata as a JSON string before sending */
                        if (SchemaSerializer_SerializeCommandMetadata(GET_MODEL_HANDLE(Contoso, Thermostat), commandsMetadata) != SCHEMA_SERIALIZER_OK)
                        {
                            (void)printf("Failed serializing commands metadata\r\n");
                        }
                        else
                        {
                            unsigned char* buffer;
                            size_t bufferSize;
                            thermostat->Commands = (char*)STRING_c_str(commandsMetadata);

                            /* Here is the actual send of the Device Info */
                            if (SERIALIZE(&buffer, &bufferSize, thermostat->ObjectType, thermostat->Version, thermostat->IsSimulatedDevice, thermostat->DeviceProperties, thermostat->Commands) != IOT_AGENT_OK)
                            {
                                (void)printf("Failed serializing\r\n");
                            }
                            else
                            {
                                sendMessage(iotHubClientHandle, buffer, bufferSize);
                            }

                        }

                        STRING_delete(commandsMetadata);
                    }

					thermostat->Temperature = 50.0;
					thermostat->Humidity = 50.0;
					thermostat->DeviceId = (char*)deviceId;

                    while (1)
                    {
                        unsigned char*buffer;
                        size_t bufferSize;

						(void)printf("Sending sensor value Temperature = %02f, Humidity = %02f\r\n", thermostat->Temperature, thermostat->Humidity);

                        if (SERIALIZE(&buffer, &bufferSize, thermostat->Temperature, thermostat->Humidity, thermostat->DeviceId) != IOT_AGENT_OK)
                        {
                            (void)printf("Failed sending sensor value\r\n");
                        }
                        else
                        {
                            sendMessage(iotHubClientHandle, buffer, bufferSize);
                        }

                        ThreadAPI_Sleep(1000);
                    }
                }

                DESTROY_MODEL_INSTANCE(thermostat);
            }
            IoTHubClient_Destroy(iotHubClientHandle);
        }
        serializer_deinit();
    }
}
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);
}
void iothub_client_sample_amqp_websockets_run(void)
{
    IOTHUB_CLIENT_HANDLE iotHubClientHandle;

    EVENT_INSTANCE messages[MESSAGE_COUNT];

    srand((unsigned int)time(NULL));
    double avgWindSpeed = 10.0;

    callbackCounter = 0;
    int receiveContext = 0;

    (void)printf("Starting the IoTHub client sample AMQP over WebSockets...\r\n");
	
	if (platform_init() != 0)
	{
		(void)printf("ERROR: failed initializing the platform.\r\n");
	}
    else if ((iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, AMQP_Protocol_over_WebSocketsTls)) == NULL)
    {
        (void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
        platform_deinit();
    }
    else
    {
#ifdef MBED_BUILD_TIMESTAMP
        // For mbed add the certificate information
        if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
        {
            printf("failure to set option \"TrustedCerts\"\r\n");
        }
#endif // MBED_BUILD_TIMESTAMP

        /* 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");
        }
        else
        {
            (void)printf("IoTHubClient_SetMessageCallback...successful.\r\n");

            /* Now that we are ready to receive commands, let's send some messages */
            for (size_t i = 0; i < MESSAGE_COUNT; i++)
            {
                sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":\"myFirstDevice\",\"windSpeed\":%.2f}", avgWindSpeed+(rand()%4+2) );
                if ((messages[i].messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText))) == NULL)
                {
                    (void)printf("ERROR: iotHubMessageHandle is NULL!\r\n");
                }
                else
                {
                    messages[i].messageTrackingId = i;
                    
                    MAP_HANDLE propMap = IoTHubMessage_Properties(messages[i].messageHandle);
                    sprintf_s(propText, sizeof(propText), "PropMsg_%d", i);
                    if (Map_AddOrUpdate(propMap, "PropName", propText) != MAP_OK)
                    {
                        (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
                    }

                    if (IoTHubClient_SendEventAsync(iotHubClientHandle, messages[i].messageHandle, SendConfirmationCallback, &messages[i]) != 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();
        }
        
        IoTHubClient_Destroy(iotHubClientHandle);
        platform_deinit();
    }
}
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);
}
static int iothub_client_sample_mqtt_dm_run(const char *connectionString, bool traceOn)
{
    LogInfo("Initialize Platform");

    int retValue;
    if (platform_init() != 0)
    {
        LogError("Failed to initialize the platform.");
        retValue = -4;
    }
    else
    {
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            LogError("Failed in serializer_init.");
            retValue = -5;
        }
        else
        {
            LogInfo("Instantiate the device.");
            thingie_t *iot_device = CREATE_MODEL_INSTANCE(Contoso, thingie_t);
            if (iot_device == NULL)
            {
                LogError("Failed on CREATE_MODEL_INSTANCE.");
                retValue = -6;
            }

            else
            {
                LogInfo("Initialize From Connection String.");
                IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, MQTT_Protocol);
                if (iotHubClientHandle == NULL)
                {
                    LogError("iotHubClientHandle is NULL!");
                    retValue = -7;
                }
                else
                {
                    LogInfo("Device successfully connected.");
                    if (IoTHubClient_SetOption(iotHubClientHandle, "logtrace", &traceOn) != IOTHUB_CLIENT_OK)
                    {
                        LogError("failed to set logtrace option");
                    }

                    PHYSICAL_DEVICE *physical_device = physical_device_new(iot_device);
                    if (physical_device == NULL)
                    {
                        LogError("failed to make an iot device callback structure");
                        retValue = -8;
                    }
                    else
                    {
                        if (IoTHubClient_SetDeviceMethodCallback(iotHubClientHandle, DeviceMethodCallback, physical_device) != IOTHUB_CLIENT_OK)
                        {
                            LogError("failed to associate a callback for device methods");
                            retValue = -9;
                        }
                        else
                        {
                            bool keepRunning = send_reported(physical_device, iotHubClientHandle);
                            if (!keepRunning)
                            {
                                LogError("Failed to send initia device reported");
                                retValue = -10;
                            }
                            else
                            {
                                FIRMWARE_UPDATE_STATUS oldStatus = get_physical_device_fwupdate_status(physical_device);
                                while (keepRunning)
                                {
                                    FIRMWARE_UPDATE_STATUS newStatus = get_physical_device_fwupdate_status(physical_device);

                                    /* send reported only if the status changes */
                                    if (newStatus != oldStatus)
                                    {
                                        oldStatus = newStatus;
                                        keepRunning = send_reported(physical_device, iotHubClientHandle);
                                    }
                                    ThreadAPI_Sleep(1000);
                                }
                                retValue = 0;
                            }
                        }
                        physical_device_delete(physical_device);
                    }
                    IoTHubClient_Destroy(iotHubClientHandle);
                }
                DESTROY_MODEL_INSTANCE(iot_device);
            }
            serializer_deinit();
        }
        platform_deinit();
    }

    return retValue;
}
void device_twin_simple_sample_run(void)
{
    /*prepare the platform*/
    if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\n");
    }
    else
    {
        if (SERIALIZER_REGISTER_NAMESPACE(Contoso) == NULL)
        {
            LogError("unable to SERIALIZER_REGISTER_NAMESPACE");
        }
        else
        {
            /*create an IoTHub client*/
            IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, MQTT_Protocol); // Change to AMQP_Procotol if desired.
            if (iotHubClientHandle == NULL)
            {
                printf("Failure creating IoTHubClient handle");
            }
            else
            {
                // Turn on Log
                bool trace = true;
                (void)IoTHubClient_SetOption(iotHubClientHandle, "logtrace", &trace);

                Car* car = IoTHubDeviceTwin_CreateCar(iotHubClientHandle);
                if (car == NULL)
                {
                    printf("Failure in IoTHubDeviceTwin_CreateCar");
                }
                else
                {
                    /*setting values for reported properties*/
                    car->lastOilChangeDate = "2016";
                    car->maker.makerName = "Fabrikam";
                    car->maker.style = "sedan";
                    car->maker.year = 2014;
                    car->state.reported_maxSpeed = 100;
                    car->state.softwareVersion = 1;
                    car->state.vanityPlate = "1I1";

                    // IoTHubDeviceTwin_SendReportedStateCar sends the reported status back to IoT Hub
                    // to the associated device twin.
                    //
                    // IoTHubDeviceTwin_SendReportedStateCar is an auto-generated function, created
                    // via the macro DECLARE_DEVICETWIN_MODEL(Car,...).  It resolves to the underlying function
                    // IoTHubDeviceTwin_SendReportedState_Impl().
                    if (IoTHubDeviceTwin_SendReportedStateCar(car, deviceTwinReportStateCallback, NULL) != IOTHUB_CLIENT_OK)
                    {
                        (void)printf("Failed sending serialized reported state\n");
                    }
                    else
                    {
                        printf("Reported state will be send to IoTHub\n");

                        // Comment out the following three lines if you want to enable callback(s) for updates of the existing model (example: onDesiredMaxSpeed)
                        if (IoTHubClient_SetDeviceTwinCallback(iotHubClientHandle, deviceTwinGetStateCallback, NULL) != IOTHUB_CLIENT_OK)
                        {
                            (void)printf("Failed subscribing for device twin properties\n");
                        }
                    }

                    printf("press ENTER to end the sample\n");
                    (void)getchar();

                }
                IoTHubDeviceTwin_DestroyCar(car);
            }
            IoTHubClient_Destroy(iotHubClientHandle);
        }
    }
    platform_deinit();
}
void iothub_client_sample_http_run(void)
{
    TRANSPORT_HANDLE httpTransport;
    IOTHUB_CLIENT_HANDLE iothubClient1;
    IOTHUB_CLIENT_HANDLE iothubClient2;


    EVENT_INSTANCE messages1[MESSAGE_COUNT];
    EVENT_INSTANCE messages2[MESSAGE_COUNT];
    double avgWindSpeed = 10.0;
    double minTemperature = 20.0;
    double minHumidity = 60.0;
    double temperature = 0;
    double humidity = 0;
    int receiveContext1 = 0;
    int receiveContext2 = 0;

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

    callbackCounter = 0;

    if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        (void)printf("Starting the IoTHub client sample HTTP with Shared connection...\r\n");


        if ((httpTransport = IoTHubTransport_Create(HTTP_Protocol, hubName, hubSuffix)) == NULL)
        {
            (void)printf("ERROR: httpTransport is NULL\r\n");
        }
        else
        {
            IOTHUB_CLIENT_CONFIG config1;
            config1.deviceId = deviceId1;
            config1.deviceKey = deviceKey1;
            config1.protocol = HTTP_Protocol;
            config1.iotHubName = NULL;
            config1.iotHubSuffix = NULL;
            config1.deviceSasToken = NULL;
            if ((iothubClient1 = IoTHubClient_CreateWithTransport(httpTransport, &config1)) == NULL)
            {
                (void)printf("ERROR: 1st device handle is NULL\r\n");
            }
            else
            {
                IOTHUB_CLIENT_CONFIG config2;
                config2.deviceId = deviceId2;
                config2.deviceKey = deviceKey2;
                config2.protocol = HTTP_Protocol;
                config2.iotHubName = NULL;
                config2.iotHubSuffix = NULL;
                config2.deviceSasToken = NULL;
                if ((iothubClient2 = IoTHubClient_CreateWithTransport(httpTransport, &config2)) == NULL)
                {
                    (void)printf("ERROR: 2nd device handle is NULL\r\n");
                }
                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;
                    iothub_client_sample_http_setoptions(iothubClient1, timeout, minimumPollingTime);
                    iothub_client_sample_http_setoptions(iothubClient2, timeout, minimumPollingTime);

                    // Setting message callbacks so we can receive commands
                    if (IoTHubClient_SetMessageCallback(iothubClient1, ReceiveMessageCallback, &receiveContext1) != IOTHUB_CLIENT_OK)
                    {
                        (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback 1st device..........FAILED!\r\n");
                    }
                    else
                    {
                        if (IoTHubClient_SetMessageCallback(iothubClient2, ReceiveMessageCallback, &receiveContext2) != IOTHUB_CLIENT_OK)
                        {
                            (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback 2nd device..........FAILED!\r\n");
                        }
                        else
                        {
                            // Now that we are ready to receive commands, let's send some messages
                            int i;

                            (void)printf("IoTHubClient_LL_SetMessageCallback...successful.\r\n");

                            for (i = 0; i < MESSAGE_COUNT; i++)
                            {
                                temperature = minTemperature + (rand() % 10);
                                humidity = minHumidity +  (rand() % 20);

                                sprintf_s(msgText, sizeof(msgText), "{\"deviceId\": \"%s\",\"windSpeed\":%.2f,\"temperature\":%.2f,\"humidity\":%.2f}", deviceId1, avgWindSpeed + (rand() % 4 + 2), temperature, humidity);
                                iothub_client_sample_http_send_one_msg(iothubClient1, &messages1[i], i);

                                temperature = minTemperature + (rand() % 10);
                                humidity = minHumidity +  (rand() % 20);

                                sprintf_s(msgText, sizeof(msgText), "{\"deviceId\": \"%s\",\"windSpeed\":%.2f,\"temperature\":%.2f,\"humidity\":%.2f}", deviceId2, avgWindSpeed + (rand() % 4 + 2), temperature, humidity);
                                iothub_client_sample_http_send_one_msg(iothubClient2, &messages2[i], i);
                            }
                            // Wait for any incoming messages
                            (void)printf("Press any key to exit the application. \r\n");
                            (void)getchar();
                        }
                    }
                    IoTHubClient_Destroy(iothubClient2);
                }
                IoTHubClient_Destroy(iothubClient1);
            }
            IoTHubTransport_Destroy(httpTransport);
        }
        platform_deinit();
    }
}
void simplesample_amqp_run(void)
{

	if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\r\n");
        exit(1);
    }
    
	if (serializer_init(NULL) != SERIALIZER_OK)
	{
		(void)printf("Failed on serializer_init\r\n");
	}
	else
	{
		/* Setup IoTHub client configuration */
		IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, AMQP_Protocol);
		srand((unsigned int)time(NULL));
		int avgMTemperature = 10;

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

			ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
			if (myWeather == NULL)
			{
				(void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
			}
			else
			{
				unsigned char* destination;
				size_t destinationSize;

				if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
				{
					printf("unable to IoTHubClient_SetMessageCallback\r\n");
				}
				else
				{
					int Lock_fd__i = open_lockfile(LOCKFILE);
					if (setuid(getuid()) < 0)
					{
						perror("Dropping privileges failed. (did you use sudo?)\n");
						exit(EXIT_FAILURE);
					}

					int Result__i = wiringPiSetup();
					if (Result__i != 0) exit(Result__i);

					int Spi_fd__i = wiringPiSPISetup(Spi_channel__i, Spi_clock__i);
					if (Spi_fd__i < 0)
					{
						printf("Can't setup SPI, error %i calling wiringPiSPISetup(%i, %i)  %s\n",
							Spi_fd__i, Spi_channel__i, Spi_clock__i, strerror(Spi_fd__i));
						exit(Spi_fd__i);
					}

					int Init_result__i = bme280_init(Spi_channel__i);
					if (Init_result__i != 1)
					{
						printf("It appears that no BMP280 module on Chip Enable %i is attached. Aborting.\n", Spi_channel__i);
						exit(1);
					}

					pinMode(Red_led_pin__i, OUTPUT);
					pinMode(Grn_led_pin__i, OUTPUT);

					////////////////


					// Read the Temp & Pressure module.
					float Temp_C__f = -300.0;
					float Pressure_Pa__f = -300;
					float Humidity_pct__f = -300;
					Result__i = bme280_read_sensors(&Temp_C__f, &Pressure_Pa__f,
						&Humidity_pct__f);

					if (Result__i == 1)
					{
						printf("Temperature = %.1f *C  Pressure = %.1f Pa  Humidity = %1f %%\n",
							Temp_C__f, Pressure_Pa__f, Humidity_pct__f);
					}
					else
					{
						printf("Unable to read BME280 on pin %i\n", Spi_channel__i);
					}

					char buff[11];
					int timeNow = 0;

					int c;
					while (1)
					{
						timeNow = (int)time(NULL);

						sprintf(buff, "%d", timeNow);

						myWeather->DeviceId = "raspy";
						myWeather->EventTime = buff;

						if (Result__i == 1)
						{
							myWeather->MTemperature = Temp_C__f;
							printf("Humidity = %.1f%% Temperature = %.1f*C \n",
								Humidity_pct__f, Temp_C__f);
						}
						else
						{
							myWeather->MTemperature = 404.0;
							printf("Unable to read BME280 on pin %i\n", Spi_channel__i);
							pinMode(Red_led_pin__i, OUTPUT);
						}


						if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->EventTime, myWeather->MTemperature) != IOT_AGENT_OK)
						{
							(void)printf("Failed to serialize\r\n");
						}
						else
						{
							sendMessage(iotHubClientHandle, destination, destinationSize);
						}

						delay(5000);
					}
					/* wait for commands */
				  // (void)getchar();

					close_lockfile(Lock_fd__i);

				}
				DESTROY_MODEL_INSTANCE(myWeather);
			}
			IoTHubClient_Destroy(iotHubClientHandle);
		}
		serializer_deinit();
	}
}