Exemple #1
0
// control / network / logic init
static void init_ctl(void) {
  // disable interrupts
  cpu_irq_disable();

  // intialize the event queue
  init_events();
  print_dbg("\r\n init_events");

  // intialize encoders
  print_dbg("\r\n init_encoders");
  init_encoders();

  // send ADC config
  print_dbg("\r\n init_adc");
  init_adc();

  // start timers
  print_dbg("\r\n init_sys_timers");
  init_sys_timers();
  //  init_app_timers();

  // enable interrupts
  cpu_irq_enable();

}
	void CamaraLucida::init_cml(string kinect_calibration_filename,
								string proj_calibration_filename,
								string xml_config_filename)
	{
		_inited = true;
		
		xml_config.loadFile(xml_config_filename);
		xml_config.pushTag("camaralucida");
		
		calib.near = xml_config.getValue("near", 0.1);
		calib.far = xml_config.getValue("far", 20.0);
		
		load_data(kinect_calibration_filename, proj_calibration_filename);
		
		proj_loc = ofVec3f(	proj_RT[12], proj_RT[13], proj_RT[14] );	
		proj_fwd = ofVec3f(	proj_RT[8], proj_RT[9], proj_RT[10] );
		proj_up = ofVec3f( proj_RT[4], proj_RT[5], proj_RT[6] );
		proj_trg = proj_loc + proj_fwd;
		
		rgb_loc = ofVec3f( rgb_RT[12], rgb_RT[13], rgb_RT[14] );	
		rgb_fwd = ofVec3f( rgb_RT[8], rgb_RT[9], rgb_RT[10] );
		rgb_up = ofVec3f( rgb_RT[4], rgb_RT[5], rgb_RT[6] );
		rgb_trg = rgb_loc + rgb_fwd;
		
		init_keys();
		init_events();
		init_gl_scene_control();
	}
    void CamaraLucida::init( 
            string config_path, Depthmap* depthmap )
    {
        this->depthmap = depthmap; 
        this->config_path = config_path;

        xml.loadFile(config_path);
        xml.pushTag("camaralucida");

        int dxoff = xml.getValue("depth_xoff", -8); 

        init_keys(); 
        init_events();

        config = new Config( &xml );

        Calibration calib( config ); 

        proj = new OpticalDevice( calib.proj_config() );
        depth = new cml::Kinect( calib.depth_config(), dxoff );
        rgb = new OpticalDevice( calib.rgb_config() );

        mesh = new Mesh( 
                config->mesh_step, 
                depth->width(), depth->height(),
                config->tex_width, config->tex_height );

        renderer = new Renderer(config, proj, depth, rgb);

        depthmap->init( depth, mesh );

        _debug = false;
        _render_help = false;
    };
Exemple #4
0
bool QuartzWindow::open( 
                    uint32  /* WindowClass */ wc,
                    int*    /* WindowAttributes  */  attrs,
                    int   left,
                    int   top, 
                    int   right, 
                    int   bottom, 
                    const char* title,
                    const char* font_name,
                    int   font_size ) {
  HIRect bounds = (HIRect) CGRectMake(left, top, right, bottom);
  
  OSStatus err =  HIWindowCreate(wc, attrs, NULL, kHICoordSpace72DPIGlobal, &bounds, &_quartz_win);
  if (err != noErr)
    return false;
  SetWRefCon(my_window(), (int32)this);

    
  CFStringRef cftitle = CFStringCreateWithCString(NULL, title, kCFStringEncodingMacRoman);
  SetWindowTitleWithCFString(my_window(), cftitle);
  CFRelease(cftitle);

  WindowSet::add_window(my_window());
  _is_open = true;
  
  init_colors();
  init_events();
  
  
  return true;                   
} 
//defined in the header file corresponding to this file
//
ComparisonReturnedTable CompareCVPolygons(std::vector<OPENCV_POINT>& poly_reference, std::vector<OPENCV_POINT>& poly_target)
{
    TURN_REP trf, trg;
    TURN_REP* f;
    TURN_REP* g;
    EVENT_REC e;
    double ht0, slope, alpha, theta_star, metric2, metric, ht0_err, slope_err;


        poly_to_turn_rep(poly_reference, &trg);
        g = &trg;

            poly_to_turn_rep(poly_target, &trf);
	    f = &trf;


              init_vals(f, g, &ht0, &slope, &alpha);
              init_events(f, g);
              metric2 = h_t0min(f, g,
			        ht0, slope, alpha,
                                reinit_interval(f, g),
                	        &theta_star, &e, &ht0_err, &slope_err);


            /*
             * Fixups: The value of metric2 can be a tiny
             * negative number for an exact match.  Call it 0.
             * Theta_star can be over 360 or under -360 because we
             * handle t=0 events at t=1. Normalize to [-PI,PI).
             */
            metric = metric2 > 0 ? sqrt(metric2) : 0;

		return ComparisonReturnedTable(metric, turn(theta_star, 0)*180/M_PI,
                   tr_i(f, e.fi), tr_i(g, e.gi), ht0_err, slope_err);
}
Exemple #6
0
/*
  initialize network
*/
bool setup_network(void) {
    now = time(NULL);

    init_events();
    init_connections();
    init_subnets();
    init_nodes();
    init_edges();
    init_requests();

    if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
        if(pinginterval < 1) {
            pinginterval = 86400;
        }
    } else
        pinginterval = 60;

    if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
        pingtimeout = 5;
    if(pingtimeout < 1 || pingtimeout > pinginterval)
        pingtimeout = pinginterval;

    if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
        maxoutbufsize = 10 * MTU;

    if(!setup_myself())
        return false;

    return true;
}
Exemple #7
0
void init(void)
  {
    mapy_init();
    ddl_init();
    vga_font = LoadResourceFont("BOLDCZ");
    default_font = vga_font;
    icones = LoadResourceFont("IKONY");
    graph_init(1);
    curcolor = RGB555(24,24,24);memcpy(charcolors,flat_color(0x0000),sizeof(charcolors));
    init_events(100);
    curfont = default_font;
    register_ms_cursor(LoadResourceFont("SIPKA.HI"));
    init_mysky();
//    hranice_mysky(0,0,639,479);
    add_task(1024,key_test);
    send_message(E_ADD,E_STATUS_LINE,status_line);
    send_message(E_STATUS_LINE,E_ADD,E_IDLE,all_status);
    send_message(E_STATUS_LINE,E_ADD,E_IDLE,status_mem_info);
    send_message(E_STATUS_LINE,E_ADD,E_IDLE,show_time);
    send_message(E_ADD,E_TIMER,pc_metter);
    send_message(E_ADD,E_KEYBOARD,exit_key);
    send_message(E_ADD,E_PRGERROR,prg_error);
    signal(SIGILL,raise_error_conv);
    signal(SIGSEGV,raise_error_conv);
    install_gui();
    redraw_desktop();do_events();
    send_message(E_ADD,E_MOUSE,main_menu);
    msg_box_font = vga_font;
    msg_icn_font = icones;
    ukaz_mysku();
    update_mysky();
    }
