/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data)
{
  static struct etimer periodic, start_sending_timer;
  static struct ctimer backoff_timer;
  int start_sending_flag = 0;

  PROCESS_BEGIN();

  PROCESS_PAUSE();

  set_global_address();

  PRINTF("UDP client process started\n");

  print_local_addresses();
  cc2420_set_txpower(3);
  NETSTACK_MAC.off(1);
  /* new connection with remote host */
  client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL);
  if(client_conn == NULL) {
    PRINTF("No UDP connection available, exiting the process!\n");
    PROCESS_EXIT();
  }
  udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT));

  PRINTF("Created a connection with the server ");
  PRINT6ADDR(&client_conn->ripaddr);
  PRINTF(" local/remote port %u/%u\n",
         UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));

  /* new connection with MNs */
  mn_conn = udp_new(NULL, UIP_HTONS(UDP_MN_PORT2), NULL);
  if(mn_conn == NULL) {
    PRINTF("No MN UDP connection available, exiting the process!\n");
    PROCESS_EXIT();
  }
  udp_bind(mn_conn, UIP_HTONS(UDP_MN_PORT1));
  PRINTF("Created a connection with the client ");
    PRINT6ADDR(&mn_conn->ripaddr);
    PRINTF(" local/remote port %u/%u\n",
           UIP_HTONS(mn_conn->lport), UIP_HTONS(mn_conn->rport));

etimer_set(&start_sending_timer, START_SENDING_TIME);
  /*rpl_set_mode(RPL_MODE_LEAF);*/
  etimer_set(&periodic, SEND_INTERVAL);
  while(1) {
    PROCESS_YIELD();
    if(ev == tcpip_event) {
      tcpip_handler();
    }
if(etimer_expired(&start_sending_timer)){
	start_sending_flag = 1;
}
    if(etimer_expired(&periodic) && start_sending_flag == 1) {
      etimer_reset(&periodic);
      if(mobility_flag == 0) {
        ctimer_set(&backoff_timer, SEND_TIME, send_packet, NULL);
      }
    }
  }

  PROCESS_END();
}
Exemple #2
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(hello_world_process, ev, data)
{
  PROCESS_BEGIN();

  uint32_t                err_code;

  // Initialize the SoftDevice handler module.
  SOFTDEVICE_HANDLER_INIT(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, false);
  // Register with the SoftDevice handler module for BLE events.
  err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
  APP_ERROR_CHECK(err_code);
  // Register with the SoftDevice handler module for BLE events.
  err_code = softdevice_sys_evt_handler_set(sys_evt_dispatch);
  APP_ERROR_CHECK(err_code);

  ble_gap_conn_sec_mode_t sec_mode;
  char name_buffer[9];
  sprintf(name_buffer, "%08X",(unsigned int) NRF_FICR->DEVICEID[0]);
  BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  err_code = sd_ble_gap_device_name_set(&sec_mode,
                                        (const uint8_t *)name_buffer,
                                        strlen(name_buffer));
  APP_ERROR_CHECK(err_code);

  ble_advdata_t advdata;
  uint8_t       flags = BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
  ble_advdata_service_data_t service_data[2];
  uint8_t battery_data = 98;//battery_level_get();
  uint32_t temperature_data = 0xFE001213;
  service_data[0].service_uuid = BLE_UUID_BATTERY_SERVICE;
  service_data[0].data.size    = sizeof(battery_data);
  service_data[0].data.p_data  = &battery_data;
  service_data[1].service_uuid = BLE_UUID_HEALTH_THERMOMETER_SERVICE;
  service_data[1].data.size    = sizeof(temperature_data);
  service_data[1].data.p_data  = (uint8_t *) &temperature_data;
  // Build and set advertising data
  memset(&advdata, 0, sizeof(advdata));
  advdata.name_type            = BLE_ADVDATA_FULL_NAME;
  advdata.include_appearance   = false;
  advdata.flags.size           = sizeof(flags);
  advdata.flags.p_data         = &flags;
  advdata.service_data_count   = 2;
  advdata.p_service_data_array = service_data;
  err_code = ble_advdata_set(&advdata, NULL);
  APP_ERROR_CHECK(err_code);

  ble_gap_adv_params_t adv_params;
  // Start advertising
  memset(&adv_params, 0, sizeof(adv_params));
  adv_params.type        = BLE_GAP_ADV_TYPE_ADV_NONCONN_IND;
  adv_params.p_peer_addr = NULL;
  adv_params.fp          = BLE_GAP_ADV_FP_ANY;
  adv_params.interval    = ADV_INTERVAL;
  adv_params.timeout     = ADV_TIMEOUT_IN_SECONDS;
  err_code = sd_ble_gap_adv_start(&adv_params);
  APP_ERROR_CHECK(err_code);
  leds_off(LEDS_ALL);
  leds_on(LEDS_RED);

  PROCESS_PAUSE();
  etimer_set(&et_hello, CLOCK_SECOND/2);
  rand_val = 0;
  blinks = 0;

  while(1) {
    PROCESS_WAIT_EVENT();

    if(ev == PROCESS_EVENT_TIMER) {
    	sd_rand_application_vector_get(&blinks,1);
      printf("Sensor says #%X\n", (unsigned int) blinks);

      etimer_reset(&et_hello);
    }
  }

  PROCESS_END();
}
Exemple #3
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data) {
	PROCESS_BEGIN()
	;

	PROCESS_PAUSE()
	;

	set_global_address();

	//	senderStartTime = get_time_ms();
	PRINTF("UDP client process started\n");

	//	print_local_addresses();

	/* new connection with remote host */
	client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL);
	udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT));

	//	PRINTF("Created a connection with the server ");
	//	PRINT6ADDR(&client_conn->ripaddr);
	//	PRINTF(" local/remote port %u/%u\n",
	//			UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));
	// Initial value of nodeInf

	// Initial values
	nodeInf.sinkMinTX = 65535;
	stopCond = 0;

	static struct etimer et;

	//etimer_set(&et, CLOCK_SECOND * 1 + random_rand() % (CLOCK_SECOND * 1));

	static struct etimer periodic;
	//etimer_set(&et, 2 * CLOCK_SECOND);

	int i;
	while (1) {
//		PROCESS_YIELD();

		PROCESS_WAIT_EVENT()
		;

		/* Send a packet every 30 seconds. */
		if (etimer_expired(&periodic)) {
			i = 0;
			etimer_set(&periodic, CLOCK_SECOND * 2);
			etimer_set(&et, random_rand() % (CLOCK_SECOND * 2));
		}

		if (stopCond == 1) {
			break;
		}

		//

		if (ev == tcpip_event) {
			tcpip_handler();
		} else if (etimer_expired(&et)) {

			client_send();
		}
	}

PROCESS_END();
}
Exemple #4
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_server_process, ev, data)
{
  uip_ipaddr_t ipaddr;
  struct uip_ds6_addr *root_if;

  PROCESS_BEGIN();

  PROCESS_PAUSE();

  SENSORS_ACTIVATE(button_sensor);

  PRINTF("UDP server started\n");

#if UIP_CONF_ROUTER
  uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 1);
  /* uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); */
  uip_ds6_addr_add(&ipaddr, 0, ADDR_MANUAL);
  root_if = uip_ds6_addr_lookup(&ipaddr);
  if(root_if != NULL) {
    /*Changed*/
    rpl_dag_t *dag;  
    dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)&ipaddr);
    uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
    rpl_set_prefix(dag, &ipaddr, 64);
    PRINTF("created a new RPL dag\n");
#if PROJ_SMLT_TYPE
    rpl_dag_t *dag1;  
    dag1 = rpl_set_root(RPL_SECOND_INSTANCE,(uip_ip6addr_t *)&ipaddr);  
    rpl_set_prefix(dag1, &ipaddr, 64); 
    PRINTF("created a new RPL dag\n");
#endif
  } else {
    PRINTF("failed to create a new RPL DAG\n");
  }
#endif /* UIP_CONF_ROUTER */

  print_local_addresses();

  /* The data sink runs with a 100% duty cycle in order to ensure high
     packet reception rates. */
  NETSTACK_RDC.off(1);

  server_conn = udp_new(NULL, UIP_HTONS(UDP_CLIENT_PORT), NULL);
  udp_bind(server_conn, UIP_HTONS(UDP_SERVER_PORT));

  PRINTF("Created a server connection with remote address ");
  PRINT6ADDR(&server_conn->ripaddr);
  PRINTF(" local/remote port %u/%u\n", UIP_HTONS(server_conn->lport),
         UIP_HTONS(server_conn->rport));

  while(1) {
    PROCESS_YIELD();
    if(ev == tcpip_event) {
      tcpip_handler();
    } else if (ev == sensors_event && data == &button_sensor) {
      PRINTF("Initiaing global repair\n");
      rpl_repair_root(RPL_DEFAULT_INSTANCE);
#if PROJ_SMLT_TYPE
      /*Changed*/
      rpl_repair_root(RPL_SECOND_INSTANCE);
#endif
    }
  }

  PROCESS_END();
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data)
{
  static struct etimer periodic;
  static struct ctimer backoff_timer;
#if WITH_COMPOWER
  static int print = 0;
#endif

  PROCESS_BEGIN();

  PROCESS_PAUSE();

  SENSORS_ACTIVATE(battery_sensor);
  SENSORS_ACTIVATE(temp_mcu_sensor);
  SENSORS_ACTIVATE(light_sensor);
#ifdef CO2
  SENSORS_ACTIVATE(co2_sa_kxx_sensor);
#endif
  set_global_address();
  leds_init();

  PRINTF("UDP client process started\n");

  print_local_addresses();

  /* new connection with remote host */
  client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL); 
  if(client_conn == NULL) {
    PRINTF("No UDP connection available, exiting the process!\n");
    PROCESS_EXIT();
  }
  udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT)); 

  PRINTF("Created a connection with the server ");
  PRINT6ADDR(&client_conn->ripaddr);
  PRINTF(" local/remote port %u/%u\n",
	UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));

#if WITH_COMPOWER
  powertrace_sniff(POWERTRACE_ON);
#endif

  etimer_set(&periodic, SEND_INTERVAL);
  while(1) {
    PROCESS_YIELD();
    if(ev == tcpip_event) {
      tcpip_handler();
    }
    
    if(etimer_expired(&periodic)) {
      etimer_reset(&periodic);
      ctimer_set(&backoff_timer, SEND_TIME, send_packet, NULL);

#if WITH_COMPOWER
      if (print == 0) {
	powertrace_print("#P");
      }
      if (++print == 3) {
	print = 0;
      }
#endif

    }
  }

  PROCESS_END();
}
Exemple #6
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(border_router_process, ev, data)
{
  static struct etimer et;
  rpl_dag_t *dag;

  PROCESS_BEGIN();

/* While waiting for the prefix to be sent through the SLIP connection, the future
 * border router can join an existing DAG as a parent or child, or acquire a default 
 * router that will later take precedence over the SLIP fallback interface.
 * Prevent that by turning the radio off until we are initialized as a DAG root.
 */
  prefix_set = 0;
  NETSTACK_MAC.off(0);

  PROCESS_PAUSE();

  SENSORS_ACTIVATE(button_sensor);

  PRINTF("RPL-Border router started\n");
#if 0
   /* The border router runs with a 100% duty cycle in order to ensure high
     packet reception rates.
     Note if the MAC RDC is not turned off now, aggressive power management of the
     cpu will interfere with establishing the SLIP connection */
  NETSTACK_MAC.off(1);
#endif
 
  /* Request prefix until it has been received */
  while(!prefix_set) {
    etimer_set(&et, CLOCK_SECOND);
    request_prefix();
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
  }

  dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)dag_id);
  if(dag != NULL) {
    rpl_set_prefix(dag, &prefix, 64);
    PRINTF("created a new RPL dag\n");
  }

  /* Now turn the radio on, but disable radio duty cycling.
   * Since we are the DAG root, reception delays would constrain mesh throughbut.
   */
  NETSTACK_MAC.off(1);
  
#if DEBUG || 1
  print_local_addresses();
#endif

