SatCat5
io_throttle.cc
1 // Copyright 2021-2025 The Aerospace Corporation.
3 // This file is a part of SatCat5, licensed under CERN-OHL-W v2 or later.
5 
6 #include <satcat5/io_throttle.h>
7 #include <satcat5/polling.h>
8 #include <satcat5/utils.h>
9 
13 
14 WriteableThrottle::WriteableThrottle(
16  unsigned rate_bps)
17  : WriteableRedirect(dst)
18  , m_rate_bps(rate_bps)
19  , m_tokens(rate_bps / 1024) // Start with ~8 msec worth of credit
20  , m_tref(SATCAT5_CLOCK->now()) // Set initial reference time
21 {
22  timer_every(100);
23 }
24 
25 unsigned WriteableThrottle::get_write_space() const {
26  // Limit transmission based on time since the last packet.
27  // Note: Cannot use increment_usec() here due to "const" requirement.
28  unsigned limit1 = calc_tokens(m_tref.elapsed_usec());
29  unsigned limit2 = WriteableRedirect::get_write_space();
30  return min_unsigned(limit1, limit2);
31 }
32 
34  // Reset flow-control state after each successful packet.
36  if (ok) {
37  m_tokens = 0;
38  m_tref = SATCAT5_CLOCK->now();
39  }
40  return ok;
41 }
42 
43 unsigned WriteableThrottle::calc_tokens(unsigned usec) const {
44  // Calculate increment in bytes from elapsed time in microseconds.
45  u64 incr_bytes = (u64(usec) * u64(m_rate_bps)) / 8000000;
46  return saturate_add(m_tokens, unsigned(incr_bytes));
47 }
48 
50  // Increment TimeRef occasionally to prevent rollover.
51  m_tokens = calc_tokens(m_tref.increment_usec());
52 }
Abstract API for writing byte-streams and packets.
Definition: io_writeable.h:24
unsigned get_write_space() const override
How many bytes can be written without blocking?
bool write_finalize() override
Mark end of frame and release temporary working data.
A rate-controlled io::WriteableRedirect.
Definition: io_throttle.h:21
void timer_event() override
Child class MUST override this method.
Definition: io_throttle.cc:49
bool write_finalize() override
Mark end of frame and release temporary working data.
Definition: io_throttle.cc:33
Core event-processing loop for SatCat5 software.
unsigned elapsed_usec() const
Elapsed time in microseconds.
Definition: timeref.cc:25
unsigned increment_usec()
Measure elapsed time in microseconds, then increment by the returned quantized value.
Definition: timeref.cc:33
Miscellaneous mathematical utility functions.
constexpr unsigned min_unsigned(unsigned a, unsigned b)
Min and max functions.
Definition: utils.h:111
constexpr T saturate_add(T a, T b, T c=T(-1))
Unsigned add with saturation: min(A + B, C).
Definition: utils.h:250