1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
//! Backend providing support for fan sensors.
//!
//! A la dbus-sensors's `fansensor` daemon.

use std::collections::HashMap;

use crate::{
	DaemonState,
	dbus_helpers::props::*,
	powerstate::PowerState,
	sensor,
	sensor::{
		Sensor,
		SensorConfig,
		SensorMode::ReadOnly,
		SensorType,
	},
	sysfs,
	threshold,
	types::*,
};

/// An enum representing which specific variety of fan sensor we're dealing with.
#[derive(Debug)]
enum FanSensorType {
	/// ASPEED AST2x00 fan tach/pwm.
	AspeedFan,
}

impl TryFrom<&String> for FanSensorType {
	type Error = Box<dyn std::error::Error>;
	fn try_from(s: &String) -> ErrResult<Self> {
		match s.as_ref() {
			"AspeedFan" => Ok(Self::AspeedFan),
			_ => Err(err_unsupported(format!("Unsupported fan sensor type '{}'", s))),
		}
	}
}

/// Internal representation of fan sensor config data from dbus.
#[derive(Debug)]
pub struct FanSensorConfig {
	/// Index of this particular sensor (channel) within the containing hardware device.
	index: u64,
	/// Sensor name.
	name: String,
	/// Host power state in which this sensor is active.
	power_state: PowerState,
	/// Sub-type of fan sensor.
	subtype: FanSensorType,
	/// Threshold settings for the sensor.
	thresholds: Vec<threshold::ThresholdConfig>,
	/// Minimum reading value for the sensor.
	minreading: f64,
	/// Maximum reading value for the sensor.
	maxreading: f64,
}

impl FanSensorConfig {
	/// Construct a [`FanSensorConfig`] from raw dbus config data.
	pub fn from_dbus(basecfg: &dbus::arg::PropMap, baseintf: &str,
	                 intfs: &HashMap<String, dbus::arg::PropMap>) -> ErrResult<Self> {
		let index = *prop_get_mandatory(basecfg, "Index")?;
		let name: &String = prop_get_mandatory(basecfg, "Name")?;
		let power_state = prop_get_default_from(basecfg, "PowerState", PowerState::Always)?;
		let subtype = prop_get_mandatory_from(basecfg, "Type")?;
		let thresholds = threshold::get_configs_from_dbus(baseintf, intfs);
		let minreading = *prop_get_default(basecfg, "MinReading", &0.0f64)?;

		// default carried over from dbus-sensors's fansensor
		let maxreading = *prop_get_default(basecfg, "MaxReading", &25000.0f64)?;

		Ok(Self {
			index,
			name: name.clone(),
			power_state,
			subtype,
			thresholds,
			minreading,
			maxreading,
		})
	}
}

/// Instantiate any active fan sensors configured in `cfgmap`.
pub async fn instantiate_sensors(daemonstate: &DaemonState, dbuspaths: &FilterSet<InventoryPath>)
                                 -> ErrResult<()>
{
	let cfgmap = daemonstate.config.lock().await;
	let configs = cfgmap.iter()
		.filter_map(|(path, cfg)| {
			match cfg {
				SensorConfig::Fan(c) if dbuspaths.contains(path) => Some((path, c)),
				_ => None,
			}
		});
	let pattern = format!("{}/*.pwm-tacho-controller", sysfs::PLATFORM_DEVICE_DIR);
	let controller_dir = sysfs::get_single_glob_match(&pattern)?;
	let hwmondir = sysfs::get_single_hwmon_dir(&controller_dir)?;
	for (path, fancfg) in configs {
		let mut sensors = daemonstate.sensors.lock().await;

		let Some(entry) = sensor::get_nonactive_sensor_entry(&mut sensors,
		                                                     fancfg.name.clone()).await else {
			continue;
		};

		let ioctx = match sysfs::prepare_indexed_hwmon_ioctx(&hwmondir, fancfg.index,
		                                                     SensorType::RPM,
		                                                     fancfg.power_state, &None).await {
			Ok(Some(ioctx)) => ioctx,
			Ok(None) => continue,
			Err(e) => {
				eprintln!("Error preparing {} from {}: {}", fancfg.name,
				          hwmondir.display(), e);
				continue;
			},
		};

		let ctor = || {
			Sensor::new(path,&fancfg.name, SensorType::RPM, &daemonstate.sensor_intfs,
			            &daemonstate.bus, ReadOnly)
				.with_power_state(fancfg.power_state)
				.with_thresholds_from(&fancfg.thresholds,
				                      &daemonstate.sensor_intfs.thresholds,
				                      &daemonstate.bus)
				.with_minval(fancfg.minreading)
				.with_maxval(fancfg.maxreading)
		};
		sensor::install_or_activate(entry, &daemonstate.crossroads, ioctx,
		                            &daemonstate.sensor_intfs, ctor).await;
	}
	Ok(())
}

/// Whether or not the given `cfgtype` is supported by the `fan` sensor backend.
pub fn match_cfgtype(cfgtype: &str) -> bool {
	cfgtype == "AspeedFan"
}