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
use core::marker::PhantomData;

use crate::ll_api::{ll_cmd::*, GpioInitFlag, PortNum};

trait PortModeFlag {
    fn to_flag(&self) -> GpioInitFlag;
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PortModeInput {
    InFloating,
    InPullUp,
    InPullDown,
}

impl PortModeFlag for PortModeInput {
    fn to_flag(&self) -> GpioInitFlag {
        match self {
            PortModeInput::InFloating => GpioInitFlag::InFloating,
            PortModeInput::InPullUp => GpioInitFlag::InPU,
            PortModeInput::InPullDown => GpioInitFlag::InPD,
        }
    }
}

pub enum PortModeOutput {
    OutOD,
    OutPP,
}

impl PortModeFlag for PortModeOutput {
    fn to_flag(&self) -> GpioInitFlag {
        match self {
            PortModeOutput::OutOD => GpioInitFlag::OutOD,
            PortModeOutput::OutPP => GpioInitFlag::OutPP,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct PortReg {
    /// Port input data register
    idr: *mut u16,
    /// Port output data register
    odr: *mut u16,
    /// Port bit set register
    bsr: *mut u16,
    /// Port bit reset register
    bcr: *mut u16,
}

pub struct InputPort;
pub struct OutputPort;

pub struct Port<MODE> {
    gpio: PortNum,
    mask: u16,
    regs: PortReg,
    _mode: PhantomData<MODE>,
}

impl Port<()> {
    /// Creates a new GPIO port instance.
    ///
    /// # Arguments
    /// * `gpio` - The port number.
    /// * `mask` - A bit mask specifying which pins are part of this port.
    ///
    /// # Returns
    /// A new `Port` instance with uninitialized mode.
    pub fn new(gpio: PortNum, mask: u16) -> Port<()> {
        let regs: PortReg = PortReg {
            idr: core::ptr::null_mut::<u16>(),
            odr: core::ptr::null_mut::<u16>(),
            bsr: core::ptr::null_mut::<u16>(),
            bcr: core::ptr::null_mut::<u16>(),
        };
        let port = Port {
            gpio,
            mask,
            regs,
            _mode: PhantomData,
        };

        // Initialize the port registers.
        ll_invoke_inner!(
            INVOKE_ID_GPIO_GET_PORT_REG,
            &(port.regs) as *const _ as usize
        );

        port
    }

    /// Converts the port to an input mode.
    ///
    /// # Arguments
    /// * `mode` - The input mode configuration.
    ///
    /// # Returns
    /// A new `Port` instance configured as an input port.
    pub fn into_input(&self, mode: PortModeInput) -> Port<InputPort> {
        let pin_mode = mode.to_flag();
        self.port_init(pin_mode);

        Port {
            gpio: self.gpio,
            mask: self.mask,
            regs: self.regs.clone(),
            _mode: PhantomData,
        }
    }

    /// Converts the port to an output mode.
    ///
    /// # Arguments
    /// * `mode` - The output mode configuration.
    ///
    /// # Returns
    /// A new `Port` instance configured as an output port.
    pub fn into_output(&self, mode: PortModeOutput) -> Port<OutputPort> {
        let pin_mode = mode.to_flag();
        self.port_init(pin_mode);

        Port {
            gpio: self.gpio,
            mask: self.mask,
            regs: self.regs.clone(),
            _mode: PhantomData,
        }
    }

    /// Initializes individual pins on the port according to the given mode.
    ///
    /// # Arguments
    /// * `mode` - The initialization flag for the pins.
    fn port_init(&self, mode: GpioInitFlag) {
        for pin in 0..16 {
            if (self.mask & (1 << pin)) > 0 {
                ll_invoke_inner!(INVOKE_ID_GPIO_INIT, self.gpio, pin, mode);
            }
        }
    }
}

impl Port<OutputPort> {
    /// Sets the specified bits of the output register without checking bounds or validity.
    ///
    /// # Safety
    /// This function must only be called when it is safe to modify the output register directly.
    #[inline]
    pub unsafe fn set_bits_uncheck(&mut self, bits: u16) {
        core::ptr::write_volatile(self.regs.bsr, bits)
    }

    /// Clears the specified bits of the output register without checking bounds or validity.
    ///
    /// # Safety
    /// This function must only be called when it is safe to modify the output register directly.
    #[inline]
    pub unsafe fn clr_bits_uncheck(&mut self, bits: u16) {
        core::ptr::write_volatile(self.regs.bcr, bits);
    }

    /// Reads the current value of the output register without checking bounds or validity.
    ///
    /// # Safety
    /// This function must only be called when it is safe to read from the output register directly.
    #[inline]
    pub unsafe fn read_output_bits_uncheck(&mut self) -> u16 {
        core::ptr::read_volatile(self.regs.odr)
    }

    /// Writes a value to the output register without checking bounds or validity.
    ///
    /// # Safety
    /// This function must only be called when it is safe to modify the output register directly.
    #[inline]
    pub unsafe fn write_bits_uncheck(&mut self, bits: u16) {
        core::ptr::write_volatile(self.regs.odr, bits);
    }

    /// Sets the specified bits of the output register, applying the bit mask.
    pub fn set_bits(&mut self, bits: u16) {
        if !self.regs.bsr.is_null() {
            unsafe { self.set_bits_uncheck(bits & self.mask) }
        } else {
            let read = self.read_output_bits();
            self.write_bits(bits | read);
        }
    }

    /// Clears the specified bits of the output register, applying the bit mask.
    pub fn clr_bits(&mut self, bits: u16) {
        if !self.regs.bcr.is_null() {
            unsafe { self.clr_bits_uncheck(bits & self.mask) }
        } else {
            let read = self.read_output_bits();
            self.write_bits(!bits & read);
        }
    }

    /// Reads the current value of the output register, applying the bit mask.
    pub fn read_output_bits(&mut self) -> u16 {
        if !self.regs.odr.is_null() {
            return unsafe { self.read_output_bits_uncheck() } & self.mask;
        }
        return 0;
    }

    /// Writes a value to the output register, applying the bit mask.
    pub fn write_bits(&mut self, bits: u16) {
        if !self.regs.odr.is_null() {
            unsafe {
                let read = self.read_output_bits_uncheck() & !self.mask;
                self.write_bits_uncheck((bits & self.mask) | read);
            }
        }
    }
}

impl Port<InputPort> {
    /// Reads the current value of the input register without checking bounds or validity.
    ///
    /// # Safety
    /// This function must only be called when it is safe to read from the input register directly.
    #[inline]
    pub unsafe fn read_input_bits_uncheck(&mut self) -> u16 {
        core::ptr::read_volatile(self.regs.idr)
    }

    /// Reads the current value of the input register, applying the bit mask.
    pub fn read_input_bits(&mut self) -> u16 {
        if !self.regs.idr.is_null() {
            return unsafe { self.read_input_bits_uncheck() } & self.mask;
        }
        return 0;
    }
}

impl<MODE> embedded_hal::digital::ErrorType for Port<MODE> {
    type Error = core::convert::Infallible;
}

impl embedded_hal::digital::OutputPin for Port<OutputPort> {
    #[inline(always)]
    fn set_high(&mut self) -> Result<(), Self::Error> {
        self.set_bits(self.mask);
        Ok(())
    }

    #[inline(always)]
    fn set_low(&mut self) -> Result<(), Self::Error> {
        self.clr_bits(self.mask);
        Ok(())
    }
}

impl embedded_hal::digital::StatefulOutputPin for Port<OutputPort> {
    #[inline(always)]
    fn is_set_high(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_output_bits() > 0)
    }

    #[inline(always)]
    fn is_set_low(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_output_bits() == 0)
    }
}

impl embedded_hal::digital::InputPin for Port<InputPort> {
    #[inline(always)]
    fn is_high(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_input_bits() > 0)
    }

    #[inline(always)]
    fn is_low(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_input_bits() == 0)
    }
}