Skip to main content

rx480e_wq_driver/
lib.rs

1//! `no_std` [`embedded-hal`](embedded_hal) input helper for RX480-E-WQ / RX480E-4
2//! decoded output pins.
3//!
4//! This crate reads the module's active-high `D0`-`D3` decoded channel outputs
5//! and `VT` valid-transmission output through [`embedded_hal::digital::InputPin`].
6//!
7//! Pin conventions:
8//! - `D0`-`D3` are active-high decoded channel outputs.
9//! - `VT` is active-high and indicates a valid transmission.
10//! - Bits are laid out as `D0=0b0000_0001`, `D1=0b0000_0010`, `D2=0b0000_0100`,
11//!   `D3=0b0000_1000`, `VT=0b0001_0000`.
12//! - Sampling is sequential (`D0`, `D1`, `D2`, `D3`, `VT`), not atomic.
13//! - `poll_change` compares against an initial all-low baseline, so a pin that
14//!   is already high on the first call is reported as a rising edge.
15//!
16//! It reports structured [`Snapshot`] and [`Event`] values that application
17//! firmware can turn into logs, relay actions, MQTT messages, or other behavior.
18//!
19//! It does **not** decode raw RF, pair remotes, clear learned codes, inspect the
20//! RX480 module's internal learned-code memory, transmit RF, or measure pulse
21//! durations.
22//!
23//! ```no_run
24//! use rx480e_wq_driver::{ChannelState, Rx480eWq};
25//!
26//! # fn run<D0, D1, D2, D3, VT>(d0: D0, d1: D1, d2: D2, d3: D3, vt: VT) -> Result<(), D0::Error>
27//! # where
28//! #     D0: embedded_hal::digital::InputPin,
29//! #     D1: embedded_hal::digital::InputPin<Error = D0::Error>,
30//! #     D2: embedded_hal::digital::InputPin<Error = D0::Error>,
31//! #     D3: embedded_hal::digital::InputPin<Error = D0::Error>,
32//! #     VT: embedded_hal::digital::InputPin<Error = D0::Error>,
33//! # {
34//! let mut rx = Rx480eWq::new(d0, d1, d2, d3, vt);
35//!
36//! if let Some(event) = rx.poll_change()? {
37//!     if event.vt_rising() {
38//!         // A valid RF frame was accepted by the RX480 module.
39//!     }
40//!
41//!     match event.current.channel_state() {
42//!         ChannelState::Single(channel) => {
43//!             // One of D0-D3 is active. `VT` is handled separately.
44//!             let _name = channel.name();
45//!         }
46//!         ChannelState::None if event.current.vt_only() => {
47//!             // VT is active, but no D0-D3 output is active.
48//!         }
49//!         ChannelState::None => {}
50//!         ChannelState::Multiple(mask) => {
51//!             // Multiple D0-D3 outputs are active.
52//!             let _mask = mask;
53//!         }
54//!     }
55//! }
56//! # Ok(())
57//! # }
58//! ```
59
60#![no_std]
61
62use embedded_hal::digital::InputPin;
63
64/// Bit for the active-high `D0` channel output.
65pub const D0_BIT: u8 = 0b0000_0001;
66/// Bit for the active-high `D1` channel output.
67pub const D1_BIT: u8 = 0b0000_0010;
68/// Bit for the active-high `D2` channel output.
69pub const D2_BIT: u8 = 0b0000_0100;
70/// Bit for the active-high `D3` channel output.
71pub const D3_BIT: u8 = 0b0000_1000;
72/// Bit for the active-high `VT` valid-transmission output.
73pub const VT_BIT: u8 = 0b0001_0000;
74
75/// One decoded channel output (`D0`-`D3`).
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
77pub enum Channel {
78    D0,
79    D1,
80    D2,
81    D3,
82}
83
84impl Channel {
85    pub fn name(self) -> &'static str {
86        match self {
87            Channel::D0 => "D0",
88            Channel::D1 => "D1",
89            Channel::D2 => "D2",
90            Channel::D3 => "D3",
91        }
92    }
93
94    pub fn bit(self) -> u8 {
95        match self {
96            Channel::D0 => D0_BIT,
97            Channel::D1 => D1_BIT,
98            Channel::D2 => D2_BIT,
99            Channel::D3 => D3_BIT,
100        }
101    }
102}
103
104/// One sampled signal (`D0`-`D3` or `VT`).
105#[derive(Clone, Copy, Debug, Eq, PartialEq)]
106pub enum Signal {
107    D0,
108    D1,
109    D2,
110    D3,
111    VT,
112}
113
114impl Signal {
115    pub fn name(self) -> &'static str {
116        match self {
117            Signal::D0 => "D0",
118            Signal::D1 => "D1",
119            Signal::D2 => "D2",
120            Signal::D3 => "D3",
121            Signal::VT => "VT",
122        }
123    }
124
125    pub fn bit(self) -> u8 {
126        match self {
127            Signal::D0 => D0_BIT,
128            Signal::D1 => D1_BIT,
129            Signal::D2 => D2_BIT,
130            Signal::D3 => D3_BIT,
131            Signal::VT => VT_BIT,
132        }
133    }
134}
135
136/// Decoded `D0`-`D3` channel state.
137///
138/// `VT` is not returned as a `ChannelState`; use [`Snapshot::vt_only`],
139/// [`Event::vt_rising`], or [`Event::vt_falling`] for valid-transmission state.
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub enum ChannelState {
142    None,
143    Single(Channel),
144    Multiple(u8),
145}
146
147/// Rising/falling transition on a sampled signal.
148#[derive(Clone, Copy, Debug, Eq, PartialEq)]
149pub enum Edge {
150    Rising,
151    Falling,
152}
153
154/// Classify only the `D0`-`D3` channel bits.
155pub fn channel_state_from_channel_bits(bits: u8) -> ChannelState {
156    match bits & (D0_BIT | D1_BIT | D2_BIT | D3_BIT) {
157        D0_BIT => ChannelState::Single(Channel::D0),
158        D1_BIT => ChannelState::Single(Channel::D1),
159        D2_BIT => ChannelState::Single(Channel::D2),
160        D3_BIT => ChannelState::Single(Channel::D3),
161        0 => ChannelState::None,
162        mask => ChannelState::Multiple(mask),
163    }
164}
165
166#[deprecated(note = "use channel_state_from_channel_bits")]
167pub fn channel_state_from_bits(bits: u8) -> ChannelState {
168    channel_state_from_channel_bits(bits)
169}
170
171#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
172pub struct Snapshot {
173    pub d0: bool,
174    pub d1: bool,
175    pub d2: bool,
176    pub d3: bool,
177    pub vt: bool,
178}
179
180impl Snapshot {
181    pub fn get(&self, channel: Channel) -> bool {
182        match channel {
183            Channel::D0 => self.d0,
184            Channel::D1 => self.d1,
185            Channel::D2 => self.d2,
186            Channel::D3 => self.d3,
187        }
188    }
189
190    pub fn get_signal(&self, signal: Signal) -> bool {
191        match signal {
192            Signal::D0 => self.d0,
193            Signal::D1 => self.d1,
194            Signal::D2 => self.d2,
195            Signal::D3 => self.d3,
196            Signal::VT => self.vt,
197        }
198    }
199
200    /// Packed `D0`-`D3` bits in the low nibble.
201    pub fn channel_bits(&self) -> u8 {
202        (self.d0 as u8) | ((self.d1 as u8) << 1) | ((self.d2 as u8) << 2) | ((self.d3 as u8) << 3)
203    }
204
205    /// Returns true when at least one `D0`-`D3` channel output is active.
206    pub fn any_channel_active(&self) -> bool {
207        self.channel_bits() != 0
208    }
209
210    /// Packed snapshot bits: channels in the low nibble, `VT` in bit 4.
211    pub fn bits(&self) -> u8 {
212        self.channel_bits() | ((self.vt as u8) << 4)
213    }
214
215    /// Returns true when the `VT` valid-transmission output is active.
216    pub fn is_valid_transmission(&self) -> bool {
217        self.vt
218    }
219
220    pub fn active_channel(&self) -> Option<Channel> {
221        match channel_state_from_channel_bits(self.channel_bits()) {
222            ChannelState::Single(channel) => Some(channel),
223            _ => None,
224        }
225    }
226
227    pub fn channel_state(&self) -> ChannelState {
228        channel_state_from_channel_bits(self.channel_bits())
229    }
230
231    /// Returns true when `VT` is active but no `D0`-`D3` channel output is active.
232    pub fn vt_only(&self) -> bool {
233        self.vt && self.channel_bits() == 0
234    }
235}
236
237#[derive(Clone, Copy, Debug, Eq, PartialEq)]
238pub struct Event {
239    pub previous: Snapshot,
240    pub current: Snapshot,
241}
242
243impl Event {
244    pub fn changed_mask(&self) -> u8 {
245        self.previous.bits() ^ self.current.bits()
246    }
247
248    pub fn edge(&self, signal: Signal) -> Option<Edge> {
249        match (
250            self.previous.get_signal(signal),
251            self.current.get_signal(signal),
252        ) {
253            (false, true) => Some(Edge::Rising),
254            (true, false) => Some(Edge::Falling),
255            _ => None,
256        }
257    }
258
259    pub fn vt_rising(&self) -> bool {
260        self.edge(Signal::VT) == Some(Edge::Rising)
261    }
262
263    pub fn vt_falling(&self) -> bool {
264        self.edge(Signal::VT) == Some(Edge::Falling)
265    }
266}
267
268pub struct Rx480eWq<D0, D1, D2, D3, VT> {
269    d0: D0,
270    d1: D1,
271    d2: D2,
272    d3: D3,
273    vt: VT,
274    last: Snapshot,
275}
276
277impl<D0, D1, D2, D3, VT> Rx480eWq<D0, D1, D2, D3, VT>
278where
279    D0: InputPin,
280    D1: InputPin<Error = D0::Error>,
281    D2: InputPin<Error = D0::Error>,
282    D3: InputPin<Error = D0::Error>,
283    VT: InputPin<Error = D0::Error>,
284{
285    pub fn new(d0: D0, d1: D1, d2: D2, d3: D3, vt: VT) -> Self {
286        Self {
287            d0,
288            d1,
289            d2,
290            d3,
291            vt,
292            last: Snapshot::default(),
293        }
294    }
295
296    pub fn sample(&mut self) -> Result<Snapshot, D0::Error> {
297        Ok(Snapshot {
298            d0: self.d0.is_high()?,
299            d1: self.d1.is_high()?,
300            d2: self.d2.is_high()?,
301            d3: self.d3.is_high()?,
302            vt: self.vt.is_high()?,
303        })
304    }
305
306    /// Sample all pins and return an event when the snapshot differs from the
307    /// previous sample.
308    pub fn poll_change(&mut self) -> Result<Option<Event>, D0::Error> {
309        let current = self.sample()?;
310        if current == self.last {
311            return Ok(None);
312        }
313        let previous = self.last;
314        self.last = current;
315        Ok(Some(Event { previous, current }))
316    }
317}
318
319#[cfg(test)]
320extern crate std;
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use core::cell::Cell;
326
327    #[derive(Clone)]
328    struct MockPin {
329        state: Cell<bool>,
330    }
331
332    impl MockPin {
333        fn new(state: bool) -> Self {
334            Self {
335                state: Cell::new(state),
336            }
337        }
338    }
339
340    impl embedded_hal::digital::ErrorType for MockPin {
341        type Error = core::convert::Infallible;
342    }
343
344    impl InputPin for MockPin {
345        fn is_high(&mut self) -> Result<bool, Self::Error> {
346            Ok(self.state.get())
347        }
348        fn is_low(&mut self) -> Result<bool, Self::Error> {
349            Ok(!self.state.get())
350        }
351    }
352
353    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
354    struct PinError;
355
356    impl embedded_hal::digital::Error for PinError {
357        fn kind(&self) -> embedded_hal::digital::ErrorKind {
358            embedded_hal::digital::ErrorKind::Other
359        }
360    }
361
362    struct ErrorPin;
363
364    impl embedded_hal::digital::ErrorType for ErrorPin {
365        type Error = PinError;
366    }
367
368    impl InputPin for ErrorPin {
369        fn is_high(&mut self) -> Result<bool, Self::Error> {
370            Err(PinError)
371        }
372
373        fn is_low(&mut self) -> Result<bool, Self::Error> {
374            Err(PinError)
375        }
376    }
377
378    #[test]
379    fn sample_reads_all_channels() {
380        let mut dev = Rx480eWq::new(
381            MockPin::new(true),
382            MockPin::new(false),
383            MockPin::new(true),
384            MockPin::new(false),
385            MockPin::new(true),
386        );
387        let s = dev.sample().unwrap();
388        assert_eq!(
389            s,
390            Snapshot {
391                d0: true,
392                d1: false,
393                d2: true,
394                d3: false,
395                vt: true
396            }
397        );
398    }
399
400    #[test]
401    fn channel_helpers_return_stable_names_and_bits() {
402        assert_eq!(Channel::D0.name(), "D0");
403        assert_eq!(Channel::D1.name(), "D1");
404        assert_eq!(Channel::D2.name(), "D2");
405        assert_eq!(Channel::D3.name(), "D3");
406
407        assert_eq!(Channel::D0.bit(), D0_BIT);
408        assert_eq!(Channel::D1.bit(), D1_BIT);
409        assert_eq!(Channel::D2.bit(), D2_BIT);
410        assert_eq!(Channel::D3.bit(), D3_BIT);
411    }
412
413    #[test]
414    fn signal_helpers_return_stable_names_and_bits() {
415        assert_eq!(Signal::D0.name(), "D0");
416        assert_eq!(Signal::D1.name(), "D1");
417        assert_eq!(Signal::D2.name(), "D2");
418        assert_eq!(Signal::D3.name(), "D3");
419        assert_eq!(Signal::VT.name(), "VT");
420
421        assert_eq!(Signal::D0.bit(), D0_BIT);
422        assert_eq!(Signal::D1.bit(), D1_BIT);
423        assert_eq!(Signal::D2.bit(), D2_BIT);
424        assert_eq!(Signal::D3.bit(), D3_BIT);
425        assert_eq!(Signal::VT.bit(), VT_BIT);
426    }
427
428    #[test]
429    fn poll_change_emits_event_when_state_changes() {
430        let mut dev = Rx480eWq::new(
431            MockPin::new(false),
432            MockPin::new(false),
433            MockPin::new(false),
434            MockPin::new(false),
435            MockPin::new(false),
436        );
437        assert!(dev.poll_change().unwrap().is_none());
438        dev.d0.state.set(true);
439        let evt = dev.poll_change().unwrap().expect("event");
440        assert!(!evt.previous.d0);
441        assert!(evt.current.d0);
442    }
443
444    #[test]
445    fn snapshot_helpers_classify_channels() {
446        let single = Snapshot {
447            d0: false,
448            d1: true,
449            d2: false,
450            d3: false,
451            vt: true,
452        };
453        assert_eq!(single.channel_bits(), D1_BIT);
454        assert!(single.any_channel_active());
455        assert_eq!(single.bits(), D1_BIT | VT_BIT);
456        assert!(single.is_valid_transmission());
457        assert_eq!(single.active_channel(), Some(Channel::D1));
458        assert_eq!(single.channel_state(), ChannelState::Single(Channel::D1));
459        assert!(!single.vt_only());
460
461        let vt_only = Snapshot {
462            vt: true,
463            ..Snapshot::default()
464        };
465        assert_eq!(vt_only.channel_state(), ChannelState::None);
466        assert!(!vt_only.any_channel_active());
467        assert!(vt_only.vt_only());
468
469        let multi = Snapshot {
470            d0: true,
471            d1: false,
472            d2: true,
473            d3: false,
474            vt: true,
475        };
476        assert_eq!(multi.channel_bits(), D0_BIT | D2_BIT);
477        assert_eq!(multi.active_channel(), None);
478        assert_eq!(
479            multi.channel_state(),
480            ChannelState::Multiple(D0_BIT | D2_BIT)
481        );
482    }
483
484    #[test]
485    fn event_helpers_report_changed_mask_and_edges() {
486        let event = Event {
487            previous: Snapshot::default(),
488            current: Snapshot {
489                d0: true,
490                vt: true,
491                ..Snapshot::default()
492            },
493        };
494
495        assert_eq!(event.changed_mask(), D0_BIT | VT_BIT);
496        assert_eq!(event.edge(Signal::D0), Some(Edge::Rising));
497        assert_eq!(event.edge(Signal::VT), Some(Edge::Rising));
498        assert!(event.vt_rising());
499        assert!(!event.vt_falling());
500
501        let falling = Event {
502            previous: event.current,
503            current: Snapshot::default(),
504        };
505        assert_eq!(falling.edge(Signal::D0), Some(Edge::Falling));
506        assert_eq!(falling.edge(Signal::VT), Some(Edge::Falling));
507        assert!(falling.vt_falling());
508    }
509
510    #[test]
511    fn poll_change_suppresses_repeated_same_state() {
512        let mut dev = Rx480eWq::new(
513            MockPin::new(false),
514            MockPin::new(false),
515            MockPin::new(false),
516            MockPin::new(false),
517            MockPin::new(false),
518        );
519
520        assert!(dev.poll_change().unwrap().is_none());
521        assert!(dev.poll_change().unwrap().is_none());
522    }
523
524    #[test]
525    fn channel_state_from_channel_bits_detects_multi_channel() {
526        assert_eq!(channel_state_from_channel_bits(0), ChannelState::None);
527        assert_eq!(
528            channel_state_from_channel_bits(D3_BIT),
529            ChannelState::Single(Channel::D3)
530        );
531        assert_eq!(
532            channel_state_from_channel_bits(D0_BIT | D1_BIT),
533            ChannelState::Multiple(D0_BIT | D1_BIT)
534        );
535        assert_eq!(channel_state_from_channel_bits(VT_BIT), ChannelState::None);
536    }
537
538    #[test]
539    fn sample_propagates_pin_errors() {
540        let mut dev = Rx480eWq::new(ErrorPin, ErrorPin, ErrorPin, ErrorPin, ErrorPin);
541        assert_eq!(dev.sample(), Err(PinError));
542    }
543}