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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use std::{
    fmt,
    hash::{Hash, Hasher},
};

use crate::{error::Result, header::Header, id_hash::IdHash};

/// A tuple of identification information about a `Packet` value.
///
/// It consists of the following parts:
///
/// - the channel
/// - the destination address
/// - the source address
/// - the command
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PacketId(pub u8, pub u16, pub u16, pub u16);

impl PacketId {
    /// Create an ID string for the given `PacketId` value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use resol_vbus::PacketId;
    ///
    /// assert_eq!("11_1213_1415_10_1718", PacketId(0x11, 0x1213, 0x1415, 0x1718).packet_id_string());
    /// ```
    pub fn packet_id_string(&self) -> String {
        format!(
            "{:02X}_{:04X}_{:04X}_10_{:04X}",
            self.0, self.1, self.2, self.3
        )
    }
}

/// A trait to get a `PacketId` for a given value.
pub trait ToPacketId {
    /// Get the `PacketId` for a given value.
    fn to_packet_id(&self) -> Result<PacketId>;
}

impl ToPacketId for PacketId {
    fn to_packet_id(&self) -> Result<PacketId> {
        Ok(*self)
    }
}

impl ToPacketId for str {
    /// Parse the string into a packet ID tuple.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use resol_vbus::{PacketId, ToPacketId};
    ///
    /// assert_eq!(PacketId(0x11, 0x1213, 0x1415, 0x1718), "11_1213_1415_10_1718".to_packet_id().unwrap());
    /// ```
    fn to_packet_id(&self) -> Result<PacketId> {
        let is_not_hex_char = |c| match c {
            '0'...'9' | 'A'...'F' | 'a'...'f' => false,
            _ => true,
        };

        if self.len() < 20 {
            return Err(format!("Invalid length of input {:?}", self).into());
        }

        let mut parts = self.split('_');

        let channel_str = parts.next().unwrap();
        if channel_str.len() != 2 {
            return Err(format!("Invalid length of channel {:?}", channel_str).into());
        }
        if channel_str.chars().any(&is_not_hex_char) {
            return Err(format!("Invalid characters in channel {:?}", channel_str).into());
        }
        let channel = u8::from_str_radix(channel_str, 16).unwrap();

        let destination_address_str = parts.next().unwrap();
        if destination_address_str.len() != 4 {
            return Err(format!(
                "Invalid length of destination address {:?}",
                destination_address_str
            )
            .into());
        }
        if destination_address_str.chars().any(&is_not_hex_char) {
            return Err(format!(
                "Invalid characters in destination address {:?}",
                destination_address_str
            )
            .into());
        }
        let destination_address = u16::from_str_radix(destination_address_str, 16).unwrap();

        let source_address_str = parts.next().unwrap();
        if source_address_str.len() != 4 {
            return Err(format!("Invalid length of source address {:?}", source_address_str).into());
        }
        if source_address_str.chars().any(&is_not_hex_char) {
            return Err(format!(
                "Invalid characters in source address {:?}",
                source_address_str
            )
            .into());
        }
        let source_address = u16::from_str_radix(source_address_str, 16).unwrap();

        let protocol_version_str = parts.next().unwrap();
        if protocol_version_str.len() != 2 {
            return Err(format!(
                "Invalid length of protocol version {:?}",
                protocol_version_str
            )
            .into());
        }
        if protocol_version_str.chars().any(&is_not_hex_char) {
            return Err(format!(
                "Invalid characters in protocol version {:?}",
                protocol_version_str
            )
            .into());
        }
        let protocol_version = u8::from_str_radix(protocol_version_str, 16).unwrap();
        if (protocol_version & 0xF0) != 0x10 {
            return Err(format!("Unsupported protocol version 0x{:02X}", protocol_version).into());
        }

        let command_str = parts.next().unwrap();
        if command_str.len() != 4 {
            return Err(format!("Invalid length of command {:?}", command_str).into());
        }
        if command_str.chars().any(&is_not_hex_char) {
            return Err(format!("Invalid characters in command {:?}", command_str).into());
        }
        let command = u16::from_str_radix(command_str, 16).unwrap();

        Ok(PacketId(
            channel,
            destination_address,
            source_address,
            command,
        ))
    }
}

/// A tuple of identification information about a field in a `Packet` value.
///
/// It consists of the following parts:
///
/// - the packet ID tuple (channel, destination address, source address and command)
/// - the field ID
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PacketFieldId<'a>(pub PacketId, pub &'a str);

