Skip to content

Commit

Permalink
Add ping stats
Browse files Browse the repository at this point in the history
  • Loading branch information
at-wat committed Dec 8, 2023
1 parent bea3bcd commit 4a357ef
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
30 changes: 30 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"errors"
"io"
"sync"
"time"
)

// ErrNotConnected is returned if a function is called before Connect.
Expand Down Expand Up @@ -45,6 +46,35 @@ type BaseClient struct {
muConnecting sync.RWMutex
muWrite sync.Mutex
idLast uint32

muStats sync.RWMutex
stats BaseStats
}

// BaseStats stores base client statistics.
type BaseStats struct {
RecentPingDelay time.Duration
MaxPingDelay time.Duration
MinPingDelay time.Duration
}

func (c *BaseClient) storePingDelay(d time.Duration) {
c.muStats.Lock()
c.stats.RecentPingDelay = d
if c.stats.MaxPingDelay < d {
c.stats.MaxPingDelay = d
}
if c.stats.MinPingDelay > d || c.stats.MinPingDelay == 0 {
c.stats.MinPingDelay = d
}
c.muStats.Unlock()
}

// Stats returns base client stats.
func (c *BaseClient) Stats() BaseStats {
c.muStats.RLock()
defer c.muStats.RUnlock()
return c.stats

Check warning on line 77 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L74-L77

Added lines #L74 - L77 were not covered by tests
}

// Handle registers the message handler.
Expand Down
5 changes: 5 additions & 0 deletions pingreq.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package mqtt

import (
"context"
"time"
)

// Ping to the broker.
Expand All @@ -33,6 +34,8 @@ func (c *BaseClient) Ping(ctx context.Context) error {
sig.mu.Unlock()

pkt := pack(packetPingReq.b())

tReq := time.Now()
if err := c.write(pkt); err != nil {
return wrapError(err, "sending PINGREQ")
}
Expand All @@ -42,6 +45,8 @@ func (c *BaseClient) Ping(ctx context.Context) error {
case <-ctx.Done():
return wrapError(ctx.Err(), "waiting PINGRESP")
case <-chPingResp:
tRes := time.Now()
c.storePingDelay(tRes.Sub(tReq))
}
return nil
}

0 comments on commit 4a357ef

Please sign in to comment.