ace-gateway 0.1.0

DoIP Gateway, ISO-TP bridge node, and DoIP Tester
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! DoIP gateway state machine.
//!
//! The gateway sits between two simulation buses:
//!     - TCP bus (DoIP side): receives DoIP frames from testers
//!     - CAN bus (ISO-TP side): sends/receives raw CAN-addressed UDS bytes
//!
//! It owns one ConnectionState per tester (up to MAX_TESTERS) and a PendingRouteTable that matches
//! CAN responses back to their tester.
//!
//! The gateway is a SimNode on the TCP bus. It communicates with the IsoTpNode on the CAN bus via
//! raw UDS bytes addressed by CAN ID.

// region: Imports

use ace_core::FrameWrite;
use ace_doip::{
    error::DoipError,
    ext::DoipFrameExt,
    header::{DoipHeader, PayloadType, ProtocolVersion},
    payload::{
        AliveCheckRequest, AliveCheckResponse, DiagnosticAckCode, DiagnosticMessageAck,
        DiagnosticMessageNack, DiagnosticNackCode, GenericNack, NackCode,
    },
    session::{ActivationAuthProvider, ActivationStateMachine, ConnectionEvent, ConnectionState},
};
use ace_proto::{doip::constants::DOIP_HEADER_LEN, DoipFrame};
use ace_sim::{clock::Instant, io::NodeAddress};

use crate::{
    config::GatewayConfig,
    router::{PendingRoute, PendingRouteTable},
};

// endregion: Imports

// region: Capacity Constants

/// Max DoIP frame size for the TCP bus side.
pub const TCP_MAX_FRAME: usize = 4096 + DOIP_HEADER_LEN + 4; // UDS + DoIP header + addresses

/// Max outbox depth on the TCP bus side.
pub const TCP_MAX_OUTBOX: usize = 16;

/// Max raw UDS frame size for the CAN bus side
pub const CAN_MAX_FRAME: usize = 4096;

/// Max outbox depth on the CAN bus side.
pub const CAN_MAX_OUTBOX: usize = 16;

// endregion: Capacity Constants

// region: GatewayError

#[derive(Debug)]
pub enum GatewayError {
    /// DoIP header validation failed.
    InvalidDoipHeader,

    /// Codec encode/decode error.
    Codec,

    /// TCP outbox full.
    TcpOutboxFull,

    /// CAN outbox full.
    CanOutboxFull,

    /// No connection slot available for a new tester.
    NoConnectionSlot,
}

// endregion: GatewayError

// region: ConnectionSlot

/// A slot for one tester TCP connection.
struct ConnectionSlot<A: ActivationAuthProvider, const BUF: usize> {
    /// The logical address of the connected tester - `None` if slot is free.
    tester_address: Option<u16>,
    state: ConnectionState<A, BUF>,
}

// endregion: ConnectionSlot

// region: DoipGateway

pub struct DoipGateway<A, const MAX_TESTERS: usize = 1, const BUF: usize = 4096>
where
    A: ActivationAuthProvider + Clone,
{
    config: GatewayConfig,
    auth: A,
    address: NodeAddress,

    /// Outbound DoIP frames for the TCP bus.
    tcp_outbox: heapless::Vec<(NodeAddress, heapless::Vec<u8, TCP_MAX_FRAME>), TCP_MAX_OUTBOX>,

    /// Outbound UDS bytes for the CAN bus (address by CAN request ID).
    can_outbox: heapless::Vec<(NodeAddress, heapless::Vec<u8, CAN_MAX_FRAME>), CAN_MAX_OUTBOX>,

    /// Pending route table - matches CAN responses to tester connections.
    routes: PendingRouteTable<MAX_TESTERS>,

    /// Active tester connection slots.
    connections: heapless::Vec<ConnectionSlot<A, BUF>, MAX_TESTERS>,
}

