airtouch5 0.2.0

A library for communicating with AirTouch 5 air conditioning system control consoles
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
//! Transport framing protocol for AirTouch5

use std::io::Result;

use crc16::{State as Crc16, MODBUS};
use tokio_util::{
    bytes::Buf,
    codec::{Decoder, Encoder},
};

use super::MessageKind;

/// A framed message to or from the AirTouch5
///
/// This is a general transport frame, see [`message`][crate::message] for
/// encoding and decoding specific message types.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Frame {
    /// The addressee of the message.
    pub address: u16,
    /// The message identifier. May be any value for requests, and the
    /// corresponding response will have the same value.
    pub msg_id: u8,
    /// The type of the message.
    pub msg_type: u8,
    /// The kind of message, based on the message type and address
    pub kind: MessageKind,
    /// Message data bytes.
    pub data: Vec<u8>,
}

/// A frame or recoverable error.
///
/// A recoverable error might be, for example, a checksum failure, which
/// prevents the frame from being decoded but does not desynchronize the
/// connection, so future frames can still be read.
#[derive(Clone, Debug)]
pub(crate) enum MaybeFrame {
    /// A valid frame.
    Frame(Frame),
    /// Checksum failure. The first value is the calculated checksum, and
    /// the second is the checksum from the frame footer.
    CrcError(u16, u16),
}

/// Encodes and decodes frames to and from I/O streams.
#[derive(Clone, Copy)]
pub(crate) struct FrameCodec {}

impl FrameCodec {
    /// Length of the full header. The full header includes the magic number,
    /// address, message ID, message type, and data length. See section §3.a
    /// through §3.e; note that the specification refers to the magic number
    /// as the "header", but we include al the above fields in our "full
    /// header".
    const LEN_HEADER: usize = 10;
    /// Length of the frame footer. The frame footer contains the checksum.
    /// See section §3.g.
    const LEN_FOOTER: usize = 2;
    /// Combined length of the full header and footer. The length of the
    /// entire frame is this value plus the data length from the header.
    const LEN_FRAME_MIN: usize = Self::LEN_HEADER + Self::LEN_FOOTER;

    /// The magic number value identifying the start of a frame. See section
    /// §3.a.
    const HEADER_MAGIC: u32 = 0x5555_55aa;

    /// Construct a `FrameCodec`
    pub(crate) fn new() -> Self {
        Self {}
    }
}

/// Utility macro to decode a big-endian integer from the frame header or
/// footer.
///
/// # Examples
///
/// ```ignore
/// let buf = &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xff];
/// let mut p = 0;
/// assert_eq!(get_!(u32, buf, p), 0x01020304);
/// assert_eq!(p, 4);
/// assert_eq!(get_!(u8, buf, p), 0x05);
/// assert_eq!(get_!(u16, buf, p), 0x0607);
/// assert_eq!(get_!(i8, buf, p), -1);
/// assert_eq!(p, 8);
/// ```
macro_rules! get_ {
    ( $t:ty, $src:expr, $off:ident ) => {{
        let len_ = std::mem::size_of::<$t>();
        let res_ = <$t>::from_be_bytes(($src)[$off..$off + len_].try_into().unwrap());
        $off += len_;
        res_
    }};
}

/// Utility macro to decode a big-endian integer from the frame header or
/// footer, without consuming it.
///
/// # Examples
///
/// ```ignore
/// let buf = &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xff];
/// let mut p = 0;
/// assert_eq!(peek_!(u32, buf, p), 0x01020304);
/// assert_eq!(p, 0);
/// assert_eq!(peek_!(u8, buf, p), 0x01);
/// assert_eq!(peek_!(u16, buf, p), 0x0102);
/// p = 7;
/// assert_eq!(peek_!(i8, buf, p), -1);
/// assert_eq!(p, 7);
/// ```
macro_rules! peek_ {
    ( $t:ty, $src:expr, $off:ident ) => {{
        let len_ = std::mem::size_of::<$t>();
        let res_ = <$t>::from_be_bytes(($src)[$off..$off + len_].try_into().unwrap());
        res_
    }};
}

