Skip to main content

bacnet_encoding/constructed/
action_list.rs

1//! `BACnetActionList` and `BACnetActionCommand` (ASHRAE 135-2020 Clause 21),
2//! the element of a Command object's Action array (Clause 12.10.8).
3//!
4//! An action list frames its commands in an opening/closing context tag `[0]`
5//! pair and puts them back to back inside it. A command is nine context-tagged
6//! members numbered in order: device `[0]` (optional), object `[1]`, property
7//! `[2]`, array index `[3]` (optional), the value framed in `[4]`, priority
8//! `[5]` and post delay `[6]` (both optional), then the quit-on-failure `[7]`
9//! and write-successful `[8]` BOOLEANs. An Action array read whole
10//! concatenates its lists with no further frame.
11
12#[cfg(not(feature = "std"))]
13use alloc::vec::Vec;
14
15use bacnet_types::constructed::{BACnetActionCommand, BACnetActionList};
16use bacnet_types::enums::PropertyIdentifier;
17use bacnet_types::error::{DecodeError, DecodingKind, Error, RangeError};
18use bytes::BytesMut;
19
20use super::tagged::{
21    decode_ctx_boolean, decode_ctx_object_id, decode_ctx_unsigned, decode_framed_value,
22    decode_optional_ctx, expect_opening,
23};
24use super::MAX_FRAMED_ITEMS;
25use crate::{primitives, tags};
26
27const WHAT: &str = "BACnetActionCommand";
28
29/// Encode one bare `BACnetActionCommand`, appending to `buf`.
30///
31/// Fails, leaving `buf` as it was, when the priority is outside 1..=16 or the
32/// value can't be encoded (see [`primitives::encode_property_value`]).
33pub fn encode_action_command(
34    buf: &mut BytesMut,
35    command: &BACnetActionCommand,
36) -> Result<(), Error> {
37    if let Some(priority) = command.priority
38        && !(1..=16).contains(&priority) {
39            return Err(
40                RangeError::new("BACnetActionCommand: priority {} is outside 1..=16")
41                    .with_value(priority.into())
42                    .into(),
43            );
44        }
45    let start = buf.len();
46    if let Some(device) = &command.device_identifier {
47        primitives::encode_ctx_object_id(buf, 0, device);
48    }
49    primitives::encode_ctx_object_id(buf, 1, &command.object_identifier);
50    primitives::encode_ctx_enumerated(buf, 2, command.property_identifier.to_raw());
51    if let Some(index) = command.property_array_index {
52        primitives::encode_ctx_unsigned(buf, 3, u64::from(index));
53    }
54    tags::encode_opening_tag(buf, 4);
55    if let Err(error) = primitives::encode_property_value(buf, &command.property_value) {
56        buf.truncate(start);
57        return Err(error);
58    }
59    tags::encode_closing_tag(buf, 4);
60    if let Some(priority) = command.priority {
61        primitives::encode_ctx_unsigned(buf, 5, u64::from(priority));
62    }
63    if let Some(delay) = command.post_delay {
64        primitives::encode_ctx_unsigned(buf, 6, u64::from(delay));
65    }
66    primitives::encode_ctx_boolean(buf, 7, command.quit_on_failure);
67    primitives::encode_ctx_boolean(buf, 8, command.write_successful);
68    Ok(())
69}
70
71/// Decode one bare `BACnetActionCommand` at `offset`; returns it and the
72/// offset past its write-successful flag.
73///
74/// The value inside `[4]` decodes as one application value when it holds one
75/// element and as a [`PropertyValue::List`] otherwise (empty included). A
76/// context-tagged element in it decodes to [`PropertyValue::ApplicationData`],
77/// so the value re-encodes to the same octets.
78///
79/// [`PropertyValue::List`]: bacnet_types::primitives::PropertyValue::List
80/// [`PropertyValue::ApplicationData`]: bacnet_types::primitives::PropertyValue::ApplicationData
81pub fn decode_action_command(
82    data: &[u8],
83    offset: usize,
84) -> Result<(BACnetActionCommand, usize), Error> {
85    let (device_identifier, offset) =
86        decode_optional_ctx(data, offset, 0, WHAT, decode_ctx_object_id)?;
87    let (object_identifier, offset) = decode_ctx_object_id(data, offset, 1, WHAT)?;
88    let (property, offset) = decode_ctx_unsigned::<u32>(data, offset, 2, WHAT)?;
89    let property_identifier = PropertyIdentifier::from_raw(property);
90    let (property_array_index, offset) =
91        decode_optional_ctx(data, offset, 3, WHAT, decode_ctx_unsigned::<u32>)?;
92
93    let content = expect_opening(data, offset, 4, WHAT)?;
94    let (property_value, offset) = decode_framed_value(data, content, 4, WHAT)?;
95
96    let (priority, next) = decode_optional_ctx(data, offset, 5, WHAT, decode_ctx_unsigned::<u32>)?;
97    let priority = priority
98        .map(|value| {
99            u8::try_from(value)
100                .ok()
101                .filter(|p| (1..=16).contains(p))
102                .ok_or_else(|| {
103                    DecodeError::new(
104                        DecodingKind::InvalidEncoding,
105                        offset,
106                        "priority {} is outside 1..=16",
107                    )
108                    .within(WHAT)
109                    .with_value(value.into())
110                })
111        })
112        .transpose()?;
113    let (post_delay, offset) =
114        decode_optional_ctx(data, next, 6, WHAT, decode_ctx_unsigned::<u32>)?;
115    let (quit_on_failure, offset) = decode_ctx_boolean(data, offset, 7, WHAT)?;
116    let (write_successful, offset) = decode_ctx_boolean(data, offset, 8, WHAT)?;
117    Ok((
118        BACnetActionCommand {
119            device_identifier,
120            object_identifier,
121            property_identifier,
122            property_array_index,
123            property_value,
124            priority,
125            post_delay,
126            quit_on_failure,
127            write_successful,
128        },
129        offset,
130    ))
131}
132
133/// Encode one `BACnetActionList`, its `[0]` frame included, appending to
134/// `buf`. Fails, leaving `buf` as it was, when a command fails to encode.
135pub fn encode_action_list(buf: &mut BytesMut, list: &BACnetActionList) -> Result<(), Error> {
136    let start = buf.len();
137    tags::encode_opening_tag(buf, 0);
138    for command in &list.commands {
139        if let Err(error) = encode_action_command(buf, command) {
140            buf.truncate(start);
141            return Err(error);
142        }
143    }
144    tags::encode_closing_tag(buf, 0);
145    Ok(())
146}
147
148/// Decode one `BACnetActionList` at `offset`; returns it and the offset past
149/// its closing `[0]` tag, so an Action array is walked by calling this at
150/// each element's start.
151pub fn decode_action_list(data: &[u8], offset: usize) -> Result<(BACnetActionList, usize), Error> {
152    let content = expect_opening(data, offset, 0, "BACnetActionList")?;
153    let (inner, end) = tags::extract_context_value(data, content, 0)?;
154    let body = &data[..content + inner.len()];
155    let mut commands = Vec::new();
156    let mut offset = content;
157    while offset < body.len() {
158        if commands.len() >= MAX_FRAMED_ITEMS {
159            return Err(Error::overflow(
160                offset,
161                "BACnetActionList: commands exceed item limit",
162            ));
163        }
164        let (command, next) = decode_action_command(body, offset)?;
165        commands.push(command);
166        offset = next;
167    }
168    Ok((BACnetActionList { commands }, end))
169}