diff --git a/vbantxt.go b/vbantxt.go index d40e64e..5a1671b 100644 --- a/vbantxt.go +++ b/vbantxt.go @@ -4,6 +4,8 @@ import ( "fmt" "io" "time" + + "github.com/charmbracelet/log" ) // VbanTxt is used to send VBAN-TXT requests to a distant Voicemeeter/Matrix. @@ -11,6 +13,7 @@ type VbanTxt struct { conn io.WriteCloser packet packet ratelimit time.Duration + lastSend time.Time } // New constructs a fully formed VbanTxt instance. This is the package's entry point. @@ -40,8 +43,18 @@ func New(host string, port int, streamname string, options ...Option) (*VbanTxt, } // Send is responsible for firing each VBAN-TXT request. -// It waits for {vt.ratelimit} time before returning. +// It enforces rate limiting by waiting only when necessary. func (vt *VbanTxt) Send(cmd string) error { + if elapsed := time.Since(vt.lastSend); elapsed < vt.ratelimit { + log.Debugf( + "Rate limit in effect. Waiting for %v before sending next command.", + vt.ratelimit-elapsed, + ) + time.Sleep(vt.ratelimit - elapsed) + } + + vt.lastSend = time.Now() + _, err := vt.conn.Write(append(vt.packet.header(), cmd...)) if err != nil { return fmt.Errorf("error sending command (%s): %w", cmd, err) @@ -49,8 +62,6 @@ func (vt *VbanTxt) Send(cmd string) error { vt.packet.bumpFrameCounter() - time.Sleep(vt.ratelimit) - return nil }