Skip to content

Commit

Permalink
Graceful shutdown if serial port not available (#86)
Browse files Browse the repository at this point in the history
* Graceful shutdown if serial port not available

* Formatting
  • Loading branch information
mthmulders authored Dec 3, 2023
1 parent 0c8206b commit fb6db91
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
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);
}
}

0 comments on commit fb6db91

Please sign in to comment.