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
#[macro_use]
extern crate error_chain;
#[cfg(target_os = "windows")]
extern crate winreg;
pub mod errors;
use errors::*;
#[cfg(target_os = "windows")]
pub fn enumerate_serial_ports() -> Result<Vec<String>> {
use winreg::RegKey;
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ};
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let serial_device_map = hklm.open_subkey_with_flags("HARDWARE\\DEVICEMAP\\SERIALCOMM", KEY_READ)
.chain_err(|| "Unable to open registry")?;
let mut devices = vec![];
for entry in serial_device_map.enum_values() {
let name = entry.chain_err(|| "The registry entry could not be retrieved")?.0;
let device = serial_device_map.get_value(name)
.chain_err(|| "The registry entry's value could not be retrieved")?;
devices.push(device);
}
Ok(devices)
}
#[cfg(target_os = "linux")]
pub fn enumerate_serial_ports() -> Result<Vec<String>> {
use std::fs;
let device_directory = fs::read_dir("/dev/serial/by-id").chain_err(|| "/dev/serial not found")?;
let mut devices = vec![];
for entry in device_directory {
let path = entry.chain_err(|| "Directory entry could not be read")?
.path()
.canonicalize()
.chain_err(|| "Could not get absolute path of serial port")?;
let path_string = match path.to_str() {
Some(path_string) => path_string.into(),
None => return Err(Error::from("Path could not be converted to string")),
};
devices.push(path_string);
}
Ok(devices)
}