автоматический полив rust - НАУКА О БЛАГОУСТРОЙСТВЕ

автоматический полив rust

«`rust
use std::{env, fs};
use std::io::{BufRead, BufReader};
use std::sync::mpsc::{self, Receiver, SyncSender};
use std::thread;
use std::time::{Duration, Instant};

fn main() {
let args: Vec = env::args().collect();
let config_file = &args[1];
let config = fs::read_to_string(config_file).unwrap();
let config: Config = serde_yaml::from_str(&config).unwrap();

let (sender, receiver): (SyncSender, Receiver) = mpsc::sync_channel(1);

let mut state = State {
pump_on: false,
pump_on_at: Instant::now(),
pump_off_at: Instant::now(),
watering_interval: config.watering_interval,
watering_duration: config.watering_duration,
};

let watering_thread = thread::spawn(move || {
loop {
let now = Instant::now();
if state.pump_on {
if now >= state.pump_off_at {
sender.send(false).unwrap();
state.pump_on = false;
}
} else if now >= state.pump_on_at {
sender.send(true).unwrap();
state.pump_on = true;
state.pump_off_at = now + state.watering_duration;
}
thread::sleep(Duration::from_secs(1));
}
});

let stdin = BufReader::new(std::io::stdin());
for line in stdin.lines() {
if line.unwrap() == «on» {
state.pump_on_at = Instant::now() + state.watering_interval;
} else if line.unwrap() == «off» {
state.pump_off_at = Instant::now();
state.pump_on = false;
} else if line.unwrap() == «quit» {
receiver.recv().unwrap();
state.pump_on = false;
watering_thread.join().unwrap();
break;
}
}
}

#[derive(serde::Deserialize)]
struct Config {
watering_interval: Duration,
watering_duration: Duration,
}

struct State {
pump_on: bool,
pump_on_at: Instant,
pump_off_at: Instant,
watering_interval: Duration,
watering_duration: Duration,
}
«`

This script requires a configuration file in YAML format, with the following structure:

«`yaml
watering_interval: 600 # in seconds
watering_duration: 60 # in seconds
«`

The script will start a thread that controls the watering pump, based on the configuration and user input. User input can be:

* `on`: Start watering immediately
* `off`: Stop watering immediately
* `quit`: Exit the script

The script will continue running until the user enters `quit`.