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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
#![doc = include_str!("../README.md")]

use std::{thread::sleep, time::Duration, fmt::Display, hash::Hash};

use rppal::i2c::I2c;

const IODIRA: u8 = 0x00;
const IODIRB: u8 = 0x01; 
const GPINTENA: u8 = 0x04; 
const GPINTENB: u8 = 0x05; 
const DEFVALA: u8 = 0x06; 
const DEFVALB: u8 = 0x07; 
const INTCONA: u8 = 0x08; 
const INTCONB: u8 = 0x09; 
const IOCON: u8 = 0x0A;
const GPPUA: u8 = 0x0C; 
const GPPUB: u8 = 0x0D; 
const INTFA: u8 = 0x0E; 
const INTFB: u8 = 0x0F; 
const INTCAPA: u8 = 0x10; 
const INTCAPB: u8 = 0x11; 
const GPIOA: u8 = 0x12; 
const GPIOB: u8 = 0x13; 
const OLATA: u8 = 0x14; 
const OLATB: u8 = 0x15; 

const IOCONMIRROR: Pin = Pin{pin: 6, orig: 6, shift: 0, bank: Bank::A };
const IOCONINTPOL: Pin = Pin{pin: 1, orig: 1, shift: 0, bank: Bank::A };

const NUM_GPIO: u8 = 16;

#[derive(Debug)]
/// MCP23017 Error
pub enum Error { 
    I2C(rppal::i2c::Error),
    WrongMode(Pin),
    InterruptsForcedClear,
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::I2C(e) => f.write_fmt(format_args!("I2C error, {}", e)),
            Error::WrongMode(pin) => f.write_fmt(format_args!("Pin {} was in the wrong mode", pin)),
            Error::InterruptsForcedClear => f.write_str("Interrupts had to be forced clear"),
        }
    }
}

#[derive(Debug, Clone, Copy)]
/// Pin mode
pub enum Mode {
    Input,
    Output
}

impl Display for Mode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Mode::Output => f.write_str("Outpu"),
            Mode::Input => f.write_str("Input"),
        }
    }
}

impl Into<bool> for Mode {
    fn into(self) -> bool {
        match self {
            Mode::Input => true,
            Mode::Output => false,
        }
    }
}

impl From<bool> for Mode {
    fn from(s: bool) -> Self {
        if s {
            Mode::Input
        } else {
            Mode::Output
        }
    }
}


#[derive(Debug, Clone, Copy)]
/// Pin state
pub enum State {
    High,
    Low,
}

impl Display for State {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            State::High => f.write_str("High"),
            State::Low => f.write_str("Low"),
        }
    }
}

impl Into<bool> for State {
    fn into(self) -> bool {
        match self {
            State::High => true,
            State::Low => false,
        }
    }
}

impl From<bool> for State {
    fn from(s: bool) -> Self {
        if s {
            State::High
        } else {
            State::Low
        }
    }
}

#[derive(Debug, Clone, Copy)]
/// Interrupt feature state
pub enum Feature {
    On,
    Off,
}

impl Display for Feature {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Feature::On => f.write_str("On"),
            Feature::Off => f.write_str("Off"),
        }
    }
}

impl Into<bool> for Feature {
    fn into(self) -> bool {
        match self {
            Feature::On => true,
            Feature::Off => false,
        }
    }
}

impl From<bool> for Feature {
    fn from(s: bool) -> Self {
        if s {
            Feature::On
        } else {
            Feature::Off
        }
    }
}

#[derive(Debug, Clone, Copy)]
/// INT pin start position
pub enum INTPOL {
    /// int pin starts high. when interrupt happens, pin goes low
    ActiveHigh,
    /// int pin starts low. when interrupt happens, pin goes high
    ActiveLow,
}

impl Display for INTPOL {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            INTPOL::ActiveHigh => f.write_str("Active High"),
            INTPOL::ActiveLow => f.write_str("Active Low"),
        }
    }
}

impl Into<bool> for INTPOL {
    fn into(self) -> bool {
        match self {
            INTPOL::ActiveHigh => true,
            INTPOL::ActiveLow => false,
        }
    }
}

impl From<bool> for INTPOL {
    fn from(s: bool) -> Self {
        if s {
            INTPOL::ActiveHigh
        } else {
            INTPOL::ActiveLow
        }
    }
}


#[derive(Debug, Clone, Copy)]
/// Interrupt compare mode
pub enum Compare {
    Default,
    Previous,
}

impl Display for Compare {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Compare::Default => f.write_str("Default"),
            Compare::Previous => f.write_str("Previous"),
        }
    }
}

impl Into<bool> for Compare {
    fn into(self) -> bool {
        match self {
            Compare::Default => true,
            Compare::Previous => false,
        }
    }
}

