Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Amol Disale
Published © GPL3+

Smart Home Using Netduino

Control your appliances from anywhere in the world! Monitor your room temperature, humidity, light intensity and air quality from smartphone

IntermediateFull instructions provided2 days2,643
Smart Home Using Netduino

Things used in this project

Hardware components

Netduino
Wilderness Labs Netduino
×1
Grove - Relay
Seeed Studio Grove - Relay
×1
Grove - Light Sensor
Seeed Studio Grove - Light Sensor
×1
Seeed Studio Grove - Temperature&Humidity Sensor (High-Accuracy &Mini)
Link to Buy:- https://www.seeedstudio.com/Grove-Temperature%26Humidity-Sensor-(High-Accuracy-%26-Mini)-p-1921.html Sensor Tutorial:- http://wiki.seeedstudio.com/Grove-TemptureAndHumidity_Sensor-High-Accuracy_AndMini-v1.0/
×1
Grove - Air quality sensor v1.3
Seeed Studio Grove - Air quality sensor v1.3
×1
Base Shield V2
Seeed Studio Base Shield V2
×1

Software apps and online services

Visual Studio 2015
Microsoft Visual Studio 2015
Ubidots
Ubidots

Hand tools and fabrication machines

Screwdriver

Story

Read more

Schematics

Relay Connection with Netduino board

LDR and Air Quality Sensor connections with Netduino

Final Connections with Netduino

Code

Blink

C#
Blinking the onboard led on Netduino board
using System.Threading;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;


namespace Led_Blink_Example
{
   public class Program
   {
       // An output port allows you to write (send a signal) to a pin
       static OutputPort _led = new OutputPort(Pins.ONBOARD_LED, false);
       public static void Main()
       {
           // write your Main code here 
           // turn the LED off initially
           _led.Write(false);
           // run forever
           while (true)
           {
               // turn the LED off 
               _led.Write(false);
               Thread.Sleep(500);
               // turn the LED on 
               _led.Write(true);
               Thread.Sleep(500);
           }
       }
   }
}

Ubidots Uploading and Receiving Program

C#
Program to receive the data using http get request and also uploading the data to ubidots using http post request
using System;                                 //For functions like Random number generator
using System.Net;                             //For http web request, ip address mthods
using System.Text;                            //For Encoding.UTF8.GetBytes method
using System.IO;                              //For StreamReader methods
using System.Threading;                       //For Thread methods like Sleep
using Microsoft.SPOT;                         //For Serial Debug method
using Microsoft.SPOT.Hardware;                //For input/Output functions like OutputPort
using SecretLabs.NETMF.Hardware.Netduino;     //For input/output functions like pin definition Pins.ONBOARD_LED
using Microsoft.SPOT.Net.NetworkInformation;  //for networkinterface and related methods


//Your project name should always match the below namespace name
namespace UbidotsIntervalUploading
{
    public class Program
    {
        public static void Main()
        {
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

            led.Write(true); // turn on the LED
            Thread.Sleep(1000); // sleep for 1000ms
            
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 250ms
            
            led.Write(true); // turn on the LED
            Thread.Sleep(1000); // sleep for 1000ms
            
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 1000ms

            Debug.Print("Ready to Run.....!");

            App app = new App();
            app.Run();

            while (app.IsRunning)
            {
                led.Write(true); // turn on the LED
                Thread.Sleep(250); // sleep for 250ms
                led.Write(false); // turn off the LED
                Thread.Sleep(250); // sleep for 250ms
            }

            while (app.ipCheck == false)
            {
                app.Run();
                Thread.Sleep(1000);
            }

            //led.Write(false); // turn off the LED onboard the Netduino
            //Debug.Print("Turn off the LED onboard the Netduino");

            while (true)
            {
                string deviceLabel = "netduino_smart_home";
                string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                ubidotsURL = ubidotsURL + deviceLabel + "/";
                app.MakeWebRequest(ubidotsURL);

                //Random number generator
                Random rnd = new Random();
                string sensor1Label = "lightLevel";
                //Generates 0 to 100 random number for light intensity which is in percentage
                int sensor1Data = rnd.Next(100);
                string sensor2Label = "airQuality";
                //Generates 0 to 1023 random number for air Quality
                int sensor2Data = rnd.Next(1023);
                app.UploadWebRequest(ubidotsURL, sensor1Label, sensor1Data, sensor2Label, sensor2Data);

                string controlVariable1 = "relay1button";
                int dataReceived = app.ReceiveWebRequest(ubidotsURL, controlVariable1);
                Debug.Print("");
                Debug.Print("Data Received:- " + dataReceived);

                if (dataReceived == 1)
                {
                    Debug.Print("Turning the Relay1 ON Connected to Pin D2");
                }
                else if (dataReceived == 0)
                {
                    Debug.Print("Turning the Relay1 OFF Connected to Pin D2");
                }

                Thread.Sleep(2500);
            }
        }

    }

    public class App
    {
        NetworkInterface[] _interfaces;


        //public bool IsRunning { get; set; }
        bool _IsRunning;
        public bool IsRunning
        {
            get { return _IsRunning; }
            set { _IsRunning = value; }
        }

        bool _ipCheck;
        public bool ipCheck
        {
            get { return _ipCheck; }
            set { _ipCheck = value; }
        }