Exemple #8
0
int main(){
  initOpenGL(400,400);
  init_events();
  
  main_test();
  std::cout << "Testing mem corruption\n";
  int * i = new int[12345];
  delete i;
  std::cout << "OK\n";
  return 0;

}
Exemple #9
0
/*
 * INITIAL C ENTRY POINT.
 */
void _minios_start_kernel(start_info_t *si)
{

    bmk_printf_init(minios_putc, NULL);
    bmk_core_init(STACK_SIZE_PAGE_ORDER, PAGE_SHIFT);

    arch_init(si);
    trap_init();
    bmk_sched_init();

    /* print out some useful information  */
    minios_printk("  start_info: %p(VA)\n", si);
    minios_printk("    nr_pages: 0x%lx\n", si->nr_pages);
    minios_printk("  shared_inf: 0x%08lx(MA)\n", si->shared_info);
    minios_printk("     pt_base: %p(VA)\n", (void *)si->pt_base); 
    minios_printk("nr_pt_frames: 0x%lx\n", si->nr_pt_frames);
    minios_printk("    mfn_list: %p(VA)\n", (void *)si->mfn_list); 
    minios_printk("   mod_start: 0x%lx(VA)\n", si->mod_start);
    minios_printk("     mod_len: %lu\n", si->mod_len); 
    minios_printk("       flags: 0x%x\n", (unsigned int)si->flags);
    minios_printk("    cmd_line: %s\n",  
           si->cmd_line ? (const char *)si->cmd_line : "NULL");

    /* Set up events. */
    init_events();
    
    /* ENABLE EVENT DELIVERY. This is disabled at start of day. */
    __sti();

    arch_print_info();

    setup_xen_features();

    /* Init memory management. */
    init_mm();

    /* Init time and timers. */
    init_time();

    /* Init the console driver. */
    init_console();

    /* Init grant tables */
    init_gnttab();
 
    /* Init XenBus */
    init_xenbus();

    /* Init scheduler. */
    bmk_sched_startmain(_app_main, &start_info);
    bmk_platform_halt("unreachable");
}
CAMLprim value
stub_hypervisor_suspend(value unit)
{
  CAMLparam0();
  int cancelled;

  printk("WARNING: stub_hypervisor_suspend not yet implemented\n");
  cancelled = 1;
#if 0
  /* Turn the store and console mfns to pfns - required because xc_domain_restore uses these values */
  start_info.store_mfn = mfn_to_pfn(start_info.store_mfn);
  start_info.console.domU.mfn = mfn_to_pfn(start_info.console.domU.mfn);

  /* canonicalize_pagetables can't cope with pagetable entries that are outside of the guest's mfns,
     so we must unmap anything outside of our space */
  unmap_shared_info();

  /* Actually do the suspend. When this function returns 0, we've been resumed */
  cancelled = HYPERVISOR_suspend(virt_to_mfn(&start_info));

  if(cancelled) {
    start_info.store_mfn = pfn_to_mfn(start_info.store_mfn);
    start_info.console.domU.mfn = pfn_to_mfn(start_info.console.domU.mfn);
  }

  /* Reinitialise several things */
  trap_init();
  init_events();

  /* ENABLE EVENT DELIVERY. This is disabled at start of day. */
  local_irq_enable();

  setup_xen_features();
  HYPERVISOR_shared_info = map_shared_info(start_info.shared_info);

  /* Set up event and failsafe callback addresses. */
  HYPERVISOR_set_callbacks(
						   (unsigned long)hypervisor_callback,
						   (unsigned long)failsafe_callback, 0);

  init_time();
  arch_rebuild_p2m();

  unmask_evtchn(start_info.console.domU.evtchn);
  unmask_evtchn(start_info.store_evtchn);
#endif
  CAMLreturn(Val_int(cancelled));
}
Exemple #11
0
void start_kernel(void)
{
  printk("Mirage: start_kernel\n");

  /* Set up events. */
  init_events();

  /* Enable event delivery. This is disabled at start of day. */
  local_irq_enable();

  setup_xen_features();

  /* Init memory management.
   * Needed for malloc. */
  init_mm();

  /* Init time and timers. Needed for block_domain. */
  init_time();

  /* Init the console driver.
   * We probably do need this if we want printk to send notifications correctly. */
  init_console();

  /* Init grant tables. */
  init_gnttab();

#if 1
    /* Call our main function directly, without using Mini-OS threads. */
  app_main_thread(NULL);
#else
  /* Init scheduler. */
  /* Needed if you want to use create_thread, but we can get away without it. */
  init_sched();

  /* Init XenBus */
  /* Using Mini-OS's XenBus support requires threads. */
  init_xenbus();

  /* Respond to "xl shutdown". Requires XenBus. */
  create_thread("shutdown", shutdown_thread, NULL);

  create_thread("ocaml", app_main_thread, NULL);

  /* Everything initialised, start idle thread */
  run_idle_thread();
#endif
}
Exemple #12
0
int main(int argc, char *argv[]) {
	printf("mpflow - Copyright (C) 2009 Walter de Jong <*****@*****.**>\n");
	get_options(argc, argv);

	if (lock_program() == -1) {
		printf("another instance of mpflow is already running\n");
		return 1;
	}
	init_mpd();

/* init app */
	SDK_init();

	create_window();
	set_app_icon();

	init_gl();
	draw_startup();			/* only a border */

/* note that the order of init_() functions here is important (!) */
	init_textures();
	init_text();
	init_covers();
	init_events();

	init_widget_covers();
	init_widget_about();
	init_widget_aboutbutton();
	init_widget_titlebar();

	main_widget = &w_titlebar;
	prepare_widgets();
	draw();

	for(;;) {
		SDK_handle_events();
		move_covers();

		if (!moving)
			SDL_WaitEvent(NULL);
		else
			SDK_sleep(FRAME_DELAY);
	}
	exit_program(0);
	return 0;
}
Exemple #13
0
void start_kernel(void)
{
    /* Set up events. */
    init_events();

    /* ENABLE EVENT DELIVERY. This is disabled at start of day. */
    local_irq_enable();

    setup_xen_features();

    /* Init memory management. */
    init_mm();

    /* Init GDT */
    init_gdt();

    /* Init time and timers. */
    init_time();

    /* Init the console driver. */
    init_console();

    /* Init grant tables */
    init_gnttab();
    
    /* Init scheduler. */
    init_sched();
 
    /* Init XenBus */
    init_xenbus();

    /* Init futexes */
    init_futex();

#ifdef CONFIG_XENBUS
    create_thread("shutdown", shutdown_thread, NULL);
#endif

    /* Call (possibly overridden) app_main() */
    app_main(&start_info);

    /* Everything initialised, start idle thread */
    run_idle_thread();
}
Exemple #14
0
/*
 * INITIAL C ENTRY POINT.
 */
