Example #1
0
Void Ducati_AppTask (UArg arg1, UArg arg2)
{
	FCSettings_init();
	Diags_setMask(FCSETTINGS_MODNAME"+12345678LEXAIZFS");
	CESettings_init();
	Diags_setMask(CESETTINGS_MODNAME"+12345678LEXAIZFS");
//	Diags_setMask("ti.sdo.rcm.RcmServer-12");
//	Diags_setMask("ti.sysbios.utils.Load-4");

    init_IVAHDFrwk();
    HDVICP_Reset(NULL, NULL);
    platform_init();

    /* how do we know when to unload.. */
    while (1) {
        Task_sleep(0x7fffffff);
    }

    /*The test cases will run in this task's context in the init call.
    Once init returns, testcases have exited so do deinit*/
    platform_deinit();

    exit_IVAHDFrwk();

    System_exit(0);
}
void receive_cloud_to_device_message()
{
    if (platform_init() != 0)
    {
        printf("Failed initializing platform.\r\n");
        return;
    }

    IOTHUB_CLIENT_HANDLE iothub_client_handle = IoTHubClient_CreateFromConnectionString(connection_string, AMQP_Protocol);
    if (iothub_client_handle == nullptr)
    {
        printf("Failed on IoTHubClient_Create\r\n");
    }
    else
    {
        std::promise<void> completion;
        if (IoTHubClient_SetMessageCallback(iothub_client_handle, receive_callback, &completion) != IOTHUB_CLIENT_OK)
        {
            printf("unable to IoTHubClient_SetMessageCallback\r\n");
        }

        completion.get_future().wait();
        IoTHubClient_Destroy(iothub_client_handle);
    }

    platform_deinit();
}
Example #3
0
Void Dsp_AppTask (UArg arg1, UArg arg2)
{
  OMX_ERRORTYPE eError = OMX_ErrorNone;
  //TIMM_OSAL_ERRORTYPE osalError = TIMM_OSAL_ERR_NONE;

  /*--------------------------------------------------------------------------*/
  /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  /* Initiailize the system. The initialization can include driver, syslink */
  /* cache.  */
  /*--------------------------------------------------------------------------*/
  Log_print0 (Diags_USER1,"DSP: In Dsp_AppTask");
  platform_init ();
  Log_print0 (Diags_USER1,"DSP: Platform Initialized");

  while (TRUE)
  {
    Task_sleep (DSP_APP_TASK_SLEEP_DURATION);
  }

  /*--------------------------------------------------------------------------*/
  /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  /* UnInitiailize the system.  */
  /*--------------------------------------------------------------------------*/
  platform_deinit ();
  Log_print0 (Diags_USER1,"DSP: Platform De-Initialized");

  Log_print0 (Diags_USER1,"DSP: Exiting the system");
  System_exit (0);

//EXIT:
  if (eError != OMX_ErrorNone)
  {
    Log_print1 (Diags_USER1,"Error in executing app. Failed code:%d", eError);
  }
}                               /* Dsp_AppTask */
Example #4
0
int main(int argc, char* argv[])
{
    size_t seconds = TEST_SECONDS;

    METRIC_AZURE_INFO metric_info;
    process_arguments(argc, (const char**)argv, &metric_info);

    if (platform_init() == 0)
    {
        gballoc_init();

        if (ExecuteIotHubTest(&metric_info, seconds) != 0)
        {
            (void)printf("Mqtt run failed\r\n");
        }
        gballoc_deinit();
        platform_deinit();
    }
    else
    {
        (void)printf("Platform_Init Failed\r\n");
    }

    (void)printf("Press any key to exit: ");
    (int)getchar();
    return 0;
}
void mqtt_client_sample_run()
{
    if (platform_init() != 0)
    {
        PrintLogFunction(LOG_LINE, "platform_init failed");
    }
    else
    {
        MQTT_CLIENT_HANDLE mqttHandle = mqtt_client_init(OnRecvCallback, OnOperationComplete, NULL, PrintLogFunction);
        if (mqttHandle == NULL)
        {
            PrintLogFunction(LOG_LINE, "mqtt_client_init failed");
        }
        else
        {
            MQTT_CLIENT_OPTIONS options = { 0 };
            options.clientId = "azureiotclient";
            options.willMessage = NULL;
            options.username = NULL;
            options.password = NULL;
            options.keepAliveInterval = 10;
            options.useCleanSession = true;
            options.qualityOfServiceValue = DELIVER_AT_MOST_ONCE;

            SOCKETIO_CONFIG config = {"test.mosquitto.org", PORT_NUM_UNENCRYPTED, NULL};

            XIO_HANDLE xio = xio_create(socketio_get_interface_description(), &config, PrintLogFunction);
            if (xio == NULL)
            {
                PrintLogFunction(LOG_LINE, "xio_create failed");
            }
            else
            {
                if (mqtt_client_connect(mqttHandle, xio, &options) != 0)
                {
                    PrintLogFunction(LOG_LINE, "mqtt_client_connect failed");
                }
                else
                {
                    do
                    {
                        mqtt_client_dowork(mqttHandle);
                    } while (g_continue);
                }
                xio_close(xio, OnCloseComplete, NULL);
            }
            mqtt_client_deinit(mqttHandle);
        }
        platform_deinit();
    }

#ifdef _CRT_DBG_MAP_ALLOC
    _CrtDumpMemoryLeaks();
#endif
}
void raspberrypi_photoupload_run(void)
{
	IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
	time_t now;
	struct tm *local;
	char* photoFileName;
	const unsigned char* photoContent;
	long contentLength;

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

		if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol)) == NULL)
		{
			(void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
		}
		else
		{
			printf("Connected to IoT Hub\r\n");
			while (true) {
				photoContent = take_photo(&contentLength);
				if (photoContent != NULL) {
					now = time(NULL);
					local = localtime(&now);

					photoFileName = (char*)malloc(strlen(deviceId) + 32);
					sprintf(photoFileName, "%s_%04d_%02d_%02d_%02d_%02d_%02d_Pro.jpg", deviceId, local->tm_year+1900, local->tm_mon+1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec);
					printf("Try to upload as %s size is %d\r\n", photoFileName, contentLength);
					if (IoTHubClient_LL_UploadToBlob(iotHubClientHandle, photoFileName, photoContent, contentLength) != IOTHUB_CLIENT_OK)
					{
						printf("Failed to upload picture\r\n");
					}
					else
					{
						printf("Uploaded %s %d bytes.\r\n", photoFileName, contentLength);
					}
					free((void*)photoFileName);
					free((void*)photoContent);
				}
				else {
					printf("Failed to take a picture\r\n");
				}
				sleep(duration);
			}
			IoTHubClient_LL_Destroy(iotHubClientHandle);
		}
		platform_deinit();
	}
}
int main(void)
{
    (void)platform_init();

    (void)printf("Calling IoTHubServiceClientAuth_CreateFromConnectionString with connectionString\n");
    IOTHUB_SERVICE_CLIENT_AUTH_HANDLE iotHubServiceClientHandle = IoTHubServiceClientAuth_CreateFromConnectionString(connectionString);
    if (iotHubServiceClientHandle == NULL)
    {
        (void)printf("IoTHubServiceClientAuth_CreateFromConnectionString failed\n");
    }
    else
    {
        IOTHUB_SERVICE_CLIENT_DEVICE_METHOD_HANDLE serviceClientDeviceMethodHandle = IoTHubDeviceMethod_Create(iotHubServiceClientHandle);
        if (serviceClientDeviceMethodHandle == NULL)
        {
            (void)printf("IoTHubDeviceMethod_Create failed\n");
        }
        else
        {
            (void)printf("Invoking method %s on device...\n", methodName);

            int responseStatus;
            unsigned char* responsePayload;
            size_t responsePayloadSize;
            IOTHUB_DEVICE_METHOD_RESULT invokeResult = IoTHubDeviceMethod_Invoke(serviceClientDeviceMethodHandle, deviceId, methodName, methodPayload, timeout, &responseStatus, &responsePayload, &responsePayloadSize);
            if (invokeResult == IOTHUB_DEVICE_METHOD_OK)
            {
                printf("\r\nDevice Method called\r\n");
                printf("Device Method name:    %s\r\n", methodName);
                printf("Device Method payload: %s\r\n", methodPayload);

                printf("\r\nResponse status: %d\r\n", responseStatus);
                printf("Response payload: %.*s\r\n", (int)responsePayloadSize, (const char*)responsePayload);

                free(responsePayload);
            }
            else
            {
                (void)printf("IoTHubDeviceMethod_Invoke failed with result: %d\n", invokeResult);
            }

            (void)printf("Calling IoTHubDeviceMethod_Destroy...\n");
            IoTHubDeviceMethod_Destroy(serviceClientDeviceMethodHandle);
        }

        (void)printf("Calling IoTHubServiceClientAuth_Destroy...\n");
        IoTHubServiceClientAuth_Destroy(iotHubServiceClientHandle);
    }
    platform_deinit();
}
Example #8
0
int main(void)
{
    int result;
    (void)printf("Initializing mbed specific things...\r\n");

    if ((result = platform_init()) != 0)
    {
        (void)printf("Error initializing the platform: %d\r\n",result);
        return -1;
    }

    simplesample_http_run();

    platform_deinit();

    return 0;
}
void send_device_to_cloud_message()
{
    if (platform_init() != 0)
    {
        printf("Failed initializing platform.\r\n");
        return;
    }

    // Setup IoTHub client configuration
    IOTHUB_CLIENT_HANDLE iothub_client_handle = IoTHubClient_CreateFromConnectionString(connection_string, AMQP_Protocol);
    if (iothub_client_handle == nullptr)
    {
        printf("Failed on IoTHubClient_Create\r\n");
    }
    else
    {
        std::string message = "Hello, Cloud from C++!";

        IOTHUB_MESSAGE_HANDLE message_handle = IoTHubMessage_CreateFromByteArray((const unsigned char*)message.data(), message.size());
        if (message_handle == nullptr)
        {
            printf("unable to create a new IoTHubMessage\n");
        }
        else
        {
            callback_parameter callback_param = { message };
            if (IoTHubClient_SendEventAsync(iothub_client_handle, message_handle, send_callback, &callback_param) != IOTHUB_CLIENT_OK)
            {
                printf("failed to hand over the message to IoTHubClient");
            }
            else
            {
                printf("IoTHubClient accepted the message for delivery\n");
            }

            IoTHubMessage_Destroy(message_handle);
            callback_param.completion.get_future().wait();
        }

        printf("Done!\n");
    }
    IoTHubClient_Destroy(iothub_client_handle);

    platform_deinit();
}
Example #10
0
int main(int argc, char*argv[])
{
    // create glib loop and register a ctrl+c handler
    GMainLoop* loop = g_main_loop_new(NULL, FALSE);
    handle_control_c(loop);

    int result;
    if (validate_args(argc, argv) == false)
    {
        result = 1;
    }
    else
    {
        if(platform_init() == 0)
        {
            char *json_path = argv[1];
            GATEWAY_HANDLE gateway = Gateway_CreateFromJson(json_path);
            if(gateway == NULL)
            {
                LogError("An error ocurred while creating the gateway.");
                result = 1;
            }
            else
            {
                result = 0;
                printf("Gateway is running.\r\n");
                        
                // run the glib loop
                g_main_loop_run(loop);

                printf("Gateway is quitting\r\n");
                Gateway_Destroy(gateway);
            }
            platform_deinit();
        }
        else
        {
            LogError("Failed to initialize the platform");
            result = 1;
        }
    }
    
    return result;
}
int main(int argc, char** argv)
{
    (void)argc, (void)argv;

    if (platform_init() != 0)
    {
        LogError("Cannot initialize platform.\n");
    }
    else
    {
        show_platform_info();
        show_sastoken_example();
#ifdef USE_HTTP
        http_examples();
        test_http_proxy_io();
#endif
        platform_deinit();
    }
    return 0;
}
static void __exit ccci_exit(void)
{
	unsigned int md_num = 1, i;

	//1. Get Support MD nmmber
	md_num = get_md_sys_max_num();

	//2. Init ccci driver for each modem
	for(i=0; i<md_num; i++)
	{
		// 3.1 de-Init virtual char dev
		ccci_vir_chrdev_exit(i);
		// 3.2 de-Init ccmni dev
		ccmni_exit(i);
		// 3.3 de-Init fs dev
		ccci_fs_exit(i);
		// 3.4 de-Init rpc dev
		ccci_rpc_exit(i);
		// 3.5 de-Init ipc dev
		ccci_ipc_exit(i);
		// 3.6 de-Init tty dev
		ccci_tty_exit(i);
		// 3.7 de-Init char dev
		ccci_chrdev_exit(i);
		// 3.8 De-Init md ctrl
		ccci_md_ctrl_exit(i);
		// 3.9 de-Init ccci logical layer
		ccci_logic_layer_exit(i);
		// 3.10 de-Init ccci platform layer
		platform_deinit(i);
		// 3.11 de-Init ccci device node
		ccci_dev_node_exit(i);
	}
	// 3.12 release ccci class
	release_ccci_dev_node();
	// 3.13 de-Init ccci helper grobal data
	ccci_helper_exit();
}
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;
    double minTemperature = 20.0;
    double minHumidity = 60.0;
    double temperature = 0;
    double humidity = 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
    {
        // For mbed add the certificate information
        if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
        {
            printf("failure to set option \"TrustedCerts\"\r\n");
        }

        /* Setting Message call back, so we can receive Commands. */
        if (IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
        {
            (void)printf("ERROR: IoTHubClient_SetMessageCallback..........FAILED!\r\n");
        }
        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++)
            {
                temperature = minTemperature + (rand() % 10);
                humidity = minHumidity +  (rand() % 20);
                sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":\"myFirstDevice\",\"windSpeed\":%.2f,\"temperature\":%.2f,\"humidity\":%.2f}", avgWindSpeed + (rand() % 4 + 2), temperature, humidity);
                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 = (int)i;
                    
                    MAP_HANDLE propMap = IoTHubMessage_Properties(messages[i].messageHandle);
                    (void)sprintf_s(propText, sizeof(propText), temperature > 28 ? "true" : "false");
                    if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK)
                    {
                        (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
                    }

                    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();
    }
}
int main()
{
    int result;

    if (platform_init() == 0 && initialize_hsm_system() == 0)
    {
        HSM_CLIENT_HANDLE hsm_handle;
        if ((hsm_handle = hsm_client_riot_create()) == NULL)
        {
            (void)printf("Failure getting common name\r\n");
            result = __LINE__;
        }
        else
        {
            char* enroll_type = get_user_input("Would you like to do Individual (i) or Group (g) enrollments: ", 1);
            if (enroll_type != NULL)
            {
                if (enroll_type[0] == 'g' || enroll_type[0] == 'G')
                {
                    if (ca_root_certificate_info(hsm_handle) != 0)
                    {
                        result = __LINE__;
                    }
                    else
                    {
                        result = 0;
                    }
                }
                else
                {
                    if (alias_certificate_info(hsm_handle) != 0)
                    {
                        result = __LINE__;
                    }
                    else
                    {
                        result = 0;
                    }
                }
                free(enroll_type);
            }
            else
            {
                (void)printf("Invalid option specified\r\n");
                result = __LINE__;
            }
            hsm_client_riot_destroy(hsm_handle);
        }
        deinitialize_hsm_system();
        platform_deinit();
    }
    else
    {
        (void)printf("Failed calling platform_init\r\n");
        result = __LINE__;
    }

    (void)printf("Press any key to continue:\r\n");
    (void)getchar();
    return result;
}
void iothub_client_sample_mqtt_run(void)
{
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

    EVENT_INSTANCE messages[MESSAGE_COUNT];

    g_continueRunning = true;
    srand((unsigned int)time(NULL));
    double avgWindSpeed = 10.0;
    
    callbackCounter = 0;
    int receiveContext = 0;

    if (platform_init() != 0)
    {
        (void)printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol)) == NULL)
        {
            (void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
        }
        else
        {
            bool traceOn = true;
            IoTHubClient_LL_SetOption(iotHubClientHandle, "logtrace", &traceOn);

#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_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
            {
                (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n");
            }
            else
            {
                (void)printf("IoTHubClient_LL_SetMessageCallback...successful.\r\n");

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

                            if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messages[iterator].messageHandle, SendConfirmationCallback, &messages[iterator]) != IOTHUB_CLIENT_OK)
                            {
                                (void)printf("ERROR: IoTHubClient_LL_SendEventAsync..........FAILED!\r\n");
                            }
                            else
                            {
                                (void)printf("IoTHubClient_LL_SendEventAsync accepted message [%d] for transmission to IoT Hub.\r\n", (int)iterator);
                            }
                        }
                    }
                    IoTHubClient_LL_DoWork(iotHubClientHandle);
                    ThreadAPI_Sleep(1);

                    iterator++;
                } while (g_continueRunning);

                (void)printf("iothub_client_sample_mqtt has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM);
                for (size_t index = 0; index < DOWORK_LOOP_NUM; index++)
                {
                    IoTHubClient_LL_DoWork(iotHubClientHandle);
                    ThreadAPI_Sleep(1);
                }
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        platform_deinit();
    }
}
void iothub_client_sample_amqp_run(void)
{
    TRANSPORT_HANDLE transport_handle;
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle1;
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle2;

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

    g_continueRunning = true;

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

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

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

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

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

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

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

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

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

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

                        iterator++;
                    } while (g_continueRunning);

                    (void)printf("iothub_client_sample_mqtt has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM);
                    for (size_t index = 0; index < DOWORK_LOOP_NUM; index++)
                    {
                        IoTHubClient_LL_DoWork(iotHubClientHandle1);
                        ThreadAPI_Sleep(1);
                    }
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle1);
                IoTHubClient_LL_Destroy(iotHubClientHandle2);
            }
            IoTHubTransport_Destroy(transport_handle);
        }
        platform_deinit();
    }
}
void simplesample_mqtt_run(void)
{
    if (platform_init() != 0)
    {
        (void)printf("Failed to initialize platform.\r\n");
    }
    else
    {
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            (void)printf("Failed on serializer_init\r\n");
        }
        else
        {
            IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
            srand((unsigned int)time(NULL));
            int avgWindSpeed = 10;

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

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

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

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

                    DESTROY_MODEL_INSTANCE(myWeather);
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_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();
    }
}
static int __init ccci_init(void)
{
	int ret = CCCI_ERR_MODULE_INIT_OK;
	unsigned int md_num = 1;	
	int i = 0;
	int md_en[MAX_MD_NUM] = {0};
	
	//1. Get and set Support MD nmmber
	md_num = get_md_sys_max_num();
	set_md_sys_max_num(md_num);

	//2. Get and set MD enable table
	for(i = 0; i < md_num; i++) {
		if(get_modem_is_enabled(i)){
			md_en[i] = 1;
			set_md_enable(i, 1);
		} else {
			md_en[i] = 0;
			set_md_enable(i, 0);
		}
	}

#ifdef ENABLE_CCCI_DRV_BUILDIN
CCCI_MSG("ccci_init: device_initcall_sync\n");
#else  // MODULE
CCCI_MSG("ccci_init: module_init\n");
#endif

	//3. Init ccci device table	
    ret = init_ccci_dev_node();
	if(ret) {
		CCCI_MSG("init_ccci_dev_node fail: %d\n", ret);
		ret = -CCCI_ERR_INIT_DEV_NODE_FAIL;
		goto out;
	}

	//4. Init ccci driver for each modem
	for(i = 0; i < md_num; i++)
	{
		if(md_en[i] == 0) {
			CCCI_MSG_INF(i, "cci", "md initial fail: md%d is not enabled\n", i+1);
			continue;
		}
		
		// 4.0 Init platform support function
		ret = platform_init(i, !md_en[i]);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "platform_init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_PLATFORM_FAIL;
			goto platform_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "platform_init OK!\n");
		}

		// Make ccci device node
		ret = mk_ccci_dev_node(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "mk_ccci_dev_node fail: %d\n", ret);
			ret = -CCCI_ERR_MK_DEV_NODE_FAIL;
			goto mk_node_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "mk_ccci_dev_node OK!\n");
		}

		// Statistics init
		statistics_init(i);

		// 4.1 Init ccci logical layer
		ret = ccci_logic_layer_init(i);
		if(ret) {
			CCCI_MSG_INF(i, "cci", "ccci logical layer init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_LOGIC_LAYER_FAIL;
			goto logic_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_logic_layer_init OK!\n");
		}
		
		// 4.2 Init md ctrl
		ret = ccci_md_ctrl_init(i);
		if(ret) {
			CCCI_MSG_INF(i, "cci", "ccci md ctrl init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_MD_CTRL_FAIL;
			goto mdctl_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_md_ctrl_init OK!\n");
		}
		
		// 4.3 Init char dev
		ret = ccci_chrdev_init(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "ccci_chrdev_init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_CHAR_DEV_FAIL;
			goto char_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_chrdev_init OK!\n");
		}
		
		// 4.4 Init tty dev
		ret = ccci_tty_init(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "ccci_tty_init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_TTY_FAIL;
			goto tty_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_tty_init OK!\n");
		}
		
		// 4.5 Init ipc dev
		ret = ccci_ipc_init(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "ccci_ipc_init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_IPC_FAIL;
			goto ipc_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_ipc_init OK!\n");
		}
		
		// 4.6 Init rpc dev
		ret = ccci_rpc_init(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "ccci_rpc_init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_RPC_FAIL;
			goto rpc_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_rpc_init OK!\n");
		}
		
		// 4.7 Init fs dev
		ret = ccci_fs_init(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "ccci_fs_init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_FS_FAIL;
			goto fs_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_fs_init OK!\n");
		}
		
		// 4.8 Init ccmni dev
		ret = ccmni_init(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "ccmni_init fail: %d\n", ret);
			ret = -CCCI_ERR_INIT_CCMNI_FAIL;
			goto ccmni_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccmni_init OK!\n");
		}
		
		// 4.9 Init pmic dev
		// ....
		
		// 4.10 Init vir char dev
		ret = ccci_vir_chrdev_init(i);
		if (ret) {
			CCCI_MSG_INF(i, "cci", "ccci_vir_chrdev_init fail: %d\n", ret);		
			ret = -CCCI_ERR_INIT_VIR_CHAR_FAIL;
			goto virchar_out;
		} else {
			CCCI_DBG_MSG(i, "cci", "ccci_vir_chrdev_init OK!\n");
		}
		
		CCCI_MSG_INF(i, "cci", "md initial OK!\n");
	}

	// 5. Init common section
	ret = ccci_md_ctrl_common_init();
	if (ret == 0)
		goto out;
	else {
		i = md_num-1;
		CCCI_MSG_INF(i, "cci", "ccci_md_ctrl_common_init fail: %d\n", ret);
	}

