libautomotive 0.1.0

A Rust library for automotive systems and protocols
Documentation
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use super::ApplicationLayer;
use crate::error::{AutomotiveError, Result};
use crate::transport::TransportLayer;
use crate::types::{Config, Frame};

// UDS Service IDs
pub const SID_DIAGNOSTIC_SESSION_CONTROL: u8 = 0x10;
pub const SID_ECU_RESET: u8 = 0x11;
pub const SID_SECURITY_ACCESS: u8 = 0x27;
pub const SID_TESTER_PRESENT: u8 = 0x3E;
pub const SID_READ_DATA_BY_ID: u8 = 0x22;
pub const SID_WRITE_DATA_BY_ID: u8 = 0x2E;
pub const SID_CLEAR_DIAGNOSTIC_INFO: u8 = 0x14;
pub const SID_READ_DTC: u8 = 0x19;

// Additional UDS Service IDs
pub const SID_COMMUNICATION_CONTROL: u8 = 0x28;
pub const SID_AUTHENTICATION: u8 = 0x29;
pub const SID_READ_DATA_BY_PERIODIC_ID: u8 = 0x2A;
pub const SID_DYNAMICALLY_DEFINE_DATA_ID: u8 = 0x2C;
pub const SID_READ_MEMORY_BY_ADDRESS: u8 = 0x23;
pub const SID_WRITE_MEMORY_BY_ADDRESS: u8 = 0x3D;
pub const SID_READ_SCALING_DATA_BY_ID: u8 = 0x24;
pub const SID_INPUT_OUTPUT_CONTROL_BY_ID: u8 = 0x2F;
pub const SID_ROUTINE_CONTROL: u8 = 0x31;
pub const SID_REQUEST_DOWNLOAD: u8 = 0x34;
pub const SID_REQUEST_UPLOAD: u8 = 0x35;
pub const SID_TRANSFER_DATA: u8 = 0x36;
pub const SID_REQUEST_TRANSFER_EXIT: u8 = 0x37;

// UDS Response Type
#[derive(Debug, Clone, PartialEq)]
pub enum UdsResponseType {
    Positive,
    Negative(u8), // NRC
}

// UDS Session Type
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UdsSessionType {
    Default = 0x01,
    Programming = 0x02,
    Extended = 0x03,
    SafetySystem = 0x04,
}

// UDS Reset Type
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UdsResetType {
    HardReset = 0x01,
    KeyOffOnReset = 0x02,
    SoftReset = 0x03,
    EnableRapidPowerShutdown = 0x04,
    DisableRapidPowerShutdown = 0x05,
}

// UDS Negative Response Codes
pub const NRC_GENERAL_REJECT: u8 = 0x10;
pub const NRC_SERVICE_NOT_SUPPORTED: u8 = 0x11;
pub const NRC_SUB_FUNCTION_NOT_SUPPORTED: u8 = 0x12;
pub const NRC_INCORRECT_MESSAGE_LENGTH: u8 = 0x13;
pub const NRC_CONDITIONS_NOT_CORRECT: u8 = 0x22;
pub const NRC_REQUEST_SEQUENCE_ERROR: u8 = 0x24;
pub const NRC_REQUEST_OUT_OF_RANGE: u8 = 0x31;
pub const NRC_SECURITY_ACCESS_DENIED: u8 = 0x33;
pub const NRC_INVALID_KEY: u8 = 0x35;
pub const NRC_EXCEEDED_NUMBER_OF_ATTEMPTS: u8 = 0x36;
pub const NRC_RESPONSE_PENDING: u8 = 0x78;

/// UDS Request Message
#[derive(Debug, Clone)]
pub struct UdsRequest {
    pub service_id: u8,
    pub parameters: Vec<u8>,
}

/// UDS Response Message
#[derive(Debug, Clone)]
pub struct UdsResponse {
    pub service_id: u8,
    pub data: Vec<u8>,
}

/// UDS Session Status
#[derive(Debug, Clone)]
pub struct SessionStatus {
    pub session_type: UdsSessionType,
    pub security_level: u8,
    pub last_activity: std::time::Instant,
    pub tester_present_sent: bool,
}

impl Default for SessionStatus {
    fn default() -> Self {
        Self {
            session_type: UdsSessionType::Default,
            security_level: 0,
            last_activity: std::time::Instant::now(),
            tester_present_sent: false,
        }
    }
}

/// UDS Configuration
#[derive(Debug, Clone)]
pub struct UdsConfig {
    pub timeout_ms: u32,
    pub p2_timeout_ms: u32,
    pub p2_star_timeout_ms: u32,
    pub s3_client_timeout_ms: u32,
    pub tester_present_interval_ms: u32,
}

