Wifi using nanoFramework on the M5Core2

When we’re creating an IoT device, the likelihood is we’ll want to connect to Wifi and the internet (well it’s sort of in the IoT name isn’t it).

Please note, this post is heavily based upon the nanoFramework samples, so do go and view them for a whole host of excellent sample code.

The nanoFramework comes with a NuGet package named nanoFramework.System.Device.Wifi which you’ll need to add to your project.

Now we can use the WifiNetworkHelper class to connect to your DHCP server (your router generally) using the ConnectDhcp method. Now this will also save the configuration of the network ssid and password.

const string ssid = "YOUR_SSID";
const string password = "YOUR_WIFI_PASSWORD";

var cs = new CancellationTokenSource(60000);
var success = WifiNetworkHelper.ConnectDhcp(ssid, password, requiresDateTime: true, token: cs.Token);
if (!success)
{
    Debug.WriteLine($"Cannot connect to the WiFi, error: {WifiNetworkHelper.Status}");
    if (WifiNetworkHelper.HelperException != null)
    {
        Debug.WriteLine($"ex: {WifiNetworkHelper.HelperException}");
    }
}
else
{
   Debug.WriteLine("Connected successfully");
}

As mentioned, the ConnectDhcp method saves our configuration, so once that’s happened, we can switch to using the Reconnect method instead, i.e.

var cs = new CancellationTokenSource(60000);
var success = WifiNetworkHelper.Reconnect(requiresDateTime: true, token: cs.Token);
if (!success)
{
    Debug.WriteLine($"Cannot connect to the WiFi, error: {WifiNetworkHelper.Status}");
    if (WifiNetworkHelper.HelperException != null)
    {
        Debug.WriteLine($"ex: {WifiNetworkHelper.HelperException}");
    }
}
else
{
   Debug.WriteLine("Connected successfully");
}

The ssid and password are stored using the Wireless80211Configuration on the device. So we can check if our configuration has been stored – this ofcourse also means we can get access to the configuration – beware if security is an issue that these are then available as plain text

var configuration = Wireless80211Configuration.GetAllWireless80211Configurations();
foreach (var config in configuration)
{
   Debug.WriteLine($"SSID: {config.Ssid}, Password: {config.Password}");
}