Last active
April 24, 2024 01:45
-
-
Save patridge/c067f197eb39d3bd5bfc72a42b5b825f to your computer and use it in GitHub Desktop.
Meadow wifi helper to allow awaiting the wifi connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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