• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2022 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://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, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Library to analyze timestamp."""
15
16from typing import List
17import datetime
18from pw_chrono_protos import chrono_pb2
19
20_UTC_EPOCH = datetime.datetime(1970, 1, 1, 00, 00, 00)
21
22_UNKNOWN = chrono_pb2.EpochType.Enum.UNKNOWN
23_TIME_SINCE_BOOT = chrono_pb2.EpochType.Enum.TIME_SINCE_BOOT
24_UTC_WALL_CLOCK = chrono_pb2.EpochType.Enum.UTC_WALL_CLOCK
25
26
27def process_snapshot(serialized_snapshot: bytes):
28    captured_timestamps = chrono_pb2.SnapshotTimestamps()
29    captured_timestamps.ParseFromString(serialized_snapshot)
30    return timestamp_output(captured_timestamps)
31
32
33def timestamp_output(timestamps: chrono_pb2.SnapshotTimestamps):
34    output: List[str] = []
35    if not timestamps.timestamps:
36        return ''
37
38    plural = '' if len(timestamps.timestamps) == 1 else 's'
39    output.append(f'Snapshot capture timestamp{plural}')
40    for timepoint in timestamps.timestamps:
41        time = timestamp_snapshot_analyzer(timepoint)
42        clock_epoch_type = timepoint.clock_parameters.epoch_type
43        if clock_epoch_type == _TIME_SINCE_BOOT:
44            output.append(f'  Time since boot:   {time}')
45        elif clock_epoch_type == _UTC_WALL_CLOCK:
46            utc_time = time + _UTC_EPOCH
47            output.append(f'  UTC time:   {utc_time}')
48        else:
49            output.append(f'  Time since unknown epoch {_UNKNOWN}:   unknown')
50
51    return '\n'.join(output)
52
53
54def timestamp_snapshot_analyzer(
55    captured_timepoint: chrono_pb2.TimePoint,
56) -> datetime.timedelta:
57    ticks = captured_timepoint.timestamp
58    clock_period = (
59        captured_timepoint.clock_parameters.tick_period_seconds_numerator
60        / captured_timepoint.clock_parameters.tick_period_seconds_denominator
61    )
62    elapsed_seconds = ticks * clock_period
63
64    time_delta = datetime.timedelta(seconds=elapsed_seconds)
65
66    return time_delta
67