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
extern crate libc;
extern crate libsensors_sys as libsensors;

pub use libsensors::sensors_feature_type as FeatureType;
pub use libsensors::sensors_subfeature_type as SubfeatureType;

use std::ffi::CStr;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::{Once, ONCE_INIT};

static INIT: Once = ONCE_INIT;

#[derive(Copy, Clone, Debug)]
pub enum LibsensorsError {
	Wildcards,
	NoEntry,
	AccessRead,
	Kernel,
	DivZero,
	ChipName,
	BusName,
	Parse,
	AccessWrite,
	IO,
	Recursion,
	Unknown,
}

impl LibsensorsError {
	fn from_i32(e: i32) -> LibsensorsError {
		use self::LibsensorsError::*;

		match e {
			libsensors::SENSORS_ERR_WILDCARDS => Wildcards,
			libsensors::SENSORS_ERR_NO_ENTRY => NoEntry,
			libsensors::SENSORS_ERR_ACCESS_R => AccessRead,
			libsensors::SENSORS_ERR_KERNEL => Kernel,
			libsensors::SENSORS_ERR_DIV_ZERO => DivZero,
			libsensors::SENSORS_ERR_CHIP_NAME => ChipName,
			libsensors::SENSORS_ERR_BUS_NAME => BusName,
			libsensors::SENSORS_ERR_PARSE => Parse,
			libsensors::SENSORS_ERR_ACCESS_W => AccessWrite,
			libsensors::SENSORS_ERR_IO => IO,
			libsensors::SENSORS_ERR_RECURSION => Recursion,
			_ => Unknown,
		}
	}
}

impl std::fmt::Display for LibsensorsError {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		use std::error::Error;

		write!(f, "libsensors error: {}", self.description())
	}
}

impl std::error::Error for LibsensorsError {
	fn description(&self) -> &str {
		use self::LibsensorsError::*;

		match *self {
			Unknown => "Unknown error",
			Wildcards => "Wildcard found in chip name",
			NoEntry => "No such subfeature known",
			AccessRead => "Can't read",
			Kernel => "Kernel interface error",
			DivZero => "Divide by zero",
			ChipName => "Can't parse chip name",
			BusName => "Can't parse bus name",
			Parse => "General parse error",
			AccessWrite => "Can't write",
			IO => "I/O error",
			Recursion => "Evaluation recurses too deep",
		}
	}

	fn cause(&self) -> Option<&std::error::Error> {
		None
	}
}

#[derive(Copy, Clone, Debug)]
pub struct Sensors {
	marker: PhantomData<()>,
}

#[derive(Copy, Clone, Debug)]
pub struct BusId {
	bus_type: i16,
	nr: i16,
}

#[derive(Debug)]
pub struct Chip {
	inner: *const libsensors::sensors_chip_name,
	prefix: String,
	bus: BusId,
	addr: i32,
	path: PathBuf,
}

pub struct ChipIterator {
	chip_name: Option<libsensors::sensors_chip_name>,
	index: i32,
}

/// Data about a single chip feature (or category leader)
#[derive(Debug)]
pub struct Feature {
	inner: *const libsensors::sensors_feature,
	chip_ptr: *const libsensors::sensors_chip_name,
	name: String,
	number: i32,
	feature_type: FeatureType,
}

pub struct FeatureIterator {
	chip_ptr: *const libsensors::sensors_chip_name,
	index: i32,
}

#[derive(Debug)]
pub struct Subfeature {
	inner: *const libsensors::sensors_subfeature,
	chip_ptr: *const libsensors::sensors_chip_name,
	name: String,
	number: i32,
	subfeature_type: SubfeatureType,
	mapping: i32,
	flags: u32,
}

pub struct SubfeatureIterator {
	chip_ptr: *const libsensors::sensors_chip_name,
	feature_ptr: *const libsensors::sensors_feature,
	index: i32,
}

impl Sensors {
	pub fn new() -> Self {
		INIT.call_once(|| unsafe {
			assert_eq!(libsensors::sensors_init(std::ptr::null_mut()), 0);
			assert_eq!(libc::atexit(Self::cleanup), 0);
		});

		Sensors {
			marker: PhantomData,
		}
	}

	extern "C" fn cleanup() {
		unsafe {
			libsensors::sensors_cleanup();
		}
	}

