示例#1
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(example_abc_process, ev, data)
{
	
	static struct channel *c;
	static struct etimer et;

	PROCESS_BEGIN();
	char buffer[32];	
	
	//button_sensor.activate();
	SENSORS_ACTIVATE(button_sensor);
	
	
	printf("ready to rock\n");
	
	//ds2411_init();
	static int i;
	
	
	//cc2420_init();
	//cc2420_set_pan_addr(panId, 0 /*XXX*/, ds2411_id);
	//cc2420_set_channel(26);

	//abc_open(&abc, 128, &abc_call);
//  set_rime_addr();	
//  cc2420_init();
  //cc2420_set_pan_addr(panId, 0 , ds2411_id);
//  cc2420_set_channel(RF_CHANNEL);

  //cc2420_set_txpower(31);
  //nullmac_init(&cc2420_driver);
  //rime_init(&nullmac_driver);


	//cc2420_set_txpower(31);

	//cc2420_on();
	channel_init();

	packetbuf_clear();

	driver = nullmac_init(&cc2420_driver);	
        //rime_init(driver);
	//driver = sicslowmac_init(&cc2420_driver);
	
	cc2420_set_channel(26);
	channel_open(c, 34);		
	/*packetbuf_clear();*/
	
	driver->set_receive_function(recv);
	//packetbuf_clear();
	
	channel_set_attributes(34, attributes);
	//set_receive_function(driver);	

	driver->on();	
	leds_toggle(LEDS_RED);
	
	packetbuf_clear();
	etimer_set(&et, CLOCK_SECOND * 2 + random_rand() % (CLOCK_SECOND * 2));
	PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
	leds_toggle(LEDS_RED);
	PROCESS_WAIT_EVENT_UNTIL(ev == sensors_event && data == &button_sensor);
	

	while(1)
	{
		if (i % 20 == 19)
		{
			PROCESS_WAIT_EVENT_UNTIL(ev == sensors_event && data == &button_sensor);
		}
		else
		{

			printf("wait!");
			etimer_set(&et, CLOCK_SECOND * 0.5 +  random_rand() % (CLOCK_SECOND) * 0.25);
				
			PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
		}	
		sprintf(buffer, "ping %d\0",i);
		
		printf("Attempting to send %s\n", buffer);

		// send the message straight to the radio
		//cc2420_send ( buffer, (int)strlen(buffer) );
		packetbuf_clear();

		packetbuf_copyfrom(&buffer, (int)strlen(buffer));
                //driver->on();
		//cc2420_driver.send(&buffer, (int)strlen(buffer));
		//cc2420_send ( &buffer, (int)strlen(buffer) );
		
		driver->send();
		
		//rime_output();		
		//abc_send(&abc);
		//chameleon_output(c);
		//driver->off(1);		
		printf("Message sent\n");
		leds_toggle(LEDS_YELLOW);

		i = i + 1;
	}

	PROCESS_END();
}
示例#2
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();
}
示例#3
0
/**
 * \brief Communication Data Class (CDC) Process
 *
 *   This is the link between USB and the "good stuff". In this routine data
 *   is received and processed by CDC-ACM Class
 */
PROCESS_THREAD(cdc_process, ev, data_proc)
{
	PROCESS_BEGIN();

#if USB_CONF_RS232
	static FILE *rs232_stdout,*usb_stdout;
	rs232_stdout=stdout;
#endif

	while(1) {
	    // turn off LED's if necessary
		if (led3_timer) led3_timer--;
		else			Led3_off();

 		if(Is_device_enumerated()) {
			// If the configuration is different than the last time we checked...
			if((uart_usb_get_control_line_state()&1)!=previous_uart_usb_control_line_state) {
				previous_uart_usb_control_line_state = uart_usb_get_control_line_state()&1;
				static FILE* previous_stdout;

				if(previous_uart_usb_control_line_state&1) {
					previous_stdout = stdout;
					uart_usb_init();
					uart_usb_set_stdout();
				//	menu_print(); do this later
				} else {
					stdout = previous_stdout;
				}
#if USB_CONF_RS232
				usb_stdout=stdout;
#endif
			}

			//Flush buffer if timeout
	        if(timer >= 4 && tx_counter!=0 ){
	            timer = 0;
	            uart_usb_flush();
	        } else {
				timer++;
			}

#if USB_CONF_RS232
			stdout=usb_stdout;
#endif
			while (uart_usb_test_hit()){
  		  	   menu_process(uart_usb_getchar());   // See what they want
            }
#if USB_CONF_RS232
            if (usbstick_mode.debugOn) {
			  stdout=rs232_stdout;
			} else {
			  stdout=NULL;
			}
#endif
		}//if (Is_device_enumerated())



		if (USB_CONFIG_HAS_DEBUG_PORT(usb_configuration_nb)) {
			etimer_set(&et, CLOCK_SECOND/80);
		} else {
			etimer_set(&et, CLOCK_SECOND);
		}

		PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

	} // while(1)

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

	memb_init(&memb_nodelist);
	list_init(list_nodelist);

	BOOT_COMPONENT_WAIT(component_topologycontrol);

	static struct etimer waittime;
	etimer_set(&waittime, CLOCK_SECOND * COMPONENT_TOPOLOGYCONTROL_LMST_UPDATEINTERVAL);
	while(1) {
		PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&waittime));
		etimer_reset(&waittime);

		// with a large neighbourhood the algorithm may take a looong time, so stop the watchdog
		// that the node is not rebooted because the CPU thinks there's an endless loop running
		watchdog_stop();

		// Prim algorithm
		// (connects edge of every node except the graph's root node - the node this code is running on=
		_lmst_nodelist_reconstruct();
		while(_lmst_nodelist_hasunconnected()) {

			// find best edge according to PRIM and LMST algorithm
			neighbor_t *edge_actual, *edge_best = NULL;
			for(edge_actual = list_head(component_neighbordiscovery_neighbors()); edge_actual != NULL; edge_actual = list_item_next(edge_actual)) {
				bool node1_connected = _lmst_nodelist_isconnected(edge_actual->node1) && !_lmst_nodelist_isconnected(edge_actual->node2);
				bool node2_connected = _lmst_nodelist_isconnected(edge_actual->node2) && !_lmst_nodelist_isconnected(edge_actual->node1);
				if(node1_connected ^ node2_connected) {
					bool criteria1 = (edge_best == NULL || MAX(edge_actual->weight_node1_to_node2, edge_actual->weight_node2_to_node1) < MAX(edge_best->weight_node1_to_node2, edge_best->weight_node2_to_node1));
					bool criteria2 = (MAX(edge_actual->weight_node1_to_node2, edge_actual->weight_node2_to_node1) == MAX(edge_best->weight_node1_to_node2, edge_best->weight_node2_to_node1) && networkaddr_cmp(NETWORKADDR_MAX(edge_actual), NETWORKADDR_MAX(edge_best)) < 0);
					if(criteria1 || criteria2)
						edge_best = edge_actual;
				}
			}
			if(edge_best == NULL) {
				printf("ERROR[topologycontrol-lmst]: no edge for spanning tree found\n");
				watchdog_reboot(); // we would end in an endless loop
			}

			_lmst_nodelist_connect(edge_best);
		}

#if DEBUG
		node_t *item_node;
		PRINTF("DEBUG: [topologycontrol-lmst] spanning tree: ");
		for(item_node = list_head(list_nodelist); item_node != NULL; item_node = list_item_next(item_node)) {
			if(networkaddr_equal(item_node->address, networkaddr_node_addr()))
				continue;

			PRINTF("%s<->", networkaddr2string_buffered(item_node->edge->node1));
			PRINTF("%s", networkaddr2string_buffered(item_node->edge->node2));
			PRINTF("%s", item_node->next == NULL ? "\n" : ", ");
		}
