Skip to main content

netwatch_rs/
device.rs

1use crate::error::Result;
2use std::time::SystemTime;
3
4#[derive(Debug, Clone)]
5pub struct NetworkStats {
6    pub timestamp: SystemTime,
7    pub bytes_in: u64,
8    pub bytes_out: u64,
9    pub packets_in: u64,
10    pub packets_out: u64,
11    pub errors_in: u64,
12    pub errors_out: u64,
13    pub drops_in: u64,
14    pub drops_out: u64,
15}
16
17impl Default for NetworkStats {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl NetworkStats {
24    pub fn new() -> Self {
25        Self {
26            timestamp: SystemTime::now(),
27            bytes_in: 0,
28            bytes_out: 0,
29            packets_in: 0,
30            packets_out: 0,
31            errors_in: 0,
32            errors_out: 0,
33            drops_in: 0,
34            drops_out: 0,
35        }
36    }
37}
38
39pub trait NetworkReader: Send + Sync {
40    fn list_devices(&self) -> Result<Vec<String>>;
41    fn read_stats(&self, device: &str) -> Result<NetworkStats>;
42    fn is_available(&self) -> bool;
43}
44
45#[derive(Debug, Clone)]
46pub struct Device {
47    pub name: String,
48    pub stats: NetworkStats,
49    pub is_active: bool,
50}
51
52impl Device {
53    pub fn new(name: String) -> Self {
54        Self {
55            name,
56            stats: NetworkStats::new(),
57            is_active: false,
58        }
59    }
60
61    pub fn update(&mut self, reader: &dyn NetworkReader) -> Result<()> {
62        match reader.read_stats(&self.name) {
63            Ok(stats) => {
64                self.stats = stats;
65                self.is_active = true;
66                Ok(())
67            }
68            Err(e) => {
69                self.is_active = false;
70                Err(e)
71            }
72        }
73    }
74}