summaryrefslogtreecommitdiff
path: root/src/definitions.rs
blob: 5a414dd21b337832aa31563b5537ad449bc1da64 (plain)
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
use serde_yaml;

use exprparser;
use qexpr;
use qvalue::*;
use types::{NamedValue, Value};

use std::collections::{HashMap, HashSet};

#[derive(Debug, Deserialize)]
pub struct RawECURequest {
    sendto: u16,
    recvfrom: Option<u16>,
    flowctrl: Option<u16>,
    packet: Vec<u8>,
}

impl RawECURequest {
    pub fn sendto(&self) -> u16 {
        self.sendto
    }

    pub fn recvfrom(&self) -> u16 {
        self.recvfrom.unwrap_or(self.sendto + 8)
    }

    pub fn flowctrl(&self) -> u16 {
        self.flowctrl.unwrap_or(self.sendto)
    }

    pub fn packet(&self) -> &[u8] {
        &self.packet
    }
}

#[derive(Debug, Deserialize)]
pub struct RawECUResponseEntry {
    name: String,
    offset: usize,
    length: usize,
    check: Option<Vec<u8>>,
    kind: Option<String>,
    base: Option<u8>,
    count: Option<u8>,
}

#[derive(Debug, Deserialize)]
pub struct RawECUResponse {
    length: usize,
    values: Vec<RawECUResponseEntry>,
}

#[derive(Debug, Deserialize)]
pub struct RawECUEntry {
    name: String,
    description: String,
    cadence: usize,
    request: RawECURequest,
    response: RawECUResponse,
}

impl RawECUEntry {
    pub fn get_all() -> &'static [RawECUEntry] {
        lazy_static! {
            static ref ECUS: Vec<RawECUEntry> =
                serde_yaml::from_slice(include_bytes!("../definitions/raw.yaml")).unwrap();
        }
        &ECUS
    }

    pub fn ecu_for(id: u16, payload: &[u8]) -> Option<&'static RawECUEntry> {
        'ecu: for ecu in RawECUEntry::get_all() {
            if (ecu.request().sendto() == id || ecu.request().recvfrom() == id
                || ecu.request().flowctrl() == id)
                && ecu.response.length == payload.len()
            {
                for entry in &ecu.response.values {
                    if let Some(ref vals) = entry.check {
                        let has = &payload[entry.offset..(entry.offset + vals.len())];
                        for i in 0..vals.len() {
                            if has[i] != vals[i] {
                                continue 'ecu;
                            }
                        }
                    }
                }
                return Some(ecu);
            }
        }
        None
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn description(&self) -> &str {
        &self.description
    }

    pub fn request(&self) -> &RawECURequest {
        &self.request
    }

    pub fn cadence(&self) -> usize {
        self.cadence
    }

    pub fn decode(&self, payload: &[u8]) -> Option<Vec<NamedValue>> {
        trace!("Decoding for {} ({})", self.name(), self.description());
        let mut ret = Vec::new();

        if payload.len() != self.response.length {
            warn!(
                "Unable to decode, length incorrect. {} != {}",
                payload.len(),
                self.response.length
            );
            return None;
        }

        let mut used_locations: HashSet<usize> = HashSet::new();

        for entry in &self.response.values {
            for i in entry.offset..(entry.offset + entry.length) {
                used_locations.insert(i);
            }
            if let Some(ref kind) = entry.kind {
                let value: Value = match kind.as_ref() {
                    "unsigned" => match entry.length {
                        1 => payload[entry.offset].into(),
                        2 => (((payload[entry.offset] as u16) << 8)
                            + (payload[entry.offset + 1] as u16))
                            .into(),
                        3 => (((payload[entry.offset] as u32) << 16)
                            + ((payload[entry.offset + 1] as u32) << 8)
                            + (payload[entry.offset + 2] as u32))
                            .into(),
                        4 => (((payload[entry.offset] as u32) << 24)
                            + ((payload[entry.offset + 1] as u32) << 16)
                            + ((payload[entry.offset + 2] as u32) << 8)
                            + (payload[entry.offset + 3] as u32))
                            .into(),
                        _ => panic!("Unhandled length: {}", entry.length),
                    },
                    "signed" => match entry.length {
                        1 => (payload[entry.offset] as i8).into(),
                        2 => ((((payload[entry.offset] as u16) << 8)
                            + (payload[entry.offset + 1] as u16))
                            as i16)
                            .into(),
                        3 => ((((payload[entry.offset] as u32) << 16)
                            + ((payload[entry.offset + 1] as u32) << 8)
                            + (payload[entry.offset + 2] as u32))
                            as i32)
                            .into(),
                        4 => ((((payload[entry.offset] as u32) << 24)
                            + ((payload[entry.offset + 1] as u32) << 16)
                            + ((payload[entry.offset + 2] as u32) << 8)
                            + (payload[entry.offset + 3] as u32))
                            as i32)
                            .into(),
                        _ => panic!("Unhandled length: {}", entry.length),
                    },
                    "unsigned-le" => match entry.length {
                        1 => payload[entry.offset].into(),
                        2 => (((payload[entry.offset + 1] as u16) << 8)
                            + (payload[entry.offset] as u16))
                            .into(),
                        3 => (((payload[entry.offset + 2] as u32) << 16)
                            + ((payload[entry.offset + 1] as u32) << 8)
                            + (payload[entry.offset] as u32))
                            .into(),
                        4 => (((payload[entry.offset + 3] as u32) << 24)
                            + ((payload[entry.offset + 2] as u32) << 16)
                            + ((payload[entry.offset + 1] as u32) << 8)
                            + (payload[entry.offset] as u32))
                            .into(),
                        _ => panic!("Unhandled length: {}", entry.length),
                    },
                    "signed-le" => match entry.length {
                        1 => (payload[entry.offset] as i8).into(),
                        2 => ((((payload[entry.offset + 1] as u16) << 8)
                            + (payload[entry.offset] as u16)) as i16)
                            .into(),
                        3 => ((((payload[entry.offset + 2] as u32) << 16)
                            + ((payload[entry.offset + 1] as u32) << 8)
                            + (payload[entry.offset] as u32)) as i32)
                            .into(),
                        4 => ((((payload[entry.offset + 3] as u32) << 24)
                            + ((payload[entry.offset + 2] as u32) << 16)
                            + ((payload[entry.offset + 1] as u32) << 8)
                            + (payload[entry.offset] as u32)) as i32)
                            .into(),
                        _ => panic!("Unhandled length: {}", entry.length),
                    },
                    "bit" => ((payload[entry.offset] & (1 << entry.base.unwrap())) != 0).into(),
                    _ => {
                        panic!("Unhandled");
                    }
                };
                let name = {
                    let mut n = self.name().to_owned();
                    n.push('.');
                    n.push_str(&entry.name);
                    n
                };
                ret.push(NamedValue::new(&name, Some(value)));
            }
        }

        for i in 0..payload.len() {
            if !used_locations.contains(&i) {
                let name = {
                    let mut n = self.name().to_owned();
                    n.push_str(&format!(".unused_{}", i));
                    n
                };
                ret.push(NamedValue::new(&name, Some(Value::from_raw(payload[i]))));
            }
        }

        Some(ret)
    }
}