impl Config for UdsConfig {
    fn validate(&self) -> Result<()> {
        Ok(())
    }
}

impl Default for UdsConfig {
    fn default() -> Self {
        Self {
            timeout_ms: 1000,
            p2_timeout_ms: 5000,
            p2_star_timeout_ms: 5000,
            s3_client_timeout_ms: 5000,
            tester_present_interval_ms: 2000,
        }
    }
}

/// UDS Implementation
pub struct Uds<T: TransportLayer> {
    config: UdsConfig,
    transport: T,
    pub status: SessionStatus, // Make public for testing
    is_open: bool,
    handling_session_timing: bool, // Flag to prevent recursive session timing handling
}

impl<T: TransportLayer> Uds<T> {
    /// Creates a new UDS instance with the given transport layer
    pub fn with_transport(config: UdsConfig, transport: T) -> Self {
        Self {
            config,
            transport,
            status: SessionStatus::default(),
            is_open: false,
            handling_session_timing: false,
        }
    }

    /// Changes the diagnostic session
    pub fn change_session(&mut self, session_type: UdsSessionType) -> Result<()> {
        let request = UdsRequest {
            service_id: SID_DIAGNOSTIC_SESSION_CONTROL,
            parameters: vec![session_type as u8],
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Err(AutomotiveError::InvalidParameter)
        } else {
            self.status.session_type = session_type;
            self.status.last_activity = std::time::Instant::now();
            Ok(())
        }
    }

    /// Performs ECU reset
    pub fn ecu_reset(&mut self, reset_type: UdsResetType) -> Result<()> {
        let request = UdsRequest {
            service_id: SID_ECU_RESET,
            parameters: vec![reset_type as u8],
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Ok(())
        } else {
            Err(AutomotiveError::UdsError("Failed to reset ECU".into()))
        }
    }

    /// Reads data by identifier
    pub fn read_data_by_id(&mut self, did: u16) -> Result<Vec<u8>> {
        let request = UdsRequest {
            service_id: SID_READ_DATA_BY_ID,
            parameters: vec![(did >> 8) as u8, did as u8],
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Err(AutomotiveError::UdsError("Failed to read data".into()))
        } else {
            Ok(response.data)
        }
    }

    /// Writes data by identifier
    pub fn write_data_by_id(&mut self, did: u16, data: &[u8]) -> Result<()> {
        let mut request_data = vec![(did >> 8) as u8, did as u8];
        request_data.extend_from_slice(data);

        let request = UdsRequest {
            service_id: SID_WRITE_DATA_BY_ID,
            parameters: request_data,
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Ok(())
        } else {
            Err(AutomotiveError::UdsError("Failed to write data".into()))
        }
    }

    /// Sends tester present message
    pub fn tester_present(&mut self) -> Result<()> {
        let request = UdsRequest {
            service_id: SID_TESTER_PRESENT,
            parameters: vec![],
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            self.status.tester_present_sent = true;
            Ok(())
        } else {
            Err(AutomotiveError::UdsError(
                "Failed to send tester present".into(),
            ))
        }
    }

    /// Performs security access
    pub fn security_access(&mut self, level: u8, key_fn: impl Fn(&[u8]) -> Vec<u8>) -> Result<()> {
        // Request seed
        let request = UdsRequest {
            service_id: SID_SECURITY_ACCESS,
            parameters: vec![2 * level - 1],
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Err(AutomotiveError::UdsError("Failed to get seed".into()))
        } else {
            // Calculate key
            let key = key_fn(&response.data);

            // Send key
            let request = UdsRequest {
                service_id: SID_SECURITY_ACCESS,
                parameters: key,
            };

            let response = self.send_request(&request)?;

            if response.data.is_empty() {
                self.status.security_level = level;
                self.status.last_activity = std::time::Instant::now();
                Ok(())
            } else {
                Err(AutomotiveError::UdsError("Invalid key".into()))
            }
        }
    }

    /// Performs routine control
    pub fn routine_control(
        &mut self,
        _routine_type: u8,
        routine_id: u16,
        data: &[u8],
    ) -> Result<Vec<u8>> {
        let mut request_data = vec![(routine_id >> 8) as u8, routine_id as u8];
        request_data.extend_from_slice(data);

        let request = UdsRequest {
            service_id: SID_ROUTINE_CONTROL,
            parameters: request_data,
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Err(AutomotiveError::UdsError("Routine control failed".into()))
        } else {
            Ok(response.data[2..].to_vec())
        }
    }

