use crate::error::{Error, Result};
use crate::gatt::CharacteristicProperties as Properties;
use crate::uuid::{BluetoothUuid, IntoUuid};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Permissions(pub u32);
impl Permissions {
pub const READABLE: u32 = 0x01;
pub const WRITEABLE: u32 = 0x02;
pub const READ_ENCRYPTION_REQUIRED: u32 = 0x04;
pub const WRITE_ENCRYPTION_REQUIRED: u32 = 0x08;
#[inline]
pub fn has(self, bit: u32) -> bool {
self.0 & bit != 0
}
#[inline]
pub fn readable(self) -> bool {
self.has(Self::READABLE)
}
#[inline]
pub fn writeable(self) -> bool {
self.has(Self::WRITEABLE)
}
#[inline]
pub fn any_write(self) -> bool {
self.has(Self::WRITEABLE) || self.has(Self::WRITE_ENCRYPTION_REQUIRED)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum AttError {
Success = 0x00,
InvalidHandle = 0x01,
ReadNotPermitted = 0x02,
WriteNotPermitted = 0x03,
InvalidPdu = 0x04,
InsufficientAuthentication = 0x05,
RequestNotSupported = 0x06,
InvalidOffset = 0x07,
InsufficientAuthorization = 0x08,
PrepareQueueFull = 0x09,
AttributeNotFound = 0x0A,
AttributeNotLong = 0x0B,
InsufficientEncryptionKeySize = 0x0C,
InvalidAttributeValueLength = 0x0D,
UnlikelyError = 0x0E,
InsufficientEncryption = 0x0F,
UnsupportedGroupType = 0x10,
InsufficientResources = 0x11,
}
#[derive(Debug, Clone)]
pub struct Write {
pub characteristic: BluetoothUuid,
pub offset: usize,
pub value: Vec<u8>,
}
#[derive(Debug, Clone, Default)]
pub struct RestoredPeripheral {
pub advertised_local_name: Option<String>,
pub advertised_services: Vec<BluetoothUuid>,
pub service_count: usize,
}
#[derive(Debug, Clone)]
pub struct Descriptor {
pub uuid: BluetoothUuid,
pub value: Vec<u8>,
#[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
pub is_string: bool,
}
impl Descriptor {
pub fn user_description(text: impl Into<String>) -> Self {
Self {
uuid: BluetoothUuid::from_u16(0x2901),
value: text.into().into_bytes(),
is_string: true,
}
}
pub fn presentation_format(bytes: impl Into<Vec<u8>>) -> Self {
Self {
uuid: BluetoothUuid::from_u16(0x2904),
value: bytes.into(),
is_string: false,
}
}
pub fn validate(&self) -> Result<()> {
if self.uuid == cccd_uuid() {
return Err(Error::NotSupported(
"the client characteristic configuration descriptor is added automatically \
when a characteristic can notify — every platform here manages it, and \
declaring it would publish a second one"
.into(),
));
}
if self.value.is_empty() {
return Err(Error::NotSupported("a descriptor must have a value".into()));
}
Ok(())
}
}
pub fn cccd_uuid() -> BluetoothUuid {
crate::uuid::descriptors::CLIENT_CHARACTERISTIC_CONFIGURATION
}
#[derive(Debug, Clone)]
pub struct Characteristic {
pub uuid: BluetoothUuid,
pub properties: u32,
pub permissions: u32,
pub value: Option<Vec<u8>>,
pub descriptors: Vec<Descriptor>,
}
impl Characteristic {
pub fn new(uuid: impl IntoUuid) -> Result<Self> {
Ok(Self {
uuid: uuid.into_uuid()?,
properties: 0,
permissions: 0,
value: None,
descriptors: Vec::new(),
})
}
pub fn read(mut self) -> Self {
self.properties |= Properties::READ;
self.permissions |= Permissions::READABLE;
self
}
pub fn write(mut self) -> Self {
self.properties |= Properties::WRITE;
self.permissions |= Permissions::WRITEABLE;
self
}
pub fn write_without_response(mut self) -> Self {
self.properties |= Properties::WRITE_WITHOUT_RESPONSE;
self.permissions |= Permissions::WRITEABLE;
self
}
pub fn notify(mut self) -> Self {
self.properties |= Properties::NOTIFY;
self
}
pub fn indicate(mut self) -> Self {
self.properties |= Properties::INDICATE;
self
}
pub fn require_encryption(mut self) -> Self {
if self.permissions & Permissions::READABLE != 0 {
self.permissions |= Permissions::READ_ENCRYPTION_REQUIRED;
}
if self.permissions & Permissions::WRITEABLE != 0 {
self.permissions |= Permissions::WRITE_ENCRYPTION_REQUIRED;
}
self
}
pub fn value(mut self, value: impl Into<Vec<u8>>) -> Self {
self.value = Some(value.into());
self
}
pub fn descriptor(mut self, descriptor: Descriptor) -> Self {
self.descriptors.push(descriptor);
self
}
pub fn validate(&self) -> Result<()> {
if self.properties == 0 {
return Err(Error::NotSupported(format!(
"characteristic {} has no properties — add read(), write() or notify()",
self.uuid
)));
}
for d in &self.descriptors {
d.validate()?;
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct Service {
pub uuid: BluetoothUuid,
pub primary: bool,
pub characteristics: Vec<Characteristic>,
}
impl Service {
pub fn new(uuid: impl IntoUuid) -> Result<Self> {
Ok(Self {
uuid: uuid.into_uuid()?,
primary: true,
characteristics: Vec::new(),
})
}
pub fn secondary(mut self) -> Self {
self.primary = false;
self
}
pub fn characteristic(mut self, characteristic: Characteristic) -> Self {
self.characteristics.push(characteristic);
self
}
pub fn validate(&self) -> Result<()> {
if self.characteristics.is_empty() {
return Err(Error::NotSupported(format!(
"service {} has no characteristics",
self.uuid
)));
}
for c in &self.characteristics {
c.validate()?;
}
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct Advertising {
pub local_name: Option<String>,
pub services: Vec<BluetoothUuid>,
pub interval: Option<(std::time::Duration, std::time::Duration)>,
}
pub const MIN_ADVERTISING_INTERVAL: std::time::Duration = std::time::Duration::from_millis(20);
pub const MAX_ADVERTISING_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10_240);
impl Advertising {
pub fn new() -> Self {
Self::default()
}
pub fn local_name(mut self, name: impl Into<String>) -> Self {
self.local_name = Some(name.into());
self
}
pub fn service(mut self, uuid: impl IntoUuid) -> Result<Self> {
self.services.push(uuid.into_uuid()?);
Ok(self)
}
pub fn interval(mut self, min: std::time::Duration, max: std::time::Duration) -> Result<Self> {
let range = MIN_ADVERTISING_INTERVAL..=MAX_ADVERTISING_INTERVAL;
if !range.contains(&min) || !range.contains(&max) || min > max {
return Err(Error::InvalidModification(format!(
"advertising interval {min:?}..{max:?} must be within 20 ms..10.24 s, min first"
)));
}
self.interval = Some((min, max));
Ok(self)
}
}
#[cfg(test)]
mod advertising_tests {
use super::*;
use std::time::Duration;
#[test]
fn intervals_are_validated() {
let ms = Duration::from_millis;
assert_eq!(Advertising::new().interval(ms(100), ms(150)).unwrap().interval, Some((ms(100), ms(150))));
assert!(Advertising::new().interval(ms(10), ms(150)).is_err(), "below 20 ms");
assert!(Advertising::new().interval(ms(100), ms(20_000)).is_err(), "above 10.24 s");
assert!(Advertising::new().interval(ms(200), ms(100)).is_err(), "min after max");
assert_eq!(Advertising::new().interval, None, "the platform decides by default");
}
}