bc2f6eeecec449143af38fddfe64d7f746c3f54b
[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 mut machine: Box<dyn machine::Machine> = match settings.machine_name {
27 settings::MachineName::Jiji => {
28 Box::new(machine::MachineJiji::new().expect("Unable to create MachineJiji"))
29 }
30 settings::MachineName::LyssMetal => {
31 Box::new(machine::MachineLyssMetal::new().expect("Unable to create MachineLyssMetal"))
32 }
33 };
34
35 let mut kernel = [0f32; consts::KERNEL_SIZE_SAMPLES];
36 let mut current_pos = 0usize;
37
38 let mut tick = 0i64;
39 let period = Duration::from_micros(1_000_000u64 / consts::FREQ_TEMP_POLLING as u64);
40
41 loop {
42 if completed.load(Ordering::Relaxed) {
43 break;
44 }
45
46 let time_beginning_loop = time::Instant::now();
47
48 let temp = (machine.get_cpu_tmp() + machine.get_gpu_tmp()) / 2f32;
49 kernel[current_pos] = temp;
50 current_pos = (current_pos + 1) % consts::KERNEL_SIZE_SAMPLES;
51 let mean_temp = {
52 let mut s = 0f32;
53 for t in kernel {
54 s += t;
55 }
56 s / kernel.len() as f32
57 };
58
59 let normalized_temp = num::clamp(
60 (mean_temp - settings.cold_temperature)
61 / (settings.hot_temperature - settings.cold_temperature),
62 0f32,
63 1f32,
64 ); // Between 0 (cold) and 1 (hot).
65
66 let color =
67 rgb::linear_interpolation(settings.cold_color, settings.hot_color, normalized_temp);
68
69 // println!("normalized_temp: {normalized_temp}");
70
71 if tick % (consts::FREQ_TEMP_POLLING / consts::FREQ_REFRESHING_RGB) as i64 == 0 {
72 println!("Update RGB: {color:?}, temp: {mean_temp}");
73 machine.set_color(&color);
74 }
75
76 let elapsed = time::Instant::now() - time_beginning_loop;
77 if elapsed < period {
78 let to_wait = period - elapsed;
79 sleep.wait(to_wait);
80 }
81 tick += 1;
82 }
83
84 // println!("Press any key to continue...");
85 // std::io::stdin().read_line(&mut String::new()).unwrap();
86
87 winring0::deinit();
88 }