Last active
March 27, 2018 01:20
-
-
Save naikrovek/682c2c30f09a7024c2a32075bd85e9d8 to your computer and use it in GitHub Desktop.
This file contains 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.Diagnostics; | |
using System.Linq; | |
using Windows.Devices.WiFi; | |
using Windows.Foundation.Diagnostics; | |
using Windows.ApplicationModel.Background; | |
using Windows.Networking.Connectivity; | |
using Windows.Security.Credentials; | |
using System.Threading.Tasks; | |
namespace WiFiConnector { | |
public sealed class StartupTask : IBackgroundTask { | |
// network details & credentials. | |
private string networkName = "YOUR_SSID"; | |
private string username = "user"; | |
private string domain = "domain"; // optional; may be required in your environment. | |
private string password = "password"; | |
// log to the ETW provider Microsoft-Windows-Diagnostics-LoggingChannel | |
LoggingChannel lc = new LoggingChannel("WiFiConnector", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a")); | |
public async void Run(IBackgroundTaskInstance taskInstance) { | |
BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); | |
WiFiAdapter firstAdapter; | |
do { | |
// Request access to WiFiAdapter | |
WiFiAccessStatus access = await WiFiAdapter.RequestAccessAsync(); | |
if (WiFiAccessStatus.Allowed != access) { | |
lc.LogMessage("WiFi Access is denied: " + access.ToString(), LoggingLevel.Error); | |
} | |
lc.LogMessage("starting do loop.", LoggingLevel.Verbose); | |
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); | |
lc.LogMessage("Testing if we're connected already.", LoggingLevel.Information); | |
if (networkName != GetCurrentWifiNetwork()) { | |
lc.LogMessage("Not already connected to network; continuing.", LoggingLevel.Information); | |
// not already connected. | |
if (result.Count >= 1) { | |
lc.LogMessage(result.Count + " wifi adapter(s) found. Using first.", LoggingLevel.Information); | |
firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); | |
// get the list of available networks: | |
lc.LogMessage("Getting nearby Wi-Fi networks.", LoggingLevel.Information); | |
await firstAdapter.ScanAsync(); | |
// make sure that networkName is available: | |
var availableNetworks = firstAdapter.NetworkReport; | |
lc.LogMessage(availableNetworks.AvailableNetworks.Count + " networks found.", LoggingLevel.Information); | |
WiFiAvailableNetwork correctNetwork = null; | |
foreach (var wifinetwork in availableNetworks.AvailableNetworks) { | |
if (wifinetwork.Ssid == networkName) { | |
lc.LogMessage(networkName + " found."); | |
correctNetwork = wifinetwork; | |
break; | |
} | |
} | |
if (null == correctNetwork) { | |
lc.LogMessage("network not found.", LoggingLevel.Error); | |
return; // proper network not visible, no reason to continue. | |
} | |
WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic; | |
var credential = new PasswordCredential { | |
UserName = username, | |
Resource = domain, // optional | |
Password = password | |
}; | |
WiFiConnectionResult wifiResult = null; | |
Task<WiFiConnectionResult> didConnect = null; | |
didConnect = firstAdapter.ConnectAsync(correctNetwork, reconnectionKind, credential).AsTask<WiFiConnectionResult>(); | |
if (didConnect != null) { | |
lc.LogMessage("Attempting connection to " + networkName + "."); | |
wifiResult = await didConnect; | |
} | |
if (wifiResult != null && wifiResult.ConnectionStatus == WiFiConnectionStatus.Success) { | |
// we've connected. yay. | |
lc.LogMessage("Connected.", LoggingLevel.Information); | |
} else { | |
// ooh, we failed to connect. !? That shoudln't happen. | |
// do nothing so we can try again. | |
lc.LogMessage(".. uhh, failed to connect. Check your credentials?", LoggingLevel.Error); | |
} | |
} else { | |
// no wifi adapters. | |
lc.LogMessage("No Wi-Fi adapters found. :(", LoggingLevel.Error); | |
} | |
} else { | |
// already connected. do nothin. | |
lc.LogMessage("Already connected to correct network. Nothing to do.", LoggingLevel.Information); | |
} | |
// we're doing this in a loop because we're an iot background application. | |
lc.LogMessage("30 second delay before we try again or reconnect if disconnected.", LoggingLevel.Information); | |
await Task.Delay(30000); | |
} while (true); | |
} | |
private string GetCurrentWifiNetwork() { | |
var connectionProfiles = NetworkInformation.GetConnectionProfiles(); | |
if (connectionProfiles.Count < 1) { | |
return null; | |
} | |
var validProfiles = connectionProfiles.Where(profile => { | |
return (profile.IsWlanConnectionProfile && profile.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None); | |
}); | |
if (validProfiles.Count() < 1) { | |
return null; | |
} | |
ConnectionProfile firstProfile = validProfiles.First(); | |
return firstProfile.ProfileName; | |
} | |
private bool IsConnected(WiFiAvailableNetwork network) { | |
if (network == null) { | |
return false; | |
} | |
string profileName = GetCurrentWifiNetwork(); | |
if (!String.IsNullOrEmpty(network.Ssid) && !String.IsNullOrEmpty(profileName) && (network.Ssid == profileName)) { | |
return true; | |
} | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!
Needed to add the following to package.appxmanifest: