.. _sec-wifi-basic-operations:

Basic Operations
================

This section describes the core WLAN operations available on the |DEVICE|,
each corresponding to a function in the ``Wlan_*`` API.

Starting WLAN
-------------

``Wlan_Start`` powers on the WLAN device, initializes the stack threads
(CME, transport, event handler, etc.), and activates the host interface.
The firmware, bootloader, and configuration containers are loaded from
non-volatile memory and programmed to the MAC layer. This must be the
first WLAN call made by the application.

An event handler callback is required. The callback receives all
asynchronous WLAN events:

.. code-block:: c

    void WlanStackEventHandler(WlanEvent_t *pWlanEvent)
    {
        if (!pWlanEvent)
        {
            return;
        }

        switch (pWlanEvent->Id)
        {
            case WLAN_EVENT_CONNECT:
                break;
            case WLAN_EVENT_DISCONNECT:
                break;
            case WLAN_EVENT_SCAN_RESULT:
                break;
            default:
                UART_PRINT("\n\r[WLAN EVENT] Unexpected event [%d]\n\r",
                           pWlanEvent->Id);
                break;
        }
    }

.. code-block:: c

    int32_t ret = Wlan_Start(WlanStackEventHandler);

    if (ret == OSI_OK)
    {
        Report("\n\rWlan start success!");
    }
    else
    {
        Report("\n\rWlan start failed: %d. See errors.h for error codes.\n\r", ret);
    }

Stopping WLAN
-------------

``Wlan_Stop`` powers off the WLAN device and deactivates the host
interface. All stack threads are deleted and their queues and semaphores
are destroyed. All roles must be brought down before calling this
function.

Pass ``FALSE`` for a normal stop or ``TRUE`` to stop in recovery mode:

.. code-block:: c

    int32_t ret = Wlan_Stop(FALSE);

    if (ret == 0)
    {
        Report("\n\rWlan stop success!");
    }
    else
    {
        Report("\n\rWlan stop failed: %d. See errors.h for error codes.\n\r", ret);
    }

Starting Station Role
---------------------

``Wlan_RoleUp(WLAN_ROLE_STA, ...)`` adds and starts the station role,
registering a network interface with the LwIP stack.

.. note::

    ``WLAN_SET_STA_WIFI_BAND`` must be called before ``Wlan_RoleUp`` to
    enable the desired band. The default behavior is 2.4 GHz only. To
    use 5 GHz or both bands, set this explicitly as shown below.

.. code-block:: c

    int32_t        ret = 0;
    RoleUpStaCmd_t RoleUpStaParams;
    memset(&RoleUpStaParams, 0, sizeof(RoleUpStaCmd_t));

    /* Enable both 2.4 GHz and 5 GHz bands */
    uint8_t sta_wifi_band = (uint8_t)BAND_SEL_BOTH;
    Wlan_Set(WLAN_SET_STA_WIFI_BAND, &sta_wifi_band);

    RoleUpStaParams.wpsDisabled = TRUE;

    ret = Wlan_RoleUp(WLAN_ROLE_STA, &RoleUpStaParams, WLAN_WAIT_FOREVER);

Stopping Station Role
---------------------

``Wlan_RoleDown(WLAN_ROLE_STA, ...)`` stops and removes the station role.
If the station is connected, disconnect first:

.. code-block:: c

    int32_t ret = 0;

    if (connected)
    {
        ret = Wlan_Disconnect(WLAN_ROLE_STA, NULL);
    }

    if (ret != OSI_OK)
    {
        Report("Wlan_Disconnect() failed");
        return ret;
    }

    ret = Wlan_RoleDown(WLAN_ROLE_STA, WLAN_WAIT_FOREVER);

Starting AP Role
----------------

``Wlan_RoleUp(WLAN_ROLE_AP, ...)`` adds and starts the AP role,
registering a network interface with the LwIP stack.

.. code-block:: c

    int32_t       ret = 0;
    RoleUpApCmd_t RoleUpApParams;
    memset(&RoleUpApParams, 0, sizeof(RoleUpApParams));

    RoleUpApParams.sta_limit = 4;
    RoleUpApParams.hidden    = FALSE;
    RoleUpApParams.tx_pow    = WLAN_MAX_TX_POWER_DBM; /* dBm; capped to regulatory max */
    RoleUpApParams.channel   = 6;
    RoleUpApParams.sae_pwe   = 2;

    Report("Starting AP on channel %d", RoleUpApParams.channel);

    ret = Wlan_RoleUp(WLAN_ROLE_AP, &RoleUpApParams, OSI_WAIT_FOR_SECOND * 10);

.. note::

    * ``tx_pow`` accepts values from ``WLAN_MIN_TX_POWER_DBM`` (-10 dBm) to
      ``WLAN_MAX_TX_POWER_DBM`` (21 dBm). Values outside this range or above the
      regulatory limit for the operating channel are capped to the regulatory maximum.
    * TX power is configured per role and does not persist across role stop/start
      cycles. Reconfigure it after each ``Wlan_RoleUp``, or use
      ``Wlan_Set(WLAN_SET_TX_POWER, ...)`` after the role is active.
    * For WPS configuration in AP role, see :ref:`sec-wifi-wps`.

