Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

trying to prettify the logging output #12

Merged
merged 4 commits into from
May 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ tokio = { version = "1.12.0", features = [
"io-util",
] }
nfc-stream = { git = "https://github.com/kalkspace/nfc-stream-rs.git" }
tracing = "0.1.38"
tracing-subscriber = "0.3.17"
21 changes: 12 additions & 9 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ use bluez_async::{
use futures_util::StreamExt;
use std::{future::Future, sync::Arc};
use tokio::sync::mpsc;
use tracing::{debug, info};

use crate::command::Command;

#[derive(Debug)]
pub struct Client {
session: Arc<BluetoothSession>,
device: DeviceInfo,
Expand All @@ -33,12 +35,12 @@ impl UnconnectedClient {
pub async fn connect(self) -> Result<Client, anyhow::Error> {
let (_, sess) = BluetoothSession::new().await?;

println!("looking for device");
info!("looking for device");
let device = self.discover_device(&sess).await?;
println!("found my device: {:?}", device);
info!("found my device: {:?}", device);

retry(5, || sess.connect(&device.id)).await?;
println!("connected!");
info!("connected!");

Ok(Client {
session: Arc::new(sess),
Expand All @@ -56,20 +58,20 @@ impl UnconnectedClient {
let device = match device {
Some(dev) => dev,
None => {
println!("starting to scan...");
info!("starting to scan...");
sess.start_discovery().await?;

let events = sess.event_stream().await?;
let info = events
.filter_map(|ev| {
println!("got event: {:?}", ev);
info!("got even: {:?}", ev);
Box::pin(async {
if let BluetoothEvent::Device {
event: DeviceEvent::Discovered,
id,
} = ev
{
println!("Discovered {}", id);
info!("Discovered {}", id);
let info = sess.get_device_info(&id).await.unwrap();
if info.mac_address == self.mac_addr {
return Some(info);
Expand Down Expand Up @@ -127,21 +129,22 @@ impl Client {
.into_iter()
.find(|c| c.uuid.to_string() == characteristic_id)
.ok_or_else(|| anyhow!("characteristic not found"))?;
println!("characteristic found: {:?}", characteristic);

debug!("characteristic found: {:?}", characteristic);

let mut events = self.session.event_stream().await?;
let (gdio_tx, gdio_rx) = mpsc::channel(100);
let bg_characteristic_id = characteristic.id.clone();
tokio::spawn(async move {
while let Some(event) = events.next().await {
println!("Got event: {:?}", event);
debug!("Got event: {:?}", event);
if let BluetoothEvent::Characteristic {
event: CharacteristicEvent::Value { value },
id,
} = event
{
if id == bg_characteristic_id {
println!("Value: {:02X?}", value);
debug!("Value: {:02X?}", value);
if gdio_tx.send(value).await.is_err() {
eprintln!("failed to send into channel!");
}
Expand Down
7 changes: 4 additions & 3 deletions src/encrypted.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::anyhow;
use sodiumoxide::crypto::box_::{gen_nonce, open_precomputed, seal_precomputed, Nonce};
use tracing::info;

use crate::{client::CharacteristicClient, command::Command, pairing::AuthInfo};

Expand All @@ -15,7 +16,7 @@ impl AuthenticatedClient {

pub async fn write(&self, command: Command) -> Result<(), anyhow::Error> {
let payload = command.into_bytes_with_auth(self.auth_info.authorization_id);
println!("sending plaintext: {:02X?}", payload);
info!("sending plaintext: {:02X?}", payload);

let nonce = gen_nonce();
let ciphertext = seal_precomputed(&payload, &nonce, &self.auth_info.shared_key);
Expand All @@ -26,7 +27,7 @@ impl AuthenticatedClient {
let ciphertext_len = (ciphertext.len() as u16).to_le_bytes();
message.extend_from_slice(&ciphertext_len);
message.extend_from_slice(&ciphertext);
println!("sending full message: {:02X?}", message);
info!("sending full message: {:02X?}", message);

self.client.write_raw(message).await?;

Expand All @@ -45,7 +46,7 @@ impl AuthenticatedClient {
let decrypted_bytes = open_precomputed(encrypted_bytes, &nonce, &self.auth_info.shared_key)
.map_err(|_| anyhow!("Failed to decrypt message"))?;

println!("received plaintext: {:02X?}", decrypted_bytes);
info!("received plaintext: {:02X?}", decrypted_bytes);

let (cmd, _auth_id) = Command::parse_with_auth(&decrypted_bytes)?;

Expand Down
3 changes: 2 additions & 1 deletion src/keyturner.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::convert::TryInto;

use anyhow::anyhow;
use tracing::info;

use crate::{
client::Client,
Expand Down Expand Up @@ -71,7 +72,7 @@ impl Keyturner {
Command::Status(command::StatusCode::Complete) => break,
Command::ErrorReport { code, .. } => return Err(code.into()),
Command::KeyturnerStates(state) => {
println!("KeyturnerState: {:?}", state);
info!("KeyturnerState: {:?}", state);
last_state = state;
}
_ => return Err(anyhow!("Unexpected command")),
Expand Down
11 changes: 8 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use keyturner::Keyturner;
use pairing::{AuthInfo, PairingClient};
use serde::Deserialize;
use tokio::fs::read_to_string;
use tracing::info;

use crate::client::UnconnectedClient;

Expand All @@ -27,8 +28,12 @@ struct Config {
card_ids: Vec<[u8; 4]>,
}

// only log error cases, if you're going to ignore the error otherwise
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
tracing_subscriber::fmt::init();

info!("test log zum testen");
let config = read_to_string("config.json").await?;
let config: Config = serde_json::from_str(&config)?;

Expand All @@ -48,7 +53,7 @@ async fn main() -> Result<(), anyhow::Error> {
loop {
let item = stream.next().await;

println!("{:?}", item);
info!("{:?}", item);

let Some(item) = item else {
// We expect the item to always be Some because the Stream is never closed
Expand All @@ -72,7 +77,7 @@ async fn main() -> Result<(), anyhow::Error> {
command::LockState::Locked => LockAction::Unlock,
command::LockState::Unlocked => LockAction::Lock,
state => {
println!("Unable to perform action. Invalid state: {:?}", state);
info!("Unable to perform action. Invalid state: {:?}", state);
continue;
}
};
Expand All @@ -82,7 +87,7 @@ async fn main() -> Result<(), anyhow::Error> {
// We drain the stream to prevent accidental duplicate actions
while futures_util::poll!(stream.next()).is_ready() {}
} else {
println!("Unknown ID");
info!("Unknown ID");
}
}
}
Expand Down
Loading