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
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
//! AC capability extended message.
//!
//! See ยง4.b.i.

use std::collections::BTreeMap;

use bitflags::bitflags;

use super::extended::{extended_message, ExtendedMessage, ExtendedMessageSubtype};

const SUBTYPE_AC_CAP: ExtendedMessageSubtype = 0xff11;

pub type Setpoint = u8;

bitflags! {
    #[derive(Clone, Debug, PartialEq)]
    #[rustfmt::skip]
    pub struct AcModes: u8 {
        const Auto             = 1 << 0;
        const Heat             = 1 << 1;
        const Dry              = 1 << 2;
        const Fan              = 1 << 3;
        const Cool             = 1 << 4;
    }

    #[derive(Clone, Debug, PartialEq)]
    #[rustfmt::skip]
    pub struct FanSpeeds: u8 {
        const Auto             = 1 << 0;
        const Quiet            = 1 << 1;
        const Low              = 1 << 2;
        const Medium           = 1 << 3;
        const High             = 1 << 4;
        const Powerful         = 1 << 5;
        const Turbo            = 1 << 6;
        const IntelligentAuto  = 1 << 7;
    }
}

/// Describes the capabilities of a single AC unit.
#[derive(Clone, Debug, PartialEq)]
pub struct AcCapability {
    /// AC unit name, maximum 16 bytes.
    pub name: String,
    /// Starting zone index.
    pub zone_start_index: u8,
    /// Number of zones.
    pub zone_count: u8,
    /// Supported AC operating modes.
    pub supported_modes: AcModes,
    /// Supported fan speeds.
    pub supported_fan_speeds: FanSpeeds,
    /// The lowest possible cooling setpoint
    pub setpoint_cool_min: Setpoint,
    /// The highest possible cooling setpoint
    pub setpoint_cool_max: Setpoint,
    /// The lowest possible heating setpoint
    pub setpoint_heat_min: Setpoint,
    /// The highest possible heating setpoint
    pub setpoint_heat_max: Setpoint,
}

impl std::fmt::Display for AcCapability {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let w = std::cmp::max(f.width().unwrap_or(NAME_LEN_MAX), self.name.len());
        let s = " ".repeat(w + 2);
        if f.alternate() {
            write!(f,
                "{:>w$}: Zones: {} [{}\u{2013}{}]\n{s}Modes: {}\n{s}Fan: {}\n{s}Cooling: {}\u{2013}{}\n{s}Heating: {}\u{2013}{}",
                self.name,
                self.zone_count,
                self.zone_start_index,
                self.zone_count + self.zone_start_index - 1,
                self.supported_modes.iter_names().map(|(n, _)| n).collect::<Vec<&str>>().join(","),
                self.supported_fan_speeds.iter_names().map(|(n, _)| n).collect::<Vec<&str>>().join(","),
                self.setpoint_cool_min,
                self.setpoint_cool_max,
                self.setpoint_heat_min,
                self.setpoint_heat_max,
            )
        } else {
            write!(f,
                "{}: Zones: {} [{}\u{2013}{}]; Modes: {}; Fan: {}; Cooling: {}\u{2013}{}; Heating: {}\u{2013}{}",
                self.name,
                self.zone_count,
                self.zone_start_index,
                self.zone_count + self.zone_start_index - 1,
                self.supported_modes.iter_names().map(|(n, _)| n).collect::<Vec<&str>>().join(","),
                self.supported_fan_speeds.iter_names().map(|(n, _)| n).collect::<Vec<&str>>().join(","),
                self.setpoint_cool_min,
                self.setpoint_cool_max,
                self.setpoint_heat_min,
                self.setpoint_heat_max,
            )
        }
    }
}

/// The on-wire size of the AcCapability data
const AC_CAP_SIZE: usize = 24;
/// The maximum name length, in bytes.
const NAME_LEN_MAX: usize = 16;

