summaryrefslogtreecommitdiff
path: root/timers.py
blob: 5ba51fa01d66ba1b9148a581c5a27e24711fac28 (plain)
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
43
44
45
import datetime
import sys, termios, tty
import inputs

frequency = 120 # 120Hz refresh

def timer(length=0, ratio = 0.2, rest_accum=0):
    """countdown and stopwatch; pass length as 0 for stopwatch"""
    start = datetime.datetime.now()
    end = start + datetime.timedelta(seconds=length) # change to mins in final
    accum = 0
    timeout = 1/frequency

    old_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    while True:
        now = datetime.datetime.now()
        elapsed = now - start
        rest = elapsed * ratio + datetime.timedelta(seconds=rest_accum)
        time_left = end - now
        if length > 0 and time_left.total_seconds() <= 0:
            break

        ch = inputs.getch_nb(timeout)
        if ch == 'q':
            rest = datetime.timedelta()
            break
        elif ch == ' ':
            break

        if length > 0:
            time_display = time_left
        else:
            time_display = elapsed

        # see https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
        print("\x1b[2K\r" + inputs.delta_to_HM(time_display) + "\t" +
              inputs.delta_to_HM(rest), end="", flush=True)

        accum += timeout
        if accum >= 1:
            accum = 0
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

    return (elapsed.total_seconds(), rest.total_seconds(), start)