#endif

		// ignore every node which is not directly connected in the spanning tree
		node_t *node;
		for(node = list_head(list_nodelist); node != NULL; node = list_item_next(node)) {
			if(!networkaddr_equal(node->address, networkaddr_node_addr()) && !networkaddr_equal(node->edge->node1, networkaddr_node_addr()) && !networkaddr_equal(node->edge->node2, networkaddr_node_addr())) {
				component_network_ignoredlinks_add(node->address);
			}
		}

		watchdog_start();

		// LMST is only run once because if links have been ignored they are no longer available in the neighbor discovery
		// and hence a spanning tree can no longer be built
		PRINTF("DEBUG: [topologycontrol-lmst] LMST algorithm is finished and will run no more\n");
		break;
	}

	PROCESS_END();
}
示例#5
0
/*---------------------------------------------------------------------------*/
static
PT_THREAD(handle_dhcp(process_event_t ev, void *data))
{
  clock_time_t ticks;

  PT_BEGIN(&s.pt);
//  printf("handle_dhcp\n");
 init:
// printf("init\n");
  xid++;
  s.state = STATE_SENDING;
  s.ticks = CLOCK_SECOND * 4;
  while(1) {
    while(ev != tcpip_event) {
      tcpip_poll_udp(s.conn);
      PT_YIELD(&s.pt);
    }
    send_discover();
    etimer_set(&s.etimer, s.ticks);
    do {
      PT_YIELD(&s.pt);
//      printf("tcpip_event:%d ev:%d uip_newdata():%d msg_for_me():%d\n",tcpip_event, ev,uip_newdata(),msg_for_me());
      if(ev == tcpip_event && uip_newdata() && msg_for_me() == DHCPOFFER) {
//    printf("here2\n");
	parse_msg();
	s.state = STATE_OFFER_RECEIVED;
	goto selecting;
      }
    } while(!etimer_expired(&s.etimer));

    if(s.ticks < CLOCK_SECOND * 60) {
      s.ticks *= 2;
    }
  }
  
 selecting:
// printf("selecting\n");
  xid++;
  s.ticks = CLOCK_SECOND;
  do {
    while(ev != tcpip_event) {
      tcpip_poll_udp(s.conn);
      PT_YIELD(&s.pt);
    }
    send_request();
    etimer_set(&s.etimer, s.ticks);
    do {
      PT_YIELD(&s.pt);
      if(ev == tcpip_event && uip_newdata() && msg_for_me() == DHCPACK) {
	parse_msg();
	s.state = STATE_CONFIG_RECEIVED;
	goto bound;
      }
    } while (!etimer_expired(&s.etimer));

    if(s.ticks <= CLOCK_SECOND * 10) {
      s.ticks += CLOCK_SECOND;
    } else {
      goto init;
    }
  } while(s.state != STATE_CONFIG_RECEIVED);
  
 bound:
#if 0
  printf("Got IP address %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s.ipaddr));
  printf("Got netmask %d.%d.%d.%d\n",	 uip_ipaddr_to_quad(&s.netmask));
  printf("Got DNS server %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s.dnsaddr));
  printf("Got default router %d.%d.%d.%d\n",
	 uip_ipaddr_to_quad(&s.default_router));
  printf("Lease expires in %ld seconds\n",
	 uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1]));
#endif
//  printf("bound\n");

  ip64_dhcpc_configured(&s);
  
#define MAX_TICKS (~((clock_time_t)0) / 2)
#define MAX_TICKS32 (~((uint32_t)0))
#define IMIN(a, b) ((a) < (b) ? (a) : (b))

  if((uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1]))*CLOCK_SECOND/2
     <= MAX_TICKS32) {
    s.ticks = (uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1])
	       )*CLOCK_SECOND/2;
  } else {
    s.ticks = MAX_TICKS32;
  }

  while(s.ticks > 0) {
    ticks = IMIN(s.ticks, MAX_TICKS);
    s.ticks -= ticks;
    etimer_set(&s.etimer, ticks);
    PT_YIELD_UNTIL(&s.pt, etimer_expired(&s.etimer));
  }

  if((uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1]))*CLOCK_SECOND/2
     <= MAX_TICKS32) {
    s.ticks = (uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1])
	       )*CLOCK_SECOND/2;
  } else {
    s.ticks = MAX_TICKS32;
  }

  /* renewing: */
  xid++;
  do {
    while(ev != tcpip_event) {
      tcpip_poll_udp(s.conn);
      PT_YIELD(&s.pt);
    }
    send_request();
    ticks = IMIN(s.ticks / 2, MAX_TICKS);
    s.ticks -= ticks;
    etimer_set(&s.etimer, ticks);
    do {
      PT_YIELD(&s.pt);
      if(ev == tcpip_event && uip_newdata() && msg_for_me() == DHCPACK) {
	parse_msg();
	goto bound;
      }
    } while(!etimer_expired(&s.etimer));
  } while(s.ticks >= CLOCK_SECOND*3);

  /* rebinding: */

  /* lease_expired: */
  ip64_dhcpc_unconfigured(&s);
  goto init;

  PT_END(&s.pt);
}
示例#6
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();
}
示例#7
0
PROCESS_THREAD(sbk_out_process, ev, data)
{
	PROCESS_BEGIN();
	
	while (1)
	{
		PROCESS_WAIT_UNTIL(sbk_out_track!=0);
		
		if (sbk_in_track==sbk_out_track)
			DBG("Durchfahrt auf Gleis ");
		else
			DBG("Ausfahrt von Gleis ");
		DBG('0' + sbk_out_track);
		DBG("\r\n");
		
		PROCESS_WAIT_UNTIL(sbk_out_track!=sbk_in_track);
		
		switch (sbk_out_track)
		{
			case 1:
				shiftreg |= (1<<RELAIS_G1_OUT);
				break;
			case 2:
				shiftreg |= (1<<RELAIS_G2_OUT);
				break;
			case 3:
				shiftreg |= (1<<RELAIS_G3_OUT);
				break;
			case 4:
				shiftreg |= (1<<RELAIS_G4_OUT);
				break;
			case 5:
				shiftreg |= (1<<RELAIS_G5_OUT);
				break;
			case 6:
				shiftreg |= (1<<RELAIS_G6_OUT);
				break;
			default:
				break;
		}
		
		shiftreg_out16(shiftreg,1);

		// First: wait until track is occupied (allows setting route even when track is empty)
		while ((gbm_register_filt_filt&(1<<sbk_out_track))==0)
		{
			PROCESS_PAUSE();
		}
		
		// Second: wait until track is free again.
		while ((gbm_register_filt_filt&(1<<sbk_out_track))!=0)
		{
			PROCESS_PAUSE();
		}
		
/*
		while (1)
		{			
			if (!gbm_register_filt&(1<<TRACK2GBM(sbk_out_track)))
			{
				break;
			}

			PT_YIELD(pt);
		}
*/		

		etimer_set(&sbk_out_timer, 20*CLOCK_SECOND);
		//sbk_out_timer = TickGet();
		
		// Wait for timeout before resetting sbk exit (this can be overridden by the upper control system)
		//PT_WAIT_UNTIL(pt, (TickGet()-sbk_out_timer) >= 20*TICKS_PER_SECOND);
		PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&sbk_out_timer));
		
		shiftreg &= ~((1<<RELAIS_G1_OUT)
					|(1<<RELAIS_G2_OUT)
					|(1<<RELAIS_G3_OUT)
					|(1<<RELAIS_G4_OUT)
					|(1<<RELAIS_G5_OUT)
					|(1<<RELAIS_G6_OUT));
		
		shiftreg_out16(shiftreg,1);
		
		sbk_out_track = 0;
		process_poll(&sbk_in_process);
	}
	
	PROCESS_END();
}
示例#8
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(ping_process, ev, data)
{
  PROCESS_BEGIN();

  while(1)
    {
      //etimer_set (&et_tx, CLOCK_SECOND * 4 + random_rand() % (CLOCK_SECOND * 4));
      etimer_set (&et_tx, CLOCK_SECOND * 5);// + random_rand() % (CLOCK_SECOND * 1));

      PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER);

    txbuffer[SCENARIO] 	= 	55;
    txbuffer[COUNT] 	= 	count++;
    txbuffer[SENDER] 	=	DEVICE_ID;
    txbuffer[23]	=	88;
    txbuffer[24]	=	77;


    /* ---- TX ---- */

    // Change this to not hardcode the packet length
    nrf_radio_send (txbuffer, 25);

    PRINTF ("PING\t TX: ----- Packet: %hi %hi %hi %hi %hi %hi %hi %hi\n\r",
    txbuffer[SCENARIO], txbuffer[COUNT], txbuffer[SENDER], txbuffer[DELAY],
    txbuffer[MULT], txbuffer[POWERA], txbuffer[POWERB], txbuffer[OPTIONAL]);

    /* ---- RX ---- */
    //nrf_radio_on();
    NETSTACK_RADIO.on();

    /* do we have a packet pending?*/

    /* FIXME CR: quick hack to prevent the program from waiting on an
     * Radio END Event if the packets have collided.
     */
    while (NRF_RADIO->EVENTS_END == 0 && escape < 400000)
      {
	escape++;
      }
    /* Reset the escape counter */
    escape = 0;

    /* Switch the radio off */
    //nrf_radio_off();
    NETSTACK_RADIO.off();

    /* Read what is in the radio buffer */
    nrf_radio_read(rxbuffer, sizeof(rxbuffer));

    PRINTF ("PING\t RX: ----- Last packet: %hi %hi %hi %hi %hi %hi %hi %hi\t\tRSSI: %i\n\r",
    rxbuffer[SCENARIO], rxbuffer[COUNT], rxbuffer[SENDER], rxbuffer[DELAY],
    rxbuffer[MULT], rxbuffer[POWERA], rxbuffer[POWERB], rxbuffer[OPTIONAL], nrf_radio_rssi());

    /* Check of whom we received a packet and count it */

    count_score();

    }

  PROCESS_END();
}
示例#9
0
/*---------------------------------------------------------------------------*/
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();
}
示例#10
0
文件: client.c 项目: copton/ocram
PROCESS_THREAD(rpc_client, ev, data)
{
    static uip_ipaddr_t peer1, peer2;
    static struct etimer et;
    static rpc_call_t call_tell, call_slow_sensor, call_fast_sensor, call_slow_sensor2, call_slow_sensor3;
    static rpc_response_t responses[MAX_TELL_DEPTH];
    static struct uip_udp_conn* conn;
    int16_t size;
    bool success;

    PROCESS_BEGIN();

    ipconfig(true);
    uip_ip6addr(&peer1, 0xfe80, 0, 0, 0, 0x0212, 0x7402, 0x0002, 0x0202);
    uip_ip6addr(&peer2, 0xfe80, 0, 0, 0, 0x0212, 0x7403, 0x0003, 0x0303);
    conn = udp_new(NULL, 0, NULL);
    udp_bind(conn, UDP_CLIENT_PORT);

    static int counter = 0;
    etimer_set(&et, CALL_INTERVAL);
    for (counter=0; counter<10; counter++) {
        static int pending = 0;
        PROCESS_YIELD_UNTIL(etimer_expired(&et));

        rpc_call_read_slow_sensor(1, &call_slow_sensor);
        rpc_call_tell(&peer2, &call_slow_sensor, &call_tell);
        size = rpc_marshall_call(&call_tell, uip_appdata, UIP_BUFSIZE);
        ASSERT (size != -1);
        printf("trace: "); rpc_print_call(&call_tell);
        uip_udp_packet_sendto(conn, uip_appdata, size, &peer1, UDP_SERVER_PORT);
        pending++;

        rpc_call_read_slow_sensor(2, &call_slow_sensor2);
        size = rpc_marshall_call(&call_slow_sensor2, uip_appdata, UIP_BUFSIZE);
        ASSERT (size != -1);
        printf("trace: "); rpc_print_call(&call_slow_sensor2);
        uip_udp_packet_sendto(conn, uip_appdata, size, &peer1, UDP_SERVER_PORT);
        pending++;

        rpc_call_read_slow_sensor(3, &call_slow_sensor3);
        size = rpc_marshall_call(&call_slow_sensor3, uip_appdata, UIP_BUFSIZE);
        ASSERT (size != -1);
        printf("trace: "); rpc_print_call(&call_slow_sensor3);
        uip_udp_packet_sendto(conn, uip_appdata, size, &peer1, UDP_SERVER_PORT);
        pending++;

        rpc_call_read_fast_sensor(1, &call_fast_sensor);
        size = rpc_marshall_call(&call_fast_sensor, uip_appdata, UIP_BUFSIZE);
        ASSERT (size != -1);
        printf("trace: "); rpc_print_call(&call_fast_sensor);
        uip_udp_packet_sendto(conn, uip_appdata, size, &peer1, UDP_SERVER_PORT);
        pending++;

        while(pending != 0) {
            PROCESS_YIELD_UNTIL(ev == tcpip_event && uip_newdata());
            success = rpc_unmarshall_response(responses, MAX_TELL_DEPTH, uip_appdata, uip_datalen());
            rpc_response_t* response = responses + 0;
            ASSERT(success == true);
            printf("trace: "); rpc_print_response(response);
            if (0) {
            } else if (response->sequence == call_fast_sensor.sequence) {
                ASSERT(response->function == RPC_READ_FAST_SENSOR);
                pending--;
            } else if (response->sequence == call_tell.sequence) {
                ASSERT(response->function == RPC_TELL);
                ASSERT(response->data.tell.response->sequence == call_tell.data.tell.call->sequence);
                ASSERT(response->data.tell.response->function == RPC_READ_SLOW_SENSOR);
                pending--;
            } else if (response->sequence == call_slow_sensor2.sequence) {
                ASSERT(response->function == RPC_READ_SLOW_SENSOR);
                pending--;
            } else if (response->sequence == call_slow_sensor3.sequence) {
                ASSERT(response->function == RPC_READ_SLOW_SENSOR);
                pending--;
            }
        }

        etimer_reset(&et);
    }

    printf("QUIT\n");

    PROCESS_END();
}
示例#11
0
static PT_THREAD(handle_mqtt_connection(mqtt_state_t* state))
{
  static struct etimer keepalive_timer;

  uint8_t msg_type;
  uint8_t msg_qos;
  uint16_t msg_id;

  PSOCK_BEGIN(&state->ps);

  // Initialise and send CONNECT message
  mqtt_msg_init(&state->mqtt_connection, state->out_buffer, state->out_buffer_length);
  state->outbound_message =  mqtt_msg_connect(&state->mqtt_connection, state->connect_info);
  PSOCK_SEND(&state->ps, state->outbound_message->data, state->outbound_message->length);
  state->outbound_message = NULL;

  // Wait for CONACK message
  PSOCK_READBUF_LEN(&state->ps, 2);
  if(mqtt_get_type(state->in_buffer) != MQTT_MSG_TYPE_CONNACK)
    PSOCK_CLOSE_EXIT(&state->ps);
  
  // Tell the client we're connected
  mqtt_flags |= MQTT_FLAG_CONNECTED;
  complete_pending(state, MQTT_EVENT_TYPE_CONNECTED);

  // Setup the keep alive timer and enter main message processing loop
  etimer_set(&keepalive_timer, CLOCK_SECOND * state->connect_info->keepalive);
  while(1)
  {
    // Wait for something to happen: 
    //   new incoming data, 
    //   new outgoing data, 
    //   keep alive timer expired
    PSOCK_WAIT_UNTIL(&state->ps, PSOCK_NEWDATA(&state->ps) || 
                                 state->outbound_message != NULL ||
                                 etimer_expired(&keepalive_timer));

    // If there's a new message waiting to go out, then send it
    if(state->outbound_message != NULL)
    {
      PSOCK_SEND(&state->ps, state->outbound_message->data, state->outbound_message->length);
      state->outbound_message = NULL;

      // If it was a PUBLISH message with QoS-0 then tell the client it's done
      if(state->pending_msg_type == MQTT_MSG_TYPE_PUBLISH && state->pending_msg_id == 0)
        complete_pending(state, MQTT_EVENT_TYPE_PUBLISHED);

      // Reset the keepalive timer as we've just sent some data
      etimer_restart(&keepalive_timer);
      continue;
    }

    // If the keep-alive timer expired then prepare a ping for sending
    // and reset the timer
    if(etimer_expired(&keepalive_timer))
    {
      state->outbound_message = mqtt_msg_pingreq(&state->mqtt_connection);
      etimer_reset(&keepalive_timer);
      continue;
    }

    // If we get here we must have woken for new incoming data, 
    // read and process it.
    PSOCK_READBUF_LEN(&state->ps, 2);
    
    state->message_length_read = PSOCK_DATALEN(&state->ps);
    state->message_length = mqtt_get_total_length(state->in_buffer, state->message_length_read);

    msg_type = mqtt_get_type(state->in_buffer);
    msg_qos  = mqtt_get_qos(state->in_buffer);
    msg_id   = mqtt_get_id(state->in_buffer, state->in_buffer_length);
    switch(msg_type)
    {
      case MQTT_MSG_TYPE_SUBACK:
        if(state->pending_msg_type == MQTT_MSG_TYPE_SUBSCRIBE && state->pending_msg_id == msg_id)
          complete_pending(state, MQTT_EVENT_TYPE_SUBSCRIBED);
        break;
      case MQTT_MSG_TYPE_UNSUBACK:
        if(state->pending_msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && state->pending_msg_id == msg_id)
          complete_pending(state, MQTT_EVENT_TYPE_UNSUBSCRIBED);
        break;
      case MQTT_MSG_TYPE_PUBLISH:
        if(msg_qos == 1)
          state->outbound_message = mqtt_msg_puback(&state->mqtt_connection, msg_id);
        else if(msg_qos == 2)
          state->outbound_message = mqtt_msg_pubrec(&state->mqtt_connection, msg_id);

        deliver_publish(state, state->in_buffer, state->message_length_read);
        break;
      case MQTT_MSG_TYPE_PUBACK:
        if(state->pending_msg_type == MQTT_MSG_TYPE_PUBLISH && state->pending_msg_id == msg_id)
          complete_pending(state, MQTT_EVENT_TYPE_PUBLISHED);
        break;
      case MQTT_MSG_TYPE_PUBREC:
        state->outbound_message = mqtt_msg_pubrel(&state->mqtt_connection, msg_id);
        break;
      case MQTT_MSG_TYPE_PUBREL:
        state->outbound_message = mqtt_msg_pubcomp(&state->mqtt_connection, msg_id);
        break;
      case MQTT_MSG_TYPE_PUBCOMP:
        if(state->pending_msg_type == MQTT_MSG_TYPE_PUBLISH && state->pending_msg_id == msg_id)
          complete_pending(state, MQTT_EVENT_TYPE_PUBLISHED);
        break;
      case MQTT_MSG_TYPE_PINGREQ:
        state->outbound_message = mqtt_msg_pingresp(&state->mqtt_connection);
        break;
      case MQTT_MSG_TYPE_PINGRESP:
        // Ignore
        break;
    }

    // NOTE: this is done down here and not in the switch case above
    //       because the PSOCK_READBUF_LEN() won't work inside a switch
    //       statement due to the way protothreads resume.
    if(msg_type == MQTT_MSG_TYPE_PUBLISH)
    {
      uint16_t len;

      // adjust message_length and message_length_read so that
      // they only account for the publish data and not the rest of the 
      // message, this is done so that the offset passed with the
      // continuation event is the offset within the publish data and
      // not the offset within the message as a whole.
      len = state->message_length_read;
      mqtt_get_publish_data(state->in_buffer, &len);
      len = state->message_length_read - len;
      state->message_length -= len;
      state->message_length_read -= len;

      while(state->message_length_read < state->message_length)
      {
        PSOCK_READBUF_LEN(&state->ps, state->message_length - state->message_length_read);
        deliver_publish_continuation(state, state->message_length_read, state->in_buffer, PSOCK_DATALEN(&state->ps));
        state->message_length_read += PSOCK_DATALEN(&state->ps);
      }
    }
  }

  PSOCK_END(&state->ps);
}
示例#12
0
PROCESS_THREAD(clock_test_process, ev, data)
{
  static struct etimer et;
  static clock_time_t count, start_count, end_count, diff;
  static unsigned long sec;
  static u8_t i;

  PROCESS_BEGIN();

  clock_slow_down(50);
  printf("Start Bench\n");
  i = 0;
  etimer_set(&et, CLOCK_SECOND*2);
  	 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

	 setVCoreValue(VCORE_25MHZ);
	 setSystemClock(SYSCLK_25MHZ);
#ifdef PLATFORM_HAS_UART
	 uartInit(SYSCLK_25MHZ);
#endif
	 task();
	 etimer_set(&et, CLOCK_SECOND*2);
	 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));


	 setVCoreValue(VCORE_20MHZ);
	 setSystemClock(SYSCLK_20MHZ);
