garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /bt/src/att.rs

raw

//! ATT: the attribute protocol's PDUs, parsed and built, and a server that
//! answers them from a [`Table`](crate::gatt::Table).

use crate::gatt::{Table, Uuid};
use alloc::vec::Vec;

pub const ERROR_RESPONSE: u8 = 0x01;
pub const EXCHANGE_MTU_REQUEST: u8 = 0x02;
pub const EXCHANGE_MTU_RESPONSE: u8 = 0x03;
pub const FIND_INFORMATION_REQUEST: u8 = 0x04;
pub const FIND_INFORMATION_RESPONSE: u8 = 0x05;
pub const READ_BY_TYPE_REQUEST: u8 = 0x08;
pub const READ_BY_TYPE_RESPONSE: u8 = 0x09;
pub const READ_REQUEST: u8 = 0x0a;
pub const READ_RESPONSE: u8 = 0x0b;
pub const READ_BY_GROUP_TYPE_REQUEST: u8 = 0x10;
pub const READ_BY_GROUP_TYPE_RESPONSE: u8 = 0x11;
pub const WRITE_REQUEST: u8 = 0x12;
pub const WRITE_RESPONSE: u8 = 0x13;
pub const WRITE_COMMAND: u8 = 0x52;
pub const HANDLE_VALUE_NOTIFICATION: u8 = 0x1b;

pub const ERR_INVALID_HANDLE: u8 = 0x01;
pub const ERR_READ_NOT_PERMITTED: u8 = 0x02;
pub const ERR_WRITE_NOT_PERMITTED: u8 = 0x03;
pub const ERR_REQUEST_NOT_SUPPORTED: u8 = 0x06;
pub const ERR_ATTRIBUTE_NOT_FOUND: u8 = 0x0a;

/// The default MTU, and what Pinnacle asks for (a contact card in one read).
pub const DEFAULT_MTU: usize = 23;
pub const WANTED_MTU: usize = 247;

fn u16_at(b: &[u8], at: usize) -> Option<u16> {
    Some(u16::from_le_bytes([*b.get(at)?, *b.get(at + 1)?]))
}

pub fn error(request: u8, handle: u16, code: u8) -> Vec<u8> {
    let mut out = alloc::vec![ERROR_RESPONSE, request];
    out.extend_from_slice(&handle.to_le_bytes());
    out.push(code);
    out
}

pub fn exchange_mtu_request(mtu: u16) -> Vec<u8> {
    let mut out = alloc::vec![EXCHANGE_MTU_REQUEST];
    out.extend_from_slice(&mtu.to_le_bytes());
    out
}

pub fn read_by_group_type_request(start: u16, end: u16, group: u16) -> Vec<u8> {
    let mut out = alloc::vec![READ_BY_GROUP_TYPE_REQUEST];
    out.extend_from_slice(&start.to_le_bytes());
    out.extend_from_slice(&end.to_le_bytes());
    out.extend_from_slice(&group.to_le_bytes());
    out
}

pub fn read_by_type_request(start: u16, end: u16, kind: u16) -> Vec<u8> {
    let mut out = alloc::vec![READ_BY_TYPE_REQUEST];
    out.extend_from_slice(&start.to_le_bytes());
    out.extend_from_slice(&end.to_le_bytes());
    out.extend_from_slice(&kind.to_le_bytes());
    out
}

pub fn find_information_request(start: u16, end: u16) -> Vec<u8> {
    let mut out = alloc::vec![FIND_INFORMATION_REQUEST];
    out.extend_from_slice(&start.to_le_bytes());
    out.extend_from_slice(&end.to_le_bytes());
    out
}

pub fn read_request(handle: u16) -> Vec<u8> {
    let mut out = alloc::vec![READ_REQUEST];
    out.extend_from_slice(&handle.to_le_bytes());
    out
}

pub fn write_request(handle: u16, value: &[u8]) -> Vec<u8> {
    let mut out = alloc::vec![WRITE_REQUEST];
    out.extend_from_slice(&handle.to_le_bytes());
    out.extend_from_slice(value);
    out
}

pub fn write_command(handle: u16, value: &[u8]) -> Vec<u8> {
    let mut out = alloc::vec![WRITE_COMMAND];
    out.extend_from_slice(&handle.to_le_bytes());
    out.extend_from_slice(value);
    out
}

pub fn notification(handle: u16, value: &[u8]) -> Vec<u8> {
    let mut out = alloc::vec![HANDLE_VALUE_NOTIFICATION];
    out.extend_from_slice(&handle.to_le_bytes());
    out.extend_from_slice(value);
    out
}

/// What a server did with a request: the PDU to answer with, and a client
/// configuration it changed (value handle, notifications on).
pub struct Served {
    pub response: Option<Vec<u8>>,
    pub subscribed: Option<(u16, bool)>,
    /// A value a client wrote: its handle.
    pub written: Option<u16>,
}

