]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/agnostic/time.py
Add PIO implementation of rotaryio for the Pi 5
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / agnostic / time.py
1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4 """Platform agnostic time implementation"""
5
6 from adafruit_blinka import agnostic
7
8 # We intentionally are patching into this namespace so skip the wildcard check.
9 # pylint: disable=unused-wildcard-import,wildcard-import
10
11 if agnostic.implementation == "circuitpython":
12     from time import *
13 elif agnostic.implementation == "micropython":
14     import utime
15     from utime import sleep
16
17     from ucollections import namedtuple
18
19     _struct_time = namedtuple(
20         "struct_time",
21         (
22             "tm_year",
23             "tm_mon",
24             "tm_mday",
25             "tm_hour",
26             "tm_min",
27             "tm_sec",
28             "tm_wday",
29             "tm_yday",
30             "tm_isdst",
31         ),
32     )
33
34     # pylint: disable=too-many-arguments
35     def _marshal_time(
36         tm_year,
37         tm_mon,
38         tm_mday,
39         tm_hour=0,
40         tm_min=0,
41         tm_sec=0,
42         tm_wday=-1,
43         tm_yday=-1,
44         tm_isdst=-1,
45     ):
46         """Construct struct_time with default values."""
47         _struct_time(
48             tm_year,
49             tm_mon,
50             tm_mday,
51             tm_hour,
52             tm_min,
53             tm_sec,
54             tm_wday,
55             tm_yday,
56             tm_isdst,
57         )
58
59     def struct_time(time_tuple):
60         """Create a struct_time"""
61         return _marshal_time(*time_tuple)
62
63     # pylint: disable=invalid-name
64     _total_ms = 0
65     _prev_ticks_ms = utime.ticks_ms()
66
67     def monotonic():
68         """A monotonically increasing time in seconds. No defined start time."""
69         # Assumes that monotonic is called more frequently than the wraparound of micropython's
70         # utime.ticks_ms()
71         global _prev_ticks_ms, _total_ms  # pylint: disable=global-statement
72         ticks_ms = utime.ticks_ms()
73         _total_ms += utime.ticks_diff(ticks_ms, _prev_ticks_ms)
74         _prev_ticks_ms = ticks_ms
75         return _total_ms * 0.001