예제 #1
0
int32_t main(void)
{
	uint32_t u32Index;
	uint8_t mac_def[6];
	uip_ipaddr_t ipaddr;
	struct timer periodic_timer, arp_timer;
	volatile int32_t ax88796c_isr;
	
	Board_Init();
	Uart4_Init();
	_delay_init();
	// Setup scheduler and tasks
	Scheduler_Init();
	Scheduler_AddTask(Task_SetLEDs, 0, 100);
	Scheduler_AddTask(Task_ProcessSwitches, 0, 50);
	Scheduler_AddTask(Task_Adconverter, 500, 100);
	Scheduler_AddTask(Task_SerialTerminalOutput, 0, 1000);

	Scheduler_Start();

	// Configure uIP
	timer_set(&periodic_timer, CLOCK_SECOND / 2);
	timer_set(&arp_timer, CLOCK_SECOND * 10);
	
	mac_def[0] = UIP_ETHADDR0;
	mac_def[1] = UIP_ETHADDR1;
	mac_def[2] = UIP_ETHADDR2;
	mac_def[3] = UIP_ETHADDR3;
	mac_def[4] = UIP_ETHADDR4;
	mac_def[5] = UIP_ETHADDR5;
	
	ax88796c_init(mac_def);
	uip_init();

	init_uip_clock_time();
	
	uip_ipaddr(ipaddr, UIP_IPADDR0,UIP_IPADDR1,UIP_IPADDR2,UIP_IPADDR3);
	uip_sethostaddr(ipaddr);
	
	uip_ipaddr(ipaddr, UIP_DRIPADDR0,UIP_DRIPADDR1,UIP_DRIPADDR2,UIP_DRIPADDR3);
	uip_setdraddr(ipaddr);
	
	uip_ipaddr(ipaddr, UIP_NETMASK0,UIP_NETMASK1,UIP_NETMASK2,UIP_NETMASK3);
	uip_setnetmask(ipaddr);
	
	httpd_init();
	
	/* hello_world_init(); */
    /* telnetd_init(); */
	
	/*{
		dhcpc_init(&mac_def, 6);
	}*/
  
	/*
	uip_ipaddr(ipaddr, 127,0,0,1);
	smtp_configure("localhost", ipaddr);
	SMTP_SEND("*****@*****.**", "", "*****@*****.**", 
		"Testing SMTP from uIP", 
		"Test message sent by uIP\r\n");
	*/

	/*
    webclient_init();
    resolv_init();
    uip_ipaddr(ipaddr, 168,95,1,1);
    resolv_conf(ipaddr);
    resolv_query("www.sics.se");
	*/
	
	while(1){
		Scheduler_DispatchTasks();
		
		ax88796c_isr = ax88796c_check_int();
		if(ax88796c_isr & ISR_LINK){
			if(!ax88796c_check_media()){
				printf ("Link down.\n");
			}else{
				uint16_t bmcr;
				bmcr = ax88796c_mdio_read(PHY_ID, MII_BMCR);
				printf("Link up, %sMbps, %s-duplex\n",(bmcr & BMCR_SPEED100) ? "100" : "10", \
				(bmcr & BMCR_FULLDPLX) ? "full" : "half");
				
			}
		}
		if(ax88796c_isr & ISR_RXPCT){
			uip_len = ax88796c_packet_receive(uip_buf);
		}else{
			uip_len = 0;
		}
		ax88796c_clear_int(ax88796c_isr);
		
		if(uip_len > 0) {
			if(UipBuf->type == htons(UIP_ETHTYPE_IP)) {
				uip_arp_ipin();
				uip_input();
				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if(uip_len > 0) {
					uip_arp_out();
					ax88796c_packet_send(uip_buf,uip_len);
				}
			} else if(UipBuf->type == htons(UIP_ETHTYPE_ARP)) {
				uip_arp_arpin();
				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if(uip_len > 0) {
					ax88796c_packet_send(uip_buf,uip_len);
				}
			}

		} else if(timer_expired(&periodic_timer)) {
			timer_reset(&periodic_timer);
			for(u32Index = 0; u32Index < UIP_CONNS; u32Index++) {
				uip_periodic(u32Index);
				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if(uip_len > 0) {
					uip_arp_out();
					ax88796c_packet_send(uip_buf,uip_len);
				}
			}

#if UIP_UDP
			for(u32Index = 0; u32Index < UIP_UDP_CONNS; u32Index++) {
				uip_udp_periodic(u32Index);
				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if(uip_len > 0) {
					uip_arp_out();
					ax88796c_packet_send(uip_buf,uip_len);
				}
			}
#endif /* UIP_UDP */

			/* Call the ARP timer function every 10 seconds. */
			if(timer_expired(&arp_timer)) {
				timer_reset(&arp_timer);
				uip_arp_timer();
			}
		}
	}
}
void vuIP_Task( void *pvParameters )
{
portBASE_TYPE i;
uip_ipaddr_t xIPAddr;
struct timer periodic_timer, arp_timer;

	/* Create the semaphore used by the ISR to wake this task. */
	vSemaphoreCreateBinary( xSemaphore );
	
	/* Initialise the uIP stack. */
	timer_set( &periodic_timer, configTICK_RATE_HZ / 2 );
	timer_set( &arp_timer, configTICK_RATE_HZ * 10 );
	uip_init();
	uip_ipaddr( xIPAddr, uipIP_ADDR0, uipIP_ADDR1, uipIP_ADDR2, uipIP_ADDR3 );
	uip_sethostaddr( xIPAddr );
	uip_ipaddr( xIPAddr, uipNET_MASK0, uipNET_MASK1, uipNET_MASK2, uipNET_MASK3 );
	uip_setnetmask( xIPAddr );
	uip_ipaddr( xIPAddr, uipGATEWAY_ADDR0, uipGATEWAY_ADDR1, uipGATEWAY_ADDR2, uipGATEWAY_ADDR3 );
	uip_setdraddr( xIPAddr );	
	httpd_init();

	/* Initialise the MAC. */
	ENET_InitClocksGPIO();
	ENET_Init();
	portENTER_CRITICAL();
	{
		ENET_Start();
		prvSetMACAddress();
		VIC_Config( ENET_ITLine, VIC_IRQ, 1 );
		VIC_ITCmd( ENET_ITLine, ENABLE );	
		ENET_DMA->ISR = uipDMI_RX_CURRENT_DONE;
 		ENET_DMA->IER = uipDMI_RX_CURRENT_DONE;
	}
	portEXIT_CRITICAL();
	

	while(1)
	{
		/* Is there received data ready to be processed? */
		uip_len = ENET_HandleRxPkt( uip_buf );
		
		if( uip_len > 0 )
		{
			/* Standard uIP loop taken from the uIP manual. */
			if( xHeader->type == htons( UIP_ETHTYPE_IP ) )
			{
				uip_arp_ipin();
				uip_input();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					uip_arp_out();
					prvENET_Send();
				}
			}
			else if( xHeader->type == htons( UIP_ETHTYPE_ARP ) )
			{
				uip_arp_arpin();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					prvENET_Send();
				}
			}
		}
		else
		{
			if( timer_expired( &periodic_timer ) )
			{
				timer_reset( &periodic_timer );
				for( i = 0; i < UIP_CONNS; i++ )
				{
					uip_periodic( i );
	
					/* If the above function invocation resulted in data that
					should be sent out on the network, the global variable
					uip_len is set to a value > 0. */
					if( uip_len > 0 )
					{
						uip_arp_out();
						prvENET_Send();
					}
				}	
	
				/* Call the ARP timer function every 10 seconds. */
				if( timer_expired( &arp_timer ) )
				{
					timer_reset( &arp_timer );
					uip_arp_timer();
				}
			}
			else
			{			
				/* We did not receive a packet, and there was no periodic
				processing to perform.  Block for a fixed period.  If a packet
				is received during this period we will be woken by the ISR
				giving us the Semaphore. */
				xSemaphoreTake( xSemaphore, configTICK_RATE_HZ / 2 );			
			}
		}
	}
}
예제 #3
0
파일: uIP_Task.c 프로젝트: Pinekn/freeRTOS
void vuIP_Task( void *pvParameters )
{
portBASE_TYPE i;
uip_ipaddr_t xIPAddr;
struct timer periodic_timer, arp_timer;
extern void ( vEMAC_ISR )( void );

	/* Just to get rid of the compiler warning. */
	( void ) pvParameters;

	/* Enable/Reset the Ethernet Controller */

	/* Create the semaphore used by the ISR to wake this task. */
	vSemaphoreCreateBinary( xFECSemaphore );
	
	/* Initialise the uIP stack. */
	timer_set( &periodic_timer, configTICK_RATE_HZ / 2 );
	timer_set( &arp_timer, configTICK_RATE_HZ * 10 );
	uip_init();
	uip_ipaddr( xIPAddr, configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 );
	uip_sethostaddr( xIPAddr );
	uip_ipaddr( xIPAddr, configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3 );
	uip_setnetmask( xIPAddr );		
	httpd_init();

	vInitFEC();

	for( ;; )
	{
		/* Is there received data ready to be processed? */
		uip_len = ( unsigned short ) ulFECRx();
		
		if( ( uip_len > 0 ) && ( uip_buf != NULL ) )
		{
			/* Standard uIP loop taken from the uIP manual. */

			if( xHeader->type == htons( UIP_ETHTYPE_IP ) )
			{
				uip_arp_ipin();
				uip_input();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					uip_arp_out();
					vFECTx();
				}
			}
			else if( xHeader->type == htons( UIP_ETHTYPE_ARP ) )
			{
				uip_arp_arpin();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					vFECTx();
				}
			}			
		}
		else
		{
			if( ( timer_expired( &periodic_timer ) ) && ( uip_buf != NULL ) )
			{
				timer_reset( &periodic_timer );
				for( i = 0; i < UIP_CONNS; i++ )
				{
					uip_periodic( i );
	
					/* If the above function invocation resulted in data that
					should be sent out on the network, the global variable
					uip_len is set to a value > 0. */
					if( uip_len > 0 )
					{
						uip_arp_out();
						vFECTx();
					}
				}	
	
				/* Call the ARP timer function every 10 seconds. */
				if( timer_expired( &arp_timer ) )
				{
					timer_reset( &arp_timer );
					uip_arp_timer();
				}
			}
			else
			{			
				/* We did not receive a packet, and there was no periodic
				processing to perform.  Block for a fixed period.  If a packet
				is received during this period we will be woken by the ISR
				giving us the Semaphore. */
				xSemaphoreTake( xFECSemaphore, configTICK_RATE_HZ / 2 );			
			}
		}
	}
}
예제 #4
0
/*-----------------------------------------------------------------------------------*/
void
main(void)
{
  struct ethernet_config *ethernet_config;

  videomode(VIDEOMODE_80COL);

  process_init();

#if 1
  ethernet_config = config_read("contiki.cfg");
#else
  {
    static struct ethernet_config config = {0xDE08, "cs8900a.eth"};
    uip_ipaddr_t addr;

    uip_ipaddr(&addr, 192,168,0,128);
    uip_sethostaddr(&addr);

    uip_ipaddr(&addr, 255,255,255,0);
    uip_setnetmask(&addr);

    uip_ipaddr(&addr, 192,168,0,1);
    uip_setdraddr(&addr);

    uip_ipaddr(&addr, 192,168,0,1);
    resolv_conf(&addr);

    ethernet_config = &config;
  }
#endif

#if (WITH_GUI && WITH_MOUSE)
  {
    static const uint8_t mouse_sprite[64] = {
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x0F, 0xE0, 0x00, 0x0F, 0xC0, 0x00, 0x0F,
      0x80, 0x00, 0x0F, 0xC0, 0x00, 0x0D, 0xE0, 0x00,
      0x08, 0xF0, 0x00, 0x00, 0x78, 0x00, 0x00, 0x3C,
      0x00, 0x00, 0x1E, 0x00, 0x00, 0x0F, 0x00, 0x00,
      0x07, 0x80, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

    memcpy((void*)0x0E00, mouse_sprite, sizeof(mouse_sprite));
    *(uint8_t*)0x07F8 = 0x0E00 / 64;
    VIC.spr0_color = COLOR_WHITE;
  }
#endif /* WITH_GUI && WITH_MOUSE */

  procinit_init();

  process_start((struct process *)&ethernet_process, (char *)ethernet_config);

  autostart_start(autostart_processes);

  log_message("Contiki up and running ...", "");
  
  while(1) {

    process_run();

    etimer_request_poll();
  }
}
예제 #5
0
/*---------------------------------------------------------------------------*/
int
main(int argc, char **argv)
{
  /*
   * Initalize hardware.
   */
  msp430_cpu_init();
  clock_init();
  leds_init();
  leds_on(LEDS_RED);

  clock_wait(100);

  uart0_init(BAUD2UBR(115200)); /* Must come before first printf */
#if WITH_UIP
  slip_arch_init(BAUD2UBR(115200));
#endif /* WITH_UIP */

  /* XXX hack: Fix it so that the 802.15.4 MAC address is compatible
     with an Ethernet MAC address - byte 0 (byte 2 in the DS ID)
     cannot be odd. */
  //Enric node_mac[2] &= 0xfe;
  node_mac[0] = 0x00;
  node_mac[1] = 0x12;
  node_mac[2] = 0x76;
  node_mac[3] = 0x01;
  node_mac[4] = 0x02;
  node_mac[5] = 0x03;
  node_mac[2] = 0x04;
  node_mac[7] = 0x05;

  
  xmem_init();

  rtimer_init();
  /*
   * Hardware initialization done!
   */

  
  /* Restore node id if such has been stored in external mem */
  node_id_restore();


  /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */
#ifdef IEEE_802154_MAC_ADDRESS
  {
    uint8_t ieee[] = IEEE_802154_MAC_ADDRESS;
    memcpy(node_mac, ieee, sizeof(uip_lladdr.addr));
    node_mac[7] = node_id & 0xff;
  }
#endif

  //Enric random_init(node_mac[0] + node_id);
  
   /*
   * Initialize Contiki and our processes.
   */
  process_init();
  process_start(&etimer_process, NULL);

  process_start(&sensors_process, NULL);

  ctimer_init();

  set_rime_addr();

  cc2420_init();
  accm_init();

  {
    uint8_t longaddr[8];
    uint16_t shortaddr;
    
    shortaddr = (rimeaddr_node_addr.u8[0] << 8) +
      rimeaddr_node_addr.u8[1];
    memset(longaddr, 0, sizeof(longaddr));
    rimeaddr_copy((rimeaddr_t *)&longaddr, &rimeaddr_node_addr);
    printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x ",
           longaddr[0], longaddr[1], longaddr[2], longaddr[3],
           longaddr[4], longaddr[5], longaddr[6], longaddr[7]);
    
    cc2420_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr);
  }
  cc2420_set_channel(RF_CHANNEL);

  leds_off(LEDS_ALL);

  PRINTF(CONTIKI_VERSION_STRING " started. ");

  if(node_id > 0) {
    PRINTF("Node id is set to %u.\n", node_id);
  } else {
    PRINTF("Node id is not set.\n");
  }

  //Enric printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
	 //Enric node_mac[0], node_mac[1], node_mac[2], node_mac[3],
	 //Enric node_mac[4], node_mac[5], node_mac[6], node_mac[7]);

#if WITH_UIP6
  PRINTF("in WITH_UIP6\n"); //Enric
  memcpy(&uip_lladdr.addr, node_mac, sizeof(uip_lladdr.addr));
  /* Setup nullmac-like MAC for 802.15.4 */
/*   sicslowpan_init(sicslowmac_init(&cc2420_driver)); */
/*   printf(" %s channel %u\n", sicslowmac_driver.name, RF_CHANNEL); */

  /* Setup X-MAC for 802.15.4 */
  queuebuf_init();

  NETSTACK_RDC.init();
  NETSTACK_MAC.init();
  NETSTACK_NETWORK.init();

  printf("%s %s, channel check rate %lu Hz, radio channel %u\n",
         NETSTACK_MAC.name, NETSTACK_RDC.name,
         CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1:
                         NETSTACK_RDC.channel_check_interval()),
         RF_CHANNEL);

  process_start(&tcpip_process, NULL);

  printf("Tentative link-local IPv6 address ");
  {
    uip_ds6_addr_t *lladdr;
    int i;
    lladdr = uip_ds6_get_link_local(-1);
    for(i = 0; i < 7; ++i) {
      printf("%02x%02x:", lladdr->ipaddr.u8[i * 2],
             lladdr->ipaddr.u8[i * 2 + 1]);
    }
    printf("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]);
  }
  
  if(!UIP_CONF_IPV6_RPL) {
    uip_ipaddr_t ipaddr;
    int i;
    uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
    uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
    uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE);
    printf("Tentative global IPv6 address ");
    for(i = 0; i < 7; ++i) {
      printf("%02x%02x:",
             ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]);
    }
    printf("%02x%02x\n",
           ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]);
  }

#else /* WITH_UIP6 */

  NETSTACK_RDC.init();
  NETSTACK_MAC.init();
  NETSTACK_NETWORK.init();

  printf("%s %s, channel check rate %lu Hz, radio channel %u\n",
         NETSTACK_MAC.name, NETSTACK_RDC.name,
         CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0? 1:
                         NETSTACK_RDC.channel_check_interval()),
         RF_CHANNEL);
#endif /* WITH_UIP6 */

#if !WITH_UIP && !WITH_UIP6
  uart0_set_input(serial_line_input_byte);
  serial_line_init();
#endif

#if PROFILE_CONF_ON
  profile_init();
#endif /* PROFILE_CONF_ON */

  leds_off(LEDS_GREEN);

#if TIMESYNCH_CONF_ENABLED
  timesynch_init();
  timesynch_set_authority_level(rimeaddr_node_addr.u8[0]);
#endif /* TIMESYNCH_CONF_ENABLED */

#if WITH_UIP
  process_start(&tcpip_process, NULL);
  process_start(&uip_fw_process, NULL);	/* Start IP output */
  process_start(&slip_process, NULL);

  slip_set_input_callback(set_gateway);

  {
    uip_ipaddr_t hostaddr, netmask;

    uip_init();

    uip_ipaddr(&hostaddr, 172,16,
	       rimeaddr_node_addr.u8[0],rimeaddr_node_addr.u8[1]);
    uip_ipaddr(&netmask, 255,255,0,0);
    uip_ipaddr_copy(&meshif.ipaddr, &hostaddr);

    uip_sethostaddr(&hostaddr);
    uip_setnetmask(&netmask);
    uip_over_mesh_set_net(&hostaddr, &netmask);
    /*    uip_fw_register(&slipif);*/
    uip_over_mesh_set_gateway_netif(&slipif);
    uip_fw_default(&meshif);
    uip_over_mesh_init(UIP_OVER_MESH_CHANNEL);
    printf("uIP started with IP address %d.%d.%d.%d\n",
	   uip_ipaddr_to_quad(&hostaddr));
  }
#endif /* WITH_UIP */

  energest_init();
  ENERGEST_ON(ENERGEST_TYPE_CPU);

  print_processes(autostart_processes);
  autostart_start(autostart_processes);

  /*
   * This is the scheduler loop.
   */
#if DCOSYNCH_CONF_ENABLED
  timer_set(&mgt_timer, DCOSYNCH_PERIOD * CLOCK_SECOND);