#ifdef PLATFORM_HAS_UART
	 uartInit(SYSCLK_20MHZ);
#endif
	 task();
	 etimer_set(&et, CLOCK_SECOND*2);
	 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

	 setVCoreValue(VCORE_16MHZ);
	 setSystemClock(SYSCLK_16MHZ);
#ifdef PLATFORM_HAS_UART
	 uartInit(SYSCLK_16MHZ);
#endif
	 task();
	 etimer_set(&et, CLOCK_SECOND*2);
	 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

	 setVCoreValue(VCORE_12MHZ);
	 setSystemClock(SYSCLK_12MHZ);
#ifdef PLATFORM_HAS_UART
	 uartInit(SYSCLK_12MHZ);
#endif
	 task();
	 etimer_set(&et, CLOCK_SECOND*2);
	 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

	 setVCoreValue(VCORE_8MHZ);
	 setSystemClock(SYSCLK_8MHZ);
#ifdef PLATFORM_HAS_UART
	 uartInit(SYSCLK_8MHZ);
#endif
	 task();
	 etimer_set(&et, CLOCK_SECOND*2);
	 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

	setVCoreValue(VCORE_4MHZ);
	setSystemClock(SYSCLK_4MHZ);
#ifdef PLATFORM_HAS_UART
	 uartInit(SYSCLK_4MHZ);
