time_sync_tracker_fuchsia.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "chromecast/net/time_sync_tracker_fuchsia.h"
  5. #include <lib/zx/clock.h>
  6. #include <zircon/utc.h>
  7. #include "base/bind.h"
  8. #include "base/fuchsia/fuchsia_logging.h"
  9. #include "base/logging.h"
  10. #include "base/task/single_thread_task_runner.h"
  11. #include "base/time/time.h"
  12. namespace chromecast {
  13. namespace {
  14. // How often zx::clock is polled in seconds.
  15. const unsigned int kPollPeriodSeconds = 1;
  16. zx_handle_t GetUtcClockHandle() {
  17. zx_handle_t clock_handle = zx_utc_reference_get();
  18. DCHECK(clock_handle != ZX_HANDLE_INVALID);
  19. return clock_handle;
  20. }
  21. } // namespace
  22. TimeSyncTrackerFuchsia::TimeSyncTrackerFuchsia(
  23. scoped_refptr<base::SingleThreadTaskRunner> task_runner)
  24. : task_runner_(std::move(task_runner)),
  25. utc_clock_(GetUtcClockHandle()),
  26. weak_factory_(this) {
  27. DCHECK(task_runner_);
  28. weak_this_ = weak_factory_.GetWeakPtr();
  29. }
  30. TimeSyncTrackerFuchsia::~TimeSyncTrackerFuchsia() = default;
  31. void TimeSyncTrackerFuchsia::OnNetworkConnected() {
  32. if (!is_polling_ && !is_time_synced_) {
  33. is_polling_ = true;
  34. task_runner_->PostTask(
  35. FROM_HERE,
  36. base::BindOnce(&TimeSyncTrackerFuchsia::Poll, weak_this_));
  37. }
  38. }
  39. bool TimeSyncTrackerFuchsia::IsTimeSynced() const {
  40. return is_time_synced_;
  41. }
  42. void TimeSyncTrackerFuchsia::Poll() {
  43. DCHECK(task_runner_->BelongsToCurrentThread());
  44. DCHECK(is_polling_);
  45. zx_clock_details_v1_t details;
  46. zx_status_t status = utc_clock_->get_details(&details);
  47. ZX_CHECK(status == ZX_OK, status) << "zx_clock_get_details";
  48. is_time_synced_ =
  49. details.backstop_time != details.ticks_to_synthetic.synthetic_offset;
  50. DVLOG(2) << __func__ << ": backstop_time=" << details.backstop_time
  51. << ", synthetic_offset=" << details.ticks_to_synthetic.synthetic_offset
  52. << ", synced=" << is_time_synced_;
  53. if (!is_time_synced_) {
  54. task_runner_->PostDelayedTask(
  55. FROM_HERE, base::BindOnce(&TimeSyncTrackerFuchsia::Poll, weak_this_),
  56. base::Seconds(kPollPeriodSeconds));
  57. return;
  58. }
  59. is_polling_ = false;
  60. Notify();
  61. }
  62. } // namespace chromecast