let mut rng = rand::thread_rng();
+ let mut number_of_pings = 0;
+ let mut total_ping_duration = Duration::default();
+
let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
socket.connect("192.168.2.102:8739").unwrap();
socket
loop {
let time_beginning_loop = time::Instant::now();
- if let Err(error) = ping(&socket, &mut rng) {
- error_state = true;
- println!("Error: {:?}", error);
- if time::Instant::now() - time_last_email_send >= EMAIL_RESEND_PERIOD {
- // Send e-mail.
- println!("Sending email...");
- match send_email(
- "Watchdog ERROR",
- &format!("Error: {:?}", error),
- &config.smtp_login,
- &config.smtp_password,
- ) {
- Err(email_error) => println!("Error sending email: {:?}", email_error),
- _ => {
- println!("Email successfully sent");
- time_last_email_send = time::Instant::now();
- }
+ match ping(&socket, &mut rng) {
+ Ok(t) => {
+ total_ping_duration += t;
+ number_of_pings += 1;
+
+ if error_state {
+ error_state = false;
+ println!("End of erroneous state");
}
- }
- } else {
- if error_state {
- error_state = false;
- println!("End of erroneous state");
- }
- if time::Instant::now() - time_last_state_printed >= STATE_PRINT_PERIOD {
- println!("No error detected");
- time_last_state_printed = time::Instant::now();
+ if time::Instant::now() - time_last_state_printed >= STATE_PRINT_PERIOD {
+ println!(
+ "No error detected. Mean of ping time: {} μs",
+ total_ping_duration.as_micros() / number_of_pings
+ );
+ total_ping_duration = Duration::default();
+ number_of_pings = 0;
+ time_last_state_printed = time::Instant::now();
+ }
+ }
+ Err(error) => {
+ error_state = true;
+ println!("Error: {:?}", error);
+ if time::Instant::now() - time_last_email_send >= EMAIL_RESEND_PERIOD {
+ // Send e-mail.
+ println!("Sending email...");
+ match send_email(
+ "Watchdog ERROR",
+ &format!("Error: {:?}", error),
+ &config.smtp_login,
+ &config.smtp_password,
+ ) {
+ Err(email_error) => println!("Error sending email: {:?}", email_error),
+ _ => {
+ println!("Email successfully sent");
+ time_last_email_send = time::Instant::now();
+ }
+ }
+ }
}
}
WrongMessageReceived(String),
}
-fn ping(socket: &UdpSocket, rng: &mut ThreadRng) -> std::result::Result<(), PingError> {
+fn ping(socket: &UdpSocket, rng: &mut ThreadRng) -> std::result::Result<Duration, PingError> {
let number: u64 = rng.gen();
let mut buffer = number.to_le_bytes();
+ let now = time::Instant::now();
match socket.send(&buffer) {
Ok(_size_sent) => {
buffer.fill(0);
Err(error) => return Err(PingError::SocketError(error)),
}
- Ok(())
+ Ok(time::Instant::now() - now)
}
fn send_email(title: &str, body: &str, login: &str, pass: &str) -> Result<()> {