//***************************************************************************** // //! 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); }
/*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 }
//***************************************************************************** // //! 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); }
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; }
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_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
/*------------------------------------------------------------------------ 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; }
//***************************************************************************** // //! 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); }
/// \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; }
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); }
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; }
void StartSmartConfig(void) { ulSmartConfigFinished = 0; ulCC3000Connected = 0; ulCC3000DHCP = 0; OkToDoShutDown=0; // Reset all the previous configuration if (wlan_ioctl_set_connection_policy(0, 0, 0) != 0) { digitalWrite(ErrorLED, HIGH); return; } if (wlan_ioctl_del_profile(255) != 0) { digitalWrite(ErrorLED, HIGH); return; } //Wait until CC3000 is disconnected while (ulCC3000Connected == 1) { delayMicroseconds(100); } // Serial.println("waiting for disconnect"); // Trigger the Smart Config process // Start blinking LED6 during Smart Configuration process digitalWrite(ConnLED, HIGH); if (wlan_smart_config_set_prefix((char*)aucCC3000_prefix) != 0){ digitalWrite(ErrorLED, HIGH); return; } digitalWrite(ConnLED, LOW); // Start the SmartConfig start process if (wlan_smart_config_start(0) != 0){ digitalWrite(ErrorLED, HIGH); return; } if (DEBUG_MODE) { Serial.println("smart config start"); } digitalWrite(ConnLED, HIGH); // Wait for Smartconfig process complete while (ulSmartConfigFinished == 0) { delay(500); digitalWrite(ConnLED, LOW); delay(500); digitalWrite(ConnLED, HIGH); } if (DEBUG_MODE) { Serial.println("smart config finished"); } digitalWrite(ConnLED, LOW); // Configure to connect automatically to the AP retrieved in the // Smart config process. Enabled fast connect. if (wlan_ioctl_set_connection_policy(0, 0, 1) != 0){ digitalWrite(ErrorLED, HIGH); return; } // reset the CC3000 wlan_stop(); delayMicroseconds(500); 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); if (DEBUG_MODE) { Serial.print("Config done"); } }
//***************************************************************************** // //! 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(); // Globally enable interrupts __enable_interrupt(); // // WLAN On API Implementation // wlan_init( CC3000_UsynchCallback, sendWLFWPatch, sendDriverPatch, sendBootLoaderPatch, ReadWlanInterruptPin, WlanInterruptEnable, WlanInterruptDisable, WriteWlanPin); // // Trigger a WLAN device // 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|HCI_EVNT_WLAN_UNSOL_INIT); // Generate 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++ = '\r'; *ccPtr++ = '\n'; *ccPtr++ = '\0'; ccLen = strlen(cc3000IP); DispatcherUartSendPacket((unsigned char*)cc3000IP, strlen(cc3000IP)); // CC3000 has been initialized setCC3000MachineState(CC3000_INIT); unsigned long aucDHCP, aucARP, aucKeepalive, aucInactivity; aucDHCP = 14400; aucARP = 3600; aucKeepalive = 10; aucInactivity = 50; if(netapp_timeout_values(&(aucDHCP), &(aucARP), &(aucKeepalive), &(aucInactivity)) != 0) { while(1); } return(0); }
void StartSmartConfig(void) { // Reset all the previous configuration // wlan_ioctl_set_connection_policy(0, 0, 0); wlan_ioctl_del_profile(255); //Wait until CC3000 is dissconected while (ulCC3000Connected == 1) { __delay_cycles(100); } // Start blinking LED6 during Smart Configuration process turnLedOn(LED6); wlan_smart_config_set_prefix(aucCC3000_prefix); //wlan_first_time_config_set_prefix(aucCC3000_prefix); turnLedOff(LED6); // Start the SmartConfig start process wlan_smart_config_start(1); turnLedOn(LED6); // // Wait for Smart config finished // while (ulSmartConfigFinished == 0) { __delay_cycles(6000000); turnLedOn(LED6); __delay_cycles(6000000); turnLedOff(LED6); } turnLedOff(LED6); // 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(0, 0, 1); // // reset the CC3000 // wlan_stop(); __delay_cycles(600000); wlan_start(0); ConnectUsingSmartConfig = 1; ulSmartConfigFinished = 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); }
int wlan_connect_init() { wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE | HCI_EVNT_WLAN_UNSOL_INIT); return 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); }
/******************************************************************************* * 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; }
/* * @brief Initialization is used to configure all of the registers of the microcontroller * Steps: * 1) Initialize CC3000 * 2) Set MUX Select_A to LOW, so we can send the Kill command from Atmega TX line * (C0 input on MUX) * 3) Set Mode to Safety Mode * 4) Set MUX Select A to HIGH, so we get into Autonomous mode by default * (C1 input on MUX) */ inline void Initialization (void) { #ifdef WATCHDOG_ENABLED wdt_enable(WDTO_8S); // WDTO_8S means set the watchdog to 8 seconds. #endif //Turn on the Power LED to identify that the device is on. // [UNUSED] DDRC |= (1 << DDC7); //STATUS LED //Set up the LEDs for WLAN_ON and DHCP: DDRC |= (1 << DDC6); //WLAN_INIT LED DDRC |= (1 << DDC7); //DHCP_Complete LED. This will turn on and very slowly blink DDRB |= (1 << DDB7); // MUX Select line, setting as output. DDRE |= (1 << DDE2); // DDRF set outbound for Safe Mode LED DDRD |= (1 << DDD6); // DDRF set outbound for Manual Mode LED DDRD |= (1 << DDD4); // DDRF set outbound for Auto Mode LED PORTF |= (1 << PF0); // Extra GPIO Pin PORTF |= (1 << PF1); // Extra GPIO Pin #ifndef SKIP_BOOT DDRB |= (1 << DDB4); DDRD |= (1 << DDD7); DDRD |= (1 << DDD6); PORTB |= (1 << PB4); _delay_ms(200); PORTD |= (1 << PD7); _delay_ms(200); PORTD |= (1 << PD6); _delay_ms(200); PORTB &= ~(1 << PB4); _delay_ms(200); PORTD &= ~(1 << PD7); _delay_ms(200); PORTD &= ~(1 << PD6); #endif _delay_ms(500); PORTF &= ~(1 << PF0); PORTF &= ~(1 << PF1); // #ifdef ENERGY_ANALYSIS_ENABLED // //Enable Timer/Counter0 Interrupt on compare match of OCR0A: // TIMSK0 = (1 << OCIE0A); // //Set the Output Compare Register for the timer to compare against: // OCR0A = Energy_Analysis_Interval; // //Configure the ADC to have the reference pin be AREF on pin 21, and make sure everything is set to defaults: // ADMUX = 0x00; // //Enable the Analog to Digital Conversion (ADC): // ADCSRA = (1 << ADEN); //25 Clock cycles to initialize. // #endif #ifdef CC3000_ENABLED //Enable the CC3000, and setup the SPI configurations. init_spi(); //Set up the CC3000 API for communication. wlan_init(CC3000_Unsynch_Call_Back, Send_WLFW_Patch, Send_Driver_Patch, Send_Boot_Loader_Patch, Read_WLAN_Interrupt_Pin, WLAN_Interrupt_Enable, WLAN_Interrupt_Disable, Write_WLAN_Pin); PORTB |= (1 << PB6); //Set the WLAN_INIT LED on. sei(); //Enable the CC3000, and wait for initialization process to finish. wlan_start(0); wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_UNSOL_INIT|HCI_EVNT_WLAN_ASYNC_PING_REPORT); //Make sure we disconnect from any previous routers before we connect to a new one to prevent confusion on the device. wlan_disconnect(); wlan_connect(WLAN_SEC_UNSEC, ROUTER_SSID, SSID_LENGTH, NULL, NULL, 0); while(!DHCP_Complete) { _delay_ms(1000); } #ifdef WATCHDOG_ENABLED wdt_reset(); #endif //Bind a socket to receive data: //sockaddr Mission_Control_Address; memset((char *) &Mission_Control_Address, 0, sizeof(Mission_Control_Address)); Mission_Control_Address.sa_family = AF_INET; //The Source Port: Mission_Control_Address.sa_data[0] = (char)HEX_PORT_1; //(char)0x09; Mission_Control_Address.sa_data[1] = (char)HEX_PORT_2; //(char)0x56; //Configure the socket to not time out to keep the connection active. //-------------------------------------------------------------------- unsigned long aucDHCP = 14400; unsigned long aucARP = 3600; unsigned long aucKeepalive = 10; unsigned long aucInactivity = 0; netapp_timeout_values(&aucDHCP, &aucARP, &aucKeepalive, &aucInactivity); //TODO: //Should check the CC3000's profiles. In the case that there are no profiles found, then //inform the PC system, or use an LED. //Open a UDP socket that grabs datagram: Socket_Handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); switch(Socket_Handle) { case -1: //Error //Flag somehow. break; default: //Success //Set the socket configuration for blocking (since it is the only thing that is allowed). switch( bind(Socket_Handle, &Mission_Control_Address, sizeof(sockaddr))) { case -1: //Flag as ERROR. break; default: //Flag as good. break; } break; } #endif // NEED TO SETUP A QUICK REMOVAL FLAG FOR THIS CODE TO TEST THE CC3000. // #ifdef MOTOR_CONTROL_FLAG // Set up our Motor Controller Selection lines and the output for the RS232 lines: // DDRD |= (1 << DDD3) | (1 << DDD4) | (1 << DDD5); DDRD |= (1 << DDD3) | (1 << DDD5); // Initialize the UART (RS-232 communications) for the motor controller interface: // Set the Baud rate to 115200 bits/s. ((System Oscillator clock frequency / (2 * BAUD) ) - 1) // NOTE: The value may not be correct, according to the data sheet (pg. 213). // With the value 16, the error is 2.1% (lower than 8, being -3.5%). // This comes from util/setbaud.h UBRR1H = UBRRH_VALUE; /*Set baud rate*/ UBRR1L = UBRRL_VALUE; /*Set baud rate*/ //Defined in util/setbaud.h: #if USE_2X UCSR1A |= (1 << U2X1); //Double the baud rate for asynchronous communication. #else UCSR1A &= ~(1 << U2X1); #endif // Set to no parity and in Asynchronous mode. // 1 Stop bit. // 1 Start bit. // Set to 8-bit data. UCSR1C |= (1 << UCSZ11) | (1 << UCSZ10); //Enable the Rx and Tx lines. UCSR1B |= (1 << TXEN1); #ifdef TWI_ENABLED //Set the SCL frequency to 200 KHz. From the equation: f(SCL) = F_CPU/(16 + (2*TWBR) * (4^TWPS)) TWBR = 12; DDRB |= (1 << DDB4); //Setup PortB4 as the TWI error LED. #endif //End TWI_ENABLED _delay_ms(1000); //Wait for one second for the RoboteQs to finish booting. Set_Mode(SAFETY_MODE); // Set to Safe Mode to send Kill Command to Roboteq's Set_Mode(AUTONOMOUS_MODE); #ifdef ROUTER_WATCHDOG_ENABLED Count = 0; //Clear the Count variable out. TCNT1 = 0; //Clear the TCNT register. TCCR1B = (1 << CS12) | (1 << CS10); //Set the prescaler for 1024. TIMSK1 = (1 << OCIE1A); //Enable output compare for 1A. OCR1A = 39063; //Set the system to interrupt every 5 seconds. //OCR1A = (Multiplier) * (F_CPU) / (Prescaler) //39063 = (5) * (8000000) / (1024) #endif }
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(); }
/*------------------------------------------------------------------------ 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; }
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); }
void main (void) { unsigned long wake_utt; int rc; long lrc; char as_text[BSP430_UPTIME_AS_TEXT_LENGTH]; uint32_u ntp_addr; uint32_u self_addr; vBSP430platformInitialize_ni(); (void)iBSP430consoleInitialize(); cprintf("\nntp " __DATE__ " " __TIME__ "\n"); /* Initialization can be done with interrupts disabled, since the * function does nothing but store callbacks. We use the same * callback for all three update capabilities. */ rc = iBSP430cc3000spiInitialize(wlan_cb, NULL, NULL, NULL); if (0 > rc) { cprintf("ERR: Initialization failed: %d\n", rc); return; } BSP430_CORE_ENABLE_INTERRUPT(); /* Local addresses use all zeros for inet addr. bind does not * support dynamic assignment of unused port through sin_port=0. */ memset(&local_addr, 0, sizeof(local_addr)); local_addr.sai.sin_family = AF_INET; local_addr.sai.sin_port = htons(60123); /* Remote server will be determined by DNS from the NTP pool once we * start. */ remote_addr = local_addr; remote_addr.sai.sin_port = htons(123); ntp_addr.u32 = 0; self_addr.u32 = 0; cprintf("Remote: %s:%u\n", net_ipv4AsText(&remote_addr.sai.sin_addr), ntohs(remote_addr.sai.sin_port)); rc = sizeof(sBSP430uptimeNTPPacketHeader); if (48 != rc) { cprintf("ERR: NTP header size %d\n", rc); return; } wake_utt = ulBSP430uptime(); (void)rc; while (1) { unsigned long timeout_utt; do { tNetappIpconfigRetArgs ipc; unsigned long start_utt; unsigned long finished_utt; int sfd; int nfds; fd_set rfds; int servers_left; int retries_left; /* Clear everything as we're starting a cycle */ BSP430_CORE_DISABLE_INTERRUPT(); do { event_flags_v = 0; start_utt = ulBSP430uptime_ni(); } while (0); BSP430_CORE_ENABLE_INTERRUPT(); /* Start the WAN process. This is asynchronous; wait up to 2 * seconds for it to complete. */ cprintf("%s: ", xBSP430uptimeAsText(start_utt, as_text)); cputchar('W'); wlan_start(0); vBSP430ledSet(BSP430_LED_RED, 1); (void)wlan_set_event_mask(0UL); lrc = BSP430_UPTIME_MS_TO_UTT(2000); timeout_utt = ulBSP430uptime() + lrc; while ((! (EVENT_FLAG_WLANCONN & event_flags_v)) && (0 < ((lrc = lBSP430uptimeSleepUntil(timeout_utt, LPM0_bits))))) { } if (! (EVENT_FLAG_WLANCONN & event_flags_v)) { cprintf("WLAN start failed\n"); break; } /* Wait for IP connectivity (signalled by a DHCP event). * Continue using the previous timeout. */ cputchar('D'); while ((! (EVENT_FLAG_IPCONN & event_flags_v)) && (0 < ((lrc = lBSP430uptimeSleepUntil(timeout_utt, LPM0_bits))))) { } if (! (EVENT_FLAG_IPCONN & event_flags_v)) { cprintf("IP conn failed\n"); break; } /* Inspect the IP configuration. Sometimes we get the event, * but there's no IP assigned. */ netapp_ipconfig(&ipc); memcpy(self_addr.u8, ipc.aucIP, sizeof(self_addr)); if (! self_addr.u32) { cprintf("IP assignment failed\n"); break; } vBSP430ledSet(BSP430_LED_GREEN, 1); /* Obtain a UDP socket and bind it for local operations. */ cputchar('I'); sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (0 > sfd) { cprintf("socket() failed: %d\n", sfd); break; } cputchar('S'); lrc = bind(sfd, &local_addr.sa, sizeof(local_addr.sa)); if (0 > lrc) { cprintf("bind() failed: %ld\n", lrc); break; } cputchar('B'); servers_left = NTP_SERVERS_PER_ATTEMPT; retries_left = NTP_REQUESTS_PER_SERVER; do { sBSP430uptimeNTPPacketHeader ntp0; sBSP430uptimeNTPPacketHeader ntp1; int have_invalid_epoch; struct timeval tv; sockaddr_u src; socklen_t slen = sizeof(src); unsigned long recv_utt; uint64_t recv_ntp; int64_t adjustment_ntp; long adjustment_ms; unsigned long rtt_us; have_invalid_epoch = 0 != iBSP430uptimeCheckEpochValidity(); if (! remote_addr.sai.sin_addr.s_addr) { const char ntp_fqdn[] = "0.pool.ntp.org"; ntp_addr.u32 = 0; rc = gethostbyname((char *)ntp_fqdn, sizeof(ntp_fqdn)-1, &ntp_addr.u32); cputchar('d'); if (-95 == rc) { /* ARP request failed; retry usually works */ rc = gethostbyname((char *)ntp_fqdn, sizeof(ntp_fqdn)-1, &ntp_addr.u32); cputchar('d'); } if (0 == ntp_addr.u32) { cprintf("gethostbyname(%s) failed: %d\n", ntp_fqdn, rc); rc = -1; break; } remote_addr.sai.sin_addr.s_addr = htonl(ntp_addr.u32); cprintf("{%s}", net_ipv4AsText(&remote_addr.sai.sin_addr)); retries_left = NTP_REQUESTS_PER_SERVER; } /* Configure the NTP request and send it */ iBSP430uptimeInitializeNTPRequest(&ntp0); iBSP430uptimeSetNTPXmtField(&ntp0, NULL); BSP430_CORE_DISABLE_INTERRUPT(); do { /* Clear the shutdown bit, so we know when it's ok to shut * down after this send */ event_flags_v &= ~EVENT_FLAG_SHUTDOWN; } while (0); BSP430_CORE_ENABLE_INTERRUPT(); rc = sendto(sfd, &ntp0, sizeof(ntp0), 0, &remote_addr.sa, sizeof(remote_addr.sai)); if (sizeof(ntp0) != rc) { cprintf("sendto %s:%u failed: %d\n", net_ipv4AsText(&remote_addr.sai.sin_addr), ntohs(remote_addr.sai.sin_port), rc); rc = -1; break; } cputchar('s'); /* If we get an answer it should be here in less than 100 * ms, but give it 400 ms just to be kind. */ tv.tv_sec = 0; tv.tv_usec = 400000UL; FD_ZERO(&rfds); FD_SET(sfd, &rfds); nfds = sfd+1; rc = select(nfds, &rfds, NULL, NULL, &tv); if (! FD_ISSET(sfd, &rfds)) { /* We didn't get an answer. If there are any retries left, use them. */ if (0 < retries_left--) { rc = 1; continue; } /* No retries left on this server: forget about it. If * there are any servers left, try another. */ cputchar('!'); remote_addr.sai.sin_addr.s_addr = 0; if (0 < servers_left--) { rc = 1; continue; } /* No retries from all available servers. Fail this attempt */ cprintf("no responsive NTP server found\n"); rc = -1; break; } /* Got a response. Record the time it came in and then read * it (no high-resolution packet RX time available, but we * believe it's here already so set the RX time first). The * message is unacceptable if it isn't an NTP packet. */ recv_utt = ulBSP430uptime(); rc = recvfrom(sfd, &ntp1, sizeof(ntp1), 0, &src.sa, &slen); if (sizeof(ntp1) != rc) { cprintf("recv failed: %d\n", rc); rc = -1; break; } cputchar('r'); /* Convert the RX time to NTP, then process the message to * determine the offset. */ rc = iBSP430uptimeAsNTP(recv_utt, &recv_ntp, have_invalid_epoch); if (0 != rc) { cprintf("NTP decode failed: %d\n", rc); continue; } rc = iBSP430uptimeProcessNTPResponse(&ntp0, &ntp1, recv_ntp, &adjustment_ntp, &adjustment_ms, &rtt_us); if (0 != rc) { cprintf("Process failed: %d\n", rc); continue; } if (have_invalid_epoch) { rc = iBSP430uptimeSetEpochFromNTP(BSP430_UPTIME_BYPASS_EPOCH_NTP + adjustment_ntp); cputchar('E'); if (0 != rc) { cprintf("\nERR: SetEpoch failed: %d\n", rc); } #if (NTP_ADJUST_EACH_ITER - 0) } else { rc = iBSP430uptimeAdjustEpochFromNTP(adjustment_ntp); cputchar('A'); if (0 != rc) { cprintf("\nERR: AdjustEpoch failed: %d\n", rc); } #endif } cprintf("[%s:%u adj %lld ntp = %ld ms, rtt %lu us]", net_ipv4AsText(&remote_addr.sai.sin_addr), ntohs(remote_addr.sai.sin_port), adjustment_ntp, adjustment_ms, rtt_us); } while (0 != rc); if (0 != rc) { cprintf("NTP query failed\n"); break; } #if 0 /* The shutdown OK seems to arrive about 1000 ms after the last * transmit, which is unnecessarily long. As we're not doing * TCP, there's no reason to wait for it. */ lrc = BSP430_UPTIME_MS_TO_UTT(4000); timeout_utt = ulBSP430uptime() + lrc; while ((! (EVENT_FLAG_SHUTDOWN & event_flags_v)) && (0 < ((lrc = lBSP430uptimeSleepUntil(timeout_utt, LPM0_bits))))) { } if (! (EVENT_FLAG_SHUTDOWN & event_flags_v)) { cprintf("SHUTDOWN ok never received\n"); break; } #endif finished_utt = ulBSP430uptime(); cprintf("[%s]\n", xBSP430uptimeAsText(finished_utt - start_utt, as_text)); } while (0); BSP430_CORE_DISABLE_INTERRUPT(); do { event_flags_v = 0; } while (0); BSP430_CORE_ENABLE_INTERRUPT(); wlan_stop(); vBSP430ledSet(BSP430_LED_GREEN, 0); vBSP430ledSet(BSP430_LED_RED, 0); wake_utt += 60 * ulBSP430uptimeConversionFrequency_Hz(); while (0 < lBSP430uptimeSleepUntil(wake_utt, LPM2_bits)) { } } cprintf("Fell off end\n"); }