//*****************************************************************************************************************************
//*****************************************************************************************************************************
//*****************************************************************************************************************************
void waitForConnection(void)
{
	setup_data_packet_header();

	//RESET ADC and DMA:
	refresh_ADC();
	ADC_STATE = HALTED;
	//RESET DMA STATE.
	refresh_DMA();
	DMA_STATE = HALTED;

    if(currentCC3000State() & CC3000_SERVER_INIT) 	// Check whether the server functionality is successfully initialized
    {
        while(1) 									// Begin waiting for client and handle the connection
        {
            hci_unsolicited_event_handler();
            addrlen = sizeof(clientaddr);
            
            // accept blocks until we receive a connection
			while ( (clientDescriptor == -1) || (clientDescriptor == -2) )
			{
				clientDescriptor = accept(serverSocket, (sockaddr *) &clientaddr, &addrlen);
			}
            hci_unsolicited_event_handler();

            if(clientDescriptor >= 0)				// Connection Accepted, Wait for data exchange
            {
                setCC3000MachineState(CC3000_CLIENT_CONNECTED);
                unsolicicted_events_timer_disable();
                //**********************
                // Important Function. Manages incoming Message aswell as initiating outgoing message.
                incomingPacketManager();
                //**********************


			}
            else if(clientDescriptor == SOCKET_INACTIVE_ERR)
            {
				clientDescriptor = -1;
                // Reinitialize the server
                shutdownServer();
                initServer();
            }
            if(bytesRecvd < 0){check_socket_connection();} //If the recieve function goes inactive, shuts down. This checks for that case
            hci_unsolicited_event_handler();
        }
    }
}
Beispiel #2
0
//*****************************************************************************
//
//!  SpiReceiveHandler
//!
//!  @param         pvBuffer - pointer to the received data buffer
//!                      The function triggers Received event/data processing
//!
//!  @param         Pointer to the received data
//!  @return        none
//!
//!  @brief         The function triggers Received event/data processing. It is
//! 			          called from the SPI library to receive the data
//
//*****************************************************************************
void SpiReceiveHandler(void *pvBuffer)
{
    tSLInformation.usEventOrDataReceived = 1;
    tSLInformation.pucReceivedData = (unsigned char 	*)pvBuffer;

    hci_unsolicited_event_handler();
}
void main(void)
{
    WDTCTL = WDTPW + WDTHOLD;				// Stop WDT
    resetCC3000StateMachine();				// Start CC3000 State Machine
    initDriver();							// Initialize Board and CC3000
    unsolicicted_events_timer_init();		// Initialize CC3000 Unsolicited Events Timer
    __enable_interrupt();					// Enable interrupts for UART
    DefaultWifiConnection();				// Do a default connection

    while (1)
    {

        hci_unsolicited_event_handler();	// Handle any un-solicited event if required - the function shall be triggered few times in a second
        unsolicicted_events_timer_init();

        if(currentCC3000State() & CC3000_IP_ALLOC)
        {
            turnLedOn(CC3000_IP_ALLOC_IND);
            unsolicicted_events_timer_disable();
            
            // Attempt to start data server
            initServer();
            if(currentCC3000State() & CC3000_SERVER_INIT)
            {
                waitForConnection();
            }
            else//Wait for a bit, and try again.
            {
                __delay_cycles(100000);
            }
            unsolicicted_events_timer_init();
        }
    }
}
//*****************************************************************************
//
//! exoHAL_SocketSend
//!
//!  \param  socket - socket handle; buffer - string buffer containing info to
//!          send; len - size of string in bytes;
//!
//!  \return Number of bytes sent
//!
//!  \brief  Sends data out the network interface
//
//*****************************************************************************
unsigned char
exoHAL_SocketSend(long socket, char * buffer, unsigned char len)
{
  int result;
  result = send(socket, buffer, (long)len, 0); //always set flags to 0 for CC3000
  hci_unsolicited_event_handler();
  return  (unsigned char)result;
}
Beispiel #5
0
//*****************************************************************************
//
//!  SpiReceiveHandler
//!
//!  @param         pvBuffer - pointer to the received data buffer
//!                      The function triggers Received event/data processing
//!                 
//!  @param         Pointer to the received data
//!  @return        none
//!
//!  @brief         The function triggers Received event/data processing. It is 
//! 			          called from the SPI library to receive the data
//
//*****************************************************************************
void SpiReceiveHandler(void *pvBuffer)
{	
	tSLInformation.usEventOrDataReceived = 1;
	tSLInformation.pucReceivedData = (unsigned char 	*)pvBuffer;
//	TM_DEBUG("processing spi recieve handler %ul", (unsigned char *)tSLInformation.pucReceivedData[0]);
	
	hci_unsolicited_event_handler();
}
Beispiel #6
0
//*****************************************************************************
//
//!  SpiReceiveHandler
//!
//!  @param         pvBuffer - pointer to the received data buffer
//!                      The function triggers Received event/data processing
//!                 
//!  @param         Pointer to the received data
//!  @return        none
//!
//!  @brief         The function triggers Received event/data processing. It is 
//! 			          called from the SPI library to receive the data
//
//*****************************************************************************
void SpiReceiveHandler(void *pvBuffer)
{	
	// if (DEBUG_MODE) {
	// 			digitalWrite(DEBUG_LED, HIGH);
	// 		}
	tSLInformation.usEventOrDataReceived = 1;
	tSLInformation.pucReceivedData = (unsigned char 	*)pvBuffer;
	
	hci_unsolicited_event_handler();
}
void SpiReceiveHandler(void *pvBuffer)
{
  tSLInformation.pucReceivedData = (uint8_t *)pvBuffer;
  tSLInformation.usEventOrDataReceived = 1;

  uint16_t event_type;
  STREAM_TO_UINT16((char *)tSLInformation.pucReceivedData, HCI_EVENT_OPCODE_OFFSET,event_type);
  nllvdbg("Evtn:0x%x\n", event_type);

  hci_unsolicited_event_handler();
}
Beispiel #8
0
//*****************************************************************************
//
// The interrupt handler for the SysTick timer.  This handler is called every 1ms
// 
//
//*****************************************************************************
void
SysTickHandler(void)
{
    static unsigned long ulTickCount = 0;
    //
    // Increment the tick counter.
    //
    ulTickCount++;
    //Process after 500 ms
    if(ulTickCount >= 500)
    {
        //
        // Handle any un-solicited event if required - the function shall be triggered 
        // few times in a second
        //
        hci_unsolicited_event_handler();
        ulTickCount = 1;
    }
}
Beispiel #9
0
void SimpleLinkWaitData(uint8_t *pBuf, uint8_t *from, uint8_t *fromlen)
{
  /* In the blocking implementation the control to caller will be returned only
   * after the end of current transaction, i.e. only after data will be received
   */

  nllvdbg("Looking for Data\n");
  uint16_t event_type;
  uint16_t opcode = tSLInformation.usRxEventOpcode;

  do
    {
      tSLInformation.pucReceivedData = cc3000_wait();
      tSLInformation.usEventOrDataReceived = 1;

      if (*tSLInformation.pucReceivedData == HCI_TYPE_DATA)
        {
          tSLInformation.usRxDataPending = 1;
          hci_event_handler(pBuf, from, fromlen);
          break;
        }
      else
        {
          STREAM_TO_UINT16((char *)tSLInformation.pucReceivedData, HCI_EVENT_OPCODE_OFFSET, event_type);
          nllvdbg("Evtn:0x%x\n", event_type);

          if (hci_unsolicited_event_handler() == 1)
            {
              nllvdbg("Processed Event  0x%x want Data! Opcode 0x%x\n", event_type, opcode);
            }
          else
            {
              nllvdbg("!!!!!opcode 0x%x\n", opcode);
            }

          UNUSED(event_type);
        }
    }
  while (*tSLInformation.pucReceivedData == HCI_TYPE_EVNT);

  nllvdbg("Done for Data 0x%x\n", opcode);
  UNUSED(opcode);
}
Beispiel #10
0
void SimpleLinkWaitEvent(uint16_t opcode, void *pRetParams)
{
  /* In the blocking implementation the control to caller will be returned only
   * after the end of current transaction
   */

  tSLInformation.usRxEventOpcode = opcode;
  nllvdbg("Looking for opcode 0x%x\n", opcode);
  uint16_t event_type;

  do
    {
      nllvdbg("cc3000_wait\n");
      tSLInformation.pucReceivedData = cc3000_wait();
      tSLInformation.usEventOrDataReceived = 1;
      STREAM_TO_UINT16((FAR char *)tSLInformation.pucReceivedData,
                       HCI_EVENT_OPCODE_OFFSET, event_type);

      if (*tSLInformation.pucReceivedData == HCI_TYPE_EVNT)
        {
          nllvdbg("Evtn:0x%x\n", event_type);
        }

      if (event_type != opcode)
        {
          if (hci_unsolicited_event_handler() == 1)
            {
              nllvdbg("Processed Event  0x%x want 0x%x\n", event_type, opcode);
            }
        }
      else
        {
          nllvdbg("Processing opcode 0x%x\n", opcode);
          hci_event_handler(pRetParams, 0, 0);
        }
    }
  while (tSLInformation.usRxEventOpcode != 0);

  nllvdbg("Done for opcode 0x%x\n", opcode);
}
Beispiel #11
0
/*******************************************************************************
 * Function Name  : Start_Smart_Config.
 * Description    : The function triggers a smart configuration process on CC3000.
 * Input          : None.
 * Output         : None.
 * Return         : None.
 *******************************************************************************/
