Accessories
Arduino for motors and lights library.
AccessoriesCircularBuffer.cpp
1 /*************************************************************
2 project: <Accessories>
3 author: <Thierry PARIS>
4 description: <Class for a circular buffer of data stored in EEPROM>
5 *************************************************************/
6 
7 // Copied from EEPROMExtent library
8 
9 #include "Accessories.h"
10 #ifndef NO_EEPROM
11 #include "AccessoriesCircularBuffer.hpp"
12 #include <EEPROM.h>
13 
14 /*
15 A circular buffer is a way to reduce the use of each EEPROM cell,
16 and improve life time of the full EEPROM memory.
17 An index of bytes is stored at the beginning of the area.
18 Each index represents a data area.
19 
20 |0|1|2|3|4||---0---|---1---|---2---|---3---|---4---|
21 
22 */
23 
24 byte AccessoriesCircularBuffer::FindEnd()
25 {
26  /*
27  prev is the previous value from the item in the list
28  |..|..|prev|i|..|..|
29 
30  we begin with the first item of the list. In this case, the previous is the last one:
31  |i|..|..|..|..|prev|
32  */
33 
34  int prevpos = this->StartListPos + this->ReplicaNumber - 1;
35  byte prev = EEPROM.read(prevpos);
36 
37  for (int i = 0; i < this->ReplicaNumber; i++)
38  {
39  int pos = this->StartListPos + i;
40 
41  // Checks it the current value is really the previous value + 1 :
42  // 4 must be 3+1, 0 must be 255 + 1 !
43  if (prev + 1 != EEPROM.read(pos))
44  return prevpos - this->StartListPos;
45 
46  prev = EEPROM.read(pos);
47  prevpos = pos;
48  }
49 
50  // Should never reach this code !
51 
52  return 255;
53 }
54 
56 {
57  for (int i = this->StartListPos; i < this->StartListPos + (this->ItemSize + 1) * this->ReplicaNumber; i++)
58  EEPROM.write(i, 0);
59 }
60 
62 {
63  byte place = FindEnd();
64  return this->StartListPos + this->ReplicaNumber + (this->ItemSize * place);
65 }
66 
68 {
69  byte place = FindEnd();
70  byte itemNb = EEPROM.read(this->StartListPos + place);
71 
72  place++;
73  if (place >= this->ReplicaNumber)
74  place = 0;
75 
76  EEPROM.update(this->StartListPos + place, ++itemNb);
77 
78  return this->StartListPos + this->ReplicaNumber + (this->ItemSize * place);
79 }
80 
81 #ifdef ACCESSORIES_DEBUG_MODE
82 void AccessoriesCircularBuffer::printStatus()
83 {
84  Serial.print(F("CB Status : "));
85  for (int i = 0; i < this->ReplicaNumber; i++)
86  {
87  Serial.print(F("|"));
88  Serial.print(EEPROM.read(this->StartListPos + i));
89  }
90  Serial.println(F("|"));
91 }
92 #endif
93 #endif