virchar_out:
	ccci_vir_chrdev_exit(i);
	
ccmni_out:
	ccmni_exit(i);

fs_out:
	ccci_fs_exit(i);
	
rpc_out:
	ccci_rpc_exit(i);

ipc_out:
	ccci_ipc_exit(i);
	
tty_out:
	ccci_tty_exit(i);
	
char_out:
	ccci_chrdev_exit(i);

mdctl_out:
	ccci_md_ctrl_exit(i);
	
logic_out:
	ccci_logic_layer_exit(i);
	
platform_out:
	platform_deinit(i);
	
mk_node_out:
	ccci_dev_node_exit(i);
	
out:
	if ((i == MD_SYS2) && (md_num > MD_SYS2)) {
		ccci_vir_chrdev_exit(MD_SYS1);
		ccmni_exit(MD_SYS1);
		ccci_fs_exit(MD_SYS1);
		ccci_rpc_exit(MD_SYS1);
		ccci_ipc_exit(MD_SYS1);
		ccci_tty_exit(MD_SYS1);
		ccci_chrdev_exit(MD_SYS1);
		ccci_md_ctrl_exit(MD_SYS1);
		ccci_logic_layer_exit(MD_SYS1);
		platform_deinit(MD_SYS1);
		ccci_dev_node_exit(MD_SYS1);
	}
	
	if (ret == CCCI_ERR_MODULE_INIT_OK)
		CCCI_MSG("ccci module init OK\n");
	else {		
		release_ccci_dev_node();
		ccci_helper_exit();
		CCCI_MSG("ccci module init fail: %d\n", ret);
	}
	
	return ret;
}
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;
}
Example #21
0
int main(int argc, char** argv)
{
	int result;

    (void)argc, argv;
    amqpalloc_set_memory_tracing_enabled(true);

	if (platform_init() != 0)
	{
		result = -1;
	}
	else
	{
		CONNECTION_HANDLE connection;
		SESSION_HANDLE session;
		LINK_HANDLE link;
		MESSAGE_SENDER_HANDLE message_sender;
		MESSAGE_HANDLE message;

		size_t last_memory_used = 0;

		/* create socket IO */
		XIO_HANDLE socket_io;

		SOCKETIO_CONFIG socketio_config = { "localhost", 5672, NULL };
		socket_io = xio_create(socketio_get_interface_description(), &socketio_config);

		/* create the connection, session and link */
		connection = connection_create(socket_io, "localhost", "some", NULL, NULL);
		session = session_create(connection, NULL, NULL);
		session_set_incoming_window(session, 2147483647);
		session_set_outgoing_window(session, 65536);

		AMQP_VALUE source = messaging_create_source("ingress");
		AMQP_VALUE target = messaging_create_target("localhost/ingress");
		link = link_create(session, "sender-link", role_sender, source, target);
		link_set_snd_settle_mode(link, sender_settle_mode_settled);
		(void)link_set_max_message_size(link, 65536);

		amqpvalue_destroy(source);
		amqpvalue_destroy(target);

		message = message_create();
		unsigned char hello[] = { 'H', 'e', 'l', 'l', 'o' };
		BINARY_DATA binary_data;
        binary_data.bytes = hello;
        binary_data.length = sizeof(hello);
		message_add_body_amqp_data(message, binary_data);

		/* create a message sender */
		message_sender = messagesender_create(link, NULL, NULL);
		if (messagesender_open(message_sender) == 0)
		{
			uint32_t i;

#if _WIN32
			unsigned long startTime = (unsigned long)GetTickCount64();
#endif

			for (i = 0; i < msg_count; i++)
			{
				(void)messagesender_send(message_sender, message, on_message_send_complete, message);
			}

			message_destroy(message);

			while (true)
			{
				size_t current_memory_used;
				size_t maximum_memory_used;
				connection_dowork(connection);

				current_memory_used = amqpalloc_get_current_memory_used();
				maximum_memory_used = amqpalloc_get_maximum_memory_used();

				if (current_memory_used != last_memory_used)
				{
					(void)printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used);
					last_memory_used = current_memory_used;
				}

				if (sent_messages == msg_count)
				{
					break;
				}
			}

#if _WIN32
			unsigned long endTime = (unsigned long)GetTickCount64();

			(void)printf("Send %zu messages in %lu ms: %.02f msgs/sec\r\n", msg_count, (endTime - startTime), (float)msg_count / ((float)(endTime - startTime) / 1000));
#endif
		}

		messagesender_destroy(message_sender);
		link_destroy(link);
		session_destroy(session);
		connection_destroy(connection);
		xio_destroy(socket_io);
		platform_deinit();

		(void)printf("Max memory usage:%lu\r\n", (unsigned long)amqpalloc_get_maximum_memory_used());
		(void)printf("Current memory usage:%lu\r\n", (unsigned long)amqpalloc_get_current_memory_used());

		result = 0;
	}

