webbluetooth_core/peripheral.rs
1//! What a peripheral publishes, independent of how.
2//!
3//! Service, characteristic and descriptor definitions, the permission and error
4//! vocabularies, and the advertising payload. None of this touches a platform
5//! API — the engines in `apple.rs` and `android.rs` turn it into
6//! `CBMutableService` or `BluetoothGattService` respectively.
7//!
8//! What each platform *accepts* differs, so validation is delegated: see
9//! `validate_characteristic` and `validate_descriptor` in whichever engine is
10//! compiled.
11//!
12//! Names like `Request::Read` and `Peripheral::publish` in the prose below
13//! belong to `webbluetooth::peripheral`, above this: the adapters are what
14//! turn these definitions into a running GATT server, and they cannot be
15//! linked from here without pointing a crate at the one that depends on it.
16
17use crate::error::{Error, Result};
18use crate::gatt::CharacteristicProperties as Properties;
19use crate::uuid::{BluetoothUuid, IntoUuid};
20
21/// What a peripheral may permit a central to do with an attribute.
22///
23/// The Bluetooth permission bits. CoreBluetooth calls these
24/// `CBAttributePermissions`; Android splits the same ideas across
25/// `BluetoothGattCharacteristic.PERMISSION_*`.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub struct Permissions(pub u32);
28
29impl Permissions {
30 /// A central may read it.
31 pub const READABLE: u32 = 0x01;
32 /// A central may write it.
33 pub const WRITEABLE: u32 = 0x02;
34 /// Reads require an encrypted link.
35 pub const READ_ENCRYPTION_REQUIRED: u32 = 0x04;
36 /// Writes require an encrypted link.
37 pub const WRITE_ENCRYPTION_REQUIRED: u32 = 0x08;
38
39 /// Whether one of the bits above is set.
40 #[inline]
41 pub fn has(self, bit: u32) -> bool {
42 self.0 & bit != 0
43 }
44 /// Whether [`Self::READABLE`] is set.
45 #[inline]
46 pub fn readable(self) -> bool {
47 self.has(Self::READABLE)
48 }
49 /// Whether [`Self::WRITEABLE`] is set.
50 #[inline]
51 pub fn writeable(self) -> bool {
52 self.has(Self::WRITEABLE)
53 }
54 /// Any permission that would let a central write.
55 #[inline]
56 pub fn any_write(self) -> bool {
57 self.has(Self::WRITEABLE) || self.has(Self::WRITE_ENCRYPTION_REQUIRED)
58 }
59}
60
61/// The status a request is answered with.
62///
63/// These are the Bluetooth ATT error codes, so a central sees exactly the
64/// failure the protocol defines rather than a generic one. Both platforms
65/// transmit the same numbers.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67#[repr(u8)]
68pub enum AttError {
69 /// The operation succeeded. Not an error; answering with it is the normal reply.
70 Success = 0x00,
71 /// The attribute handle is not valid on this server.
72 InvalidHandle = 0x01,
73 /// The attribute cannot be read.
74 ReadNotPermitted = 0x02,
75 /// The attribute cannot be written.
76 WriteNotPermitted = 0x03,
77 /// The request was malformed.
78 InvalidPdu = 0x04,
79 /// The link is not authenticated enough for this attribute.
80 InsufficientAuthentication = 0x05,
81 /// The server does not support this request. What a dropped request answers.
82 RequestNotSupported = 0x06,
83 /// The offset is past the end of the attribute.
84 InvalidOffset = 0x07,
85 /// The client is not authorised for this attribute.
86 InsufficientAuthorization = 0x08,
87 /// Too many queued prepare-writes.
88 PrepareQueueFull = 0x09,
89 /// No attribute in the requested range.
90 AttributeNotFound = 0x0A,
91 /// The attribute cannot be read or written with a blob request.
92 AttributeNotLong = 0x0B,
93 /// The encryption key is too short for this attribute.
94 InsufficientEncryptionKeySize = 0x0C,
95 /// The value's length is wrong for this attribute.
96 InvalidAttributeValueLength = 0x0D,
97 /// The request failed for a reason with no better code. The catch-all.
98 UnlikelyError = 0x0E,
99 /// The link must be encrypted first.
100 InsufficientEncryption = 0x0F,
101 /// The attribute type is not a supported grouping type.
102 UnsupportedGroupType = 0x10,
103 /// The server is out of resources to complete the request.
104 InsufficientResources = 0x11,
105}
106
107/// One write within a `WriteRequest`.
108#[derive(Debug, Clone)]
109pub struct Write {
110 /// Which characteristic is being written.
111 pub characteristic: BluetoothUuid,
112 /// Where in the attribute the bytes go.
113 pub offset: usize,
114 /// The bytes.
115 pub value: Vec<u8>,
116}
117
118/// What the system preserved for a peripheral across a relaunch.
119#[derive(Debug, Clone, Default)]
120pub struct RestoredPeripheral {
121 /// The local name that was being advertised.
122 pub advertised_local_name: Option<String>,
123 /// The services that were being advertised.
124 pub advertised_services: Vec<BluetoothUuid>,
125 /// How many services were published.
126 pub service_count: usize,
127}
128
129/// A descriptor to publish alongside a characteristic.
130#[derive(Debug, Clone)]
131pub struct Descriptor {
132 /// Which descriptor this is. The CCCD is not yours to declare.
133 pub uuid: BluetoothUuid,
134 /// Its value, which a descriptor must have.
135 pub value: Vec<u8>,
136 /// Whether the value is text. CoreBluetooth types a descriptor's value by
137 /// UUID — `NSString` for a user description, `NSData` for a presentation
138 /// format — so it must be told which. Android takes bytes either way.
139 #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
140 pub is_string: bool,
141}
142
143impl Descriptor {
144 /// A Characteristic User Description (`0x2901`) — a human-readable label.
145 pub fn user_description(text: impl Into<String>) -> Self {
146 Self {
147 uuid: BluetoothUuid::from_u16(0x2901),
148 value: text.into().into_bytes(),
149 is_string: true,
150 }
151 }
152
153 /// A Characteristic Presentation Format descriptor (`0x2904`).
154 ///
155 /// Seven bytes: format, exponent, unit (16-bit), namespace, description
156 /// (16-bit).
157 pub fn presentation_format(bytes: impl Into<Vec<u8>>) -> Self {
158 Self {
159 uuid: BluetoothUuid::from_u16(0x2904),
160 value: bytes.into(),
161 is_string: false,
162 }
163 }
164
165 /// The two rules every platform enforces.
166 ///
167 /// Both were written out four times before they were written here, once
168 /// per adapter, differing only in which stack the message blamed for
169 /// managing the CCCD. They all manage it.
170 pub fn validate(&self) -> Result<()> {
171 if self.uuid == cccd_uuid() {
172 return Err(Error::NotSupported(
173 "the client characteristic configuration descriptor is added automatically \
174 when a characteristic can notify — every platform here manages it, and \
175 declaring it would publish a second one"
176 .into(),
177 ));
178 }
179 if self.value.is_empty() {
180 return Err(Error::NotSupported("a descriptor must have a value".into()));
181 }
182 Ok(())
183 }
184}
185
186/// The client characteristic configuration descriptor.
187///
188/// Named once here because all four adapters need it and all four used to
189/// define it: the engine adds it to any characteristic that can notify, so it
190/// is never the caller's to declare.
191pub fn cccd_uuid() -> BluetoothUuid {
192 crate::uuid::descriptors::CLIENT_CHARACTERISTIC_CONFIGURATION
193}
194
195/// A characteristic to publish.
196#[derive(Debug, Clone)]
197pub struct Characteristic {
198 /// Which characteristic this is.
199 pub uuid: BluetoothUuid,
200 /// [`crate::CharacteristicProperties`] bits: what a central may do.
201 pub properties: u32,
202 /// [`Permissions`] bits: what a central must have done to be allowed to.
203 pub permissions: u32,
204 /// A fixed value, answered by the stack without waking the application.
205 ///
206 /// CoreBluetooth requires a characteristic with one to be read-only,
207 /// because a cached value can never change; the other platforms do not,
208 /// and the check is applied where Apple publishes.
209 pub value: Option<Vec<u8>>,
210 /// Descriptors published alongside it.
211 pub descriptors: Vec<Descriptor>,
212}
213
214impl Characteristic {
215 /// Begin defining a characteristic. It has no properties until you add some.
216 pub fn new(uuid: impl IntoUuid) -> Result<Self> {
217 Ok(Self {
218 uuid: uuid.into_uuid()?,
219 properties: 0,
220 permissions: 0,
221 value: None,
222 descriptors: Vec::new(),
223 })
224 }
225
226 /// Allow reads. Answered by `Request::Read` unless a fixed
227 /// [`Characteristic::value`] is set.
228 pub fn read(mut self) -> Self {
229 self.properties |= Properties::READ;
230 self.permissions |= Permissions::READABLE;
231 self
232 }
233
234 /// Allow acknowledged writes.
235 pub fn write(mut self) -> Self {
236 self.properties |= Properties::WRITE;
237 self.permissions |= Permissions::WRITEABLE;
238 self
239 }
240
241 /// Allow unacknowledged writes.
242 pub fn write_without_response(mut self) -> Self {
243 self.properties |= Properties::WRITE_WITHOUT_RESPONSE;
244 self.permissions |= Permissions::WRITEABLE;
245 self
246 }
247
248 /// Allow subscription. CoreBluetooth adds the Client Characteristic
249 /// Configuration descriptor for you.
250 pub fn notify(mut self) -> Self {
251 self.properties |= Properties::NOTIFY;
252 self
253 }
254
255 /// Allow acknowledged subscription.
256 pub fn indicate(mut self) -> Self {
257 self.properties |= Properties::INDICATE;
258 self
259 }
260
261 /// Require an encrypted link for reads and writes.
262 pub fn require_encryption(mut self) -> Self {
263 if self.permissions & Permissions::READABLE != 0 {
264 self.permissions |= Permissions::READ_ENCRYPTION_REQUIRED;
265 }
266 if self.permissions & Permissions::WRITEABLE != 0 {
267 self.permissions |= Permissions::WRITE_ENCRYPTION_REQUIRED;
268 }
269 self
270 }
271
272 /// Serve a fixed value from CoreBluetooth's cache, with no read requests
273 /// reaching your code.
274 ///
275 /// Forces read-only: `Peripheral::publish` rejects a characteristic that
276 /// combines a fixed value with `write`, `notify` or `indicate`, because
277 /// CoreBluetooth raises on that.
278 pub fn value(mut self, value: impl Into<Vec<u8>>) -> Self {
279 self.value = Some(value.into());
280 self
281 }
282
283 /// Attach a descriptor.
284 /// Publish a descriptor alongside this characteristic.
285 pub fn descriptor(mut self, descriptor: Descriptor) -> Self {
286 self.descriptors.push(descriptor);
287 self
288 }
289
290 /// The rules every platform enforces on a characteristic, and on the
291 /// descriptors under it. A platform may add its own where it publishes.
292 pub fn validate(&self) -> Result<()> {
293 if self.properties == 0 {
294 return Err(Error::NotSupported(format!(
295 "characteristic {} has no properties — add read(), write() or notify()",
296 self.uuid
297 )));
298 }
299 for d in &self.descriptors {
300 d.validate()?;
301 }
302 Ok(())
303 }
304}
305
306// A platform may have rules of its own on top of these — CoreBluetooth
307// refuses a cached value on anything writeable or notifying, where BlueZ does
308// not care — and applies them where it publishes. What is here is what holds
309// everywhere, so that a definition rejected on one platform is not quietly
310// accepted on another.
311
312/// A service to publish.
313#[derive(Debug, Clone)]
314pub struct Service {
315 /// Which service this is.
316 pub uuid: BluetoothUuid,
317 /// Primary rather than included in another service.
318 pub primary: bool,
319 /// Its characteristics. A service needs at least one.
320 pub characteristics: Vec<Characteristic>,
321}
322
323impl Service {
324 /// Begin defining a primary service.
325 pub fn new(uuid: impl IntoUuid) -> Result<Self> {
326 Ok(Self {
327 uuid: uuid.into_uuid()?,
328 primary: true,
329 characteristics: Vec::new(),
330 })
331 }
332
333 /// Make this a secondary (included) service rather than a primary one.
334 pub fn secondary(mut self) -> Self {
335 self.primary = false;
336 self
337 }
338
339 /// Add a characteristic.
340 /// Add a characteristic to this service.
341 pub fn characteristic(mut self, characteristic: Characteristic) -> Self {
342 self.characteristics.push(characteristic);
343 self
344 }
345
346 /// The rules every platform enforces on a service and everything in it.
347 pub fn validate(&self) -> Result<()> {
348 if self.characteristics.is_empty() {
349 return Err(Error::NotSupported(format!(
350 "service {} has no characteristics",
351 self.uuid
352 )));
353 }
354 for c in &self.characteristics {
355 c.validate()?;
356 }
357 Ok(())
358 }
359}
360
361/// What to put in the advertisement.
362///
363/// Apple honours only a local name and a service UUID list in the peripheral
364/// role — no manufacturer data, no service data. The packet holds 28 bytes for
365/// everything; service UUIDs that do not fit go to the overflow area, where
366/// only an Apple device scanning for them explicitly will see them.
367#[derive(Debug, Clone, Default)]
368pub struct Advertising {
369 /// The name to advertise, if any.
370 pub local_name: Option<String>,
371 /// Service UUIDs to advertise, which is what a central filters on.
372 pub services: Vec<BluetoothUuid>,
373}
374
375impl Advertising {
376 /// Advertise nothing in particular. Add a name or a service.
377 pub fn new() -> Self {
378 Self::default()
379 }
380
381 /// The name centrals will show.
382 pub fn local_name(mut self, name: impl Into<String>) -> Self {
383 self.local_name = Some(name.into());
384 self
385 }
386
387 /// Advertise a service UUID, so centrals filtering for it find this device.
388 pub fn service(mut self, uuid: impl IntoUuid) -> Result<Self> {
389 self.services.push(uuid.into_uuid()?);
390 Ok(self)
391 }
392}