#endif
	 task();
	 etimer_set(&et, CLOCK_SECOND*2);
	 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

   setVCoreValue(VCORE_1MHZ);
   setSystemClock(SYSCLK_1MHZ);
#ifdef PLATFORM_HAS_UART
	 uartInit(SYSCLK_1MHZ);
#endif
	 task();
	 while(1){
		 etimer_set(&et, CLOCK_SECOND*2);
		 PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
	 }

  PROCESS_END();
}
示例#13
0
PROCESS_THREAD(blink_process, ev, data)
{

  static struct etimer et_blink;
  etimer_set(&et_blink, CLOCK_SECOND);
  PROCESS_BEGIN();
static char lux_value[6];
static char lux_value2[6];
static char raw_value[6];
static char raw_value2[6];
static  char temperature_val[6];
static  uint16_t  adc_data=0;
static  uint16_t  adc_data2=0;
static  float adc_lux=0;
static  float adc_lux2=0;
static  float measured_temp=0;
//  static int blinks = 0;

  ssd1306_clear(); 
  ssd1306_set_page_address(0);
  ssd1306_set_column_address(2);
  ssd1306_write_text("Lumen in Lux:");
   
  ssd1306_set_page_address(1);
  ssd1306_set_column_address(2);
  ssd1306_write_text("Raw ADC out :");
 
  ssd1306_set_page_address(2);
  ssd1306_set_column_address(2);
  ssd1306_write_text("Ambient Temperature measured:");


  while(1) {

    PROCESS_WAIT_EVENT();
if (ev==PROCESS_EVENT_TIMER)
   {
   DDRB |=(1<<PORTB4);
   PORTB ^= (1<<PORTB4);
   adc_init();
   adc_data=get_adc(0);
   adc_lux=adc_data*0.9765625;
     
 /*
   amps=adc_volt/10000.0;
   microamps=amps/1000000;
   lux_data=microamps*2;
*/
  itoa(adc_lux, lux_value, 10);
  ssd1306_set_page_address(0);
  ssd1306_set_column_address(73);
  ssd1306_write_text(lux_value);

  itoa(adc_data, raw_value, 10);
  ssd1306_set_page_address(1);
  ssd1306_set_column_address(73);
  ssd1306_write_text(raw_value);

  adc_init_full(ADC_CHAN_ADC0, ADC_TRIG_FREE_RUN, ADC_REF_AVCC, ADC_PS_64);
  adc_conversion_start();
 
  adc_lux2=adc_data2*0.9765626;

  itoa(adc_lux2, lux_value2, 10);
  ssd1306_set_page_address(0);
  ssd1306_set_column_address(95);
  ssd1306_write_text(lux_value2);

  itoa(adc_data2, raw_value2, 10);
  ssd1306_set_page_address(1);
  ssd1306_set_column_address(95);
  ssd1306_write_text(raw_value2);

  measured_temp=ReadTempVal();
  itoa(measured_temp, temperature_val, 10);
  ssd1306_set_page_address(2);
  ssd1306_set_column_address(95);
  ssd1306_write_text(temperature_val);

  }


  }

  PROCESS_END();
}
示例#14
0
PROCESS_THREAD(rest_server_example, ev, data)
{
  static struct etimer ds_periodic_timer;
#if REST_RES_DS1820
  static struct etimer ds_read_timer;
#endif

  PROCESS_BEGIN();

  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);

/* if static routes are used rather than RPL */
#if !UIP_CONF_IPV6_RPL && !defined (CONTIKI_TARGET_MINIMAL_NET) && !defined (CONTIKI_TARGET_NATIVE)
  set_global_address();
  configure_routing();
#endif

  /* Initialize the OSD Hardware. */
  hw_init();

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

  /* Activate the application-specific resources. */
#if REST_RES_DS1820
  rest_activate_resource(&resource_ds1820);
#endif
#if REST_RES_DHT11
  rest_activate_resource(&resource_dht11);
#endif
#if REST_RES_DHT11TEMP
  rest_activate_resource(&resource_dht11temp);
#endif
#if REST_RES_INFO
  rest_activate_resource(&resource_info);
#endif
#if defined (PLATFORM_HAS_LEDS)
#if REST_RES_LEDS
  rest_activate_resource(&resource_leds);
#endif
#if REST_RES_TOGGLE
  rest_activate_resource(&resource_toggle);
#endif
#endif /* PLATFORM_HAS_LEDS */
#if defined (PLATFORM_HAS_TEMPERATURE) && REST_RES_TEMPERATURE
  SENSORS_ACTIVATE(temperature_sensor);
  rest_activate_resource(&resource_temperature);
#endif
#if defined (PLATFORM_HAS_BATTERY) && REST_RES_BATTERY
  SENSORS_ACTIVATE(battery_sensor);
  rest_activate_resource(&resource_battery);