/// Answers `pdu` from `table`, within `mtu`.
pub fn serve(table: &mut Table, pdu: &[u8], mtu: usize) -> Served {
    let mut served = Served {
        response: None,
        subscribed: None,
        written: None,
    };
    let Some(&opcode) = pdu.first() else {
        return served;
    };
    let err = |code: u8, handle: u16| Some(error(opcode, handle, code));
    served.response = match opcode {
        EXCHANGE_MTU_REQUEST => {
            let mut out = alloc::vec![EXCHANGE_MTU_RESPONSE];
            out.extend_from_slice(&(WANTED_MTU as u16).to_le_bytes());
            Some(out)
        }
        READ_BY_GROUP_TYPE_REQUEST | READ_BY_TYPE_REQUEST => {
            let (Some(start), Some(end), Some(kind)) = (u16_at(pdu, 1), u16_at(pdu, 3), u16_at(pdu, 5))
            else {
                return served;
            };
            if start == 0 || start > end {
                return Served {
                    response: err(ERR_INVALID_HANDLE, start),
                    ..served
                };
            }
            let grouped = opcode == READ_BY_GROUP_TYPE_REQUEST;
            let mut out = alloc::vec![
                if grouped {
                    READ_BY_GROUP_TYPE_RESPONSE
                } else {
                    READ_BY_TYPE_RESPONSE
                },
                0
            ];
            let mut entry_len = None;
            for a in table
                .attributes
                .iter()
                .filter(|a| a.handle >= start && a.handle <= end)
            {
                if a.kind != Uuid::Short(kind) {
                    continue;
                }
                let mut entry = a.handle.to_le_bytes().to_vec();
                if grouped {
                    let end_handle = table
                        .services
                        .iter()
                        .find(|s| s.handle == a.handle)
                        .map_or(a.handle, |s| s.end);
                    entry.extend_from_slice(&end_handle.to_le_bytes());
                }
                let room = mtu - 2 - entry.len();
                entry.extend_from_slice(&a.value[..a.value.len().min(room)]);
                match entry_len {
                    None => entry_len = Some(entry.len()),
                    Some(l) if l != entry.len() => break,
                    _ => {}
                }
                if out.len() + entry.len() > mtu {
                    break;
                }
                out.extend_from_slice(&entry);
            }
            match entry_len {
                None => err(ERR_ATTRIBUTE_NOT_FOUND, start),
                Some(l) => {
                    out[1] = l as u8;
                    Some(out)
                }
            }
        }
        FIND_INFORMATION_REQUEST => {
            let (Some(start), Some(end)) = (u16_at(pdu, 1), u16_at(pdu, 3)) else {
                return served;
            };
            let mut out = alloc::vec![FIND_INFORMATION_RESPONSE, 0];
            let mut format = None;
            for a in table
                .attributes
                .iter()
                .filter(|a| a.handle >= start && a.handle <= end)
            {
                let f = match a.kind {
                    Uuid::Short(_) => 1,
                    Uuid::Long(_) => 2,
                };
                match format {
                    None => format = Some(f),
                    Some(have) if have != f => break,
                    _ => {}
                }
                let bytes = a.kind.bytes();
                if out.len() + 2 + bytes.len() > mtu {
                    break;
                }
                out.extend_from_slice(&a.handle.to_le_bytes());
                out.extend_from_slice(&bytes);
            }
            match format {
                None => err(ERR_ATTRIBUTE_NOT_FOUND, start),
                Some(f) => {
                    out[1] = f;
                    Some(out)
                }
            }
        }
        READ_REQUEST => {
            let Some(handle) = u16_at(pdu, 1) else {
                return served;
            };
            match table.get(handle) {
                None => err(ERR_INVALID_HANDLE, handle),
                Some(a) if !a.readable => err(ERR_READ_NOT_PERMITTED, handle),
                Some(a) => {
                    let mut out = alloc::vec![READ_RESPONSE];
                    out.extend_from_slice(&a.value[..a.value.len().min(mtu - 1)]);
                    Some(out)
                }
            }
        }
        WRITE_REQUEST | WRITE_COMMAND => {
            let Some(handle) = u16_at(pdu, 1) else {
                return served;
            };
            let value = &pdu[3..];
            let answer = opcode == WRITE_REQUEST;
            match table.get_mut(handle) {
                None if answer => err(ERR_INVALID_HANDLE, handle),
                Some(a) if !a.writable && answer => err(ERR_WRITE_NOT_PERMITTED, handle),
                Some(a) if a.writable => {
                    a.value = value.to_vec();
                    if let Some(of) = a.configures {
                        served.subscribed = Some((of, value.first().is_some_and(|b| b & 1 != 0)));
                    } else {
                        served.written = Some(handle);
                    }
                    answer.then(|| alloc::vec![WRITE_RESPONSE])
                }
                _ => None,
            }
        }
        // A response or notification sent to a server: nothing to answer.
        _ if opcode & 1 == 1 || opcode == HANDLE_VALUE_NOTIFICATION => None,
        _ => err(ERR_REQUEST_NOT_SUPPORTED, 0),
    };
    served
}