Ejemplo n.º 1
0
int main(void) {
  MAP_IntVTableBaseSet((unsigned long) &int_vectors[0]);
  MAP_IntMasterEnable();
  PRCMCC3200MCUInit();

/* Console UART init. */
#ifndef NO_DEBUG
  MAP_PRCMPeripheralClkEnable(DEBUG_UART_PERIPH, PRCM_RUN_MODE_CLK);
#if MIOT_DEBUG_UART == 0
  MAP_PinTypeUART(PIN_55, PIN_MODE_3); /* UART0_TX */
  MAP_PinTypeUART(PIN_57, PIN_MODE_3); /* UART0_RX */
#else
  MAP_PinTypeUART(PIN_07, PIN_MODE_5); /* UART1_TX */
  MAP_PinTypeUART(PIN_08, PIN_MODE_5); /* UART1_RX */
#endif
  MAP_UARTConfigSetExpClk(
      DEBUG_UART_BASE, MAP_PRCMPeripheralClockGet(DEBUG_UART_PERIPH),
      MIOT_DEBUG_UART_BAUD_RATE,
      (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));
  MAP_UARTFIFOLevelSet(DEBUG_UART_BASE, UART_FIFO_TX1_8, UART_FIFO_RX4_8);
  MAP_UARTFIFODisable(DEBUG_UART_BASE);
#endif

  dbg_puts("\r\n\n");

  if (sl_Start(NULL, NULL, NULL) < 0) abort();
  dbg_putc('S');

  int cidx = get_active_boot_cfg_idx();
  if (cidx < 0) abort();
  dbg_putc('0' + cidx);
  struct boot_cfg cfg;
  if (read_boot_cfg(cidx, &cfg) < 0) abort();

  dbg_puts(cfg.app_image_file);
  dbg_putc('@');
  print_addr(cfg.app_load_addr);

  /*
   * Zero memory before loading.
   * This should provide proper initialisation for BSS, wherever it is.
   */
  uint32_t *pstart = (uint32_t *) 0x20000000;
  uint32_t *pend = (&_text_start - 0x100 /* our stack */);
  for (uint32_t *p = pstart; p < pend; p++) *p = 0;

  if (load_image(cfg.app_image_file, (_u8 *) cfg.app_load_addr) != 0) {
    abort();
  }

  dbg_putc('.');

  sl_Stop(0);
  print_addr(*(((uint32_t *) cfg.app_load_addr) + 1));
  dbg_puts("\r\n\n");

  MAP_IntMasterDisable();
  MAP_IntVTableBaseSet(cfg.app_load_addr);

  run(cfg.app_load_addr); /* Does not return. */

  abort();

  return 0; /* not reached */
}
Ejemplo n.º 2
0
//*****************************************************************************
//
//! \brief  the aim of this example code is to demonstrate File-system
//!          capabilities of the device.
//!         For simplicity, the serial flash is used as the device under test.
//!
//! \param  None
//!
//! \return none
//!
//! \note   Green LED is turned solid in case of success
//!         Red LED is turned solid in case of failure
//
//*****************************************************************************
void main()
{
    long lRetVal;
    unsigned char policyVal;
    long lFileHandle;
    unsigned long ulToken;

    //
    // Initialize Board configurations
    //
    BoardInit();

    //
    // Configure the pinmux settings for the peripherals exercised
    //
    PinMuxConfig();

    //
    // Configure LEDs
    //
    GPIO_IF_LedConfigure(LED1|LED3);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);


    //
    // Initializing the CC3200 networking layers
    //
    lRetVal = sl_Start(NULL, NULL, NULL);
    if(lRetVal < 0)
    {
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        LOOP_FOREVER();
    }

    //
    // reset all network policies
    //
    lRetVal = sl_WlanPolicySet(  SL_POLICY_CONNECTION,
                    SL_CONNECTION_POLICY(0,0,0,0,0),
                    &policyVal,
                    1 /*PolicyValLen*/);
    if(lRetVal < 0)
    {
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        LOOP_FOREVER();
    }
    
    if(WriteFileToDevice(&ulToken, &lFileHandle) < 0)
    {
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        LOOP_FOREVER();
    }

    if(ReadFileFromDevice(ulToken, lFileHandle) < 0)
    {
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
         LOOP_FOREVER();
    }

    //
    // turn ON the green LED indicating success
    //
    GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
    lRetVal = sl_Stop(SL_STOP_TIMEOUT);

       LOOP_FOREVER();

}
Ejemplo n.º 3
0
//*****************************************************************************
//
//! 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;
}
Ejemplo n.º 4
0
/*
 * Application's entry point
 */
