|
| 1 | +// Copyright 2022 Robotec.ai. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +using System; |
| 16 | +using System.Diagnostics; |
| 17 | + |
| 18 | +namespace ROS2 |
| 19 | +{ |
| 20 | + |
| 21 | +/// <summary> |
| 22 | +/// DateTime based clock that has resolution increased using Stopwatch. |
| 23 | +/// DateTime is used to synchronize since Stopwatch tends to drift. |
| 24 | +/// </summary> |
| 25 | +public class DotnetTimeSource : ITimeSource |
| 26 | +{ |
| 27 | + private readonly double maxUnsyncedSeconds = 10; |
| 28 | + |
| 29 | + private Stopwatch stopwatch = new Stopwatch(); |
| 30 | + |
| 31 | + private readonly object mutex = new object(); |
| 32 | + |
| 33 | + private double systemTimeIntervalStart = 0; |
| 34 | + |
| 35 | + private double stopwatchStartTimeStamp; |
| 36 | + |
| 37 | + private double TotalSystemTimeSeconds() |
| 38 | + { |
| 39 | + return TimeSpan.FromTicks(DateTime.UtcNow.Ticks).TotalSeconds; |
| 40 | + } |
| 41 | + |
| 42 | + private void UpdateSystemTime() |
| 43 | + { |
| 44 | + systemTimeIntervalStart = TotalSystemTimeSeconds(); |
| 45 | + stopwatchStartTimeStamp = Stopwatch.GetTimestamp(); |
| 46 | + } |
| 47 | + |
| 48 | + public DotnetTimeSource() |
| 49 | + { |
| 50 | + UpdateSystemTime(); |
| 51 | + } |
| 52 | + |
| 53 | + public void GetTime(out int seconds, out uint nanoseconds) |
| 54 | + { |
| 55 | + lock(mutex) // Threading |
| 56 | + { |
| 57 | + double endTimestamp = Stopwatch.GetTimestamp(); |
| 58 | + var durationInSeconds = endTimestamp - stopwatchStartTimeStamp; |
| 59 | + double timeOffset = 0; |
| 60 | + if (durationInSeconds >= maxUnsyncedSeconds) |
| 61 | + { // acquire DateTime to sync |
| 62 | + UpdateSystemTime(); |
| 63 | + } |
| 64 | + else |
| 65 | + { // use Stopwatch offset |
| 66 | + timeOffset = durationInSeconds; |
| 67 | + } |
| 68 | + |
| 69 | + TimeUtils.TimeFromTotalSeconds(systemTimeIntervalStart + timeOffset, out seconds, out nanoseconds); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +} // namespace ROS2 |
| 75 | + |
0 commit comments