//**************************************************************************** // //! \brief OOB Application Main Task - Initializes SimpleLink Driver and //! Handles HTTP Requests //! \param[in] pvParameters is the data passed to the Task //! //! \return None // //**************************************************************************** static void OOBTask(void *pvParameters) { //Read Device Mode Configuration ReadDeviceConfiguration(); //Connect to Network ConnectToNetwork(); //Handle Async Events while(1) { //LED Actions if(g_ucLEDStatus == LED_ON) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus == LED_OFF) { GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus==LED_BLINK) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } } }
//***************************************************************************** // //! GETChar //! //! \param ucBuffer to which Command will be populated //! //! \return Success or Failure //! //! \brief Get the char string from UART // //***************************************************************************** unsigned int GETChar(unsigned char *ucBuffer) { int i = 0; char c; uiUartline = 0; // // Wait to receive a character over UART // while (MAP_UARTCharsAvail(CONSOLE) == false) { osi_Sleep(1); } c = MAP_UARTCharGetNonBlocking(CONSOLE); MAP_UARTCharPut(CONSOLE, c); ilength = 0; // // Checking the end of line // while (c != '\r' && c != '\n') { uiUartline = 1; // // Copying Data from UART into a buffer // if (c != '\b') { ilength++; *(ucBuffer + i) = c; i++; } // // Deleting last character when you hit backspace // if (c == '\b') { i--; ilength--; } while (MAP_UARTCharsAvail(CONSOLE) == false) { osi_Sleep(1); } c = MAP_UARTCharGetNonBlocking(CONSOLE); MAP_UARTCharPut(CONSOLE, c); } strncpy((char*)g_ucUARTBuffer, (char *)ucBuffer, ilength); memset(g_ucUARTRecvBuffer, 0, sizeof(g_ucUARTRecvBuffer)); return uiUartline; }
//***************************************************************************** // //! MicroPhone Control Routine //! //! \param pValue - pointer to a memory structure that is passed //! to the interrupt handler. //! //! \return None // //***************************************************************************** void MicroPhoneControl(void* pValue) { int iCount=0; unsigned long ulPin5Val = 1; //Check whether GPIO Level is Stable As No Debouncing Circuit in LP for(iCount=0;iCount<3;iCount++) { osi_Sleep(200); ulPin5Val = MAP_GPIOPinRead(GPIOA1_BASE,GPIO_PIN_5); if(ulPin5Val) { //False Alarm return; } } if (g_ucMicStartFlag == 0) { for(iCount = 0; iCount<3; iCount++) { //Blink LED 3 times to Indicate ON GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); osi_Sleep(50); GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); osi_Sleep(50); } g_ucMicStartFlag = 1; } else { //Blink LED 3 times to Indicate OFF for(iCount = 0; iCount<3; iCount++) { GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); osi_Sleep(50); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); osi_Sleep(50); } g_ucMicStartFlag = 0; } //Enable GPIO Interrupt MAP_GPIOIntClear(GPIOA1_BASE,GPIO_PIN_5); MAP_IntPendClear(INT_GPIOA1); MAP_IntEnable(INT_GPIOA1); MAP_GPIOIntEnable(GPIOA1_BASE,GPIO_PIN_5); }
int fm_player(void) { char song_url[128] = {0}; // It's very tricky douban encoding track name into sequence number, so the url is pretty formated int index = 0; Report("Douban FM is ready\r\n"); while(1) { //fm_get_channel(); if(index >= 10) index = 0; else index++; memset(song_url, 0, sizeof(song_url)); fm_get_song(song_url, "1", index); if (strlen(song_url)) { Report("Going to play : %s\r\n", song_url); GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO); fm_play_song(song_url); GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO); } else { // wait for next try Report("Cannot fitch a song to play, waiting for next try\r\n"); osi_Sleep(1000); } } }
//***************************************************************************** // //! Disconnect Disconnects from an Access Point //! //! \param none //! //! \return 0 disconnected done, other already disconnected // //***************************************************************************** long Network_IF_DisconnectFromAP() { long lRetVal = 0; if (IS_CONNECTED(g_ulStatus)) { lRetVal = sl_WlanDisconnect(); if(0 == lRetVal) { // Wait while(IS_CONNECTED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif } return lRetVal; } else { return lRetVal; } } else { return lRetVal; } }
void TargetTask(void * param) { while(1) { //printf("target\n"); osi_Sleep(10); } }
//**************************************************************************** // //! \brief OOB Application Main Task - Initializes SimpleLink Driver and //! Handles HTTP Requests //! \param[in] pvParameters is the data passed to the Task //! //! \return None // //**************************************************************************** static void OOBTask(void *pvParameters) { long lRetVal = -1; //Read Device Mode Configuration ReadDeviceConfiguration(); //Connect to Network lRetVal = ConnectToNetwork(); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } //Handle Async Events while(1) { //LED Actions if(g_ucLEDStatus == LED_ON) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus == LED_OFF) { GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus==LED_BLINK) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } } }
struct bm222_ctx *bm222_init(uint8_t addr) { struct bm222_ctx *ctx = (struct bm222_ctx *) calloc(1, sizeof(*ctx)); if (ctx == NULL) return NULL; ctx->addr = addr; { unsigned char val[2] = {BM222_REG_BGW_SOFTRESET, BM222_DO_SOFT_RESET}; if (I2C_IF_Write(addr, val, 2, 1) != 0) goto out_err; osi_Sleep(2 /* ms */); /* t_w,up1 = 1.8 ms */ } if (!bm222_fifo_init(ctx)) return false; { unsigned char val[2] = {BM222_REG_PMU_BW, BM222_PMU_BW_125_HZ}; if (I2C_IF_Write(addr, val, 2, 1) != 0) goto out_err; } return ctx; out_err: free(ctx); return NULL; }
void WlanConnect() { //Add Profile sl_WlanProfileAdd(g_cWlanSSID, strlen((char*)g_cWlanSSID), 0, &g_SecParams, 0,g_ucPriority,0); //Connecting to the Access point sl_WlanConnect(g_cWlanSSID, strlen((char*)g_cWlanSSID), 0, &g_SecParams, 0); //waiting for the device to connect to the AP and obtain ip address while (g_uiConnectTimeoutCnt<CONNECTION_TIMEOUT_COUNT && ((g_ucConnectionStatus == 0) || (g_ucIpObtained == 0))) { osi_Sleep(1); //Sleep 1 millisecond g_uiConnectTimeoutCnt++; } g_uiConnectTimeoutCnt = 0; }
/* function : socket连接到服务器 input : crs_socket_handler_t *sock : socket handle int8_t *ip : 服务器的IP地址,点分十进制表示 uint16_t port :服务器的端口号 uint32_t timeout_usec : 0表示阻塞,非0表示超时时间 return value : success : 返回0 fail : 返回 -1 */ extern int32_t crs_tcp_connect(crs_socket_handler_t *sock, char *ip, uint16_t port, uint32_t timeout_usec) { int32_t fd = sock->fd; struct sockaddr_in peer_addr; int val,timeout_ms; val = 0; timeout_ms = timeout_usec/1000; crs_memset(&peer_addr, 0, sizeof(peer_addr)); peer_addr.sin_family = AF_INET; peer_addr.sin_addr.s_addr = crs_inet_addr(ip); peer_addr.sin_port = htons(port); while (1) { val = connect(fd, (struct sockaddr *)&peer_addr, sizeof(peer_addr)); if((SL_EALREADY == val)||(SL_POOL_IS_EMPTY == val)) { if(timeout_ms > 0) { timeout_ms -=5; osi_Sleep(5); continue; } else { return -1; } } else if(val < 0) { return (-1); } else { break; } } return val; }
//***************************************************************************** // //! \brief This function Get the Scan Result //! //! \param[in] none //! //! \return Size of Scan Result Array //! //! \note //! // //***************************************************************************** int GetScanResult(Sl_WlanNetworkEntry_t* netEntries ) { UINT8 policyOpt; UINT32 IntervalVal = 60; int retVal; policyOpt = SL_CONNECTION_POLICY(0, 0, 0, 0, 0); retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION , policyOpt, NULL, 0); if(retVal < 0) { /* Error */ } // enable scan policyOpt = SL_SCAN_POLICY(1); // set scan policy - this starts the scan retVal = sl_WlanPolicySet(SL_POLICY_SCAN , policyOpt, (UINT8 *)(IntervalVal), sizeof(IntervalVal)); // delay 1 second to verify scan is started osi_Sleep(1000); // retVal indicates the valid number of entries // The scan results are occupied in netEntries[] retVal = sl_WlanGetNetworkList(0, SCAN_TABLE_SIZE, netEntries); // Disable scan policyOpt = SL_SCAN_POLICY(0); // set scan policy - this stops the scan sl_WlanPolicySet(SL_POLICY_SCAN , policyOpt, (UINT8 *)(IntervalVal), sizeof(IntervalVal)); return retVal; }
//***************************************************************************** // //! Network_IF_InitDriver //! The function initializes a CC3200 device and triggers it to start operation //! //! \param uiMode (device mode in which device will be configured) //! //! \return 0 : sucess, -ve : failure // //***************************************************************************** long Network_IF_InitDriver(unsigned int uiMode) { long lRetVal = -1; // Reset CC3200 Network State Machine InitializeAppVariables(); // // 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 application // // 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"); 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(NULL,NULL,NULL); if (lRetVal < 0 || lRetVal != ROLE_STA) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } UART_PRINT("Started SimpleLink Device: STA Mode\n\r"); if(uiMode == ROLE_AP) { UART_PRINT("Switching to AP mode on application request\n\r"); // Switch to AP role and restart lRetVal = sl_WlanSetMode(uiMode); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(0xFF); lRetVal = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lRetVal); // Check if the device is up in AP Mode if (ROLE_AP == lRetVal) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif } } else { // We don't want to proceed if the device is not coming up in AP-mode ASSERT_ON_ERROR(DEVICE_NOT_IN_AP_MODE); } UART_PRINT("Re-started SimpleLink Device: AP Mode\n\r"); } else if(uiMode == ROLE_P2P) { UART_PRINT("Switching to P2P mode on application request\n\r"); // Switch to AP role and restart lRetVal = sl_WlanSetMode(uiMode); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(0xFF); lRetVal = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lRetVal); // Check if the device is in station again if (ROLE_P2P != lRetVal) { // We don't want to proceed if the device is not coming up in P2P-mode ASSERT_ON_ERROR(DEVICE_NOT_IN_P2P_MODE); } UART_PRINT("Re-started SimpleLink Device: P2P Mode\n\r"); } else { // Device already started in STA-Mode } return 0; }
void SpeakerControl(void* pValue) { int iCount=0; unsigned long ulPin6Val = 1; long lRetVal = -1; //Check whether GPIO Level is Stable As No Debouncing Circuit in LP for(iCount=0;iCount<3;iCount++) { osi_Sleep(200); ulPin6Val = MAP_GPIOPinRead(GPIOA2_BASE,GPIO_PIN_6); if(ulPin6Val) { //False Alarm return; } } if (g_ucSpkrStartFlag == 0) { #ifndef MULTICAST //Un Register mDNS Service. lRetVal = sl_NetAppMDNSUnRegisterService((signed char *)CC3200_MDNS_NAME,\ (unsigned char)strlen((const char *)CC3200_MDNS_NAME)); if(lRetVal < 0) { UART_PRINT("Unable to unregister MDNS service\n\r"); } //Registering for the mDNS service. lRetVal = sl_NetAppMDNSRegisterService((signed char *)CC3200_MDNS_NAME, \ (unsigned char)strlen((const char *)CC3200_MDNS_NAME),\ (signed char *)"multicast",\ (unsigned char)strlen((const char *)"multicast"),\ AUDIO_PORT,1000,0); if(lRetVal < 0) { UART_PRINT("Unable to register MDNS service\n\r"); LOOP_FOREVER(); } #endif //Blink LED 3 times to Indicate ON for(iCount = 0; iCount<3; iCount++) { GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO); osi_Sleep(50); GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO); osi_Sleep(50); } g_ucSpkrStartFlag = 1; } else { //Un Register mDNS Service. lRetVal = sl_NetAppMDNSUnRegisterService((signed char *)CC3200_MDNS_NAME,\ (unsigned char)strlen((const char *)CC3200_MDNS_NAME)); if(lRetVal < 0) { UART_PRINT("Unable to unregister MDNS service\n\r"); } //Blink LED 3 times to Indicate OFF for(iCount = 0; iCount<3; iCount++) { GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO); osi_Sleep(50); GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO); osi_Sleep(50); } g_ucSpkrStartFlag = 0; } //Enable GPIO Interrupt MAP_GPIOIntClear(GPIOA2_BASE,GPIO_PIN_6); MAP_IntPendClear(INT_GPIOA2); MAP_IntEnable(INT_GPIOA2); MAP_GPIOIntEnable(GPIOA2_BASE,GPIO_PIN_6); }
//***************************************************************************** //! \brief This function puts the device in its default state. It: //! - Set the mode to STATION //! - Configures connection policy to Auto and AutoSmartConfig //! - Deletes all the stored profiles //! - Enables DHCP //! - Disables Scan policy //! - Sets Tx power to maximum //! - Sets power policy to normal //! - Unregister mDNS services //! - Remove all filters //! //! \param none //! \return On success, zero is returned. On error, negative is returned //***************************************************************************** long ConfigureSimpleLinkToDefaultState() { SlVersionFull ver = {{0}}; _WlanRxFilterOperationCommandBuff_t RxFilterIdMask = {{0}}; unsigned char ucVal = 1; unsigned char ucConfigOpt = 0; unsigned char ucConfigLen = 0; unsigned char ucPower = 0; long lRetVal = -1; long lMode = -1; lMode = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lMode); // If the device is not in station-mode, try configuring it in station-mode if (ROLE_STA != lMode) { if (ROLE_AP == lMode) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif } } // Switch to STA role and restart lRetVal = sl_WlanSetMode(ROLE_STA); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(0xFF); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lRetVal); // Check if the device is in station again if (ROLE_STA != lRetVal) { // We don't want to proceed if the device is not coming up in STA-mode ASSERT_ON_ERROR(DEVICE_NOT_IN_STATION_MODE); } } // Get the device's version-information ucConfigOpt = SL_DEVICE_GENERAL_VERSION; ucConfigLen = sizeof(ver); lRetVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &ucConfigOpt, &ucConfigLen, (unsigned char *)(&ver)); ASSERT_ON_ERROR(lRetVal); UART_PRINT("Host Driver Version: %s\n\r",SL_DRIVER_VERSION); UART_PRINT("Build Version %d.%d.%d.%d.31.%d.%d.%d.%d.%d.%d.%d.%d\n\r", ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3], ver.ChipFwAndPhyVersion.FwVersion[0],ver.ChipFwAndPhyVersion.FwVersion[1], ver.ChipFwAndPhyVersion.FwVersion[2],ver.ChipFwAndPhyVersion.FwVersion[3], ver.ChipFwAndPhyVersion.PhyVersion[0],ver.ChipFwAndPhyVersion.PhyVersion[1], ver.ChipFwAndPhyVersion.PhyVersion[2],ver.ChipFwAndPhyVersion.PhyVersion[3]); // Set connection policy to Auto + SmartConfig // (Device's default connection policy) lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0); ASSERT_ON_ERROR(lRetVal); // Remove all profiles lRetVal = sl_WlanProfileDel(0xFF); ASSERT_ON_ERROR(lRetVal); // // Device in station-mode. Disconnect previous connection if any // The function returns 0 if 'Disconnected done', negative number if already // disconnected Wait for 'disconnection' event if 0 is returned, Ignore // other return-codes // lRetVal = sl_WlanDisconnect(); if(0 == lRetVal) { // Wait while(IS_CONNECTED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif } } // Enable DHCP client lRetVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&ucVal); ASSERT_ON_ERROR(lRetVal); // Disable scan ucConfigOpt = SL_SCAN_POLICY(0); lRetVal = sl_WlanPolicySet(SL_POLICY_SCAN , ucConfigOpt, NULL, 0); ASSERT_ON_ERROR(lRetVal); // Set Tx power level for station mode // Number between 0-15, as dB offset from max power - 0 will set max power ucPower = 0; lRetVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&ucPower); ASSERT_ON_ERROR(lRetVal); // Set PM policy to normal lRetVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0); ASSERT_ON_ERROR(lRetVal); // Unregister mDNS services lRetVal = sl_NetAppMDNSUnRegisterService(0, 0); ASSERT_ON_ERROR(lRetVal); // Remove all 64 filters (8*8) memset(RxFilterIdMask.FilterIdMask, 0xFF, 8); lRetVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask, sizeof(_WlanRxFilterOperationCommandBuff_t)); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(SL_STOP_TIMEOUT); ASSERT_ON_ERROR(lRetVal); InitializeAppVariables(); return lRetVal; // Success }
long ConnectToNetwork() { long lRetVal = -1; unsigned int uiConnectTimeoutCnt =0; //Start Simplelink Device lRetVal = sl_Start(NULL,NULL,NULL); ASSERT_ON_ERROR(lRetVal); if(lRetVal != ROLE_STA) { if (ROLE_AP == lRetVal) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } } // // Configure to STA Mode // lRetVal = ConfigureMode(ROLE_STA); if(lRetVal !=ROLE_STA) { UART_PRINT("Unable to set STA mode...\n\r"); lRetVal = sl_Stop(SL_STOP_TIMEOUT); CLR_STATUS_BIT_ALL(g_ulStatus); return DEVICE_NOT_IN_STATION_MODE; } } //waiting for the device to Auto Connect while(uiConnectTimeoutCnt<AUTO_CONNECTION_TIMEOUT_COUNT && ((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus)))) { //Turn Green LED On GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); osi_Sleep(50); //Turn Green LED Off GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); osi_Sleep(50); uiConnectTimeoutCnt++; } //Couldn't connect Using Auto Profile if(uiConnectTimeoutCnt==AUTO_CONNECTION_TIMEOUT_COUNT) { CLR_STATUS_BIT_ALL(g_ulStatus); //Turn Green LED On GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); //Connect Using Smart Config lRetVal = SmartConfigConnect(); ASSERT_ON_ERROR(lRetVal); //Waiting for the device to Auto Connect while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { MAP_UtilsDelay(500); } //Turn Green LED Off GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); } return SUCCESS; }
void initNetwork(signed char *ssid, SlSecParams_t *keyParams) { memset(g_ConnectionSSID, 0, sizeof(g_ConnectionSSID)); memset(g_ConnectionBSSID, 0, sizeof(g_ConnectionBSSID)); short status = sl_Start(0, 0, 0); if (status >= 0) { printVersionInfo(); // disable scan unsigned char configOpt = SL_SCAN_POLICY(0); sl_WlanPolicySet(SL_POLICY_SCAN, configOpt, NULL, 0); // set tx power to maximum unsigned char txPower = 0; sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&txPower); // set power policy to normal sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0); // remove all rx filters _WlanRxFilterOperationCommandBuff_t rxFilterIdMask; memset(rxFilterIdMask.FilterIdMask, 0xFF, 8); sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (unsigned char *)&rxFilterIdMask, sizeof(_WlanRxFilterOperationCommandBuff_t)); status = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 0), NULL, 0); } if (status < 0) { sl_Stop(SL_STOP_TIMEOUT); ERR_PRINT(status); LOOP_FOREVER(); } if (status < 0) { sl_Stop(SL_STOP_TIMEOUT); ERR_PRINT(status); LOOP_FOREVER(); } sl_WlanDisconnect(); status = sl_WlanSetMode(ROLE_STA); if (status < 0) { sl_Stop(SL_STOP_TIMEOUT); ERR_PRINT(status); LOOP_FOREVER(); } UART_PRINT("\r\n"); UART_PRINT("[QuickStart] Network init\r\n"); status = sl_WlanConnect(ssid, strlen((char *)ssid), NULL, keyParams, NULL); if (status < 0) { sl_Stop(SL_STOP_TIMEOUT); ERR_PRINT(status); LOOP_FOREVER(); } while (!IS_IP_ACQUIRED(g_Status)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(100); #endif } sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); }
void delay_m(int m) { osi_Sleep(m); }
void sj_usleep(int usecs) { osi_Sleep(usecs / 1000 /* ms */); }
//**************************************************************************** // //! \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is //! Placed, Force it to AP mode //! //! \return None // //**************************************************************************** void ConnectToNetwork() { char ucAPSSID[32]; unsigned short len, config_opt; // staring simplelink g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); unsigned char macAddressVal[SL_MAC_ADDR_LEN]; unsigned char macAddressLen = SL_MAC_ADDR_LEN; sl_NetCfgGet(SL_MAC_ADDRESS_GET,NULL,&macAddressLen,(unsigned char *)macAddressVal); Report("CC3200 LaunchPad MAC Address: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n\r", macAddressVal[0],macAddressVal[1],macAddressVal[2],macAddressVal[3],macAddressVal[4],macAddressVal[5]); // Device is in AP Mode and Force AP Jumper is not Connected if(((g_uiSimplelinkRole == ROLE_AP) || (g_uiSimplelinkRole == ROLE_P2P)) && g_uiDeviceModeConfig == ROLE_STA ) { //Switch to STA Mode sl_WlanSetMode(ROLE_STA); sl_Stop(SL_STOP_TIMEOUT); g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); } //Device is in STA Mode and Force AP Jumper is Connected if(((g_uiSimplelinkRole == ROLE_STA) || (g_uiSimplelinkRole == ROLE_P2P)) && g_uiDeviceModeConfig == ROLE_AP ) { //Switch to AP Mode sl_WlanSetMode(ROLE_AP); sl_Stop(SL_STOP_TIMEOUT); g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); } //No Mode Change Required if(g_uiSimplelinkRole == ROLE_AP) { //waiting for the AP to acquire IP address from Internal DHCP Server while (!(g_usMCNetworkUstate & MCU_IP_ALLOC)) { } char iCount=0; //Read the AP SSID memset(ucAPSSID,'\0',AP_SSID_LEN_MAX); len = AP_SSID_LEN_MAX; config_opt = WLAN_AP_OPT_SSID; sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (unsigned char*) ucAPSSID); //Blink LED 3 times to Indicate AP Mode for(iCount=0;iCount<3;iCount++) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(400); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(400); } } else { //waiting for the device to Auto Connect while (((!(g_usMCNetworkUstate & MCU_AP_ASSOC)) || !(g_usMCNetworkUstate & MCU_IP_ALLOC))&& g_ucConnectTimeout < AUTO_CONNECTION_TIMEOUT_COUNT) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(50); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(50); g_ucConnectTimeout++; } //Couldn't connect Using Auto Profile if(g_ucConnectTimeout == AUTO_CONNECTION_TIMEOUT_COUNT) { //Blink Red LED to Indicate Connection Error GPIO_IF_LedOn(MCU_RED_LED_GPIO); g_ucConnectTimeout &= ~MCU_AP_ASSOC; g_ucConnectTimeout &= ~MCU_IP_ALLOC; //Connect Using Smart Config SmartConfigConnect(); //Waiting for the device to Auto Connect while (!(g_usMCNetworkUstate & MCU_AP_ASSOC) || !(g_usMCNetworkUstate & MCU_IP_ALLOC)) { MAP_UtilsDelay(500); } } //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); g_iInternetAccess = ConnectionTest(); if (g_iInternetAccess == 0) { Report("Successful connection to the Internet\r\n"); osi_SyncObjSignal(&semaphore_Connected); //signal "Connected" semaphore so mqtt task can continue } else { Report("Could not obtain connection to the Internet\r\n"); } } }
static void blinkenlights_task(void *arg) { while (1) { cc3200_leds(GREEN, TOGGLE); osi_Sleep(500); } }
//**************************************************************************** // //! \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is //! Placed, Force it to AP mode //! //! \return 0 - Success //! -1 - Failure // //**************************************************************************** long ConnectToNetwork() { long lRetVal = -1; unsigned int uiConnectTimeoutCnt =0; // staring simplelink lRetVal = sl_Start(NULL,NULL,NULL); ASSERT_ON_ERROR( lRetVal); // Device is in AP Mode and Force AP Jumper is not Connected if(ROLE_STA != lRetVal && g_uiDeviceModeConfig == ROLE_STA ) { if (ROLE_AP == lRetVal) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } } //Switch to STA Mode lRetVal = ConfigureMode(ROLE_STA); ASSERT_ON_ERROR( lRetVal); } //Device is in STA Mode and Force AP Jumper is Connected if(ROLE_AP != lRetVal && g_uiDeviceModeConfig == ROLE_AP ) { //Switch to AP Mode lRetVal = ConfigureMode(ROLE_AP); ASSERT_ON_ERROR( lRetVal); } //No Mode Change Required if(lRetVal == ROLE_AP) { //waiting for the AP to acquire IP address from Internal DHCP Server // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); char cCount=0; //Blink LED 3 times to Indicate AP Mode for(cCount=0;cCount<3;cCount++) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(400); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(400); } char ssid[32]; unsigned short len = 32; unsigned short config_opt = WLAN_AP_OPT_SSID; sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (unsigned char* )ssid); UART_PRINT("\n\r Connect to : \'%s\'\n\r\n\r",ssid); } else { //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //waiting for the device to Auto Connect while(uiConnectTimeoutCnt<AUTO_CONNECTION_TIMEOUT_COUNT && ((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus)))) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(50); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(50); uiConnectTimeoutCnt++; } //Couldn't connect Using Auto Profile if(uiConnectTimeoutCnt == AUTO_CONNECTION_TIMEOUT_COUNT) { //Blink Red LED to Indicate Connection Error GPIO_IF_LedOn(MCU_RED_LED_GPIO); CLR_STATUS_BIT_ALL(g_ulStatus); //Connect Using Smart Config lRetVal = SmartConfigConnect(); ASSERT_ON_ERROR(lRetVal); //Waiting for the device to Auto Connect while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { MAP_UtilsDelay(500); } } //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); g_iInternetAccess = ConnectionTest(); } return SUCCESS; }
//***************************************************************************** // //! Get the Command string from UART //! //! \param pucBuffer is the command store to which command will be populated //! \param ucBufLen is the length of buffer store available //! //! \return Length of the bytes received. -1 if buffer length exceeded. //! //***************************************************************************** int GetCmd(char *pcBuffer, unsigned int uiBufLen) { char cChar; int iLen = 0; // // Wait to receive a character over UART // while(MAP_UARTCharsAvail(CONSOLE) == false) { #if defined(USE_FREERTOS) || defined(USE_TI_RTOS) osi_Sleep(1); #endif } cChar = MAP_UARTCharGetNonBlocking(CONSOLE); // // Echo the received character // MAP_UARTCharPut(CONSOLE, cChar); iLen = 0; // // Checking the end of Command // while((cChar != '\r') && (cChar !='\n') ) { // // Handling overflow of buffer // if(iLen >= uiBufLen) { return -1; } // // Copying Data from UART into a buffer // if(cChar != '\b') { *(pcBuffer + iLen) = cChar; iLen++; } else { // // Deleting last character when you hit backspace // if(iLen) { iLen--; } } // // Wait to receive a character over UART // while(MAP_UARTCharsAvail(CONSOLE) == false) { #if defined(USE_FREERTOS) || defined(USE_TI_RTOS) osi_Sleep(1); #endif } cChar = MAP_UARTCharGetNonBlocking(CONSOLE); // // Echo the received character // MAP_UARTCharPut(CONSOLE, cChar); } *(pcBuffer + iLen) = '\0'; Report("\n\r"); return iLen; }
//***************************************************************************** // //! Task implementing MQTT client communication to other web client through //! a broker //! //! \param none //! //! This function //! 1. Initializes network driver and connects to the default AP //! 2. Initializes the mqtt library and set up MQTT connection configurations //! 3. set up the button events and their callbacks(for publishing) //! 4. handles the callback signals //! //! \return None //! //***************************************************************************** void MqttClient(void *pvParameters) { long lRetVal = -1; int iCount = 0; int iNumBroker = 0; int iConnBroker = 0; event_msg RecvQue; unsigned char policyVal; connect_config *local_con_conf = (connect_config *)app_hndl; // // Configure LED // GPIO_IF_LedConfigure(LED1|LED2|LED3); GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); // // 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",lRetVal); LOOP_FOREVER(); } // switch on Green LED to indicate Simplelink is properly up GPIO_IF_LedOn(MCU_ON_IND); // Start Timer to blink Red LED till AP connection LedTimerConfigNStart(); // 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 an AP failed\n\r"); LOOP_FOREVER(); } lRetVal = sl_WlanProfileAdd(SSID_NAME,strlen(SSID_NAME),0,&SecurityParams,0,1,0); //set AUTO policy lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1,0,0,0,0), &policyVal, 1 /*PolicyValLen*/); // // 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); UtilsDelay(20000000); GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); // // Register Push Button Handlers // Button_IF_Init(pushButtonInterruptHandler2,pushButtonInterruptHandler3); // // Initialze MQTT client lib // lRetVal = sl_ExtLib_MqttClientInit(&Mqtt_Client); if(lRetVal != 0) { // lib initialization failed UART_PRINT("MQTT Client lib initialization failed\n\r"); LOOP_FOREVER(); } /******************* connection to the broker ***************************/ iNumBroker = sizeof(usr_connect_config)/sizeof(connect_config); if(iNumBroker > MAX_BROKER_CONN) { UART_PRINT("Num of brokers are more then max num of brokers\n\r"); LOOP_FOREVER(); } connect_to_broker: while(iCount < iNumBroker) { //create client context local_con_conf[iCount].clt_ctx = sl_ExtLib_MqttClientCtxCreate(&local_con_conf[iCount].broker_config, &local_con_conf[iCount].CallBAcks, &(local_con_conf[iCount])); // // Set Client ID // sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx, SL_MQTT_PARAM_CLIENT_ID, local_con_conf[iCount].client_id, strlen((char*)(local_con_conf[iCount].client_id))); // // Set will Params // if(local_con_conf[iCount].will_params.will_topic != NULL) { sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx, SL_MQTT_PARAM_WILL_PARAM, &(local_con_conf[iCount].will_params), sizeof(SlMqttWill_t)); } // // setting username and password // if(local_con_conf[iCount].usr_name != NULL) { sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx, SL_MQTT_PARAM_USER_NAME, local_con_conf[iCount].usr_name, strlen((char*)local_con_conf[iCount].usr_name)); if(local_con_conf[iCount].usr_pwd != NULL) { sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx, SL_MQTT_PARAM_PASS_WORD, local_con_conf[iCount].usr_pwd, strlen((char*)local_con_conf[iCount].usr_pwd)); } } // // connectin to the broker // if((sl_ExtLib_MqttClientConnect((void*)local_con_conf[iCount].clt_ctx, local_con_conf[iCount].is_clean, local_con_conf[iCount].keep_alive_time) & 0xFF) != 0) { UART_PRINT("\n\rBroker connect fail for conn no. %d \n\r",iCount+1); //delete the context for this connection sl_ExtLib_MqttClientCtxDelete(local_con_conf[iCount].clt_ctx); break; } else { UART_PRINT("\n\rSuccess: conn to Broker no. %d\n\r ", iCount+1); local_con_conf[iCount].is_connected = true; iConnBroker++; } // // Subscribe to topics // if(sl_ExtLib_MqttClientSub((void*)local_con_conf[iCount].clt_ctx, local_con_conf[iCount].topic, local_con_conf[iCount].qos, TOPIC_COUNT) < 0) { UART_PRINT("\n\r Subscription Error for conn no. %d\n\r", iCount+1); UART_PRINT("Disconnecting from the broker\r\n"); sl_ExtLib_MqttClientDisconnect(local_con_conf[iCount].clt_ctx); local_con_conf[iCount].is_connected = false; //delete the context for this connection sl_ExtLib_MqttClientCtxDelete(local_con_conf[iCount].clt_ctx); iConnBroker--; break; } else { int iSub; UART_PRINT("Client subscribed on following topics:\n\r"); for(iSub = 0; iSub < local_con_conf[iCount].num_topics; iSub++) { UART_PRINT("%s\n\r", local_con_conf[iCount].topic[iSub]); } } iCount++; } if(iConnBroker < 1) { // // no succesful connection to broker // goto end; } iCount = 0; for(;;) { osi_MsgQRead( &g_PBQueue, &RecvQue, OSI_WAIT_FOREVER); if(PUSH_BUTTON_SW2_PRESSED == RecvQue.event) { Button_IF_EnableInterrupt(SW2); // // send publish message // sl_ExtLib_MqttClientSend((void*)local_con_conf[iCount].clt_ctx, pub_topic_sw2,data_sw2,strlen((char*)data_sw2),QOS2,RETAIN); UART_PRINT("\n\r CC3200 Publishes the following message \n\r"); UART_PRINT("Topic: %s\n\r",pub_topic_sw2); UART_PRINT("Data: %s\n\r",data_sw2); } else if(PUSH_BUTTON_SW3_PRESSED == RecvQue.event) { Button_IF_EnableInterrupt(SW3); // // send publish message // sl_ExtLib_MqttClientSend((void*)local_con_conf[iCount].clt_ctx, pub_topic_sw3,data_sw3,strlen((char*)data_sw3),QOS2,RETAIN); UART_PRINT("\n\r CC3200 Publishes the following message \n\r"); UART_PRINT("Topic: %s\n\r",pub_topic_sw3); UART_PRINT("Data: %s\n\r",data_sw3); } else if(BROKER_DISCONNECTION == RecvQue.event) { iConnBroker--; /* Derive the value of the local_con_conf or clt_ctx from the message */ sl_ExtLib_MqttClientCtxDelete(((connect_config*)(RecvQue.hndl))->clt_ctx); if(!IS_CONNECTED(g_ulStatus)) { UART_PRINT("device has disconnected from AP \n\r"); UART_PRINT("retry connection to the AP\n\r"); while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus))) { osi_Sleep(10); } goto connect_to_broker; } if(iConnBroker < 1) { // // device not connected to any broker // goto end; } } } end: // // Deinitializating the client library // sl_ExtLib_MqttClientExit(); UART_PRINT("\n\r Exiting the Application\n\r"); LOOP_FOREVER(); }
/* function : 从socket中接收数据到buf[0:n)中,超时时间为timeout_usec微秒 input : crs_socket_handler_t *sock : socket handle void *buf : 存储所接收数据的buffer uint32_t n :指示第二个参数buf的长度 uint32_t timeout_usec : 非0表示超时时间,0表示阻塞 return value : success : 返回所接收到的字符的数量,0表示没接收到数据 fail : 返回-1,表示连接断开 */ extern int32_t crs_tcp_recv(crs_socket_handler_t *sock, void *buf, uint32_t n, uint32_t timeout_usec) { int32_t fd = sock->fd; int32_t ret; uint32_t len = n; uint8_t * recv_buf; recv_buf = buf; if (0 == timeout_usec) { return recv(fd, recv_buf, len, SL_SO_NONBLOCKING); } uint32_t timeout_left = timeout_usec; struct timeval delay; while(len > 0) { crs_memset(&delay, 0, sizeof(struct timeval)); delay.tv_sec = timeout_left / 1000000; delay.tv_usec = timeout_left % 1000000; fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); ret = select(fd + 1, &fds, NULL, NULL, &delay); if(ret < 0) { return -1; } else if(ret == 0) { return 0; } else { if(FD_ISSET(fd, &fds)) { timeout_left = delay.tv_sec * 1000000 + delay.tv_usec; ret = recv(fd, recv_buf, len, 0); if(SL_EAGAIN == ret) { osi_Sleep(100); continue; } else if(ret<0) { return -1; } else { return ret; } } else { return -1; } } } return 0; }
//***************************************************************************** // //! Network_IF_ConnectAP Connect to an Access Point using the specified SSID //! //! \param[in] pcSsid is a string of the AP's SSID //! \param[in] SecurityParams is Security parameter for AP //! //! \return On success, zero is returned. On error, -ve value is returned // //***************************************************************************** long Network_IF_ConnectAP(char *pcSsid, SlSecParams_t SecurityParams) { #ifndef NOTERM char acCmdStore[128]; unsigned short usConnTimeout; unsigned char ucRecvdAPDetails; #endif long lRetVal; unsigned long ulIP = 0; unsigned long ulSubMask = 0; unsigned long ulDefGateway = 0; unsigned long ulDns = 0; // // Disconnect from the AP // Network_IF_DisconnectFromAP(); // // This triggers the CC3200 to connect to specific AP // lRetVal = sl_WlanConnect((signed char *)pcSsid, strlen((const char *)pcSsid), NULL, &SecurityParams, NULL); ASSERT_ON_ERROR(lRetVal); // // Wait for ~10 sec to check if connection to desire AP succeeds // while(g_usConnectIndex < 15) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif MAP_UtilsDelay(8000000); if(IS_CONNECTED(g_ulStatus) && IS_IP_ACQUIRED(g_ulStatus)) { break; } g_usConnectIndex++; } #ifndef NOTERM // // Check and loop until AP connection successful, else ask new AP SSID name // while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus))) { // // Disconnect the previous attempt // Network_IF_DisconnectFromAP(); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); UART_PRINT("Device could not connect to %s\n\r",pcSsid); do { ucRecvdAPDetails = 0; UART_PRINT("\n\r\n\rPlease enter the AP(open) SSID name # "); // // Get the AP name to connect over the UART // lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal > 0) { // remove start/end spaces if any lRetVal = TrimSpace(acCmdStore); // // Parse the AP name // strncpy(pcSsid, acCmdStore, lRetVal); if(pcSsid != NULL) { ucRecvdAPDetails = 1; pcSsid[lRetVal] = '\0'; } } }while(ucRecvdAPDetails == 0); // // Reset Security Parameters to OPEN security type // SecurityParams.Key = (signed char *)""; SecurityParams.KeyLen = 0; SecurityParams.Type = SL_SEC_TYPE_OPEN; UART_PRINT("\n\rTrying to connect to AP: %s ...\n\r",pcSsid); // // Get the current timer tick and setup the timeout accordingly // usConnTimeout = g_usConnectIndex + 15; // // This triggers the CC3200 to connect to specific AP // lRetVal = sl_WlanConnect((signed char *)pcSsid, strlen((const char *)pcSsid), NULL, &SecurityParams, NULL); ASSERT_ON_ERROR(lRetVal); // // Wait ~10 sec to check if connection to specifed AP succeeds // while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus))) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif MAP_UtilsDelay(8000000); if(g_usConnectIndex >= usConnTimeout) { break; } g_usConnectIndex++; } } #endif // // Put message on UART // UART_PRINT("\n\rDevice has connected to %s\n\r",pcSsid); // // Get IP address // lRetVal = Network_IF_IpConfigGet(&ulIP,&ulSubMask,&ulDefGateway,&ulDns); ASSERT_ON_ERROR(lRetVal); // // Send the information // UART_PRINT("Device IP Address is %d.%d.%d.%d \n\r\n\r", SL_IPV4_BYTE(ulIP, 3),SL_IPV4_BYTE(ulIP, 2), SL_IPV4_BYTE(ulIP, 1),SL_IPV4_BYTE(ulIP, 0)); return 0; }
void ControlServer(void *pvParameters) { char ServerBuffer[CONFIG_SERVER_BUFFER]; char MsgBuffer[100]; char *pMsgBuffer; SlSockAddrIn_t sAddr; SlSockAddrIn_t sLocalAddr; int32_t i32SockID; int32_t i32NewSockID; int32_t i32DataSize; int32_t i32NonBlocking = 1; SlSocklen_t i32AddrSize; int32_t retval; pMsgBuffer = &MsgBuffer[0]; InitVariables(); retval = ResetSimpleLink(); if (retval < 0) while (1) ; WlanConnect(); sprintf(MsgBuffer, "Connectado a rede: %s\n\r" "IP: %d.%d.%d.%d\n\r" "Gateway: %d.%d.%d.%d\n\r", SL_IPV4_BYTE(g_sSLCon.DeviceIP, 3), SL_IPV4_BYTE(g_sSLCon.DeviceIP, 2), SL_IPV4_BYTE(g_sSLCon.DeviceIP, 1), SL_IPV4_BYTE(g_sSLCon.DeviceIP, 0), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 3), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 2), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 1), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 0)); osi_MsgQWrite(&g_sUartQuee, &pMsgBuffer, OSI_NO_WAIT); sLocalAddr.sin_family = SL_AF_INET; sLocalAddr.sin_port = sl_Htons((unsigned short) g_sSLCon.PortNumber); sLocalAddr.sin_addr.s_addr = 0; i32SockID = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0); sl_Bind(i32SockID, (SlSockAddr_t *) &sLocalAddr, sizeof(SlSockAddrIn_t)); sl_Listen(i32SockID, 0); sl_SetSockOpt(i32SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &i32NonBlocking, sizeof(i32NonBlocking)); while (1) { i32NewSockID = SL_EAGAIN; while (i32NewSockID < 0) { i32NewSockID = sl_Accept(i32SockID, (struct SlSockAddr_t *) &sAddr, (SlSocklen_t*) &i32AddrSize); if (i32NewSockID == SL_EAGAIN) { osi_Sleep(100); } else if (i32NewSockID < 0) { while (1) { } } } i32DataSize = sl_Recv(i32NewSockID, ServerBuffer, CONFIG_SERVER_BUFFER, 0); if (strcmp(ServerBuffer, "Led On") == 0) { Led_Green(LED_ON); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } else if (strcmp(ServerBuffer, "Led Off") == 0) { Led_Green(LED_OFF); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } else if (strcmp(ServerBuffer, "Lamp On") == 0) { MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, GPIO_PIN_6); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } else if (strcmp(ServerBuffer, "Lamp Off") == 0) { MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, 0); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } sl_Send(i32NewSockID, ServerBuffer, i32DataSize, 0); sl_Close(i32NewSockID); } }
/* function : 发送数据buf[0:n) input : crs_socket_handler_t *sock : socket handle void *buf : 发送的字符串 uint32_t n :指示第二个参数buf的长度 return value : success : 返回所发送的数据的长度 fail : 返回-1,表示连接断开 */ extern int32_t crs_tcp_send(crs_socket_handler_t *sock, void *buf, uint32_t n, uint32_t timeout_usec) { uint32_t send_len ; uint8_t *send_buf; uint32_t ___timeout; int32_t fd ; int32_t ret=0; send_len = n; send_buf = buf; ___timeout = timeout_usec; fd = sock->fd; //dbg("FREE STACK SPACE:%d\r\n",uxTaskGetStackHighWaterMark()); //TODO 如果timeout_usec 为0 则直接进行发送一次 if (0 == timeout_usec) { ret = send(fd, send_buf, send_len, 0); return ret; } while (0 != send_len) { //判断是否可写 fd_set wset; struct timeval timeout; FD_ZERO(&wset); FD_SET(fd, &wset); timeout.tv_sec = (___timeout)/1000000; timeout.tv_usec = (___timeout)%1000000; ret = select(fd+1, NULL, &wset, NULL, &timeout); if (0 > ret) { return -1; } else if(0 == ret) { return 0; } else { if (FD_ISSET(fd, &wset)) { ___timeout = timeout.tv_sec*1000000 + timeout.tv_usec; } else { return -1; //sock 错误? } //send ret = send(fd, send_buf, send_len, 0); if (SL_EAGAIN == ret) { osi_Sleep(100); continue; } else if(ret < 0) { return (-1); } return ret; } } return 0; }
int sj_wifi_setup_ap(const struct sys_config_wifi_ap *cfg) { int ret; uint8_t v; SlNetCfgIpV4Args_t ipcfg; SlNetAppDhcpServerBasicOpt_t dhcpcfg; if ((ret = sl_WlanSetMode(ROLE_AP)) != 0) { fprintf(stderr, "sl_WlanSetMode: %d\n", ret); return 0; } if ((ret = sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SSID, strlen(cfg->ssid), (const uint8_t *) cfg->ssid)) != 0) { fprintf(stderr, "sl_WlanSet(WLAN_AP_OPT_SSID): %d\n", ret); return 0; } v = strlen(cfg->pass) > 0 ? SL_SEC_TYPE_WPA : SL_SEC_TYPE_OPEN; if ((ret = sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SECURITY_TYPE, 1, &v)) != 0) { fprintf(stderr, "sl_WlanSet(WLAN_AP_OPT_SECURITY_TYPE): %d\n", ret); return 0; } if (v == SL_SEC_TYPE_WPA && (ret = sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_PASSWORD, strlen(cfg->pass), (const uint8_t *) cfg->pass)) != 0) { fprintf(stderr, "sl_WlanSet(WLAN_AP_OPT_PASSWORD): %d\n", ret); return 0; } v = cfg->channel; if ((ret = sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_CHANNEL, 1, (uint8_t *) &v)) != 0) { fprintf(stderr, "sl_WlanSet(WLAN_AP_OPT_CHANNEL): %d\n", ret); return 0; } v = cfg->hidden; if ((ret = sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_HIDDEN_SSID, 1, (uint8_t *) &v)) != 0) { fprintf(stderr, "sl_WlanSet(WLAN_AP_OPT_HIDDEN_SSID): %d\n", ret); return 0; } memset(&ipcfg, 0, sizeof(ipcfg)); if (!inet_pton(AF_INET, cfg->ip, &ipcfg.ipV4) || !inet_pton(AF_INET, cfg->netmask, &ipcfg.ipV4Mask) || !inet_pton(AF_INET, cfg->gw, &ipcfg.ipV4Gateway) || !inet_pton(AF_INET, cfg->gw, &ipcfg.ipV4DnsServer) || (ret = sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE, IPCONFIG_MODE_ENABLE_IPV4, sizeof(ipcfg), (uint8_t *) &ipcfg)) != 0) { fprintf(stderr, "sl_NetCfgSet(IPCONFIG_MODE_ENABLE_IPV4): %d\n", ret); return 0; } memset(&dhcpcfg, 0, sizeof(dhcpcfg)); dhcpcfg.lease_time = 900; if (!inet_pton(AF_INET, cfg->dhcp_start, &dhcpcfg.ipv4_addr_start) || !inet_pton(AF_INET, cfg->dhcp_end, &dhcpcfg.ipv4_addr_last) || (ret = sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, sizeof(dhcpcfg), (uint8_t *) &dhcpcfg)) != 0) { fprintf(stderr, "sl_NetCfgSet(NETAPP_SET_DHCP_SRV_BASIC_OPT): %d\n", ret); return 0; } /* We don't need TI's web server. */ sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); /* Turning the device off and on for the change to take effect. */ sl_Stop(0); sl_Start(NULL, NULL, NULL); osi_Sleep(100); fprintf(stderr, "AP %s configured\n", cfg->ssid); return 1; }
//**************************************************************************** // //! \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is //! Placed, Force it to AP mode //! //! \return 0 on success else error code // //**************************************************************************** long ConnectToNetwork() { char ucAPSSID[32]; unsigned short len, config_opt; long lRetVal = -1; // staring simplelink g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); // Device is not in STA mode and Force AP Jumper is not Connected //- Switch to STA mode if(g_uiSimplelinkRole != ROLE_STA && g_uiDeviceModeConfig == ROLE_STA ) { //Switch to STA Mode lRetVal = sl_WlanSetMode(ROLE_STA); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(SL_STOP_TIMEOUT); g_usMCNetworkUstate = 0; g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); UART_PRINT("started in STA mode\n\r"); } //Device is not in AP mode and Force AP Jumper is Connected - //Switch to AP mode if(g_uiSimplelinkRole != ROLE_AP && g_uiDeviceModeConfig == ROLE_AP ) { //Switch to AP Mode lRetVal = sl_WlanSetMode(ROLE_AP); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(SL_STOP_TIMEOUT); g_usMCNetworkUstate = 0; g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); } //No Mode Change Required if(g_uiSimplelinkRole == ROLE_AP) { //waiting for the AP to acquire IP address from Internal DHCP Server while(!IS_IP_ACQUIRED(g_ulStatus)) { } //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); char iCount=0; //Read the AP SSID memset(ucAPSSID,'\0',AP_SSID_LEN_MAX); len = AP_SSID_LEN_MAX; config_opt = WLAN_AP_OPT_SSID; lRetVal = sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (unsigned char*) ucAPSSID); ASSERT_ON_ERROR(lRetVal); Report("\n\rDevice is in AP Mode, Please Connect to AP [%s] and" "type [mysimplelink.net] in the browser \n\r",ucAPSSID); //Blink LED 3 times to Indicate AP Mode for(iCount=0;iCount<3;iCount++) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(400); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(400); } } else { //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); /*//waiting for the device to Auto Connect while ( (!IS_IP_ACQUIRED(g_ulStatus))&& g_ucConnectTimeout < AUTO_CONNECTION_TIMEOUT_COUNT) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(50); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(50); g_ucConnectTimeout++; } //Couldn't connect Using Auto Profile if(g_ucConnectTimeout == AUTO_CONNECTION_TIMEOUT_COUNT) { //Blink Red LED to Indicate Connection Error GPIO_IF_LedOn(MCU_RED_LED_GPIO); CLR_STATUS_BIT_ALL(g_ulStatus); Report("Use Smart Config Application to configure the device.\n\r"); //Connect Using Smart Config lRetVal = SmartConfigConnect(); ASSERT_ON_ERROR(lRetVal); //Waiting for the device to Auto Connect while(!IS_IP_ACQUIRED(g_ulStatus)) { MAP_UtilsDelay(500); }*/ SlSecParams_t secParams = {0}; secParams.Key = (signed char *)SECURITY_KEY; secParams.KeyLen = strlen(SECURITY_KEY); secParams.Type = SECURITY_TYPE; lRetVal = sl_WlanConnect((signed char *)SSID_NAME, strlen((const char *)SSID_NAME), 0, &secParams, 0); ASSERT_ON_ERROR(lRetVal); // Wait for WLAN Event while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { //Turn Green LED On GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); osi_Sleep(50); //Turn Green LED Off GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); osi_Sleep(50); } //Turn Green LED Off GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); UART_PRINT("connected\n\r"); } //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); UART_PRINT("\n\rDevice is in STA Mode, Connect to the AP[%s] and type" "IP address [%d.%d.%d.%d] in the browser \n\r",g_ucConnectionSSID, SL_IPV4_BYTE(g_uiIpAddress,3),SL_IPV4_BYTE(g_uiIpAddress,2), SL_IPV4_BYTE(g_uiIpAddress,1),SL_IPV4_BYTE(g_uiIpAddress,0)); return SUCCESS; }