#endif

  /* Define application-specific events here. */
  etimer_set(&ds_periodic_timer, MESURE_INTERVAL);
  while(1) {
    PROCESS_WAIT_EVENT();
#if defined (PLATFORM_HAS_BUTTON)
    if (ev == sensors_event && data == &button_sensor) {
      PRINTF("BUTTON\n");
    }
#endif /* PLATFORM_HAS_BUTTON */
    if(etimer_expired(&ds_periodic_timer)) {
        PRINTF("Periodic\n");
        etimer_reset(&ds_periodic_timer);
#if REST_RES_DHT11
    //    DHT_Read_Data(&dht11_temp, &dht11_hum);
        DHT_Read_Data(&dht11_temp, &dht11_hum);
#endif
#if REST_RES_DS1820
        if(ds1820_convert()){
          etimer_set(&ds_read_timer, READ_TIME);
        }
#endif
    }
#if REST_RES_DS1820
    if(etimer_expired(&ds_read_timer)) {
        PRINTF("DS1820_Read\n");
        ds1820_read();
    }
#endif
  } /* while (1) */

  PROCESS_END();
}
示例#15
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();
}
示例#16
0
/*---------------------------------------------------------------*/
PROCESS_THREAD(null_app_process, ev, data)
{
	PROCESS_BEGIN();
	printf("Hello world Started\n");

	app_conn_open(&nullApp_callback);

	static uint16_t debug_buf[7] = {0};
	static struct etimer rxtimer;
	static char input_buf[MAX_PKT_PAYLOAD_SIZE] = {0};
	static uint16_t counter = 0;


	if (node_id != 0)
		//etimer_set(&rxtimer,(unsigned long)(SEGMENT_PERIOD));
		etimer_set( &rxtimer, (unsigned long)(CLOCK_SECOND/256));
	else
		etimer_set(&rxtimer,CLOCK_SECOND/256);

	//init_mpu6050();
	//uint8_t rv;
	//rv = read_(MPU_ADDRESS, 0x75, 0);
	//printf("%d \n", rv);

	if(node_id != 0)
	{

	  while(1)
	  {

	    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&rxtimer));

	    etimer_reset(&rxtimer);


	    int i = 0;
	    for(i = 0; i < 7; i++)
	    {
		    counter++;
		    debug_buf[i] = sin(counter);
	    }

/*
	    counter++;
	    debug_buf[0] = sin(counter) << 6;

	    counter++;
	    debug_buf[1] = sin(counter) << 6;

	    counter++;
	    debug_buf[2] = sin(counter) << 6;

	    counter++;
	    debug_buf[3] = sin(counter) << 7;
	    counter++;
	    debug_buf[4] = sin(counter) << 7;
	    counter++;
	    debug_buf[5] = sin(counter) << 7;

	    counter++;
	    debug_buf[6] = sin(counter) << 4;

*/
	    app_conn_send((uint8_t *)debug_buf,sizeof(int16_t)*7);

	  }
	}
	PROCESS_END();
}
示例#17
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();
}
示例#18
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data) {
    static struct etimer et;
    static uip_ipaddr_t ipaddr;

    PROCESS_BEGIN();

    print_local_addresses();

    etimer_set(&et, CLOCK_SECOND * 60);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

    uip_ip6addr(&ipaddr,
            server_addr[destination_index][0],
            server_addr[destination_index][1],
            server_addr[destination_index][2],
            server_addr[destination_index][3],
            server_addr[destination_index][4],
            server_addr[destination_index][5],
            server_addr[destination_index][6],
            server_addr[destination_index][7]);
    /* new connection with remote host */
    client_conn = udp_new(&ipaddr, UIP_HTONS(3000), NULL);
    udp_bind(client_conn, UIP_HTONS(3001));
    printf("Connect to ");
    PRINT6ADDR(&client_conn->ripaddr);
    printf(" %u/%u\n",
            UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));

    etimer_set(&et, (random_rand() % SEND_INTERVAL) + CLOCK_SECOND);
    while (1) {
        PROCESS_YIELD();
        if (etimer_expired(&et)) {
            if (((((int8_t) seq_id_client + 1) & 0x7e) == 0x7e) ||
                    ((((int8_t) seq_id_client + 1) & 0x7f) == 0x7f)) {
                seq_id_client++;
            } else {
                uint8_t old_destination_index = destination_index;
                destination_index = (((0xffff & (seq_id_client + 1)) / 128) % MAX_DESTINATIONS);
                if (old_destination_index != destination_index) {
                    uip_ip6addr(&ipaddr,
                            server_addr[destination_index][0],
                            server_addr[destination_index][1],
                            server_addr[destination_index][2],
                            server_addr[destination_index][3],
                            server_addr[destination_index][4],
                            server_addr[destination_index][5],
                            server_addr[destination_index][6],
                            server_addr[destination_index][7]);
                    /* new connection with remote host */
                    client_conn = udp_new(&ipaddr, UIP_HTONS(3000), NULL);
                    udp_bind(client_conn, UIP_HTONS(3001));
                    printf("Connected to ");
                    PRINT6ADDR(&client_conn->ripaddr);
                    printf(" %u/%u\n",
                            UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport));
                    // Store the current seq_id_server_expected and get the new one
                    seq_id_server_expected_list[old_destination_index] = seq_id_server_expected;
                    seq_id_server_expected = seq_id_server_expected_list[destination_index];
                    seq_id_server_list[old_destination_index] = seq_id_server;
                    seq_id_server = seq_id_server_list[destination_index];
                }
                timeout_handler();
            }
            etimer_set(&et, (random_rand() % SEND_INTERVAL) + CLOCK_SECOND);
        } else if (ev == tcpip_event) {
            tcpip_handler();
        }
    }

    PROCESS_END();
}
示例#19
0
PROCESS_THREAD(felicia_main, ev, data)
{
  static struct etimer timer;

  PROCESS_BEGIN();

  /* Initialize the CoAP server and activate resources */
  rest_init_engine();
#if PLATFORM_HAS_LEDS
#ifdef RESOURCE_LED0_CONF_LED
  rest_activate_resource(&resource_led, (char *)"led");
  rest_activate_resource(&resource_led0, (char *)"led/0");
#endif
#ifdef RESOURCE_LED1_CONF_LED
  rest_activate_resource(&resource_led1, (char *)"led/1");
#endif
#endif
  rest_activate_resource(&resource_ipv6_neighbors, (char *)"ipv6/neighbors");
  rest_activate_resource(&resource_rpl_info, (char *)"rpl-info");
  rest_activate_resource(&resource_rpl_parent, (char *)"rpl-info/parent");
  rest_activate_resource(&resource_rpl_rank, (char *)"rpl-info/rank");
  rest_activate_resource(&resource_rpl_link_metric, (char *)"rpl-info/link-metric");

#if PLATFORM_HAS_SLIDE_SWITCH
  SENSORS_ACTIVATE(slide_switch_sensor);
#endif

#if PLATFORM_HAS_BUTTON
  SENSORS_ACTIVATE(button_sensor);
  rest_activate_resource(&resource_push_button_event, (char *)"push-button");
#endif

#if PLATFORM_HAS_SENSORS
  rest_activate_resource(&resource_temperature, (char *)"temperature");
#endif

  PROCESS_PAUSE();

#if WITH_WEBSERVER
  process_start(&node_webserver_simple_process, NULL);
#endif

#if WITH_IPSO
  /* Initialize the OMA LWM2M engine */
  lwm2m_engine_init();

  /* Register default LWM2M objects */
  lwm2m_engine_register_default_objects();

  /* Register default IPSO objects */
  ipso_objects_init();

  setup_lwm2m_servers();
#endif

  while(1) {
    etimer_set(&timer, CLOCK_SECOND * 5);
    PROCESS_WAIT_EVENT();

#if PLATFORM_HAS_BUTTON
    if(ev == sensors_event && data == &button_sensor) {
      resource_push_button_event.trigger();
      PRINTF("Button pressed!\n");
    }
#endif

#if PLATFORM_HAS_SLIDE_SWITCH
    if(ev == sensors_event && data == &slide_switch_sensor) {
      PRINTF("Sliding switch is %s\n",
             slide_switch_sensor.value(0) ? "on" : "off");
    }
#endif
  }

  PROCESS_END();
}
示例#20
0
/*---------------------------------------------------------------------------*/
static void
state_machine(void)
{
    switch(state) {
    case MQTT_CLIENT_STATE_INIT:
        /* If we have just been configured register MQTT connection */
        mqtt_register(&conn, &mqtt_client_process, client_id, mqtt_event,
                      MQTT_CLIENT_MAX_SEGMENT_SIZE);

        /*
         * Authentication: provide user name and password
         */
        if(strlen(conf->auth_token) > 0) {
            mqtt_set_username_password(&conn, "use-token-auth",
                                       conf->auth_token);
        }

        /* _register() will set auto_reconnect. We don't want that. */
        conn.auto_reconnect = 0;
        connect_attempt = 1;

        /*
         * Wipe out the default route so we'll republish it every time we switch to
         * a new broker
         */
        memset(&def_route, 0, sizeof(def_route));

        state = MQTT_CLIENT_STATE_REGISTERED;
        DBG("Init\n");
    /* Continue */
    case MQTT_CLIENT_STATE_REGISTERED:
        if(uip_ds6_get_global(ADDR_PREFERRED) != NULL) {
            /* Registered and with a public IP. Connect */
            DBG("Registered. Connect attempt %u\n", connect_attempt);
            ping_parent();
            connect_to_broker();
        }
        etimer_set(&publish_periodic_timer, CC26XX_WEB_DEMO_NET_CONNECT_PERIODIC);
        return;
        break;
    case MQTT_CLIENT_STATE_CONNECTING:
        leds_on(CC26XX_WEB_DEMO_STATUS_LED);
        ctimer_set(&ct, CONNECTING_LED_DURATION, publish_led_off, NULL);
        /* Not connected yet. Wait */
        DBG("Connecting (%u)\n", connect_attempt);
        break;
    case MQTT_CLIENT_STATE_CONNECTED:
    /* Don't subscribe unless we are a registered device
    if(strncasecmp(conf->org_id, QUICKSTART, strlen(conf->org_id)) == 0) {
      DBG("Using 'quickstart': Skipping subscribe\n");
      state = MQTT_CLIENT_STATE_PUBLISHING;
    }*/
    /* Continue */
    case MQTT_CLIENT_STATE_PUBLISHING:
        /* If the timer expired, the connection is stable. */
        if(timer_expired(&connection_life)) {
            /*
             * Intentionally using 0 here instead of 1: We want RECONNECT_ATTEMPTS
             * attempts if we disconnect after a successful connect
             */
            connect_attempt = 0;
        }

        if(mqtt_ready(&conn) && conn.out_buffer_sent) {
            /* Connected. Publish */
            if(state == MQTT_CLIENT_STATE_CONNECTED) {
                subscribe();
                state = MQTT_CLIENT_STATE_PUBLISHING;
            } else {
                leds_on(CC26XX_WEB_DEMO_STATUS_LED);
                ctimer_set(&ct, PUBLISH_LED_ON_DURATION, publish_led_off, NULL);
                publish();
            }
            etimer_set(&publish_periodic_timer, conf->pub_interval);

            DBG("Publishing\n");
            /* Return here so we don't end up rescheduling the timer */
            return;
        } else {
            /*
             * Our publish timer fired, but some MQTT packet is already in flight
             * (either not sent at all, or sent but not fully ACKd).
             *
             * This can mean that we have lost connectivity to our broker or that
             * simply there is some network delay. In both cases, we refuse to
             * trigger a new message and we wait for TCP to either ACK the entire
             * packet after retries, or to timeout and notify us.
             */
            DBG("Publishing... (MQTT state=%d, q=%u)\n", conn.state,
                conn.out_queue_full);
        }
        break;
    case MQTT_CLIENT_STATE_DISCONNECTED:
        DBG("Disconnected\n");
        if(connect_attempt < RECONNECT_ATTEMPTS ||
                RECONNECT_ATTEMPTS == RETRY_FOREVER) {
            /* Disconnect and backoff */
            clock_time_t interval;
            mqtt_disconnect(&conn);
            connect_attempt++;

            interval = connect_attempt < 3 ? RECONNECT_INTERVAL << connect_attempt :
                       RECONNECT_INTERVAL << 3;

            DBG("Disconnected. Attempt %u in %lu ticks\n", connect_attempt, interval);

            etimer_set(&publish_periodic_timer, interval);

            state = MQTT_CLIENT_STATE_REGISTERED;
            return;
        } else {
            /* Max reconnect attempts reached. Enter error state */
            state = MQTT_CLIENT_STATE_ERROR;
            DBG("Aborting connection after %u attempts\n", connect_attempt - 1);
        }
        break;
    case MQTT_CLIENT_STATE_NEWCONFIG:
        /* Only update config after we have disconnected */
        if(conn.state == MQTT_CONN_STATE_NOT_CONNECTED) {
            update_config();
            DBG("New config\n");

            /* update_config() scheduled next pass. Return */
            return;
        }
        break;
    case MQTT_CLIENT_STATE_CONFIG_ERROR:
        /* Idle away. The only way out is a new config */
        printf("Bad configuration.\n");
        return;
    case MQTT_CLIENT_STATE_ERROR:
    default:
        leds_on(CC26XX_WEB_DEMO_STATUS_LED);
        /*
         * 'default' should never happen.
         *
         * If we enter here it's because of some error. Stop timers. The only thing
         * that can bring us out is a new config event
         */
        printf("Default case: State=0x%02x\n", state);
        return;
    }

    /* If we didn't return so far, reschedule ourselves */
    etimer_set(&publish_periodic_timer, STATE_MACHINE_PERIODIC);
}
示例#21
0
PROCESS_THREAD(sbk_in_process, ev, data)
{

	PROCESS_BEGIN();
	
	while (1)
	{
		PROCESS_WAIT_UNTIL(sbk_in_track!=0);
		
		DBG("Einfahrt auf Gleis ");
		DBG('0' + sbk_in_track);
		DBG("\r\n");
		
		switch (sbk_in_track)
		{
			case 1:
				shiftreg |= (1<<RELAIS_G1_IN);
				break;
			case 2:
				shiftreg |= (1<<RELAIS_G2_IN);
				break;
			case 3:
				shiftreg |= (1<<RELAIS_G3_IN);
				break;
			case 4:
				shiftreg |= (1<<RELAIS_G4_IN);
				break;
			case 5:
				shiftreg |= (1<<RELAIS_G5_IN);
				break;
			case 6:
				shiftreg |= (1<<RELAIS_G6_IN);
				break;
			default:
				break;
		}
		
		shiftreg_out16(shiftreg,1);
		
#if 0
		// First: wait until track is free (allows proper functioning of the cleaning mode)
		PROCESS_WAIT_UNTIL((gbm_register_filt_filt&(1<<sbk_in_track))==0);
		
		// Second: wait until track is occupied again
		PROCESS_WAIT_UNTIL((gbm_register_filt_filt&(1<<sbk_in_track))!=0);
#else
		while ((gbm_register_filt_filt&(1<<sbk_in_track))!=0)
		{
			PROCESS_PAUSE();
		}
		
		while ((gbm_register_filt_filt&(1<<sbk_in_track))==0)
		{
			PROCESS_PAUSE();
		}

#endif		
		if ((sbk_in_track!=sbk_out_track) && (sbk_mode==SBK_MODE_FSS))
		{
			// --> FSS aktivieren via LN --> 120612: nicht nötig, da ständig aktiv
			shiftreg |= (1<<RELAIS_FSS);
			shiftreg_out16(shiftreg,1);
			etimer_set(&sbk_in_timer, 3*CLOCK_SECOND);
			PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&sbk_in_timer));
		}
		
		//PT_WAIT_UNTIL(pt, (TickGet()-sbk_in_timer) >= 3*TICKS_PER_SECOND);
		
		shiftreg &= ~((1<<RELAIS_G1_IN)
					|(1<<RELAIS_G2_IN)
					|(1<<RELAIS_G3_IN)
					|(1<<RELAIS_G4_IN)
					|(1<<RELAIS_G5_IN)
					|(1<<RELAIS_G6_IN)
					|(1<<RELAIS_FSS));
		
		// FSS deaktivieren (oder automatisch nach Ablauf von Timeout)
		shiftreg_out16(shiftreg,1);
		
		sbk_in_track = 0;
		process_poll(&sbk_out_process);
	}
	
	PROCESS_END();
}
示例#22
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(mqtt_client_process, ev, data)
{

    PROCESS_BEGIN();

    printf("CC26XX MQTT Client Process\n");

    conf = &cc26xx_web_demo_config.mqtt_config;
    if(init_config() != 1) {
        PROCESS_EXIT();
    }

    register_http_post_handlers();

    def_rt_rssi = 0x8000000;
    uip_icmp6_echo_reply_callback_add(&echo_reply_notification,
                                      echo_reply_handler);
    etimer_set(&echo_request_timer, conf->def_rt_ping_interval);

    /* Main loop */
    while(1) {

        PROCESS_YIELD();

        if(ev == sensors_event && data == CC26XX_WEB_DEMO_MQTT_PUBLISH_TRIGGER) {
            if(state == MQTT_CLIENT_STATE_ERROR) {
                connect_attempt = 1;
                state = MQTT_CLIENT_STATE_REGISTERED;
            }
        }

        if(ev == httpd_simple_event_new_config) {
            /*
             * Schedule next pass in a while. When HTTPD sends us this event, it is
             * also in the process of sending the config page. Wait a little before
             * reconnecting, so as to not cause congestion.
             */
            etimer_set(&publish_periodic_timer, NEW_CONFIG_WAIT_INTERVAL);
        }

        if(ev == cc26xx_web_demo_config_loaded_event) {
            update_config();
        }

        if((ev == PROCESS_EVENT_TIMER && data == &publish_periodic_timer) ||
                ev == PROCESS_EVENT_POLL ||
                ev == cc26xx_web_demo_publish_event ||
                (ev == sensors_event && data == CC26XX_WEB_DEMO_MQTT_PUBLISH_TRIGGER)) {
            state_machine();
        }

        if(ev == PROCESS_EVENT_TIMER && data == &echo_request_timer) {
            ping_parent();
            etimer_set(&echo_request_timer, conf->def_rt_ping_interval);
        }

        if(ev == cc26xx_web_demo_load_config_defaults) {
            init_config();
            etimer_set(&publish_periodic_timer, NEW_CONFIG_WAIT_INTERVAL);
        }
    }

    PROCESS_END();
}
示例#23
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(udp_client_process, ev, data)
{
  static struct etimer periodic, set_tx_timer;
  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));



  //---------------------- Set Tx ----------

  etimer_set(&set_tx_timer, 30 * CLOCK_SECOND);
  set_tx_flag();
