Print used bandwidth in status

This commit is contained in:
Nonoo 2020-10-26 14:59:49 +01:00
parent 1ea0400d8d
commit d43350b59d
3 changed files with 67 additions and 1 deletions

58
bandwidth.go Normal file
View file

@ -0,0 +1,58 @@
package main
import (
"fmt"
"sync"
"time"
)
type bandwidthStruct struct {
toRadioBytes int
fromRadioBytes int
lastGet time.Time
}
var bandwidth bandwidthStruct
var bandwidthMutex sync.Mutex
func (b *bandwidthStruct) reset() {
bandwidthMutex.Lock()
defer bandwidthMutex.Unlock()
bandwidth = bandwidthStruct{}
}
func (b *bandwidthStruct) add(toRadioBytes, fromRadioBytes int) {
bandwidthMutex.Lock()
defer bandwidthMutex.Unlock()
b.toRadioBytes += toRadioBytes
b.fromRadioBytes += fromRadioBytes
}
func (b *bandwidthStruct) get() (toRadioBytesPerSec, fromRadioBytesPerSec int) {
bandwidthMutex.Lock()
defer bandwidthMutex.Unlock()
secs := time.Since(b.lastGet).Seconds()
toRadioBytesPerSec = int(float64(b.toRadioBytes) / secs)
fromRadioBytesPerSec = int(float64(b.fromRadioBytes) / secs)
b.toRadioBytes = 0
b.fromRadioBytes = 0
b.lastGet = time.Now()
return
}
func (b *bandwidthStruct) formatByteCount(c int) string {
const unit = 1000
if c < unit {
return fmt.Sprintf("%d B", c)
}
div, exp := int(unit), 0
for n := c / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(c)/float64(div), "kMGTPE"[exp])
}

View file

@ -229,6 +229,7 @@ func (s *controlStream) handleRead(r []byte) error {
func (s *controlStream) loop() {
startTime := time.Now()
bandwidth.reset()
s.secondAuthTimer = time.NewTimer(200 * time.Millisecond)
s.reauthTimeoutTimer = time.NewTimer(0)
@ -260,7 +261,10 @@ func (s *controlStream) loop() {
log.Error("auth timeout, audio/serial stream may stop")
case <-statusLogTicker.C:
if s.serialAndAudioStreamOpened {
log.Print("running for ", time.Since(startTime), " roundtrip latency ", s.common.pkt7.latency)
up, down := bandwidth.get()
log.Print("running for ", time.Since(startTime).Round(time.Second),
" rtt ", s.common.pkt7.latency.Milliseconds(), "ms up ",
bandwidth.formatByteCount(up), "/s down ", bandwidth.formatByteCount(down), "/s")
}
case <-s.deinitNeededChan:
s.deinitFinishedChan <- true

View file

@ -31,12 +31,16 @@ func (s *streamCommon) send(d []byte) error {
if _, err := s.conn.Write(d); err != nil {
return err
}
bandwidth.add(len(d), 0)
return nil
}
func (s *streamCommon) read() ([]byte, error) {
b := make([]byte, 1500)
n, _, err := s.conn.ReadFromUDP(b)
if err == nil {
bandwidth.add(0, n)
}
return b[:n], err
}