pub struct CadencedECUs {
    count: usize,
    ecu: usize,
}

impl CadencedECUs {
    pub fn new() -> CadencedECUs {
        CadencedECUs { count: 0, ecu: 0 }
    }
}

impl Iterator for CadencedECUs {
    type Item = &'static RawECUEntry;
    fn next(&mut self) -> Option<Self::Item> {
        let ecus = RawECUEntry::get_all();
        loop {
            if self.ecu == ecus.len() {
                self.ecu = 0;
                self.count += 1
            }
            let ecu = &ecus[self.ecu];
            self.ecu += 1;
            if (self.count % ecu.cadence()) == 0 {
                return Some(ecu);
            }
        }
    }
}

#[derive(Debug, Deserialize)]
struct RawUnit {
    id: String,
    aliases: Vec<String>,
    suffix: String,
    expr: String,
}

impl RawUnit {
    fn get_all() -> &'static [RawUnit] {
        lazy_static! {
            static ref UNITS: Vec<RawUnit> =
                serde_yaml::from_slice(include_bytes!("../definitions/units.yaml")).unwrap();
        }
        &UNITS
    }
}

#[derive(Debug)]
pub struct Units {
    raw: &'static [RawUnit],
    qvals: Vec<QValue>,
    all: HashMap<String, usize>,
}

impl Units {
    pub fn get() -> &'static Units {
        lazy_static! {
            static ref UNITS: Units = Units::new();
        }
        &UNITS
    }

    fn new() -> Units {
        let raw = RawUnit::get_all();
        let mut qvals = Vec::new();
        let mut allsyms = HashMap::new();
        let mut symbols = HashMap::new();

        symbols.insert(
            "raw.voltage".to_owned(),
            QValue::unit(BaseQuantity::Voltage),
        );
        symbols.insert(
            "raw.current".to_owned(),
            QValue::unit(BaseQuantity::Current),
        );
        symbols.insert(
            "raw.temperature".to_owned(),
            QValue::unit(BaseQuantity::Temperature),
        );
        symbols.insert(
            "raw.distance".to_owned(),
            QValue::unit(BaseQuantity::Distance),
        );
        symbols.insert("raw.time".to_owned(), QValue::unit(BaseQuantity::Time));

        for i in 0..raw.len() {
            if let Some(parsed) = exprparser::parse_expression(&raw[i].expr) {
                if let Some(unit) = qexpr::evaluate(&parsed, &mut symbols) {
                    qvals.push(unit);
                    if allsyms.contains_key(&raw[i].id) {
                        panic!("Duplicated unit name/alias: {}", &raw[i].id);
                    }
                    allsyms.insert(raw[i].id.clone(), i);
                    symbols.insert(raw[i].id.clone(), unit);
                    for alias in &raw[i].aliases {
                        if allsyms.contains_key(alias) {
                            panic!("Duplicated unit name/alias: {}", alias);
                        }
                        allsyms.insert(alias.clone(), i);
                        symbols.insert(alias.clone(), unit);
                    }
                } else {
                    println!("Current symbols: {:?}", symbols);
                    println!("Expression: {:?}", parsed);
                    panic!("Unable to evaluate units expression for {}", raw[i].id);
                }
            } else {
                panic!("Unable to parse units expression for {}", raw[i].id);
            }
        }

        Units {
            raw: raw,
            qvals: qvals,
            all: allsyms,
        }
    }

    pub fn count(&self) -> usize {
        self.raw.len()
    }

    pub fn populate(&self, into: &mut HashMap<String, QValue>) {
        self.all.iter().for_each(|(k, v)| {
            into.insert(k.clone(), self.qvals[*v].clone());
        });
    }
}