    /// Performs input/output control
    pub fn io_control(
        &mut self,
        did: u16,
        control_param: u8,
        control_state: &[u8],
    ) -> Result<Vec<u8>> {
        let mut request_data = vec![(did >> 8) as u8, did as u8, control_param];
        request_data.extend_from_slice(control_state);

        let request = UdsRequest {
            service_id: SID_INPUT_OUTPUT_CONTROL_BY_ID,
            parameters: request_data,
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Ok(vec![])
        } else {
            Ok(response.data[3..].to_vec())
        }
    }

    /// Reads memory by address
    pub fn read_memory(&mut self, address: u32, size: u16) -> Result<Vec<u8>> {
        let request_data = vec![
            4, // Address length
            2, // Size length
            (address >> 24) as u8,
            (address >> 16) as u8,
            (address >> 8) as u8,
            address as u8,
            (size >> 8) as u8,
            size as u8,
        ];

        let request = UdsRequest {
            service_id: SID_READ_MEMORY_BY_ADDRESS,
            parameters: request_data,
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Err(AutomotiveError::UdsError("Memory read failed".into()))
        } else {
            Ok(response.data)
        }
    }

    /// Writes memory by address
    pub fn write_memory(&mut self, address: u32, data: &[u8]) -> Result<()> {
        let mut request_data = vec![
            4, // Address length
            (data.len() as u16 >> 8) as u8,
            data.len() as u8,
            (address >> 24) as u8,
            (address >> 16) as u8,
            (address >> 8) as u8,
            address as u8,
        ];
        request_data.extend_from_slice(data);

        let request = UdsRequest {
            service_id: SID_WRITE_MEMORY_BY_ADDRESS,
            parameters: request_data,
        };

        let response = self.send_request(&request)?;

        if response.data.is_empty() {
            Ok(())
        } else {
            Err(AutomotiveError::UdsError("Memory write failed".into()))
        }
    }

    /// Handles session timing and tester present
    fn handle_session_timing(&mut self) -> Result<()> {
        if self.handling_session_timing {
            return Ok(());
        }
        self.handling_session_timing = true;

        let now = std::time::Instant::now();

        // Check session timeout
        if self.status.session_type != UdsSessionType::Default
            && now.duration_since(self.status.last_activity).as_millis()
                > self.config.timeout_ms as u128
        {
            // Session timeout occurred, reset to default session
            self.status = SessionStatus::default();
            self.handling_session_timing = false;
            return Ok(());
        }

        // Send tester present if needed
        if self.status.session_type != UdsSessionType::Default
            && (!self.status.tester_present_sent
                || now.duration_since(self.status.last_activity).as_millis()
                    > self.config.timeout_ms as u128)
        {
            let request = UdsRequest {
                service_id: SID_TESTER_PRESENT,
                parameters: vec![],
            };

            // Send request directly without session timing
            self.transport.write_frame(&Frame {
                id: 0,
                data: vec![request.service_id],
                timestamp: 0,
                is_extended: false,
                is_fd: false,
            })?;

            // Receive response
            let response = self.transport.read_frame()?;
            if response.data.len() >= 1 && response.data[0] == request.service_id + 0x40 {
                self.status.tester_present_sent = true;
            }
        }

        self.handling_session_timing = false;
        Ok(())
    }
}

impl<T: TransportLayer> ApplicationLayer for Uds<T> {
    type Config = UdsConfig;
    type Request = UdsRequest;
    type Response = UdsResponse;

    fn new(config: Self::Config) -> Result<Self> {
        Err(AutomotiveError::NotInitialized) // Requires transport layer
    }

    fn open(&mut self) -> Result<()> {
        if self.is_open {
            return Ok(());
        }
        self.transport.open()?;
        self.is_open = true;
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.is_open = false;
        Ok(())
    }

    fn send_request(&mut self, request: &Self::Request) -> Result<Self::Response> {
        if !self.is_open {
            return Err(AutomotiveError::NotInitialized);
        }
        let mut data = vec![request.service_id];
        data.extend_from_slice(&request.parameters);
        self.transport.write_frame(&Frame {
            id: 0,
            data,
            timestamp: 0,
            is_extended: false,
            is_fd: false,
        })?;
        let response = self.transport.read_frame()?;
        if response.data.is_empty() {
            return Err(AutomotiveError::InvalidParameter);
        }
        Ok(UdsResponse {
            service_id: response.data[0],
            data: response.data[1..].to_vec(),
        })
    }

    fn set_timeout(&mut self, timeout_ms: u32) -> Result<()> {
        if !self.is_open {
            return Err(AutomotiveError::NotInitialized);
        }
        self.transport.set_timeout(timeout_ms)
    }
}