impl From<bool> for Compare {
    fn from(s: bool) -> Self {
        if s {
            Compare::Default
        } else {
            Compare::Previous
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// GPIO bank
pub enum Bank {
    A,
    B
}

impl Display for Bank {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Bank::A => f.write_str("A"),
            Bank::B => f.write_str("B"),
        }
    }
}

#[derive(Debug, Clone, Eq, Ord)]
/// GPIO Pin
pub struct Pin {
    pin: u8,
    orig: u8,
    shift: u8,
    bank: Bank,
}

impl Display for Pin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("Pin: {} ({}), Bank: {}", self.pin, self.orig, self.bank))
    }
}

impl From<&Pin> for u8 {
    fn from(p: &Pin) -> Self {
        p.orig
    }
}

impl Pin {
    /// Pin between 0-15, 0 to 7 is bank A, 8 to 15 is bank B
    pub const fn new(pin: u8) -> Option<Pin> {
        if pin >= NUM_GPIO {
            None
        } else {
            if pin < 8 {
                Some(Pin{pin, orig: pin, shift: 0, bank: Bank::A})
            } else {
                Some(Pin{pin: pin-8, orig: pin, shift: 8, bank: Bank::B})
            }
        }
    }

    pub(crate) fn mode(&self, direction: u16) -> Mode {
        Mode::from(direction & (1 << self.orig) == 0)
    }

    pub(crate) fn apply_u16(&self, bitmap: u16, value: u8) -> u16 {
        let mut bytes = bitmap.to_be_bytes();
        if self.shift != 8 {
            bytes[1] = value.to_be_bytes()[0];
        } else {
            bytes[0] = value.to_be_bytes()[0];
        }
        return u16::from_be_bytes(bytes)
    }
}

impl PartialEq for Pin {
    fn eq(&self, other: &Self) -> bool {
        self.pin == other.pin && self.bank == other.bank
    }
}

impl PartialOrd for Pin {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match self.bank.partial_cmp(&other.bank) {
            Some(core::cmp::Ordering::Equal) => self.pin.partial_cmp(&other.pin),
            ord => return ord,
        }
    }
}

impl Hash for Pin {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.pin.hash(state);
        self.bank.hash(state);
    }
}

/// MCP23017 i2c Interface
pub struct MCP23017 {
    i2c: I2c,
    direction: u16,
    mirrored: Feature,
}

impl MCP23017 {
    pub fn new(address: u16, bus: u8) -> Result<MCP23017, Error> {
        let mut i2c = I2c::with_bus(bus).map_err(|e| Error::I2C(e))?;
        i2c.set_slave_address(address).map_err(|e| Error::I2C(e))?;

        let mut direction = i2c.smbus_read_byte(IODIRA).map_err(|e| Error::I2C(e))? as u16; 
        direction |= (i2c.smbus_read_byte(IODIRB).map_err(|e| Error::I2C(e))? as u16) << 8;

        let mcp23017 = MCP23017 { i2c, direction,  mirrored: Feature::Off};
        mcp23017.reset()?;
        Ok(mcp23017)
    }

    /// Change a specific bit in a byte
    fn change_bit(bitmap: u8, pin: &Pin, value: bool) -> u8 {
        if value {
            bitmap | (1 << pin.pin)
        } else {
            bitmap & !(1 << pin.pin)
        }
    }

    /// Set an output pin to a specific value.
    fn read_and_change_pin(&self, register: u8, pin: &Pin, value: bool, cur_value: Option<u8>) -> Result<u8, Error> {
        // if we don't know what the current register's full value is, get it first
        let cur_value = match cur_value {
            Some(cur_value) => cur_value,
            None => self.i2c.smbus_read_byte(register).map_err(|e| Error::I2C(e))?,
        };

        // set the single bit that corresponds to the specific pin within the full register value
        let new_value = MCP23017::change_bit(cur_value, &pin, value);

        // write and return the full register value
        self.i2c.smbus_write_byte(register, new_value).map_err(|e| Error::I2C(e))?;
        Ok(new_value)
    }

    /// Used to set the pullUp resistor setting for a pin.
    /// Returns the whole register value.
    pub fn pull_up(&self, pin: &Pin, value: State) -> Result<u16, Error> {
        let pull = match pin.bank {
            Bank::A => self.read_and_change_pin(GPPUA, pin, value.into(), None)?,
            Bank::B => self.read_and_change_pin(GPPUA, pin, value.into(), None)?,
        } as u16;

        Ok(pull << pin.shift)
    }