	/// Returns an iterator over all detected chips that match a given chip name
	pub fn detected_chips<S: AsRef<str>>(&self, name: S) -> Result<ChipIterator, LibsensorsError> {
		let c_name = std::ffi::CString::new(name.as_ref()).unwrap();
		let mut chip_name = libsensors::sensors_chip_name {
			prefix: std::ptr::null_mut(),
			bus: libsensors::sensors_bus_id {
				type_: Default::default(),
				nr: Default::default(),
			},
			addr: Default::default(),
			path: std::ptr::null_mut(),
		};

		let res = unsafe { libsensors::sensors_parse_chip_name(c_name.as_ptr(), &mut chip_name) };
		if res == 0 {
			let iterator = ChipIterator {
				chip_name: Some(chip_name),
				index: 0,
			};

			Ok(iterator)
		} else {
			Err(LibsensorsError::from_i32(res))
		}
	}
}

impl BusId {
	pub fn bus_type(&self) -> i16 {
		self.bus_type
	}

	pub fn nr(&self) -> i16 {
		self.nr
	}

	/// Return the adapter name of the bus.
	/// If it could not be found, it returns None
	pub fn get_adapter_name(&self) -> Option<String> {
		let bus_id = libsensors::sensors_bus_id {
			type_: self.bus_type,
			nr: self.nr,
		};
		let cstr_ptr = unsafe { libsensors::sensors_get_adapter_name(&bus_id) };
		if !cstr_ptr.is_null() {
			let cstr = unsafe { CStr::from_ptr(cstr_ptr) };
			Some(cstr.to_string_lossy().into_owned())
		} else {
			None
		}
	}
}

impl Chip {
	unsafe fn from_ptr(ptr: *const libsensors::sensors_chip_name) -> Chip {
		let chip = *ptr;
		let prefix_cstr = CStr::from_ptr(chip.prefix);
		let path_cstr = CStr::from_ptr(chip.path);

		Chip {
			inner: ptr,
			prefix: prefix_cstr.to_string_lossy().into_owned(),
			bus: BusId {
				bus_type: chip.bus.type_,
				nr: chip.bus.nr,
			},
			addr: chip.addr,
			path: PathBuf::from(path_cstr.to_string_lossy().into_owned()),
		}
	}

	fn c_ptr(&self) -> *const libsensors::sensors_chip_name {
		self.inner
	}

	pub fn prefix(&self) -> &str {
		self.prefix.as_str()
	}

	pub fn address(&self) -> i32 {
		self.addr
	}

	pub fn path(&self) -> &Path {
		self.path.as_path()
	}

	pub fn bus(&self) -> &BusId {
		&self.bus
	}

	/// Return the chip name from its internal representation.
	pub fn get_name(&self) -> Result<String, LibsensorsError> {
		let mut buffer: [std::os::raw::c_char; 128] = [0; 128];
		let res = unsafe {
			libsensors::sensors_snprintf_chip_name(&mut buffer[0], buffer.len(), self.c_ptr())
		};
		if res >= 0 {
			let name_cstr = unsafe { CStr::from_ptr(&buffer[0]) };
			Ok(name_cstr.to_string_lossy().into_owned())
		} else {
			Err(LibsensorsError::from_i32(res))
		}
	}
}

impl Feature {
	unsafe fn from_ptr(
		ptr: *const libsensors::sensors_feature,
		chip: *const libsensors::sensors_chip_name,
	) -> Feature {
		let feature = *ptr;
		let name_cstr = CStr::from_ptr(feature.name);

		Feature {
			inner: ptr,
			chip_ptr: chip,
			name: name_cstr.to_string_lossy().into_owned(),
			number: feature.number,
			feature_type: feature.type_,
		}
	}

	fn c_ptr(&self) -> *const libsensors::sensors_feature {
		self.inner
	}

	pub fn name(&self) -> &str {
		self.name.as_str()
	}

	pub fn number(&self) -> i32 {
		self.number
	}

	pub fn feature_type(&self) -> &FeatureType {
		&self.feature_type
	}

	/// Look up the label of the feature.
	/// If no label exists for this feature, its name is returned itself.
	pub fn get_label(&self) -> Result<String, LibsensorsError> {
		let label_ptr = unsafe { libsensors::sensors_get_label(self.chip_ptr, self.c_ptr()) };
		if !label_ptr.is_null() {
			let label = unsafe { CStr::from_ptr(label_ptr).to_string_lossy().into_owned() };
			unsafe {
				libc::free(label_ptr as *mut libc::c_void);
			}
			Ok(label)
		} else {
			Err(LibsensorsError::Unknown)
		}
	}

