libmedium 0.13.4

Library to interface with lm_sensors
Documentation
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Module containing the async Hwmon struct and related functionality.

mod helper_functions;
mod iterator;

use super::error::{Error, Result};
use helper_functions::*;

pub use iterator::{Iter, NamedIter};

use crate::parsing::{Error as ParsingError, Result as ParsingResult};
use crate::sensors::async_sensors::{
    curr::*, energy::*, fan::*, humidity::*, intrusion::*, power::*, pwm::*, temp::*, voltage::*,
};

use crate::units::Raw;

use tokio::fs::read_to_string;

use std::{
    cmp::Ordering,
    collections::BTreeMap,
    fmt::Debug,
    io::ErrorKind as IoErrorKind,
    path::{Path, PathBuf},
    time::Duration,
};

/// Struct representing a hwmon directory.
#[derive(Debug, Clone)]
pub struct Hwmon {
    name: String,
    label: Option<String>,
    path: PathBuf,
    index: u16,
    currents: BTreeMap<u16, CurrentSensorStruct>,
    energies: BTreeMap<u16, EnergySensorStruct>,
    fans: BTreeMap<u16, FanSensorStruct>,
    humidities: BTreeMap<u16, HumiditySensorStruct>,
    intrusions: BTreeMap<u16, IntrusionSensorStruct>,
    powers: BTreeMap<u16, PowerSensorStruct>,
    pwms: BTreeMap<u16, PwmSensorStruct>,
    temps: BTreeMap<u16, TempSensorStruct>,
    voltages: BTreeMap<u16, VoltageSensorStruct>,
}

impl Hwmon {
    /// Returns the hwmon's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the hwmon's label (if any).
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Returns the hwmon's path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// returns the hwmon's index.
    pub fn index(&self) -> u16 {
        self.index
    }

    /// Returns this hwmon's device path.
    /// This path does not change between reboots.
    pub fn device_path(&self) -> PathBuf {
        // Every hwmon in sysfs has a device link so this should never panic.
        self.path().join("device").canonicalize().unwrap()
    }

    /// Returns this hwmon's update interval.
    /// If the hwmon does not expose the value, an error is returned.
    pub async fn update_interval(&self) -> Result<Duration> {
        let path = self.path().join("update_interval");

        match read_to_string(&path).await {
            Ok(s) => Duration::from_raw(&s).map_err(|e| Error::unit(e, path)),
            Err(e) => {
                if e.kind() == IoErrorKind::NotFound {
                    Err(Error::update_interval_not_available())
                } else {
                    Err(Error::io(e, path))
                }
            }
        }
    }

    /// Returns whether this hwmon beeps if an alarm condition exists.
    /// If the hwmon does not expose the value, an error is returned.
    pub async fn beep_enable(&self) -> Result<bool> {
        let path = self.path().join("beep_enable");

        match read_to_string(&path).await {
            Ok(s) => bool::from_raw(&s).map_err(|e| Error::unit(e, path)),
            Err(e) => {
                if e.kind() == IoErrorKind::NotFound {
                    Err(Error::beep_enable())
                } else {
                    Err(Error::io(e, path))
                }
            }
        }
    }