#endif
  watchdog_start();
  /*  watchdog_stop();*/
  while(1) {
    int r;
#if PROFILE_CONF_ON
    profile_episode_start();
#endif /* PROFILE_CONF_ON */
    do {
      /* Reset watchdog. */
      watchdog_periodic();
      r = process_run();
    } while(r > 0);
#if PROFILE_CONF_ON
    profile_episode_end();
#endif /* PROFILE_CONF_ON */

    /*
     * Idle processing.
     */
    int s = splhigh();		/* Disable interrupts. */
    /* uart0_active is for avoiding LPM3 when still sending or receiving */
    if(process_nevents() != 0 || uart0_active()) {
      splx(s);			/* Re-enable interrupts. */
    } else {
      static unsigned long irq_energest = 0;

#if DCOSYNCH_CONF_ENABLED
      /* before going down to sleep possibly do some management */
      if (timer_expired(&mgt_timer)) {
	timer_reset(&mgt_timer);
	msp430_sync_dco();
      }
#endif

      /* Re-enable interrupts and go to sleep atomically. */
      ENERGEST_OFF(ENERGEST_TYPE_CPU);
      ENERGEST_ON(ENERGEST_TYPE_LPM);
      /* We only want to measure the processing done in IRQs when we
	 are asleep, so we discard the processing time done when we
	 were awake. */
      energest_type_set(ENERGEST_TYPE_IRQ, irq_energest);
      watchdog_stop();
      _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This
					      statement will block
					      until the CPU is
					      woken up by an
					      interrupt that sets
					      the wake up flag. */

      /* We get the current processing time for interrupts that was
	 done during the LPM and store it for next time around.  */
      dint();
      irq_energest = energest_type_time(ENERGEST_TYPE_IRQ);
      eint();
      watchdog_start();
      ENERGEST_OFF(ENERGEST_TYPE_LPM);
      ENERGEST_ON(ENERGEST_TYPE_CPU);
    }
  }

  return 0;
}
예제 #6
0
/*---------------------------------------------------------------------------*/
int
main(int argc, char **argv)
{
  /*
   * Initalize hardware.
   */

  msp430_cpu_init();
  clock_init();
  leds_init();

  leds_on(LEDS_RED);

  clock_wait(2);

  uart1_init(115200); /* Must come before first printf */

#if NETSTACK_CONF_WITH_IPV4
  slip_arch_init(115200);
#endif /* NETSTACK_CONF_WITH_IPV4 */

  clock_wait(1);

  leds_on(LEDS_GREEN);
  //ds2411_init();

  /* XXX hack: Fix it so that the 802.15.4 MAC address is compatible
     with an Ethernet MAC address - byte 0 (byte 2 in the DS ID)
     cannot be odd. */
  //ds2411_id[2] &= 0xfe;

  leds_on(LEDS_BLUE);
  xmem_init();

  leds_off(LEDS_RED);
  rtimer_init();
  /*
   * Hardware initialization done!
   */

  /* Restore node id if such has been stored in external mem */
  node_id_restore();

  if(!node_id) {
    node_id = NODE_ID;
  }

  /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */
#ifdef IEEE_802154_MAC_ADDRESS
  {
    uint8_t ieee[] = IEEE_802154_MAC_ADDRESS;
    //memcpy(ds2411_id, ieee, sizeof(uip_lladdr.addr));
    //ds2411_id[7] = node_id & 0xff;
  }
#endif

  //random_init(ds2411_id[0] + node_id);

  leds_off(LEDS_BLUE);
  /*
   * Initialize Contiki and our processes.
   */
  process_init();
  process_start(&etimer_process, NULL);

  ctimer_init();

  init_platform();

  set_rime_addr();
  random_init(linkaddr_node_addr.u8[LINKADDR_SIZE-2] + linkaddr_node_addr.u8[LINKADDR_SIZE-1]);

  cc2520_init();
  {
    uint8_t longaddr[8];
    uint16_t shortaddr;

    shortaddr = (linkaddr_node_addr.u8[0] << 8) +
      linkaddr_node_addr.u8[1];
    memset(longaddr, 0, sizeof(longaddr));
    linkaddr_copy((linkaddr_t *)&longaddr, &linkaddr_node_addr);

    printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x ",
           longaddr[0], longaddr[1], longaddr[2], longaddr[3],
           longaddr[4], longaddr[5], longaddr[6], longaddr[7]);

    cc2520_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr);
  }
  cc2520_set_channel(RF_CHANNEL);

  printf(CONTIKI_VERSION_STRING " started. ");
  if(node_id > 0) {
    printf("Node id is set to %u.\n", node_id);
  } else {
    printf("Node id is not set.\n");
  }

#if NETSTACK_CONF_WITH_IPV6
  /* memcpy(&uip_lladdr.addr, ds2411_id, sizeof(uip_lladdr.addr)); */
  memcpy(&uip_lladdr.addr, linkaddr_node_addr.u8,
         UIP_LLADDR_LEN > LINKADDR_SIZE ? LINKADDR_SIZE : UIP_LLADDR_LEN);

  /* Setup nullmac-like MAC for 802.15.4 */
/*   sicslowpan_init(sicslowmac_init(&cc2520_driver)); */
/*   printf(" %s channel %u\n", sicslowmac_driver.name, RF_CHANNEL); */

  /* Setup X-MAC for 802.15.4 */
  queuebuf_init();
  NETSTACK_RDC.init();
  NETSTACK_MAC.init();
  NETSTACK_NETWORK.init();

  printf("%s %s, channel check rate %lu Hz, radio channel %u\n",
         NETSTACK_MAC.name, NETSTACK_RDC.name,
         CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1:
                         NETSTACK_RDC.channel_check_interval()),
         RF_CHANNEL);

  process_start(&tcpip_process, NULL);

  printf("Tentative link-local IPv6 address ");
  {
    uip_ds6_addr_t *lladdr;
    int i;
    lladdr = uip_ds6_get_link_local(-1);
    for(i = 0; i < 7; ++i) {
      printf("%02x%02x:", lladdr->ipaddr.u8[i * 2],
             lladdr->ipaddr.u8[i * 2 + 1]);
    }
    printf("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]);
  }

  if(!UIP_CONF_IPV6_RPL) {
    uip_ipaddr_t ipaddr;
    int i;
    uip_ip6addr(&ipaddr, UIP_DS6_DEFAULT_PREFIX, 0, 0, 0, 0, 0, 0, 0);
    uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
    uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE);
    printf("Tentative global IPv6 address ");
    for(i = 0; i < 7; ++i) {
      printf("%02x%02x:",
             ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]);
    }
    printf("%02x%02x\n",
           ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]);
  }

#else /* NETSTACK_CONF_WITH_IPV6 */

  NETSTACK_RDC.init();
  NETSTACK_MAC.init();
  NETSTACK_NETWORK.init();

  printf("%s %s, channel check rate %lu Hz, radio channel %u\n",
         NETSTACK_MAC.name, NETSTACK_RDC.name,
         CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0? 1:
                         NETSTACK_RDC.channel_check_interval()),
         RF_CHANNEL);
#endif /* NETSTACK_CONF_WITH_IPV6 */

#if !NETSTACK_CONF_WITH_IPV4 && !NETSTACK_CONF_WITH_IPV6
  uart1_set_input(serial_line_input_byte);
  serial_line_init();
#endif

  leds_off(LEDS_GREEN);

#if TIMESYNCH_CONF_ENABLED
  timesynch_init();
  timesynch_set_authority_level((linkaddr_node_addr.u8[0] << 4) + 16);
#endif /* TIMESYNCH_CONF_ENABLED */

#if NETSTACK_CONF_WITH_IPV4
  process_start(&tcpip_process, NULL);
  process_start(&uip_fw_process, NULL);	/* Start IP output */
  process_start(&slip_process, NULL);

  slip_set_input_callback(set_gateway);

  {
    uip_ipaddr_t hostaddr, netmask;

    uip_init();

    uip_ipaddr(&hostaddr, 172,16,
	       linkaddr_node_addr.u8[0],linkaddr_node_addr.u8[1]);
    uip_ipaddr(&netmask, 255,255,0,0);
    uip_ipaddr_copy(&meshif.ipaddr, &hostaddr);

    uip_sethostaddr(&hostaddr);
    uip_setnetmask(&netmask);
    uip_over_mesh_set_net(&hostaddr, &netmask);
    /*    uip_fw_register(&slipif);*/
    uip_over_mesh_set_gateway_netif(&slipif);
    uip_fw_default(&meshif);
    uip_over_mesh_init(UIP_OVER_MESH_CHANNEL);
    printf("uIP started with IP address %d.%d.%d.%d\n",
           uip_ipaddr_to_quad(&hostaddr));
  }
#endif /* NETSTACK_CONF_WITH_IPV4 */

  energest_init();
  ENERGEST_ON(ENERGEST_TYPE_CPU);

  watchdog_start();
  /* Stop the watchdog */
  watchdog_stop();

#if !PROCESS_CONF_NO_PROCESS_NAMES
  print_processes(autostart_processes);
#else /* !PROCESS_CONF_NO_PROCESS_NAMES */
  putchar('\n'); /* include putchar() */
#endif /* !PROCESS_CONF_NO_PROCESS_NAMES */
  autostart_start(autostart_processes);

  /*
   * This is the scheduler loop.
   */
  while(1) {

    int r;
    do {
      /* Reset watchdog. */
      watchdog_periodic();
      r = process_run();
    } while(r > 0);

    /*
     * Idle processing.
     */
    int s = splhigh();		/* Disable interrupts. */
    /* uart1_active is for avoiding LPM3 when still sending or receiving */
    if(process_nevents() != 0 || uart1_active()) {
      splx(s);                  /* Re-enable interrupts. */
    } else {
      static unsigned long irq_energest = 0;

      /* Re-enable interrupts and go to sleep atomically. */
      ENERGEST_SWITCH(ENERGEST_TYPE_CPU, ENERGEST_TYPE_LPM);
      /* We only want to measure the processing done in IRQs when we
	 are asleep, so we discard the processing time done when we
	 were awake. */
      energest_type_set(ENERGEST_TYPE_IRQ, irq_energest);
      watchdog_stop();
      _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This
                                              statement will block
                                              until the CPU is
                                              woken up by an
                                              interrupt that sets
                                              the wake up flag. */

      /* We get the current processing time for interrupts that was
         done during the LPM and store it for next time around.  */
      dint();
      irq_energest = energest_type_time(ENERGEST_TYPE_IRQ);
      eint();
      watchdog_start();
      ENERGEST_SWITCH(ENERGEST_TYPE_LPM, ENERGEST_TYPE_CPU);
    }
  }
}
예제 #7
0
/*---------------------------------------------------------------------------*/
int
main(int argc, char **argv)
{
  /*
   * Initalize hardware.
   */
  msp430_cpu_init();
  clock_init();
  leds_init();
  leds_toggle(LEDS_RED | LEDS_GREEN | LEDS_BLUE);
  
#if WITH_UIP
  slip_arch_init(BAUD2UBR(115200)); /* Must come before first printf */
#else /* WITH_UIP */
  uart1_init(BAUD2UBR(115200)); /* Must come before first printf */
#endif /* WITH_UIP */
  
  printf("Starting %s "
	 "($Id: contiki-sky-main.c,v 1.9 2009/11/20 10:45:07 nifi Exp $)\n", __FILE__);
  ds2411_init();
  xmem_init();
  leds_toggle(LEDS_RED | LEDS_GREEN | LEDS_BLUE);

  rtimer_init();
  /*
   * Hardware initialization done!
   */

  /* Restore node id if such has been stored in external mem */
//  node_id_burn(3);
  node_id_restore();
  printf("node_id : %hu\n", node_id);

  printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
	 ds2411_id[0], ds2411_id[1], ds2411_id[2], ds2411_id[3],
	 ds2411_id[4], ds2411_id[5], ds2411_id[6], ds2411_id[7]);

#if WITH_UIP
  uip_init();
  uip_sethostaddr(&slipif.ipaddr);
  uip_setnetmask(&slipif.netmask);
  uip_fw_default(&slipif);	/* Point2point, no default router. */
#endif /* WITH_UIP */

  /*
   * Initialize Contiki and our processes.
   */
  process_init();
  process_start(&etimer_process, NULL);
  process_start(&sensors_process, NULL);

  /*
   * Initialize light and humidity/temp sensors.
   */
  SENSORS_ACTIVATE(light_sensor);
  SENSORS_ACTIVATE(sht11_sensor);

  ctimer_init();

  set_rime_addr();

  cc2420_init();
  cc2420_set_pan_addr(panId, 0 /*XXX*/, ds2411_id);
  cc2420_set_channel(RF_CHANNEL);

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

  /*  rimeaddr_set_node_addr*/
#if WITH_UIP
  process_start(&tcpip_process, NULL);
  process_start(&uip_fw_process, NULL);	/* Start IP output */
  process_start(&slip_process, NULL);