#if ENABLE_CBC_LINK_SECURITY
//   /*
//	* new connection with remote host at port 0
//	* to allow multiple remote ports on the same
//	* connection
//	*/
//	sec_conn = udp_new(NULL, 0, NULL);
//	if(sec_conn == NULL) {
//		PRINTFSECKEY("No UDP conn, exiting proc!\n");
//		PROCESS_EXIT();
//	}
//	udp_bind(sec_conn, UIP_HTONS(UDP_CLIENT_SEC_PORT));
#endif

  while(1) {
    PROCESS_YIELD();
    if (ev == sensors_event && data == &button_sensor) {
      PRINTF("Initiating global repair\n");
      rpl_repair_root(RPL_DEFAULT_INSTANCE);
    }
  }

  PROCESS_END();
}
Exemple #7
0
PROCESS_THREAD(shell_owtest_process, ev, data) {
	int err;

	PROCESS_BEGIN();

	// Attempt to acquire 1-Wire lock
	while (!ow_lock()) {
		PROCESS_PAUSE();
	}

	// Reset the bus
	err = ow_reset();
	if (err < 0) {
		shell_output_P(&owtest_command, PSTR("Bus reset failed.\n"));
		PROCESS_EXIT();
	}
	else if (err == 0) {
		shell_output_P(&owtest_command, PSTR("No presence detected.\n"));
		PROCESS_EXIT();
	}

	// Start the search
	err = ow_search_first(&search, 0);
	do {
		if (err < 0) {
			shell_output_P(&owtest_command, PSTR("Search error: %d\n"), err);
			PROCESS_EXIT();
		}
		else if (err == 0) {
			shell_output_P(&owtest_command, PSTR("No devices found.\n"));
			break;
		}

		// Print search result
		shell_output_P(&owtest_command,
			PSTR("Found: %02x.%02x%02x%02x%02x%02x%02x\n"),
			search.rom_no.family, // family code
			search.rom_no.id[0], search.rom_no.id[1], search.rom_no.id[2],
			search.rom_no.id[3], search.rom_no.id[4], search.rom_no.id[5]);

		// If it's a DS18B20, read it
		if (search.rom_no.family == 0x28) {
			shell_output_P(&owtest_command, PSTR("Reading temperature...\n"));
			PROCESS_PT_SPAWN(&ow_pt, read_temp(&ow_pt, &search.rom_no));
		}

		// If we found the last device on the bus, break out of the loop
		if (search.last_device_flag) {
			break;
		}

		// Find the next device on the bus
		err = ow_search_next(&search);
	} while (1);

	// Relinquish bus lock
	ow_unlock();

	shell_output_P(&owtest_command, PSTR("Search complete.\n"));

	PROCESS_END();
}
Exemple #8
0
PROCESS_THREAD(er_example_server, ev, data)
{
    
  PROCESS_BEGIN();

  PROCESS_PAUSE();

  PRINTF("Starting Erbium Example Server\n");

#ifdef RF_CHANNEL
  PRINTF("RF channel: %u\n", RF_CHANNEL);
#endif
#ifdef IEEE802154_PANID
  PRINTF("PAN ID: 0x%04X\n", IEEE802154_PANID);
#endif

  PRINTF("uIP buffer: %u\n", UIP_BUFSIZE);
  PRINTF("LL header: %u\n", UIP_LLH_LEN);
  PRINTF("IP+UDP header: %u\n", UIP_IPUDPH_LEN);
  PRINTF("REST max chunk: %u\n", REST_MAX_CHUNK_SIZE);

  /* Initialize the REST engine. */
  rest_init_engine();

  /*
   * Bind the resources to their Uri-Path.
   * WARNING: Activating twice only means alternate path, not two instances!
   * All static variables are the same for each URI path.
   */
//  rest_activate_resource(&res_hello, "test/hello");
/*  rest_activate_resource(&res_mirror, "debug/mirror"); */
/*  rest_activate_resource(&res_chunks, "test/chunks"); */
/*  rest_activate_resource(&res_separate, "test/separate"); */
  rest_activate_resource(&res_motion_periodic, "periodic/motion");
/*  rest_activate_resource(&res_event, "sensors/button"); */
/*  rest_activate_resource(&res_sub, "test/sub"); */
/*  rest_activate_resource(&res_b1_sep_b2, "test/b1sepb2"); */
#if PLATFORM_HAS_LEDS
  rest_activate_resource(&res_leds, "actuators/leds"); 
//  rest_activate_resource(&res_toggle, "actuators/toggle");
#endif
  
#if PLATFORM_HAS_ALARM
  rest_activate_resource(&res_alarm, "actuators/alarm");
  relay_enable(6);
#endif
  
#if PLATFORM_HAS_LB
  rest_activate_resource(&res_lb, "actuators/light_bulb");
  relay_enable(7);
#endif
  
#if PLATFORM_HAS_MOTION
  rest_activate_resource(&res_motion,"sensors/motion");
  SENSORS_ACTIVATE(phidgets);
#endif
  
#if PLATFORM_HAS_LIGHT
  rest_activate_resource(&res_light, "sensors/light"); 
  SENSORS_ACTIVATE(light_sensor);  
#endif

  

#if PLATFORM_HAS_SHT11
  rest_activate_resource(&res_sht11, "sensors/sht11");  
  SENSORS_ACTIVATE(sht11_sensor);  
  
#endif
//  SET_IP_FROM_STR((char *)THIS_IP,this_addr);
//    SET_THIS_ADDR(this_addr);
  /* Define application-specific events here. */
  while(1) {
    PROCESS_WAIT_EVENT();
#if PLATFORM_HAS_BUTTON
    if(ev == sensors_event && data == &button_sensor) {
      PRINTF("*******BUTTON*******\n");

      /* Call the event_handler for this application-specific event. */
      res_event.trigger();

      /* Also call the separate response example handler. */
      res_separate.resume();
    }
#endif /* PLATFORM_HAS_BUTTON */
  }                             /* while (1) */

  PROCESS_END();
}
PROCESS_THREAD(test_process, ev, data)
{
    static int n;
    static int i;
    static int errors = 0;
    static struct etimer timer;
    static uint32_t time_start, time_stop;
    uint8_t buffer[128];
    int bundle_length;
    struct mmem * bundle_original = NULL;
    struct mmem * bundle_restored = NULL;
    struct mmem * bundle_spare = NULL;
    uint32_t bundle_number;
    uint32_t bundle_number_spare;

    PROCESS_BEGIN();

    PROCESS_PAUSE();

    profiling_init();
    profiling_start();

    // Wait again
    etimer_set(&timer, CLOCK_SECOND);
    PROCESS_WAIT_UNTIL(etimer_expired(&timer));

    /* Profile initialization separately */
    profiling_stop();
    watchdog_stop();
    profiling_report("init", 0);
    watchdog_start();
    printf("Init done, starting test using %s storage\n", BUNDLE_STORAGE.name);

    profiling_init();
    profiling_start();

    // Measure the current time
    time_start = test_precise_timestamp();

    for(i=0; i<=1; i++) {
        struct mmem bla;
        if( i > 0 ) {
            mmem_alloc(&bla, 1);
        }

        printf("Serializing and deserializing bundle...\n");
        if( my_create_bundle(0, &bundle_number, 3600) ) {
            printf("\tBundle created successfully \n");
        } else {
            printf("\tBundle could not be created \n");
            errors ++;
        }

        printf("Serializing and deserializing bundle...\n");
        if( my_create_bundle(1, &bundle_number_spare, 3600) ) {
            printf("\tSpare Bundle created successfully \n");
        } else {
            printf("\tSpare Bundle could not be created \n");
            errors ++;
        }

        bundle_original = BUNDLE_STORAGE.read_bundle(bundle_number);
        if( bundle_original == NULL ) {
            printf("VERIFY: MMEM ptr is invalid\n");
            errors ++;
        }

        bundle_spare = BUNDLE_STORAGE.read_bundle(bundle_number_spare);
        if( bundle_spare == NULL ) {
            printf("VERIFY: MMEM ptr is invalid\n");
            errors ++;
        }

        // Fake timing information in the bundle to make verify successful
        struct bundle_t * bundle_original_bundle = (struct bundle_t *) MMEM_PTR(bundle_original);
        bundle_original_bundle->aeb_value_ms = 54;
        bundle_original_bundle->rec_time = clock_time();

        // Serialize the bundle
        memset(buffer, 0, 128);
        bundle_length = bundle_encode_bundle(bundle_original, buffer, 128);
        if( bundle_length < 0 ) {
            printf("SERIALIZE: fail\n");
            errors ++;
        }

        n = my_static_compare(buffer, bundle_length);
        if( n > 0 ) {
            printf("COMPARE: fail\n");
            errors += n;
        }

        // Deserialize it
        bundle_restored = bundle_recover_bundle(buffer, bundle_length);
        if( bundle_restored == NULL ) {
            printf("DESERIALIZE: unable to recover\n");
            errors ++;
        }

        n = my_compare_bundles(bundle_original, bundle_restored);
        if( n == 0 ) {
            printf("\tBundle serialized and deserialized successfully\n");
        } else {
            printf("COMPARE: differences\n");
            errors ++;
        }

        // Dellocate memory
        bundle_decrement(bundle_restored);
        bundle_restored = NULL;

        bundle_decrement(bundle_original);
        bundle_original = NULL;

        bundle_decrement(bundle_spare);
        bundle_spare = NULL;

        memset(buffer, 0, 128);

        // Delete bundle from storage
        n = BUNDLE_STORAGE.del_bundle(bundle_number, REASON_DELIVERED);
        if( n ) {
            printf("\tBundle deleted successfully\n");
        } else {
            printf("\tBundle could not be deleted\n");
            errors++;
        }


        printf("Comparing static bundle...\n");
        if( my_create_bundle(0, &bundle_number, 3600) ) {
            printf("\tReference Bundle created successfully \n");
        } else {
            printf("\ttReference Bundle could not be created \n");
            errors ++;
        }

        bundle_original = BUNDLE_STORAGE.read_bundle(bundle_number);
        if( bundle_original == NULL ) {
            printf("VERIFY: MMEM ptr is invalid\n");
            errors ++;
        }

        // Deserialize it
        bundle_restored = bundle_recover_bundle(static_compare_bundle, sizeof(static_compare_bundle));
        if( bundle_restored == NULL ) {
            printf("DESERIALIZE: unable to recover static bundle\n");
            errors ++;
        }

        // Deserialize it one more time
        bundle_spare = bundle_recover_bundle(static_compare_bundle, sizeof(static_compare_bundle));
        if( bundle_spare == NULL ) {
            printf("DESERIALIZE: unable to recover static bundle\n");
            errors ++;
        }

        n = my_compare_bundles(bundle_original, bundle_restored);
        if( n == 0 ) {
            printf("\tStatic Bundle verified successfully\n");
        } else {
            printf("COMPARE: differences\n");
            errors ++;
        }

        n = my_compare_bundles(bundle_original, bundle_spare);
        if( n == 0 ) {
            printf("\tStatic Bundle verified successfully\n");
        } else {
            printf("COMPARE: differences\n");
            errors ++;
        }

        // Dellocate memory
        bundle_decrement(bundle_restored);
        bundle_restored = NULL;

        bundle_decrement(bundle_original);
        bundle_original = NULL;

        bundle_decrement(bundle_spare);
        bundle_spare = NULL;
    }

    time_stop = test_precise_timestamp();

    watchdog_stop();
    profiling_report("serializer", 0);

    TEST_REPORT("No of errors", errors, 1, "errors");
    TEST_REPORT("Duration", time_stop-time_start, CLOCK_SECOND, "s");

    if( errors > 0 ) {
        TEST_FAIL("More than 0 errors occured");
    } else {
        TEST_PASS();
    }

    PROCESS_END();
}
Exemple #10
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(ctr_test_process, ev, data)
{
  static const char *const str_res[] = {
    "success",
    "invalid param",
    "NULL error",
    "resource in use",
    "DMA bus error",
    "keystore read error",
    "keystore write error",
    "authentication failed"
  };
  static const uint8_t keys128[][128 / 8] = {
    { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
      0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }
  };
  static const uint8_t keys192[][192 / 8] = {
    { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52,
      0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
      0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b }
  };
  static const uint8_t keys256[][256 / 8] = {
    { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe,
      0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
      0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7,
      0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 }
  };
  static const struct {
    const void *keys;
    uint8_t key_size;
    uint8_t count;
  } keys[] = {
    { keys128, AES_KEY_STORE_SIZE_KEY_SIZE_128,
      sizeof(keys128) / sizeof(keys128[0]) },
    { keys192, AES_KEY_STORE_SIZE_KEY_SIZE_192,
      sizeof(keys192) / sizeof(keys192[0]) },
    { keys256, AES_KEY_STORE_SIZE_KEY_SIZE_256,
      sizeof(keys256) / sizeof(keys256[0]) }
  };
  static const struct {
    bool encrypt;
    uint8_t key_size_index;
    uint8_t key_area;
    uint8_t nonce[NONCE_MAX_LEN];
    uint8_t ictr[ICTR_MAX_LEN];
    uint8_t ctr_len;
    uint8_t mdata[MDATA_MAX_LEN];
    uint16_t mdata_len;
    uint8_t expected[MDATA_MAX_LEN];
  } vectors[] = {
    {
      true, /* encrypt */
      0, /* key_size_index */
      0, /* key_area */
      {}, /* nonce */
      { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
        0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, /* ictr */
      16, /* ctr_len */
      { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
        0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
        0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
        0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
        0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
        0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
        0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
        0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }, /* mdata */
      64, /* mdata_len */
      { 0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26,
        0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce,
        0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff,
        0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff,
        0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e,
        0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab,
        0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1,
        0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee } /* expected */
    }, {
      false, /* encrypt */
      0, /* key_size_index */
      0, /* key_area */
      {}, /* nonce */
      { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
        0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, /* ictr */
      16, /* ctr_len */
      { 0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26,
        0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce,
        0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff,
        0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff,
        0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e,
        0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab,
        0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1,
        0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee }, /* mdata */
      64, /* mdata_len */
      { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
        0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
        0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
        0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
        0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
        0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
        0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
        0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 } /* expected */
    }, {
      true, /* encrypt */
      1, /* key_size_index */
      0, /* key_area */
      {}, /* nonce */
      { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
        0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, /* ictr */
      16, /* ctr_len */
      { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
        0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
        0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
        0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
        0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
        0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
        0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
        0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }, /* mdata */
      64, /* mdata_len */
      { 0x1a, 0xbc, 0x93, 0x24, 0x17, 0x52, 0x1c, 0xa2,
        0x4f, 0x2b, 0x04, 0x59, 0xfe, 0x7e, 0x6e, 0x0b,
        0x09, 0x03, 0x39, 0xec, 0x0a, 0xa6, 0xfa, 0xef,
        0xd5, 0xcc, 0xc2, 0xc6, 0xf4, 0xce, 0x8e, 0x94,
        0x1e, 0x36, 0xb2, 0x6b, 0xd1, 0xeb, 0xc6, 0x70,
        0xd1, 0xbd, 0x1d, 0x66, 0x56, 0x20, 0xab, 0xf7,
        0x4f, 0x78, 0xa7, 0xf6, 0xd2, 0x98, 0x09, 0x58,
        0x5a, 0x97, 0xda, 0xec, 0x58, 0xc6, 0xb0, 0x50 } /* expected */
    }, {
      false, /* encrypt */
      1, /* key_size_index */
      0, /* key_area */
      {}, /* nonce */
      { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
        0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, /* ictr */
      16, /* ctr_len */
      { 0x1a, 0xbc, 0x93, 0x24, 0x17, 0x52, 0x1c, 0xa2,
        0x4f, 0x2b, 0x04, 0x59, 0xfe, 0x7e, 0x6e, 0x0b,
        0x09, 0x03, 0x39, 0xec, 0x0a, 0xa6, 0xfa, 0xef,
        0xd5, 0xcc, 0xc2, 0xc6, 0xf4, 0xce, 0x8e, 0x94,
        0x1e, 0x36, 0xb2, 0x6b, 0xd1, 0xeb, 0xc6, 0x70,
        0xd1, 0xbd, 0x1d, 0x66, 0x56, 0x20, 0xab, 0xf7,
        0x4f, 0x78, 0xa7, 0xf6, 0xd2, 0x98, 0x09, 0x58,
        0x5a, 0x97, 0xda, 0xec, 0x58, 0xc6, 0xb0, 0x50 }, /* mdata */
      64, /* mdata_len */
      { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
        0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
        0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
        0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
        0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
        0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
        0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
        0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 } /* expected */
    }, {
      true, /* encrypt */
      2, /* key_size_index */
      0, /* key_area */
      {}, /* nonce */
      { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
        0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, /* ictr */
      16, /* ctr_len */
      { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
        0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
        0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
        0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
        0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
        0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
        0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
        0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }, /* mdata */
      64, /* mdata_len */
      { 0x60, 0x1e, 0xc3, 0x13, 0x77, 0x57, 0x89, 0xa5,
        0xb7, 0xa7, 0xf5, 0x04, 0xbb, 0xf3, 0xd2, 0x28,
        0xf4, 0x43, 0xe3, 0xca, 0x4d, 0x62, 0xb5, 0x9a,
        0xca, 0x84, 0xe9, 0x90, 0xca, 0xca, 0xf5, 0xc5,
        0x2b, 0x09, 0x30, 0xda, 0xa2, 0x3d, 0xe9, 0x4c,
        0xe8, 0x70, 0x17, 0xba, 0x2d, 0x84, 0x98, 0x8d,
        0xdf, 0xc9, 0xc5, 0x8d, 0xb6, 0x7a, 0xad, 0xa6,
        0x13, 0xc2, 0xdd, 0x08, 0x45, 0x79, 0x41, 0xa6 } /* expected */
    }, {
      false, /* encrypt */
      2, /* key_size_index */
      0, /* key_area */
      {}, /* nonce */
      { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
        0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, /* ictr */
      16, /* ctr_len */
      { 0x60, 0x1e, 0xc3, 0x13, 0x77, 0x57, 0x89, 0xa5,
        0xb7, 0xa7, 0xf5, 0x04, 0xbb, 0xf3, 0xd2, 0x28,
        0xf4, 0x43, 0xe3, 0xca, 0x4d, 0x62, 0xb5, 0x9a,
        0xca, 0x84, 0xe9, 0x90, 0xca, 0xca, 0xf5, 0xc5,
        0x2b, 0x09, 0x30, 0xda, 0xa2, 0x3d, 0xe9, 0x4c,
        0xe8, 0x70, 0x17, 0xba, 0x2d, 0x84, 0x98, 0x8d,
        0xdf, 0xc9, 0xc5, 0x8d, 0xb6, 0x7a, 0xad, 0xa6,
        0x13, 0xc2, 0xdd, 0x08, 0x45, 0x79, 0x41, 0xa6 }, /* mdata */
      64, /* mdata_len */
      { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
        0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
        0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
        0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
        0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
        0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
        0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
        0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 } /* expected */
    }
  };
  static uint8_t mdata[MDATA_MAX_LEN];
  static int i;
  static uint8_t key_size_index = -1, ret;
  static int8_t res;
  static rtimer_clock_t time, time2, total_time;

  PROCESS_BEGIN();

  puts("-----------------------------------------\n"
       "Initializing cryptoprocessor...");
  crypto_init();

  for(i = 0; i < sizeof(vectors) / sizeof(vectors[0]); i++) {
    if(key_size_index != vectors[i].key_size_index) {
      key_size_index = vectors[i].key_size_index;
      printf("-----------------------------------------\n"
             "Filling %d-bit key store...\n", 128 + (key_size_index << 6));
      time = RTIMER_NOW();
      ret = aes_load_keys(keys[key_size_index].keys,
              keys[key_size_index].key_size, keys[key_size_index].count, 0);
      time = RTIMER_NOW() - time;
      printf("aes_load_keys(): %s, %lu us\n", str_res[ret],
             (uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
      PROCESS_PAUSE();
      if(ret != CRYPTO_SUCCESS) {
        break;
      }
    }

    printf("-----------------------------------------\n"
           "Test vector #%d: %s\n"
           "key_area=%d ctr_len=%d mdata_len=%d\n",
           i, vectors[i].encrypt ? "encrypt" : "decrypt",
           vectors[i].key_area, vectors[i].ctr_len, vectors[i].mdata_len);

    /* mdata has to be in SRAM. */
    rom_util_memcpy(mdata, vectors[i].mdata, vectors[i].mdata_len);

    time = RTIMER_NOW();
    ret = ctr_crypt_start(vectors[i].encrypt, vectors[i].key_area,
                          vectors[i].nonce, vectors[i].ictr, vectors[i].ctr_len,
                          mdata, mdata, vectors[i].mdata_len,
                          &ctr_test_process);
    time2 = RTIMER_NOW();
    time = time2 - time;
    total_time = time;
    if(ret == CRYPTO_SUCCESS) {
      PROCESS_WAIT_EVENT_UNTIL((res = ctr_crypt_check_status()) !=
                               CRYPTO_PENDING);
      time2 = RTIMER_NOW() - time2;
      total_time += time2;
    }
    printf("ctr_crypt_start(): %s, %lu us\n", str_res[ret],
           (uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
    if(ret != CRYPTO_SUCCESS) {
      PROCESS_PAUSE();
      continue;
    }
    printf("ctr_crypt_check_status() wait: %s, %lu us\n", str_res[res],
           (uint32_t)((uint64_t)time2 * 1000000 / RTIMER_SECOND));
    PROCESS_PAUSE();
    if(res != CRYPTO_SUCCESS) {
      continue;
    }

    if(rom_util_memcmp(mdata, vectors[i].expected, vectors[i].mdata_len)) {
      puts("Output message does not match expected one");
    } else {
      puts("Output message OK");
    }

    printf("Total duration: %lu us\n",
           (uint32_t)((uint64_t)total_time * 1000000 / RTIMER_SECOND));
  }

  puts("-----------------------------------------\n"
       "Disabling cryptoprocessor...");
  crypto_disable();

  puts("Done!");

  PROCESS_END();
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(simple_transceiver_process, ev, data)
{
	static struct registration_api registration;
	static struct etimer timer;
	static int create_bundles;
	struct bundle_block_t * block = NULL;
	struct mmem * incoming_bundle_memory = NULL;
	int n;

	PROCESS_BEGIN();

	/* Wait for the agent to be initialized */
	PROCESS_PAUSE();

	/* Register our endpoint to send and receive bundles */
	registration.status = APP_ACTIVE;
	registration.application_process = PROCESS_CURRENT();
	registration.app_id = 15;
	process_post(&agent_process, dtn_application_registration_event, &registration);

	/* Set a timer */
	etimer_set(&timer, CLOCK_SECOND * 6);

	/* And enable bundle creation */
	create_bundles = 1;

	/* Continously send bundles */
	while(1) {
		PROCESS_WAIT_EVENT();

		/* Send the next bundle */
		if( etimer_expired(&timer) && create_bundles ) {
			/* We need payload */
			uint8_t payload[40];
			memset(payload, 0, 40);

			printf("Sending bundle to ipn:%lu.%d\n", CONF_SEND_TO_NODE, CONF_SEND_TO_SERVICE);

			/* Send out the bundle with our payload */
			n = send_bundle(CONF_SEND_TO_NODE, CONF_SEND_TO_SERVICE, payload, 40);

			if( n >= 0 ) {
				/* Whenever we have sent a bundle, we wait for feedback from the agent */
				create_bundles = 0;
			} else {
				/* Otherwise we just reschedule and send again */
				etimer_reset(&timer);
			}
		}

		/* The last bundle has been saved */
		if( ev == dtn_bundle_stored ) {
			/* The bundle has been processed, so create more bundles */
			create_bundles = 1;
			etimer_restart(&timer);
		}

		/* The last bundle could not be saved */
		if( ev == dtn_bundle_store_failed ) {
			/* The bundle has been (unsuccessfully) processed, so create more bundles */
			create_bundles = 1;
			etimer_restart(&timer);
		}

		/* Incoming bundle */
		if( ev == submit_data_to_application_event ) {
			/* data contains a pointer to the bundle memory */
			incoming_bundle_memory = (struct mmem *) data;

			/* We can read several attributes as defined in bundle.h */
			uint32_t source_node;
			uint32_t source_service;
			bundle_get_attr(incoming_bundle_memory, SRC_NODE, &source_node);
			bundle_get_attr(incoming_bundle_memory, SRC_SERV, &source_service);

			/* We can obtain the bundle payload block like so: */
			block = bundle_get_payload_block(incoming_bundle_memory);

			printf("Bundle received from ipn:%lu.%lu with %u bytes: ", source_node, source_service, block->block_size);
			for(n=0; n<block->block_size; n++) {
				printf("%02X ", block->payload[n]);
			}
			printf("\n");

			/* After processing the bundle, we have to notify the agent to free up the memory */
			process_post(&agent_process, dtn_processing_finished, incoming_bundle_memory);

			/* Afterwards, we should void our pointer to not get confused */
			incoming_bundle_memory = NULL;
		}

	}

	PROCESS_END();
}
PROCESS_THREAD(border_router_process, ev, data)
{
  static struct etimer et;
  rpl_dag_t *dag;

  PROCESS_BEGIN();
  prefix_set = 0;

  PROCESS_PAUSE();

  PRINTF("RPL-Border router started\n");

  slip_config_handle_arguments(contiki_argc, contiki_argv);

  /* tun init is also responsible for setting up the SLIP connection */
  tun_init();

  while(!mac_set) {
    etimer_set(&et, CLOCK_SECOND);
    request_mac();
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
  }

  if(slip_config_ipaddr != NULL) {
    uip_ipaddr_t prefix;

    if(uiplib_ipaddrconv((const char *)slip_config_ipaddr, &prefix)) {
      PRINTF("Setting prefix ");
      PRINT6ADDR(&prefix);
      PRINTF("\n");
      set_prefix_64(&prefix);
    } else {
      PRINTF("Parse error: %s\n", slip_config_ipaddr);
      exit(0);
    }
  }

  dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)dag_id);
  if(dag != NULL) {
    rpl_set_prefix(dag, &prefix, 64);
    PRINTF("created a new RPL dag\n");
  }

#if DEBUG
  print_local_addresses();
#endif

  /* The border router runs with a 100% duty cycle in order to ensure high
     packet reception rates. */
  //NETSTACK_MAC.off(1);
  udp_bconn = udp_broadcast_new(UIP_HTONS(BROADCAST_PORT), tcpip_handler);
  while(1) {
	PROCESS_YIELD();
        if(ev==tcpip_event)
        {	printf("Tcpip event\n");
                tcpip_handler();
        }	
    /* do anything here??? */
  }

  PROCESS_END();
}
Exemple #13
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(shell_repeat_process, ev, data)
{
  static int reps, period;
  static char command[MAX_COMMANDLENGTH];
  static struct etimer etimer;
  static int i;
  const char *args, *next;

  if(ev == shell_event_input) {
    struct shell_input *input;
    input = data;
    /*    printf("shell repeat input %d %d\n", input->len1, input->len2);*/
    if(input->len1 + input->len2 != 0) {
      shell_output(&repeat_command, input->data1, input->len1,
		   input->data2, input->len2);
    }
  }

  PROCESS_BEGIN();

  /*  printf("data '%s'\n", data);*/

  args = data;

  if(args == NULL) {
    shell_output_str(&repeat_command, "usage 0", "");
    PROCESS_EXIT();
  }
  
  reps = shell_strtolong(args, &next);
  if(next == args) {
    shell_output_str(&repeat_command, "usage 1", "");
    PROCESS_EXIT();
  }

  args = next;
  period = shell_strtolong(args, &next);
  if(next == args) {
    shell_output_str(&repeat_command, "usage 2", "");
    PROCESS_EXIT();
  }

  args = next;

  while(*args == ' ') {
    args++;
  }
  
  strncpy(command, args, MAX_COMMANDLENGTH);
  if(strlen(command) == 0) {
    shell_output_str(&repeat_command, "usage 3", "");
    PROCESS_EXIT();
  }

  /*  printf("repeats %d period %d command '%s'\n",
      reps, period, command);*/

  etimer_set(&etimer, CLOCK_SECOND * period);
  for(i = 0; reps == 0 || i < reps; ++i) {

    process_start(&shell_repeat_server_process, command);
    process_post(&shell_repeat_server_process,
		 PROCESS_EVENT_CONTINUE,
		 &shell_repeat_process);
    PROCESS_WAIT_UNTIL(ev == PROCESS_EVENT_EXITED &&
		       data == &shell_repeat_server_process);
    
    PROCESS_PAUSE();
    PROCESS_WAIT_UNTIL(etimer_expired(&etimer));
    etimer_reset(&etimer);
  }
  

  PROCESS_END();
}
Exemple #14
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(sha256_test_process, ev, data)
{
  static const char *const str_res[] = {
    "success",
    "invalid param",
    "NULL error",
    "resource in use",
    "DMA bus error"
  };
  static const struct {
    const char *data[3];
    uint8_t sha256[32];
  } vectors[] = {
    { /* Simple */
      {
        "abc",
        NULL,
        NULL
      }, {
        0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
        0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
        0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
        0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad
      }
    }, { /* Simple */
      {
        "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
        NULL,
        NULL,
      }, {
        0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
        0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
        0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
        0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1
      }
    }, { /* Message of length 130 */
      {
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklabcd"
        "efghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn",
        NULL,
        NULL
      }, {
        0x15, 0xd2, 0x3e, 0xea, 0x57, 0xb3, 0xd4, 0x61,
        0xbf, 0x38, 0x91, 0x12, 0xab, 0x4c, 0x43, 0xce,
        0x85, 0xe1, 0x68, 0x23, 0x8a, 0xaa, 0x54, 0x8e,
        0xc8, 0x6f, 0x0c, 0x9d, 0x65, 0xf9, 0xb9, 0x23
      }
    }, { /* Message of length 128 */
      {
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklabcd"
        "efghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl",
        NULL,
        NULL
      }, {
        0xf8, 0xa3, 0xf2, 0x26, 0xfc, 0x42, 0x10, 0xe9,
        0x0d, 0x13, 0x0c, 0x7f, 0x41, 0xf2, 0xbe, 0x66,
        0x45, 0x53, 0x85, 0xd2, 0x92, 0x0a, 0xda, 0x78,
        0x15, 0xf8, 0xf7, 0x95, 0xd9, 0x44, 0x90, 0x5f
      }
    }, { /* Message of length 64 */
      {
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl",
        NULL,
        NULL
      }, {
        0x2f, 0xcd, 0x5a, 0x0d, 0x60, 0xe4, 0xc9, 0x41,
        0x38, 0x1f, 0xcc, 0x4e, 0x00, 0xa4, 0xbf, 0x8b,
        0xe4, 0x22, 0xc3, 0xdd, 0xfa, 0xfb, 0x93, 0xc8,
        0x09, 0xe8, 0xd1, 0xe2, 0xbf, 0xff, 0xae, 0x8e
      }
    }, { /* Message of length 66 */
      {
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn",
        NULL,
        NULL
      }, {
        0x92, 0x90, 0x1c, 0x85, 0x82, 0xe3, 0x1c, 0x05,
        0x69, 0xb5, 0x36, 0x26, 0x9c, 0xe2, 0x2c, 0xc8,
        0x30, 0x8b, 0xa4, 0x17, 0xab, 0x36, 0xc1, 0xbb,
        0xaf, 0x08, 0x4f, 0xf5, 0x8b, 0x18, 0xdc, 0x6a
      }
    }, {
      {
        "abcdbcdecdefde",
        "fgefghfghighijhijkijkljklmklmnlmnomnopnopq",
        NULL
      }, {
        0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
        0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
        0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
        0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1
      }
    }, {
      {
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl",
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl",
        NULL
      }, {
        0xf8, 0xa3, 0xf2, 0x26, 0xfc, 0x42, 0x10, 0xe9,
        0x0d, 0x13, 0x0c, 0x7f, 0x41, 0xf2, 0xbe, 0x66,
        0x45, 0x53, 0x85, 0xd2, 0x92, 0x0a, 0xda, 0x78,
        0x15, 0xf8, 0xf7, 0x95, 0xd9, 0x44, 0x90, 0x5f
      }
    }, {
      {
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefgh",
        "ijkl",
        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl"
      }, {
        0xf8, 0xa3, 0xf2, 0x26, 0xfc, 0x42, 0x10, 0xe9,
        0x0d, 0x13, 0x0c, 0x7f, 0x41, 0xf2, 0xbe, 0x66,
        0x45, 0x53, 0x85, 0xd2, 0x92, 0x0a, 0xda, 0x78,
        0x15, 0xf8, 0xf7, 0x95, 0xd9, 0x44, 0x90, 0x5f
      }
    }
  };
  static sha256_state_t state;
  static uint8_t sha256[32];
  static int i, j;
  static uint8_t ret;
  static rtimer_clock_t total_time;
  rtimer_clock_t time;
  size_t len;

  PROCESS_BEGIN();

  puts("-----------------------------------------\n"
       "Initializing cryptoprocessor...");
  crypto_init();

  for(i = 0; i < sizeof(vectors) / sizeof(vectors[0]); i++) {
    printf("-----------------------------------------\n"
           "Test vector #%d:\n", i);

    time = RTIMER_NOW();
    ret = sha256_init(&state);
    time = RTIMER_NOW() - time;
    total_time = time;
    printf("sha256_init(): %s, %lu us\n", str_res[ret],
           (uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
    PROCESS_PAUSE();
    if(ret != CRYPTO_SUCCESS) {
      continue;
    }

    for(j = 0; j < sizeof(vectors[i].data) / sizeof(vectors[i].data[0]) &&
               vectors[i].data[j] != NULL; j++) {
      len = strlen(vectors[i].data[j]);
      printf("Buffer #%d (length: %u):\n", j, len);
      time = RTIMER_NOW();
      ret = sha256_process(&state, vectors[i].data[j], len);
      time = RTIMER_NOW() - time;
      total_time += time;
      printf("sha256_process(): %s, %lu us\n", str_res[ret],
             (uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
      PROCESS_PAUSE();
      if(ret != CRYPTO_SUCCESS) {
        break;
      }
    }
    if(ret != CRYPTO_SUCCESS) {
      continue;
    }

    time = RTIMER_NOW();
    ret = sha256_done(&state, sha256);
    time = RTIMER_NOW() - time;
    total_time += time;
    printf("sha256_done(): %s, %lu us\n", str_res[ret],
           (uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
    PROCESS_PAUSE();
    if(ret != CRYPTO_SUCCESS) {
      continue;
    }

    if(rom_util_memcmp(sha256, vectors[i].sha256, sizeof(sha256))) {
      puts("Computed SHA-256 hash does not match expected hash");
    } else {
      puts("Computed SHA-256 hash OK");
    }
    printf("Total duration: %lu us\n",
           (uint32_t)((uint64_t)total_time * 1000000 / RTIMER_SECOND));
  }

  puts("-----------------------------------------\n"
       "Disabling cryptoprocessor...");
  crypto_disable();

  puts("Done!");

  PROCESS_END();
}
Exemple #15
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(shell_netperf_process, ev, data)
{
  static struct etimer e;
  static linkaddr_t receiver;
  const char *nextptr;
  const char *args;
  static char recvstr[40];
  static int i, num_packets;
  static uint8_t do_broadcast, do_unicast, do_pingpong, do_stream_pingpong;

  PROCESS_BEGIN();

  current_type = TYPE_NONE;
  
  do_broadcast = do_unicast = do_pingpong =
    do_stream_pingpong = 0;
  
  args = data;

  /* Parse the -bups options */
  while(*args == '-') {
    ++args;
    while(*args != ' ' &&
	  *args != 0) {
      if(*args == 'b') {
	do_broadcast = 1;
      }
      if(*args == 'u') {
	do_unicast = 1;
      }
      if(*args == 'p') {
	do_pingpong = 1;
      }
      if(*args == 's') {
	do_stream_pingpong = 1;
      }
      ++args;
    }
    while(*args == ' ') {
      args++;
    }
  }

  /* Parse the receiver address */
  receiver.u8[0] = shell_strtolong(args, &nextptr);
  if(nextptr == data || *nextptr != '.') {
    print_usage();
    PROCESS_EXIT();
  }
  args = nextptr + 1;
  receiver.u8[1] = shell_strtolong(args, &nextptr);

  /* Store the receiver address as a string since we need to print it
     out later. */
  snprintf(recvstr, sizeof(recvstr), "%d.%d",
	   receiver.u8[0], receiver.u8[1]);

  /* Parse the number of packets to send */
  args = nextptr;
  while(*args == ' ') {
    ++args;
  }
  num_packets = shell_strtolong(args, &nextptr);  
  if(nextptr == data || num_packets == 0) {
    print_usage();
    PROCESS_EXIT();
  }

  /* Send broadcast packets, if requested */
  if(do_broadcast) {
    current_type = TYPE_BROADCAST;
    shell_output_str(&netperf_command, "-------- Broadcast --------", "");
    
    shell_output_str(&netperf_command, "Contacting ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_CLEAR)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    shell_output_str(&netperf_command, "Measuring broadcast performance to ", recvstr);
    
    setup_sending(&receiver, num_packets);
    for(i = 0; i < num_packets; ++i) {
      if(construct_next_packet()) {
	broadcast_send(&broadcast);
	stats.sent++;
      }
      PROCESS_PAUSE();
    }
    
    shell_output_str(&netperf_command, "Requesting statistics from ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_STATS)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    /* Wait for reply */
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    finalize_stats(&stats);
    print_local_stats(&stats);
  }

  if(do_unicast) {
    current_type = TYPE_UNICAST;
    shell_output_str(&netperf_command, "-------- Unicast one-way --------", "");
    
    shell_output_str(&netperf_command, "Contacting ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_CLEAR)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    shell_output_str(&netperf_command, "Measuring unicast performance to ", recvstr);
    
    setup_sending(&receiver, num_packets);
    
    for(i = 0; i < num_packets; ++i) {
      if(construct_next_packet()) {
	unicast_send(&unicast, &receiver);
	stats.sent++;
      }
      PROCESS_PAUSE();
    }
    
    shell_output_str(&netperf_command, "Requesting statistics from ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_STATS)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    /* Wait for reply */
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    finalize_stats(&stats);
    print_local_stats(&stats);
  }
  if(do_pingpong) {
    current_type = TYPE_UNICAST_PINGPONG;
    shell_output_str(&netperf_command, "-------- Unicast ping-pong--------", "");
    
    shell_output_str(&netperf_command, "Contacting ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_CLEAR)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    shell_output_str(&netperf_command, "Measuring two-way unicast performance to ", recvstr);
    
    setup_sending(&receiver, num_packets);
    
    for(i = 0; i < num_packets; ++i) {
      if(construct_next_echo()) {
        
	unicast_send(&unicast, &receiver);
	stats.sent++;
      }
      etimer_set(&e, CLOCK_SECOND);
      PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT || etimer_expired(&e));
    }
    
    shell_output_str(&netperf_command, "Requesting statistics from ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_STATS)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    /* Wait for reply */
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    finalize_stats(&stats);
    print_local_stats(&stats);
  }
  if(do_stream_pingpong) {
    current_type = TYPE_UNICAST_STREAM;
    shell_output_str(&netperf_command, "-------- Unicast stream ping-pong--------", "");
    
    shell_output_str(&netperf_command, "Contacting ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_CLEAR)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    shell_output_str(&netperf_command, "Measuring two-way unicast stream performance to ", recvstr);
    
    setup_sending(&receiver, num_packets);
    
    for(i = 0; i < num_packets; ++i) {
      if(construct_next_stream_echo()) {
	unicast_send(&unicast, &receiver);
	stats.sent++;
      }
      etimer_set(&e, CLOCK_SECOND);
      PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT || etimer_expired(&e));
    }
    
    shell_output_str(&netperf_command, "Requesting statistics from ", recvstr);
    while(!send_ctrl_command(&receiver, CTRL_COMMAND_STATS)) {
      PROCESS_PAUSE();
    }
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    /* Wait for reply */
    PROCESS_YIELD_UNTIL(ev == CONTINUE_EVENT);
    
    finalize_stats(&stats);
    print_local_stats(&stats);
    
  }

  shell_output_str(&netperf_command, "Done", "");
  PROCESS_END();
}
Exemple #16
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(dtnpingecho_process, ev, data)
{
	static uint32_t bundles_recv = 0;
	uint32_t tmp;

	uint32_t source_node;
	uint32_t source_service;
	uint32_t incoming_lifetime;

	struct mmem * bundlemem = NULL;
	struct bundle_block_t * block = NULL;

	// preserve the payload to send it back
	uint8_t payload_buffer[64];
	uint8_t payload_length;

	PROCESS_BEGIN();

	/* Give agent time to initialize */
	PROCESS_PAUSE();

	/* Register ping endpoint */
	reg.status = APP_ACTIVE;
	reg.application_process = PROCESS_CURRENT();;
	reg.app_id = DTN_PING_ENDPOINT;
	process_post(&agent_process, dtn_application_registration_event,&reg);

	printf("DTN Ping Echo running on ipn:%lu.%lu\n", dtn_node_id, reg.app_id);

	while (1) {
		PROCESS_WAIT_EVENT_UNTIL(ev == submit_data_to_application_event);

		// Reconstruct the bundle struct from the event
		bundlemem = (struct mmem *) data;

		block = bundle_get_payload_block(bundlemem);
		if( block == NULL ) {
			printf("No payload block\n");
			continue;
		}

		if (block->block_size > 64) {
			printf("Payload too big, clamping to maximum size.\n");
			payload_length = 64;
		} else {
			payload_length = block->block_size;
		}
		memcpy(payload_buffer, block->payload, payload_length);

		// Extract the source information to send a reply back
		bundle_get_attr(bundlemem, SRC_NODE, &source_node);
		bundle_get_attr(bundlemem, SRC_SERV, &source_service);

		// Extract lifetime from incoming bundle
		bundle_get_attr(bundlemem, LIFE_TIME, &incoming_lifetime);

		bundles_recv++;
		printf("PING %lu of %u bytes received from ipn:%lu.%lu\n", bundles_recv, block->block_size, source_node, source_service);

		// Tell the agent, that have processed the bundle
		process_post(&agent_process, dtn_processing_finished, bundlemem);
		bundlemem = NULL;
		block = NULL;

		// Create the reply bundle
		bundlemem = bundle_create_bundle();
		if (!bundlemem) {
			printf("create_bundle failed\n");
			continue;
		}

		// Set the reply EID to the incoming bundle information
		bundle_set_attr(bundlemem, DEST_NODE, &source_node);
		bundle_set_attr(bundlemem, DEST_SERV, &source_service);

		// Set our service to 11 [DTN_PING_ENDPOINT] (IBR-DTN expects that)
		tmp = DTN_PING_ENDPOINT;
		bundle_set_attr(bundlemem, SRC_SERV, &tmp);

		// Now set the flags
		tmp = BUNDLE_FLAG_SINGLETON;
		bundle_set_attr(bundlemem, FLAGS, &tmp);

		// Set the same lifetime and timestamp as the incoming bundle
		bundle_set_attr(bundlemem, LIFE_TIME, &incoming_lifetime);

		// Copy payload from incoming bundle
		bundle_add_block(bundlemem, BUNDLE_BLOCK_TYPE_PAYLOAD, BUNDLE_BLOCK_FLAG_NULL, payload_buffer, payload_length);

		// And submit the bundle to the agent
		process_post(&agent_process, dtn_send_bundle_event, (void *) bundlemem);
	}

	PROCESS_END();
}
PROCESS_THREAD(test_process, ev, data)
{
	static int n;
	static uint32_t i;
	static int errors = 0;
	static struct etimer timer;
	static uint32_t time_start, time_stop;

	PROCESS_BEGIN();

	/* Initialize the flash before the storage comes along */
	PRINTF("Intializing Flash...\n");
	BUNDLE_STORAGE.format();

	PROCESS_PAUSE();

	profiling_init();
	profiling_start();

	// Wait again
	etimer_set(&timer, CLOCK_SECOND);
	PROCESS_WAIT_UNTIL(etimer_expired(&timer));

	printf("Init done, starting test using %s storage\n", BUNDLE_STORAGE.name);

	profiling_init();
	profiling_start();

	// Measure the current time
	time_start = test_precise_timestamp();

	PRINTF("Create and Verify bundles in sequence\n");
	for(i=0; i<TEST_BUNDLES; i++) {
		PROCESS_PAUSE();

		if( my_create_bundle(i, &bundle_numbers[i], 3600) ) {
			PRINTF("\tBundle %lu created successfully \n", i);
		} else {
			PRINTF("\tBundle %lu could not be created \n", i);
			errors ++;
			continue;
		}

		if( my_verify_bundle(bundle_numbers[i], i) ) {
			PRINTF("\tBundle %lu read back successfully \n", i);
		} else {
			PRINTF("\tBundle %lu could not be read back and verified \n", i);
			errors ++;
		}
	}

	printf("Reinitialize storage\n");
	/* Reinitialize the storage and see, if the bundles persist */
	BUNDLE_STORAGE.init();

	PRINTF("Verify and Delete bundles in sequence\n");
	for(i=0; i<TEST_BUNDLES; i++) {
		if( my_verify_bundle(bundle_numbers[i], i) ) {
			PRINTF("\tBundle %lu read back successfully \n", i);
		} else {
			PRINTF("\tBundle %lu could not be read back and verified \n", i);
			errors ++;
		}

		n = BUNDLE_STORAGE.del_bundle(bundle_numbers[i], REASON_DELIVERED);

		if( n ) {
			PRINTF("\tBundle %lu deleted successfully\n", i);
		} else {
			PRINTF("\tBundle %lu could not be deleted\n", i);
			errors++;
		}
	}

	time_stop = test_precise_timestamp();

	watchdog_stop();
	profiling_report("persistent-storage", 0);

	TEST_REPORT("No of errors", errors, 1, "errors");
	TEST_REPORT("Duration", time_stop-time_start, CLOCK_SECOND, "s");

	if( errors > 0 ) {
		TEST_FAIL("More than 1 error occured");
	} else {
		TEST_PASS();
	}

	PROCESS_END();
}
Exemple #18
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(border_router_process, ev, data)
{
  rpl_dag_t *dag;

  PROCESS_BEGIN();

/* While waiting for the prefix to be sent through the SLIP connection, the future
 * border router can join an existing DAG as a parent or child, or acquire a default
 * router that will later take precedence over the SLIP fallback interface.
 * Prevent that by turning the radio off until we are initialized as a DAG root.
 */
  prefix_set = 0;
  NETSTACK_MAC.off(0);

  PROCESS_PAUSE();

  //SENSORS_ACTIVATE(button_sensor);

  PRINTF("RPL-Border router started\n");
#if 0
   /* The border router runs with a 100% duty cycle in order to ensure high
     packet reception rates.
     Note if the MAC RDC is not turned off now, aggressive power management of the
     cpu will interfere with establishing the SLIP connection */
  NETSTACK_MAC.off(1);
#endif

  /* Request prefix until it has been received */
#define REQUEST_PREFIX  1
#if REQUEST_PREFIX

  static struct etimer et;

  while(!prefix_set) {
    etimer_set(&et, 1000);
    request_prefix();
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
  }

  dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)dag_id);
   if(dag != NULL) {
     rpl_set_prefix(dag, &prefix, 64);
     PRINTF("created a new RPL dag\n");
   }

#else
  {
      char buf[sizeof(dag_id)];
      memcpy(buf,dag_id,sizeof(dag_id));
      dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)buf);

      /* Assign separate addresses to the uip stack and the host network
          interface, but with the same prefix E.g. bbbb::ff:fe00:200 to
          the stack and bbbb::1 to the host *fallback* network interface
          Otherwise the host will trap packets intended for the stack,
          just as the stack will trap packets intended for the host
          $ifconfig usb0 -arp on Ubuntu to skip the neighbor
          solicitations. Add explicit neighbors on other OSs */

      if(dag != NULL)
      {
    	  PRINTF("Created a new RPL dag\n");

  #if UIP_CONF_ROUTER_RECEIVE_RA
        /* Contiki stack will shut down until assigned an address from the
  	 interface RA Currently this requires changes in the core
  	 rpl-icmp6.c to pass the link-local RA broadcast.
        */

  #else
        {
			int i;
			uip_ip6addr_t ipaddr;
		  #ifdef HARD_CODED_ADDRESS
			uiplib_ipaddrconv(HARD_CODED_ADDRESS, &ipaddr);
		  #else
			uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0x1);
		  #endif
			uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
			uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);
			rpl_set_prefix(dag, &ipaddr, 64);

			for(i = 0; i < UIP_DS6_ADDR_NB; i++) {
			  if(uip_ds6_if.addr_list[i].isused) {
				PRINTF("IPV6 Address: ");
				sprint_ip6(uip_ds6_if.addr_list[i].ipaddr);
				PRINTF("\n");
			  }
			}
        }
  #endif
      }
    }
#endif

  /* Now turn the radio on, but disable radio duty cycling.
   * Since we are the DAG root, reception delays would constrain mesh throughbut.
   */
  NETSTACK_MAC.off(1);

#if DEBUG || 1
  print_local_addresses();
#endif

  while(1) {
    PROCESS_YIELD();   
    if (ev == sensors_event){
		PRINTF("Initiating global repair\n");
		rpl_repair_root(RPL_DEFAULT_INSTANCE);
    }
  }

  PROCESS_END();
}
PROCESS_THREAD(er_example_server, ev, data)
{
  PROCESS_BEGIN();

  PROCESS_PAUSE();

  PRINTF("Starting Erbium Example Server\n");

#ifdef RF_CHANNEL
  PRINTF("RF channel: %u\n", RF_CHANNEL);
#endif
#ifdef IEEE802154_PANID
  PRINTF("PAN ID: 0x%04X\n", IEEE802154_PANID);
#endif

  PRINTF("uIP buffer: %u\n", UIP_BUFSIZE);
  PRINTF("LL header: %u\n", UIP_LLH_LEN);
  PRINTF("IP+UDP header: %u\n", UIP_IPUDPH_LEN);
  PRINTF("REST max chunk: %u\n", REST_MAX_CHUNK_SIZE);

  /* Initialize the REST engine. */
  rest_init_engine();

  /*
   * Bind the resources to their Uri-Path.
   * WARNING: Activating twice only means alternate path, not two instances!
   * All static variables are the same for each URI path.
   */
  rest_activate_resource(&res_led, "lamp");
  rest_activate_resource(&res_temp, "lamp/temperature");
  rest_activate_resource(&res_temp_thresh_on, "lamp/temp_thresh_on");
  rest_activate_resource(&res_temp_thresh_off, "lamp/temp_thresh_off");
  rest_activate_resource(&res_adf7242_lgi, "ADF7242/LQI");

  rest_activate_resource(&res_hello, "test/hello");
/*  rest_activate_resource(&res_mirror, "debug/mirror"); */
/*  rest_activate_resource(&res_chunks, "test/chunks"); */
/*  rest_activate_resource(&res_separate, "test/separate"); */
/*  rest_activate_resource(&res_push, "test/push"); */
/*  rest_activate_resource(&res_event, "sensors/button"); */
/*  rest_activate_resource(&res_sub, "test/sub"); */
/*  rest_activate_resource(&res_b1_sep_b2, "test/b1sepb2"); */
#if PLATFORM_HAS_LEDS
/*  rest_activate_resource(&res_leds, "actuators/leds"); */
  rest_activate_resource(&res_toggle, "actuators/toggle");
#endif
#if PLATFORM_HAS_LIGHT
/*  rest_activate_resource(&res_light, "sensors/light"); */
#endif

  /* Define application-specific events here. */
  while(1) {
    PROCESS_WAIT_EVENT();
#if PLATFORM_HAS_BUTTON
    if(ev == sensors_event && data == &button_sensor) {
      PRINTF("*******BUTTON*******\n");

      /* Call the event_handler for this application-specific event. */
      res_event.trigger();

      /* Also call the separate response example handler. */
      res_separate.resume();
    }
#endif /* PLATFORM_HAS_BUTTON */
  }                             /* while (1) */

  PROCESS_END();
}
Exemple #20
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();
}
Exemple #21
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_server_process, ev, data)
{
  uip_ipaddr_t ipaddr;
  struct uip_ds6_addr *root_if;

  PROCESS_BEGIN();

  PROCESS_PAUSE();

  SENSORS_ACTIVATE(button_sensor);

  PRINTF("UDP server started\n");

#if UIP_CONF_ROUTER
/* The choice of server address determines its 6LoPAN header compression.
 * Obviously the choice made here must also be selected in udp-client.c.
 *
 * For correct Wireshark decoding using a sniffer, add the /64 prefix to the 6LowPAN protocol preferences,
 * e.g. set Context 0 to aaaa::.  At present Wireshark copies Context/128 and then overwrites it.
 * (Setting Context 0 to aaaa::1111:2222:3333:4444 will report a 16 bit compressed address of aaaa::1111:22ff:fe33:xxxx)
 * Note Wireshark's IPCMV6 checksum verification depends on the correct uncompressed addresses.
 */
 
#if 0
/* Mode 1 - 64 bits inline */
   uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 1);
#elif 1
/* Mode 2 - 16 bits inline */
  uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0x00ff, 0xfe00, 1);
#else
/* Mode 3 - derived from link local (MAC) address */
  uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
  uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
#endif

  uip_ds6_addr_add(&ipaddr, 0, ADDR_MANUAL);
  root_if = uip_ds6_addr_lookup(&ipaddr);
  if(root_if != NULL) {
    rpl_dag_t *dag;
    dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)&ipaddr);
    uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
    rpl_set_prefix(dag, &ipaddr, 64);
    PRINTF("created a new RPL dag\n");
  } else {
    PRINTF("failed to create a new RPL DAG\n");
  }
#endif /* UIP_CONF_ROUTER */
  
  print_local_addresses();

  /* The data sink runs with a 100% duty cycle in order to ensure high 
     packet reception rates. */
  NETSTACK_MAC.off(1);

  server_conn = udp_new(NULL, UIP_HTONS(UDP_CLIENT_PORT), NULL);
  if(server_conn == NULL) {
    PRINTF("No UDP connection available, exiting the process!\n");
    PROCESS_EXIT();
  }
  udp_bind(server_conn, UIP_HTONS(UDP_SERVER_PORT));

  PRINTF("Created a server connection with remote address ");
  PRINT6ADDR(&server_conn->ripaddr);
  PRINTF(" local/remote port %u/%u\n", UIP_HTONS(server_conn->lport),
         UIP_HTONS(server_conn->rport));

  while(1) {
    PROCESS_YIELD();
    if(ev == tcpip_event) {
      tcpip_handler();
    } else if (ev == sensors_event && data == &button_sensor) {
      PRINTF("Initiaing global repair\n");
      rpl_repair_root(RPL_DEFAULT_INSTANCE);
    }
  }

  PROCESS_END();
}
PROCESS_THREAD(border_router_process, ev, data)
{

  PROCESS_BEGIN();

  PROCESS_PAUSE();

  {
    rpl_dag_t *dag;
    char buf[sizeof(dag_id)];
    memcpy(buf,dag_id,sizeof(dag_id));
    dag = rpl_set_root((uip_ip6addr_t *)buf);
    
    /* Assign separate addresses to the uip stack and the host network
        interface, but with the same prefix E.g. bbbb::ff:fe00:200 to
        the stack and bbbb::1 to the host *fallback* network interface
        Otherwise the host will trap packets intended for the stack,
        just as the stack will trap packets intended for the host
        $ifconfig usb0 -arp on Ubuntu to skip the neighbor
        solicitations. Add explicit neighbors on other OSs */

    if(dag != NULL) {
      printf("Created a new RPL dag\n");
      
#if UIP_CONF_ROUTER_RECEIVE_RA
      /* Contiki stack will shut down until assigned an address from the
	 interface RA Currently this requires changes in the core
	 rpl-icmp6.c to pass the link-local RA broadcast.
      */
      
#else
      {
	static void sprint_ip6(uip_ip6addr_t addr);
	int i;
	uip_ip6addr_t ipaddr;
#ifdef HARD_CODED_ADDRESS
	uiplib_ipaddrconv(HARD_CODED_ADDRESS, &ipaddr);
#else
	uip_ip6addr(&ipaddr, 0xbbbb, 0, 0, 0, 0, 0, 0, 0x1);
#endif
	uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
	uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);
	rpl_set_prefix(dag, &ipaddr, 64);

	for(i = 0; i < UIP_DS6_ADDR_NB; i++) {
	  if(uip_ds6_if.addr_list[i].isused) {
	    printf("IPV6 Address: ");
	    sprint_ip6(uip_ds6_if.addr_list[i].ipaddr);
	    printf("\n");
	  }
	}
      }
#endif
    }
  }
  /* The border router runs with a 100% duty cycle in order to ensure high
     packet reception rates. */
  /* NETSTACK_MAC.off(1); */

  while(1) {
    PROCESS_YIELD();
    /* Local and global dag repair can be done from ? */
    /*  rpl_set_prefix(rpl_get_dag(RPL_ANY_INSTANCE), &ipaddr, 64);
	rpl_repair_dag(rpl_get_dag(RPL_ANY_INSTANCE)); */
  }

  PROCESS_END();
}
PROCESS_THREAD(test_process, ev, data)
{
	static uint32_t time_start = 0;
	static uint32_t time_stop = 0;
	static uint32_t errors = 0;
	static uint32_t collisions = 0;
	uint32_t i = 0;
	uint32_t test_data[10] = {251284450, 371537862, 425973621, 81975339, 170405567, 225666122, 421777121, 118094495, 410814580, 414999832};

	PROCESS_BEGIN();
	PROCESS_PAUSE();

	printf("Init done, starting test using redudancy implementation %s\n", REDUNDANCE.name);

	// Initialize the profiling
	profiling_init();
	profiling_start();

	// Measure the current time
	time_start = test_precise_timestamp();

	// -----------------------------------
	// Check if no bundles are stored
	printf("Making sure list is empty\n");
	for(i=0; i<0xFFFFF; i++) {
		if( REDUNDANCE.check(i) ) {
			errors ++;
			printf("ERROR: %lu reported to be set but should be empty\n", i);
		}

		// Keep the watchdog happy
		if( i % 10 == 0 ) {
			watchdog_periodic();
		}

		if( i % 10000 == 0 ) {
			printf("\t%lu...\n", i);
		}
	}

	// -----------------------------------
	// Store 10 bundles
	printf("Storing 10 bundles...\n");
	for(i=0; i<10; i++) {
		REDUNDANCE.set(test_data[i]);

		// Keep the watchdog happy
		if( i % 5 == 0 ) {
			watchdog_periodic();
		}
	}

	// Keep the watchdog happy
	watchdog_periodic();

	// -----------------------------------
	// Retrieve the 10 bundles
	printf("Reading 10 bundles back...\n");
	for(i=0; i<10; i++) {
		if( !REDUNDANCE.check(test_data[i]) ) {
			printf("ERROR: %lu should be set but is not\n", i);
			errors++;
		} else {
			printf("\t%lu is fine\n", test_data[i]);
		}
	}

	// Keep the watchdog happy
	watchdog_periodic();

	// -----------------------------------
	// Check how many bundle ID are actually reported as set
	printf("Counting collisions...\n");
	for(i=0; i<0xFFFFF; i++) {
		if( REDUNDANCE.check(i) ) {
			printf("\tcollision at %lu\n", i);
			collisions ++;
		}

		// Keep the watchdog happy
		if( i % 10 == 0 ) {
			watchdog_periodic();
		}

		if( i % 10000 == 0 ) {
			printf("\t%lu...\n", i);
		}
	}

	printf("We have %lu collisions\n", collisions);

	// Keep the watchdog happy
	watchdog_periodic();

	// -----------------------------------
	// Now set 1000 bundle IDs and check the last 10 of them
	printf("Setting 1000 bundle IDs...\n");
	for(i=0; i<1000; i++) {
		REDUNDANCE.set(i);

		// Keep the watchdog happy
		if( i % 5 == 0 ) {
			watchdog_periodic();
		}
	}

	// Keep the watchdog happy
	watchdog_periodic();

	printf("Verifying IDs...\n");
	for(i=990; i<1000; i++) {
		if( !REDUNDANCE.check(i) ) {
			printf("ERROR: %lu should be set but is not\n", i);
			errors++;
		}

		// Keep the watchdog happy
		if( i % 5 == 0 ) {
			watchdog_periodic();
		}
	}

	printf("Done\n");

	// Measure the current time
	time_stop = test_precise_timestamp();

	watchdog_stop();
	profiling_report("redundancy", 0);

	TEST_REPORT("No of errors", errors, 1, "errors");
	TEST_REPORT("Duration", time_stop-time_start, CLOCK_SECOND, "s");
	TEST_REPORT("No of collisions", collisions, 1, "collisions");

	if( errors > 0 ) {
		TEST_FAIL("More than 1 error occurred");
	} else {
		TEST_PASS();
	}

	PROCESS_END();
}
PROCESS_THREAD(proc_epoch_syncer, ev, data) {
	static struct etimer send_timer;
	static struct etimer epoch_timer;
	static const struct broadcast_callbacks broadcast_cbs = {__broadcast_recv_cb, __broadcast_sent_cb};
	static struct broadcast_conn conn;

	PROCESS_EXITHANDLER(broadcast_close(&conn));

	PROCESS_BEGIN();


#ifdef TRACK_CONNECTIONS
	/* Log the node id */
	printf("board-id64 0x%.16llx\n", board_get_id64());
#endif
#ifdef XFER_CRC16
	/* Log the node id */
	printf("xfer crc16\n");
#endif
	printf("epoch interval %ld ticks\n", EPOCH_INTERVAL);

	/*
	 * Alloc the two syncer events
	 */
	evt_epoch_synced = process_alloc_event();
	evt_end_of_epoch = process_alloc_event();

	/*
	 * Open a `connection` on the syncer broadcasting channel
	 */
	broadcast_open(&conn, BROADCAST_CHANNEL_TIMESYNC, &broadcast_cbs);

	/*
	 * init the epoch-syncer instance
	 */
	epoch_syncer_init(&__epoch_syncer);

	/*
	 * This is the main syncer loop. Initially we try to sync the
	 * epoch between nodes without concurrently running any other
	 * algo. After a period, at which time the network is synced,
	 * we start generating epoch events which can be
	 * consumed by, e.g., the estimator process.
	 */
	etimer_set(&epoch_timer, __epoch_syncer.epoch_interval);
	__epoch_syncer.epoch_start_time = clock_time();
	__epoch_syncer.epoch_end_time = etimer_expiration_time(&epoch_timer);
	while (1) {
		/*
		 * The start of a new epoch !
		 */
		epoch_syncer_at_epoch_start(&__epoch_syncer);


		clock_time_t now;
		clock_time_t time_to_epoch_end;
			
		now = clock_time();

		assert(__epoch_syncer.epoch_end_time == etimer_expiration_time(&epoch_timer));
		assert(__epoch_syncer.epoch_end_time > now);
		time_to_epoch_end = __epoch_syncer.epoch_end_time - now;

		/* 
		 * Setup a random wait time before sending the sync packet
		 *
		 * ! we cannot let send_timer delay the epoch_timer, especially
		 *   when the next `end-of-epoch-time` has been anticipated by a lot
		 *   (this can happen at startup)
		 */
		if (time_to_epoch_end > __epoch_syncer.epoch_sync_start) {
			long int send_wait;
			long int send_wait_rnd;
			long int rnd;

			rnd = rand();
			send_wait_rnd = (unsigned)rnd % (unsigned) __epoch_syncer.epoch_sync_xfer_interval;
			send_wait = __epoch_syncer.epoch_sync_start + send_wait_rnd;
			assert(send_wait >= __epoch_syncer.epoch_sync_start);
			assert(send_wait <= __epoch_syncer.epoch_sync_start + __epoch_syncer.epoch_sync_xfer_interval);

			if (send_wait > time_to_epoch_end)
				send_wait = __epoch_syncer.epoch_sync_start;

			assert(send_wait < time_to_epoch_end);
			etimer_set(&send_timer, send_wait);

			PROCESS_WAIT_UNTIL(etimer_expired(&send_timer));

			/*
			 * Acquire the radio lock
			 *
			 * ! we don't use WAIT/YIELD_UNTIL() because
			 *   1) we do not want to yield if we can acquire the lock on the first try
			 *   2) no kernel signal is generated when the lock is released (we would `deadlock')
			 */
			do {
				if (!radio_trylock())
					break;

				PROCESS_PAUSE();
			} while (1);


			{
				clock_time_t now;
				struct epoch_sync_packet packet;
					
				/*
				 * broadcast the sync packet
				 *
				 * ! We put this part into its own block since non static stack
				 * variables/allocations in the parent block wouldn't get preserved trough
				 * kernel calls (e.g. the PROCESS_PAUSE() a few lines above)
				 */
#ifdef TRACK_CONNECTIONS
				packet.board_id16 = board_get_id16();
#endif
				packet.epoch = __epoch_syncer.epoch;

				now = clock_time();
				assert(now > __epoch_syncer.epoch_start_time);
				assert(__epoch_syncer.epoch_end_time > now);
				packet.time_from_epoch_start = now - __epoch_syncer.epoch_start_time;
				packet.time_to_epoch_end = __epoch_syncer.epoch_end_time - now;

				
#ifdef XFER_CRC16
				/*
				 * Compute the packet crc with the .crc16 field zeroed
				 */
				{
					uint16_t crc16;

					packet.crc16 = 0;
					crc16 = crc16_data((const unsigned char *)&packet,  sizeof(struct epoch_sync_packet), 0);

					packet.crc16 = crc16;
				}
#endif
				packetbuf_copyfrom(&packet, sizeof(struct epoch_sync_packet));
				broadcast_send(&conn);
			}
		} else {
			printf("epoch-syncer: skipping sync send\n");
		}
			

		/*
		 * We cannot YIELD here: if epoch_timer has already expired there won't be
		 * any event to wake us up.
		 *
		 * FIXME: if we get here and the epoch timer has fired
		 * already print by how much we are late: this can be terribly useful
		 * to trace bugs in the epoch sync code or the kernel.
		 */
		if (etimer_expired(&epoch_timer)) {
			long int now;

			now = clock_time();
			assert(now > __epoch_syncer.epoch_end_time);
			
		} else {
			char do_wait;
			do_wait = 1;

			if (__epoch_syncer.sum_sync_offsets) {
				long int avg_offset = __epoch_syncer.sum_sync_offsets / __epoch_syncer.nr_offsets;
				const long int threshold = CLOCK_SECOND;

				if (avg_offset > threshold) {
					/*
					 * if we are late don't wait until the timer expires
					 * ! this migth give us the opportunity to re-enter the right sync_xfer_interval
					 */
					do_wait = 0;
				} else if (avg_offset < -threshold) {
					/*
					 * we are too fast, delay end of epoch
					 */
					clock_time_t now;
					clock_time_t time_to_epoch_end;
			
					now = clock_time();
					assert(__epoch_syncer.epoch_end_time == etimer_expiration_time(&epoch_timer));
					assert(__epoch_syncer.epoch_end_time > now);
					time_to_epoch_end = __epoch_syncer.epoch_end_time - now;

					long int delay = time_to_epoch_end + (-avg_offset/2);

					static struct etimer delay_timer;
					trace("epoch-syncer: delaying end-of-epoch by %ld ticks\n", (-avg_offset/2));
					etimer_set(&delay_timer, delay);
					__epoch_syncer.epoch_end_time += (-avg_offset/2);

					PROCESS_WAIT_UNTIL(etimer_expired(&delay_timer));
				}
			}

			if (do_wait) {
				PROCESS_WAIT_UNTIL(etimer_expired(&epoch_timer));
			} else {
				trace("epoch-syncer: not waiting for end-of-epoch\n");
			}
		}
		trace("epoch-syncer: epoch %d ended\n",  __epoch_syncer.epoch);

#ifdef TRACK_CONNECTIONS
		connection_print_and_zero(CONNECTION_TRACK_SYNC, __epoch_syncer.epoch);
#endif

		/*
		 * Re-Set the end-of-epoch timer
		 */
		if (__epoch_syncer.epoch == EPOCHS_UNTIL_SYNCED) {
			/*
			 * We have hopefully achieved sync at this point
			 *
			 * 1) update the epoch timings, and set the epoch timer
			 *
			 * 2) signal the size-estimator process that the epoch is now synced
			 */
			__epoch_syncer.epoch_interval = EPOCH_INTERVAL;
			__epoch_syncer.epoch_sync_start = EPOCH_SYNC_START;
			__epoch_syncer.epoch_sync_xfer_interval = EPOCH_SYNC_XFER_INTERVAL;

			etimer_stop(&epoch_timer);
			etimer_set(&epoch_timer, __epoch_syncer.epoch_interval);
			/*
			 * The epoch timer has been re-set: update the time until the next epoch end
			 * Increase the epoch count.
			 * ! these operations must happen in a block which cannot block in kernel calls
			 */
			__epoch_syncer.epoch_start_time = clock_time();
			__epoch_syncer.epoch_end_time = etimer_expiration_time(&epoch_timer);
			__epoch_syncer.epoch++;

			process_post(&proc_size_estimator, evt_epoch_synced, NULL);
		} else {
			/*
			 * Re-set and adjust the epoch timer using the data received trough sync packets
			 * (in this epoch)
			 *
			 * ! using re-set (instead of, e.g., restart) is important here in order to avoid
			 *   drifting
			 */ 
			etimer_reset(&epoch_timer);

			/*
			 * The epoch timer has been re-set: update the time until the next epoch end
			 * Increase the epoch count.
			 * ! these operations must happen in a block which cannot block in kernel calls
			 */
			//__epoch_syncer.epoch_start_time = epoch_timer.timer.start;
			__epoch_syncer.epoch_start_time = clock_time();
			__epoch_syncer.epoch_end_time = etimer_expiration_time(&epoch_timer);
			__epoch_syncer.epoch++;
			if (__epoch_syncer.sum_sync_offsets) {
				long int avg_offset = __epoch_syncer.sum_sync_offsets / __epoch_syncer.nr_offsets;
				const long int threshold = 1;//(CLOCK_SECOND/32);//*3;

#if __CONTIKI_NETSTACK_RDC==__CONTIKI_NETSTACK_RDC_NULL
				const int tx_delay = 0;
#elif __CONTIKI_NETSTACK_RDC==__CONTIKI_NETSTACK_RDC_CXMAC
				/*
				 * When the cxmac RDC is used we must consider an added delay due to the fact that when
				 * other nodes radios are turned off the sync packet must be re-sent.
				 */
				const int tx_delay = 8;
#endif

				/*
				 * estimate the avg tx delay
				 */
				avg_offset += tx_delay;

				trace("epoch-syncer: sync offsets %d ~ %ld < %ld < %ld\n", __epoch_syncer.nr_offsets,  __epoch_syncer.min_offset + tx_delay, avg_offset, __epoch_syncer.max_offset+tx_delay);
				
				if ((avg_offset < -threshold) || (avg_offset > threshold)) {
					clock_time_t new_expiration_time;

					const long int adjust_threshold = CLOCK_SECOND/2;
					long int adjust;
		
					/*
					 * feedback control the next expiration time
					 */
					adjust = -avg_offset/2;
					adjust = min(adjust, adjust_threshold);
					adjust = max(adjust, -adjust_threshold);

					if (adjust)
						etimer_adjust(&epoch_timer, adjust);
						
					new_expiration_time = etimer_expiration_time(&epoch_timer);
					__epoch_syncer.epoch_end_time = new_expiration_time;
				}
			}

			if (__epoch_syncer.epoch > EPOCHS_UNTIL_SYNCED) {
				/*
				 * Signal the estimator-process that this epoch has ended
				 */
				process_post(&proc_size_estimator, evt_end_of_epoch, NULL);
			}
		}
	}

	PROCESS_END();
}
Exemple #25
0
PROCESS_THREAD(er_example_server, ev, data)
{
  PROCESS_BEGIN();

  PROCESS_PAUSE();

  PRINTF("Starting Erbium Example Server\n");

#ifdef RF_CHANNEL
  PRINTF("RF channel: %u\n", RF_CHANNEL);
#endif
#ifdef IEEE802154_PANID
  PRINTF("PAN ID: 0x%04X\n", IEEE802154_PANID);
#endif

  PRINTF("uIP buffer: %u\n", UIP_BUFSIZE);
  PRINTF("LL header: %u\n", UIP_LLH_LEN);
  PRINTF("IP+UDP header: %u\n", UIP_IPUDPH_LEN);
  PRINTF("REST max chunk: %u\n", REST_MAX_CHUNK_SIZE);

  /* Initialize the REST engine. */
  rest_init_engine();

  /*
   * Bind the resources to their Uri-Path.
   * WARNING: Activating twice only means alternate path, not two instances!
   * All static variables are the same for each URI path.
   */
  rest_activate_resource(&res_hello, "test/hello");
/*  rest_activate_resource(&res_mirror, "debug/mirror"); */
/*  rest_activate_resource(&res_chunks, "test/chunks"); */
/*  rest_activate_resource(&res_separate, "test/separate"); */
  rest_activate_resource(&res_push, "test/push");
/*  rest_activate_resource(&res_event, "test/serial"); */
/*  rest_activate_resource(&res_sub, "test/sub"); */
/*  rest_activate_resource(&res_b1_sep_b2, "test/b1sepb2"); */
#if PLATFORM_HAS_LEDS
/*  rest_activate_resource(&res_leds, "actuators/leds"); */
  rest_activate_resource(&res_toggle, "actuators/toggle");
#endif
#if PLATFORM_HAS_LIGHT
  rest_activate_resource(&res_light, "sensors/light"); 
  SENSORS_ACTIVATE(light_sensor);  
#endif
#if PLATFORM_HAS_BATTERY
  rest_activate_resource(&res_battery, "sensors/battery");  
  SENSORS_ACTIVATE(battery_sensor);  
#endif
#if PLATFORM_HAS_TEMPERATURE
  rest_activate_resource(&res_temperature, "sensors/temperature");  
  SENSORS_ACTIVATE(temperature_sensor);  
#endif
/*
#if PLATFORM_HAS_RADIO
  rest_activate_resource(&res_radio, "sensors/radio");  
  SENSORS_ACTIVATE(radio_sensor);  
#endif
#if PLATFORM_HAS_SHT11
  rest_activate_resource(&res_sht11, "sensors/sht11");  
  SENSORS_ACTIVATE(sht11_sensor);  
#endif
*/
#if PLATFORM_HAS_PRESSURE
  rest_activate_resource(&res_pressure, "sensors/pressure");
  SENSORS_ACTIVATE(pressure_sensor);
#endif
#if PLATFORM_HAS_GYROSCOPE
  rest_activate_resource(&res_gyros, "sensors/gyros");
  SENSORS_ACTIVATE(gyr_sensor);
#endif
#if PLATFORM_HAS_ACCELEROMETER
  rest_activate_resource(&res_accel, "sensors/accel");
  SENSORS_ACTIVATE(acc_sensor);
#endif
#if PLATFORM_HAS_MAGNETOMETER
  rest_activate_resource(&res_magne, "sensors/magne");
  SENSORS_ACTIVATE(mag_sensor);
#endif

  /* Define application-specific events here. */
  while(1) {
    PROCESS_WAIT_EVENT();
    if(ev == serial_line_event_message) {
      res_serial_data = (char*)data;

      /* Call the event_handler for this application-specific event. */
      res_event.trigger();

      /* Also call the separate response example handler. */
      // res_separate.resume();
    }
  }                             /* while (1) */

  PROCESS_END();
}
Exemple #26
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data)
{
  static struct etimer periodic;
  static struct ctimer backoff_timer;

  PROCESS_BEGIN();

  PRINTF("Configuring sensors... ");

  leds_on(LEDS_GREEN);

  i2c_init();

  leds_on(LEDS_YELLOW);

  if(i2c_start(ADG715_A|I2C_WRITE)){
    leds_on(LEDS_RED);
  }

  i2c_write(0xFF);

  leds_off(LEDS_YELLOW);

  PRINTF("done!\n");

  PROCESS_PAUSE();

  set_global_address();
  
  PRINTF("UDP client process started\n");

  print_local_addresses();

  /* new connection with remote host */
  /* TEST PARA RAFA */

  uip_ipaddr_t ipaddr;
  get_node_address(&ipaddr);
  ipaddr.u16[7] = 0xFFFF;
  PRINT6ADDR(&ipaddr);

  client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL); 
  udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT)); 

  PRINTF("Created a connection with the server ");
  PRINT6ADDR(&client_conn->ripaddr);
  PRINTF(" local/remote port %u/%u\n",
	UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));

  etimer_set(&periodic, SEND_INTERVAL);
  while(1) {
    PROCESS_YIELD();
    if(ev == tcpip_event) {
      tcpip_handler();
    }
    
    if(etimer_expired(&periodic)) {
      etimer_reset(&periodic);
      ctimer_set(&backoff_timer, SEND_TIME, send_packet, NULL);
    }
  }

  PROCESS_END();
}
Exemple #27
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data)
{
  static struct etimer periodic;
  static struct ctimer backoff_timer;
 static struct etimer wait;
//static int tx[] = { 31, 27, 23, 19, 15, 11, 7, 3};
static int i ;
#if WITH_COMPOWER
  static int print = 0;
#endif

  PROCESS_BEGIN();

  //powertrace_start(CLOCK_SECOND * 2); //elnaz

  cc2420_set_txpower(19);

  printf(" Tx=%d\n", cc2420_get_txpower());

  PROCESS_PAUSE();

  set_global_address();

  PRINTF("UDP client process started\n");

  print_local_addresses();

  /* new connection with remote host */
  client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL);
  if(client_conn == NULL) {
    PRINTF("No UDP connection available, exiting the process!\n");
    PROCESS_EXIT();
  }
  udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT));

  PRINTF("Created a connection with the server ");
  PRINT6ADDR(&client_conn->ripaddr);
  PRINTF(" local/remote port %u/%u\n",
	UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));