    /// Returns all current sensors found in this `Hwmon`.
    pub fn currents(
        &self,
    ) -> &BTreeMap<u16, impl AsyncCurrentSensor + Clone + Send + Sync + 'static> {
        &self.currents
    }

    /// Returns all energy sensors found in this `Hwmon`.
    pub fn energies(
        &self,
    ) -> &BTreeMap<u16, impl AsyncEnergySensor + Clone + Send + Sync + 'static> {
        &self.energies
    }

    /// Returns all fan sensors found in this `Hwmon`.
    pub fn fans(&self) -> &BTreeMap<u16, impl AsyncFanSensor + Clone + Send + Sync + 'static> {
        &self.fans
    }

    /// Returns all humidity sensors found in this `Hwmon`.
    pub fn humidities(
        &self,
    ) -> &BTreeMap<u16, impl AsyncHumiditySensor + Clone + Send + Sync + 'static> {
        &self.humidities
    }

    /// Returns all intrusion sensors found in this `Hwmon`.
    pub fn intrusions(
        &self,
    ) -> &BTreeMap<u16, impl AsyncIntrusionSensor + Clone + Send + Sync + 'static> {
        &self.intrusions
    }

    /// Returns all power sensors found in this `Hwmon`.
    pub fn powers(&self) -> &BTreeMap<u16, impl AsyncPowerSensor + Clone + Send + Sync + 'static> {
        &self.powers
    }

    /// Returns all pwm sensors found in this `Hwmon`.
    pub fn pwms(&self) -> &BTreeMap<u16, impl AsyncPwmSensor + Clone + Send + Sync + 'static> {
        &self.pwms
    }

    /// Returns all temp sensors found in this `Hwmon`.
    pub fn temps(&self) -> &BTreeMap<u16, impl AsyncTempSensor + Clone + Send + Sync + 'static> {
        &self.temps
    }

    /// Returns all voltage sensors found in this `Hwmon`.
    pub fn voltages(
        &self,
    ) -> &BTreeMap<u16, impl AsyncVoltageSensor + Clone + Send + Sync + 'static> {
        &self.voltages
    }

    /// Returns the current sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn current(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncCurrentSensor + Clone + Send + Sync + 'static)> {
        self.currents.get(&index)
    }

    /// Returns the energy sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn energy(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncEnergySensor + Clone + Send + Sync + 'static)> {
        self.energies.get(&index)
    }

    /// Returns the fan sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn fan(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncFanSensor + Clone + Send + Sync + 'static)> {
        self.fans.get(&index)
    }

    /// Returns the humidity sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn humidity(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncHumiditySensor + Clone + Send + Sync + 'static)> {
        self.humidities.get(&index)
    }

    /// Returns the intrusion sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn intrusion(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncIntrusionSensor + Clone + Send + Sync + 'static)> {
        self.intrusions.get(&index)
    }

    /// Returns the power sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn power(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncPowerSensor + Clone + Send + Sync + 'static)> {
        self.powers.get(&index)
    }

    /// Returns the pwm sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn pwm(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncPwmSensor + Clone + Send + Sync + 'static)> {
        self.pwms.get(&index)
    }

    /// Returns the temp sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn temp(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncTempSensor + Clone + Send + Sync + 'static)> {
        self.temps.get(&index)
    }

    /// Returns the voltage sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn voltage(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncVoltageSensor + Clone + Send + Sync + 'static)> {
        self.voltages.get(&index)
    }

    pub(crate) async fn try_from_path(path: impl Into<PathBuf>, index: u16) -> ParsingResult<Self> {
        let path = path.into();

        check_path(&path)?;

        let mut hwmon = Self {
            name: get_name(&path).await?,
            label: get_label(&path).await.ok(),
            path,
            index,
            currents: BTreeMap::new(),
            energies: BTreeMap::new(),
            fans: BTreeMap::new(),
            humidities: BTreeMap::new(),
            intrusions: BTreeMap::new(),
            powers: BTreeMap::new(),
            pwms: BTreeMap::new(),
            temps: BTreeMap::new(),
            voltages: BTreeMap::new(),
        };

        hwmon.currents = init_sensors(&hwmon, 1).await?;
        hwmon.energies = init_sensors(&hwmon, 1).await?;
        hwmon.fans = init_sensors(&hwmon, 1).await?;
        hwmon.humidities = init_sensors(&hwmon, 1).await?;
        hwmon.intrusions = init_sensors(&hwmon, 0).await?;
        hwmon.powers = init_sensors(&hwmon, 1).await?;
        hwmon.pwms = init_sensors(&hwmon, 1).await?;
        hwmon.temps = init_sensors(&hwmon, 1).await?;
        hwmon.voltages = init_sensors(&hwmon, 0).await?;

        Ok(hwmon)
    }
}

