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
use crate::{
error::{ComponentInitError, ComponentReadyError, PinRegisterError},
hal_pin::{HalPin, InputPin, OutputPin},
HalComponent,
};
use linuxcnc_hal_sys::{hal_init, hal_ready, EINVAL, ENOMEM, HAL_NAME_LEN};
use signal_hook::iterator::Signals;
use std::ffi::CString;
#[derive(Debug, PartialEq)]
pub struct HalComponentBuilder {
name: &'static str,
id: i32,
}
impl HalComponentBuilder {
pub fn new(name: &'static str) -> Result<Self, ComponentInitError> {
if name.len() > HAL_NAME_LEN as usize {
println!(
"Component name must be no longer than {} bytes",
HAL_NAME_LEN
);
Err(ComponentInitError::NameLength)
} else {
let name_c = CString::new(name).map_err(|_| ComponentInitError::InvalidName)?;
let id = unsafe { hal_init(name_c.as_ptr() as *const i8) };
match id {
x if x == -(EINVAL as i32) => Err(ComponentInitError::Init),
x if x == -(ENOMEM as i32) => Err(ComponentInitError::Memory),
id if id > 0 => {
println!("Init component {} with ID {}", name, id);
Ok(Self { name, id })
}
code => unreachable!("Hit unreachable error code {}", code),
}
}
}
pub fn register_input_pin<P>(
&mut self,
pin_name: &'static str,
) -> Result<InputPin<P>, PinRegisterError>
where
P: HalPin + 'static,
{
let full_name = format!("{}.{}", self.name, pin_name);
let pin = InputPin::<P>::new(full_name.clone(), self.id)?;
Ok(pin)
}
pub fn register_output_pin<P>(
&mut self,
pin_name: &'static str,
) -> Result<OutputPin<P>, PinRegisterError>
where
P: HalPin + 'static,
{
let full_name = format!("{}.{}", self.name, pin_name);
let pin = OutputPin::<P>::new(full_name.clone(), self.id)?;
Ok(pin)
}
pub fn ready(self) -> Result<HalComponent, ComponentReadyError> {
let ret = unsafe { hal_ready(self.id) };
match ret {
x if x == -(EINVAL as i32) => Err(ComponentReadyError::Invalid),
0 => {
let signals = Signals::new(&[signal_hook::SIGTERM, signal_hook::SIGINT])
.map_err(ComponentReadyError::Signals)?;
println!("Signals registered, component is ready");
let HalComponentBuilder { name, id, .. } = self;
Ok(HalComponent { name, id, signals })
}
ret => unreachable!("Unknown error status {} returned from hal_ready()", ret),
}
}
pub fn id(&self) -> i32 {
self.id
}
pub fn name(&self) -> &str {
self.name
}
}