feat(buf): implement SoftSerial traits for HalfDuplexSerial with RingBuffer

This commit is contained in:
doryan 2025-05-22 21:52:03 +04:00
parent 7cbbe955bb
commit b72be2fc3b

View File

@ -14,6 +14,8 @@ use avr_device::asm::delay_cycles;
use static_pins::StaticPinOps;
mod structures;
pub type PollResult = Result<(), PollError>;
pub type ReadByteResult = Result<u8, CorruptedData>;
pub type CorruptedData = (u8, u8);
@ -107,56 +109,20 @@ pub trait SoftSerialWriter<P, T>
where
P: PinOps + StaticPinOps,
{
#[inline(never)]
fn write_byte(&self, data: u8) {
let (mut data, mut parity_bit) = (data, 0);
for _ in 0..8 {
if data & MSB == 0 {
P::set_high();
parity_bit ^= 0;
} else {
P::set_low();
parity_bit ^= 1;
}
delay_us(SERIAL_DELAY);
data <<= 1;
}
// Hamming code and CRC are very weightful and slow, so I use simple parity check
if parity_bit == 0 {
P::set_high();
} else {
P::set_low();
}
delay_us(SERIAL_DELAY);
}
fn write_byte(&self, data: u8);
fn write_bytes(&self, transmit_data: T);
}
impl<P> SoftSerialWriter<P, &[u8]> for HalfDuplexSerial<P>
where
P: PinOps + StaticPinOps,
{
fn write_bytes(&self, transmit_data: &[u8]) {
for byte in transmit_data {
self.write_byte(*byte);
self.sync_transmitter();
}
}
}
pub trait SoftSerialReader<P, T>
where
P: PinOps + StaticPinOps,
{
#[inline(never)]
fn read_byte(&self) -> ReadByteResult {
fn read_byte(&self) -> ReadByteResult;
fn read_bytes(&self, recieve_data: T);
}
#[inline(always)]
pub(crate) fn _priv_read_byte<P: PinOps + StaticPinOps>() -> ReadByteResult {
let (mut data, mut reciever_parity_bit) = (0, 0);
delay_cycles(FIRST_ENTRY_READING);
@ -191,16 +157,64 @@ where
Ok(data)
}
fn read_bytes(&self, recieve_data: T);
#[inline(always)]
pub(crate) fn _priv_write_bytes<P: PinOps + StaticPinOps>(data: u8) {
let (mut data, mut parity_bit) = (data, 0);
for _ in 0..8 {
if data & MSB == 0 {
P::set_high();
parity_bit ^= 0;
} else {
P::set_low();
parity_bit ^= 1;
}
delay_us(SERIAL_DELAY);
data <<= 1;
}
// Hamming code and CRC are very weightful and slow, so I use simple parity check
if parity_bit == 0 {
P::set_high();
} else {
P::set_low();
}
delay_us(SERIAL_DELAY);
}
impl<P> SoftSerialWriter<P, &[u8]> for HalfDuplexSerial<P>
where
P: PinOps + StaticPinOps,
{
#[inline(never)]
fn write_byte(&self, data: u8) {
_priv_write_bytes::<P>(data);
}
fn write_bytes(&self, transmit_data: &[u8]) {
for byte in transmit_data {
<Self as SoftSerialWriter<P, &[u8]>>::write_byte(self, *byte);
self.sync_transmitter();
}
}
}
impl<P> SoftSerialReader<P, &mut [u8]> for HalfDuplexSerial<P>
where
P: PinOps + StaticPinOps,
{
#[inline(never)]
fn read_byte(&self) -> ReadByteResult {
_priv_read_byte::<P>()
}
fn read_bytes(&self, recieve_data: &mut [u8]) {
for byte in recieve_data {
if let Ok(data) = self.read_byte() {
if let Ok(data) = <Self as SoftSerialReader<P, &mut [u8]>>::read_byte(self) {
*byte = data;
}
self.sync_reciever();