set_tx();
  PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&set_tx_timer));
 clear_tx_flag();
  //--------------------------------------

#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();
}
示例#24
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(aestest, ev, data)
{
    static int i, j;
    unsigned long start, end;
    static struct etimer periodic_timer;

    PROCESS_BEGIN();

    printf("#Fixed AES-128 implementation test for %s.\n", TARGET_NAME);
#ifndef AES_128_CONF
    printf("#Using Contiki software implementation.\n");
#else
    printf("#Using Hardware coprocessor.\n");
#endif
    printf("#Rounds in each sample: %d\n", NROUND);
    printf("#Sample size: %d\n", NSAMPLE);
    printf("#Rtimer clock ticks per second on this platform is : %lu\n",
           (unsigned long) RTIMER_SECOND);
    printf("#datablock address: %u\n", (unsigned int) datablock);

    etimer_set(&periodic_timer, (2 * CLOCK_SECOND));

    //Initialise Data
    for (j = 0; j < NROUND; j++)
        memcpy(datablock[j], fixed_data, AES_BLOCK_LEN);

    for (i = 0; i < NSAMPLE; i++) {
        PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&periodic_timer));
        etimer_reset(&periodic_timer);

#ifdef VERBOSE_AESTEST
        printf("#Sample %d/%d\n", i + 1, NSAMPLE);
        PrintBlock("#Key\t: ", Aes128Key, "\n");
        PrintBlock("#Plaintext\t: ", datablock[0], "\n");
#endif

        AES_128.set_key(Aes128Key);

        //Start timing.
        start = RTIMER_NOW();
#ifndef TIMING_FRAMEWORK_TEST
        for (j = 0; j < NROUND; j++) {
            AES_128.encrypt(datablock[j]);
        }
#else
        for (j = 0; j < NROUND * 10; j++) {
            random_rand();
        }
#endif
        end = RTIMER_NOW();

        //Print result.
#ifdef VERBOSE_AESTEST
        PrintBlock("#Ciphertext\t: ", datablock[0], "\n");
        printf("#Round\t: %d\n", NROUND);
        printf("#Start\t: %lu\n", start);
        printf("#End\t: %lu\n", end);
        printf("#Time Elapsed\t:\n");
