//*****************************************************************************
//
//! initDriver
//!
//!  \param  None
//!
//!  \return none
//!
//!  \brief  The function initializes a CC3000 device and triggers it to start operation
//
//*****************************************************************************
int
initDriver(void)
{



    pio_init(); // Init GPIO's
    init_spi();
    wlan_init( CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch, sendBootLoaderPatch, ReadWlanInterruptPin, WlanInterruptEnable, WlanInterruptDisable, WriteWlanPin);
    wlan_start(0);

	if (IP_ALLOC_METHOD == USE_STATIC_IP){// The DHCP setting shave been removed.

		pucSubnetMask[0] = 0xFF;// Subnet mask is assumed to be 255.255.255.0
		pucSubnetMask[1] = 0xFF;
		pucSubnetMask[2] = 0xFF;
		pucSubnetMask[3] = 0x0;


		pucIP_Addr[0] = STATIC_IP_OCT1;    // CC3000's IP
		pucIP_Addr[1] = STATIC_IP_OCT2;
		pucIP_Addr[2] = STATIC_IP_OCT3;
		pucIP_Addr[3] = STATIC_IP_OCT4;

		pucIP_DefaultGWAddr[0] = STATIC_IP_OCT1;// Default Gateway/Router IP
		pucIP_DefaultGWAddr[1] = STATIC_IP_OCT2;
		pucIP_DefaultGWAddr[2] = STATIC_IP_OCT3;
		pucIP_DefaultGWAddr[3] = 1;

		pucDNS[0] = STATIC_IP_OCT1;// We assume the router is also a DNS server
		pucDNS[1] = STATIC_IP_OCT2;
		pucDNS[2] = STATIC_IP_OCT3;
		pucDNS[3] = 1;

		netapp_dhcp((unsigned long *)pucIP_Addr, (unsigned long *)pucSubnetMask,
					(unsigned long *)pucIP_DefaultGWAddr, (unsigned long *)pucDNS);

		// reset the CC3000 to apply Static Setting
		wlan_stop();
		__delay_cycles(6000000);
		wlan_start(0);
	}
    
    // Mask out all non-required events from CC3000
    wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_ASYNC_PING_REPORT);
    
    unsolicicted_events_timer_init();
    
    // CC3000 has been initialized
    setCC3000MachineState(CC3000_INIT);
    
    return(0);
}
Example #2
0
void hw_net_initialize (void)
{
	CC3000_START;
	SpiInit(4e6);
	hw_wait_us(10);

	wlan_init(CC3000_UsynchCallback, NULL, NULL, NULL, ReadWlanInterruptPin,
	WlanInterruptEnable, WlanInterruptDisable, WriteWlanPin);

	wlan_start(0);

	int r = wlan_ioctl_set_connection_policy(0, 0, 0);
	if (r != 0) {
		TM_DEBUG("Fail setting policy %i", r);
	}

	r = wlan_ioctl_set_scan_params(10000, 100, 100, 5, 0x7FF, -100, 0, 205, wifi_intervals);
	if (r != 0) {
		TM_DEBUG("Fail setting scan params %i", r);
	}

	r = wlan_ioctl_set_connection_policy(0, true, true);
	if (r != 0) {
		TM_DEBUG("Fail setting connection policy %i", r);
	}

	wlan_stop();
	hw_wait_ms(10);
	wlan_start(0);

//	tm_sleep_ms(100);
//	TM_COMMAND('w',"setting event mask\n");
	wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_UNSOL_INIT|HCI_EVNT_WLAN_ASYNC_PING_REPORT);
//	TM_COMMAND('w',"done setting event mask\n");

 	unsigned long aucDHCP = 14400;
	unsigned long aucARP = 3600;
	unsigned long aucKeepalive = 10;
	unsigned long aucInactivity = 0;
	if (netapp_timeout_values(&aucDHCP, &aucARP, &aucKeepalive, &aucInactivity) != 0) {
		TM_DEBUG("Error setting inactivity timeout!");
	}

	unsigned char version[2];
	if (nvmem_read_sp_version(version)) {
		TM_ERR("Failed to read CC3000 firmware version.");
	} 

	memcpy(hw_cc_ver, version, 2);

	CC3000_END;
}
void CC3000_Init(void) {

	SPIInterruptsEnabled = 0;

	#ifdef TEENSY3
	pinMode(WLAN_IRQ, INPUT_PULLUP);
	#else
	pinMode(WLAN_IRQ, INPUT);
	#endif
	
	attachInterrupt(WLAN_IRQ_INTNUM, CC3000InterruptHandler, FALLING);
	
	pinMode(WLAN_EN, OUTPUT);
	digitalWrite(WLAN_EN, LOW);	// make sure it's off until we're ready
	
	pinMode(WLAN_CS, OUTPUT);
	Set_CC3000_CS_NotActive();	// turn off CS until we're ready
	
	wlan_init( CC3000_AsyncCallback,
		SendFirmwarePatch,
		SendDriverPatch,
		SendBootloaderPatch,
		ReadWlanInterruptPin,
		WlanInterruptEnable,
		WlanInterruptDisable,
		WriteWlanEnablePin);
	
	wlan_start(0);
	}
