diff --git a/common/realtime.py b/common/realtime.py index dd97ea3d787ccf..ef3d6b95ed2eb1 100644 --- a/common/realtime.py +++ b/common/realtime.py @@ -48,11 +48,15 @@ class Ratekeeper: def __init__(self, rate: float, print_delay_threshold: float | None = 0.0) -> None: """Rate in Hz for ratekeeping. print_delay_threshold must be nonnegative.""" self._interval = 1. / rate - self._next_frame_time = time.monotonic() + self._interval self._print_delay_threshold = print_delay_threshold + self._process_name = getproctitle() + self.reset() + self._last_monitor_time = -1 + + def reset(self): self._frame = 0 self._remaining = 0.0 - self._process_name = getproctitle() + self._next_frame_time = time.monotonic() + self._interval self._dts = deque([self._interval], maxlen=100) self._last_monitor_time = time.monotonic() @@ -79,6 +83,9 @@ def keep_time(self) -> bool: # Monitors the cumulative lag, but does not enforce a rate def monitor_time(self) -> bool: + if self._last_monitor_time < 0: + self.reset() + prev = self._last_monitor_time self._last_monitor_time = time.monotonic() self._dts.append(self._last_monitor_time - prev) diff --git a/system/micd.py b/system/micd.py index 713146b1cde430..af1aa3136063a7 100755 --- a/system/micd.py +++ b/system/micd.py @@ -43,6 +43,7 @@ def apply_a_weighting(measurements: np.ndarray) -> np.ndarray: class Mic: def __init__(self): + self.rk = Ratekeeper(RATE) self.pm = messaging.PubMaster(['microphone']) self.measurements = np.empty(0) @@ -59,6 +60,7 @@ def update(self): msg.microphone.soundPressureWeightedDb = float(self.sound_pressure_level_weighted) self.pm.send('microphone', msg) + self.rk.keep_time() def callback(self, indata, frames, time, status): """ @@ -92,11 +94,8 @@ def micd_thread(self): with self.get_stream(sd) as stream: cloudlog.info(f"micd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}") - - self.rk = Ratekeeper(RATE) while True: self.update() - self.rk.keep_time() def main():