#endif
        printf("%lu\n", end - start);

        finalise();
    }

    printf("#%d tests done for %s.\n", NSAMPLE, TARGET_NAME);

    PROCESS_END();
}
示例#25
0
/* A periodic process to send TSCH Enhanced Beacons (EB) */
PROCESS_THREAD(tsch_send_eb_process, ev, data)
{
  static struct etimer eb_timer;

  PROCESS_BEGIN();

  /* Wait until association */
  etimer_set(&eb_timer, CLOCK_SECOND / 10);
  while(!tsch_is_associated) {
    PROCESS_WAIT_UNTIL(etimer_expired(&eb_timer));
    etimer_reset(&eb_timer);
  }

  /* Set an initial delay except for coordinator, which should send an EB asap */
  if(!tsch_is_coordinator) {
    etimer_set(&eb_timer, random_rand() % TSCH_EB_PERIOD);
    PROCESS_WAIT_UNTIL(etimer_expired(&eb_timer));
  }

  while(1) {
    unsigned long delay;

    if(tsch_is_associated && tsch_current_eb_period > 0) {
      /* Enqueue EB only if there isn't already one in queue */
      if(tsch_queue_packet_count(&tsch_eb_address) == 0) {
        int eb_len;
        uint8_t hdr_len = 0;
        uint8_t tsch_sync_ie_offset;
        /* Prepare the EB packet and schedule it to be sent */
        packetbuf_clear();
        /* We don't use seqno 0 */
        if(++tsch_packet_seqno == 0) {
          tsch_packet_seqno++;
        }
        packetbuf_set_attr(PACKETBUF_ATTR_FRAME_TYPE, FRAME802154_BEACONFRAME);
        packetbuf_set_attr(PACKETBUF_ATTR_MAC_SEQNO, tsch_packet_seqno);
#if LLSEC802154_ENABLED
        if(tsch_is_pan_secured) {
          /* Set security level, key id and index */
          packetbuf_set_attr(PACKETBUF_ATTR_SECURITY_LEVEL, TSCH_SECURITY_KEY_SEC_LEVEL_EB);
          packetbuf_set_attr(PACKETBUF_ATTR_KEY_ID_MODE, FRAME802154_1_BYTE_KEY_ID_MODE); /* Use 1-byte key index */
          packetbuf_set_attr(PACKETBUF_ATTR_KEY_INDEX, TSCH_SECURITY_KEY_INDEX_EB);
        }
#endif /* LLSEC802154_ENABLED */
        eb_len = tsch_packet_create_eb(packetbuf_dataptr(), PACKETBUF_SIZE,
            tsch_packet_seqno, &hdr_len, &tsch_sync_ie_offset);
        if(eb_len != 0) {
          struct tsch_packet *p;
          packetbuf_set_datalen(eb_len);
          /* Enqueue EB packet */
          if(!(p = tsch_queue_add_packet(&tsch_eb_address, NULL, NULL))) {
            PRINTF("TSCH:! could not enqueue EB packet\n");
          } else {
            PRINTF("TSCH: enqueue EB packet %u %u\n", eb_len, hdr_len);
            p->tsch_sync_ie_offset = tsch_sync_ie_offset;
            p->header_len = hdr_len;
          }
        }
      }
    }
    if(tsch_current_eb_period > 0) {
      /* Next EB transmission with a random delay
       * within [tsch_current_eb_period*0.75, tsch_current_eb_period[ */
      delay = (tsch_current_eb_period - tsch_current_eb_period / 4)
        + random_rand() % (tsch_current_eb_period / 4);
    } else {
      delay = TSCH_EB_PERIOD;
    }
    etimer_set(&eb_timer, delay);
    PROCESS_WAIT_UNTIL(etimer_expired(&eb_timer));
  }
  PROCESS_END();
}
示例#26
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(remote_grove_gyro_process, ev, data)
{
  PROCESS_BEGIN();

  uint8_t aux;

  /* Use Contiki's sensor macro to enable the sensor */
  SENSORS_ACTIVATE(grove_gyro);

  /* The sensor itself is in low-power mode, to power on just the sensor and not
   * the 3 gyroscope axis use GROVE_GYRO_SENSOR.  Alternatively the value
   * GROVE_GYRO_ALL could also be used to power everything at once
   */
  grove_gyro.configure(GROVE_GYRO_POWER_ON, GROVE_GYRO_SENSOR);  

  /* Read back the configured sensor I2C address to check if the sensor is
   * working OK, this is the only case in which the value() returns a value
   */
  aux = grove_gyro.value(GROVE_GYRO_ADDR);
  if(aux == GROVE_GYRO_EXPECTED_ADDR) {
    printf("Gyro sensor started with addr 0x%02X\n", GROVE_GYRO_EXPECTED_ADDR);
  } else {
    printf("Gyro sensor with unrecognized address 0x%02X\n", aux);
    PROCESS_EXIT();
  }

  /* Register the interrupt handler */
  GROVE_GYRO_REGISTER_INT(gyro_interrupt_callback);

  /* The gyroscope sensor should be on now but the three gyroscope axis should
   * be off, to enable a single axis or any combination of the 3 you can use as
   * argument either GROVE_GYRO_X, GROVE_GYRO_Y, GROVE_GYRO_Z.  To enable or
   * disable the three axis alternatively use GROVE_GYRO_XYZ
   */
  grove_gyro.configure(GROVE_GYRO_POWER_ON, GROVE_GYRO_XYZ);

  /* Calibrate the sensor taking 200 samples every 5ms for the zero-point offset
   * value, this has to be done manually and is up to the user
   */
  grove_gyro.configure(GROVE_GYRO_CALIBRATE_ZERO, 1);

  /* Enabling the data interrupt will feed data directly to the extern data
   * structure and notify us about it, depending on the sampling rate and
   * divisor this could generate many interrupts/second.  A zero argument would
   * disable the interrupts
   */
  grove_gyro.configure(GROVE_GYRO_DATA_INTERRUPT, 1);

  /* And periodically poll the sensor, values are in º/s */

  while(1) {
    etimer_set(&et, SENSOR_READ_INTERVAL);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

    /* This sensor has a different operation from others using Contiki's sensor
     * API, to make data acquisition we write the readings directly to the
     * extern data structure, allowing to write more than 1 value at the same 
     * operation, and also allowing upon a data interrupt event to immediatly 
     * access the data.  The return value of the value() call is then the status 
     * result of the read operation
     */
    if(grove_gyro.value(GROVE_GYRO_XYZ) == GROVE_GYRO_SUCCESS) {

      /* Converted values with a 2-digit precision */
      printf("Gyro: X: %u.%u, Y: %u.%u, Z: %u.%u\n", gyro_values.x / 100,
                                                     gyro_values.x % 100,
                                                     gyro_values.y / 100,
                                                     gyro_values.y % 100,
                                                     gyro_values.z / 100,
                                                     gyro_values.z % 100);
    } else {
      printf("Error, enable the DEBUG flag in the grove-gyro driver for info,");
      printf(" or check if the sensor is properly connected\n");
      PROCESS_EXIT();
    }

    if(grove_gyro.value(GROVE_GYRO_TEMP) == GROVE_GYRO_SUCCESS) {
      printf("Gyro: temperature %d.%02u C\n", gyro_values.temp / 100,
                                             gyro_values.temp % 100);
    } else {
      printf("Error, enable the DEBUG flag in the grove-gyro driver for info,");
      printf(" or check if the sensor is properly connected\n");
      PROCESS_EXIT();
    }
  }
  PROCESS_END();
}
示例#27
0
PROCESS_THREAD(cetic_6lbr_process, ev, data)
{
  static struct etimer timer;
  static int addr_number;
  PROCESS_BEGIN();

  /* Step 0: Basic infrastructure initialization */

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

  //Turn off radio until 6LBR is properly configured
  NETSTACK_MAC.off(0);

  cetic_6lbr_restart_event = process_alloc_event();
  cetic_6lbr_reload_event = process_alloc_event();
  cetic_6lbr_startup = clock_seconds();

#if CETIC_6LBR_MULTI_RADIO
  network_itf_init();
#endif

  /* Step 1: Platform specific initialization */

  platform_init();

  /* Step 2: Register configuration hooks and set default configuration */

#if CETIC_6LBR_NODE_INFO
  node_info_config();
#endif

  /* Step 3: Load configuration from NVM and configuration file */

  platform_load_config(CONFIG_LEVEL_BOOT);

#if !LOG6LBR_STATIC
  if(nvm_data.log_level != 0xFF) {
    Log6lbr_level = nvm_data.log_level;
    Log6lbr_services = nvm_data.log_services;
  }
  LOG6LBR_NOTICE("Log level: %d (services: %x)\n", Log6lbr_level, Log6lbr_services);
#else
  LOG6LBR_NOTICE("Log level: %d (services: %x)\n", LOG6LBR_LEVEL, LOG6LBR_SERVICE_DEFAULT);
#endif

  /* Step 4: Initialize radio and network interfaces */
#if CETIC_6LBR_FRAMER_WRAPPER
  framer_wrapper_init();
#endif

#if CETIC_6LBR_MAC_WRAPPER
  mac_wrapper_init();
#endif

#if CETIC_6LBR_MULTI_RADIO
  CETIC_6LBR_MULTI_RADIO_DEFAULT_MAC.init();
#endif

#if !CETIC_6LBR_ONE_ITF
  platform_radio_init();
  while(!radio_ready) {
    PROCESS_PAUSE();
  }
#endif

  eth_drv_init();

  while(!ethernet_ready) {
    PROCESS_PAUSE();
  }

  //Turn on radio and keep it always on
  NETSTACK_MAC.off(1);

  /* Step 5: Initialize Network stack */

#if CETIC_6LBR_LLSEC_WRAPPER
#if CETIC_6LBR_WITH_ADAPTIVESEC
  llsec_strategy_wrapper_init();
#endif
  llsec_wrapper_init();
#endif

#if CETIC_6LBR_MULTICAST_WRAPPER
  multicast_wrapper_init();
#endif
  //6LoWPAN init
  memcpy(addr_contexts[0].prefix, nvm_data.wsn_6lowpan_context_0, sizeof(addr_contexts[0].prefix));

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

  PROCESS_PAUSE();

  /* Step 6: Configure network interfaces */

  packet_filter_init();
  cetic_6lbr_init();

  //Wait result of DAD on 6LBR addresses
  addr_number = uip_ds6_get_addr_number(-1);
  LOG6LBR_INFO("Checking addresses duplication\n");
  etimer_set(&timer, CLOCK_SECOND);
  while(uip_ds6_get_addr_number(ADDR_TENTATIVE) > 0) {
    PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER);
    etimer_set(&timer, CLOCK_SECOND);
  }
  //Can not use equality as autoconf address could be created when running DAD
  if(uip_ds6_get_addr_number(-1) < addr_number) {
    LOG6LBR_FATAL("Addresses duplication failed\n");
    cetic_6lbr_restart_type = CETIC_6LBR_RESTART;
    platform_restart();
  }

  /* Step 7: Finalize configuration of network interfaces */
  cetic_6lbr_init_finalize();

  /* Step 8: Initialize 6LBR core and base applications */

  platform_load_config(CONFIG_LEVEL_CORE);
  PROCESS_PAUSE();

