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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use regex::Regex;
use std::{
env,
fmt::Display,
fs::{self, File},
io::{BufRead, BufReader},
path::{Path, PathBuf},
};
#[derive(Debug, Default)]
struct IO {
pub name: String,
pub size: Option<usize>,
}
impl IO {
fn new(name: &str, size: Option<&str>) -> Self {
Self {
name: name.to_string(),
size: size.and_then(|s| s.parse().ok()),
}
}
}
#[derive(Debug, Default)]
struct List(Vec<IO>);
impl Display for List {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let var: Vec<_> = self
.0
.iter()
.map(|IO { name, size }| {
if let Some(size) = size {
format!("{}: [0f64; {}]", name, size)
} else {
format!("{}: 0f64", name)
}
})
.collect();
write!(f, "{}", var.join(","))
}
}
#[derive(Debug, Default)]
struct Model {
name: String,
inputs: List,
outputs: List,
states: List,
}
impl Display for Model {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
r"
/// Simulink controller wrapper
#[derive(Debug, Clone, Copy, Default)]
pub struct {model} {{
// Inputs Simulink structure
pub inputs: ExtU_{model}_T,
// Outputs Simulink structure
pub outputs: ExtY_{model}_T,
states: DW_{model}_T,
}}
impl Default for ExtU_{model}_T {{
fn default() -> Self {{
Self {{ {var_u} }}
}}
}}
impl Default for ExtY_{model}_T {{
fn default() -> Self {{
Self {{ {var_y} }}
}}
}}
impl Default for DW_{model}_T {{
fn default() -> Self {{
Self {{ {var_x} }}
}}
}}
impl {model} {{
/// Creates a new controller
pub fn new() -> Self {{
let mut this: Self = Default::default();
let mut data: RT_MODEL_{model}_T = tag_RTM_{model}_T {{
dwork: &mut this.states as *mut _,
}};
unsafe {{
{model}_initialize(
&mut data as *mut _,
&mut this.inputs as *mut _,
&mut this.outputs as *mut _,
)
}}
this
}}
/// Steps the controller
pub fn step(&mut self) {{
let mut data: RT_MODEL_{model}_T = tag_RTM_{model}_T {{
dwork: &mut self.states as *mut _,
}};
unsafe {{
{model}_step(
&mut data as *mut _,
&mut self.inputs as *mut _,
&mut self.outputs as *mut _,
)
}}
}}
}}
",
model = self.name,
var_u = self.inputs.to_string(),
var_y = self.outputs.to_string(),
var_x = self.states.to_string(),
)
}
}
fn parse_io(lines: &mut std::io::Lines<BufReader<File>>, io: &str) -> Option<List> {
let re = Regex::new(r"_T (?P<name>\w+)(?:\[(?P<size>\d+)\])?").unwrap();
match lines.next() {
Some(Ok(line)) if line.starts_with("typedef struct") => {
println!("| {}:", io);
let mut io_data = vec![];
while let Some(Ok(line)) = lines.next() {
if line.contains(io) {
break;
} else {
if let Some(caps) = re.captures(&line) {
let size = caps.name("size").map(|m| m.as_str());
println!("| - {:<22}: {:>5}", &caps["name"], size.unwrap_or("1"),);
io_data.push(IO::new(&caps["name"], size))
}
}
}
Some(List(io_data))
}
_ => None,
}
}
pub struct Sys {
controller: Option<String>,
sources: Vec<PathBuf>,
headers: Vec<PathBuf>,
}
impl Sys {
pub fn new<S: Into<String>>(rs_type: Option<S>) -> Self {
let sys = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()).join("sys");
let mut sources = vec![];
let mut headers = vec![];
if let Ok(entries) = fs::read_dir(&sys) {
for entry in entries {
if let Ok(entry) = entry {
let file_name = entry.path();
if let Some(extension) = file_name.extension() {
match extension.to_str() {
Some("c") => {
sources.push(file_name);
}
Some("h") => {
headers.push(file_name);
}
_ => (),
}
}
}
}
}
Self {
controller: rs_type.map(|x| x.into()),
sources,
headers,
}
}
fn header(&self) -> Option<&str> {
self.headers.iter().find_map(|header| {
header.to_str().filter(|f| {
!(f.ends_with("rtwtypes.h")
|| f.ends_with("rt_defines.h")
|| f.ends_with("_private.h")
|| f.ends_with("_types.h"))
})
})
}
fn parse_header(&self) -> Model {
let Some(header) = self.header() else { panic!("cannot find error in sys")};
let file = File::open(header).expect(&format!("file {:?} not found", header));
let reader = BufReader::new(file);
let mut lines = reader.lines();
let mut model = Model::default();
model.name = loop {
if let Some(Ok(line)) = lines.next() {
if line.contains("File:") {
let regex = Regex::new(r"File:\s*(\w+)\.h").unwrap();
if let Some(captures) = regex.captures(&line) {
let name = captures.get(1).unwrap().as_str();
break name.to_string();
}
}
}
};
while let Some(Ok(line)) = lines.next() {
if line.contains("External inputs") {
model.inputs = parse_io(&mut lines, "ExtU").unwrap();
}
if line.contains("External outputs") {
model.outputs = parse_io(&mut lines, "ExtY").unwrap();
}
if line.contains("Block states") {
model.states = parse_io(&mut lines, "DW").unwrap();
}
}
model
}
pub fn compile(&self) -> &Self {
let mut cc_builder = cc::Build::new();
self.sources
.iter()
.fold(&mut cc_builder, |cc_builder, source| {
cc_builder.file(source)
});
let bindings_builder = self
.headers
.iter()
.fold(bindgen::builder(), |bindings, header| {
println!("cargo:rerun-if-changed={:}", header.to_str().unwrap());
bindings.header(
header
.to_str()
.expect(&format!("{:?} conversion to str failed", header)),
)
});
let lib = env::var("CARGO_PKG_NAME").unwrap();
println!("cargo:rustc-link-search=native=lib{}", lib);
println!("cargo:rustc-link-lib={}", lib);
cc_builder.compile(lib.as_str());
let bindings = bindings_builder
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
self
}
pub fn generate_module(&self) {
let out_dir = env::var_os("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("controller.rs");
fs::write(&dest_path, format!("{}", self)).unwrap();
}
}
impl Display for Sys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let model = self.parse_header();
if let Some(controller) = self.controller.as_ref() {
writeln!(f, "/// Rust binder to Simulink C controller wrapper")?;
writeln!(f, "#[allow(dead_code)]")?;
writeln!(f, "pub type {} = {};", controller, model.name)?;
}
model.fmt(f)
}
}