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::{remove_file, File}; 5 use std::io::{prelude::*, BufReader, BufWriter}; 6 use std::path::PathBuf; 7 8 use serde::{Deserialize, Serialize}; 9 use sys_util::info; 10 11 use crate::error::{Error, Result}; 12 13 /// `Datastore`, which stores and reads calibration values in yaml format. 14 #[derive(Debug, Deserialize, Serialize, Copy, Clone)] 15 pub enum Datastore { 16 /// Indicates using values in VPD. 17 UseVPD, 18 DSM { 19 rdc: i32, 20 temp: i32, 21 }, 22 } 23 24 impl Datastore { 25 /// The dir of datastore. 26 pub const DATASTORE_DIR: &'static str = "/var/lib/sound_card_init"; 27 28 /// Creates a `Datastore` and initializes its fields from the datastore file. from_file(snd_card: &str, channel: usize) -> Result<Datastore>29 pub fn from_file(snd_card: &str, channel: usize) -> Result<Datastore> { 30 let path = Self::path(snd_card, channel); 31 let reader = 32 BufReader::new(File::open(&path).map_err(|e| Error::FileIOFailed(path.to_owned(), e))?); 33 let datastore: Datastore = 34 serde_yaml::from_reader(reader).map_err(|e| Error::SerdeError(path.to_owned(), e))?; 35 Ok(datastore) 36 } 37 38 /// Saves a `Datastore` to file. save(&self, snd_card: &str, channel: usize) -> Result<()>39 pub fn save(&self, snd_card: &str, channel: usize) -> Result<()> { 40 let path = Self::path(snd_card, channel); 41 42 let mut writer = BufWriter::new( 43 File::create(&path).map_err(|e| Error::FileIOFailed(path.to_owned(), e))?, 44 ); 45 writer 46 .write( 47 serde_yaml::to_string(self) 48 .map_err(|e| Error::SerdeError(path.to_owned(), e))? 49 .as_bytes(), 50 ) 51 .map_err(|e| Error::FileIOFailed(path.to_owned(), e))?; 52 writer 53 .flush() 54 .map_err(|e| Error::FileIOFailed(path.to_owned(), e))?; 55 info!("update Datastore {}: {:?}", path.to_string_lossy(), self); 56 Ok(()) 57 } 58 59 /// Deletes the datastore file. delete(snd_card: &str, channel: usize) -> Result<()>60 pub fn delete(snd_card: &str, channel: usize) -> Result<()> { 61 let path = Self::path(snd_card, channel); 62 remove_file(&path).map_err(|e| Error::FileIOFailed(path.to_owned(), e))?; 63 info!("datastore: {:#?} is deleted.", path); 64 Ok(()) 65 } 66 path(snd_card: &str, channel: usize) -> PathBuf67 fn path(snd_card: &str, channel: usize) -> PathBuf { 68 PathBuf::from(Self::DATASTORE_DIR) 69 .join(snd_card) 70 .join(format!("calib_{}", channel)) 71 } 72 } 73