#if WITH_COMPOWER
  powertrace_sniff(POWERTRACE_ON);
#endif

  etimer_set(&periodic, SEND_INTERVAL);

//for(i = 0 ; i<8 ; i++)
//{


  while(seq<100)
     {
    	PROCESS_YIELD();
    	if(ev == tcpip_event)
    	{
     	 tcpip_handler();
    	}

    	if(etimer_expired(&periodic))
    	{
	      	etimer_reset(&periodic);
	     	 ctimer_set(&backoff_timer, SEND_TIME, send_packet, NULL);
        }  //end etimer_expired

     }
  	 seq = 0;
     etimer_stop(&periodic);

     etimer_set(&wait, WAIT_INTERVAL);

     PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER);
  etimer_set(&periodic, SEND_INTERVAL);

//  } // end loop on Tx

  PROCESS_END();
}
Exemple #28
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(coffee_test_process, ev, data)
{
  int fd_write, n, i;
  static int cnt = 0;
  uint8_t buffer[FILE_SIZE];
  clock_time_t now;
  unsigned short now_fine;
  static uint32_t time_start, time_stop;

  printf("###########################################################\n");

  PROCESS_BEGIN();

  printf("process running\n");

  // wait for 5 sec
  etimer_set(&et, CLOCK_SECOND * 5);
  PROCESS_YIELD_UNTIL(etimer_expired(&et));

#if (COFFEE_DEVICE == 6)
  int initialized = 0, i;

  SDCARD_POWER_ON();

  //--- Detecting devices and partitions
  TEST_EQUALS(diskio_detect_devices(), DISKIO_SUCCESS);

  info = diskio_devices();
  for (i = 0; i < DISKIO_MAX_DEVICES; i++) {
    if ((info + i)->type == (DISKIO_DEVICE_TYPE_SD_CARD | DISKIO_DEVICE_TYPE_PARTITION)) {
      info += i;
      initialized = 1;
      break; 
    }
  }
  TEST_EQUALS(initialized, 1);

  diskio_set_default_device(info);
#endif

  printf("fomartting...\n");
  TEST_EQUALS(cfs_coffee_format(), 0);
  //printf("test starting\n");

  do {
    now_fine = clock_time();
    now = clock_seconds();
  } while (now_fine != clock_time());
  time_start = ((unsigned long)now)*CLOCK_SECOND + now_fine%CLOCK_SECOND;

  while(1) {
    // Shortest possible pause
    PROCESS_PAUSE();

    // Determine the filename
    char b_file[8];
    sprintf(b_file,"%u.b", cnt);

    // Set the file size
    printf("Reserving '%s'...\n", b_file);
    TEST_EQUALS(cfs_coffee_reserve(b_file, FILE_SIZE), 0);

      // And open it
    printf("Opening '%s'...\n", b_file);
    fd_write = cfs_open(b_file, CFS_WRITE);
    TEST_NEQ(fd_write, -1);

    // fill buffer
    for(i=0; i<FILE_SIZE; i++) {
      buffer[i] = cnt % 0xFF;
    }

    // Open was successful, write has to be successful too since the size has been reserved
    printf("Writing'%s'...\n", b_file);
    n = cfs_write(fd_write, buffer, FILE_SIZE);
    cfs_close(fd_write);

    TEST_EQUALS(n, FILE_SIZE);

    printf("%s written\n", b_file);

    if( cnt >= FILES_IN_STORAGE ) {
      int fd_read;

      // Figure out the filename
      char r_file[8];
      sprintf(r_file,"%u.b", cnt - FILES_IN_STORAGE);

      // Open the bundle file
      printf("Reopening '%s'...\n", r_file);
      fd_read = cfs_open(r_file, CFS_READ);
      if(fd_read == -1) {
        // Could not open file
        printf("############# STORAGE: could not open file %s\n", r_file);
        fail();
      }

      memset(buffer, 0, FILE_SIZE);

      // And now read the bundle back from flash
      printf("Reading '%s'...\n", b_file);
      if (cfs_read(fd_read, buffer, FILE_SIZE) == -1){
        printf("############# STORAGE: cfs_read error\n");
        cfs_close(fd_read);
        fail();
      }
      cfs_close(fd_read);

      for(i=0; i<FILE_SIZE; i++) {
        if( buffer[i] != (cnt - FILES_IN_STORAGE) % 0xFF ) {
          printf("############# STORAGE: verify error\n");
          fail();
        }
      }

      if( cfs_remove(r_file) == -1 ) {
        printf("############# STORAGE: unable to remove %s\n", r_file);
        fail();
      }

      printf("%s deleted\n", r_file);
    }

    cnt ++;

    if( cnt >= 10 ) {
      do {
        now_fine = clock_time();
        now = clock_seconds();
      } while (now_fine != clock_time());
      time_stop = ((unsigned long)now)*CLOCK_SECOND + now_fine%CLOCK_SECOND;

      TEST_REPORT("data written", FILE_SIZE*cnt*CLOCK_SECOND, time_stop-time_start, "bytes/s");
      TEST_PASS();
      watchdog_stop();
      while(1);
    }
  }

  PROCESS_END();
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data)
{
  static struct etimer periodic;
  static struct ctimer backoff_timer;




#if WITH_COMPOWER
  static int print = 0;
#endif

  PROCESS_BEGIN();

  PROCESS_PAUSE();

  set_global_address();
  
  PRINTF("UDP client process started\n");

  print_local_addresses();

  /* new connection with remote host */
  client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL); 
  if(client_conn == NULL) {
    PRINTF("No UDP connection available, exiting the process!\n");
    PROCESS_EXIT();
  }
  udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT)); 

  PRINTF("Created a connection with the server ");
  PRINT6ADDR(&client_conn->ripaddr);
  PRINTF(" local/remote port %u/%u\n",
	UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));

 // printf("%d \n", CLOCK_SECOND);
  
