Reformat code, add optional range, rename C file

Signed-off-by: Ivan Bushchik <ivabus@ivabus.dev>
This commit is contained in:
Ivan Bushchik 2024-01-10 22:17:03 +03:00
parent 2910c3f314
commit 105372a965
No known key found for this signature in database
GPG key ID: 2F16FBF3262E090C
4 changed files with 28 additions and 19 deletions

View file

@ -1,20 +1,16 @@
# Privod (оптический привод)
Eject CD/DVD/BD drive at random time (from 5 secs to 5 mins)
Eject CD/DVD/BD drive at random time.
Linux only.
## Usage
```shell
cargo run <PATH_TO_DRIVE>
cargo run <PATH_TO_DRIVE> [RANGE_START] [RANGE_END]
```
`PATH_TO_DRIVE` is usually `/dev/sr0`
## TODO
- [ ] Delay setup
`PATH_TO_DRIVE` is usually `/dev/sr0`, `RANGE_START` (in secs) and `RANGE_END` (in secs) are optional (default is 5 and 300).
## License

View file

@ -1,6 +1,4 @@
fn main() {
cc::Build::new()
.file("src/get_status.c")
.compile("get_status");
println!("cargo:rerun-if-changed=src/get_status.c");
cc::Build::new().file("src/privod.c").compile("privod");
println!("cargo:rerun-if-changed=src/privod.c");
}

View file

@ -1,31 +1,43 @@
use rand::Rng;
use std::ffi::{c_char, CString};
#[link(name = "get_status")]
extern "C" {
pub fn get_status(drive_path: *const c_char) -> std::ffi::c_int;
pub fn eject(drive_path: *const c_char);
}
fn sleep_rnd() {
let sleeptime = rand::thread_rng().gen_range(5..300);
fn sleep_rnd(start: u64, end: u64) {
let sleeptime = rand::thread_rng().gen_range(start..=end);
eprintln!("Sleeping for {} secs", &sleeptime);
std::thread::sleep(std::time::Duration::from_secs(sleeptime));
}
fn main() {
let args = std::env::args().collect::<Vec<String>>();
if args.len() != 2 && args.len() != 4 {
eprintln!(
"Usage: {} <PATH_TO_DRIVE> [RANGE_START] [RANGE_END]",
args[0]
);
std::process::exit(1);
}
let (start, end) = if args.len() == 4 {
(args[2].parse().unwrap(), args[3].parse().unwrap())
} else {
(5, 300)
};
let dr_name = CString::new(std::env::args().collect::<Vec<String>>()[1].as_bytes()).unwrap();
unsafe {
loop {
if get_status(dr_name.as_ptr()) != 0x1 {
while get_status(dr_name.as_ptr()) != 0x1_i32 {
eprintln!("Status != 0x1, sleeping 100ms");
std::thread::sleep(std::time::Duration::from_millis(100));
eprintln!("Status != closed, sleeping 250ms");
std::thread::sleep(std::time::Duration::from_millis(250));
}
sleep_rnd()
sleep_rnd(start, end)
}
eject(dr_name.as_ptr());
sleep_rnd();
sleep_rnd(start, end);
}
}
}

View file

@ -3,6 +3,9 @@
#include <linux/cdrom.h>
#include <unistd.h>
// Status: 0 - opened, 1 - closed, 2 - failed
int get_status(char *drive_path) {
int cdrom;
int status=1;
@ -20,7 +23,7 @@ int get_status(char *drive_path) {
}
void eject(char *drive_path) {
// Ignoring everything
// Ignore everything
int cdrom;
cdrom = open(drive_path, O_RDONLY | O_NONBLOCK);
ioctl (cdrom, CDROMEJECT);