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:
03 |
using System.Net.Sockets; |
05 |
using Microsoft.SPOT.Hardware; |
06 |
using SecretLabs.NETMF.Hardware; |
07 |
using SecretLabs.NETMF.Hardware.Netduino; |
08 |
using Microsoft.SPOT.Time; |
10 |
namespace NetduinoPlusWebServer |
19 |
/// <param name="TimeServer">Timeserver</param> |
20 |
/// <returns>Local NTP Time</returns> |
21 |
public static DateTime NTPTime(String TimeServer) |
23 |
// Find endpoint for timeserver |
24 |
IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123); |
26 |
// Connect to timeserver |
27 |
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); |
30 |
// Make send/receive buffer |
31 |
byte [] ntpData = new byte [48]; |
32 |
Array.Clear(ntpData, 0, 48); |
34 |
// Set protocol version |
43 |
byte offsetTransmitTime = 40; |
48 |
for ( int i = 0; i <= 3; i++) |
49 |
intpart = (intpart << 8 ) | ntpData[offsetTransmitTime + i]; |
51 |
for ( int i = 4; i <= 7; i++) |
52 |
fractpart = (fractpart << 8 ) | ntpData[offsetTransmitTime + i]; |
54 |
ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L); |
58 |
TimeSpan timeSpan = TimeSpan.FromTicks(( long )milliseconds * TimeSpan.TicksPerMillisecond); |
59 |
DateTime dateTime = new DateTime(1900, 1, 1); |
62 |
TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime); |
63 |
DateTime networkDateTime = (dateTime + offsetAmount); |
65 |
return networkDateTime; |
Me gusta esto:
Me gusta Cargando...
Relacionado