#[cfg(feature = "writeable")]
impl Hwmon {
    /// Set this hwmon's update interval.
    /// If the hwmon does not expose the value, an error is returned.
    pub async fn set_update_interval(&self, interval: Duration) -> Result<()> {
        let path = self.path().join("update_interval");

        match tokio::fs::write(&path, interval.to_raw().as_bytes()).await {
            Ok(_) => Ok(()),
            Err(e) => match e.kind() {
                IoErrorKind::NotFound => Err(Error::update_interval_not_available()),
                IoErrorKind::PermissionDenied => Err(Error::insufficient_rights(path)),
                _ => Err(Error::io(e, path)),
            },
        }
    }

    /// Set whether this hwmon beeps if an alarm condition exists.
    /// If the hwmon does not expose the value, an error is returned.
    pub async fn set_beep_enable(&self, beep_enable: bool) -> Result<()> {
        let path = self.path().join("beep_enable");

        match tokio::fs::write(&path, beep_enable.to_raw().as_bytes()).await {
            Ok(_) => Ok(()),
            Err(e) => match e.kind() {
                IoErrorKind::NotFound => Err(Error::beep_enable()),
                IoErrorKind::PermissionDenied => Err(Error::insufficient_rights(path)),
                _ => Err(Error::io(e, path)),
            },
        }
    }

    /// Returns all writeable current sensors found in this `Hwmon`.
    pub fn writeable_currents(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteableCurrentSensor + Clone + Send + Sync + 'static> {
        &self.currents
    }

    /// Returns all writeable energy sensors found in this `Hwmon`.
    pub fn writeable_energies(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteableEnergySensor + Clone + Send + Sync + 'static> {
        &self.energies
    }

    /// Returns all writeable fan sensors found in this `Hwmon`.
    pub fn writeable_fans(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteableFanSensor + Clone + Send + Sync + 'static> {
        &self.fans
    }

    /// Returns all writeable humidity sensors found in this `Hwmon`.
    pub fn writeable_humidities(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteableHumiditySensor + Clone + Send + Sync + 'static> {
        &self.humidities
    }

    /// Returns all writeable intrusion sensors found in this `Hwmon`.
    pub fn writeable_intrusions(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteableIntrusionSensor + Clone + Send + Sync + 'static> {
        &self.intrusions
    }

    /// Returns all writeable power sensors found in this `Hwmon`.
    pub fn writeable_powers(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteablePowerSensor + Clone + Send + Sync + 'static> {
        &self.powers
    }

    /// Returns all writeable pwm sensors found in this `Hwmon`.
    pub fn writeable_pwms(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteablePwmSensor + Clone + Send + Sync + 'static> {
        &self.pwms
    }

    /// Returns all writeable temp sensors found in this `Hwmon`.
    pub fn writeable_temps(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteableTempSensor + Clone + Send + Sync + 'static> {
        &self.temps
    }

    /// Returns all writeable voltage sensors found in this `Hwmon`.
    pub fn writeable_voltages(
        &self,
    ) -> &BTreeMap<u16, impl AsyncWriteableVoltageSensor + Clone + Send + Sync + 'static> {
        &self.voltages
    }

    /// Returns the writeable current sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_current(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteableCurrentSensor + Clone + Send + Sync + 'static)> {
        self.currents.get(&index)
    }

    /// Returns the writeable energy sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_energy(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteableEnergySensor + Clone + Send + Sync + 'static)> {
        self.energies.get(&index)
    }

    /// Returns the writeable fan sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_fan(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteableFanSensor + Clone + Send + Sync + 'static)> {
        self.fans.get(&index)
    }

    /// Returns the writeable humidity sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_humidity(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteableHumiditySensor + Clone + Send + Sync + 'static)> {
        self.humidities.get(&index)
    }

    /// Returns the writeable intrusion sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_intrusion(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteableIntrusionSensor + Clone + Send + Sync + 'static)> {
        self.intrusions.get(&index)
    }

    /// Returns the writeable power sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_power(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteablePowerSensor + Clone + Send + Sync + 'static)> {
        self.powers.get(&index)
    }

    /// Returns the writeable pwm sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_pwm(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteablePwmSensor + Clone + Send + Sync + 'static)> {
        self.pwms.get(&index)
    }

    /// Returns the writeable temp sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_temp(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteableTempSensor + Clone + Send + Sync + 'static)> {
        self.temps.get(&index)
    }

    /// Returns the writeable voltage sensor with the given index.
    /// Returns `None`, if no sensor with the given index exists.
    pub fn writeable_voltage(
        &self,
        index: u16,
    ) -> Option<&(impl AsyncWriteableVoltageSensor + Clone + Send + Sync + 'static)> {
        self.voltages.get(&index)
    }
}

