iso13400-2 0.1.0

A ISO 13400-2 protocol.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
use crate::{error::Error, utils, *};
use getset::{CopyGetters, Getters};
use std::fmt::{Display, Formatter};

#[derive(Debug, Clone, Eq, PartialEq, CopyGetters)]
#[get_copy = "pub"]
pub struct HeaderNegative {
    pub(crate) code: HeaderNegativeCode,
}

impl HeaderNegative {
    pub fn new(code: HeaderNegativeCode) -> Self {
        Self { code }
    }

    #[inline]
    const fn length() -> usize {
        1
    }
}

impl TryFrom<&[u8]> for HeaderNegative {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (_, offset) = utils::data_len_check(data, Self::length(), true)?;
        let code = data[offset];
        let code = HeaderNegativeCode::from(code);

        Ok(Self { code })
    }
}

impl From<HeaderNegative> for Vec<u8> {
    fn from(val: HeaderNegative) -> Self {
        let mut result = HEADER_NEGATIVE.to_be_bytes().to_vec();
        let length = HeaderNegative::length() as u32;
        result.extend(length.to_be_bytes());
        result.push(val.code.into());

        result
    }
}

/****** --- UDP --- ********/

/// response with delay
/// send response 3 times with interval 500ms
/// the RoutingActive from client must be 0xE0 when further_act = 0x10.
#[derive(Debug, Clone, Eq, PartialEq, Getters, CopyGetters)]
pub struct VehicleID {
    // 0x0004
    #[get = "pub"]
    pub(crate) vin: String,
    #[get_copy = "pub"]
    pub(crate) address: LogicAddress,
    #[get_copy = "pub"]
    pub(crate) eid: Eid,
    #[get_copy = "pub"]
    pub(crate) gid: Gid,
    #[get_copy = "pub"]
    pub(crate) further_act: FurtherAction,
    #[get_copy = "pub"]
    pub(crate) sync_status: Option<SyncStatus>,
}

impl VehicleID {
    pub fn new(
        vin: String,
        address: LogicAddress,
        eid: Eid,
        gid: Gid,
        further_act: FurtherAction,
        sync_status: Option<SyncStatus>,
    ) -> Result<Self, Error> {
        let vin_len = vin.len();
        if vin_len != LENGTH_OF_VIN {
            return Err(Error::InvalidParam(format!(
                "length of vin must equal {}",
                LENGTH_OF_VIN
            )));
        }

        Ok(Self {
            vin,
            address,
            eid,
            gid,
            further_act,
            sync_status,
        })
    }

    /// min length
    #[inline]
    const fn length() -> usize {
        LENGTH_OF_VIN + SIZE_OF_ADDRESS + Eid::length() + Gid::length() + 1
    }
}

impl TryFrom<&[u8]> for VehicleID {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (data_len, mut offset) = utils::data_len_check(data, Self::length(), false)?;
        let vin = match String::from_utf8(data[offset..offset + LENGTH_OF_VIN].to_vec()) {
            Ok(v) => v,
            Err(_) => {
                rsutil::warn!("invalid UTF-8 string: {}", hex::encode(data));
                "-".repeat(data_len)
            }
        };
        offset += LENGTH_OF_VIN;
        let address =
            u16::from_be_bytes(data[offset..offset + SIZE_OF_ADDRESS].try_into().unwrap());
        offset += SIZE_OF_ADDRESS;
        let address = LogicAddress::from(address);
        let eid = Eid::try_from(&data[offset..])?;
        offset += Eid::length();
        let gid = Gid::try_from(&data[offset..])?;
        offset += Gid::length();
        let further_act = FurtherAction::from(data[offset]);
        offset += 1;
        let sync_status = match data_len - offset {
            0 => Ok(None),
            1 => Ok(Some(SyncStatus::from(data[offset]))),
            _ => Err(Error::InvalidLength {
                actual: data_len,
                expected: Self::length() + 1,
            }),
        }?;

        Ok(Self {
            vin,
            address,
            eid,
            gid,
            further_act,
            sync_status,
        })
    }
}

impl From<VehicleID> for Vec<u8> {
    fn from(val: VehicleID) -> Self {
        let mut result = UDP_RESP_VEHICLE_IDENTIFIER.to_be_bytes().to_vec();
        let mut length = VehicleID::length() as u32;
        if val.sync_status.is_some() {
            length += 1;
        }
        result.extend(length.to_be_bytes());
        result.extend(val.vin.as_bytes());
        let address: u16 = val.address.into();
        result.extend(address.to_be_bytes());
        result.append(&mut val.eid.into());
        result.append(&mut val.gid.into());
        result.push(val.further_act.into());
        if let Some(status) = val.sync_status {
            result.push(status.into());
        }

        result
    }
}

