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;
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 }

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