#endif /* WITH_UIP */

  SENSORS_ACTIVATE(button_sensor);
  
  print_processes(autostart_processes);
  autostart_start(autostart_processes);

  energest_init();
  
  /*
   * This is the scheduler loop.
   */
  printf("process_run()...\n");
  ENERGEST_ON(ENERGEST_TYPE_CPU);
  while (1) {
    do {
      /* Reset watchdog. */
    } while(process_run() > 0);

    /*
     * Idle processing.
     */
    if(lpm_en) {
    int s = splhigh();		/* Disable interrupts. */
    if(process_nevents() != 0) {
      splx(s);			/* Re-enable interrupts. */
    } else {
    	
      static unsigned long irq_energest = 0;
      /* Re-enable interrupts and go to sleep atomically. */
      ENERGEST_OFF(ENERGEST_TYPE_CPU);
      ENERGEST_ON(ENERGEST_TYPE_LPM);
      /* We only want to measure the processing done in IRQs when we
	 are asleep, so we discard the processing time done when we
	 were awake. */
      energest_type_set(ENERGEST_TYPE_IRQ, irq_energest);
      _BIS_SR(GIE | SCG0 | /*SCG1 |*/ CPUOFF); /* LPM3 sleep. */
      /* We get the current processing time for interrupts that was
	 done during the LPM and store it for next time around.  */
      dint();
      irq_energest = energest_type_time(ENERGEST_TYPE_IRQ);
      eint();
      ENERGEST_OFF(ENERGEST_TYPE_LPM);
      ENERGEST_ON(ENERGEST_TYPE_CPU);
    }
    }
  }

  return 0;
}
예제 #8
0
void vuIP_Task( void *pvParameters )
{
portBASE_TYPE i;
uip_ipaddr_t xIPAddr;
struct timer periodic_timer, arp_timer;

	/* To prevent compiler warnings. */
	( void ) pvParameters;

	/* Initialise the uIP stack. */
	timer_set( &periodic_timer, configTICK_RATE_HZ / 2 );
	timer_set( &arp_timer, configTICK_RATE_HZ * 10 );
	uip_init();
	uip_ipaddr( xIPAddr, configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 );
	uip_sethostaddr( xIPAddr );

	/* Initialise the WEB server. */
	httpd_init();

	/* Initialise the Ethernet controller peripheral. */
	vFECInit();

	for( ;; )
	{
		/* Is there received data ready to be processed? */
		uip_len = usFECGetRxedData();

		if( uip_len > 0 )
		{
			/* Standard uIP loop taken from the uIP manual. */

			if( xHeader->type == htons( UIP_ETHTYPE_IP ) )
			{
				uip_arp_ipin();
				uip_input();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					uip_arp_out();
					vFECSendData();
				}
				else
				{
					/* If we are not sending data then let the FEC driver know
					the buffer is no longer required. */
					vFECRxProcessingCompleted();
				}
			}
			else if( xHeader->type == htons( UIP_ETHTYPE_ARP ) )
			{
				uip_arp_arpin();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					vFECSendData();
				}
				else
				{
					/* If we are not sending data then let the FEC driver know
					the buffer is no longer required. */
					vFECRxProcessingCompleted();
				}
			}
			else
			{
				/* If we are not sending data then let the FEC driver know
				the buffer is no longer required. */
				vFECRxProcessingCompleted();
			}
		}
		else
		{
			if( timer_expired( &periodic_timer ) )
			{
				timer_reset( &periodic_timer );
				for( i = 0; i < UIP_CONNS; i++ )
				{
					uip_periodic( i );

					/* If the above function invocation resulted in data that
					should be sent out on the network, the global variable
					uip_len is set to a value > 0. */
					if( uip_len > 0 )
					{
						uip_arp_out();
						vFECSendData();
					}
				}

				/* Call the ARP timer function every 10 seconds. */
				if( timer_expired( &arp_timer ) )
				{
					timer_reset( &arp_timer );
					uip_arp_timer();
				}
			}
			else
			{
				/* We did not receive a packet, and there was no periodic
				processing to perform.  Block for a fixed period.  If a packet
				is received during this period we will be woken by the ISR
				giving us the Semaphore. */
				xSemaphoreTake( xFECSemaphore, configTICK_RATE_HZ / 2 );
			}
		}
	}
}
예제 #9
0
파일: net_conf.c 프로젝트: atalax/avr-uip-2
int net_conf_init(void)
{
	uip_ipaddr_t ipaddr;

	if (!init_load_done)
		net_conf_load();
	init_load_done = 1;

	//net_conf_enable_dhcp=0;

	if ((net_conf_enable_dhcp != 1) &&
	    (net_conf_enable_dhcp != 0)) {
		// if the setting is invalid, enable by default
#if UIP_CONF_BROADCAST == 1
		net_conf_enable_dhcp = 1;
#else
		net_conf_enable_dhcp = 0;
#endif
		// update the eeprom with the correct data
		net_conf_save();
	}

	// if the mac address in eeprom looks bad, use the defaults
	if ((net_conf_eth_addr[0] == 0xff) ||
	    (
	        (net_conf_eth_addr[0] == 0x00) &&
	        (net_conf_eth_addr[1] == 0x00) &&
	        (net_conf_eth_addr[2] == 0x00) &&
	        (net_conf_eth_addr[3] == 0x00) &&
	        (net_conf_eth_addr[4] == 0x00) &&
	        (net_conf_eth_addr[5] == 0x00))) {
		net_conf_eth_addr[0] = UIP_ETHADDR0;
		net_conf_eth_addr[1] = UIP_ETHADDR1;
		net_conf_eth_addr[2] = UIP_ETHADDR2;
		net_conf_eth_addr[3] = UIP_ETHADDR3;
		net_conf_eth_addr[4] = UIP_ETHADDR4;
		net_conf_eth_addr[5] = UIP_ETHADDR5;
		net_conf_mac_save();
	}

	my_eth_addr.addr[0] = net_conf_eth_addr[0];
	my_eth_addr.addr[1] = net_conf_eth_addr[1];
	my_eth_addr.addr[2] = net_conf_eth_addr[2];
	my_eth_addr.addr[3] = net_conf_eth_addr[3];
	my_eth_addr.addr[4] = net_conf_eth_addr[4];
	my_eth_addr.addr[5] = net_conf_eth_addr[5];

	uip_setethaddr(my_eth_addr);

	if (!net_conf_enable_dhcp) {
		// if the IP looks good in flash, use it
		if ((net_conf_ip_addr[0] != 255) &&
		    (net_conf_ip_addr[0] != 0))
			net_conf_uip_set();
		else {
			// ip in flash didn't look good... use default
			uip_ipaddr(ipaddr, UIP_IPADDR0, UIP_IPADDR1,
			           UIP_IPADDR2, UIP_IPADDR3);
			uip_sethostaddr(ipaddr);

			net_conf_ip_addr[0] = UIP_IPADDR0;
			net_conf_ip_addr[1] = UIP_IPADDR1;
			net_conf_ip_addr[2] = UIP_IPADDR2;
			net_conf_ip_addr[3] = UIP_IPADDR3;

			uip_ipaddr(ipaddr, UIP_DRIPADDR0, UIP_DRIPADDR1,
			           UIP_DRIPADDR2, UIP_DRIPADDR3);
			uip_setdraddr(ipaddr);

			net_conf_gateway[0] = UIP_DRIPADDR0;
			net_conf_gateway[1] = UIP_DRIPADDR1;
			net_conf_gateway[2] = UIP_DRIPADDR2;
			net_conf_gateway[3] = UIP_DRIPADDR3;

			uip_ipaddr(ipaddr, UIP_NETMASK0, UIP_NETMASK1,
			           UIP_NETMASK2, UIP_NETMASK3);
			uip_setnetmask(ipaddr);

			net_conf_net_mask[0] = UIP_NETMASK0;
			net_conf_net_mask[1] = UIP_NETMASK1;
			net_conf_net_mask[2] = UIP_NETMASK2;
			net_conf_net_mask[3] = UIP_NETMASK3;

			// update the eeprom with the correct data
			net_conf_save();
		}
	}

	return 0;
}
예제 #10
0
파일: dhcpd.c 프로젝트: EFraim/trans-vpn
static void dhcpdHandlePacket(void) {
  struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;

  if (!ipaddr_set) {
    uip_ipaddr( ipaddr,                 10, 200, 0, 1);
    uip_ipaddr( dhcpd_client_ipaddr,    10, 200, 0, 2);
    uip_ipaddr( dhcpd_broadcast_ipaddr, 10, 200, 0, 3);
    uip_sethostaddr(ipaddr);
    ipaddr_set = 1;
  }

  printf("This is a DHCP broadcast op=%d ",m->op);
  if (m->op == DHCP_REQUEST) {
    //printf("xid = %02x %02x %02x %02x ",(m->xid)[0],(m->xid)[1],(m->xid)[2],(m->xid)[3]);
    //printf("secs = %02x ",m->secs);
    //printf("flags (bc?) = %02x ",m->flags);
    if (memcmp(m->options,magic_cookie,4)==0)
      printf("found magic cookie ");
    else {
      printf("magic cookie missing! ");
      return;
    }
    int type = parse_options(&m->options[4], uip_datalen());
    //printf("DHCP message type %d ",type);
    if (type == DHCPDISCOVER) {
      printf("<<discover>> ");
      memcpy((uint8_t*) &dhcp_header,m,sizeof(dhcp_header));
      dhcpd_state = DHCPD_SEND_OFFER;
      udp_poll_request = 1;
      return;


      m->op = DHCP_REPLY;
      uip_ipaddr_t ipaddr;
      //uip_ipaddr( m->yiaddr, 192, 168, 12, 2);
      uip_ipaddr_copy(m->yiaddr,dhcpd_client_ipaddr);
      memset(m->ciaddr,0,4);
      //memset(m->siaddr,0,4);
      uip_ipaddr_copy(m->siaddr,uip_hostaddr);

      u8_t *end;
      end = add_msg_type(&m->options[4], DHCPOFFER);
      //end = add_subnetmask(end, 255,255,255,0);
      end = add_subnetmask(end, 255,255,255, 0xfc); // a /30 address
      end = add_lease_time(end);
      end = add_server_id_myself(end);
      //end = add_dns_server_myself(end);
      //end = add_domain_name(end);
      end = add_end(end);

      uip_send(uip_appdata, end - (u8_t *)uip_appdata);
    }
    if (type == DHCPREQUEST) {
      printf("<<request>> ");
      memcpy((uint8_t*) &dhcp_header,m,sizeof(dhcp_header));
      dhcpd_state = DHCPD_SEND_ACK;
      udp_poll_request = 1;
      return;

      m->op = DHCP_REPLY;
      uip_ipaddr_t ipaddr;
      //uip_ipaddr( m->yiaddr,  192, 168, 12, 2);
      uip_ipaddr_copy(m->yiaddr,dhcpd_client_ipaddr);
      memset(m->ciaddr,0,4);
      //memset(m->siaddr,0,4);
      uip_ipaddr_copy(m->siaddr,uip_hostaddr);


      u8_t *end;
      end = add_msg_type(&m->options[4], DHCPACK);
      //end = add_subnetmask(end, 255,255,255,0);
      //end = add_subnetmask(end, 255,255,255, 0xfC); // a /30 address
      //end = add_subnetmask(end, 255,255,255, 0xfe); // a /31 address
      end = add_subnetmask(end, 255,255,255, 0xfc); // a /30 address
      end = add_lease_time(end);
      end = add_server_id_myself(end);
      //end = add_dns_server_myself(end);
      //end = add_domain_name(end);
      end = add_end(end);

      uip_send(uip_appdata, end - (u8_t *)uip_appdata);
      dhcpd_address_assigned(); // notify the rest of teh system
    }
  }
}
예제 #11
0
void vuIP_TASK( void *pvParameters )
{
      int i;
      struct uip_eth_addr MacAddr = *(struct uip_eth_addr *)pvParameters;
      uip_ipaddr_t ipaddr;
      struct timer periodic_timer, arp_timer;
      
      clock_init();  
      timer_set(&periodic_timer, CLOCK_SECOND / 2);
      timer_set(&arp_timer, CLOCK_SECOND * 10);

      /* Initialise the Enc28j60*/
      enc28j60Init(MacAddr.addr);
      
      /* Initialize the uIP TCP/IP stack. */
      uip_init();
      uip_arp_init();
      
      /*init mac addr to uip*/
      uip_setethaddr(MacAddr);
      
      uip_ipaddr(ipaddr, 192,168,1,101);
      uip_sethostaddr(ipaddr);
      uip_ipaddr(ipaddr, 192,168,1,1);
      uip_setdraddr(ipaddr);
      uip_ipaddr(ipaddr, 255,255,255,0);
      uip_setnetmask(ipaddr);
      
      /* Initialize the HTTP server. */
      telnetd_init();

      while(1) {
        uip_len = enc28j60PacketReceive();
        if(uip_len > 0) 
        {
          if(pucUIP_Buffer->type == htons(UIP_ETHTYPE_IP)) 
          {
            uip_arp_ipin();
            uip_input();
            /* If the above function invocation resulted in data that
            should be sent out on the network, the global variable
            uip_len is set to a value > 0. */
            if(uip_len > 0) {
              uip_arp_out();
              enc28j60PacketSend();
            }
          }
          else if(pucUIP_Buffer->type == htons(UIP_ETHTYPE_ARP)) 
          {
            uip_arp_arpin();
            /* If the above function invocation resulted in data that
            should be sent out on the network, the global variable
            uip_len is set to a value > 0. */
            if(uip_len > 0) {
              enc28j60PacketSend();
            }
          }
          
        }
        else if(timer_expired(&periodic_timer)) 
        {
          timer_reset(&periodic_timer);
          for(i = 0; i < UIP_CONNS; i++) 
          {
            uip_periodic(i);
            /* If the above function invocation resulted in data that
            should be sent out on the network, the global variable
            uip_len is set to a value > 0. */
            if(uip_len > 0) 
            {
              uip_arp_out();
              enc28j60PacketSend();
            }
          }
          
#if UIP_UDP
          for(i = 0; i < UIP_UDP_CONNS; i++) 
          {
            uip_udp_periodic(i);
            /* If the above function invocation resulted in data that
            should be sent out on the network, the global variable
            uip_len is set to a value > 0. */
            if(uip_len > 0) 
            {
              uip_arp_out();
              enc28j60PacketSend();
            }
          }
#endif /* UIP_UDP */
          
          /* Call the ARP timer function every 10 seconds. */
          if(timer_expired(&arp_timer)) 
          {
            timer_reset(&arp_timer);
            uip_arp_timer();
          }
        }
      }
}
예제 #12
0
static int tcpecho_netsetup()
{
  /* If this task is excecutated as an NSH built-in function, then the
   * network has already been configured by NSH's start-up logic.
   */

#ifndef CONFIG_NSH_BUILTIN_APPS
  struct in_addr addr;
#if defined(CONFIG_EXAMPLES_TCPECHO_DHCPC) || defined(CONFIG_EXAMPLES_TCPECHO_NOMAC)
  uint8_t mac[IFHWADDRLEN];
#endif
#ifdef CONFIG_EXAMPLES_TCPECHO_DHCPC
  struct dhcpc_state ds;
  void *handle;
#endif

/* Many embedded network interfaces must have a software assigned MAC */

#ifdef CONFIG_EXAMPLES_TCPECHO_NOMAC
  mac[0] = 0x00;
  mac[1] = 0xe0;
  mac[2] = 0xde;
  mac[3] = 0xad;
  mac[4] = 0xbe;
  mac[5] = 0xef;
  uip_setmacaddr("eth0", mac);
#endif

  /* Set up our host address */

#ifdef CONFIG_EXAMPLES_TCPECHO_DHCPC
  addr.s_addr = 0;
#else
  addr.s_addr = HTONL(CONFIG_EXAMPLES_TCPECHO_IPADDR);
#endif
  uip_sethostaddr("eth0", &addr);

  /* Set up the default router address */

  addr.s_addr = HTONL(CONFIG_EXAMPLES_TCPECHO_DRIPADDR);
  uip_setdraddr("eth0", &addr);

  /* Setup the subnet mask */

  addr.s_addr = HTONL(CONFIG_EXAMPLES_TCPECHO_NETMASK);
  uip_setnetmask("eth0", &addr);

#ifdef CONFIG_EXAMPLES_TCPECHO_DHCPC
  /* Set up the resolver */

  resolv_init();

  /* Get the MAC address of the NIC */

  uip_getmacaddr("eth0", mac);

  /* Set up the DHCPC modules */

  handle = dhcpc_open(&mac, IFHWADDRLEN);

  /* Get an IP address.  Note:  there is no logic here for renewing the address in this
   * example.  The address should be renewed in ds.lease_time/2 seconds.
   */

  if (!handle)
    {
      return ERROR;
    }

  if (dhcpc_request(handle, &ds) != OK)
    {
      return ERROR;
    }

  uip_sethostaddr("eth1", &ds.ipaddr);

  if (ds.netmask.s_addr != 0)
    {
      uip_setnetmask("eth0", &ds.netmask);
    }

  if (ds.default_router.s_addr != 0)
    {
      uip_setdraddr("eth0", &ds.default_router);
    }

  if (ds.dnsaddr.s_addr != 0)
    {
      resolv_conf(&ds.dnsaddr);
    }

  dhcpc_close(handle);
  printf("IP: %s\n", inet_ntoa(ds.ipaddr));

#endif /* CONFIG_EXAMPLES_TCPECHO_DHCPC */
#endif /* CONFIG_NSH_BUILTIN_APPS */

  return OK;
}
예제 #13
0
/*************************************************************************
 * Function Name: main
 * Parameters: none
 *
 * Return: none
 *
 * Description: main
 *
 *************************************************************************/
