void iothub_client_sample_http_run(void)
{
    TRANSPORT_HANDLE httpTransport;
    IOTHUB_CLIENT_HANDLE iothubClient1;
    IOTHUB_CLIENT_HANDLE iothubClient2;


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

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

    callbackCounter = 0;

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


        if ((httpTransport = IoTHubTransport_Create(HTTP_Protocol, hubName, hubSuffix)) == NULL)
        {
            (void)printf("ERROR: httpTransport is NULL\r\n");
        }
        else
        {
            IOTHUB_CLIENT_CONFIG config1;
            config1.deviceId = deviceId1;
            config1.deviceKey = deviceKey1;
            config1.protocol = HTTP_Protocol;
            config1.iotHubName = NULL;
            config1.iotHubSuffix = NULL;
            config1.deviceSasToken = NULL;
            if ((iothubClient1 = IoTHubClient_CreateWithTransport(httpTransport, &config1)) == NULL)
            {
                (void)printf("ERROR: 1st device handle is NULL\r\n");
            }
            else
            {
                IOTHUB_CLIENT_CONFIG config2;
                config2.deviceId = deviceId2;
                config2.deviceKey = deviceKey2;
                config2.protocol = HTTP_Protocol;
                config2.iotHubName = NULL;
                config2.iotHubSuffix = NULL;
                config2.deviceSasToken = NULL;
                if ((iothubClient2 = IoTHubClient_CreateWithTransport(httpTransport, &config2)) == NULL)
                {
                    (void)printf("ERROR: 2nd device handle is NULL\r\n");
                }
                else
                {
                    unsigned int timeout = 241000;
                    // Because it can poll "after 9 seconds" polls will happen effectively // at ~10 seconds.
                    // Note that for scalabilty, the default value of minimumPollingTime
                    // is 25 minutes. For more information, see:
                    // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
                    unsigned int minimumPollingTime = 9;
                    iothub_client_sample_http_setoptions(iothubClient1, timeout, minimumPollingTime);
                    iothub_client_sample_http_setoptions(iothubClient2, timeout, minimumPollingTime);

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

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

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

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

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

                                sprintf_s(msgText, sizeof(msgText), "{\"deviceId\": \"%s\",\"windSpeed\":%.2f,\"temperature\":%.2f,\"humidity\":%.2f}", deviceId2, avgWindSpeed + (rand() % 4 + 2), temperature, humidity);
                                iothub_client_sample_http_send_one_msg(iothubClient2, &messages2[i], i);
                            }
                            // Wait for any incoming messages
                            (void)printf("Press any key to exit the application. \r\n");
                            (void)getchar();
                        }
                    }
                    IoTHubClient_Destroy(iothubClient2);
                }
                IoTHubClient_Destroy(iothubClient1);
            }
            IoTHubTransport_Destroy(httpTransport);
        }
        platform_deinit();
    }
}
Ejemplo n.º 2
0
void nodemcu_init(void)
{
    NODE_ERR("\n");
    // Initialize platform first for lua modules.   
    if( platform_init() != PLATFORM_OK )
    {
        // This should never happen
        NODE_DBG("Can not init platform for modules.\n");
        return;
    }

#if defined(FLASH_SAFE_API)
    if( flash_safe_get_size_byte() != flash_rom_get_size_byte()) {
        NODE_ERR("Self adjust flash size.\n");
        // Fit hardware real flash size.
        flash_rom_set_size_byte(flash_safe_get_size_byte());
        // Flash init data at FLASHSIZE - 0x04000 Byte.
        flash_init_data_default();
        // Flash blank data at FLASHSIZE - 0x02000 Byte.
        flash_init_data_blank();
        if( !fs_format() )
        {
            NODE_ERR( "\ni*** ERROR ***: unable to format. FS might be compromised.\n" );
            NODE_ERR( "It is advised to re-flash the NodeMCU image.\n" );
        }
        else{
            NODE_ERR( "format done.\n" );
        }
        fs_unmount();   // mounted by format.
    }
#endif // defined(FLASH_SAFE_API)

    if( !flash_init_data_written() ){
        NODE_ERR("Restore init data.\n");
        // Flash init data at FLASHSIZE - 0x04000 Byte.
        flash_init_data_default();
        // Flash blank data at FLASHSIZE - 0x02000 Byte.
        flash_init_data_blank(); 
    }

#if defined( BUILD_WOFS )
    romfs_init();

    // if( !wofs_format() )
    // {
    //     NODE_ERR( "\ni*** ERROR ***: unable to erase the flash. WOFS might be compromised.\n" );
    //     NODE_ERR( "It is advised to re-flash the NodeWifi image.\n" );
    // }
    // else
    //     NODE_ERR( "format done.\n" );

    // test_romfs();
#elif defined ( BUILD_SPIFFS )
    fs_mount();
    // test_spiffs();
#endif
    // endpoint_setup();

    // char* lua_argv[] = { (char *)"lua", (char *)"-e", (char *)"print(collectgarbage'count');ttt={};for i=1,100 do table.insert(ttt,i*2 -1);print(i);end for k, v in pairs(ttt) do print('<'..k..' '..v..'>') end print(collectgarbage'count');", NULL };
    // lua_main( 3, lua_argv );
    // char* lua_argv[] = { (char *)"lua", (char *)"-i", NULL };
    // lua_main( 2, lua_argv );
    // char* lua_argv[] = { (char *)"lua", (char *)"-e", (char *)"pwm.setup(0,100,50) pwm.start(0) pwm.stop(0)", NULL };
    // lua_main( 3, lua_argv );
    // NODE_DBG("Flash sec num: 0x%x\n", flash_get_sec_num());
    task_init();
    system_os_post(USER_TASK_PRIO_0,SIG_LUA,'s');
}
Ejemplo n.º 3
0
/* C entry point for boot CPU */
void __init start_xen(unsigned long boot_phys_offset,
                      unsigned long fdt_paddr,
                      unsigned long cpuid)
{
    size_t fdt_size;
    int cpus, i;
    const char *cmdline;

    setup_cache();

    percpu_init_areas();
    set_processor_id(0); /* needed early, for smp_processor_id() */

    smp_clear_cpu_maps();

    /* This is mapped by head.S */
    device_tree_flattened = (void *)BOOT_FDT_VIRT_START
        + (fdt_paddr & ((1 << SECOND_SHIFT) - 1));
    fdt_size = device_tree_early_init(device_tree_flattened, fdt_paddr);

    cmdline = device_tree_bootargs(device_tree_flattened);
    early_printk("Command line: %s\n", cmdline);
    cmdline_parse(cmdline);

    setup_pagetables(boot_phys_offset, get_xen_paddr());
    setup_mm(fdt_paddr, fdt_size);

    vm_init();
    dt_unflatten_host_device_tree();
    dt_irq_xlate = gic_irq_xlate;

    dt_uart_init();
    console_init_preirq();

    system_state = SYS_STATE_boot;

    processor_id();

    platform_init();

    smp_init_cpus();
    cpus = smp_get_max_cpus();

    init_xen_time();

    gic_init();

    set_current((struct vcpu *)0xfffff000); /* debug sanity */
    idle_vcpu[0] = current;

    init_traps();

    setup_virt_paging();

    p2m_vmid_allocator_init();

    softirq_init();

    tasklet_subsys_init();

    init_IRQ();

    gic_route_ppis();
    gic_route_spis();

    init_maintenance_interrupt();
    init_timer_interrupt();

    timer_init();

    init_idle_domain();

    rcu_init();

    arch_init_memory();

    local_irq_enable();
    local_abort_enable();

    smp_prepare_cpus(cpus);

    initialize_keytable();

    console_init_postirq();

    do_presmp_initcalls();

    for_each_present_cpu ( i )
    {
        if ( (num_online_cpus() < cpus) && !cpu_online(i) )
        {
            int ret = cpu_up(i);
            if ( ret != 0 )
                printk("Failed to bring up CPU %u (error %d)\n", i, ret);
        }
    }

    printk("Brought up %ld CPUs\n", (long)num_online_cpus());
    /* TODO: smp_cpus_done(); */

    do_initcalls();

    /* Create initial domain 0. */
    dom0 = domain_create(0, 0, 0);
    if ( IS_ERR(dom0) || (alloc_dom0_vcpu0() == NULL) )
            panic("Error creating domain 0");

    dom0->is_privileged = 1;
    dom0->target = NULL;

    if ( construct_dom0(dom0) != 0)
            panic("Could not set up DOM0 guest OS");

    /* Scrub RAM that is still free and so may go to an unprivileged domain. */
    scrub_heap_pages();

    init_constructors();

    console_endboot();

    /* Hide UART from DOM0 if we're using it */
    serial_endboot();

    system_state = SYS_STATE_active;

    domain_unpause_by_systemcontroller(dom0);

    /* Switch on to the dynamically allocated stack for the idle vcpu
     * since the static one we're running on is about to be freed. */
    memcpy(idle_vcpu[0]->arch.cpu_info, get_cpu_info(),
           sizeof(struct cpu_info));
    switch_stack_and_jump(idle_vcpu[0]->arch.cpu_info, init_done);
}
Ejemplo n.º 4
0
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;
}
Ejemplo n.º 5
0
void qaas_mqtt_run(char param[])
{
    int count = 0;
    char macAdrs[18];
    unsigned char* destination;
    size_t destinationSize;
   

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

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

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

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

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

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

                    DESTROY_MODEL_INSTANCE(deviceInfo);
                }
                IoTHubClient_LL_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_deinit();
    }
}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
0
Archivo: setup.c Proyecto: caomw/xen
/* C entry point for boot CPU */
void __init start_xen(unsigned long boot_phys_offset,
                      unsigned long fdt_paddr,
                      unsigned long cpuid)
{
    size_t fdt_size;
    int cpus, i;
    paddr_t xen_paddr;
    const char *cmdline;
    struct bootmodule *xen_bootmodule;
    struct domain *dom0;
    struct xen_arch_domainconfig config;

    setup_cache();

    percpu_init_areas();
    set_processor_id(0); /* needed early, for smp_processor_id() */

    set_current((struct vcpu *)0xfffff000); /* debug sanity */
    idle_vcpu[0] = current;

    setup_virtual_regions(NULL, NULL);
    /* Initialize traps early allow us to get backtrace when an error occurred */
    init_traps();

    smp_clear_cpu_maps();

    /* This is mapped by head.S */
    device_tree_flattened = (void *)BOOT_FDT_VIRT_START
        + (fdt_paddr & ((1 << SECOND_SHIFT) - 1));
    fdt_size = boot_fdt_info(device_tree_flattened, fdt_paddr);

    cmdline = boot_fdt_cmdline(device_tree_flattened);
    printk("Command line: %s\n", cmdline);
    cmdline_parse(cmdline);

    /* Register Xen's load address as a boot module. */
    xen_bootmodule = add_boot_module(BOOTMOD_XEN,
                             (paddr_t)(uintptr_t)(_start + boot_phys_offset),
                             (paddr_t)(uintptr_t)(_end - _start + 1), NULL);
    BUG_ON(!xen_bootmodule);

    xen_paddr = get_xen_paddr();
    setup_pagetables(boot_phys_offset, xen_paddr);

    /* Update Xen's address now that we have relocated. */
    printk("Update BOOTMOD_XEN from %"PRIpaddr"-%"PRIpaddr" => %"PRIpaddr"-%"PRIpaddr"\n",
           xen_bootmodule->start, xen_bootmodule->start + xen_bootmodule->size,
           xen_paddr, xen_paddr + xen_bootmodule->size);
    xen_bootmodule->start = xen_paddr;

    setup_mm(fdt_paddr, fdt_size);

    /* Parse the ACPI tables for possible boot-time configuration */
    acpi_boot_table_init();

    end_boot_allocator();

    vm_init();
    dt_unflatten_host_device_tree();

    init_IRQ();

    platform_init();

    preinit_xen_time();

    gic_preinit();

    arm_uart_init();
    console_init_preirq();
    console_init_ring();

    system_state = SYS_STATE_boot;

    processor_id();

    smp_init_cpus();
    cpus = smp_get_max_cpus();

    init_xen_time();

    gic_init();

    p2m_vmid_allocator_init();

    softirq_init();

    tasklet_subsys_init();


    xsm_dt_init();

    init_maintenance_interrupt();
    init_timer_interrupt();

    timer_init();

    init_idle_domain();

    rcu_init();

    arch_init_memory();

    local_irq_enable();
    local_abort_enable();

    smp_prepare_cpus(cpus);

    initialize_keytable();

    console_init_postirq();

    do_presmp_initcalls();

    for_each_present_cpu ( i )
    {
        if ( (num_online_cpus() < cpus) && !cpu_online(i) )
        {
            int ret = cpu_up(i);
            if ( ret != 0 )
                printk("Failed to bring up CPU %u (error %d)\n", i, ret);
        }
    }

    printk("Brought up %ld CPUs\n", (long)num_online_cpus());
    /* TODO: smp_cpus_done(); */

    setup_virt_paging();

    iommu_setup();

    do_initcalls();

    /*
     * It needs to be called after do_initcalls to be able to use
     * stop_machine (tasklets initialized via an initcall).
     */
    apply_alternatives_all();

    /* Create initial domain 0. */
    /* The vGIC for DOM0 is exactly emulating the hardware GIC */
    config.gic_version = XEN_DOMCTL_CONFIG_GIC_NATIVE;
    config.nr_spis = gic_number_lines() - 32;

    dom0 = domain_create(0, 0, 0, &config);
    if ( IS_ERR(dom0) || (alloc_dom0_vcpu0(dom0) == NULL) )
            panic("Error creating domain 0");

    dom0->is_privileged = 1;
    dom0->target = NULL;

    if ( construct_dom0(dom0) != 0)
            panic("Could not set up DOM0 guest OS");

    /* Scrub RAM that is still free and so may go to an unprivileged domain. */
    scrub_heap_pages();

    init_constructors();

    console_endboot();

    /* Hide UART from DOM0 if we're using it */
    serial_endboot();

    system_state = SYS_STATE_active;

    /* Must be done past setting system_state. */
    unregister_init_virtual_region();

    domain_unpause_by_systemcontroller(dom0);

    /* Switch on to the dynamically allocated stack for the idle vcpu
     * since the static one we're running on is about to be freed. */
    memcpy(idle_vcpu[0]->arch.cpu_info, get_cpu_info(),
           sizeof(struct cpu_info));
    switch_stack_and_jump(idle_vcpu[0]->arch.cpu_info, init_done);
}
int main(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));

    IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol;
