コード例 #1
0
const char* IoTHubAccount_GetEventhubAccessKey(void)
{
    char *iothub_connection_string;
    static char access_key[128];

    if ((iothub_connection_string = IoTHubAccount_GetIoTHubConnString()) != NULL)
    {
        STRING_HANDLE iothub_connection_string_str;

        if((iothub_connection_string_str = STRING_construct(iothub_connection_string)) != NULL)
        {
            STRING_TOKENIZER_HANDLE tokenizer;

            if ((tokenizer = STRING_TOKENIZER_create(iothub_connection_string_str)) != NULL)
            {
                STRING_HANDLE tokenString;

                if ((tokenString = STRING_new()) != NULL)
                {
                    STRING_HANDLE valueString;

                    if ((valueString = STRING_new()) != NULL)
                    {
                        while ((STRING_TOKENIZER_get_next_token(tokenizer, tokenString, "=") == 0))
                        {
                            char tokenValue[128];
                            strcpy(tokenValue, STRING_c_str(tokenString));

                            if (STRING_TOKENIZER_get_next_token(tokenizer, tokenString, ";") != 0)
                            {
                                break;
                            }

                            if (strcmp(tokenValue, "SharedAccessKey") == 0)
                            {
                                strcpy(access_key, STRING_c_str(tokenString));
                                break;
                            }
                        }

                        STRING_delete(valueString);
                    }

                    STRING_delete(tokenString);
                }

                STRING_TOKENIZER_destroy(tokenizer);
            }

            STRING_delete(iothub_connection_string_str);
        }
    }

    return access_key;
}
コード例 #2
0
 static void setup_dev_auth_emulator_generate_credentials_mocks(const char* token_scope)
 {
     STRICT_EXPECTED_CALL(STRING_new());
     STRICT_EXPECTED_CALL(get_time(IGNORED_PTR_ARG));
     STRICT_EXPECTED_CALL(STRING_construct(token_scope));
     STRICT_EXPECTED_CALL(STRING_construct(IGNORED_PTR_ARG))
         .IgnoreArgument_psz();
     STRICT_EXPECTED_CALL(SASToken_Create(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_NUM_ARG))
         .IgnoreArgument_scope()
         .IgnoreArgument_keyName()
         .IgnoreArgument_expiry()
         .IgnoreArgument_key();
     STRICT_EXPECTED_CALL(STRING_c_str(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(mallocAndStrcpy_s(IGNORED_PTR_ARG, IGNORED_PTR_ARG))
         .IgnoreArgument_destination()
         .IgnoreArgument_source();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
 }
コード例 #3
0
static int InitializeConnection(PMQTTTRANSPORT_HANDLE_DATA transportState, bool initialConnection)
{
    int result = 0;
    if (!transportState->connected && !transportState->destroyCalled)
    {
        // Construct SAS token
        size_t secSinceEpoch = (size_t)(difftime(get_time(NULL), EPOCH_TIME_T_VALUE) + 0);
        size_t expiryTime = secSinceEpoch + SAS_TOKEN_DEFAULT_LIFETIME;

        // Not checking the success of this variable, if fail it will fail in the SASToken creation and return false;
        STRING_HANDLE emptyKeyName = STRING_new();
        STRING_HANDLE sasToken = SASToken_Create(transportState->device_key, transportState->sasTokenSr, emptyKeyName, expiryTime);
        if (sasToken == NULL)
        {
            result = __LINE__;
        }
        else
        {
            MQTT_CLIENT_OPTIONS options = { 0 };
            options.clientId = (char*)STRING_c_str(transportState->device_id);
            options.willMessage = NULL;
            options.username = (char*)STRING_c_str(transportState->configPassedThroughUsername);
            options.password = (char*)STRING_c_str(sasToken);
            options.keepAliveInterval = DEFAULT_MQTT_KEEPALIVE;
            options.useCleanSession = false;
            options.qualityOfServiceValue = DELIVER_AT_LEAST_ONCE;

            // construct address
            const char* hostAddress = STRING_c_str(transportState->hostAddress);
            const char* hostName = strstr(hostAddress, "//");
            if (hostName == NULL)
            {
                hostName = hostAddress;
            }
            else
            {
                // Increment beyond the double backslash
                hostName += 2;
            }

            transportState->xioTransport = getIoTransportProvider(hostName, transportState->portNum);
            if (mqtt_client_connect(transportState->mqttClient, transportState->xioTransport, &options) != 0)
            {
                LogError("failure connecting to address %s:%d.\r\n", STRING_c_str(transportState->hostAddress), transportState->portNum);
                result = __LINE__;
            }
            else
            {
                transportState->connected = true;
                result = 0;
            }
            STRING_delete(emptyKeyName);
            STRING_delete(sasToken);
        }
    }
    return result;
}
コード例 #4
0
/* Codes_SRS_CONNECTIONSTRINGPARSER_01_001: [connectionstringparser_parse shall parse all key value pairs from the connection_string passed in as argument and return a new map that holds the key/value pairs.] */
MAP_HANDLE connectionstringparser_parse(STRING_HANDLE connection_string)
{
    MAP_HANDLE result;

    if (connection_string == NULL)
    {
        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_002: [If connection_string is NULL then connectionstringparser_parse shall fail and return NULL.] */
        result = NULL;
        LogError("NULL connection string passed to tokenizer.");
    }
    else
    {
        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_003: [connectionstringparser_parse shall create a STRING tokenizer to be used for parsing the connection string, by calling STRING_TOKENIZER_create.] */
        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_004: [connectionstringparser_parse shall start scanning at the beginning of the connection string.] */
        STRING_TOKENIZER_HANDLE tokenizer = STRING_TOKENIZER_create(connection_string);
        if (tokenizer == NULL)
        {
            /* Codes_SRS_CONNECTIONSTRINGPARSER_01_015: [If STRING_TOKENIZER_create fails, connectionstringparser_parse shall fail and return NULL.] */
            result = NULL;
            LogError("Error creating STRING tokenizer.");
        }
        else
        {
            /* Codes_SRS_CONNECTIONSTRINGPARSER_01_016: [2 STRINGs shall be allocated in order to hold the to be parsed key and value tokens.] */
            STRING_HANDLE token_key_string = STRING_new();
            if (token_key_string == NULL)
            {
                /* Codes_SRS_CONNECTIONSTRINGPARSER_01_017: [If allocating the STRINGs fails connectionstringparser_parse shall fail and return NULL.] */
                result = NULL;
                LogError("Error creating key token STRING.");
            }
            else
            {
                STRING_HANDLE token_value_string = STRING_new();
                if (token_value_string == NULL)
                {
                    /* Codes_SRS_CONNECTIONSTRINGPARSER_01_017: [If allocating the STRINGs fails connectionstringparser_parse shall fail and return NULL.] */
                    result = NULL;
                    LogError("Error creating value token STRING.");
                }
                else
                {
                    result = Map_Create(NULL);
                    if (result == NULL)
                    {
                        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_018: [If creating the result map fails, then connectionstringparser_parse shall return NULL.] */
                        LogError("Error creating Map.");
                    }
                    else
                    {
                        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_005: [The following actions shall be repeated until parsing is complete:] */
                        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_006: [connectionstringparser_parse shall find a token (the key of the key/value pair) delimited by the `=` character, by calling STRING_TOKENIZER_get_next_token.] */
                        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_007: [If STRING_TOKENIZER_get_next_token fails, parsing shall be considered complete.] */
                        while (STRING_TOKENIZER_get_next_token(tokenizer, token_key_string, "=") == 0)
                        {
                            bool is_error = false;

                            /* Codes_SRS_CONNECTIONSTRINGPARSER_01_008: [connectionstringparser_parse shall find a token (the value of the key/value pair) delimited by the `;` character, by calling STRING_TOKENIZER_get_next_token.] */
                            if (STRING_TOKENIZER_get_next_token(tokenizer, token_value_string, ";") != 0)
                            {
                                /* Codes_SRS_CONNECTIONSTRINGPARSER_01_009: [If STRING_TOKENIZER_get_next_token fails, connectionstringparser_parse shall fail and return NULL (freeing the allocated result map).] */
                                is_error = true;
                                LogError("Error reading value token from the connection string.");
                            }
                            else
                            {
                                /* Codes_SRS_CONNECTIONSTRINGPARSER_01_011: [The C strings for the key and value shall be extracted from the previously parsed STRINGs by using STRING_c_str.] */
                                const char* token = STRING_c_str(token_key_string);
                                /* Codes_SRS_CONNECTIONSTRINGPARSER_01_013: [If STRING_c_str fails then connectionstringparser_parse shall fail and return NULL (freeing the allocated result map).] */
                                if ((token == NULL) ||
                                    /* Codes_SRS_CONNECTIONSTRINGPARSER_01_019: [If the key length is zero then connectionstringparser_parse shall fail and return NULL (freeing the allocated result map).] */
                                    (strlen(token) == 0))
                                {
                                    is_error = true;
                                    LogError("The key token is NULL or empty.");
                                }
                                else
                                {
                                    /* Codes_SRS_CONNECTIONSTRINGPARSER_01_011: [The C strings for the key and value shall be extracted from the previously parsed STRINGs by using STRING_c_str.] */
                                    const char* value = STRING_c_str(token_value_string);
                                    if (value == NULL)
                                    {
                                        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_013: [If STRING_c_str fails then connectionstringparser_parse shall fail and return NULL (freeing the allocated result map).] */
                                        is_error = true;
                                        LogError("Could not get C string for value token.");
                                    }
                                    else
                                    {
                                        /* Codes_SRS_CONNECTIONSTRINGPARSER_01_010: [The key and value shall be added to the result map by using Map_Add.] */
                                        if (Map_Add(result, token, value) != 0)
                                        {
                                            /* Codes_SRS_CONNECTIONSTRINGPARSER_01_012: [If Map_Add fails connectionstringparser_parse shall fail and return NULL (freeing the allocated result map).] */
                                            is_error = true;
                                            LogError("Could not add the key/value pair to the result map.");
                                        }
                                    }
                                }
                            }

                            if (is_error)
                            {
                                LogError("Error parsing connection string.");
                                Map_Destroy(result);
                                result = NULL;
                                break;
                            }
                        }
                    }

                    STRING_delete(token_value_string);
                }

                STRING_delete(token_key_string);
            }

            /* Codes_SRS_CONNECTIONSTRINGPARSER_01_014: [After the parsing is complete the previously allocated STRINGs and STRING tokenizer shall be freed by calling STRING_TOKENIZER_destroy.] */
            STRING_TOKENIZER_destroy(tokenizer);
        }
    }

    return result;
}
コード例 #5
0
IOTHUB_CLIENT_LL_HANDLE IoTHubClient_LL_CreateFromConnectionString(const char* connectionString, IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol)
{
    IOTHUB_CLIENT_LL_HANDLE result = NULL;

    /*Codes_SRS_IOTHUBCLIENT_LL_05_001: [IoTHubClient_LL_CreateFromConnectionString shall obtain the version string by a call to IoTHubClient_GetVersionString.]*/
    /*Codes_SRS_IOTHUBCLIENT_LL_05_002: [IoTHubClient_LL_CreateFromConnectionString shall print the version string to standard output.]*/
    LogInfo("IoT Hub SDK for C, version %s", IoTHubClient_GetVersionString());

    /* Codes_SRS_IOTHUBCLIENT_LL_12_003: [IoTHubClient_LL_CreateFromConnectionString shall verify the input parameter and if it is NULL then return NULL] */
    if (connectionString == NULL)
    {
        LogError("Input parameter is NULL: connectionString");
    }
    else if (protocol == NULL)
    {
        LogError("Input parameter is NULL: protocol");
    }
    else
    {
        /* Codes_SRS_IOTHUBCLIENT_LL_12_004: [IoTHubClient_LL_CreateFromConnectionString shall allocate IOTHUB_CLIENT_CONFIG structure] */
        IOTHUB_CLIENT_CONFIG* config = malloc(sizeof(IOTHUB_CLIENT_CONFIG));
        if (config == NULL)
        {
            /* Codes_SRS_IOTHUBCLIENT_LL_12_012: [If the allocation failed IoTHubClient_LL_CreateFromConnectionString  returns NULL]  */
            LogError("Malloc failed");
            return NULL;
        }
        else
        {
            STRING_TOKENIZER_HANDLE tokenizer1 = NULL;
            STRING_HANDLE connString = NULL;
            STRING_HANDLE tokenString = NULL;
            STRING_HANDLE valueString = NULL;
            STRING_HANDLE hostNameString = NULL;
            STRING_HANDLE hostSuffixString = NULL;
            STRING_HANDLE deviceIdString = NULL;
            STRING_HANDLE deviceKeyString = NULL;
            STRING_HANDLE deviceSasTokenString = NULL;
            STRING_HANDLE protocolGateway = NULL;

            config->protocol = protocol;

            config->iotHubName = NULL;
            config->iotHubSuffix = NULL;
            config->deviceId = NULL;
            config->deviceKey = NULL;
            config->deviceSasToken = NULL;

            /* Codes_SRS_IOTHUBCLIENT_LL_04_002: [If it does not, it shall pass the protocolGatewayHostName NULL.] */
            config->protocolGatewayHostName = NULL;

            if ((connString = STRING_construct(connectionString)) == NULL)
            {
                LogError("Error constructing connectiong String");
            }
            else if ((tokenizer1 = STRING_TOKENIZER_create(connString)) == NULL)
            {
                LogError("Error creating Tokenizer");
            }
            else if ((tokenString = STRING_new()) == NULL)
            {
                LogError("Error creating Token String");
            }
            else if ((valueString = STRING_new()) == NULL)
            {
                LogError("Error creating Value String");
            }
            else if ((hostNameString = STRING_new()) == NULL)
            {
                LogError("Error creating HostName String");
            }
            else if ((hostSuffixString = STRING_new()) == NULL)
            {
                LogError("Error creating HostSuffix String");
            }
            /* Codes_SRS_IOTHUBCLIENT_LL_12_005: [IoTHubClient_LL_CreateFromConnectionString shall try to parse the connectionString input parameter for the following structure: "Key1=value1;key2=value2;key3=value3..."] */
            /* Codes_SRS_IOTHUBCLIENT_LL_12_006: [IoTHubClient_LL_CreateFromConnectionString shall verify the existence of the following Key/Value pairs in the connection string: HostName, DeviceId, SharedAccessKey or SharedAccessSignature.]  */
            else
            {
                while ((STRING_TOKENIZER_get_next_token(tokenizer1, tokenString, "=") == 0))
                {
                    if (STRING_TOKENIZER_get_next_token(tokenizer1, valueString, ";") != 0)
                    {
                        LogError("Tokenizer error");
                        break;
                    }
                    else
                    {
                        if (tokenString != NULL)
                        {
                            /* Codes_SRS_IOTHUBCLIENT_LL_12_010: [IoTHubClient_LL_CreateFromConnectionString shall fill up the IOTHUB_CLIENT_CONFIG structure using the following mapping: iotHubName = Name, iotHubSuffix = Suffix, deviceId = DeviceId, deviceKey = SharedAccessKey or deviceSasToken = SharedAccessSignature] */
                            const char* s_token = STRING_c_str(tokenString);
                            if (strcmp(s_token, HOSTNAME_TOKEN) == 0)
                            {
                                /* Codes_SRS_IOTHUBCLIENT_LL_12_009: [IoTHubClient_LL_CreateFromConnectionString shall split the value of HostName to Name and Suffix using the first "." as a separator] */
                                STRING_TOKENIZER_HANDLE tokenizer2 = NULL;
                                if ((tokenizer2 = STRING_TOKENIZER_create(valueString)) == NULL)
                                {
                                    LogError("Error creating Tokenizer");
                                    break;
                                }
                                else
                                {
                                    /* Codes_SRS_IOTHUBCLIENT_LL_12_015: [If the string split failed, IoTHubClient_LL_CreateFromConnectionString returns NULL ] */
                                    if (STRING_TOKENIZER_get_next_token(tokenizer2, hostNameString, ".") != 0)
                                    {
                                        LogError("Tokenizer error");
                                        STRING_TOKENIZER_destroy(tokenizer2);
                                        break;
                                    }
                                    else
                                    {
                                        config->iotHubName = STRING_c_str(hostNameString);
                                        if (STRING_TOKENIZER_get_next_token(tokenizer2, hostSuffixString, ";") != 0)
                                        {
                                            LogError("Tokenizer error");
                                            STRING_TOKENIZER_destroy(tokenizer2);
                                            break;
                                        }
                                        else
                                        {
                                            config->iotHubSuffix = STRING_c_str(hostSuffixString);
                                        }
                                    }
                                    STRING_TOKENIZER_destroy(tokenizer2);
                                }
                            }
                            else if (strcmp(s_token, DEVICEID_TOKEN) == 0)
                            {
                                deviceIdString = STRING_clone(valueString);
                                if (deviceIdString != NULL)
                                {
                                    config->deviceId = STRING_c_str(deviceIdString);
                                }
                            }
                            else if (strcmp(s_token, DEVICEKEY_TOKEN) == 0)
                            {
                                deviceKeyString = STRING_clone(valueString);
                                if (deviceKeyString != NULL)
                                {
                                    config->deviceKey = STRING_c_str(deviceKeyString);
                                }
                            }
                            else if (strcmp(s_token, DEVICESAS_TOKEN) == 0)
                            {
                                deviceSasTokenString = STRING_clone(valueString);
                                if (deviceSasTokenString != NULL)
                                {
                                    config->deviceSasToken = STRING_c_str(deviceSasTokenString);
                                }
                            }
                            /* Codes_SRS_IOTHUBCLIENT_LL_04_001: [IoTHubClient_LL_CreateFromConnectionString shall verify the existence of key/value pair GatewayHostName. If it does exist it shall pass the value to IoTHubClient_LL_Create API.] */
                            else if (strcmp(s_token, PROTOCOL_GATEWAY_HOST) == 0)
                            {
                                protocolGateway = STRING_clone(valueString);
                                if (protocolGateway != NULL)
                                {
                                    config->protocolGatewayHostName = STRING_c_str(protocolGateway);
                                }
                            }
                        }
                    }
                }
                /* parsing is done - check the result */
                if (config->iotHubName == NULL)
                {
                    LogError("iotHubName is not found");
                }
                else if (config->iotHubSuffix == NULL)
                {
                    LogError("iotHubSuffix is not found");
                }
                else if (config->deviceId == NULL)
                {
                    LogError("deviceId is not found");
                }
                else if (config->deviceKey == NULL && config->deviceSasToken == NULL)
                {
                    LogError("deviceKey/deviceSasToken not found");
                }
                else if (config->deviceKey != NULL && config->deviceSasToken != NULL)
                {
                    LogError("Both device Key & SAS token are defined. Only one should be provided.");
                }
                else
                {
                    /* Codes_SRS_IOTHUBCLIENT_LL_12_011: [IoTHubClient_LL_CreateFromConnectionString shall call into the IoTHubClient_LL_Create API with the current structure and returns with the return value of it] */
                    
                    result = IoTHubClient_LL_Create(config);
                    if (result == NULL)
                    {
                        LogError("IoTHubClient_LL_Create failed");
                    }
                    else
                    {
                        /*return as is*/
                    }
                }
            }
            if (deviceSasTokenString != NULL)
                STRING_delete(deviceSasTokenString);
            if (deviceKeyString != NULL)
                STRING_delete(deviceKeyString);
            if (deviceIdString != NULL)
                STRING_delete(deviceIdString);
            if (hostSuffixString != NULL)
                STRING_delete(hostSuffixString);
            if (hostNameString != NULL)
                STRING_delete(hostNameString);
            if (valueString != NULL)
                STRING_delete(valueString);
            if (tokenString != NULL)
                STRING_delete(tokenString);
            if (connString != NULL)
                STRING_delete(connString);
            if (protocolGateway != NULL)
                STRING_delete(protocolGateway);

            if (tokenizer1 != NULL)
                STRING_TOKENIZER_destroy(tokenizer1);

            free(config);
        }
    }
    return result;
}
コード例 #6
0
ファイル: main.cpp プロジェクト: neo7206/azure-iot-sdks
int main(void)
{
    pc.baud(115200);

    THREAD_HANDLE ThreadHandle;

    (void)printf("Initializing mbed specific things...\r\n");

    (void)printf("doing a one time EthernetInterface::init();\r\n");
    if (EthernetInterface::init() != 0)
    {
         (void)printf("Failed EthernetInterface::init();\r\n");
         return -1;
    }
    (void)printf("done doing a one time EthernetInterface::init();\r\n");

    if (setupRealTime() != 0)
    {
         (void)printf("Failed setting up real time clock\r\n");
         return -1;
    }

    /* clear the LED light upon startup */
    red_led = 1;
    blue_led = 1;
    green_led = 1;

    alarm_type = ALARM_NONE;
    led_on = 0;

    /* clear the screen */
    lcd.cls();

    if (ThreadAPI_Create(&ThreadHandle, LED_Update_Thread, NULL) != THREADAPI_OK)
    {
        (void)printf("Error spinning LED update thread.\r\n");
        return -1;
    }

    /* initialize the IoTHubClient */
    if (serializer_init(NULL) != SERIALIZER_OK)
    {
        (void)printf("Failed on serializer_init\r\n");
    }
    else
    {
        /* Setup IoTHub client configuration */

        IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

        if (iotHubClientHandle == NULL)
        {
            (void)printf("Failed on IoTHubClient_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)
            {
                printf("failure to set option \"MinimumPollingTime\"\r\n");
            }

            FrdmDevice* frdmDevice = CREATE_MODEL_INSTANCE(Contoso, FrdmDevice, true);
            if (frdmDevice == NULL)
            {
                (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
            }
            else
            {
                IOTHUB_CLIENT_RESULT setMessageResult = IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, frdmDevice);
                if (setMessageResult != IOTHUB_CLIENT_OK)
                {
                    (void)printf("unable to IoTHubClient_SetMessageCallback\r\n");
                }
                else
                {
                    STRING_HANDLE commandsMetadata;

                    temp = (sensor.temp() * 9 / 5) + 32;

                    /* send the device info upon startup so that the cloud app knows
                    what commands are available and the fact that the device is up */
                    frdmDevice->ObjectType = "DeviceInfo-HW";
                    frdmDevice->ObjectName = "An ALARM device";
                    frdmDevice->Version = "1.0";
                    frdmDevice->SystemProperties.DeviceID = (char*)deviceId;
                    frdmDevice->SystemProperties.Enabled = true;

                    /* build the description of the commands on the device */
                    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, FrdmDevice), commandsMetadata) != SCHEMA_SERIALIZER_OK)
                        {
                            (void)printf("Failed serializing commands metadata\r\n");
                        }
                        else
                        {
                            frdmDevice->Commands = (char*)STRING_c_str(commandsMetadata);

                            /* Send the device information and commands metadata to the cloud */
                            {
                                unsigned char* destination;
                                size_t destinationSize;
                                if (SERIALIZE(&destination, &destinationSize, frdmDevice->ObjectName, frdmDevice->ObjectType, frdmDevice->SystemProperties, frdmDevice->Version, frdmDevice->Commands) != IOT_AGENT_OK)
                                {
                                    (void)printf("Failed to serialize\r\n");
                                }
                                else
                                {
                                    sendMessage(iotHubClientHandle, destination, destinationSize);
                                    free(destination);
                                }
                            }
                        }

                        STRING_delete(commandsMetadata);
                    }

                    frdmDevice->ObjectName = (ascii_char_ptr)deviceId;
                    frdmDevice->ObjectType = "SensorTagEvent";
                    frdmDevice->Version = "1.0";
                    frdmDevice->TargetAlarmDevice = (ascii_char_ptr)deviceId;

                    while (1)
                    {
                        unsigned char* destination;
                        size_t destinationSize;

                        (void)printf("Sending %.02f\r\n", temp);
                        frdmDevice->temp = temp;

                        if (SERIALIZE(&destination, &destinationSize, frdmDevice->ObjectName, frdmDevice->ObjectType, frdmDevice->Version, frdmDevice->TargetAlarmDevice, frdmDevice->temp) != IOT_AGENT_OK)
                        {
                            (void)printf("Failed to serialize\r\n");
                        }
                        else
                        {
                            sendMessage(iotHubClientHandle, destination, destinationSize);
                            free(destination);
                        }

                        /* schedule IoTHubClient to send events/receive commands */
                        IoTHubClient_LL_DoWork(iotHubClientHandle);
                    }
                }
                DESTROY_MODEL_INSTANCE(frdmDevice);
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        serializer_deinit();
    }
}
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();
    }
}
コード例 #8
0
JSON_ENCODER_RESULT JSONEncoder_EncodeTree(MULTITREE_HANDLE treeHandle, STRING_HANDLE destination, JSON_ENCODER_TOSTRING_FUNC toStringFunc)
{
    JSON_ENCODER_RESULT result;

    size_t childCount;

    /* Codes_SRS_JSON_ENCODER_99_032:[If any of the arguments passed to JSONEncoder_EncodeTree is NULL then JSON_ENCODER_INVALID_ARG shall be returned.] */
    if ((treeHandle == NULL) ||
        (destination == NULL) ||
        (toStringFunc == NULL))
    {
        result = JSON_ENCODER_INVALID_ARG;
        LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
    }
    /*Codes_SRS_JSON_ENCODER_99_035:[ JSON encoder shall inquire the number of child nodes (further called childCount) of the current node (given by parameter treeHandle.]*/
    else if (MultiTree_GetChildCount(treeHandle, &childCount) != MULTITREE_OK)
    {
        result = JSON_ENCODER_MULTITREE_ERROR;
        LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
    }
    else
    {
        size_t i;
        /*Codes_SRS_JSON_ENCODER_99_036:[ The string "{" shall be added to the output;]*/
        if (STRING_concat(destination,  "{") != 0)
        {
            result = JSON_ENCODER_ERROR;
            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
        }
        else
        {
            result = JSON_ENCODER_OK;
            for (i = 0; (i < childCount) && (result == JSON_ENCODER_OK); i++)
            {
                MULTITREE_HANDLE childTreeHandle;

                if ((i > 0) &&
                    (STRING_concat(destination, ", ") != 0))
                {
                    result = JSON_ENCODER_ERROR;
                    LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                }
                else if (STRING_concat(destination, "\"") != 0)
                {
                    result = JSON_ENCODER_ERROR;
                    LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                }
                else
                {
                    STRING_HANDLE name = STRING_new();
                    if (name == NULL)
                    {
                        result = JSON_ENCODER_ERROR;
                        LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                    }
                    else
                    {
                        if (MultiTree_GetChild(treeHandle, i, &childTreeHandle) != MULTITREE_OK)
                        {
                            result = JSON_ENCODER_MULTITREE_ERROR;
                            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                        }
                        else if (MultiTree_GetName(childTreeHandle, name) != MULTITREE_OK)
                        {
                            result = JSON_ENCODER_MULTITREE_ERROR;
                            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                        }
                        else if (STRING_concat_with_STRING(destination, name) != 0)
                        {
                            result = JSON_ENCODER_ERROR;
                            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                        }
                        else if (STRING_concat(destination, "\":") != 0)
                        {
                            result = JSON_ENCODER_ERROR;
                            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                        }
                        else
                        {
                            size_t innerChildCount;
                            if (MultiTree_GetChildCount(childTreeHandle, &innerChildCount) != MULTITREE_OK)
                            {
                                result = JSON_ENCODER_MULTITREE_ERROR;
                                LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                            }
                            else
                            {
                                if (innerChildCount > 0)
                                {
                                    STRING_HANDLE child = STRING_new();
                                    if (child == NULL)
                                    {
                                        result = JSON_ENCODER_ERROR;
                                        LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                                    }
                                    else
                                    {
                                        if ((result = JSONEncoder_EncodeTree(childTreeHandle, child, toStringFunc)) != JSON_ENCODER_OK)
                                        {
                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                                        }
                                        else if (STRING_concat_with_STRING(destination, child)!=0)
                                        {
                                            result = JSON_ENCODER_ERROR;
                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                                        }
                                        STRING_delete(child);
                                    }
                                }
                                else
                                {
                                    const void* value;
                                    if (MultiTree_GetValue(childTreeHandle, &value) != MULTITREE_OK)
                                    {
                                        result = JSON_ENCODER_MULTITREE_ERROR;
                                        LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));

                                    }
                                    else
                                    {
                                        STRING_HANDLE childValue = STRING_new();
                                        if (childValue == NULL)
                                        {
                                            result = JSON_ENCODER_ERROR;
                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                                        }
                                        else
                                        {
                                            if (toStringFunc(childValue, value) != JSON_ENCODER_TOSTRING_OK)
                                            {
                                                result = JSON_ENCODER_TOSTRING_FUNCTION_ERROR;
                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                                            }
                                            else if (STRING_concat_with_STRING(destination, childValue)!=0)
                                            {
                                                result = JSON_ENCODER_ERROR;
                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                                            }
                                            else
                                            {
                                                /*do nothing, result = JSON_ENCODER_OK is set above at the beginning of the FOR loop*/
                                            }
                                            STRING_delete(childValue);
                                        }
                                    }
                                }
                            }
                        }
                        STRING_delete(name);
                    }
                }
            }

            if ((i == childCount) && (result == JSON_ENCODER_OK))
            {
                if (STRING_concat(destination,  "}") != 0)
                {
                    result = JSON_ENCODER_ERROR;
                    LogError("(result = %s)\r\n", ENUM_TO_STRING(JSON_ENCODER_RESULT, result));
                }
                else
                {
                    /* Codes_SRS_JSON_ENCODER_99_031:[On success, JSONEncoder_EncodeTree shall return JSON_ENCODER_OK.] */
                    result = JSON_ENCODER_OK;
                }
            }
        }
    }

    return result;
