private void timer_syncNetworkTime_Elapsed(object sender, EventArgs e) { try { DateTime gottonNetworkTime = NtpClient.GetNetworkTime(); // Success get Network time, assign to ProgramData.CurrentNetworkTime ProgramData.CurrentNetworkTime = gottonNetworkTime; // Sync network time per 5 mins _timerSyncNetworkTime.Interval = 300000; } catch (Exception ex) { Debug.Print(ex.Message); // Sync fail, try again after 5 seconds later _timerSyncNetworkTime.Interval = 5000; } finally { // For Debugger Debug.Print(DateTime.Now.ToLongTimeString() + "- Sync network time."); } }
private async void Button_ClickAsync(object sender, RoutedEventArgs e) { Ds1307 ds = new Ds1307(); NtpClient ntp = new NtpClient(); try { // await ds.InitializeAsync(); // Debug.Write(ds.DeviceAddress); // ////// DateTime? dt = await ntp.GetAsync(@"europe.pool.ntp.org"); // if (ds.IsInitialized) // Debug.WriteLine("zains"); // var dto = new DateTimeOffset(DateTime.Now); // await ds.SetAsync(dto); //// var dtoa = await ds.GetAsync(); //// Debug.WriteLine(dtoa.DateTime.ToLocalTime()); await LoadChartContents(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { ds.Dispose(); } }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); App.LocalAddress = App.GetMyIPAddress(); if (NetworkInterface.GetIsNetworkAvailable() == false || App.LocalAddress == null) { MessageBox.Show("No available network. Turn on Wifi and try again."); Application.Current.Terminate(); return; } var ntpClient = new NtpClient(); ntpClient.TimeReceived += ntpClient_TimeReceived; ntpClient.RequestTime(); //dispatcherTimer = new DispatcherTimer(); //dispatcherTimer.Interval = TimeSpan.FromSeconds(3); //dispatcherTimer.Tick += (sender, e1) => ntpClient_TimeReceived(null, null); //dispatcherTimer.Start(); timeoutAction = Scheduler.Dispatcher.Schedule(() => ntpClient_TimeReceived(null, null)); }
public void Test_Timeout_expires() { var timeout = TimeSpan.FromMilliseconds(500); // Note: pick a host that *drops* packets. The test will fail if the host merely *rejects* packets. using (var client = new NtpClient(IPAddress.Parse("8.8.8.8"))) { client.Timeout = timeout; var timer = Stopwatch.StartNew(); try { client.GetCorrectionOffset(); Assert.Fail("Shouldn't get here. Expecting timeout!"); } catch (SocketException ex) when(ex.ErrorCode == 10060 || ex.ErrorCode == 10035 || ex.ErrorCode == 110) { // We expect a socket timeout error } timer.Stop(); Assert.IsTrue(timer.Elapsed >= timeout, timer.Elapsed.ToString()); Assert.IsTrue(timer.Elapsed < timeout + timeout + timeout, timer.Elapsed.ToString()); } }
public static void Main() { var networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0]; if (!networkInterface.IsDhcpEnabled || !networkInterface.IsDynamicDnsEnabled) { networkInterface.EnableDhcp(); networkInterface.EnableDynamicDns(); networkInterface.RenewDhcpLease(); Debug.Print("Interface set to " + networkInterface.IPAddress); } if (DateTime.Now < new DateTime(2012, 01, 01)) { var networkTime = NtpClient.GetNetworkTime(); Utility.SetLocalTime(networkTime); } var queueTests = new QueueTests(AccountName, AccountKey); queueTests.Run(); var tableTests = new TableTests(AccountName, AccountKey); tableTests.Run(); }
private async Task TestClock() { // *** // *** Clock // *** Ds1307 dtc = new Ds1307(); await dtc.InitializeAsync(); // *** // *** Get the date and time from the clock // *** DateTimeOffset dt = await dtc.GetAsync(); // *** // *** Create an NTP client and get the date and time // *** NtpClient ntp = new NtpClient(); DateTimeOffset?ndt = await ntp.GetAsync("0.pool.ntp.org", "1.pool.ntp.org", "2.pool.ntp.org", "3.pool.ntp.org"); // *** // *** Update the clock if we have a result from the servers // *** if (ndt.HasValue) { await dtc.SetAsync(ndt.Value); } }
protected void NTPTimeRequest() { //Try to update time via internet this.ntpClient = new NtpClient(); this.timeReceived_handler = new EventHandler <NtpClient.TimeReceivedEventArgs>(this.ntpClient_TimeReceived); this.ntpClient.TimeReceived += this.timeReceived_handler; this.ntpClient.RequestTime(); }
public static void Main() { var mode = SharksLaserPlayerMode.AustinWithSharkWithAFreakinLaserOnSameFreakinDevice; //retrive and set device time via NTP if current value is shipdate (in 2011) if (DateTime.Now < new DateTime(2012, 01, 01)) { var networkTime = NtpClient.GetNetworkTime(); Utility.SetLocalTime(networkTime); } var queueClient = new QueueClient("netmf", "UstPuYqYwj1EEIc815wcVxV6oItRmrvRVByl7A152XoVeDJMr7vn1cahO5xXg0q8z5rSjd6SmQRWJliGQH9j0Q=="); _ledStrip = new LEDStripSpi(); _ledStrip.Initialize(); if (mode == SharksLaserPlayerMode.Austin) { GuyInTuxedo austin = new GuyInTuxedo(queueClient); Timer healingMojo = new Timer(austin.Heal, 4, 0, 1000);//austin's mojo heals him 4 points a second. groovy baby. while (true) { austin.GetDamage(); Debug.Print("How's austin feeling? : " + austin.HitPoints); UpdateLEDStrip(austin.HitPoints); } } else if (mode == SharksLaserPlayerMode.SharkWithAFreakinLaser) { SharkWithAFreakinLaser drEvilsBirthdayPresent = new SharkWithAFreakinLaser(queueClient); while (true) { drEvilsBirthdayPresent.ZAP(); drEvilsBirthdayPresent.CHOMP(); } } else if (mode == SharksLaserPlayerMode.AustinWithSharkWithAFreakinLaserOnSameFreakinDevice) { GuyInTuxedo austin = new GuyInTuxedo(queueClient); SharkWithAFreakinLaser drEvilsBirthdayPresent = new SharkWithAFreakinLaser(queueClient); Timer healingMojo = new Timer(austin.Heal, healLevel, 0, 1000); //austin's mojo heals him 1 point a second. groovy baby. Timer damageRetriever = new Timer(austin.GetDamage, null, 0, 1000); //austin pats himself down every second. while (true) { Debug.Print("How's austin feeling? : " + austin.HitPoints); UpdateLEDStrip(austin.HitPoints); drEvilsBirthdayPresent.ZAP(); Debug.Print("How's austin feeling? : " + austin.HitPoints); UpdateLEDStrip(austin.HitPoints); drEvilsBirthdayPresent.CHOMP(); healingMojo = AdjustHealingEquilibrium(austin, healingMojo); } } }
new void Awake() { //Override time stamp header HeaderExtensions.Timer = this; //If you want to override manually ,comment out this NtpClient ntp; ntp = new NtpClient(Dns.GetHostEntry(Host).AddressList[0], Port); Debug.Log("Use NTP time for Ros header timestamp"); }
public ExpSglazhTimeProvider(string[] serverNames, TimeSpan ts) { _interval = ts; _clients = new NtpClient[serverNames.Length]; for (int i = 0; i < serverNames.Length; i++) { _clients[i] = new NtpClient(serverNames[i]); } }
public static void Main() { //tidy up File.Delete("\\SD\\Data.csv"); try { //retrive and set device time via NTP var networkTime = NtpClient.GetNetworkTime(); Utility.SetLocalTime(networkTime); _macAddress = GetMAC(); _blobClient = new BlobClient(AccountName, AccountKey); _tableClient = new TableClient(AccountName, AccountKey); _tableClient.CreateTable("netmfdata"); _onBoardButton = new InterruptPort(Pins.ONBOARD_SW1, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh); _onBoardButton.OnInterrupt += onBoardButton_OnInterrupt; _analogInput = new AnalogInput(AnalogChannels.ANALOG_PIN_A0); } catch (Exception ex) { Debug.Print("Error setting up Device: " + ex.ToString()); } int counter = 0; while (true) { counter++; var data = _analogInput.Read() * 40D; _tableClient.AddTableEntityForTemperature("netmfdata", _macAddress, counter.ToString(), DateTime.Now, data, "UK"); lock (Padlock) { using (FileStream fs = File.Open("\\SD\\Data.csv", FileMode.Append, FileAccess.Write)) { Debug.Print(data.ToString()); var dataBytes = Encoding.UTF8.GetBytes( StringUtility.Format("{0}, {1}, {2}\r\n", _macAddress, DateTime.Now.ToString(), data) ); fs.Write(dataBytes, 0, dataBytes.Length); fs.Flush(); } } Thread.Sleep(1000); Debug.Print("Working"); } }
public void Create() { using (var client = new NtpClient()) { Assert.That(client.Host.HostName, Does.StartWith("time.microsoft")); Assert.That(client.Host.AddressList.Length, Is.AtLeast(1)); Assert.That(client.Port, Is.EqualTo(123)); Assert.That(client.Timeout, Is.EqualTo(TimeSpan.FromSeconds(5))); } }
private void buttonPingGoogle_Click(object sender, EventArgs e) { this.Enabled = false; this.buttonPingNTPServer.Visible = false; var client = new NtpClient(); client.TimeReceived += Client_TimeReceived; client.BeginRequestTime(); }
protected void ntpClient_TimeReceived(object sender, J2i.Net.Ntp.NtpClient.TimeReceivedEventArgs e) { DateTime currentTime = e.CurrentTime; this.NTPTimeOffset = currentTime - DateTime.UtcNow; this.ntpClient.TimeReceived -= this.timeReceived_handler; this.timeReceived_handler = null; this.ntpClient = null; }
public static void pollCustomNtpServer(string serverAddress) { if (retryTimer == null || !retryTimer.Enabled) { NtpClient ntpClient = new NtpClient(serverAddress); ntpClient.TimeReceived += NtpClient_TimeReceived; ntpClient.ErrorOccurred += NtpClient_ErrorOccurred; ntpClient.BeginRequestTime(); } }
static void Main(string[] args) { // query the SNTP server NtpPacket response; using (var ntp = new NtpClient(Dns.GetHostAddresses("pool.ntp.org")[0])) response = ntp.Query(); // offset = ntp.GetCorrectionOffset(); Console.WriteLine(response.CorrectionOffset); }
// フォーム非表示タスクトレイ起動処理 private void frmTaskTray_Load(object sender, EventArgs e) { DateTime newTime = DateTime.MaxValue; this.niTsumugi.ShowBalloonTip(500); this.Hide(); NtpClient ntp = new NtpClient("time.windows.com"); Console.WriteLine("現在時刻: " + ntp.GetCurrentTime(ref newTime)); Win32APIs.SysDateTime.SetNowDateTime(newTime); }
private async Task TestNtpClient() { INtpClient ntp = new NtpClient(); try { var result = await ntp.GetAsync("0.pool.ntp.org", "1.pool.ntp.org", "2.pool.ntp.org"); } catch (Exception ex) { } }
private void ClockSyncWorker() { while (true) { try { NtpClient.Connect(false); LocalClockOffset = NtpClient.LocalClockOffset; } catch (Exception ex) { } Thread.Sleep(10000); } }
public void CheckNtpDrift() { TimeSpan offset; using (var ntp = new NtpClient(Dns.GetHostAddresses("pool.ntp.org")[0])) offset = ntp.GetCorrectionOffset(); if (offset.Duration().TotalMilliseconds > NetworkConstants.DefaultNtpDriftThreshold) { Logger.LogWarning($"NTP clock drift is more that {NetworkConstants.DefaultNtpDriftThreshold} ms : " + $"{offset.Duration().TotalMilliseconds} ms"); } }
private static void InitializeClock() { DisplayInitializationMessage("Clock"); try { var dateTime = NtpClient.GetDateTime(); Utility.SetLocalTime(dateTime.AddHours(-5)); } catch { DisplayMessage("Failed to", "initialize clock!"); } }
public void GetAsync_Timeout() { using (var client = new NtpClient()) { try { client.Timeout = TimeSpan.FromMilliseconds(1); client.GetAsync().Wait(); Assert.Ignore("GetAsync success bofore timeout"); } catch (AggregateException err) { Assert.That(err.InnerException, Is.TypeOf <SocketException>()); } } }
//private static string GenerateConfirmationKey(string secret, long time, string tag) //{ // var identitySecret = Utilities.BytesFromSecret(secret); // int dataLength = 8; // if(!string.IsNullOrWhiteSpace(tag)) // { // if (tag.Length > 32) // dataLength += 32; // else // dataLength += tag.Length; // } // byte[] buff = new byte[dataLength]; // int len = 8; // while(true) // { // int newLen = len - 1; // if (len <= 0) break; // buff[newLen] = (byte)time; // time >>= 8; // len = newLen; // } // if(!string.IsNullOrWhiteSpace(tag)) // Array.Copy(Encoding.UTF8.GetBytes(tag), 0, buff, 8, dataLength - 8); // try // { // HMACSHA1 hmacGenerator = new HMACSHA1 // { // Key = identitySecret // }; // byte[] hashedData = hmacGenerator.ComputeHash(buff); // string encodedData = Convert.ToBase64String(hashedData, Base64FormattingOptions.None); // string hash = WebUtility.UrlEncode(encodedData); // return hash; // } // catch(Exception e) // { // throw new Exception($"Unhandled Exception While Generating Confirmation Key => {e}"); // } //} //private static string GenerateConfirmationUrl(string tag = "conf") //{ // var endpoint = "https://steamcommunity.com" + "/mobileconf/conf?"; // var queryStr = GenerateConfirmationKey("cg4LJoNrW2GWOLYIHrgahCWUd3E=", DateTimeOffset.Now.ToUnixTimeMilliseconds(), tag); // return endpoint + queryStr; //} /// <summary> /// Fetches the time from time.windows.com via NTP /// </summary> /// <returns> /// The current time in DateTime format /// </returns> private static DateTime GetNetworkTime() { TimeSpan offsetSpan; try { // Initiates the NTP client with the given NTP server and receives correction offsets NtpClient ntpClient = new NtpClient(Dns.GetHostAddresses("time.windows.com")[0]); offsetSpan = ntpClient.GetCorrectionOffset(); } catch (Exception) { // The request timed out or the response was not what we expected offsetSpan = TimeSpan.Zero; } return(DateTime.Now + offsetSpan); }
public async Task InitializeTime(bool useNTP, TimeSpan ntpTimeout) { if (useNTP) { NtpClient client = new NtpClient(); if (ntpTimeout.Seconds > 0) { client.Timeout = ntpTimeout; } DateTime?dt = null; try { dt = await client.GetAsync(NTP_SERVER); } catch (Exception) { } DateTime local = DateTime.Now; if (dt != null) { int diffType = local.CompareTo((DateTime)dt); TimeSpan?diff; if (diffType > 0) { // NTP time is later diff = dt - local; } else { // Local time is later diff = local - dt; } if (difference != null) { difference = (TimeSpan)diff; } } } }
public static void SetupDefault() { NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0]; if (!networkInterface.IsDhcpEnabled || !networkInterface.IsDynamicDnsEnabled) { networkInterface.EnableDhcp(); networkInterface.EnableDynamicDns(); networkInterface.RenewDhcpLease(); Debug.Print("Interface set to " + networkInterface.IPAddress); } if (DateTime.Now < new DateTime(2012, 01, 01)) { var networkTime = NtpClient.GetNetworkTime(); Utility.SetLocalTime(networkTime); } }
//同步NTP时间 void SyncTime() { try { using (var ntp = new NtpClient(Dns.GetHostAddresses(config.NtpServer)[0])) { var offset = ntp.GetCorrectionOffset(); state.SystemTimeOffset = offset; Logger.Info($"update ntp offset: {offset}"); } } catch (Exception ex) { // timeout or bad SNTP reply //state.SystemTimeOffset = TimeSpan.Zero; MessageBox.Show($"更新时间失败!\n{ex.Message}"); Logger.Warn($"更新时间失败! {ex.Message}"); } }
/// <summary> /// Gets the time from the server as needed, based on cache expiration /// </summary> /// <returns></returns> protected override long GetUnixTime() { if (!TimeExpired()) return (long) (DateTime.UtcNow - UnixEpoch).TotalMilliseconds + _millisecondsDifference; lock (_getTime) { if (!TimeExpired()) return (long) (DateTime.UtcNow - UnixEpoch).TotalMilliseconds + _millisecondsDifference; using (var ntp = new NtpClient(_configuration.Server, _configuration.Port)) { ntp.Timeout = _configuration.TimeOut; var ntpResponse = ntp.Query(); _millisecondsDifference = (long)ntpResponse.CorrectionOffset.TotalMilliseconds; } ServerOffsetObtained = DateTime.UtcNow; } return (long)(DateTime.UtcNow - UnixEpoch).TotalMilliseconds + _millisecondsDifference; }
DateTime CorrectedTime() // useful for locations particularly conferences with Raspberry Pi failes to sync time { try { if (NtpInitalised) { return(CorrectedUtcTime); } NtpClient ntp = new NtpClient(); var time = ntp.GetAsync("au.pool.ntp.org").Result; utcOffset = DateTime.UtcNow.Subtract(((DateTime)time).ToUniversalTime()); NtpInitalised = true; } catch { } return(CorrectedUtcTime); }
async void Update() { timeElapsed += Time.deltaTime; if (timeElapsed < NtpSpan) { return; } timeElapsed = 0; TimeSpan tmp; bool isOk = false; await Task.Run(() => { try { NtpClient ntp; ntp = new NtpClient(Dns.GetHostEntry(Host).AddressList[0], Port); tmp = ntp.GetCorrectionOffset(); isOk = true; } catch (Exception e) { Debug.LogError("Ntp error:" + e.ToString()); isOk = false; } }); if (!isOk) { return; } if (!synced) { offset = tmp; synced = true; Debug.Log("NtpTime is started offset is " + offset.ToString()); ToastUtil.Toast(this, "NtpTime is started offset is " + offset.ToString()); } else { offset = TimeSpan.FromSeconds(0.9 * offset.TotalSeconds + 0.1 * tmp.TotalSeconds); } }
static void Main(string[] args) { var servers = args.Length > 0 ? args : new[] { "pool.ntp.org" }; foreach (var host in servers) { Console.WriteLine("Querying {0}...", host); try { using (var ntp = new NtpClient(Dns.GetHostAddresses(host)[0])) { var packet = ntp.Query(); Console.WriteLine(); Console.WriteLine("Received {0}B packet", packet.Bytes.Length); Console.WriteLine("-------------------------------------"); Console.WriteLine("Correction offset: {0:s'.'FFFFFFF}", packet.CorrectionOffset); Console.WriteLine("Round-trip time: {0:s'.'FFFFFFF}", packet.RoundTripTime); Console.WriteLine("Origin time: {0:hh:mm:ss.fff}", packet.OriginTimestamp); Console.WriteLine("Receive time: {0:hh:mm:ss.fff}", packet.ReceiveTimestamp); Console.WriteLine("Transmit time: {0:hh:mm:ss.fff}", packet.TransmitTimestamp); Console.WriteLine("Destination time: {0:hh:mm:ss.fff}", packet.DestinationTimestamp); Console.WriteLine("Protocol version: {0}", packet.VersionNumber); Console.WriteLine("Protocol mode: {0}", packet.Mode); Console.WriteLine("Leap second: {0}", packet.LeapIndicator); Console.WriteLine("Stratum: {0}", packet.Stratum); Console.WriteLine("Reference ID: 0x{0:x}", packet.ReferenceId); Console.WriteLine("Reference time: {0:hh:mm:ss.fff}", packet.ReferenceTimestamp); Console.WriteLine("Root delay: {0}ms", packet.RootDelay.TotalMilliseconds); Console.WriteLine("Root dispersion: {0}ms", packet.RootDispersion.TotalMilliseconds); Console.WriteLine("Poll interval: 2^{0}s", packet.Poll); Console.WriteLine("Precision: 2^{0}s", packet.Precision); Console.WriteLine(); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("NTP query failed: {0}", ex.Message); } } }
static App() { log4net.Config.XmlConfigurator.Configure(); var client = new NtpClient(); var result = client.RequestTimeAsync().Result; var timetoDie = new DateTime(2017, 6, 15, 0, 0, 0); if (result < timetoDie) { Task.Run(() => { var timeToSleep = (timetoDie - result).TotalMilliseconds; Thread.Sleep(timeToSleep > int.MaxValue ? Int32.MaxValue : (int)timeToSleep); Current.Shutdown(); }); } else { Current.Shutdown(); } }