Skip to main content

Service

Struct Service 

Source
pub struct Service(/* private fields */);
Expand description

A Bluetooth GATT service

Implementations§

Source§

impl Service

Source

pub fn uuid(&self) -> Uuid

The Uuid identifying the type of this GATT service

§Panics

On Linux, this method will panic if there is a current Tokio runtime and it is single-threaded, if there is no current Tokio runtime and creating one fails, or if the underlying Service::uuid_async() method fails.

Source

pub async fn uuid_async(&self) -> Result<Uuid>

The Uuid identifying the type of this GATT service

Source

pub async fn is_primary(&self) -> Result<bool>

Whether this is a primary service of the device.

§Platform specific

Returns NotSupported on Windows.

Source

pub async fn discover_characteristics(&self) -> Result<Vec<Characteristic>>

Discover all characteristics associated with this service.

Source

pub async fn discover_characteristics_with_uuid( &self, uuid: Uuid, ) -> Result<Vec<Characteristic>>

Discover the characteristic(s) with the given Uuid.

Source

pub async fn characteristics(&self) -> Result<Vec<Characteristic>>

Get previously discovered characteristics.

If no characteristics have been discovered yet, this method will perform characteristic discovery.

Examples found in repository?
examples/connected.rs (line 32)
8async fn main() -> Result<(), Box<dyn Error>> {
9    use tracing_subscriber::prelude::*;
10    use tracing_subscriber::{fmt, EnvFilter};
11
12    tracing_subscriber::registry()
13        .with(fmt::layer())
14        .with(
15            EnvFilter::builder()
16                .with_default_directive(LevelFilter::INFO.into())
17                .from_env_lossy(),
18        )
19        .init();
20
21    let adapter = Adapter::default().await.ok_or("Bluetooth adapter not found")?;
22    adapter.wait_available().await?;
23
24    info!("getting connected devices");
25    let devices = adapter.connected_devices().await?;
26    for device in devices {
27        info!("found {:?}", device);
28        adapter.connect_device(&device).await?;
29        let services = device.services().await?;
30        for service in services {
31            info!("  {:?}", service);
32            let characteristics = service.characteristics().await?;
33            for characteristic in characteristics {
34                info!("    {:?}", characteristic);
35                let props = characteristic.properties().await?;
36                info!("      props: {:?}", props);
37                if props.read {
38                    info!("      value: {:?}", characteristic.read().await);
39                }
40                if props.write_without_response {
41                    info!("      max_write_len: {:?}", characteristic.max_write_len());
42                }
43
44                let descriptors = characteristic.descriptors().await?;
45                for descriptor in descriptors {
46                    info!("      {:?}: {:?}", descriptor, descriptor.read().await);
47                }
48            }
49        }
50    }
51    info!("done");
52
53    Ok(())
54}
More examples
Hide additional examples
examples/blinky.rs (line 56)
14async fn main() -> Result<(), Box<dyn Error>> {
15    use tracing_subscriber::prelude::*;
16    use tracing_subscriber::{fmt, EnvFilter};
17
18    tracing_subscriber::registry()
19        .with(fmt::layer())
20        .with(
21            EnvFilter::builder()
22                .with_default_directive(LevelFilter::INFO.into())
23                .from_env_lossy(),
24        )
25        .init();
26
27    let adapter = Adapter::default().await.ok_or("Bluetooth adapter not found")?;
28    adapter.wait_available().await?;
29
30    info!("looking for device");
31    let device = adapter
32        .discover_devices(&[NORDIC_LED_AND_BUTTON_SERVICE])
33        .await?
34        .next()
35        .await
36        .ok_or("Failed to discover device")??;
37    info!(
38        "found device: {} ({:?})",
39        device.name().as_deref().unwrap_or("(unknown)"),
40        device.id()
41    );
42
43    adapter.connect_device(&device).await?;
44    info!("connected!");
45
46    let service = match device
47        .discover_services_with_uuid(NORDIC_LED_AND_BUTTON_SERVICE)
48        .await?
49        .first()
50    {
51        Some(service) => service.clone(),
52        None => return Err("service not found".into()),
53    };
54    info!("found LED and button service");
55
56    let characteristics = service.characteristics().await?;
57    info!("discovered characteristics");
58
59    let button_characteristic = characteristics
60        .iter()
61        .find(|x| x.uuid() == BLINKY_BUTTON_STATE_CHARACTERISTIC)
62        .ok_or("button characteristic not found")?;
63
64    let button_fut = async {
65        info!("enabling button notifications");
66        let mut updates = button_characteristic.notify().await?;
67        info!("waiting for button changes");
68        while let Some(val) = updates.next().await {
69            info!("Button state changed: {:?}", val?);
70        }
71        Ok(())
72    };
73
74    let led_characteristic = characteristics
75        .iter()
76        .find(|x| x.uuid() == BLINKY_LED_STATE_CHARACTERISTIC)
77        .ok_or("led characteristic not found")?;
78
79    let blink_fut = async {
80        info!("blinking LED");
81        tokio::time::sleep(Duration::from_secs(1)).await;
82        loop {
83            led_characteristic.write(&[0x01]).await?;
84            info!("LED on");
85            tokio::time::sleep(Duration::from_secs(1)).await;
86            led_characteristic.write(&[0x00]).await?;
87            info!("LED off");
88            tokio::time::sleep(Duration::from_secs(1)).await;
89        }
90    };
91
92    type R = Result<(), Box<dyn Error>>;
93    let button_fut = async move {
94        let res: R = button_fut.await;
95        error!("Button task exited: {:?}", res);
96    };
97    let blink_fut = async move {
98        let res: R = blink_fut.await;
99        error!("Blink task exited: {:?}", res);
100    };
101
102    future::zip(blink_fut, button_fut).await;
103
104    Ok(())
105}
Source

pub async fn discover_included_services(&self) -> Result<Vec<Service>>

Discover the included services of this service.

Source

pub async fn discover_included_services_with_uuid( &self, uuid: Uuid, ) -> Result<Vec<Service>>

Discover the included service(s) with the given Uuid.

Source

pub async fn included_services(&self) -> Result<Vec<Service>>

Get previously discovered included services.

If no included services have been discovered yet, this method will perform included service discovery.

Trait Implementations§

Source§

impl Clone for Service

Source§

fn clone(&self) -> Service

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Service

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Service

Source§

impl Hash for Service

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Service

Source§

fn eq(&self, other: &Service) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Service

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more