void start_kernel(start_info_t *si)
{
    static char hello[] = "Bootstrapping...\n";

    (void)HYPERVISOR_console_io(CONSOLEIO_write, strlen(hello), hello);

    arch_init(si);

    trap_init();

    /* print out some useful information  */
    printk("Mirage OS!\n");
    printk("  start_info: %p(VA)\n", si);
    printk("    nr_pages: 0x%lx\n", si->nr_pages);
    printk("  shared_inf: 0x%08lx(MA)\n", si->shared_info);
    printk("     pt_base: %p(VA)\n", (void *)si->pt_base); 
    printk("nr_pt_frames: 0x%lx\n", si->nr_pt_frames);
    printk("    mfn_list: %p(VA)\n", (void *)si->mfn_list); 
    printk("   mod_start: 0x%lx(VA)\n", si->mod_start);
    printk("     mod_len: %lu\n", si->mod_len); 
    printk("       flags: 0x%x\n", (unsigned int)si->flags);
    printk("    cmd_line: %s\n",  
           si->cmd_line ? (const char *)si->cmd_line : "NULL");

    /* Set up events. */
    init_events();
    
    /* ENABLE EVENT DELIVERY. This is disabled at start of day. */
    __sti();

    arch_print_info();

    setup_xen_features();

    /* Init memory management. */
    init_mm();

    /* Init time and timers. */
    init_time();

    /* Call (possibly overridden) app_main() */
    app_main(&start_info);
}
Exemple #15
0
int main(void)
{
	sysclk_init();

	init_dbg_rs232(FMCK_HZ);

	init_gpio();
	assign_main_event_handlers();
	init_events();
	init_tc();
	init_spi();
	init_adc();

	irq_initialize_vectors();
	register_interrupts();
	cpu_irq_enable();

	init_usb_host();
	init_monome();

	if(flash_is_fresh()) {
		// nothing has been stored in the flash memory so far
		// so you need to initialize any variables you store in flash here with appropriate default values
	}
	else {
		// read from flash
		flash_read();
	}

	clock_pulse = &clock;
	clock_external = !gpio_get_pin_value(B09);

	// start timers that track clock, ADCs (including the clock and the param knobs) and the front panel button
	timer_add(&clockTimer,120,&clockTimer_callback, NULL);
	timer_add(&keyTimer,50,&keyTimer_callback, NULL);
	timer_add(&adcTimer,100,&adcTimer_callback, NULL);
	clock_temp = 10000; // out of ADC range to force tempo

	// main loop - you probably don't need to do anything here as everything should be done by handlers
	while (true) {
		check_events();
	}
}
Exemple #16
0
t_env			*init_env(char *path)
{
	t_env		*e;

	if (!(e = (t_env *)malloc(sizeof(t_env))))
		ft_error(1, NULL, "Not enough memory.\n");
	if (!(e->mlx = mlx_init()))
		ft_error(1, e, "Mlx fail init.\n");
	if (!(e->win = mlx_new_window(e->mlx, WIDTH, HEIGHT, NAME)))
		ft_error(1, e, "Win fail init.\n");
	if (!init_scene(e, path))
		ft_error(1, e, "Wrong file format.\n");
	e->x_ratio = 0.5 / (double)WIDTH;
	e->y_ratio = 0.35 / (double)HEIGHT;
	init_events(e);
	init_types(e);
	init_screen(e->mlx, &e->screen, WIDTH, HEIGHT);
	return (e);
}
Exemple #17
0
int
main(int argc, char *argv[])
{
    int next_tick, loops;
    float interpolation;
    init_graphics("Graphics Demo");
    init_events();
    init_entities();


    next_tick = SDL_GetTicks();

    while( gameIsRunning ){
        loops = 0;
        /*
        if( SDL_GetTicks() == next_tick ){
            printf("Im here\n");
            SDL_Delay(10);
            continue;
        }
        */

        while( SDL_GetTicks() > next_tick && loops++ < MAX_FRAME_SKIP ){
            handle_events();
            update_game();

            next_tick += 1000 / GAME_SPEED_HZ;
        }

    
        interpolation = float(SDL_GetTicks() + (1000 / GAME_SPEED_HZ) - next_tick) / float(1000 / GAME_SPEED_HZ);
        render( interpolation );

        //putpixel( screen, 100, 100, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );


        //SDL_Flip(screen);
    }

    //SDL_FreeSurface( screen );
    clean_up();
}
Exemple #18
0
void startup() {
	totalbytes = 0;
	               
	printf("Acidblood %s\n", VERSION);
	init_conf() ;
	init_signals() ;
	init_networking() ;
	conf_userdata=NULL ;
	conf_channels=NULL ;
	init_usercommands() ;
	init_ctcp() ;
	init_srvcommands() ;
	init_log();
	init_serverinfo() ;
	init_numeric() ;
	init_timers() ;
	init_events() ;
	read_main_config() ;
	init_modules() ;
}
Exemple #19
0
static int init(void)
{
	srandom(time(NULL));

	if (!glfwInit()) {
		perror("Can't init glfw\n");
		goto err_glfw;
	}

	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	window = glfwCreateWindow(config.screen_width, config.screen_height, "Anko", NULL, NULL);
	if (!window) {
		glfwTerminate();
		goto err_window;
	}
	glfwMakeContextCurrent(window);

	printf("OpenGL Version : %s\n\n", glGetString(GL_VERSION));

	if (!init_context())
		goto err_context;
	if (!load_textures())
		goto err_texture;
	init_events(window);

	if(!load_font())
		goto err_font;

	return 1;

err_font:
	unload_textures();
err_texture:
	close_context();
err_context:
	glfwDestroyWindow(window);
err_window:
	glfwTerminate();
err_glfw:
	return 0;
}
/* Main kernel entry point, called by trampoline */
void start_kernel(start_info_t * start_info)
{
	/* Map the shared info page */
	HYPERVISOR_update_va_mapping((unsigned long) &shared_info, 
			__pte(start_info->shared_info | 7),
			UVMF_INVLPG);
	/* Set the pointer used in the bootstrap for reenabling
	 * event delivery after an upcall */
	HYPERVISOR_shared_info = &shared_info;
	/* Set up and unmask events */
	init_events();
	/* Initialise the console */
	console_init(start_info);
	/* Write a message to check that it worked */
	console_write("Hello world!\r\n");
	/* Loop, handling events */
	while(1)
	{
		HYPERVISOR_sched_op(SCHEDOP_block,0);
	}
}
Exemple #21
0
/* Main kernel entry point, called by trampoline */
void start_kernel (start_info_t *start_info)
{
    sched_shutdown_t op;

    /* Map the shared info page */
    HYPERVISOR_update_va_mapping((unsigned long) &shared_info,
                                 __pte(start_info->shared_info | 7),
                                 UVMF_INVLPG);

    HYPERVISOR_shared_info = &shared_info;

    init_events ();
    console_init (start_info);
    console_write ("Just a hello!\r\n");

    snprintf (buf, sizeof (buf), "1: %d, 2: %x\r\n", 1234, 1234);
    console_write (buf);

    /* 	op.reason = SHUTDOWN_poweroff; */
    /* 	HYPERVISOR_sched_op (SCHEDOP_shutdown, &op); */

    while (1)
        HYPERVISOR_sched_op (SCHEDOP_block, 0);
}
/*
 * Parse options, read polygons, convert to turning reps, initialize
 * everything, compute the answers, and print the answers.  Do all
 * this in a loop until all the polygons are gone.
 */
