Hi Anshul
I think it would be easier if the code you posted could be compiled, I think it is missing some significant bits.
If you are writing a web server why dont you start with somebody elses code as a base, or look at the way they have approached it.
try http://forums.netdui...ted-web-server/
or http://forums.netdui...nmikawebserver/
Make sure to set any borrowed projects to the appropriate firmware version.
If you are listening to a socket and your ethernet cable is unplugged, an exception is thrown.
If you catch it you will know that you have some sort of network error.
Sorry, I thought I would just post the relevant bits, but here's the full code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
namespace IRSensor_LightControl
{
public class Program
{
//servers that perform the X10/lighting operations
public static string IPAddressAVSAGER = "192.168.1.102";
public static string IPAddressAnshulNB = "192.168.1.101";
//Default Active IP
public static string ActiveIP = IPAddressAnshulNB;
//IO
private static InputPort irSensor = new InputPort(Pins.GPIO_PIN_D9, false, ResistorModes.Disabled); //IR Sensor
//private static AnalogInput pot = new AnalogInput(Pins.GPIO_PIN_A0); //Wait Time Pot
private static InputPort pushButton = new InputPort(Pins.GPIO_PIN_D8, true, ResistorModes.Disabled); //Push button to toggle online/offline
private static InputPort computerSwitch = new InputPort(Pins.GPIO_PIN_D10, false, ResistorModes.Disabled); //computer selector : 1=AVSAGER, 0=AnshulNB
private static OutputPort onBoardLed = new OutputPort(Pins.ONBOARD_LED, false);
private static OutputPort greenLed = new OutputPort(Pins.GPIO_PIN_D0, false);
private static OutputPort redLed = new OutputPort(Pins.GPIO_PIN_D1, false);
private static OutputPort buzzer = new OutputPort(Pins.GPIO_PIN_D2, false);
//HTTP
private static HttpWebResponse HttpWResponse; //request object
private static HttpWebRequest HttpWRequest; //response object
//whether or not the Netduino should send signals to the server
//if false, it just blinks the greenled
private static bool online = true;
//is the light currently on
private static bool lightOn = false;
//has the light status been set yet
private static bool lightStatusSet = false;
//time to wait until turn off signal is sent in ms
private static int motionWaitTime = 300000;
//http request timeout time
private static int webRequestTimeOut = 15000;
public static void Main()
{
//initialize flags and variables
bool status;
bool lastStatus = false;
bool statusSet = false;
DateTime waitTime = DateTime.Now;
//initalize debugging parameters
DateTime startTime = new DateTime();
DateTime endtime = new DateTime();
//start looping execution
while (true)
{
//get active ip from switch
ActiveIP = computerSwitch.Read() ? IPAddressAVSAGER : IPAddressAnshulNB;
//if online, set blue led to on
onBoardLed.Write(online);
//check for online toggle button press
if (pushButton.Read())
online = !online;
//set motionWaitTime -- FIX
//motionWaitTime = (pot.Read() + 1024) * ;
//set status
status = irSensor.Read();
Debug.Print(irSensor.Read().ToString());
//if there is at least one status to compare to - so it doesn't try to compare to last status on first run
if (statusSet)
{
//did the status change? if so..
if (status != lastStatus)
{
//if its high now and was low before, means it just activated -- send 'on' signal and start the timer
if (status)
{
TurnOnLight();
waitTime = DateTime.Now;
startTime = DateTime.Now;
}
//if its low now and was high before, stop the timer, means is just deactivated
//write out the duration of activation
if (!status)
{
waitTime = DateTime.Now;
endtime = DateTime.Now;
TimeSpan duration = endtime.Subtract(startTime);
Debug.Print("============ Motion detected for a duration of " + (duration.Seconds * 1000 + duration.Milliseconds) +
" ms ============");
//Thread.Sleep(2000); -- to have time to look at the duration in the debug screen
}
}
//if status did not change, if motionWaitTime amount of milliseconds have elapsed, turn the light off, if not, keep looping
else
{
Debug.Print((DateTime.Now.Subtract(waitTime).Minutes * 60000 + DateTime.Now.Subtract(waitTime).Seconds * 1000 + DateTime.Now.Subtract(waitTime).Milliseconds).ToString());
if (!status)
{
if ((DateTime.Now.Subtract(waitTime).Minutes * 60000 + DateTime.Now.Subtract(waitTime).Seconds * 1000 + DateTime.Now.Subtract(waitTime).Milliseconds) > motionWaitTime)
{
if (lightOn || (!lightStatusSet))
{
Debug.Print("======================================");
Debug.Print("Turning off lights.");
Debug.Print("======================================");
TurnOffLight();
waitTime = DateTime.Now;
lightOn = false;
}
}
}
}
}
//save status
lastStatus = status;
//store save status flag
statusSet = true;
}
}
public static void BlinkLED(OutputPort led, int period)
{
led.Write(!led.Read());
Thread.Sleep(period);
led.Write(!led.Read());
Thread.Sleep(period);
led.Write(!led.Read());
Thread.Sleep(period);
led.Write(!led.Read());
}
public static void Fader(int samplingPeriod, OutputPort obLed)
{
var fader_start_time = DateTime.Now;
long fader_length = samplingPeriod;
double interval_low = 10;
double interval_high = 500;
int interval = (int)interval_high; //stores the interval between blinks, starts with the longest interval
while (DateTime.Now.CompareTo(fader_start_time.AddMilliseconds(fader_length)) < 0)
{
obLed.Write(true);
Thread.Sleep(interval);
//interval = (interval_low - interval_high)/(fader_length)*(DateTime.Now - fader_start_time).Milliseconds + interval_high;
double x = (DateTime.Now - fader_start_time).Milliseconds + (DateTime.Now - fader_start_time).Seconds * 1000;
double y = ((interval_low - interval_high) / fader_length) * x + interval_high;
interval = (int)y;
interval = System.Math.Max(interval, 0);
obLed.Write(false);
Thread.Sleep(interval);
//interval = (interval_low - interval_high) / (fader_length) * (DateTime.Now - fader_start_time).Milliseconds + interval_high;
x = (DateTime.Now - fader_start_time).Milliseconds + (DateTime.Now - fader_start_time).Seconds * 1000;
y = ((interval_low - interval_high) / fader_length) * x + interval_high;
interval = (int)y;
interval = System.Math.Max(interval, 0);
}
}
//public static void TurnOnLight()
//{
// led.Write(true);
//}
//public static void TurnOffLight()
//{
// led.Write(false);
//}
public static void TurnOnLight()
{
Uri URL = new Uri("http://" + ActiveIP + "/ASPXNetduinoServerOnPC2/TurnOnLight.aspx");
HttpWRequest = (HttpWebRequest)WebRequest.Create(URL);
// set the name of the user agent. This is the client name that is passed to IIS
HttpWRequest.UserAgent = "CSharp HTTP Sample";
// set the connection keep-alive
HttpWRequest.KeepAlive = true; //this is the default
//we don't want caching to take place so we need
// to set the pragma header to say we don't want caching
HttpWRequest.Headers.Set("Pragma", "no-cache");
//set the request timeout to 5 min.
HttpWRequest.Timeout = webRequestTimeOut;
// set the request method
HttpWRequest.Method = "GET";
//if online, send signal
if (online)
{
Thread webRequestThread = new Thread(new ThreadStart(WebRequestMethod)); //create new thread to perform web request
DateTime webThreadStartTime = DateTime.Now; //start timer
try
{
webRequestThread.Start();
webRequestThread.Join(webRequestTimeOut);
//webRequestThread.Start(); //start thread
}
catch (Exception ex)
{
//indicate failure if exception
BlinkLED(redLed, 250);
greenLed.Write(false);
redLed.Write(true);
}
//bool responseReceived = false;
//wait until web request times out or webrequest object is assigned a value which means the request went there and back
/*while (DateTime.Now.Subtract(webThreadStartTime).Seconds * 1000 + DateTime.Now.Subtract(webThreadStartTime).Milliseconds < webRequestTimeOut)
{
//check to see if web response has been received, if so, break out of loop, if not
if (HttpWResponse != null)
{
responseReceived = true;
break;
}
}
*/
//if no response was received
if (HttpWResponse == null)
{
//abort web request thread
//webRequestThread.Abort();
//indicate failure
BlinkLED(redLed, 250);
greenLed.Write(false);
redLed.Write(true);
}
else
{
//join the thread
//webRequestThread.Join();
//if http response was 200:OK, indicate success)
if (HttpWResponse.StatusCode == HttpStatusCode.OK)
{
BlinkLED(greenLed, 250);
redLed.Write(false);
greenLed.Write(true);
//set internal light statuses
lightOn = true;
lightStatusSet = true;
}
//else indicate failure
else
{
BlinkLED(redLed, 250);
greenLed.Write(false);
redLed.Write(true);
}
}
//empty the web respose object for next iteration
HttpWResponse = null;
}
//if not online, blink greenLed so show "success"
else
{
BlinkLED(greenLed, 250);
greenLed.Write(true);
}
}
public static void TurnOffLight()
{
Uri URL = new Uri("http://" + ActiveIP + "/ASPXNetduinoServerOnPC2/TurnOffLight.aspx");
HttpWRequest = (HttpWebRequest)WebRequest.Create(URL);
// set the name of the user agent. This is the client name that is passed to IIS
HttpWRequest.UserAgent = "CSharp HTTP Sample";
// set the connection keep-alive
HttpWRequest.KeepAlive = true; //this is the default
//we don't want caching to take place so we need
// to set the pragma header to say we don't want caching
HttpWRequest.Headers.Set("Pragma", "no-cache");
//set the request timeout to 30 secs.
HttpWRequest.Timeout = webRequestTimeOut;
// set the request method
HttpWRequest.Method = "GET";
//if online, send signal
if (online)
{
Thread webRequestThread = new Thread(new ThreadStart(WebRequestMethod)); //create new thread to perform web request
DateTime webThreadStartTime = DateTime.Now; //start timer
try
{
webRequestThread.Start();
webRequestThread.Join(webRequestTimeOut);
//webRequestThread.Start(); //start thread
}
catch (Exception ex)
{
//indicate failure if exception
BlinkLED(redLed, 250);
greenLed.Write(false);
redLed.Write(true);
}
//bool responseReceived = false;
//wait until web request times out or webrequest object is assigned a value which means the request went there and back
/*while (DateTime.Now.Subtract(webThreadStartTime).Seconds * 1000 + DateTime.Now.Subtract(webThreadStartTime).Milliseconds < webRequestTimeOut)
{
//check to see if web response has been received, if so, break out of loop, if not
if (HttpWResponse != null)
{
responseReceived = true;
break;
}
}*/
if (HttpWResponse == null)
{
//abort web request thread
//webRequestThread.Abort();
//indicate failure
BlinkLED(redLed, 250);
greenLed.Write(false);
redLed.Write(true);
}
else
{
//join the thread
//webRequestThread.Join();
//if http response was 200:OK, indicate success)
if (HttpWResponse.StatusCode == HttpStatusCode.OK)
{
BlinkLED(greenLed, 250);
redLed.Write(false);
greenLed.Write(true);
//set internal light statuses
lightOn = false;
lightStatusSet = true;
}
//else indicate failure
else
{
BlinkLED(redLed, 250);
greenLed.Write(false);
redLed.Write(true);
}
}
//empty the web response
HttpWResponse = null;
}
//if not online, turn off greenLed so show "success"
else
{
BlinkLED(greenLed, 250);
greenLed.Write(false);
}
}
public static void WebRequestMethod()
{
try
{
HttpWResponse = (HttpWebResponse)(((WebRequest)HttpWRequest).GetResponse());
}
catch (Exception ex)
{
//indicate failure
greenLed.Write(false);
redLed.Write(true);
}
}
}
}
Yeah I see what you're saying about the sockets and the servers, but I'm not using the sockets layer, I'm just using the HttpWebRequest object. And I'm actually programming a HTTP client on the Netduino Plus, I'm using IIS as the server on my Windows PC. The Netduino is supposed to send a HTTP Web Request to the IIS Server on my Windows machine and IIS responds accordingly. This works perfectly when the ethernet cable is connected to the Netduino+. But when the ethernet cable is disconnected, it just gets stuck at the HttpWRequest.GetResponse() method, EVEN when I'm running this method on a separate thread, as in the code. I'd appreciate any tips. Thanks for your help