#[derive(Debug, Clone, Eq, PartialEq, CopyGetters)]
#[get_copy = "pub"]
pub struct EntityStatus {
    // 0x4002
    pub(crate) node_type: NodeType,
    /// 1 ~ 255
    pub(crate) mcts: u8, // Max. concurrent TCP_DATA sockets
    /// 0 ~ 255
    pub(crate) ncts: u8, // Current opened TCP_DATA sockets
    /// 0 ~ 4GB
    pub(crate) max_data_size: Option<u32>,
}

impl EntityStatus {
    pub fn new(node_type: NodeType, mcts: u8, ncts: u8, max_data_size: Option<u32>) -> Self {
        Self {
            node_type,
            mcts,
            ncts,
            max_data_size,
        }
    }

    /// min length
    #[inline]
    const fn length() -> usize {
        1 + 1 + 1
    }
}

impl TryFrom<&[u8]> for EntityStatus {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (data_len, mut offset) = utils::data_len_check(data, Self::length(), false)?;
        let node_type = data[offset];
        offset += 1;
        let node_type = NodeType::from(node_type);
        let mcts = data[offset];
        offset += 1;
        let ncts = data[offset];
        offset += 1;
        let max_data_size = match data_len - offset {
            0 => Ok(None),
            4 => Ok(Some(u32::from_be_bytes(
                data[offset..offset + 4].try_into().unwrap(),
            ))),
            _ => Err(Error::InvalidLength {
                actual: data_len,
                expected: Self::length() + 4,
            }),
        }?;

        Ok(Self {
            node_type,
            mcts,
            ncts,
            max_data_size,
        })
    }
}

impl From<EntityStatus> for Vec<u8> {
    fn from(val: EntityStatus) -> Self {
        let mut result = UDP_RESP_ENTITY_STATUS.to_be_bytes().to_vec();
        let mut length = EntityStatus::length() as u32;
        if val.max_data_size.is_some() {
            length += 4;
        }
        result.extend(length.to_be_bytes());
        result.push(val.node_type.into());
        result.push(val.mcts);
        result.push(val.ncts);
        if let Some(size) = val.max_data_size {
            result.extend(size.to_be_bytes());
        }

        result
    }
}

impl Display for EntityStatus {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DoIP Entity Status")
            .field("\n              Node Type", &self.node_type)
            .field("\n    Max. TCP Connectors", &self.mcts)
            .field("\n Current TCP Connectors", &self.ncts)
            .field("\n       Max. Data Length", &self.max_data_size)
            .finish()
    }
}

#[derive(Debug, Clone, Eq, PartialEq, CopyGetters)]
#[get_copy = "pub"]
pub struct DiagnosticPowerMode {
    // 0x4004
    pub(crate) mode: PowerMode,
}

impl DiagnosticPowerMode {
    pub fn new(mode: PowerMode) -> Self {
        Self { mode }
    }

    #[inline]
    const fn length() -> usize {
        1
    }
}

impl TryFrom<&[u8]> for DiagnosticPowerMode {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (_, offset) = utils::data_len_check(data, Self::length(), true)?;
        let mode = data[offset];
        let mode = PowerMode::from(mode);
        Ok(Self { mode })
    }
}

impl From<DiagnosticPowerMode> for Vec<u8> {
    fn from(val: DiagnosticPowerMode) -> Self {
        let mut result = UDP_RESP_DIAGNOSTIC_POWER_MODE.to_be_bytes().to_vec();
        let length = DiagnosticPowerMode::length() as u32;
        result.extend(length.to_be_bytes());
        result.push(val.mode.into());
        result
    }
}
/****** --- end of UDP --- ********/

/****** --- TCP --- ********/
#[derive(Debug, Clone, Eq, PartialEq, CopyGetters)]
#[get_copy = "pub"]
pub struct RoutingActive {
    // 0x0006
    pub(crate) dst_addr: LogicAddress,
    pub(crate) src_addr: LogicAddress,
    pub(crate) active_code: ActiveCode,
    pub(crate) reserved: u32,
    // #[getter(name = "user_define")]
    pub(crate) user_def: Option<u32>,
}

impl RoutingActive {
    pub fn new(
        dst_addr: LogicAddress,
        src_addr: LogicAddress,
        active_code: ActiveCode,
        user_def: Option<u32>,
    ) -> Self {
        Self {
            dst_addr,
            src_addr,
            active_code,
            reserved: Default::default(),
            user_def,
        }
    }

    /// min length
    #[inline]
    const fn length() -> usize {
        SIZE_OF_ADDRESS + SIZE_OF_ADDRESS + 1 + 4
    }
}