int main(int argc, char** argv)
{
    int update_p, precise_p, n_repeats, i;
    TURN_REP trf, trg;
    TURN_REP* f;
    TURN_REP* g;
    std::vector<OPENCV_POINT> pf, pg;
    EVENT_REC e;
    double ht0, slope, alpha, theta_star, metric2, metric, ht0_err, slope_err;

#ifdef CPU_TIME
    struct tms cpu_time;
    clock_t cpu_start_time;
    int elapsed_ms;
    int total_elapsed_ms = 0;
#define start_cpu_time() \
      (times(&cpu_time), cpu_start_time = cpu_time.tms_utime)
#define get_cpu_time() \
      (times(&cpu_time), (cpu_time.tms_utime - cpu_start_time)*1000/HZ)
#endif

    precise_p = 0;
    update_p = 1;
    n_repeats = 1;
    while(--argc)
    {
        ++argv;
        if (argv[0][0] == '-' && argv[0][1] != '\0')
            switch(argv[0][1]) {
                case 'p':
                    precise_p = 1;
                    break;
                case 'n':
                    update_p = 0;
                    break;
		case 'r':
		    if (sscanf(&argv[0][2], "%d", &i) == 1)
		      n_repeats = i;
		    break;
                default:
                    fprintf(stderr, "sim: unknown option\n");
                    return 1;
            }
    }
    if (read_poly(pg)) //reference polygon is pg
    {
        poly_to_turn_rep(pg, &trg);
        g = &trg;
        while (read_poly(pf))
        {
            poly_to_turn_rep(pf, &trf);
	    f = &trf;
#ifdef CPU_TIME
	    start_cpu_time();
#endif
	    /* Performance measure repeat loop. */
	    for (i = 0; i < n_repeats; ++i)
            {

              init_vals(f, g, &ht0, &slope, &alpha);
              init_events(f, g);
              metric2 = h_t0min(f, g,
			        ht0, slope, alpha,
                                update_p ? reinit_interval(f, g) : 0,
                	        &theta_star, &e, &ht0_err, &slope_err);
	    }
#ifdef CPU_TIME
	    elapsed_ms = get_cpu_time();
	    total_elapsed_ms += elapsed_ms;
#endif
            /*
             * Fixups: The value of metric2 can be a tiny
             * negative number for an exact match.  Call it 0.
             * Theta_star can be over 360 or under -360 because we
             * handle t=0 events at t=1. Normalize to [-PI,PI).
             */
            metric = metric2 > 0 ? sqrt(metric2) : 0;
            printf(precise_p ? "%.18lg %.18lg %d %d %lg %lg" : "%lg %lg %d %d %lg %lg",
                   metric, turn(theta_star, 0)*180/M_PI,
                   tr_i(f, e.fi), tr_i(g, e.gi), ht0_err, slope_err);

#ifdef CPU_TIME
	    printf(" %d\n", (elapsed_ms + (n_repeats/2))/n_repeats);
#else
	    printf("\n");
#endif

        }
    }

#ifdef CPU_TIME
    printf("total user time: %d ms\n", (total_elapsed_ms + (n_repeats/2))/n_repeats);
#endif

    return 0;
}
Exemple #23
0
/**
 * Initialize the PDCA transfer for the example.
 */
static void init_pdca(void)
{
	/* PDCA channel options */
	static const pdca_channel_config_t pdca_tx_configs = {
		.addr = (void *)event_string,
		.pid = PDCA_PID_USART2_TX,
		.size = sizeof(event_string),
		.r_addr = 0,
		.r_size = 0,
		.ring = false,
		.etrig = true,
		.transfer_size = PDCA_MR_SIZE_BYTE
	};

	/* Enable PDCA module */
	pdca_enable(PDCA);

	/* Init PDCA channel with the pdca_options.*/
	pdca_channel_set_config(PEVC_ID_USER_PDCA_0, &pdca_tx_configs);

	/* Set callback for PDCA channel */
	pdca_channel_set_callback(PEVC_ID_USER_PDCA_0, pdca_tranfer_done,
			PDCA_0_IRQn, 1, PDCA_IER_TRC | PDCA_IER_TERR);

	/* Enable PDCA channel */
	pdca_channel_enable(PEVC_ID_USER_PDCA_0);
}

