Add support to 'shutdown' signal
authorGreg Burri <greg.burri@gmail.com>
Tue, 19 Sep 2023 12:17:30 +0000 (14:17 +0200)
committerGreg Burri <greg.burri@gmail.com>
Tue, 19 Sep 2023 12:17:30 +0000 (14:17 +0200)
from the Windows services system

Cargo.toml
IntelOC/IntelOC.csproj
src/a770.rs
src/main.rs

index 0089ff5..59c3461 100644 (file)
@@ -14,6 +14,12 @@ ron = "0.8" # Rust object notation, to load configuration files.
 
 num = "0.4"
 
+dirs = "5.0"
+anyhow = "1.0"
+
+flexi_logger = "0.26"
+log = "0.4"
+
 windows-service = "0.6"
 
 hidapi = "2.4"
index 8a0b3ce..0a2d496 100644 (file)
@@ -16,7 +16,7 @@
   </ItemGroup>
 
   <Target Name="PostBuild" AfterTargets="PostBuildEvent">
-    <Exec Command="copy $(ProjectDir)$(OutDir)$(ProjectName)* $(ProjectDir)..\target\release&#xD;&#xA;" />
+    <Exec Command="copy $(ProjectDir)$(OutDir)$(ProjectName)* $(ProjectDir)..\target\$(Configuration)&#xD;&#xA;" />
   </Target>
 
 </Project>
index b37d742..29c3028 100644 (file)
@@ -70,5 +70,6 @@ impl A770 {
 impl Drop for A770 {
     fn drop(&mut self) {
         self.process.kill().unwrap();
+        self.process.try_wait().unwrap();
     }
 }
index 432d51e..5f6e55a 100644 (file)
@@ -13,6 +13,8 @@ use std::{
     time::{self, Duration},
 };
 
+use anyhow::Result;
+use log::{error, info, trace, warn, debug};
 use windows::Win32::Foundation::{ERROR_SERVICE_DOES_NOT_EXIST, WIN32_ERROR};
 use windows_service::{
     service::{
@@ -53,10 +55,28 @@ mod sensors_jiji;
 mod settings;
 mod timer;
 
-fn main() -> Result<(), windows_service::Error> {
+fn main() -> Result<()> {
+    let is_debug = cfg!(debug_assertions);
+
+    flexi_logger::Logger::try_with_str(if is_debug { "debug" } else { "info" })?
+        .log_to_file(
+            flexi_logger::FileSpec::default()
+                .directory(dirs::config_dir().unwrap().join(consts::SERVICE_NAME))
+                .basename(consts::SERVICE_NAME),
+        )
+        .duplicate_to_stdout(flexi_logger::Duplicate::All)
+        .format(if is_debug { flexi_logger::default_format } else { flexi_logger::detailed_format })
+        .rotate(
+            flexi_logger::Criterion::Size(1024 * 1024),
+            flexi_logger::Naming::Timestamps,
+            flexi_logger::Cleanup::KeepLogFiles(10),
+        )
+        .print_message()
+        .start()?;
+
     let args: Vec<String> = env::args().collect();
 
-    println!("Temperature to RGB");
+    info!("Temperature to RGB");
 
     if args.contains(&"--no-service".to_string()) {
         let completed: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
@@ -100,7 +120,7 @@ fn install_service() -> windows_service::Result<()> {
     };
     let service = service_manager.create_service(&service_info, ServiceAccess::CHANGE_CONFIG)?;
     service.set_description(
-        "A service to set the color of hardware according to the temperatur of GPU and CPU",
+        "A service to set the color of hardware according to the temperature of GPU and CPU",
     )?;
     Ok(())
 }
@@ -152,7 +172,7 @@ fn service_main(arguments: Vec<OsString>) {
     }
 }
 
-fn run_service(arguments: Vec<OsString>) -> Result<(), windows_service::Error> {
+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);
@@ -163,11 +183,11 @@ fn run_service(arguments: Vec<OsString>) -> Result<(), windows_service::Error> {
                 // Handle stop event and return control back to the system.
                 ServiceControlHandlerResult::NoError
             }
-            // ServiceControl::Shutdown => {
-            //     completed_event_handler.store(true, Ordering::Relaxed);
-            //     // Handle stop event and return control back to the system.
-            //     ServiceControlHandlerResult::NoError
-            // }
+            ServiceControl::Shutdown => {
+                completed_event_handler.store(true, Ordering::Relaxed);
+                // Handle stop event and return control back to the system.
+                ServiceControlHandlerResult::NoError
+            }
             // ServiceControl::Preshutdown => {
             //     completed_event_handler.store(true, Ordering::Relaxed);
             //     ServiceControlHandlerResult::NoError
@@ -192,7 +212,7 @@ fn run_service(arguments: Vec<OsString>) -> Result<(), windows_service::Error> {
         current_state: ServiceState::Running,
 
         // Accept stop events when running
-        controls_accepted: ServiceControlAccept::STOP, // | ServiceControlAccept::SHUTDOWN,
+        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),
@@ -220,6 +240,8 @@ fn run_service(arguments: Vec<OsString>) -> Result<(), windows_service::Error> {
         process_id: None,
     })?;
 
+    info!("Main loop stopped: Temperature to RGB will now shut down");
+
     Ok(())
 }