Skip to main content

bluetooth_mesh_stack/
access.rs

1//! The access layer (Mesh Protocol 3.7): opcodes and the messages of the
2//! foundation models (Configuration, sent with the device key) and of the
3//! Generic OnOff and Level models. Opcode names come from the SIG's
4//! assigned numbers ([`bluetooth_numbers::mesh_opcode`]).
5
6/// An opcode: 1 octet (`0x00`-`0x7e`), 2 octets (`0x8000`-`0xbfff`), or 3
7/// octets (`0xc0xxxx`, a vendor's, with its company identifier).
8pub type Opcode = u32;
9
10/// Splits an access payload into opcode and parameters.
11pub fn split(payload: &[u8]) -> Option<(Opcode, &[u8])> {
12    let (&b0, _) = payload.split_first()?;
13    match b0 {
14        0x7f => None, // reserved for future use
15        0x00..=0x7e => Some((u32::from(b0), &payload[1..])),
16        0x80..=0xbf => {
17            let b1 = *payload.get(1)?;
18            Some((u32::from_be_bytes([0, 0, b0, b1]), &payload[2..]))
19        }
20        _ => {
21            let r = payload.get(1..3)?;
22            Some((u32::from_be_bytes([0, b0, r[0], r[1]]), &payload[3..]))
23        }
24    }
25}
26
27/// An access payload: opcode then parameters.
28pub fn message(opcode: Opcode, params: &[u8]) -> Vec<u8> {
29    let mut v = match opcode {
30        0..=0x7e => vec![opcode as u8],
31        0x8000..=0xbfff => (opcode as u16).to_be_bytes().to_vec(),
32        _ => opcode.to_be_bytes()[1..].to_vec(),
33    };
34    v.extend_from_slice(params);
35    v
36}
37
38/// The opcode's name.
39pub fn name(opcode: Opcode) -> Option<&'static str> {
40    bluetooth_numbers::mesh_opcode(opcode)
41}
42
43/// Configuration and Generic opcodes the provisioner uses.
44pub mod op {
45    use super::Opcode;
46    /// Config AppKey Add.
47    pub const APPKEY_ADD: Opcode = 0x00;
48    /// Config AppKey Status.
49    pub const APPKEY_STATUS: Opcode = 0x8003;
50    /// Config Composition Data Get.
51    pub const COMPOSITION_GET: Opcode = 0x8008;
52    /// Config Composition Data Status.
53    pub const COMPOSITION_STATUS: Opcode = 0x02;
54    /// Config Default TTL Get.
55    pub const DEFAULT_TTL_GET: Opcode = 0x800c;
56    /// Config Default TTL Status.
57    pub const DEFAULT_TTL_STATUS: Opcode = 0x800e;
58    /// Config Model App Bind.
59    pub const MODEL_APP_BIND: Opcode = 0x803d;
60    /// Config Model App Status.
61    pub const MODEL_APP_STATUS: Opcode = 0x803e;
62    /// Config Model Publication Set.
63    pub const MODEL_PUB_SET: Opcode = 0x03;
64    /// Config Model Publication Status.
65    pub const MODEL_PUB_STATUS: Opcode = 0x8019;
66    /// Config Model Subscription Add.
67    pub const MODEL_SUB_ADD: Opcode = 0x801b;
68    /// Config Model Subscription Status.
69    pub const MODEL_SUB_STATUS: Opcode = 0x801f;
70    /// Config Node Reset.
71    pub const NODE_RESET: Opcode = 0x8049;
72    /// Config Node Reset Status.
73    pub const NODE_RESET_STATUS: Opcode = 0x804a;
74    /// Generic OnOff Get.
75    pub const ONOFF_GET: Opcode = 0x8201;
76    /// Generic OnOff Set.
77    pub const ONOFF_SET: Opcode = 0x8202;
78    /// Generic OnOff Set Unacknowledged.
79    pub const ONOFF_SET_UNACK: Opcode = 0x8203;
80    /// Generic OnOff Status.
81    pub const ONOFF_STATUS: Opcode = 0x8204;
82    /// Generic Level Get.
83    pub const LEVEL_GET: Opcode = 0x8205;
84    /// Generic Level Set.
85    pub const LEVEL_SET: Opcode = 0x8206;
86    /// Generic Level Set Unacknowledged.
87    pub const LEVEL_SET_UNACK: Opcode = 0x8207;
88    /// Generic Level Status.
89    pub const LEVEL_STATUS: Opcode = 0x8208;
90}
91
92/// Two 12-bit key indexes packed in three octets, little-endian.
93pub fn key_indexes(net: u16, app: u16) -> [u8; 3] {
94    let v = u32::from(net & 0xfff) | (u32::from(app & 0xfff) << 12);
95    [v as u8, (v >> 8) as u8, (v >> 16) as u8]
96}
97
98/// Config AppKey Add.
99pub fn appkey_add(net_index: u16, app_index: u16, app_key: &[u8; 16]) -> Vec<u8> {
100    let mut p = key_indexes(net_index, app_index).to_vec();
101    p.extend_from_slice(app_key);
102    message(op::APPKEY_ADD, &p)
103}
104
105/// A model: a SIG model (16 bits) or a vendor's (company, model).
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107pub enum ModelId {
108    /// A SIG model.
109    Sig(u16),
110    /// A vendor model: company identifier, model.
111    Vendor(u16, u16),
112}
113
114impl ModelId {
115    fn bytes(&self) -> Vec<u8> {
116        match self {
117            ModelId::Sig(m) => m.to_le_bytes().to_vec(),
118            ModelId::Vendor(c, m) => {
119                let mut v = c.to_le_bytes().to_vec();
120                v.extend_from_slice(&m.to_le_bytes());
121                v
122            }
123        }
124    }
125
126    /// The SIG's name for a SIG model.
127    pub fn name(&self) -> Option<&'static str> {
128        match self {
129            ModelId::Sig(m) => bluetooth_numbers::mesh_model(*m),
130            ModelId::Vendor(..) => None,
131        }
132    }
133}
134
135/// Config Model App Bind.
136pub fn model_app_bind(element: u16, app_index: u16, model: ModelId) -> Vec<u8> {
137    let mut p = element.to_le_bytes().to_vec();
138    p.extend_from_slice(&(app_index & 0xfff).to_le_bytes());
139    p.extend(model.bytes());
140    message(op::MODEL_APP_BIND, &p)
141}
142
143/// Config Model Subscription Add.
144pub fn model_sub_add(element: u16, group: u16, model: ModelId) -> Vec<u8> {
145    let mut p = element.to_le_bytes().to_vec();
146    p.extend_from_slice(&group.to_le_bytes());
147    p.extend(model.bytes());
148    message(op::MODEL_SUB_ADD, &p)
149}
150
151/// Config Model Publication Set: publish to `address` with `app_index`,
152/// TTL, period (raw byte), retransmit count and interval steps.
153pub fn model_pub_set(
154    element: u16,
155    address: u16,
156    app_index: u16,
157    ttl: u8,
158    period: u8,
159    model: ModelId,
160) -> Vec<u8> {
161    let mut p = element.to_le_bytes().to_vec();
162    p.extend_from_slice(&address.to_le_bytes());
163    p.extend_from_slice(&(app_index & 0xfff).to_le_bytes());
164    p.push(ttl);
165    p.push(period);
166    p.push(0); // no retransmissions
167    p.extend(model.bytes());
168    message(op::MODEL_PUB_SET, &p)
169}
170
171/// One element of a node.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct Element {
174    /// Location descriptor.
175    pub location: u16,
176    /// Its models.
177    pub models: Vec<ModelId>,
178}
179
180/// Composition Data page 0.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct Composition {
183    /// Company identifier.
184    pub cid: u16,
185    /// Product identifier.
186    pub pid: u16,
187    /// Version identifier.
188    pub vid: u16,
189    /// Replay protection list size.
190    pub crpl: u16,
191    /// Features: relay, proxy, friend, low power (bits 0-3).
192    pub features: u16,
193    /// Elements, the primary first.
194    pub elements: Vec<Element>,
195}
196
197impl Composition {
198    /// Parses a Config Composition Data Status's parameters (page then data).
199    pub fn parse(params: &[u8]) -> Option<Composition> {
200        let (&page, d) = params.split_first()?;
201        if page != 0 || d.len() < 10 {
202            return None;
203        }
204        let u = |i: usize| u16::from_le_bytes([d[i], d[i + 1]]);
205        let mut c = Composition {
206            cid: u(0),
207            pid: u(2),
208            vid: u(4),
209            crpl: u(6),
210            features: u(8),
211            elements: Vec::new(),
212        };
213        let mut r = &d[10..];
214        while !r.is_empty() {
215            if r.len() < 4 {
216                return None;
217            }
218            let (loc, ns, nv) = (
219                u16::from_le_bytes([r[0], r[1]]),
220                usize::from(r[2]),
221                usize::from(r[3]),
222            );
223            let need = 4 + 2 * ns + 4 * nv;
224            if r.len() < need {
225                return None;
226            }
227            let mut models = Vec::with_capacity(ns + nv);
228            for i in 0..ns {
229                models.push(ModelId::Sig(u16::from_le_bytes([
230                    r[4 + 2 * i],
231                    r[5 + 2 * i],
232                ])));
233            }
234            for i in 0..nv {
235                let o = 4 + 2 * ns + 4 * i;
236                models.push(ModelId::Vendor(
237                    u16::from_le_bytes([r[o], r[o + 1]]),
238                    u16::from_le_bytes([r[o + 2], r[o + 3]]),
239                ));
240            }
241            c.elements.push(Element {
242                location: loc,
243                models,
244            });
245            r = &r[need..];
246        }
247        Some(c)
248    }
249}
250
251/// Generic OnOff Set (or Set Unacknowledged): on or off, with a
252/// transaction identifier.
253pub fn onoff_set(on: bool, tid: u8, acknowledged: bool) -> Vec<u8> {
254    message(
255        if acknowledged {
256            op::ONOFF_SET
257        } else {
258            op::ONOFF_SET_UNACK
259        },
260        &[u8::from(on), tid],
261    )
262}
263
264/// Generic Level Set (or Set Unacknowledged).
265pub fn level_set(level: i16, tid: u8, acknowledged: bool) -> Vec<u8> {
266    let mut p = level.to_le_bytes().to_vec();
267    p.push(tid);
268    message(
269        if acknowledged {
270            op::LEVEL_SET
271        } else {
272            op::LEVEL_SET_UNACK
273        },
274        &p,
275    )
276}
277
278/// A Generic OnOff or Level Status: present (and target, when moving).
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum GenericStatus {
281    /// OnOff: present, target.
282    OnOff(bool, Option<bool>),
283    /// Level: present, target.
284    Level(i16, Option<i16>),
285}
286
287/// Parses a Generic OnOff or Level Status.
288pub fn generic_status(opcode: Opcode, p: &[u8]) -> Option<GenericStatus> {
289    match (opcode, p.len()) {
290        (op::ONOFF_STATUS, 1) => Some(GenericStatus::OnOff(p[0] == 1, None)),
291        (op::ONOFF_STATUS, 3) => Some(GenericStatus::OnOff(p[0] == 1, Some(p[1] == 1))),
292        (op::LEVEL_STATUS, 2) => Some(GenericStatus::Level(i16::from_le_bytes([p[0], p[1]]), None)),
293        (op::LEVEL_STATUS, 5) => Some(GenericStatus::Level(
294            i16::from_le_bytes([p[0], p[1]]),
295            Some(i16::from_le_bytes([p[2], p[3]])),
296        )),
297        _ => None,
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn opcodes_round_trip_and_name() {
307        for opc in [0x00u32, 0x02, 0x8201, 0x804a, 0xc0_5901] {
308            let m = message(opc, &[9]);
309            assert_eq!(split(&m), Some((opc, &[9u8][..])));
310        }
311        assert_eq!(split(&[0x7f]), None);
312        assert_eq!(split(&[0x82]), None);
313        assert_eq!(name(op::ONOFF_SET), Some("Generic OnOff Set"));
314        assert_eq!(name(op::APPKEY_ADD), Some("Config AppKey Add"));
315        assert_eq!(ModelId::Sig(0x1000).name(), Some("Generic OnOff Server"));
316    }
317
318    #[test]
319    fn config_messages() {
320        assert_eq!(key_indexes(0x123, 0x456), [0x23, 0x61, 0x45]);
321        let m = appkey_add(0, 1, &[0xaa; 16]);
322        assert_eq!(&m[..4], &[0x00, 0x00, 0x10, 0x00]);
323        assert_eq!(m.len(), 20);
324        assert_eq!(
325            model_app_bind(0x0b0c, 1, ModelId::Sig(0x1000)),
326            vec![0x80, 0x3d, 0x0c, 0x0b, 0x01, 0x00, 0x00, 0x10]
327        );
328    }
329
330    #[test]
331    fn composition_data() {
332        // CID 0x0059, PID 1, VID 2, CRPL 0x10, features relay+proxy; one
333        // element at location 0x0100 with Config Server, Health Server,
334        // Generic OnOff Server and one vendor model.
335        let p = hex::decode(
336            "00 5900 0100 0200 1000 0300 0001 03 01 0000 0200 0010 5900 2a00".replace(' ', ""),
337        )
338        .unwrap();
339        let c = Composition::parse(&p).unwrap();
340        assert_eq!((c.cid, c.features), (0x0059, 3));
341        assert_eq!(
342            c.elements[0].models,
343            vec![
344                ModelId::Sig(0),
345                ModelId::Sig(2),
346                ModelId::Sig(0x1000),
347                ModelId::Vendor(0x59, 0x2a)
348            ]
349        );
350        assert!(Composition::parse(&p[..p.len() - 1]).is_none());
351    }
352
353    #[test]
354    fn generic_messages() {
355        assert_eq!(onoff_set(true, 7, true), vec![0x82, 0x02, 1, 7]);
356        assert_eq!(
357            generic_status(op::ONOFF_STATUS, &[1, 0, 5]),
358            Some(GenericStatus::OnOff(true, Some(false)))
359        );
360        assert_eq!(
361            generic_status(op::LEVEL_STATUS, &[0xff, 0x7f]),
362            Some(GenericStatus::Level(i16::MAX, None))
363        );
364        assert_eq!(generic_status(op::LEVEL_STATUS, &[1]), None);
365    }
366}