void Start_Smart_Config(void)
{
	WLAN_SMART_CONFIG_FINISHED = 0;
	WLAN_SMART_CONFIG_STOP = 0;
	WLAN_SERIAL_CONFIG_DONE = 0;
	WLAN_CONNECTED = 0;
	WLAN_DHCP = 0;
	WLAN_CAN_SHUTDOWN = 0;

	SPARK_SOCKET_CONNECTED = 0;
	SPARK_HANDSHAKE_COMPLETED = 0;
	SPARK_FLASH_UPDATE = 0;
	SPARK_LED_FADE = 0;

	LED_SetRGBColor(RGB_COLOR_BLUE);
	LED_On(LED_RGB);

	/* Reset all the previous configuration */
	wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE);

	NVMEM_Spark_File_Data[WLAN_POLICY_FILE_OFFSET] = 0;
	nvmem_write(NVMEM_SPARK_FILE_ID, 1, WLAN_POLICY_FILE_OFFSET, &NVMEM_Spark_File_Data[WLAN_POLICY_FILE_OFFSET]);

	/* Wait until CC3000 is disconnected */
	while (WLAN_CONNECTED == 1)
	{
		//Delay 100ms
		Delay(100);
		hci_unsolicited_event_handler();
	}

	/* Create new entry for AES encryption key */
	nvmem_create_entry(NVMEM_AES128_KEY_FILEID,16);

	/* Write AES key to NVMEM */
	aes_write_key((unsigned char *)(&smartconfigkey[0]));

	wlan_smart_config_set_prefix((char*)aucCC3000_prefix);

	/* Start the SmartConfig start process */
	wlan_smart_config_start(1);

	WiFiCredentialsReader wifi_creds_reader(wifi_add_profile_callback);

	/* Wait for SmartConfig/SerialConfig to finish */
	while (!(WLAN_SMART_CONFIG_FINISHED | WLAN_SERIAL_CONFIG_DONE))
	{
		if(WLAN_DELETE_PROFILES && wlan_ioctl_del_profile(255) == 0)
		{
			int toggle = 25;
			while(toggle--)
			{
				LED_Toggle(LED_RGB);
				Delay(50);
			}
			NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET] = 0;
			nvmem_write(NVMEM_SPARK_FILE_ID, 1, WLAN_PROFILE_FILE_OFFSET, &NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET]);
			WLAN_DELETE_PROFILES = 0;
		}
		else
		{
			LED_Toggle(LED_RGB);
			Delay(250);
			wifi_creds_reader.read();
		}
	}

	LED_On(LED_RGB);

	/* read count of wlan profiles stored */
	nvmem_read(NVMEM_SPARK_FILE_ID, 1, WLAN_PROFILE_FILE_OFFSET, &NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET]);