	/// Returns the subfeature of the given type,
	/// if it exists, None otherwise.
	pub fn get_subfeature(&self, subfeature_type: SubfeatureType) -> Option<Subfeature> {
		let ptr = unsafe {
			libsensors::sensors_get_subfeature(self.chip_ptr, self.c_ptr(), subfeature_type)
		};

		if !ptr.is_null() {
			unsafe { Some(Subfeature::from_ptr(ptr, self.chip_ptr)) }
		} else {
			None
		}
	}
}

impl Subfeature {
	unsafe fn from_ptr(
		ptr: *const libsensors::sensors_subfeature,
		chip: *const libsensors::sensors_chip_name,
	) -> Subfeature {
		let subfeature = *ptr;
		let name_cstr = CStr::from_ptr(subfeature.name);

		Subfeature {
			inner: ptr,
			chip_ptr: chip,
			name: name_cstr.to_string_lossy().into_owned(),
			number: subfeature.number,
			subfeature_type: subfeature.type_,
			mapping: subfeature.mapping,
			flags: subfeature.flags,
		}
	}

	pub fn name(&self) -> &str {
		self.name.as_str()
	}

	pub fn subfeature_type(&self) -> &SubfeatureType {
		&self.subfeature_type
	}

	/// Read the value of the subfeature.
	pub fn get_value(&self) -> Result<f64, LibsensorsError> {
		let mut value: f64 = 0.0;
		let res = unsafe { libsensors::sensors_get_value(self.chip_ptr, self.number, &mut value) };
		if res >= 0 {
			Ok(value)
		} else {
			Err(LibsensorsError::from_i32(res))
		}
	}

	/// Set the value of the subfeature.
	pub fn set_value(&self, value: f64) -> Result<(), LibsensorsError> {
		let res = unsafe { libsensors::sensors_set_value(self.chip_ptr, self.number, value) };
		if res >= 0 {
			Ok(())
		} else {
			Err(LibsensorsError::from_i32(res))
		}
	}
}

impl IntoIterator for Sensors {
	type Item = Chip;
	type IntoIter = ChipIterator;

	fn into_iter(self) -> Self::IntoIter {
		ChipIterator {
			chip_name: None,
			index: 0,
		}.into_iter()
	}
}

impl Iterator for ChipIterator {
	type Item = Chip;

	fn next(&mut self) -> Option<Self::Item> {
		let chip_name_ptr: *const libsensors::sensors_chip_name =
			if let Some(chip_name) = self.chip_name {
				&chip_name
			} else {
				std::ptr::null_mut()
			};

		let ptr = unsafe { libsensors::sensors_get_detected_chips(chip_name_ptr, &mut self.index) };

		if !ptr.is_null() {
			unsafe { Some(Chip::from_ptr(ptr)) }
		} else {
			None
		}
	}
}

impl Drop for ChipIterator {
	fn drop(&mut self) {
		if let Some(mut chip_name) = self.chip_name {
			unsafe {
				libsensors::sensors_free_chip_name(&mut chip_name);
			}
		};
	}
}

impl IntoIterator for Chip {
	type Item = Feature;
	type IntoIter = FeatureIterator;

	fn into_iter(self) -> Self::IntoIter {
		FeatureIterator {
			index: 0,
			chip_ptr: self.c_ptr(),
		}.into_iter()
	}
}

impl Iterator for FeatureIterator {
	type Item = Feature;

	fn next(&mut self) -> Option<Self::Item> {
		let ptr = unsafe { libsensors::sensors_get_features(self.chip_ptr, &mut self.index) };

		if !ptr.is_null() && !self.chip_ptr.is_null() {
			unsafe { Some(Feature::from_ptr(ptr, self.chip_ptr)) }
		} else {
			None
		}
	}
}

impl IntoIterator for Feature {
	type Item = Subfeature;
	type IntoIter = SubfeatureIterator;

	fn into_iter(self) -> Self::IntoIter {
		SubfeatureIterator {
			index: 0,
			chip_ptr: self.chip_ptr,
			feature_ptr: self.c_ptr(),
		}.into_iter()
	}
}

impl Iterator for SubfeatureIterator {
	type Item = Subfeature;

	fn next(&mut self) -> Option<Self::Item> {
		let ptr = unsafe {
			libsensors::sensors_get_all_subfeatures(
				self.chip_ptr,
				self.feature_ptr,
				&mut self.index,
			)
		};

		if !ptr.is_null() {
			unsafe { Some(Subfeature::from_ptr(ptr, self.chip_ptr)) }
		} else {
			None
		}
	}
}