int main(void)
{
typedef Int32U ram_unit;
// int cursor_x = (C_GLCD_H_SIZE - CURSOR_H_SIZE)/2, cursor_y = (C_GLCD_V_SIZE - CURSOR_V_SIZE)/2;
// unsigned long int deltaT;
static float freq_aveg;
int LCD_updatecount;
LCD_updatecount = 0;


//From uip start
unsigned int i;
uip_ipaddr_t ipaddr;
struct timer periodic_timer, arp_timer;
//From uip end
  /*** COMPARE FIX POINT 523235 ***/
  /*** COMPARE FIX POINT 523235 ***/
  GLCD_Ctrl (FALSE);
  // Init GPIO
  GpioInit();
#ifndef SDRAM_DEBUG
  // MAM init
  MAMCR_bit.MODECTRL = 0;
  MAMTIM_bit.CYCLES  = 3;   // FCLK > 40 MHz
  MAMCR_bit.MODECTRL = 2;   // MAM functions fully enabled
  // Init clock
  InitClock();
  // SDRAM Init
  SDRAM_Init();
#endif // SDRAM_DEBUG
  // Init VIC
  VIC_Init();
  // GLCD init
  // GLCD_Init (IarLogoPic.pPicStream, NULL); // Can be removed, remember to remove the h and c file as well
  // GLCD_Init (LogoPic.pPicStream, NULL);  // Can be removed, remember to remove the h and c file as well
  GLCD_Init (what_is_a_blissPic.pPicStream, NULL);
  GLCD_Cursor_Dis(0); //From uip
  // GLCD_Cursor_Dis(0);

  // GLCD_Copy_Cursor ((Int32U *)Cursor, 0, sizeof(Cursor)/sizeof(Int32U));
  /*** COMPARE FIX POINT 534252 ***/
  /*** COMPARE FIX POINT 534252 ***/
  GLCD_Cursor_Cfg(CRSR_FRAME_SYNC | CRSR_PIX_32); //From uip
  // GLCD_Cursor_Cfg(CRSR_FRAME_SYNC | CRSR_PIX_64);
  // GLCD_Move_Cursor(cursor_x, cursor_y);
  // GLCD_Cursor_En(0);

  //From uip start
  // Sys timer init 1/100 sec tick
  clock_init(2);

  timer_set(&periodic_timer, CLOCK_SECOND / 2);
  timer_set(&arp_timer, CLOCK_SECOND * 10);
  //From uip end


  // Init USB Link  LED
  USB_D_LINK_LED_SEL = 0; // GPIO
  USB_D_LINK_LED_FSET = USB_D_LINK_LED_MASK;
  USB_D_LINK_LED_FDIR |= USB_D_LINK_LED_MASK;
  
  USB_H_LINK_LED_SEL = 0; // GPIO
  USB_H_LINK_LED_FSET = USB_H_LINK_LED_MASK;
  USB_H_LINK_LED_FDIR |= USB_H_LINK_LED_MASK;

  
  /*-----------------------------------------------------------------*/
  
  // Init AD0[3] for current meassurement
  PINSEL1_bit.P0_26 = 1; // Assign P26 to AD0[3], page 180
  PINMODE1_bit.P0_26 = 2; // //Neither pull-up or pull-down
  // PCONP_bit.PCAD = 1;     // Note: Clear the PDN bit in the AD0CR before clearing this bit and set this before PDN
  // Other initial parameters are already set
  // AD0CR_bit.SEL  = 8;     // select Ch3 [1111]
  current_amp = 0;
  
  
  /*-----------------------------------------------------------------*/
  // Init the DAC converter
  //Clock: In the PCLK_SEL0 register (Table 4�), select PCLK_DAC
    //PCLKSEL0_bit.PCLK_DAC = 3UL;// **HAS Desided for values yet!** // '11' at bit 23 and 22  (which is CCLK/8)  //or use 0x3 for 3UL instead  
  //Pins: Select the DAC pin and pin mode in registers PINSEL1 and PINMODE1 (see Section 9�.
  //PINSEL1 |= (2UL<<20); //  PINSEL1_bit.P0_26 = 1; //??        
    //PINSEL1_bit.P0_26 = 2UL; 
  //"PINMODE registers control the on-chip pull-up/pull-down resistor feature for all GPIO ports." - page 178
  //PINMODE1 |= ________; // See table 128 for values. Write to bit 21:20
    //PINMODE1_bit.P0_26 = 2UL;  //P0.26MODE = 2UL; //Neither pull-up or pull-down


 /* ------------------------------------------------------------------*/
  // Init ADC converter
  // Power the ADC converter
  PINSEL1_bit.P0_25 = 1; // Assign Pin 25 to ADO[2]
  PINMODE1_bit.P0_25 = 1; // Neither pull-up or pull-dow
  PCONP_bit.PCAD = 1;     // Note: Clear the PDN bit in the AD0CR before clearing this bit and set this before PDN
  AD0CR_bit.PDN = 1;      // A/D converter is operational
  AD0CR_bit.START = 0;    // Conversion not started
  AD0CR_bit.BURST  = 0;   // disable burst
  // AD0CR_bit.SEL  = 4;     // select Ch2 [11]
  
  // Select number of clocks for each conversion
  AD0CR_bit.CLKS = 0; // [000] 11 clocks / 10 bits
  AD0CR_bit.CLKDIV = SYS_GetFpclk(ADC_PCLK_OFFSET)/ 10000; // 4500000;  // Should be equal to 10K samplingrate
  ADINTEN_bit.ADGINTEN = 1; // Global A/D channels enabled by ADINTEN 7:0
  // Since only on channel is used at the moment the global flag is enabled
  
  VIC_SetVectoredIRQ(AD0IntrHandler,1,VIC_AD0); // Set the interrupt call
  VICINTENABLE |= 1UL << VIC_AD0;
  


  // Setting parameters for the low-pass filter
  DACR_previous = 0; // Initialize DACR_temp which is y(i-1)
  deltaT = 1.0/TIMER0_TICK_PER_SEC; // Set the sample rate
  // Calculate the R*C for cut-off frequency of the low pass filter
  alpha = deltaT/(1./(2.*3.1416*100.) + deltaT); // Cut-off = 100 Hz
  done = 0; // Channel stage
/* ------------------------------------------------------------------*/
  
  // Setting the port to P0[11] and P0[19]
  PINSEL1_bit.P0_19 = 0; // GPIO to P0[19]
  PINSEL0_bit.P0_11 = 0; // GPIO to P0[11]
  PINMODE1_bit.P0_19 = 2; // Pin has neither pull up or down
  PINMODE0_bit.P0_11 = 2; // Pin has neither pull up or down
  FIO0DIR_bit.P0_19  = 1; 
  FIO0CLR  = (1UL<<19);
  FIO0DIR_bit.P0_11 = 1;
  FIO0CLR  = (1UL<<11);
  
  FIO0PIN_bit.P0_19 = 1;
  FIO0PIN_bit.P0_11 = 1;
/* ------------------------------------------------------------------*/  
  // Enable TIM0 clocks
  PCONP_bit.PCTIM0 = 1; // enable clock

  // Init Time0
  T0TCR_bit.CE = 0;     // counting  disable
  T0TCR_bit.CR = 1;     // set reset
  T0TCR_bit.CR = 0;     // release reset
  T0CTCR_bit.CTM = 0;   // Timer Mode: every rising PCLK edge
  T0MCR_bit.MR0I = 1;   // Enable Interrupt on MR0
  T0MCR_bit.MR0R = 1;   // Enable reset on MR0
  T0MCR_bit.MR0S = 0;   // Disable stop on MR0
  // set timer 0 period
  T0PR = 0;
  T0MR0 = SYS_GetFpclk(TIMER0_PCLK_OFFSET)/(TIMER0_TICK_PER_SEC);
  // init timer 0 interrupt
  T0IR_bit.MR0INT = 1;  // clear pending interrupt
  VIC_SetVectoredIRQ(Timer0IntrHandler,0,VIC_TIMER0);
  VICINTENABLE |= 1UL << VIC_TIMER0;
  T0TCR_bit.CE = 1;     // counting Enable
  __enable_interrupt();
  GLCD_Ctrl (TRUE);

#if 0
  SDRAM_Test();
#endif

  /*
  //
  SMB380_Init();

  SMB380_GetID(&Smb380Id, &Smb380Ver);

  SMB380_Data_t XYZT;
  */

  /*** COMPARE FIX POINT 856364 ***/
  /*** COMPARE FIX POINT 856364 ***/
  /*** COMPARE FIX POINT 856364 ***/
  /*** COMPARE FIX POINT 856364 ***/

  //From uip start
  GLCD_SetFont(&Terminal_18_24_12,0x000000,0x000cd4ff);
  GLCD_SetWindow(85,10,255,33);
  GLCD_TextSetPos(0,0);
  GLCD_print("\f Room Station");
  
  
  //From uip start

  /*** COMPARE FIX POINT 458923 ***/
  /*** COMPARE FIX POINT 458923 ***/

  // GLCD_SetWindow(5,200,319,239);
  // GLCD_SetFont(&Terminal_6_8_6,0x0000FF,0x000cd4ff);

  // Initialize the ethernet device driver
  do
  {
    GLCD_TextSetPos(0,0);
  }
  while(!tapdev_init());
  GLCD_TextSetPos(0,0);

  // uIP web server
  // Initialize the uIP TCP/IP stack.
  uip_init();

  uip_ipaddr(ipaddr, 192,168,0,100);
  uip_sethostaddr(ipaddr);
  uip_ipaddr(ipaddr, 192,168,0,1);
  uip_setdraddr(ipaddr);
  uip_ipaddr(ipaddr, 255,255,255,0);
  uip_setnetmask(ipaddr);

  // Initialize the HTTP server.
  httpd_init();

  /*** COMPARE FIX POINT 4572742 ***/
  /*** COMPARE FIX POINT 4572742 ***/
  /*** COMPARE FIX POINT 4572742 ***/
  /*** COMPARE FIX POINT 4572742 ***/


/*** WHILE LOOP START ***/
  while(1)
  {

  /*** COMPARE FIX POINT 938194 ***/
  /*** COMPARE FIX POINT 938194 ***/
  /*** COMPARE FIX POINT 938194 ***/
  /*** COMPARE FIX POINT 938194 ***/
  /*** COMPARE FIX POINT 938194 ***/

    uip_len = tapdev_read(uip_buf);
    if(uip_len > 0)
    {
      if(BUF->type == htons(UIP_ETHTYPE_IP))
      {
	      uip_arp_ipin();
	      uip_input();
	      /* If the above function invocation resulted in data that
	         should be sent out on the network, the global variable
	         uip_len is set to a value > 0. */
	      if(uip_len > 0)
        {
	        uip_arp_out();
	        tapdev_send(uip_buf,uip_len);
	      }
      }
      else if(BUF->type == htons(UIP_ETHTYPE_ARP))
      {
        uip_arp_arpin();
	      /* If the above function invocation resulted in data that
	         should be sent out on the network, the global variable
	         uip_len is set to a value > 0. */
	      if(uip_len > 0)
        {
	        tapdev_send(uip_buf,uip_len);
	      }
      }
    }
    else if(timer_expired(&periodic_timer))
    {
      timer_reset(&periodic_timer);
      for(i = 0; i < UIP_CONNS; i++)
      {
      	uip_periodic(i);
        /* If the above function invocation resulted in data that
           should be sent out on the network, the global variable
           uip_len is set to a value > 0. */
        if(uip_len > 0)
        {
          uip_arp_out();
          tapdev_send(uip_buf,uip_len);
        }
      }
#if UIP_UDP
      for(i = 0; i < UIP_UDP_CONNS; i++) {
        uip_udp_periodic(i);
        /* If the above function invocation resulted in data that
           should be sent out on the network, the global variable
           uip_len is set to a value > 0. */
        if(uip_len > 0) {
          uip_arp_out();
          tapdev_send();
        }
      }
#endif /* UIP_UDP */
      /* Call the ARP timer function every 10 seconds. */
      if(timer_expired(&arp_timer))
      {
        timer_reset(&arp_timer);
        uip_arp_timer();
      }
    }

    #define AVERAGECOUNT 100000
    if(LCD_updatecount <= AVERAGECOUNT) {
      ++LCD_updatecount;
      freq_aveg += freq;
    }
    else { 
      freq_aveg = freq_aveg/AVERAGECOUNT;

      updateFreqHistory(freq_aveg); //Must be kept together with freq calculation!

      GLCD_SetWindow(20,55,150,80);
      GLCD_SetFont(&Terminal_18_24_12,0x000000,0x009fee00);
      GLCD_TextSetPos(0,5);
      GLCD_print("\f Hz %3.3f", freq_aveg);
      freq_aveg = 0;
      
      GLCD_SetWindow(20,90,150,115);
      GLCD_SetFont(&Terminal_18_24_12,0x000000,0x009fee00);
      GLCD_TextSetPos(0,5);
      GLCD_print("\f  V  %3.3f", sqrtf(vol_rms_result));

      updateVoltageHistory(sqrtf(vol_rms_result));
      
      GLCD_SetWindow(20,125,150,150);
      GLCD_SetFont(&Terminal_18_24_12,0x000000,0x009fee00);
      GLCD_TextSetPos(0,5);
      GLCD_print("\f uA  %3.3f", sqrtf(current_amp));
      
      GLCD_SetWindow(20,160,150,185);
      GLCD_SetFont(&Terminal_18_24_12,0x000000,0x009fee00);
      GLCD_TextSetPos(0,5);
      GLCD_print("\f uP  %3.3f", sqrtf(vol_rms_result)*sqrtf(current_amp));
      LCD_updatecount = 0;
    }
    
    
  }//while(1) loop

}//main function
예제 #14
0
파일: dhcp.c 프로젝트: EtherGraf/ethersex
void dhcp_net_main(void) {


  if(uip_newdata()) {

    switch (uip_udp_conn->appstate.dhcp.state) {
      
    case STATE_DISCOVERING:

      if (parse_msg() == DHCPOFFER) {
	send_request();
	uip_flags &= ~UIP_NEWDATA;
	uip_udp_conn->appstate.dhcp.state = STATE_REQUESTING;
	uip_udp_conn->appstate.dhcp.retry_timer   = 2; // retry
	uip_udp_conn->appstate.dhcp.retry_counter = 1;
	tick_sec = 0;
      }

      break;

    case STATE_REQUESTING:

      if (parse_msg() == DHCPACK) {
	uip_udp_conn->appstate.dhcp.state = STATE_CONFIGURED;

	uip_sethostaddr(uip_udp_conn->appstate.dhcp.ipaddr);
	uip_setdraddr(uip_udp_conn->appstate.dhcp.default_router);
	uip_setnetmask(uip_udp_conn->appstate.dhcp.netmask);

#ifdef DNS_SUPPORT
	resolv_conf(uip_udp_conn->appstate.dhcp.dnsaddr);
	//	eeprom_save(dns_server, &uip_udp_conn->appstate.dhcp.dnsaddr, IPADDR_LEN);
#endif

	// eeprom_save(ip, &uip_udp_conn->appstate.dhcp.ipaddr, IPADDR_LEN);
	// eeprom_save(netmask, &uip_udp_conn->appstate.dhcp.netmask, IPADDR_LEN);
	// eeprom_save(gateway, &uip_udp_conn->appstate.dhcp.default_router, IPADDR_LEN);

	// eeprom_update_chksum();

	/* Remove the bootp connection */
	uip_udp_remove(uip_udp_conn);

      }

      break;

    }
    
  } else {

    // No data yet
    
    switch (uip_udp_conn->appstate.dhcp.state) {
      
    case STATE_INITIAL:
    case STATE_DISCOVERING:
      
      if (tick_sec>uip_udp_conn->appstate.dhcp.retry_timer) {
	send_discover();
	uip_flags &= ~UIP_NEWDATA;
	uip_udp_conn->appstate.dhcp.state = STATE_DISCOVERING;
	if (uip_udp_conn->appstate.dhcp.retry_counter++>10)
	  return dhcp_set_static();
	uip_udp_conn->appstate.dhcp.retry_timer = 2 * uip_udp_conn->appstate.dhcp.retry_counter; // retry
	tick_sec = 0;
      }
      break;
      

    case STATE_REQUESTING:
      if (tick_sec>uip_udp_conn->appstate.dhcp.retry_timer) {
	send_request();
	uip_flags &= ~UIP_NEWDATA;
	if (uip_udp_conn->appstate.dhcp.retry_counter++>10)
	  return dhcp_set_static();
	uip_udp_conn->appstate.dhcp.retry_timer = 2; // retry
	tick_sec = 0;
      }
      break;
      
    }
    
  }


}
예제 #15
0
파일: thttpd_main.c 프로젝트: airlink/nuttx
int thttp_main(int argc, char *argv[])
{
  struct in_addr addr;
#ifdef CONFIG_EXAMPLE_THTTPD_NOMAC
  uint8_t mac[IFHWADDRLEN];
#endif
  char *thttpd_argv = "thttpd";
  int ret;

  /* Configure SLIP */

#ifdef CONFIG_NET_SLIP
  ret = slip_initialize(SLIP_DEVNO, CONFIG_NET_SLIPTTY);
  if (ret < 0)
    {
      message("ERROR: SLIP initialization failed: %d\n", ret);
      exit(1);
    }
#endif

/* Many embedded network interfaces must have a software assigned MAC */

#ifdef CONFIG_EXAMPLE_THTTPD_NOMAC
  message("Assigning MAC\n");

  mac[0] = 0x00;
  mac[1] = 0xe0;
  mac[2] = 0xde;
  mac[3] = 0xad;
  mac[4] = 0xbe;
  mac[5] = 0xef;
  uip_setmacaddr(NET_DEVNAME, mac);
#endif

  /* Set up our host address */

  message("Setup network addresses\n");
  addr.s_addr = HTONL(CONFIG_THTTPD_IPADDR);
  uip_sethostaddr(NET_DEVNAME, &addr);

  /* Set up the default router address */

  addr.s_addr = HTONL(CONFIG_EXAMPLE_THTTPD_DRIPADDR);
  uip_setdraddr(NET_DEVNAME, &addr);

  /* Setup the subnet mask */

  addr.s_addr = HTONL(CONFIG_EXAMPLE_THTTPD_NETMASK);
  uip_setnetmask(NET_DEVNAME, &addr);

  /* Initialize the NXFLAT binary loader */

  message("Initializing the NXFLAT binary loader\n");
  ret = nxflat_initialize();
  if (ret < 0)
    {
      message("ERROR: Initialization of the NXFLAT loader failed: %d\n", ret);
      exit(2);
    }

  /* Create a ROM disk for the ROMFS filesystem */

  message("Registering romdisk\n");
  ret = romdisk_register(0, (uint8_t*)romfs_img, NSECTORS(romfs_img_len), SECTORSIZE);
  if (ret < 0)
    {
      message("ERROR: romdisk_register failed: %d\n", ret);
      nxflat_uninitialize();
      exit(1);
    }

  /* Mount the file system */

  message("Mounting ROMFS filesystem at target=%s with source=%s\n",
         MOUNTPT, ROMFSDEV);

  ret = mount(ROMFSDEV, MOUNTPT, "romfs", MS_RDONLY, NULL);
  if (ret < 0)
    {
      message("ERROR: mount(%s,%s,romfs) failed: %s\n",
              ROMFSDEV, MOUNTPT, errno);
      nxflat_uninitialize();
    }

  /* Start THTTPD.  At present, symbol table info is passed via global variables */

  g_thttpdsymtab   = exports;
  g_thttpdnsymbols = NEXPORTS;

  message("Starting THTTPD\n");
  msgflush();
  thttpd_main(1, &thttpd_argv);
  message("THTTPD terminated\n");
  msgflush();
  return 0;
}
예제 #16
0
파일: main.c 프로젝트: ichpuchtli/freeburn
/*---------------------------------------------------------------------------*/
int
main(void)
{
  int i;
  uip_ipaddr_t ipaddr;
  struct timer periodic_timer, arp_timer;

  timer_set(&periodic_timer, CLOCK_SECOND / 2);
  timer_set(&arp_timer, CLOCK_SECOND * 10);
  
#ifdef __CYGWIN__
  wpcap_init();
#else
  tapdev_init();
#endif
  uip_init();

  uip_ipaddr(ipaddr, 192,168,0,2);
  uip_sethostaddr(ipaddr);
  uip_ipaddr(ipaddr, 192,168,0,1);
  uip_setdraddr(ipaddr);
  uip_ipaddr(ipaddr, 255,255,255,0);
  uip_setnetmask(ipaddr);

  httpd_init();
  
  /*  telnetd_init();*/
  
  /*  hello_world_init();*/

  /*  {
      u8_t mac[6] = {1,2,3,4,5,6};
      dhcpc_init(&mac, 6);
      }*/
  
  /*uip_ipaddr(ipaddr, 127,0,0,1);
  smtp_configure("localhost", ipaddr);
  SMTP_SEND("*****@*****.**", NULL, "*****@*****.**",
	    "Testing SMTP from uIP",
	    "Test message sent by uIP\r\n");*/

  /*
    webclient_init();
    resolv_init();
    uip_ipaddr(ipaddr, 195,54,122,204);
    resolv_conf(ipaddr);
    resolv_query("www.sics.se");*/


  
  while(1) {
#ifdef __CYGWIN__
    uip_len = wpcap_read();
#else
    uip_len = tapdev_read();
#endif
    if(uip_len > 0) {
      if(BUF->type == htons(UIP_ETHTYPE_IP)) {
	uip_arp_ipin();
	uip_input();
	/* If the above function invocation resulted in data that
	   should be sent out on the network, the global variable
	   uip_len is set to a value > 0. */
	if(uip_len > 0) {
	  uip_arp_out();
#ifdef __CYGWIN__
	  wpcap_send();
#else
	  tapdev_send();
#endif
	}
      } else if(BUF->type == htons(UIP_ETHTYPE_ARP)) {
	uip_arp_arpin();
	/* If the above function invocation resulted in data that
	   should be sent out on the network, the global variable
	   uip_len is set to a value > 0. */
	if(uip_len > 0) {
#ifdef __CYGWIN__
	  wpcap_send();
#else
	  tapdev_send();
#endif
	}
      }

    } else if(timer_expired(&periodic_timer)) {
      timer_reset(&periodic_timer);
      for(i = 0; i < UIP_CONNS; i++) {
	uip_periodic(i);
	/* If the above function invocation resulted in data that
	   should be sent out on the network, the global variable
	   uip_len is set to a value > 0. */
	if(uip_len > 0) {
	  uip_arp_out();
#ifdef __CYGWIN__
	  wpcap_send();
#else
	  tapdev_send();
#endif
	}
      }

#if UIP_UDP
      for(i = 0; i < UIP_UDP_CONNS; i++) {
	uip_udp_periodic(i);
	/* If the above function invocation resulted in data that
	   should be sent out on the network, the global variable
	   uip_len is set to a value > 0. */
	if(uip_len > 0) {
	  uip_arp_out();
#ifdef __CYGWIN__
	  wpcap_send();
#else
	  tapdev_send();
#endif
	}
      }
#endif /* UIP_UDP */
      
      /* Call the ARP timer function every 10 seconds. */
      if(timer_expired(&arp_timer)) {
	timer_reset(&arp_timer);
	uip_arp_timer();
      }
    }
  }
  return 0;
}
int main(void)
{
    pInt8U pBuffer;
    Int32U Size,TranSize;
    int i=0,j;
    int k=0;
    int cnt=0;
    int tempcnt=0;
    int concurCnt = 0;
    Flo64 curP, curQ;
    int meanCalc=1,displayIntro=1;
    AlgoPowers_t PowerLines[3];
    AlgoPowers_t prevPLines;
    AlgoPowers_t curPLines;
    int LearnNewMean = 1;
    int learning =1;
    int recognized=0;
    int plugOut = 0;
    Flo64 cInterval = 5000;
    
    //web
    unsigned int e;
    uip_ipaddr_t ipaddr;
    struct timer periodic_timer, arp_timer;
    
    // int deviceCnt[3] = {0};
    //AlgoLine_t TestLine;
    // pAlgoLine_t pTestLine=&TestLine;
    AlgoDevice_t tmpDev;
//    AlgoDevice_t devProfiles[3]={0};
    AlgoDevice_t devProfiles[3];
    int devNum=0;
    
    
    bool addDevice = 1;
    
    Int32S devLamps[3];
    
    
    #if CDC_DEVICE_SUPPORT_LINE_CODING > 0
        CDC_LineCoding_t CDC_LineCoding;
    UartLineCoding_t UartLineCoding;
    #endif // CDC_DEVICE_SUPPORT_LINE_CODING > 0
        
    
    
    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //  GUI init  START
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // initialize touch parametres
    Int32U cursor_x = (C_GLCD_H_SIZE - CURSOR_H_SIZE)/2, cursor_y = (C_GLCD_V_SIZE - CURSOR_V_SIZE)/2;
    ToushRes_t XY_Touch;
    Boolean Touch = FALSE;
    
    
    GLCD_Ctrl (FALSE);
    
    // Init GPIO
    GpioInit();
    
    #ifndef SDRAM_DEBUG
    // MAM init
    MAMCR_bit.MODECTRL = 0;
    MAMTIM_bit.CYCLES  = 3;   // FCLK > 40 MHz
    MAMCR_bit.MODECTRL = 2;   // MAM functions fully enabled
    // Init clock
    InitClock();
    // SDRAM Init
    SDRAM_Init();
    #endif // SDRAM_DEBUG
        // Init VIC   ---interrupt
    VIC_Init();
    
    
    // GLCD init
    GLCD_Init (NULL, NULL);
    
    GLCD_Cursor_Dis(0);
    
    GLCD_Copy_Cursor ((Int32U *)Cursor, 0, sizeof(Cursor)/sizeof(Int32U));
    
    GLCD_Cursor_Cfg(CRSR_FRAME_SYNC | CRSR_PIX_32);
    
    GLCD_Move_Cursor(cursor_x, cursor_y);
    
    GLCD_Cursor_En(0);
    
    // Init touch screen
    TouchScrInit();
    
    // Touched indication LED
    USB_H_LINK_LED_SEL = 0; // GPIO
    USB_H_LINK_LED_FSET = USB_H_LINK_LED_MASK;
    USB_H_LINK_LED_FDIR |= USB_H_LINK_LED_MASK;
    
    // Init UART 0
    UartInit(UART_0,0,NORM);
    
    
    __enable_interrupt();
    
    GLCD_Ctrl (TRUE);
    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //  GUI init  END
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    
    
    /* devProfiles[0].dP= 101366.22;   //blow dryer
    devProfiles[0].dQ =51765.90;
    
    devProfiles[1].dP= 35957.14;    //light bulb
    devProfiles[1].dQ = 9045.64;
    */
    
    
    //  GLCD_print("Device char %f %f\r\n",devProfiles[devNum].dP, devProfiles[devNum].dQ );
    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    // Update the baud rate
    UartLineCoding.dwDTERate = 115200;
    // Update the stop bits number
    UartLineCoding.bStopBitsFormat = UART_ONE_STOP_BIT;
    // Update the parity type
    UartLineCoding.bParityType = UART_NO_PARITY;
    // Update the word width
    UartLineCoding.bDataBits = (UartWordWidth_t)(3);
    //Description: Init UART Baud rate, Word width, Stop bits, Parity type
    UartSetLineCoding(UART_0,UartLineCoding);
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    //calculate the no load powerlines
    //calcMeanRange(&prevPLines);
    // GLCD_print("P %f %f\n\r",prevPLines.P.CiHigh, prevPLines.P.CiLow);
    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    for(i=0; i<3; i++){
      devProfiles[i].dP=0;
      devProfiles[i].dQ=0;
      devLamps[i]=0;
    }
    
    // initialize gui
    gui_monitoringScreen(devProfiles,devLamps);
    
    GLCD_SetFont(&Terminal_6_8_6,0x0000FF,0x000cd4ff);
    GLCD_SetWindow(0,0,319,239);
    GLCD_TextSetPos(0,0);
    //calculate the no load powerlines
    calcMeanRange(&prevPLines);
    
    while(1)
    {
        
        ///////////////////////////////////////////////////////////////////////////////
        GLCD_SetFont(&Terminal_6_8_6,0x0000FF,0x000cd4ff);
        GLCD_SetWindow(0,0,319,239);
        GLCD_TextSetPos(0,0);
        
        /////////////////////////////////////////////////////////////////////////////////
        
        /////////////////////////////////////////////////////////////////////////////////
        //algo    START
        /////////////////////////////////////////////////////////////////////////////////
        if(dataReady){
            dataReady=0;
            GLCD_print("%s\r\n",dataArray);
            //  GLCD_print("reach reach!!!\r\n");
                        
            //convert the incoming data to floats
            dataConversion(dataArray, dataP, dataQ, dataT, cnt);           
            
            //keep track of devices
            GLCD_print("Device zero:%d   one:%d   two:%d\r",devLamps[0],
            devLamps[1],devLamps[2]);
            
            concurCnt=0;
            //detect a step change.
            if(detectStepChange(&prevPLines, dataP[cnt], dataQ[cnt] )){
                tempcnt=(int) fmod(cnt+4,45);
                while(cnt != tempcnt){
                    if(dataReady){
                        dataConversion(dataArray, dataP, dataQ, dataT, cnt);
                        if(detectStepChange(&prevPLines, dataP[cnt], dataQ[cnt] )){
                            concurCnt++;
                        }
                        cnt++;
                        dataReady=0;
                        if(cnt>=45){
                            cnt=0;
                        }
                    }
                }
                
                if(concurCnt>=3){
                    //calculate new powerlines
                    calcMeanRange(&curPLines);
                    
                    tmpDev.dP = curPLines.P.mean - prevPLines.P.mean;
                    tmpDev.dQ = curPLines.Q.mean - prevPLines.Q.mean;
                    GLCD_print("test dev dP is %f\r\n",tmpDev.dP);
                    GLCD_print("test dev dQ is %f\r\n",tmpDev.dQ);
                    
                    
                    //in learning phase
                    if(screen==1){
                        
                        // GLCD_print("we can now add DEVICES!!!\r\n");
                        
                        if(devNum==3){
                            GLCD_print("Can't learn anymore devices\r\n");
                            learning=0;
                        }
                        else{
                            if(tmpDev.dP>0 && tmpDev.dQ>0){
                                
                                GLCD_print("add device or not?\r\n");
                                
                                if(addDevice){
                                    
                                    devProfiles[devNum].dP = tmpDev.dP;
                                    devProfiles[devNum].dQ = tmpDev.dQ;
                                    GLCD_print("new profile %d p:%f q:%f\r\n",devNum,
                                    tmpDev.dP,tmpDev.dQ);
                                    devNum++;
                                }
                                
                            }
                            else{
                                GLCD_print("device is unplugged\r\n");
                                //DO THE CHECK
                                
                                //   determineDevice(devProfiles,tmpDev,&devNum,devLamps);
                                //gui_monitoringScreen(devProfiles,devLamps);
                            }
                        }
                    }
                    //in user phase
                    else if (screen==0){
                        if(devNum==0){
                            GLCD_print("No devices on file. Please enter learning mode");
                        }
                        
                        else{
                            //check aganst known devices
                            for(k=0;k<3;k++){
                                GLCD_print("devProfile %d p:%f  q:%f\r\n",k, devProfiles[k].dP,
                                devProfiles[k].dQ);
                                //if plugging out, the deltas will be negative
                                if(tmpDev.dP<0 && tmpDev.dQ<0){
                                    plugOut=1;
                                    tmpDev.dP = fabs(tmpDev.dP);
                                    tmpDev.dQ = fabs(tmpDev.dQ);
                                }
                                
                                if(withinRange(tmpDev,devProfiles[k],cInterval)){
                                    if(plugOut){
                                        GLCD_print("device %d unplugged!\r\n",k);
                                        plugOut=0;
                                        devLamps[k]=0;
                                    }
                                    else{
                                        GLCD_print("device %d plugged in!\r\n",k);
                                        devLamps[k]=1;
                                    }
                                    gui_monitoringScreen(devProfiles,devLamps);
                                    break;
                                }
                            }
                        } // end of if(devNum>0)
                    }   // end user phase
                    prevPLines = curPLines;
                    GLCD_print("prevPlines %f, %f\r",prevPLines.P,prevPLines.Q);
                }       // end of (concurCnt>=3)
            }           // end of detectStepChange()
            cnt++;
            //dataReady=0;
            if(cnt >= 45){
                cnt=0;
            }
        }               // end of dataReady
        /////////////////////////////////////////////////////////////////////////////////
        //                      End of Algo
        /////////////////////////////////////////////////////////////////////////////////
        
        
        /////////////////////////////////////////////////////////////////////////////////
        //      GUI start
        /////////////////////////////////////////////////////////////////////////////////
        
        if(TouchGet(&XY_Touch))
        {
            cursor_x = XY_Touch.X;
            cursor_y = XY_Touch.Y;
            GLCD_Move_Cursor(cursor_x, cursor_y);
            
            if (FALSE == Touch)
            {
                Touch = TRUE;
                USB_H_LINK_LED_FCLR = USB_H_LINK_LED_MASK;
            }
        }
        
        // check the need to swtich screen
        else if(Touch)
        {
            switch(screen)
            {
                
                case 0: // 0 = Monitoring screen
                
                // Touch logic
                if(modeButtonState)
                {
                    if (cursor_x <= 80 && cursor_y >= 190)
                    {
                        gui_toggleMode(devProfiles,devLamps);
                        break;
                    }
                }
                if(settingsButtonState)
                {
                    if (cursor_x >= 239 && cursor_y >= 190)
                    {
                        gui_settingsScreen();
                        break;
                    }
                }
                break;
                case 1: // 1 = Learning screen
                // Touch logic
                if(modeButtonState)
                {
                    if (cursor_x <= 80 && cursor_y >= 190) //  mode
                    {
                        gui_toggleMode(devProfiles,devLamps);
                        break;
                    }
                }
                if(settingsButtonState)
                {
                    if (cursor_x >= 239 && cursor_y >= 190) //  set
                    {
                        gui_settingsScreen();
                        break;
                    }
                }
                if(addDeviceButtonState)
                {
                    // add device button placement (80,70,240,120)
                    if (cursor_x >= 80 && cursor_y >= 70 && cursor_x <= 240 && cursor_y <= 120)
                    {
                        addDevice = 1;
                        
                        //gui_addDeviceScreen();
                        break;
                    }
                }
                break;
                case 2: // 2 = Add device screen
                // Back button
                if(backButtonState)
                {
                    if (cursor_x <= 80 && cursor_y >= 190)
                    {
                        gui_learningScreen();
                        break;
                    }
                }
                break;
                case 3: // 3: Settings screen
                // Back button
                if(backButtonState)
                {
                    if (cursor_x <= 80 && cursor_y >= 190)
                    {
                        if(gui_getMode())
                        {
                            gui_learningScreen();
                            break;
                        }
                        else
                        {
                            gui_monitoringScreen(devProfiles,devLamps);
                            break;
                        }
                    }
                }
                if(settingsButtonState)
                {
                    if (cursor_x >= 239 && cursor_y >= 190)
                    {
                        gui_settingsScreen();
                        break;
                    }
                }
                break;
                case 4: // 4: Delete Devices screen
                // Back button
                if(backButtonState)
                {
                    if (cursor_x <= 80 && cursor_y >= 190)
                    {
                        gui_learningScreen();
                        break;
                    }
                }
                
                break;
            }
            USB_H_LINK_LED_FSET = USB_H_LINK_LED_MASK;
            Touch = FALSE;
            
        }
        /////////////////////////////////////////////////////////////////////////////////
        
        /////////////////////////////////////////////////////////////////////////////////
    }
    
    
  // Initialize the ethernet device driver
  do
  {
    GLCD_TextSetPos(0,0);
  }
  while(!tapdev_init());
  GLCD_TextSetPos(0,0);

  // uIP web server
  // Initialize the uIP TCP/IP stack.
  uip_init();

  uip_ipaddr(ipaddr, 192,168,0,100);
  uip_sethostaddr(ipaddr);
  uip_ipaddr(ipaddr, 192,168,0,1);
  uip_setdraddr(ipaddr);
  uip_ipaddr(ipaddr, 255,255,255,0);
  uip_setnetmask(ipaddr);

  // Initialize the HTTP server.
  httpd_init();

  while(1)
  {
    uip_len = tapdev_read(uip_buf);
    if(uip_len > 0)
    {
      if(BUF->type == htons(UIP_ETHTYPE_IP))
      {
	      uip_arp_ipin();
	      uip_input();
	      /* If the above function invocation resulted in data that
	         should be sent out on the network, the global variable
	         uip_len is set to a value > 0. */
	      if(uip_len > 0)
        {
	        uip_arp_out();
	        tapdev_send(uip_buf,uip_len);
	      }
      }
      else if(BUF->type == htons(UIP_ETHTYPE_ARP))
      {
        uip_arp_arpin();
	      /* If the above function invocation resulted in data that
	         should be sent out on the network, the global variable
	         uip_len is set to a value > 0. */
	      if(uip_len > 0)
        {
	        tapdev_send(uip_buf,uip_len);
	      }
      }
    }
    else if(timer_expired(&periodic_timer))
    {
      timer_reset(&periodic_timer);
      for(e = 0; e < UIP_CONNS; e++)
      {
      	uip_periodic(e);
        /* If the above function invocation resulted in data that
           should be sent out on the network, the global variable
           uip_len is set to a value > 0. */
        if(uip_len > 0)
        {
          uip_arp_out();
          tapdev_send(uip_buf,uip_len);
        }
      }
#if UIP_UDP
      for(e = 0; e < UIP_UDP_CONNS; e++) {
        uip_udp_periodic(e);
        /* If the above function invocation resulted in data that
           should be sent out on the network, the global variable
           uip_len is set to a value > 0. */
        if(uip_len > 0) {
          uip_arp_out();
          tapdev_send();
        }
      }
#endif /* UIP_UDP */
      /* Call the ARP timer function every 10 seconds. */
      if(timer_expired(&arp_timer))
      {
        timer_reset(&arp_timer);
        uip_arp_timer();
      }
    }
  }
    
}
예제 #18
0
파일: bootp.c 프로젝트: asuro/ethersex
void
bootp_handle_reply(void)
{
    int i;
    struct bootp *pk = uip_appdata;

    if(pk->bp_op != BOOTREPLY)
	return;					/* ugh? shouldn't happen */

    if(pk->bp_htype != HTYPE_ETHERNET)
	return;

    for(i = 0; i < 4; i ++) {
	if(pk->bp_xid[i] != uip_udp_conn->appstate.bootp.xid[i])
	    return;				/* session id doesn't match */

	if(pk->bp_vend[i] != replycookie[i])
	    return;				/* reply cookie doesn't match */
    }


    /*
     * looks like we have received a valid bootp reply,
     * prepare to override eeprom configuration
     */
    uip_ipaddr_t ips[5];
    memset(&ips, 0, sizeof(ips));

    /* extract our ip addresses, subnet-mask and gateway ... */
    memcpy(&ips[0], pk->bp_yiaddr, 4);
    uip_sethostaddr(&ips[0]);

    debug_printf ("BOOTP: configured new ip address %d.%d.%d.%d\n",
                  ((unsigned char *) ips)[0], ((unsigned char *) ips)[1],
                  ((unsigned char *) ips)[2], ((unsigned char *) ips)[3]);

    unsigned char *ptr = pk->bp_vend + 4;
    while(*ptr != 0xFF) {
	switch(* ptr) {
	case TAG_SUBNET_MASK:
	    memcpy(&ips[1], &ptr[2], 4);
	    uip_setnetmask(&ips[1]);
	    break;

	case TAG_GATEWAY:
	    memcpy(&ips[2], &ptr[2], 4);
	    uip_setdraddr(&ips[2]);
	    break;
#ifdef DNS_SUPPORT
        case TAG_DOMAIN_SERVER:
	    memcpy(&ips[3], &ptr[2], 4);
            resolv_conf(&ips[3]);
            break;
#endif
#ifdef NTP_SUPPORT
        case TAG_NTP_SERVER:
            /* This will set the ntp connection to the server set by the bootp
             * request
             */
	    memcpy(&ips[4], &ptr[2], 4);
            ntp_conf(&ips[4]);
            break;
#endif
	}

	ptr = ptr + ptr[1] + 2;
    }

    /* Remove the bootp connection */
    uip_udp_remove(uip_udp_conn);

#ifdef BOOTP_TO_EEPROM_SUPPORT
    eeprom_save(ip, &ips[0], IPADDR_LEN);
    eeprom_save(netmask, &ips[1], IPADDR_LEN);
    eeprom_save(gateway, &ips[2], IPADDR_LEN);
#ifdef DNS_SUPPORT
    eeprom_save(dns_server, &ips[3], IPADDR_LEN);
#endif
#ifdef NTP_SUPPORT
    eeprom_save(ntp_server, &ips[4], IPADDR_LEN);
#endif
    eeprom_update_chksum();
#endif /* BOOTP_TO_EEPROM_SUPPORT */

#ifdef DYNDNS_SUPPORT
    dyndns_update();
#endif

#if defined(TFTP_SUPPORT) && defined(BOOTLOADER_SUPPORT)
    if(pk->bp_file[0] == 0)
	return;					/* no boot filename provided */

    debug_putstr("load:");
    debug_putstr(pk->bp_file);
    debug_putchar('\n');

    /* create tftp connection, which will fire the download request */
    uip_ipaddr_t ip;
    uip_ipaddr(&ip, pk->bp_siaddr[0], pk->bp_siaddr[1],
	       pk->bp_siaddr[2], pk->bp_siaddr[3]);

    tftp_fire_tftpomatic(&ip, pk->bp_file);
#endif /* TFTP_SUPPORT */
}
예제 #19
0
/*---------------------------------------------------------------------------*/
#if WITH_TINYOS_AUTO_IDS
uint16_t TOS_NODE_ID = 0x1234; /* non-zero */
uint16_t TOS_LOCAL_ADDRESS = 0x1234; /* non-zero */
#endif /* WITH_TINYOS_AUTO_IDS */
int
main(void)
{
  /* Set stack overflow address for detecting overflow in runtime */
  vAHI_SetStackOverflow(TRUE, ((uint32_t *)&heap_location)[0]);

  /* Initialize random with a seed from the SoC random generator.
   * This must be done before selecting the high-precision external oscillator.
   */
  vAHI_StartRandomNumberGenerator(E_AHI_RND_SINGLE_SHOT, E_AHI_INTS_DISABLED);
  random_init(u16AHI_ReadRandomNumber());

  clock_init();
  rtimer_init();

#if JN516X_EXTERNAL_CRYSTAL_OSCILLATOR
  /* initialize the 32kHz crystal and wait for ready */
  xosc_init();
  /* need to reinitialize because the wait-for-ready process uses system timers */
  clock_init();
  rtimer_init();
#endif

  watchdog_init();
  leds_init();
  leds_on(LEDS_ALL);
  init_node_mac();

  energest_init();
  ENERGEST_ON(ENERGEST_TYPE_CPU);

  node_id_restore();

#if WITH_TINYOS_AUTO_IDS
  node_id = TOS_NODE_ID;
#endif /* WITH_TINYOS_AUTO_IDS */
  /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */
#ifdef IEEE_802154_MAC_ADDRESS
  {
    uint8_t ieee[] = IEEE_802154_MAC_ADDRESS;
    memcpy(node_mac, ieee, sizeof(uip_lladdr.addr));
    node_mac[7] = node_id & 0xff;
  }
#endif

  process_init();
  ctimer_init();
  uart0_init(UART_BAUD_RATE); /* Must come before first PRINTF */

#if NETSTACK_CONF_WITH_IPV4
  slip_arch_init(UART_BAUD_RATE);
#endif /* NETSTACK_CONF_WITH_IPV4 */

  /* check for reset source */
  if(bAHI_WatchdogResetEvent()) {
    PRINTF("Init: Watchdog timer has reset device!\r\n");
  }
  process_start(&etimer_process, NULL);
  set_linkaddr();
  netstack_init();

#if NETSTACK_CONF_WITH_IPV6
#if UIP_CONF_IPV6_RPL
  PRINTF(CONTIKI_VERSION_STRING " started with IPV6, RPL\n");
#else
  PRINTF(CONTIKI_VERSION_STRING " started with IPV6\n");
#endif
#elif NETSTACK_CONF_WITH_IPV4
  PRINTF(CONTIKI_VERSION_STRING " started with IPV4\n");
#else
  PRINTF(CONTIKI_VERSION_STRING " started\n");
#endif

  if(node_id > 0) {
    PRINTF("Node id is set to %u.\n", node_id);
  } else {
    PRINTF("Node id is not set.\n");
  }
#if NETSTACK_CONF_WITH_IPV6
  memcpy(&uip_lladdr.addr, node_mac, sizeof(uip_lladdr.addr));
  queuebuf_init();
#endif /* NETSTACK_CONF_WITH_IPV6 */

  PRINTF("%s %s %s\n", NETSTACK_LLSEC.name, NETSTACK_MAC.name, NETSTACK_RDC.name);

#if !NETSTACK_CONF_WITH_IPV4 && !NETSTACK_CONF_WITH_IPV6
  uart0_set_input(serial_line_input_byte);
  serial_line_init();
#endif

#if TIMESYNCH_CONF_ENABLED
  timesynch_init();
  timesynch_set_authority_level((linkaddr_node_addr.u8[0] << 4) + 16);
#endif /* TIMESYNCH_CONF_ENABLED */

#if NETSTACK_CONF_WITH_IPV4
  process_start(&tcpip_process, NULL);
  process_start(&uip_fw_process, NULL); /* Start IP output */
  process_start(&slip_process, NULL);

  slip_set_input_callback(set_gateway);

  {
    uip_ipaddr_t hostaddr, netmask;

    uip_init();

    uip_ipaddr(&hostaddr, 172, 16,
               linkaddr_node_addr.u8[0], linkaddr_node_addr.u8[1]);
    uip_ipaddr(&netmask, 255, 255, 0, 0);
    uip_ipaddr_copy(&meshif.ipaddr, &hostaddr);

    uip_sethostaddr(&hostaddr);
    uip_setnetmask(&netmask);
    uip_over_mesh_set_net(&hostaddr, &netmask);
    /*    uip_fw_register(&slipif);*/
    uip_over_mesh_set_gateway_netif(&slipif);
    uip_fw_default(&meshif);
    uip_over_mesh_init(UIP_OVER_MESH_CHANNEL);
    PRINTF("uIP started with IP address %d.%d.%d.%d\n",
           uip_ipaddr_to_quad(&hostaddr));
  }
#endif /* NETSTACK_CONF_WITH_IPV4 */

  watchdog_start();
  NETSTACK_LLSEC.init();

#if NETSTACK_CONF_WITH_IPV6
  start_uip6();
#endif /* NETSTACK_CONF_WITH_IPV6 */

  /* need this to reliably generate the first rtimer callback and callbacks in other 
     auto-start processes */
  (void)u32AHI_Init();

  start_autostart_processes();

  leds_off(LEDS_ALL);

  main_loop();

  return -1;
}
예제 #20
0
/** uIP stack application callback for the DHCP client. This function must be called each time the TCP/IP stack
 *  needs a UDP packet to be processed.
 */
