Add a color (2 colors can be now defined for a machine).
[temp2RGB.git] / src / main.rs
index 5f6e55a..a0443f7 100644 (file)
@@ -2,7 +2,6 @@
 extern crate windows_service;
 
 use std::{
-    collections::HashMap,
     env,
     ffi::OsString,
     sync::{
@@ -14,7 +13,7 @@ use std::{
 };
 
 use anyhow::Result;
-use log::{error, info, trace, warn, debug};
+use log::{debug, error, info, trace, warn};
 use windows::Win32::Foundation::{ERROR_SERVICE_DOES_NOT_EXIST, WIN32_ERROR};
 use windows_service::{
     service::{
@@ -25,36 +24,37 @@ use windows_service::{
     service_dispatcher,
     service_manager::{ServiceManager, ServiceManagerAccess},
 };
-use wmi::{COMLibrary, Variant, WMIConnection};
-
-use crate::rgb::RGB;
 
 define_windows_service!(ffi_service_main, service_main);
 
-mod winring0 {
+mod wrapper_winring0 {
     #![allow(warnings, unused)]
     include!(concat!(env!("OUT_DIR"), "/ols_api.rs"));
 }
-
 mod intel_arc {
     #![allow(warnings, unused)]
     include!(concat!(env!("OUT_DIR"), "/intel_arc.rs"));
 }
-
 mod a770;
-mod b650_e;
+mod asus_aura_usb;
+mod corsair_lighting_pro;
+mod lian_li_sl_infinity;
 mod machine;
 mod main_loop;
+mod winring0;
 // mod common;
 mod consts;
 mod corsair_vengeance;
 mod piix4_i2c;
 mod rgb;
 // mod roccat; Disabled.
-mod sensors_jiji;
+mod cpu_temperature;
 mod settings;
+mod tests;
 mod timer;
 
+// Important: when starting as a service, the directory where the log and config files
+// are put is 'C:\Windows\System32\config\systemprofile\AppData\Roaming\Temp2RGB'.
 fn main() -> Result<()> {
     let is_debug = cfg!(debug_assertions);
 
@@ -65,7 +65,11 @@ fn main() -> Result<()> {
                 .basename(consts::SERVICE_NAME),
         )
         .duplicate_to_stdout(flexi_logger::Duplicate::All)
-        .format(if is_debug { flexi_logger::default_format } else { flexi_logger::detailed_format })
+        .format(if is_debug {
+            flexi_logger::default_format
+        } else {
+            flexi_logger::detailed_format
+        })
         .rotate(
             flexi_logger::Criterion::Size(1024 * 1024),
             flexi_logger::Naming::Timestamps,
@@ -74,6 +78,8 @@ fn main() -> Result<()> {
         .print_message()
         .start()?;
 
+    log_panics::init();
+
     let args: Vec<String> = env::args().collect();
 
     info!("Temperature to RGB");
@@ -82,7 +88,7 @@ fn main() -> Result<()> {
         let completed: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
         main_loop::main_loop(completed.clone());
     } else if args.contains(&"--tests".to_string()) {
-        tests();
+        tests::tests();
     } else if args.contains(&"--install-service".to_string()) {
         println!("Installing service...");
         install_service()?;
@@ -168,7 +174,7 @@ fn uninstall_service() -> windows_service::Result<()> {
 
 fn service_main(arguments: Vec<OsString>) {
     if let Err(error) = run_service(arguments) {
-        println!("Error: {error}");
+        error!("{error}");
     }
 }
 
@@ -176,6 +182,9 @@ fn run_service(_arguments: Vec<OsString>) -> Result<(), windows_service::Error>
     let completed: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
 
     let completed_event_handler = Arc::clone(&completed);
+
+    info!("Setuping the event handler...");
+
     let event_handler = move |control_event| -> ServiceControlHandlerResult {
         match control_event {
             ServiceControl::Stop => {
@@ -204,29 +213,15 @@ fn run_service(_arguments: Vec<OsString>) -> Result<(), windows_service::Error>
     // Register system service event handler
     let status_handle = service_control_handler::register(consts::SERVICE_NAME, event_handler)?;
 
-    let running_status = ServiceStatus {
-        // Should match the one from system service registry
+    status_handle.set_service_status(ServiceStatus {
         service_type: ServiceType::OWN_PROCESS,
-
-        // The new state
         current_state: ServiceState::Running,
-
-        // Accept stop events when running
         controls_accepted: ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN,
-
-        // Used to report an error when starting or stopping only, otherwise must be zero
         exit_code: ServiceExitCode::Win32(0),
-
-        // Only used for pending states, otherwise must be zero
         checkpoint: 0,
-
-        // Only used for pending states, otherwise must be zero
         wait_hint: Duration::default(),
-
-        process_id: None,
-    };
-
-    status_handle.set_service_status(running_status)?;
+        process_id: None, //Some(std::process::id()),
+    })?;
 
     main_loop::main_loop(completed.clone());
 
@@ -237,133 +232,10 @@ fn run_service(_arguments: Vec<OsString>) -> Result<(), windows_service::Error>
         exit_code: ServiceExitCode::Win32(0),
         checkpoint: 0,
         wait_hint: Duration::default(),
-        process_id: None,
+        process_id: None, //Some(std::process::id()),
     })?;
 
     info!("Main loop stopped: Temperature to RGB will now shut down");
 
     Ok(())
 }
-
-fn tests() {
-    println!("Running some tests...");
-
-    // test_b650_e();
-    // list_usb_devices();
-    // test_roccat();
-    // test_wmi();
-    // test_corsair();
-    test_a770();
-    // test_read_temp();
-
-    println!("Press any key to continue...");
-    std::io::stdin().read_line(&mut String::new()).unwrap();
-}
-
-fn test_wmi() {
-    let com_con = COMLibrary::new().unwrap();
-    let wmi_con = WMIConnection::new(com_con.into()).unwrap();
-
-    //let results: Vec<HashMap<String, Variant>> = wmi_con.raw_query("SELECT * FROM Win32_PnPSignedDriver WHERE Description LIKE '%SMBUS%' OR Description LIKE '%SM BUS%'").unwrap();
-    //let results: Vec<HashMap<String, Variant>> = wmi_con.raw_query("SELECT * FROM Win32_PnPSignedDriver WHERE Description LIKE 'Intel(R) NF I2C Host Controller'").unwrap();
-    let results: Vec<HashMap<String, Variant>> = wmi_con
-        .raw_query("SELECT * FROM Win32_PnPSignedDriver")
-        .unwrap();
-    //let results: Vec<HashMap<String, Variant>> = wmi_con.raw_query("SELECT * FROM Win32_PnPAllocatedResource").unwrap();
-
-    for os in results {
-        println!("-------------------");
-        println!("{:#?}", os);
-    }
-}
-fn list_usb_devices() {
-    let api = hidapi::HidApi::new().unwrap();
-    for device in api.device_list() {
-        println!("{:?}", device);
-        println!("name: {}", device.product_string().unwrap());
-        println!("interface number: {}", device.interface_number());
-        println!("page: {}", device.usage_page());
-        println!("usage: {}", device.usage());
-        println!("----");
-    }
-}
-
-// fn test_roccat() {
-//     let api = hidapi::HidApi::new().unwrap();
-//     let roccat_device = roccat::get_device(&api);
-
-//     let manufacturer = roccat_device.get_manufacturer_string().unwrap();
-//     dbg!(manufacturer);
-
-//     let product = roccat_device.get_product_string().unwrap();
-//     dbg!(product);
-
-//     let serial = roccat_device.get_serial_number_string().unwrap();
-//     dbg!(serial);
-
-//     roccat::init(&roccat_device);
-//     roccat::set_color(
-//         &roccat_device,
-//         &RGB {
-//             red: 0,
-//             green: 255,
-//             blue: 40,
-//         },
-//     );
-// }
-
-fn test_b650_e() {
-    let api = hidapi::HidApi::new().unwrap();
-
-    let b650e_device = b650_e::get_device(&api);
-
-    println!("Firmware: {}", b650_e::get_firmware_string(&b650e_device));
-
-    let configuration = b650_e::get_configuration_table(&b650e_device);
-    println!("Configuration:");
-    for i in 0..60 {
-        print!("{:02X} ", configuration[i]);
-        if (i + 1) % 6 == 0 {
-            println!("");
-        }
-    }
-
-    // Only once, at start.
-    b650_e::set_fixed_mode(&b650e_device);
-
-    b650_e::set_color(
-        &b650e_device,
-        &RGB {
-            red: 255,
-            green: 0,
-            blue: 0,
-        },
-    );
-    b650_e::save_current_color(&b650e_device);
-}
-
-fn test_corsair() {
-    let corsair_controllers = [
-        corsair_vengeance::Controller::new(0x19),
-        corsair_vengeance::Controller::new(0x1B),
-    ];
-    for controller in corsair_controllers {
-        controller.set_color(&RGB {
-            red: 255,
-            green: 0,
-            blue: 0,
-        });
-    }
-}
-
-fn test_a770() {
-    // a770::set_rgb(255, 0, 0);
-    let mut a770 = a770::A770::new();
-    a770.set_color(255, 0, 0);
-}
-
-fn test_read_temp() {
-    let sensors = sensors_jiji::Sensors::new();
-    println!("temp cpu: {}", sensors.read_cpu_temp());
-    println!("temp gpu: {}", sensors.read_gpu_temp());
-}