use crate::data_messages::*;
use crate::receive_error::*;
use std::fmt;
use std::mem::size_of;
#[repr(C)]
#[derive(Clone, Copy)]
pub struct ButtonMessage {
pub timestamp: u64,
pub state: f32,
}
impl Default for ButtonMessage {
fn default() -> Self {
Self {
timestamp: 0,
state: 0.0,
}
}
}
impl DataMessage for ButtonMessage {
fn get_ascii_id() -> u8 {
b'O'
}
fn parse_ascii(message: &str) -> Result<Self, ReceiveError> {
match scan_fmt!(message, "{},{d},{f}\n", char, u64, f32) {
Ok((_, timestamp, state)) => Ok(Self {
timestamp,
state,
}),
Err(_) => Err(ReceiveError::UnableToParseAsciiMessage),
}
}
fn parse_binary(message: &[u8]) -> Result<Self, ReceiveError> {
#[repr(C, packed)]
struct BinaryMessage {
_id: u8,
timestamp: u64,
state: f32,
_termination: u8,
}
if message.len() != size_of::<BinaryMessage>() {
return Err(ReceiveError::InvalidBinaryMessageLength);
}
let binary_message = unsafe {
let ref binary_message = *(message.as_ptr() as *const BinaryMessage);
binary_message
};
Ok(Self {
timestamp: binary_message.timestamp,
state: binary_message.state,
})
}
fn get_csv_file_name(&self) -> &'static str {
"Button.csv"
}
fn get_csv_headings(&self) -> &'static str {
"Timestamp (us),State\n"
}
fn to_csv_row(&self) -> String {
format!("{},{:.6}\n", self.timestamp, self.state)
}
}
impl fmt::Display for ButtonMessage {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{:>8} us {:>8.3}", self.timestamp, self.state)
}
}