Wi-Fi
WiFiInterface class hierarchy
The WifiInterface provides a simple C++ API for connecting to the internet over a Wi-Fi device.
Wi-Fi class reference
Public Types | |
typedef mbed::Callback< void(nsapi_value_or_error_t result, SocketAddress *address)> | hostbyname_cb_t |
Hostname translation callback (for use with gethostbyname_async()). More... |
Public Member Functions | |
virtual nsapi_error_t | set_credentials (const char *ssid, const char *pass, nsapi_security_t security=NSAPI_SECURITY_NONE)=0 |
Set the Wi-Fi network credentials. More... | |
virtual nsapi_error_t | set_channel (uint8_t channel)=0 |
Set the Wi-Fi network channel. More... | |
virtual int8_t | get_rssi ()=0 |
Get the current radio signal strength for active connection. More... | |
virtual nsapi_error_t | connect (const char *ssid, const char *pass, nsapi_security_t security=NSAPI_SECURITY_NONE, uint8_t channel=0)=0 |
Attempt to connect to a Wi-Fi network. More... | |
nsapi_error_t | connect () override=0 |
Attempt to connect to a Wi-Fi network. More... | |
nsapi_error_t | disconnect () override=0 |
Stop the interface. More... | |
virtual nsapi_size_or_error_t | scan (WiFiAccessPoint *res, nsapi_size_t count)=0 |
Scan for available networks. More... | |
WiFiInterface * | wifiInterface () final |
Return pointer to a WiFiInterface. More... | |
void | set_default_parameters () override |
defined(DOXYGEN_ONLY) More... | |
virtual void | set_as_default () |
Set network interface as default one. More... | |
virtual const char * | get_mac_address () |
Get the local MAC address. More... | |
virtual nsapi_error_t | set_mac_address (uint8_t *mac_addr, nsapi_size_t addr_len) |
Set the MAC address to the interface. More... | |
virtual nsapi_error_t | get_ip_address (SocketAddress *address) |
Get the local IP address. More... | |
virtual nsapi_error_t | get_ipv6_link_local_address (SocketAddress *address) |
Get the IPv6 link local address. More... | |
virtual nsapi_error_t | get_netmask (SocketAddress *address) |
Get the local network mask. More... | |
virtual nsapi_error_t | get_gateway (SocketAddress *address) |
Get the local gateway. More... | |
virtual char * | get_interface_name (char *interface_name) |
Get the network interface name. More... | |
virtual nsapi_error_t | set_network (const SocketAddress &ip_address, const SocketAddress &netmask, const SocketAddress &gateway) |
Configure this network interface to use a static IP address. More... | |
virtual nsapi_error_t | set_dhcp (bool dhcp) |
Enable or disable DHCP on connecting the network. More... | |
virtual nsapi_error_t | gethostbyname (const char *host, SocketAddress *address, nsapi_version_t version=NSAPI_UNSPEC, const char *interface_name=NULL) |
Translate a hostname to an IP address with specific version using network interface name. More... | |
virtual nsapi_value_or_error_t | getaddrinfo (const char *hostname, SocketAddress *hints, SocketAddress **res, const char *interface_name=NULL) |
Translate a hostname to the multiple IP addresses with specific version using network interface name. More... | |
virtual nsapi_value_or_error_t | gethostbyname_async (const char *host, hostbyname_cb_t callback, nsapi_version_t version=NSAPI_UNSPEC, const char *interface_name=NULL) |
Translate a hostname to an IP address (asynchronous) using network interface name. More... | |
virtual nsapi_value_or_error_t | getaddrinfo_async (const char *hostname, SocketAddress *hints, hostbyname_cb_t callback, const char *interface_name=NULL) |
Translate a hostname to the multiple IP addresses (asynchronous) using network interface name. More... | |
virtual nsapi_error_t | gethostbyname_async_cancel (int id) |
Cancel asynchronous hostname translation. More... | |
virtual nsapi_error_t | add_dns_server (const SocketAddress &address, const char *interface_name) |
Add a domain name server to list of servers to query. More... | |
virtual nsapi_error_t | get_dns_server (int index, SocketAddress *address, const char *interface_name=NULL) |
Get a domain name server from a list of servers to query. More... | |
virtual void | attach (mbed::Callback< void(nsapi_event_t, intptr_t)> status_cb) |
Register callback for status reporting. More... | |
void | add_event_listener (mbed::Callback< void(nsapi_event_t, intptr_t)> status_cb) |
Add event listener for interface. More... | |
virtual nsapi_connection_status_t | get_connection_status () const |
Get the connection status. More... | |
virtual nsapi_error_t | set_blocking (bool blocking) |
Set asynchronous operation of connect() and disconnect() calls. More... | |
virtual EthInterface * | ethInterface () |
Return pointer to an EthInterface. More... | |
virtual MeshInterface * | meshInterface () |
Return pointer to a MeshInterface. More... | |
virtual EMACInterface * | emacInterface () |
Return pointer to an EMACInterface. More... | |
virtual CellularInterface * | cellularInterface () |
Return pointer to a CellularInterface. More... |
Static Public Member Functions | |
static WiFiInterface * | get_default_instance () |
Get the default Wi-Fi interface. More... |
Usage
To bring up the network interface of an external Wi-Fi device (for example, the ESP8266Interface):
- Instantiate an implementation of the WiFiInterface class.
- Initialize the AT command parser.
- Call the
connect()
function with an SSID and password for the Wi-Fi network.- Command the Wi-Fi device to connect to network.
- Once connected, you can use the WiFiInterface as a target for opening network sockets.
To bring up the network interface of an Ethernet-like driver (for example, the OdinWiFiInterface):
- Instantiate an implementation of the WiFiInterface class.
- Initialize the Wi-Fi driver for the target.
- Initialize network stack (LWIP).
- Call the
connect()
function with an SSID and password for the Wi-Fi network.- Connect the Wi-Fi driver to the Wi-Fi network.
- Ensure the network stack acquires the IP address and DNS server address.
- Once connected, you can use the WiFiInterface as a target for opening network sockets.
Troubleshooting information
Network interface connect()
and set_credential()
might return following errors:
Error code | Possible reason |
---|---|
NSAPI_ERROR_UNSUPPORTED |
Security mode is unsupported. |
NSAPI_ERROR_PARAMETER |
Wrong parameters supplied for the given security mode, for example, no password. |
NSAPI_ERROR_NO_SSID |
The device did not find the given Wi-Fi network. |
NSAPI_ERROR_AUTH_FAILURE |
Wrong password given. |
NSAPI_ERROR_DEVICE_ERROR |
Unknown failure happened in the device. The device may not be capable of reporting more descriptive error codes. |
Security
For specifying security settings, both connect()
and set_credential()
have optional parameter nsapi_security_t security
, which defines the security mode the device uses. WifiInterface supports the following security modes:
nsapi_security_t |
Security mode |
---|---|
NSAPI_SECURITY_NONE |
Not secure. Require no password or encryption. |
NSAPI_SECURITY_WEP |
WEP security. Outdated. |
NSAPI_SECURITY_WPA |
WPA security mode. Obsolete by WPA2; do not use. |
NSAPI_SECURITY_WPA2 |
WPA2 security. Mostly used security mode. |
NSAPI_SECURITY_WPA_WPA2 |
Allows either WPA or WPA2 security. |
Please note that settings should match the security mode from the access point. Also, not all drivers support every mode. For most compatible settings, use NSAPI_SECURITY_WPA_WPA2
, and set the Wi-Fi access point to allow only WPA2 mode.
Wi-Fi example
This program scans for Wi-Fi access points in the area. There are multiple Wi-Fi components that implement the WiFiInterface class. The example below uses the ESP8266Interface and OdinWiFiInterface.
The ESP8266Interface uses AT commands over serial interface to connect to an external Wi-Fi device. The OdinWiFiInterface provides an Ethernet-like driver to the Mbed OS network stack. The network stack uses the driver to connect to Wi-Fi:
/*
* Copyright (c) 2006-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
#include "TCPSocket.h"
#if TARGET_UBLOX_EVK_ODIN_W2
#include "OdinWiFiInterface.h"
OdinWiFiInterface wifi;
#else
#if !TARGET_FF_ARDUINO
#error [NOT_SUPPORTED] Only Arduino form factor devices are supported at this time
#endif
#include "ESP8266Interface.h"
ESP8266Interface wifi(D1, D0);
#endif
const char *sec2str(nsapi_security_t sec)
{
switch (sec) {
case NSAPI_SECURITY_NONE:
return "None";
case NSAPI_SECURITY_WEP:
return "WEP";
case NSAPI_SECURITY_WPA:
return "WPA";
case NSAPI_SECURITY_WPA2:
return "WPA2";
case NSAPI_SECURITY_WPA_WPA2:
return "WPA/WPA2";
case NSAPI_SECURITY_UNKNOWN:
default:
return "Unknown";
}
}
void scan_demo(WiFiInterface *wifi)
{
WiFiAccessPoint *ap;
printf("Scan:\r\n");
int count = wifi->scan(NULL, 0);
/* Limit number of network arbitrary to 15 */
count = count < 15 ? count : 15;
ap = new WiFiAccessPoint[count];
count = wifi->scan(ap, count);
for (int i = 0; i < count; i++) {
printf("Network: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\r\n", ap[i].get_ssid(),
sec2str(ap[i].get_security()), ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2],
ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5], ap[i].get_rssi(), ap[i].get_channel());
}
printf("%d networks available.\r\n", count);
delete[] ap;
}
void http_demo(NetworkInterface *net)
{
// Open a socket on the network interface, and create a TCP connection to mbed.org
TCPSocket socket;
socket.open(net);
SocketAddress a;
net->gethostbyname("ifconfig.io", &a);
a.set_port(80);
socket.connect(a);
// Send a simple http request
char sbuffer[] = "GET / HTTP/1.1\r\nHost: ifconfig.io\r\n\r\n";
int scount = socket.send(sbuffer, sizeof sbuffer);
printf("sent %d [%.*s]\n", scount, strstr(sbuffer, "\r\n") - sbuffer, sbuffer);
// Recieve a simple http response and print out the response line
char rbuffer[64];
int rcount = socket.recv(rbuffer, sizeof rbuffer);
printf("recv %d [%.*s]\n", rcount, strstr(rbuffer, "\r\n") - rbuffer, rbuffer);
// Close the socket to return its memory and bring down the network interface
socket.close();
}
int main()
{
SocketAddress a;
printf("WiFi example\r\n\r\n");
scan_demo(&wifi);
printf("\r\nConnecting...\r\n");
int ret = wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
if (ret != 0) {
printf("\r\nConnection error\r\n");
return -1;
}
printf("Success\r\n\r\n");
printf("MAC: %s\r\n", wifi.get_mac_address());
wifi.get_ip_address(&a);
printf("IP: %s\r\n", a.get_ip_address());
wifi.get_netmask(&a);
printf("Netmask: %s\r\n", a.get_ip_address());
wifi.get_gateway(&a);
printf("Gateway: %s\r\n", a.get_ip_address());
printf("RSSI: %d\r\n\r\n", wifi.get_rssi());
http_demo(&wifi);
wifi.disconnect();
printf("\r\nDone\r\n");
}
Related content
- Wi-Fi components.
- Network socket API overview.
- Wi-Fi architecture.