        public void Run()
        {
            this.IsRunning = true;
            Debug.Print("Initializing the networks...");
            bool goodToGo = InitializeNetwork();
            this.ipCheck = goodToGo;

            if (goodToGo)
            {
                string deviceLabel = "netduino_smart_home";
                string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                ubidotsURL = ubidotsURL + deviceLabel + "/";
                MakeWebRequest(ubidotsURL);
            }

            this.IsRunning = false;
        }


        protected bool InitializeNetwork()
        {
            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                Debug.Print("Wireless tests run only on Device");
                return false;
            }

            Debug.Print("Getting all the network interfaces.");
            _interfaces = NetworkInterface.GetAllNetworkInterfaces();

            // debug output
            ListNetworkInterfaces();

            // loop through each network interface
            foreach (var net in _interfaces)
            {

                // debug out
                ListNetworkInfo(net);

                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;
                }

                // check for an IP address, try to get one if it's empty
                return CheckIPAddress(net);
            }

            // if we got here, should be false.
            return false;
        }

        public void UploadWebRequest(string url, string sensor1, int sensor1Data, string sensor2, int sensor2Data)
        {
            string payload = "{\"" + sensor1 + "\": " + sensor1Data + ",\"" + sensor2 + "\": " + sensor2Data + "}";

            Debug.Print("JSON String is " + payload);

            var request = (HttpWebRequest)WebRequest.Create(url);

            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }

        public int ReceiveWebRequest(string url, string controlVar)
        {
            string requestUrl = url + controlVar + "/" + "lv";
            Debug.Print("Making a Get Request to:- " + requestUrl);
            //"http://things.ubidots.com/api/v1.6/devices/testDevice/relay1button/lv";

            var request = (HttpWebRequest)WebRequest.Create(requestUrl);

            request.Method = "GET";
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");

            var httpResponse = (HttpWebResponse)request.GetResponse();
            int dataReceived = 0;
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                string resultData = result;
                Debug.Print("Relay Data:- " + resultData + " length:- " + resultData.Length);
                double temp = double.Parse(resultData);
                dataReceived = (int)temp;
            }

            return dataReceived;
        }

        public void MakeWebRequest(string url)
        {
            var value = 25;
            string sensor = "temperature";

            string payload = "{\"" + sensor + "\": " + value + "}";

            Debug.Print("JSON String is " + payload);

            //string payload = "{\"temperature\": 56, \"luminosity\": {\"value\":16}}";
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            //Creating a byte array for our payload for length calculation
            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream(); 
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }


        protected bool CheckIPAddress(NetworkInterface net)
        {
            int timeout = 10000; // timeout, in milliseconds to wait for an IP. 10,000 = 10 seconds

            // check to see if the IP address is empty (0.0.0.0). IPAddress.Any is 0.0.0.0.
            if (net.IPAddress == IPAddress.Any.ToString())
            {
                Debug.Print("No IP Address");

                if (net.IsDhcpEnabled)
                {
                    Debug.Print("DHCP is enabled, attempting to get an IP Address");

                    // ask for an IP address from DHCP [note this is a static, not sure which network interface it would act on]
                    int sleepInterval = 10;
                    int maxIntervalCount = timeout / sleepInterval;
                    int count = 0;
                    while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any && count < maxIntervalCount)
                    {
                        Debug.Print("Sleep while obtaining an IP");
                        Thread.Sleep(10);
                        count++;
                    };

                    // if we got here, we either timed out or got an address, so let's find out.
                    if (net.IPAddress == IPAddress.Any.ToString())
                    {
                        Debug.Print("Failed to get an IP Address in the alotted time.");
                        return false;
                    }

                    Debug.Print("Got IP Address: " + net.IPAddress.ToString());
                    return true;

                    //NOTE: this does not work, even though it's on the actual network device. [shrug]
                    // try to renew the DHCP lease and get a new IP Address
                    //net.RenewDhcpLease ();
                    //while (net.IPAddress == "0.0.0.0") {
                    //    Thread.Sleep (10);
                    //}

                }
                else
                {
                    Debug.Print("DHCP is not enabled, and no IP address is configured, bailing out.");
                    return false;
                }
            }
            else
            {
                Debug.Print("Already had IP Address: " + net.IPAddress.ToString());
                return true;
            }

        }

        protected void ListNetworkInterfaces()
        {
            foreach (var net in _interfaces)
            {
                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;

                }
            }
        }

        protected void ListNetworkInfo(NetworkInterface net)
        {
            Debug.Print("MAC Address: " + BytesToHexString(net.PhysicalAddress));
            Debug.Print("DHCP enabled: " + net.IsDhcpEnabled.ToString());
            Debug.Print("Dynamic DNS enabled: " + net.IsDynamicDnsEnabled.ToString());
            Debug.Print("IP Address: " + net.IPAddress.ToString());
            Debug.Print("Subnet Mask: " + net.SubnetMask.ToString());
            Debug.Print("Gateway: " + net.GatewayAddress.ToString());

            if (net is Wireless80211)
            {
                var wifi = net as Wireless80211;
                Debug.Print("SSID:" + wifi.Ssid.ToString());
            }

        }

        private static string BytesToHexString(byte[] bytes)
        {
            string hexString = string.Empty;

            // Create a character array for hexidecimal conversion.
            const string hexChars = "0123456789ABCDEF";

            // Loop through the bytes.
            for (byte b = 0; b < bytes.Length; b++)
            {
                if (b > 0)
                    hexString += "-";

                // Grab the top 4 bits and append the hex equivalent to the return string.        
                hexString += hexChars[bytes[b] >> 4];

                // Mask off the upper 4 bits to get the rest of it.
                hexString += hexChars[bytes[b] & 0x0F];
            }

            return hexString;
        }

    }

}

