ae4c2215702dd5ca71bc8dfabc576a32622ed504
[temp2RGB.git] / src / main_loop.rs
1 use std::{
2 sync::{
3 atomic::{AtomicBool, Ordering},
4 Arc,
5 },
6 time::{self, Duration},
7 };
8
9 use crate::{consts, machine, rgb, settings, timer, winring0};
10
11 pub fn main_loop(completed: Arc<AtomicBool>) {
12 if consts::FREQ_REFRESHING_RGB > consts::FREQ_TEMP_POLLING {
13 panic!("Polling frequency must be greater or equal than RGB refresh frequency");
14 }
15
16 if consts::FREQ_TEMP_POLLING % consts::FREQ_REFRESHING_RGB != 0 {
17 panic!("Polling frequency must be a multiple of RGB refresh frequency");
18 }
19
20 winring0::init();
21
22 let sleep = timer::Sleep::new();
23 let settings = settings::Settings::read(consts::FILE_CONF).expect("Cannot load settings");
24 println!("Settings: {settings:?}");
25
26 let machine: &mut dyn machine::Machine = &mut machine::MachineJiji::new();
27
28 let mut kernel = [0f32; consts::KERNEL_SIZE_SAMPLES];
29 let mut current_pos = 0usize;
30
31 let mut tick = 0i64;
32 let period = Duration::from_micros(1_000_000u64 / consts::FREQ_TEMP_POLLING as u64);
33
34 loop {
35 if completed.load(Ordering::Relaxed) {
36 break;
37 }
38
39 let time_beginning_loop = time::Instant::now();
40
41 let temp = (machine.get_cpu_tmp() + machine.get_gpu_tmp()) / 2f32;
42 kernel[current_pos] = temp;
43 current_pos = (current_pos + 1) % consts::KERNEL_SIZE_SAMPLES;
44 let mean_temp = {
45 let mut s = 0f32;
46 for t in kernel {
47 s += t;
48 }
49 s / kernel.len() as f32
50 };
51
52 let normalized_temp = num::clamp(
53 (mean_temp - settings.cold_temperature)
54 / (settings.hot_temperature - settings.cold_temperature),
55 0f32,
56 1f32,
57 ); // Between 0 (cold) and 1 (hot).
58
59 let color =
60 rgb::linear_interpolation(settings.cold_color, settings.hot_color, normalized_temp);
61
62 // println!("normalized_temp: {normalized_temp}");
63
64 if tick % (consts::FREQ_TEMP_POLLING / consts::FREQ_REFRESHING_RGB) as i64 == 0 {
65 println!("Update RGB: {color:?}, temp: {mean_temp}");
66 machine.set_color(&color);
67 }
68
69 let elapsed = time::Instant::now() - time_beginning_loop;
70 if elapsed < period {
71 let to_wait = period - elapsed;
72 sleep.wait(to_wait);
73 }
74 tick += 1;
75 }
76
77 // println!("Press any key to continue...");
78 // std::io::stdin().read_line(&mut String::new()).unwrap();
79
80 winring0::deinit();
81 }