2024 04 06 20 25 25 netduino is dead   Buscar con Google y 5 páginas más   Personal  Microsoft​ Edge

 

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;

 

        }

 

    }

 

}

 

 

Deja un comentario

Este sitio utiliza Akismet para reducir el spam. Conoce cómo se procesan los datos de tus comentarios.

La FRASE DEL MES

«Cualquier tecnología suficientemente avanzada es indistinguible de la magia.»

~ Arthur C. Clarke