impl<'a> PacketFieldId<'a> {
    /// Get the packet ID string for a given `PacketFieldId` value.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use resol_vbus::{PacketId, PacketFieldId};
    ///
    /// let packet_field_id = PacketFieldId(PacketId(0x11, 0x1213, 0x1415, 0x1718), "012_4_0");
    /// assert_eq!("11_1213_1415_10_1718", packet_field_id.packet_id_string());
    /// ```
    pub fn packet_id_string(&self) -> String {
        self.0.packet_id_string()
    }

    /// Get the packet field ID string for a given `PacketFieldId` value.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use resol_vbus::{PacketId, PacketFieldId};
    ///
    /// let packet_field_id = PacketFieldId(PacketId(0x11, 0x1213, 0x1415, 0x1718), "012_4_0");
    /// assert_eq!("11_1213_1415_10_1718_012_4_0", packet_field_id.packet_field_id_string());
    /// ```
    pub fn packet_field_id_string(&self) -> String {
        format!("{}_{}", self.packet_id_string(), self.1)
    }
}

/// A trait to get a `PacketFieldId` for a given value.
pub trait ToPacketFieldId {
    /// Get the `PacketFieldId` for a given value.
    fn to_packet_field_id(&self) -> Result<PacketFieldId>;
}

impl<'a> ToPacketFieldId for PacketFieldId<'a> {
    fn to_packet_field_id(&self) -> Result<PacketFieldId> {
        Ok(*self)
    }
}

impl ToPacketFieldId for str {
    /// Parse the string into a packet field ID tuple.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use resol_vbus::{PacketId, PacketFieldId, ToPacketFieldId};
    ///
    /// assert_eq!(PacketFieldId(PacketId(0x11, 0x1213, 0x1415, 0x1718), "012_4_0"), "11_1213_1415_10_1718_012_4_0".to_packet_field_id().unwrap());
    /// ```
    fn to_packet_field_id(&self) -> Result<PacketFieldId> {
        if self.len() < 21 {
            return Err(format!("Invalid length of input {:?}", self).into());
        }

        let packet_id = self.to_packet_id()?;

        let field_id = &self[21..];

        Ok(PacketFieldId(packet_id, field_id))
    }
}

/// The `Packet` type stores information according to the VBus protocol version 1.x.
///
/// Packets are used to transmit larger amount of information (up to 508 bytes of payload) relying
/// on the fact that both sides of the communication know how that payload is structured and how to
/// extract the information out of it.
///
/// ## The "identity" of `Packet` values
///
/// As described in [the corresponding section of the `Header` struct][1] VBus data types use
/// some of their fields as part of their "identity". In addition to the fields used by the
/// `Header` type the `Packet` type also respects the `command` field. That means that two `Packet`
/// with differing `timestamp`, `frame_count` and `frame_data` fields are still considered
/// "identical", if the other fields match.
///
/// [1]: struct.Header.html#the-identity-of-header-values
///
/// ## The payload of `Packet` values
///
/// The VBus Protocol Specification describes that all the fields used for the `Packet`'s
/// "identity" can also be used to determine the structure of the payload contained in the
/// `frame_data` field. The [`Specification`][2] type can be used to decode the payload
/// information.
///
/// [2]: struct.Specification.html
pub struct Packet {
    /// The shared `Header` of all VBus protocol types.
    pub header: Header,

    /// The command of this `Packet`.
    pub command: u16,

    /// The number of 4-byte frames attached to this `Packet`.
    pub frame_count: u8,

    /// The actual data from the frames attached to this `Packet`.
    pub frame_data: [u8; 508],
}

impl Packet {
    /// Return the length of the valid area of the `frame_data`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use resol_vbus::{Header, Packet};
    /// use resol_vbus::utils::utc_timestamp;
    ///
    /// let packet = Packet {
    ///     header: Header {
    ///         timestamp: utc_timestamp(1485688933),
    ///         channel: 0x11,
    ///         destination_address: 0x1213,
    ///         source_address: 0x1415,
    ///         protocol_version: 0x16,
    ///     },
    ///     command: 0x1718,
    ///     frame_count: 0x19,
    ///     frame_data: [0u8; 508],
    /// };
    ///
    /// assert_eq!(100, packet.valid_frame_data_len());
    /// ```
    pub fn valid_frame_data_len(&self) -> usize {
        self.frame_count as usize * 4
    }

    /// Return the valid area of the `frame_data` immutably.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use resol_vbus::{Header, Packet};
    /// use resol_vbus::utils::utc_timestamp;
    ///
    /// let packet = Packet {
    ///     header: Header {
    ///         timestamp: utc_timestamp(1485688933),
    ///         channel: 0x11,
    ///         destination_address: 0x1213,
    ///         source_address: 0x1415,
    ///         protocol_version: 0x16,
    ///     },
    ///     command: 0x1718,
    ///     frame_count: 0x19,
    ///     frame_data: [0u8; 508],
    /// };
    ///
    /// assert_eq!(508, packet.frame_data.len());
    /// assert_eq!(100, packet.valid_frame_data().len());
    /// ```
    pub fn valid_frame_data(&self) -> &[u8] {
        let end = self.valid_frame_data_len();
        &self.frame_data[0..end]
    }