/**
 *  Configure serial console.
 */
static void configure_console(void)
{
	const usart_serial_options_t uart_serial_options = {
		.baudrate = CONF_UART_BAUDRATE,
#ifdef CONF_UART_CHAR_LENGTH
		.charlength = CONF_UART_CHAR_LENGTH,
#endif
		.paritytype = CONF_UART_PARITY,
#ifdef CONF_UART_STOP_BITS
		.stopbits = CONF_UART_STOP_BITS,
#endif
	};

	/* Configure console. */
	stdio_serial_init(CONF_UART, &uart_serial_options);
}

/**
 * \brief Main entry point for event example.
 */
int main(void)
{
	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Initialize the console uart */
	configure_console();

	/* Output example information */
	printf("\r\n\r\n-- Events example 2 --\r\n");
	printf("-- %s\r\n", BOARD_NAME);
	printf("-- Compiled: %s %s --\r\n", __DATE__, __TIME__);

	/* Configure pin to trigger an enent on falling edge */
	ioport_set_pin_mode(CONF_EXAMPLE_PIN_EVENT, IOPORT_MODE_PULLUP |
			IOPORT_MODE_MUX_C);
	ioport_disable_pin(CONF_EXAMPLE_PIN_EVENT);
	ioport_set_pin_sense_mode(CONF_EXAMPLE_PIN_EVENT, IOPORT_SENSE_FALLING);
	gpio_enable_pin_periph_event(CONF_EXAMPLE_PIN_EVENT);
	printf(CONF_EXAMPLE_EVENT_MSG);

	init_events();

	init_pdca();

	while (1) {
		/* Toggle LED0 every 500 ms */
		LED_Toggle(LED0);
		delay_ms(500);
	}
}
Exemple #24
0
int main(int argc, char *argv[])
{
#ifndef _WIN32
  if (geteuid() == 0)
  {
    fprintf(stderr, "Running IRC services is root is not recommended.");
    return 1;
  }
  setup_corefile();
#endif
  memset(&ServicesInfo, 0, sizeof(ServicesInfo));
  memset(&ServicesState, 0, sizeof(ServicesState));

  ServicesState.configfile = CPATH; 
  ServicesState.logfile    = LPATH;
  ServicesState.pidfile    = PPATH;
  ServicesState.fully_connected = 0;

  parseargs(&argc, &argv, myopts);

  if(ServicesState.printversion)
  {
    printf("oftc-ircservices: version: %s\n", VERSION);
    exit(EXIT_SUCCESS);
  }

  if(chdir(DPATH))
  {
    perror("chdir");
    exit(EXIT_FAILURE);
  }

#ifndef _WIN32
  if(!ServicesState.foreground)
    make_daemon();
  else
    print_startup(getpid());
#endif

  setup_signals();
  memset(&me, 0, sizeof(me));

  libio_init(!ServicesState.foreground);
  init_events();
  iorecv_cb = register_callback("iorecv", iorecv_default);
  connected_cb = register_callback("server connected", server_connected);
  iosend_cb = register_callback("iosend", iosend_default);

  OpenSSL_add_all_digests();
 
  init_interface();
  check_pidfile(ServicesState.pidfile);
  init_log(ServicesState.logfile);

#ifdef HAVE_RUBY
  init_ruby();
  signal(SIGSEGV, SIG_DFL);
#endif

  init_channel();
  init_conf();
  init_client();
  init_parser();
  init_channel_modes();
  init_mqueue();
  init_tor();

  me.from = me.servptr = &me;
  SetServer(&me);
  SetMe(&me);
  dlinkAdd(&me, &me.node, &global_client_list);
  
  read_services_conf(TRUE);
  init_db();
  init_uid();
 
#ifdef HAVE_PYTHON
  init_python();
#endif

  init_kill();

  write_pidfile(ServicesState.pidfile);
  ilog(L_NOTICE, "Services Ready");

  db_load_driver();
#ifdef USE_SHARED_MODULES
  if(chdir(MODPATH))
  {
    ilog(L_ERROR, "Could not load core modules from %s: %s",
         MODPATH, strerror(errno));
    exit(EXIT_FAILURE);
  }

  /* Go back to DPATH after checking to see if we can chdir to MODPATH */
  chdir(DPATH);
#else
  load_all_modules(1);
#endif

  boot_modules(1);
  
  connect_server();

  for(;;)
  {
    while (eventNextTime() <= CurrentTime)
      eventRun();

    execute_callback(do_event_cb);

    if(events_loop() == -1)
    {
      ilog(L_CRIT, "libevent returned error %d", errno);
      services_die("Libevent returned some sort of error", NO);
      break;
    }

    comm_select();
    send_queued_all();

    if(dorehash)
    {
      ilog(L_INFO, "Got SIGHUP, reloading configuration");
      read_services_conf(NO);
      dorehash = 0;
    }
  }

  return 0;
}
Exemple #25
0
int mosquitto_main_loop(struct mosquitto_db *db, int *listensock, int listensock_count, int listener_max)
{
    time_t start_time = time(NULL);
    time_t last_backup = time(NULL);
    time_t last_store_clean = time(NULL);
    time_t now;

    sigset_t sigblock, origsig;

    int i, s;  /* temp variables */
    struct epoll_event* events = NULL;
    int epollfd_count = 0;
    int epollfd_index;
    int efd;  /* epoll fd */



    while (run) {

    mqtt3_db_sys_update(db, db->config->sys_interval, start_time);
    events = init_events(events, listensock_count, db->context_count, &epollfd_count);

    if (!events) {
        _mosquitto_log_printf (NULL, MOSQ_LOG_ERR, "Error: Out of memory.");
        return MOSQ_ERR_NOMEM;
    }

    memset(events, -1, sizeof(struct epoll_event) * epollfd_count);

    epollfd_index = 0;
    efd = create_event(events, listensock, listensock_count, &epollfd_index);

    now = time (NULL);
    reg_context_events(db, events, &epollfd_index, efd, now);


        mqtt3_db_message_timeout_check(db, db->config->retry_interval);

        sigprocmask(SIG_SETMASK, &sigblock, &origsig);

        s = epoll_wait(efd, events, 64, -1);

        if (s == -1) {
            printf("errno value: %d, it means: %s", errno, strerror(errno));
            loop_handle_errors(db, events, efd);
        }

        if (s == -1) {
            printf("errno value: %d, it means: %s", errno, strerror(errno));
            loop_handle_errors(db, events, efd);
        } else{
            loop_handle_reads_writes(db, events, efd);

            for(i=0; i<listensock_count; i++){
                if(events[i].events & (EPOLLIN | EPOLLPRI)){
                    while((s = mqtt3_socket_accept(db, listensock[i], &events[i], efd)) != -1){

                    }
                }
            }
        }

        sigprocmask(SIG_SETMASK, &origsig, NULL);

#ifdef WITH_PERSISTENCE
        if(db->config->persistence && db->config->autosave_interval){
            if(db->config->autosave_on_changes){
                if(db->persistence_changes > db->config->autosave_interval){
                    mqtt3_db_backup(db, false, false);
                    db->persistence_changes = 0;
                }
            }else{
                if(last_backup + db->config->autosave_interval < now){
                    mqtt3_db_backup(db, false, false);
                    last_backup = time(NULL);
                }
            }
        }
#endif
        if(!db->config->store_clean_interval || last_store_clean + db->config->store_clean_interval < now){
            mqtt3_db_store_clean(db);
            last_store_clean = time(NULL);
        }
#ifdef WITH_PERSISTENCE
        if(flag_db_backup){
            mqtt3_db_backup(db, false, false);
            flag_db_backup = false;
        }
#endif
        if(flag_reload){
            _mosquitto_log_printf(NULL, MOSQ_LOG_INFO, "Reloading config.");
            mqtt3_config_read(db->config, true);
            mosquitto_security_cleanup(db, true);
            mosquitto_security_init(db, true);
            mosquitto_security_apply(db);
            mqtt3_log_init(db->config->log_type, db->config->log_dest);
            flag_reload = false;
        }
        if(flag_tree_print){
            mqtt3_sub_tree_print(&db->subs, 0);
            flag_tree_print = false;
        }
    }

    if(events) _mosquitto_free(events);
    return MOSQ_ERR_SUCCESS;
}
Exemple #26
0
Fichier : rqd.c Projet : hyper/rqd
//-----------------------------------------------------------------------------
// Main... process command line parameters, and then setup our listening 
// sockets and event loop.
int main(int argc, char **argv) 
{
	system_data_t   sysdata;

///============================================================================
/// Initialization.
///============================================================================

	init_sysdata(&sysdata);
	init_settings(&sysdata);

	get_options(sysdata.settings, argc, argv);
	
	init_maxconns(&sysdata);
	init_daemon(&sysdata);
	init_events(&sysdata);
	init_logging(&sysdata);

	logger(sysdata.logging, 1, "System starting up");

	init_signals(&sysdata);
	init_buffers(&sysdata);
	init_servers(&sysdata);
	init_stats(&sysdata);
	init_risp(&sysdata);
	init_nodes(&sysdata);
	init_msglist(&sysdata);
	init_queues(&sysdata);
	init_controllers(&sysdata);


///============================================================================
/// Main Event Loop.
///============================================================================

	// enter the event loop.
	logger(sysdata.logging, 1, "Starting Event Loop");
	assert(sysdata.evbase);
	event_base_loop(sysdata.evbase, 0);
	logger(sysdata.logging, 1, "Shutdown preparations complete.  Shutting down now.");


///============================================================================
/// Shutdown
///============================================================================

	cleanup_events(&sysdata);
	cleanup_controllers(&sysdata);
	cleanup_queues(&sysdata);
	cleanup_msglist(&sysdata);
	cleanup_nodes(&sysdata);
	cleanup_risp(&sysdata);
	cleanup_stats(&sysdata);
	cleanup_servers(&sysdata);
	cleanup_buffers(&sysdata);
	cleanup_signals(&sysdata);
	
	logger(sysdata.logging, 1, "Shutdown complete.\n");

	cleanup_logging(&sysdata);
	cleanup_daemon(&sysdata);
	cleanup_maxconns(&sysdata);
	cleanup_settings(&sysdata);
	cleanup_sysdata(&sysdata);
	
	// good-bye.
	return 0;
}
Exemple #27
0
/**
 * \brief Initialize the PDCA transfer for the example.
 */