impl PartialEq for Hwmon {
    fn eq(&self, other: &Self) -> bool {
        self.path.eq(other.path())
    }
}

impl Eq for Hwmon {}

impl PartialOrd for Hwmon {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Hwmon {
    fn cmp(&self, other: &Self) -> Ordering {
        self.path.cmp(&other.path)
    }
}

/// This crate's central struct.
/// It stores all parsed [`Hwmon`]s which you can query either by name, device path or index.
#[derive(Debug, Clone)]
pub struct Hwmons {
    #[cfg(feature = "unrestricted_parsing")]
    path: PathBuf,
    hwmons: BTreeMap<u16, Hwmon>,
}

impl Hwmons {
    /// Parses /sys/class/hwmon and returns the found hwmons as a `Hwmons` object.
    pub async fn parse() -> ParsingResult<Self> {
        Self::parse_path("/sys/class/hwmon/").await
    }

    /// Returns an iterator over all hwmons with the given name and their indices.
    /// Returns an empty iterator, if there is no `Hwmon` with the given name.
    pub fn hwmons_by_name<N: AsRef<str>>(&self, name: N) -> NamedIter<'_, N> {
        NamedIter::new(self.iter(), name)
    }

    /// Get a `Hwmon` by its index.
    /// Returns `None`, if there is no `Hwmon` with the given index.
    pub fn hwmon_by_index(&self, index: u16) -> Option<&Hwmon> {
        self.hwmons.get(&index)
    }

    /// Get a `Hwmon` by its device path.
    /// Returns `None`, if there is no `Hwmon` with the given device path.
    pub fn hwmon_by_device_path(&self, device_path: impl AsRef<Path>) -> Option<&Hwmon> {
        self.hwmons
            .values()
            .find(move |&hwmon| hwmon.device_path() == device_path.as_ref())
    }

    /// Returns an iterator over all hwmons, their names and their indices.
    pub fn iter(&self) -> Iter<'_> {
        Iter::new(self.hwmons.iter())
    }

    /// Parses the provided path and returns the found hwmons as a Hwmons object.
    #[cfg(feature = "unrestricted_parsing")]
    pub async fn parse_unrestricted(path: impl AsRef<Path>) -> ParsingResult<Self> {
        Self::parse_path(path).await
    }

    /// The path that was parsed to generate this object.
    #[cfg(feature = "unrestricted_parsing")]
    pub fn path(&self) -> &Path {
        &self.path
    }

    pub(crate) async fn parse_path(path: impl AsRef<Path>) -> ParsingResult<Self> {
        let path = path.as_ref();

        let mut hwmons = Hwmons {
            #[cfg(feature = "unrestricted_parsing")]
            path: path.to_path_buf(),
            hwmons: BTreeMap::new(),
        };

        let mut index;

        for entry in path.read_dir().map_err(|e| ParsingError::hwmons(e, path))? {
            let entry = entry.map_err(|e| ParsingError::hwmons(e, path))?;
            let entry_path = entry.path();

            if !entry_path.is_dir() {
                continue;
            }

            let file_name = entry.file_name();

            if let Some(index_str) = file_name.to_string_lossy().strip_prefix("hwmon") {
                index = index_str
                    .parse()
                    .map_err(|e| ParsingError::hwmon_index(e, &entry_path))?;
            } else {
                continue;
            }

            hwmons
                .hwmons
                .insert(index, Hwmon::try_from_path(entry_path, index).await?);
        }

        Ok(hwmons)
    }
}

#[cfg(test)]
mod tests;