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
//!HAL abstraction for EEPROM
//!
use core::marker;

#[derive(ufmt::derive::uDebug, Debug)]
pub struct OutOfBoundsError;

/// Internal trait for low-level EEPROM peripherals.
///
/// This trait defines the common interface for all EEPROM peripheral variants.
pub trait EepromOps<H> {
    const CAPACITY: u16;

    /// Read a single byte from offset `address`.  Does not do a bounds check.
    ///
    /// **Warning**: This is a low-level method and should not be called directly from user code.
    fn raw_read_byte(&self, address: u16) -> u8;
    /// Erase and write a single byte at offset `address`.  Does not do a bounds check.
    ///
    /// **Warning**: This is a low-level method and should not be called directly from user code.
    fn raw_write_byte(&mut self, address: u16, data: u8);
    /// Erase a single byte at offset `address`.  Does not do a bounds check.
    ///
    /// **Warning**: This is a low-level method and should not be called directly from user code.
    fn raw_erase_byte(&mut self, address: u16);
}

pub struct Eeprom<H, EEPROM> {
    p: EEPROM,
    _h: marker::PhantomData<H>,
}

impl<H, EEPROM> Eeprom<H, EEPROM>
where
    EEPROM: EepromOps<H>,
{
    pub const CAPACITY: u16 = EEPROM::CAPACITY;

    #[inline]
    pub fn new(p: EEPROM) -> Self {
        Self {
            p,
            _h: marker::PhantomData,
        }
    }
    #[inline]
    pub fn capacity(&self) -> u16 {
        Self::CAPACITY
    }

    #[inline]
    pub fn read_byte(&self, offset: u16) -> u8 {
        assert!(offset < Self::CAPACITY);
        self.p.raw_read_byte(offset)
    }

    #[inline]
    pub fn write_byte(&mut self, offset: u16, data: u8) {
        assert!(offset < Self::CAPACITY);
        self.p.raw_write_byte(offset, data)
    }

    #[inline]
    pub fn erase_byte(&mut self, offset: u16) {
        assert!(offset < Self::CAPACITY);
        self.p.raw_erase_byte(offset)
    }

    pub fn read(&self, offset: u16, buf: &mut [u8]) -> Result<(), OutOfBoundsError> {
        if buf.len() as u16 + offset > Self::CAPACITY {
            return Err(OutOfBoundsError);
        }
        for (i, byte) in buf.iter_mut().enumerate() {
            *byte = self.p.raw_read_byte(offset + i as u16);
        }
        Ok(())
    }

    pub fn write(&mut self, offset: u16, buf: &[u8]) -> Result<(), OutOfBoundsError> {
        if buf.len() as u16 + offset > Self::CAPACITY {
            return Err(OutOfBoundsError);
        }

        for (i, byte) in buf.iter().enumerate() {
            self.p.raw_write_byte(offset + i as u16, *byte)
        }
        Ok(())
    }

    pub fn erase(&mut self, from: u16, to: u16) -> Result<(), OutOfBoundsError> {
        if to > Self::CAPACITY || from > to {
            return Err(OutOfBoundsError);
        }

        for i in from..to {
            self.p.raw_erase_byte(i)
        }

        Ok(())
    }
}

impl<H, EEPROM> embedded_storage::nor_flash::ReadNorFlash for Eeprom<H, EEPROM>
where
    EEPROM: EepromOps<H>,
{
    type Error = OutOfBoundsError;
    const READ_SIZE: usize = 1;

    fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
        Eeprom::<H, EEPROM>::read(self, offset as u16, bytes)
    }

    fn capacity(&self) -> usize {
        Eeprom::<H, EEPROM>::capacity(self) as usize
    }
}

impl<H, EEPROM> embedded_storage::nor_flash::NorFlash for Eeprom<H, EEPROM>
where
    EEPROM: EepromOps<H>,
{
    const WRITE_SIZE: usize = 1;
    const ERASE_SIZE: usize = 1;
    fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
        Eeprom::<H, EEPROM>::erase(self, from as u16, to as u16)
    }

    fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        Eeprom::<H, EEPROM>::write(self, offset as u16, bytes)
    }
}
// AVR supports multiple writes
impl<H, EEPROM> embedded_storage::nor_flash::MultiwriteNorFlash for Eeprom<H, EEPROM> where
    EEPROM: EepromOps<H>
{
}

