From 84547002a57ed05f1d874ad607bd29816c1d8e30 Mon Sep 17 00:00:00 2001 From: hmjsp Date: Fri, 19 Dec 2025 09:32:26 +0000 Subject: make timer accurate; add non blocking input - timer accurate and quits when 'q' is pressed, in a non blocking manner, polling at 120Hz - some minor refactoring in inputs.py too --- main.py | 44 +++++++++++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 13 deletions(-) (limited to 'main.py') diff --git a/main.py b/main.py index 2ce1450..93c6a5d 100644 --- a/main.py +++ b/main.py @@ -2,8 +2,12 @@ import pygal import csv import time import datetime +import datetime import hashlib from collections import OrderedDict +import termios +import tty +import sys import inputs import formatting as f @@ -29,23 +33,37 @@ if option == 't': print("timer length (in minutes)? ", end="", flush=True) timer_length = inputs.get_pos_int() - # need timer to be accurate; sleep until next second start? processing time - # although small will still add to time so needs to be avoided - # timer loop - time_left = timer_length #* 60 - time_start = time.time() - while time_left: + time_left = timer_length + start = datetime.datetime.now() + end = start + datetime.timedelta(seconds=time_left) # change to mins in final + accum = 0 + timeout = 1/120 # 120Hz refresh + + old_settings = termios.tcgetattr(sys.stdin) + tty.setcbreak(sys.stdin.fileno()) + while True: + now = datetime.datetime.now() + time_left = end - now + if time_left.total_seconds() <= 0: + break + + ch = inputs.getch_nb(timeout) + if ch == 'q': + print("exited early!") + break # see https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 - print("\x1b[2K\r" + f.sec_to_min(time_left), end="", flush=True) - time_left -= 1 - time.sleep(1) + print("\x1b[2K\r" + inputs.delta_to_HM(time_left), end="", flush=True) + accum += timeout + if accum >= 1: + accum = 0 + termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) print("\nfocus session finished!\nlogging...") session = OrderedDict() - session["id"] = hashlib.sha256(str(time_start).encode('utf8')).hexdigest() - session["date"] = time.strftime("%Y-%m-%d") - session["start"] = time.strftime("%H:%M") - session["elapsed"] = timer_length * 60 + session["id"] = hashlib.sha256(str(start).encode('utf8')).hexdigest() + session["date"] = start.strftime("%Y-%m-%d") + session["start"] = start.strftime("%H:%M") + session["elapsed"] = int(timer_length - time_left.total_seconds()) session["type"] = "focus" session["tag"] = tag session["timer"] = "timer" -- cgit v1.2.3