int ConnectNetwork(Network* n, char* addr, int port) { SlSockAddrIn_t sAddr; int addrSize; int retVal; unsigned long ipAddress; sl_NetAppDnsGetHostByName(addr, strlen(addr), &ipAddress, AF_INET); sAddr.sin_family = AF_INET; sAddr.sin_port = sl_Htons((unsigned short)port); sAddr.sin_addr.s_addr = sl_Htonl(ipAddress); addrSize = sizeof(SlSockAddrIn_t); n->my_socket = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( n->my_socket < 0 ) { // error return -1; } retVal = sl_Connect(n->my_socket, ( SlSockAddr_t *)&sAddr, addrSize); if( retVal < 0 ) { // error sl_Close(n->my_socket); return retVal; } SysTickIntRegister(SysTickIntHandler); SysTickPeriodSet(80000); SysTickEnable(); return retVal; }
int main0(void){ // "Embedded Systems: Real Time Interfacing to ARM Cortex M Microcontrollers", // ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2014, Volume 2, Program 11.2 UINT8 IsDHCP = 0; _NetCfgIpV4Args_t ipV4; SlSockAddrIn_t Addr; UINT16 AddrSize = 0; INT16 SockID = 0; UINT32 data; unsigned char len = sizeof(_NetCfgIpV4Args_t); initClk(); // PLL 50 MHz, ADC needs PPL active 15 ADC0_InitSWTriggerSeq3(7); // Ain7 is on PD0 16 sl_Start(0, 0, 0); // Initializing the CC3100 device 17 WlanConnect(); // connect to AP 18 sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len, // 19 (unsigned char *)&ipV4); // 20 Addr.sin_family = SL_AF_INET; // 21 Addr.sin_port = sl_Htons((UINT16)PORT_NUM); // 22 Addr.sin_addr.s_addr = sl_Htonl((UINT32)IP_ADDR); // 23 AddrSize = sizeof(SlSockAddrIn_t); // 24 SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); // 25 while(1){ uBuf[0] = ATYPE; // analog data type 26 uBuf[1] = '='; // 27 data = ADC0_InSeq3(); // 0 to 4095, Ain7 is on PD0 28 Int2Str(data,(char*)&uBuf[2]); // 6 digit number 29 sl_SendTo(SockID, uBuf, BUF_SIZE, 0, // 30 (SlSockAddr_t *)&Addr, AddrSize); // 31 ROM_SysCtlDelay(ROM_SysCtlClockGet() / 25); // 40ms 32 } }
/*! \brief Create TCP connection with openweathermap.org \param[in] none \return Socket descriptor for success otherwise negative \warning */ static int CreateConnection(void){ SlSockAddrIn_t Addr; INT32 sd = 0; INT32 AddrSize = 0; INT16 ret_val = 0; Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(80); /* Change the DestinationIP endianity, to big endian */ Addr.sin_addr.s_addr = sl_Htonl(appData.DestinationIP); AddrSize = sizeof(SlSockAddrIn_t); sd = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( sd < 0 ){ LCD_OutString("Error creating socket\r\n"); return sd; } ret_val = sl_Connect(sd, ( SlSockAddr_t *)&Addr, AddrSize); if( ret_val < 0 ){ /* error */ LCD_OutString("Error connecting to socket\r\n"); return ret_val; } return sd; }
int NetworkConnectTLS(Network *n, char* addr, int port, SlSockSecureFiles_t* certificates, unsigned char sec_method, unsigned int cipher, char server_verify) { SlSockAddrIn_t sAddr; int addrSize; int retVal; unsigned long ipAddress; retVal = sl_NetAppDnsGetHostByName(addr, strlen(addr), &ipAddress, AF_INET); if (retVal < 0) { return -1; } sAddr.sin_family = AF_INET; sAddr.sin_port = sl_Htons((unsigned short)port); sAddr.sin_addr.s_addr = sl_Htonl(ipAddress); addrSize = sizeof(SlSockAddrIn_t); n->my_socket = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_SEC_SOCKET); if (n->my_socket < 0) { return -1; } SlSockSecureMethod method; method.secureMethod = sec_method; retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECMETHOD, &method, sizeof(method)); if (retVal < 0) { return retVal; } SlSockSecureMask mask; mask.secureMask = cipher; retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &mask, sizeof(mask)); if (retVal < 0) { return retVal; } if (certificates != NULL) { retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECURE_FILES, certificates->secureFiles, sizeof(SlSockSecureFiles_t)); if (retVal < 0) { return retVal; } } retVal = sl_Connect(n->my_socket, (SlSockAddr_t *)&sAddr, addrSize); if (retVal < 0) { if (server_verify || retVal != -453) { sl_Close(n->my_socket); return retVal; } } SysTickIntRegister(SysTickIntHandler); SysTickPeriodSet(80000); SysTickEnable(); return retVal; }
//**************************************************************************** // //! \brief Opening a UDP client side socket and sending data //! //! This function opens a UDP socket and tries to connect to a Server IP_ADDR //! waiting on port PORT_NUM. //! Then the function will send 1000 UDP packets to the server. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, -1 on Error. // //**************************************************************************** int BsdUdpClient(unsigned short usPort) { int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; //filling the UDP server socket address sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)usPort); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)g_ulDestinationIp); iAddrSize = sizeof(SlSockAddrIn_t); // creating a UDP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( iSockID < 0 ) { // error ASSERT_ON_ERROR(UCP_CLIENT_FAILED); } // for a UDP connection connect is not required // sending 1000 packets to the UDP server while (lLoopCount < g_ulPacketCount) { // sending packet iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0, (SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus <= 0 ) { // error sl_Close(iSockID); ASSERT_ON_ERROR(UCP_CLIENT_FAILED); } lLoopCount++; } UART_PRINT("Sent %u packets successfully\n\r",g_ulPacketCount); //closing the socket after sending 1000 packets sl_Close(iSockID); return SUCCESS; }
//--tested, working--// IPAddress WiFiClass::localIP() { // //the local IP is maintained with callbacks, so _SlNonOsMainLoopTask() //is critical. The IP is "written" into the buffer to avoid memory errors // _SlNonOsMainLoopTask(); IPAddress retIP(0,0,0,0); retIP = sl_Htonl(local_IP); return retIP; }
char* HTTP_Request(const char *hostName, uint16_t port, const char *method, const char *request, char *requestData1, char *requestData2) { SlSockAddrIn_t Addr; int32_t retVal; uint32_t ASize = 0; cleanup(); strcpy(HostName, hostName); UARTprintf("\r\n\r\nUsing host: %s\r\n", HostName); retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET); if(retVal == 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(port); Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian ASize = sizeof(SlSockAddrIn_t); SockID = -1; SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( SockID >= 0 ){ retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize); } if((SockID >= 0)&&(retVal >= 0)){ uint32_t copyIndex = 0; strcpy(&SendBuff[copyIndex], method); copyIndex += strlen(method); strcpy(&SendBuff[copyIndex], " "); copyIndex += 1; strcpy(&SendBuff[copyIndex], request); copyIndex += strlen(request); if(requestData1) { strcpy(&SendBuff[copyIndex], requestData1); copyIndex += strlen(requestData1); } if(requestData2) { strcpy(&SendBuff[copyIndex], requestData2); copyIndex += strlen(requestData2); } strcpy(&SendBuff[copyIndex], REQ_1); copyIndex += strlen(REQ_1); strcpy(&SendBuff[copyIndex], hostName); copyIndex += strlen(hostName); strcpy(&SendBuff[copyIndex], REQ_2); copyIndex += strlen(REQ_2); SendBuff[copyIndex] = '\0'; UARTprintf("Sending request: %s\r\n\r\n", SendBuff); sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response sl_Close(SockID); return Recvbuff; } } return NULL; }
//--tested, working--// int WiFiClass::hostByName(char* aHostname, IPAddress& aResult) { if (!_initialized) { init(); } // //Use the netapp api to resolve an IP for the requested hostname // unsigned long DestinationIP; int iRet = sl_NetAppDnsGetHostByName(aHostname, strlen(aHostname), &DestinationIP, SL_AF_INET); aResult = sl_Htonl(DestinationIP); if (iRet >= 0) { return 1; } else { return iRet; } }
//--tested, working--// IPAddress WiFiClass::localIP() { // //the local IP is maintained with callbacks, so _SlNonOsMainLoopTask() //is critical. The IP is "written" into the buffer to avoid memory errors // _SlNonOsMainLoopTask(); SlNetCfgIpV4Args_t config = {0}; unsigned char len = sizeof(SlNetCfgIpV4Args_t); sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO, NULL, &len, (unsigned char*)&config); // //change the uint32_t IP to the IPAddress class and return // IPAddress retIP(0,0,0,0); retIP = sl_Htonl(config.ipV4); return retIP; }
//--tested, working--// IPAddress WiFiClass::gatewayIP() { if (!_initialized) { init(); } // //get current configuration // _NetCfgIpV4Args_t config = {0}; unsigned char len = sizeof(_NetCfgIpV4Args_t); sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO, NULL, &len, (unsigned char*)&config); // //change the uint32_t IP to the IPAddress class and return // IPAddress retIP(0,0,0,0); retIP = sl_Htonl(config.ipV4Gateway); return retIP; }
ext_tcp_utils_function_return_state_t ext_tcp_utils_getaddrbyhost(kaa_dns_resolve_listener_t *resolve_listener , const kaa_dns_resolve_info_t *resolve_props , kaa_sockaddr_t *result , kaa_socklen_t *result_size) { (void)resolve_listener; KAA_RETURN_IF_NIL4(resolve_props, resolve_props->hostname, result, result_size, RET_STATE_VALUE_ERROR); if (*result_size < sizeof(struct sockaddr_in)) return RET_STATE_BUFFER_NOT_ENOUGH; unsigned long out_ip = 0; int ai_family; int resolve_error = 0; struct sockaddr_in tmp_addr; ai_family = AF_INET; *result_size = sizeof(struct sockaddr_in); char hostname_str[resolve_props->hostname_length + 1]; memcpy(hostname_str, resolve_props->hostname, resolve_props->hostname_length); hostname_str[resolve_props->hostname_length] = '\0'; if (strcmp(hostname_str, "localhost")) resolve_error = sl_NetAppDnsGetHostByName((signed char*)hostname_str, resolve_props->hostname_length, &out_ip, ai_family); else out_ip = 0x7F000001; memset(&tmp_addr, 0, *result_size); tmp_addr.sin_family = ai_family; tmp_addr.sin_addr.s_addr = sl_Htonl((unsigned int)out_ip); tmp_addr.sin_port = sl_Htons((unsigned short)resolve_props->port); if (resolve_error || !out_ip) return RET_STATE_VALUE_ERROR; memcpy(result, (struct sockaddr*)&tmp_addr, *result_size); return RET_STATE_VALUE_READY; }
//***************************************************************************** // //! This function demonstrates how certificate can be used with SSL. //! The procedure includes the following steps: //! 1) connect to an open AP //! 2) get the server name via a DNS request //! 3) define all socket options and point to the CA certificate //! 4) connect to the server via TCP //! //! \param None //! //! \return 0 on success else error code //! \return LED1 is turned solid in case of success //! LED2 is turned solid in case of failure //! //***************************************************************************** static int tls_connect() { SlSockAddrIn_t Addr; int iAddrSize; unsigned char ucMethod = SL_SO_SEC_METHOD_TLSV1_2; unsigned int uiIP,uiCipher = SL_SEC_MASK_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA; long lRetVal = -1; int iSockID; lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET); if(lRetVal < 0) { UART_PRINT("Device couldn't retrive the host name \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(uiIP); iAddrSize = sizeof(SlSockAddrIn_t); // // opens a secure socket // iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( iSockID < 0 ) { UART_PRINT("Device unable to create secure socket \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // configure the socket as TLS1.2 // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod,\ sizeof(ucMethod)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket as ECDHE RSA WITH AES256 CBC SHA // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher,\ sizeof(uiCipher)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket with CA certificate - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_CA_FILE_NAME, \ SL_SSL_CA_CERT, \ strlen(SL_SSL_CA_CERT)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } //configure the socket with Client Certificate - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, \ SL_SSL_CLIENT, \ strlen(SL_SSL_CLIENT)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } //configure the socket with Private Key - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, \ SL_SSL_PRIVATE, \ strlen(SL_SSL_PRIVATE)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } /* connect to the peer device - Google server */ lRetVal = sl_Connect(iSockID, ( SlSockAddr_t *)&Addr, iAddrSize); if(lRetVal < 0) { UART_PRINT("Device couldn't connect to AWS server \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } else{ UART_PRINT("Device has connected to the website:"); UART_PRINT(SERVER_NAME); UART_PRINT("\n\r"); } GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); return iSockID; }
//***************************************************************************** // //! This function demonstrates how certificate can be used with SSL. //! The procedure includes the following steps: //! 1) connect to an open AP //! 2) get the server name via a DNS request //! 3) define all socket options and point to the CA certificate //! 4) connect to the server via TCP //! //! \param None //! //! \return 0 on success else error code //! \return LED1 is turned solid in case of success //! LED2 is turned solid in case of failure //! //***************************************************************************** static long ssl() { SlSockAddrIn_t Addr; int iAddrSize; unsigned char ucMethod = SL_SO_SEC_METHOD_SSLV3; unsigned int uiIP,uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; long lRetVal = -1; int iSockID; GPIO_IF_LedConfigure(LED1|LED3); GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); lRetVal = InitializeAppVariables(); ASSERT_ON_ERROR(lRetVal); // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its default state at start of applicaton // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) UART_PRINT("Failed to configure the device in its default state \n\r"); return lRetVal; } UART_PRINT("Device is configured in default state \n\r"); CLR_STATUS_BIT_ALL(g_ulStatus); /// // Assumption is that the device is configured in station mode already // and it is in its default state // lRetVal = sl_Start(0, 0, 0); if (lRetVal < 0 || ROLE_STA != lRetVal) { UART_PRINT("Failed to start the device \n\r"); return lRetVal; } UART_PRINT("Device started as STATION \n\r"); // //Connecting to WLAN AP // lRetVal = WlanConnect(); if(lRetVal < 0) { UART_PRINT("Failed to establish connection w/ an AP \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } UART_PRINT("Connection established w/ AP and IP is aquired \n\r"); //Set time of the device for certificate verification. lRetVal = set_time(); if(lRetVal < 0) { UART_PRINT("Unable to set time in the device"); return lRetVal; } lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET); if(lRetVal < 0) { UART_PRINT("Device couldn't retrive the host name \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(uiIP); iAddrSize = sizeof(SlSockAddrIn_t); // // opens a secure socket // iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( iSockID < 0 ) { UART_PRINT("Device unable to create secure socket \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // configure the socket as SSLV3.0 // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod,\ sizeof(ucMethod)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket as RSA with RC4 128 SHA // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher,\ sizeof(uiCipher)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket with GOOGLE CA certificate - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_CA_FILE_NAME, \ SL_SSL_CA_CERT_FILE_NAME, \ strlen(SL_SSL_CA_CERT_FILE_NAME)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SO_SECURE_DOMAIN_NAME_VERIFICATION, \ g_Host, strlen((const char *)g_Host)); if( lRetVal < 0 ) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } /* connect to the peer device - Google server */ lRetVal = sl_Connect(iSockID, ( SlSockAddr_t *)&Addr, iAddrSize); if(lRetVal < 0) { UART_PRINT("Device couldn't connect to Google server \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); return SUCCESS; }
//***************************************************************************** // //! Function to connect to server and download the requested file //! //! \param none //! //! \return Error-code or SUCCESS //! //***************************************************************************** static long ServerFileDownload() { long lRetVal = -1; struct sockaddr_in addr; HTTPCli_Struct cli; // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its desired state at start of applicaton // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) { UART_PRINT("Failed to configure the device in its default state, " "Error-code: %d\n\r", DEVICE_NOT_IN_STATION_MODE); } LOOP_FOREVER(); } UART_PRINT("Device is configured in default state \n\r"); // // Assumption is that the device is configured in station mode already // and it is in its default state // lRetVal = sl_Start(0, 0, 0); if (lRetVal < 0 || ROLE_STA != lRetVal) { ASSERT_ON_ERROR(DEVICE_START_FAILED); } UART_PRINT("Device started as STATION \n\r"); // Connecting to WLAN AP - Set with static parameters defined at the top // After this call we will be connected and have IP address lRetVal = WlanConnect(); UART_PRINT("Connected to the AP: %s\r\n", SSID_NAME); lRetVal = sl_NetAppDnsGetHostByName((signed char *)HOST_NAME, strlen((const char *)HOST_NAME), &g_ulDestinationIP,SL_AF_INET); if(lRetVal < 0) { ASSERT_ON_ERROR(GET_HOST_IP_FAILED); } // Set up the input parameters for HTTP Connection addr.sin_family = AF_INET; addr.sin_port = htons(HOST_PORT); addr.sin_addr.s_addr = sl_Htonl(g_ulDestinationIP); // Testing HTTPCli open call: handle, address params only HTTPCli_construct(&cli); lRetVal = HTTPCli_connect(&cli, (struct sockaddr *)&addr, 0, NULL); if (lRetVal < 0) { UART_PRINT("Connection to server failed\n\r"); ASSERT_ON_ERROR(SERVER_CONNECTION_FAILED); } else { UART_PRINT("Connection to server created successfully\r\n"); } // Download the file, verify the file and replace the exiting file lRetVal = GetData(&cli); if(lRetVal < 0) { UART_PRINT("Device couldn't download the file from the server\n\r"); } HTTPCli_destruct(&cli); return SUCCESS; }
//**************************************************************************** // //! \brief Opening a UDP client side socket and sending data //! //! This function opens a UDP socket and tries to connect to a Server IP_ADDR //! waiting on port PORT_NUM. //! Then the function will send 1000 UDP packets to the server. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, -1 on Error. // //**************************************************************************** int BsdUdpClient(unsigned short usPort, unsigned long ulDesitnationIP) { int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; int iPackets; // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; // // Filling the UDP server socket address // sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)usPort); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)ulDesitnationIP); iAddrSize = sizeof(SlSockAddrIn_t); // // Initialize number of packets variable // iPackets = UDP_PACKET_COUNT; // // Creating a UDP socket // iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( iSockID < 0 ) { // error return -1; } UART_PRINT("\n\rSending Packets\n\r"); // // Loop forever sending packets // while (1) { // // Sending packet // iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0, ( SlSockAddr_t *)&sAddr, iAddrSize); // // Decrement the packet count // iPackets--; UART_PRINT("."); // // If send fails or packet count reaches 0 stop acking the watchdog // so that it resets the system // if( iStatus > 0 && iPackets > 0) { WatchdogAck(); } UtilsDelay(8000000); } }
//***************************************************************************** // //! \brief Task Created by main fucntion. This task prints the wake up reason //! (from hibernate or from restart). start simplelink, set NWP power //! policy and connects to an AP. Creates UDP client and send UDP //! packets at around 1Mbit/sec for certain time. Disconnect form AP //! and stops the simplelink.Setup GPIO and Timer as wakeup source from //! low power modes. Go into HIBernate. //! //! \param pvParameters is a general void pointer (not used here). //! //! \return none // //***************************************************************************** void TimerGPIOTask(void *pvParameters) { cc_hndl tTimerHndl; cc_hndl tGPIOHndl; int iSockDesc = 0; int iRetVal = 0; int iCounter = 0; sockaddr_in sServerAddr; unsigned char *pcSendBuff; unsigned char cSyncMsg; // // creating the queue for signalling about connection events // iRetVal = osi_MsgQCreate(&g_tConnection, NULL, sizeof( unsigned char ), 3); if (iRetVal < 0) { UART_PRINT("unable to create the msg queue\n\r"); LOOP_FOREVER(); } // filling the buffer for (iCounter=0 ; iCounter<BUFF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } pcSendBuff = g_cBsdBuf; if(MAP_PRCMSysResetCauseGet() == PRCM_POWER_ON) { // // Displays the Application Banner // DisplayBanner(); // // starting the simplelink // iRetVal = sl_Start(NULL, NULL, NULL); if (iRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } // // Switch to STA mode if device is not in this mode // SwitchToStaMode(iRetVal); // // Set the power management policy of NWP // iRetVal = sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0); if (iRetVal < 0) { UART_PRINT("unable to configure network power policy\n\r"); LOOP_FOREVER(); } } else if(MAP_PRCMSysResetCauseGet() == PRCM_HIB_EXIT) { UART_PRINT("woken from hib\n\r"); // // starting the simplelink // iRetVal = sl_Start(NULL, NULL, NULL); if (iRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } } else if(MAP_PRCMSysResetCauseGet() == PRCM_WDT_RESET) { UART_PRINT("woken from WDT Reset\n\r"); // // starting the simplelink // iRetVal = sl_Start(NULL, NULL, NULL); if (iRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } } else { UART_PRINT("woken cause unknown\n\r"); } // // connecting to the Access Point // if(-1 == WlanConnect()) { UART_PRINT("Connection to AP failed\n\r"); goto no_network_connection; }else{ UART_PRINT("Connected to AP\n\r"); } // // creating a UDP socket // iSockDesc = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if(iSockDesc < 0) { UART_PRINT("sock error\n\r"); LOOP_FOREVER(); } // // configure the UDP Server address // sServerAddr.sin_family = SL_AF_INET; sServerAddr.sin_port = sl_Htons(APP_UDP_PORT); sServerAddr.sin_addr.s_addr = sl_Htonl(SERVER_IP_ADDRESS); // // Set 5 sec timer allowing 5 sec of UDP Tx. // tTimerHndl = SetTimer(); g_ucTrafficEnable = 1; while(g_ucTrafficEnable == 1) { // // sending message // iRetVal = sendto(iSockDesc, pcSendBuff,BUFF_SIZE, 0, (struct sockaddr *)&sServerAddr,sizeof(sServerAddr)); if(iRetVal < 0) { UART_PRINT("send error\n\r"); LOOP_FOREVER(); } ManageDelay(128,BUFF_SIZE); } UART_PRINT("sent\n\r"); // // stop and delete the timer // cc_timer_stop(tTimerHndl); cc_timer_delete(tTimerHndl); // //close the socket // close(iSockDesc); if(iRetVal < 0) { UART_PRINT("could not close the socket\n\r"); } // // disconnect from the Access Point // WlanDisconnect(); no_network_connection: // // stop the simplelink with reqd. timeout value (30 ms) // sl_Stop(SL_STOP_TIMEOUT); // // setting Timer as one of the wakeup source // tTimerHndl = SetTimerAsWkUp(); // // setting some GPIO as one of the wakeup source // tGPIOHndl = SetGPIOAsWkUp(); /* handles, if required, can be used to stop the timer, but not used here*/ UNUSED(tTimerHndl); UNUSED(tGPIOHndl); // // Setting up HIBERNATE as the lowest power mode for the system. // lp3p0_setup_power_policy(POWER_POLICY_HIBERNATE); // // idle wait will push the system into the lowest power mode(HIBERNATE). // iRetVal = osi_MsgQCreate(&g_tWaitForHib, NULL, sizeof( unsigned char ), 1); if (iRetVal < 0) { UART_PRINT("unable to create the msg queue\n\r"); LOOP_FOREVER(); } osi_MsgQRead(&g_tWaitForHib, &cSyncMsg, OSI_WAIT_FOREVER); // // infinite loop (must not reach here) // LOOP_FOREVER(); }
int main1(void){ UINT8 IsDHCP = 0; _NetCfgIpV4Args_t ipV4; SlSockAddrIn_t Addr; UINT16 AddrSize = 0; INT16 SockID = 0; INT16 Status = 1; // ok UINT32 data; unsigned char len = sizeof(_NetCfgIpV4Args_t); stopWDT(); // Stop WDT initClk(); // PLL 50 MHz, ADC needs PPL active Board_Init(); // initialize LaunchPad I/O ConfigureUART(); // Initialize the UART. UARTprintf("Section 11.4 IoT example, Volume 2 Real-time interfacing\n"); #if ADC ADC0_InitSWTriggerSeq3(7); // Ain7 is on PD0 UARTprintf("This node is configured to measure signals from Ain7=PD0\n"); #endif #if EKG UARTprintf("This node is configured to generate simulated EKG data\n"); #endif UARTprintf(" and send UDP packets to IP: %d.%d.%d.%d Port: %d\n\n", SL_IPV4_BYTE(IP_ADDR,3), SL_IPV4_BYTE(IP_ADDR,2), SL_IPV4_BYTE(IP_ADDR,1), SL_IPV4_BYTE(IP_ADDR,0),PORT_NUM); while(1){ sl_Start(0, 0, 0);/* Initializing the CC3100 device */ /* Connecting to WLAN AP - Set with static parameters defined at the top After this call we will be connected and have IP address */ WlanConnect(); // connect to AP /* Read the IP parameter */ sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len,(unsigned char *)&ipV4); UARTprintf("This node is at IP: %d.%d.%d.%d\n", SL_IPV4_BYTE(ipV4.ipV4,3), SL_IPV4_BYTE(ipV4.ipV4,2), SL_IPV4_BYTE(ipV4.ipV4,1), SL_IPV4_BYTE(ipV4.ipV4,0)); while(Status > 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons((UINT16)PORT_NUM); Addr.sin_addr.s_addr = sl_Htonl((UINT32)IP_ADDR); AddrSize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( SockID < 0 ){ UARTprintf("SockIDerror "); Status = -1; // error }else{ while(Status>0){ UARTprintf("\nSending a UDP packet ..."); uBuf[0] = ATYPE; // defines this as an analog data type uBuf[1] = '='; #if ADC data = ADC0_InSeq3(); // 0 to 4095, Ain7 is on PD0 #endif #if EKG data = EKGbuf[EKGindex]; EKGindex = (EKGindex+1)%EKGSIZE; // 100 Hz #endif Int2Str(data,(char*)&uBuf[2]); // [2] to [7] is 6 digit number UARTprintf(" %s ",uBuf); LED_Toggle(); Status = sl_SendTo(SockID, uBuf, BUF_SIZE, 0, (SlSockAddr_t *)&Addr, AddrSize); ROM_SysCtlDelay(ROM_SysCtlClockGet() / 25); // 80ms if( Status <= 0 ){ UARTprintf("SockIDerror %d ",Status); }else{ UARTprintf("ok"); } } sl_Close(SockID); } } } }
//***************************************************************************** // //! This function POST to Event Hub REST API using TLS //! //! \param None //! //! \return 0 on success else error code //! \return Error number on Failure // //***************************************************************************** long PostEventHubSSL() { SlSockAddrIn_t Addr; int iAddrSize; unsigned char ucMethod = SL_SO_SEC_METHOD_TLSV1; //SL_SO_SEC_METHOD_SSLv3_TLSV1_2; //SL_SO_SEC_METHOD_TLSV1_2; //SL_SO_SEC_METHOD_SSLV3; unsigned int uiIP; unsigned int uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; long lRetVal = -1; int iSSLSockID; char acSendBuff[512]; char acRecvbuff[1460]; //char* pcBufData; char* pcBufHeaders; // // Retrieve IP from Hostname // lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET); if(lRetVal < 0) { CLI_Write("Could not retrive the IP Address for Azure Server.\n\r"); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(SSL_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(uiIP); iAddrSize = sizeof(SlSockAddrIn_t); // // Opens a secure socket // iSSLSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( iSSLSockID < 0 ) { CLI_Write("Unable to create secure socket.\n\r"); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // Configure the socket as TLS (SSLV3.0 does not work because of POODLE - http://en.wikipedia.org/wiki/POODLE) // lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod, sizeof(ucMethod)); if(lRetVal < 0) { CLI_Write("Couldn't set socket option (TLS).\n\r"); sl_Close(iSSLSockID); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // Configure the socket as RSA with RC4 128 SHA // lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher, sizeof(uiCipher)); if(lRetVal < 0) { CLI_Write("Couldn't set socket option (RSA).\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Configure the socket with Azure CA certificate - for server verification // lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, SL_SSL_CA_CERT_FILE_NAME, strlen(SL_SSL_CA_CERT_FILE_NAME)); if(lRetVal < 0) { CLI_Write("Couldn't set socket option (CA Certificate).\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Configure the recieve timeout // struct SlTimeval_t timeVal; timeVal.tv_sec = SERVER_RESPONSE_TIMEOUT; // In Seconds timeVal.tv_usec = 0; // Microseconds. 10000 microseconds resolution lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_RCVTIMEO, (unsigned char*)&timeVal, sizeof(timeVal)); if(lRetVal < 0) { CLI_Write("Couldn't set socket option (Receive Timeout).\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Connect to the peer device - Azure server */ // lRetVal = sl_Connect(iSSLSockID, ( SlSockAddr_t *)&Addr, iAddrSize); if(lRetVal < 0) { CLI_Write("Couldn't connect to Azure server.\n\r"); sl_Close(iSSLSockID); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // Generate a random number for the temperture // srand((unsigned int)time(NULL)); float a = 5.0; float fRandTemp = 25 - (((float)rand()/(float)(RAND_MAX)) * a); char cTempChar[5]; sprintf(cTempChar, "%.2f", fRandTemp); // // Creates the HTTP POST string. // int dataLength = strlen(DATA1) + 5 + strlen(DATA2); char cCLLength[4]; pcBufHeaders = acSendBuff; strcpy(pcBufHeaders, POSTHEADER); pcBufHeaders += strlen(POSTHEADER); strcpy(pcBufHeaders, HOSTHEADER); pcBufHeaders += strlen(HOSTHEADER); strcpy(pcBufHeaders, AUTHHEADER); pcBufHeaders += strlen(AUTHHEADER); strcpy(pcBufHeaders, CHEADER); pcBufHeaders += strlen(CHEADER); strcpy(pcBufHeaders, CTHEADER); pcBufHeaders += strlen(CTHEADER); strcpy(pcBufHeaders, CLHEADER1); pcBufHeaders += strlen(CLHEADER1); sprintf(cCLLength, "%d", dataLength); strcpy(pcBufHeaders, cCLLength); pcBufHeaders += strlen(cCLLength); strcpy(pcBufHeaders, CLHEADER2); pcBufHeaders += strlen(CLHEADER2); strcpy(pcBufHeaders, DATA1); pcBufHeaders += strlen(DATA1); strcpy(pcBufHeaders , cTempChar); pcBufHeaders += strlen(cTempChar); strcpy(pcBufHeaders, DATA2); int testDataLength = strlen(pcBufHeaders); // // Send the packet to the server */ // lRetVal = sl_Send(iSSLSockID, acSendBuff, strlen(acSendBuff), 0); if(lRetVal < 0) { CLI_Write("POST failed.\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Receive response packet from the server */ // lRetVal = sl_Recv(iSSLSockID, &acRecvbuff[0], sizeof(acRecvbuff), 0); if(lRetVal < 0) { CLI_Write("Received failed.\n\r"); sl_Close(iSSLSockID); return lRetVal; } else { CLI_Write("HTTP POST Successful. Telemetry successfully logged\n\r"); } sl_Close(iSSLSockID); return SUCCESS; }
//**************************************************************************** // MAIN FUNCTION //**************************************************************************** int main(void) { long lRetVal; char cCmdBuff[20]; signed char cCmd = APP_SLEEP; SlSockAddrIn_t sAddr; SlSockAddrIn_t sLocalAddr; SlSockAddrIn_t sBrdAddr; int iCounter; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; short sTestBufLen; struct SlTimeval_t timeVal; // // Board Initialization // BoardInit(); // // uDMA Initialization // UDMAInit(); // // Configure the pinmux settings for the peripherals exercised // Note: pinmux has been modified after the output from pin mux tools // to enable sleep clk for the peripherals exercised // PinMuxConfig(); // // Initialize the platform // platform_init(); // // Initialise the UART terminal // InitTerm(); // // Display banner // DisplayBanner(); // // starting the simplelink // lRetVal = sl_Start(NULL, NULL, NULL); if (lRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } // // Swtich to STA mode if device is not // SwitchToStaMode(lRetVal); // // set connection policy // sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(0, 0, 0, 0, 0), NULL, 0); // // Set the power management policy of NWP // lRetVal = sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0); UART_PRINT("Trying to Connect to AP: %s ...\r\n",SSID_NAME); // //Connecting to WLAN AP // lRetVal = WlanConnect(); if(lRetVal < 0) { UART_PRINT("Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; //filling the UDP server socket address sLocalAddr.sin_family = SL_AF_INET; sLocalAddr.sin_port = sl_Htons((unsigned short)PORT_NUM); sLocalAddr.sin_addr.s_addr = 0; //filling the UDP server socket address sBrdAddr.sin_family = SL_AF_INET; sBrdAddr.sin_port = sl_Htons((unsigned short)PORT_NUM); sBrdAddr.sin_addr.s_addr = sl_Htonl((unsigned int)g_ulDestinationIp); iAddrSize = sizeof(SlSockAddrIn_t); // creating a UDP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); /* setting time out for socket recv */ timeVal.tv_sec = 5; // Seconds timeVal.tv_usec = 0; // Microseconds. 10000 microseconds resolution sl_SetSockOpt(iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (_u8 *)&timeVal, sizeof(timeVal)); // binding the UDP socket to the UDP server address iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize); if( iStatus < 0 ) { // error sl_Close(iSockID); ASSERT_ON_ERROR(iStatus); } // // setting Apps power policy // lp3p0_setup_power_policy(POWER_POLICY_STANDBY); UART_PRINT("enter one of the following command:\n\r"); UART_PRINT("sleep - for putting the system into LPDS mode\n\r"); UART_PRINT(" GPIO 13 and timer(5 sec) are the wk source configured\n\r"); UART_PRINT("recv - for receiving 1000 UDP packets\n\r"); UART_PRINT("send - for broadcasting 1000 UDP packets\n\r"); do{ UART_PRINT("cmd#"); // // get cmd over UART // GetCmd(cCmdBuff, 20); // // parse the command // ParseCmd(cCmdBuff, &cCmd); if(cCmd == APP_SLEEP) { // // set timer and gpio as wake src // set_rtc_as_wk_src(WK_LPDS, LPDS_DUR_SEC, false); set_gpio_as_wk_src(WK_LPDS, GPIO_SRC_WKUP, PRCM_LPDS_FALL_EDGE); cc_idle_task_pm(); } else if(cCmd == APP_RECV) { lLoopCount = 0; /// waits for 1000 packets from a UDP client while (lLoopCount < g_ulPacketCount) { iStatus = sl_RecvFrom(iSockID, g_cBsdBuf, sTestBufLen, 0, ( SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize ); if( iStatus < 0 ) { //error break; } lLoopCount++; } UART_PRINT("Recieved %u packets successfully \n\r",lLoopCount); if(lLoopCount != g_ulPacketCount) { if(iStatus == SL_EAGAIN) { UART_PRINT("timed out\n\r"); } else { UART_PRINT("recv error: %d\n\r", iStatus); } } } else if(cCmd == APP_SEND) { lLoopCount = 0; // sending 1000 packets to the UDP server while (lLoopCount < g_ulPacketCount) { // sending packet iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0, (SlSockAddr_t *)&sBrdAddr, iAddrSize); if( iStatus <= 0 ) { // error UART_PRINT("send error\n\r"); break; } lLoopCount++; } UART_PRINT("Sent %u packets successfully\n\r",lLoopCount); } }while(FOREVER); }
int BsdTcpClient(unsigned short usPort) { UART_PRINT("BsdTcpClient\r\n"); while(serverCreatOK == 0) { //looping till simplelink starts Z_DelayMS(10); // ; UART_PRINT("serverCreatOK == 0 \n\r"); } UART_PRINT("serverCreatOK == 1\r\n"); int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; long lBytesSent = 0; long lNonBlocking = 0; //0 :non-blocking, // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; //filling the TCP server socket address sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)PORT_NUM); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)SL_IPV4_VAL(192,168,2,5)); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { // error return -1; } Report("creating a TCP socket yes\r\n"); iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); Report("connecting to TCP server\r\n"); // connecting to TCP server while(0>sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize)){ Report("connecting to TCP server error\r\n"); // vTaskSuspend(clientTaskHandle); vTaskResume((xTaskHandle)&ServerTaskHandle); } /* iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { // error return -1; } */ Report("connecting to TCP server yes\r\n"); // sending 1000 packets to the TCP server while (lLoopCount < 1) { // sending packet iStatus = sl_Send(iSockID, g_cBsdBuf, sTestBufLen, 0 ); /* if( iStatus <= 0 ) { // error return -1; } */ vTaskResume((xTaskHandle)&ServerTaskHandle); lLoopCount++; lBytesSent += iStatus; } //closing the socket after sending 1000 packets sl_Close(iSockID); Report("closing the socket after sending 1000 packets\r\n"); //filling the TCP server socket address sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)1883); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)SL_IPV4_VAL(9,186,88,87)); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { // error return -1; } Report("creating a TCP socket yes\r\n"); iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); Report("connecting to TCP server\r\n"); // connecting to TCP server while(0>sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize)){ Report("connecting to TCP server error\r\n"); } /* iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { // error return -1; } */ Report("connecting to TCP server yes\r\n"); //filling the TCP server socket address sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)1883); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)SL_IPV4_VAL(9,186,88,87)); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { // error return -1; } Report("creating a TCP socket yes\r\n"); lNonBlocking =1; iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); Report("connecting to TCP server\r\n"); // connecting to TCP server while(0>sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize)){ Report("connecting to TCP server error\r\n"); } /* iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { // error return -1; } */ Report("connecting to TCP server yes\r\n"); return 0; }
//**************************************************************************** // //! Task function implementing the UDP client and showcasing the hibernate //! functionality //! //! \param none //! //! This function //! 1. Creates a UDP socket //! 2. Broadcasts a packet on the socket //! 3. Closes the socket //! 4. Enters the HIBernate mode //! //! \return None. // //**************************************************************************** void HIBUDPBroadcastTask(void *pvParameters) { int iSocketDesc; long lRetVal; struct sockaddr_in sBroadcastAddr; char pcBroadcastMessage[]="32xx HIB example application"; // // Check the wakeup source. If first itme entry or wakeup from HIB // if(MAP_PRCMSysResetCauseGet() == 0) { DisplayBanner(APPNAME); DBG_PRINT("HIB: Wake up on Power ON\n\r"); } else if(MAP_PRCMSysResetCauseGet() == PRCM_HIB_EXIT) { DBG_PRINT("HIB: Woken up from Hibernate\n\r"); } else { } GPIO_IF_LedConfigure(LED1); GPIO_IF_LedOff(MCU_RED_LED_GPIO); // // Configure Timer for blinking the LED for IP acquisition // LedTimerConfigNStart(); // // // Reset The state of the machine // Network_IF_ResetMCUStateMachine(); // // Start the driver // lRetVal = Network_IF_InitDriver(ROLE_STA); if(lRetVal < 0) { UART_PRINT("Failed to start SimpleLink Device\n\r"); LOOP_FOREVER(); } // Initialize AP security params SecurityParams.Key = (signed char*)SECURITY_KEY; SecurityParams.KeyLen = strlen(SECURITY_KEY); SecurityParams.Type = SECURITY_TYPE; // // Connect to the Access Point // lRetVal = Network_IF_ConnectAP(SSID_NAME, SecurityParams); if(lRetVal < 0) { UART_PRINT("Connection to AP failed\n\r",lRetVal); LOOP_FOREVER(); } // // Disable the LED blinking Timer as Device is connected to AP // LedTimerDeinitStop(); // // Switch ON RED LED to indicate that Device acquired an IP // GPIO_IF_LedOn(MCU_IP_ALLOC_IND); // // Create UDP socket // iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, 0); if(iSocketDesc < 0) { DBG_PRINT("HIB: Socket create failed\n\r"); goto end; } DBG_PRINT("HIB: Socket created\n\r"); // // Assign socket structure values for a braodcast message // sBroadcastAddr.sin_family = AF_INET; sBroadcastAddr.sin_addr.s_addr= sl_Htonl(0xFFFFFFFF); sBroadcastAddr.sin_port= sl_Htons(APP_UDP_PORT); // // Broadcast message // lRetVal = sendto(iSocketDesc, (char *)&pcBroadcastMessage[0], sizeof(pcBroadcastMessage), 0, (struct sockaddr *)&sBroadcastAddr,sizeof(sBroadcastAddr)); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } UNUSED(lRetVal); DBG_PRINT("HIB: sent message\n\r"); // // Close the socket // close(iSocketDesc); DBG_PRINT("HIB: Socket closed\n\r"); // // Stop the driver // lRetVal = Network_IF_DeInitDriver(); if(lRetVal < 0) { UART_PRINT("Failed to stop SimpleLink Device\n\r"); LOOP_FOREVER(); } // // Switch Off RED & Green LEDs to indicate that Device is // disconnected from AP and Simplelink is shutdown // GPIO_IF_LedOff(MCU_IP_ALLOC_IND); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); // // Enter HIB here configuring the wakeup-timer // EnterHIBernate(); end: DBG_PRINT("HIB: Test Complete\n\r"); // // Loop here // LOOP_FOREVER(); }
int main(void){int32_t retVal; SlSecParams_t secParams; char *pConfig = NULL; INT32 ASize = 0; SlSockAddrIn_t Addr; ADC0_InitSWTriggerSeq3_Ch9(); // allow time to finish activating initClk(); // PLL 50 MHz Output_On(); UART_Init(); // Send data to PC, 115200 bps Timer1_Init(); LED_Init(); // initialize LaunchPad I/O UARTprintf("Weather App\n"); retVal = configureSimpleLinkToDefaultState(pConfig); // set policies if(retVal < 0)Crash(4000000); retVal = sl_Start(0, pConfig, 0); if((retVal < 0) || (ROLE_STA != retVal) ) Crash(8000000); secParams.Key = PASSKEY; secParams.KeyLen = strlen(PASSKEY); secParams.Type = SEC_TYPE; // OPEN, WPA, or WEP sl_WlanConnect(SSID_NAME, strlen(SSID_NAME), 0, &secParams, 0); while((0 == (g_Status&CONNECTED)) || (0 == (g_Status&IP_AQUIRED))){ _SlNonOsMainLoopTask(); } UARTprintf("Connected\n"); while(1){ int i = 0; while(i < 10){ int sendc = 0; strcpy(HostName,"openweathermap.org"); retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET); if(retVal == 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(80); Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian ASize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( SockID >= 0 ){ retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize); } if((SockID >= 0)&&(retVal >= 0)){ strcpy(SendBuff,REQUEST); sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response sl_Close(SockID); LED_GreenOn(); UARTprintf("\r\n\r\n"); UARTprintf(Recvbuff); UARTprintf("\r\n"); } } ST7735_OutUDec(sendc); ST7735_OutString("\n"); i++; } //while(Board_Input()==0){}; // wait for touch LED_GreenOff(); //Temp Part e getTemp(Recvbuff); ST7735_OutChar('T'); ST7735_OutChar('e'); ST7735_OutChar('m'); ST7735_OutChar('p'); ST7735_OutChar(' '); ST7735_OutChar('='); ST7735_OutChar(' '); for(int i = 0; i < 5; i++){ ST7735_OutChar(myArray[i]); } ST7735_OutChar('\n'); //ADC Part f ADC0_SAC_R = ADC_SAC_AVG_64X; //enable 64 times average before obtaining result int voltage = ADC0_InSeq3(); ST7735_OutString("Voltage~"); ST7735_sDecOut3(voltage); char* voltageString; char voltageStringNum[5]; sprintf(voltageStringNum, "%.1d.%.3d", voltage/1000, voltage%1000); //ST7735_OutString(voltageStringNum); char* sendString; char str1[173] = "GET /query?city=Austin%20Texas&id=Ty%20Winkler%20Jeremiah%20Bartlett&greet=Voltage%3D"; strcat(str1, voltageStringNum); strcat(str1, "V&edxcode=8086 HTTP/1.1\r\nUser-Agent: Keil\r\nHost: embsysmooc.appspot.com\r\n\r\n"); strcpy(HostName,"embsysmooc.appspot.com"); retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET); if(retVal == 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(80); Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian ASize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( SockID >= 0 ){ retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize); } if((SockID >= 0)&&(retVal >= 0)){ strcpy(SendBuff, str1); count = 0; sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response sl_Close(SockID); LED_GreenOn(); UARTprintf("\r\n\r\n"); //ST7735_OutString(Recvbuff); UARTprintf("\r\n"); } } while(1); } }
int main(void) { UINT8 IsDHCP = 0; int32_t i32CommandStatus; _NetCfgIpV4Args_t ipV4; SlSockAddrIn_t Addr; UINT16 AddrSize = 0; INT16 SockID = 0; UINT32 data; long x = 0; //counter unsigned char len = sizeof(_NetCfgIpV4Args_t); int Status = 0; /* Stop WDT */ stopWDT(); /* Initialize the system clock of MCU */ initClk(); Board_Init(); // initialize LaunchPad I/O and PD1 LED ConfigureUART(); // Initialize the UART. UARTprintf("Section 11.4 IoT example, Volume 2 Real-time interfacing\n"); UARTprintf("This application is configured to generate text\n"); UARTprintf(" and send UDP packets to IP: %d.%d.%d.%d Port: %d\n\n", SL_IPV4_BYTE(IP_ADDR,3), SL_IPV4_BYTE(IP_ADDR,2), SL_IPV4_BYTE(IP_ADDR,1), SL_IPV4_BYTE(IP_ADDR,0),PORT_NUM); //added code from the powerpoint slide /* Initializing the CC3100 device */ sl_Start(0, 0, 0); /* Connecting to WLAN AP - Set with static parameters defined at the top After this call we will be connected and have IP address */ WlanConnect(); /* Read the IP parameter */ sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len,(unsigned char *)&ipV4); UARTprintf("This node is at IP: %d.%d.%d.%d\n", SL_IPV4_BYTE(ipV4.ipV4,3), SL_IPV4_BYTE(ipV4.ipV4,2), SL_IPV4_BYTE(ipV4.ipV4,1), SL_IPV4_BYTE(ipV4.ipV4,0)); Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons((UINT16)PORT_NUM); Addr.sin_addr.s_addr = sl_Htonl((UINT32)IP_ADDR); AddrSize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); // Loop forever waiting for commands from PC... // while(1) { // Print prompt for user. UARTprintf("\n>"); // Peek to see if a full command is ready for processing. while(UARTPeek('\r') == -1) LED_On(); // Approximately 1 millisecond delay. ROM_SysCtlDelay(ROM_SysCtlClockGet() / 3000); } // A '\r' was detected so get the line of text from the receive buffer. while(Status >= 0){ UARTprintf("\nSending a UDP packet ...\n"); UARTgets(g_cInput,sizeof(g_cInput)); //this function receives the input from the Putty and places it in a string //DO NOT CHANGE ANYTHING ABOVE THIS COMMENT //WHAT WE NEED TO DO: //work with the g_cInput to get the array of letters typed into the Putty //then send that Array using UARTprintf uBuf[0] = ATYPE; // defines this as an analog data type uBuf[1] = '='; data = 1000; Int2Str(data,(char*)&uBuf[2]); // [2] to [7] is 6 digit number UARTprintf(" %s ",uBuf); //this line sends a string to the receiver //the above 5 lines print out a = 1000; //everything below this is just error cases if( SockID < 0 ){ UARTprintf("SockIDerror "); Status = -1; // error }else{ LED_Toggle(); Status = sl_SendTo(SockID, uBuf, BUF_SIZE, 0, (SlSockAddr_t *)&Addr, AddrSize); if( Status <= 0 ){ sl_Close(SockID); UARTprintf("SockIDerror %d ",Status); }else{ UARTprintf("ok"); } } ROM_SysCtlDelay(ROM_SysCtlClockGet() / 100); // 10ms LED_Off(); } }
int main(int argc, char** argv) { SlSockAddrIn_t Addr = {0}; _u32 cipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; _u32 googleIP = 0; _u8 method = SL_SO_SEC_METHOD_SSLV3; _i32 AddrSize = -1; _i32 g_SockID = -1; _i32 retVal = -1; retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); /* Stop WDT and initialize the system-clock of the MCU These functions needs to be implemented in PAL */ stopWDT(); initClk(); /* Configure command line interface */ CLI_Configure(); displayBanner(); /* * Following function configures the device to default state by cleaning * the persistent settings stored in NVMEM (viz. connection profiles & * policies, power policy etc) * * Applications may choose to skip this step if the developer is sure * that the device is in its default state at start of application * * Note that all profiles and persistent settings that were done on the * device will be lost */ retVal = configureSimpleLinkToDefaultState(); if(retVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == retVal) { CLI_Write(" Failed to configure the device in its default state \n\r"); } LOOP_FOREVER(); } CLI_Write(" Device is configured in default state \n\r"); /* * Assumption is that the device is configured in station mode already * and it is in its default state */ /* Initializing the CC3100 device */ retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } CLI_Write(" Device started as STATION \n\r"); /* Connecting to WLAN AP - Set with static parameters defined at the top After this call we will be connected and have IP address */ retVal = establishConnectionWithAP(); if(retVal < 0) { CLI_Write(" Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } CLI_Write(" Connection established w/ AP and IP is acquired \n\r"); /* Update the CC3100 time */ retVal = SetTime(); if (retVal < 0) { CLI_Write(" Failed to set the device time \n\r"); LOOP_FOREVER(); } CLI_Write(" Establishing secure connection w/ google server \n\r"); /* get the server name via a DNS request */ retVal = sl_NetAppDnsGetHostByName(g_Google, pal_Strlen(g_Google), &googleIP, SL_AF_INET); if( retVal < 0 ) { CLI_Write(" Failed to get the IP address \n\r"); LOOP_FOREVER(); } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(googleIP); AddrSize = sizeof(SlSockAddrIn_t); /* opens a secure socket */ g_SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( g_SockID < 0 ) { CLI_Write(" Failed to open socket \n\r"); LOOP_FOREVER(); } /* configure the socket as SSLV3.0 */ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &method, sizeof(method)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* configure the socket as RSA with RC4 128 SHA */ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &cipher, sizeof(cipher)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* configure the socket with GOOGLE CA certificate-for server verification*/ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, SL_SSL_CA_CERT, pal_Strlen(SL_SSL_CA_CERT)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* connect to the peer device - GMail server */ retVal = sl_Connect(g_SockID, ( SlSockAddr_t *)&Addr, AddrSize); if (retVal < 0 ) { CLI_Write(" Failed to connect w/ google server \n\r"); LOOP_FOREVER(); } CLI_Write(" Connection w/ google server established successfully \n\r"); /* Stop the CC3100 device */ retVal = sl_Stop(SL_STOP_TIMEOUT); if(retVal < 0) LOOP_FOREVER(); return 0; }
/**************************************************************************** // //! \brief Opening a TCP client side socket and sending data //! //! This function opens a TCP socket and tries to connect to a Server IP_ADDR //! waiting on port PORT_NUM. //! If the socket connection is successful then the function will send 1000 //! TCP packets to the server. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, -1 on Error. // ****************************************************************************/ int BsdTcpClient(unsigned short usPort) { int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; unsigned long lLoopCount = 0; long lBytesSent = 0; // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; //filling the TCP server socket address sAddr.sin_family = SL_AF_INET; // sAddr.sin_port = usPort; // sAddr.sin_addr.s_addr = IP_ADDR ; sAddr.sin_port = sl_Htons((unsigned short)usPort); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)IP_ADDR); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { UART_PRINT("error at creating a TCP socket ! \n\r"); // error return -1; } UART_PRINT("iSockID :"); Z_NumDispaly(iSockID, 2); // connecting to TCP server iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { UART_PRINT("error at connecting to TCP server ! \n\r"); // error return -1; } UART_PRINT(" connected to TCP server ok! \n\r"); // sending 1000 packets to the TCP server while (lLoopCount < 1000) { // sending packet iStatus = sl_Send(iSockID, g_cBsdBuf, sTestBufLen, 0 ); if( iStatus <= 0 ) { UART_PRINT("error at sending packet"); Z_NumDispaly(lLoopCount,2); // error return -1; } lLoopCount++; lBytesSent += iStatus; } //closing the socket after sending 1000 packets sl_Close(iSockID); return 0; }