/// Utility macro to encode a big-endian integer into the frame header or
/// footer, optionally checksumming it.
///
/// # Examples
///
/// ```ignore
/// let mut buf: Vec<u8> = vec![];
/// buf.reserve(12);
/// put_!(u32, 0x1234abcd, buf);
/// let mut crc = Crc16::<MODBUS>::new();
/// put_!(u32, 0x4321fedc, buf, crc);
/// put_!(u16, 0xacab, buf, crc);
/// put_!(u8, 19, buf, crc);
/// put_!(i8, -18, buf, crc);
/// let expected = &[0x12, 0x34, 0xab, 0xcd, 0x43, 0x21, 0xfe, 0xdc, 0xac, 0xab, 0x13, 0xee];
/// assert_eq!(&buf[..], expected);
/// assert_eq!(crc.get(), Crc16::<MODBUS>::calculate(&expected[4..]));
/// ```
macro_rules! put_ {
    ( $t:ty, $val:expr, $dst:expr ) => {{
        let slc_ = <$t>::to_be_bytes(($val) as $t);
        ($dst).extend_from_slice(&slc_);
    }};
    ( $t:ty, $val:expr, $dst:expr, $crc:ident ) => {{
        let slc_ = <$t>::to_be_bytes(($val) as $t);
        ($dst).extend_from_slice(&slc_);
        ($crc).update(&slc_);
    }};
}

impl Decoder for FrameCodec {
    type Item = MaybeFrame;
    type Error = std::io::Error;

    fn decode(&mut self, src: &mut tokio_util::bytes::BytesMut) -> Result<Option<Self::Item>> {
        let mut p = 0;

        // look for the magic number
        // in practice, the console sends data other than the documented
        // frames, so skip anything unrecognized.
        loop {
            if src.len() < p + std::mem::size_of_val(&Self::HEADER_MAGIC) {
                src.reserve(Self::LEN_HEADER - src.len());
                return Ok(None);
            }
            if peek_!(u32, src, p) == Self::HEADER_MAGIC {
                src.advance(p);
                p = std::mem::size_of_val(&Self::HEADER_MAGIC);
                break;
            }
            p += 1;
        }

        // check for enough data to contain the full header
        if src.len() < Self::LEN_HEADER {
            src.reserve(Self::LEN_HEADER - src.len());
            return Ok(None);
        }
        let address = get_!(u16, src, p);
        let msg_id = get_!(u8, src, p);
        let msg_type = get_!(u8, src, p);
        let data_len = get_!(u16, src, p) as usize;

        // now we know the length, check if we have a full frame
        let expected_bytes = data_len + Self::LEN_FRAME_MIN;
        if src.len() < expected_bytes {
            src.reserve(expected_bytes - src.len());
            return Ok(None);
        }

        // have a full frame, consume it from the source
        let data = src.split_to(expected_bytes);

        // and checksum it
        let crc_calculated = Crc16::<MODBUS>::calculate(
            // magic isn't included in checksum
            &data[std::mem::size_of_val(&Self::HEADER_MAGIC)..Self::LEN_HEADER + data_len],
        );
        p += data_len;
        let crc_expected = get_!(u16, data, p);
        assert_eq!(p, expected_bytes);
        if crc_calculated != crc_expected {
            return Ok(Some(MaybeFrame::CrcError(crc_calculated, crc_expected)));
        }

        Ok(Some(MaybeFrame::Frame(Frame {
            address,
            msg_id,
            msg_type,
            kind: (msg_type, address).into(),
            data: data[Self::LEN_HEADER..data.len() - Self::LEN_FOOTER].to_vec(),
        })))
    }
}

impl Encoder<Frame> for FrameCodec {
    type Error = std::io::Error;