impl<A, const MAX_TESTERS: usize, const BUF: usize> DoipGateway<A, MAX_TESTERS, BUF>
where
    A: ActivationAuthProvider + Clone,
{
    pub fn new(config: GatewayConfig, auth: A, address: NodeAddress) -> Self {
        Self {
            config,
            auth,
            address,
            tcp_outbox: heapless::Vec::new(),
            can_outbox: heapless::Vec::new(),
            routes: PendingRouteTable::new(),
            connections: heapless::Vec::new(),
        }
    }

    // region: SimNode surface - TCP bus

    pub fn address(&self) -> &NodeAddress {
        &self.address
    }

    /// Handles a raw DoIP frame from the TCP bus.
    ///
    /// Validates the header, dispatches on payload type, and drives the connection state machine
    /// for the originating tester.
    pub fn handle_tcp(
        &mut self,
        src: &NodeAddress,
        data: &[u8],
        now: Instant,
    ) -> Result<(), GatewayError> {
        let frame = DoipFrame::from_slice(data);

        if let Err(_) = frame.validate_header() {
            self.send_generic_nack(src)?;
            return Err(GatewayError::InvalidDoipHeader);
        }

        let payload_type = match frame.payload_type() {
            Some(Ok(pt)) => pt,
            _ => {
                self.send_generic_nack(src)?;
                return Err(GatewayError::InvalidDoipHeader);
            }
        };

        let payload_data = frame.payload_bytes().unwrap_or(&[]);

        let tester_address = src.0 as u16;
        self.ensure_slot(tester_address, now)?;

        let slot_idx = self.find_slot_idx(tester_address);

        if let Some(idx) = slot_idx {
            self.connections[idx]
                .state
                .handle(&payload_type, payload_data, now);
            self.process_connection_events(idx, src, now)?;
        }

        Ok(())
    }

    /// Handles a raw UDS response frame from the CAN bus (via IsoTpNode).
    ///
    /// The NodeAddress carries the CAN response ID so the router can match it to the originating
    /// tester.
    pub fn handle_can(
        &mut self,
        src: &NodeAddress,
        data: &[u8],
        _now: Instant,
    ) -> Result<(), GatewayError> {
        let can_id = src.0;

        let route = match self.routes.take_by_can_response_id(can_id) {
            Some(r) => r,
            None => return Ok(()),
        };

        self.send_diagnostic_message(
            &NodeAddress(route.tester_address as u32),
            route.doip_source,
            route.doip_target,
            data,
        )
    }

    pub fn tick(&mut self, now: Instant) -> Result<(), GatewayError> {
        for idx in 0..self.connections.len() {
            self.connections[idx].state.tick(now);

            let events: heapless::Vec<ConnectionEvent<BUF>, 8> =
                self.connections[idx].state.drain_events().collect();

            let tester_addr = self.connections[idx]
                .tester_address
                .map(|a| NodeAddress(a as u32))
                .unwrap_or(NodeAddress(0));

            for event in events {
                self.handle_connection_event(idx, &tester_addr, event)?;
            }
        }

        Ok(())
    }

    /// Drains outbound DoIP frames for the TCP bus.
    pub fn drain_tcp_outbox(
        &mut self,
        out: &mut heapless::Vec<(NodeAddress, heapless::Vec<u8, TCP_MAX_FRAME>), TCP_MAX_OUTBOX>,
    ) -> usize {
        let n = self.tcp_outbox.len();

        for item in self.tcp_outbox.drain(..) {
            let _ = out.push(item);
        }

        n
    }

    /// Drains outbound UDS frames for the CAN bus.
    pub fn drain_can_outbox(
        &mut self,
        out: &mut heapless::Vec<(NodeAddress, heapless::Vec<u8, CAN_MAX_FRAME>), CAN_MAX_OUTBOX>,
    ) -> usize {
        let n = self.can_outbox.len();

        for item in self.can_outbox.drain(..) {
            let _ = out.push(item);
        }

        n
    }

    // endregion: SimNode surface

    // region: Connection Slot Management

    fn find_slot_idx(&self, tester_address: u16) -> Option<usize> {
        self.connections
            .iter()
            .position(|s| s.tester_address == Some(tester_address))
    }

    fn ensure_slot(&mut self, tester_address: u16, now: Instant) -> Result<(), GatewayError> {
        if self.find_slot_idx(tester_address).is_some() {
            return Ok(());
        }

        if self.connections.is_full() {
            return Err(GatewayError::NoConnectionSlot);
        }

        let mut registered = heapless::Vec::new();

        for &addr in &self.config.registered_testers {
            let _ = registered.push(addr);
        }

        let mut supported = heapless::Vec::new();

        for t in &self.config.supported_activation_types {
            let _ = supported.push(t.clone());
        }

        let activation = ActivationStateMachine::new(
            self.config.logical_address,
            registered,
            supported,
            self.auth.clone(),
        );

        let state = ConnectionState::new(self.config.connection_config.clone(), activation, now);

        let _ = self.connections.push(ConnectionSlot {
            tester_address: Some(tester_address),
            state,
        });

        Ok(())
    }

    fn remove_slot(&mut self, tester_address: u16) {
        if let Some(pos) = self
            .connections
            .iter()
            .position(|s| s.tester_address == Some(tester_address))
        {
            self.connections.remove(pos);
            self.routes.remove_tester(tester_address);
        }
    }

    // endregion: Connection Slot Management

    // region: Event Processing

    fn process_connection_events(
        &mut self,
        slot_idx: usize,
        tester: &NodeAddress,
        _now: Instant,
    ) -> Result<(), GatewayError> {
        let events: heapless::Vec<ConnectionEvent<BUF>, 8> =
            self.connections[slot_idx].state.drain_events().collect();

        for event in events {
            self.handle_connection_event(slot_idx, tester, event)?;
        }

        Ok(())
    }

    fn handle_connection_event(
        &mut self,
        slot_idx: usize,
        tester: &NodeAddress,
        event: ConnectionEvent<BUF>,
    ) -> Result<(), GatewayError> {
        match event {
            ConnectionEvent::SendActivationResponse(resp) => {
                self.encode_and_send_tcp(tester, PayloadType::RoutingActivationResponse, &resp)?;
            }

            ConnectionEvent::SendDiagnosticAck {
                source_address,
                target_address,
            } => {
                let ack = DiagnosticMessageAck {
                    source_address: source_address.to_be_bytes(),
                    target_address: target_address.to_be_bytes(),
                    ack_code: DiagnosticAckCode::Acknowledged,
                    data: &[],
                };
                self.encode_and_send_tcp(tester, PayloadType::DiagnosticMessageAck, &ack)?;
            }

            ConnectionEvent::SendDiagnosticNack {
                source_address,
                target_address,
                nack_code,
            } => {
                let ack = DiagnosticMessageNack {
                    source_address: source_address.to_be_bytes(),
                    target_address: target_address.to_be_bytes(),
                    nack_code,
                };
                self.encode_and_send_tcp(tester, PayloadType::DiagnosticMessageNack, &ack)?;
            }

            ConnectionEvent::ForwardToEcu {
                source_address,
                target_address,
                uds_data,
            } => {
                let node = match self.config.find_node(target_address) {
                    Some(n) => n.clone(),
                    None => {
                        let nack = DiagnosticMessageNack {
                            source_address: source_address.to_be_bytes(),
                            target_address: target_address.to_be_bytes(),
                            nack_code: DiagnosticNackCode::UnknownTargetAddress,
                        };

                        return self.encode_and_send_tcp(
                            tester,
                            PayloadType::DiagnosticMessageNack,
                            &nack,
                        );
                    }
                };

                let tester_address = self.connections[slot_idx].tester_address.unwrap_or(0);

                let _ = self.routes.insert(PendingRoute {
                    tester_address,
                    doip_source: source_address,
                    doip_target: target_address,
                    response_can_id: node.response_can_id,
                });

                let mut frame = heapless::Vec::new();
                let _ = frame.extend_from_slice(&uds_data);

                self.can_outbox
                    .push((NodeAddress(node.request_can_id), frame))
                    .map_err(|_| GatewayError::CanOutboxFull)?;
            }

            ConnectionEvent::SendAliveCheckRequest => {
                let req = AliveCheckRequest {};

                self.encode_and_send_tcp(tester, PayloadType::AliveCheckRequest, &req)?;
            }

            ConnectionEvent::SendAliveCheckResponse => {
                let tester_address = self.connections[slot_idx].tester_address.unwrap_or(0);

                let resp = AliveCheckResponse {
                    source_address: tester_address.to_be_bytes(),
                };

                self.encode_and_send_tcp(tester, PayloadType::AliveCheckResponse, &resp)?;
            }

            ConnectionEvent::Close => {
                let tester_address = self.connections[slot_idx].tester_address.unwrap_or(0);

                self.remove_slot(tester_address);
            }
        }

        Ok(())
    }

    // endregion: Event Processing

    // region: Frame Construction Helpers

    fn encode_and_send_tcp<T: FrameWrite<Error = DoipError>>(
        &mut self,
        dst: &NodeAddress,
        payload_type: PayloadType,
        payload: &T,
    ) -> Result<(), GatewayError> {
        let mut payload_buf: heapless::Vec<u8, TCP_MAX_FRAME> = heapless::Vec::new();
        {
            let mut slice = payload_buf.as_mut();
            payload
                .encode(&mut slice)
                .map_err(|_| GatewayError::Codec)?;
        }

        let header = DoipHeader {
            protocol_version: ProtocolVersion::Iso13400_2012,
            inverse_protocol_version: !(ProtocolVersion::Iso13400_2012 as u8),
            payload_type,
            payload_length: payload_buf.len() as u32,
        };

        let mut frame = heapless::Vec::new();
        {
            let mut slice = frame.as_mut();
            header.encode(&mut slice).map_err(|_| GatewayError::Codec)?;
            payload
                .encode(&mut slice)
                .map_err(|_| GatewayError::Codec)?;
        }

        self.tcp_outbox
            .push((dst.clone(), frame))
            .map_err(|_| GatewayError::TcpOutboxFull)
    }

    fn send_diagnostic_message(
        &mut self,
        dst: &NodeAddress,
        source_address: u16,
        target_address: u16,
        uds_data: &[u8],
    ) -> Result<(), GatewayError> {
        let mut frame: heapless::Vec<u8, TCP_MAX_FRAME> = heapless::Vec::new();

        let payload_len = 4 + uds_data.len();

        let header = DoipHeader {
            protocol_version: ProtocolVersion::Iso13400_2012,
            inverse_protocol_version: !(ProtocolVersion::Iso13400_2012 as u8),
            payload_type: PayloadType::DiagnosticMessage,
            payload_length: payload_len as u32,
        };

        {
            let mut slice = frame.as_mut();
            header.encode(&mut slice).map_err(|_| GatewayError::Codec)?;
        }

        let src_bytes = source_address.to_be_bytes();
        let _ = frame.extend_from_slice(&src_bytes);

        let tgt_bytes = target_address.to_be_bytes();
        let _ = frame.extend_from_slice(&tgt_bytes);

        let _ = frame.extend_from_slice(&uds_data);

        self.tcp_outbox
            .push((dst.clone(), frame))
            .map_err(|_| GatewayError::TcpOutboxFull)
    }

    fn send_generic_nack(&mut self, dst: &NodeAddress) -> Result<(), GatewayError> {
        let nack = GenericNack {
            nack_code: NackCode::InvalidPayloadLength,
        };

        self.encode_and_send_tcp(dst, PayloadType::GenericNack, &nack)
    }

    // endregion: Frame Construction Helpers
}

// endregion: DoipGateway