kappanhang/bandwidth.go

81 lines
1.7 KiB
Go
Raw Normal View History

2020-10-26 14:59:49 +01:00
package main
import (
"fmt"
"sync"
"time"
)
type bandwidthStruct struct {
toRadioBytes int
toRadioPkts int
2020-10-26 14:59:49 +01:00
fromRadioBytes int
fromRadioPkts int
lostPkts int
2020-10-26 14:59:49 +01:00
lastGet time.Time
}
var bandwidth bandwidthStruct
var bandwidthMutex sync.Mutex
func (b *bandwidthStruct) reset() {
bandwidthMutex.Lock()
defer bandwidthMutex.Unlock()
bandwidth = bandwidthStruct{}
}
// Call this function when a packet is sent or received.
2020-10-26 14:59:49 +01:00
func (b *bandwidthStruct) add(toRadioBytes, fromRadioBytes int) {
bandwidthMutex.Lock()
defer bandwidthMutex.Unlock()
b.toRadioBytes += toRadioBytes
if toRadioBytes > 0 {
b.toRadioPkts++
}
2020-10-26 14:59:49 +01:00
b.fromRadioBytes += fromRadioBytes
if fromRadioBytes > 0 {
b.fromRadioPkts++
}
}
// Call this function when a packet is sent or received.
func (b *bandwidthStruct) reportLoss(pkts int) {
bandwidthMutex.Lock()
defer bandwidthMutex.Unlock()
b.lostPkts += pkts
2020-10-26 14:59:49 +01:00
}
func (b *bandwidthStruct) get() (toRadioBytesPerSec, fromRadioBytesPerSec int, lossPercent float64) {
2020-10-26 14:59:49 +01:00
bandwidthMutex.Lock()
defer bandwidthMutex.Unlock()
secs := time.Since(b.lastGet).Seconds()
toRadioBytesPerSec = int(float64(b.toRadioBytes) / secs)
fromRadioBytesPerSec = int(float64(b.fromRadioBytes) / secs)
2020-10-26 17:31:17 +01:00
lossPercent = (float64(b.lostPkts) / float64(b.lostPkts+b.fromRadioPkts)) * 100
2020-10-26 14:59:49 +01:00
b.toRadioBytes = 0
b.toRadioPkts = 0
2020-10-26 14:59:49 +01:00
b.fromRadioBytes = 0
b.fromRadioPkts = 0
b.lostPkts = 0
2020-10-26 14:59:49 +01:00
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])
}