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
/* generic.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Generic serial EEPROM implementations


// Imports ===================================================================
use core::cell::RefCell;
use avr_oxide::devices::serialbus::{SerialBusClient,UsesSerialBusClient};
use avrox_storage::{RandomRead, RandomWrite, SAddr, SSize};
use avrox_storage::random::{AccessHint, Storage};
use avr_oxide::OxideResult::{Ok,Err};

// Declarations ==============================================================
/// 8 bit wide data, 16 bit wide address implementation, with big-endian
/// addressing.
pub struct SerPromD8A16be<const PROM_SIZE: u32, const PAGESIZE: u16, BC: SerialBusClient> {
  bus: RefCell<BC>
}

// Code ======================================================================
impl<const PROM_SIZE:u32, const PAGESIZE:u16, BC> UsesSerialBusClient<BC> for SerPromD8A16be<PROM_SIZE,PAGESIZE,BC>
  where
    BC: SerialBusClient
{
  fn using_client(client: BC) -> Self {
    SerPromD8A16be {
      bus: RefCell::new(client)
    }
  }
}

impl<const PROM_SIZE:u32, const PAGESIZE:u16, BC> SerPromD8A16be<PROM_SIZE,PAGESIZE,BC>
where
  BC: SerialBusClient
{
  fn reduce_len_to_page_boundary(&self, addr: u16, len: u16) -> u16 {
    let page_max = (((addr / PAGESIZE) + 1) * PAGESIZE)-1;
    let max_len = (page_max - addr)+1;

    if max_len > len {
      len
    } else {
      max_len
    }
  }
}

impl<const PROM_SIZE:u32, const PAGESIZE:u16, BC> Storage for SerPromD8A16be<PROM_SIZE,PAGESIZE,BC>
where
  BC: SerialBusClient
{
  const ADDRESSABLE_BYTES: SSize = PROM_SIZE as SSize;
}

impl<const PROM_SIZE:u32, const PAGESIZE:u16, BC> RandomRead for SerPromD8A16be<PROM_SIZE,PAGESIZE,BC>
  where
    BC: SerialBusClient
{
  fn read_at_hinted(&self, addr: SAddr, buf: &mut [u8], _hint: AccessHint) -> avr_oxide::io::Result<usize> {
    if addr < PROM_SIZE {
      let addr = addr as u16;

      let max_bytes = self.reduce_len_to_page_boundary(addr, buf.len() as u16);

      let data_buf = &mut buf[0..max_bytes as usize];

      let addr_buf = [
        (addr >> 8) as u8,
        addr as u8
      ];

      match self.bus.borrow_mut().write_then_read(&addr_buf, data_buf) {
        Ok(bytes) => {
          Ok(bytes)
        },
        Err(_) => {
          Err(avr_oxide::io::IoError::Unknown)
        }
      }
    } else {
      Err(avr_oxide::io::IoError::EndOfFile)
    }
  }
}

impl<const PROM_SIZE:u32, const PAGESIZE:u16, BC> RandomWrite for SerPromD8A16be<PROM_SIZE,PAGESIZE,BC>
  where
    BC: SerialBusClient
{
  fn write_at_hinted(&mut self, addr: SAddr, buf: &[u8], _hint: AccessHint) -> avr_oxide::io::Result<usize> {
    if addr < PROM_SIZE {
      let addr = addr as u16;

      let max_bytes = self.reduce_len_to_page_boundary(addr, buf.len() as u16);

      let command_buf = [
        &[
          (addr >> 8) as u8,
          addr as u8
        ],
        &buf[0..max_bytes as usize]
      ];

      match self.bus.borrow_mut().write_from_multiple(&command_buf) {
        Ok(_) => {
          Ok(max_bytes as usize)
        },
        Err(_) => {
          Err(avr_oxide::io::IoError::Unknown)
        }
      }
    } else {
      Err(avr_oxide::io::IoError::NoFreeSpace)
    }
  }

  fn flush(&mut self) -> avr_oxide::io::Result<()> {
    // We don't have buffers to flush, so this will always succeed
    Ok(())
  }
}

// Tests =====================================================================
#[cfg(test)]
pub mod dummy {
  use avr_oxide::devices::serialbus::SerialBusClient;
  use avr_oxide::hal::generic::twi::{TwiAddr, TwiError};
  use avr_oxide::OxideResult;
  use avr_oxide::OxideResult::{Ok,Err};

  /// A dummy bus client that implements typical behaviour of a serial PROM
  /// where only the last 8 bits of the address register increment with
  /// each read/write operation, wrapping at the end.  Effectively we can
  /// only read/write a page at a time without re-sending the address
  /// register to update the upper bits of the read/write address.
  pub struct DummyPromBusClient<const BASEADDR: u8,const SIZE: usize> {
    i2c_addr: TwiAddr,
    page_addr_register: u32,
    byte_addr_register: u8,
    data: [u8; SIZE]
  }

  impl<const BASEADDR: u8, const SIZE: usize> DummyPromBusClient<BASEADDR,SIZE> {
    pub fn new() -> Self {
      Self {
        i2c_addr: TwiAddr::addr(BASEADDR),
        page_addr_register: 0xdeadbeef,
        byte_addr_register: 0xff,
        data: [0xff; SIZE]
      }
    }

    fn get_addr_postincrement(&mut self) -> u32 {
      let addr = self.page_addr_register + self.byte_addr_register as u32;

      self.byte_addr_register = self.byte_addr_register.overflowing_add(1).0;

      addr
    }

    fn set_addr(&mut self, addr_buffer: &[u8]) {
      self.page_addr_register = (addr_buffer[0] as u32) << 8;
      self.byte_addr_register = addr_buffer[1];
    }
  }

  impl<const BASEADDR: u8, const SIZE: usize> SerialBusClient for DummyPromBusClient<BASEADDR,SIZE> {
    fn get_bus_addr(&self) -> TwiAddr {
      self.i2c_addr
    }

    fn clone_with_bus_addr(&self, addr: TwiAddr) -> Self {
      Self {
        i2c_addr: addr,
        page_addr_register: 0xdeadbeef,
        byte_addr_register: 0xff,
        data: [0xff; SIZE]
      }
    }

    fn write_from(&mut self, buffer: &[u8]) -> OxideResult<(), TwiError> {
      for byte in buffer {
        let addr = self.get_addr_postincrement();

        self.data[addr as usize] = *byte;
      }
      Ok(())
    }

    fn write_from_multiple(&mut self, buffers: &[&[u8]]) -> OxideResult<(), TwiError> {
      self.set_addr(buffers[0]);
      for buffer in &buffers[1..] {
        self.write_from(*buffer)?;
      }
      Ok(())
    }

    fn read_into(&mut self, buffer: &mut [u8]) -> OxideResult<usize, TwiError> {
      let mut bytes = 0usize;

      for byte in buffer {
        let addr = self.get_addr_postincrement();

        *byte = self.data[addr as usize];
        bytes += 1;
      }
      Ok(bytes)
    }

    fn write_then_read(&mut self, command: &[u8], result: &mut [u8]) -> OxideResult<usize, TwiError> {
      self.set_addr(&command);
      self.read_into(result)
    }

    fn write_multiple_then_read(&mut self, commands: &[&[u8]], result: &mut [u8]) -> OxideResult<usize, TwiError> {
      unimplemented!()
    }
  }
}

#[cfg(test)]
pub mod tests {
  use avrox_storage::serprom::generic::dummy::DummyPromBusClient;
  use avrox_storage::serprom::generic::SerPromD8A16be;
  use avr_oxide::devices::serialbus::UsesSerialBusClient;
  use avrox_storage::{RandomRead,RandomWrite};

  pub type TestProm = SerPromD8A16be<65536,256,DummyPromBusClient<0x50,65536>>;

  #[test]
  fn test_basic_prom_operations() {
    let mut test_prom = TestProm::using_client(DummyPromBusClient::new());
    let mut buffer = [ 0x00u8, 0x00u8, 0x00u8, 0x00u8 ];

    // Check basic write/read
    test_prom.write_all_at(0x0000u32, &[ 0x01u8, 0x02u8, 0x03u8, 0x04u8 ]).unwrap();
    test_prom.read_full_at(0x0000u32, &mut buffer).unwrap();
    assert_eq!(buffer, [ 0x01u8, 0x02u8, 0x03u8, 0x04u8 ]);

    // Check basic write/read at a different address
    test_prom.write_all_at(0x0123u32, &[ 0x01u8, 0x02u8, 0x03u8, 0x04u8 ]).unwrap();
    test_prom.read_full_at(0x0123u32, &mut buffer).unwrap();
    assert_eq!(buffer, [ 0x01u8, 0x02u8, 0x03u8, 0x04u8 ]);

  }

  #[test]
  fn test_prom_page_boundaries() {
    let mut test_prom = TestProm::using_client(DummyPromBusClient::new());
    let mut buffer = [ 0x00u8, 0x00u8, 0x00u8, 0x00u8 ];

    // The following write should wrap over the end of a page boundary,
    // so if the PROM driver implementation is wrong we'll corrupt ram
    test_prom.write_all_at(0x02feu32, &[ 0xde, 0xad, 0xbe, 0xef ]).unwrap();

    // This read should 'appear' to work, because the read will also wrap
    // at the boundary
    test_prom.read_full_at(0x02feu32, &mut buffer).unwrap();
    assert_eq!(buffer, [ 0xde, 0xad, 0xbe, 0xef ]);

    // But we must check it's actually right...
    test_prom.read_full_at(0x0300u32, &mut buffer).unwrap();
    assert_eq!(buffer, [ 0xbe, 0xef, 0xff, 0xff ]);

    // And didn't write at the beginning of the page
    test_prom.read_full_at(0x0200u32, &mut buffer).unwrap();
    assert_eq!(buffer, [ 0xff, 0xff, 0xff, 0xff ]);
  }
}