Skip to content

Commit

Permalink
update lib versions and minor code changes
Browse files Browse the repository at this point in the history
  • Loading branch information
blandger committed Jan 12, 2025
1 parent b322b39 commit 28524c2
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 56 deletions.
23 changes: 12 additions & 11 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ members = [
"handler",
"examples/connect",
"examples/battery_level",
"examples/async_trait_update",
]
resolver = "2"

Expand All @@ -16,19 +17,19 @@ edition = "2021"
repository = "https://github.com/blandger/mielophone"

[workspace.dependencies]
btleplug = { version = "0.11.5", features = ["serde"] }
btleplug = { version = "0.11.7", features = ["serde"] }
#btleplug = { path = "../btleplug-blandger" }
tokio = { version = "1.36.0", features = ["full"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
async-trait = "0.1.77"
futures = "0.3.30"
tokio = { version = "1.42.0", features = ["full"] }
tokio-stream = { version = "0.1.14", features = ["sync"] }
uuid = "1.7.0"
thiserror = "1.0.56"
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
async-trait = "0.1.83"
futures = "0.3.31"
uuid = "1.11"
thiserror = "2.0.9"

color-eyre = "0.6.2"
chrono = "0.4.33"
color-eyre = "0.6.3"
chrono = "0.4.39"

#[build]
#rustflags = ["-C", "link-args=-gz"] #zip debug data
#rustflags = ["-C", "link-args=-gz"] #zip debug data
27 changes: 14 additions & 13 deletions brainbit/src/bbit/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::bbit::uuids::WRITE_COMMAN_UUID;
use crate::{find_characteristic, Error};
use btleplug::api::{Characteristic, Peripheral as _, WriteType};
use btleplug::platform::Peripheral;
use tracing::debug;

/// Struct that has access to command point.
#[derive(Debug, PartialEq, Eq)]
Expand All @@ -20,7 +21,7 @@ impl ControlPoint {

/// Send command to [`ControlPoint`] waiting for a response from device.
pub async fn send_command(&self, device: &Peripheral, data: &[u8]) -> BBitResult<()> {
tracing::debug!("Send command to sensor: {:02X?}", data);
debug!("Send command to sensor: {:02X?}", data);
self.write(device, data).await?;
Ok(())
}
Expand All @@ -31,11 +32,11 @@ impl ControlPoint {
device: &Peripheral,
command: ControlPointCommand,
) -> BBitResult<()> {
tracing::debug!("Send control enum command to sensor: {command:?}");
debug!("Send control enum command to sensor: {command:?}");
let command_as_bytes: Vec<u8> =
<ControlPointCommand as TryInto<Vec<u8>>>::try_into(command).unwrap();
self.write(device, command_as_bytes.as_slice()).await?;
tracing::debug!(
debug!(
"Written control enum command to sensor: {:02X?}",
command_as_bytes
);
Expand All @@ -44,7 +45,7 @@ impl ControlPoint {

/// Send command to [`ControlPoint`] without a response.
async fn write(&self, device: &Peripheral, data: &[u8]) -> BBitResult<()> {
tracing::debug!("Write data command to sensor: {:02X?}", data);
debug!("Write data command to sensor: {:02X?}", data);
device
.write(&self.control_point, data, WriteType::WithResponse)
.await
Expand Down Expand Up @@ -165,27 +166,27 @@ mod tests {
];
let command =
ControlPointCommand::new(ControlCommandType::StartResist, Some(Vec::from(cmd_data)));
tracing::debug!("source = {command:?}");
debug!("source = {command:?}");

let expected: [u8; 8] = [0x03, 0x91, 0x48, 0x48, 0x48, 0x00, 0x00, 0x00];
tracing::debug!("expected = {command:?}");
debug!("expected = {command:?}");
let command_as_bytes: Vec<u8> =
<ControlPointCommand as TryInto<Vec<u8>>>::try_into(command).unwrap();
tracing::debug!("commands as bytes = {:?}", &command_as_bytes);
debug!("commands as bytes = {:?}", &command_as_bytes);

assert_eq!(&expected, command_as_bytes.as_slice())
}

#[test]
fn test_stop_command() {
let command = ControlPointCommand::new(ControlCommandType::StopAll, None);
tracing::debug!("source = {command:?}");
debug!("source = {command:?}");

let expected: [u8; 1] = [0x01];
tracing::debug!("expected = {command:?}");
debug!("expected = {command:?}");
let command_as_bytes: Vec<u8> =
<ControlPointCommand as TryInto<Vec<u8>>>::try_into(command).unwrap();
tracing::debug!("commands as bytes = {:?}", &command_as_bytes);
debug!("commands as bytes = {:?}", &command_as_bytes);

assert_eq!(&expected, command_as_bytes.as_slice())
}
Expand All @@ -197,13 +198,13 @@ mod tests {
ControlCommandType::StartEegSignal,
Some(Vec::from(cmd_data)),
);
tracing::debug!("source = {command:?}");
debug!("source = {command:?}");

let expected: [u8; 5] = [0x02, 0x00, 0x00, 0x00, 0x00];
tracing::debug!("expected = {command:?}");
debug!("expected = {command:?}");
let command_as_bytes: Vec<u8> =
<ControlPointCommand as TryInto<Vec<u8>>>::try_into(command).unwrap();
tracing::debug!("commands as bytes = {:?}", &command_as_bytes);
debug!("commands as bytes = {:?}", &command_as_bytes);

assert_eq!(&expected, command_as_bytes.as_slice())
}
Expand Down
42 changes: 21 additions & 21 deletions brainbit/src/bbit/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use btleplug::{
};
use futures::stream::StreamExt;
use tokio::sync::{mpsc, oneshot, watch};
use tracing::instrument;
use tracing::{debug, instrument};
use uuid::Uuid;

use crate::bbit::control::{ControlCommandType, ControlPoint, ControlPointCommand};
Expand Down Expand Up @@ -81,7 +81,7 @@ impl BBitSensor<Bluetooth> {
tokio::time::sleep(Duration::from_secs(2)).await;
}
Ok(_) => {
tracing::debug!("BLE '{device_name}' is connected...");
debug!("BLE '{device_name}' is connected...");
}
}
}
Expand Down Expand Up @@ -163,7 +163,7 @@ impl BBitSensor<Bluetooth> {
/// Try to connect to a device. Implements the [`crate::BleSensor::connect`] function
#[instrument(skip(self))]
async fn try_connect(&mut self, device_name: &str) -> BBitResult<()> {
tracing::debug!("trying to connect to '{device_name}'...");
debug!("trying to connect to '{device_name}'...");
let adapters = self
.ble_manager
.adapters()
Expand All @@ -174,7 +174,7 @@ impl BBitSensor<Bluetooth> {
return Err(Error::NoBleAdaptor);
};

tracing::debug!("Start scanning for 2 sec...");
debug!("Start scanning for 2 sec...");
let mut scan_filter = ScanFilter::default();
scan_filter.services.push(NSS2_SERVICE_UUID);
central.start_scan(scan_filter).await?;
Expand All @@ -197,10 +197,10 @@ impl BBitSensor<Bluetooth> {
tracing::warn!("Device '{device_name}' is not found !");
return Err(Error::NoDevice);
};
tracing::debug!("BLE '{device_name}' is found, try to connect...");
debug!("BLE '{device_name}' is found, try to connect...");

device.connect().await?;
tracing::debug!("Try to discover...");
debug!("Try to discover...");
device.discover_services().await?;

let controller = ControlPoint::new(device).await?;
Expand Down Expand Up @@ -244,11 +244,11 @@ impl BBitSensor<Configure> {
);
self.stop_measurement().await?;
if self.level.eeg_rate {
tracing::debug!("Will subscribe to Resist event...");
debug!("Will subscribe to Resist event...");
self.subscribe(EventType::EegOrResistance.into()).await?;
}
if self.level.device_status {
tracing::debug!("Will subscribe to DeviceStatus event...");
debug!("Will subscribe to DeviceStatus event...");
self.subscribe_device_status_change().await?;
}

Expand Down Expand Up @@ -301,7 +301,7 @@ impl BBitSensor<EventLoop> {
while let Some(data) = notification_stream.next().await {
tracing::trace!("loop - received bluetooth data: {:02X?}", data);
if *pause_rx.borrow() {
tracing::debug!("loop paused: ignoring data all data");
debug!("loop paused: ignoring data all data");
continue;
}
if data.uuid == NotifyUuid::DeviceStateChange.into() {
Expand All @@ -315,7 +315,7 @@ impl BBitSensor<EventLoop> {
};
}
Err(error) => {
tracing::debug!("Error receiving Device Status data: {error:?}");
debug!("Error receiving Device Status data: {error:?}");
}
}
} else if data.uuid == NotifyUuid::EegOrResistanceMeasurementChange.into() {
Expand Down Expand Up @@ -343,30 +343,30 @@ impl BBitSensor<EventLoop> {
// either BLE messages or commands comes
tokio::select! {
Some(data) = bt_rx.recv() => {
tracing::debug!("received bt channel message: {:02X?}", data);
debug!("received bt channel message: {:02X?}", data);
use BluetoothEvent::*;
match data {
DeviceStatus(status_data) => handler.device_status_update(status_data).await,
EggOrResistanceData(eeg_data) => handler.eeg_update(eeg_data).await,
}
}
Some(event) = event_rx.recv() => {
tracing::debug!("received event: {:02x?}", event);
debug!("received event: {:02x?}", event);
match event {
BleDeviceEvent::Stop => {
let res = event_sensor.stop_measurement().await;
tracing::debug!("Stop Signal?: {res:?}");
debug!("Stop Signal?: {res:?}");
break;
},
BleDeviceEvent::StartSignal{ret} => {
let res = event_sensor.start_measurement(MeasurementType::Eeg).await;
tracing::debug!("Started Signal Measurement?: {res:?}");
debug!("Started Signal Measurement?: {res:?}");
let _ = ret.send(res);
},
BleDeviceEvent::StartResistance{channel_type, ret} => {
let res = event_sensor.start_measurement(
MeasurementType::Resistance(channel_type)).await;
tracing::debug!("Started Resists Measurement?: {res:?}");
debug!("Started Resists Measurement?: {res:?}");
let _ = ret.send(res);
},
}
Expand Down Expand Up @@ -395,7 +395,7 @@ impl<L: Level + Connected> BBitSensor<L> {
.ok_or(Error::CharacteristicNotFound)?;

device.subscribe(&characteristic).await?;
tracing::debug!("DONE, subscribed to stream of '{:?}' type", notify_stream);
debug!("DONE, subscribed to stream of '{:?}' type", notify_stream);
Ok(())
}

Expand All @@ -411,7 +411,7 @@ impl<L: Level + Connected> BBitSensor<L> {
.ok_or(Error::CharacteristicNotFound)?;

device.unsubscribe(&characteristic).await?;
tracing::debug!(
debug!(
"DONE, unsubscribed from stream of '{:?}' type",
notify_stream
);
Expand Down Expand Up @@ -460,7 +460,7 @@ impl<L: Level + Connected> BBitSensor<L> {
);
let _ = self.device_info.set(device_info);
}
tracing::debug!("device info: '{:?}'", self.device_info.get());
debug!("device info: '{:?}'", self.device_info.get());
Ok(self.device_info.get().unwrap().clone())
}

Expand Down Expand Up @@ -496,7 +496,7 @@ impl<L: Level + Connected> BBitSensor<L> {
/// Stop any type of possible measurement
#[instrument(skip(self))]
async fn stop_measurement(&self) -> BBitResult<()> {
tracing::debug!("Stopping any measurement...");
debug!("Stopping any measurement...");
let controller = self.control_point.as_ref().unwrap();
let device = self.ble_device.as_ref().unwrap();
let command = ControlPointCommand::new(ControlCommandType::StopAll, None);
Expand All @@ -510,7 +510,7 @@ impl<L: Level + Connected> BBitSensor<L> {
/// returned data.
#[instrument(skip(self))]
async fn start_measurement(&self, measure_type: MeasurementType) -> BBitResult<()> {
tracing::debug!("Starting an '{measure_type:?}' measurement...");
debug!("Starting an '{measure_type:?}' measurement...");
let controller = self.control_point.as_ref().unwrap();
let device = self.ble_device.as_ref().unwrap();
let command: ControlPointCommand = match measure_type {
Expand Down Expand Up @@ -573,7 +573,7 @@ impl<L: Level + Connected> BBitSensor<L> {
controller
.send_control_command_enum(&device, command)
.await?;
tracing::debug!("DONE. Started an '{measure_type:?}' measurement");
debug!("DONE. Started an '{measure_type:?}' measurement");
Ok(())
}
}
Expand Down
17 changes: 17 additions & 0 deletions examples/async_trait_update/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "fix_async_trait"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
description = "Connect to BBit device example"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
brainbit = { version = "0.1.0", path = "../../brainbit" }
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true

color-eyre.workspace = true
chrono.workspace = true
6 changes: 6 additions & 0 deletions examples/async_trait_update/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
Ok(())
}
4 changes: 2 additions & 2 deletions examples/battery_level/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{

use async_trait::async_trait;
use tokio::sync::oneshot;
use tracing::instrument;
use tracing::{debug, instrument};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};

use brainbit::bbit::device::BBitSensor;
Expand Down Expand Up @@ -62,7 +62,7 @@ impl Handler {
impl EventHandler for Handler {
#[instrument(skip(self))]
async fn device_status_update(&self, status_data: DeviceStatusData) {
tracing::debug!("received Status: {status_data}");
debug!("received Status: {status_data}");
COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
Expand Down
14 changes: 7 additions & 7 deletions handler/src/main_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fs::File;
use std::io::Write;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use tracing::instrument;
use tracing::{debug, instrument};

use async_trait::async_trait;
use brainbit::bbit::resist::ResistState;
Expand Down Expand Up @@ -39,7 +39,7 @@ impl EventHandler for BBitHandler {
let formatted: String = time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
// formatted = formatted.replace("\'", "");
let msg = format!("{formatted:?} - {status_data}\n");
tracing::debug!(msg);
debug!(msg);
{
// write eeg data to file
let mut lock = self.output.lock().unwrap();
Expand Down Expand Up @@ -69,17 +69,17 @@ impl EventHandler for BBitHandler {
let nss2status = self.device_status.lock().unwrap().status_nss2;
match nss2status {
Nss2Status::ResistTransmission => {
tracing::debug!(msg);
debug!(msg);
let skipped_number = self.skipped_resist_records_number.load(Ordering::Relaxed);
if skipped_number > 0 {
// skip 'SKIP_FIRST_RESIST_RECORDS_NUMBER' records
tracing::debug!("Skipping = {:?} packet", skipped_number);
debug!("Skipping = {:?} packet", skipped_number);
self.decrease_skipped_resist_records_number();
return;
}
let gathered_records_number = self.get_resist_measure_records_len();
if gathered_records_number >= STORE_RESIST_RECORDS_NUMBER {
tracing::debug!(
debug!(
"Gathered = {:?} records for ch='{}'",
gathered_records_number,
self.current_chanel_number_resist_measure
Expand All @@ -89,10 +89,10 @@ impl EventHandler for BBitHandler {
}
}
Nss2Status::EegTransmission => {
tracing::debug!(msg);
debug!(msg);
}
Nss2Status::Stopped => {
tracing::debug!("Stopped device in main");
debug!("Stopped device in main");
}
_ => {}
}
Expand Down
Loading

0 comments on commit 28524c2

Please sign in to comment.