Skip to content

Instantly share code, notes, and snippets.

@patridge
Last active April 24, 2024 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patridge/c067f197eb39d3bd5bfc72a42b5b825f to your computer and use it in GitHub Desktop.
Save patridge/c067f197eb39d3bd5bfc72a42b5b825f to your computer and use it in GitHub Desktop.
Meadow wifi helper to allow awaiting the wifi connection
using System;
using System.Threading;
using System.Threading.Tasks;
using Meadow.Hardware;
namespace MeadowHelpers {
public static class IWiFiNetworkAdapterExtensions {
public static async Task<NetworkConnectionEventArgs> WaitForNetworkConnection(this IWiFiNetworkAdapter wifiAdapter, string? ssid = null, string? password = null, TimeSpan timeout = default(TimeSpan), CancellationToken cancellationToken = default(CancellationToken))
{
var tcs = new TaskCompletionSource<NetworkConnectionEventArgs>();
NetworkConnectionHandler? handler = null;
handler = (networkAdapter, networkConnectionEventArgs) =>
{
// Unsubscribe from the event after it's been fired.
wifiAdapter.NetworkConnected -= handler;
tcs.SetResult(networkConnectionEventArgs);
};
wifiAdapter.NetworkConnected += handler;
var wifiConnectTask = wifiAdapter.Connect(ssid, password, timeout, cancellationToken);
_ = wifiConnectTask.ContinueWith((t) =>
{
if (t.IsFaulted)
{
tcs.SetException(t.Exception);
}
else
{
// Rely on .NetworkConnected event to set the result.
}
});
return await tcs.Task;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment