rotary_switch_helper/
lib.rs

1use std::time::Duration;
2
3use anyhow::Result;
4use log::{debug, trace};
5use rppal::gpio::Gpio;
6
7pub mod rotary_encoder;
8pub mod switch_encoder;
9
10use rotary_encoder::Direction;
11
12#[allow(dead_code)]
13pub struct PiInput {
14    rot_encoders: Vec<rotary_encoder::Encoder>,
15    sw_encoders: Vec<switch_encoder::Encoder>,
16}
17
18#[derive(Debug)]
19pub enum EncoderType {
20    Rotary,
21    Switch,
22}
23
24#[derive(Debug)]
25pub struct SwitchDefinition {
26    pub name: String,
27    pub name_long_press: Option<String>,
28    pub sw_pin: u8,
29    pub callback: fn(&str, bool),
30    pub time_threshold: Option<Duration>,
31}
32
33#[derive(Debug)]
34pub struct RotaryDefinition {
35    pub name: String,
36    pub name_shifted: Option<String>,
37    pub sw_pin: Option<u8>,
38    pub dt_pin: u8,
39    pub clk_pin: u8,
40    pub callback: fn(&str, Direction),
41}
42
43impl PiInput {
44    pub fn new(switches: &[SwitchDefinition], rotaries: &[RotaryDefinition]) -> Result<Self> {
45        debug!("Initializing PiInput...");
46        let gpio = Gpio::new()?;
47
48        let rot_encoders = rotaries
49            .iter()
50            .map(|r| {
51                rotary_encoder::Encoder::new(
52                    &r.name,
53                    r.name_shifted.as_deref(),
54                    &gpio,
55                    r.dt_pin,
56                    r.clk_pin,
57                    r.sw_pin,
58                    r.callback,
59                )
60            })
61            .collect::<Result<Vec<rotary_encoder::Encoder>>>()?;
62
63        let sw_encoders = switches
64            .iter()
65            .map(|s| {
66                switch_encoder::Encoder::new(
67                    &s.name,
68                    s.name_long_press.as_deref(),
69                    &gpio,
70                    s.sw_pin,
71                    s.time_threshold,
72                    s.callback,
73                )
74            })
75            .collect::<Result<Vec<switch_encoder::Encoder>>>()?;
76
77        trace!("PiInput initialized");
78        Ok(Self {
79            rot_encoders,
80            sw_encoders,
81        })
82    }
83}