Beispiel #1
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(shell_append_process, ev, data)
{
  static int fd = 0;
  struct shell_input *input;

  PROCESS_EXITHANDLER(cfs_close(fd));
  
  PROCESS_BEGIN();

  fd = cfs_open(data, CFS_WRITE | CFS_APPEND);

  if(fd < 0) {
    shell_output_str(&append_command,
		     "append: could not open file for writing: ", data);
  } else {
    while(1) {
      PROCESS_WAIT_EVENT_UNTIL(ev == shell_event_input);
      input = data;
      /*    printf("cat input %d %d\n", input->len1, input->len2);*/
      if(input->len1 + input->len2 == 0) {
	cfs_close(fd);
	PROCESS_EXIT();
      }
      
      cfs_write(fd, input->data1, input->len1);
      cfs_write(fd, input->data2, input->len2);
      
      shell_output(&append_command,
		   input->data1, input->len1,
		   input->data2, input->len2);
    }
  }
  
  PROCESS_END();
}
PROCESS_THREAD(sniffer_process, ev, data)
{
	static struct etimer et;

	leds_off(LEDS_ALL); /* turn off LEDs */
	SENSORS_ACTIVATE(button_sensor); /* turn on button sensor */

	PROCESS_EXITHANDLER(broadcast_close(&bc));
	PROCESS_BEGIN();

	broadcast_open(&bc, SNIFFER_CHANNEL, &broadcast_call);

	process_start(&wait_process, NULL); /* Start wait process.  This will end the main process when a button sensor 						event is posted */

	while(1) /* Infinite loop */
	{
		etimer_set(&et, CLOCK_SECOND * 2 * PERIOD); /* Wait 4 seconds per loop for a receive event */

		PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

		#if DEBUG
			printf("Loop\n");
		#endif
	}


	SENSORS_DEACTIVATE(button_sensor); /* Deactivate sensor when we're done */
	PROCESS_END();
}
Beispiel #3
0
PROCESS_THREAD(interferer_example, ev, data)
{
 PROCESS_EXITHANDLER()  
 PROCESS_BEGIN();

 // Initial configurations on CC2420: channel and tx power
 watchdog_stop();
 cc2420_set_txpower(CC2420_TXPOWER_MAX);
 cc2420_set_channel(INTERFERED_CHANNEL);
 printf("HandyMote: interfering continuously with random power\n");
 
 // Interfering continuously with random power
 CC2420_SPI_ENABLE();
 set_jammer(CARRIER_TYPE);
 int randelay, randpower;
 while(1){
	 randpower = random_value(MIN_POWER,MAX_POWER);
	 randelay = random_value(MIN_TIME,MAX_TIME);	 
	 power_jammer(randpower);
	 clock_delay(randelay);
 }
 CC2420_SPI_DISABLE();

 PROCESS_WAIT_EVENT();  
 PROCESS_END();
}
Beispiel #4
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(blindnode_bcast_rec, ev, data)
{
  static struct etimer et;
  static uint8_t n;
  int i;

  PROCESS_EXITHANDLER(broadcast_close(&broadcast));

  PROCESS_BEGIN();

  printf("Reading Chip ID: 0x%02x\n", CHIPID);
  /* Read our chip ID. If we are not cc2431, bail out */
  if(CHIPID != CC2431_CHIP_ID) {
    printf("Hardware does not have a location engine. Exiting.\n");
    PROCESS_EXIT();
  }

  /* OK, we are cc2431. Do stuff */
  n = 0;

  /* Initalise our structs and parameters */
  memset(ref_coords, 0, sizeof(struct refcoords) * MAX_REF_NODES);
  memset(&parameters, 0, sizeof(struct meas_params));

  /*
   * Just hard-coding measurement parameters here.
   * Ideally, this should be part of a calibration mechanism
   */
  parameters.alpha=SAMPLE_ALPHA;
  parameters.x_min=0;
  parameters.x_delta=255;
  parameters.y_min=0;
  parameters.y_delta=255;

  set_imaginary_ref_nodes();

  broadcast_open(&broadcast, 129, &broadcast_call);

  while(1) {

    etimer_set(&et, CLOCK_SECOND);

    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

    /*
     * With the hard-coded parameters and locations, we will calculate
     * for all possible values of n [0 , 31]
     */
    parameters.n=n;
    calculate();
    n++;
    if(n==32) { n=0; }

    /* Send our calculated location to some monitoring node */
    packetbuf_copyfrom(&coords, 2*sizeof(uint8_t));
    broadcast_send(&broadcast);
  }
  PROCESS_END();
}
Beispiel #5
0
PROCESS_THREAD(accmeter_process, ev, data) {
  PROCESS_POLLHANDLER(poll_handler());
  PROCESS_EXITHANDLER();
  PROCESS_BEGIN();
  while(1){
    PROCESS_WAIT_EVENT_UNTIL(0);    // should do nothing in while loop.
  }
  PROCESS_END();
}
Beispiel #6
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(netdb_process, ev, data)
{
  PROCESS_EXITHANDLER(mesh_close(&mesh));
  PROCESS_BEGIN();

  mesh_open(&mesh, NETDB_CHANNEL, &callbacks);
  process_start(&query_process, NULL);

  PROCESS_END();
}
Beispiel #7
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(motion_int_process, ev, data)
{
    PROCESS_EXITHANDLER();
    PROCESS_BEGIN();

    while(1) {
        PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL);
        presence_int_callback(0);
    }
    PROCESS_END();
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(rime_unicast_sender, ev, data)
{
  PROCESS_EXITHANDLER(unicast_close(&uc));

  PROCESS_BEGIN();


  unicast_open(&uc, 146, &unicast_callbacks); // channel = 145
  while(1){
	PROCESS_YIELD();
  }
  PROCESS_END();
}
Beispiel #9
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(example_unicast_process, ev, data)
{
        static int i = 0;
        static struct etimer et;

        PROCESS_EXITHANDLER(unicast_close(&uc));
        PROCESS_BEGIN();

        unicast_open(&uc, 128, &unicast_callbacks);

        printf("rimeaddr_node_addr = [%u, %u]\n", rimeaddr_node_addr.u8[0],
                        rimeaddr_node_addr.u8[1]);


        /* Put receiver node in listening mode */
        if (rimeaddr_node_addr.u8[0] == receiver_node_rime_addr[0]
                        && rimeaddr_node_addr.u8[1] == receiver_node_rime_addr[1]) {
                /*
                 * Exit process
                 * Received messages handled by 'recv_uc(...)'
                 */
                printf("Receiver node listening\n");
        } else {
                /* Sending messages */
                printf("Write a character on serial link to send message\n");

                PROCESS_WAIT_EVENT_UNTIL(ev == serial_line_event_message);
                etimer_set(&et, 1 * CLOCK_SECOND);
                while (1) {
                        char msg[64];
                        int len;
                        rimeaddr_t addr;


                        PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

                        len = 1 + sprintf(msg, "hello world #%u", i);
                        i++;

                        packetbuf_copyfrom(msg, len);
                        addr.u8[0] = receiver_node_rime_addr[0];
                        addr.u8[1] = receiver_node_rime_addr[1];

                        unicast_send(&uc, &addr);
                        printf("unicast message sent [%i bytes]\n", len);

                        etimer_reset(&et);
                }
        }
        PROCESS_END();
}
PROCESS_THREAD(interferer_example, ev, data)
{
 PROCESS_EXITHANDLER()  
 PROCESS_BEGIN();
 
 static struct etimer et;
 //powertrace_start(CLOCK_SECOND * 2);

 // Initial configurations on CC2420: channel and tx power
 watchdog_stop();
 cc2420_set_txpower(power);
 cc2420_set_channel(26);
 //printf("interfering with periodic interference\n"); 
 // Continuous Interference
 
 CC2420_SPI_ENABLE();
 
 //SPI_SET_UNMODULATED(0x1800,0x0100,0x0508,0x0004);
 SPI_SET_MODULATED(0x050C);
 
 //powertrace_start(CLOCK_SECOND*2);

 while(1){	
 
 for(power=3; power<32; power+=4){
 SPI_SET_TXPOWER((0xa0ff & 0xffe0) | (power & 0x1f));
 etimer_set(&et, CLOCK_SECOND/1000);
 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
 //printf ("transmit power = %d\n",power);
 }
 
 for(power=27; power>3; power-=4){
 SPI_SET_TXPOWER((0xa0ff & 0xffe0) | (power & 0x1f));
 etimer_set(&et, CLOCK_SECOND/1000);
 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
 //printf ("transmit power = %d\n",power);
 }
 
 for(power=3; power<32; power+=2){
 SPI_SET_TXPOWER((0xa0ff & 0xffe0) | (0 & 0x1f));
 etimer_set(&et, CLOCK_SECOND/1000);
 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
 //printf ("transmit power = %d\n",power);
 }
 
} 
 CC2420_SPI_DISABLE();
 void powertrace_stop(void); 
 PROCESS_WAIT_EVENT();  
 PROCESS_END();
}
Beispiel #11
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(shell_write_process, ev, data)
{
  static int fd = 0;
  struct shell_input *input;
  int r;

  PROCESS_EXITHANDLER(cfs_close(fd));
  
  PROCESS_BEGIN();

  fd = cfs_open(data, CFS_WRITE);

  if(fd < 0) {
    shell_output_str(&write_command,
		     "write: could not open file for writing: ", data);
  } else {
    while(1) {
      PROCESS_WAIT_EVENT_UNTIL(ev == shell_event_input);
      input = data;
      /*    printf("cat input %d %d\n", input->len1, input->len2);*/
      if(input->len1 + input->len2 == 0) {
	cfs_close(fd);
	PROCESS_EXIT();
      }

      r = 0;      
      if(input->len1 > 0) {
	r = cfs_write(fd, input->data1, input->len1);
      }

      if(r >= 0 && input->len2 > 0) {
	r = cfs_write(fd, input->data2, input->len2);
      }

      if(r < 0) {
	shell_output_str(&write_command, "write: could not write to the file",
			 NULL);
      } else {
	shell_output(&write_command,
		     input->data1, input->len1,
		     input->data2, input->len2);
      }
    }
  }
  
  PROCESS_END();
}
Beispiel #12
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(example_trickle_process, ev, data)
{
	PROCESS_EXITHANDLER(trickle_close(&trickle));
	PROCESS_BEGIN();

	trickle_open(&trickle, CLOCK_SECOND, 128, &trickle_call);

	printf("Write a character on serial link to send message\n");
	while (1) {
		PROCESS_WAIT_EVENT_UNTIL(ev == serial_line_event_message);

		printf("UART: sent\n");
		packetbuf_copyfrom("Hello, world", 13);
		trickle_send(&trickle);
	}
	PROCESS_END();
}
Beispiel #13
0
  PROCESS_THREAD(raven_relay_process, ev, data) {
    uip_ipaddr_t ipaddr;
    PROCESS_POLLHANDLER(pollhandler());
    PROCESS_EXITHANDLER(exithandler());

    // see: http://senstools.gforge.inria.fr/doku.php?id=contiki:examples
    PROCESS_BEGIN();
    PRINTF("Relay process startup.\r\n");
    // wait 3 second, in order to have the IP addresses well configured
    etimer_set(&udp_periodic_timer, CLOCK_CONF_SECOND*3);
    // wait until the timer has expired
    PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER);
    // Define Address of the server that receives our heartbeats.
    // TODO: Make this dynamic
