Skip to content

Commit

Permalink
some refactoring
Browse files Browse the repository at this point in the history
gordyf committed Nov 16, 2024
1 parent f2fead2 commit 0b35133
Showing 5 changed files with 46 additions and 177 deletions.
155 changes: 22 additions & 133 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -8,9 +8,10 @@ lto = true
codegen-units = 1

[dependencies]
chrono = "0.4.38"
clap = { version = "4.5.20", features = ["derive", "env"] }
csv = "1.3.1"
jiff = "0.1.14"
num-traits = "0.2.19"
pid = "4.0.0"
rand = "0.8.5"
rumqttc = "0.24.0"
4 changes: 2 additions & 2 deletions src/commands/run.rs
Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@ pub struct RunArgs {
}

impl RunArgs {
pub async fn run(self: RunArgs, mut pid: Pid<f32>) -> Result<(), Box<dyn std::error::Error>> {
pub async fn run(self: RunArgs, mut pid: Pid<f64>) -> Result<(), Box<dyn std::error::Error>> {
let mut mqttoptions = MqttOptions::new("mqtt_pid", self.mqtt_host, self.mqtt_port);
mqttoptions.set_keep_alive(Duration::from_secs(5));
mqttoptions.set_max_packet_size(2000, 1000);
@@ -48,7 +48,7 @@ impl RunArgs {
let last_input_value = *rx.borrow_and_update();

let output = pid
.next_control_output(last_input_value as f32)
.next_control_output(last_input_value as f64)
.output
.clamp(0.0, 100.0)
.round() as u8;
48 changes: 14 additions & 34 deletions src/commands/simulate.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::io::{BufRead, BufReader};

use chrono::{DateTime, Duration, TimeZone, Timelike, Utc};
use clap::Parser;
use jiff::{Timestamp, ToSpan};
use pid::Pid;

#[derive(Parser, Clone)]
@@ -11,14 +11,14 @@ pub struct SimulateArgs {
}

struct Event {
value: f32,
timestamp: DateTime<Utc>,
value: f64,
timestamp: Timestamp,
}

impl SimulateArgs {
pub async fn run(
self: SimulateArgs,
mut pid: Pid<f32>,
mut pid: Pid<f64>,
) -> Result<(), Box<dyn std::error::Error>> {
// Read the CSV file
let mut events: Vec<Event> = Vec::new();
@@ -31,10 +31,12 @@ impl SimulateArgs {
if parts.len() != 2 {
continue; // Skip invalid lines
}
let value: f32 = parts[0].parse()?;
let value = parts[0].parse()?;
let timestamp_str = parts[1];
let timestamp = timestamp_str.parse::<DateTime<Utc>>()?;
events.push(Event { value, timestamp });
events.push(Event {
value,
timestamp: timestamp_str.parse()?,
});
}

// Sort events by timestamp
@@ -48,28 +50,8 @@ impl SimulateArgs {
let first_event = events.first().unwrap();
let last_event = events.last().unwrap();

let start_time = first_event
.timestamp
.date_naive()
.and_hms_opt(
first_event.timestamp.hour(),
first_event.timestamp.minute(),
first_event.timestamp.second(),
)
.unwrap();

let mut end_time = last_event
.timestamp
.date_naive()
.and_hms_opt(
last_event.timestamp.hour(),
last_event.timestamp.minute(),
last_event.timestamp.second(),
)
.unwrap();

// Include the last second
end_time += Duration::seconds(1);
let start_time = first_event.timestamp;
let end_time = last_event.timestamp + 1.seconds();

let mut current_value = 0.0;
let mut event_index = 0;
@@ -78,19 +60,17 @@ impl SimulateArgs {

while t_s < end_time {
// Update current_value based on events
while event_index < events.len()
&& events[event_index].timestamp <= Utc.from_utc_datetime(&t_s)
{
while event_index < events.len() && events[event_index].timestamp <= t_s {
current_value = events[event_index].value;
event_index += 1;
}

let output = pid.next_control_output(current_value).output;
let output = output.clamp(0.0, 100.0);
println!("{},{},{}", t_s, current_value, output);
println!("{},{},{}", t_s.as_second(), current_value, output);

// Increment time by one second
t_s += Duration::seconds(1);
t_s += 1.seconds();
}

Ok(())
13 changes: 6 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -21,7 +21,7 @@ struct Args {
kd: f32,

#[command(subcommand)]
command: Option<Commands>,
command: Commands,
}

#[derive(Subcommand, Clone)]
@@ -33,14 +33,13 @@ enum Commands {
#[tokio::main]
async fn main() {
let args = Args::parse();
let mut pid = Pid::new(args.setpoint, 100.0);
let mut pid = Pid::<f64>::new(args.setpoint, 100.0);
pid.p(args.kp, 100.0);
pid.i(args.ki, 100.0);
pid.d(args.kd, 100.0);

match args.command.clone().unwrap() {
Commands::Run(command) => command.run(pid).await,
Commands::Simulate(command) => command.run(pid).await,
}
.unwrap();
match args.command {
Commands::Run(command) => command.run(pid).await.unwrap(),
Commands::Simulate(command) => command.run(pid).await.unwrap(),
};
}

0 comments on commit 0b35133

Please sign in to comment.