Example #4
0
BOOL cc3000_finishAddProfileAndConnect() {
  int connectToOpenAPs = 1;
  int useFastConnect = 1;
  int useProfiles = 1;
  if (wlan_ioctl_set_connection_policy(connectToOpenAPs, useFastConnect, useProfiles) != CC3000_SUCCESS) {
    printf("failed to set connection policy\n");
    return FALSE;
  }

  wlan_stop();
  delay_ms(100);

  BOOL patchAvailable = FALSE;
  wlan_start(patchAvailable);

  int16_t timer = WLAN_CONNECT_TIMEOUT;
  while (!_cc3000_status.isConnected) {
    delay_ms(10);
    timer -= 10;
    if (timer <= 0) {
      printf("Timed out!\n");
      return FALSE;
    }
    _cc3000_irqPoll();
  }
  return TRUE;
}
Example #5
0
int main() {
    printf("Hello, CC3000!\r\n");

    board_init();

    /* Initialise the module */
    printf("Initializing...\r\n");

    init_spi();

    printf("init\r\n");
    wlan_init(CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch,
              sendBootLoaderPatch, ReadWlanInterruptPin, WlanInterruptEnable,
              WlanInterruptDisable, WriteWlanPin);
    printf("start\r\n");

    wlan_start(0);

    printf("ioctl\n\r");

    while(1) {
        // myled = 1;
        // wait(0.2);
        // myled = 0;
        // wait(0.2);
    }
}
Example #6
0
void ManualAddProfile(void)
{
  char ssidName[] = "YourAP";
  char AP_KEY[] = "yourpass";
  uint8_t rval;

  if (!isInitialized)
    {
      printf("CC3000 not initialized; can't run manual add profile.");
      return;
    }

  printf("Starting manual add profile...\n");

  printf("  Disabling auto connection...\n");
  wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE);

  printf("  Adding profile...\n");
  rval = wlan_add_profile  (
          WLAN_SEC_WPA2,     /* WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2 */
          (uint8_t *)ssidName,
          strlen(ssidName),
          NULL,              /* BSSID, TI always uses NULL */
          0,                 /* Profile priority */
          0x18,              /* Key length for WEP security, undocumented why this needs to be 0x18 */
          0x1e,              /* Key index, undocumented why this needs to be 0x1e */
          0x2,               /* key management, undocumented why this needs to be 2 */
          (uint8_t *)AP_KEY, /* WPA security key */
          strlen(AP_KEY)     /* WPA security key length */
          );

  if (rval!=255)
    {
      /* This code is lifted from http://e2e.ti.com/support/low_power_rf/f/851/p/180859/672551.aspx;
       * the actual API documentation on wlan_add_profile doesn't specify any of this....
       */

      printf("  Manual add profile success, stored in profile: %d\n", rval);

      printf("  Enabling auto connection...\n");
      wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE);

      printf("  Stopping CC3000...\n");
      wlan_stop();

      printf("  Stopping for 5 seconds...\n");
      usleep(5000000);

      printf("  Restarting CC3000...\n");
      wlan_start(0);

      printf("  Manual add profile done!");
    }
  else
    {
      printf("  Manual add profile failured (all profiles full?).");
    }
}
//*****************************************************************************
//
//! initDriver
//!
//!  @param  None
//!
//!  @return none
//!
//!  @brief  The function initializes a CC3000 device and triggers it to 
//!          start operation
//
//*****************************************************************************
int
initDriver(void)
{
	
	// Init GPIO's
	pio_init();
	
	//Init Spi
	init_spi();
	
	DispatcherUARTConfigure();
	
	// WLAN On API Implementation
	wlan_init( CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch, sendBootLoaderPatch, ReadWlanInterruptPin, WlanInterruptEnable, WlanInterruptDisable, WriteWlanPin);
	
	// Trigger a WLAN device
	wlan_start(0);
	
	// Turn on the LED 5 to indicate that we are active and initiated WLAN successfully
	turnLedOn(5);
	
	// Mask out all non-required events from CC3000
	wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_UNSOL_INIT|HCI_EVNT_WLAN_ASYNC_PING_REPORT);
	
	// Generate the event to CLI: send a version string
	{
		char cc3000IP[50];
		char *ccPtr;
		unsigned short ccLen;
		
		DispatcherUartSendPacket((unsigned char*)pucUARTExampleAppString, sizeof(pucUARTExampleAppString));
		
		
		ccPtr = &cc3000IP[0];
		ccLen = my_itoa(PALTFORM_VERSION, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '.';
		ccLen = my_itoa(APPLICATION_VERSION, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '.';
		ccLen = my_itoa(SPI_VERSION_NUMBER, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '.';
		ccLen = my_itoa(DRIVER_VERSION_NUMBER, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '\f';
		*ccPtr++ = '\r';
		*ccPtr++ = '\0';
		
		DispatcherUartSendPacket((unsigned char*)cc3000IP, strlen(cc3000IP));
	}
	
	wakeup_timer_init();
	
	ucStopSmartConfig   = 0;
	
	return(0);
}
Example #8
0
/*JSON{ "type":"staticmethod",
         "class" : "WLAN", "name" : "start",
         "generate" : "jswrap_wlan_start",
         "description" : "",
         "params" : [  ]
}*/
void jswrap_wlan_start() {
  wlan_start(0);
  // Mask out all non-required events from CC3000
  wlan_set_event_mask(
      HCI_EVNT_WLAN_KEEPALIVE |
      HCI_EVNT_WLAN_UNSOL_INIT);

  // TODO: check return value !=0
  wlan_ioctl_set_connection_policy(0, 0, 0); // don't auto-connect
  wlan_ioctl_del_profile(255); // delete stored eeprom data
}
Example #9
0
/* Start CC3000, must be called after EXT_DRIVER and
 * SPI_DRIVER are initialized
 **/
static void initCC3000Hw(void)
{
    chprintf((BaseSequentialStream *)&SERIAL_DRIVER, "wlan_init ...");
    cc3000ChibiosWlanInit(&CC3K_SPI_DRIVER, &chCC3SpiConfig,
            &CC3K_EXT_DRIVER, &chExtConfig,
            0,0,0, ccprint);
    chprintf((BaseSequentialStream *)&SERIAL_DRIVER,"done!\r\n");

    chprintf((BaseSequentialStream *)&SERIAL_DRIVER,"wlan_start ...");
    wlan_start(0);
    chprintf((BaseSequentialStream *)&SERIAL_DRIVER,"done!\r\n");

}
Example #10
0
signed int
init_wifiDriver(void)
{
    signed char ret;

    //
	// Init GPIO's
	//
	if(!wifi_SPI_gpio_init_Done)
	{
		return -1;  //error
	}

		//
        //initialize SPI bus.
		//
		// Must be done to establish SimpleLink between microcontroller and cc3000.
		// all  cc3000 api will work only after successful SPI initialization /enabling SimpleLink .
		//	All CC3000 api() {except wlan_init()api }  wait for SimpleLinkWaitEvent(HCI_Cmd_Name, &retval).
        //
        ret=init_spi();
        if(ret)
        {
        	return -2;
        }

	//
	// Register various callback with HostDriver framework  for
    //		1.	 processing  not masked asynchronous Event.
    //		2.	 msp430 bsp functions for cc3000 interrupt pin and wlan_Enable pin
   //
       wlan_init( CC3000_AsyncEventCallback, sendWLFWPatch, sendDriverPatch, sendBootLoaderPatch, ReadWlanInterruptPin, WlanInterruptEnable, WlanInterruptDisable, WriteWlanPin);

	//
	// Starts the CC3000 Wifi chip  to become enabled for wifi operations.
     //blocks till wifi chip doesnt get UP.
	//
	wlan_start(0);

	//
	// Mask out all non-required asynchronous events from CC3000
	//
	ret=	wlan_set_event_mask( HCI_EVNT_WLAN_KEEPALIVE | HCI_EVNT_WLAN_UNSOL_INIT | HCI_EVNT_WLAN_ASYNC_PING_REPORT);
	if(ret){

			return -3;
		  }


    return(0);
}
void CC3000_Init(void)
{
  static bool once = false;

  if (!once)
     {
       wireless_archinitialize();
       once = true;
     }

  cc3000_wlan_init( CC3000_AsyncCallback,
    SendFirmwarePatch,
    SendDriverPatch,
    SendBootloaderPatch);

  wlan_start(0);
}
Example #12
0
void
reset_CC3000()
{
  //
        // reset the CC3000
        //
        wlan_stop();

        //
         __delay_cycles(410000);   // 1 msecond delay

        // Reenable/restart  the CC3000 device.
        //
        wlan_start(0);
         __delay_cycles(410000);   // 1 msecond delay


}
/*------------------------------------------------------------------------
  Spider_begin
  
  Initial Spider L3, 
  
  return  0, Initial success.
  
-----------------------------------------------------------------------*/
int Spider_begin(void){

  // Initial Arduino hardware interface connect with CC3000.
  CC3000_Init();

  // Initial callback functions to wlan api.
  wlan_init( Spider_AsyncCallback, SendFirmwarePatch, SendDriverPatch, SendBootloaderPatch, 
             ReadWlanInterruptPin, WlanInterruptEnable, WlanInterruptDisable, WriteWlanPin);

  // Starting CC3000
  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);

  //Initial success.
  HW_Initialed = 1;
  return 0;
}
Example #14
0
void cc3000_initialise(JsVar *wlanObj) {
  jsvObjectSetChild(jsiGetParser()->root, CC3000_OBJ_NAME, wlanObj);

  cc3000_spi_open();
  wlan_init(cc3000_usynch_callback,
            sendNoPatch/*sendWLFWPatch*/,
            sendNoPatch/*sendDriverPatch*/,
            sendNoPatch/*sendBootLoaderPatch*/,
            cc3000_read_irq_pin, cc3000_irq_enable, cc3000_irq_disable, cc3000_write_en_pin);
  wlan_start(0/* No patches */);
  // Mask out all non-required events from CC3000
  wlan_set_event_mask(
      HCI_EVNT_WLAN_KEEPALIVE |
      HCI_EVNT_WLAN_UNSOL_INIT);

  // TODO: check return value !=0
  wlan_ioctl_set_connection_policy(0, 0, 0); // don't auto-connect
  wlan_ioctl_del_profile(255); // delete stored eeprom data
Example #15
0
//*****************************************************************************
//
//! initDriver
//!
//!  \param[in] cRequestPatch 0 to load with EEPROM patches 
//!             and 1 to load with no patches
//!
//!  \return none
//!
//!  \brief  The function initializes a CC3000 device 
//!          and triggers it to start operation
//
//*****************************************************************************
static int initDriver(unsigned short cRequestPatch)
{
    // WLAN On API Implementation
    wlan_init(CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch, sendBootLoaderPatch,
              ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin);

    // Trigger a WLAN device
    wlan_start(cRequestPatch);
    wlan_smart_config_set_prefix((char*)aucCC3000_prefix);
    wlan_ioctl_set_connection_policy(0, 0, 0);
    wlan_ioctl_del_profile(255);

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

    //unsolicicted_events_timer_init();
    systick_sleep(100);
    return(0);
}
Example #16
0
/// \classmethod \constructor(spi, pin_cs, pin_en, pin_irq)
/// Initialise the CC3000 using the given SPI bus and pins and return a CC3k object.
//
// Note: pins were originally hard-coded to:
//      PYBv1.0: init(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)
//        [SPI on Y position; Y6=B13=SCK, Y7=B14=MISO, Y8=B15=MOSI]
//
//      STM32F4DISC: init(pyb.SPI(2), pyb.Pin.cpu.A15, pyb.Pin.cpu.B10, pyb.Pin.cpu.B11)
STATIC mp_obj_t cc3k_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
    // check arguments
    mp_arg_check_num(n_args, n_kw, 4, 4, false);

    // set the pins to use
    SpiInit(
        spi_get_handle(args[0]),
        pin_find(args[1]),
        pin_find(args[2]),
        pin_find(args[3])
    );

    // initialize and start the module
    wlan_init(cc3k_callback, NULL, NULL, NULL,
            ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin);

    if (wlan_start(0) != 0) {
        nlr_raise(mp_obj_new_exception_msg(
                    &mp_type_OSError, "Failed to init wlan module"));
    }

    // set connection policy. this should be called explicitly by the user
    // wlan_ioctl_set_connection_policy(0, 0, 0);

    // Mask out all non-required events from the CC3000
    wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|
                        HCI_EVNT_WLAN_UNSOL_INIT|
                        HCI_EVNT_WLAN_ASYNC_PING_REPORT|
                        HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE);

    cc3k_obj_t *cc3k = m_new_obj(cc3k_obj_t);
    cc3k->base.type = (mp_obj_type_t*)&mod_network_nic_type_cc3k;

    // register with network module
    mod_network_register_nic(cc3k);

    return cc3k;
}
Example #17
0
static mp_obj_t mod_wlan_init()
{
    /* Initialize WLAN module */
    wlan_init(sWlanCallback, NULL, NULL, NULL,
            ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin);

    /* Start WLAN module */
    if (wlan_start(0) != 0) {
        nlr_raise(mp_obj_new_exception_msg(
                    &mp_type_OSError, "Failed to init wlan module"));
    }

    /* Set connection policy */
    // wlan_ioctl_set_connection_policy(0, 0, 0);

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

    return mp_const_none;
}
//*****************************************************************************
//
//! initDriver
//!
//!  \param[in] cRequestPatch 0 to load with EEPROM patches and 1 to load with no patches
//!
//!  \return none
//!
//!  \brief  The function initializes a CC3000 device and triggers it to start operation
//
//*****************************************************************************
int
initDriver(unsigned short cRequestPatch)
{
	

    //
	// Init GPIO's
	//
	pio_init();
	//
    //init all layers
    //
    init_spi();


	//
	// WLAN On API Implementation
	//
	wlan_init( CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch, sendBootLoaderPatch, ReadWlanInterruptPin, WlanInterruptEnable, WlanInterruptDisable, WriteWlanPin);
	//
	// Trigger a WLAN device
	//
	wlan_start(cRequestPatch);
  wlan_smart_config_set_prefix(aucCC3000_prefix);
	
	// Turn on the LED 5 to indicate that we are active and initiated WLAN successfully
     turnLedOn(5);

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

        unsolicicted_events_timer_init();
    return(0);
}
Example #19
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);
}
Example #20
0
//*****************************************************************************
//
//! initDriver
//!
//!  @param  None
//!
//!  @return none
//!
//!  @brief  The function initializes a CC3000 device and triggers it to start 
//!          operation
//
//*****************************************************************************
int
initDriver(void)
{
	
	// Init GPIO's
	pio_init();
	
	// Init Spi
	init_spi(); 
	
	// Enable processor interrupts
	MAP_IntMasterEnable(); 
	
	// WLAN On API Implementation
	wlan_init( CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch, 
						sendBootLoaderPatch, ReadWlanInterruptPin, WlanInterruptEnable, 
						WlanInterruptDisable, WriteWlanPin);
	
	// Trigger a WLAN device
	wlan_start(0);	

	// Turn on the LED 1 (RED) to indicate that we are active and initiated WLAN successfully
	turnLedOn(1);
	
	// Mask out all non-required events from CC3000
	wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_UNSOL_INIT
											|HCI_EVNT_WLAN_ASYNC_PING_REPORT);
	
	DispatcherUARTConfigure(SysCtlClockGet());
	SysCtlDelay(1000000); 
	
	// Generate teh event to CLI: send a version string
	{
		char cc3000IP[50];
		char *ccPtr;
		unsigned short ccLen;
		
		DispatcherUartSendPacket((unsigned char*)pucUARTExampleAppString, 
														 sizeof(pucUARTExampleAppString));
		
		ccPtr = &cc3000IP[0];
		ccLen = itoa(PALTFORM_VERSION, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '.';
		ccLen = itoa(APPLICATION_VERSION, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '.';
		ccLen = itoa(SPI_VERSION_NUMBER, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '.';
		ccLen = itoa(DRIVER_VERSION_NUMBER, ccPtr);
		ccPtr += ccLen;
		*ccPtr++ = '\f';
		*ccPtr++ = '\r';
		*ccPtr++ = '\0';		
		DispatcherUartSendPacket((unsigned char*)cc3000IP, strlen(cc3000IP));
	}
	
	ucStopSmartConfig   = 0;
	
	// Configure SysTick to occur X times per second, to use as a time
	// reference.  Enable SysTick to generate interrupts.
	InitSysTick();
	
	return(0);
}
Example #21
0
static void cmd_smart_cc3000(BaseSequentialStream *chp, int argc, char *argv[])
{
    long rval;

    (void)argv;
    if(argc > 0)
    {
        chprintf(chp, "Usage: setup\r\n");
        return;
    }

    chprintf(chp, "Disconnecting ");
    wlan_disconnect();
    while(cc3000AsyncData.connected == 1)
    {
        chprintf(chp, ".");
    }
    chprintf(chp, "done!\r\n");

    chprintf(chp, "Disabling auto connect policy ...\r\n");
    /* Set connection policy to disable */
    if ((rval = wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE)) != 0)
    {
        chprintf(chp, "Error disabling auto connect policy ...\r\n");
        return;
    }

    /* Delete all profiles */
    chprintf(chp, "Deleting all profiles ...\r\n");
    if ((rval = wlan_ioctl_del_profile(255)) != 0)
    {
        chprintf(chp, "Error deleting profiles ...\r\n");
        return;
    }


    chprintf(chp, "Creating AES keys ...\r\n");
    nvmem_create_entry(NVMEM_AES128_KEY_FILEID, AES128_KEY_SIZE);
    aes_write_key((UINT8 *) AES_KEY);

    // Set the smart config prefix
    chprintf(chp, "Setting smart config prefix ...\r\n");
    if((rval = wlan_smart_config_set_prefix(smartConfigPrefix)) != 0)
    {
        chprintf(chp, "Error setting smart config prefix ... \r\n");
        return;
    }
    chprintf(chp, "Starting CC3000 SmartConfig ...\r\n");
    if((rval = wlan_smart_config_start(0)) != 0)
    {
        chprintf(chp, "Error starting smart config ...\r\n");
        return;
    }

    chprintf(chp, "Waiting for SmartConfig to finish ...\r\n");
    /* Wait until smart config is finished */
    while(cc3000AsyncData.smartConfigFinished == 0)
    {
        // We blink the led here .. the thread process
        // will set this to PAL_LOW (since we are disconnected)
        palWritePad(CON_LED_PORT, CON_LED_PIN, PAL_HIGH);
        chThdSleep(MS2ST(200));
    }

    chprintf(chp, "Smart config packet received ...\r\n");
    /* Re enable auto connect policy */
    if ((rval = wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE)) != 0)
    {
        chprintf(chp, "Error setting auto connect policy ...\r\n");
        return;
    }

    /* Restart wlan */
    wlan_stop();
    chprintf(chp, "Reconnecting ...\r\n");
    chThdSleep(MS2ST(2000));
    wlan_start(0);
    /* No need to call connect, hopefully auto connect policy
     * can connect to our AP now
     **/
    chprintf(chp, "Waiting for connection to AP ...\r\n");
    while (cc3000AsyncData.dhcp.present != 1)
    {
        chThdSleep(MS2ST(5));
    }

    show_cc3_dhcp_info(chp);
    mdnsAdvertiser(1, deviceName, strlen(deviceName));

}
Example #22
0
static void cmd_setup_cc3000(BaseSequentialStream *chp, int argc, char *argv[])
{
    char ssid_name[32];
    char ssid_key[40];
    char ssid_sectype[3];
    unsigned long sectype;
    unsigned char rval;

    (void)argv;
    if(argc > 0)
    {
        chprintf(chp, "Usage: smartcfg\r\n");
        return;
    }

    chprintf(chp, "Enter Security profile: \r\n");
    chprintf(chp, "  [0] Unsecured\r\n");
    chprintf(chp, "  [1] WEP\r\n");
    chprintf(chp, "  [2] WPA\r\n");
    chprintf(chp, "  [3] WPA2\r\n");

    shellGetLine(chp, ssid_sectype, 3);
    sectype = ssid_sectype[0] - '0';

    chprintf(chp, "Enter the AP SSID\r\n");
    shellGetLine(chp, ssid_name, 32);

    chprintf(chp, "Enter SSID Key\r\n");
    shellGetLine(chp, ssid_key, 40);

    chprintf(chp, "Type[%d]\r\n", sectype);
    chprintf(chp, "SSID[%s]\r\n", ssid_name);
    chprintf(chp, "Passkey[%s]\r\n", ssid_key);

    chprintf(chp, "Disabling connection policy ...\r\n");
    wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE);

    chprintf(chp, "Adding profile ...\r\n");
    rval = wlan_add_profile(sectype,
            (unsigned char *) ssid_name,
            strlen(ssid_name),
            NULL,
            0,
            0x18,
            0x1e,
            0x2,
            (unsigned char *) ssid_key,
            strlen(ssid_key)
            );

    if (rval != 255)
    {
        chprintf(chp, "Add profile returned: %d\r\n", rval);

        chprintf(chp, "Enabling auto connect ...\r\n");
        wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE);
        chprintf(chp, "Restarting wlan ...\r\n");
        wlan_stop();
        chThdSleep(MS2ST(500));
        wlan_start(0);

        return;

    }else
    {
        // TODO: Delete profiles and add again
        chprintf(chp, "Error adding profile (list full) ...\r\n");
        return;
    }

    chprintf(chp, "Lan profile added!\r\n");
}
Example #23
0
void SPARK_WLAN_Loop(void)
{
        static int cofd_count = 0;

        if(SPARK_WLAN_RESET || SPARK_WLAN_SLEEP)
	{
		if(SPARK_WLAN_STARTED)
		{
			if (LED_RGB_OVERRIDE)
			{
				LED_Signaling_Stop();
			}
			WLAN_CONNECTED = 0;
			WLAN_DHCP = 0;
			SPARK_WLAN_RESET = 0;
			SPARK_WLAN_STARTED = 0;
			SPARK_SOCKET_CONNECTED = 0;
			SPARK_HANDSHAKE_COMPLETED = 0;
			SPARK_FLASH_UPDATE = 0;
			SPARK_LED_FADE = 0;
			Spark_Error_Count = 0;
			cofd_count = 0;

			CC3000_Write_Enable_Pin(WLAN_DISABLE);
			//wlan_stop();

			Delay(100);

			if(WLAN_SMART_CONFIG_START)
			{
				//Workaround to enter smart config when socket connect had blocked
				wlan_start(0);

				SPARK_WLAN_STARTED = 1;

				/* Start CC3000 Smart Config Process */
				Start_Smart_Config();
			}

			LED_SetRGBColor(RGB_COLOR_GREEN);
			LED_On(LED_RGB);
		}
	}
	else
	{
		if(!SPARK_WLAN_STARTED)
		{
			wlan_start(0);

			SPARK_WLAN_STARTED = 1;
		}
	}

	if(WLAN_SMART_CONFIG_START)
	{
		/* Start CC3000 Smart Config Process */
		Start_Smart_Config();
	}
	else if (WLAN_MANUAL_CONNECT > 0 && !WLAN_DHCP)
	{
	    wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE);
	    /* Edit the below line before use*/
	    wlan_connect(WLAN_SEC_WPA2, _ssid, strlen(_ssid), NULL, (unsigned char*)_password, strlen(_password));
	    WLAN_MANUAL_CONNECT = -1;
	}

	// Complete Smart Config Process:
	// 1. if smart config is done
	// 2. CC3000 established AP connection
	// 3. DHCP IP is configured
	// then send mDNS packet to stop external SmartConfig application
	if ((WLAN_SMART_CONFIG_STOP == 1) && (WLAN_DHCP == 1) && (WLAN_CONNECTED == 1))
	{
		unsigned char loop_index = 0;

		while (loop_index < 3)
		{
			mdnsAdvertiser(1,device_name,strlen(device_name));
			loop_index++;
		}

		WLAN_SMART_CONFIG_STOP = 0;
	}

	if(SPARK_SOCKET_HANDSHAKE == 0)
	{
		if(SPARK_SOCKET_CONNECTED || SPARK_HANDSHAKE_COMPLETED)
		{
			Spark_Disconnect();

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

			LED_SetRGBColor(RGB_COLOR_GREEN);
			LED_On(LED_RGB);
		}

		return;
	}

	if(TimingSparkConnectDelay != 0)
	{
		return;
	}

	if(WLAN_DHCP && !SPARK_WLAN_SLEEP && !SPARK_SOCKET_CONNECTED)
	{
		Delay(100);

		netapp_ipconfig(&ip_config);

		if(Spark_Error_Count)
		{
			LED_SetRGBColor(RGB_COLOR_RED);

			while(Spark_Error_Count != 0)
			{
				LED_On(LED_RGB);
				Delay(500);
				LED_Off(LED_RGB);
				Delay(500);
				Spark_Error_Count--;
			}

			//Send the Error Count to Cloud: NVMEM_Spark_File_Data[ERROR_COUNT_FILE_OFFSET]
			//To Do

			//Reset Error Count
			NVMEM_Spark_File_Data[ERROR_COUNT_FILE_OFFSET] = 0;
			nvmem_write(NVMEM_SPARK_FILE_ID, 1, ERROR_COUNT_FILE_OFFSET, &NVMEM_Spark_File_Data[ERROR_COUNT_FILE_OFFSET]);
		}

		LED_SetRGBColor(RGB_COLOR_CYAN);
		LED_On(LED_RGB);

		if(Spark_Connect() >= 0)
                {
                        cofd_count  = 0;
                        SPARK_SOCKET_CONNECTED = 1;
			TimingCloudHandshakeTimeout = 0;
                }
                else
		{
			if(SPARK_WLAN_RESET)
				return;

                        if ((cofd_count += RESET_ON_CFOD) == MAX_FAILED_CONNECTS)
			{
			    SPARK_WLAN_RESET = RESET_ON_CFOD;
			    ERROR("Resetting CC3000 due to %d failed connect attempts", MAX_FAILED_CONNECTS);

			}

			if(Internet_Test() < 0)
			{
				//No Internet Connection
	                        if ((cofd_count += RESET_ON_CFOD) == MAX_FAILED_CONNECTS)
	                        {
	                            SPARK_WLAN_RESET = RESET_ON_CFOD;
	                            ERROR("Resetting CC3000 due to %d failed connect attempts", MAX_FAILED_CONNECTS);
	                        }
				Spark_Error_Count = 2;
			}
			else
			{
				//Cloud not Reachable
				Spark_Error_Count = 3;
			}

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

			SPARK_SOCKET_CONNECTED = 0;
		}
	}

	if (SPARK_SOCKET_CONNECTED)
	{
		if (!SPARK_HANDSHAKE_COMPLETED)
		{
			int err = Spark_Handshake();

			if (err)
			{
				if (0 > err)
				{
					// Wrong key error, red
					LED_SetRGBColor(0xff0000);
				}
				else if (1 == err)
				{
					// RSA decryption error, orange
					LED_SetRGBColor(0xff6000);
				}
				else if (2 == err)
				{
					// RSA signature verification error, magenta
					LED_SetRGBColor(0xff00ff);
				}
				LED_On(LED_RGB);

				Cloud_Handshake_Error_Count++;
				TimingSparkConnectDelay = Cloud_Handshake_Error_Count * TIMING_CLOUD_HANDSHAKE_TIMEOUT;
			}
			else
			{
				SPARK_HANDSHAKE_COMPLETED = 1;
				Cloud_Handshake_Error_Count = 0;
				TimingCloudActivityTimeout = 0;
			}
		}

		if (!Spark_Communication_Loop())
		{
			if (LED_RGB_OVERRIDE)
			{
				LED_Signaling_Stop();
			}

			SPARK_FLASH_UPDATE = 0;
			SPARK_LED_FADE = 0;
			SPARK_HANDSHAKE_COMPLETED = 0;
			SPARK_SOCKET_CONNECTED = 0;
		}
	}
}
Example #24
0
void SPARK_WLAN_Setup(void (*presence_announcement_callback)(void))
{
	announce_presence = presence_announcement_callback;

	/* Initialize CC3000's CS, EN and INT pins to their default states */
	CC3000_WIFI_Init();

	/* Configure & initialize CC3000 SPI_DMA Interface */
	CC3000_SPI_DMA_Init();

	/* WLAN On API Implementation */
	wlan_init(WLAN_Async_Callback, WLAN_Firmware_Patch, WLAN_Driver_Patch, WLAN_BootLoader_Patch,
				CC3000_Read_Interrupt_Pin, CC3000_Interrupt_Enable, CC3000_Interrupt_Disable, CC3000_Write_Enable_Pin);

	Delay(100);

	/* Trigger a WLAN device */
	wlan_start(0);

	SPARK_LED_FADE = 0;

	SPARK_WLAN_STARTED = 1;

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

	if(NVMEM_SPARK_Reset_SysFlag == 0x0001 || nvmem_read(NVMEM_SPARK_FILE_ID, NVMEM_SPARK_FILE_SIZE, 0, NVMEM_Spark_File_Data) != NVMEM_SPARK_FILE_SIZE)
	{
		/* Delete all previously stored wlan profiles */
		wlan_ioctl_del_profile(255);

		/* Create new entry for Spark File in CC3000 EEPROM */
		nvmem_create_entry(NVMEM_SPARK_FILE_ID, NVMEM_SPARK_FILE_SIZE);

		memset(NVMEM_Spark_File_Data,0, arraySize(NVMEM_Spark_File_Data));

		nvmem_write(NVMEM_SPARK_FILE_ID, NVMEM_SPARK_FILE_SIZE, 0, NVMEM_Spark_File_Data);

		NVMEM_SPARK_Reset_SysFlag = 0x0000;
		Save_SystemFlags();
	}

	if(WLAN_MANUAL_CONNECT == 0)
	{
		if(NVMEM_Spark_File_Data[WLAN_PROFILE_FILE_OFFSET] == 0)
		{
			WLAN_SMART_CONFIG_START = 1;
		}
		else if(NVMEM_Spark_File_Data[WLAN_POLICY_FILE_OFFSET] == 0)
		{
			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]);
		}
	}

	if((WLAN_MANUAL_CONNECT > 0) || !WLAN_SMART_CONFIG_START)
	{
		LED_SetRGBColor(RGB_COLOR_GREEN);
		LED_On(LED_RGB);
	}

	nvmem_read_sp_version(patchVer);
	if (patchVer[1] == 24)//19 for old patch
	{
		/* Latest Patch Available after flashing "cc3000-patch-programmer.bin" */
	}

	Clear_NetApp_Dhcp();

	Set_NetApp_Timeout();
}
Example #25
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;
}
Example #26
0
/* mgmt mutex MUST be locked by caller */
static clarityError clarityMgmtAttemptActivate_mtxext(void)
{
    clarityError rtn = CLARITY_SUCCESS;
#if 0
    uint32_t ip = 0;
    uint32_t subnet = 0;
    uint32_t gateway = 0;
    uint32_t dns = 0;
#endif

    if (mgmtData.active == true)
    {
        return CLARITY_SUCCESS;
    }


#if 0
    if (mgmtData.ap->deviceIp.isStatic == true)
    {
        ip = htonl(mgmtData.ap->deviceIp.ip);
        subnet = htonl(mgmtData.ap->deviceIp.subnet);
        gateway = htonl(mgmtData.ap->deviceIp.gateway);
        dns = htonl(mgmtData.ap->deviceIp.dns);
    }
#endif

    clarityCC3000ApiLock();
    wlan_start(0);       
    mgmtData.active = true;

#if 0
    if (netapp_dhcp(&ip, &subnet, &gateway, &dns) != 0)
    {
        CLAR_PRINT_ERROR();
        rtn = CLARITY_ERROR_CC3000_NETAPP;
    }

    wlan_disconnect();
    wlan_stop();
    chThdSleep(MS2ST(200));
    wlan_start(0);
#endif
    clarityCC3000ApiUnlock();

    if ((rtn = connectToWifi_mtxext()) != CLARITY_SUCCESS)
    {
        CLAR_PRINT_ERROR();
    }

    if (rtn != CLARITY_SUCCESS)
    {
        clarityCC3000ApiLock();
        wlan_disconnect();
        wlan_stop();       
        clarityCC3000ApiUnlock();

        mgmtData.active = false;

    }

    return rtn;
}
Example #27
0
void StartSmartConfig(void)
{
  long rval;

  if (!isInitialized)
    {
      printf("CC3000 not initialized; can't run Smart Config.\n");
      return;
    }

  printf("Starting Smart Config\n");

  printf("  Disabling auto-connect policy...");
  if ((rval = wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE)) !=0)
    {
      printf(" Failed!\n    Setting auto connection policy failed, error: %lx\n",
             (unsigned long)rval);
      return;
    }

  printf(" Succeed\n");
  printf("  Deleting all existing profiles...");
  fflush(stdout);

  if ((rval = wlan_ioctl_del_profile(255)) !=0)
    {
      printf(" Failed!\n    Deleting all profiles failed, error: %lx\n",
             (unsigned long)rval);
      return;
    }

  printf(" Succeed\n");
  wait_on(20*MS_PER_SEC, &ulCC3000Connected, 0, "  Waiting until disconnected");

  printf("  Setting smart config prefix...");
  fflush(stdout);

  if ((rval = wlan_smart_config_set_prefix(simpleConfigPrefix)) !=0)
    {
      printf(" Failed!\n    Setting smart config prefix failed, error: %lx",
             (unsigned long)rval);
      return;
    }

  printf(" Succeed\n");
  printf("  Starting smart config...");
  fflush(stdout);

  if ((rval = wlan_smart_config_start(0)) !=0)
    {
      printf(" Failed!\n    Starting smart config failed, error: %lx\n",
             (unsigned long)rval);
      return;
    }

  printf(" Succeed\n");

  if (!wait_on(30*MS_PER_SEC, &ulSmartConfigFinished, 1, "  Waiting on Starting smart config done"))
    {
      printf("    Timed out waiting for Smart Config to finish. Hopefully it did anyway\n");
    }

  printf("  Smart Config packet %s!\n",ulSmartConfigFinished ? "seen" : "NOT seen");

  printf("  Enabling auto-connect policy...");
  fflush(stdout);

  if ((rval = wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE)) !=0)
    {
      printf(" Failed!\n    Setting auto connection policy failed, error: %lx\n",
             (unsigned long)rval);
      return;
    }

  printf(" Succeed\n");
  printf("  Stopping CC3000...\n");
  fflush(stdout);
  wlan_stop();  /* No error returned here, so nothing to check */

  printf("  Pausing for 2 seconds...\n");
  sleep(2);

  printf("  Restarting CC3000... \n");
  wlan_start(0);  /* No error returned here, so nothing to check */

  if (!wait_on(20*MS_PER_SEC, &ulCC3000Connected, 1, "  Waiting for connection to AP"))
    {
      printf("    Timed out waiting for connection to AP\n");
      return;
    }

  if (!wait_on(15*MS_PER_SEC, &ulCC3000DHCP, 1, "  Waiting for IP address from DHCP"))
    {
      printf("    Timed out waiting for IP address from DHCP\n");
      return;
    }

  printf("  Sending mDNS broadcast to signal we're done with Smart Config...\n");
  fflush(stdout);

  /* The API documentation says mdnsAdvertiser() is supposed to return 0 on
   * success and SOC_ERROR on failure, but it looks like what it actually
   * returns is the socket number it used. So we ignore it.
   */

  mdnsadvertiser(1, device_name, strlen(device_name));

  printf("  Smart Config finished Successfully!\n");
  ShowInformation();
  fflush(stdout);
}
Example #28
0
BOOL cc3000_setup(BOOL patchReq, uint8_t connectPolicy, const char* deviceName) {
  printf("BEGIN CC3000 Setup (patchReq: %d, connectPolicy: %d, deviceName: %s)\n", patchReq, connectPolicy, deviceName);

  _cc3000_pingReportNum = 0;
  _cc3000_irqEnabled = FALSE;
  memset(&_cc3000_status, 0, sizeof(_cc3000_status));
  memset(&_cc3000_pingReport, 0, sizeof(_cc3000_pingReport));
  for (int i = 0; i < MAX_SOCKETS; i++) {
    _cc3000_sockets[i].closed = FALSE;
  }
  _cc3000_inIrq = FALSE;

  wlan_init(
    _cc3000_asyncCallback,
    _cc3000_sendFWPatches,
    _cc3000_sendDriverPatches,
    _cc3000_sendBootLoaderPatches,
    _cc3000_readWlanInterruptPin,
    _cc3000_wlanInterruptEnable,
    _cc3000_wlanInterruptDisable,
    _cc3000_writeWlanPin
  );

  wlan_start(patchReq);

  uint8_t firmwareMajor, firmwareMinor;
  if (_cc3000_getFirmwareVersion(&firmwareMajor, &firmwareMinor)) {
    printf("CC3000 firmware: %d.%d\n", firmwareMajor, firmwareMinor);
  } else {
    printf("failed to get firmware\n");
    return FALSE;
  }

  // Check if we should erase previous stored connection details
  // (most likely written with data from the SmartConfig app)
  int connectToOpenAPs = (connectPolicy & CC3000_CONNECT_POLICY_OPEN_AP) ? 1 : 0;
  int useFastConnect = (connectPolicy & CC3000_CONNECT_POLICY_FAST) ? 1 : 0;
  int useProfiles = (connectPolicy & CC3000_CONNECT_POLICY_PROFILES) ? 1 : 0;
  wlan_ioctl_set_connection_policy(connectToOpenAPs, useFastConnect, useProfiles);
  if (connectToOpenAPs == 0 && useFastConnect == 0 && useProfiles == 0) {
    // Delete previous profiles from memory
    wlan_ioctl_del_profile(255);
  }

  if (wlan_set_event_mask(HCI_EVNT_WLAN_UNSOL_INIT        |
                          //HCI_EVNT_WLAN_ASYNC_PING_REPORT |// we want ping reports
                          //HCI_EVNT_BSD_TCP_CLOSE_WAIT |
                          //HCI_EVNT_WLAN_TX_COMPLETE |
                          HCI_EVNT_WLAN_KEEPALIVE) != CC3000_SUCCESS) {
    printf("WLAN Set Event Mask FAIL\n");
    return FALSE;
  }

  // Wait for re-connection if we're using SmartConfig data
  if (connectPolicy & CC3000_CONNECT_POLICY_SMART_CONFIG) {
    // Wait for a connection
    uint32_t timeout = 0;
    while (!_cc3000_status.isConnected) {
      _cc3000_irqPoll();
      if (timeout > WLAN_CONNECT_TIMEOUT) {
        return FALSE;
      }
      timeout += 10;
      delay_ms(10);
    }

    delay_ms(1000);
    if (_cc3000_status.hasDHCP) {
      mdnsAdvertiser(1, (char*) deviceName, strlen(deviceName));
    }
  }

  printf("END CC3000 Setup\n");
  return TRUE;
}
/**
 * @brief Configure SPI for MCU to CC3000
 *
 * @return True if SPI initialization completed successfully. False otherwise.
 */
