Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Best practices: how to wait for a Wi-Fi network connection


  • Please log in to reply
15 replies to this topic

#1 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 09 May 2015 - 05:49 PM

Without needing to boot a big OS, Netduino 3 starts up pretty fast.

As a side-effect of this, your code will probably start executing before the Wi-Fi radio even finishes connecting to your Wi-Fi access point.

As standard procedure, we recommend that all apps wait for network connectivity before using System.Net classes or SslStream to access the network. Otherwise, if you try connecting to Internet hosts without a live connection, you will just get SocketExceptions (as expected).

Option 1: using DHCP, wait in a loop for a DHCP-allocated IP address
Most users will have their Netduino 3 Wi-Fi mainboards configured to obtain their IP address using DHCP. A really easy way to wait for connectivity is to wait for an IP address like this:
// wait for DHCP-allocated IP address
while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) ;

Option 2: using static IP, wait in a loop for network connectivity
If you are using static IP, add the NetduinoExtensions.dll assembly to your project. Then you can simply wait in a loop for the network connection to go live.
// wait for network connectivity
while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) ;

Option 3: wait in a loop, regardless of whether DHCP or static IP is used
This is a good option for apps you're writing for public consumption. Just add the NetduinoExtensions.dll assembly to your project and then add this code at the top of your app.
if (!Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IsDhcpEnabled)
{
    // using static IP
    while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) ; // wait for network connectivity
}
else
{
    // using DHCP
    while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) ; // wait for DHCP-allocated IP address
}

Option 4: event-driven code to wait for network connectivity and address allocation
This is my favorite option and is the most elegant. This is the recommended solution if your code is multi-threaded or you just want the most flexibility and lowest power consumption. Here we will use events and a WaitHandle to signal when connectivity is live.

Add the following code at the top of your class, as class-level fields:
static System.Threading.AutoResetEvent _networkAvailableEvent = new System.Threading.AutoResetEvent(false);
static System.Threading.AutoResetEvent _networkAddressChangedEvent = new System.Threading.AutoResetEvent(false);
Add the following code in your Main function to wire up the event handlers.
// wire up events to wait for network link to connect and address to be acquired
Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
// if the network is already up or dhcp address is already set, pre-set those flags.
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
    _networkAvailableEvent.Set();
if (Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IsDhcpEnabled && Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress != "0.0.0.0")
    _networkAddressChangedEvent.Set();
Add the following code in your Main function to wait for the network connection:
_networkAvailableEvent.WaitOne();
_networkAddressChangedEvent.WaitOne();
Finally, add these event handlers to your class:
static void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
    _networkAddressChangedEvent.Set();
}

static void NetworkChange_NetworkAvailabilityChanged(object sender, Microsoft.SPOT.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
{
    if (e.IsAvailable)
    {
        _networkAvailableEvent.Set();
    }
}

Final notes
In all of the above cases, network connectivity is also usually indicated by a green ACT LED on your Netduino 3 Wi-Fi mainboard. There are some exceptions to that rule (such as the edge case where your router is all out of IP addresses to allocate) but it's a good general rule.

Chris

#2 Frode

Frode

    Advanced Member

  • Members
  • PipPipPip
  • 202 posts
  • LocationNorway

Posted 11 May 2015 - 02:22 AM

Best practice posts like these are gold! Very much appreciated!



#3 Robert Hugo

Robert Hugo

    Advanced Member

  • Members
  • PipPipPip
  • 35 posts

Posted 11 May 2015 - 03:22 AM

I totally concur, Frode. Much appreciated, Chris.



#4 Frode

Frode

    Advanced Member

  • Members
  • PipPipPip
  • 202 posts
  • LocationNorway

Posted 14 May 2015 - 09:15 PM

Where is NetduinoExtensions.dll? I couldn't find it in the Netduino SDK.



#5 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 14 May 2015 - 10:09 PM

Hi Frode,

Where is NetduinoExtensions.dll? I couldn't find it in the Netduino SDK.

If you "Add References..." in your project, it is listed in the .NET assemblies window.

You can also reference it directly at:
C:\Program Files (x86)\Secret Labs\Netduino SDK\Assemblies\v4.3

If it's not there, upgrade to the latest Netduino SDK (over on the downloads page) and you should be good to go.

Chris

#6 Frode

Frode

    Advanced Member

  • Members
  • PipPipPip
  • 202 posts
  • LocationNorway

Posted 15 May 2015 - 01:57 AM

Thanks, found it. The SDK linked to from the 4.3.2 (Update 2) firmware forum thread points to an old one, so that's where it all went wrong :) Found the new May 2015 SDK on the Downloads page, and then I got NetduinoExtensions.dll in my v4.3 folder.



#7 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 15 May 2015 - 02:34 AM

The SDK linked to from the 4.3.2 (Update 2) firmware forum thread points to an old one, so that's where it all went wrong :)

Excellent catch, Frode. Links are fixed (and now permanently link to the latest Netduino SDK release).

Chris

#8 Robert Hugo

Robert Hugo

    Advanced Member

  • Members
  • PipPipPip
  • 35 posts

Posted 20 May 2015 - 04:05 AM

For option 4 above, what is the reason to wait for both address changed and availability? Meaning, is it enough to wait only for availability, which is what *I* really care about, per se (the system may disagree, which is why I am asking)?

 

Thanks,

Rob



#9 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 20 May 2015 - 04:17 AM

Hi Rob,

For option 4 above, what is the reason to wait for both address changed and availability? Meaning, is it enough to wait only for availability, which is what *I* really care about, per se (the system may disagree, which is why I am asking)?

If you're using a static IP address, you only need to wait for network availability.

If you're using DHCP-allocated IP address then you need to wait for an address. Technically you don't need to wait for network availability (since getting an address typically means that you have network availability), but it's still a good best practice in case we introduced auto-IP or something in the future.

If you only wait for availability when using DHCP you'll have troubles...since your code will likely try to use the network before you have an assigned address.

Chris

#10 Xcone

Xcone

    New Member

  • Members
  • Pip
  • 2 posts

Posted 12 July 2015 - 06:26 PM

Hi there,

 

New to Netduino (or any such device at all) and just received my Netduino 3 Wifi device. Managed to fix the first few bumps to get it work. Which include Firmware/SDK difference which prevented my from using GoBus. So now that I got that working I want some fun with Wifi.

I tried your examples above, and they didn't work. At first the ACT led was Always orange, which I thought was odd, considering you mention 'green' above. Then realised I had to put in some network settings using MFDeploy and now the ACT led is indeed green. But those examples you posted  still don't work. Considering I'm the newby here, it has to be me, right? :-)

So I guess I'm blaming my network/security settings:

I left DHCP enabled

Encryption: WPAPSK ( which I guess is the same as WPA2? )

Used the correct passphrase (double checked)

And entered the network name in SSID.

 

I have no clue what to fill in the field 'Authentication'. Couldn't find any similar names in my router settings. So I tried them all to no avail.

Left the network key to 2048 bit, but I haven't got a clue if that matters?

What is Rekey Internal?

 

This line keeps being 'True': IPAddress.GetDefaultLocalAddress() == IPAddress.Any

And so, it doesn't pass the while loop. And I figure it's also the reason why in the version with the events, the events never occur.

 

Sooooo ... any pointers would be very much apreciated :-)

 

