use std::collections::HashMap;
use std::path::Path;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use btleplug::api::ValueNotification;
use btleplug::api::{
Central, CentralEvent, CharPropFlags, Characteristic as BleCharacteristic, Manager as _, Peripheral as _,
ScanFilter, WriteType,
};
use btleplug::platform::{Adapter, Manager, Peripheral, PeripheralId};
use frenz_proto::{Characteristic, Command, Packet, Response, ResponseBody};
use futures::{Stream, StreamExt};
use tokio::sync::{Notify, RwLock, broadcast, mpsc};
use tokio::task::JoinHandle;
use crate::clock::{mono_ns, wall_ns};
use crate::error::Error;
use crate::event::{Decoder, Event, Health, RawRecord};
const CHANNEL_CAPACITY: usize = 1 << 14;
#[derive(Debug, Clone)]
pub struct Discovered {
pub name: String,
pub rssi: Option<i16>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StartSequence {
#[default]
Standard,
None,
}
#[derive(Debug, Clone)]
pub struct ConnectOptions {
pub scan_timeout: Duration,
pub start: StartSequence,
pub command_timeout: Duration,
pub reconnect: Option<Duration>,
pub notify: Vec<Characteristic>,
}
impl Default for ConnectOptions {
fn default() -> Self {
Self {
scan_timeout: Duration::from_secs(30),
start: StartSequence::default(),
command_timeout: Duration::from_secs(2),
reconnect: Some(Duration::from_secs(300)),
notify: Characteristic::NOTIFY.to_vec(),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct BandInfo {
pub name: String,
pub firmware: Option<String>,
pub imu_calibration: Option<([u8; 3], [u16; 3])>,
pub gatt: Vec<(String, String, String)>,
}
async fn first_adapter() -> Result<Adapter, Error> {
Manager::new()
.await?
.adapters()
.await?
.into_iter()
.next()
.ok_or(Error::NoAdapter)
}
async fn frenz_peripherals(adapter: &Adapter) -> Result<Vec<(Discovered, Peripheral)>, Error> {
let mut found = Vec::new();
for p in adapter.peripherals().await? {
if let Some(props) = p.properties().await?
&& let Some(name) = props.local_name
&& name.to_ascii_uppercase().starts_with("FRENZ")
{
found.push((Discovered { name, rssi: props.rssi }, p));
}
}
Ok(found)
}
pub async fn scan(duration: Duration) -> Result<Vec<Discovered>, Error> {
let adapter = first_adapter().await?;
adapter.start_scan(ScanFilter::default()).await?;
tokio::time::sleep(duration).await;
let mut found: Vec<_> = frenz_peripherals(&adapter).await?.into_iter().map(|(d, _)| d).collect();
adapter.stop_scan().await.ok();
found.sort_by_key(|d| std::cmp::Reverse(d.rssi.unwrap_or(i16::MIN)));
Ok(found)
}
const STALL: Duration = Duration::from_secs(10);
type Notifications = Pin<Box<dyn Stream<Item = ValueNotification> + Send>>;
type CentralEvents = Pin<Box<dyn Stream<Item = CentralEvent> + Send>>;
struct Link {
peripheral: Peripheral,
characteristics: HashMap<Characteristic, BleCharacteristic>,
}
enum ToDecoder {
Notification(i64, Characteristic, Arc<[u8]>),
Reset,
StreamStart(i64),
ReplayEnded,
}
struct Shared {
name: String,
options: ConnectOptions,
events: broadcast::Sender<Event>,
raw: broadcast::Sender<RawRecord>,
health: Mutex<Health>,
last_start_ns: AtomicI64,
info: Mutex<BandInfo>,
link: RwLock<Option<Link>>,
closing: AtomicBool,
device: Mutex<Option<PeripheralId>>,
subscribed: Notify,
}
impl Shared {
fn new(name: &str, options: ConnectOptions) -> (Arc<Self>, broadcast::Receiver<RawRecord>) {
let (events, _) = broadcast::channel(CHANNEL_CAPACITY);
let (raw, initial_raw) = broadcast::channel(CHANNEL_CAPACITY);
let shared = Arc::new(Self {
name: name.to_owned(),
options,
events,
raw,
health: Mutex::new(Health::default()),
last_start_ns: AtomicI64::new(i64::MIN / 2),
info: Mutex::new(BandInfo {
name: name.to_owned(),
..BandInfo::default()
}),
link: RwLock::new(None),
closing: AtomicBool::new(false),
device: Mutex::new(None),
subscribed: Notify::new(),
});
(shared, initial_raw)
}
fn mark(&self, label: &str) {
let _ = self.raw.send(RawRecord::Marker {
mono_ns: mono_ns(),
wall_ns: wall_ns(),
label: label.to_owned(),
});
}
fn with_health<R>(&self, f: impl FnOnce(&mut Health) -> R) -> R {
f(&mut self.health.lock().unwrap_or_else(PoisonError::into_inner))
}
async fn establish(&self, scan_timeout: Duration) -> Result<(Notifications, CentralEvents, PeripheralId), Error> {
let adapter = first_adapter().await?;
adapter.start_scan(ScanFilter::default()).await?;
let deadline = tokio::time::Instant::now() + scan_timeout;
let pinned = self.device.lock().unwrap_or_else(PoisonError::into_inner).clone();
let peripheral = loop {
if let Some((_, p)) = frenz_peripherals(&adapter)
.await?
.into_iter()
.find(|(d, p)| d.name == self.name && pinned.as_ref().is_none_or(|id| *id == p.id()))
{
break p;
}
if tokio::time::Instant::now() >= deadline {
adapter.stop_scan().await.ok();
return Err(Error::NotFound {
name: self.name.clone(),
timeout: scan_timeout,
});
}
tokio::time::sleep(Duration::from_millis(250)).await;
};
adapter.stop_scan().await.ok();
let connect_timeout = Duration::from_secs(15);
tokio::time::timeout(connect_timeout, peripheral.connect())
.await
.map_err(|_| Error::NotFound {
name: self.name.clone(),
timeout: connect_timeout,
})??;
peripheral.discover_services().await?;
let mut characteristics = HashMap::new();
let mut gatt = Vec::new();
for c in peripheral.characteristics() {
gatt.push((
c.service_uuid.to_string(),
c.uuid.to_string(),
format!("{:?}", c.properties),
));
if let Some(known) = Characteristic::from_uuid(c.uuid.as_u128()) {
characteristics.insert(known, c);
}
}
for required in Characteristic::NOTIFY.into_iter().chain([Characteristic::CommandRx]) {
if !characteristics.contains_key(&required) {
return Err(Error::MissingCharacteristic(required.name()));
}
}
let notifications = peripheral.notifications().await?;
let central_events = adapter.events().await?;
let id = peripheral.id();
self.device
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get_or_insert_with(|| id.clone());
self.info.lock().unwrap_or_else(PoisonError::into_inner).gatt = gatt;
self.mark("connected");
for c in &self.options.notify {
if let Some(ble) = characteristics.get(c)
&& ble.properties.contains(CharPropFlags::NOTIFY)
{
peripheral.subscribe(ble).await?;
}
}
self.mark("subscribed_all");
*self.link.write().await = Some(Link {
peripheral,
characteristics,
});
self.with_health(|h| h.connected = true);
Ok((notifications, central_events, id))
}
async fn send(&self, command: Command) -> Result<(), Error> {
let link = self.link.read().await;
let link = link.as_ref().ok_or(Error::Disconnected)?;
let rx = link
.characteristics
.get(&Characteristic::CommandRx)
.ok_or(Error::MissingCharacteristic("command_rx"))?;
let encoded = command.encode();
if matches!(command, Command::StreamControl { enable: true, .. }) {
self.last_start_ns.store(mono_ns(), Ordering::Relaxed);
}
let result = link
.peripheral
.write(rx, encoded.as_bytes(), WriteType::WithoutResponse)
.await;
let _ = self.raw.send(RawRecord::Write {
mono_ns: mono_ns(),
wall_ns: wall_ns(),
label: format!("{command:?}"),
bytes: encoded.as_bytes().into(),
error: result.as_ref().err().map(ToString::to_string),
});
Ok(result?)
}
async fn request(&self, command: Command) -> Result<Response, Error> {
let mut events = self.events.subscribe();
self.send(command).await?;
let opcode = command.opcode();
let timeout = self.options.command_timeout;
let response = tokio::time::timeout(timeout, async {
loop {
match events.recv().await {
Ok(Event::Packet { packet, .. }) => {
if let Packet::Response(r) = packet.as_ref()
&& r.opcode == opcode
{
return Ok(r.clone());
}
}
Ok(Event::Disconnected { .. }) | Err(broadcast::error::RecvError::Closed) => {
return Err(Error::Disconnected);
}
Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
}
}
})
.await
.map_err(|_| Error::Timeout { opcode, timeout })??;
if response.ok() {
Ok(response)
} else {
Err(Error::CommandFailed {
opcode,
status: response.status,
})
}
}
async fn run_start_sequence(&self) -> Result<(), Error> {
let now = u32::try_from(wall_ns() / 1_000_000_000).unwrap_or(u32::MAX);
let pause = Duration::from_millis(100);
match self.options.start {
StartSequence::None => return Ok(()),
StartSequence::Standard => {
if let Ok(r) = self.request(Command::GetFirmwareVersion).await
&& let Ok(ResponseBody::FirmwareVersion(v)) = r.body()
{
self.info.lock().unwrap_or_else(PoisonError::into_inner).firmware = Some(v.to_owned());
}
self.send(Command::TimeSync(now)).await?;
self.send(Command::SetPromptVolume(0)).await?;
tokio::time::sleep(pause).await;
self.send(Command::HeartRatePeriodic(true)).await?;
tokio::time::sleep(pause).await;
self.send(Command::OnConnected).await?;
self.send(Command::StreamControl {
mask: 0xff,
enable: true,
})
.await?;
tokio::time::sleep(pause).await;
}
}
if let Ok(r) = self.request(Command::GetImuCalibration).await
&& let Ok(ResponseBody::ImuCalibration { std, diff }) = r.body()
{
self.info.lock().unwrap_or_else(PoisonError::into_inner).imu_calibration = Some((std, diff));
}
self.send(Command::StartSession).await?;
self.mark("start_sequence_sent");
Ok(())
}
}
async fn supervise(
shared: Arc<Shared>,
mut notifications: Notifications,
mut central_events: CentralEvents,
mut id: PeripheralId,
to_decoder: mpsc::UnboundedSender<ToDecoder>,
) {
loop {
loop {
tokio::select! {
n = notifications.next() => {
let Some(n) = n else { break };
let (mono, wall) = (mono_ns(), wall_ns());
let Some(characteristic) = Characteristic::from_uuid(n.uuid.as_u128()) else { continue };
let bytes: Arc<[u8]> = n.value.into();
let _ = shared.raw.send(RawRecord::Notification { mono_ns: mono, wall_ns: wall, characteristic, bytes: bytes.clone() });
if to_decoder.send(ToDecoder::Notification(mono, characteristic, bytes)).is_err() {
return;
}
}
e = central_events.next() => match e {
Some(CentralEvent::DeviceDisconnected(d)) if d == id => break,
Some(_) => {}
None => break,
},
() = tokio::time::sleep(STALL) => {
let link = shared.link.read().await;
let alive = match link.as_ref() {
Some(l) => l.peripheral.is_connected().await.unwrap_or(false),
None => false,
};
if !alive { break }
}
}
}
if let Some(link) = shared.link.write().await.take() {
link.peripheral.disconnect().await.ok();
}
shared.with_health(|h| h.connected = false);
shared.mark("disconnected");
let _ = shared.events.send(Event::Disconnected { mono_ns: mono_ns() });
let Some(window) = shared
.options
.reconnect
.filter(|_| !shared.closing.load(Ordering::Relaxed))
else {
return;
};
let deadline = tokio::time::Instant::now() + window;
let mut attempt = 0u32;
loop {
if shared.closing.load(Ordering::Relaxed) {
return;
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
shared.mark("reconnect_gave_up");
let _ = shared.events.send(Event::ReconnectFailed { mono_ns: mono_ns() });
return;
}
attempt += 1;
let _ = shared.events.send(Event::Reconnecting {
mono_ns: mono_ns(),
attempt,
});
match shared.establish(remaining.min(Duration::from_secs(10))).await {
Ok((n, c, i)) => {
notifications = n;
central_events = c;
id = i;
break;
}
Err(_) => {
let backoff = Duration::from_secs(u64::from(attempt.min(5)));
tokio::time::sleep(backoff.min(deadline.saturating_duration_since(tokio::time::Instant::now())))
.await;
}
}
}
let _ = to_decoder.send(ToDecoder::Reset);
shared.with_health(|h| h.reconnects += 1);
shared.mark("reconnected");
let again = shared.clone();
tokio::spawn(async move {
again.run_start_sequence().await.ok();
let _ = again.events.send(Event::Reconnected { mono_ns: mono_ns() });
});
}
}
fn spawn_decoder(shared: Arc<Shared>) -> (mpsc::UnboundedSender<ToDecoder>, JoinHandle<()>) {
let (to_decoder, mut decoder_rx) = mpsc::unbounded_channel::<ToDecoder>();
let task = tokio::spawn(async move {
let mut decoder = Decoder::default();
let mut out = Vec::new();
while let Some(message) = decoder_rx.recv().await {
match message {
ToDecoder::Reset => decoder.reset(),
ToDecoder::StreamStart(mono) => shared.last_start_ns.store(mono, Ordering::Relaxed),
ToDecoder::ReplayEnded => {
shared.with_health(|h| h.connected = false);
shared.mark("disconnected");
let _ = shared.events.send(Event::Disconnected { mono_ns: mono_ns() });
}
ToDecoder::Notification(mono, characteristic, bytes) => {
let last_start = shared.last_start_ns.load(Ordering::Relaxed);
shared.with_health(|h| decoder.handle(mono, characteristic, &bytes, last_start, h, &mut out));
for event in out.drain(..) {
let _ = shared.events.send(event);
}
}
}
}
});
(to_decoder, task)
}
#[derive(Debug, Clone, Copy)]
pub struct ReplayOptions {
pub speed: f64,
}
impl Default for ReplayOptions {
fn default() -> Self {
Self { speed: 1.0 }
}
}
struct Replayable {
name: String,
firmware: Option<String>,
records: Vec<(i64, Recorded)>,
}
enum Recorded {
Notification(Characteristic, Arc<[u8]>),
Write {
label: String,
bytes: Arc<[u8]>,
error: Option<String>,
},
}
fn load_replayable(path: &Path) -> Result<Replayable, Error> {
let db = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
let meta = |key: &str| -> Result<Option<String>, Error> {
let mut statement = db.prepare("SELECT value FROM meta WHERE key = ?1")?;
let mut rows = statement.query([key])?;
Ok(match rows.next()? {
Some(row) => Some(row.get(0)?),
None => None,
})
};
let name = meta("device_name")?.unwrap_or_else(|| "FRENZ-REPLAY".to_owned());
let firmware = meta("firmware")?.filter(|f| !f.is_empty());
let mut statement = db.prepare("SELECT mono_ns, char, payload FROM notifications ORDER BY id")?;
let mut rows = statement.query([])?;
let mut records = Vec::new();
while let Some(row) = rows.next()? {
let (mono, uuid, payload): (i64, String, Vec<u8>) = (row.get(0)?, row.get(1)?, row.get(2)?);
if let Some(characteristic) = uuid::Uuid::parse_str(&uuid)
.ok()
.and_then(|u| Characteristic::from_uuid(u.as_u128()))
{
records.push((mono, Recorded::Notification(characteristic, payload.into())));
}
}
let mut statement = db.prepare("SELECT mono_ns, label, payload, error FROM writes ORDER BY id")?;
let mut rows = statement.query([])?;
while let Some(row) = rows.next()? {
let (mono, label, payload, error): (i64, String, Vec<u8>, Option<String>) =
(row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?);
records.push((
mono,
Recorded::Write {
label,
bytes: payload.into(),
error,
},
));
}
records.sort_by_key(|(mono, record)| (*mono, matches!(record, Recorded::Notification(..))));
Ok(Replayable {
name,
firmware,
records,
})
}
fn starts_streams(bytes: &[u8]) -> bool {
let start = Command::StreamControl { mask: 0, enable: true }.encode();
matches!((bytes, start.as_bytes()), ([opcode, _, enable], [start_opcode, _, start_enable])
if opcode == start_opcode && enable == start_enable)
}
async fn replay(
shared: Arc<Shared>,
records: Vec<(i64, Recorded)>,
speed: f64,
to_decoder: mpsc::UnboundedSender<ToDecoder>,
) {
shared.subscribed.notified().await;
let paced = speed.is_finite() && speed > 0.0;
let started = tokio::time::Instant::now();
let first = records
.iter()
.find(|(_, record)| matches!(record, Recorded::Notification(..)))
.map_or(0, |(mono, _)| *mono);
for (recorded, record) in records {
if shared.closing.load(Ordering::Relaxed) {
return;
}
if paced {
let offset = Duration::from_secs_f64((recorded - first).max(0) as f64 / 1e9 / speed);
tokio::time::sleep_until(started + offset).await;
} else {
tokio::task::yield_now().await;
}
let (mono, wall) = (mono_ns(), wall_ns());
let (characteristic, bytes) = match record {
Recorded::Notification(characteristic, bytes) => (characteristic, bytes),
Recorded::Write { label, bytes, error } => {
if starts_streams(&bytes) && to_decoder.send(ToDecoder::StreamStart(mono)).is_err() {
return;
}
let _ = shared.raw.send(RawRecord::Write {
mono_ns: mono,
wall_ns: wall,
label,
bytes,
error,
});
continue;
}
};
let _ = shared.raw.send(RawRecord::Notification {
mono_ns: mono,
wall_ns: wall,
characteristic,
bytes: bytes.clone(),
});
if to_decoder
.send(ToDecoder::Notification(mono, characteristic, bytes))
.is_err()
{
return;
}
}
let _ = to_decoder.send(ToDecoder::ReplayEnded);
}
pub struct Band {
shared: Arc<Shared>,
tasks: Vec<JoinHandle<()>>,
initial_raw: Mutex<Option<broadcast::Receiver<RawRecord>>>,
}
impl Band {
pub async fn connect(name: &str, options: ConnectOptions) -> Result<Self, Error> {
let scan_timeout = options.scan_timeout;
let (shared, initial_raw) = Shared::new(name, options);
let (notifications, central_events, id) = shared.establish(scan_timeout).await?;
let (to_decoder, decoder) = spawn_decoder(shared.clone());
let mut tasks = vec![decoder];
tasks.push(tokio::spawn(supervise(
shared.clone(),
notifications,
central_events,
id,
to_decoder,
)));
let band = Self {
shared,
tasks,
initial_raw: Mutex::new(Some(initial_raw)),
};
band.shared.run_start_sequence().await?;
Ok(band)
}
pub async fn replay(recording: impl AsRef<Path>, options: ReplayOptions) -> Result<Self, Error> {
let path = recording.as_ref().to_path_buf();
let loaded = tokio::task::spawn_blocking(move || load_replayable(&path))
.await
.map_err(std::io::Error::other)??;
let (shared, initial_raw) = Shared::new(
&loaded.name,
ConnectOptions {
reconnect: None,
start: StartSequence::None,
..ConnectOptions::default()
},
);
shared.info.lock().unwrap_or_else(PoisonError::into_inner).firmware = loaded.firmware;
shared.with_health(|h| h.connected = true);
shared.last_start_ns.store(mono_ns(), Ordering::Relaxed);
shared.mark("connected");
let (to_decoder, decoder) = spawn_decoder(shared.clone());
let player = tokio::spawn(replay(shared.clone(), loaded.records, options.speed, to_decoder));
Ok(Self {
shared,
tasks: vec![decoder, player],
initial_raw: Mutex::new(Some(initial_raw)),
})
}
pub fn info(&self) -> BandInfo {
self.shared.info.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
pub fn health(&self) -> Health {
self.shared.with_health(|h| h.clone())
}
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
let receiver = self.shared.events.subscribe();
self.shared.subscribed.notify_one();
receiver
}
pub fn subscribe_raw(&self) -> broadcast::Receiver<RawRecord> {
let receiver = self.shared.raw.subscribe();
self.shared.subscribed.notify_one();
receiver
}
pub fn subscribe_raw_from_start(&self) -> broadcast::Receiver<RawRecord> {
let receiver = self
.initial_raw
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
.unwrap_or_else(|| self.shared.raw.subscribe());
self.shared.subscribed.notify_one();
receiver
}
pub fn mark(&self, label: &str) {
self.shared.mark(label);
}
pub async fn send(&self, command: Command) -> Result<(), Error> {
self.shared.send(command).await
}
pub async fn request(&self, command: Command) -> Result<Response, Error> {
self.shared.request(command).await
}
pub async fn battery(&self) -> Result<u8, Error> {
match self.request(Command::GetBattery).await?.body() {
Ok(ResponseBody::Battery(p)) => Ok(p),
_ => Err(Error::CommandFailed {
opcode: 0x02,
status: 0xff,
}),
}
}
pub async fn stop(mut self) -> Result<Health, Error> {
self.shared.closing.store(true, Ordering::Relaxed);
if self.health().connected {
self.send(Command::StreamControl {
mask: 0xff,
enable: false,
})
.await
.ok();
tokio::time::sleep(Duration::from_millis(100)).await;
self.send(Command::EndSession).await.ok();
tokio::time::sleep(Duration::from_millis(500)).await;
self.mark("stop_sequence_sent");
if let Some(link) = self.shared.link.write().await.take() {
link.peripheral.disconnect().await.ok();
}
}
tokio::time::sleep(Duration::from_millis(200)).await;
for task in self.tasks.drain(..) {
task.abort();
}
Ok(self.health())
}
}
impl Drop for Band {
fn drop(&mut self) {
self.shared.closing.store(true, Ordering::Relaxed);
for task in &self.tasks {
task.abort();
}
}
}