    /// Set pin to either input or output mode.
    /// Returns the value of the combined IODIRA and IODIRB registers.
    pub fn pin_mode(&mut self, pin: &Pin, mode: Mode) -> Result<u16, Error> {
        let mode = match pin.bank {
            Bank::A => self.read_and_change_pin(IODIRA, pin, mode.into(), None)?,
            Bank::B => self.read_and_change_pin(IODIRB, pin, mode.into(), None)?,
        };
        
        self.direction = pin.apply_u16(self.direction, mode);
        Ok(self.direction)
    }

    /// Set an output pin to a specific value.
    pub fn output(&self, pin: &Pin, value: State) -> Result<u8, Error>{
        if matches!(pin.mode(self.direction), Mode::Output) {
            return Err(Error::WrongMode(pin.clone()))
        }
        match pin.bank {
            Bank::A => self.read_and_change_pin(GPIOA, pin, value.into(), self.i2c.smbus_read_byte(OLATA).ok()),
            Bank::B => self.read_and_change_pin(GPIOB, pin, value.into(), self.i2c.smbus_read_byte(OLATB).ok()),
        }
    }

    /// Read the value of a pin.
    pub fn input(&self, pin: &Pin) -> Result<State, Error> {
        if matches!(pin.mode(self.direction), Mode::Input) {
            return Err(Error::WrongMode(pin.clone()))
        }
        
        // reads the whole register then compares the value of the specific pin
        let bank_value = match pin.bank {
            Bank::A => self.i2c.smbus_read_byte(GPIOA).map_err(|e| Error::I2C(e))?,
            Bank::B => self.i2c.smbus_read_byte(GPIOB).map_err(|e| Error::I2C(e))?,
        };

        Ok(State::from(bank_value & (1 << pin.pin) != 0))
    }


    /// Read the value of a pin regardless of it's mode
    pub fn current_val(&self, pin: &Pin) -> Result<State, Error> {
        // reads the whole register then compares the value of the specific pin
        let bank_value = match pin.bank {
            Bank::A => self.i2c.smbus_read_byte(GPIOA).map_err(|e| Error::I2C(e))?,
            Bank::B => self.i2c.smbus_read_byte(GPIOB).map_err(|e| Error::I2C(e))?,
        };

        Ok(State::from(bank_value & (1 << pin.pin) != 0))
    }

    /// Configure system interrupt settings.
    /// Mirror - are the int pins mirrored?
    /// Intpol - polarity of the int pin.
    pub fn config_system_interrupt(&mut self, mirror: Feature, intpol: State) -> Result<(), Error>{
        // get current register settings
        let mut register_value = self.i2c.smbus_read_byte(IOCON).map_err(|e| Error::I2C(e))?;
        // set mirror bit
        register_value = MCP23017::change_bit(register_value, &IOCONMIRROR, mirror.into());

        // set the intpol bit
        register_value = MCP23017::change_bit(register_value, &IOCONINTPOL, intpol.into());

        // set ODR pin
        self.i2c.smbus_write_byte(IOCON, register_value).map_err(|e| Error::I2C(e))?;
        self.mirrored = mirror;
        Ok(())
    }

    /// Configure interrupt setting for a specific pin. set on or off.
    pub fn config_pin_interrupt(&self, pin: &Pin, enabled: Feature, compare_mode: Compare, defval: Option<State>) -> Result<(), Error>{
        if matches!(pin.mode(self.direction), Mode::Input) {
            return Err(Error::WrongMode(pin.clone()))
        }

        match pin.bank {
            Bank::A => {
                // first, interrupt on change feature
                self.read_and_change_pin(GPINTENA, pin, enabled.into(), None)?;
                // then, compare mode (previous value or default value?)
                self.read_and_change_pin(INTCONA, pin, compare_mode.into(), None)?;
                // last, the default value. set it regardless if compareMode requires it, in case the requirement has changed since program start
                self.read_and_change_pin(DEFVALA, pin, defval.unwrap_or(State::Low).into(), None)?;
            },
            Bank::B => {
                self.read_and_change_pin(GPINTENB, pin, enabled.into(), None)?;
                self.read_and_change_pin(INTCONB, pin, compare_mode.into(), None)?;
                self.read_and_change_pin(DEFVALB, pin, defval.unwrap_or(State::Low).into(), None)?;

            },
        }
        Ok(())
    }

