Cargo fmt
[temp2RGB.git] / src / main.rs
1 #[macro_use]
2 extern crate windows_service;
3
4 use std::{
5 collections::HashMap,
6 env,
7 ffi::OsString,
8 sync::{
9 atomic::{AtomicBool, Ordering},
10 Arc,
11 },
12 thread::sleep,
13 time::{self, Duration},
14 };
15
16 use anyhow::Result;
17 use log::{debug, error, info, trace, warn};
18 use windows::Win32::Foundation::{ERROR_SERVICE_DOES_NOT_EXIST, WIN32_ERROR};
19 use windows_service::{
20 service::{
21 ServiceAccess, ServiceControl, ServiceControlAccept, ServiceErrorControl, ServiceExitCode,
22 ServiceInfo, ServiceStartType, ServiceState, ServiceStatus, ServiceType,
23 },
24 service_control_handler::{self, ServiceControlHandlerResult, ServiceStatusHandle},
25 service_dispatcher,
26 service_manager::{ServiceManager, ServiceManagerAccess},
27 };
28 use wmi::{COMLibrary, Variant, WMIConnection};
29
30 use crate::rgb::RGB;
31
32 define_windows_service!(ffi_service_main, service_main);
33
34 mod winring0 {
35 #![allow(warnings, unused)]
36 include!(concat!(env!("OUT_DIR"), "/ols_api.rs"));
37 }
38
39 mod intel_arc {
40 #![allow(warnings, unused)]
41 include!(concat!(env!("OUT_DIR"), "/intel_arc.rs"));
42 }
43
44 mod a770;
45 mod b650_e;
46 mod machine;
47 mod main_loop;
48 // mod common;
49 mod consts;
50 mod corsair_vengeance;
51 mod piix4_i2c;
52 mod rgb;
53 // mod roccat; Disabled.
54 mod sensors_jiji;
55 mod settings;
56 mod timer;
57
58 fn main() -> Result<()> {
59 let is_debug = cfg!(debug_assertions);
60
61 flexi_logger::Logger::try_with_str(if is_debug { "debug" } else { "info" })?
62 .log_to_file(
63 flexi_logger::FileSpec::default()
64 .directory(dirs::config_dir().unwrap().join(consts::SERVICE_NAME))
65 .basename(consts::SERVICE_NAME),
66 )
67 .duplicate_to_stdout(flexi_logger::Duplicate::All)
68 .format(if is_debug {
69 flexi_logger::default_format
70 } else {
71 flexi_logger::detailed_format
72 })
73 .rotate(
74 flexi_logger::Criterion::Size(1024 * 1024),
75 flexi_logger::Naming::Timestamps,
76 flexi_logger::Cleanup::KeepLogFiles(10),
77 )
78 .print_message()
79 .start()?;
80
81 let args: Vec<String> = env::args().collect();
82
83 info!("Temperature to RGB");
84
85 if args.contains(&"--no-service".to_string()) {
86 let completed: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
87 main_loop::main_loop(completed.clone());
88 } else if args.contains(&"--tests".to_string()) {
89 tests();
90 } else if args.contains(&"--install-service".to_string()) {
91 println!("Installing service...");
92 install_service()?;
93 } else if args.contains(&"--uninstall-service".to_string()) {
94 println!("Uninstalling service...");
95 uninstall_service()?;
96 } else {
97 service_dispatcher::start(consts::SERVICE_NAME, ffi_service_main)?;
98 }
99
100 Ok(())
101 }
102
103 fn install_service() -> windows_service::Result<()> {
104 let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
105 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
106
107 let service_binary_path = std::env::current_exe()
108 .unwrap()
109 .with_file_name("temp_2_rgb.exe");
110
111 println!("Installing service: {service_binary_path:?}");
112
113 let service_info = ServiceInfo {
114 name: OsString::from(consts::SERVICE_NAME),
115 display_name: OsString::from(consts::SERVICE_NAME),
116 service_type: ServiceType::OWN_PROCESS,
117 start_type: ServiceStartType::AutoStart,
118 error_control: ServiceErrorControl::Normal,
119 executable_path: service_binary_path,
120 launch_arguments: vec![],
121 dependencies: vec![],
122 account_name: None, // run as System
123 account_password: None,
124 };
125 let service = service_manager.create_service(&service_info, ServiceAccess::CHANGE_CONFIG)?;
126 service.set_description(
127 "A service to set the color of hardware according to the temperature of GPU and CPU",
128 )?;
129 Ok(())
130 }
131
132 fn uninstall_service() -> windows_service::Result<()> {
133 let manager_access = ServiceManagerAccess::CONNECT;
134 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
135
136 let service_access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE;
137 let service = service_manager.open_service(consts::SERVICE_NAME, service_access)?;
138
139 // The service will be marked for deletion as long as this function call succeeds.
140 // However, it will not be deleted from the database until it is stopped and all open handles to it are closed.
141 service.delete()?;
142
143 // Our handle to it is not closed yet. So we can still query it.
144 if service.query_status()?.current_state != ServiceState::Stopped {
145 // If the service cannot be stopped, it will be deleted when the system restarts.
146 service.stop()?;
147 }
148
149 // Explicitly close our open handle to the service. This is automatically called when `service` goes out of scope.
150 drop(service);
151
152 // Win32 API does not give us a way to wait for service deletion.
153 // To check if the service is deleted from the database, we have to poll it ourselves.
154 let start = time::Instant::now();
155 let timeout = Duration::from_secs(5);
156 while start.elapsed() < timeout {
157 if let Err(windows_service::Error::Winapi(e)) =
158 service_manager.open_service(consts::SERVICE_NAME, ServiceAccess::QUERY_STATUS)
159 {
160 let WIN32_ERROR(error_num) = ERROR_SERVICE_DOES_NOT_EXIST;
161 if e.raw_os_error() == Some(error_num as i32) {
162 println!("{} is deleted.", consts::SERVICE_NAME);
163 return Ok(());
164 }
165 }
166 sleep(Duration::from_secs(1));
167 }
168 println!("{} is marked for deletion.", consts::SERVICE_NAME);
169
170 Ok(())
171 }
172
173 fn service_main(arguments: Vec<OsString>) {
174 if let Err(error) = run_service(arguments) {
175 error!("{error}");
176 }
177 }
178
179 fn run_service(_arguments: Vec<OsString>) -> Result<(), windows_service::Error> {
180 let completed: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
181
182 let completed_event_handler = Arc::clone(&completed);
183
184 info!("Setuping the event handler...");
185
186 let event_handler = move |control_event| -> ServiceControlHandlerResult {
187 match control_event {
188 ServiceControl::Stop => {
189 completed_event_handler.store(true, Ordering::Relaxed);
190 // Handle stop event and return control back to the system.
191 ServiceControlHandlerResult::NoError
192 }
193 ServiceControl::Shutdown => {
194 completed_event_handler.store(true, Ordering::Relaxed);
195 // Handle stop event and return control back to the system.
196 ServiceControlHandlerResult::NoError
197 }
198 // ServiceControl::Preshutdown => {
199 // completed_event_handler.store(true, Ordering::Relaxed);
200 // ServiceControlHandlerResult::NoError
201 // }
202 // ServiceControl::PowerEvent(param) => {
203 // ServiceControlHandlerResult::NotImplemented
204 // }
205 // All services must accept Interrogate even if it's a no-op.
206 ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
207 _ => ServiceControlHandlerResult::NotImplemented,
208 }
209 };
210
211 // Register system service event handler
212 let status_handle = service_control_handler::register(consts::SERVICE_NAME, event_handler)?;
213
214 status_handle.set_service_status(ServiceStatus {
215 service_type: ServiceType::OWN_PROCESS,
216 current_state: ServiceState::Running,
217 controls_accepted: ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN,
218 exit_code: ServiceExitCode::Win32(0),
219 checkpoint: 0,
220 wait_hint: Duration::default(),
221 process_id: None, //Some(std::process::id()),
222 })?;
223
224 main_loop::main_loop(completed.clone());
225
226 status_handle.set_service_status(ServiceStatus {
227 service_type: ServiceType::OWN_PROCESS,
228 current_state: ServiceState::Stopped,
229 controls_accepted: ServiceControlAccept::empty(),
230 exit_code: ServiceExitCode::Win32(0),
231 checkpoint: 0,
232 wait_hint: Duration::default(),
233 process_id: None, //Some(std::process::id()),
234 })?;
235
236 info!("Main loop stopped: Temperature to RGB will now shut down");
237
238 Ok(())
239 }
240
241 fn tests() {
242 println!("Running some tests...");
243
244 // test_b650_e();
245 // list_usb_devices();
246 // test_roccat();
247 // test_wmi();
248 // test_corsair();
249 test_a770();
250 // test_read_temp();
251
252 println!("Press any key to continue...");
253 std::io::stdin().read_line(&mut String::new()).unwrap();
254 }
255
256 fn test_wmi() {
257 let com_con = COMLibrary::new().unwrap();
258 let wmi_con = WMIConnection::new(com_con.into()).unwrap();
259
260 //let results: Vec<HashMap<String, Variant>> = wmi_con.raw_query("SELECT * FROM Win32_PnPSignedDriver WHERE Description LIKE '%SMBUS%' OR Description LIKE '%SM BUS%'").unwrap();
261 //let results: Vec<HashMap<String, Variant>> = wmi_con.raw_query("SELECT * FROM Win32_PnPSignedDriver WHERE Description LIKE 'Intel(R) NF I2C Host Controller'").unwrap();
262 let results: Vec<HashMap<String, Variant>> = wmi_con
263 .raw_query("SELECT * FROM Win32_PnPSignedDriver")
264 .unwrap();
265 //let results: Vec<HashMap<String, Variant>> = wmi_con.raw_query("SELECT * FROM Win32_PnPAllocatedResource").unwrap();
266
267 for os in results {
268 println!("-------------------");
269 println!("{:#?}", os);
270 }
271 }
272 fn list_usb_devices() {
273 let api = hidapi::HidApi::new().unwrap();
274 for device in api.device_list() {
275 println!("{:?}", device);
276 println!("name: {}", device.product_string().unwrap());
277 println!("interface number: {}", device.interface_number());
278 println!("page: {}", device.usage_page());
279 println!("usage: {}", device.usage());
280 println!("----");
281 }
282 }
283
284 // fn test_roccat() {
285 // let api = hidapi::HidApi::new().unwrap();
286 // let roccat_device = roccat::get_device(&api);
287
288 // let manufacturer = roccat_device.get_manufacturer_string().unwrap();
289 // dbg!(manufacturer);
290
291 // let product = roccat_device.get_product_string().unwrap();
292 // dbg!(product);
293
294 // let serial = roccat_device.get_serial_number_string().unwrap();
295 // dbg!(serial);
296
297 // roccat::init(&roccat_device);
298 // roccat::set_color(
299 // &roccat_device,
300 // &RGB {
301 // red: 0,
302 // green: 255,
303 // blue: 40,
304 // },
305 // );
306 // }
307
308 fn test_b650_e() {
309 let api = hidapi::HidApi::new().unwrap();
310
311 let b650e_device = b650_e::get_device(&api);
312
313 println!("Firmware: {}", b650_e::get_firmware_string(&b650e_device));
314
315 let configuration = b650_e::get_configuration_table(&b650e_device);
316 println!("Configuration:");
317 for i in 0..60 {
318 print!("{:02X} ", configuration[i]);
319 if (i + 1) % 6 == 0 {
320 println!("");
321 }
322 }
323
324 // Only once, at start.
325 b650_e::set_fixed_mode(&b650e_device);
326
327 b650_e::set_color(
328 &b650e_device,
329 &RGB {
330 red: 255,
331 green: 0,
332 blue: 0,
333 },
334 );
335 b650_e::save_current_color(&b650e_device);
336 }
337
338 fn test_corsair() {
339 let corsair_controllers = [
340 corsair_vengeance::Controller::new(0x19),
341 corsair_vengeance::Controller::new(0x1B),
342 ];
343 for controller in corsair_controllers {
344 controller.set_color(&RGB {
345 red: 255,
346 green: 0,
347 blue: 0,
348 });
349 }
350 }
351
352 fn test_a770() {
353 // a770::set_rgb(255, 0, 0);
354 let mut a770 = a770::A770::new();
355 a770.set_color(255, 0, 0);
356 }
357
358 fn test_read_temp() {
359 let sensors = sensors_jiji::Sensors::new();
360 println!("temp cpu: {}", sensors.read_cpu_temp());
361 println!("temp gpu: {}", sensors.read_gpu_temp());
362 }