aboutsummaryrefslogtreecommitdiff
path: root/source/util/Clock.mc
blob: 44a0e37853ffd10646e206c8a2aacd74dd44e986 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Author:  cirakg & claude ai
// Summary: UTC time for TOTP: the 2038-safe widening of the watch clock, the user's offset, and the trusted clock.
//
// Connect IQ stores time as a 32-bit signed integer, which turns negative on
// 2038-01-19. Reading it as unsigned keeps it correct until 2106 (README 9).
// The trusted clock (Time.CURRENT_TIME_RTC, API 3.0.10) is synced from GPS and
// can't be changed by the user; the UI warns when it is unsynced or differs
// from the normal clock.

import Toybox.Lang;
import Toybox.Time;

module Clock {

    const TWO_POW_32 = 4294967296l;

    // A 32-bit clock value read as unsigned.
    function toUnsigned(value as Number) as Long {
        var v = value.toLong();
        return v < 0 ? v + TWO_POW_32 : v;
    }

    // Current unix time (UTC seconds) plus the user's offset for clock skew.
    function nowUnix(offsetSeconds as Number) as Long {
        if (TestMode.ON) {
            return TestMode.NOW + offsetSeconds;
        }
        return toUnsigned(Time.now().value()) + offsetSeconds;
    }

    // The trusted clock's unix time, or null when it isn't synced yet.
    function trustedUnix() as Long? {
        if (TestMode.ON) {
            return TestMode.NOW;
        }
        try {
            return toUnsigned(Time.getCurrentTime({:currentTimeType => Time.CURRENT_TIME_RTC}).value());
        } catch (e instanceof Time.RealTimeClockNotValidException) {
            return null;
        }
    }
}