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
//! The [acpi_call](https://github.com/mkottman/acpi_call) kernel module is needed for this crate to interacti with acpi.
//!
//! ```no_run
//! # use rog_fan_curve::{
//! #     Curve,
//! #     Board,
//! #     Fan,
//! #     CurveError,
//! # };
//! # fn foo() -> Result<(), CurveError> {
//! let mut curve = Curve::new();
//! 
//! curve.set_point(0, 0x1e, 0x00);
//! curve.set_point(1, 0x2d, 0x01);
//! curve.set_point(2, 0x32, 0x04);
//! curve.set_point(3, 0x3c, 0x04);
//! curve.set_point(4, 0x46, 0x13);
//! curve.set_point(5, 0x50, 0x40);
//! curve.set_point(6, 0x5a, 0x64);
//! curve.set_point(7, 0x64, 0x64);
//! 
//! let board = Board::from_name("GA401IV").unwrap();
//! 
//! curve.apply(board, Fan::Cpu)?;
//! curve.apply(board, Fan::Gpu)?;
//! 
//! # Ok(())
//! # }
//! ```

use std::io::prelude::*;
use std::fs::OpenOptions;

#[derive(Debug)]
pub enum CurveError {
    Acpi(String),
    InvalidFan,
    Io(std::io::Error),
}

impl From<std::io::Error> for CurveError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}

#[derive(Debug)]
pub struct Curve {
    curve: [u8; 16],
}

impl Curve {
    pub fn new() -> Self {
        Self {
            curve: [
                0x1e, 0x2d, 0x32, 0x3c,
                0x46, 0x50, 0x5a, 0x64,
                0x12, 0x12, 0x12, 0x20,
                0x30, 0x40, 0x64, 0x64,
            ],
        }
    }
    
    /// Sets a point on the fan curve
    ///
    /// # Arguments
    ///
    /// * `n` - The point on the fan curve to change, must be between 0 and 7 inclusive
    /// * `temp` - Degrees celcius
    /// * `speed` -> Percent? fan speed
    pub fn set_point(&mut self, n: u8, temp: u8, speed: u8) {
        assert!(n <= 7); // must be >= 0 due to type
        let n = n as usize;
        self.curve[n] = temp;
        self.curve[n+8] = speed;
    }
    
    /// Applies the fan curve via acpi_call
    pub fn apply(&self, board: Board, fan: Fan) -> Result<(), CurveError> {
        assert_eq!(board, Board::Ga401iv);
        let fan_addr = fan.address().ok_or(CurveError::InvalidFan)?;
        let command = make_command(self, fan_addr);
        // dbg!(&command);
        acpi_call(&command)
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Board {
    Ga401iv,
}

impl Board {
    /// Gets the board name from the kernel using `/sys/class/dmi/id/board_name`
    pub fn from_board_name() -> Option<Self> {
        let name = std::fs::read_to_string("/sys/class/dmi/id/board_name").ok()?;
        Self::from_name(name.trim())
    }
    
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "GA401IV" => Some(Board::Ga401iv),
            _ => None,
        }
    }
}

/// A fan, some boards may not have all fans.
#[derive(Debug, Clone, Copy)]
pub enum Fan {
    Cpu,
    Gpu,
}

impl Fan {
    fn address(&self) -> Option<u32> {
        match self {
            Fan::Cpu => Some(0x40),
            Fan::Gpu => Some(0x44),
        }
    }
}

fn make_command(curve: &Curve, fan: u32) -> String {
    let mut command = "\\_SB.PCI0.SBRG.EC0.SUFC ".to_string();
    
    for param_bytes in curve.curve.chunks_exact(4) {
        let mut param = param_bytes[0] as u32;
        param += (param_bytes[1] as u32) << 0x08;
        param += (param_bytes[2] as u32) << 0x10;
        param += (param_bytes[3] as u32) << 0x18;
        command.push_str(&format!("{:0>#010x} ", param));
    }
    
    command.push_str(&format!("{:#x}", fan));
    
    command
}

fn acpi_call(command: &str) -> Result<(), CurveError> {
    let mut file = OpenOptions::new()
        .read(true)
        .write(true)
        .open("/proc/acpi/call")?;
    
    file.write_all(command.as_bytes())?;
    
    file.seek(std::io::SeekFrom::Start(0))?;
    
    let mut out = String::new();
    file.read_to_string(&mut out)?;
    
    // dbg!(&out);
    
    if out.starts_with("Error:") {
        return Err(CurveError::Acpi(out))
    }
    
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_make_command() {
        let curve = Curve {
            curve: [
                0x1e, 0x2d, 0x32, 0x3c,
                0x46, 0x50, 0x5a, 0x64,
                0x00, 0x01, 0x04, 0x04,
                0x13, 0x40, 0x64, 0x64,
            ],
        };
        
        let command = make_command(&curve, 0x40);
        dbg!(&command);
        
        assert_eq!(&command, "\\_SB.PCI0.SBRG.EC0.SUFC 0x3c322d1e 0x645a5046 0x04040100 0x64644013 0x40")
    }
    
    #[test]
    fn set_point() {
        let mut curve = Curve {
            curve: [
                0x0a, 0x0a, 0x0a, 0x0a,
                0x0a, 0x0a, 0x0a, 0x0a,
                0x0a, 0x0a, 0x0a, 0x0a,
                0x0a, 0x0a, 0x0a, 0x0a,
            ],
        };
        
        curve.set_point(0, 0, 1);
        curve.set_point(1, 2, 3);
        curve.set_point(2, 4, 5);
        curve.set_point(3, 6, 7);
        curve.set_point(4, 8, 9);
        curve.set_point(5, 10, 11);
        curve.set_point(6, 12, 13);
        curve.set_point(7, 14, 15);
        
        assert_eq!(&curve.curve, &[
             0,  2,  4,  6,
             8, 10, 12, 14,
             1,  3,  5,  7,
             9, 11, 13, 15,
        ]);
    }
}