static void init_pdca(void)
{
	/* PDCA channel options */
	static const pdca_channel_config_t pdca_tx_configs = {
		.addr = (void *)event_string,
		.pid = CONF_PDCA_PID_USART_TX,
		.size = sizeof(event_string),
		.r_addr = 0,
		.r_size = 0,
		.ring = false,
		.etrig = true,
		.transfer_size = PDCA_MR_SIZE_BYTE
	};

	/* Enable PDCA module */
	pdca_enable(PDCA);

	/* Init PDCA channel with the pdca_options.*/
	pdca_channel_set_config(PEVC_ID_USER_PDCA_0, &pdca_tx_configs);

	/* Set callback for PDCA channel */
	pdca_channel_set_callback(PEVC_ID_USER_PDCA_0, pdca_tranfer_done,
			PDCA_0_IRQn, 1, PDCA_IER_TRC | PDCA_IER_TERR);

	/* Enable PDCA channel */
	pdca_channel_enable(PEVC_ID_USER_PDCA_0);
}

/**
 *  \brief Configure serial console.
 */
static void configure_console(void)
{
	const usart_serial_options_t uart_serial_options = {
		.baudrate = CONF_UART_BAUDRATE,
#ifdef CONF_UART_CHAR_LENGTH
		.charlength = CONF_UART_CHAR_LENGTH,
#endif /* CONF_UART_CHAR_LENGTH */
		.paritytype = CONF_UART_PARITY,
#ifdef CONF_UART_STOP_BITS
		.stopbits = CONF_UART_STOP_BITS,
#endif /* CONF_UART_STOP_BITS */
	};

	/* Configure console. */
	stdio_serial_init(CONF_UART, &uart_serial_options);
}