Netduino On-board LED Control using Ubidots IoT Platform

C#
Controlling the LED present on the Netduino board from Ubidots IoT Platform website dashboard or from it's Smartphone Application.
using System;                                 //For functions like Random number generator
using System.Net;                             //For http web request, ip address mthods
using System.Text;                            //For Encoding.UTF8.GetBytes method
using System.IO;                              //For StreamReader methods
using System.Threading;                       //For Thread methods like Sleep
using Microsoft.SPOT;                         //For Serial Debug method
using Microsoft.SPOT.Hardware;                //For input/Output functions like OutputPort
using SecretLabs.NETMF.Hardware.Netduino;     //For input/output functions like pin definition Pins.ONBOARD_LED
using Microsoft.SPOT.Net.NetworkInformation;  //for networkinterface and related methods


//Your project name should always match the below namespace name
namespace UbidotsIntervalUploading
{
    public class Program
    {
        public static void Main()
        {
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
            led.Write(true); // turn on the LED
            Thread.Sleep(1000); // sleep for 250ms
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 250ms
            led.Write(true); // turn on the LED
            Thread.Sleep(500); // sleep for 250ms
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 250ms
            Debug.Print("Ready to Run.....!");

            App app = new App();
            app.Run();

            while (app.IsRunning)
            {
                led.Write(true); // turn on the LED
                Thread.Sleep(250); // sleep for 250ms
                led.Write(false); // turn off the LED
                Thread.Sleep(250); // sleep for 250ms
            }

            while (app.ipCheck == false)
            {
                app.Run();
                Thread.Sleep(1000);
            }

            led.Write(false); // turn off the LED onboard the Netduino
            Debug.Print("Turn off the LED onboard the Netduino");

            while (true)
            {
                string deviceLabel = "netduino_smart_home";
                string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                ubidotsURL = ubidotsURL + deviceLabel + "/";

                string controlVariable1 = "relay1button";
                int dataReceived = app.ReceiveWebRequest(ubidotsURL, controlVariable1);
                Debug.Print("");
                Debug.Print("Data Received:- " + dataReceived);

                if (dataReceived == 1)
                {
                    Debug.Print("Turn ON the LED onboard the Netduino");
                    led.Write(true); // turn ON the LED onboard the Netduino
                }
                else if (dataReceived == 0)
                {
                    Debug.Print("Turn OFF the LED onboard the Netduino");
                    led.Write(false); // turn OFF the LED onboard the Netduino
                }

                Thread.Sleep(2500);
            }
        }

    }

    public class App
    {
        NetworkInterface[] _interfaces;


        //public bool IsRunning { get; set; }
        bool _IsRunning;
        public bool IsRunning
        {
            get { return _IsRunning; }
            set { _IsRunning = value; }
        }

        bool _ipCheck;
        public bool ipCheck
        {
            get { return _ipCheck; }
            set { _ipCheck = value; }
        }

        public void Run()
        {
            this.IsRunning = true;
            Debug.Print("Initializing the networks...");
            bool goodToGo = InitializeNetwork();
            this.ipCheck = goodToGo;

            if (goodToGo)
            {
                string deviceLabel = "netduino_smart_home";
                string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                ubidotsURL = ubidotsURL + deviceLabel + "/";
                MakeWebRequest(ubidotsURL);
            }

            this.IsRunning = false;
        }


        protected bool InitializeNetwork()
        {
            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                Debug.Print("Wireless tests run only on Device");
                return false;
            }

            Debug.Print("Getting all the network interfaces.");
            _interfaces = NetworkInterface.GetAllNetworkInterfaces();

            // debug output
            ListNetworkInterfaces();

            // loop through each network interface
            foreach (var net in _interfaces)
            {

                // debug out
                ListNetworkInfo(net);

                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;
                }

                // check for an IP address, try to get one if it's empty
                return CheckIPAddress(net);
            }

