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
65 protected:
66 int readStorage(unsigned int offset,
67 unsigned char *buf,
68 unsigned int size,
69 bool logs) {
70 if (logs) {
71 Serial.print(F("readStorage: "));
72 Serial.print(size);
73 Serial.print(F("; Read: ["));
74 }
75 for (int i = 0; i < size; i++) {
76 buf[i] = fram.read8(offset + i);
77 if (logs) {
78 Serial.print(static_cast<unsigned char *>(buf)[i], HEX);
79 Serial.print(F(" "));
80 }
81 }
82 if (logs) {
83 Serial.println(F("]"));
84 }
85 return size;
86 }
87
88 int writeStorage(unsigned int offset,
89 const unsigned char *buf,
90 unsigned int size) {
91 fram.writeEnable(true);
92 fram.write(offset, const_cast<uint8_t *>(buf), size);
93 fram.writeEnable(false);
94 Serial.print(F("Wrote "));
95 Serial.print(size);
96 Serial.print(F(" bytes to storage at "));
97 Serial.println(offset);
98 return size;
99 }
100
101 Adafruit_FRAM_SPI fram;
102};
103
104}; // namespace Supla
105
106#endif // SRC_SUPLA_STORAGE_FRAM_SPI_H_