#ifdef USE_HTTP
    protocol = HTTP_Protocol;
#endif
#ifdef USE_MQTT
    protocol = MQTT_Protocol;
#endif
#ifdef USE_AMQP
    protocol = AMQP_Protocol;
#endif

    callbackCounter = 0;

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

        if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, protocol)) == NULL)
        {
            (void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
        }
        else
        {
#ifdef USE_HTTP
            if (protocol == HTTP_Protocol)
            {
                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");
                }
            }
            else
#endif
            {
                bool trace = true;
                (void)IoTHubClient_LL_SetOption(iotHubClientHandle, "logtrace", &trace);
            }

            /*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);
                                (void)sprintf_s(propText, sizeof(propText), "PropMsg_%zu", 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_x509 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();
    }
}
static int iothub_client_sample_mqtt_dm_run(const char *connectionString, bool traceOn)
{
    LogInfo("Initialize Platform");

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

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

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

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

    return retValue;
}
void 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();
    }
}
Ejemplo n.º 11
0
Archivo: main.c Proyecto: malind/bam
/* ********* */
int main(int argc, char **argv)
{
	int i, error;

	/* set exe */
	session.exe = argv[0];

	/* fetch program name, if we can */
	for(i = 0; argv[0][i]; ++i)
	{
		if(argv[0][i] == '/' || argv[0][i] == '\\')
			session.name = &argv[0][i+1];
	}

	/* parse environment parameters */
	if(getenv("BAM_OPTIONS"))
	{
		if(parse_parameters_str(getenv("BAM_OPTIONS")))
			return -1;
	}
	
	/* parse commandline parameters */
	if(parse_parameters(argc-1, argv+1))
		return -1;

	/* set eventlog */
	if(option_win_msvcmode)
		session.win_msvcmode = option_win_msvcmode;

	/* init platform */
	platform_init();

	/* set eventlog */
	if(option_debug_eventlog)
	{
		session.eventlog = fopen(option_debug_eventlog, "w");
		session.eventlogflush = option_debug_eventlogflush;
		if(!session.eventlog)
		{
			printf("%s: error opening '%s' for output\n", session.name, option_debug_eventlog);
			return 1;
		}
	}

	/* parse the report str */
	for(i = 0; option_report_str[i]; i++)
	{
		if(option_report_str[i] == 'c')
			session.report_color = 1;
		else if(option_report_str[i] == 'b')
			session.report_bar = 1;
		else if(option_report_str[i] == 's')
			session.report_steps = 1;
	}
	
	/* convert the threads string */
	if(option_threads_str)
	{
		session.threads = atoi(option_threads_str);
		if(session.threads < 0)
		{
			printf("%s: invalid number of threads supplied\n", session.name);
			return 1;
		}
	}
	else
	{
		session.threads = threads_corecount();
		if(session.verbose)
			printf("%s: detected %d cores\n", session.name, session.threads);
	}
	
	/* check for help argument */
	if(option_print_debughelp)
	{
		print_help(OF_PRINT|OF_DEBUG);
		return 0;
	}
	else if(option_print_help)
	{
		print_help(OF_PRINT);
		return 0;
	}

	/* */
	if(option_debug_dumpinternal)
	{
		int f;
		for(f = 0; internal_files[f].filename; f++)
		{
			printf("%s:\n", internal_files[f].filename);
			puts(internal_files[f].content);
		}
				
		return 0;
	}
	
	if(option_lua_execute)
	{
		struct lua_State* lua = lua_newstate(lua_alloctor_malloc, 0x0);
		lua_atpanic(lua, lf_panicfunc);

		/* register all functions */
		if(register_lua_globals(lua, "script_dir", option_lua_execute) != 0)
		{
			printf("%s: error: registering of lua functions failed\n", session.name);
			return -1;
		}

		lua_getglobal(lua, "errorfunc");
		switch(luaL_loadfile(lua, option_lua_execute))
		{
			case 0: break;
			case LUA_ERRSYNTAX:
					lf_errorfunc(lua);
					return -1;
			case LUA_ERRMEM: 
					printf("%s: memory allocation error\n", session.name);
					return -1;
			case LUA_ERRFILE:
					printf("%s: error opening '%s'\n", session.name, option_lua_execute);
					return -1;
			default:
					printf("%s: unknown error\n", session.name);
					return -1;
		}

		/* call the code chunk */	
		if(lua_pcall(lua, 0, LUA_MULTRET, -2) != 0)
		{
			printf("%s: script error (-t for more detail)\n", session.name);
			return -1;
		}

		lua_close(lua);
		error = 0;
	}
	else
	{
		/* init the context */
		error = bam(option_script, option_targets, option_num_targets);
	}
	
	platform_shutdown();


	/* error could be some high value like 256 seams like this could */
	/* be clamped down to a unsigned char and not be an error anymore */
	if(error)
		return 1;

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

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

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

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

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

                }
                IoTHubDeviceTwin_DestroyCar(car);
            }
            IoTHubClient_Destroy(iotHubClientHandle);
        }
    }
    platform_deinit();
}
Ejemplo n.º 13
0
PROCESS_THREAD(cetic_6lbr_process, ev, data)
{
  PROCESS_BEGIN();

  cetic_6lbr_startup = clock_seconds();

#if CONTIKI_TARGET_NATIVE
  slip_config_handle_arguments(contiki_argc, contiki_argv);
  if (watchdog_interval) {
    process_start(&native_6lbr_watchdog, NULL);
  } else {
    LOG6LBR_WARN("6LBR Watchdog disabled\n");
  }
#endif

  LOG6LBR_INFO("Starting 6LBR version " CETIC_6LBR_VERSION " (" CONTIKI_VERSION_STRING ")\n");

  load_nvm_config();

  platform_init();

  process_start(&eth_drv_process, NULL);

  while(!ethernet_ready) {
    PROCESS_PAUSE();
  }

  //clean up any early packet
  uip_len = 0;
  process_start(&tcpip_process, NULL);

  PROCESS_PAUSE();

#if CETIC_NODE_INFO
  node_info_init();
#endif

  packet_filter_init();
  cetic_6lbr_init();

#if WEBSERVER
  process_start(&webserver_nogui_process, NULL);
#endif
#if UDPSERVER
  process_start(&udp_server_process, NULL);
#endif

  LOG6LBR_INFO("CETIC 6LBR Started\n");

#if CONTIKI_TARGET_NATIVE
  PROCESS_WAIT_EVENT();
  etimer_set(&reboot_timer, CLOCK_SECOND);
  PROCESS_WAIT_EVENT();
  switch (cetic_6lbr_restart_type) {
    case CETIC_6LBR_RESTART:
      LOG6LBR_INFO("Exiting...\n");
      exit(0);
      break;
    case CETIC_6LBR_REBOOT:
      LOG6LBR_INFO("Rebooting...\n");
      system("reboot");
      break;
    case CETIC_6LBR_HALT:
      LOG6LBR_INFO("Halting...\n");
      system("halt");
      break;
    default:
      //We should never end up here...
      exit(1);
  }
  //We should never end up here...
  exit(1);
#endif

  PROCESS_END();
}
Ejemplo n.º 14
0
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);
                            (void)sprintf_s(propText, sizeof(propText), "PropMsg_%zu", 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();
    }
}
Ejemplo n.º 15
0
int main(void)
{
   uint8_t tmp=0;
   int32_t ret = 0;
   uint8_t memsize[2][8] = {{2,2,2,2,2,2,2,2},{2,2,2,2,2,2,2,2}};
   uint8_t txsize[8] = {2,2,2,2,2,2,2,2};
   uint8_t rxsize[8] = {2,2,2,2,2,2,2,2};
   uint8_t pDestaddr[4] = {192,168,0,200};
   int8_t num;

   uint8_t ping_reply_received = 0;

   ///////////////////////////////////////////
   // Host dependent peripheral initialized //
   ///////////////////////////////////////////
   platform_init();


   //////////
   // TODO //
   ////////////////////////////////////////////////////////////////////////////////////////////////////
   // First of all, Should register SPI callback functions implemented by user for accessing WIZCHIP //
   ////////////////////////////////////////////////////////////////////////////////////////////////////
   /* Critical section callback - No use in this example */
   //reg_wizchip_cris_cbfunc(0, 0);
   /* Chip selection call back */
#if   _WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_SPI_VDM_
    reg_wizchip_cs_cbfunc(wizchip_select, wizchip_deselect);
#elif _WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_SPI_FDM_
    reg_wizchip_cs_cbfunc(wizchip_select, wizchip_select);  // CS must be tried with LOW.
#else
   #if (_WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_SIP_) != _WIZCHIP_IO_MODE_SIP_
      #error "Unknown _WIZCHIP_IO_MODE_"
   #else
      reg_wizchip_cs_cbfunc(wizchip_select, wizchip_deselect);
   #endif
#endif
    /* SPI Read & Write callback function */
    reg_wizchip_spi_cbfunc(wizchip_read, wizchip_write);
    ////////////////////////////////////////////////////////////////////////

    /* WIZCHIP SOCKET Buffer initialize */

    wizchip_init(txsize,rxsize);

    /* Network initialization */
    network_init();


	/*******************************/
	/* WIZnet W5500 Code Examples  */
	/* TCPS/UDPS IPRAW test     */
	/*******************************/
    printf("------------PING_TEST_START-----------------------\r\n");
    tmp = ping_auto(0,pDestaddr);
    //tmp = ping_count(0,3,pDestaddr);
    if(tmp == SUCCESS)
    	printf("-----------PING TEST OK----------\r\n");
    else
        printf("----------ERROR  = %d----------\r\n",tmp);

} // end of main()
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();
    }
}
Ejemplo n.º 17
0
/*
 * Called when the instance of the TA is created. This is the first call in
 * the TA.
 */
