Capstone: A Tested, Threaded Wind Farm Monitor
Combine everything in a complete Rust project: a generated data set, one thread per turbine, enums and match, Result errors, a sorted report and a passing test suite, all verified with an independent Python implementation.
In this lesson you will
- Structure a complete cargo project
- Combine threads, enums and tests
- Produce a deterministic report
- Cross-check with Python
About 28 minutes
The finished monitor
The capstone assembles the whole course into one program, the monitor that Ines set out to build in lesson 1. It generates a deterministic day of readings for four turbines, using a simple linear congruential generator so that the data is the same on every run and the same in Python, analyses each turbine on its own thread, classifies each hour with the enum and match from lesson 5, counts alarms, reports the figures in sorted order, and carries a test module that checks the pieces. The program uses only the standard library.
The structure is the one you have learned. A Class enum with derive covers calm, working, strong and storm, a Stats struct collects the numbers, a function analyse takes a slice and returns a Stats or an error for empty input, and the threads send their results through a channel, which the main thread sorts by turbine id before printing. The generator and the analysis are separate functions, so that they can be tested separately, and everything that could fail returns a Result.
use std::fmt;
use std::sync::mpsc;
use std::thread;
#[derive(Debug, Clone, Copy, PartialEq)]
enum Class { Calm, Working, Strong, Storm }
impl Class {
fn of(speed: f64) -> Class {
match speed as u32 {
0..=3 => Class::Calm,
4..=14 => Class::Working,
15..=24 => Class::Strong,
_ => Class::Storm,
}
}
}
#[derive(Debug)]
struct Stats { id: u32, hours: usize, mean: f64, max: f64, strong: usize, longest_strong: usize }
#[derive(Debug, PartialEq)]
enum MonitorError { NoData(u32) }
impl fmt::Display for MonitorError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { MonitorError::NoData(id) => write!(f, "turbine {} has no data", id) }
}
}
fn generate(seed: u64, hours: usize) -> Vec<f64> {
let mut state = seed;
let mut out = Vec::with_capacity(hours);
for _ in 0..hours {
state = (state.wrapping_mul(1103515245).wrapping_add(12345)) % 2147483648;
out.push(3.0 + (state % 1500) as f64 / 100.0);
}
out
}
fn analyse(id: u32, data: &[f64]) -> Result<Stats, MonitorError> {
if data.is_empty() { return Err(MonitorError::NoData(id)); }
let mut sum = 0.0;
let mut max = f64::MIN;
let mut strong = 0;
let mut run = 0;
let mut longest = 0;
for &s in data {
sum += s;
if s > max { max = s; }
if matches!(Class::of(s), Class::Strong | Class::Storm) {
strong += 1;
run += 1;
if run > longest { longest = run; }
} else {
run = 0;
}
}
Ok(Stats { id, hours: data.len(), mean: sum / data.len() as f64, max, strong, longest_strong: longest })
}
fn main() {
let (tx, rx) = mpsc::channel();
for id in 1..=4u32 {
let tx = tx.clone();
thread::spawn(move || {
let hours = if id == 4 { 0 } else { 24 };
let data = generate(id as u64 * 7919, hours);
tx.send(analyse(id, &data)).unwrap();
});
}
drop(tx);
let mut ok = Vec::new();
let mut errors = Vec::new();
for r in rx { match r { Ok(s) => ok.push(s), Err(e) => errors.push(e) } }
ok.sort_by_key(|s| s.id);
println!("{:<8}{:>6}{:>9}{:>8}{:>8}{:>9}", "turbine", "hours", "mean", "max", "strong", "longest");
for s in &ok {
println!("{:<8}{:>6}{:>9.3}{:>8.2}{:>8}{:>9}", s.id, s.hours, s.mean, s.max, s.strong, s.longest_strong);
}
for e in &errors { println!("error: {}", e); }
let total: usize = ok.iter().map(|s| s.strong).sum();
println!("strong hours across the farm: {}", total);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generator_is_deterministic() {
assert_eq!(generate(7919, 5), generate(7919, 5));
assert_ne!(generate(7919, 5), generate(15838, 5));
}
#[test]
fn generator_stays_in_range() {
assert!(generate(1, 1000).iter().all(|s| (3.0..18.0).contains(s)));
}
#[test]
fn classes() {
assert_eq!(Class::of(3.9), Class::Calm);
assert_eq!(Class::of(14.99), Class::Working);
assert_eq!(Class::of(15.0), Class::Strong);
assert_eq!(Class::of(30.0), Class::Storm);
}
#[test]
fn longest_run() {
let s = analyse(1, &[1.0, 16.0, 17.0, 5.0, 20.0]).unwrap();
assert_eq!((s.strong, s.longest_strong), (3, 2));
}
#[test]
fn empty_data_is_an_error() {
assert_eq!(analyse(9, &[]).unwrap_err(), MonitorError::NoData(9));
}
}
turbine hours mean max strong longest
1 24 10.495 17.98 7 2
2 24 11.802 17.40 9 1
3 24 10.500 17.44 6 2
error: turbine 4 has no data
strong hours across the farm: 22
running 5 tests
test tests::classes ... ok
test tests::empty_data_is_an_error ... ok
test tests::generator_is_deterministic ... ok
test tests::generator_stays_in_range ... ok
test tests::longest_run ... ok
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Finished `dev` profile
The monitor ran four threads, one per turbine, and printed the table above. Turbine 4 was given no data on purpose, to exercise the error path, and it produced the message “turbine 4 has no data” through the Display implementation instead of crashing the farm. The three working turbines each analysed 24 hours of generated readings: turbine 1 had mean 10.495, maximum 17.98, 7 strong hours and a longest strong run of 2 hours; turbine 2 had mean 11.802, maximum 17.40, 9 strong hours and a longest strong run of 1 hours; turbine 3 had mean 10.500, maximum 17.44, 6 strong hours and a longest strong run of 2 hours. Across the farm there were 22 strong hours. The channel delivered the results in whatever order the threads finished, and sorting by id made the report identical on every run.
The test suite, with five tests, passed: “test result: ok. 5 passed; 0 failed”. The tests check that the generator is deterministic and stays within 3 to 18 metres per second, that the class boundaries behave, that the longest strong run of the sequence 1, 16, 17, 5, 20 is 2 hours with 3 strong hours in all, and that empty data gives the error. Together they cover the logic that matters and take a fraction of a second to run.
Independent check: a Python script reproduced the generator with the same constants, classified the same readings with the same boundaries, and counted the same strong hours and runs, without any code shared with the Rust program. Every row of the table, including the means to three decimals and the maxima to two, and the farm total match. That agreement, between two implementations in two languages, is strong evidence that the Rust logic does what the specification says.
Check by hand with the test case: for the readings 1, 16, 17, 5 and 20, the strong readings are 16, 17 and 20, a total of three, and the longest consecutive run is the pair 16 and 17, so the test expects the pair (3, 2). The generator uses wrapping arithmetic modulo 2 to the power 31, so a speed is always 3 plus a number between 0 and 14.99, which is why every reading is between 3.00 and 17.99.
Where to go next
- Read The Rust Programming Language, the free official book, and Rust by Example, at doc.rust-lang.org.
- Use crates from crates.io for what the standard library lacks: serde for data formats, clap for command lines, tokio for async. Check each crate’s current documentation.
- Run cargo clippy and cargo fmt on every project, and keep the tests in your continuous integration.
- Read other people’s code: the standard library and popular crates are open source.
- Build something real: a command-line tool for your own files, or a small web service.
The Rust program above is correct, and the cross-check is how we know. For any code that produces numbers someone will rely on, compare it with an independent calculation, even a rough one, before trusting it.
A random generator seeded with a fixed value gives repeatable test data. Real randomness in tests makes failures hard to reproduce.
Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording. You have now completed the Rust course. Library versions and the ecosystem change, so check crates.io for current crates.
Practice
Add a fifth turbine with 48 hours of data, add a column for the hour of the maximum, and write a test for it. Write the report to a file as CSV, as in lesson 12. Replace the channel with Arc<Mutex<Vec>> and compare the two designs.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why sort the results before printing?
- Rust requires it
- To save memory
- To compile faster
- Threads finish in unpredictable order
Repeatable output.
Why is the generator deterministic?
- It reads the clock
- It uses true randomness
- It uses a fixed seed and arithmetic
- It uses threads
So that tests and Python agree.
What does turbine 4 demonstrate?
- A panic
- A race
- The error path with a Result
- A lifetime
The Display message is shown.
How was the output verified?
- By eye
- A separate Python implementation
- By another thread
- It was not
Two implementations, one answer.
What does matches! do here?
- Prints
- Tests a value against patterns
- Sorts
- Clones
Used for the strong or storm check.
Summary
- A complete project: generator, enum classification, threads, channel, Result errors, report and tests.
- Deterministic data makes results and tests repeatable.
- An independent Python implementation confirms the numbers.
- The standard library alone goes a long way; add crates when you need them.
Questions
What should I learn after this course?
The official book, then a real project. Learn traits in more depth, error handling libraries, async Rust and unsafe code last. Check doc.rust-lang.org for the current learning resources.
Can I use this in my job?
Rust is used for systems software, command-line tools, WebAssembly and network services. Check current job listings in your region, since demand changes.
Is the program fast?
It is compiled to native code, and for such a small data set the time is negligible. Use cargo build --release and measure before optimising anything.
