static mp_obj_t mod_wlan_ifconfig() { tNetappIpconfigRetArgs ipconfig; uint8_t *ip = &ipconfig.aucIP[0]; uint8_t *mask= &ipconfig.aucSubnetMask[0]; uint8_t *gw= &ipconfig.aucDefaultGateway[0]; uint8_t *dhcp= &ipconfig.aucDHCPServer[0]; uint8_t *dns= &ipconfig.aucDNSServer[0]; uint8_t *mac= &ipconfig.uaMacAddr[0]; // uint8_t *ssid= &ipconfig.uaSSID[0]; //32 netapp_ipconfig(&ipconfig); printf ("IP:%d.%d.%d.%d\n" \ "Mask:%d.%d.%d.%d\n"\ "GW:%d.%d.%d.%d\n" \ "DHCP:%d.%d.%d.%d\n"\ "DNS:%d.%d.%d.%d\n" \ "MAC:%02X:%02X:%02X:%02X:%02X:%02X\n", ip[3], ip[2], ip[1], ip[0], mask[3], mask[2], mask[1], mask[0], gw[3], gw[2], gw[1], gw[0], dhcp[3], dhcp[2], dhcp[1], dhcp[0], dns[3], dns[2], dns[1], dns[0], mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]); return mp_const_none; }
int wlan_connected_rssi() { int _returnValue = 0; system_tick_t _functionStart = HAL_Timer_Get_Milli_Seconds(); while ((HAL_Timer_Get_Milli_Seconds() - _functionStart) < 1000) { tNetappIpconfigRetArgs config; netapp_ipconfig((void*)&config); int l; for (l=0; l<16; l++) { char wlan_scan_results_table[50]; if(wlan_ioctl_get_scan_results(0, (unsigned char*)wlan_scan_results_table) != 0) { _returnValue = 1; break; } if (wlan_scan_results_table[0] == 0) break; if (!strcmp(wlan_scan_results_table+12, config.uaSSID)) { _returnValue = ((wlan_scan_results_table[8] >> 1) - 127); break; } } if (_returnValue != 0) { break; } }
/*JSON{ "type":"method", "class" : "WLAN", "name" : "setIP", "generate" : "jswrap_wlan_setIP", "description" : ["Set the current IP address for get an IP from DHCP (if no options object is specified).", "**Note:** Changes are written to non-volatile memory, but will only take effect after calling `wlan.reconnect()`" ], "params" : [ [ "options", "JsVar", "Object containing IP address options `{ ip : '1,2,3,4', subnet, gateway, dns }`, or do not supply an object in otder to force DHCP."] ], "return" : ["bool", "True on success"] }*/ bool jswrap_wlan_setIP(JsVar *wlanObj, JsVar *options) { NOT_USED(wlanObj); if (networkState != NETWORKSTATE_ONLINE) { jsError("Not connected to the internet"); return false; } tNetappIpconfigRetArgs ipconfig; netapp_ipconfig(&ipconfig); if (jsvIsObject(options)) { _wlan_getIP_set_address(options, "ip", &ipconfig.aucIP[0]); _wlan_getIP_set_address(options, "subnet", &ipconfig.aucSubnetMask[0]); _wlan_getIP_set_address(options, "gateway", &ipconfig.aucDefaultGateway[0]); _wlan_getIP_set_address(options, "dns", &ipconfig.aucDNSServer[0]); } else { // DHCP - just set all values to 0 *((unsigned long*)&ipconfig.aucIP[0]) = 0; *((unsigned long*)&ipconfig.aucSubnetMask) = 0; *((unsigned long*)&ipconfig.aucDefaultGateway) = 0; } return netapp_dhcp( (unsigned long *)&ipconfig.aucIP[0], (unsigned long *)&ipconfig.aucSubnetMask[0], (unsigned long *)&ipconfig.aucDefaultGateway[0], (unsigned long *)&ipconfig.aucDNSServer[0]) == 0; }
/*JSON{ "type" : "method", "class" : "WLAN", "name" : "getIP", "generate" : "jswrap_wlan_getIP", "return" : ["JsVar",""] } Get the current IP address */ JsVar *jswrap_wlan_getIP(JsVar *wlanObj) { NOT_USED(wlanObj); if (networkState != NETWORKSTATE_ONLINE) { jsError("Not connected to the internet"); return 0; } JsNetwork net; if (!networkGetFromVar(&net)) return 0; tNetappIpconfigRetArgs ipconfig; netapp_ipconfig(&ipconfig); networkFree(&net); /* If byte 1 is 0 we don't have a valid address */ if (ipconfig.aucIP[3] == 0) return 0; JsVar *data = jsvNewWithFlags(JSV_OBJECT); networkPutAddressAsString(data, "ip", &ipconfig.aucIP[0], -4, 10, '.'); networkPutAddressAsString(data, "subnet", &ipconfig.aucSubnetMask[0], -4, 10, '.'); networkPutAddressAsString(data, "gateway", &ipconfig.aucDefaultGateway[0], -4, 10, '.'); networkPutAddressAsString(data, "dhcp", &ipconfig.aucDHCPServer[0], -4, 10, '.'); networkPutAddressAsString(data, "dns", &ipconfig.aucDNSServer[0], -4, 10, '.'); networkPutAddressAsString(data, "mac", &ipconfig.uaMacAddr[0], -6, 16, 0); return data; }
tNetappIpconfigRetArgs * getCC3000Info() { if(!(currentCC3000State() & CC3000_SERVER_INIT)) { // If we're not blocked by accept or others, obtain the latest netapp_ipconfig(&ipinfo); } return &ipinfo; }
uint32_t hw_net_defaultgateway () { CC3000_START; tNetappIpconfigRetArgs ipinfo; netapp_ipconfig(&ipinfo); CC3000_END; char* aliasable_ip = (char*) ipinfo.aucDefaultGateway; return *((uint32_t *) aliasable_ip); }
uint32_t hw_net_dnsserver () { CC3000_START; tNetappIpconfigRetArgs ipinfo; netapp_ipconfig(&ipinfo); CC3000_END; char* aliasable_ip = (char*) ipinfo.aucDNSServer; return *((uint32_t *) aliasable_ip); }
void setup() { server.begin(); netapp_ipconfig(&ip_config); #ifdef DEBUG Serial.begin(115200); #endif IPAddress myIp = Network.localIP(); sprintf(myIpString, "%d.%d.%d.%d:%d", myIp[0], myIp[1], myIp[2], myIp[3], PORT); Spark.variable("endpoint", myIpString, STRING); }
int hw_net_ssid (char ssid[33]) { if (hw_net_online_status()) { CC3000_START; tNetappIpconfigRetArgs ipinfo; netapp_ipconfig(&ipinfo); memset(ssid, 0, 33); memcpy(ssid, ipinfo.uaSSID, 32); CC3000_END; } else { memset(ssid, 0, 33); } return 0; }
void ShowInformation(void) { tNetappIpconfigRetArgs inf; char localB[33]; int i; if (!isInitialized) { printf("CC3000 not initialized; can't get information.\n"); return; } printf("CC3000 information:\n"); netapp_ipconfig(&inf); printf(" IP address: "); PrintIPBytes(inf.aucIP); printf(" Subnet mask: "); PrintIPBytes(inf.aucSubnetMask); printf(" Gateway: "); PrintIPBytes(inf.aucDefaultGateway); printf(" DHCP server: "); PrintIPBytes(inf.aucDHCPServer); printf(" DNS server: "); PrintIPBytes(inf.aucDNSServer); printf(" MAC address: "); for (i=(MAC_ADDR_LEN-1); i>=0; i--) { if (i!=(MAC_ADDR_LEN-1)) { printf(":"); } printf("%x", inf.uaMacAddr[i]); } printf("\n"); memset(localB, 0, sizeof(localB)); strncpy(localB, (char*)inf.uaSSID,sizeof(localB)); printf(" Connected to SSID: %s\n", localB); }
/*JSON{ "type":"staticmethod", "class" : "WLAN", "name" : "getIP", "generate" : "jswrap_wlan_getIP", "description" : "Get the current IP address", "return" : ["JsVar", ""] }*/ JsVar *jswrap_wlan_getIP() { tNetappIpconfigRetArgs ipconfig; netapp_ipconfig(&ipconfig); /* If byte 1 is 0 we don't have a valid address */ if (ipconfig.aucIP[3] == 0) return 0; JsVar *data = jsvNewWithFlags(JSV_OBJECT); _wlan_getIP_get_address(data, "ip", &ipconfig.aucIP, 4, 10, '.'); _wlan_getIP_get_address(data, "subnet", &ipconfig.aucSubnetMask, 4, 10, '.'); _wlan_getIP_get_address(data, "gateway", &ipconfig.aucDefaultGateway, 4, 10, '.'); _wlan_getIP_get_address(data, "dhcp", &ipconfig.aucDHCPServer, 4, 10, '.'); _wlan_getIP_get_address(data, "dns", &ipconfig.aucDNSServer, 4, 10, '.'); _wlan_getIP_get_address(data, "mac", &ipconfig.uaMacAddr, 6, 16, 0); // unsigned char uaSSID[32]; return data; }
void setup() { server.begin(); netapp_ipconfig(&ip_config); #if DEBUG Serial.begin(115200); #endif IPAddress ip = WiFi.localIP(); static char ipAddress[24] = ""; char octet[5]; itoa(ip[0], octet, 10); strcat(ipAddress, octet); strcat(ipAddress, "."); itoa(ip[1], octet, 10); strcat(ipAddress, octet); strcat(ipAddress, "."); itoa(ip[2], octet, 10); strcat(ipAddress, octet); strcat(ipAddress, "."); itoa(ip[3], octet, 10); strcat(ipAddress, octet); strcat(ipAddress, ":"); itoa(PORT, octet, 10); strcat(ipAddress, octet); Spark.variable("endpoint", ipAddress, STRING); }
BOOL cc3000_getIPAddress(uint32_t* retip, uint32_t* netmask, uint32_t* gateway, uint32_t* dhcpserv, uint32_t* dnsserv) { if (!_cc3000_status.isConnected) { return FALSE; } if (!_cc3000_status.hasDHCP) { return FALSE; } tNetappIpconfigRetArgs ipconfig; netapp_ipconfig(&ipconfig); /* If byte 1 is 0 we don't have a valid address */ if (ipconfig.aucIP[3] == 0) { return FALSE; } memcpy(retip, ipconfig.aucIP, 4); memcpy(netmask, ipconfig.aucSubnetMask, 4); memcpy(gateway, ipconfig.aucDefaultGateway, 4); memcpy(dhcpserv, ipconfig.aucDHCPServer, 4); memcpy(dnsserv, ipconfig.aucDNSServer, 4); return TRUE; }
/** * @brief Attempts to connect to network stored in memory. * * FastConnect attempts to connect to the WiFi network (AP) stored in non- * volatile memory. The user needs to run SmartConfig first in order to create * a network profile in memory before running FastConnect. * * @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::fastConnect(unsigned int timeout) { 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 auto-connect */ if (wlan_ioctl_set_connection_policy(DISABLE, DISABLE, ENABLE) != CC3000_SUCCESS) { return false; } /* Wait for connection and DHCP-assigned IP address */ time = millis(); while (getDHCPStatus() == false) { if (timeout != 0) { if ( (millis() - time) > timeout ) { return false; } } } /* Get connection information */ netapp_ipconfig(&connection_info_); 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; }
/** * @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; }
void loop() { if (client.connected()) { digitalWrite(D4,HIGH); digitalWrite(D0,HIGH); delay(200); digitalWrite(D4,LOW); digitalWrite(D0,LOW); while (client.available()) { digitalWrite(D4,HIGH); digitalWrite(D7,HIGH); delay(200); digitalWrite(D4,LOW); digitalWrite(D7,LOW); Serial.println(); int val = client.read(); Serial.println(val); netapp_ipconfig(&ipconfig); char connectedSSID[32]; sprintf(connectedSSID, "%s", ipconfig.uaSSID); digitalWrite(D7,HIGH); delay(500); digitalWrite(D7,LOW); delay(500); long err = wlan_ioctl_get_scan_results(0, ucResults); int _numEntry = ((uint8_t) ucResults[3] << 24) | ((uint8_t) ucResults[2] << 16) | ((uint8_t) ucResults[1] << 8) | ((uint8_t) ucResults[0]); if (err == 0 && _numEntry > 0) { digitalWrite(D4,HIGH); delay(100); digitalWrite(D4,LOW); int _stat = ((uint8_t) ucResults[7] << 24) | ((uint8_t) ucResults[6] << 16) | ((uint8_t) ucResults[5] << 8) | ((uint8_t) ucResults[4]); bool _valid = (uint8_t) ucResults[8] & 0x1; int _rssi = (uint8_t) ucResults[8] >> 1; int _mode = ((uint8_t) ucResults[9] | 0xC0) & 0x3; int _ssidlen = (uint8_t) ucResults[9] >> 2; char ssid[32]; int idx = 0; while(idx < _ssidlen) { ssid[idx] = ucResults[idx+12]; idx++; } ssid[_ssidlen] = (char) NULL; if (strcmp(connectedSSID, ssid) == 0){ digitalWrite(D0,HIGH); delay(100); digitalWrite(D0,LOW); Serial.print("WiFi scan status: "); server.write("WiFi scan status: "); switch (_stat) { case 0: Serial.print("aged, "); server.write("aged, "); break; case 1: Serial.print("valid, "); server.write("valid, "); break; case 2: Serial.print("no results, "); server.write("no results, "); break; } Serial.print(_numEntry); Serial.print(" nets found. "); Serial.print(ssid); server.write(_numEntry); server.write(" nets found. "); server.write(ssid); if (_valid){ Serial.print(" is valid, RSSI: "); server.write(" is valid, RSSI: "); } else{ Serial.print("not valid, RSSI: "); server.write("not valid, RSSI: "); } Serial.print(_rssi); Serial.print(", mode: "); server.write(_rssi); server.write(", mode: "); switch (_mode) { case 0: Serial.println("OPEN"); server.write("OPEN\n"); break; case 1: Serial.println("WEP"); server.write("WEP\n"); break; case 2: Serial.println("WPA"); server.write("WPA\n"); break; case 3: Serial.println("WPA2"); server.write("WPA2\n"); break; } } incomingByte = Serial.read(); //key press 'a' to get data if (incomingByte == 97){ Serial.print("local ip : "); Serial.println(Network.localIP()); Serial.print("subnet mask: "); Serial.println(Network.subnetMask()); Serial.print("gateway ip : "); Serial.println(Network.gatewayIP()); Serial.print("ssid : "); Serial.println(Network.SSID()); Serial.println(); } Serial.print(connectedSSID); Serial.print( " "); Serial.println(ssid); server.write(connectedSSID); server.write( " "); server.write(ssid); server.write("\n"); } else {
tNetappIpconfigRetArgs * getCC3000Info() { netapp_ipconfig(&ipinfo); return (&ipinfo); }
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; } } }
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; } } }
void loop() { netapp_ipconfig(&ipconfig); char connectedSSID[32]; sprintf(connectedSSID, "%s", ipconfig.uaSSID); digitalWrite(ledPin1,HIGH); delay(50); digitalWrite(ledPin1,LOW); delay(50); long errParams = wlan_ioctl_set_scan_params(1000, 20, 30, 2, 0x7ff, -80, 0, 205, aiIntervalList[16]); long errResults = wlan_ioctl_get_scan_results(0, ucResults); int _numEntry = ((uint8_t) ucResults[3] << 24) | ((uint8_t) ucResults[2] << 16) | ((uint8_t) ucResults[1] << 8) | ((uint8_t) ucResults[0]); if (errParams == 0 && errResults == 0 && _numEntry > 0) { digitalWrite(ledPin2,HIGH); delay(50); digitalWrite(ledPin2,LOW); int _stat = ((uint8_t) ucResults[7] << 24) | ((uint8_t) ucResults[6] << 16) | ((uint8_t) ucResults[5] << 8) | ((uint8_t) ucResults[4]); bool _valid = (uint8_t) ucResults[8] & 0x1; int _rssi = (uint8_t) ucResults[8] >> 1; int _mode = ((uint8_t) ucResults[9] | 0xC0) & 0x3; int _ssidlen = (uint8_t) ucResults[9] >> 2; char ssid[32]; int idx = 0; while(strcmp(connectedSSID, ssid) != 0) { ssid[idx] = ucResults[idx+12]; idx++; ssid[_ssidlen] = (char) NULL; } digitalWrite(ledPin3,HIGH); delay(100); digitalWrite(ledPin3,LOW); Serial.print("WiFi scan status: "); switch (_stat) { case 0: Serial.print("aged, "); break; case 1: Serial.print("valid, "); break; case 2: Serial.print("no results, "); break; } Serial.print(_numEntry); Serial.print(" nets found. "); Serial.print(ssid); Serial1.println(ssid); if (_valid){ Serial.print(" is valid, RSSI: "); } else Serial.print("not valid, RSSI: "); Serial.print(_rssi); Serial1.println(_rssi); Serial.print(", mode: "); switch (_mode) { case 0: Serial.println("OPEN"); break; case 1: Serial.println("WEP"); break; case 2: Serial.println("WPA"); break; case 3: Serial.println("WPA2"); break; } // else { // Serial.print(connectedSSID); // Serial.print(" >______< "); // Serial.println(ssid); // } incomingByte = Serial.read(); //key press 'a' to get data if (incomingByte == 97){ Serial.println(Network.localIP()); Serial.println(Network.subnetMask()); Serial.println(Network.gatewayIP()); Serial.println(Network.SSID()); } }
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"); }