Sincronizar la hora de tu netduino


Este utilidad  para nuestro Netduino    toma el dato fecha-hora(datetime)   de un servidor  NTP
El código se basa  en http://weblogs.asp.net/mschwarz/archive/2008/03/09/wrong-datetime-on-net-micro-framework-devices.aspx
Código para Netduino-Plus:

using
 System;
02 using Microsoft.SPOT;
03 using System.Net.Sockets;
04 using System.Net;
05 using Microsoft.SPOT.Hardware;
06 using SecretLabs.NETMF.Hardware;
07 using SecretLabs.NETMF.Hardware.Netduino;
08 using Microsoft.SPOT.Time;
09
10 namespace NetduinoPlusWebServer
11 {
12     class TimeHandeler
13     {
14  
19         /// <param name="TimeServer">Timeserver</param>
20         /// <returns>Local NTP Time</returns>
21         public static DateTime NTPTime(String TimeServer)
22         {
23             // Find endpoint for timeserver
24             IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
25
26             // Connect to timeserver
27             Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
28             s.Connect(ep);
29
30             // Make send/receive buffer
31             byte[] ntpData = new byte[48];
32             Array.Clear(ntpData, 0, 48);
33
34             // Set protocol version
35             ntpData[0] = 0x1B;
36
37             // Send Request
38             s.Send(ntpData);
39
40             // Receive Time
41             s.Receive(ntpData);
42
43             byte offsetTransmitTime = 40;
44
45             ulong intpart = 0;
46             ulong fractpart = 0;
47
48             for (int i = 0; i <= 3; i++)
49                 intpart = (intpart <<  8 ) | ntpData[offsetTransmitTime + i];
50
51             for (int i = 4; i <= 7; i++)
52                 fractpart = (fractpart <<  8 ) | ntpData[offsetTransmitTime + i];
53
54             ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
55
56             s.Close();
57
58             TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
59             DateTime dateTime = new DateTime(1900, 1, 1);
60             dateTime += timeSpan;
61
62             TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
63             DateTime networkDateTime = (dateTime + offsetAmount);
64
65             return networkDateTime;
66         }
67
68     }
69 }

Primeros Pasos con Netduino como webserber


En estas lineas vamos a mostrar cómo crear un pequeños servidor web, que ejecutaremos en nuestro Netduino (+). El servidor web debe responder ante cada petición HTTP con un «Hola Mundo».

Empezamos creando un nuevo proyecto de tipo Netduino Plus en nuestro Visual Studio–> Botón derecho sobre el proyecto y elige «Añadir nuevo elemento». –>Añade una nueva clase llamada WebServer.cs.
Aquí presentamos una versión muy simple de nuestro servidor web  que se mantiene a la escucha, atendiendo las peticiones, y respondiendo «Hola Mundo» mientras hace parpadear el led de nuestro Netduino Plus.
public class WebServer : IDisposable
{
   private Socket socket = null;
   private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
   public WebServer()
  {
       //Inicializamos el socket
       socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       //Conectamos el socket
       socket.Bind(new IPEndPoint(IPAddress.Any, 80));
      //Iniciamos la escucha
      socket.Listen(10);
      ListenForRequest();
 }
 public void ListenForRequest()
{
  while (true)
  {
     using (Socket clientSocket = socket.Accept())
     {
       //Aceptamos el cliente
       IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
       EndPoint clientEndPoint = clientSocket.RemoteEndPoint;
       int bytesReceived = clientSocket.Available;
       if (bytesReceived > 0)
      {
           //Obtenemos la petición
           byte[] buffer = new byte[bytesReceived];
           int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
           string request = new string(Encoding.UTF8.GetChars(buffer));
           Debug.Print(request);
         //Componemos la respuesta (Nota 1)
           string response = «Hola Mundo»;
           string header = «HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: » + response.Length.ToString() + «\r\nConnection: close\r\n\r\n»;
           clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
           clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
           //Parpadeo del led
           led.Write(true);
           Thread.Sleep(150);
           led.Write(false);
      }
    }
  }
}
#region IDisposable Members
~WebServer()
{
      Dispose();
}
public void Dispose()
{
     if (socket != null)
        socket.Close();
}
#endregion
}
El siguiente paso es añadir el siguiente código para iniciar el servidor web.
public static void Main()
{
    Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableDhcp();
    WebServer webServer = new WebServer();
    webServer.ListenForRequest();
}
En el siguiente paso, tenemos que desplegar el código en nuestro Netduino haciendo click en las propiedades del proyecto.
Una vez cambiadas las propiedades del proyecto, seleccionamos la pestaña «.Net Micro Framework» y cambiamos las siguientes propiedades:
Transport: USB
Device: NetduinoPlus_NetduinoPlus
Ahora solo nos queda pulsar F5 para pasar nuestro código a Netduino ,esperar unos inst asegurando que  nuestro Netduino-plus esta conectado a internet   realizamos la siguiente petición mediante nuestro navegador.
http://192.168.1.2/ ( o la ip que le haya asignado nuestro router a nuestro netduino)