bool SFE_CC3000::init()
{

    /* Check if CC3000 SPI is already initialized */
    if (is_initialized_) {
        return true;
    }
    
    /* Determine available interrupt pins on supported microcontrollers */
#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega168__) || \
    defined(__AVR_ATmega328P__) || defined (__AVR_ATmega328__)
    switch (g_int_pin) {
        case 2:
            g_int_num = 0;
            break;
        case 3:
            g_int_num = 1;
            break;
        default:
            Serial.println("ERROR: Interrupt line not attached to pin 2 or 3");
            return false;
    }
#elif defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__) || \
    defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
    
    switch (g_int_pin) {
        case 2:
            g_int_num = 0;
            break;
        case 3:
            g_int_num = 1;
            break;
        case 18:
            g_int_num = 5;
            break;
        case 19:
            g_int_num = 4;
            break;
        case 20:
            g_int_num = 3;
            break;
        case 21:
            g_int_num = 2;
            break;
        default:
            Serial.println("ERROR: Interrupt not pin 2, 3, 18, 19, 20, or 21");
            return false;
    }
#elif defined(__AVR_ATmega32U4__)
    switch (g_int_pin) {
        case 3:
            g_int_num = 0;
            break;
        case 2:
            g_int_num = 1;
            break;
        case 0:
            g_int_num = 2;
            break;
        case 1:
            g_int_num = 3;
            break;
        case 7:
            g_int_num = 4;
            break;
        default:
            Serial.println("ERROR: Interrupt not pin 0, 1, 2, 3, or 7");
            return false;
    }
#else
        Serial.println("ERROR: Microcontroller not supported");
        return false;
#endif
    
    /* Initialize interrupt, CS, and enable pins */

	/* Digital pins can be used as INPUT */
    pinMode(g_int_pin, INPUT);
    pinMode(g_en_pin, OUTPUT);
    pinMode(g_cs_pin, OUTPUT);
    digitalWrite(g_en_pin, LOW);
    
    /* Set up SPI, save default SPI parameters */
    SPI.begin();
    //SPI.setDataMode(SPI_MODE1);
    //SPI.setBitOrder(MSBFIRST);
    //SPI.setClockDivider(SPI_CLK_DIV);
    
    /* De-assert CS */
    digitalWrite(g_cs_pin, HIGH);
    
    /* Initialize CC3000 library - provide callback definitions */
    wlan_init(  cc3000AsyncCallback,
                sendFirmwarePatch,
                sendDriverPatch,
                sendBootLoaderPatch,
                readWlanInterruptPin,
                enableWlanInterrupt,
                disableWlanInterrupt,
                writeWlanPin);
    
    /* CC3000 needs a delay before starting WLAN or it gets stuck sometimes */
    delay(100);
    
    /* Start CC3000 - asserts enable pin and blocks until init is complete */
    wlan_start(0);
    
    /* Mask out non-required events */
    wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE | HCI_EVNT_WLAN_UNSOL_INIT);
    
    is_initialized_ = true;
    
    return true;
}
/**
 * @brief Begins SmartConfig. The user needs to run the SmartConfig phone app.
 *
 * @param[in] timeout optional time (ms) to wait before stopping. 0 = no timeout
 * @return True if connected to wireless network. False otherwise.
 */
