wordclock/src/asynced.py

51 lines
1.5 KiB
Python
Raw Permalink Normal View History

# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import compat
2024-03-01 17:13:18 +01:00
from typing import Generator
2024-02-27 08:05:22 +01:00
2024-03-01 17:13:18 +01:00
def delay(secs: float) -> Generator[None, None, None]:
end = compat.monotonic() + secs
while compat.monotonic() < end:
yield None
2024-03-01 17:13:18 +01:00
def fps(fps: float) -> Generator[None, None, None]:
yield None
dt = 1 / fps
until = compat.monotonic() + dt
while True:
remain = until - compat.monotonic()
if remain > 0:
compat.sleep(remain)
until += dt
if remain < -dt:
# Catch up a bit
until += -remain / 3
yield None
2024-03-01 17:13:18 +01:00
def wait(stop_ms: int) -> Generator[int, None, None]:
"""Waits for stop_ms to pass, yielding how many ms have passed so far."""
start = compat.monotonic()
while True:
elapsed = int((compat.monotonic() - start) * 1000)
2024-03-01 17:13:18 +01:00
elapsed = min(stop_ms, elapsed)
yield elapsed
2024-03-01 17:13:18 +01:00
if elapsed >= stop_ms:
break