#[macro_export]
macro_rules! impl_eeprom_common {
    (
        hal: $HAL:ty,
        peripheral: $EEPROM:ty,
        capacity: $capacity:literal,
        addr_width: $addrwidth:ty,
        set_address: |$periph_var:ident, $address:ident| $set_address:block,
        set_erasewrite_mode: |$periph_ewmode_var:ident| $set_erasewrite_mode:block,
        set_erase_mode: |$periph_emode_var:ident| $set_erase_mode:block,
        set_write_mode: |$periph_wmode_var:ident| $set_write_mode:block,
    ) => {
        impl $crate::eeprom::EepromOps<$HAL> for $EEPROM {
            const CAPACITY: u16 = $capacity;

            fn raw_read_byte(&self, address: u16) -> u8 {
                unsafe {
                    {
                        let $periph_var = &self;
                        let $address = address as $addrwidth;
                        $set_address
                    }

                    self.eecr.write(|w| w.eere().set_bit());
                    self.eedr.read().bits()
                }
            }

            fn raw_write_byte(&mut self, address: u16, data: u8) {
                unsafe {
                    {
                        let $periph_var = &self;
                        let $address = address as $addrwidth;
                        $set_address
                    }

                    //Start EEPROM read operation
                    self.eecr.write(|w| w.eere().set_bit());
                    let old_value = self.eedr.read().bits();
                    let diff_mask = old_value ^ data;

                    // Check if any bits are changed to '1' in the new value.
                    if (diff_mask & data) != 0 {
                        // Now we know that _some_ bits need to be erased to '1'.

                        // Check if any bits in the new value are '0'.
                        if data != 0xff {
                            // Now we know that some bits need to be programmed to '0' also.
                            self.eedr.write(|w| w.bits(data)); // Set EEPROM data register.

                            {
                                let $periph_ewmode_var = &self;
                                $set_erasewrite_mode
                            }
                            self.eecr.modify(|_, w| w.eepe().set_bit()); // Start Erase+Write operation.
                        } else {
                            // Now we know that all bits should be erased.
                            {
                                let $periph_emode_var = &self;
                                $set_erase_mode
                            }
                            self.eecr.modify(|_, w| w.eepe().set_bit()); // Start Erase-only operation.
                        }
                    }
                    //Now we know that _no_ bits need to be erased to '1'.
                    else {
                        // Check if any bits are changed from '1' in the old value.
                        if diff_mask != 0 {
                            // Now we know that _some_ bits need to the programmed to '0'.
                            self.eedr.write(|w| w.bits(data)); // Set EEPROM data register.
                            {
                                let $periph_wmode_var = &self;
                                $set_write_mode
                            }
                            self.eecr.modify(|_, w| w.eepe().set_bit()); // Start Write-only operation.
                        }
                    }
                }
            }

            fn raw_erase_byte(&mut self, address: u16) {
                unsafe {
                    {
                        let $periph_var = &self;
                        let $address = address as $addrwidth;
                        $set_address
                    }
                    // Now we know that all bits should be erased.
                    {
                        let $periph_emode_var = &self;
                        $set_erase_mode
                    }
                    // Start Erase-only operation.
                    self.eecr.modify(|_, w| w.eepe().set_bit());
                }
            }
        }
    };
}

#[macro_export]
macro_rules! impl_eeprom_atmega_old {
    (
        hal: $HAL:ty,
        peripheral: $EEPROM:ty,
        capacity: $capacity:literal,
        addr_width: $addrwidth:ty,
        set_address: |$periph_var:ident, $address:ident| $set_address:block,
    ) => {
        mod atmega_helper {
            #[inline]
            pub unsafe fn wait_read(regs: &$EEPROM) {
                //Wait for completion of previous write.
                while regs.eecr.read().eewe().bit_is_set() {}
            }

            #[inline]
            pub unsafe fn set_address(regs: &$EEPROM, address: u16) {
                wait_read(regs);
                let $periph_var = regs;
                let $address = address;
                $set_address
            }
        }

        impl $crate::eeprom::EepromOps<$HAL> for $EEPROM {
            const CAPACITY: u16 = $capacity;

            fn raw_read_byte(&self, address: u16) -> u8 {
                unsafe {
                    atmega_helper::set_address(&self, address);
                }
                self.eecr.write(|w| w.eere().set_bit());
                self.eedr.read().bits()
            }

            fn raw_write_byte(&mut self, address: u16, data: u8) {
                unsafe {
                    atmega_helper::set_address(&self, address);
                }

                //Start EEPROM read operation
                self.eedr.write(|w| unsafe { w.bits(data) });

                self.eecr.write(|w| w.eemwe().set_bit().eewe().clear_bit());

                self.eecr.write(|w| w.eewe().set_bit());
            }

            fn raw_erase_byte(&mut self, address: u16) {
                self.raw_write_byte(address, 0);
            }
        }
    };
}