impl TryFrom<&[u8]> for RoutingActive {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (data_len, mut offset) = utils::data_len_check(data, Self::length(), false)?;
        let dst_addr =
            u16::from_be_bytes(data[offset..offset + SIZE_OF_ADDRESS].try_into().unwrap());
        offset += SIZE_OF_ADDRESS;
        let dst_addr = LogicAddress::from(dst_addr);
        let src_addr =
            u16::from_be_bytes(data[offset..offset + SIZE_OF_ADDRESS].try_into().unwrap());
        offset += SIZE_OF_ADDRESS;
        let src_addr = LogicAddress::from(src_addr);
        let active = data[offset];
        offset += 1;
        let active_code = ActiveCode::from(active);
        let reserved = u32::from_be_bytes(data[offset..offset + 4].try_into().unwrap());
        offset += 4;
        let user_def = match data_len - offset {
            0 => Ok(None),
            4 => Ok(Some(u32::from_be_bytes(
                data[offset..offset + 4].try_into().unwrap(),
            ))),
            _ => Err(Error::InvalidLength {
                actual: data_len,
                expected: Self::length() + 4,
            }),
        }?;

        Ok(Self {
            dst_addr,
            src_addr,
            active_code,
            reserved,
            user_def,
        })
    }
}

impl From<RoutingActive> for Vec<u8> {
    fn from(val: RoutingActive) -> Self {
        let mut result = TCP_RESP_ROUTING_ACTIVE.to_be_bytes().to_vec();
        let mut length = RoutingActive::length() as u32;
        if val.user_def.is_some() {
            length += 4;
        }
        result.extend(length.to_be_bytes());
        let dst_addr: u16 = val.dst_addr.into();
        result.extend(dst_addr.to_be_bytes());
        let src_addr: u16 = val.src_addr.into();
        result.extend(src_addr.to_be_bytes());
        result.push(val.active_code.into());
        result.extend(val.reserved.to_be_bytes());
        if let Some(user_def) = val.user_def {
            result.extend(user_def.to_be_bytes());
        }

        result
    }
}

#[derive(Debug, Clone, Eq, PartialEq, CopyGetters)]
#[get_copy = "pub"]
pub struct AliveCheck {
    // 0x0008
    pub(crate) src_addr: LogicAddress,
}

impl AliveCheck {
    pub fn new(addr: LogicAddress) -> Self {
        Self { src_addr: addr }
    }

    #[inline]
    const fn length() -> usize {
        SIZE_OF_ADDRESS
    }
}

impl TryFrom<&[u8]> for AliveCheck {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (_, offset) = utils::data_len_check(data, Self::length(), true)?;
        let src_addr = u16::from_be_bytes(data[offset..].try_into().unwrap());
        let src_addr = LogicAddress::from(src_addr);

        Ok(Self { src_addr })
    }
}

impl From<AliveCheck> for Vec<u8> {
    fn from(val: AliveCheck) -> Self {
        let mut result = TCP_RESP_ALIVE_CHECK.to_be_bytes().to_vec();
        let length = AliveCheck::length() as u32;
        result.extend(length.to_be_bytes());
        let src_addr: u16 = val.src_addr.into();
        result.extend(src_addr.to_be_bytes());
        result
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Getters)]
#[get = "pub"]
pub struct DiagnosticPositive {
    // 0x8002
    #[getset(get_copy = "pub")]
    pub(crate) src_addr: LogicAddress,
    #[getset(get_copy = "pub")]
    pub(crate) dst_addr: LogicAddress,
    #[getset(get_copy = "pub")]
    pub(crate) code: DiagnosticPositiveCode,
    // #[getter(name = "previous_diagnostic_data")]
    #[getset(get = "pub")]
    pub(crate) pre_diag_data: Vec<u8>,
}

impl DiagnosticPositive {
    pub fn new(
        src_addr: LogicAddress,
        dst_addr: LogicAddress,
        code: DiagnosticPositiveCode,
        pre_diag_data: Vec<u8>,
    ) -> Self {
        if code != DiagnosticPositiveCode::Confirm {
            rsutil::warn!("Diagnostic Positive code: {:?}", code);
        }
        Self {
            src_addr,
            dst_addr,
            code,
            pre_diag_data,
        }
    }
    /// min length
    #[inline]
    const fn length() -> usize {
        SIZE_OF_ADDRESS + SIZE_OF_ADDRESS + 1
    }
}