    /// Private function to return pin and value from an interrupt
    fn read_interrupt_register(&self, port: Bank) -> Result<Option<(Pin, State)>, Error> {
        match port {
            Bank::A => {
                let interrupted_a = self.i2c.smbus_read_byte(INTFA).map_err(|e| Error::I2C(e))?;
                if interrupted_a != 0 {

                    let pin = Pin::new((interrupted_a as f32).log2() as u8);
                    // get the value of the pin
                    let value_register = self.i2c.smbus_read_byte(INTCAPA).map_err(|e| Error::I2C(e))?;
                    let value = pin.clone().map(|pin| {let num = pin.pin; (pin, State::from(value_register & (1 << num) != 0))});
                    Ok(value)
                } else {
                    Ok(None)
                } 
            },
            Bank::B => {
                let interrupted_b = self.i2c.smbus_read_byte(INTFB).map_err(|e| Error::I2C(e))?;
                if interrupted_b != 0 {

                    let pin = Pin::new((interrupted_b as f32).log2() as u8);
                    // get the value of the pin
                    let value_register = self.i2c.smbus_read_byte(INTCAPB).map_err(|e| Error::I2C(e))?;
                    let value = pin.clone().map(|pin| {let num = pin.pin; (pin, State::from(value_register & (1 << num) != 0))});
                    Ok(value)
                } else {
                    Ok(None)
                } 
            }
        }
    }

    // This function should be called when INTA or INTB is triggered to indicate an interrupt occurred.
    /// The function determines the pin that caused the interrupt and gets its value.
    /// The interrupt is cleared.
    /// Returns pin and the value.
    pub fn read_interrupt(&self, port: Bank) -> Result<Option<(Pin, State)>, Error> {
        // if the mirror is enabled, we don't know what port caused the interrupt, so read both
        match self.mirrored {
            Feature::On => {
                self.read_interrupt_register(Bank::A).map(|state| {
                    state.or_else(|| self.read_interrupt_register(Bank::B).unwrap_or(None))
                })
            },
            Feature::Off => self.read_interrupt_register(port),
        }
    }

    /// Check to see if there is an interrupt pending 3 times in a row (indicating it's stuck) 
    /// and if needed clear the interrupt without reading values.
    pub fn clear_interrupts(&self) -> Result<(), Error> {
        if self.i2c.smbus_read_byte(INTFA).map_err(|e| Error::I2C(e))? > 0
            || self.i2c.smbus_read_byte(INTFB).map_err(|e| Error::I2C(e))? > 0 {
            
            for _ in [0..3] {
                if self.i2c.smbus_read_byte(INTFA).map_err(|e| Error::I2C(e))? == 0
                    || self.i2c.smbus_read_byte(INTFB).map_err(|e| Error::I2C(e))? == 0 {
                    return Ok(());
                } else {
                    sleep(Duration::from_millis(500));
                }
            }

            //  force reset
            self.i2c.smbus_read_byte(GPIOA).map_err(|e| Error::I2C(e))?;
            self.i2c.smbus_read_byte(GPIOB).map_err(|e| Error::I2C(e))?;
            Err(Error::InterruptsForcedClear)
        } else {
            Ok(())
        }
    }

    /// Reset all pins and interrupts
    pub fn reset(&self) -> Result<(), Error> {
        self.i2c.smbus_write_byte(IODIRA, 0xFF).map_err(|e| Error::I2C(e))?;  // all inputs on port A
        self.i2c.smbus_write_byte(IODIRB, 0xFF).map_err(|e| Error::I2C(e))?;  // all inputs on port B
        // make sure the output registers are set to off
        self.i2c.smbus_write_byte(GPIOA, 0x00).map_err(|e| Error::I2C(e))?;
        self.i2c.smbus_write_byte(GPIOB, 0x00).map_err(|e| Error::I2C(e))?;
	    // disable the pull-ups on all ports
        self.i2c.smbus_write_byte(GPPUA, 0x00).map_err(|e| Error::I2C(e))?;
        self.i2c.smbus_write_byte(GPPUB, 0x00).map_err(|e| Error::I2C(e))?;
        // clear the IOCON configuration register, which is chip default
        self.i2c.smbus_write_byte(IOCON, 0x00).map_err(|e| Error::I2C(e))?;

        // disable interrupts on all pins 
        self.i2c.smbus_write_byte(GPINTENA, 0x00).map_err(|e| Error::I2C(e))?;
        self.i2c.smbus_write_byte(GPINTENB, 0x00).map_err(|e| Error::I2C(e))?;
        // interrupt on change register set to compare to previous value by default
        self.i2c.smbus_write_byte(INTCONA, 0x00).map_err(|e| Error::I2C(e))?;
        self.i2c.smbus_write_byte(INTCONB, 0x00).map_err(|e| Error::I2C(e))?;
        // interrupt compare value registers
        self.i2c.smbus_write_byte(DEFVALA, 0x00).map_err(|e| Error::I2C(e))?;
        self.i2c.smbus_write_byte(DEFVALB, 0x00).map_err(|e| Error::I2C(e))?;
        // clear any interrupts to start fresh
        self.i2c.smbus_read_byte(GPIOA).map_err(|e| Error::I2C(e))?;
        self.i2c.smbus_read_byte(GPIOB).map_err(|e| Error::I2C(e))?;

        Ok(())
    }
}