1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom};
use std::num;
use std::process::Command;
use std::thread;
use std::time::Duration;
fn read_to_string(f: &mut File, mut buf: &mut String) -> io::Result<()> {
f.seek(SeekFrom::Start(0))?;
f.read_to_string(&mut buf)?;
Ok(())
}
pub fn str_to_f32(s: &str) -> Result<f32, num::ParseFloatError> {
s.trim().parse()
}
pub struct Monitor<T>
where
T: FnMut() -> String,
{
reader: T,
period: Duration,
first: bool,
}
impl<T> Monitor<T>
where
T: FnMut() -> String,
{
fn new(reader: T, period: f32) -> Self {
Monitor {
reader,
period: Duration::from_secs_f32(period),
first: true,
}
}
pub fn read(&mut self) -> String {
(self.reader)()
}
}
impl<T> Iterator for Monitor<T>
where
T: FnMut() -> String,
{
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
if self.first {
self.first = false;
} else {
thread::sleep(self.period);
}
Some(self.read())
}
}
pub fn monitor_file(path: String, period: f32) -> Monitor<impl FnMut() -> String> {
let mut file = File::open(&path).unwrap();
let mut buf = String::new();
Monitor::new(
move || {
buf.truncate(0);
if let Ok(_) = read_to_string(&mut file, &mut buf) {
buf.clone()
} else {
format!("Failed to read: {}", &path)
}
},
period,
)
}
pub fn monitor_command(
cmd: &'static str,
args: &'static [&'static str],
period: f32,
) -> Monitor<impl FnMut() -> String> {
Monitor::new(
move || {
if let Ok(output) = Command::new(cmd).args(args).output() {
String::from_utf8(output.stdout).unwrap()
} else {
format!("Command failed: '{:?}'", &cmd)
}
},
period,
)
}
pub fn wait_for_signal(signal: i32, timeout: f32) -> crossbeam_channel::Receiver<()> {
let (s, r) = crossbeam_channel::unbounded();
let s2 = s.clone();
unsafe {
signal_hook::register(signal, move || s2.send(()).unwrap()).unwrap();
}
thread::spawn(move || loop {
thread::sleep(Duration::from_secs_f32(timeout));
s.send(()).unwrap();
});
r
}