void DHCPClientApp_Callback(void)
{
	uip_udp_appstate_t* const AppState    = &uip_udp_conn->appstate;
	DHCP_Header_t*      const AppData     = (DHCP_Header_t*)uip_appdata;
	uint16_t                  AppDataSize = 0;

	switch (AppState->DHCPClient.CurrentState)
	{
		case DHCP_STATE_SendDiscover:
			/* Clear all DHCP settings, reset client IP address */
			memset(&AppState->DHCPClient.DHCPOffer_Data, 0x00, sizeof(AppState->DHCPClient.DHCPOffer_Data));
			uip_sethostaddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP);

			/* Fill out the DHCP response header */
			AppDataSize += DHCPClientApp_FillDHCPHeader(AppData, DHCP_DISCOVER, AppState);

			/* Add the required DHCP options list to the packet */
			uint8_t RequiredOptionList[] = {DHCP_OPTION_SUBNET_MASK, DHCP_OPTION_ROUTER, DHCP_OPTION_DNS_SERVER};
			AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_REQ_LIST, sizeof(RequiredOptionList),
			                                    RequiredOptionList);

			/* Send the DHCP DISCOVER packet */
			uip_udp_send(AppDataSize);

			/* Reset the timeout timer, progress to next state */
			timer_reset(&AppState->DHCPClient.Timeout);
			AppState->DHCPClient.CurrentState = DHCP_STATE_WaitForOffer;

			break;
		case DHCP_STATE_WaitForOffer:
			if (!(uip_newdata()))
			{
				/* Check if the DHCP timeout period has expired while waiting for a response */
				if (timer_expired(&AppState->DHCPClient.Timeout))
				  AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover;

				break;
			}

			uint8_t OfferResponse_MessageType;
			if ((AppData->TransactionID == DHCP_TRANSACTION_ID) &&
			    DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &OfferResponse_MessageType) &&
			    (OfferResponse_MessageType == DHCP_OFFER))
			{
				/* Received a DHCP offer for an IP address, copy over values for later request */
				memcpy(&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP, &AppData->YourIP, sizeof(uip_ipaddr_t));
				DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_SUBNET_MASK, &AppState->DHCPClient.DHCPOffer_Data.Netmask);
				DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_ROUTER,      &AppState->DHCPClient.DHCPOffer_Data.GatewayIP);
				DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_SERVER_ID,   &AppState->DHCPClient.DHCPOffer_Data.ServerIP);

				timer_reset(&AppState->DHCPClient.Timeout);
				AppState->DHCPClient.CurrentState = DHCP_STATE_SendRequest;
			}

			break;
		case DHCP_STATE_SendRequest:
			/* Fill out the DHCP response header */
			AppDataSize += DHCPClientApp_FillDHCPHeader(AppData, DHCP_REQUEST, AppState);

			/* Add the DHCP REQUESTED IP ADDRESS option to the packet */
			AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_REQ_IPADDR, sizeof(uip_ipaddr_t),
			                                    &AppState->DHCPClient.DHCPOffer_Data.AllocatedIP);

			/* Add the DHCP SERVER IP ADDRESS option to the packet */
			AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_SERVER_ID, sizeof(uip_ipaddr_t),
			                                    &AppState->DHCPClient.DHCPOffer_Data.ServerIP);

			/* Send the DHCP REQUEST packet */
			uip_udp_send(AppDataSize);

			/* Reset the timeout timer, progress to next state */
			timer_reset(&AppState->DHCPClient.Timeout);
			AppState->DHCPClient.CurrentState = DHCP_STATE_WaitForACK;

			break;
		case DHCP_STATE_WaitForACK:
			if (!(uip_newdata()))
			{
				/* Check if the DHCP timeout period has expired while waiting for a response */
				if (timer_expired(&AppState->DHCPClient.Timeout))
				  AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover;

				break;
			}

			uint8_t RequestResponse_MessageType;
			if ((AppData->TransactionID == DHCP_TRANSACTION_ID) &&
			    DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &RequestResponse_MessageType) &&
			    (RequestResponse_MessageType == DHCP_ACK))
			{
				/* Set the new network parameters from the DHCP server */
				uip_sethostaddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP);
				uip_setnetmask((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.Netmask);
				uip_setdraddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.GatewayIP);

				AppState->DHCPClient.CurrentState = DHCP_STATE_AddressLeased;
			}

			break;
	}
}
예제 #21
0
void vuIP_Task( void *pvParameters )
{
portBASE_TYPE i;
uip_ipaddr_t xIPAddr;
struct timer periodic_timer, arp_timer;

	( void ) pvParameters;

	/* Create the semaphore used by the ISR to wake this task. */
	vSemaphoreCreateBinary( xEMACSemaphore );

	/* Initialise the uIP stack. */
	timer_set( &periodic_timer, configTICK_RATE_HZ / 2 );
	timer_set( &arp_timer, configTICK_RATE_HZ * 10 );
	uip_init();
	uip_ipaddr( xIPAddr, configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 );
	uip_sethostaddr( xIPAddr );
	uip_ipaddr( xIPAddr, configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3 );
	uip_setnetmask( xIPAddr );
	httpd_init();

	/* Initialise the MAC. */
	while( xEthInitialise() != pdPASS )
	{
		vTaskDelay( uipINIT_WAIT );
	}

	prvSetMACAddress();

	for( ;; )
	{
		/* Is there received data ready to be processed? */
		uip_len = usGetMACRxData();

		if( ( uip_len > 0 ) && ( uip_buf != NULL ) )
		{
			/* Standard uIP loop taken from the uIP manual. */
			if( xHeader->type == htons( UIP_ETHTYPE_IP ) )
			{
				uip_arp_ipin();
				uip_input();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					uip_arp_out();
					vSendMACData( uip_len );
				}
			}
			else if( xHeader->type == htons( UIP_ETHTYPE_ARP ) )
			{
				uip_arp_arpin();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					vSendMACData( uip_len );
				}
			}
		}
		else
		{
			if( ( timer_expired( &periodic_timer ) ) && ( uip_buf != NULL ) )
			{
				timer_reset( &periodic_timer );
				for( i = 0; i < UIP_CONNS; i++ )
				{
					uip_periodic( i );

					/* If the above function invocation resulted in data that
					should be sent out on the network, the global variable
					uip_len is set to a value > 0. */
					if( uip_len > 0 )
					{
						uip_arp_out();
						vSendMACData( uip_len );
					}
				}

				/* Call the ARP timer function every 10 seconds. */
				if( timer_expired( &arp_timer ) )
				{
					timer_reset( &arp_timer );
					uip_arp_timer();
				}
			}
			else
			{
				/* We did not receive a packet, and there was no periodic
				processing to perform.  Block for a fixed period.  If a packet
				is received during this period we will be woken by the ISR
				giving us the Semaphore. */
				xSemaphoreTake( xEMACSemaphore, configTICK_RATE_HZ / 2 );
			}
		}
	}
}
예제 #22
0
PROCESS_THREAD(eriks_process, ev , data)
{
  static struct etimer timer;
  uip_ipaddr_t myaddr;
  uip_ipaddr_t hostaddr;
  uip_ipaddr_t netmask;
#if 0
  struct dhcps_client_lease dhleases[3];
  struct dhcps_config dhconfig;
#endif
  PROCESS_BEGIN();
  printf("Eriks super process\n\r");

  uip_init();

#if 0
  dhconfig.leases = &dhleases[0];
  dhconfig.num_leases = 3;
  dhconfig.default_lease_time = 3600;
  uip_ipaddr(&dhconfig.netmask, 255,255,255,255);
  uip_ipaddr(&dhconfig.dnsaddr, 1,2,3,4);
  uip_ipaddr(&dhconfig.dnsaddr, 1,0,0,1);
  dhconfig.flags = DHCP_CONF_NETMASK | DHCP_CONF_DEFAULT_ROUTER;
#endif
  /* usb_set_user_process(process_current); */

  uip_ipaddr(&myaddr, 10,0,0,2);
  uip_sethostaddr(&hostaddr);

  uip_ipaddr(&netmask, 255,0,0,0);
  uip_sethostaddr(&hostaddr);

  uip_ipaddr(&myaddr, 10,0,0,1);
  uip_ipaddr(&netmask, 255,255,0,0);

  usb_setup();
#if 0
  usb_cdc_eth_set_ifaddr(&myaddr);
  usb_cdc_eth_setup();
  
  dhcps_init(&dhconfig);
    
  while(ev != PROCESS_EVENT_EXIT) {
    PROCESS_WAIT_EVENT();
    printf("EVENT\n\r");
  }

#else
  usb_cdc_acm_setup();

  while(ev != PROCESS_EVENT_EXIT) {
    PROCESS_WAIT_EVENT();
    if (ev == PROCESS_EVENT_TIMER) {
      leds_toggle(LEDS_YELLOW);
      /* printf("FIFOP: %d\n", FIFOP_IS_1); */
      etimer_restart(&timer);
    } else if (ev == PROCESS_EVENT_MSG) {
      const struct usb_user_msg * const msg = data;
      switch(msg->type) {
      case USB_USER_MSG_TYPE_CONFIG:
        printf("User config\n");
        if (msg->data.config != 0) {
#if 0
          usb_setup_bulk_endpoint(DEV_TO_HOST,
                                  input_buffer, sizeof(input_buffer));
          usb_setup_bulk_endpoint(HOST_TO_DEV,
                                  output_buffer, sizeof(output_buffer));
          usb_setup_interrupt_endpoint(0x83,interrupt_buffer,
                                       sizeof(interrupt_buffer));
          etimer_set(&timer, CLOCK_SECOND);
#endif
        } else {
#if 0
          etimer_stop(&timer);
          usb_disable_endpoint(DEV_TO_HOST);
          usb_disable_endpoint(HOST_TO_DEV);
          usb_disable_endpoint(0x83);
#endif	  
        }
        break;
      case USB_USER_MSG_TYPE_EP_OUT(2):
        {
#if 0
          /*unsigned int len = msg->data.length; 
            printf("Received %d:\n", len);  */
          {
            unsigned char ch;
            unsigned int xfer;
	    /*
            while((xfer = usb_recv_data(HOST_TO_DEV, &ch, 1)) > 0) {
              printf(" %02x",ch);
	    */
              /* if (slip_input_byte(ch)) break; */

            }
#endif
            /* printf("\n"); */
        }
        break;
      }
    }
  }

#endif
  printf("Exiting USB process\n\r");
  PROCESS_END();
}
예제 #23
0
int dhcpc_request(void *handle, struct dhcpc_state *presult)
{
  struct dhcpc_state_s *pdhcpc = (struct dhcpc_state_s *)handle;
  struct in_addr oldaddr;
  struct in_addr newaddr;
  ssize_t result;
  uint8_t msgtype;
  int     retries;
  int     state;

  /* Save the currently assigned IP address (should be INADDR_ANY) */

  oldaddr.s_addr = 0;
  uip_gethostaddr("eth0", &oldaddr);

  /* Loop until we receive the lease (or an error occurs) */

  do
    {
      /* Set the IP address to INADDR_ANY. */

      newaddr.s_addr = INADDR_ANY;
      (void)uip_sethostaddr("eth0", &newaddr);

      /* Loop sending DISCOVER until we receive an OFFER from a DHCP
       * server.  We will lock on to the first OFFER and decline any
       * subsequent offers (which will happen if there are more than one
       * DHCP servers on the network.
       */

      state = STATE_INITIAL;
      do
        {
          /* Send the DISCOVER command */

          dbg("Broadcast DISCOVER\n");
          if (dhcpc_sendmsg(pdhcpc, presult, DHCPDISCOVER) < 0)
            {
              return ERROR;
            }

          /* Get the DHCPOFFER response */

          result = recv(pdhcpc->sockfd, &pdhcpc->packet, sizeof(struct dhcp_msg), 0);
          if (result >= 0)
            {
              msgtype = dhcpc_parsemsg(pdhcpc, result, presult);
              if (msgtype == DHCPOFFER)
                {
                  /* Save the servid from the presult so that it is not clobbered
                   * by a new OFFER.
                   */

                  dbg("Received OFFER from %08x\n", ntohl(presult->serverid.s_addr));
                  pdhcpc->ipaddr.s_addr   = presult->ipaddr.s_addr;
                  pdhcpc->serverid.s_addr = presult->serverid.s_addr;

                  /* Temporarily use the address offered by the server and break
                   * out of the loop.
                   */

                  (void)uip_sethostaddr("eth0", &presult->ipaddr);
                  state = STATE_HAVE_OFFER;
                }
            }

          /* An error has occurred.  If this was a timeout error (meaning that
           * nothing was received on this socket for a long period of time).
           * Then loop and send the DISCOVER command again.
           */

          else if (errno != EAGAIN)
            {
              /* An error other than a timeout was received -- error out */

              return ERROR;
            }
        }
      while (state == STATE_INITIAL);


      /* Loop sending the REQUEST up to three times (if there is no response) */

      retries = 0;
      do
        {
          /* Send the REQUEST message to obtain the lease that was offered to us. */

          dbg("Send REQUEST\n");
          if (dhcpc_sendmsg(pdhcpc, presult, DHCPREQUEST) < 0)
            {
              return ERROR;
            }
          retries++;

          /* Get the ACK/NAK response to the REQUEST (or timeout) */

          result = recv(pdhcpc->sockfd, &pdhcpc->packet, sizeof(struct dhcp_msg), 0);
          if (result >= 0)
            {
              /* Parse the response */

              msgtype = dhcpc_parsemsg(pdhcpc, result, presult);

              /* The ACK response means that the server has accepted our request
               * and we have the lease.
               */

              if (msgtype == DHCPACK)
                {
                  dbg("Received ACK\n");
                  state = STATE_HAVE_LEASE;
                }

              /* NAK means the server has refused our request.  Break out of
               * this loop with state == STATE_HAVE_OFFER and send DISCOVER again
               */

              else if (msgtype == DHCPNAK)
                {
                  dbg("Received NAK\n");
                  break;
                }

              /* If we get any OFFERs from other servers, then decline them now
               * and continue waiting for the ACK from the server that we
               * requested from.
               */

              else if (msgtype == DHCPOFFER)
                {
                  dbg("Received another OFFER, send DECLINE\n");
                  (void)dhcpc_sendmsg(pdhcpc, presult, DHCPDECLINE);
                }

              /* Otherwise, it is something that we do not recognize */

              else
                {
                  dbg("Ignoring msgtype=%d\n", msgtype);
                }
            }

          /* An error has occurred.  If this was a timeout error (meaning
           * that nothing was received on this socket for a long period of time).
           * Then break out and send the DISCOVER command again (at most
           * 3 times).
           */

          else if (errno != EAGAIN)
            {
              /* An error other than a timeout was received */

              (void)uip_sethostaddr("eth0", &oldaddr);
              return ERROR;
            }
        }
      while (state == STATE_HAVE_OFFER && retries < 3);
    }
  while (state != STATE_HAVE_LEASE);

  dbg("Got IP address %d.%d.%d.%d\n",
      (presult->ipaddr.s_addr >> 24 ) & 0xff,
      (presult->ipaddr.s_addr >> 16 ) & 0xff,
      (presult->ipaddr.s_addr >> 8  ) & 0xff,
      (presult->ipaddr.s_addr       ) & 0xff);
  dbg("Got netmask %d.%d.%d.%d\n",
      (presult->netmask.s_addr >> 24 ) & 0xff,
      (presult->netmask.s_addr >> 16 ) & 0xff,
      (presult->netmask.s_addr >> 8  ) & 0xff,
      (presult->netmask.s_addr       ) & 0xff);
  dbg("Got DNS server %d.%d.%d.%d\n",
      (presult->dnsaddr.s_addr >> 24 ) & 0xff,
      (presult->dnsaddr.s_addr >> 16 ) & 0xff,
      (presult->dnsaddr.s_addr >> 8  ) & 0xff,
      (presult->dnsaddr.s_addr       ) & 0xff);
  dbg("Got default router %d.%d.%d.%d\n",
      (presult->default_router.s_addr >> 24 ) & 0xff,
      (presult->default_router.s_addr >> 16 ) & 0xff,
      (presult->default_router.s_addr >> 8  ) & 0xff,
      (presult->default_router.s_addr       ) & 0xff);
  dbg("Lease expires in %d seconds\n", presult->lease_time);
  return OK;
}
예제 #24
0
파일: contiki-main.c 프로젝트: 1uk3/contiki
/*---------------------------------------------------------------------------*/
int
main(void)
{
  clock_init();
#if UIP_CONF_IPV6
/* A hard coded address overrides the stack default MAC address to
   allow multiple instances. uip6.c defines it as
   {0x00,0x06,0x98,0x00,0x02,0x32} giving an ipv6 address of
   [fe80::206:98ff:fe00:232] We make it simpler, {0x02,0x00,0x00 + the
   last three bytes of the hard coded address (if any are nonzero).
   HARD_CODED_ADDRESS can be defined in the contiki-conf.h file, or
   here to allow quick builds using different addresses.  If
   HARD_CODED_ADDRESS has a prefix it also applied, unless built as a
   RPL end node.  E.g. bbbb::12:3456 becomes fe80::ff:fe12:3456 and
   prefix bbbb::/64 if non-RPL ::10 becomes fe80::ff:fe00:10 and
   prefix awaits RA or RPL formation bbbb:: gives an address of
   bbbb::206:98ff:fe00:232 if non-RPL */
#ifdef HARD_CODED_ADDRESS
  {
  uip_ipaddr_t ipaddr;
  uiplib_ipaddrconv(HARD_CODED_ADDRESS, &ipaddr);
  if((ipaddr.u8[13] != 0) ||
     (ipaddr.u8[14] != 0) ||
     (ipaddr.u8[15] != 0)) {
    if(sizeof(uip_lladdr) == 6) {  /* Minimal-net uses ethernet MAC */
      uip_lladdr.addr[0] = 0x02;
      uip_lladdr.addr[1] = 0;
      uip_lladdr.addr[2] = 0;
      uip_lladdr.addr[3] = ipaddr.u8[13];
      uip_lladdr.addr[4] = ipaddr.u8[14];
      uip_lladdr.addr[5] = ipaddr.u8[15];
    }
  }
 }
#endif /* HARD_CODED_ADDRESS */
#endif /* UIP_CONF_IPV6 */

  process_init();
/* procinit_init initializes RPL which sets a ctimer for the first DIS */
/* We must start etimers and ctimers,before calling it */
  process_start(&etimer_process, NULL);
  ctimer_init();

#if RPL_BORDER_ROUTER
  process_start(&border_router_process, NULL);
  printf("Border Router Process started\n");
#elif UIP_CONF_IPV6_RPL
  printf("RPL enabled\n");
#endif

  procinit_init();
  autostart_start(autostart_processes); 

  /* Set default IP addresses if not specified */
#if !UIP_CONF_IPV6
  {
    uip_ipaddr_t addr;

    uip_gethostaddr(&addr);
    if(addr.u8[0] == 0) {
      uip_ipaddr(&addr, 172,18,0,2);
    }
    printf("IP Address:  %d.%d.%d.%d\n", uip_ipaddr_to_quad(&addr));
    uip_sethostaddr(&addr);
    
    uip_getnetmask(&addr);
    if(addr.u8[0] == 0) {
      uip_ipaddr(&addr, 255,255,0,0);
      uip_setnetmask(&addr);
    }
    printf("Subnet Mask: %d.%d.%d.%d\n", uip_ipaddr_to_quad(&addr));
    
    uip_getdraddr(&addr);
    if(addr.u8[0] == 0) {
      uip_ipaddr(&addr, 172,18,0,1);
      uip_setdraddr(&addr);
    }
    printf("Def. Router: %d.%d.%d.%d\n", uip_ipaddr_to_quad(&addr));
  }
#else /* UIP_CONF_IPV6 */

#if !UIP_CONF_IPV6_RPL
  {
    uip_ipaddr_t ipaddr;
#ifdef HARD_CODED_ADDRESS
    uiplib_ipaddrconv(HARD_CODED_ADDRESS, &ipaddr);
#else
    uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
#endif
    if((ipaddr.u16[0] != 0) ||
       (ipaddr.u16[1] != 0) ||
       (ipaddr.u16[2] != 0) ||
       (ipaddr.u16[3] != 0)) {
#if UIP_CONF_ROUTER
      if(!uip_ds6_prefix_add(&ipaddr, UIP_DEFAULT_PREFIX_LEN, 0, 0, 0, 0)) {
        fprintf(stderr,"uip_ds6_prefix_add() failed.\n");
        exit(EXIT_FAILURE);
      }
#else /* UIP_CONF_ROUTER */
      if(!uip_ds6_prefix_add(&ipaddr, UIP_DEFAULT_PREFIX_LEN, 0)) {
        fprintf(stderr,"uip_ds6_prefix_add() failed.\n");
        exit(EXIT_FAILURE);
      }
#endif /* UIP_CONF_ROUTER */

      uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
      uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);
    }
  }