    /// Return the valid area of the `frame_data` mutably.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use resol_vbus::{Header, Packet};
    /// use resol_vbus::utils::utc_timestamp;
    ///
    /// let mut packet = Packet {
    ///     header: Header {
    ///         timestamp: utc_timestamp(1485688933),
    ///         channel: 0x11,
    ///         destination_address: 0x1213,
    ///         source_address: 0x1415,
    ///         protocol_version: 0x16,
    ///     },
    ///     command: 0x1718,
    ///     frame_count: 0x19,
    ///     frame_data: [0u8; 508],
    /// };
    ///
    /// assert_eq!(508, packet.frame_data.len());
    /// assert_eq!(100, packet.valid_frame_data_mut().len());
    /// ```
    pub fn valid_frame_data_mut(&mut self) -> &mut [u8] {
        let end = self.valid_frame_data_len();
        &mut self.frame_data[0..end]
    }

    /// Returns identification information about this `Packet`.
    ///
    /// The result contains all fields that count towards the "identity" of the `Packet` with the
    /// exception of the `protocol_version` (since it must be 1.x to be a `Packet` anyway):
    ///
    /// - `channel`
    /// - `destination_address`
    /// - `source_address`
    /// - `command`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use resol_vbus::{Header, Packet, PacketId};
    /// use resol_vbus::utils::utc_timestamp;
    ///
    /// let packet = Packet {
    ///     header: Header {
    ///         timestamp: utc_timestamp(1485688933),
    ///         channel: 0x11,
    ///         destination_address: 0x1213,
    ///         source_address: 0x1415,
    ///         protocol_version: 0x16,
    ///     },
    ///     command: 0x1718,
    ///     frame_count: 0x19,
    ///     frame_data: [0u8; 508],
    /// };
    ///
    /// assert_eq!(PacketId(0x11, 0x1213, 0x1415, 0x1718), packet.packet_id());
    /// ```
    pub fn packet_id(&self) -> PacketId {
        PacketId(
            self.header.channel,
            self.header.destination_address,
            self.header.source_address,
            self.command,
        )
    }

    /// Creates an identification string for this `Packet`.
    ///
    /// The string contains all fields that count towards the "identity" of the `Packet`:
    ///
    /// - `channel`
    /// - `destination_address`
    /// - `source_address`
    /// - `protocol_version`
    /// - `command`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use resol_vbus::{Header, Packet};
    /// use resol_vbus::utils::utc_timestamp;
    ///
    /// let packet = Packet {
    ///     header: Header {
    ///         timestamp: utc_timestamp(1485688933),
    ///         channel: 0x11,
    ///         destination_address: 0x1213,
    ///         source_address: 0x1415,
    ///         protocol_version: 0x16,
    ///     },
    ///     command: 0x1718,
    ///     frame_count: 0x19,
    ///     frame_data: [0u8; 508],
    /// };
    ///
    /// assert_eq!("11_1213_1415_16_1718", packet.id_string());
    /// ```
    pub fn id_string(&self) -> String {
        format!("{}_{:04X}", self.header.id_string(), self.command)
    }
}

impl IdHash for Packet {
    /// Returns an identification hash for this `Packet`.
    ///
    /// The hash contains all fields that count towards the "identity" of the `Packet`:
    ///
    /// - `channel`
    /// - `destination_address`
    /// - `source_address`
    /// - `protocol_version`
    /// - `command`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use resol_vbus::{Header, Packet, id_hash};
    /// use resol_vbus::utils::utc_timestamp;
    ///
    /// let packet = Packet {
    ///     header: Header {
    ///         timestamp: utc_timestamp(1485688933),
    ///         channel: 0x11,
    ///         destination_address: 0x1213,
    ///         source_address: 0x1415,
    ///         protocol_version: 0x16,
    ///     },
    ///     command: 0x1718,
    ///     frame_count: 0x19,
    ///     frame_data: [0u8; 508],
    /// };
    ///
    /// assert_eq!(2215810099849021132, id_hash(&packet));
    /// ```
    fn id_hash<H: Hasher>(&self, h: &mut H) {
        self.header.id_hash(h);
        self.command.hash(h);
    }
}

impl ToPacketId for Packet {
    fn to_packet_id(&self) -> Result<PacketId> {
        Ok(self.packet_id())
    }
}

impl fmt::Debug for Packet {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Packet")
            .field("header", &self.header)
            .field("command", &format_args!("0x{:04X}", self.command))
            .field("frame_count", &format_args!("0x{:02X}", self.frame_count))
            .field("frame_data", &format_args!("..."))
            .finish()
    }
}