#if CETIC_6LBR_WITH_WEBSERVER
  webserver_init();
#endif

#if CETIC_6LBR_NODE_INFO
  node_info_init();
#endif

#if CETIC_6LBR_NODE_CONFIG
  node_config_init();
#endif

  /* Step 9: Initialize and configure 6LBR applications */

  platform_load_config(CONFIG_LEVEL_BASE);
  PROCESS_PAUSE();

#if CETIC_6LBR_WITH_UDPSERVER
  udp_server_init();
#endif
#if UDPCLIENT
  process_start(&udp_client_process, NULL);
#endif

#if WITH_TINYDTLS
  dtls_init();
#endif

#if WITH_COAPSERVER
  if((nvm_data.global_flags & CETIC_GLOBAL_DISABLE_COAP_SERVER) == 0) {
    coap_server_init();
  }
#endif

#if WITH_DTLS_ECHO
  process_start(&dtls_echo_server_process, NULL);
#endif

#if CETIC_6LBR_WITH_NVM_PROXY
  nvm_proxy_init();
#endif

#if CETIC_6LBR_WITH_DNS_PROXY
  dns_proxy_init();
#endif

  /* Step 10: Finalize platform configuration and load runtime configuration */

  platform_finalize();
  platform_load_config(CONFIG_LEVEL_APP);

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

  PROCESS_WAIT_EVENT_UNTIL(ev == cetic_6lbr_restart_event);

  etimer_set(&timer, CLOCK_SECOND);
  PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER);

  /* Shutdown 6LBR */

  //Turn off radio
  NETSTACK_MAC.off(0);
  platform_restart();

  PROCESS_END();
}
示例#28
0
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(clock_test_process, ev, data)
{

  PROCESS_BEGIN();

  etimer_set(&et, 2 * CLOCK_SECOND);

  PROCESS_YIELD();

#if TEST_CLOCK_DELAY_USEC
  printf("clock_delay_usec test, (10,000 x i) usec:\n");
  i = 1;
  while(i < 7) {
    start_count = RTIMER_NOW();
    clock_delay_usec(10000 * i);
    end_count = RTIMER_NOW();
    diff = end_count - start_count;
    printf("Requested: %u usec, Real: %u rtimer ticks = ~%u us\n",
           10000 * i, diff, diff * 64);
    i++;
  }
#endif

#if TEST_RTIMER
  printf("Rtimer Test, 1 sec (%u rtimer ticks):\n", RTIMER_SECOND);
  i = 0;
  while(i < 5) {
    etimer_set(&et, 2 * CLOCK_SECOND);
    printf("=======================\n");
    ct = clock_time();
    rt_now = RTIMER_NOW();
    rt_for = rt_now + RTIMER_SECOND;
    printf("Now=%u (clock = %u) - For=%u\n", rt_now, ct, rt_for);
    if(rtimer_set(&rt, rt_for, 1, (rtimer_callback_t) rt_callback, NULL) !=
       RTIMER_OK) {
      printf("Error setting\n");
    }

    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
    i++;
  }
#endif

#if TEST_ETIMER
  printf("Clock tick and etimer test, 1 sec (%u clock ticks):\n",
         CLOCK_SECOND);
  i = 0;
  while(i < 10) {
    etimer_set(&et, CLOCK_SECOND);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
    etimer_reset(&et);

    count = clock_time();
    printf("%u ticks\n", count);

    leds_toggle(LEDS_RED);
    i++;
  }
#endif

#if TEST_CLOCK_SECONDS
  printf("Clock seconds test (5s):\n");
  i = 0;
  while(i < 10) {
    etimer_set(&et, 5 * CLOCK_SECOND);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
    etimer_reset(&et);

    sec = clock_seconds();
    printf("%lu seconds\n", sec);

    leds_toggle(LEDS_GREEN);
    i++;
  }
#endif

  printf("Done!\n");

  PROCESS_END();
}
示例#29
0
/*---------------------------------------------------------------*/
PROCESS_THREAD(null_app_process, ev, data)
{
	PROCESS_BEGIN();
	printf("Sensor No Comm Started\n");

	// turn off radio
	NETSTACK_RDC.off(0);
	NETSTACK_RADIO.off();


	// connect with MPU
	static uint8_t MPU_status = 0;
	static mpu_data_union samples;
	static struct etimer rxtimer;
	int i = 0;

	if (node_id != 0)
	{
		MPU_status = 0;
		for(i = 0; i < 100 & (~MPU_status);i++)
		{
			MPU_status = mpu_enable();
		}

		if (MPU_status == 0)
			printf("MPU could not be enabled.\n");

		MPU_status = 0;
		for(i = 0; i < 100 & (~MPU_status);i++)
		{
			MPU_status = mpu_wakeup();
		}

		if (MPU_status == 0)
		{
			printf("MPU could not be awakened.\n");
		}
		etimer_set(&rxtimer, (unsigned long)(CLOCK_SECOND/SAMPLING_FREQ));
	}

	// sampling
	if (node_id != 0)
	{
		while(1)
		{
			PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&rxtimer));
			etimer_reset(&rxtimer);

			MPU_status = mpu_sample_all(&samples);

			if (MPU_status != 0)
			{
				printf("%d,%d,%d,%d\n",samples.data.accel_x,samples.data.accel_y,samples.data.accel_z,samples.data.temperature);
			}
			else
			{
				printf("Cannot sample data\n");
			}
		}
	}

	
	PROCESS_END();
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(unicast_sender_process, ev, data)
{
  static struct etimer periodic_timer;
  static struct etimer send_timer;

  uip_ipaddr_t *addr;

  PROCESS_BEGIN();

  SENSORS_ACTIVATE(button_sensor);
 // SENSORS_ACTIVATE(light_sensor);

  servreg_hack_init();

  set_global_address();

  simple_udp_register(&unicast_connection, UDP_PORT,
                      NULL, UDP_PORT, receiver);
  rx_start_duration = energest_type_time(ENERGEST_TYPE_LISTEN);
  //etimer_set(&periodic_timer, SEND_INTERVAL);
  while(1) {

   // PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&periodic_timer));
    PROCESS_WAIT_EVENT_UNTIL(ev == sensors_event && data == &button_sensor);
   // etimer_reset(&periodic_timer);
    etimer_set(&send_timer, SEND_TIME);

    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&send_timer));
    addr = servreg_hack_lookup(SERVICE_ID);

    if(addr != NULL) {
      static unsigned int button_number;
      char buf[50];

      if(button_number == 0) {
	button_number = 1;
	leds_toggle(LEDS_ALL);
      } else {
	button_number = 0;
	leds_toggle(LEDS_ALL);
      }

      printf("Sending unicast to ");
      uip_debug_ipaddr_print(addr);
      printf("\n");

      //sprintf(buf, "Occupancy Detector: %d, Luminaire Illuminance: %d", button_number, LUMINAIRE_ILLUMINANCE);
      sprintf(buf, "Occupancy Detector: %d, Luminous Intensity: %d", button_number, /*(int)(random() % 180 + 320 )*/ 1500 );      

      simple_udp_sendto(&unicast_connection, buf, strlen(buf) + 1, addr);
	    //  printf("energy rx: %lu\n", energest_type_time(ENERGEST_TYPE_LISTEN) - rx_start_duration);
		//printf("energy tx: %lu\n", energest_type_time(ENERGEST_TYPE_TRANSMIT) - rx_start_duration);
		//printf("cpu: %lu\n", energest_type_time(ENERGEST_TYPE_CPU) - rx_start_duration);
		//printf("lpm: %lu\n", energest_type_time(ENERGEST_TYPE_LPM) - rx_start_duration);
    } else {
      printf("Service %d not found\n", SERVICE_ID);
    }
  }

  PROCESS_END();
}