1 // Copyright 2020 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 use std::fs::File;
5 use std::io::prelude::*;
6 use std::io::BufReader;
7 use std::path::PathBuf;
8 
9 use crate::error::{Error, Result};
10 
11 const VPD_DIR: &str = "/sys/firmware/vpd/ro/vpdfile";
12 
13 /// `VPD`, which represents the amplifier factory calibration values.
14 #[derive(Default, Debug)]
15 pub struct VPD {
16     pub dsm_calib_r0: i32,
17     pub dsm_calib_temp: i32,
18 }
19 
20 impl VPD {
21     /// Creates a `VPD` and initializes its fields from VPD_DIR/dsm_calib_r0_{channel}.
22     /// # Arguments
23     ///
24     /// * `channel` - channel number.
new(channel: usize) -> Result<VPD>25     pub fn new(channel: usize) -> Result<VPD> {
26         let mut vpd: VPD = Default::default();
27         vpd.dsm_calib_r0 = read_vpd_files(&format!("dsm_calib_r0_{}", channel))?;
28         vpd.dsm_calib_temp = read_vpd_files(&format!("dsm_calib_temp_{}", channel))?;
29         Ok(vpd)
30     }
31 }
32 
read_vpd_files(file: &str) -> Result<i32>33 fn read_vpd_files(file: &str) -> Result<i32> {
34     let path = PathBuf::from(VPD_DIR).with_file_name(file);
35     let io_err = |e| Error::FileIOFailed(path.to_owned(), e);
36     let mut reader = BufReader::new(File::open(&path).map_err(io_err)?);
37     let mut line = String::new();
38     reader.read_line(&mut line).map_err(io_err)?;
39     line.parse::<i32>()
40         .map_err(|e| Error::VPDParseFailed(path.to_string_lossy().to_string(), e))
41 }
42