bool SFE_CC3000::startSmartConfig(unsigned int timeout)
{
    char cc3000_prefix[] = {'T', 'T', 'T'};
    unsigned long time;
    
    /* Reset all global connection variables */
    ulSmartConfigFinished = 0;
	ulCC3000Connected = 0;
	ulCC3000DHCP = 0;
	OkToDoShutDown=0;
    
    /* If CC3000 is not initialized, return false. */
	if (!getInitStatus()) {
        return false;
    }
    
    /* Set connection profile to manual (no fast or auto connect) */
    if (wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE) != 
                                                            CC3000_SUCCESS) {
        return false;
    }
    
    /* Delete old connection profiles */
    if (wlan_ioctl_del_profile(255) != CC3000_SUCCESS) {
        return false;
    }
    
    /* Wait until CC3000 is disconnected */
    while (getConnectionStatus()) {
        delay(1);
    }
    
    /* Sets the prefix for SmartConfig. Should always be "TTT" */
    if (wlan_smart_config_set_prefix((char*)cc3000_prefix) != CC3000_SUCCESS) {
        return false;
    }
    
    /* Start the SmartConfig process */
    if (wlan_smart_config_start(0) != CC3000_SUCCESS) {
        return false;
    }
    
    /* Wait for SmartConfig to complete */
    time = millis();
    while (ulSmartConfigFinished == 0) {
        if (timeout != 0) {
            if ( (millis() - time) > timeout ) {
                return false;
            }
        }
    }
    
    /* Configure to connect automatically to AP from SmartConfig process */
    if (wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE) != 
                                                            CC3000_SUCCESS) {
        return false;
    }
    
    /* Reset CC3000 */
    wlan_stop();
    delay(400);
    wlan_start(0);
    
    /* Wait for connection and DHCP-assigned IP address */
    while (getDHCPStatus() == false) {
        if (timeout != 0) {
            if ( (millis() - time) > timeout ) {
                return false;
            }
        }
    }
    
    /* If we make it this far, we need to tell the SmartConfig app to stop */
    mdnsAdvertiser(1, DEVICE_NAME, strlen(DEVICE_NAME));
    
    /* Get connection information */
    netapp_ipconfig(&connection_info_);

    return true;
}