Skip to content

Commit

Permalink
fix it properly
Browse files Browse the repository at this point in the history
  • Loading branch information
adeebshihadeh committed Dec 5, 2024
1 parent e29af73 commit a19deef
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
11 changes: 9 additions & 2 deletions common/realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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)
Expand Down
5 changes: 2 additions & 3 deletions system/micd.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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):
"""
Expand Down Expand Up @@ -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():
Expand Down

0 comments on commit a19deef

Please sign in to comment.