#ifdef _CRTDBG_MAP_ALLOC
	_CrtDumpMemoryLeaks();
#endif

	return result;
}
Example #22
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();
    }
}
void devicemethod_simplesample_run(void)
{
    if (platform_init() != 0)
    {
        (void)printf("Failed to initialize platform.\r\n");
    }
    else
    {
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            (void)printf("Failed on serializer_init\r\n");
        }
        else
        {
            IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
            srand((unsigned int)time(NULL));
            int avgWindSpeed = 10;

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


                ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
                if (myWeather == NULL)
                {
                    (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
                }
                else if (IoTHubClient_LL_SetDeviceMethodCallback(iotHubClientHandle, DeviceMethodCallback, myWeather) != IOTHUB_CLIENT_OK)
                {
                    (void)printf("Failed on IoTHubClient_SetDeviceMethodCallback\r\n");
                }
                else
                {
                    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
                    {
                        printf("unable to IoTHubClient_SetMessageCallback\r\n");
                    }
                    else
                    {
                        myWeather->DeviceId = "myWeatherStation";
                        myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
                        {
                            unsigned char* destination;
                            size_t destinationSize;
                            if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != CODEFIRST_OK)
                            {
                                (void)printf("Failed to serialize\r\n");
                            }
                            else
                            {
                                sendMessage(iotHubClientHandle, destination, destinationSize);
                                free(destination);
                            }
                        }

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

                    DESTROY_MODEL_INSTANCE(myWeather);
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_deinit();
    }
}
Example #24
0
int main(int argc, char** argv)
{
	int result;
	XIO_HANDLE sasl_io = NULL;
	CONNECTION_HANDLE connection = NULL;
	SESSION_HANDLE session = NULL;
	LINK_HANDLE link = NULL;
	MESSAGE_RECEIVER_HANDLE message_receiver = NULL;

	amqpalloc_set_memory_tracing_enabled(true);

	if (platform_init() != 0)
	{
		result = -1;
	}
	else
	{
		size_t last_memory_used = 0;

		/* create SASL plain handler */
		SASL_PLAIN_CONFIG sasl_plain_config = { EH_KEY_NAME, EH_KEY, NULL };
		SASL_MECHANISM_HANDLE sasl_mechanism_handle = saslmechanism_create(saslplain_get_interface(), &sasl_plain_config);
		XIO_HANDLE tls_io;

		/* create the TLS IO */
        TLSIO_CONFIG tls_io_config = { EH_HOST, 5671 };
		const IO_INTERFACE_DESCRIPTION* tlsio_interface = platform_get_default_tlsio();
		tls_io = xio_create(tlsio_interface, &tls_io_config, NULL);

		/* create the SASL client IO using the TLS IO */
		SASLCLIENTIO_CONFIG sasl_io_config = { tls_io, sasl_mechanism_handle };
		sasl_io = xio_create(saslclientio_get_interface_description(), &sasl_io_config, NULL);

		/* create the connection, session and link */
		connection = connection_create(sasl_io, EH_HOST, "whatever", NULL, NULL);
		session = session_create(connection, NULL, NULL);

		/* set incoming window to 100 for the session */
		session_set_incoming_window(session, 100);
		AMQP_VALUE source = messaging_create_source("amqps://" EH_HOST "/ingress/ConsumerGroups/$Default/Partitions/0");
		AMQP_VALUE target = messaging_create_target("ingress-rx");
		link = link_create(session, "receiver-link", role_receiver, source, target);
		link_set_rcv_settle_mode(link, receiver_settle_mode_first);
		amqpvalue_destroy(source);
		amqpvalue_destroy(target);

		/* create a message receiver */
		message_receiver = messagereceiver_create(link, NULL, NULL);
		if ((message_receiver == NULL) ||
			(messagereceiver_open(message_receiver, on_message_received, message_receiver) != 0))
		{
			result = -1;
		}
		else
		{
			while (true)
			{
				size_t current_memory_used;
				size_t maximum_memory_used;
				connection_dowork(connection);

				current_memory_used = amqpalloc_get_current_memory_used();
				maximum_memory_used = amqpalloc_get_maximum_memory_used();

				if (current_memory_used != last_memory_used)
				{
					printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used);
					last_memory_used = current_memory_used;
				}
			}

			result = 0;
		}

		messagereceiver_destroy(message_receiver);
		link_destroy(link);
		session_destroy(session);
		connection_destroy(connection);
		platform_deinit();

		printf("Max memory usage:%lu\r\n", (unsigned long)amqpalloc_get_maximum_memory_used());
		printf("Current memory usage:%lu\r\n", (unsigned long)amqpalloc_get_current_memory_used());

#ifdef _CRTDBG_MAP_ALLOC
		_CrtDumpMemoryLeaks();
#endif
	}

	return result;
}
void iothub_client_sample_http_run(void)
{
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

    EVENT_INSTANCE messages[MESSAGE_COUNT];
    double avgWindSpeed = 10.0;
    int receiveContext = 0;
    g_continueRunning = true;

    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 x509...\r\n");

        if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol)) == NULL)
        {
            (void)printf("ERROR: iotHubClientHandle 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;
            if (IoTHubClient_LL_SetOption(iotHubClientHandle, "timeout", &timeout) != IOTHUB_CLIENT_OK)
            {
                printf("failure to set option \"timeout\"\r\n");
            }

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

            /*this brings in x509 privateKey and certificate*/
            if (
                (IoTHubClient_LL_SetOption(iotHubClientHandle, "x509certificate", x509certificate) != IOTHUB_CLIENT_OK) ||
                (IoTHubClient_LL_SetOption(iotHubClientHandle, "x509privatekey", x509privatekey) != IOTHUB_CLIENT_OK)
                )
            {
                printf("failure to set options for x509, aborting\r\n");
            }
            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_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
                {
                    (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n");
                }
                else
                {
                    (void)printf("IoTHubClient_LL_SetMessageCallback...successful.\r\n");

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

                                messages[iterator].messageTrackingId = iterator;

                                propMap = IoTHubMessage_Properties(messages[iterator].messageHandle);
                                sprintf_s(propText, sizeof(propText), "PropMsg_%d", iterator);
                                if (Map_AddOrUpdate(propMap, "PropName", propText) != MAP_OK)
                                {
                                    (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
                                }

                                if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messages[iterator].messageHandle, SendConfirmationCallback, &messages[iterator]) != IOTHUB_CLIENT_OK)
                                {
                                    (void)printf("ERROR: IoTHubClient_LL_SendEventAsync..........FAILED!\r\n");
                                }
                                else
                                {
                                    (void)printf("IoTHubClient_LL_SendEventAsync accepted message [%zu] for transmission to IoT Hub.\r\n", iterator);
                                }

                            }
                        }
                        IoTHubClient_LL_DoWork(iotHubClientHandle);
                        ThreadAPI_Sleep(1);

                        iterator++;
                    } while (g_continueRunning);

                    (void)printf("iothub_client_sample_mqtt has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM);
                    for (size_t index = 0; index < DOWORK_LOOP_NUM; index++)
                    {
                        IoTHubClient_LL_DoWork(iotHubClientHandle);
                        ThreadAPI_Sleep(1);
                    }
                }
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        platform_deinit();
    }
}
void iothub_messaging_ll_sample_run(void)
{
    xlogging_set_log_function(consolelogger_log);

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

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

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

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

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

                        IoTHubMessaging_LL_Close(iotHubMessagingHandle);
                    }
                }
                (void)printf("Calling IoTHubMessaging_LL_Destroy...\n");
                IoTHubMessaging_LL_Destroy(iotHubMessagingHandle);
            }
            (void)printf("Calling IoTHubServiceClientAuth_Destroy...\n");
            IoTHubServiceClientAuth_Destroy(iotHubServiceClientHandle);
        }
        platform_deinit();
    }
}
void iothub_client_sample_mqtt_run(void)
{
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

    EVENT_INSTANCE messages[MESSAGE_COUNT];

    continueRunning = true;
    srand((unsigned int)time(NULL));
    double avgWindSpeed = 10.0;
    
    callbackCounter = 0;
    int receiveContext = 0;

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

    if (platform_init() != 0)
    {
        (void)printf("ERROR: platform_init fails!\r\n");
    }
    else
    {
        if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol)) == NULL)
        {
            (void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
        }
        else
        {
            bool traceOn = true;
            IoTHubClient_LL_SetOption(iotHubClientHandle, "logtrace", &traceOn);

            /* Setting Message call back, so we can receive Commands. */
            if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
            {
                (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n");
            }
            else
            {
                (void)printf("IoTHubClient_LL_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;

                        if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messages[i].messageHandle, SendConfirmationCallback, &messages[i]) != IOTHUB_CLIENT_OK)
                        {
                            (void)printf("ERROR: IoTHubClient_LL_SendEventAsync..........FAILED!\r\n");
                        }
                        else
                        {
                            (void)printf("IoTHubClient_LL_SendEventAsync accepted message [%d] for transmission to IoT Hub.\r\n", (int)i);
                        }

                    }
                }
            }

            /* Wait for Commands. */
            while (continueRunning)
            {
                IoTHubClient_LL_DoWork(iotHubClientHandle);
                ThreadAPI_Sleep(1);
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        platform_deinit();
    }
}
Example #28
0
int main(int argc, char *argv[])
{
    if(argc <= 1)
        return print_usage(argv[0]);

    main_argc = argc;
    main_argv = argv;

    if(!strcmp(argv[1], "-c"))
    {
        if(argc <= 3)
            return print_usage(argv[0]);

        char *net_addr = argv[2];
        int net_port = atoi(argv[3]);
        printf("TODO: connect to \"%s\" port %i\n", net_addr, net_port);
        main_largstart = 4;

        boot_mode = 1;
        return 101;
    } else if(!strcmp(argv[1], "-s")) {
        if(argc <= 3)
            return print_usage(argv[0]);

        int net_port = atoi(argv[2]);
        mod_basedir = argv[3];
        printf("TODO: run a server on port %i, mod \"%s\"\n", net_port, mod_basedir);
        main_largstart = 4;

        boot_mode = 3;
    } else if(!strcmp(argv[1], "-d")) {
        if(argc <= 3)
            return print_usage(argv[0]);

        int net_port = atoi(argv[2]);
        mod_basedir = argv[3];
        printf("TODO: run a ded server on port %i, mod \"%s\"\n", net_port, mod_basedir);
        main_largstart = 4;

        boot_mode = 2;
        return 101;
    } else {
        return print_usage(argv[0]);
    }

    if(memcmp(mod_basedir,"pkg/",4))
    {
        fprintf(stderr, "ERROR: package base dir must start with \"pkg/\"!\n");
        return 109;
    }

    if(strlen(mod_basedir) < 5)
    {
        fprintf(stderr, "ERROR: package base dir can't actually be \"pkg/\"!\n");
        return 109;
    }

    if((!(boot_mode & 1)) || !platform_init()) {
        if(!icelua_init()) {
            if(!net_init()) {
                if((!(boot_mode & 1)) || !video_init()) {
                    if((!(boot_mode & 1)) || !wav_init()) {
                        if((!(boot_mode & 1)) || !render_init(screen->w, screen->h)) {
                            run_game();
                            if(boot_mode & 1) render_deinit();
                        }
                        if(boot_mode & 1) wav_deinit();
                    }
                    if(boot_mode & 1) video_deinit();
                }
                net_deinit();
            }
            icelua_deinit();
        }
        if(boot_mode & 1) platform_deinit();
    }

    return 0;
}
Example #29
0
int main(int argc, char** argv)
{
	int result;

    (void)argc, argv;
	amqpalloc_set_memory_tracing_enabled(true);

	if (platform_init() != 0)
	{
		result = -1;
	}
	else
	{
		XIO_HANDLE sasl_io;
		CONNECTION_HANDLE connection;
		SESSION_HANDLE session;
		LINK_HANDLE link;
		MESSAGE_SENDER_HANDLE message_sender;
		MESSAGE_HANDLE message;

		size_t last_memory_used = 0;

		/* create SASL PLAIN handler */
		SASL_PLAIN_CONFIG sasl_plain_config = { EH_KEY_NAME, EH_KEY, NULL };
		SASL_MECHANISM_HANDLE sasl_mechanism_handle = saslmechanism_create(saslplain_get_interface(), &sasl_plain_config);
		XIO_HANDLE tls_io;

		/* create the TLS IO */
        TLSIO_CONFIG tls_io_config = { EH_HOST, 5671 };
		const IO_INTERFACE_DESCRIPTION* tlsio_interface = platform_get_default_tlsio();
		tls_io = xio_create(tlsio_interface, &tls_io_config);

		/* create the SASL client IO using the TLS IO */
		SASLCLIENTIO_CONFIG sasl_io_config;
        sasl_io_config.underlying_io = tls_io;
        sasl_io_config.sasl_mechanism = sasl_mechanism_handle;
		sasl_io = xio_create(saslclientio_get_interface_description(), &sasl_io_config);

		/* create the connection, session and link */
		connection = connection_create(sasl_io, EH_HOST, "some", NULL, NULL);
		session = session_create(connection, NULL, NULL);
		session_set_incoming_window(session, 2147483647);
		session_set_outgoing_window(session, 65536);

		AMQP_VALUE source = messaging_create_source("ingress");
		AMQP_VALUE target = messaging_create_target("amqps://" EH_HOST "/" EH_NAME);
		link = link_create(session, "sender-link", role_sender, source, target);
		link_set_snd_settle_mode(link, sender_settle_mode_unsettled);
		(void)link_set_max_message_size(link, 65536);

		amqpvalue_destroy(source);
		amqpvalue_destroy(target);

		message = message_create();
		unsigned char hello[] = { 'H', 'e', 'l', 'l', 'o' };
		BINARY_DATA binary_data;
        binary_data.bytes = hello;
        binary_data.length = sizeof(hello);
		message_add_body_amqp_data(message, binary_data);

		/* create a message sender */
		message_sender = messagesender_create(link, NULL, NULL);
		if (messagesender_open(message_sender) == 0)
		{
			uint32_t i;

#if _WIN32
			unsigned long startTime = (unsigned long)GetTickCount64();
#endif

			for (i = 0; i < msg_count; i++)
			{
				(void)messagesender_send(message_sender, message, on_message_send_complete, message);
			}

			message_destroy(message);

			while (true)
			{
				size_t current_memory_used;
				size_t maximum_memory_used;
				connection_dowork(connection);

				current_memory_used = amqpalloc_get_current_memory_used();
				maximum_memory_used = amqpalloc_get_maximum_memory_used();

				if (current_memory_used != last_memory_used)
				{
					(void)printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used);
					last_memory_used = current_memory_used;
				}

				if (sent_messages == msg_count)
				{
					break;
				}
			}

#if _WIN32
			unsigned long endTime = (unsigned long)GetTickCount64();

			(void)printf("Send %zu messages in %lu ms: %.02f msgs/sec\r\n", msg_count, (endTime - startTime), (float)msg_count / ((float)(endTime - startTime) / 1000));
#endif
		}

		messagesender_destroy(message_sender);
		link_destroy(link);
		session_destroy(session);
		connection_destroy(connection);
		xio_destroy(sasl_io);
		xio_destroy(tls_io);
		saslmechanism_destroy(sasl_mechanism_handle);
		platform_deinit();

		(void)printf("Max memory usage:%lu\r\n", (unsigned long)amqpalloc_get_maximum_memory_used());
		(void)printf("Current memory usage:%lu\r\n", (unsigned long)amqpalloc_get_current_memory_used());

		result = 0;
	}

#ifdef _CRTDBG_MAP_ALLOC
	_CrtDumpMemoryLeaks();
#endif

	return result;
}
Example #30
0
void qaas_mqtt_run(char param[])
{
    int count = 0;
    char macAdrs[18];
    unsigned char* destination;
    size_t destinationSize;
   

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

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

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

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

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

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

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