Thanks!

 

Kind regards,

Koen



#11 Terrence

Terrence

    Member

  • Members
  • PipPip
  • 24 posts

Posted 09 August 2015 - 06:23 PM

In #4 above,

Microsoft.SPOT.Net.NetworkInformation
and
System.Net.NetworkInformation

1. why are you using both?

2 My System.Net does not have .NetworkInformation. What dll is it in?

#12 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 10 August 2015 - 05:55 PM

Hi Koen,

This line keeps being 'True': IPAddress.GetDefaultLocalAddress() == IPAddress.Any
And so, it doesn't pass the while loop. And I figure it's also the reason why in the version with the events, the events never occur.

Hmm. Let's see if we can get you up and running here really quick.

Do you have MAC address filtering set up in your Wi-Fi router by any chance?

Does your router have a browser-based admin panel, where you can check to see if your board is getting authenticated (and what IP address it's getting)?

Welcome to the Netduino community,

Chris

#13 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 10 August 2015 - 05:57 PM

Hi Terrence,

Microsoft.SPOT.Net.NetworkInformation
and
System.Net.NetworkInformation

1. why are you using both?

We're trying to move away from the old Microsoft.SPOT classes, so the new features are going into the traditional .NET namespace for compatibility with other .NET-based code.

2 My System.Net does not have .NetworkInformation. What dll is it in?

Oh yes... This is in the NetduinoExtensions.dll assembly. Add it to your project and then add "using NetduinoExtensions" up top if necessary--and you should see the additional classes.

Please note that the System.Net NetworkInterface code only applies to checking link status on Netduino 3 Wi-Fi _with_ static IP configuration. With DHCP...you can just wait until you get an address.

Chris

#14 Terrence

Terrence

    Member

  • Members
  • PipPip
  • 24 posts

Posted 10 August 2015 - 09:27 PM

Thank you Chris.



#15 ImplicitSystems

ImplicitSystems

    Member

  • Members
  • PipPip
  • 10 posts
  • LocationLake Havasu City, AZ

Posted 26 August 2015 - 11:53 PM

Is there a way to choose what loads depending on the device being deployed to?  I use both the ND2Plus and the ND3Wi-Fi

 

If I deploy to a ND2Plus I get the following crash during debug:

Assembly: SecretLabs.NETMF.Hardware (4.3.1.0)

Resolving.

Link failure: some assembly references cannot be resolved!!


Assembly: NetduinoExtensions (4.3.2.1) needs assembly 'Netduino.IP' (1.0.0.0)

Error: a3000000

Waiting for debug commands...

The program '[36] Micro Framework application: Managed' has exited with code 0 (0x0).

Andy

#16 Gigios

Gigios

    Member

  • Members
  • PipPip
  • 13 posts
  • LocationItaly

Posted 27 August 2015 - 01:25 PM

 

Is there a way to choose what loads depending on the device being deployed to?  I use both the ND2Plus and the ND3Wi-Fi

 

If I deploy to a ND2Plus I get the following crash during debug:

Assembly: SecretLabs.NETMF.Hardware (4.3.1.0)

Resolving.

Link failure: some assembly references cannot be resolved!!


Assembly: NetduinoExtensions (4.3.2.1) needs assembly 'Netduino.IP' (1.0.0.0)

Error: a3000000

Waiting for debug commands...

The program '[36] Micro Framework application: Managed' has exited with code 0 (0x0).

 

I had the same problem when I tryed to use ND2+ with the program used on ND3.

You must update the Firmware of the Netduino 2 with the 'Netduino.IP':

http://forums.netdui...etduino-plus-2/

 

After the upgrade you should be able to run your program without problems.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.