#[macro_export]
macro_rules! impl_eeprom_atmega {
    (
        hal: $HAL:ty,
        peripheral: $EEPROM:ty,
        capacity: $capacity:literal,
        addr_width: $addrwidth:ty,
        set_address: |$periph_var:ident, $address:ident| $set_address:block,
    ) => {
        mod atmega_helper {
            #[inline]
            pub unsafe fn wait_read(regs: &$EEPROM) {
                //Wait for completion of previous write.
                while regs.eecr.read().eepe().bit_is_set() {}
            }
            #[inline]
            pub unsafe fn set_address(regs: &$EEPROM, address: $addrwidth) {
                wait_read(regs);
                let $periph_var = regs;
                let $address = address;
                $set_address
            }
            #[inline]
            pub unsafe fn set_erasewrite_mode(regs: &$EEPROM) {
                regs.eecr.write(|w| {
                    // Set Master Write Enable bit, and and Erase+Write mode mode..
                    w.eempe().set_bit().eepm().val_0x00()
                })
            }
            #[inline]
            pub unsafe fn set_erase_mode(regs: &$EEPROM) {
                regs.eecr.write(|w| {
                    // Set Master Write Enable bit, and Erase-only mode..
                    w.eempe().set_bit().eepm().val_0x01()
                });
            }
            #[inline]
            pub unsafe fn set_write_mode(regs: &$EEPROM) {
                regs.eecr.write(|w| {
                    // Set Master Write Enable bit, and Write-only mode..
                    w.eempe().set_bit().eepm().val_0x02()
                });
            }
        }

        $crate::impl_eeprom_common! {
            hal: $HAL,
            peripheral: $EEPROM,
            capacity: $capacity,
            addr_width: $addrwidth,
            set_address: |peripheral, address| {atmega_helper::set_address(peripheral, address)},
            set_erasewrite_mode: |peripheral| {atmega_helper::set_erasewrite_mode(peripheral)},
            set_erase_mode: |peripheral| {atmega_helper::set_erase_mode(peripheral)},
            set_write_mode: |peripheral| {atmega_helper::set_write_mode(peripheral)},
        }
    };
}

#[macro_export]
macro_rules! impl_eeprom_attiny {
    (
        hal: $HAL:ty,
        peripheral: $EEPROM:ty,
        capacity: $capacity:literal,
        addr_width: $addrwidth:ty,
        set_address: |$periph_var:ident, $address:ident| $set_address:block,
    ) => {
        mod attiny_helper {
            #[inline]
            pub unsafe fn wait_read(regs: &$EEPROM) {
                while regs.eecr.read().eepe().bit_is_set() {}
            }
            #[inline]
            pub unsafe fn set_address(regs: &$EEPROM, address: $addrwidth) {
                wait_read(regs);
                let $periph_var = regs;
                let $address = address;
                $set_address
            }
            #[inline]
            pub unsafe fn set_erasewrite_mode(regs: &$EEPROM) {
                regs.eecr.write(|w| {
                    // Set Master Write Enable bit...and and Erase+Write mode mode..
                    w.eempe().set_bit().eepm().atomic()
                });
            }
            #[inline]
            pub unsafe fn set_erase_mode(regs: &$EEPROM) {
                regs.eecr.write(|w| {
                    // Set Master Write Enable bit, and Erase-only mode..
                    w.eempe().set_bit().eepm().erase()
                });
            }
            #[inline]
            pub unsafe fn set_write_mode(regs: &$EEPROM) {
                regs.eecr.write(|w| {
                    // Set Master Write Enable bit, and Write-only mode..
                    w.eempe().set_bit().eepm().write()
                });
            }
        }

        $crate::impl_eeprom_common! {
            hal: $HAL,
            peripheral: $EEPROM,
            capacity: $capacity,
            addr_width: $addrwidth,
            set_address: |peripheral, address| {attiny_helper::set_address(peripheral, address)},
            set_erasewrite_mode: |peripheral| {attiny_helper::set_erasewrite_mode(peripheral)},
            set_erase_mode: |peripheral| {attiny_helper::set_erase_mode(peripheral)},
            set_write_mode: |peripheral| {attiny_helper::set_write_mode(peripheral)},
        }
    };
}