emerald_runtime/
power.rs

1use std::{
2    fs::File,
3    io::{Error, Write},
4};
5
6use kernel_user_link::power::{POWER_DEVICE_PATH, REBOOT_COMMAND, SHUTDOWN_COMMAND};
7
8pub enum PowerCommand {
9    Shutdown,
10    Reboot,
11}
12
13impl PowerCommand {
14    pub fn from_str(s: &str) -> Option<Self> {
15        match s {
16            "shutdown" => Some(Self::Shutdown),
17            "reboot" => Some(Self::Reboot),
18            _ => None,
19        }
20    }
21
22    pub fn run(&self) -> Result<(), Error> {
23        let cmd = match self {
24            Self::Shutdown => SHUTDOWN_COMMAND,
25            Self::Reboot => REBOOT_COMMAND,
26        };
27        let mut power_file = File::options().write(true).open(POWER_DEVICE_PATH)?;
28        if power_file.write(cmd)? != cmd.len() {
29            return Err(Error::new(
30                std::io::ErrorKind::Other,
31                "failed to write all bytes",
32            ));
33        }
34        Ok(())
35    }
36}