extended_message!(SUBTYPE_AC_CAP,
pub struct AcCapabilityRequest {
    /// The index of the AC to retrieve the capabilities of, or `None` to
    /// retrieve the capabilities of all ACs.
    pub ac_index: Option<u8>,
}
pub struct AcCapabilityResponse {
    /// Map of zone index to zone name.
    pub acs: BTreeMap<u8, AcCapability>,
}
{
    fn impl_frame_data_len(&self) -> usize {
        if self.ac_index.is_none() { 0 } else { size_of::<u8>() }
    }

    fn impl_frame_data<W: std::io::Write>(&self, dst: &mut W) -> Result<(), super::MessageError> {
        if let Some(idx) = self.ac_index {
            dst.write_all(&idx.to_be_bytes())?;
        }
        Ok(())
    }

    fn from_frame_data(message_id: u8, data: Vec<u8>) -> Result<Self, super::MessageError> {
        match data[..] {
            [] => { Ok(Self { message_id, ac_index: None }) },
            [ac_index] => { Ok(Self { message_id, ac_index: Some(ac_index) }) },
            _ => Err(MessageError::InvalidData),
        }
    }
}
{
    fn impl_frame_data_len(&self) -> usize {
        (AC_CAP_SIZE + 2 * size_of::<u8>()) * self.acs.len()
    }

    fn impl_frame_data<W: std::io::Write>(&self, dst: &mut W) -> Result<(), super::MessageError> {
        for (idx, ac) in self.acs.iter() {
            // TODO: with a msrv of 1.91 we could more cleanly just do:
            // let name_len = ac.name.floor_char_boundary(NAME_LEN_MAX);
            let name_len = {
                let mut i = std::cmp::min(ac.name.len(), NAME_LEN_MAX);
                while !ac.name.is_char_boundary(i) {
                    i -= 1;
                }
                i
            };

            dst.write_all(&idx.to_be_bytes())?;
            dst.write_all(&(AC_CAP_SIZE as u8).to_be_bytes())?;
            dst.write_all(&ac.name.as_bytes()[..name_len])?;
            dst.write_all("\0".repeat(NAME_LEN_MAX - name_len).as_bytes())?;
            dst.write_all(&ac.zone_start_index.to_be_bytes())?;
            dst.write_all(&ac.zone_count.to_be_bytes())?;
            dst.write_all(&ac.supported_modes.bits().to_be_bytes())?;
            dst.write_all(&ac.supported_fan_speeds.bits().to_be_bytes())?;
            dst.write_all(&ac.setpoint_cool_min.to_be_bytes())?;
            dst.write_all(&ac.setpoint_cool_max.to_be_bytes())?;
            dst.write_all(&ac.setpoint_heat_min.to_be_bytes())?;
            dst.write_all(&ac.setpoint_heat_max.to_be_bytes())?;
        }
        Ok(())
    }

    fn from_frame_data(message_id: u8, data: Vec<u8>) -> Result<Self, super::MessageError> {
        let mut i: usize = 0;
        let mut acs = BTreeMap::new();
        while i < data.len() {
            if data.len() < i + AC_CAP_SIZE + 2 * size_of::<u8>()
                || (data[i+1] as usize) < AC_CAP_SIZE
            {
                return Err(MessageError::InvalidData);
            }
            let idx = data[i];
            let sz = data[i+1] as usize;
            let name_buf = &data[i+2..i+2+NAME_LEN_MAX];
            let name_len = name_buf.iter().position(|&c| c == b'\0').unwrap_or(NAME_LEN_MAX);
            let zone_start_index = data[i+18];
            let zone_count = data[i+19];
            let supported_modes = AcModes::from_bits_retain(data[i+20]);
            let supported_fan_speeds = FanSpeeds::from_bits_retain(data[i+21]);
            let setpoint_cool_min = data[i+22];
            let setpoint_cool_max = data[i+23];
            let setpoint_heat_min = data[i+24];
            let setpoint_heat_max = data[i+25];

            // Although the protocol reserves 16 bytes for the AC unit name, the console UI
            // appears to only allow entry of up to 12 bytes of utf-8 encoding (and doesn't
            // suffer from the [truncation problem](index.html#bugs-zone-name-encoding)
            // that zone names do). Nevertheless, guard against invalid utf-8.
            let name = String::from_utf8_lossy(&name_buf[..name_len]).to_string();

            acs.insert(idx, AcCapability {
                name,
                zone_start_index,
                zone_count,
                supported_modes,
                supported_fan_speeds,
                setpoint_cool_min,
                setpoint_cool_max,
                setpoint_heat_min,
                setpoint_heat_max,
             });
            i += sz + 2 * size_of::<u8>();
        }
        Ok(Self { message_id, acs })
    }
});

impl AcCapabilityRequest {
    /// Construct an `AcCapabilityRequest` for the given ac index, or `None` to
    /// request all ACs.
    pub fn new(ac_index: Option<u8>) -> Self {
        Self {
            message_id: super::next_msg_id(),
            ac_index,
        }
    }
}

