use std::sync::Arc;
use uuid::Uuid;
use crate::error::Error;
use crate::handler::{Handler, SubscriptionHandler};
use crate::models::{BleDevice, Service, WriteType};
#[derive(Clone)]
pub struct Connection {
handler: &'static Handler,
address: Arc<str>,
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Connection")
.field("address", &self.address)
.finish_non_exhaustive()
}
}
impl PartialEq for Connection {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(self.handler, other.handler) && self.address == other.address
}
}
impl Eq for Connection {}
impl Connection {
pub(crate) fn new(handler: &'static Handler, address: &str) -> Self {
Self {
handler,
address: address.into(),
}
}
#[must_use]
pub fn address(&self) -> &str {
&self.address
}
#[must_use]
pub fn is_connected(&self) -> bool {
self.handler.is_device_connected(&self.address)
}
pub async fn device(&self) -> Result<BleDevice, Error> {
self.handler.connected_device_at(&self.address).await
}
pub async fn mtu(&self) -> Result<u16, Error> {
self.handler.device_mtu(&self.address).await
}
pub async fn services(&self) -> Result<Vec<Service>, Error> {
self.handler.discover_services(&self.address).await
}
pub async fn send_data(
&self,
c: Uuid,
service: Option<Uuid>,
data: &[u8],
write_type: WriteType,
) -> Result<(), Error> {
self.handler
.send_data_to(&self.address, c, service, data, write_type)
.await
}
pub async fn recv_data(&self, c: Uuid, service: Option<Uuid>) -> Result<Vec<u8>, Error> {
self.handler.recv_data_from(&self.address, c, service).await
}
pub async fn subscribe(
&self,
c: Uuid,
service: Option<Uuid>,
callback: impl Into<SubscriptionHandler>,
) -> Result<(), Error> {
self.handler
.subscribe_to(&self.address, c, service, callback)
.await
}
pub async fn unsubscribe(&self, c: Uuid, service: Option<Uuid>) -> Result<(), Error> {
self.handler
.unsubscribe_from(&self.address, c, service)
.await
}
pub async fn disconnect(&self) -> Result<(), Error> {
self.handler.disconnect_device(&self.address).await
}
}