impl Clone for Packet {
    fn clone(&self) -> Self {
        let mut frame_data = [0u8; 508];
        frame_data.copy_from_slice(&self.frame_data);

        Packet {
            header: self.header.clone(),
            command: self.command,
            frame_count: self.frame_count,
            frame_data,
        }
    }
}

impl AsRef<Header> for Packet {
    fn as_ref(&self) -> &Header {
        &self.header
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::{error::Error, utils::utc_timestamp};

    #[test]
    fn test_packet_id_string() {
        assert_eq!(
            "11_1213_1415_10_1718",
            PacketId(0x11, 0x1213, 0x1415, 0x1718).packet_id_string()
        );
    }

    #[test]
    fn test_packet_id_to_packet_id() {
        let packet_id = PacketId(0x11, 0x1213, 0x1415, 0x1718);

        let result = packet_id.to_packet_id().expect("Must not fail");

        assert_eq!(packet_id, result);
    }

    #[test]
    fn test_str_to_packet_id() {
        assert_eq!(
            PacketId(0x11, 0x1213, 0x1415, 0x1718),
            "11_1213_1415_10_1718".to_packet_id().unwrap()
        );
        assert_eq!(
            PacketId(0x11, 0x1213, 0x1415, 0x1718),
            "11_1213_1415_10_1718_XXX_X_X".to_packet_id().unwrap()
        );
        assert_eq!(
            Error::new("Invalid length of input \"11_1213_1415_10_171\""),
            "11_1213_1415_10_171".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid length of channel \"111\""),
            "111_1213_1415_10_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid characters in channel \"1G\""),
            "1G_1213_1415_10_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid length of destination address \"12131\""),
            "11_12131_1415_10_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid characters in destination address \"121G\""),
            "11_121G_1415_10_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid length of source address \"14151\""),
            "11_1213_14151_10_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid characters in source address \"141G\""),
            "11_1213_141G_10_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid length of protocol version \"101\""),
            "11_1213_1415_101_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid characters in protocol version \"1G\""),
            "11_1213_1415_1G_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Unsupported protocol version 0x20"),
            "11_1213_1415_20_1718".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid length of command \"17181\""),
            "11_1213_1415_10_17181".to_packet_id().unwrap_err()
        );
        assert_eq!(
            Error::new("Invalid characters in command \"171G\""),
            "11_1213_1415_10_171G".to_packet_id().unwrap_err()
        );
    }

    #[test]
    fn test_packet_field_id_packet_id_string() {
        let packet_field_id = PacketFieldId(PacketId(0x11, 0x1213, 0x1415, 0x1718), "019_2_0");

        let result = packet_field_id.packet_id_string();

        assert_eq!("11_1213_1415_10_1718", result);
    }

    #[test]
    fn test_packet_field_id_packet_field_id_string() {
        let packet_field_id = PacketFieldId(PacketId(0x11, 0x1213, 0x1415, 0x1718), "019_2_0");

        let result = packet_field_id.packet_field_id_string();

        assert_eq!("11_1213_1415_10_1718_019_2_0", result);
    }

    #[test]
    fn test_packet_field_id_to_packet_field_id() {
        let packet_field_id = PacketFieldId(PacketId(0x11, 0x1213, 0x1415, 0x1718), "019_2_0");

        let result = packet_field_id.to_packet_field_id().expect("Must not fail");

        assert_eq!(packet_field_id, result);
    }

    #[test]
    fn test_str_to_packet_field_id() {
        let packet_field_id_string = "11_1213_1415_10_1718_019_2_0";

        let result = packet_field_id_string
            .to_packet_field_id()
            .expect("Must not fail");

        assert_eq!(packet_field_id_string, result.packet_field_id_string());

        let result = "11_1213_1415_10_1718".to_packet_field_id().unwrap_err();

        assert_eq!(
            Error::new("Invalid length of input \"11_1213_1415_10_1718\""),
            result
        );
    }

    #[test]
    fn test_debug_fmt() {
        let packet = Packet {
            header: Header {
                timestamp: utc_timestamp(1485688933),
                channel: 0x11,
                destination_address: 0x1213,
                source_address: 0x1415,
                protocol_version: 0x16,
            },
            command: 0x1718,
            frame_count: 0x19,
            frame_data: [0u8; 508],
        };

        let result = format!("{:?}", packet);

        assert_eq!("Packet { header: Header { timestamp: 2017-01-29T11:22:13Z, channel: 0x11, destination_address: 0x1213, source_address: 0x1415, protocol_version: 0x16 }, command: 0x1718, frame_count: 0x19, frame_data: ... }", result);
    }
}