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