beep/
lib.rs

1use nix::{self, ioctl_write_int_bad};
2use std::fs::{File, OpenOptions};
3use std::os::unix::io::AsRawFd;
4use lazy_static::lazy_static;
5
6pub use nix::Error;
7
8const FILE            : &str = "/dev/console";
9const KIOCSOUND       : u64  = 0x4B2F;
10const TIMER_FREQUENCY : u32  = 1193180;
11
12lazy_static! {
13    static ref DEVICE: File =
14        OpenOptions::new()
15            .append(true)
16            .open(FILE)
17            .expect(&format!("Could not open {}", FILE));
18}
19
20ioctl_write_int_bad!(kiocsound, KIOCSOUND);
21
22/// Play an indefinite tone of a given `hertz`.
23///
24/// For instance:
25///
26/// ```
27/// use std::{thread, time::Duration};
28/// use beep::beep;
29///
30/// fn main() {
31///     beep(440);
32///     thread::sleep(Duration::from_millis(500));
33///     beep(880);
34///     thread::sleep(Duration::from_millis(500));
35///     beep(0);
36/// }
37/// ```
38///
39pub fn beep(hertz: u16) -> nix::Result<()>
40{
41    let period_in_clock_cycles =
42        TIMER_FREQUENCY.checked_div(hertz as u32).unwrap_or(0);
43
44    unsafe {
45        kiocsound(DEVICE.as_raw_fd(), period_in_clock_cycles as i32)?;
46    }
47
48    Ok(())
49}