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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//! Abstractions used to configure the MAX7301 hardware.

use expander::Expander;
use interface::ExpanderInterface;
use registers::valid_port;

fn port_bank_and_offset(port: u8) -> (u8, u8) {
    (valid_port(port) / 4 - 1, port % 4)
}

/// A `PortMode` enumerates the three supported modes that each GPIO pin on the MAX7301 may be
/// configured to.
#[derive(Clone, Copy, Debug)]
pub enum PortMode {
    /// Push-pull logic output.
    Output,
    /// Floating logic input.
    InputFloating,
    /// Logic input with weak pull-up.
    InputPullup,
}

impl From<PortMode> for u8 {
    fn from(cfg: PortMode) -> u8 {
        use self::PortMode::*;
        match cfg {
            Output => 0b01,
            InputFloating => 0b10,
            InputPullup => 0b11,
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct BankConfig(u8);

#[derive(Clone, Copy, Debug, PartialEq)]
enum BankConfigStatus {
    Unchanged,
    ReadModify,
    Overwrite,
}

impl Default for BankConfig {
    fn default() -> Self {
        Self(0)
    }
}

impl BankConfig {
    fn set_port(&mut self, port_offset: u8, cfg: PortMode) {
        match port_offset {
            0..=4 => {
                let mask = !(0b11u8 << port_offset * 2);
                let cfg_bits = u8::from(cfg) << port_offset * 2;
                self.0 = self.0 & mask | cfg_bits;
            }
            _ => panic!("Config register can only hold 4 ports"),
        }
    }
    fn keep_mask(&self) -> u8 {
        (0..4)
            .into_iter()
            .map(|p| {
                if self.0 & (0b11u8 << p * 2) == 0 {
                    0b11u8 << p * 2
                } else {
                    0u8
                }
            })
            .fold(0u8, |m, a| a | m)
    }
    fn status(&self) -> BankConfigStatus {
        match self.keep_mask() {
            0xFF => BankConfigStatus::Unchanged,
            0x00 => BankConfigStatus::Overwrite,
            _ => BankConfigStatus::ReadModify,
        }
    }
    fn merge(&self, current: u8) -> Self {
        Self(current & self.keep_mask() | self.0)
    }
}

impl From<BankConfig> for u8 {
    fn from(cfg: BankConfig) -> u8 {
        cfg.0
    }
}

#[derive(Clone)]
pub(crate) struct ExpanderConfig {
    shutdown: bool,
    transition_detect: bool,
}

impl Default for ExpanderConfig {
    fn default() -> Self {
        Self {
            shutdown: true,
            transition_detect: false,
        }
    }
}

impl From<ExpanderConfig> for u8 {
    fn from(cfg: ExpanderConfig) -> u8 {
        let shtd = if cfg.shutdown { 0 } else { 0b00000001 };
        let txnd = if cfg.transition_detect { 0b10000000 } else { 0 };
        shtd | txnd
    }
}

/// A `Configurator` provides methods to build a list of device configuration changes, such as port
/// modes and device configuration bits, and commit them to the device. You obtain one from the
/// `Expander::configure()`, chain method calls on it to make configuration changes, and then end
/// the chain with `commit()` to transmit them to the MAX7301.
///
/// ```
/// # use max7301::interface::noop::NoopInterface;
/// # use max7301::expander::Expander;
/// # use max7301::config::PortMode;
/// # let ei = NoopInterface;
/// let mut expander = Expander::new(ei);
/// expander
///     .configure()
///     .ports(4..=7, PortMode::Output)
///     .shutdown(false)
///     .commit()
///     .unwrap();
/// ```
#[must_use = "Configuration changes are not applied unless committed"]
pub struct Configurator<'e, EI: ExpanderInterface + Send> {
    expander: &'e mut Expander<EI>,
    expander_config_dirty: bool,
    banks: [BankConfig; 7],
}

impl<'e, EI: ExpanderInterface + Send> Configurator<'e, EI> {
    pub(crate) fn new(expander: &'e mut Expander<EI>) -> Self {
        Self {
            expander,
            expander_config_dirty: false,
            banks: [BankConfig(0); 7],
        }
    }

    fn set_port(&mut self, port: u8, mode: PortMode) {
        let (bank, offset) = port_bank_and_offset(port);
        self.banks[bank as usize].set_port(offset, mode);
    }

    /// Set the port mode of a single GPIO pin on the MAX7301 to `mode`. `port` is the port number
    /// as specified in the device datasheet, in the range `4..=31`.
    pub fn port(mut self, port: u8, mode: PortMode) -> Self {
        self.set_port(port, mode);
        self
    }

    /// Set the port mode of a sequence of GPIO pins to the given `PortMode`. `ports` must yield
    /// values corresponding to port numbers as specified in the device datasheet, in the range
    /// `4..=31`. All of the ports will be set to mode `mode`.
    pub fn ports<I>(mut self, ports: I, mode: PortMode) -> Self
    where
        I: IntoIterator<Item = u8>,
    {
        for port in ports {
            self.set_port(port, mode);
        }
        self
    }

    /// Set the MAX7301's shutdown bit. When `false` the device will operate normally; when `true`
    /// the device enters shutdown mode. In shutdown mode all ports are overridden to input mode
    /// and pull-up current sources are disabled, but all registers retain their values and may be
    /// read and written normally. See the datasheet for more details.
    pub fn shutdown(mut self, enable: bool) -> Self {
        self.expander.config.shutdown = enable;
        self.expander_config_dirty = true;
        self
    }

    /// Set the MAX7301's transition detection feature control bit. When `false` the feature is
    /// disabled; when `true` ports 24 through 31 will be monitored for changes, setting an
    /// interrupt pin when they are detected. See datasheet for details. Interrupts generated from
    /// this hardware feature are not managed by this driver.
    pub fn detect_transitions(mut self, enable: bool) -> Self {
        self.expander.config.transition_detect = enable;
        self.expander_config_dirty = true;
        self
    }

    /// Commit the configuration changes to the MAX7301. The configurator will attempt to update
    /// the device's configuration registers while minimizing bus traffic (avoiding
    /// read-modify-writes when possible, not setting registers that were not changed).
    pub fn commit(self) -> Result<(), ()> {
        for (bank, bank_config) in self.banks.iter().enumerate() {
            match bank_config.status() {
                BankConfigStatus::Unchanged => {}
                BankConfigStatus::Overwrite => {
                    self.expander.write_bank_config(bank as u8, *bank_config)?;
                }
                BankConfigStatus::ReadModify => {
                    self.expander
                        .read_modify_bank_config(bank as u8, |cur| bank_config.merge(cur))?;
                }
            }
        }
        if self.expander_config_dirty {
            self.expander.write_config()
        } else {
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bank_config_set_port_valid() {
        let mut bank = BankConfig::default();
        bank.set_port(0, PortMode::InputPullup);
        bank.set_port(2, PortMode::Output);
        assert_eq!(u8::from(bank), 0b00010011);
    }

    #[test]
    #[should_panic]
    fn bank_config_set_port_invalid() {
        let mut bank = BankConfig::default();
        bank.set_port(4, PortMode::InputPullup);
    }

    #[test]
    fn bank_config_keep_mask_unchanged() {
        let bank = BankConfig::default();
        assert_eq!(bank.keep_mask(), 0b11111111);
        assert_eq!(bank.status(), BankConfigStatus::Unchanged);
    }

    #[test]
    fn bank_config_keep_mask_change_0() {
        let mut bank = BankConfig::default();
        bank.set_port(0, PortMode::InputPullup);
        assert_eq!(bank.keep_mask(), 0b11111100);
        assert_eq!(bank.status(), BankConfigStatus::ReadModify);
    }

    #[test]
    fn bank_config_keep_mask_change_0_2() {
        let mut bank = BankConfig::default();
        bank.set_port(0, PortMode::InputPullup);
        bank.set_port(2, PortMode::Output);
        assert_eq!(bank.keep_mask(), 0b11001100);
        assert_eq!(bank.status(), BankConfigStatus::ReadModify);
    }

    #[test]
    fn bank_config_keep_mask_change_all() {
        let mut bank = BankConfig::default();
        for p in 0..4 {
            bank.set_port(p, PortMode::Output);
        }
        assert_eq!(bank.keep_mask(), 0b00000000);
        assert_eq!(bank.status(), BankConfigStatus::Overwrite);
    }

    #[test]
    fn bank_config_merge() {
        let orig = 0b11101010u8;
        let mut bank = BankConfig::default();
        bank.set_port(0, PortMode::InputPullup);
        bank.set_port(2, PortMode::Output);
        assert_eq!(u8::from(bank.merge(orig)), 0b11011011u8);
    }

    #[test]
    fn expander_config_default() {
        let expander_config = ExpanderConfig::default();
        assert_eq!(u8::from(expander_config), 0b00000000);
    }

    #[test]
    fn expander_config_disable_shutdown() {
        let mut expander_config = ExpanderConfig::default();
        expander_config.shutdown = false;
        assert_eq!(u8::from(expander_config), 0b00000001);
    }

    #[test]
    fn expander_config_enable_transition_detect() {
        let mut expander_config = ExpanderConfig::default();
        expander_config.transition_detect = true;
        assert_eq!(u8::from(expander_config), 0b10000000);
    }
}