#endif /* !UIP_CONF_IPV6_RPL */

#endif /* !UIP_CONF_IPV6 */

 // procinit_init();
 // autostart_start(autostart_processes); 

  /* Make standard output unbuffered. */
  setvbuf(stdout, (char *)NULL, _IONBF, 0);

  printf("\n*******%s online*******\n",CONTIKI_VERSION_STRING);

#if UIP_CONF_IPV6 && !RPL_BORDER_ROUTER  /* Border router process prints addresses later */
  {
    int i = 0;
    int interface_count = 0;
    for(i = 0; i < UIP_DS6_ADDR_NB; i++) {
      if(uip_ds6_if.addr_list[i].isused) {
        printf("IPV6 Addresss: ");
        sprint_ip6(uip_ds6_if.addr_list[i].ipaddr);
        printf("\n");
        interface_count++;
      }
    }
    assert(0 < interface_count);
  }
#endif

  while(1) {
    fd_set fds;
    int n;
    struct timeval tv;
    clock_time_t next_event;
    
    n = process_run();
    next_event = etimer_next_expiration_time() - clock_time();

#if DEBUG_SLEEP
    if(n > 0)
      printf("sleep: %d events pending\n",n);
    else
      printf("sleep: next event @ T-%.03f\n",(double)next_event / (double)CLOCK_SECOND);
#endif

#ifdef __CYGWIN__
    /* wpcap doesn't appear to support select, so
     * we can't idle the process on windows. */
    next_event = 0;
#endif

    if(next_event > (CLOCK_SECOND * 2))
      next_event = CLOCK_SECOND * 2;
    tv.tv_sec = n ? 0 : (next_event / CLOCK_SECOND);
    tv.tv_usec = n ? 0 : ((next_event % 1000) * 1000);

    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
#ifdef __CYGWIN__
    select(1, &fds, NULL, NULL, &tv);
#else
    FD_SET(tapdev_fd(), &fds);
    if(0 > select(tapdev_fd() + 1, &fds, NULL, NULL, &tv)) {
      perror("Call to select() failed.");
      exit(EXIT_FAILURE);
    }
#endif

    if(FD_ISSET(STDIN_FILENO, &fds)) {
      char c;
      if(read(STDIN_FILENO, &c, 1) > 0) {
	serial_line_input_byte(c);
      }
    }
#ifdef __CYGWIN__
    process_poll(&wpcap_process);
#else
    process_poll(&tapdev_process);
#endif
    etimer_request_poll();
  }
  
  return 0;
}
예제 #25
0
void vuIP_Task( void *pvParameters )
{
portBASE_TYPE i;
uip_ipaddr_t xIPAddr;
struct timer periodic_timer, arp_timer;
extern void ( vEMAC_ISR_Wrapper )( void );

	( void ) pvParameters;

	/* Initialise the uIP stack. */
	timer_set( &periodic_timer, configTICK_RATE_HZ / 2 );
	timer_set( &arp_timer, configTICK_RATE_HZ * 10 );
	uip_init();
	uip_ipaddr( xIPAddr, configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 );
	uip_sethostaddr( xIPAddr );
	uip_ipaddr( xIPAddr, configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3 );
	uip_setnetmask( xIPAddr );
	httpd_init();

	/* Create the semaphore used to wake the uIP task. */
	vSemaphoreCreateBinary( xEMACSemaphore );

	/* Initialise the MAC. */
	while( lEMACInit() != pdPASS )
    {
        vTaskDelay( uipINIT_WAIT );
    }

	portENTER_CRITICAL();
	{
		LPC_EMAC->IntEnable = ( INT_RX_DONE | INT_TX_DONE );

		/* Set the interrupt priority to the max permissible to cause some
		interrupt nesting. */
		NVIC_SetPriority( ENET_IRQn, configEMAC_INTERRUPT_PRIORITY );

		/* Enable the interrupt. */
		NVIC_EnableIRQ( ENET_IRQn );
		prvSetMACAddress();
	}
	portEXIT_CRITICAL();


	for( ;; )
	{
		/* Is there received data ready to be processed? */
		uip_len = ulGetEMACRxData();

		if( ( uip_len > 0 ) && ( uip_buf != NULL ) )
		{
			/* Standard uIP loop taken from the uIP manual. */
			if( xHeader->type == htons( UIP_ETHTYPE_IP ) )
			{
				uip_arp_ipin();
				uip_input();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					uip_arp_out();
					vSendEMACTxData( uip_len );
				}
			}
			else if( xHeader->type == htons( UIP_ETHTYPE_ARP ) )
			{
				uip_arp_arpin();

				/* If the above function invocation resulted in data that
				should be sent out on the network, the global variable
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					vSendEMACTxData( uip_len );
				}
			}
		}
		else
		{
			if( timer_expired( &periodic_timer ) && ( uip_buf != NULL ) )
			{
				timer_reset( &periodic_timer );
				for( i = 0; i < UIP_CONNS; i++ )
				{
					uip_periodic( i );

					/* If the above function invocation resulted in data that
					should be sent out on the network, the global variable
					uip_len is set to a value > 0. */
					if( uip_len > 0 )
					{
						uip_arp_out();
						vSendEMACTxData( uip_len );
					}
				}

				/* Call the ARP timer function every 10 seconds. */
				if( timer_expired( &arp_timer ) )
				{
					timer_reset( &arp_timer );
					uip_arp_timer();
				}
			}
			else
			{
				/* We did not receive a packet, and there was no periodic
				processing to perform.  Block for a fixed period.  If a packet
				is received during this period we will be woken by the ISR
				giving us the Semaphore. */
				xSemaphoreTake( xEMACSemaphore, configTICK_RATE_HZ / 2 );
			}
		}
	}
}
예제 #26
0
static portTASK_FUNCTION( tunggu, pvParameters )
{
	struct t_env *envx;
	envx = (char *) ALMT_ENV;
	
	portBASE_TYPE xARPTimer;
	uip_ipaddr_t xIPAddr;
	int loop;
	int mul;
	unsigned int timer_menit=0;
	unsigned int loop_menit=0;	
	static volatile portTickType xStartTime, xCurrentTime;
	
	vTaskDelay(200);
	
	/* baca environtment (dapat IP dll dulu) */
	baca_env(0);
	printf("UIP : uip_init\r\n");

	uip_init ();
	
	//uip_ipaddr( xIPAddr, uipIP_ADDR0, uipIP_ADDR1, uipIP_ADDR2, uipIP_ADDR3 );
	uip_ipaddr( xIPAddr, envx->IP0, envx->IP1, envx->IP2, envx->IP3 );
	uip_sethostaddr( xIPAddr );

	printf("ARP : arp_init\r\n");
	uip_arp_init ();
	
	printf("Init ENC28J .. ");

	if (enc28j60Init() == 1)	{
		 printf(" .. ENC OK\r\n");
	}	else
		printf("ENC tidak respons !\r\n");

	#ifdef PAKE_HTTP
	printf("SIMPLE HTTP : init\r\n");
	httpd_init ();
	#endif
	
	#ifdef PAKE_TELNETD
	printf("SIMPLE TELNET : init\r\n");
    telnetd_init ();
	#endif

#ifdef BOARD_KOMON
    printf("MONITA : monita init\r\n");
//    monita_init();
#endif
	
#if (PAKAI_KONTROL == 1)
	printf("MONITA : monita kontrol init\r\n");
	kontrol_init();
#endif

//#ifdef BOARD_TAMPILAN
//#ifdef CARI_SUMBERNYA
#ifdef SAMPURASUN_SERVER
	printf("MONITA : sambungan_aktif init\r\n");
	sambungan_init();
	mul = 0;
#endif

#ifdef SAMPURASUN_CLIENT
    //printf("MONITA : monita init\r\n");
    printf("Monita : sampurasun client init !\r\n");
    monita_init();
#endif

#ifdef PAKAI_WEBCLIENT
		int ngitung=0;
		webclient_init();
		printf("webclient inited !\r\n");
		unsigned char datakeserver[512];
		int wclient=0, jmlData=0, nos=0, flag_nos=0, flag_sumber=0, jmlsumbernya=0;
		//int noPMaktif[JML_SUMBER];
		char il[256], dl[256];
		char ipdest[15], angkaangka[5];
		extern int kirimURL;
		extern char terkirimURL;
		extern int  noawal;
		int tiapKirim=950;
		int maxkirim=12;
#endif

#ifdef PAKAI_KIRIM_BALIK
	
	int anginkecil=0;
	int giliran;
	extern int sumber_datanya;
	extern int target_kirim;
	target_kirim = 4-1;
	sumber_datanya=3-1;

	//giliran=1-1;
	
	printf("Kirim Balik inited, Target data: sumber %d, target kirim: %d !\r\n", sumber_datanya+1, target_kirim+1);
#endif

	/*  Initialise the local timers */
	xStartTime = xTaskGetTickCount ();
	xARPTimer = 0;
	
	/* supaya cukup waktu buat siap2 */
	loop = -1000;
	
	#ifdef BOARD_KOMON_420_SABANG
	vTaskDelay(200);
	#endif

	#ifdef PAKAI_WEBCLIENT
		vTaskDelay(2000);
		vTaskDelay(2000);
	#endif
	//printf("mau loop for\r\n");
	for (;;)
	{
		vTaskDelay(1);
		//portYIELD();
		#if 1
		#ifdef PAKAI_WEBCLIENT
		if (envx->statusWebClient==1) {
			wclient++;
			if (envx->burst==1) {
				jmlData=kirimModul(1, 0, 0, il, dl);
				//jmlsumbernya=1;
				tiapKirim = 500;
			} else 
			{			// kirim 1-1
				/*
				#ifdef BANYAK_SUMBER
					struct t_sumber *pmx;
					pmx = (char *) ALMT_SUMBER;
					jmlsumbernya=0;
					for(selang=0; selang<JML_SUMBER; selang++) {
						if (pmx[selang].status==1) {
							printf("selang: %d, status: %d\r\n", selang, pmx[selang].status);
							noPMaktif[jmlsumbernya]=selang;
							jmlsumbernya++;
						}
					}
					if (jmlsumbernya==0) {
						jmlsumbernya=1;
					}
					//jmlData=kirimModul(0, noPMaktif[sumbernya], 0, il, dl);
					printf("jml Data: %d, sumbernya: %d\r\n", jmlData, sumbernya);
					// kenapa ini ??? harusnya tiap detik, knapa jadi tiap 4 detik ????
					//tiapKirim = (int) (100/jmlsumbernya);
					tiapKirim = (int) (195/jmlsumbernya);
					//printf("wclient: %d\r\n", wclient);
				#endif
				//*/
			}	
			if (wclient == tiapKirim) {
				ngitung++;
				
				struct t_sumber *sumber;
				sumber = (char *) ALMT_SUMBER;
				if (!flag_nos) {
					nos++;
					while(sumber[nos-1].status!=1) {	// cari modul sumber aktif
						if (nos>JML_SUMBER) {
							nos=0;
							jmlsumbernya=0;
						}
						nos++;
					}
				}
				jmlsumbernya++;
				//printf("kirim: %5d, nos: %d, wclient: %d, sumber.status: %d, jmlsumbernya: %d\r\n", ngitung, nos-1, wclient, sumber[nos-1].status, jmlsumbernya);
				
				// cek datanya PM ?? // <--- ternyata gak cuma PM, modul lain juga bisa
				if (sumber[nos-1].tipe==0 || sumber[nos-1].tipe==1 || sumber[nos-1].tipe==100)	{	// PM710 || PM810
					jmlData=kirimModul(0, nos-1, noawal, il, dl);
					if (jmlData==12) {
						flag_nos=1;
					} else {		// sudah habis, reset ke 0
						flag_nos=0;
						noawal=0;
					}
					//printf("nilai noawal: %d, flagnos: %d\r\n", noawal, flag_nos);
				} else	{
					jmlData=kirimModul(0, nos-1, 0, il, dl);
					noawal=0;
				}
				
				// hitung jml loop kirim ke server
				if (flag_sumber<jmlsumbernya) {
					flag_sumber=jmlsumbernya;
					tiapKirim=950/jmlsumbernya;
				}
				
				
				wclient = 0;				

				if (jmlData>0) {
					
					sprintf(ipdest, "%d.%d.%d.%d", envx->GW0, envx->GW1, envx->GW2, envx->GW3);
					//portENTER_CRITICAL();
					//sprintf(datakeserver, "%s?i=%s&p=diesel&j=%d&%s&%s", envx->berkas, envx->SN, jmlData, il, dl);
					strcpy(datakeserver, envx->berkas);
					strcat(datakeserver, "?i=");
					strcat(datakeserver, envx->SN);
					strcat(datakeserver, "&p=diesel&j=");
					sprintf(angkaangka, "%d", jmlData);
					strcat(datakeserver, angkaangka);
					strcat(datakeserver, "&");
					strcat(datakeserver, il);
					strcat(datakeserver, "&");
					strcat(datakeserver, dl);
					//portEXIT_CRITICAL();
					//printf("datakeserver: %s\r\n",datakeserver);
					webclient_get(ipdest, 80, datakeserver);
					
				}
			}
		}
		#endif
		
		//#if defined(BOARD_TAMPILAN) || defined (TAMPILAN_MALINGPING) 
		#ifdef SAMPURASUN_SERVER
		//#ifdef CARI_SUMBERNYA
		loop++;
		if (loop > 200) 		// 50, 40, 80
		{
			loop = 0;
			
			sambungan_connect(mul);	
			
			mul++;
			if (mul > JML_SUMBER) mul = 0;
			
		}
		#endif
		
		#ifdef PAKAI_KIRIM_BALIK
			anginkecil++;
			if (anginkecil > 2000) {	/* tiap 2 detik */
				
				kirim_balik_connect(target_kirim);
				
				anginkecil=0;
				//giliran++;
				//if (giliran > JML_SUMBER) mul = 0;
			}
		#endif
		
		//if (enc28j60WaitForData (uipMAX_BLOCK_TIME) == pdTRUE)
		if (cek_paket())	{
			//printf("masuk cekpaket \r\n");
			#if 1
			  paket_per_menit++;
			  /* Let the network device driver read an entire IP packet
		         into the uip_buf. If it returns > 0, there is a packet in the
		         uip_buf buffer. */
		      if ((uip_len = enc28j60Receive ()) > 0)
		      {				  
				  if (pucUIP_Buffer->type == htons (UIP_ETHTYPE_IP))
		    	  {
		    	            uip_arp_ipin ();
		    	            uip_input ();

		    	            /* If the above function invocation resulted in data that
		    	               should be sent out on the network, the global variable
		    	               uip_len is set to a value > 0. */
		    	            if (uip_len > 0)
		    	            {
		    	              uip_arp_out ();
		    	              enc28j60Send ();
							  paket_kita++;
		    	            }
		    	     }
		    	     else if (pucUIP_Buffer->type == htons (UIP_ETHTYPE_ARP))
		    	     {
		    	            uip_arp_arpin ();

		    	            /* If the above function invocation resulted in data that
		    	               should be sent out on the network, the global variable
		    	               uip_len is set to a value > 0. */
		    	            if (uip_len > 0)
		    	              enc28j60Send ();
		    	     }

		      }
		      #endif
		}
		else		{
		      /* The poll function returned 0, so no packet was
		         received. Instead we check if it is time that we do the
		         periodic processing. */
		      xCurrentTime = xTaskGetTickCount ();

		      if ((xCurrentTime - xStartTime) >= RT_CLOCK_SECOND)
		      {
		        portBASE_TYPE i;

		        /* Reset the timer. */
		        xStartTime = xCurrentTime;

		        /* Periodic check of all connections. */
		        for (i = 0; i < UIP_CONNS; i++)
		        {
		          uip_periodic (i);

		          /* If the above function invocation resulted in data that
		             should be sent out on the network, the global variable
		             uip_len is set to a value > 0. */
		          if (uip_len > 0)
		          {
		            //printf("S:%d", i);
					uip_arp_out ();
		            enc28j60Send ();
		          }
		        }

		#if UIP_UDP_KU
		        for (i = 0; i < UIP_UDP_CONNS; i++)
		        {
		          uip_udp_periodic (i);

		          /* If the above function invocation resulted in data that
		             should be sent out on the network, the global variable
		             uip_len is set to a value > 0. */
		          if (uip_len > 0)
		          {
		            uip_arp_out ();
		            enc28j60Send ();
		          }
		        }
		#endif /* UIP_UDP */

		        /* Periodically call the ARP timer function. */
		        if (++xARPTimer == uipARP_FREQUENCY)
		        {
		          uip_arp_timer ();
		          xARPTimer = 0;
		        }
		      }
			  
			  	if ((xCurrentTime - timer_menit) >= RT_MENIT)
			  	{
				  	extern unsigned int error_ENC;
					
					timer_menit = xCurrentTime;
					loop_menit++;				
					/*
					printf("%d menit, paket = %d, kita=%d, idle=%d\n", loop_menit, paket_per_menit, paket_kita, loop_idle);
					if (error_ENC != 0)
					{
						printf("ERR ENC = %X\n", error_ENC);	
					}*/
					
					paket_per_menit = 0;
					paket_kita = 0;
				}
		 }	// tanpa paket
		
		/*
		// proses ADC dipindah ke shell 1 Okt 2010// 
		#ifdef PAKAI_ADC
			#ifdef BOARD_KOMON_A_RTD
			proses_data_adc();
			#endif
			 
			#ifdef BOARD_KOMON_B_THERMO
			proses_data_adc();
			#endif
			 
			#ifdef BOARD_KOMON_420_SAJA
			proses_data_adc();
			#endif
		#endif
		//*/
	#endif
	}
}
예제 #27
0
/*---------------------------------------------------------------------------*/
int
main(void)
{
  clock_init();
#if UIP_CONF_IPV6
/* A hard coded address overrides the stack default MAC address to
   allow multiple instances. uip6.c defines it as
   {0x00,0x06,0x98,0x00,0x02,0x32} giving an ipv6 address of
   [fe80::206:98ff:fe00:232] We make it simpler, {0x02,0x00,0x00 + the
   last three bytes of the hard coded address (if any are nonzero).
   HARD_CODED_ADDRESS can be defined in the contiki-conf.h file, or
   here to allow quick builds using different addresses.  If
   HARD_CODED_ADDRESS has a prefix it also applied, unless built as a
   RPL end node.  E.g. bbbb::12:3456 becomes fe80::ff:fe12:3456 and
   prefix bbbb::/64 if non-RPL ::10 becomes fe80::ff:fe00:10 and
   prefix awaits RA or RPL formation bbbb:: gives an address of
   bbbb::206:98ff:fe00:232 if non-RPL */
#ifdef HARD_CODED_ADDRESS
  {
  uip_ipaddr_t ipaddr;
  uiplib_ipaddrconv(HARD_CODED_ADDRESS, &ipaddr);
  if((ipaddr.u8[13] != 0) ||
     (ipaddr.u8[14] != 0) ||
     (ipaddr.u8[15] != 0)) {
    if(sizeof(uip_lladdr) == 6) {  /* Minimal-net uses ethernet MAC */
      uip_lladdr.addr[0] = 0x02;
      uip_lladdr.addr[1] = 0;
      uip_lladdr.addr[2] = 0;
      uip_lladdr.addr[3] = ipaddr.u8[13];
      uip_lladdr.addr[4] = ipaddr.u8[14];
      uip_lladdr.addr[5] = ipaddr.u8[15];
    }
  }
 }
#endif /* HARD_CODED_ADDRESS */
#endif /* UIP_CONF_IPV6 */

  process_init();
/* procinit_init initializes RPL which sets a ctimer for the first DIS */
/* We must start etimers and ctimers,before calling it */
  process_start(&etimer_process, NULL);
  ctimer_init();

#if RPL_BORDER_ROUTER
  process_start(&border_router_process, NULL);
  printf("Border Router Process started\n");
#elif UIP_CONF_IPV6_RPL
  printf("RPL enabled\n");
#endif

  procinit_init();
  autostart_start(autostart_processes); 

  /* Set default IP addresses if not specified */
#if !UIP_CONF_IPV6
  {
    uip_ipaddr_t addr;

    uip_gethostaddr(&addr);
    if(addr.u8[0] == 0) {
      uip_ipaddr(&addr, 10,1,1,2);
    }
    printf("IP Address:  %d.%d.%d.%d\n", uip_ipaddr_to_quad(&addr));
    uip_sethostaddr(&addr);
    
    uip_getnetmask(&addr);
    if(addr.u8[0] == 0) {
      uip_ipaddr(&addr, 255,255,255,0);
      uip_setnetmask(&addr);
    }
    printf("Subnet Mask: %d.%d.%d.%d\n", uip_ipaddr_to_quad(&addr));
    
    uip_getdraddr(&addr);
    if(addr.u8[0] == 0) {
      uip_ipaddr(&addr, 10,1,1,1);
      uip_setdraddr(&addr);
    }
    printf("Def. Router: %d.%d.%d.%d\n", uip_ipaddr_to_quad(&addr));
  }
#else /* UIP_CONF_IPV6 */

#if !UIP_CONF_IPV6_RPL
  {
    uip_ipaddr_t ipaddr;
#ifdef HARD_CODED_ADDRESS
    uiplib_ipaddrconv(HARD_CODED_ADDRESS, &ipaddr);
#else
    uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
#endif
    if((ipaddr.u16[0] != 0) ||
       (ipaddr.u16[1] != 0) ||
       (ipaddr.u16[2] != 0) ||
       (ipaddr.u16[3] != 0)) {
#if UIP_CONF_ROUTER
      uip_ds6_prefix_add(&ipaddr, UIP_DEFAULT_PREFIX_LEN, 0, 0, 0, 0);
#else /* UIP_CONF_ROUTER */
      uip_ds6_prefix_add(&ipaddr, UIP_DEFAULT_PREFIX_LEN, 0);
#endif /* UIP_CONF_ROUTER */

      uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
      uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);
    }
  }