impl TryFrom<&[u8]> for DiagnosticPositive {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (_, mut offset) = utils::data_len_check(data, Self::length(), false)?;
        let src_addr =
            u16::from_be_bytes(data[offset..offset + SIZE_OF_ADDRESS].try_into().unwrap());
        offset += SIZE_OF_ADDRESS;
        let src_addr = LogicAddress::from(src_addr);
        let dst_addr =
            u16::from_be_bytes(data[offset..offset + SIZE_OF_ADDRESS].try_into().unwrap());
        offset += SIZE_OF_ADDRESS;
        let dst_addr = LogicAddress::from(dst_addr);
        let code = DiagnosticPositiveCode::from(data[offset]);
        offset += 1;
        let pre_diag_msg = data[offset..].to_vec();

        Ok(Self::new(src_addr, dst_addr, code, pre_diag_msg))
    }
}

impl From<DiagnosticPositive> for Vec<u8> {
    fn from(mut val: DiagnosticPositive) -> Self {
        let mut result = TCP_RESP_DIAGNOSTIC_POSITIVE.to_be_bytes().to_vec();
        let length = (DiagnosticPositive::length() + val.pre_diag_data.len()) as u32;
        result.extend(length.to_be_bytes());
        let src_addr: u16 = val.src_addr.into();
        result.extend(src_addr.to_be_bytes());
        let dst_addr: u16 = val.dst_addr.into();
        result.extend(dst_addr.to_be_bytes());
        result.push(val.code.into());
        result.append(&mut val.pre_diag_data);

        result
    }
}

impl Display for DiagnosticPositive {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Diagnostic Positive")
            .field("\n       Source Address", &self.src_addr)
            .field("\n       Target Address", &self.dst_addr)
            .field("\n                 Code", &self.code)
            .field("\n        Previous Data", &hex::encode(&self.pre_diag_data))
            .finish()
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Getters, CopyGetters)]
pub struct DiagnosticNegative {
    // 0x8003
    #[getset(get_copy = "pub")]
    pub(crate) src_addr: LogicAddress,
    #[getset(get_copy = "pub")]
    pub(crate) dst_addr: LogicAddress,
    #[getset(get_copy = "pub")]
    pub(crate) code: DiagnosticNegativeCode,
    // #[getter(name = "previous_diagnostic_data")]
    #[getset(get = "pub")]
    pub(crate) pre_diag_data: Vec<u8>,
}

impl DiagnosticNegative {
    pub fn new(
        src_addr: LogicAddress,
        dst_addr: LogicAddress,
        code: DiagnosticNegativeCode,
        pre_diag_data: Vec<u8>,
    ) -> Self {
        Self {
            src_addr,
            dst_addr,
            code,
            pre_diag_data,
        }
    }

    /// min length
    #[inline]
    const fn length() -> usize {
        SIZE_OF_ADDRESS + SIZE_OF_ADDRESS + 1
    }
}

impl TryFrom<&[u8]> for DiagnosticNegative {
    type Error = Error;
    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        let (_, mut offset) = utils::data_len_check(data, Self::length(), false)?;
        let src_addr =
            u16::from_be_bytes(data[offset..offset + SIZE_OF_ADDRESS].try_into().unwrap());
        offset += SIZE_OF_ADDRESS;
        let src_addr = LogicAddress::from(src_addr);
        let dst_addr =
            u16::from_be_bytes(data[offset..offset + SIZE_OF_ADDRESS].try_into().unwrap());
        offset += SIZE_OF_ADDRESS;
        let dst_addr = LogicAddress::from(dst_addr);
        let code = DiagnosticNegativeCode::from(data[offset]);
        offset += 1;
        let pre_diag_data = data[offset..].to_vec();

        Ok(Self {
            src_addr,
            dst_addr,
            code,
            pre_diag_data,
        })
    }
}

impl From<DiagnosticNegative> for Vec<u8> {
    fn from(mut val: DiagnosticNegative) -> Self {
        let mut result = TCP_RESP_DIAGNOSTIC_NEGATIVE.to_be_bytes().to_vec();
        let length = (DiagnosticNegative::length() + val.pre_diag_data.len()) as u32;
        result.extend(length.to_be_bytes());
        let src_addr: u16 = val.src_addr.into();
        result.extend(src_addr.to_be_bytes());
        let dst_addr: u16 = val.dst_addr.into();
        result.extend(dst_addr.to_be_bytes());
        result.push(val.code.into());
        result.append(&mut val.pre_diag_data);

        result
    }
}

impl Display for DiagnosticNegative {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Diagnostic Negative")
            .field("\n       Source Address", &self.src_addr)
            .field("\n       Target Address", &self.dst_addr)
            .field("\n                 Code", &self.code)
            .field("\n        Previous Data", &hex::encode(&self.pre_diag_data))
            .finish()
    }
}
/****** --- end of UDP --- ********/