#ifdef UDP_ADDR_A
    uip_ip6addr(&ipaddr,
        UDP_ADDR_A,UDP_ADDR_B,UDP_ADDR_C,UDP_ADDR_D,
        UDP_ADDR_E,UDP_ADDR_F,UDP_ADDR_G,UDP_ADDR_H);
#else /* UDP_ADDR_A */
    uip_ip6addr(&ipaddr,0xbbbb,0,0,0,0xd69a,0x20ff,0xfe07,0x7664);
#endif /* UDP_ADDR_A */

    udpconn = udp_new(NULL, HTONS(0), NULL);

    //udpconn = udp_new(&ipaddr, HTONS(0xF0B0+1), NULL);
    udp_bind(udpconn, HTONS(0xF0B0));
    // udp_attach(udpconn, NULL);

    PRINTF("Created connection with remote peer ");
    PRINT6ADDR(&udpconn->ripaddr);
    PRINTF("\r\nlocal/remote port %u/%u\r\n", HTONS(udpconn->lport),HTONS(udpconn->rport));

    print_local_addresses();
    etimer_set(&udp_periodic_timer, 60*CLOCK_SECOND);

    while(1){
      PRINTF("--- Relay: Waiting for events.\r\n");
      //   tcpip_poll_udp(udpconn);
      PROCESS_WAIT_EVENT();
      //    PROCESS_YIELD();
      udphandler(ev, data);
    }


    PROCESS_END();
  }
   PROCESS_THREAD( contiki_ext_radio_process, ev, data )
   {
      PROCESS_EXITHANDLER( abc_close(&wiselib::contiki::contiki_extdata_radio_conn) );

      PROCESS_BEGIN();

      abc_open( &wiselib::contiki::contiki_extdata_radio_conn, 128, &wiselib::contiki::abc_call );

      while(1)
      {
         static struct etimer et;
         etimer_set( &et, CLOCK_SECOND );

         PROCESS_WAIT_EVENT_UNTIL( etimer_expired(&et) );
      }

      PROCESS_END();
   }
