supla-device
Loading...
Searching...
No Matches
fram_spi.h
1/*
2 Copyright (C) AC SOFTWARE SP. Z O.O.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18
19/*
20 * This extension depends on Adafruit FRAM SPI library
21 * Please install it from librarary manager in Arduino
22 */
23
24#ifndef SRC_SUPLA_STORAGE_FRAM_SPI_H_
25#define SRC_SUPLA_STORAGE_FRAM_SPI_H_
26
27#include <SPI.h>
28
29#include "Adafruit_FRAM_SPI.h"
30#include "storage.h"
31
32#define SUPLA_FRAM_WRITING_PERIOD 1000
33
34namespace Supla {
35
36class FramSpi : public Storage {
37 public:
38 FramSpi(int8_t clk,
39 int8_t miso,
40 int8_t mosi,
41 int8_t framCs,
42 unsigned int storageStartingOffset = 0)
43 : Storage(storageStartingOffset), fram(clk, miso, mosi, framCs) {
44 setStateSavePeriod(SUPLA_FRAM_WRITING_PERIOD);
45 }
46
47 explicit FramSpi(int8_t framCs, unsigned int storageStartingOffset = 0)
48 : Storage(storageStartingOffset), fram(framCs) {
49 setStateSavePeriod(SUPLA_FRAM_WRITING_PERIOD);
50 }
51
52 bool init() {
53 if (fram.begin()) {
54 Serial.println(F("Storage: FRAM found"));
55 } else {
56 Serial.println(F("Storage: FRAM not found"));
57 }
58
59 return Storage::init();
60 }
61
62 void commit() {}
63
64 protected:
65 int readStorage(unsigned int offset,
66 unsigned char *buf,
67 int size,
68 bool logs) {
69 if (logs) {
70 Serial.print(F("readStorage: "));
71 Serial.print(size);
72 Serial.print(F("; Read: ["));
73 }
74 for (int i = 0; i < size; i++) {
75 buf[i] = fram.read8(offset + i);
76 if (logs) {
77 Serial.print(static_cast<unsigned char *>(buf)[i], HEX);
78 Serial.print(F(" "));
79 }
80 }
81 if (logs) {
82 Serial.println(F("]"));
83 }
84 return size;
85 }
86
87 int writeStorage(unsigned int offset, const unsigned char *buf, int size) {
88 fram.writeEnable(true);
89 fram.write(offset, const_cast<uint8_t *>(buf), size);
90 fram.writeEnable(false);
91 Serial.print(F("Wrote "));
92 Serial.print(size);
93 Serial.print(F(" bytes to storage at "));
94 Serial.println(offset);
95 return size;
96 }
97
98 Adafruit_FRAM_SPI fram;
99};
100
101}; // namespace Supla
102
103#endif // SRC_SUPLA_STORAGE_FRAM_SPI_H_