#endif /* !UIP_CONF_IPV6_RPL */

#endif /* !UIP_CONF_IPV6 */

 // procinit_init();
 // autostart_start(autostart_processes); 

  /* Make standard output unbuffered. */
  setvbuf(stdout, (char *)NULL, _IONBF, 0);

  printf("\n*******%s online*******\n",CONTIKI_VERSION_STRING);

#if UIP_CONF_IPV6 && !RPL_BORDER_ROUTER  /* Border router process prints addresses later */
  {
    uint8_t i;
    for(i = 0; i < UIP_DS6_ADDR_NB; i++) {
      if(uip_ds6_if.addr_list[i].isused) {
	printf("IPV6 Addresss: ");
	sprint_ip6(uip_ds6_if.addr_list[i].ipaddr);
	printf("\n");
      }
    }
  }
#endif

  while(1) {
    fd_set fds;
    int n;
    struct timeval tv;
    
    n = process_run();

    tv.tv_sec = 0;
    tv.tv_usec = 1000;
    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    select(1, &fds, NULL, NULL, &tv);

    if(FD_ISSET(STDIN_FILENO, &fds)) {
      char c;
      if(read(STDIN_FILENO, &c, 1) > 0) {
	serial_line_input_byte(c);
      }
    }
    etimer_request_poll();
  }
  
  return 0;
}
예제 #28
0
/*---------------------------------------------------------------------------*/
int
main(int argc, char **argv)
{
  /*
   * Initalize hardware.
   */
  msp430_cpu_init();
  clock_init();
  leds_init();
  leds_on(LEDS_RED);

  uart1_init(BAUD2UBR(115200)); /* Must come before first printf */
#if WITH_UIP
  slip_arch_init(BAUD2UBR(115200));
#endif /* WITH_UIP */

  leds_on(LEDS_GREEN);
  ds2411_init();

  /* XXX hack: Fix it so that the 802.15.4 MAC address is compatible
     with an Ethernet MAC address - byte 0 (byte 2 in the DS ID)
     cannot be odd. */
  ds2411_id[2] &= 0xfe;
  
  leds_on(LEDS_BLUE);
  xmem_init();

  leds_off(LEDS_RED);
  rtimer_init();
  /*
   * Hardware initialization done!
   */

  
  /* Restore node id if such has been stored in external mem */
  node_id_restore();

  random_init(ds2411_id[0] + node_id);
  
  leds_off(LEDS_BLUE);
  /*
   * Initialize Contiki and our processes.
   */
  process_init();
  process_start(&etimer_process, NULL);
  process_start(&sensors_process, NULL);

  /*
   * Initialize light and humidity/temp sensors.
   */
  sensors_light_init();
  battery_sensor.activate();
  sht11_init();

  ctimer_init();

  cc2420_init();
  cc2420_set_pan_addr(IEEE802154_PANID, 0 /*XXX*/, ds2411_id);
  cc2420_set_channel(RF_CHANNEL);

  printf(CONTIKI_VERSION_STRING " started. ");
  if(node_id > 0) {
    printf("Node id is set to %u.\n", node_id);
  } else {
    printf("Node id is not set.\n");
  }
  set_rime_addr();
  printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
	 ds2411_id[0], ds2411_id[1], ds2411_id[2], ds2411_id[3],
	 ds2411_id[4], ds2411_id[5], ds2411_id[6], ds2411_id[7]);

