using System; using System.Threading; using System.Net; using System.Text; using System.Net.Sockets; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; //need for Utility class using Microsoft.SPOT.Net; using GHI.Premium.Net; namespace WIFI { public class NTP { public static bool Time(string TimeServer, int GmtOffset = 0) { Socket s = null; try { EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123); s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); byte[] ntpData = new byte[48]; Array.Clear(ntpData, 0, 48); ntpData[0] = 0x1B; // Set protocol version s.SendTo(ntpData, rep); // Send Request if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout { s.ReceiveFrom(ntpData, ref rep); // Receive Time 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); Utility.SetLocalTime(networkDateTime); return true; } s.Close(); } catch { try { s.Close(); } catch { } } return false; } } }