/**
 * \brief Main entry point for event example.
 */
int main(void)
{
	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Initialize the console uart */
	configure_console();

	/* Output example information */
	printf("\r\n\r\n-- Events example 1 --\r\n");
	printf("-- %s\r\n", BOARD_NAME);
	printf("-- Compiled: %s %s --\r\n", __DATE__, __TIME__);

	//! [quick_start_init_all_basic_use]
	/* Initialize AST as event generator. */
	//! [quick_start_init_ast_basic_use]
	init_ast();
	//! [quick_start_init_ast_basic_use]

	/* Initialise events for this example. */
	//! [quick_start_init_events_basic_use]
	init_events();
	//! [quick_start_init_events_basic_use]

	/* Initialize the PDCA as event user */
	//! [quick_start_init_pdca_basic_use]
	init_pdca();
	//! [quick_start_init_pdca_basic_use]
	//! [quick_start_init_all_basic_use]

	while (1) {
		/* Toggle LED0 every 500 ms */
		LED_Toggle(LED0);
		delay_ms(500);
	}
}
void initNtop(char *devices) {
  char value[32];

  revertSlashIfWIN32(myGlobals.dbPath, 0);
  revertSlashIfWIN32(myGlobals.spoolPath, 0);

  initIPServices();
  handleProtocols();

  myGlobals.l7.numSupportedProtocols = IPOQUE_MAX_SUPPORTED_PROTOCOLS;

  if(myGlobals.numIpProtosToMonitor == 0)
    addDefaultProtocols();

  /*
   * Initialize memory and data.
   */
  initDevices(devices);

  init_events();

  if(myGlobals.runningPref.enableSessionHandling)
    initPassiveSessions();

  initL7Discovery();

  /* ********************************** */

  initGdbm(myGlobals.dbPath, myGlobals.spoolPath, 0);

  /* We just initialized gdbm: let's now dump serials */
  dumpHostSerial(&myGlobals.broadcastEntry->hostSerial, myGlobals.broadcastEntry->serialHostIndex);
  dumpHostSerial(&myGlobals.otherHostEntry->hostSerial, myGlobals.otherHostEntry->serialHostIndex);

  if(myGlobals.runningPref.daemonMode) {
    /*
      Before bacoming a daemon we need o make sure that
      ntop has been installed properly and that all the
      html files are on the right place
    */

    int idx, found = 0;

    for(idx=0; (!found) && (myGlobals.dataFileDirs[idx] != NULL); idx++) {
      char tmpStr[256];
      struct stat statbuf;

      if(strcmp(myGlobals.dataFileDirs[idx], ".") /* ignore local paths */ ) {
	safe_snprintf(__FILE__, __LINE__, tmpStr, sizeof(tmpStr),
		      "%s/html/%s",
		      myGlobals.dataFileDirs[idx],
		      "ntop.gif" /* This file must always exist */);

	if(stat(tmpStr, &statbuf) == 0) {
	  found = 1;
	  break;
	}
      }
    }

    if(!found) {
      traceEvent(CONST_TRACE_WARNING, "ntop will not become a daemon as it has not been");
      traceEvent(CONST_TRACE_WARNING, "installed properly (did you do 'make install')");
    } else
      daemonizeUnderUnix();
  }

  /* Handle local addresses (if any) */
  handleLocalAddresses(myGlobals.runningPref.localAddresses);

  /* Handle known subnetworks (if any) */
  handleKnownAddresses(myGlobals.runningPref.knownSubnets);

  if((myGlobals.pcap_file_list != NULL) 
     && (myGlobals.runningPref.localAddresses == NULL)) {
    char *any_net = "0.0.0.0/0";

    traceEvent(CONST_TRACE_WARNING,
	       "-m | local-subnets must be specified when the -f option is used"
	       "Assuming %s", any_net);
    myGlobals.runningPref.localAddresses = strdup(any_net);
  }

  if(myGlobals.runningPref.currentFilterExpression != NULL)
    parseTrafficFilter();
  else
    myGlobals.runningPref.currentFilterExpression = strdup(""); /* so that it isn't NULL! */

  /* Handle flows (if any) */
  handleFlowsSpecs();

  createPortHash();
  initCounters();
  initApps();
  initThreads();

#ifndef MAKE_MICRO_NTOP
  traceEvent(CONST_TRACE_NOISY, "Starting Plugins");
  startPlugins();
  traceEvent(CONST_TRACE_NOISY, "Plugins started... continuing with initialization");
#endif

#if defined(MEMORY_DEBUG) && defined(MAKE_WITH_SAFER_ROUTINES)
  resetLeaks();
#endif

  addNewIpProtocolToHandle("IGMP", 2, 0 /* no proto */);
  addNewIpProtocolToHandle("OSPF", 89, 0 /* no proto */);
  addNewIpProtocolToHandle("IPsec", 50, 51);

  init_maps();
  loadGeoIP();

  /* Note that by default ntop will merge network interfaces */
  if(myGlobals.runningPref.mergeInterfaces == 0)
    traceEvent(CONST_TRACE_ALWAYSDISPLAY, "NOTE: Interface merge disabled by default");
  else
    traceEvent(CONST_TRACE_ALWAYSDISPLAY, "NOTE: Interface merge enabled by default");

  if(fetchPrefsValue("globals.displayPolicy", value, sizeof(value)) == -1) {
    myGlobals.hostsDisplayPolicy = showAllHosts /* 0 */;
    storePrefsValue("globals.displayPolicy", "0");
  } else {
    myGlobals.hostsDisplayPolicy = atoi(value);

    /* Out of range check */
    if((myGlobals.hostsDisplayPolicy < showAllHosts)
       || (myGlobals.hostsDisplayPolicy > showOnlyRemoteHosts))
      myGlobals.hostsDisplayPolicy = showAllHosts;
  }

  if(fetchPrefsValue("globals.localityPolicy", value, sizeof(value)) == -1) {
    myGlobals.localityDisplayPolicy = showSentReceived /* 0 */;
    storePrefsValue("globals.localityPolicy", "0");
  } else {
    myGlobals.localityDisplayPolicy = atoi(value);

    /* Out of range check */
    if((myGlobals.localityDisplayPolicy < showSentReceived)
       || (myGlobals.localityDisplayPolicy > showOnlyReceived))
      myGlobals.localityDisplayPolicy = showSentReceived;
  }

  if(myGlobals.runningPref.skipVersionCheck != TRUE) {
    pthread_t myThreadId;
    createThread(&myThreadId, checkVersion, NULL);
  }
}
Exemple #29
0
/* init_ll_socket */
ll_socket_t *init_ll_socket
	(	const bool is_transmitter, const int tx_delay,
		const char *ll_if_name, const int ll_sap,
		const int frame_type	)
{

	#ifdef KERNEL_RING
		int tx_socket_fd = -1, rx_socket_fd = -1;
	#else
		int socket_fd = -1;
	#endif
	int ll_if_index = -1;
	ll_socket_t *s = new_ll_socket();
	
	s->state = LL_SOCKET_STATE_UNDEF;

	// 1) create RAW socket(s)	
	#ifdef KERNEL_RING
		if ( ( tx_socket_fd = socket(AF_PACKET, SOCK_RAW, ll_sap) ) < 0 )
			{ handle_sys_error("Could not open TX socket"); }
		if ( ( rx_socket_fd = socket(AF_PACKET, SOCK_RAW, ll_sap) ) < 0 )
			{ handle_sys_error("Could not open RX socket"); }
	#else
		if ( ( socket_fd = socket(AF_PACKET, SOCK_RAW, ll_sap) ) < 0 )
			{ handle_sys_error("Could not open socket"); }
	#endif
/*
		int so_broadcast=1;
		int z = setsockopt(socket_fd,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof so_broadcast);
		printf("nome socket %d \n",socket_fd);

		if ( z )perror("setsockopt(2)");//If the setsockopt(2) function returns zero, the socket s has been enabled to perform broadcasting
		//printf(socket_fd);
*/
	
	// 2) initialize fields
	#ifdef KERNEL_RING
		s->tx_socket_fd = tx_socket_fd;
		s->rx_socket_fd = rx_socket_fd;
	#else
		s->socket_fd = socket_fd;
		s->buffer = new_ll_framebuffer();
	#endif

	s->ll_sap = ll_sap;
	s->frame_type = frame_type;
	s->tx_delay = tx_delay;

	#ifdef KERNEL_RING
		log_app_msg("Socket created, TX_FD = %d, RX_FD = %d, ll_sap = %d\n",
						tx_socket_fd, rx_socket_fd, ll_sap);
	#else
		log_app_msg("Socket created, FD = %d, ll_sap = %d\n",
						socket_fd, ll_sap);
	#endif
	
	// 3) get interface index from interface name
	#ifdef KERNEL_RING
		int socket_fd = tx_socket_fd;
	#endif
	//if ( ( ll_if_index = if_name_2_if_index(socket_fd, ll_if_name) ) < 0 ) //cambio
		if ((ll_if_index=if_nametoindex(ll_if_name))<0)
		{ handle_app_error("Could not get index, if_name = %s\n", ll_if_name); }
	//
	strncpy(s->if_name, ll_if_name, strlen(ll_if_name));
	s->if_index = ll_if_index;
	//printf("%s %d\n", ll_if_name,s->if_index);
	//int j=1;
	//printf(ll_if_index);
	
	// 4) get interface MAC address from interface name
	//if (is_transmitter){
	if ( get_mac_address
			(socket_fd, ll_if_name, (unsigned char *)s->if_mac) < 0 )
	{
		handle_app_error(	"Could not get MAC address, if_name = %s\n"
							, ll_if_name	);
	}//}

	log_app_msg("IF: name = %s, index = %d, MAC = ", ll_if_name, ll_if_index);
		print_eth_address((unsigned char *)s->if_mac);
		log_app_msg("\n");

	// 5) initialize events
	if ( init_events(is_transmitter, s) < 0 )
		{ handle_app_error("Could not initialize event manager!"); }
printf("volvo de init_events\n");
print_eth_address(s->if_mac);
	// Ready is socket's final state
	s->state = LL_SOCKET_STATE_READY;

	return(s);
	
}
Exemple #30
0
int main(void) {
	u8 i1;

	sysclk_init();

	init_dbg_rs232(FMCK_HZ);

	init_gpio();
	assign_main_event_handlers();
	init_events();
	init_tc();
	init_spi();
	init_adc();

	irq_initialize_vectors();
	register_interrupts();
	cpu_irq_enable();

	init_usb_host();
	init_monome();

	init_i2c_slave(0x30);

	print_dbg("\r\n\n// meadowphysics //////////////////////////////// ");
	print_dbg_ulong(sizeof(flashy));

	print_dbg(" ");
	print_dbg_ulong(sizeof(m));


	if(flash_is_fresh()) {
		print_dbg("\r\nfirst run.");
		flash_unfresh();
		flashc_memset32((void*)&(flashy.preset_select), 0, 4, true);


		// clear out some reasonable defaults
		for(i1=0;i1<8;i1++) {
			m.positions[i1] = i1;
			m.points[i1] = i1;
			m.points_save[i1] = i1;
			m.triggers[i1] = 0;
			m.trig_dests[i1] = 0;
			m.rules[i1] = 0;
			m.rule_dests[i1] = i1;
		}

		m.positions[0] = m.points[0] = 3;
		m.trig_dests[0] = 254;

		// save all presets, clear glyphs
		for(i1=0;i1<8;i1++) {
			flashc_memcpy((void *)&flashy.m[i1], &m, sizeof(m), true);
			glyph[i1] = (1<<i1);
			flashc_memcpy((void *)&flashy.glyph[i1], &glyph, sizeof(glyph), true);
		}
	}
	else {
		// load from flash at startup
		preset_select = flashy.preset_select;
		flash_read();
		for(i1=0;i1<8;i1++)
			glyph[i1] = flashy.glyph[preset_select][i1];
	}

	LENGTH = 15;
	SIZE = 16;

	re = &refresh;

	process_ii = &mp_process_ii;

	clock_pulse = &clock;
	clock_external = !gpio_get_pin_value(B09);

	timer_add(&clockTimer,120,&clockTimer_callback, NULL);
	timer_add(&keyTimer,50,&keyTimer_callback, NULL);
	timer_add(&adcTimer,100,&adcTimer_callback, NULL);
	clock_temp = 10000; // out of ADC range to force tempo

	while (true) {
		check_events();
	}
}