TEE_Result TA_CreateEntryPoint(void)
{
	platform_init();
	return TEE_SUCCESS;
}
Ejemplo n.º 18
0
int SendBatch_Sample(void)
{
    int result;
    time_t t = time(&t);
    (void)printf("Starting the EventHub Client SendBatch Sample (%s)...\r\n", EventHubClient_GetVersionString() ); 

    if (platform_init() != 0)
    {
        (void)printf("ERROR: Failed initializing platform!\r\n");
        result = 1;
    }
    else
    {
        //Create an Array of EventData so we can send these data batched.
        EVENTDATA_HANDLE eventDataList[NUM_OF_MSG_TO_SEND];

        size_t index;
        for (index = 0; index < NUM_OF_MSG_TO_SEND; index++)
        {
            char msgContent[BUFFER_SIZE];
            size_t msgLength = sprintf_s(msgContent, BUFFER_SIZE, "{\"messageId\":%ul, \"timeValue\":%I64d, \"name\":\"SendBatch_Sample\"}", index, t);

            if ((eventDataList[index] = EventData_CreateWithNewMemory((const unsigned char*)msgContent, msgLength)) == NULL)
            {
                (void)printf("ERROR: EventData_CreateWithNewMemory returned NULL!\r\n");
                result = 1;
                break;
            }
        }

        if (index == NUM_OF_MSG_TO_SEND)
        {
            EVENTHUBCLIENT_HANDLE eventHubClientHandle = EventHubClient_CreateFromConnectionString(connectionString, eventHubPath);
            if (eventHubClientHandle == NULL)
            {
                (void)printf("ERROR: EventHubClient_CreateFromConnectionString returned NULL!\r\n");
                result = 1;
            }
            else
            {
                for (size_t i = 0; i < NUM_OF_MSG_TO_SEND; i++)
                {
                    EventData_SetPartitionKey(eventDataList[i], PARTITION_KEY_INFO);
                }


                MAP_HANDLE mapProperties = EventData_Properties(eventDataList[0]);
                if (mapProperties != NULL)
                {
                    if ((Map_AddOrUpdate(mapProperties, "SendBatch_HL_1", TEST_STRING_VALUE_1) != MAP_OK) ||
                        (Map_AddOrUpdate(mapProperties, "SendBatch_HL_2", TEST_STRING_VALUE_2) != MAP_OK)
                        )
                    {
                        (void)printf("ERROR: Map_AddOrUpdate failed!\r\n");
                    }
                }

                //Send all 3 data created above on the same call (Batched)
                if (EventHubClient_SendBatch(eventHubClientHandle, eventDataList, NUM_OF_MSG_TO_SEND) != EVENTHUBCLIENT_OK)
                {
                    (void)printf("ERROR: EventHubClient_SendBatch failed!\r\n");
                    result = 1;
                }
                else
                {
                    (void)printf("EventHubClient_SendBatch.......Successful\r\n");
                    result = 0;
                }
                EventHubClient_Destroy(eventHubClientHandle);
            }
        }
        for (size_t i = 0; i < index; i++)
        {
            EventData_Destroy(eventDataList[i]);
        }

        platform_init();
    }

    return result;
}
Ejemplo n.º 19
0
void GameManager::init()
{
#ifdef CHOWDREN_USER_PROFILER
    user_log.open("log.txt", "w");
#endif

#ifdef CHOWDREN_USE_PROFILER
    PROFILE_SET_DAMPING(0.0);
#endif
    frame = &static_frames;

#ifdef CHOWDREN_IS_DEMO
    idle_timer_started = false;
    global_time = show_build_timer = reset_timer = manual_reset_timer = 0.0;
#endif

#ifdef CHOWDREN_USE_JOYTOKEY
    simulate_count = 0;
    axis_moved = false;
    last_axis = -1;
    deadzone = 0.4f;
    pad_selected = false;
    pad_disconnected = false;
    for (int i = 0; i < CHOWDREN_BUTTON_MAX-1; i++)
        key_mappings[i] = -1;
    for (int i = 0; i < CHOWDREN_AXIS_MAX-1; i++) {
        axis_pos_mappings[i] = -1;
        axis_neg_mappings[i] = -1;
        axis_values[i] = 0;
    }
#endif
    platform_init();
    media.init();
    set_window(false);

    // application setup
    preload_images();
    reset_globals();
    setup_keys(this);

    // setup random generator from start
    cross_srand((unsigned int)platform_get_global_time());

    fps_limit.start();
    set_framerate(FRAMERATE);

    int start_frame = 0;
#if defined(CHOWDREN_IS_AVGN)
    start_frame = 0;
#elif defined(CHOWDREN_IS_HFA)
    start_frame = 0;
#elif defined(CHOWDREN_IS_FP)
    player_died = false;
    lives = 3;
    start_frame = 0;
    // values->set(1, 2);
    // values->set(12, 2);
#elif defined(CHOWDREN_IS_NAH)
    platform_set_scale_type(2);
    // start_frame = 3;
    // set_local("fre");
    // values->set(13, 25);
    // strings->set(23, "OBJETS");
    // strings->set(9, "-fre");
#else
    start_frame = 0;
#endif

#ifdef NDEBUG
    set_frame(0);
#else
    set_frame(start_frame);
#endif
}
Ejemplo n.º 20
0
int main( void )
{
  int i;
  FILE* fp;

  // Initialize platform first
  if( platform_init() != PLATFORM_OK )
  {
    // This should never happen
    while( 1 );
  }

  // Initialize device manager
  dm_init();

  // Register the ROM filesystem
  romfs_init();

  // Register the MMC filesystem
  mmcfs_init();

  // Register the Semihosting filesystem
  semifs_init();

  // Register the remote filesystem
  remotefs_init();

  // Register NIFFS
  nffs_init();

  // Search for autorun files in the defined order and execute the 1st if found
  for( i = 0; i < sizeof( boot_order ) / sizeof( *boot_order ); i++ )
  {
    if( ( fp = fopen( boot_order[ i ], "r" ) ) != NULL )
    {
      fclose( fp );
      char* lua_argv[] = { (char *)"lua", (char *)boot_order[i], NULL };
      lua_main( 2, lua_argv );
      break; // autoruns only the first found
    }
  }

#ifdef ELUA_BOOT_RPC
  boot_rpc();
#else
  
  // Run the shell
  if( shell_init() == 0 )
  {
    // Start Lua directly
    char* lua_argv[] = { (char *)"lua", NULL };
    lua_main( 1, lua_argv );
  }
  else
    shell_start();
#endif // #ifdef ELUA_BOOT_RPC

#ifdef ELUA_SIMULATOR
  hostif_exit(0);
  return 0;
#else
  while( 1 );
#endif
}
Ejemplo n.º 21
0
int32 main(void)
{
#define TCP_LISTEN_PORT	5000
#define UDP_LISTEN_PORT	5000

	int8 ret, root;
	uint32 dhcp_renew, dhcp_rebind, dhcp_time;
	uint32 dhcp_tick, led_tick;

	ret = platform_init();
	if(ret != RET_OK) {
		goto FAIL_TRAP;
	}

	ret = network_init(SOCK_DHCP, NULL, NULL);
	if(ret != RET_OK) {
		ERRA("network_init fail - ret(%d)", ret);
		goto FAIL_TRAP;
	}

	printf("\r\n-----------------------------------\r\n");
	printf("SMTP Client using W5200\r\n");
	printf("-----------------------------------\r\n\r\n");

	Delay_tick(2000);
	do {
		ret = dhcp_manual(DHCP_ACT_START, NULL, &dhcp_renew, &dhcp_rebind);
	} while(ret != RET_OK);
	dhcp_renew = wizpf_tick_conv(FALSE, dhcp_renew);
	dhcp_rebind = wizpf_tick_conv(FALSE, dhcp_rebind);
	dhcp_time = dhcp_renew;

	menu_init();
	root = menu_add("Network setting", 0, NULL);
	menu_add("Show", root, mn_show_network);
	menu_add("Static Set", root, mn_set_network);
	menu_add("Loopback", 0, mn_loopback);
	menu_add("LED Test", 0, mn_set_led);
	root = menu_add("App Test", 0, NULL);
	menu_add("DNS", root, mn_dns);
	menu_add("BASE64", root, mn_base64);
	menu_add("eMail", root, mn_email);

	menu_print_tree();

	dhcp_tick = led_tick = wizpf_get_systick();

	while(1) {
		if(wizpf_tick_elapse(dhcp_tick) > dhcp_time) {
			if(dhcp_time==dhcp_renew) DBG("start renew"); else DBG("start rebind");
			ret = dhcp_manual(dhcp_time==dhcp_renew? DHCP_ACT_RENEW: DHCP_ACT_REBIND, 
				NULL, &dhcp_renew, &dhcp_rebind);
			dhcp_tick = wizpf_get_systick();
			if(ret == RET_OK) {	// renew success
				dhcp_renew = wizpf_tick_conv(FALSE, dhcp_renew);
				dhcp_rebind = wizpf_tick_conv(FALSE, dhcp_rebind);
				dhcp_time = dhcp_renew;
			} else {
				if(dhcp_time == dhcp_renew) dhcp_time = dhcp_rebind; // renew fail, so try rebind
				else dhcp_time = 60000; // retry after 1 min
			}
		}
		menu_run();
		if(lb_tcp) loopback_tcps(7, (uint16)TCP_LISTEN_PORT);
		if(lb_udp) loopback_udp(7, (uint16)UDP_LISTEN_PORT);
		if(wizpf_tick_elapse(led_tick) > 1000) {
			wizpf_led_set(WIZ_LED3, VAL_TOG);
			led_tick = wizpf_get_systick();
		}
	}

FAIL_TRAP:
	wizpf_led_trap(1);
	return 0;
}
Ejemplo n.º 22
0
static int jiveL_initSDL(lua_State *L) {
	const SDL_VideoInfo *video_info;
#ifndef JIVE_NO_DISPLAY
	JiveSurface *srf, *splash;
	Uint16 splash_w, splash_h;
	bool fullscreen = false;
	char splashfile[32] = "jive/splash.png";
#endif
	/* logging */
	log_ui_draw = LOG_CATEGORY_GET("squeezeplay.ui.draw");
	log_ui = LOG_CATEGORY_GET("squeezeplay.ui");

	/* linux fbcon does not need a mouse */
	SDL_putenv("SDL_NOMOUSE=1");

#ifdef JIVE_NO_DISPLAY
#   define JIVE_SDL_FEATURES (SDL_INIT_EVENTLOOP)
#else
#   define JIVE_SDL_FEATURES (SDL_INIT_VIDEO)
#endif
	/* initialise SDL */
	if (SDL_Init(JIVE_SDL_FEATURES) < 0) {
		LOG_ERROR(log_ui_draw, "SDL_Init(V|T|A): %s\n", SDL_GetError());
		SDL_Quit();
		exit(-1);
	}

	/* report video info */
	if ((video_info = SDL_GetVideoInfo())) {
		LOG_INFO(log_ui_draw, "%d,%d %d bits/pixel %d bytes/pixel [R<<%d G<<%d B<<%d]", video_info->current_w, video_info->current_h, video_info->vfmt->BitsPerPixel, video_info->vfmt->BytesPerPixel, video_info->vfmt->Rshift, video_info->vfmt->Gshift, video_info->vfmt->Bshift);
		LOG_INFO(log_ui_draw, "Hardware acceleration %s available", video_info->hw_available?"is":"is not");
		LOG_INFO(log_ui_draw, "Window Manager %s available", video_info->wm_available?"is":"is not");
	}

	/* Register callback for additional events (used for multimedia keys)*/
	SDL_EventState(SDL_SYSWMEVENT,SDL_ENABLE);
	SDL_SetEventFilter(filter_events);

	// Secific magic for windows|linux|macos
	platform_init(L);

#ifndef JIVE_NO_DISPLAY

	/* open window */
	SDL_WM_SetCaption("SqueezePlay", "SqueezePlay");
	SDL_ShowCursor(SDL_DISABLE);
	SDL_EnableKeyRepeat (100, 100);
	SDL_EnableUNICODE(1);


#ifdef SCREEN_ROTATION_ENABLED
	screen_w = video_info->current_h;
	screen_h = video_info->current_w;
#else
	screen_w = video_info->current_w;
	screen_h = video_info->current_h;
#endif
	screen_bpp = video_info->vfmt->BitsPerPixel;

	if (video_info->wm_available) {
		/* desktop build */
		JiveSurface *icon;

		/* load the icon */
		icon = jive_surface_load_image("jive/app.png");
		if (icon) {
			jive_surface_set_wm_icon(icon);
			jive_surface_free(icon);
		}

		splash = jive_surface_load_image(splashfile);
		if (splash) {
			jive_surface_get_size(splash, &splash_w, &splash_h);

			screen_w = splash_w;
			screen_h = splash_h;
		}
	} else {
		/* product build and full screen...*/

		sprintf(splashfile, "jive/splash%dx%d.png", screen_w, screen_h);

		splash = jive_surface_load_image(splashfile);
		if(!splash) {
			sprintf(splashfile,"jive/splash.png");
			splash = jive_surface_load_image(splashfile);
		}

		if (splash) {
			jive_surface_get_size(splash, &splash_w, &splash_h);
		}

		fullscreen = true;
	}

	srf = jive_surface_set_video_mode(screen_w, screen_h, screen_bpp, fullscreen);
	if (!srf) {
		LOG_ERROR(log_ui_draw, "Video mode not supported: %dx%d\n", screen_w, screen_h);

		SDL_Quit();
		exit(-1);
	}

	if (splash) {
		jive_surface_blit(splash, srf, (screen_w - splash_w) > 0 ?((screen_w - splash_w) / 2):0, (screen_w - splash_w) > 0 ?((screen_w - splash_w) / 2):0);
		jive_surface_flip(srf);
		LOG_INFO(log_ui_draw, "Splash %s %dx%d Screen %dx%d", splashfile,splash_w,splash_h,screen_w,screen_h);
	}

	lua_getfield(L, 1, "screen");
	if (lua_isnil(L, -1)) {
		LOG_ERROR(log_ui_draw, "no screen table");

		SDL_Quit();
		exit(-1);
	}

	/* store screen surface */
	tolua_pushusertype(L, srf, "Surface");
	lua_setfield(L, -2, "surface");

	lua_getfield(L, -1, "bounds");
	lua_pushinteger(L, screen_w);
	lua_rawseti(L, -2, 3);
	lua_pushinteger(L, screen_h);
	lua_rawseti(L, -2, 4);
	lua_pop(L, 2);

	/* background image */
	jive_background = jive_tile_fill_color(0x000000FF);

	/* jive.ui.style = {} */
	lua_getglobal(L, "jive");
	lua_getfield(L, -1, "ui");
	lua_newtable(L);
	lua_setfield(L, -2, "style");
	lua_pop(L, 2);

	ui_watchdog = watchdog_get();
	watchdog_keepalive(ui_watchdog, 6); /* 60 seconds to start */

#endif /* JIVE_NO_DISPLAY */

	return 0;
}
Ejemplo n.º 23
0
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.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;

                            (void)printf("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)
                            {
                                (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();
        }
        platform_deinit();
    }
}
void iothub_client_sample_amqp_websockets_run(void)
{
    IOTHUB_CLIENT_HANDLE iotHubClientHandle;

    EVENT_INSTANCE messages[MESSAGE_COUNT];

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

    callbackCounter = 0;
    int receiveContext = 0;

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

        /* Setting Message call back, so we can receive Commands. */
        if (IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
        {
            (void)printf("ERROR: IoTHubClient_SetMessageCallback..........FAILED!\r\n");
        }
        else
        {
            (void)printf("IoTHubClient_SetMessageCallback...successful.\r\n");

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

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

            /* Wait for Commands. */
            (void)printf("Press any key to exit the application. \r\n");
            (void)getchar();
        }
        
        IoTHubClient_Destroy(iotHubClientHandle);
        platform_deinit();
    }
}
Ejemplo n.º 25
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();
    }
}
Ejemplo n.º 26
0
int main(int ac, char *av[]) {
  FILE *fin, *fout;
  int i;
  char *outfile;

  /* platform-specific initializations, e.g., set file i/o to binary */
  platform_init();

  /* process options */
  dopts(ac, av);

  /* there are several ways to call us:
     mkbitmap                    -- stdin to stdout
     mkbitmap -o outfile         -- stdin to outfile
     mkbitmap file...            -- encode each file and generate outfile names
     mkbitmap file... -o outfile -- concatenate files and write to outfile
  */

  if (info.infilecount == 0 && info.outfile == NULL) {  /* stdin to stdout */

    process_file(stdin, stdout, "stdin", "stdout");
    return 0;

  } else if (info.infilecount == 0) {                  /* stdin to outfile */

    fout = my_fopen_write(info.outfile);
    if (!fout) {
      fprintf(stderr, "mkbitmap: %s: %s\n", info.outfile, strerror(errno));
      exit(2);
    }
    process_file(stdin, fout, "stdin", info.outfile);
    my_fclose(fout, info.outfile);
    free(info.outfile);
    return 0;

  } else if (info.outfile == NULL) {       /* infiles -> multiple outfiles */

    for (i=0; i<info.infilecount; i++) {
      outfile = make_outfilename(info.infiles[i], info.outext);
      if (!outfile) {
	fprintf(stderr, "mkbitmap: %s\n", strerror(errno));
        exit(2);
      }
      fin = my_fopen_read(info.infiles[i]);
      if (!fin) {
	fprintf(stderr, "mkbitmap: %s: %s\n", info.infiles[i], strerror(errno));
	exit(2);
      }
      fout = my_fopen_write(outfile);
      if (!fout) {
	fprintf(stderr, "mkbitmap: %s: %s\n", outfile, strerror(errno));
	exit(2);
      }
      process_file(fin, fout, info.infiles[i], outfile);
      my_fclose(fin, info.infiles[i]);
      my_fclose(fout, outfile);
      free(outfile);
    }
    return 0;

  } else {                                    /* infiles to single outfile */

    fout = my_fopen_write(info.outfile);
    if (!fout) {
      fprintf(stderr, "mkbitmap: %s: %s\n", info.outfile, strerror(errno));
      exit(2);
    }
    for (i=0; i<info.infilecount; i++) {
      fin = my_fopen_read(info.infiles[i]);
      if (!fin) {
	fprintf(stderr, "mkbitmap: %s: %s\n", info.infiles[i], strerror(errno));
	exit(2);
      }
      process_file(fin, fout, info.infiles[i], info.outfile);
      my_fclose(fin, info.infiles[i]);
    }
    my_fclose(fout, info.outfile);
    free(info.outfile);
    return 0;

  }      

  /* not reached */
}
Ejemplo n.º 27
0
int main(int ac, char *av[]) {
  backend_t *b;  /* backend info */
  FILE *fin, *fout;
  int i;
  char *outfile;

  /* platform-specific initializations, e.g., set file i/o to binary */
  platform_init();

  /* process options */
  dopts(ac, av);

  b = info.backend;
  if (b==NULL) {
    fprintf(stderr, ""POTRACE": internal error: selected backend not found\n");
    exit(1);
  }

  /* fix some parameters */
  /* if backend cannot handle opticurve, disable it */
  if (b->opticurve == 0) {
    info.param->opticurve = 0;
  }

  /* there are several ways to call us:
     potrace                     -- stdin to stdout
     potrace -o outfile          -- stdin to outfile
     potrace file...             -- encode each file and generate outfile names
     potrace -o outfile file...  -- concatenate files and write to outfile

     The latter form is only allowed one file for single-page
     backends.  For multi-page backends, each file must contain 0 or
     more complete bitmaps.
  */

  if (!info.some_infiles) {                 /* read from stdin */

    fout = my_fopen_write(info.outfile);
    if (!fout) {
      fprintf(stderr, ""POTRACE": %s: %s\n", info.outfile ? info.outfile : "stdout", strerror(errno));
      exit(2); 
    }
    if (b->init_f) {
      TRY(b->init_f(fout));
    }
    process_file(b, "stdin", info.outfile ? info.outfile : "stdout", stdin, fout);
    if (b->term_f) {
      TRY(b->term_f(fout));
    }
    my_fclose(fout, info.outfile);
    free(info.outfile);
    potrace_param_free(info.param);
    return 0;

  } else if (!info.outfile) {                /* infiles -> multiple outfiles */

    for (i=0; i<info.infilecount; i++) {
      outfile = make_outfilename(info.infiles[i], b->ext);
      if (!outfile) {
	fprintf(stderr, ""POTRACE": %s\n", strerror(errno));
	exit(2);
      }
      fin = my_fopen_read(info.infiles[i]);
      if (!fin) {
	fprintf(stderr, ""POTRACE": %s: %s\n", info.infiles[i], strerror(errno));
	exit(2);
      }
      fout = my_fopen_write(outfile);
      if (!fout) {
	fprintf(stderr, ""POTRACE": %s: %s\n", outfile, strerror(errno));
	exit(2);
      }
      if (b->init_f) {
	TRY(b->init_f(fout));
      }
      process_file(b, info.infiles[i], outfile, fin, fout);
      if (b->term_f) {
	TRY(b->term_f(fout));
      }
      my_fclose(fin, info.infiles[i]);
      my_fclose(fout, outfile);
      free(outfile);
    }
    potrace_param_free(info.param);
    return 0; 

  } else {                                   /* infiles to single outfile */

    if (!b->multi && info.infilecount >= 2) {
      fprintf(stderr, ""POTRACE": cannot use multiple input files with -o in %s mode\n", b->name);
      exit(1);
    }
    if (info.infilecount == 0) {
      fprintf(stderr, ""POTRACE": cannot use empty list of input files with -o\n");
      exit(1);
    }
    
    fout = my_fopen_write(info.outfile);
    if (!fout) {
      fprintf(stderr, ""POTRACE": %s: %s\n", info.outfile, strerror(errno));
      exit(2);
    }
    if (b->init_f) {
      TRY(b->init_f(fout));
    }
    for (i=0; i<info.infilecount; i++) {
      fin = my_fopen_read(info.infiles[i]);
      if (!fin) {
	fprintf(stderr, ""POTRACE": %s: %s\n", info.infiles[i], strerror(errno));
	exit(2);
      }
      process_file(b, info.infiles[i], info.outfile, fin, fout);
      my_fclose(fin, info.infiles[i]);
    }
    if (b->term_f) {
      TRY(b->term_f(fout));
    }
    my_fclose(fout, info.outfile);
    free(info.outfile);
    potrace_param_free(info.param);
    return 0;

  }

  /* not reached */

 try_error:
  fprintf(stderr, ""POTRACE": %s\n", strerror(errno));
  exit(2);
}
void iothub_client_sample_http_run(void)
{
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

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

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

    callbackCounter = 0;

    if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        (void)printf("Starting the IoTHub client sample HTTP...\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");
            }