            // if we got here, should be false.
            return false;
        }

        public void UploadWebRequest(string url, string sensor1, int sensor1Data, string sensor2, int sensor2Data)
        {
            string payload = "{\"" + sensor1 + "\": " + sensor1Data + ",\"" + sensor2 + "\": " + sensor2Data + "}";

            Debug.Print("JSON String is " + payload);

            var request = (HttpWebRequest)WebRequest.Create(url);

            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }

        public int ReceiveWebRequest(string url, string controlVar)
        {
            string requestUrl = url + controlVar + "/" + "lv";
            Debug.Print("Making a Get Request to:- " + requestUrl);
            //"http://things.ubidots.com/api/v1.6/devices/testDevice/relay1button/lv";

            var request = (HttpWebRequest)WebRequest.Create(requestUrl);

            request.Method = "GET";
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");

            var httpResponse = (HttpWebResponse)request.GetResponse();
            int dataReceived = 0;
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                string resultData = result;
                Debug.Print("Relay Data:- " + resultData + " length:- " + resultData.Length);
                double temp = double.Parse(resultData);
                dataReceived = (int)temp;
            }

            return dataReceived;
        }

        public void MakeWebRequest(string url)
        {
            var value = 25;
            string sensor = "temperature";

            string payload = "{\"" + sensor + "\": " + value + "}";

            Debug.Print("JSON String is " + payload);

            //string payload = "{\"temperature\": 56, \"luminosity\": {\"value\":16}}";
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            //Creating a byte array for our payload for length calculation
            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream(); 
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }


        protected bool CheckIPAddress(NetworkInterface net)
        {
            int timeout = 10000; // timeout, in milliseconds to wait for an IP. 10,000 = 10 seconds

            // check to see if the IP address is empty (0.0.0.0). IPAddress.Any is 0.0.0.0.
            if (net.IPAddress == IPAddress.Any.ToString())
            {
                Debug.Print("No IP Address");

                if (net.IsDhcpEnabled)
                {
                    Debug.Print("DHCP is enabled, attempting to get an IP Address");

                    // ask for an IP address from DHCP [note this is a static, not sure which network interface it would act on]
                    int sleepInterval = 10;
                    int maxIntervalCount = timeout / sleepInterval;
                    int count = 0;
                    while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any && count < maxIntervalCount)
                    {
                        Debug.Print("Sleep while obtaining an IP");
                        Thread.Sleep(10);
                        count++;
                    };

                    // if we got here, we either timed out or got an address, so let's find out.
                    if (net.IPAddress == IPAddress.Any.ToString())
                    {
                        Debug.Print("Failed to get an IP Address in the alotted time.");
                        return false;
                    }

                    Debug.Print("Got IP Address: " + net.IPAddress.ToString());
                    return true;

                    //NOTE: this does not work, even though it's on the actual network device. [shrug]
                    // try to renew the DHCP lease and get a new IP Address
                    //net.RenewDhcpLease ();
                    //while (net.IPAddress == "0.0.0.0") {
                    //    Thread.Sleep (10);
                    //}

                }
                else
                {
                    Debug.Print("DHCP is not enabled, and no IP address is configured, bailing out.");
                    return false;
                }
            }
            else
            {
                Debug.Print("Already had IP Address: " + net.IPAddress.ToString());
                return true;
            }

        }

        protected void ListNetworkInterfaces()
        {
            foreach (var net in _interfaces)
            {
                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;

                }
            }
        }

        protected void ListNetworkInfo(NetworkInterface net)
        {
            Debug.Print("MAC Address: " + BytesToHexString(net.PhysicalAddress));
            Debug.Print("DHCP enabled: " + net.IsDhcpEnabled.ToString());
            Debug.Print("Dynamic DNS enabled: " + net.IsDynamicDnsEnabled.ToString());
            Debug.Print("IP Address: " + net.IPAddress.ToString());
            Debug.Print("Subnet Mask: " + net.SubnetMask.ToString());
            Debug.Print("Gateway: " + net.GatewayAddress.ToString());

            if (net is Wireless80211)
            {
                var wifi = net as Wireless80211;
                Debug.Print("SSID:" + wifi.Ssid.ToString());
            }

        }

        private static string BytesToHexString(byte[] bytes)
        {
            string hexString = string.Empty;

            // Create a character array for hexidecimal conversion.
            const string hexChars = "0123456789ABCDEF";

            // Loop through the bytes.
            for (byte b = 0; b < bytes.Length; b++)
            {
                if (b > 0)
                    hexString += "-";

                // Grab the top 4 bits and append the hex equivalent to the return string.        
                hexString += hexChars[bytes[b] >> 4];

                // Mask off the upper 4 bits to get the rest of it.
                hexString += hexChars[bytes[b] & 0x0F];
            }

            return hexString;
        }

    }

}

Relay Control using Netduino and Ubidots

C#
Controlling a relay connected to a digital pin of Netduino via Ubidots website or App.
using System;                                 //For functions like Random number generator
using System.Net;                             //For http web request, ip address mthods
using System.Text;                            //For Encoding.UTF8.GetBytes method
using System.IO;                              //For StreamReader methods
using System.Threading;                       //For Thread methods like Sleep
using Microsoft.SPOT;                         //For Serial Debug method
using Microsoft.SPOT.Hardware;                //For input/Output functions like OutputPort
using SecretLabs.NETMF.Hardware.Netduino;     //For input/output functions like pin definition Pins.ONBOARD_LED
using Microsoft.SPOT.Net.NetworkInformation;  //for networkinterface and related methods


