1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#[macro_use]
pub mod remotes;
pub mod receiver;
pub mod transmitter;

#[cfg(test)]
mod tests;

pub use receiver::{NecError, NecTypeReceiver, NecResult};
pub use transmitter::NecTypeTransmitter;

pub struct StandardType;
pub struct SamsungType;

pub type NecReceiver = NecTypeReceiver<StandardType>;
pub type NecSamsungReceiver = NecTypeReceiver<SamsungType>;

pub type NecTransmitter = NecTypeTransmitter<StandardType>;
pub type NecSamsungTransmitter = NecTypeTransmitter<SamsungType>;

#[derive(Debug, Copy, Clone)]
/// A Nec Command
pub struct NecCommand {
    pub addr: u8,
    pub cmd: u8,
}

impl NecCommand {
    pub fn from(bitbuf: u32) -> Self {
        let addr = ((bitbuf) & 0xFF) as u8;
        let cmd = ((bitbuf >> 16) & 0xFF) as u8;
        Self {addr, cmd}
    }
}

pub trait NecTypeTrait {
    const PULSEDISTANCE: Pulsedistance;

    fn encode_command(cmd: NecCommand) -> u32;
}

impl NecTypeTrait for StandardType {
    const PULSEDISTANCE: Pulsedistance = Pulsedistance {
        header_high: 9000,
        header_low: 4500,
        repeat_low: 2250,
        data_high: 560,
        zero_low: 560,
        one_low: 1690,
    };

    fn encode_command(NecCommand {addr, cmd}: NecCommand) -> u32 {
        let addr = u32::from(addr) | u32::from(!addr) << 8;
        let cmd = u32::from(cmd) << 16 | u32::from(!cmd) << 24;
        addr | cmd
    }
}

impl NecTypeTrait for SamsungType {
    const PULSEDISTANCE: Pulsedistance = Pulsedistance {
        header_high: 4500,
        header_low: 4500,
        repeat_low: 2250,
        zero_low: 560,
        data_high: 560,
        one_low: 1690,
    };

    fn encode_command(NecCommand {addr, cmd}: NecCommand) -> u32 {
        // Address is inverted and command is repeated
        let addr = u32::from(addr) | u32::from(addr) << 8;
        let cmd = u32::from(cmd) << 16 | u32::from(!cmd) << 24;
        addr | cmd
    }
}

pub struct Pulsedistance {
    header_high: u32,
    header_low: u32,
    repeat_low: u32,
    data_high: u32,
    zero_low: u32,
    one_low: u32,
}