int main(int argc, char** argv)
{
    _i32 retVal = -1;

    retVal = initializeAppVariables();
    ASSERT_ON_ERROR(retVal);

    /* Stop WDT and initialize the system-clock of the MCU */
    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((_u8 *)" Failed to configure the device in its default state \n\r");

        LOOP_FOREVER();
    }

    CLI_Write((_u8 *)" 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
     */
    retVal = sl_Start(0, 0, 0);
    if ((retVal < 0) ||
        (ROLE_STA != retVal) )
    {
        CLI_Write((_u8 *)" Failed to start the device \n\r");
        LOOP_FOREVER();
    }

    CLI_Write((_u8 *)" Device started as STATION \n\r");

    /* Connecting to WLAN AP */
    retVal = establishConnectionWithAP();
    if(retVal < 0)
    {
        CLI_Write((_u8 *)" Failed to establish connection w/ an AP \n\r");
        LOOP_FOREVER();
    }

    CLI_Write((_u8 *)" Connection established w/ AP and IP is acquired \n\r");
    CLI_Write((_u8 *)" Pinging...! \n\r");

    retVal = checkLanConnection();
    if(retVal < 0)
    {
        CLI_Write((_u8 *)" Device couldn't connect to LAN \n\r");
        LOOP_FOREVER();
    }

    CLI_Write((_u8 *)" Device successfully connected to the LAN\r\n");

    retVal = checkInternetConnection();
    if(retVal < 0)
    {
        CLI_Write((_u8 *)" Device couldn't connect to the internet \n\r");
        LOOP_FOREVER();
    }

    CLI_Write((_u8 *)" Device successfully connected to the internet \n\r");
    return 0;
}
Ejemplo n.º 5
0
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;
    
}
Ejemplo n.º 6
0
int main()
{

    unsigned char ucP2PParam[4];
    long lRetVal = -1;

    //
    // Initialize Board configurations
    //
    BoardInit();
    
    //
    // Pinmuxing for GPIO, UART
    //
    PinMuxConfig();
    
    //
    // configure LEDs
    //
    GPIO_IF_LedConfigure(LED1|LED2|LED3);
    
    // off all LEDs
    GPIO_IF_LedOff(MCU_ALL_LED_IND);
    
#ifndef NOTERM
    //
    // Configuring UART
    //
    InitTerm();
#endif

    
    //
    // Display the Application Banner
    //
    DisplayBanner(APP_NAME);

    UART_PRINT("Scan Wi-FI direct device in your handheld device\n\r");

    // Initializing the CC3200 device
    lRetVal = StartDeviceInP2P();
    if(lRetVal < 0)
    {
    	LOOP_FOREVER(__LINE__);
    }

    // Set any p2p option (SL_CONNECTION_POLICY(0,0,0,any_p2p,0)) to connect to
    // first available p2p device
    sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(1,0,0,0,0),NULL,0);

    // Set the negotiation role (SL_P2P_ROLE_NEGOTIATE).
    // CC3200 will negotiate with remote device GO/client mode.
    // Other valid options are:
    //             - SL_P2P_ROLE_GROUP_OWNER
    //             - SL_P2P_ROLE_CLIENT
    sl_WlanPolicySet(SL_POLICY_P2P, SL_P2P_POLICY(SL_P2P_ROLE_NEGOTIATE,
            SL_P2P_NEG_INITIATOR_ACTIVE),NULL,0);


    // Set P2P Device name
    sl_NetAppSet(SL_NET_APP_DEVICE_CONFIG_ID, NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN,
            strlen(P2P_DEVICE_NAME), (unsigned char *)P2P_DEVICE_NAME);

    // Set P2P device type
    sl_WlanSet(SL_WLAN_CFG_P2P_PARAM_ID, WLAN_P2P_OPT_DEV_TYPE,
            strlen(P2P_CONFIG_VALUE), (unsigned char*)P2P_CONFIG_VALUE);

    // setting P2P channel parameters
    ucP2PParam[0] = LISENING_CHANNEL;
    ucP2PParam[1] = REGULATORY_CLASS;
    ucP2PParam[2] = OPERATING_CHANNEL;
    ucP2PParam[3] = REGULATORY_CLASS;

    // Set P2P Device listen and open channel valid channels are 1/6/11
    sl_WlanSet(SL_WLAN_CFG_P2P_PARAM_ID, WLAN_P2P_OPT_CHANNEL_N_REGS,
                sizeof(ucP2PParam), ucP2PParam);

    // Restart as P2P device
    sl_Stop(SL_STOP_TIMEOUT);
    lRetVal = sl_Start(NULL,NULL,NULL);

    if(lRetVal < 0 || lRetVal != ROLE_P2P)
    {
        UART_PRINT("Failed to start the device \n\r");
        LOOP_FOREVER(__LINE__);
    }
    else
    {
        UART_PRINT("Connect to %s \n\r",P2P_DEVICE_NAME);
    }
    
    /* Connect to configure P2P device */
    lRetVal = WlanConnect();

    if(lRetVal == 0)
    {
        GPIO_IF_LedOn(MCU_IP_ALLOC_IND);
    }
    else
    {
        UART_PRINT("Reset the device and try again\n\r");
        LOOP_FOREVER(__LINE__);
    }

    DisplayIP();
    UART_PRINT("Send TCP packets from your handheld device to CC3200's IP\n\r");
    
    /*After calling this function, you can start sending data to CC3200 IP
    * address on PORT_NUM */
    if(!(IS_CONNECT_FAILED(g_ulStatus)))
        BsdTcpServer(PORT_NUM);

    UART_PRINT("Received TCP packets successfully \n\r");
    
    // revert Device into STA mode and power off Network Processor
    sl_WlanSetMode(ROLE_STA);
    sl_Stop(SL_STOP_TIMEOUT);
    UART_PRINT("Test passed, exiting application... \n\r");
    while(1)
    {
        _SlNonOsMainLoopTask();
    }
}
Ejemplo n.º 7
0
//*****************************************************************************
//
//! \brief Connecting to a WLAN Accesspoint
//! This function connects to the required AP (SSID_NAME).
//! This code example assumes the AP doesn't use WIFI security.
//! The function will return only once we are connected
//! and have acquired IP address
//!
//! \param[in] None
//!
//! \return 0 means success, -1 means failure
//!
//! \note
//!
//! \warning    If the WLAN connection fails or we don't aquire an IP address,
//!             We will be stuck in this function forever.
//
//*****************************************************************************
int WlanConnect()
{
    int iRetCode = 0;
    int iRetVal = 0;
    int iConnect = 0;
    unsigned char ucQueueMsg = 0;
    SlSecParams_t secParams;

    secParams.Key = (signed char *)SECURITY_KEY;
    secParams.KeyLen = strlen((const char *)secParams.Key);
    secParams.Type = SECURITY_TYPE;

    //
    // Set up the watchdog interrupt handler.
    //
    WDT_IF_Init(WatchdogIntHandler, MILLISECONDS_TO_TICKS(WD_PERIOD_MS));
    /* Enabling the Sleep clock for the Watch Dog Timer*/
    MAP_PRCMPeripheralClkEnable(PRCM_WDT, PRCM_SLP_MODE_CLK);
    
    g_ucFeedWatchdog = 1;
    g_ucWdogCount = 0;
    while(!(ucQueueMsg & (EVENT_IP_ACQUIRED|CONNECTION_FAILED)))
    {
        UART_PRINT("Trying to connect to AP: ");
        UART_PRINT(SSID_NAME);
        UART_PRINT("\n\r");
        sl_WlanConnect((signed char *)SSID_NAME,
                        strlen((const char *)SSID_NAME), 0, &secParams, 0);
        iConnect = 0;
        do{
            osi_MsgQRead(&g_tConnection, &ucQueueMsg, OSI_WAIT_FOREVER);

            switch(ucQueueMsg)
            {
                case EVENT_CONNECTION:
                    iConnect = 1;
                    break;

                case EVENT_IP_ACQUIRED:
                    iRetVal = 0;
                    break;

                case WDOG_EXPIRED:

                    //
                    // disconnect from the Access Point
                    //
                    if(iConnect)
                    {
                        WlanDisconnect();
                    }

                    //
                    // stop the simplelink with reqd. timeout value (30 ms)
                    //
                    sl_Stop(SL_STOP_TIMEOUT);

                    UART_PRINT("sl stop\n\r");

                    MAP_UtilsDelay(8000);

                    //
                    // starting the simplelink
                    //
                    sl_Start(NULL, NULL, NULL);

                    UART_PRINT("sl start\n\r");
                    break;

                case EVENT_DISCONNECTION:
                    iConnect = 0;
                    break;

                case CONNECTION_FAILED:
                    iRetVal = -1;
                    break;

                default:
                    UART_PRINT("unexpected event\n\r");
                    break;
            }
        }while(ucQueueMsg == (unsigned char)EVENT_CONNECTION);
    }
    iRetCode = MAP_WatchdogRunning(WDT_BASE);
    if(iRetCode)
    {
       WDT_IF_DeInit();
       MAP_PRCMPeripheralClkDisable(PRCM_WDT, PRCM_RUN_MODE_CLK);
    }
    ASSERT_ON_ERROR(iRetVal);
    return(iRetVal);
}
Ejemplo n.º 8
0
void Task_WifiScan(void* params)
{
    (void)params; //avoid unused error
    long retval;
    unsigned char policy;
    unsigned int policy_len;

    LOG(LOG_VERBOSE, "Starting WiFi network scan...");

    SetLEDBlink(LED_1, LED_BLINK_PATTERN_WIFI_SCANNING);

    if(WifiDefaultSettings() == RET_FAILURE) {
        goto error;
    }

    retval = sl_Start(0,0,0);
    if(retval<0)  {
        goto error;
    }

    //first, delete current connection policy
    policy = SL_CONNECTION_POLICY(0,0,0,0,0);
    retval = sl_WlanPolicySet(SL_POLICY_CONNECTION, policy, NULL, 0);
    if(retval<0)  {
        goto error;
    }

    //make scan policy
    policy = SL_SCAN_POLICY(1);
    policy_len = WIFI_SCAN_TIME_S;
    retval = sl_WlanPolicySet(SL_POLICY_SCAN, policy, (unsigned char*)&policy_len, sizeof(policy_len));
    if(retval<0)  {
        goto error;
    }

    //wait for the scan to complete
    const TickType_t delay = (1100*WIFI_SCAN_TIME_S) / portTICK_PERIOD_MS;
    vTaskDelay(delay);

    //get the results back
    unsigned char index = 0;
    retval = sl_WlanGetNetworkList(index, (unsigned char)WIFI_NUM_NETWORKS, &(wifi_state.networks[index]));

    //retval holds the number of networks now, and they are saved in the state.

    //disable the scan
    policy = SL_SCAN_POLICY(0);
    retval = sl_WlanPolicySet(SL_POLICY_SCAN, policy, NULL, 0);
    if(retval<0)  {
        goto error;
    }

    //disable SimpleLink altogether
    retval = sl_Stop(SL_STOP_TIMEOUT);
    if(retval<0)  {
        goto error;
    }

    LOG(LOG_VERBOSE, "WiFi network scan complete.");

    ClearLED(LED_1);

#ifdef DO_STACK_CHECK
    wifi_state.stack_watermark = uxTaskGetStackHighWaterMark(NULL);
#endif

    //exit (delete this task)
    WifiTaskEndCallback(&Task_WifiScan);
    vTaskDelete(NULL);

    return;

error:
    SetLEDBlink(LED_1, LED_BLINK_PATTERN_WIFI_FAILED);
    TASK_RETURN_ERROR(ERROR_UNKNOWN, "WIFI scan fail");
    return;
}
Ejemplo n.º 9
0
//****************************************************************************
//
//!    \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;
}
Ejemplo n.º 10
0
//*****************************************************************************
//
//! Configure the device as xmpp client
//!
//! \param  pvParameters pointer to parameters
//!
//! \return None
//
//*****************************************************************************
static void XmppClient(void *pvParameters)
{
    SlNetAppXmppOpt_t XmppOption;
    SlNetAppXmppUserName_t UserName;
    SlNetAppXmppPassword_t Password;
    SlNetAppXmppDomain_t Domain;
    SlNetAppXmppResource_t Resource;
    unsigned char pRemoteJid[REMOTE_USERID_LEN];
    unsigned char pRecvMessage[RECV_MSG_LEN];
    signed short  Status = 0;

    long lRetVal = -1;
    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 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");
        }

        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)
    {
      UART_PRINT("Failed to start the device \n\r");
      LOOP_FOREVER();
    }

    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();
    if(lRetVal < 0)
    {
        UART_PRINT("Unable to connect wlan.\n\r");
        LOOP_FOREVER();
    }


    // Configuring different parameters which are required for XMPP connection
    XmppOption.Port = XMPP_DST_PORT;
    XmppOption.Family = SL_AF_INET;
    XmppOption.SecurityMethod = SO_SECMETHOD_SSLV3;
    XmppOption.SecurityCypher = SECURE_MASK_SSL_RSA_WITH_RC4_128_SHA;
    XmppOption.Ip = XMPP_IP_ADDR;

    //DNS query to get IP address of XMPP Server