//Your project name should always match the below namespace name
namespace UbidotsIntervalUploading
{
    public class Program
    {
        public static void Main()
        {
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
            OutputPort relay1 = new OutputPort(Pins.GPIO_PIN_D2, false);
            relay1.Write(false); // turn off the relay
            Debug.Print("Turning the Relay1 OFF Connected to Pin D2");

            //relay1.Write(true); // turn on the relay
            led.Write(true); // turn on the LED
            Thread.Sleep(1000); // sleep for 1000ms
            
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 250ms
            
            led.Write(true); // turn on the LED
            Thread.Sleep(1000); // sleep for 1000ms
            
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 1000ms

            Debug.Print("Ready to Run.....!");

            App app = new App();
            app.Run();

            while (app.IsRunning)
            {
                led.Write(true); // turn on the LED
                Thread.Sleep(250); // sleep for 250ms
                led.Write(false); // turn off the LED
                Thread.Sleep(250); // sleep for 250ms
            }

            while (app.ipCheck == false)
            {
                app.Run();
                Thread.Sleep(1000);
            }

            //led.Write(false); // turn off the LED onboard the Netduino
            //Debug.Print("Turn off the LED onboard the Netduino");

            while (true)
            {
                string deviceLabel = "netduino_smart_home";
                string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                ubidotsURL = ubidotsURL + deviceLabel + "/";

                string controlVariable1 = "relay1button";
                int dataReceived = app.ReceiveWebRequest(ubidotsURL, controlVariable1);
                Debug.Print("");
                Debug.Print("Data Received:- " + dataReceived);

                if (dataReceived == 1)
                {
                    relay1.Write(true); // turn on the relay
                    Debug.Print("Turning the Relay1 ON Connected to Pin D2");
                }
                else if (dataReceived == 0)
                {
                    relay1.Write(false); // turn off the relay
                    Debug.Print("Turning the Relay1 OFF Connected to Pin D2");
                }

                Thread.Sleep(2500);
            }
        }

    }

    public class App
    {
        NetworkInterface[] _interfaces;


        //public bool IsRunning { get; set; }
        bool _IsRunning;
        public bool IsRunning
        {
            get { return _IsRunning; }
            set { _IsRunning = value; }
        }

        bool _ipCheck;
        public bool ipCheck
        {
            get { return _ipCheck; }
            set { _ipCheck = value; }
        }

        public void Run()
        {
            this.IsRunning = true;
            Debug.Print("Initializing the networks...");
            bool goodToGo = InitializeNetwork();
            this.ipCheck = goodToGo;

            if (goodToGo)
            {
                string deviceLabel = "netduino_smart_home";
                string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                ubidotsURL = ubidotsURL + deviceLabel + "/";
                MakeWebRequest(ubidotsURL);
            }

            this.IsRunning = false;
        }


        protected bool InitializeNetwork()
        {
            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                Debug.Print("Wireless tests run only on Device");
                return false;
            }

            Debug.Print("Getting all the network interfaces.");
            _interfaces = NetworkInterface.GetAllNetworkInterfaces();

            // debug output
            ListNetworkInterfaces();

            // loop through each network interface
            foreach (var net in _interfaces)
            {

                // debug out
                ListNetworkInfo(net);

                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;
                }

                // check for an IP address, try to get one if it's empty
                return CheckIPAddress(net);
            }

            // if we got here, should be false.
            return false;
        }

        public void UploadWebRequest(string url, string sensor1, int sensor1Data, string sensor2, int sensor2Data)
        {
            string payload = "{\"" + sensor1 + "\": " + sensor1Data + ",\"" + sensor2 + "\": " + sensor2Data + "}";

            Debug.Print("JSON String is " + payload);

            var request = (HttpWebRequest)WebRequest.Create(url);

            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }

        public int ReceiveWebRequest(string url, string controlVar)
        {
            string requestUrl = url + controlVar + "/" + "lv";
            Debug.Print("Making a Get Request to:- " + requestUrl);
            //"http://things.ubidots.com/api/v1.6/devices/testDevice/relay1button/lv";

            var request = (HttpWebRequest)WebRequest.Create(requestUrl);

            request.Method = "GET";
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");

            var httpResponse = (HttpWebResponse)request.GetResponse();
            int dataReceived = 0;
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                string resultData = result;
                Debug.Print("Relay Data:- " + resultData + " length:- " + resultData.Length);
                double temp = double.Parse(resultData);
                dataReceived = (int)temp;
            }

            return dataReceived;
        }

        public void MakeWebRequest(string url)
        {
            var value = 25;
            string sensor = "temperature";

            string payload = "{\"" + sensor + "\": " + value + "}";

            Debug.Print("JSON String is " + payload);

            //string payload = "{\"temperature\": 56, \"luminosity\": {\"value\":16}}";
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            //Creating a byte array for our payload for length calculation
            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream(); 
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }


        protected bool CheckIPAddress(NetworkInterface net)
        {
            int timeout = 10000; // timeout, in milliseconds to wait for an IP. 10,000 = 10 seconds

            // check to see if the IP address is empty (0.0.0.0). IPAddress.Any is 0.0.0.0.
            if (net.IPAddress == IPAddress.Any.ToString())
            {
                Debug.Print("No IP Address");

                if (net.IsDhcpEnabled)
                {
                    Debug.Print("DHCP is enabled, attempting to get an IP Address");

                    // ask for an IP address from DHCP [note this is a static, not sure which network interface it would act on]
                    int sleepInterval = 10;
                    int maxIntervalCount = timeout / sleepInterval;
                    int count = 0;
                    while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any && count < maxIntervalCount)
                    {
                        Debug.Print("Sleep while obtaining an IP");
                        Thread.Sleep(10);
                        count++;
                    };

                    // if we got here, we either timed out or got an address, so let's find out.
                    if (net.IPAddress == IPAddress.Any.ToString())
                    {
                        Debug.Print("Failed to get an IP Address in the alotted time.");
                        return false;
                    }

                    Debug.Print("Got IP Address: " + net.IPAddress.ToString());
                    return true;

                    //NOTE: this does not work, even though it's on the actual network device. [shrug]
                    // try to renew the DHCP lease and get a new IP Address
                    //net.RenewDhcpLease ();
                    //while (net.IPAddress == "0.0.0.0") {
                    //    Thread.Sleep (10);
                    //}

                }
                else
                {
                    Debug.Print("DHCP is not enabled, and no IP address is configured, bailing out.");
                    return false;
                }
            }
            else
            {
                Debug.Print("Already had IP Address: " + net.IPAddress.ToString());
                return true;
            }

        }

        protected void ListNetworkInterfaces()
        {
            foreach (var net in _interfaces)
            {
                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;

                }
            }
        }

        protected void ListNetworkInfo(NetworkInterface net)
        {
            Debug.Print("MAC Address: " + BytesToHexString(net.PhysicalAddress));
            Debug.Print("DHCP enabled: " + net.IsDhcpEnabled.ToString());
            Debug.Print("Dynamic DNS enabled: " + net.IsDynamicDnsEnabled.ToString());
            Debug.Print("IP Address: " + net.IPAddress.ToString());
            Debug.Print("Subnet Mask: " + net.SubnetMask.ToString());
            Debug.Print("Gateway: " + net.GatewayAddress.ToString());

            if (net is Wireless80211)
            {
                var wifi = net as Wireless80211;
                Debug.Print("SSID:" + wifi.Ssid.ToString());
            }

        }

        private static string BytesToHexString(byte[] bytes)
        {
            string hexString = string.Empty;

            // Create a character array for hexidecimal conversion.
            const string hexChars = "0123456789ABCDEF";

            // Loop through the bytes.
            for (byte b = 0; b < bytes.Length; b++)
            {
                if (b > 0)
                    hexString += "-";

                // Grab the top 4 bits and append the hex equivalent to the return string.        
                hexString += hexChars[bytes[b] >> 4];

                // Mask off the upper 4 bits to get the rest of it.
                hexString += hexChars[bytes[b] & 0x0F];
            }

            return hexString;
        }

    }

}