#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
            {
                int i;

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

                /* Now that we are ready to receive commands, let's send some messages */
                for (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
                    {
                        MAP_HANDLE propMap;

                        messages[i].messageTrackingId = i;

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

                        if (IoTHubClient_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", i);
                        }

                    }
                }
            }

            /* Wait for Commands. */
            while (1)
            {
                IoTHubClient_LL_DoWork(iotHubClientHandle);
            }

            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        platform_deinit();
    }
}
Ejemplo n.º 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
	{
		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;
}
Ejemplo n.º 30
0
int main(int argc, char** argv)
{
	if (argc < 2)
		err("usage : ./obj portno");

	int sfd[P];
	int i, nsfd, fd = -1;
	int port = atoi(argv[1]);
	char buf[M];

	fd_set master, test;
	FD_ZERO(&master);
	FD_ZERO(&test);

	shared_init();
	platform_init(port);

	for (i = 0; i < P; i++)
	{
		sfd[i] = tcpsocket_bind(port + i);
		printf("Station %d listening on port : %d\n", i, port + i);

		if (fd < sfd[i])
			fd = sfd[i];
		FD_SET(sfd[i], &master);
	}

	while (1)
	{
		test = master;
		select(fd + 1, &test, NULL, NULL, NULL);
		
		for (i = 0; i < P; i++)
		{
			if (FD_ISSET(sfd[i], &test))
			{
				nsfd = tcp_accept(sfd[i]);
				break;
			}
		}
		
		if (i != P)
		{
			printf("Train arrived on station - %d\n", i);
			for (i = 0; i < P; i++)
			{
				if (available(i))
				{
					printf("Platform %d is available\n", i + 1);
					sprintf(buf, "%d", port + P + i);
					write(nsfd, buf, M);
					sleep(1);
					sprintf(buf, "pkill -SIGUSR1 p%d", i + 1);
					system(buf);
					break;
				}
			}

			if (i == P)
			{
				write(nsfd, "-1", 2);
			}
			close(nsfd);
		}
	}
}