//	if(NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET] >= 7)
//	{
//		if(wlan_ioctl_del_profile(255) == 0)
//			NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET] = 0;
//	}

	if(WLAN_SMART_CONFIG_FINISHED)
	{
		/* Decrypt configuration information and add profile */
		wlan_profile_index = wlan_smart_config_process();
	}

	if(wlan_profile_index != -1)
	{
		NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET] = wlan_profile_index + 1;
	}

	/* write count of wlan profiles stored */
	nvmem_write(NVMEM_SPARK_FILE_ID, 1, WLAN_PROFILE_FILE_OFFSET, &NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET]);

	/* Configure to connect automatically to the AP retrieved in the Smart config process */
	wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE);

	NVMEM_Spark_File_Data[WLAN_POLICY_FILE_OFFSET] = 1;
	nvmem_write(NVMEM_SPARK_FILE_ID, 1, WLAN_POLICY_FILE_OFFSET, &NVMEM_Spark_File_Data[WLAN_POLICY_FILE_OFFSET]);

	/* Reset the CC3000 */
	wlan_stop();

	Delay(100);

	wlan_start(0);

	SPARK_WLAN_STARTED = 1;

	/* Mask out all non-required events */
	wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE | HCI_EVNT_WLAN_UNSOL_INIT | HCI_EVNT_WLAN_ASYNC_PING_REPORT);

    LED_SetRGBColor(RGB_COLOR_GREEN);
	LED_On(LED_RGB);

	Set_NetApp_Timeout();

	WLAN_SMART_CONFIG_START = 0;
}
Beispiel #12
0
//*****************************************************************************
//
//!  checkWiFiConnected
//!
//!  \param  None
//!
//!  \return TRUE if connected, FALSE if not
//!
//!  \brief  Checks to see that WiFi is still connected.  If not associated
//!          with an AP for 5 consecutive retries, it will reset the board.
//
//*****************************************************************************
unsigned char
checkWiFiConnected(void)
{
  unsigned char ipInfoFlagSet = 0;

  if(!(currentCC3000State() & CC3000_ASSOC)) //try to associate with an Access Point
  {
    //
    // Check whether Smart Config was run previously. If it was, we
    // use it to connect to an access point. Otherwise, we connect to the
    // default.
    //

    if((isFTCSet() == 0)&&(ConnectUsingSmartConfig==0)&&(*SmartConfigProfilestored != SMART_CONFIG_SET))
    {
      // Smart Config not set, check whether we have an SSID
      // from the assoc terminal command. If not, use fixed SSID.
        //sendString("== ConnectUsingSSID==\r\n");
        ConnectUsingSSID(SSID);
    }
    unsolicicted_events_timer_init();
    // Wait until connection is finished
    //sendString("== Wait until connection is finished==\r\n");
    while (!(currentCC3000State() & CC3000_ASSOC))
    {
      WDTCTL = WDT_ARST_1000;
      __delay_cycles(100);

      // Handle any un-solicited event if required - the function will get triggered
      // few times in a second
      hci_unsolicited_event_handler();

      // Check if user pressed button to do Smart Config
      if(runSmartConfig == 1)
          break;
    }
  }

  // Handle un-solicited events - will be triggered few times per second
  hci_unsolicited_event_handler();
  WDTCTL = WDTPW + WDTHOLD;
  // Check if we are in a connected state.  If so, set flags and LED
  if(currentCC3000State() & CC3000_IP_ALLOC)
  {
    unsolicicted_events_timer_disable(); // Turn our timer off since isr-driven routines set LEDs too...

    if (obtainIpInfoFlag == FALSE)
    {
      //sendString("== CC3000_IP_ALLOC_IND==\r\n");
      obtainIpInfoFlag = TRUE;             // Set flag so we don't constantly turn the LED on
      turnLedOn(CC3000_IP_ALLOC_IND);
      ipInfoFlagSet = 1;
      unsolicicted_events_timer_init();
    }

    if (obtainIpInfoFlag == TRUE)
    {
    	WDTCTL = WDT_ARST_1000;
      //If Smart Config was performed, we need to send complete notification to the configure (Smart Phone App)
      if (ConnectUsingSmartConfig==1)
      {
        mdnsAdvertiser(1,DevServname, sizeof(DevServname));
        ConnectUsingSmartConfig = 0;
        *SmartConfigProfilestored = SMART_CONFIG_SET;
      }
      //Start mDNS timer in order to send mDNS Advertisement every 30 seconds
      mDNS_packet_trigger_timer_enable();

      unsolicicted_events_timer_init();
    }
    WDTCTL = WDTPW + WDTHOLD;
    if( ipInfoFlagSet == 1)
    {
      // Initialize an Exosite connection
      //sendString("== Exosite Activate ==\r\n");
      cloud_status = Exosite_Activate();
      ipInfoFlagSet = 0;
    }

    return TRUE;
  }

  return FALSE;

}
Beispiel #13
0
//*****************************************************************************
//
//!  main
//!
//!  \param  None
//!
//!  \return none
//!
//!  \brief   The main loop is executed here
//
//*****************************************************************************
void main(void)
{
  unsigned char loopCount = 0;
  int loop_time = 2000;

  ulCC3000Connected = 0;
  SendmDNSAdvertisment = 0;

  // Initialize hardware and interfaces
  board_init();
  initUart();
  sendString("System init : \r\n");

  // Must initialize one time for MAC address prepare..
  if (!Exosite_Init("exosite", "cc3000wifismartconfig", IF_WIFI, 0))
  {
    show_status();
    while(1);
  }

  // Main Loop
  while (1)
  {
    // Perform Smart Config if button pressed in current run or if flag set in FRAM
    // from previous MSP430 Run.
    if(runSmartConfig == 1 || *ptrFtcAtStartup == SMART_CONFIG_SET)
    {
      // Clear flag
      ClearFTCflag();
      unsetCC3000MachineState(CC3000_ASSOC);

      // Start the Smart Config Process
      StartSmartConfig();
      runSmartConfig = 0;
    }

    WDTCTL = WDTPW + WDTHOLD;
    // If connectivity is good, run the primary functionality
    if(checkWiFiConnected())
    {
      char * pbuf = exo_buffer;

      //unsolicicted_events_timer_disable();

      if (0 == cloud_status)
      { //check to see if we have a valid connection
        loop_time = 2000;

        loopCount = 1;

        while (loopCount++ <= (WRITE_INTERVAL+1))
        {
//          WDTCTL = WDT_ARST_1000;
          if (Exosite_Read("led7_ctrl", pbuf, EXO_BUFFER_SIZE))
          {
        	// Read success
        	turnLedOn(CC3000_CLIENT_CONNECTED_IND);

            if (!strncmp(pbuf, "0", 1))
              turnLedOff(LED7);
            else if (!strncmp(pbuf, "1", 1))
              turnLedOn(LED7);
          }
          else
          {
        	if (EXO_STATUS_NOAUTH == Exosite_StatusCode())
        	{
        		turnLedOff(CC3000_CLIENT_CONNECTED_IND);
        		// Activate device again
        		cloud_status = Exosite_Activate();
        	}
          }

          hci_unsolicited_event_handler();
          unsolicicted_events_timer_init();
          //sendString("== Exosite Read==\r\n");
          WDTCTL = WDTPW + WDTHOLD;
          busyWait(loop_time);        //delay before looping again
        }

        unsolicicted_events_timer_init();
    	if (EXO_STATUS_NOAUTH != Exosite_StatusCode())
    	{
          unsigned char sensorCount = 0;
          int value;
          char strRead[6]; //largest value of an int in ascii is 5 + null terminate
          WDTCTL = WDT_ARST_1000;
          for (sensorCount = 0; sensorCount < SENSOR_END; sensorCount++)
          {
            value = getSensorResult(sensorCount);                                       //get the sensor reading
            itoa(value, strRead, 10);                           //convert to a string
            unsolicicted_events_timer_init();
            //for each reading / data source (alias), we need to build the string "alias=value" (must be URL encoded)
            //this is all just an iteration of, for example, Exosite_Write("mydata=hello_world",18);
            memcpy(pbuf,&sensorNames[sensorCount][0],strlen(&sensorNames[sensorCount][0]));  //copy alias name into buffer
            pbuf += strlen(&sensorNames[sensorCount][0]);
            *pbuf++ = 0x3d;                                             //put an '=' into buffer
            memcpy(pbuf,strRead, strlen(strRead));                      //copy value into buffer
            pbuf += strlen(strRead);
            *pbuf++ = 0x26;                                             //put an '&' into buffer, the '&' ties successive alias=val pairs together
          }
          pbuf--;                                                                       //back out the last '&'
          WDTCTL = WDT_ARST_1000;
          Exosite_Write(exo_buffer,(pbuf - exo_buffer - 1));    //write all sensor values to the cloud

          if (EXO_STATUS_OK == Exosite_StatusCode())
          { // Write success
    	    turnLedOn(CC3000_CLIENT_CONNECTED_IND);
          }
    	}
      } else {
          //we don't have a good connection yet - we keep retrying to authenticate
    	  WDTCTL = WDTPW + WDTHOLD;
          //sendString("== Exosite Activate==\r\n");
          cloud_status = Exosite_Activate();
          if (0 != cloud_status) loop_time = 30000; //delay 30 seconds before retrying...
      }

        unsolicicted_events_timer_init();
      }
      WDTCTL = WDTPW + WDTHOLD;
      // TODO - make this a sleep instead of busy wait
      busyWait(loop_time);        //delay before looping again
    }
}
/* TODO removed buffer, set it in init */
void cc3000_event::received_handler(uint8_t *buffer) {
    _simple_link.set_data_received_flag(1);
    _simple_link.set_received_data(buffer);

    hci_unsolicited_event_handler();
}
Beispiel #15
0
void StartSmartConfig(void)
{
	ulSmartConfigFinished = 0;
	ulCC3000Connected = 0;
	ulCC3000DHCP = 0;
	OkToDoShutDown=0;
	
	// Reset all the previous configuration
	wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE);	
	wlan_ioctl_del_profile(255);
	
	//Wait until CC3000 is disconnected
	while (ulCC3000Connected == 1)
	{
		SysCtlDelay(100);
		hci_unsolicited_event_handler();
	}
	
	// Start blinking LED1 during Smart Configuration process
	turnLedOn(1);
	
	wlan_smart_config_set_prefix((char*)aucCC3000_prefix);
	turnLedOff(1);		
	
	// Start the SmartConfig start process
	wlan_smart_config_start(1);
	turnLedOn(1);       
	
	// Wait for Smart config to finish
	while (ulSmartConfigFinished == 0)
	{
		turnLedOff(1);
		SysCtlDelay(16500000);
		turnLedOn(1);		  
		SysCtlDelay(16500000);
	}
	turnLedOn(1);	
	// create new entry for AES encryption key
	nvmem_create_entry(NVMEM_AES128_KEY_FILEID,16);
	
	// write AES key to NVMEM
	aes_write_key((unsigned char *)(&smartconfigkey[0]));
	
	// Decrypt configuration information and add profile
	wlan_smart_config_process();
	
	// Configure to connect automatically to the AP retrieved in the 
	// Smart config process
	wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE);
	
	
	// reset the CC3000
	wlan_stop();
	
	DispatcherUartSendPacket((unsigned char*)pucUARTCommandSmartConfigDoneString,
													 sizeof(pucUARTCommandSmartConfigDoneString));
	
	SysCtlDelay(100000);
	wlan_start(0);	
	
	// Mask out all non-required events
	wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_UNSOL_INIT|
											HCI_EVNT_WLAN_ASYNC_PING_REPORT);
}
Beispiel #16
0
//*****************************************************************************
//
//! DemoHandleUartCommand
//!
//!  @param  buffer
//!
//!  @return none
//!
//!  @brief  The function handles commands arrived from CLI
//
//*****************************************************************************
void
DemoHandleUartCommand(unsigned char *usBuffer)
{
	char *pcSsid, *pcData, *pcSockAddrAscii;
	unsigned long ulSsidLen, ulDataLength;
	volatile signed long iReturnValue;
	sockaddr tSocketAddr;
	socklen_t tRxPacketLength;
	unsigned char pucIP_Addr[4];
	unsigned char pucIP_DefaultGWAddr[4];
	unsigned char pucSubnetMask[4];
	unsigned char pucDNS[4];
	
	// usBuffer[0] contains always 0
	// usBuffer[1] maps the command
	// usBuffer[2..end] optional parameters
	switch(usBuffer[1])
	{
		// Start a smart configuration process
	case UART_COMMAND_CC3000_SIMPLE_CONFIG_START:
		StartSmartConfig();
		break;
		
		// Start a WLAN Connect process
	case UART_COMMAND_CC3000_CONNECT:
		{
			ulSsidLen = atoc(usBuffer[2]);
			pcSsid = (char *)&usBuffer[3];
			
#ifndef CC3000_TINY_DRIVER 		
			wlan_connect(WLAN_SEC_UNSEC, pcSsid, ulSsidLen,NULL, NULL, 0);
#else
			
			wlan_connect(pcSsid,ulSsidLen);
#endif
		} 
		break;
		
		
		// Handle open socket command
	case UART_COMMAND_SOCKET_OPEN:
		// wait for DHCP process to finish. if you are using a static IP address 
		// please delete the wait for DHCP event - ulCC3000DHCP 
		while ((ulCC3000DHCP == 0) || (ulCC3000Connected == 0))
		{
			hci_unsolicited_event_handler();
			
			SysCtlDelay(1000);
		}
		ulSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
		break;
		
		// Handle close socket command
	case UART_COMMAND_SOCKET_CLOSE:
		closesocket(ulSocket);
		ulSocket = 0xFFFFFFFF;
		break;
		
		
		// Handle receive data command
	case UART_COMMAND_RCV_DATA:
		iReturnValue = recvfrom(ulSocket, pucCC3000_Rx_Buffer, 
														CC3000_APP_BUFFER_SIZE, 0, &tSocketAddr, 
														&tRxPacketLength);
		if (iReturnValue <= 0)
		{
			// No data received by device
			DispatcherUartSendPacket((unsigned char*)pucUARTNoDataString, 
															 sizeof(pucUARTNoDataString));
		}
		else
		{
			// Send data to UART...
			DispatcherUartSendPacket(pucCC3000_Rx_Buffer, CC3000_APP_BUFFER_SIZE);
		}
		break;
		
		// Handle send data command
	case UART_COMMAND_SEND_DATA:
		
		// data pointer
		pcData = (char *)&usBuffer[4];
		
		// data length to send
		ulDataLength = atoshort(usBuffer[2], usBuffer[3]);
		pcSockAddrAscii = (pcData + ulDataLength);
		
		// the family is always AF_INET
		tSocketAddr.sa_family = atoshort(pcSockAddrAscii[0], pcSockAddrAscii[1]);
		
		// the destination port
		tSocketAddr.sa_data[0] = ascii_to_char(pcSockAddrAscii[2], pcSockAddrAscii[3]);
		tSocketAddr.sa_data[1] = ascii_to_char(pcSockAddrAscii[4], pcSockAddrAscii[5]);
		
		// the destination IP address
		tSocketAddr.sa_data[2] = ascii_to_char(pcSockAddrAscii[6], pcSockAddrAscii[7]);
		tSocketAddr.sa_data[3] = ascii_to_char(pcSockAddrAscii[8], pcSockAddrAscii[9]);
		tSocketAddr.sa_data[4] = ascii_to_char(pcSockAddrAscii[10], pcSockAddrAscii[11]);
		tSocketAddr.sa_data[5] = ascii_to_char(pcSockAddrAscii[12], pcSockAddrAscii[13]);
		
		sendto(ulSocket, pcData, ulDataLength, 0, &tSocketAddr, sizeof(sockaddr));
		break;
		
		// Handle bind command
	case UART_COMMAND_BSD_BIND:
		tSocketAddr.sa_family = AF_INET;
		
		// the source port
		tSocketAddr.sa_data[0] = ascii_to_char(usBuffer[2], usBuffer[3]);
		tSocketAddr.sa_data[1] = ascii_to_char(usBuffer[4], usBuffer[5]);
		
		// all 0 IP address
		memset (&tSocketAddr.sa_data[2], 0, 4);
		
		bind(ulSocket, &tSocketAddr, sizeof(sockaddr));
		
		break;
		
		// Handle IP configuration command
	case UART_COMMAND_IP_CONFIG:
		
		// Network mask is assumed to be 255.255.255.0
		pucSubnetMask[0] = 0xFF;
		pucSubnetMask[1] = 0xFF;
		pucSubnetMask[2] = 0xFF;
		pucSubnetMask[3] = 0x0;
		
		pucIP_Addr[0] = ascii_to_char(usBuffer[2], usBuffer[3]);
		pucIP_Addr[1] = ascii_to_char(usBuffer[4], usBuffer[5]);
		pucIP_Addr[2] = ascii_to_char(usBuffer[6], usBuffer[7]);
		pucIP_Addr[3] = ascii_to_char(usBuffer[8], usBuffer[9]);
		
		pucIP_DefaultGWAddr[0] = ascii_to_char(usBuffer[10], usBuffer[11]);
		pucIP_DefaultGWAddr[1] = ascii_to_char(usBuffer[12], usBuffer[13]);
		pucIP_DefaultGWAddr[2] = ascii_to_char(usBuffer[14], usBuffer[15]);
		pucIP_DefaultGWAddr[3] = ascii_to_char(usBuffer[16], usBuffer[17]);
		
		pucDNS[0] = 0;
		pucDNS[1] = 0;
		pucDNS[2] = 0;
		pucDNS[3] = 0;
		
		netapp_dhcp((unsigned long *)pucIP_Addr, (unsigned long *)pucSubnetMask, 
								(unsigned long *)pucIP_DefaultGWAddr, (unsigned long *)pucDNS);
		
		break;
		
		// Handle WLAN disconnect command
	case UART_COMMAND_CC3000_DISCONNECT:
		wlan_disconnect();
		break;
		
		// Handle erase policy command
	case UART_COMMAND_CC3000_DEL_POLICY:
		wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE);
		break;
		
		// Handle send DNS Discovery command
	case UART_COMMAND_SEND_DNS_ADVERTIZE:
		if(ulCC3000DHCP)
		{
			mdnsAdvertiser(1,device_name,strlen(device_name));
		}
		
		break;
		
	default:
		DispatcherUartSendPacket((unsigned char*)pucUARTIllegalCommandString, 
														 sizeof(pucUARTIllegalCommandString));
		break;
		
	}
	
	// Send a response - the command handling has finished
	DispatcherUartSendPacket((unsigned char *)(pucUARTCommandDoneString), 
													 sizeof(pucUARTCommandDoneString));
}
/*------------------------------------------------------------------------
  
  Spider_SmartConfig
  Use Smart config function set Spider connect to a exist AP.
  
  return  0, Connect success.
-----------------------------------------------------------------------*/
int Spider_SmartConfig(void){
    SmartConfigFinished = 0;
    SpiderConnected = 0;
    SpiderDHCP = 0;
    SpiderCanShutDown = 0;

    // Reset all the previous configuration
    wlan_ioctl_set_connection_policy(0, 0, 0);
    wlan_ioctl_del_profile(255);

    //Wait until Spider is disconnected
    while (SpiderConnected == 1){
        delay(1);
        hci_unsolicited_event_handler();
    }

    // create new entry for AES encryption key
    nvmem_create_entry(NVMEM_AES128_KEY_FILEID, AES128_KEY_SIZE);

    // write AES key to NVMEM
    aes_write_key((unsigned char *)(&SmartConfig_key[0]));

    // Start blinking LED1 during Smart Configuration process
    digitalWrite(13, HIGH);
    wlan_smart_config_set_prefix((char*)SmartConfig_prefix);
    digitalWrite(13, LOW);

    // Start the SmartConfig start process
    if(wlan_smart_config_start(0) != 0){
      return -1;
    }

    // Wait for Smart config to finish
    while (SmartConfigFinished == 0){
        digitalWrite(13, HIGH);
        delay(500);
        digitalWrite(13, LOW);
        delay(500);
    }
    digitalWrite(13, LOW);


    // Decrypt configuration information and add profile
    //wlan_smart_config_process();

#if 1
    // Configure to connect automatically to the AP retrieved in the
    // Smart config process
    wlan_ioctl_set_connection_policy(0, 0, 1);

    // reset the CC3000
    wlan_stop();

    delay(100);

    wlan_start(0);

    // Set CC3000 event masking, right now without ping report.
    wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_UNSOL_INIT|HCI_EVNT_WLAN_ASYNC_PING_REPORT);

#endif

    return 0;
}