use crate::device::PulseTransmitter;
use crate::protocols::ExtendedCommand;
use crate::protocols::ExtendedProtocol;
use crate::{Channel, Result};
pub struct ExtendedRemoteController<'a, T: PulseTransmitter> {
channel: Channel,
pulse_transmitter: &'a T,
protocol: ExtendedProtocol,
}
impl<'a, T: PulseTransmitter> ExtendedRemoteController<'a, T> {
pub fn new(pulse_transmitter: &'a T, channel: Channel) -> Result<Self> {
let protocol = ExtendedProtocol::new()?;
Ok(Self {
protocol,
pulse_transmitter,
channel,
})
}
pub fn send(&mut self, cmd: ExtendedCommand) -> Result<()> {
let pulses = self.protocol.encode_cmd(self.channel, cmd)?;
self.pulse_transmitter.send_pulses(&pulses)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::device::PulseTransmitter;
use crate::protocols::Channel;
use crate::{Error, Result};
struct MockTransmitterSuccess;
impl PulseTransmitter for MockTransmitterSuccess {
fn send_pulses(&self, pulses: &[u32]) -> Result<()> {
assert!(!pulses.is_empty());
Ok(())
}
}
struct MockTransmitterFail;
impl PulseTransmitter for MockTransmitterFail {
fn send_pulses(&self, _pulses: &[u32]) -> Result<()> {
Err(Error::Transmitting("Mock failure".to_string()))
}
}
#[test]
fn test_extended_all_commands() {
let transmitter = MockTransmitterSuccess;
let mut controller = ExtendedRemoteController::new(&transmitter, Channel::One)
.expect("Should create ExtendedRemoteController");
let commands = [
ExtendedCommand::BrakeThenFloatOnRedOutput,
ExtendedCommand::IncrementSpeedOnRedOutput,
ExtendedCommand::DecrementSpeedOnRedOutput,
ExtendedCommand::ToggleForwardOrFloatOnBlueOutput,
ExtendedCommand::ToggleAddress,
ExtendedCommand::AlignToggle,
];
for &cmd in &commands {
let result = controller.send(cmd);
assert!(result.is_ok(), "Extended command failed for {:?}", cmd);
}
}
#[test]
fn test_extended_toggle_address_sequence() {
let transmitter = MockTransmitterSuccess;
let mut controller = ExtendedRemoteController::new(&transmitter, Channel::One)
.expect("Should create ExtendedRemoteController");
controller.send(ExtendedCommand::ToggleAddress).unwrap();
controller.send(ExtendedCommand::ToggleAddress).unwrap();
}
#[test]
fn test_extended_send_fails() {
let transmitter = MockTransmitterFail;
let mut controller = ExtendedRemoteController::new(&transmitter, Channel::One)
.expect("Should create ExtendedRemoteController");
let result = controller.send(ExtendedCommand::BrakeThenFloatOnRedOutput);
assert!(result.is_err(), "Expected error from failing transmitter");
match result {
Err(Error::Transmitting(msg)) => assert!(msg.contains("Mock failure")),
_ => panic!("Unexpected error variant"),
}
}
}