mod packet_bytes_parser;
mod packet_filter;
use super::ms;
use self::{
packet_bytes_parser::PacketBytesParser,
packet_filter::{Filter, RegistrationError},
};
use super::Packet;
pub struct Receiver {
packet_filter: Filter,
packet_bytes_parser: PacketBytesParser,
}
enum ReceiverError {
PacketDuplication,
DuplicationFilterOverloaded,
}
impl Receiver {
pub fn new() -> Receiver {
Receiver {
packet_filter: Filter::new(),
packet_bytes_parser: PacketBytesParser::new(),
}
}
fn filter_out_duplicated(
&mut self,
packet: Packet,
current_time: ms,
) -> Result<Packet, ReceiverError> {
match self
.packet_filter
.filter_out_duplicated(packet, current_time)
{
Err(RegistrationError::DuplicationFound) => {
return Err(ReceiverError::PacketDuplication);
}
Err(RegistrationError::RegistrationLimitExceeded) => {
return Err(ReceiverError::DuplicationFilterOverloaded);
}
Ok(packet) => Ok(packet),
}
}
pub fn update<I>(&mut self, current_time: ms, interface_driver: &mut I)
where
I: embedded_serial::MutNonBlockingRx + embedded_serial::MutBlockingTx,
{
self._receive_byte(interface_driver);
self.packet_filter.update(current_time);
}
pub fn receive(&mut self, current_time: ms) -> Option<Packet> {
let packet = match self.packet_bytes_parser.get_packet() {
None => return None,
Some(packet) => packet,
};
let packet = match self.filter_out_duplicated(packet, current_time) {
Err(_) => return None,
Ok(packet) => packet,
};
Some(packet)
}
fn _receive_byte<I>(&mut self, interface_driver: &mut I)
where
I: embedded_serial::MutNonBlockingRx + embedded_serial::MutBlockingTx,
{
if let Ok(red_byte_option) = interface_driver.getc_try() {
if let Some(red_byte) = red_byte_option {
self.packet_bytes_parser.push_byte(red_byte);
}
}
}
}