PROCESS_THREAD(blink_process, ev, data) {
  PROCESS_POLLHANDLER();
  PROCESS_EXITHANDLER();
  PROCESS_BEGIN();
  while(1) {
    leds_toggle(LEDS_RED);
    if(adc > 0) {
      time = (CLOCK_SECOND*adc)/1024;
    } else {
      time = CLOCK_SECOND/64;
    }
    if(time == 0) {
      time = 1;
    }
    etimer_set(&etb, time);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&etb));
  }
  PROCESS_END();
}
Beispiel #16
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(vfd_process, ev, data)
{
  PROCESS_POLLHANDLER();
  PROCESS_EXITHANDLER();
  PROCESS_BEGIN();
  vfd_init();
  vfd_print_char(2, 'A');
  while(1) {
    uint8_t btns;
    btns = vfd_read_btns();
    if(btns) {
      leds_on(LEDS_RED);
    } else {
      leds_off(LEDS_RED);
    }
    PROCESS_PAUSE();
  }
  PROCESS_END();
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(slip_drv_process, ev, data)
{
  PROCESS_POLLHANDLER(pollhandler());
  PROCESS_EXITHANDLER(rs232dev_unload());
  
  PROCESS_BEGIN();

  rs232dev_init();
  
  SERVICE_REGISTER(slip_drv_service);

  process_poll(&slip_drv_process);
  
  while(1) {
    PROCESS_YIELD();
  }
  
  PROCESS_END();
}
Beispiel #18
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(hello_world_process, ev, data)
{
  PROCESS_EXITHANDLER(unicast_close(&uc))
  
  PROCESS_BEGIN();

  printf("Hello, world\n");
  
  //linkaddr_set_node_addr(&server);
  print_rime_address();
  unicast_open(&uc, 0x17, &uc_rx);
  
  for(;;)
  {
	PROCESS_YIELD();
  }
  
  PROCESS_END();
}
Beispiel #19
0
PROCESS_THREAD(sensys_tx, ev, data)
{
 PROCESS_EXITHANDLER()
 PROCESS_BEGIN();
 
 // Initial configurations  on CC2420 and resetting the timer
 leds_off(LEDS_ALL);
 cc2420_set_txpower(POWER);
 cc2420_set_channel(CHANNEL_SENDER);
 unicast_open(&uc, RIME_SENDER, &unicast_callbacks); 
 ctimer_stop(&timer1);
  
 // Ready to send...
 leds_on(LEDS_BLUE); 
 
 while(1) {
	PROCESS_WAIT_EVENT();		
 }        
 PROCESS_END();
}
Beispiel #20
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(ac_dimmer_int_process, ev, data)
{
  PROCESS_EXITHANDLER();
  PROCESS_BEGIN();

  int dimtime;

  while(1) {
    PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL);
    dimtime = (uint8_t)(100 - dimming);
    dimtime *= 100;

    /* Off cycle */
    clock_delay_usec(dimtime);
    GPIO_SET_PIN(DIMMER_GATE_PORT_BASE, DIMMER_GATE_PIN_MASK);
    /* Triac on propagation delay */
    clock_delay_usec(DIMMER_DEFAULT_GATE_PULSE_US);
    GPIO_CLR_PIN(DIMMER_GATE_PORT_BASE, DIMMER_GATE_PIN_MASK);
  }
  PROCESS_END();
}
Beispiel #21
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(cc1200_demo_process, ev, data)
{
  PROCESS_EXITHANDLER(broadcast_close(&bc))
  PROCESS_BEGIN();

  broadcast_open(&bc, BROADCAST_CHANNEL, &bc_rx);

  etimer_set(&et, LOOP_INTERVAL);

  while(1) {
    PROCESS_YIELD();
    if(ev == PROCESS_EVENT_TIMER) {
      printf("Broadcast --> %u\n", counter);
      leds_toggle(LEDS_RED);
      packetbuf_copyfrom(&counter, sizeof(counter));
      broadcast_send(&bc);
      counter++;
      etimer_set(&et, LOOP_INTERVAL);
    }
  }

  PROCESS_END();
}
PROCESS_THREAD(cc26xx_demo_process, ev, data)
{
  PROCESS_EXITHANDLER(broadcast_close(&bc))

  PROCESS_BEGIN();

  gpio_relay_init();
  relay_all_clear();
  
  
  counter = 0;
  broadcast_open(&bc, BROADCAST_CHANNEL, &bc_rx);

  etimer_set(&et, CLOCK_SECOND);
  
  while(1) {

    PROCESS_YIELD();

    if(ev == PROCESS_EVENT_TIMER) {
      leds_on(LEDS_PERIODIC);
     
      etimer_set(&et, CLOCK_SECOND*5);
      rtimer_set(&rt, RTIMER_NOW() + LEDS_OFF_HYSTERISIS, 1,
                 rt_callback, NULL);
      counter = Get_ADC_reading();
      packetbuf_copyfrom(&counter, sizeof(counter));
      broadcast_send(&bc);
     // printf("adc data value : %d \r\n",counter);
        
    } 
     watchdog_periodic();
  }

  PROCESS_END();
}
Beispiel #23
0
PROCESS_THREAD(rime_unicast_sender, ev, data)
{
  PROCESS_EXITHANDLER(unicast_close(&uc));
  
  PROCESS_BEGIN();

  leds_init();
  leds_off(LEDS_ALL);
  SENSORS_ACTIVATE(button_sensor);//activate button
  unicast_open(&uc, 290, &unicast_callbacks); // channel = 122

  while(1)
  {
    static struct etimer et;
    rimeaddr_t addr;
    
    PROCESS_WAIT_EVENT_UNTIL(ev == sensors_event && data == &button_sensor);

    //etimer_set(&et, CLOCK_SECOND);
    //PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
		
    packetbuf_copyfrom(SECRET, 15); // String + Length to be send
    //packetbuf_copyfrom("ekhais8ca6Aej0", 15); // String + Length to be send
    
    addr.u8[0] = 0x28; // Address of receiving Node
    addr.u8[1] = 0x1;
    
    if(!rimeaddr_cmp(&addr, &rimeaddr_node_addr))
    {
    	printf("Message sent\n"); // debug message
      unicast_send(&uc, &addr);
    }
  }

  PROCESS_END();
}
Beispiel #24
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(weather_meter_int_process, ev, data)
{
  PROCESS_EXITHANDLER();
  PROCESS_BEGIN();

  while(1) {
    PROCESS_YIELD();

    if((ev == anemometer_int_event) && (weather_sensors.anemometer.int_en)) {
      if(weather_sensors.anemometer.ticks >=
         weather_sensors.anemometer.int_thres) {
        anemometer_int_callback(weather_sensors.anemometer.ticks);
      }
    }

    if((ev == rain_gauge_int_event) && (weather_sensors.rain_gauge.int_en)) {
      if(weather_sensors.rain_gauge.ticks >=
         weather_sensors.rain_gauge.int_thres) {
        rain_gauge_int_callback(weather_sensors.rain_gauge.ticks);
      }
    }
  }
  PROCESS_END();
}
PROCESS_THREAD(pwmled_process, ev, data)
{
  PROCESS_POLLHANDLER();
  PROCESS_EXITHANDLER();
  PROCESS_BEGIN();

  leds_off(LEDS_ALL);

  /* no need to do simplepwm_confpin() as it no longer changes those. */
  TEST_PORT(IE) &= ~(1 << pin);
  TEST_PORT(DIR) |= (1 << pin);
  TEST_PORT(OUT) |= (1 << pin);
  TEST_PORT(SEL) &= ~(1 << pin);
  TEST_PORT(SEL2) &= ~(1 << pin);

#if 0
  while(1) {
    simple_pwm_on(20);
    etimer_set(&etr, CLOCK_SECOND/2);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&etr));
    simple_pwm_on(40);
    etimer_set(&etr, CLOCK_SECOND/2);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&etr));
    simple_pwm_on(60);
    etimer_set(&etr, CLOCK_SECOND/2);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&etr));
    simple_pwm_on(80);
    etimer_set(&etr, CLOCK_SECOND/2);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&etr));
    simple_pwm_on(100);
    etimer_set(&etr, CLOCK_SECOND/2);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&etr));
  }
