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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use core::marker::PhantomData;

use crate::{
    protocol::{
        nec::{NecCommand, NecCommandVariant},
        Nec,
    },
    receiver::{
        time::{InfraMonotonic, PulseSpans},
        DecoderFactory, DecodingError, ProtocolDecoder, State,
    },
};

fn pulselens<Cmd: NecCommandVariant>() -> [u32; 8] {
    [
        Cmd::PULSE_DISTANCE.header_high + Cmd::PULSE_DISTANCE.header_low,
        Cmd::PULSE_DISTANCE.header_high + Cmd::PULSE_DISTANCE.repeat_low,
        Cmd::PULSE_DISTANCE.data_high + Cmd::PULSE_DISTANCE.data_zero_low,
        Cmd::PULSE_DISTANCE.data_high + Cmd::PULSE_DISTANCE.data_one_low,
        0,
        0,
        0,
        0,
    ]
}

const TOL: [u32; 8] = [7, 7, 5, 5, 0, 0, 0, 0];

impl<Mono: InfraMonotonic, Cmd: NecCommandVariant> DecoderFactory<Mono> for Nec<Cmd> {
    type Decoder = NecDecoder<Mono, Cmd>;

    fn decoder(freq: u32) -> Self::Decoder {
        NecDecoder {
            state: NecState::Init,
            bitbuf: 0,
            cmd_type: Default::default(),
            dt_save: Mono::ZERO_DURATION,
            pulsespans: PulseSpans::new(freq, &pulselens::<Cmd>(), &TOL),
        }
    }
}

pub struct NecDecoder<Mono: InfraMonotonic, C = NecCommand> {
    // State
    state: NecState,
    // Data buffer
    bitbuf: u32,
    // Nec Command type
    cmd_type: PhantomData<C>,
    // Saved dt
    dt_save: Mono::Duration,

    pulsespans: PulseSpans<Mono>,
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
// Internal receiver state
pub enum NecState {
    // Waiting for first pulse
    Init,
    // Receiving data
    Receiving(u32),
    // Command received
    Done,
    // Repeat command received
    RepeatDone,
    // In error state
    Err(DecodingError),
}

impl From<NecState> for State {
    fn from(ns: NecState) -> Self {
        use NecState::*;
        match ns {
            Init => State::Idle,
            Done | RepeatDone => State::Done,
            Err(e) => State::Error(e),
            _ => State::Receiving,
        }
    }
}

impl<Mono, Cmd> ProtocolDecoder<Mono, Cmd> for NecDecoder<Mono, Cmd>
where
    Mono: InfraMonotonic,
    Cmd: NecCommandVariant,
{
    #[rustfmt::skip]
    fn event(
        &mut self,
        rising: bool,
        dur: Mono::Duration,
    ) -> State {

        use NecState::*;
        use PulseWidth::*;

        if rising {

            let total_duration = dur + self.dt_save;

            let pulsewidth = self.pulsespans.get(total_duration)
                .unwrap_or(PulseWidth::Invalid);

            let status = match (self.state, pulsewidth) {
                (Init,              Sync)   => { self.bitbuf = 0; Receiving(0) },
                (Init,              Repeat) => RepeatDone,
                (Init,              _)      => Init,

                (Receiving(31),     One)    => { self.bitbuf |= 1 << 31; Done }
                (Receiving(31),     Zero)   => Done,
                (Receiving(bit),    One)    => { self.bitbuf |= 1 << bit; Receiving(bit + 1) }
                (Receiving(bit),    Zero)   => Receiving(bit + 1),
                (Receiving(_),      _)      => Err(DecodingError::Data),

                (Done,              _)      => Done,
                (RepeatDone,        _)      => RepeatDone,
                (Err(err),          _)      => Err(err),
            };

            trace!(
                "State(prev, new): ({:?}, {:?}) pulsewidth: {:?}",
                self.state,
                status,
                pulsewidth
            );

            self.state = status;

            self.dt_save = Mono::ZERO_DURATION;
        } else {
            // Save
            self.dt_save = dur;
        }

        self.state.into()
    }
    fn command(&self) -> Option<Cmd> {
        match self.state {
            NecState::Done => Cmd::unpack(self.bitbuf, false),
            NecState::RepeatDone => Cmd::unpack(self.bitbuf, true),
            _ => None,
        }
    }

    fn reset(&mut self) {
        self.state = NecState::Init;
        self.dt_save = Mono::ZERO_DURATION;
    }

    fn spans(&self) -> &PulseSpans<Mono> {
        &self.pulsespans
    }
}

#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum PulseWidth {
    Sync = 0,
    Repeat = 1,
    Zero = 2,
    One = 3,
    Invalid = 4,
}

impl From<usize> for PulseWidth {
    fn from(v: usize) -> Self {
        match v {
            0 => PulseWidth::Sync,
            1 => PulseWidth::Repeat,
            2 => PulseWidth::Zero,
            3 => PulseWidth::One,
            _ => PulseWidth::Invalid,
        }
    }
}