LDR and Air Quality Sensor Analog Read Netduino

C#
Reading the analog sensor connected via the Grove base shield i.e Grove LDR Light Sensor and Grove Air Quality Sensor.
using System.Threading;
using Microsoft.SPOT;
using SecretLabs.NETMF.Hardware.Netduino;

namespace NetduinoAnalogExample
{
    public class Program
    {
        public static void Main()
        {
            // write your code here
            var ldrSensor = new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A0);

            var airQualitySensor = new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A1);
            //ldrSensor.SetRange(0, 100);

            while (true)
            {
                int ldrValue = ldrSensor.Read();
                int ldrMax = 670;
                int ldrMin = 0;

                Debug.Print("LDR Sensor Reading: " + ldrValue.ToString());

                int ldrPercent = analogMap(ldrValue, ldrMin, ldrMax, 0, 100);

                Debug.Print("LDR Sensor Percent: " + ldrPercent.ToString());
                
                int airQualityValue = airQualitySensor.Read();

                Debug.Print("Air Quality Sensor Reading: " + airQualityValue.ToString());

                if (airQualityValue > 700)
                {
                    Debug.Print("High Air Pollution");
                }
                else if ((airQualityValue > 300) && (airQualityValue < 700))
                {
                    Debug.Print("Low Air Pollution");
                }
                else
                {
                    Debug.Print("Air is Fresh!!");
                }

                Debug.Print("");
                Debug.Print("");

                Thread.Sleep(2500);
            }
        }


        static int analogMap(int x, int in_min, int in_max, int out_min, int out_max)
        {
            /* Map an analog value (i.e variable x which has current values from in_min to in_max) to a specific range (from out_min to out_max) */
            return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
        }
    }
}

Final Code for Smart Home Project

C#
Reading and Uploading Analog Sensor's reading like Light Intensity and Air Quality as well as controlling the relay via Ubidots Website or App.
using System;                                 //For functions like Random number generator
using System.Net;                             //For http web request, ip address mthods
using System.Text;                            //For Encoding.UTF8.GetBytes method
using System.IO;                              //For StreamReader methods
using System.Threading;                       //For Thread methods like Sleep
using Microsoft.SPOT;                         //For Serial Debug method
using Microsoft.SPOT.Hardware;                //For input/Output functions like OutputPort
using SecretLabs.NETMF.Hardware.Netduino;     //For input/output functions like pin definition Pins.ONBOARD_LED
using Microsoft.SPOT.Net.NetworkInformation;  //for networkinterface and related methods


//Your project name should always match the below namespace name
namespace UbidotsIntervalUploading
{
    public class Program
    {
        static int analogMap(int x, int in_min, int in_max, int out_min, int out_max)
        {
            /* Map an analog value (i.e variable x which has current values from in_min to in_max) to a specific range (from out_min to out_max) */
            return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
        }
        