#if WITH_UIP6
  memcpy(&uip_lladdr.addr, ds2411_id, sizeof(uip_lladdr.addr));
  sicslowpan_init(sicslowmac_init(&cc2420_driver));
  process_start(&tcpip_process, NULL);
  printf(" %s channel %u\n", sicslowmac_driver.name, RF_CHANNEL);
#if UIP_CONF_ROUTER
  rime_init(rime_udp_init(NULL));
  uip_router_register(&rimeroute);
#endif /* UIP_CONF_ROUTER */
#else /* WITH_UIP6 */
  rime_init(MAC_DRIVER.init(&cc2420_driver));
  printf(" %s channel %u\n", rime_mac->name, RF_CHANNEL);
#endif /* WITH_UIP6 */

#if !WITH_UIP && !WITH_UIP6
  uart1_set_input(serial_line_input_byte);
  serial_line_init();
#endif

#if PROFILE_CONF_ON
  profile_init();
#endif /* PROFILE_CONF_ON */

  leds_off(LEDS_GREEN);

#if WITH_FTSP
  ftsp_init();
#endif /* WITH_FTSP */

#if TIMESYNCH_CONF_ENABLED
  timesynch_init();
  timesynch_set_authority_level(rimeaddr_node_addr.u8[0]);
#endif /* TIMESYNCH_CONF_ENABLED */

#if WITH_UIP
  process_start(&tcpip_process, NULL);
  process_start(&uip_fw_process, NULL);	/* Start IP output */
  process_start(&slip_process, NULL);

  slip_set_input_callback(set_gateway);

  {
    uip_ipaddr_t hostaddr, netmask;

    uip_init();

    uip_ipaddr(&hostaddr, 172,16,
	       rimeaddr_node_addr.u8[0],rimeaddr_node_addr.u8[1]);
    uip_ipaddr(&netmask, 255,255,0,0);
    uip_ipaddr_copy(&meshif.ipaddr, &hostaddr);

    uip_sethostaddr(&hostaddr);
    uip_setnetmask(&netmask);
    uip_over_mesh_set_net(&hostaddr, &netmask);
    /*    uip_fw_register(&slipif);*/
    uip_over_mesh_set_gateway_netif(&slipif);
    uip_fw_default(&meshif);
    uip_over_mesh_init(UIP_OVER_MESH_CHANNEL);
    printf("uIP started with IP address %d.%d.%d.%d\n",
	   uip_ipaddr_to_quad(&hostaddr));
  }
#endif /* WITH_UIP */

  button_sensor.activate();

  energest_init();
  ENERGEST_ON(ENERGEST_TYPE_CPU);

  print_processes(autostart_processes);
  autostart_start(autostart_processes);

  /*
   * This is the scheduler loop.
   */
#if DCOSYNCH_CONF_ENABLED
  timer_set(&mgt_timer, DCOSYNCH_PERIOD * CLOCK_SECOND);
#endif
  watchdog_start();
  /*  watchdog_stop();*/
  while(1) {
    int r;
#if PROFILE_CONF_ON
    profile_episode_start();
#endif /* PROFILE_CONF_ON */
    do {
      /* Reset watchdog. */
      watchdog_periodic();
      r = process_run();
    } while(r > 0);
#if PROFILE_CONF_ON
    profile_episode_end();
#endif /* PROFILE_CONF_ON */

    /*
     * Idle processing.
     */
    int s = splhigh();		/* Disable interrupts. */
    /* uart1_active is for avoiding LPM3 when still sending or receiving */
    if(process_nevents() != 0 || uart1_active()) {
      splx(s);			/* Re-enable interrupts. */
    } else {
      static unsigned long irq_energest = 0;

#if DCOSYNCH_CONF_ENABLED
      /* before going down to sleep possibly do some management */
      if (timer_expired(&mgt_timer)) {
	timer_reset(&mgt_timer);
	msp430_sync_dco();
      }
#endif

      /* Re-enable interrupts and go to sleep atomically. */
      ENERGEST_OFF(ENERGEST_TYPE_CPU);
      ENERGEST_ON(ENERGEST_TYPE_LPM);
      /* We only want to measure the processing done in IRQs when we
	 are asleep, so we discard the processing time done when we
	 were awake. */
      energest_type_set(ENERGEST_TYPE_IRQ, irq_energest);
      watchdog_stop();
      _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This
					      statement will block
					      until the CPU is
					      woken up by an
					      interrupt that sets
					      the wake up flag. */

      /* We get the current processing time for interrupts that was
	 done during the LPM and store it for next time around.  */
      dint();
      irq_energest = energest_type_time(ENERGEST_TYPE_IRQ);
      eint();
      watchdog_start();
      ENERGEST_OFF(ENERGEST_TYPE_LPM);
      ENERGEST_ON(ENERGEST_TYPE_CPU);
    }
  }

  return 0;
}
예제 #29
0
void vuIP_Task( void *pvParameters )
{
portBASE_TYPE i;
uip_ipaddr_t xIPAddr;
struct timer periodic_timer, arp_timer;
extern void ( vEMAC_ISR_Wrapper )( void );

	/* Create the semaphore used by the ISR to wake this task. */
	vSemaphoreCreateBinary( xEMACSemaphore );
	
	/* Initialise the uIP stack. */
	timer_set( &periodic_timer, configTICK_RATE_HZ / 2 );
	timer_set( &arp_timer, configTICK_RATE_HZ * 10 );
	uip_init();
	uip_ipaddr( xIPAddr, uipIP_ADDR0, uipIP_ADDR1, uipIP_ADDR2, uipIP_ADDR3 );
	uip_sethostaddr( xIPAddr );
	httpd_init();

	/* Initialise the MAC. */
	while( Init_EMAC() != pdPASS )
    {
        vTaskDelay( uipINIT_WAIT );
    }

	portENTER_CRITICAL();
	{
		MAC_INTENABLE = INT_RX_DONE;
        VICIntEnable |= 0x00200000;
        VICVectAddr21 = ( portLONG ) vEMAC_ISR_Wrapper;
		prvSetMACAddress();
	}
	portEXIT_CRITICAL();
	

	for( ;; )
	{
		/* Is there received data ready to be processed? */
		uip_len = uiGetEMACRxData( uip_buf );
		
		if( uip_len > 0 )
		{
			/* Standard uIP loop taken from the uIP manual. */
			if( xHeader->type == htons( UIP_ETHTYPE_IP ) )
			{
				uip_arp_ipin();
				uip_input();

				/* If the above function invocation resulted in data that 
				should be sent out on the network, the global variable 
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					uip_arp_out();
					prvENET_Send();
				}
			}
			else if( xHeader->type == htons( UIP_ETHTYPE_ARP ) )
			{
				uip_arp_arpin();

				/* If the above function invocation resulted in data that 
				should be sent out on the network, the global variable 
				uip_len is set to a value > 0. */
				if( uip_len > 0 )
				{
					prvENET_Send();
				}
			}
		}
		else
		{
			if( timer_expired( &periodic_timer ) )
			{
				timer_reset( &periodic_timer );
				for( i = 0; i < UIP_CONNS; i++ )
				{
					uip_periodic( i );
	
					/* If the above function invocation resulted in data that 
					should be sent out on the network, the global variable 
					uip_len is set to a value > 0. */
					if( uip_len > 0 )
					{
						uip_arp_out();
						prvENET_Send();
					}
				}	
	
				/* Call the ARP timer function every 10 seconds. */
				if( timer_expired( &arp_timer ) )
				{
					timer_reset( &arp_timer );
					uip_arp_timer();
				}
			}
			else
			{			
				/* We did not receive a packet, and there was no periodic
				processing to perform.  Block for a fixed period.  If a packet
				is received during this period we will be woken by the ISR
				giving us the Semaphore. */
				xSemaphoreTake( xEMACSemaphore, configTICK_RATE_HZ / 2 );			
			}
		}
	}
}
예제 #30
0
void
network_init(void)
{
    uip_ipaddr_t ip;
    (void) ip;			/* Keep GCC quiet. */

    uip_init();

#if defined(RFM12_IP_SUPPORT) && defined(UIP_MULTI_STACK)
    uip_stack_set_active(STACK_RFM12);
    rfm12_stack_init();
#endif

#if defined(ZBUS_SUPPORT) && defined(UIP_MULTI_STACK)
    uip_stack_set_active(STACK_ZBUS);
    zbus_stack_init();
#endif

#ifdef OPENVPN_SUPPORT
    uip_stack_set_active(STACK_OPENVPN);
    openvpn_init();
#endif

    /* load base network settings */
#   ifdef DEBUG_NET_CONFIG
    debug_printf("net: loading base network settings\n");
#   endif

#   ifdef ENC28J60_SUPPORT
    uip_stack_set_active(STACK_ENC);

    /* use uip buffer as generic space here, since when this function is called,
     * no network packets will be processed */

#ifdef EEPROM_SUPPORT
    /* use global network packet buffer for configuration */
    uint8_t checksum = eeprom_get_chksum();
    uint8_t saved_checksum;
    eeprom_restore_char(crc, &saved_checksum);


    if (checksum != saved_checksum)
      eeprom_init();
#endif

#ifdef ENC28J60_SUPPORT
    network_config_load();
#endif



    /* Do the autoconfiguration after the MAC is set */
#   if UIP_CONF_IPV6 && !defined(IPV6_STATIC_SUPPORT)
    uip_setprefixlen(64);
    uip_ip6autoconfig(0xFE80, 0x0000, 0x0000, 0x0000);
#   endif

#   if defined(IPV6_STATIC_SUPPORT) && defined(TFTPOMATIC_SUPPORT)
    const unsigned char *filename = CONF_TFTP_IMAGE;
    set_CONF_TFTP_IP(&ip);

    tftp_fire_tftpomatic(&ip, filename);
    bootload_delay = CONF_BOOTLOAD_DELAY;
#   endif /* IPV6_STATIC_SUPPORT && TFTPOMATIC_SUPPORT */


#   elif !defined(ROUTER_SUPPORT) /* and not ENC28J60_SUPPORT */
    /* Don't allow for eeprom-based configuration of rfm12/zbus IP address,
       mainly for code size reasons. */
    set_CONF_ETHERRAPE_IP(&ip);
    uip_sethostaddr(&ip);

#   endif /* not ENC28J60_SUPPORT and not ROUTER_SUPPORT */

    ethersex_meta_netinit();

#   ifdef ENC28J60_SUPPORT
    init_enc28j60();
#   if UIP_CONF_IPV6
    uip_neighbor_init();
#   else
    uip_arp_init();
#   endif
#   endif

}