impl AcCapabilityResponse {
    /// Construct a `AcCapabilityResponse` for the given AC data.
    ///
    /// `acs` is an iterator of `(ac_index, AcCapability)` pairs.
    pub fn new<K: Into<u8>, V: Into<AcCapability>, T: IntoIterator<Item = (K, V)>>(acs: T) -> Self {
        Self::with_message_id(super::next_msg_id(), acs)
    }

    /// Construct a `AcCapabilityResponse` for the given AC data, with the
    /// given `message_id`.
    ///
    /// `acs` is an iterator of `(ac_index, AcCapability)` pairs.
    pub fn with_message_id<K: Into<u8>, V: Into<AcCapability>, T: IntoIterator<Item = (K, V)>>(
        message_id: u8,
        acs: T,
    ) -> Self {
        Self {
            message_id,
            acs: acs.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
        }
    }

    /// Iterate the AC capabilities of this response in AC index order.
    pub fn by_index(&self) -> impl Iterator<Item = (u8, &AcCapability)> {
        self.acs.iter().map(|(k, v)| (*k, v))
    }

    /// Iterate the AC capabilities of this response in AC name order.
    pub fn by_name(&self) -> impl Iterator<Item = (u8, &AcCapability)> {
        let mut s: Vec<_> = self.acs.iter().map(|(k, v)| (*k, v)).collect();
        // TODO: this is lexical ordering, implement proper unicode-alphabetical ordering
        s.sort_by_key(|(_, a)| &a.name);
        Iter::new(&self.acs, s.iter().map(|(k, _)| *k).collect::<Vec<_>>())
    }
}

/// Iterator newtype for ordered iteration of AC capabilities (currently only
/// for `AcCapabilityResponse::by_name()`).
struct Iter<'a, I: IntoIterator<Item = u8>> {
    acs: &'a BTreeMap<u8, AcCapability>,
    order: <I as IntoIterator>::IntoIter,
}
impl<'a, I: IntoIterator<Item = u8>> Iter<'a, I> {
    fn new(acs: &'a BTreeMap<u8, AcCapability>, order: I) -> Self {
        Self {
            acs,
            order: order.into_iter(),
        }
    }
}
impl<'a, I: IntoIterator<Item = u8>> Iterator for Iter<'a, I> {
    type Item = (u8, &'a AcCapability);

    fn next(&mut self) -> Option<Self::Item> {
        self.order.next().and_then(|i| Some((i, self.acs.get(&i)?)))
    }
}

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

    use super::super::extended::ExtendedMessageSubtype;
    use crate::conn::tests::data::*;

    static ACS: std::sync::LazyLock<[(u8, AcCapability); 3]> = std::sync::LazyLock::new(|| {
        [
            (
                0,
                AcCapability {
                    name: "Upstairs".to_string(),
                    zone_start_index: 0,
                    zone_count: 3,
                    supported_modes: AcModes::all(),
                    supported_fan_speeds: FanSpeeds::Low | FanSpeeds::Medium | FanSpeeds::High,
                    setpoint_cool_min: 16,
                    setpoint_cool_max: 30,
                    setpoint_heat_min: 16,
                    setpoint_heat_max: 30,
                },
            ),
            (
                2,
                AcCapability {
                    name: "Downstairs".to_string(),
                    zone_start_index: 0,
                    zone_count: 4,
                    supported_modes: AcModes::all(),
                    supported_fan_speeds: FanSpeeds::all(),
                    setpoint_cool_min: 18,
                    setpoint_cool_max: 30,
                    setpoint_heat_min: 16,
                    setpoint_heat_max: 26,
                },
            ),
            (
                1,
                AcCapability {
                    name: "Basement".to_string(),
                    zone_start_index: 0,
                    zone_count: 1,
                    supported_modes: AcModes::Heat | AcModes::Cool,
                    supported_fan_speeds: FanSpeeds::Low | FanSpeeds::High,
                    setpoint_cool_min: 14,
                    setpoint_cool_max: 24,
                    setpoint_heat_min: 10,
                    setpoint_heat_max: 28,
                },
            ),
        ]
    });

    #[test]
    fn test_by_name() {
        let a = AcCapabilityResponse::new(ACS.clone());
        let mut i = a.by_name();
        assert_matches!(i.next(), Some((1, ac)) => { assert_eq!(ac.name, "Basement")});
        assert_matches!(i.next(), Some((2, ac)) => { assert_eq!(ac.name, "Downstairs")});
        assert_matches!(i.next(), Some((0, ac)) => { assert_eq!(ac.name, "Upstairs")});
        assert_matches!(i.next(), None);
    }

