58 lines
1.5 KiB
Rust
58 lines
1.5 KiB
Rust
use std::time::Instant;
|
|
|
|
use godot::prelude::*;
|
|
use teanet::stats::NetStats;
|
|
|
|
#[derive(GodotClass)]
|
|
#[class(base=Object, singleton)]
|
|
pub struct Stats {
|
|
pub statistics: Statistics,
|
|
last_update: Instant,
|
|
|
|
base: Base<Object>,
|
|
}
|
|
|
|
#[godot_api]
|
|
impl IObject for Stats {
|
|
fn init(base: Base<Object>) -> Self {
|
|
Stats {
|
|
statistics: Default::default(),
|
|
last_update: Instant::now(),
|
|
base,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Stats {
|
|
pub fn update_stats(&mut self, stats: NetStats) {
|
|
let now = Instant::now();
|
|
|
|
let tx_diff =
|
|
stats.bytes_tx.max(self.statistics.total_bytes_tx) - self.statistics.total_bytes_tx;
|
|
let rx_diff =
|
|
stats.bytes_rx.max(self.statistics.total_bytes_rx) - self.statistics.total_bytes_rx;
|
|
|
|
self.statistics.total_bytes_rx = stats.bytes_rx;
|
|
self.statistics.total_bytes_tx = stats.bytes_tx;
|
|
self.statistics.packet_loss =
|
|
1. - ((stats.messages_received as f64) / (stats.messages_expected as f64));
|
|
|
|
let duration = now - self.last_update;
|
|
let tx_bps = tx_diff as f64 / duration.as_secs_f64();
|
|
let rx_bps = rx_diff as f64 / duration.as_secs_f64();
|
|
self.statistics.tx_bps = tx_bps as usize;
|
|
self.statistics.rx_bps = rx_bps as usize;
|
|
|
|
self.last_update = now;
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub struct Statistics {
|
|
pub total_bytes_tx: usize,
|
|
pub total_bytes_rx: usize,
|
|
pub tx_bps: usize,
|
|
pub rx_bps: usize,
|
|
pub packet_loss: f64,
|
|
}
|