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
use std::io::{Read, Write};
use crate::{
    Endian, HasFixedCommandId, MessageExt, ReadExt, ReadFromPayload,
    Result, WithFixedPayloadLength, WriteExt,
};

#[derive(Clone, Debug, PartialEq)]
pub struct Notification {
    pub job_position: u16,
}

impl From<Notification> for super::Notification {
    fn from(m: Notification) -> Self {
        super::Notification::JobPositionAt(m)
    }
}

impl WithFixedPayloadLength for Notification {
    const FIXED_PAYLOAD_LENGTH: u16 = u16::FIXED_PAYLOAD_LENGTH;
}

impl HasFixedCommandId for Notification {
    const COMMAND_ID: u16 = 0x8801;
}

impl MessageExt for Notification {
    fn payload_length(&self) -> u16 {
        Self::FIXED_PAYLOAD_LENGTH
    }

    fn write_payload(&self, w: &mut Write) -> Result<()> {
        w.write_u16::<Endian>(self.job_position)?;
        Ok(())
    }
}

impl ReadFromPayload for Notification {
    fn read_from_payload<R: Read>(
        r: &mut R,
        payload_length: u16,
    ) -> Result<Self> {
        Self::verify_payload_length(
            payload_length,
            "job_position_at_notification",
        )?;
        let job_position = r.read_u16::<Endian>()?;
        Ok(Self { job_position })
    }
}

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

    #[test]
    fn write_to() {
        let mut buffer = Vec::new();
        let options: u8 = 0x45;
        let sequence: u8 = 0x93;

        let message = Notification {
            job_position: 0x1234,
        };
        message.write_to(&mut buffer, options, sequence).unwrap();
        assert_eq!(
            buffer,
            [
                0x45, // options
                0x93, // sequence
                0x01, // command lower byte
                0x88, // command upper byte
                0x02, // length lower byte
                0x00, // length upper byte
                0x34, // job_position lower byte
                0x12, // job_position upper byte
            ]
        );
    }
    #[test]
    fn read_from_payload() {
        let buffer = vec![0x34, 0x12];
        let len = buffer.len() as u16;
        let message =
            Notification::read_from_payload(&mut buffer.as_slice(), len)
                .unwrap();
        assert_eq!(
            message,
            Notification {
                job_position: 0x1234,
            }
        );
    }
}