    fn encode(&mut self, frame: Frame, dst: &mut tokio_util::bytes::BytesMut) -> Result<()> {
        if frame.data.len() > u16::MAX as usize {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "data too large",
            ));
        }
        if frame.kind == MessageKind::Unknown || !frame.kind.is_valid(frame.msg_type, frame.address)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "invalid message type",
            ));
        }

        // reserve space
        let data = &frame.data[..];
        dst.reserve(Self::LEN_FRAME_MIN + data.len());

        // write magic number
        // this will need special handling in the caller / output stream, as
        // it must bypass the anti-header encoding logic
        put_!(u32, Self::HEADER_MAGIC, dst);

        // start checksumming and write rest of header
        let mut crc = Crc16::<MODBUS>::new();
        put_!(u16, frame.address, dst, crc);
        put_!(u8, frame.msg_id, dst, crc);
        put_!(u8, frame.msg_type, dst, crc);
        put_!(u16, data.len(), dst, crc);

        // write data
        dst.extend_from_slice(data);
        crc.update(data);

        // write footer
        put_!(u16, crc.get(), dst);

        Ok(())
    }
}

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

    #[test]
    fn test_get_macro() {
        let buf = &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xff];
        let mut p = 0;
        assert_eq!(get_!(u32, buf, p), 0x01020304);
        assert_eq!(p, 4);
        assert_eq!(get_!(u8, buf, p), 0x05);
        assert_eq!(get_!(u16, buf, p), 0x0607);
        assert_eq!(get_!(i8, buf, p), -1);
        assert_eq!(p, 8);
    }

    #[test]
    fn test_peek_macro() {
        let buf = &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xff];
        let mut p = 0;
        assert_eq!(peek_!(u32, buf, p), 0x01020304);
        assert_eq!(p, 0);
        assert_eq!(peek_!(u8, buf, p), 0x01);
        assert_eq!(peek_!(u16, buf, p), 0x0102);
        p = 7;
        assert_eq!(peek_!(i8, buf, p), -1);
        assert_eq!(p, 7);
    }

    #[test]
    fn test_put_macro() {
        let mut buf = Vec::with_capacity(12);
        put_!(u32, 0x1234abcd, buf);
        let mut crc = Crc16::<MODBUS>::new();
        put_!(u32, 0x4321fedc, buf, crc);
        put_!(u16, 0xacab, buf, crc);
        put_!(u8, 19, buf, crc);
        put_!(i8, -18, buf, crc);
        let expected = &[
            0x12, 0x34, 0xab, 0xcd, 0x43, 0x21, 0xfe, 0xdc, 0xac, 0xab, 0x13, 0xee,
        ];
        assert_eq!(&buf[..], expected);
        assert_eq!(crc.get(), Crc16::<MODBUS>::calculate(&expected[4..]));
    }

    #[test]
    fn test_decode_request() {
        let mut src = tokio_util::bytes::BytesMut::new();
        let mut codec = FrameCodec::new();
        assert_matches!(codec.decode(&mut src), Ok(None));
        src.extend_from_slice(&MSG_REQ_STATUS_ZONES[..FrameCodec::LEN_HEADER]);
        assert_matches!(codec.decode(&mut src), Ok(None));
        assert!(src.capacity() >= MSG_REQ_STATUS_ZONES.len());
        src.extend_from_slice(&MSG_REQ_STATUS_ZONES[FrameCodec::LEN_HEADER..]);
        assert_matches!(codec.decode(&mut src), Ok(Some(MaybeFrame::Frame(frame))) => {
            assert_eq!(frame.kind, MessageKind::ControlRequest);
            assert_eq!(frame.msg_id, 1);
            assert_eq!(frame.data.len(), 8);
        });
    }

    #[test]
    fn test_decode_request_badcrc() {
        let mut src = tokio_util::bytes::BytesMut::new();
        let mut codec = FrameCodec::new();
        src.extend_from_slice(
            &MSG_REQ_STATUS_ZONES[..MSG_REQ_STATUS_ZONES.len() - FrameCodec::LEN_FOOTER],
        );
        src.extend_from_slice(&[0xac, 0xab]);
        assert_matches!(codec.decode(&mut src), Ok(Some(MaybeFrame::CrcError(calculated, expected))) => {
            assert_eq!(expected, 0xacab);
            assert_eq!(calculated, u16::from_be_bytes(MSG_REQ_STATUS_ZONES[MSG_REQ_STATUS_ZONES.len()-FrameCodec::LEN_FOOTER..].try_into().unwrap()));
        });
    }

    #[test]
    fn test_decode_multiple() {
        let mut src = tokio_util::bytes::BytesMut::new();
        let mut codec = FrameCodec::new();
        src.extend_from_slice(MSG_REQ_STATUS_ZONES);
        src.extend_from_slice(&decode(MSG_RESP_AC_CAP));
        src.extend_from_slice(MSG_REQ_STATUS_ZONES);
        assert_matches!(codec.decode(&mut src), Ok(Some(MaybeFrame::Frame(frame))) => {
            assert_eq!(frame.kind, MessageKind::ControlRequest);
            assert_eq!(frame.msg_id, 1);
            assert_eq!(frame.data.len(), 8);
        });
        assert_matches!(codec.decode(&mut src), Ok(Some(MaybeFrame::Frame(frame))) => {
            assert_eq!(frame.kind, MessageKind::ExtendedResponse);
            assert_eq!(frame.msg_id, 1);
            assert_eq!(frame.data.len(), 28);
        });
        assert_matches!(codec.decode(&mut src), Ok(Some(MaybeFrame::Frame(frame))) => {
            assert_eq!(frame.kind, MessageKind::ControlRequest);
            assert_eq!(frame.msg_id, 1);
            assert_eq!(frame.data.len(), 8);
        });
    }

    #[test]
    fn test_decode_junk() {
        let mut src = tokio_util::bytes::BytesMut::new();
        let mut codec = FrameCodec::new();
        let junk: &[u8] = &[0x55, 0x55, 0x55, 0xab, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x4c];
        src.extend_from_slice(junk);
        src.extend_from_slice(MSG_REQ_STATUS_ZONES);
        src.extend_from_slice(junk);
        src.extend_from_slice(&decode(MSG_RESP_AC_CAP));
        assert_matches!(codec.decode(&mut src), Ok(Some(MaybeFrame::Frame(frame))) => {
            assert_eq!(frame.kind, MessageKind::ControlRequest);
            assert_eq!(frame.msg_id, 1);
            assert_eq!(frame.data.len(), 8);
        });
        assert_matches!(codec.decode(&mut src), Ok(Some(MaybeFrame::Frame(frame))) => {
            assert_eq!(frame.kind, MessageKind::ExtendedResponse);
            assert_eq!(frame.msg_id, 1);
            assert_eq!(frame.data.len(), 28);
        });
    }

    #[test]
    fn test_encode_request() {
        let address: u16 = 0x80b0;
        let msg_type: u8 = 0xc0;
        let frame = Frame {
            address,
            msg_id: 1,
            msg_type,
            kind: (msg_type, address).into(),
            data: MSG_REQ_STATUS_ZONES
                [FrameCodec::LEN_HEADER..MSG_REQ_STATUS_ZONES.len() - FrameCodec::LEN_FOOTER]
                .to_vec(),
        };
        let mut dst = tokio_util::bytes::BytesMut::new();
        let mut codec = FrameCodec::new();
        assert_matches!(codec.encode(frame, &mut dst), Ok(()) => {
            assert_eq!(dst.len(), MSG_REQ_STATUS_ZONES.len());
            assert_eq!(&dst[..], MSG_REQ_STATUS_ZONES);
        });
    }

    #[test]
    fn test_encode_request_eio() {
        let address: u16 = 0x80b0;
        let msg_type: u8 = 0x1f;
        let frame = Frame {
            address,
            msg_id: 1,
            msg_type,
            kind: (msg_type, address).into(),
            data: MSG_REQ_STATUS_ZONES
                [FrameCodec::LEN_HEADER..MSG_REQ_STATUS_ZONES.len() - FrameCodec::LEN_FOOTER]
                .to_vec(),
        };
        let mut dst = tokio_util::bytes::BytesMut::new();
        let mut codec = FrameCodec::new();
        assert_matches!(codec.encode(frame, &mut dst), Err(eio) => {
            assert_eq!(eio.kind(), std::io::ErrorKind::InvalidData);
            assert_eq!(eio.to_string(), "invalid message type");
        });
    }
}