Stopping AP Role
----------------

``Wlan_RoleDown(WLAN_ROLE_AP, ...)`` stops and removes the AP role:

.. code-block:: c

    int32_t ret = Wlan_RoleDown(WLAN_ROLE_AP, WLAN_WAIT_FOREVER);

Scanning for Networks
---------------------

``Wlan_Scan`` triggers an active scan and returns results to the
application through the event callback as ``WLAN_EVENT_SCAN_RESULT``
events.

.. code-block:: c

    int32_t      ret = 0;
    ScanCmd_t    ScanParams;
    scanCommon_t scanCommo;
    WlanRole_e   role = WLAN_ROLE_STA;

    memset(&ScanParams,  0, sizeof(ScanParams));
    memset(&scanCommo,   0, sizeof(scanCommon_t));
    memset(&app_CB.gDataBuffer, 0, sizeof(app_CB.gDataBuffer));

    ScanParams.numOfentries = MAX_SSID_ENTRIES;
    ScanParams.index        = 0;

    /* Scan both bands; options: BAND_SEL_ONLY_2_4GHZ, BAND_SEL_ONLY_5GHZ, BAND_SEL_BOTH */
    scanCommo.Band = BAND_SEL_BOTH;

    ret = Wlan_Scan(role, &scanCommo, ScanParams.numOfentries);

Connecting to an AP
-------------------

``Wlan_Connect`` initiates a connection to an AP. The required parameters
are the SSID, security type, and passphrase. The ``WLAN_EVENT_CONNECT``
event fires on success; ``WLAN_EVENT_DISCONNECT`` fires first if the
device was already connected.

.. code-block:: c

    int32_t      ret = 0;
    ConnectCmd_t ConnectParams;

    ConnectParams.secParams.Type = WLAN_SEC_TYPE_WPA_WPA2;
    ConnectParams.secParams.Key  = (int8_t *)"MyPassphrase";
    ConnectParams.ssid           = (uint8_t *)"MySSID";

    ret = Wlan_Connect((const signed char *)(ConnectParams.ssid),
                       strlen((const char *)(ConnectParams.ssid)),
                       ConnectParams.bssid,
                       ConnectParams.secParams.Type,
                       (const char *)(ConnectParams.secParams.Key),
                       (ConnectParams.secParams.Key != NULL ?
                            strlen((const char *)ConnectParams.secParams.Key) : 0),
                       0);

Disconnecting from an AP
------------------------

``Wlan_Disconnect`` terminates the current station connection. The
``WLAN_EVENT_DISCONNECT`` event fires on success.

.. code-block:: c

    int32_t ret = 0;

    if (Connected)
    {
        ret = Wlan_Disconnect(WLAN_ROLE_STA, NULL);
    }

GET and SET
===========

Getting Firmware Version
------------------------

Reads the firmware version of the radio core.

.. code-block:: c

    WlanFWVersions_t wlanFwVersions = {0};
    int32_t          status;

    status = Wlan_Get(WLAN_GET_FWVERSION, (void *)&wlanFwVersions);
    if (status < 0)
    {
        return -1;
    }

    UART_PRINT("\t MAC:  %d.%d.%d.%d",
               wlanFwVersions.major_version, wlanFwVersions.minor_version,
               wlanFwVersions.api_version,   wlanFwVersions.build_version);

    UART_PRINT("\t PHY:  %d.%d.%d.%d",
               wlanFwVersions.phy_version[0], wlanFwVersions.phy_version[1],
               wlanFwVersions.phy_version[2], wlanFwVersions.phy_version[3]);

Getting MAC Address
-------------------

Reads the MAC address for the active role. The role must be up before
calling this function.

.. code-block:: c

    WlanMacAddress_t macAddressParams = {0};
    int32_t          status;

    status = Wlan_Get(WLAN_GET_MACADDRESS, (void *)&macAddressParams);
    if (status < 0)
    {
        return -1;
    }

    UART_PRINT("\t MAC address: %02x:%02x:%02x:%02x:%02x:%02x",
               macAddressParams.pMacAddress[0], macAddressParams.pMacAddress[1],
               macAddressParams.pMacAddress[2], macAddressParams.pMacAddress[3],
               macAddressParams.pMacAddress[4], macAddressParams.pMacAddress[5]);

Setting MAC Address
-------------------

Sets the MAC address for a role. The role must be up before calling this
function.

.. code-block:: c

    WlanMacAddress_t macAddressParams;
    int32_t          ret;
    memset(&macAddressParams, 0, sizeof(WlanMacAddress_t));

    macAddressParams.roleType = WLAN_ROLE_STA;
    /* Copy the desired 6-byte MAC address into macAddressParams.pMacAddress */

    ret = Wlan_Set(WLAN_SET_MACADDRESS, (void *)&macAddressParams);

Getting Power Save Mode
-----------------------

Reads the current power save mode of the station.

