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;
using Microsoft.SPOT;

 

using System.Net.Sockets;

 

using System.Net;

 

using Microsoft.SPOT.Hardware;

 

using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
using Microsoft.SPOT.Time;

 

namespace NetduinoPlusWebServer

 

{

 

    class TimeHandeler

 

 {

 

     /// Timeserver

 

        /// Local NTP Time

 

        public static DateTime NTPTime(String TimeServer)
     {
          // Find endpoint for timeserver
           IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);

 

         // Connect to timeserver

 

        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

 

          s.Connect(ep);

 

            // Make send/receive buffer

 

         byte[] ntpData = new byte[48];

 

    Array.Clear(ntpData, 0, 48);

 

         // Set protocol version

 

       ntpData[0] = 0x1B;

 

            // Send Request

 

            s.Send(ntpData);

 

            // Receive Time

 

            s.Receive(ntpData);

 

            byte offsetTransmitTime = 40;

 

           ulong intpart = 0;

 

            ulong fractpart = 0;

 

           for (int i = 0; i <= 3; i++)

 

               intpart = (intpart <<  8 ) | ntpData[offsetTransmitTime + i];

 

           for (int i = 4; i <= 7; i++)

 

                fractpart = (fractpart <<  8 ) | ntpData[offsetTransmitTime + i];

 

            ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);

 

           s.Close();

 

            TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);

 

           DateTime dateTime = new DateTime(1900, 1, 1);

 

            dateTime += timeSpan;

 

            TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
          DateTime networkDateTime = (dateTime + offsetAmount);

 

           return networkDateTime;

 

        }

 

    }

 

}

 

 

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)