#if WITH_COMPOWER
  powertrace_sniff(POWERTRACE_ON);
#endif
   configure_adc();
  //etimer_set(&periodic, SEND_INTERVAL);
while(1) {
    PROCESS_YIELD();
    if(ev == tcpip_event) {
//      tcpip_handler();
    }
    
    //if(etimer_expired(&periodic)) {
      //PRINTF("Timer Expired ");	
      
      //etimer_reset(&periodic);
    //}

     if(ev==event_data_ready)
     {

	/*if(counter == 33)     
	{
		memmove(buf+2, buffer,  66);  
		counter = 0;    
		ctimer_set(&backoff_timer, SEND_TIME, send_packet, NULL);
	        //printf("Counter %d \n",counter);
	}*/
      
#if WITH_COMPOWER
      if (print == 0) {
	powertrace_print("#P");
      }
      if (++print == 3) {
	print = 0;
      }
#endif

    }
  }

  PROCESS_END();
}
PROCESS_THREAD(er_example_server, ev, data)
{
  PROCESS_BEGIN();

  PROCESS_PAUSE();

  PRINTF("Starting Erbium Example Server\n");
  PRINTF("uIP buffer: %u\n", UIP_BUFSIZE);
  PRINTF("LL header: %u\n", UIP_LLH_LEN);
  PRINTF("IP+UDP header: %u\n", UIP_IPUDPH_LEN);
  PRINTF("REST max chunk: %u\n", REST_MAX_CHUNK_SIZE);

  hw_init();
  /* Initialize the REST engine. */
  rest_init_engine();

  /*
   * Bind the resources to their Uri-Path.
   * WARNING: Activating twice only means alternate path, not two instances!
   * All static variables are the same for each URI path.
   */
  rest_activate_resource(&res_hello, "test/hello");
/*  rest_activate_resource(&res_mirror, "debug/mirror"); */
/*  rest_activate_resource(&res_chunks, "test/chunks"); */
/*  rest_activate_resource(&res_separate, "test/separate"); */
  rest_activate_resource(&res_push, "test/push");
/*  rest_activate_resource(&res_event, "s/button"); */
/*  rest_activate_resource(&res_sub, "test/sub"); */
/*  rest_activate_resource(&res_b1_sep_b2, "test/b1sepb2"); */
#if PLATFORM_HAS_LEDS
/*  rest_activate_resource(&res_leds, "a/leds"); */
  rest_activate_resource(&res_toggle, "a/toggle");
#endif
#if PLATFORM_HAS_LIGHT
  rest_activate_resource(&res_light, "s/light"); 
  SENSORS_ACTIVATE(light_sensor);  
#endif

#if PLATFORM_HAS_BATTERY
  rest_activate_resource(&res_battery, "s/battery");  
  SENSORS_ACTIVATE(battery_sensor);  
#endif
/*
#if PLATFORM_HAS_RADIO
  rest_activate_resource(&res_radio, "s/radio");  
  SENSORS_ACTIVATE(radio_sensor);  
#endif
#if PLATFORM_HAS_SHT11
  rest_activate_resource(&res_sht11, "s/sht11");  
  SENSORS_ACTIVATE(sht11_sensor);  
#endif
*/

  /* Define application-specific events here. */
  while(1) {
    PROCESS_WAIT_EVENT();
#if PLATFORM_HAS_BUTTON
    if(ev == sensors_event && data == &button_sensor) {
      PRINTF("*******BUTTON*******\n");

      /* Call the event_handler for this application-specific event. */
      res_event.trigger();

      /* Also call the separate response example handler. */
      res_separate.resume();
    }
#endif /* PLATFORM_HAS_BUTTON */
  }                             /* while (1) */

  PROCESS_END();
}