static void test_wlan_connect(int argc, char **argv) { #if 0 // usr for choose channel test if(argc >= 3) { int channel = atoi(argv[2]); wlan_set_channel(argc >= 2 ? argv[1] : NULL,channel); } #endif int ret = wlan_connect(argc >= 2 ? argv[1] : NULL); if (ret == WLAN_ERROR_STATE) { wmprintf("Error: connect manager not running\r\n"); return; } if (ret == WLAN_ERROR_PARAM) { wmprintf("Usage: %s <profile_name>\r\n", argv[0]); wmprintf("Error: specify a network to connect\r\n"); return; } wmprintf("Connecting to network...\r\nUse 'wlan-stat' for " "current connection status.\r\n"); }
/*------------------------------------------------------------------------ Spider_Connect Setting Spider connect to a exist AP. unsigned long sec_mode, security mode, OPEN = 0, WEP = 1, WPA = 2, WPA2 = 3, Reference with header file wlan.h. char* tar_ssid , target AP's SSID. char* tar_password , target AP's Password, leaving null with OPEN security. return 0, Connect success. return -1, Hardware uninitialized. return -2, Connection failed. -----------------------------------------------------------------------*/ int Spider_Connect(unsigned long sec_mode, char* tar_ssid, char* tar_password){ long ret; if(HW_Initialed != 1) return -1; // Disable auto connection function. wlan_ioctl_set_connection_policy(0, 0, 0); // Check and wait until CC3000 disconnect from current network. //while (SpiderConnected == 1) { // delay(100); //} // Connect to AP ret = wlan_connect(sec_mode, tar_ssid, strlen(tar_ssid), 0, (unsigned char*)tar_password, strlen(tar_password)); // Check connection failed. if(ret != 0){ return -2; } // Wait connect flag. //while(SpiderConnected != 1){ // delay(100); //} return 0; }
int target_initialise(void) { BoardInit(); wlan_configure(); sl_Start(0, 0, 0); // Both SSID and PASSWORD must be defined externally. wlan_connect(WIFI_SSID, WIFI_PASSWORD, SL_SEC_TYPE_WPA_WPA2); }
//***************************************************************************** // Crasons First FUnction //! DefaultWifiConnection //! //! \param none //! //! \return none //! //! \brief Connect to an Access Point using the default values "demo_config.h" // //***************************************************************************** int DefaultWifiConnection(void) { unsetCC3000MachineState(CC3000_ASSOC); // Disable Profiles and Fast Connect wlan_ioctl_set_connection_policy(0, 0, 0); wlan_disconnect(); __delay_cycles(10000); wlan_connect(DEFAULT_AP_SECURITY, DEFAULT_OUT_OF_BOX_SSID, strlen(DEFAULT_OUT_OF_BOX_SSID), NULL, DFAULT_AP_SECURITY_KEY, strlen(DFAULT_AP_SECURITY_KEY)); return 0; }
/*JSON{ "type":"staticmethod", "class" : "WLAN", "name" : "connect", "generate" : "jswrap_wlan_connect", "description" : "Connect to a wireless network", "params" : [ [ "ap", "JsVar", "Access point name" ], [ "key", "JsVar", "WPA2 key (or undefined for unsecured connection)" ] ], "return" : ["int", ""] }*/ JsVarInt jswrap_wlan_connect(JsVar *vAP, JsVar *vKey) { char ap[32]; char key[32]; unsigned long security = WLAN_SEC_UNSEC; jsvGetString(vAP, ap, sizeof(ap)); if (jsvIsString(vKey)) { security = WLAN_SEC_WPA2; jsvGetString(vKey, key, sizeof(key)); } // might want to set wlan_ioctl_set_connection_policy return wlan_connect(security, ap, strlen(ap), NULL, key, strlen(key)); }
int app_connect_to_p2p_go(struct wlan_network *net) { app_l("connecting to P2P GO"); memcpy(net->name, DEF_NET_NAME, sizeof(net->name)); int ret = wlan_add_network(net); if (ret != WLAN_ERROR_NONE) { app_e("network_mgr: failed to add network %d", ret); return -WM_E_AF_NW_ADD; } wlan_connect(net->name); return WM_SUCCESS; }
//***************************************************************************** // //! ConnectUsingSSID //! //! \param ssidName is a string of the AP's SSID //! //! \return none //! //! \brief Connect to an Access Point using the specified SSID // //***************************************************************************** int ConnectUsingSSID(char * ssidName) { unsetCC3000MachineState(CC3000_ASSOC); // Disable Profiles and Fast Connect wlan_ioctl_set_connection_policy(0, 0, 0); wlan_disconnect(); __delay_cycles(10000); // This triggers the CC3000 to connect to specific AP with certain parameters //sends a request to connect (does not necessarily connect - callback checks that for me) #ifndef CC3000_TINY_DRIVER wlan_connect(0, ssidName, strlen(ssidName), NULL, NULL, 0); #else wlan_connect(ssidName, strlen(ssidName)); #endif // We don't wait for connection. This is handled somewhere else (in the main // loop for example). return 0; }
void ManualConnect(void) { char ssidName[] = "YourAP"; char AP_KEY[] = "yourpass"; uint8_t rval; if (!isInitialized) { printf("CC3000 not initialized; can't run manual connect.\n"); return; } printf("Starting manual connect...\n"); printf(" Disabling auto-connect policy...\n"); (void)wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE); printf(" Deleting all existing profiles...\n"); (void)wlan_ioctl_del_profile(255); wait_on(15*MS_PER_SEC, &ulCC3000Connected, 0, " Waiting until disconnected"); printf(" Manually connecting...\n"); /* Parameter 1 is the security type: WLAN_SEC_UNSEC, WLAN_SEC_WEP, * WLAN_SEC_WPA or WLAN_SEC_WPA2 * Parameter 3 is the MAC adddress of the AP. All the TI examples * use NULL. I suppose you would want to specify this * if you were security paranoid. */ rval = wlan_connect(WLAN_SEC_WPA2, ssidName, strlen(ssidName), NULL, (uint8_t *)AP_KEY, strlen(AP_KEY)); if (rval == 0) { printf(" Manual connect success.\n"); } else { printf(" Unusual return value: %d\n", rval); } }
static mp_obj_t mod_wlan_connect(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { int ssid_len =0; const char *ssid = NULL; const char *bssid = NULL; int key_len =0; int sec = WLAN_SEC_UNSEC; const char *key = NULL; mp_map_elem_t *kw_key, *kw_sec, *kw_bssid; ssid = mp_obj_str_get_str(args[0]); ssid_len = strlen(ssid); /* get KW args */ kw_key = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("key")), MP_MAP_LOOKUP); kw_sec = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("sec")), MP_MAP_LOOKUP); kw_bssid = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("bssid")), MP_MAP_LOOKUP); /* get key and sec */ if (kw_key && kw_sec) { key = mp_obj_str_get_str(kw_key->value); key_len = strlen(key); sec = mp_obj_get_int(kw_sec->value); if (!IS_WLAN_SEC(sec)) { nlr_raise(mp_obj_new_exception_msg( &mp_type_ValueError, "Invalid security mode")); return mp_const_false; } } /* get bssid */ if (kw_bssid != NULL) { bssid = mp_obj_str_get_str(kw_bssid->value); } /* connect to AP */ if (wlan_connect(sec, (char*) ssid, ssid_len, (uint8_t*)bssid, (uint8_t*)key, key_len) != 0) { return mp_const_false; } return mp_const_true; }
/*JSON{ "type" : "method", "class" : "WLAN", "name" : "connect", "generate" : "jswrap_wlan_connect", "params" : [ ["ap","JsVar","Access point name"], ["key","JsVar","WPA2 key (or undefined for unsecured connection)"], ["callback","JsVar","Function to call back with connection status. It has one argument which is one of 'connect'/'disconnect'/'dhcp'"] ], "return" : ["bool","True if connection succeeded, false if it didn't."] } Connect to a wireless network */ bool jswrap_wlan_connect(JsVar *wlanObj, JsVar *vAP, JsVar *vKey, JsVar *callback) { if (!(jsvIsUndefined(callback) || jsvIsFunction(callback))) { jsError("Expecting callback Function but got %t", callback); return 0; } JsNetwork net; if (!networkGetFromVar(&net)) return false; // if previously completely disconnected, try and reconnect if (jsvGetBoolAndUnLock(jsvObjectGetChild(wlanObj,JS_HIDDEN_CHAR_STR"DIS",0))) { cc3000_initialise(wlanObj); jsvObjectSetChildAndUnLock(wlanObj,JS_HIDDEN_CHAR_STR"DIS", jsvNewFromBool(false)); } if (jsvIsFunction(callback)) { jsvObjectSetChild(wlanObj, CC3000_ON_STATE_CHANGE, callback); } jsvObjectSetChild(wlanObj,JS_HIDDEN_CHAR_STR"AP", vAP); // no unlock intended jsvObjectSetChild(wlanObj,JS_HIDDEN_CHAR_STR"KEY", vKey); // no unlock intended char ap[32]; char key[32]; unsigned long security = WLAN_SEC_UNSEC; jsvGetString(vAP, ap, sizeof(ap)); if (jsvIsString(vKey)) { security = WLAN_SEC_WPA2; jsvGetString(vKey, key, sizeof(key)); } // might want to set wlan_ioctl_set_connection_policy bool connected = wlan_connect(security, ap, (long)strlen(ap), NULL, (unsigned char*)key, (long)strlen(key))==0; networkFree(&net); // note that we're only online (for networkState) when DHCP succeeds return connected; }
int hw_net_connect (const char *security_type, const char *ssid, size_t ssid_len , const char *keys, size_t keys_len) { CC3000_START; int security = WLAN_SEC_WPA2; char * security_print = "wpa2"; if (keys_len == 0){ security = WLAN_SEC_UNSEC; security_print = "unsecure"; } else if (strcicmp(security_type, "wpa") == 0){ security = WLAN_SEC_WPA; security_print = "wpa"; } else if (strcicmp(security_type, "wep") == 0){ security = WLAN_SEC_WEP; security_print = "wep"; } TM_DEBUG("Attempting to connect with security type %s... ", security_print); wlan_ioctl_set_connection_policy(0, 1, 0); int connected = wlan_connect(security, (char *) ssid, ssid_len , 0, (uint8_t *) keys, keys_len); if (connected != 0) { TM_DEBUG("Error #%d in connecting. Please try again.", connected); // wlan_disconnect(); error2count = 0; _cc3000_cb_error(connected); } else { error2count = 0; TM_DEBUG("Acquiring IP address..."); _cc3000_cb_acquire(); } CC3000_END; return connected; }
int main(/*int argc, char *argv[]*/) { #ifdef CC32XX BoardInit(); wlan_configure(); sl_Start(0, 0, 0); wlan_connect("<SSID>", "<PASSWORD>", SL_SEC_TYPE_WPA_WPA2);//Into <SSID> and <PASSWORD> put your access point name and password #endif DEMO_LOG("Configuration demo started"); /** * Initialize Kaa client. */ kaa_error_t error_code = kaa_client_create(&kaa_client, NULL); KAA_DEMO_RETURN_IF_ERROR(error_code, "Failed create Kaa client"); kaa_configuration_root_receiver_t receiver = { NULL, &kaa_demo_configuration_receiver }; error_code = kaa_configuration_manager_set_root_receiver(kaa_client_get_context(kaa_client)->configuration_manager, &receiver); KAA_DEMO_RETURN_IF_ERROR(error_code, "Failed to add configuration receiver"); kaa_demo_print_configuration_message(kaa_configuration_manager_get_configuration(kaa_client_get_context(kaa_client)->configuration_manager)); /** * Start Kaa client main loop. */ error_code = kaa_client_start(kaa_client, NULL, NULL, 0); KAA_DEMO_RETURN_IF_ERROR(error_code, "Failed to start Kaa main loop"); /** * Destroy Kaa client. */ kaa_client_destroy(kaa_client); DEMO_LOG("Configuration demo stopped"); return error_code; }
//***************************************************************************** // //! DemoHandleUartCommand //! //! @param buffer //! //! @return none //! //! @brief The function handles commands arrived from CLI // //***************************************************************************** void DemoHandleUartCommand(unsigned char *usBuffer) { char *pcSsid, *pcData, *pcSockAddrAscii; unsigned long ulSsidLen, ulDataLength; volatile signed long iReturnValue; sockaddr tSocketAddr; socklen_t tRxPacketLength; unsigned char pucIP_Addr[4]; unsigned char pucIP_DefaultGWAddr[4]; unsigned char pucSubnetMask[4]; unsigned char pucDNS[4]; // usBuffer[0] contains always 0 // usBuffer[1] maps the command // usBuffer[2..end] optional parameters switch(usBuffer[1]) { // Start a smart configuration process case UART_COMMAND_CC3000_SIMPLE_CONFIG_START: StartSmartConfig(); break; // Start a WLAN Connect process case UART_COMMAND_CC3000_CONNECT: { ulSsidLen = atoc(usBuffer[2]); pcSsid = (char *)&usBuffer[3]; #ifndef CC3000_TINY_DRIVER wlan_connect(WLAN_SEC_UNSEC, pcSsid, ulSsidLen,NULL, NULL, 0); #else wlan_connect(pcSsid,ulSsidLen); #endif } break; // Handle open socket command case UART_COMMAND_SOCKET_OPEN: // wait for DHCP process to finish. if you are using a static IP address // please delete the wait for DHCP event - ulCC3000DHCP while ((ulCC3000DHCP == 0) || (ulCC3000Connected == 0)) { hci_unsolicited_event_handler(); SysCtlDelay(1000); } ulSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); break; // Handle close socket command case UART_COMMAND_SOCKET_CLOSE: closesocket(ulSocket); ulSocket = 0xFFFFFFFF; break; // Handle receive data command case UART_COMMAND_RCV_DATA: iReturnValue = recvfrom(ulSocket, pucCC3000_Rx_Buffer, CC3000_APP_BUFFER_SIZE, 0, &tSocketAddr, &tRxPacketLength); if (iReturnValue <= 0) { // No data received by device DispatcherUartSendPacket((unsigned char*)pucUARTNoDataString, sizeof(pucUARTNoDataString)); } else { // Send data to UART... DispatcherUartSendPacket(pucCC3000_Rx_Buffer, CC3000_APP_BUFFER_SIZE); } break; // Handle send data command case UART_COMMAND_SEND_DATA: // data pointer pcData = (char *)&usBuffer[4]; // data length to send ulDataLength = atoshort(usBuffer[2], usBuffer[3]); pcSockAddrAscii = (pcData + ulDataLength); // the family is always AF_INET tSocketAddr.sa_family = atoshort(pcSockAddrAscii[0], pcSockAddrAscii[1]); // the destination port tSocketAddr.sa_data[0] = ascii_to_char(pcSockAddrAscii[2], pcSockAddrAscii[3]); tSocketAddr.sa_data[1] = ascii_to_char(pcSockAddrAscii[4], pcSockAddrAscii[5]); // the destination IP address tSocketAddr.sa_data[2] = ascii_to_char(pcSockAddrAscii[6], pcSockAddrAscii[7]); tSocketAddr.sa_data[3] = ascii_to_char(pcSockAddrAscii[8], pcSockAddrAscii[9]); tSocketAddr.sa_data[4] = ascii_to_char(pcSockAddrAscii[10], pcSockAddrAscii[11]); tSocketAddr.sa_data[5] = ascii_to_char(pcSockAddrAscii[12], pcSockAddrAscii[13]); sendto(ulSocket, pcData, ulDataLength, 0, &tSocketAddr, sizeof(sockaddr)); break; // Handle bind command case UART_COMMAND_BSD_BIND: tSocketAddr.sa_family = AF_INET; // the source port tSocketAddr.sa_data[0] = ascii_to_char(usBuffer[2], usBuffer[3]); tSocketAddr.sa_data[1] = ascii_to_char(usBuffer[4], usBuffer[5]); // all 0 IP address memset (&tSocketAddr.sa_data[2], 0, 4); bind(ulSocket, &tSocketAddr, sizeof(sockaddr)); break; // Handle IP configuration command case UART_COMMAND_IP_CONFIG: // Network mask is assumed to be 255.255.255.0 pucSubnetMask[0] = 0xFF; pucSubnetMask[1] = 0xFF; pucSubnetMask[2] = 0xFF; pucSubnetMask[3] = 0x0; pucIP_Addr[0] = ascii_to_char(usBuffer[2], usBuffer[3]); pucIP_Addr[1] = ascii_to_char(usBuffer[4], usBuffer[5]); pucIP_Addr[2] = ascii_to_char(usBuffer[6], usBuffer[7]); pucIP_Addr[3] = ascii_to_char(usBuffer[8], usBuffer[9]); pucIP_DefaultGWAddr[0] = ascii_to_char(usBuffer[10], usBuffer[11]); pucIP_DefaultGWAddr[1] = ascii_to_char(usBuffer[12], usBuffer[13]); pucIP_DefaultGWAddr[2] = ascii_to_char(usBuffer[14], usBuffer[15]); pucIP_DefaultGWAddr[3] = ascii_to_char(usBuffer[16], usBuffer[17]); pucDNS[0] = 0; pucDNS[1] = 0; pucDNS[2] = 0; pucDNS[3] = 0; netapp_dhcp((unsigned long *)pucIP_Addr, (unsigned long *)pucSubnetMask, (unsigned long *)pucIP_DefaultGWAddr, (unsigned long *)pucDNS); break; // Handle WLAN disconnect command case UART_COMMAND_CC3000_DISCONNECT: wlan_disconnect(); break; // Handle erase policy command case UART_COMMAND_CC3000_DEL_POLICY: wlan_ioctl_set_connection_policy(DISABLE, DISABLE, DISABLE); break; // Handle send DNS Discovery command case UART_COMMAND_SEND_DNS_ADVERTIZE: if(ulCC3000DHCP) { mdnsAdvertiser(1,device_name,strlen(device_name)); } break; default: DispatcherUartSendPacket((unsigned char*)pucUARTIllegalCommandString, sizeof(pucUARTIllegalCommandString)); break; } // Send a response - the command handling has finished DispatcherUartSendPacket((unsigned char *)(pucUARTCommandDoneString), sizeof(pucUARTCommandDoneString)); }
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; } } }
/* must already be powered on. * MGMT LOCK/UNLOCK NEEDS CALLED EXTERNALLY */ static clarityError connectToWifi_mtxext(void) { int32_t wlanRtn; uint8_t loopIterations = 10; uint8_t presentCount = 0; clarityCC3000ApiLock(); memset((void*)&cc3000AsyncData, 0, sizeof(cc3000AsyncData)); CLAR_PRINT_LINE("about to call wlan_connect()"); if (mgmtData.ap->secType == WLAN_SEC_UNSEC) { wlanRtn = wlan_connect(mgmtData.ap->secType, mgmtData.ap->name, strnlen(mgmtData.ap->name, CLARITY_MAX_AP_STR_LEN), NULL, NULL, 0); } else { wlanRtn = wlan_connect(mgmtData.ap->secType, mgmtData.ap->name, strnlen(mgmtData.ap->name, CLARITY_MAX_AP_STR_LEN), NULL, (unsigned char*)mgmtData.ap->password, strnlen(mgmtData.ap->password, CLARITY_MAX_AP_STR_LEN)); } CLAR_PRINT_LINE("called wlan_connect()"); if (wlanRtn != 0) { CLAR_PRINT_LINE("wlan_connect() returned non zero."); } else { while (presentCount != 3) { if (cc3000AsyncData.connected != true || cc3000AsyncData.dhcp.present != true) { presentCount = 0; } else { presentCount++; } if (loopIterations-- == 0) { wlanRtn = 1; CLAR_PRINT_LINE_ARGS("Connected: %d DHCP Present: %d. Breaking!", cc3000AsyncData.connected, cc3000AsyncData.dhcp.present); break; } chThdSleep(MS2ST(500)); } } clarityCC3000ApiUnlock(); if (cc3000AsyncData.connected == true && cc3000AsyncData.dhcp.present == true) { CLAR_PRINT_LINE("Connected!"); } if (wlanRtn == 0) { return CLARITY_SUCCESS; } else { CLAR_PRINT_ERROR(); return CLARITY_ERROR_CC3000_WLAN; } }
/** * @brief Connects to a WAP using the given SSID and password * * @param[in] ssid the SSID for the wireless network * @param[in] security type of security for the network * @param[in] password optional ASCII password if connecting to a secured AP * @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::connect( char *ssid, unsigned int security, char *password, unsigned int timeout) { unsigned long time; /* If CC3000 is not initialized, return false. */ if (!getInitStatus()) { return false; } /* If already connected, return false. */ if (getDHCPStatus()) { return false; } /* If security mode is not a predefined type, return false. */ if ( !( security == WLAN_SEC_UNSEC || security == WLAN_SEC_WEP || security == WLAN_SEC_WPA || security == WLAN_SEC_WPA2) ) { 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; } /* Connect to the given access point*/ time = millis(); while (getConnectionStatus() == false) { /* Attempt to connect to an AP */ delay(10); if (security == WLAN_SEC_UNSEC) { if (wlan_connect( WLAN_SEC_UNSEC, ssid, strlen(ssid), 0, 0, 0) == CC3000_SUCCESS) { break; } } else { if (wlan_connect( security, ssid, strlen(ssid), 0, (unsigned char*)password, strlen(password)) == CC3000_SUCCESS) { break; } } /* Check against timeout. Return if out of time. */ if (timeout != 0) { if ( (millis() - time) > timeout ) { return false; } } } /* Wait for DHCP */ while (getDHCPStatus() == false) { if (timeout != 0) { if ( (millis() - time) > timeout ) { return false; } } } /* Get connection information */ netapp_ipconfig(&connection_info_); return true; }
/** * @brief Process WPS Enrollee PIN mode and PBC user selection operations * * @param pwps_info A pointer to WPS_INFO structure * @param wps_s A pointer to global WPS structure * @return WPS_STATUS_SUCCESS--success, otherwise--fail */ int wps_enrollee_start(PWPS_INFO pwps_info, WPS_DATA *wps_s) { int ret = WPS_STATUS_SUCCESS; #ifndef CONFIG_WPA2_ENTP int retry_cnt = 5; int connect_retry = 10; enum wlan_connection_state state; #endif ENTER(); pwps_info->enrollee.auth_type_flag = AUTHENTICATION_TYPE_ALL; pwps_info->enrollee.encry_type_flag = ENCRYPTION_TYPE_ALL; #ifndef CONFIG_WPA2_ENTP if (pwps_info->enrollee.device_password_id == DEVICE_PASSWORD_ID_PIN) { /* Generate PIN */ wps_generate_PIN(pwps_info); if (pwps_info->pin_generator == WPS_ENROLLEE) { pwps_info->input_state = WPS_INPUT_STATE_NO_INPUT; pwps_info->pin_pbc_set = WPS_SET; } else { pwps_info->enrollee.updated_device_password_id = DEVICE_PASSWORD_REG_SPECIFIED; } } memset(&wps_network, 0, sizeof(struct wlan_network)); if (g_ssid && strlen((const char *)g_ssid)) strncpy(wps_network.name, (const char *) g_ssid, MAX_SSID_LEN + 1); else strncpy(wps_network.name, "p2p_network", MAX_SSID_LEN + 1); memcpy(wps_network.ssid, (const char *) g_ssid, MAX_SSID_LEN + 1); memcpy(wps_network.bssid, (const char *) g_bssid, ETH_ALEN); wps_network.channel = g_channel; wps_network.address.addr_type = ADDR_TYPE_DHCP; #ifdef CONFIG_WPS2 wps_network.wps_specific = 1; #endif if (g_channel) wps_network.channel_specific = 1; else if (is_mac_all_zero(g_bssid)) wps_network.ssid_specific = 1; else wps_network.bssid_specific = 1; wps_network.security.type = WLAN_SECURITY_NONE; #ifdef CONFIG_P2P wps_network.type = WLAN_BSS_TYPE_WIFIDIRECT; wps_network.role = WLAN_BSS_ROLE_STA; #endif ret = wlan_add_network(&wps_network); if (ret != 0) { WPS_LOG(" Failed to add network %d\r\n", ret); goto fail; } do { WPS_LOG("Connecting to %s .....", wps_network.ssid); ret = wlan_connect(wps_network.name); if (ret != 0) { WPS_LOG("Failed to connect %d\r\n", ret); goto retry; } connect_retry = 200; do { /* wait for interface up */ os_thread_sleep(os_msec_to_ticks(50)); if (wlan_get_connection_state(&state)) { P2P_LOG("Error: unable to get " "connection state\r\n"); continue; } if (state == WLAN_ASSOCIATED || connect_retry == 0) break; #ifdef CONFIG_P2P connect_retry--; } while (state != WLAN_DISCONNECTED); #else } while (connect_retry--); #endif if (state != WLAN_ASSOCIATED) { WPS_LOG("Error: Not connected.\r\n"); goto retry; } WPS_LOG("Connected to following BSS (or IBSS) :"); WPS_LOG ("SSID = [%s], BSSID = [%02x:%02x:%02x:%02x:%02x:%02x]", wps_network.ssid, wps_network.bssid[0], wps_network.bssid[1], wps_network.bssid[2], wps_network.bssid[3], wps_network.bssid[4], wps_network.bssid[5]); /* Save information to global structure */ wps_s->current_ssid.ssid_len = strlen(wps_network.ssid); memcpy(wps_s->current_ssid.ssid, wps_network.ssid, wps_s->current_ssid.ssid_len); memcpy(wps_s->current_ssid.bssid, wps_network.bssid, ETH_ALEN); /* Store Peer MAC Address */ if (pwps_info->role == WPS_ENROLLEE || (IS_DISCOVERY_ENROLLEE(pwps_info)) ) { if (is_mac_all_zero((u8 *) wps_network.bssid)) { if (wlan_get_current_network(&sta_network)) goto fail; memcpy(pwps_info->registrar.mac_address, sta_network.bssid, ETH_ALEN); } else memcpy(pwps_info->registrar.mac_address, wps_network.bssid, ETH_ALEN); } #else /* Save information to global structure */ wps_s->current_ssid.ssid_len = strlen(wps_s->wpa2_network.ssid); memcpy(wps_s->current_ssid.ssid, wps_s->wpa2_network.ssid, wps_s->current_ssid.ssid_len); memcpy(wps_s->current_ssid.bssid, wps_s->wpa2_network.bssid, ETH_ALEN); /* Store Peer MAC Address */ if (pwps_info->role == WPS_ENROLLEE || (IS_DISCOVERY_ENROLLEE(pwps_info)) ) { if (is_mac_all_zero((u8 *) wps_s->wpa2_network.bssid)) { if (wlan_get_current_network(&sta_network)) goto fail; memcpy(pwps_info->registrar.mac_address, sta_network.bssid, ETH_ALEN); } else memcpy(pwps_info->registrar.mac_address, wps_s->wpa2_network.bssid, ETH_ALEN); } #endif #ifdef CONFIG_P2P WPS_LOG("Registration Process Started...."); #elif CONFIG_WPA2_ENTP WPS_LOG("Connected to following BSS (or IBSS) :"); WPS_LOG ("SSID = [%s], BSSID = [%02x:%02x:%02x:%02x:%02x:%02x]", wps_s->wpa2_network.ssid, wps_s->wpa2_network.bssid[0], wps_s->wpa2_network.bssid[1], wps_s->wpa2_network.bssid[2], wps_s->wpa2_network.bssid[3], wps_s->wpa2_network.bssid[4], wps_s->wpa2_network.bssid[5]); WPS_LOG("WPA2 Enterprise (EAP-TLS) Protocol Started ....."); #else WPS_LOG("WPS Registration Protocol Started ....."); if (wps.cb(WPS_SESSION_STARTED, NULL, 0) == -WM_FAIL) WPS_LOG("WPS Callback failed for event: %d\r\n", WPS_SESSION_STARTED); #endif /* Start WPS registration timer */ wps_start_registration_timer(pwps_info); /* Starting WPS Message Exchange Engine */ wps_state_machine_start(pwps_info); ret = WPS_STATUS_SUCCESS; #ifndef CONFIG_WPA2_ENTP break; retry: retry_cnt--; WPS_LOG("Connect to AP FAIL ! Retrying ..... \r\n"); wps_printf(DEBUG_WLAN | DEBUG_INIT, "Retry Count = %d", retry_cnt); } while (retry_cnt != 0);
void SPARK_WLAN_Loop(void) { 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; TimingSparkCommTimeout = 0; CC3000_Write_Enable_Pin(WLAN_DISABLE); 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 && !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 = 0; } // 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(WLAN_DHCP && !SPARK_WLAN_SLEEP && !SPARK_SOCKET_CONNECTED) { Delay(100); netapp_ipconfig(&ip_config); #if defined (USE_SPARK_CORE_V02) 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); #endif if(Spark_Connect() < 0) { if(SPARK_WLAN_RESET) return; if(Internet_Test() < 0) { //No Internet Connection 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; } else { SPARK_SOCKET_CONNECTED = 1; } } }
/* * @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 }