Skip to main content

bluetooth_host/gatt/
mod.rs

1//! GATT (Core Vol 3, Part G): a client for peers' servers, and our own server.
2
3pub mod client;
4pub mod server;
5
6use bluetooth_adv::Uuid;
7use serde::{Deserialize, Serialize};
8
9/// Well-known attribute types.
10pub mod uuid {
11    /// Primary Service declaration.
12    pub const PRIMARY_SERVICE: u16 = 0x2800;
13    /// Secondary Service declaration.
14    pub const SECONDARY_SERVICE: u16 = 0x2801;
15    /// Include declaration.
16    pub const INCLUDE: u16 = 0x2802;
17    /// Characteristic declaration.
18    pub const CHARACTERISTIC: u16 = 0x2803;
19    /// Characteristic Extended Properties.
20    pub const EXTENDED_PROPERTIES: u16 = 0x2900;
21    /// Characteristic User Description.
22    pub const USER_DESCRIPTION: u16 = 0x2901;
23    /// Client Characteristic Configuration.
24    pub const CCCD: u16 = 0x2902;
25    /// Server Characteristic Configuration.
26    pub const SCCD: u16 = 0x2903;
27    /// Characteristic Presentation Format.
28    pub const PRESENTATION_FORMAT: u16 = 0x2904;
29    /// Characteristic Aggregate Format.
30    pub const AGGREGATE_FORMAT: u16 = 0x2905;
31    /// GAP service.
32    pub const GAP: u16 = 0x1800;
33    /// GATT service.
34    pub const GATT: u16 = 0x1801;
35    /// Device Name.
36    pub const DEVICE_NAME: u16 = 0x2a00;
37    /// Appearance.
38    pub const APPEARANCE: u16 = 0x2a01;
39    /// Service Changed.
40    pub const SERVICE_CHANGED: u16 = 0x2a05;
41    /// Central Address Resolution.
42    pub const CENTRAL_ADDRESS_RESOLUTION: u16 = 0x2aa6;
43    /// Client Supported Features.
44    pub const CLIENT_SUPPORTED_FEATURES: u16 = 0x2b29;
45    /// Database Hash.
46    pub const DATABASE_HASH: u16 = 0x2b2a;
47    /// Server Supported Features.
48    pub const SERVER_SUPPORTED_FEATURES: u16 = 0x2b3a;
49}
50
51/// Characteristic properties (the declaration's bit field).
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
53#[serde(transparent)]
54pub struct Properties(pub u8);
55
56impl Properties {
57    /// Broadcast.
58    pub const BROADCAST: u8 = 0x01;
59    /// Read.
60    pub const READ: u8 = 0x02;
61    /// Write Without Response.
62    pub const WRITE_WITHOUT_RESPONSE: u8 = 0x04;
63    /// Write.
64    pub const WRITE: u8 = 0x08;
65    /// Notify.
66    pub const NOTIFY: u8 = 0x10;
67    /// Indicate.
68    pub const INDICATE: u8 = 0x20;
69    /// Authenticated Signed Writes.
70    pub const SIGNED_WRITE: u8 = 0x40;
71    /// Extended Properties.
72    pub const EXTENDED: u8 = 0x80;
73
74    /// Whether a bit is set.
75    pub fn has(&self, bit: u8) -> bool {
76        self.0 & bit != 0
77    }
78
79    /// The property names, for reports.
80    pub fn names(&self) -> Vec<&'static str> {
81        [
82            (Self::BROADCAST, "broadcast"),
83            (Self::READ, "read"),
84            (Self::WRITE_WITHOUT_RESPONSE, "write_without_response"),
85            (Self::WRITE, "write"),
86            (Self::NOTIFY, "notify"),
87            (Self::INDICATE, "indicate"),
88            (Self::SIGNED_WRITE, "authenticated_signed_writes"),
89            (Self::EXTENDED, "extended_properties"),
90        ]
91        .iter()
92        .filter(|(b, _)| self.has(*b))
93        .map(|(_, n)| *n)
94        .collect()
95    }
96
97    /// From property names (as [`Properties::names`] gives them).
98    pub fn from_names<S: AsRef<str>>(names: &[S]) -> Result<Properties, String> {
99        let mut p = 0;
100        for n in names {
101            p |= match n.as_ref() {
102                "broadcast" => Self::BROADCAST,
103                "read" => Self::READ,
104                "write_without_response" => Self::WRITE_WITHOUT_RESPONSE,
105                "write" => Self::WRITE,
106                "notify" => Self::NOTIFY,
107                "indicate" => Self::INDICATE,
108                "authenticated_signed_writes" => Self::SIGNED_WRITE,
109                other => return Err(format!("unknown characteristic property {other:?}")),
110            };
111        }
112        Ok(Properties(p))
113    }
114}
115
116/// A service on a peer's server.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
118pub struct Service {
119    /// Its UUID.
120    pub uuid: Uuid,
121    /// The SIG's name for it.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub name: Option<&'static str>,
124    /// Primary (rather than secondary, found through an include).
125    pub primary: bool,
126    /// The declaration's handle.
127    pub start: u16,
128    /// The last handle in the service.
129    pub end: u16,
130    /// Its characteristics, when discovered.
131    pub characteristics: Vec<Characteristic>,
132}
133
134/// A characteristic on a peer's server.
135#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
136pub struct Characteristic {
137    /// Its UUID.
138    pub uuid: Uuid,
139    /// The SIG's name for it.
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub name: Option<&'static str>,
142    /// The declaration's handle.
143    pub declaration: u16,
144    /// The value's handle (what reads and writes address).
145    pub value_handle: u16,
146    /// Properties.
147    pub properties: Properties,
148    /// The last handle belonging to the characteristic.
149    pub end: u16,
150    /// Descriptors, when discovered.
151    pub descriptors: Vec<Descriptor>,
152}
153
154impl Characteristic {
155    /// The Client Characteristic Configuration descriptor's handle, if found.
156    pub fn cccd(&self) -> Option<u16> {
157        self.descriptors
158            .iter()
159            .find(|d| d.uuid == Uuid::Uuid16(uuid::CCCD))
160            .map(|d| d.handle)
161    }
162}
163
164/// A descriptor on a peer's server.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
166pub struct Descriptor {
167    /// Its UUID.
168    pub uuid: Uuid,
169    /// Its handle.
170    pub handle: u16,
171}
172
173pub(crate) fn uuid_bytes(u: &Uuid) -> Vec<u8> {
174    match u.shortened() {
175        Uuid::Uuid16(v) => v.to_le_bytes().to_vec(),
176        // ATT carries only 16 and 128-bit UUIDs.
177        other => {
178            let mut a = other.to_u128_bytes();
179            a.reverse();
180            a.to_vec()
181        }
182    }
183}