#ifdef _MSC_VER
#pragma warning(disable: 4701) /* potentially uninitialized local variable 'result' used */ /* the scanner cannot track variable "i" and link it to childCount*/
#endif
}
コード例 #9
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();
    }
}
コード例 #10
0
ファイル: gb_error.c プロジェクト: ramonelalto/gambas
void ERROR_define(const char *pattern, char *arg[])
{
	uchar c;
	char *msg = NULL;
	int len;
	int narg = 0;

	ERROR_clear();

	if ((intptr_t)pattern >= 0 && (intptr_t)pattern < 256)
	{
		ERROR_current->info.code = (int)(intptr_t)pattern;
		pattern = _message[(int)(intptr_t)pattern];
		if (*pattern == '.')
		{
			narg = pattern[1] - '0';
			pattern += 2;
		}
	}
	else if ((intptr_t)pattern == E_ABORT)
	{
		ERROR_current->info.code = E_ABORT;
		pattern = "";
	}
	else
	{
		ERROR_current->info.code = E_CUSTOM;
		
		if (arg)
		{
			msg = (char *)pattern;
			for (;;)
			{
				c = *msg++;
				if (c == 0)
					break;
					
				if (c == '&')
				{
					c = *msg++;
					if (c >= '1' && c <= '4')
					{
						c -= '0';
						if (c > narg)
							narg = c;
					}
				}
			}
		}
	}

	if (narg)
	{
		len = get_message_length(pattern, arg, narg);
		if (len)
		{
			msg = STRING_new(NULL, len);
			ERROR_current->info.msg = msg;
			ERROR_current->info.free = TRUE;
		
			if (EXEC_debug)
			{
				int i;
				strcpy(msg, pattern);
				msg += strlen(pattern);
				for (i = 0; i < narg; i++)
				{
					*msg++ = '|';
					if (arg[i])
					{
						strcpy(msg, arg[i]);
						msg += strlen(arg[i]);
					}
				}
			}
			else
			{
				for (;;)
				{
					c = *pattern++;
					if (c == 0)
						break;
						
					if (c == '&')
					{
						c = *pattern++;
						if (c >= '1' && c <= '4')
						{
							c -= '1';
							if (arg[c])
							{
								len = strlen(arg[c]);
								memcpy(msg, arg[c], len);
								msg += len;
							}
						}
					}
					else
						*msg++ = c;
				}
				
				*msg = 0;
			}

			/*fprintf(stderr, "msg: %s\n", ERROR_current->info.msg);
			if (strcmp(ERROR_current->info.msg, "Type mismatch: wanted WebView, got Function instead") == 0)
			{
				BREAKPOINT();
				STRING_watch = ERROR_current->info.msg;
			}*/
		}
	}
	else if (ERROR_current->info.code == E_CUSTOM)
	{
		if (pattern && *pattern)
		{
			ERROR_current->info.msg = STRING_new_zero(pattern);
			ERROR_current->info.free = TRUE;
		}
		else
		{
			ERROR_current->info.msg = (char *)_message[E_UNKNOWN];
			ERROR_current->info.free = FALSE;
		}
	}
	else
	{
		ERROR_current->info.msg = (char *)pattern;
		ERROR_current->info.free = FALSE;
	}

	//fprintf(stderr, "ERROR_define: %p %d '%s'\n", ERROR_current, ERROR_current->info.code, ERROR_current->info.msg);

	//STRING_add_char(&ERROR_current->info.msg, 0);

	ERROR_current->info.cp = CP;
	ERROR_current->info.fp = FP;
	ERROR_current->info.pc = PC;
	
	#if DEBUG_ERROR
	ERROR_debug("ERROR_define: %s\n", ERROR_current->info.msg);
	#endif
}
コード例 #11
0
ファイル: mqttapi_paho.c プロジェクト: neo7206/azure-iot-sdks
static bool checkAndTryToConnect(PMQTTTAPI_HANDLE_DATA mqttApiState)
{
	bool result;

	if (mqttApiState != NULL)
	{
		if (!mqttApiState->connected)
		{
			/* Codes_SRS_MQTTAPI_04_062: [MQTTAPI_create shall generate SAS Token with an expiring time of 1 hour.] */
			size_t secondsSinceEpoch = (size_t)(difftime(get_time(NULL), EPOCH_TIME_T_VALUE) + 0);
			size_t possibleNewExpiry = secondsSinceEpoch + mqttApiState->sasTokenLifetime;
			STRING_HANDLE zeroLengthString;

			if ((zeroLengthString = STRING_new()) == NULL)
			{
				LogError("Could not generate zeroLenghtString for skn. \r\n");
				result = false;
			}
			else
			{
				STRING_HANDLE newSASToken = SASToken_Create(mqttApiState->device_key, mqttApiState->sasTokenSr, zeroLengthString, possibleNewExpiry);

				if (newSASToken == NULL)
				{
					LogError("Could not generate a SAS Token\r\n");
					result = false;
				}
				else
				{
					/* Codes_SRS_MQTTAPI_04_024: [MQTTAPI_Create shall call underlying library connection functions to establish connection with the server.]  */
					if (!connectToMQTTServer(mqttApiState->client, STRING_c_str(mqttApiState->device_id), STRING_c_str(newSASToken)))
					{
						/* Tests_SRS_MQTTAPI_04_025: [If connection fails MQTTAPI_Create shall return NULL. */
						result = false;
					}
					else
					{
						mqttApiState->connected = true;
						mqttApiState->lastExpiryUsed = possibleNewExpiry;
						result = true;
					}
					STRING_delete(newSASToken);
				}
				STRING_delete(zeroLengthString);
			}
		}
		else
		{
			//Here is the point that we need to check if we need to disconnect, generate a new SAS Token and Connect Again. 
			size_t secondsSinceEpoch;
			int differenceWithLastExpiry;
			secondsSinceEpoch = (size_t)(difftime(get_time(NULL), EPOCH_TIME_T_VALUE) + 0);
			differenceWithLastExpiry = mqttApiState->lastExpiryUsed - secondsSinceEpoch;

			/* Codes_SRS_MQTTAPI_04_063: [DoWork shall check the SAS Token Expiration time for the current connection. If the token is near to expire and there is no pending item, it shall disconnect, generate a new SAS Token with 1 hour expiration and connect again.] */
			if ((differenceWithLastExpiry <= 0)	|| 
				(((size_t)differenceWithLastExpiry) < mqttApiState->sasRefreshLine && DList_IsListEmpty(&(mqttApiState->messagesSent))
				)
				) // Within refresh minutes (or past if negative) of the expiration
			{
				/* First Disconnect */
				/* Codes_SRS_MQTTAPI_04_064: [If the token is expired we shall disconnect, signal that all pending message are failed due to Token Expired.] */
				if (MQTTClient_disconnect(mqttApiState->client, 0) != MQTTCLIENT_SUCCESS)
				{
					LogError("Token is Expired or about to be expired and Disconnect Failed. \r\n");
				}
				else
				{
					size_t possibleNewExpiry = secondsSinceEpoch + mqttApiState->sasTokenLifetime;
					STRING_HANDLE zeroLengthString;

					if ((zeroLengthString = STRING_new()) == NULL)
					{
						LogError("Could not generate zeroLenghtString for skn. \r\n");
						result = false;
					}
					else
					{
						STRING_HANDLE newSASToken = SASToken_Create(mqttApiState->device_key, mqttApiState->sasTokenSr, zeroLengthString, possibleNewExpiry);
						mqttApiState->connected = false;

						if (newSASToken == NULL)
						{
							LogError("Could not generate a SAS Token\r\n");
							result = false;
						}
						else
						{
							/* Codes_SRS_MQTTAPI_04_024: [MQTTAPI_Create shall call underlying library connection functions to establish connection with the server.]  */
							if (!connectToMQTTServer(mqttApiState->client, STRING_c_str(mqttApiState->device_id), STRING_c_str(newSASToken)))
							{
								/* Tests_SRS_MQTTAPI_04_025: [If connection fails MQTTAPI_Create shall return NULL. */
								result = false;
							}
							else
							{
								mqttApiState->connected = true;
								mqttApiState->lastExpiryUsed = possibleNewExpiry;
								if (mqttApiState->subscribed)
								{
									int rc;
									LogInfo("Trying to Subscribe after reconnect.\r\n");

									if ((rc = MQTTClient_subscribe(mqttApiState->client, STRING_c_str(mqttApiState->subscribedTopicHandleData->topicName), SUBSCRIBEQOS)) != MQTTCLIENT_SUCCESS)
									{
										LogError("Could not subscribe again. Won't be able to receive messages. Error Code: %d.\r\n", rc);
									}
									else
									{
										LogInfo("Subscribed succesfully after reconnect..\r\n");
									}
								}
								result = true;
							}
							STRING_delete(newSASToken);
						}
						STRING_delete(zeroLengthString);
					}
				}
			}


			result = true;
		}
	}
	else
	{
		LogError("Invalid Arg. Handle is NULL. \r\n");
		result = false;
	}

	return result;
}
コード例 #12
0
IOTHUB_SERVICE_CLIENT_AUTH_HANDLE IoTHubServiceClientAuth_CreateFromConnectionString(const char* connectionString)
{
    IOTHUB_SERVICE_CLIENT_AUTH_HANDLE result;

    /*Codes_SRS_IOTHUBSERVICECLIENT_12_001: [** IoTHubServiceClientAuth_CreateFromConnectionString shall verify the input parameter and if it is NULL then return NULL **]*/
    if (connectionString == NULL)
    {
        LogError("Input parameter is NULL: connectionString");
        result = NULL;
    }
    else
    {
        /*Codes_SRS_IOTHUBSERVICECLIENT_12_002: [** IoTHubServiceClientAuth_CreateFromConnectionString shall allocate memory for a new service client instance. **] */
        result = malloc(sizeof(IOTHUB_SERVICE_CLIENT_AUTH));
        if (result == NULL)
        {
            /*Codes_SRS_IOTHUBSERVICECLIENT_12_003: [** If the allocation failed, IoTHubServiceClientAuth_CreateFromConnectionString shall return NULL **] */
            LogError("Malloc failed for IOTHUB_SERVICE_CLIENT_AUTH");
        }
        else
        {
            /*Codes_SRS_IOTHUBSERVICECLIENT_12_009: [** IoTHubServiceClientAuth_CreateFromConnectionString shall create a STRING_HANDLE from the given connection string by calling STRING_construct. **] */
            STRING_HANDLE connection_string;
            if ((connection_string = STRING_construct(connectionString)) == NULL)
            {
                /*Codes_SRS_IOTHUBSERVICECLIENT_12_010: [** If the STRING_construct fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                LogError("STRING_construct failed");
                free(result);
                result = NULL;
            }
            else
            {
                /*Codes_SRS_IOTHUBSERVICECLIENT_12_004: [** IoTHubServiceClientAuth_CreateFromConnectionString shall populate hostName, iotHubName, iotHubSuffix, sharedAccessKeyName, sharedAccessKeyValue from the given connection string by calling connectionstringparser_parse **] */
                MAP_HANDLE connection_string_values_map;
                if ((connection_string_values_map = connectionstringparser_parse(connection_string)) == NULL)
                {
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_005: [** If populating the IOTHUB_SERVICE_CLIENT_AUTH fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL **] */
                    LogError("Tokenizing failed on connectionString");
                    free(result);
                    result = NULL;
                }
                else
                {
                    STRING_TOKENIZER_HANDLE tokenizer = NULL;
                    STRING_HANDLE token_key_string = NULL;
                    STRING_HANDLE token_value_string = NULL;
                    STRING_HANDLE host_name_string = NULL;
                    const char* hostName;
                    const char* keyName;
                    const char* sharedAccessKey;
                    const char* iothubName;
                    const char* iothubSuffix;

                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_004: [** IoTHubServiceClientAuth_CreateFromConnectionString shall populate hostName, iotHubName, iotHubSuffix, sharedAccessKeyName, sharedAccessKeyValue from the given connection string by calling connectionstringparser_parse **] */
                    (void)memset(result, 0, sizeof(IOTHUB_SERVICE_CLIENT_AUTH));
                    if ((hostName = Map_GetValueFromKey(connection_string_values_map, IOTHUBHOSTNAME)) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_011: [** If the populating HostName fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Couldn't find %s in connection string", IOTHUBHOSTNAME);
                        free(result);
                        result = NULL;
                    }
                    else if ((keyName = Map_GetValueFromKey(connection_string_values_map, IOTHUBSHAREDACESSKEYNAME)) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_012: [** If the populating SharedAccessKeyName fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Couldn't find %s in connection string", IOTHUBSHAREDACESSKEYNAME);
                        free(result);
                        result = NULL;
                    }
                    else if ((sharedAccessKey = Map_GetValueFromKey(connection_string_values_map, IOTHUBSHAREDACESSKEY)) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_013: [** If the populating SharedAccessKey fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Couldn't find %s in connection string", IOTHUBSHAREDACESSKEY);
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_038: [** IoTHubServiceClientAuth_CreateFromConnectionString shall create a STRING_handle from hostName by calling STRING_construct. **] */
                    else if ((host_name_string = STRING_construct(hostName)) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_039: [** If the STRING_construct fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("STRING_construct failed");
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_014: [** IoTHubServiceClientAuth_CreateFromConnectionString shall create a STRING_TOKENIZER to parse HostName by calling STRING_TOKENIZER_create. **] */
                    else if ((tokenizer = STRING_TOKENIZER_create(host_name_string)) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_015: [** If the STRING_TOKENIZER_create fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Error creating STRING tokenizer");
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_016: [** IoTHubServiceClientAuth_CreateFromConnectionString shall create a new STRING_HANDLE for token key string by calling STRING_new. **] */
                    else if ((token_key_string = STRING_new()) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_017: [** If the STRING_new fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Error creating key token STRING_HANDLE");
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_018: [** IoTHubServiceClientAuth_CreateFromConnectionString shall create a new STRING_HANDLE for token value string by calling STRING_new. **] */
                    else if ((token_value_string = STRING_new()) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_019: [** If the STRING_new fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Error creating value token STRING_HANDLE");
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_020: [** IoTHubServiceClientAuth_CreateFromConnectionString shall call STRING_TOKENIZER_get_next_token to get token key string. **] */
                    else if (STRING_TOKENIZER_get_next_token(tokenizer, token_key_string, ".") != 0)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_021: [** If the STRING_TOKENIZER_get_next_token fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Error reading key token STRING");
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_022: [** IoTHubServiceClientAuth_CreateFromConnectionString shall call STRING_TOKENIZER_get_next_token to get token value string. **] */
                    else if (STRING_TOKENIZER_get_next_token(tokenizer, token_value_string, "0") != 0)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_023: [** If the STRING_TOKENIZER_get_next_token fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("Error reading value token STRING");
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_024: [** IoTHubServiceClientAuth_CreateFromConnectionString shall allocate memory and copy hostName to result->hostName by calling mallocAndStrcpy_s. **] */
                    else if (mallocAndStrcpy_s(&result->hostname, hostName) != 0)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_025: [** If the mallocAndStrcpy_s fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("mallocAndStrcpy_s failed for hostName");
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_026: [** IoTHubServiceClientAuth_CreateFromConnectionString shall allocate memory and copy keyName to result->keyName by calling mallocAndStrcpy_s. **] */
                    else if (mallocAndStrcpy_s(&result->keyName, keyName) != 0)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_027: [** If the mallocAndStrcpy_s fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("mallocAndStrcpy_s failed for keyName");
                        free(result->hostname);
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_028: [** IoTHubServiceClientAuth_CreateFromConnectionString shall allocate memory and copy sharedAccessKey to result->sharedAccessKey by calling mallocAndStrcpy_s. **] */
                    else if (mallocAndStrcpy_s(&result->sharedAccessKey, sharedAccessKey) != 0)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_029: [** If the mallocAndStrcpy_s fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("mallocAndStrcpy_s failed for sharedAccessKey");
                        free(result->hostname);
                        free(result->keyName);
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_034: [** IoTHubServiceClientAuth_CreateFromConnectionString shall create C string from token key string handle by calling STRING_c_str. **] */
                    else if ((iothubName = STRING_c_str(token_key_string)) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_035 : [** If the STRING_c_str fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("STRING_c_str failed for iothubName");
                        free(result->hostname);
                        free(result->keyName);
                        free(result->sharedAccessKey);
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_036 : [** IoTHubServiceClientAuth_CreateFromConnectionString shall create C string from token value string handle by calling STRING_c_str. **] */
                    else if ((iothubSuffix = STRING_c_str(token_value_string)) == NULL)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_037 : [** If the mallocAndStrcpy_s fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("STRING_c_str failed for iothubSuffix");
                        free(result->hostname);
                        free(result->keyName);
                        free(result->sharedAccessKey);
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_030: [** IoTHubServiceClientAuth_CreateFromConnectionString shall allocate memory and copy iothubName to result->iothubName by calling mallocAndStrcpy_s. **] */
                    else if (mallocAndStrcpy_s(&result->iothubName, iothubName) != 0)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_031 : [** If the mallocAndStrcpy_s fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("mallocAndStrcpy_s failed for sharedAccessKey");
                        free(result->hostname);
                        free(result->keyName);
                        free(result->sharedAccessKey);
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_032: [** IoTHubServiceClientAuth_CreateFromConnectionString shall allocate memory and copy iothubSuffix to result->iothubSuffix by calling mallocAndStrcpy_s. **] */
                    else if (mallocAndStrcpy_s(&result->iothubSuffix, iothubSuffix) != 0)
                    {
                        /*Codes_SRS_IOTHUBSERVICECLIENT_12_033 : [** If the mallocAndStrcpy_s fails, IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return NULL. **] */
                        LogError("mallocAndStrcpy_s failed for sharedAccessKey");
                        free(result->hostname);
                        free(result->keyName);
                        free(result->sharedAccessKey);
                        free(result->iothubName);
                        free(result);
                        result = NULL;
                    }
                    /*Codes_SRS_IOTHUBSERVICECLIENT_12_006: [** If the IOTHUB_SERVICE_CLIENT_AUTH has been populated IoTHubServiceClientAuth_CreateFromConnectionString shall do clean up and return with a IOTHUB_SERVICE_CLIENT_AUTH_HANDLE to it **] */
                    STRING_delete(token_key_string);
                    STRING_delete(token_value_string);
                    STRING_delete(host_name_string);
                    STRING_TOKENIZER_destroy(tokenizer);
                    Map_Destroy(connection_string_values_map);
                }
                STRING_delete(connection_string);
            }
        }
    }
    return result;
}
コード例 #13
0
STRING_HANDLE SASToken_Create(STRING_HANDLE key, STRING_HANDLE scope, STRING_HANDLE keyName, size_t expiry)
{
    STRING_HANDLE result = NULL;
    char tokenExpirationTime[32] = { 0 };

    /*Codes_SRS_SASTOKEN_06_001: [If key is NULL then SASToken_Create shall return NULL.]*/
    /*Codes_SRS_SASTOKEN_06_003: [If scope is NULL then SASToken_Create shall return NULL.]*/
    /*Codes_SRS_SASTOKEN_06_007: [If keyName is NULL then SASToken_Create shall return NULL.]*/
    if ((key == NULL) ||
        (scope == NULL) ||
        (keyName == NULL))
    {
        LogError("Invalid Parameter to SASToken_Create. handle key: %p, handle scope: %p, handle keyName: %p\r\n", key, scope, keyName);
    }
    else
    {
        BUFFER_HANDLE decodedKey;
        /*Codes_SRS_SASTOKEN_06_029: [The key parameter is decoded from base64.]*/
        if ((decodedKey = Base64_Decoder(STRING_c_str(key))) == NULL)
        {
            /*Codes_SRS_SASTOKEN_06_030: [If there is an error in the decoding then SASToken_Create shall return NULL.]*/
            LogError("Unable to decode the key for generating the SAS.\r\n");
        }
        else
        {
            /*Codes_SRS_SASTOKEN_06_026: [If the conversion to string form fails for any reason then SASToken_Create shall return NULL.]*/
            if (size_tToString(tokenExpirationTime, sizeof(tokenExpirationTime), expiry) != 0)
            {
                LogError("For some reason converting seconds to a string failed.  No SAS can be generated.\r\n");
            }
            else
            {
                STRING_HANDLE toBeHashed = NULL;
                BUFFER_HANDLE hash = NULL;
                if (((hash = BUFFER_new()) == NULL) ||
                    ((toBeHashed = STRING_new()) == NULL) ||
                    ((result = STRING_new()) == NULL))
                {
                    LogError("Unable to allocate memory to prepare SAS token.\r\n")
                }
                else
                {
                    /*Codes_SRS_SASTOKEN_06_009: [The scope is the basis for creating a STRING_HANDLE.]*/
                    /*Codes_SRS_SASTOKEN_06_010: [A "\n" is appended to that string.]*/
                    /*Codes_SRS_SASTOKEN_06_011: [tokenExpirationTime is appended to that string.]*/
                    if ((STRING_concat_with_STRING(toBeHashed, scope) != 0) ||
                        (STRING_concat(toBeHashed, "\n") != 0) ||
                        (STRING_concat(toBeHashed, tokenExpirationTime) != 0))
                    {
                        LogError("Unable to build the input to the HMAC to prepare SAS token.\r\n");
                        STRING_delete(result);
                        result = NULL;
                    }
                    else
                    {
                        STRING_HANDLE base64Signature = NULL;
                        STRING_HANDLE urlEncodedSignature = NULL;
                        /*Codes_SRS_SASTOKEN_06_013: [If an error is returned from the HMAC256 function then NULL is returned from SASToken_Create.]*/
                        /*Codes_SRS_SASTOKEN_06_012: [An HMAC256 hash is calculated using the decodedKey, over toBeHashed.]*/
                        /*Codes_SRS_SASTOKEN_06_014: [If there are any errors from the following operations then NULL shall be returned.]*/
                        /*Codes_SRS_SASTOKEN_06_015: [The hash is base 64 encoded.]*/
                        /*Codes_SRS_SASTOKEN_06_028: [base64Signature shall be url encoded.]*/
                        /*Codes_SRS_SASTOKEN_06_016: [The string "SharedAccessSignature sr=" is the first part of the result of SASToken_Create.]*/
                        /*Codes_SRS_SASTOKEN_06_017: [The scope parameter is appended to result.]*/
                        /*Codes_SRS_SASTOKEN_06_018: [The string "&sig=" is appended to result.]*/
                        /*Codes_SRS_SASTOKEN_06_019: [The string urlEncodedSignature shall be appended to result.]*/
                        /*Codes_SRS_SASTOKEN_06_020: [The string "&se=" shall be appended to result.]*/
                        /*Codes_SRS_SASTOKEN_06_021: [tokenExpirationTime is appended to result.]*/
                        /*Codes_SRS_SASTOKEN_06_022: [The string "&skn=" is appended to result.]*/
                        /*Codes_SRS_SASTOKEN_06_023: [The argument keyName is appended to result.]*/
                        if ((HMACSHA256_ComputeHash(BUFFER_u_char(decodedKey), BUFFER_length(decodedKey), (const unsigned char*)STRING_c_str(toBeHashed), STRING_length(toBeHashed), hash) != HMACSHA256_OK) ||
                            ((base64Signature = Base64_Encode(hash)) == NULL) ||
                            ((urlEncodedSignature = URL_Encode(base64Signature)) == NULL) ||
                            (STRING_copy(result, "SharedAccessSignature sr=") != 0) ||
                            (STRING_concat_with_STRING(result, scope) != 0) ||
                            (STRING_concat(result, "&sig=") != 0) ||
                            (STRING_concat_with_STRING(result, urlEncodedSignature) != 0) ||
                            (STRING_concat(result, "&se=") != 0) ||
                            (STRING_concat(result, tokenExpirationTime) != 0) ||
                            (STRING_concat(result, "&skn=") != 0) ||
                            (STRING_concat_with_STRING(result, keyName) != 0))
                        {
                            LogError("Unable to build the SAS token.\r\n");
                            STRING_delete(result);
                            result = NULL;
                        }
                        else
                        {
                            /* everything OK */
                        }
                        STRING_delete(base64Signature);
                        STRING_delete(urlEncodedSignature);
                    }
                }
                STRING_delete(toBeHashed);
                BUFFER_delete(hash);
            }
            BUFFER_delete(decodedKey);
        }
    }

    return result;
}
コード例 #14
0
void remote_monitoring_run(void)
{
        initBme();

        srand((unsigned int)time(NULL));
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            LogInfo("Failed on serializer_init\r\n");
        }
        else
        {
            IOTHUB_CLIENT_CONFIG config;
            IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

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

            iotHubClientHandle = IoTHubClient_LL_Create(&config);
            if (iotHubClientHandle == NULL)
            {
                LogInfo("Failed on IoTHubClient_CreateFromConnectionString\r\n");
            }
            else
            {
#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

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

                    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, thermostat) != IOTHUB_CLIENT_OK)
                    {
                        LogInfo("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)
                        {
                            LogInfo("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)
                            {
                                LogInfo("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)
                                {
                                    LogInfo("Failed serializing\r\n");
                                }
                                else
                                {
                                    sendMessage(iotHubClientHandle, buffer, bufferSize);
                                }

                            }

                            STRING_delete(commandsMetadata);
                        }

                        thermostat->DeviceId = (char*)deviceId;
                        int sendCycle = 10;
                        int currentCycle = 0;
                        while (1)
                        {
                            if(currentCycle >= sendCycle) {
                                float Temp;
                                float Humi;
                                getNextSample(&Temp, &Humi);
                                //thermostat->Temperature = 50 + (rand() % 10 + 2);
                                thermostat->Temperature = (int)round(Temp);
                                thermostat->ExternalTemperature = 55 + (rand() % 5 + 2);
                                //thermostat->Humidity = 50 + (rand() % 8 + 2);
                                thermostat->Humidity = (int)round(Humi);
                                currentCycle = 0;
                                unsigned char*buffer;
                                size_t bufferSize;

                                LogInfo("Sending sensor value Temperature = %d, Humidity = %d\r\n", thermostat->Temperature, thermostat->Humidity);

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

                            IoTHubClient_LL_DoWork(iotHubClientHandle);
                            ThreadAPI_Sleep(100);
                            currentCycle++;
                        }
                    }

                    DESTROY_MODEL_INSTANCE(thermostat);
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle);
            }
            serializer_deinit();

    }
}