#endif /* if 0; commented out code */

  while(1) {
    simple_pwm_on(i);

    /* find next PWM setting */
    if(up) {
      if(i < PWM_MAX - PWM_STEP) {
        i += PWM_STEP;
      } else {
        i = PWM_MAX;
        up = 0;
      }
    } else {
      if(i > PWM_MIN + PWM_STEP) {
        i -= PWM_STEP;
      } else {
        i = PWM_MIN ;
        up = 1;
      }
    }
    
    /* wait a little while */
    etimer_set(&etr, INTERVAL);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&etr));
  }
  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();
}
Beispiel #27
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(shell_sequence_process, ev, data) {

	static struct etimer etimer;

	PROCESS_EXITHANDLER(leds_off(LEDS_ALL));

	PROCESS_BEGIN();

	static uint16_t temp3;
	temp3 = mylog(std_dev_0/std_dev_1);

	// Error probability parameters
	// alpha = 0.001 - Probability of false alarm.
	// beta = 0.001 - Probability of miss.
	static int b = 7;	// b = log((1-beta)/alpha) = 6.9068

	// Variables
	uint16_t observation;
	static int16_t S_n;
	// Make sure to actually reset S_n every time we run a sequence.
	S_n = 0;
	static int16_t suff_stat = 0;
	static int16_t min_level;
	min_level = 0;
	uint16_t temp1 = 0;
	uint16_t temp2 = 0;
	static int decision;
	// Make sure to actually reset decision every time we run a sequence.
	decision = 0;
	int a = 0;
	int c = 0;

	etimer_set(&etimer, (CLOCK_SECOND / 16));

	while(1) {

		blink_LEDs(LEDS_ALL);

		// Get reading from sensor.
		SENSORS_ACTIVATE(light_sensor);

		// Give the sensors time to activate before taking a reading.
		PROCESS_WAIT_UNTIL(etimer_expired(&etimer));
		etimer_set(&etimer, 11 * (CLOCK_SECOND / 16));
		observation = light_sensor.value(LIGHT_SENSOR_PHOTOSYNTHETIC);
		SENSORS_DEACTIVATE(light_sensor);

		printf("cusum-seq: observation = %d\n",observation);

		// Calculate new statistic based on:
		// suff_stat = log(std_dev_0/std_dev_1)
		// - ((observation - mean_1)^2) / (2*(std_dev_1^2)
		// + ((observation - mean_0)^2) / (2*(std_dev_0^2)	
		//suff_stat =  log(std_dev_0 / std_dev_1) - pow2(observation - mean_1) / (2*pow2(std_dev_1)) + pow2(observation - mean_0) / (2*pow2(std_dev_0));

		a = abs_sub(observation, mean_1);
		c = abs_sub(observation, mean_0);

		// If a or c is too large, calculating temp1 or temp2 can be tough.
		temp1 = temp3 + log_exp_term(c, std_dev_0);
		temp2 = log_exp_term(a, std_dev_1);
		suff_stat = temp1 - temp2;

		// Do appropriate overflow protection.
		if(S_n/2 + suff_stat/2 > 16384 ) {
			S_n = 32767;
		} else if( S_n/2 + suff_stat/2 < -16384) {
			S_n = -32768;
		} else {
			S_n = S_n + suff_stat;
		}

		// Reset the min_level appropriately.
		if(S_n < min_level) {
			min_level = S_n;
		}

		// DEBUG CODE
		printf("cusum-seq: min_level = %d\n",min_level);
		printf("cusum-seq: S_n = %d\n\n",S_n);

			
		// Make decision based on statistic.
		if(S_n >= b + min_level) {
			
			leds_on(LEDS_RED);

			rimeaddr_t addr;
			packetbuf_copyfrom("Change detected", strlen("Change detected"));
			addr.u8[0] = 62;
			addr.u8[1] = 41;
			mesh_send(&mesh, &addr);

			// Send out an observation of data if change detected.
			collect_data(&sequence_command);

			//PROCESS_END();
			if(STOP_MODE) {
				leds_off(LEDS_RED);
				PROCESS_EXIT();
			}
		}

		PROCESS_WAIT_UNTIL(etimer_expired(&etimer));
	}

	PROCESS_END();
}
Beispiel #28
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(cc2538_demo_process, ev, data)
{

  PROCESS_EXITHANDLER(broadcast_close(&bc))

  PROCESS_BEGIN();

  counter = 0;
  broadcast_open(&bc, BROADCAST_CHANNEL, &bc_rx);
  printf("temp:%u.%u\nhumidity:%u.%u\n",(int)tc,((int)(tc*10))%10 , (int)hc,((int)(hc*10))%10);
  while(1) {
    etimer_set(&et, CLOCK_SECOND*10);

    //ivanm
    // Configure ADC, Internal reference, 512 decimation rate (12bit)
    //
    SOCADCSingleConfigure(SOCADC_12_BIT, SOCADC_REF_INTERNAL);
    //
    // Trigger single conversion on AIN6 (connected to LV_ALS_OUT).
    //
    SOCADCSingleStart(SOCADC_VDD);
    //
    // Wait until conversion is completed
    //
    while(!SOCADCEndOfCOnversionGet())
    {
    }
    //
    // Get data and shift down based on decimation rate
    //
    ui1Dummy = SOCADCDataGet() >> SOCADC_12_BIT_RSHIFT;
    printf("konverzija(ADC) = 0x%08x\n",ui1Dummy);
    PROCESS_YIELD();

    if(ev == PROCESS_EVENT_TIMER) {
      leds_on(LEDS_PERIODIC);
      printf("Counter = 0x%08x\n", counter);
      err = s_measure(&temperature, checksum, TEMP);

             	  			if (err == 0)
             	  			{
             	  				//printf("Temperature (ADC value) = 0x%4x\n", temperature);

             	  				err = s_measure(&humidity, checksum, HUMI);

             	  				if (err == 0)
             	  				{
             	  					//printf("Humidity (ADC value) = 0x%4x\n", humidity);

             	  					//tc=sht11_TemperatureC(temperature);
             	  					//hc=sht11_Humidity(temperature,humidity);
             	  					tc=0;
             	  					hc=0;
             	  					printf("temp:%u.%u\nhumidity:%u.%u\n",(int)tc,((int)(tc*10))%10 , (int)hc,((int)(hc*10))%10);
             	  				}
             	  				else
             	  					printf("SHT11 error - could not read humidity!\n");
             	  			}
             	  			else
             	  				printf("SHT11 error - could not read temperature!\n");

      etimer_set(&et, CLOCK_SECOND);
      rtimer_set(&rt, RTIMER_NOW() + LEDS_OFF_HYSTERISIS, 1,
                 rt_callback, NULL);
    } else if(ev == sensors_event) {
      if(data == &button_select_sensor) {
    	  if (swt==0)
    	  {
    		packetbuf_copyfrom(&temperature, sizeof(temperature));
    	  	broadcast_send(&bc);
        	swt=1;
    	  }
          else
          {
        	packetbuf_copyfrom(&humidity, sizeof(humidity));
    	  	broadcast_send(&bc);
        	swt=0;
          }

      } else if(data == &button_left_sensor || data == &button_right_sensor) {
        leds_toggle(LEDS_BUTTON);
      } else if(data == &button_down_sensor) {
        cpu_cpsid();
        leds_on(LEDS_REBOOT);
        watchdog_reboot();
      } else if(data == &button_up_sensor) {
        sys_ctrl_reset();
      }
    } else if(ev == serial_line_event_message) {
      leds_toggle(LEDS_SERIAL_IN);
    }
    counter++;
    /* put measaruement sht11 here*/

  }

  PROCESS_END();
}
Beispiel #29
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(shell_read_process, ev, data)
{
  static int fd = 0;
  static int block_size = MAX_BLOCKSIZE;
  char *next;
  char filename[MAX_FILENAME_LEN];
  int len;
  int offset = 0;
  char buf[MAX_BLOCKSIZE];
  struct shell_input *input;

  PROCESS_EXITHANDLER(cfs_close(fd));
  PROCESS_BEGIN();

  if(data != NULL) {
    next = strchr(data, ' ');
    if(next == NULL) {
      strncpy(filename, data, sizeof(filename));
    } else {
      len = (int)(next - (char *)data);
      if(len <= 0) {
	shell_output_str(&read_command,
		       "read: filename too short: ", data);
	PROCESS_EXIT();
      }
      if(len > MAX_FILENAME_LEN) {
	shell_output_str(&read_command,
		       "read: filename too long: ", data);
	PROCESS_EXIT();
      }
      memcpy(filename, data, len);
      filename[len] = 0;

      offset = shell_strtolong(next, NULL);
      next++;
      next = strchr(next, ' ');
      if(next != NULL) {
	block_size = shell_strtolong(next, NULL);
	if(block_size > MAX_BLOCKSIZE) {
	  shell_output_str(&read_command,
			   "read: block size too large: ", data);
	  PROCESS_EXIT();
        }
      }
    }
    
    fd = cfs_open(filename, CFS_READ);
    cfs_seek(fd, offset, CFS_SEEK_SET);
    
    if(fd < 0) {
      shell_output_str(&read_command,
		       "read: could not open file for reading: ", filename);
    } else {
      
      while(1) {
	len = cfs_read(fd, buf, block_size);
	if(len <= 0) {
	  cfs_close(fd);
	  PROCESS_EXIT();
	}
	shell_output(&read_command,
		     buf, len, "", 0);
	
	process_post(&shell_read_process, PROCESS_EVENT_CONTINUE, NULL);
	PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_CONTINUE ||
				 ev == shell_event_input);
	
	if(ev == shell_event_input) {
	  input = data;
	  /*    printf("cat input %d %d\n", input->len1, input->len2);*/
	  if(input->len1 + input->len2 == 0) {
	    cfs_close(fd);
	    PROCESS_EXIT();
	  }
	}
      }
    }
  }
  
  PROCESS_END();
}
Beispiel #30
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(zoul_demo_process, ev, data)
{
  PROCESS_EXITHANDLER(broadcast_close(&bc))

  PROCESS_BEGIN();

  counter = 0;
  broadcast_open(&bc, BROADCAST_CHANNEL, &bc_rx);

  /* Configure the user button */
  button_sensor.configure(BUTTON_SENSOR_CONFIG_TYPE_INTERVAL,
                          BUTTON_PRESS_EVENT_INTERVAL);

  /* Configure the ADC ports */
  adc_sensors.configure(SENSORS_HW_INIT, ZOUL_SENSORS_ADC_ALL);

  printf("Zoul test application\n");

  etimer_set(&et, LOOP_INTERVAL);

  while(1) {

    PROCESS_YIELD();

    if(ev == PROCESS_EVENT_TIMER) {
      leds_on(LEDS_PERIODIC);

      printf("-----------------------------------------\n"
             "Counter = 0x%08x\n", counter);

      printf("VDD = %d mV\n",
             vdd3_sensor.value(CC2538_SENSORS_VALUE_TYPE_CONVERTED));

      printf("Temperature = %d mC\n",
             cc2538_temp_sensor.value(CC2538_SENSORS_VALUE_TYPE_CONVERTED));

      printf("ADC1 = %d raw\n",
             adc_sensors.value(ZOUL_SENSORS_ADC1));

      printf("ADC3 = %d raw\n",
             adc_sensors.value(ZOUL_SENSORS_ADC3));

      etimer_set(&et, LOOP_INTERVAL);
      rtimer_set(&rt, RTIMER_NOW() + LEDS_OFF_HYSTERISIS, 1,
                 rt_callback, NULL);
      counter++;
    } else if(ev == sensors_event) {
      if(data == &button_sensor) {
        if(button_sensor.value(BUTTON_SENSOR_VALUE_TYPE_LEVEL) ==
           BUTTON_SENSOR_PRESSED_LEVEL) {
          printf("Button pressed\n");
          packetbuf_copyfrom(&counter, sizeof(counter));
          broadcast_send(&bc);
        } else {
          printf("...and released!\n");
        }
      }
    } else if(ev == serial_line_event_message) {
      leds_toggle(LEDS_SERIAL_IN);
    } else if(ev == button_press_duration_exceeded) {
      printf("Button pressed for %d ticks [%u events]\n",
             (*((uint8_t *)data) * BUTTON_PRESS_EVENT_INTERVAL),
             button_sensor.value(BUTTON_SENSOR_VALUE_TYPE_PRESS_DURATION));
    }
  }

  PROCESS_END();
}