Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Graceful shutdown if serial port not available #86

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/dsmr/reader.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::settings;
use super::settings::ParityBitSetting;

use serialport::SerialPort;
use serialport::{Error, SerialPort};

use std::io::{BufRead, BufReader};
use std::str;
Expand Down Expand Up @@ -99,15 +99,16 @@ pub fn read_from_serial_port(
}
}

pub fn connect_to_meter(serial_settings: &settings::SerialSettings) -> Box<dyn SerialPort> {
pub fn connect_to_meter(
serial_settings: &settings::SerialSettings,
) -> Result<Box<dyn SerialPort>, Error> {
serialport::new(&serial_settings.port, serial_settings.baud_rate)
.data_bits(to_databits(&serial_settings.byte_size))
.flow_control(serialport::FlowControl::None)
.parity(to_serial_port_parity_bit(&serial_settings.parity_bit))
.stop_bits(serialport::StopBits::One)
.timeout(Duration::from_secs(20))
.open()
.expect("Failed to open port")
}

fn to_serial_port_parity_bit(input: &ParityBitSetting) -> serialport::Parity {
Expand Down
26 changes: 21 additions & 5 deletions src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,35 @@ pub fn main_loop(
serial_settings: dsmr::settings::SerialSettings,
read_interval: f64,
) {
const FAILURE_THRESHOLD: i8 = 20;

let interval = time::Duration::from_millis((read_interval * 1_000.0).round() as u64);
let mut consumer = dsmr::sender::DelegatingConsumer::new(&api_settings.hosts);
let mut failure_count: i8 = 0;

loop {
{
let port = dsmr::reader::connect_to_meter(&serial_settings);

let result = dsmr::reader::connect_to_meter(&serial_settings);
if result.is_ok() {
let port = result.unwrap();
dsmr::reader::read_from_serial_port(port, &mut consumer);
failure_count = 0;
} else {
log::info!("failed to connect to {}", &serial_settings.port);
failure_count += 1;
}

// Close a port following the Resource Acquisition Is Initialization (RAII) paradigm
// by explicitly dropping the reference.
if failure_count >= FAILURE_THRESHOLD {
log::error!(
"failed to connect to {} for {} times, exiting...",
&serial_settings.port,
FAILURE_THRESHOLD,
);
return;
}

// Close a port following the Resource Acquisition Is Initialization (RAII) paradigm
// by explicitly dropping the reference.

thread::sleep(interval);
}
}
Loading