        public static void Main()
        {
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
            OutputPort relay1 = new OutputPort(Pins.GPIO_PIN_D2, false);
            relay1.Write(false); // turn off the relay
            Debug.Print("Turning the Relay1 OFF Connected to Pin D2");

            var ldrSensor = new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A0);
            var airQualitySensor = new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A1);

            //relay1.Write(true); // turn on the relay
            led.Write(true); // turn on the LED
            Thread.Sleep(1000); // sleep for 1000ms
            
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 250ms
            
            led.Write(true); // turn on the LED
            Thread.Sleep(1000); // sleep for 1000ms
            
            led.Write(false); // turn off the LED
            Thread.Sleep(1000); // sleep for 1000ms

            Debug.Print("Ready to Run.....!");

            App app = new App();
            app.Run();

            while (app.IsRunning)
            {
                led.Write(true); // turn on the LED
                Thread.Sleep(250); // sleep for 250ms
                led.Write(false); // turn off the LED
                Thread.Sleep(250); // sleep for 250ms
            }

            while (app.ipCheck == false)
            {
                app.Run();
                Thread.Sleep(1000);
            }

            //led.Write(false); // turn off the LED onboard the Netduino
            //Debug.Print("Turn off the LED onboard the Netduino");

            while (true)
            {
                string deviceLabel = "netduino_smart_home";
                string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                ubidotsURL = ubidotsURL + deviceLabel + "/";
                //app.MakeWebRequest(ubidotsURL);

                int ldrValue = ldrSensor.Read();
                int ldrMax = 670;
                int ldrMin = 0;
                Debug.Print("LDR Sensor Reading: " + ldrValue.ToString());
                int ldrPercent = analogMap(ldrValue, ldrMin, ldrMax, 0, 100);
                Debug.Print("LDR Sensor Percent: " + ldrPercent.ToString());

                int airQualityValue = airQualitySensor.Read();
                Debug.Print("Air Quality Sensor Reading: " + airQualityValue.ToString());
                if (airQualityValue > 700)
                {
                    Debug.Print("High Air Pollution");
                }
                else if ((airQualityValue > 300) && (airQualityValue < 700))
                {
                    Debug.Print("Low Air Pollution");
                }
                else
                {
                    Debug.Print("Air is Fresh!!");
                }

                string sensor1Label = "lightLevel";
                int sensor1Data = ldrPercent;
                string sensor2Label = "airQuality";
                int sensor2Data = airQualityValue;
                app.UploadWebRequest(ubidotsURL, sensor1Label, sensor1Data, sensor2Label, sensor2Data);

                string controlVariable1 = "relay1button";
                int dataReceived = app.ReceiveWebRequest(ubidotsURL, controlVariable1);
                Debug.Print("");
                Debug.Print("Data Received:- " + dataReceived);

                if (dataReceived == 1)
                {
                    relay1.Write(true); // turn on the relay
                    Debug.Print("Turning the Relay1 ON Connected to Pin D2");
                }
                else if (dataReceived == 0)
                {
                    relay1.Write(false); // turn off the relay
                    Debug.Print("Turning the Relay1 OFF Connected to Pin D2");
                }

                Thread.Sleep(2500);
            }
        }

    }

    public class App
    {
        NetworkInterface[] _interfaces;


        //public bool IsRunning { get; set; }
        bool _IsRunning;
        public bool IsRunning
        {
            get { return _IsRunning; }
            set { _IsRunning = value; }
        }

        bool _ipCheck;
        public bool ipCheck
        {
            get { return _ipCheck; }
            set { _ipCheck = value; }
        }

        public void Run()
        {
            this.IsRunning = true;
            Debug.Print("Initializing the networks...");
            bool goodToGo = InitializeNetwork();
            this.ipCheck = goodToGo;

            if (goodToGo)
            {
                Debug.Print("The Netowrk Connection is good to go!");
                //string deviceLabel = "netduino_smart_home";
                //string ubidotsURL = "http://things.ubidots.com/api/v1.6/devices/";
                //ubidotsURL = ubidotsURL + deviceLabel + "/";
                //MakeWebRequest(ubidotsURL);
            }

            this.IsRunning = false;
        }


        protected bool InitializeNetwork()
        {
            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                Debug.Print("Wireless tests run only on Device");
                return false;
            }

            Debug.Print("Getting all the network interfaces.");
            _interfaces = NetworkInterface.GetAllNetworkInterfaces();

            // debug output
            ListNetworkInterfaces();

            // loop through each network interface
            foreach (var net in _interfaces)
            {

                // debug out
                ListNetworkInfo(net);

                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;
                }

                // check for an IP address, try to get one if it's empty
                return CheckIPAddress(net);
            }

            // if we got here, should be false.
            return false;
        }

        public void UploadWebRequest(string url, string sensor1, int sensor1Data, string sensor2, int sensor2Data)
        {
            string payload = "{\"" + sensor1 + "\": " + sensor1Data + ",\"" + sensor2 + "\": " + sensor2Data + "}";

            Debug.Print("JSON String is " + payload);

            var request = (HttpWebRequest)WebRequest.Create(url);

            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }

        public int ReceiveWebRequest(string url, string controlVar)
        {
            string requestUrl = url + controlVar + "/" + "lv";
            Debug.Print("Making a Get Request to:- " + requestUrl);
            //"http://things.ubidots.com/api/v1.6/devices/testDevice/relay1button/lv";

            var request = (HttpWebRequest)WebRequest.Create(requestUrl);

            request.Method = "GET";
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");

            var httpResponse = (HttpWebResponse)request.GetResponse();
            int dataReceived = 0;
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                string resultData = result;
                Debug.Print("Relay Data:- " + resultData + " length:- " + resultData.Length);
                double temp = double.Parse(resultData);
                dataReceived = (int)temp;
            }

            return dataReceived;
        }

        public void MakeWebRequest(string url)
        {
            var value = 25;
            string sensor = "temperature";

            string payload = "{\"" + sensor + "\": " + value + "}";

            Debug.Print("JSON String is " + payload);

            //string payload = "{\"temperature\": 56, \"luminosity\": {\"value\":16}}";
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            //Creating a byte array for our payload for length calculation
            byte[] byteArray = Encoding.UTF8.GetBytes(payload);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            request.Headers.Add("x-auth-token", "A1E-4gstNUeAYFJ0oPFfSZuPnNbjcPkDcO");
            Stream dataStream = request.GetRequestStream(); 
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                //Debug.Print("This is what we got from " + url + ": " + result);
                Debug.Print("Response:- " + result);
            }

        }


        protected bool CheckIPAddress(NetworkInterface net)
        {
            int timeout = 10000; // timeout, in milliseconds to wait for an IP. 10,000 = 10 seconds

            // check to see if the IP address is empty (0.0.0.0). IPAddress.Any is 0.0.0.0.
            if (net.IPAddress == IPAddress.Any.ToString())
            {
                Debug.Print("No IP Address");

                if (net.IsDhcpEnabled)
                {
                    Debug.Print("DHCP is enabled, attempting to get an IP Address");

                    // ask for an IP address from DHCP [note this is a static, not sure which network interface it would act on]
                    int sleepInterval = 10;
                    int maxIntervalCount = timeout / sleepInterval;
                    int count = 0;
                    while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any && count < maxIntervalCount)
                    {
                        Debug.Print("Sleep while obtaining an IP");
                        Thread.Sleep(10);
                        count++;
                    };

                    // if we got here, we either timed out or got an address, so let's find out.
                    if (net.IPAddress == IPAddress.Any.ToString())
                    {
                        Debug.Print("Failed to get an IP Address in the alotted time.");
                        return false;
                    }

                    Debug.Print("Got IP Address: " + net.IPAddress.ToString());
                    return true;

                    //NOTE: this does not work, even though it's on the actual network device. [shrug]
                    // try to renew the DHCP lease and get a new IP Address
                    //net.RenewDhcpLease ();
                    //while (net.IPAddress == "0.0.0.0") {
                    //    Thread.Sleep (10);
                    //}

                }
                else
                {
                    Debug.Print("DHCP is not enabled, and no IP address is configured, bailing out.");
                    return false;
                }
            }
            else
            {
                Debug.Print("Already had IP Address: " + net.IPAddress.ToString());
                return true;
            }

        }

        protected void ListNetworkInterfaces()
        {
            foreach (var net in _interfaces)
            {
                switch (net.NetworkInterfaceType)
                {
                    case (NetworkInterfaceType.Ethernet):
                        Debug.Print("Found Ethernet Interface");
                        break;
                    case (NetworkInterfaceType.Wireless80211):
                        Debug.Print("Found 802.11 WiFi Interface");
                        break;
                    case (NetworkInterfaceType.Unknown):
                        Debug.Print("Found Unknown Interface");
                        break;

                }
            }
        }

        protected void ListNetworkInfo(NetworkInterface net)
        {
            Debug.Print("MAC Address: " + BytesToHexString(net.PhysicalAddress));
            Debug.Print("DHCP enabled: " + net.IsDhcpEnabled.ToString());
            Debug.Print("Dynamic DNS enabled: " + net.IsDynamicDnsEnabled.ToString());
            Debug.Print("IP Address: " + net.IPAddress.ToString());
            Debug.Print("Subnet Mask: " + net.SubnetMask.ToString());
            Debug.Print("Gateway: " + net.GatewayAddress.ToString());

            if (net is Wireless80211)
            {
                var wifi = net as Wireless80211;
                Debug.Print("SSID:" + wifi.Ssid.ToString());
            }

        }

        private static string BytesToHexString(byte[] bytes)
        {
            string hexString = string.Empty;

            // Create a character array for hexidecimal conversion.
            const string hexChars = "0123456789ABCDEF";

            // Loop through the bytes.
            for (byte b = 0; b < bytes.Length; b++)
            {
                if (b > 0)
                    hexString += "-";

                // Grab the top 4 bits and append the hex equivalent to the return string.        
                hexString += hexChars[bytes[b] >> 4];

                // Mask off the upper 4 bits to get the rest of it.
                hexString += hexChars[bytes[b] & 0x0F];
            }

            return hexString;
        }

    }

}

Credits

Amol Disale

Amol Disale

9 projects • 100 followers
I am passionate about the idea of open-source hardware and software. I am ready to help in prototyping IoT, Smart Home, and other products.
Thanks to Brijesh Singh.

Comments