.. code-block:: c

    WlanPowerSave_e currentPsMode;
    int32_t         ret;

    ret = Wlan_Get(WLAN_GET_POWER_SAVE, (void *)&currentPsMode);

    if (ret == 0)
    {
        switch (currentPsMode)
        {
            case WLAN_STATION_AUTO_PS_MODE:
                Report("\n\r[PS MODE] Auto Power Save\n\r");
                break;
            case WLAN_STATION_ACTIVE_MODE:
                Report("\n\r[PS MODE] Active mode\n\r");
                break;
            case WLAN_STATION_POWER_SAVE_MODE:
                Report("\n\r[PS MODE] Power Save mode\n\r");
                break;
            default:
                Report("\n\r[PS MODE] Invalid mode\n\r");
                break;
        }
    }

Setting Power Save Mode
-----------------------

Sets the power save mode of the station. Valid values are
``WLAN_STATION_AUTO_PS_MODE``, ``WLAN_STATION_ACTIVE_MODE``, and
``WLAN_STATION_POWER_SAVE_MODE``.

.. code-block:: c

    WlanPowerSave_e PsMode = WLAN_STATION_AUTO_PS_MODE;
    int32_t         ret;

    ret = Wlan_Set(WLAN_SET_POWER_SAVE, (void *)&PsMode);

    if (ret < 0)
    {
        Report("\n\r[PS MODE] Failed to set PS mode %d\n\r", PsMode);
    }
    else
    {
        Report("\n\r[PS MODE] Successfully set PS mode %d\n\r", PsMode);
    }

Setting Power Management Mode
-----------------------------

Sets the power management mode of the radio. Supported modes are ELP
(Extreme Low Power), Active (fully awake), and Power Down.

.. code-block:: c

    WlanPowerManagement_e PmMode = WLAN_POWER_POLICY_AUTO;
    int32_t               ret;

    ret = Wlan_Set(WLAN_SET_POWER_MANAGEMENT, (void *)&PmMode);

    if (ret < 0)
    {
        Report("\n\r[PM MODE] Failed to set PM mode %d\n\r", PmMode);
    }
    else
    {
        Report("\n\r[PM MODE] Successfully set PM mode %d\n\r", PmMode);
    }

Setting Long Sleep Interval
---------------------------

Sets the Long Sleep Interval (LSI) mode. In LSI mode, the device wakes
for only a single broadcast period within the configured interval, reducing
power consumption at the cost of potentially missing broadcast frames.

.. code-block:: c

    WlanLongSleepInterval LsiParams;
    int32_t               ret;
    memset(&LsiParams, 0, sizeof(LsiParams));

    /* Set the desired listen interval in beacon periods */
    LsiParams.ListenInterval = 10;

    ret = Wlan_Set(WLAN_SET_LSI, (void *)&LsiParams);

    if (ret < 0)
    {
        Report("\n\r[SET LSI] Failed to set LSI %d\n\r", LsiParams.ListenInterval);
    }
    else
    {
        Report("\n\r[SET LSI] Successfully set LSI to %d\n\r", LsiParams.ListenInterval);
    }

Getting TX Power
----------------

Reads the current TX power for an active role. The role must be up (AP started or STA
connected) before calling this function.

.. code-block:: c

    WlanTxPowerGet_t txPower = {0};
    int32_t          ret;

    txPower.role = WLAN_ROLE_AP;    /* or WLAN_ROLE_STA */

    ret = Wlan_Get(WLAN_GET_TX_POWER, (void *)&txPower);
    if (ret < 0)
    {
        return -1;
    }

    UART_PRINT("\n\rCurrent TX power: %d dBm\n\r", txPower.tx_power_dbm);

Setting TX Power
----------------

Sets the TX power for an active role. Valid range is ``WLAN_MIN_TX_POWER_DBM`` (-10 dBm)
to ``WLAN_MAX_TX_POWER_DBM`` (21 dBm). Values above the regulatory limit for the operating
channel are capped to the regulatory maximum and a message is printed showing both the
requested and applied values. TX power is set per role and does not affect other concurrent
roles in a multi-role configuration.

.. code-block:: c

    WlanTxPowerSet_t txPower;
    int32_t          ret;
    memset(&txPower, 0, sizeof(WlanTxPowerSet_t));

    txPower.role         = WLAN_ROLE_AP;    /* or WLAN_ROLE_STA */
    txPower.tx_power_dbm = 17;              /* desired TX power in dBm */

    ret = Wlan_Set(WLAN_SET_TX_POWER, (void *)&txPower);

    if (ret < 0)
    {
        Report("\n\r[TX POWER] Failed to set TX power\n\r");
    }
    else
    {
        Report("\n\r[TX POWER] TX power set successfully\n\r");
    }

.. note::

    * **AP role**: TX power must be reconfigured after each ``Wlan_RoleUp``. The setting
      does not persist across AP role stop/start cycles. When set while the AP is running,
      the new value is reflected in beacon frames.
    * **STA role**: TX power applies to the current connection only. On reconnect or
      connection to a different AP, TX power resets to the regulatory maximum for the
      new operating channel.
    * **Multi-role**: TX power is independent per role. Setting AP TX power does not
      affect a concurrently active STA interface.
    * The role must be active before calling this function. For STA, the station must be
      connected; for AP, the AP must be started.