    #[test]
    fn test_ac_capability_request_all() {
        let orig = AcCapabilityRequest::new(None);
        let frame: Frame = orig.clone().try_into().expect("into frame failed");
        assert_eq!(
            frame.data.len(),
            size_of::<super::super::extended::ExtendedMessageSubtype>()
        );
        let req: AcCapabilityRequest = frame.try_into().expect("from frame failed");
        assert_eq!(req, orig);
    }

    #[test]
    fn test_ac_capability_request_one() {
        let orig = AcCapabilityRequest::new(Some(7));
        let frame: Frame = orig.clone().try_into().expect("into frame failed");
        assert_eq!(
            frame.data.len(),
            size_of::<ExtendedMessageSubtype>() + size_of::<u8>()
        );
        let req: AcCapabilityRequest = frame.try_into().expect("from frame failed");
        assert_eq!(req, orig);
        assert_eq!(req.ac_index, Some(7));
    }

    #[test]
    fn test_ac_capability_response_one() {
        let orig = AcCapabilityResponse::new([ACS[1].clone()]);
        let key = ACS[1].0;
        let frame: Frame = orig.clone().try_into().expect("into frame failed");
        assert_eq!(
            frame.data.len(),
            size_of::<ExtendedMessageSubtype>() + 2 * size_of::<u8>() + AC_CAP_SIZE
        );
        let resp: AcCapabilityResponse = frame.try_into().expect("from frame failed");
        assert_eq!(resp, orig);
        assert_eq!(resp.acs.len(), 1);
        assert_matches!(resp.acs.first_key_value(),
            Some((k, v)) => {
                assert_eq!(*k, key);
                assert_eq!(v.name, "Downstairs");
                assert_eq!(v.zone_count, 4);
            }
        );
    }

    #[test]
    fn test_ac_capability_response_all() {
        let orig = AcCapabilityResponse::new(ACS.clone());
        let frame: Frame = orig.clone().try_into().expect("into frame failed");
        assert_eq!(
            frame.data.len(),
            size_of::<ExtendedMessageSubtype>() + (2 * size_of::<u8>() + AC_CAP_SIZE) * ACS.len()
        );
        let resp: AcCapabilityResponse = frame.try_into().expect("from frame failed");
        assert_eq!(resp, orig);
        assert_eq!(resp.acs.len(), ACS.len());
        for (idx, ac) in &ACS[..] {
            assert_matches!(resp.acs.get(idx), Some(a) => {
                assert_eq!(a, ac);
            })
        }
    }

    #[test]
    fn test_ac_capability_req_from_data_one() {
        let req: AcCapabilityRequest = frame(MSG_REQ_AC_CAP_ONE)
            .try_into()
            .expect("from frame failed");
        assert_matches!(req.ac_index, Some(idx) => {
            assert_eq!(idx, 0);
        });
        let f: Frame = req.try_into().expect("into frame failed");
        assert_eq!(f, frame(MSG_REQ_AC_CAP_ONE));
    }

    #[test]
    fn test_ac_capability_req_from_data_all() {
        let req: AcCapabilityRequest = frame(MSG_REQ_AC_CAP_ALL)
            .try_into()
            .expect("from frame failed");
        assert_matches!(req.ac_index, None);
        let f: Frame = req.try_into().expect("into frame failed");
        assert_eq!(f, frame(MSG_REQ_AC_CAP_ALL));
    }

    #[test]
    fn test_ac_capability_resp_from_data() {
        let resp: AcCapabilityResponse = frame(&decode(MSG_RESP_AC_CAP))
            .try_into()
            .expect("from frame failed");
        let mut iter = resp.by_index();
        assert_matches!(iter.next(), Some((idx, ac)) => {
            assert_eq!(idx, 0);
            assert_eq!(ac.name, "UUUNIT 01 UUU");
            assert_eq!(ac.zone_count, 4);
            assert_eq!(ac.zone_start_index, 0);
            assert_eq!(ac.supported_modes,
                AcModes::Heat | AcModes::Cool | AcModes::Dry | AcModes::Auto);
            assert_eq!(ac.supported_fan_speeds,
                FanSpeeds::Low | FanSpeeds::Medium | FanSpeeds::High | FanSpeeds::Auto);
            assert_eq!((ac.setpoint_cool_min, ac.setpoint_cool_max), (16, 31));
            assert_eq!((ac.setpoint_heat_min, ac.setpoint_heat_max), (18, 31));
        });
        assert_matches!(iter.next(), None);
        drop(iter);
        let f: Frame = resp.try_into().expect("into frame failed");
        assert_eq!(f, frame(&decode(MSG_RESP_AC_CAP)));
    }
}