Skip to content

Commit

Permalink
feat: create a prettier and easier to edit config file
Browse files Browse the repository at this point in the history
  • Loading branch information
DASPRiD committed Feb 11, 2024
1 parent 54cd4ca commit 9c9c93f
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 20 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ tokio-io-timeout = "1.2.0"
thiserror = "1.0.37"
futures-util = "0.3.24"
glob = "0.3.0"
hex = "0.4.3"
hex = { version = "0.4.3", features = ["serde"] }
linux-embedded-hal = "0.3.2"
embedded-hal = "0.2.7"
rodio = { version = "0.17.1", features = ["symphonia-mp3"] }
Expand Down
45 changes: 41 additions & 4 deletions src/nfc/reader.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,47 @@
use anyhow::{anyhow, Result};
use hex::{decode_to_slice, encode, FromHex, FromHexError};
use mfrc522::comm::Interface;
use mfrc522::{Initialized, Mfrc522};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::nfc::ndef::{parse_ndef_text_record, NdefMessageParser};

pub type Uid = [u8; 7];
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct NfcUid([u8; 7]);

impl NfcUid {
pub fn as_bytes(&self) -> &[u8; 7] {
&self.0
}
}

impl<'de> Deserialize<'de> for NfcUid {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(Self(hex::deserialize(deserializer)?))
}
}

impl Serialize for NfcUid {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Ok(serializer.serialize_str(&encode(&self.0))?)
}
}

impl FromHex for NfcUid {
type Error = FromHexError;

fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
let mut out = Self([0; 7]);
decode_to_slice(hex, &mut out.0 as &mut [u8])?;
Ok(out)
}
}

pub struct NfcReader<COMM: Interface> {
mfrc522: Mfrc522<COMM, Initialized>,
Expand All @@ -15,7 +52,7 @@ impl<E, COMM: Interface<Error = E>> NfcReader<COMM> {
Self { mfrc522 }
}

pub fn select_target(&mut self) -> Option<Uid> {
pub fn select_target(&mut self) -> Option<NfcUid> {
let atqa = match self.mfrc522.reqa() {
Ok(atqa) => atqa,
Err(_) => return None,
Expand All @@ -26,15 +63,15 @@ impl<E, COMM: Interface<Error = E>> NfcReader<COMM> {
Err(_) => return None,
};

let mut uid: Uid = [0; 7];
let mut uid: [u8; 7] = [0; 7];

match raw_uid {
mfrc522::Uid::Single(raw_uid) => uid[0..4].copy_from_slice(raw_uid.as_bytes()),
mfrc522::Uid::Double(raw_uid) => uid.copy_from_slice(raw_uid.as_bytes()),
mfrc522::Uid::Triple(raw_uid) => uid.copy_from_slice(&raw_uid.as_bytes()[0..7]),
}

Some(uid)
Some(NfcUid(uid))
}

pub fn check_for_release(&mut self) -> bool {
Expand Down
4 changes: 2 additions & 2 deletions src/nfc/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;

use crate::nfc::reader::{NfcReader, Uid};
use crate::nfc::reader::{NfcReader, NfcUid};

#[derive(Debug)]
pub enum NfcCommand {
Poll {
responder: oneshot::Sender<Uid>,
responder: oneshot::Sender<NfcUid>,
cancel_rx: oneshot::Receiver<()>,
},
Read {
Expand Down
10 changes: 5 additions & 5 deletions src/subsystems/config_manager.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};

use crate::nfc::reader::Uid;
use crate::nfc::reader::NfcUid;
use anyhow::{Error, Result};
use log::info;
use serde::{Deserialize, Serialize};
Expand All @@ -26,18 +26,18 @@ pub struct VolumeConfig {

#[derive(Clone, Deserialize, Serialize)]
pub struct Config {
pub config_uids: Vec<Uid>,
pub config_uids: Vec<NfcUid>,
pub connection: Option<ConnectionConfig>,
pub volume: VolumeConfig,
}

#[derive(Debug)]
pub enum ConfigCommand {
GetConfigUids {
responder: oneshot::Sender<Vec<Uid>>,
responder: oneshot::Sender<Vec<NfcUid>>,
},
SetConfigUids {
config_uids: Vec<Uid>,
config_uids: Vec<NfcUid>,
responder: oneshot::Sender<()>,
},
GetVolume {
Expand Down Expand Up @@ -131,7 +131,7 @@ impl ConfigManager {
}

async fn store_config(&self, config: &Config) -> Result<()> {
let toml_config = toml::to_string(&config)?;
let toml_config = toml::to_string_pretty(&config)?;
let mut file = File::create(&self.config_path).await?;
file.write_all(toml_config.as_bytes()).await?;
Ok(())
Expand Down
8 changes: 4 additions & 4 deletions src/subsystems/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use tokio::sync::oneshot;
use tokio::time::sleep;
use tokio_graceful_shutdown::{IntoSubsystem, SubsystemHandle};

use crate::nfc::reader::Uid;
use crate::nfc::reader::NfcUid;
use crate::nfc::thread::{start_nfc_listener, NfcCommand};
use crate::subsystems::audio_player::PlayerCommand;
use crate::subsystems::config_manager::{ConfigCommand, ConnectionConfig};
Expand Down Expand Up @@ -203,8 +203,8 @@ impl Controller {

async fn process_config_command(
&mut self,
uid: Uid,
config_uids: &mut Vec<Uid>,
uid: NfcUid,
config_uids: &mut Vec<NfcUid>,
nfc: mpsc::Sender<NfcCommand>,
) -> Result<bool> {
let (value_tx, value_rx) = oneshot::channel();
Expand Down Expand Up @@ -302,7 +302,7 @@ impl Controller {

async fn add_config_uid(
&mut self,
config_uids: &mut Vec<Uid>,
config_uids: &mut Vec<NfcUid>,
nfc: mpsc::Sender<NfcCommand>,
) -> Result<()> {
self.led.send(LedState::Blink { color: MAGENTA }).await?;
Expand Down
8 changes: 4 additions & 4 deletions src/subsystems/networker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use tokio_rustls::client::TlsStream;
use tokio_rustls::rustls::{self, ClientConfig, OwnedTrustAnchor};
use tokio_rustls::TlsConnector;

use crate::nfc::reader::Uid;
use crate::nfc::reader::NfcUid;
use crate::subsystems::config_manager::{ConfigCommand, ConnectionConfig};
use crate::utils::skip_certificate_verification::SkipCertificateVerification;

Expand Down Expand Up @@ -56,7 +56,7 @@ pub enum NetworkerCommand {
connection_config: ConnectionConfig,
},
CheckUid {
uid: Uid,
uid: NfcUid,
responder: oneshot::Sender<CheckUidResponse>,
},
GetAudio {
Expand Down Expand Up @@ -235,11 +235,11 @@ impl Networker {
TlsConnector::from(Arc::new(client_config))
}

async fn check_uid(&mut self, uid: &Uid) -> Result<CheckUidResponse> {
async fn check_uid(&mut self, uid: &NfcUid) -> Result<CheckUidResponse> {
let stream = self.maybe_stream.as_mut().unwrap();

stream.write_u8(0x00).await?;
stream.write_all(uid).await?;
stream.write_all(uid.as_bytes()).await?;

let result = stream.read_u8().await?;

Expand Down

0 comments on commit 9c9c93f

Please sign in to comment.