//    lRetVal = sl_NetAppDnsGetHostByName(XMPP_DOMAIN_NAME, \
//                                    strlen((const char *)XMPP_DOMAIN_NAME), \
//                                    (unsigned long*)&XmppOption.Ip, SL_AF_INET);
//
//    if(lRetVal < 0)
//    {
//        UART_PRINT("Device couldn't retrive the host name \n\r");
//        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
//        LOOP_FOREVER();
//    }

    lRetVal = sl_NetAppXmppSet(SL_NET_APP_XMPP_ID, NETAPP_XMPP_ADVANCED_OPT, \
                    sizeof(SlNetAppXmppOpt_t), (unsigned char *)&XmppOption);

    if(lRetVal < 0)
    {
        UART_PRINT("Unable to connect wlan.\n\r");
        LOOP_FOREVER();
    }
    // Configure Client's user name
    memcpy(UserName.UserName, CLIENT_USER_NAME, strlen(CLIENT_USER_NAME));
    UserName.Length = strlen(CLIENT_USER_NAME);

    lRetVal = sl_NetAppXmppSet(SL_NET_APP_XMPP_ID, NETAPP_XMPP_USER_NAME, \
                                UserName.Length, \
                                (unsigned char *)&UserName);
    if(lRetVal < 0)
    {
        UART_PRINT("Unable to set XMPP user id.\n\r");
        LOOP_FOREVER();
    }

    // Configure Client's password
    memcpy(Password.Password, CLIENT_PASSWORD, strlen(CLIENT_PASSWORD));
    Password.Length = strlen(CLIENT_PASSWORD);

    lRetVal = sl_NetAppXmppSet(SL_NET_APP_XMPP_ID, NETAPP_XMPP_PASSWORD, \
                                Password.Length, \
                                (unsigned char *)&Password);
    if(lRetVal < 0)
    {
        UART_PRINT("Unable to set XMPP user password.\n\r");
        LOOP_FOREVER();
    }

    memcpy(Domain.DomainName, XMPP_DOMAIN_NAME, strlen(XMPP_DOMAIN_NAME));
    Domain.Length = strlen(XMPP_DOMAIN_NAME);

    lRetVal = sl_NetAppXmppSet(SL_NET_APP_XMPP_ID, NETAPP_XMPP_DOMAIN, \
                                Domain.Length, \
                                (unsigned char *)&Domain);
    if(lRetVal < 0)
    {
        UART_PRINT("Unable to XMPP domain.\n\r");
        LOOP_FOREVER();
    }

    memcpy(Resource.Resource, XMPP_RESOURCE,strlen(XMPP_RESOURCE));
    Resource.Length = strlen(XMPP_RESOURCE);

    lRetVal = sl_NetAppXmppSet(SL_NET_APP_XMPP_ID, NETAPP_XMPP_RESOURCE, \
                                Resource.Length, \
                                (unsigned char *)&Resource);
    if(lRetVal < 0)
    {
        UART_PRINT("Unable to set XMPP resources.\n\r");
        LOOP_FOREVER();
    }


    while(sl_NetAppXmppConnect() < 0)
    {
        MAP_UtilsDelay(10000);
    }

    Status = sl_NetAppXmppRecv(pRemoteJid, REMOTE_USERID_LEN, pRecvMessage, \
                                RECV_MSG_LEN );
    while(1)
    {
        while ( Status < 0)
        {
            MAP_UtilsDelay(10000);
            Status = sl_NetAppXmppRecv(pRemoteJid, REMOTE_USERID_LEN, \
                                        pRecvMessage, RECV_MSG_LEN );
        }

        //
        // Toggle Orange LED to indicate if it gets some chat message
        //
        GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO);
        MAP_UtilsDelay(800000);
        GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
        Status = sl_NetAppXmppSend(pRemoteJid, strlen((char*)pRemoteJid), \
                                    pRecvMessage, strlen((char*)pRecvMessage) );  
    }
}
Ejemplo n.º 11
0
static int WifiDefaultSettings(void)
{
    long retval = -1;
    unsigned char val = 1;

    unsigned char config, config_len;

    //filters
    _WlanRxFilterOperationCommandBuff_t filter_mask = {
        .Padding = {0}
    };

    //initialize the SimpleLink API
    retval = sl_Start(0,0,0);
    if(retval < 0) {
        RETURN_ERROR(ERROR_UNKNOWN, "SL start fail");
    }

    //set device in station mode
    if(retval != ROLE_STA) {
        if(retval == ROLE_AP) { //we need to wait for an event before doing anything
            while(!IS_IP_ACQUIRED(wifi_state.status)) {
#ifndef SL_PLATFORM_MULTI_THREADED
                _SlNonOsMainLoopTask();
#endif
            }
        }
        //change mode to Station
        retval = sl_WlanSetMode(ROLE_STA);
        if(retval < 0) {
            RETURN_ERROR(ERROR_UNKNOWN, "WLAN mode fail");
        }
        //restart
        retval = sl_Stop(0xFF);
        if(retval < 0) {
            RETURN_ERROR(ERROR_UNKNOWN, "SL stop fail");
        }
        retval = sl_Start(0,0,0);
        if(retval < 0) {
            RETURN_ERROR(ERROR_UNKNOWN, "SL start fail");
        }

        if(retval != ROLE_STA) {
            RETURN_ERROR(ERROR_UNKNOWN, "WLAN mode fail");
        }
    }

    //get SimpleLink version
    config = SL_DEVICE_GENERAL_VERSION;
    config_len = sizeof(SlVersionFull);
    retval = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &config, &config_len, (unsigned char*)&wifi_state.version);
    if(retval<0) {
        RETURN_ERROR(retval, "WIFI conf fail");
    }

    //default connection policy
    retval = sl_WlanPolicySet(SL_POLICY_CONNECTION,
                              SL_CONNECTION_POLICY(1, 0, 0, 0, 0),
                              NULL,
                              0);
    if(retval<0) {
        RETURN_ERROR(retval, "WIFI policy fail");
    }

    //disconnect
    retval = sl_WlanDisconnect();
    if(retval == 0) { //not yet disconnected
        while(IS_CONNECTED(wifi_state.status)) {
#ifndef SL_PLATFORM_MULTI_THREADED
            _SlNonOsMainLoopTask();
#endif
        }
    }

    //Enable DHCP client
    retval = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&val);
    if(retval<0) {
        RETURN_ERROR(retval, "WIFI conf fail");
    }

    //Disable scan policy
    config = SL_SCAN_POLICY(0);
    retval = sl_WlanPolicySet(SL_POLICY_SCAN, config, NULL, 0);
    if(retval<0) {
        RETURN_ERROR(retval, "WIFI policy fail");
    }

    //Set Tx power level for station mode
    //Number between 0-15, as dB offset from max power - 0 will set max power
    val = 0;
    retval = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,
                        WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&val);
    if(retval<0) {
        RETURN_ERROR(retval, "WIFI set fail");
    }

    // Set PM policy to normal
    retval = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
    if(retval<0) {
        RETURN_ERROR(retval, "WIFI policy fail");
    }

    // Unregister mDNS services
    retval = sl_NetAppMDNSUnRegisterService(0, 0);
    if(retval<0) {
        RETURN_ERROR(retval, "mDNS fail");
    }

    //Set mDNS device hostname
    char hostname[64];
    char macstring[20];
    unsigned char maclen = SL_MAC_ADDR_LEN;
    retval = sl_NetCfgGet(SL_MAC_ADDRESS_GET,
                          NULL,
                          &maclen,
                          wifi_state.mac);
    if(retval < 0) {
        RETURN_ERROR(retval, "WIFI conf fail");
    }
    snprintf(macstring, 20,  "%02X%02X%02X%02X%02X%02X", wifi_state.mac[0],
             wifi_state.mac[1], wifi_state.mac[2],
             wifi_state.mac[3], wifi_state.mac[4],
             wifi_state.mac[5]);
    snprintf(hostname, 64,  "LeashDebugger%s", macstring);
    retval = sl_NetAppSet (SL_NET_APP_DEVICE_CONFIG_ID,
                           NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN,
                           strlen((const char *)hostname),
                           (unsigned char *) hostname);
    // Remove  all 64 filters (8*8)
    memset(filter_mask.FilterIdMask, 0xFF, 8);
    retval = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (uint8_t*)&filter_mask,
                                sizeof(_WlanRxFilterOperationCommandBuff_t));
    if(retval<0) {
        RETURN_ERROR(retval, "WIFI filter fail");
    }

    retval = sl_Stop(SL_STOP_TIMEOUT);
    if(retval < 0) {
        RETURN_ERROR(ERROR_UNKNOWN, "SL stop fail");
    }

    wifi_state.status = 0;

    return RET_SUCCESS;
}
Ejemplo n.º 12
0
int main(void)
{

	/* Init board */
	BoardInit();

	/* Init GPIO */
	InitGPIO();

	/* Init UART */
	MAP_PRCMPeripheralClkEnable(PRCM_UARTA0, PRCM_RUN_MODE_CLK);
    InitTerm();

    /* Init I2C */
    I2C_IF_Open(I2C_MASTER_MODE_FST);

    /* Init the internet! */
    // http://azug.minpet.unibas.ch/~lukas/bricol/ti_simplelink/resources/swru368.pdf SECTION 10
	dhcpParams.lease_time = 1000;
	dhcpParams.ipv4_addr_start = 0xc0a80102;
	dhcpParams.ipv4_addr_last = 0xc0a801fe;


	sl_Start(NULL,NULL,NULL);
	MAP_UtilsDelay(8000000);

	// config IP etc
	ipV4.ipV4 = 0xc0a80101;
	ipV4.ipV4Mask = 0xFFFFFF00;
	ipV4.ipV4Gateway = 0xc0a80101;
	ipV4.ipV4DnsServer = 0xc0a80101;
	sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE, 1 ,sizeof(SlNetCfgIpV4Args_t), (unsigned char*) &ipV4);

	sl_WlanSetMode(ROLE_AP);

	// config SSID
	sl_WlanSet(SL_WLAN_CFG_AP_ID,WLAN_AP_OPT_SSID, strlen(myssid), (unsigned char*) myssid);

	sl_Stop(100);
	sl_Start(NULL,NULL,NULL);

	// start DHCP server
	sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID);
	sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, outLen,(unsigned char*) &dhcpParams);
	sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID);


	//Stop Internal HTTP Serve
	long lRetVal = -1;
	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);

	 /* Finished init the internet! */

	setRLED();

    /* Wait for operator */
    while(!readDIP1());

    clearRLED();

    /* Init IMU (alongside timers and interrupt */
    imu_setup();

    /* Init odometers */
    odometer_setup();

    set_controller_parameters(kp, ki, kd);
    set__odo_controller_parameters(kp_odo, ki_odo, kd_odo);

    /* Init motors (alongside motor GPIO, timers and interrupt */
	motorSetup();



    controller_setup();
    odometer_controller_setup();      // MUST be the last init called!


	while(1)
	{
		_SlNonOsMainLoopTask();
	}
}
Ejemplo n.º 13
0
Archivo: main.c Proyecto: bmxrt/CC3100
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;
}
Ejemplo n.º 14
0
int connectToAccessPoint(){
	long lRetVal = -1;
    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");
    return 0;
}
Ejemplo n.º 15
0
int main2(void)
{
    UINT8  IsDHCP = 0;
    int32_t i32CommandStatus;
    _NetCfgIpV4Args_t ipV4;

    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 measure analog signals from Ain7=PD0\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);
    /* 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);

    //Print the IP
    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));

    //
    // 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)
        {
            //
            // Approximately 1 millisecond delay.
            //
            ROM_SysCtlDelay(ROM_SysCtlClockGet() / 3000);
        }

        //
        // A '\r' was detected so get the line of text from the receive buffer.
        //
        UARTgets(g_cInput,sizeof(g_cInput));

        //
        // Pass the line from the user to the command processor.
        // It will be parsed and valid commands executed.
        //
        i32CommandStatus = CmdLineProcess(g_cInput);

        //
        // Handle the case of bad command.
        //
        if(i32CommandStatus == CMDLINE_BAD_CMD)
        {
            UARTprintf("    Bad command. Try again.\n");
        }
        //
        // Handle the case of too many arguments.
        //
        else if(i32CommandStatus == CMDLINE_TOO_MANY_ARGS)
        {
            UARTprintf("    Too many arguments for command. Try again.\n");
        }
        //
        // Handle the case of too few arguments.
        //
        else if(i32CommandStatus == CMDLINE_TOO_FEW_ARGS)
        {
            UARTprintf("    Too few arguments for command. Try again.\n");
        }
        //
        // Handle the case of too few arguments.
        //
        else if(i32CommandStatus == CMDLINE_INVALID_ARG)
        {
            UARTprintf("    Invalid command argument(s). Try again.\n");
        }
    }
    
}
Ejemplo n.º 16
0
int main(void)
{
    long lRetVal = -1;
    //
    // Initialize Board configurations
    //
    BoardInit();

    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 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");
        }

        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)
    {
        UART_PRINT("Failed to start the device \n\r");
        LOOP_FOREVER();
    }

    UART_PRINT("Device started as STATION \n\r");

    /* Connect to our AP using SmartConfig method */
    lRetVal = SetConnectionPolicy();
    if(lRetVal < 0)
    {
        ERR_PRINT(lRetVal);
        LOOP_FOREVER();
    }

    // revert all settings
    lRetVal = sl_WlanProfileDel(0xFF);
    if(lRetVal < 0)
    {
        ERR_PRINT(lRetVal);
        LOOP_FOREVER();
    }

    lRetVal = sl_Stop(SL_STOP_TIMEOUT);

    LOOP_FOREVER();
}
Ejemplo n.º 17
0
//*****************************************************************************
//
//! Check the device mode and switch to P2P mode
//! restart the NWP to activate P2P mode
//!
//! \param  None
//!
//! \return status code - Success:0, Failure:-ve
//
//*****************************************************************************
long StartDeviceInP2P()
{
    long retVal = -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
    //
    retVal = ConfigureSimpleLinkToDefaultState();
    if(retVal < 0)
    {
        if (DEVICE_NOT_IN_STATION_MODE == retVal)
            UART_PRINT("Failed to configure the device in its default state \n\r");

        LOOP_FOREVER(__LINE__);
    }

    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
    //

    retVal = sl_Start(NULL,NULL,NULL);

    if (retVal < 0)
    {
        UART_PRINT("Failed to start the device \n\r");
        return -1;
    }
    else if(retVal != ROLE_P2P)
    {
        sl_WlanSetMode(ROLE_P2P);
        sl_Stop(10);

        // reset the Status bits
        CLR_STATUS_BIT_ALL(g_ulStatus);

        retVal = sl_Start(NULL,NULL,NULL);
        if(retVal < 0 || retVal != ROLE_P2P)
        {
            UART_PRINT("Failed to start the device \n\r");
            return -1;
        }
        else
        {
            UART_PRINT("Started SimpleLink Device: P2P Mode\n\r");
            return SUCCESS;
        }
    }
    else
    {
        return SUCCESS;
    }
}
void WlanStationMode( void *pvParameters )
{
    int iTestResult = 0;
    unsigned long ulIP = 0;
    unsigned long ulSubMask = 0;
    unsigned long ulDefaultGateway = 0;
    unsigned long ulDNSServer = 0;
    unsigned char ucDHCP = 0;
    char cMode;
    char* buff="hhhhhh\n\r";
    unsigned char currentMacAddress[SL_MAC_ADDR_LEN];
    
    //UART_PRINT(" in WlanStationMode  \n\r"); 
    
/*  for(int a = 0; a<5; ++a){
    Z_DelayS(30);
    *buff=a+'0';
    UART_PRINT(buff);   
    }
 */   
    
    

    
    
    
    
    
    
 
    
    
  char deviceRole = ROLE_STA;  
    
  deviceRole = sl_Start(NULL,NULL,InitCallback);
 /* deviceRole = sl_Start(NULL,NULL,NULL);
    
    if(deviceRole < 0 ){
      UART_PRINT("sl_Start error  \n\r");
      return;
    }
    else if(deviceRole == ROLE_STA)
        UART_PRINT("in station mode  \n\r"); 
          else{
            UART_PRINT("in wrong mode  \n\r"); 
            return;
          }
 */     
    
 /*  if((cMode = sl_Start(NULL,NULL,NULL)) != ROLE_STA){
      UART_PRINT("hellow  \n\r"); 
      
      *buff=cMode+'0';
      UART_PRINT(buff);
      *buff=ROLE_STA+'0';
      UART_PRINT(buff);
      
 //     SL_WLAN_SET_MODE_STA();
    }
     
    UART_PRINT("hellow i am in station mode now \n\r"); 
    
  */   
    
 while(!g_uiSimplelinkstarted)
 {
        //looping till simplelink starts
  Z_DelayS(1);
  // ; 
   UART_PRINT("i am starting now \n\r"); 
 } 
             
   UART_PRINT("i am started   \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 */
    WlanConnect();
  

  
    
   UART_PRINT("i'm connected! \n\r"); 
    
    //get mac addr from s-flash
    
    SL_MAC_ADDR_GET(currentMacAddress);   
    Z_MACDispaly(currentMacAddress);
    
    
    SL_STA_IPV4_ADDR_GET(&ulIP,&ulSubMask,&ulDefaultGateway,&ulDNSServer,
                       &ucDHCP);
    
    
    
    Z_IPDispaly(&ulIP);
    MyIP=ulIP;
    Z_IPDispaly(&ulSubMask);
    Z_IPDispaly(&ulDefaultGateway);

    
    
    
    /*
    
    UNUSED(ulIP);
    UNUSED(ulSubMask);
    UNUSED(ulDNSServer);
    UNUSED(ucDHCP);
    */
    
   // iTestResult = PingTest(ulDefaultGateway);
  //  UNUSED(iTestResult);
    
 //BsdTcpServer(PORT_NUM); 
    
 //mqtt_pub();
    UART_PRINT("WlanStationMode\r\n"); 
    vTaskDelete(NULL);
    UART_PRINT("WlanStationMode\r\n"); 
 return;
 
 
    
    
    
    
    
}
Ejemplo n.º 19
0
int main(void)
{
    long lRetVal = -1;
    //
    // Initialize Board configurations
    //
    BoardInit();
    //
    // Configure the pinmux settings for the peripherals exercised
    //
    PinMuxConfig();

    #ifndef NOTERM
        InitTerm();
    #endif

    // configure RED LED
    GPIO_IF_LedConfigure(LED1);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);

    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 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");

       LOOP_FOREVER();
   }

   UART_PRINT("Device is configured in default state \n\r");


   CLR_STATUS_BIT_ALL(g_ulStatus);

   //Start simplelink
   lRetVal = sl_Start(0,0,0);
   if (lRetVal < 0 || ROLE_STA != lRetVal)
   {
       UART_PRINT("Failed to start the device \n\r");
       LOOP_FOREVER();
   }

   UART_PRINT("Device started as STATION \n\r");

   /* Connect to our AP using SmartConfig method */
   lRetVal = SmartConfigConnect();
   if(lRetVal < 0)
   {
     ERR_PRINT(lRetVal);
   }    

   LOOP_FOREVER();
}
Ejemplo n.º 20
0
void APP_Tasks(void) {
    /*
     * Processing CC3100 Tasks
     * It looks like SYS task and might be processed in SYS_Tasks
     * But for this demo it is here to make this call
     * visible
     */
    _SlNonOsMainLoopTask();

    /* Check the application's current state. */
    switch (appData.state) {
    /* Application's initial state. */
    case APP_STATE_INIT: {
        SYS_PRINT("\n\r*** PIC32 MQTT CLIENT ***\n\r");

        SYS_PRINT("\n\rInitializing CC3100\n\r");
        int res = sl_Start(NULL, NULL, NULL);
        if (res != 0) {
            SYS_PRINT("FAILED\n\r");
            appData.state = APP_STATE_DONE;
            break;
        }

        SlSecParams_t sec_params;
        memset(&sec_params, 0, sizeof(sec_params));
        sec_params.Key = NET_PWD;
        sec_params.KeyLen = sizeof(NET_PWD) - 1;
        sec_params.Type = NET_SECURITY;

        SYS_PRINT("Connecting to WiFi\n\r");

        sl_WlanConnect(NET_SSID, sizeof(NET_SSID) - 1, 0, &sec_params, NULL);

        SYS_PRINT("Initialization done\n\r");

        appData.state = APP_STATE_SERVICE_TASKS;

        break;
    }

    case APP_STATE_CONNECT_BROKER: {
        if (mg_connect(&mgr, MQTT_BROKER_ADDRESS, ev_handler) == NULL) {
            SYS_PRINT("Failed to create connection\n\r");
            appData.state = APP_STATE_DONE;
        } else {
            appData.state = APP_STATE_SERVICE_TASKS;
        }
        break;
    }
    case APP_STATE_SERVICE_TASKS: {
        static uint32_t prev_poll_time = 0;
        uint32_t now = DRV_RTCC_TimeGet();
        if (now - prev_poll_time > 100) {
            /*
             * We cannot call mg_mgr_poll every cycle
             * it leads to SPI overload (internaly mg_mgr_poll calls
             * CC3100 via SPI
             */
            mg_mgr_poll(&mgr, 1);
            prev_poll_time = now;
        }
        break;
    }

    case APP_STATE_DONE: {
        /* Do nothing here */
        break;
    }
    default: {
        /* TODO: Handle error in application's state machine. */
        break;
    }
    }
}
Ejemplo n.º 21
0
//*****************************************************************************
//
//! \brief Task Created by main fucntion.This task starts simpleink, set NWP
//!        power policy, connects to an AP. Give Signal to the other task about
//!        the connection.wait for the message form the interrupt handlers and
//!        the other task. Accordingly print the wake up cause from the low
//!        power modes.
//!
//! \param pvParameters is a general void pointer (not used here).
//!
//! \return none
//
//*****************************************************************************
void TimerGPIOTask(void *pvParameters)
{
    cc_hndl tTimerHndl = NULL; 
    cc_hndl tGPIOHndl = NULL;
    unsigned char ucQueueMsg = 0;
    unsigned char ucSyncMsg = 0;
    int iRetVal = 0;
    //
    // Displays the Application Banner
    //
    DisplayBanner();
    
    //
    // 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();
    }
    
    //
    // starting the simplelink
    //
    iRetVal = sl_Start(NULL, NULL, NULL);
    if (iRetVal < 0)
    {
        UART_PRINT("Failed to start the device \n\r");
        LOOP_FOREVER();
    }

    //
    // Swtich to STA mode if device is not
    //
    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();
    }

    //
    // connecting to the Access Point
    //
    if(-1 == WlanConnect())
    {
        sl_Stop(SL_STOP_TIMEOUT);
        UART_PRINT("Connection to AP failed\n\r");
    }
    else
    {
        UART_PRINT("Connected to AP\n\r");
        //
        //signal the other task about the sl start and connection to the AP
        //
        iRetVal = osi_MsgQWrite(&g_tConnectionFlag, &ucSyncMsg,
                                OSI_WAIT_FOREVER);
        if (iRetVal < 0)
        {
            UART_PRINT("unable to create the msg queue\n\r");
            LOOP_FOREVER();
        }
    }
    
    //
    // Queue management related configurations
    //
    iRetVal = osi_MsgQCreate(&g_tWkupSignalQueue, NULL,
                             sizeof( unsigned char ), 10);
    if (iRetVal < 0)
    {
        UART_PRINT("unable to create the msg queue\n\r");
        LOOP_FOREVER();
    }

    //
    // 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 Apps power policy
    //
    lp3p0_setup_power_policy(POWER_POLICY_STANDBY);
    
    while(FOREVER)
    {
        //
        // waits for the message from the various interrupt handlers(GPIO,
        // Timer) and the UDPServerTask.
        //
        osi_MsgQRead(&g_tWkupSignalQueue, &ucQueueMsg, OSI_WAIT_FOREVER);
        switch(ucQueueMsg){
        case 1:
            UART_PRINT("timer\n\r");
            break;
        case 2:
            UART_PRINT("GPIO\n\r");
            break;
        case 3:
            UART_PRINT("host irq\n\r");
            break;
        default:
            UART_PRINT("invalid msg\n\r");
            break;
        }
    }
}
Ejemplo n.º 22
0
//****************************************************************************
//
//! \brief Start simplelink, connect to the ap and run the ping test
//!
//! This function starts the simplelink, connect to the ap and start the ping
//! test on the default gateway for the ap
//!
//! \param[in]  pvParameters - Pointer to the list of parameters that 
//!             can bepassed to the task while creating it
//!
//! \return  None
//
//****************************************************************************
void WlanStationMode( void *pvParameters )
{

    long lRetVal = -1;
    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 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");
        }

        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)
    {
        UART_PRINT("Failed to start the device \n\r");
        LOOP_FOREVER();
    }

    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");
        LOOP_FOREVER();
    }

    UART_PRINT("Connection established w/ AP and IP is aquired \n\r");
    UART_PRINT("Pinging...! \n\r");

    //
    // Checking the Lan connection by pinging to AP gateway
    //
    lRetVal = CheckLanConnection();
    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't ping the gateway \n\r");
        LOOP_FOREVER();
    }
    
    // Turn on GREEN LED when device gets PING response from AP
    GPIO_IF_LedOn(MCU_EXECUTE_SUCCESS_IND);

    //
    // Checking the internet connection by pinging to external host
    //
    lRetVal = CheckInternetConnection();
    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't ping the external host \n\r");
        LOOP_FOREVER();
    }

    // Turn on ORAGE LED when device gets PING response from AP
    GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO);

    UART_PRINT("Device pinged both the gateway and the external host \n\r");

    UART_PRINT("WLAN STATION example executed successfully \n\r");

    //
    // power off the network processor
    //
    lRetVal = sl_Stop(SL_STOP_TIMEOUT);

    LOOP_FOREVER();
    
}
Ejemplo n.º 23
0
/*!
    \brief This function configure the SimpleLink device in its default state. It:
           - Sets 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
           - Unregisters mDNS services
           - Remove all filters

    \param[in]      none

    \return         On success, zero is returned. On error, negative is returned
*/
static _i32 configureSimpleLinkToDefaultState()
{
    SlVersionFull   ver = {0};
    _WlanRxFilterOperationCommandBuff_t  RxFilterIdMask = {0};

    _u8           val = 1;
    _u8           configOpt = 0;
    _u8           configLen = 0;
    _u8           power = 0;

    _i32          retVal = -1;
    _i32          mode = -1;

    mode = sl_Start(0, 0, 0);
    ASSERT_ON_ERROR(mode);

    /* If the device is not in station-mode, try configuring it in station-mode */
    if (ROLE_STA != mode)
    {
        if (ROLE_AP == mode)
        {
            /* If the device is in AP mode, we need to wait for this event before doing anything */
            while(!IS_IP_ACQUIRED(g_Status)) { _SlNonOsMainLoopTask(); }
        }

        /* Switch to STA role and restart */
        retVal = sl_WlanSetMode(ROLE_STA);
        ASSERT_ON_ERROR(retVal);

        retVal = sl_Stop(SL_STOP_TIMEOUT);
        ASSERT_ON_ERROR(retVal);

        retVal = sl_Start(0, 0, 0);
        ASSERT_ON_ERROR(retVal);

        /* Check if the device is in station again */
        if (ROLE_STA != retVal)
        {
            /* We don't want to proceed if the device is not coming up in station-mode */
            ASSERT_ON_ERROR(DEVICE_NOT_IN_STATION_MODE);
        }
    }

    /* Get the device's version-information */
    configOpt = SL_DEVICE_GENERAL_VERSION;
    configLen = sizeof(ver);
    retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &configOpt, &configLen, (_u8 *)(&ver));
    ASSERT_ON_ERROR(retVal);

    /* Set connection policy to Auto + SmartConfig (Device's default connection policy) */
    retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
    ASSERT_ON_ERROR(retVal);

    /* Remove all profiles */
    retVal = sl_WlanProfileDel(0xFF);
    ASSERT_ON_ERROR(retVal);

    /*
     * 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
     */
    retVal = sl_WlanDisconnect();
    if(0 == retVal)
    {
        /* Wait */
        while(IS_CONNECTED(g_Status)) { _SlNonOsMainLoopTask(); }
    }

    /* Enable DHCP client*/
    retVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&val);
    ASSERT_ON_ERROR(retVal);

    /* Disable scan */
    configOpt = SL_SCAN_POLICY(0);
    retVal = sl_WlanPolicySet(SL_POLICY_SCAN , configOpt, NULL, 0);
    ASSERT_ON_ERROR(retVal);

    /* Set Tx power level for station mode
       Number between 0-15, as dB offset from max power - 0 will set maximum power */
    power = 0;
    retVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (_u8 *)&power);
    ASSERT_ON_ERROR(retVal);

    /* Set PM policy to normal */
    retVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
    ASSERT_ON_ERROR(retVal);

    /* Unregister mDNS services */
    retVal = sl_NetAppMDNSUnRegisterService(0, 0);
    ASSERT_ON_ERROR(retVal);

    /* Remove  all 64 filters (8*8) */
    pal_Memset(RxFilterIdMask.FilterIdMask, 0xFF, 8);
    retVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask,
                       sizeof(_WlanRxFilterOperationCommandBuff_t));
    ASSERT_ON_ERROR(retVal);

    retVal = sl_Stop(SL_STOP_TIMEOUT);
    ASSERT_ON_ERROR(retVal);

    retVal = initializeAppVariables();
    ASSERT_ON_ERROR(retVal);

    return retVal; /* Success */
}
Ejemplo n.º 24
0
//****************************************************************************
//
//!	\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");
    }


    }
}
Ejemplo n.º 25
0
//****************************************************************************
//                            MAIN FUNCTION
//****************************************************************************
void main()
{
    long retVal = -1;
    unsigned long ulResetCause;
    unsigned long ulDestinationIP;

    //
    // Board Initialization
    //
    BoardInit();

    //
    // Configure the pinmux settings for the peripherals exercised
    //
    PinMuxConfig();

    //
    // Configuring UART
    //
    InitTerm();

    //
    // Initialize WDT
    //
    WDT_IF_Init(NULL,80000000 * 10);

    //
    // Get the reset cause
    //
    ulResetCause = PRCMSysResetCauseGet();

    //
    // If watchdog triggered reset request hibernate
    // to clean boot the system
    //
    if( ulResetCause == PRCM_WDT_RESET )
    {
        HIBEntrePreamble();
        MAP_PRCMOCRRegisterWrite(0,1);
        MAP_PRCMHibernateWakeupSourceEnable(PRCM_HIB_SLOW_CLK_CTR);
        MAP_PRCMHibernateIntervalSet(330);
        MAP_PRCMHibernateEnter();
    }

    //
    // uDMA Initialization
    //
    UDMAInit();

    //
    // Display banner
    //
    DisplayBanner(APPLICATION_NAME);

    if( ulResetCause == PRCM_HIB_EXIT &&  (MAP_PRCMOCRRegisterRead(0) & 1) == 1 )
    {
        UART_PRINT("Reset Cause        : Watchdog Reset\n\r");
    }
    else
    {
        UART_PRINT("Reset Cause        : Power On\n\r");

        //
        // Initialize the variables.
        //
        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 desired state at start of applicaton
        //
        // 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)
                UART_PRINT("Failed to configure the device in its default"
                            " state \n\r");

            LOOP_FOREVER();
        }
    }

    //
    // Set destination IP
    //
    ulDestinationIP = IP_ADDR;

    //
    // Asumption is that the device is configured in station mode already
    // and it is in its default state
    //
    retVal = sl_Start(0, 0, 0);

    //
    // Acknowledge the watchdog so that it doesn't resets
    //
    WatchdogAck();

    if (retVal < 0 || retVal != ROLE_STA)
    {
        UART_PRINT("Failed to start the device \n\r");
        LOOP_FOREVER();
    }

    //
    //Connecting to WLAN AP
    //
    retVal = WlanConnect();

    //
    // Acknowledge the watchdog so that it doesn't resets
    //
    WatchdogAck();

    if(retVal < 0)
    {
        UART_PRINT("Failed to establish connection w/ an AP \n\r");
        LOOP_FOREVER();
    }

    UART_PRINT("Connected to AP    : %s \n\r",SSID_NAME);

    UART_PRINT("Device IP          : %d.%d.%d.%d\n\r\n\r",
                SL_IPV4_BYTE(g_ulIpAddr,3),
                SL_IPV4_BYTE(g_ulIpAddr,2),
                SL_IPV4_BYTE(g_ulIpAddr,1),
                SL_IPV4_BYTE(g_ulIpAddr,0));


    UART_PRINT("\nStarting UDP Client\n\n\r");

    UART_PRINT("Source IP          : %d.%d.%d.%d\n\r"
                 "Destination IP     : %d.%d.%d.%d\n\r"
                 "PORT               : %d\n\r",
                 SL_IPV4_BYTE(g_ulIpAddr,3),
                 SL_IPV4_BYTE(g_ulIpAddr,2),
                 SL_IPV4_BYTE(g_ulIpAddr,1),
                 SL_IPV4_BYTE(g_ulIpAddr,0),
                 SL_IPV4_BYTE(ulDestinationIP,3),
                 SL_IPV4_BYTE(ulDestinationIP,2),
                 SL_IPV4_BYTE(ulDestinationIP,1),
                 SL_IPV4_BYTE(ulDestinationIP,0),
                 g_uiPortNum);


    //
    // Acknowledge the watchdog so that it doesn't resets
    //
    WatchdogAck();

    //
    // Send packets
    //
    BsdUdpClient(PORT_NUM,ulDestinationIP);


    //
    // power off the network processor
    //
    sl_Stop(SL_STOP_TIMEOUT);
    while (1)
    {
        _SlNonOsMainLoopTask();
    }
}
Ejemplo n.º 26
0
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);
      }
    }
  }
}
Ejemplo n.º 27
0
//*****************************************************************************
//! \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
}
Ejemplo n.º 28
0
int main(void){
  UINT8             IsDHCP = 0;
  _NetCfgIpV4Args_t ipV4;
  SlSockAddrIn_t    Addr;
  SlSockAddrIn_t    LocalAddr;
  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");
  UARTprintf("This node is configured to receive UDP packets\n");
  UARTprintf("This node should be at 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);
  ST7735_InitR(INITR_REDTAB);
  ST7735_OutString("Internet of Things\n");
  ST7735_OutString("Embedded Systems\n");
  ST7735_OutString("Vol. 2, Valvano");
  ST7735_PlotClear(0,4095);  // range from 0 to 4095
  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){
      UARTprintf("\nReceiving a UDP packet ...");

      LocalAddr.sin_family = SL_AF_INET;
      LocalAddr.sin_port = sl_Htons((UINT16)PORT_NUM);
      LocalAddr.sin_addr.s_addr = 0;
      AddrSize = sizeof(SlSockAddrIn_t);
      SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);     
      if( SockID < 0 ){
        UARTprintf("SockIDerror\n");
        Status = -1; // error
      }else{
        Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize);
        if( Status < 0 ){
          sl_Close(SockID); 
          UARTprintf("Sock Bind error\n");
        }else{
          Status = sl_RecvFrom(SockID, uBuf, BUF_SIZE, 0,
                  (SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize );
          if( Status <= 0 ){
            sl_Close(SockID);
            UARTprintf("Receive error %d ",Status);
          }else{
            LED_Toggle();
            sl_Close(SockID);
            UARTprintf("ok %s ",uBuf);
            if((uBuf[0]==ATYPE)&&(uBuf[1]== '=')){ int i,bOk; uint32_t place;
              data = 0; bOk = 1;
              i=4;  // ignore possible negative sign
              for(place = 1000; place; place = place/10){
                if((uBuf[i]&0xF0)==0x30){ // ignore spaces
                  data += place*(uBuf[i]-0x30);
                }else{
                  if((uBuf[i]&0xF0)!= ' '){
                    bOk = 0;
                  }
                }
                i++;
              }
              if(bOk){
                ST7735_PlotLine(data);
                ST7735_PlotNextErase(); 
              }
            }
          }
        }
      }
      ROM_SysCtlDelay(ROM_SysCtlClockGet() / 25); // 120ms
    }
  }
}
Ejemplo n.º 29
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;
}
Ejemplo n.º 30
0
/*!
    \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

    \param[in]      none

    \return         On success, zero is returned. On error, negative is returned
*/
static int32_t configureSimpleLinkToDefaultState(char *pConfig){
  SlVersionFull   ver = {0};
  UINT8           val = 1;
  UINT8           configOpt = 0;
  UINT8           configLen = 0;
  UINT8           power = 0;

  INT32           retVal = -1;
  INT32           mode = -1;

  mode = sl_Start(0, pConfig, 0);


    /* If the device is not in station-mode, try putting it in station-mode */
  if (ROLE_STA != mode){
    if (ROLE_AP == mode){
            /* If the device is in AP mode, we need to wait for this event before doing anything */
      while(!IS_IP_AQUIRED(g_Status));
    }

        /* Switch to STA role and restart */
    retVal = sl_WlanSetMode(ROLE_STA);

    retVal = sl_Stop(0xFF);

    retVal = sl_Start(0, pConfig, 0);

        /* Check if the device is in station again */
    if (ROLE_STA != retVal){
            /* We don't want to proceed if the device is not coming up in station-mode */
      return DEVICE_NOT_IN_STATION_MODE;
    }
  }
    /* Get the device's version-information */
  configOpt = SL_DEVICE_GENERAL_VERSION;
  configLen = sizeof(ver);
  retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &configOpt, &configLen, (unsigned char *)(&ver));

    /* Set connection policy to Auto + SmartConfig (Device's default connection policy) */
  retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);

    /* Remove all profiles */
  retVal = sl_WlanProfileDel(0xFF);

    /*
     * 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
     */
  retVal = sl_WlanDisconnect();
  if(0 == retVal){
        /* Wait */
     while(IS_CONNECTED(g_Status));
  }

    /* Enable DHCP client*/
  retVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&val);

    /* Disable scan */
  configOpt = SL_SCAN_POLICY(0);
  retVal = sl_WlanPolicySet(SL_POLICY_SCAN , configOpt, NULL, 0);

    /* Set Tx power level for station mode
       Number between 0-15, as dB offset from max power - 0 will set maximum power */
  power = 0;
  retVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&power);

    /* Set PM policy to normal */
  retVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);

    /* TBD - Unregister mDNS services */
  retVal = sl_NetAppMDNSUnRegisterService(0, 0);


  retVal = sl_Stop(0xFF);


  g_Status = 0;
  memset(&Recvbuff,0,MAX_RECV_BUFF_SIZE);
  memset(&SendBuff,0,MAX_SEND_BUFF_SIZE);
  memset(&HostName,0,MAX_HOSTNAME_SIZE);
  DestinationIP = 0;;
  SockID = 0;


  return retVal; /* Success */
}