Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

447 lines
12 KiB

6 years ago
8 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
  1. /*
  2. SETTINGS MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <EEPROM.h>
  6. #include "spi_flash.h"
  7. #include "libs/EmbedisWrap.h"
  8. #include <vector>
  9. #include <StreamString.h>
  10. #if TELNET_SUPPORT
  11. #include "libs/StreamInjector.h"
  12. #ifdef DEBUG_PORT
  13. StreamInjector _serial = StreamInjector(DEBUG_PORT);
  14. #else
  15. StreamInjector _serial = StreamInjector(Serial);
  16. #endif
  17. EmbedisWrap embedis(_serial);
  18. #else
  19. #ifdef DEBUG_PORT
  20. EmbedisWrap embedis(DEBUG_PORT);
  21. #else
  22. EmbedisWrap embedis(_serial);
  23. #endif
  24. #endif
  25. #if TERMINAL_SUPPORT
  26. #ifdef SERIAL_RX_PORT
  27. char _serial_rx_buffer[SERIAL_RX_BUFFER_SIZE];
  28. static unsigned char _serial_rx_pointer = 0;
  29. #endif
  30. #endif
  31. bool _settings_save = false;
  32. // -----------------------------------------------------------------------------
  33. // Reverse engineering EEPROM storage format
  34. // -----------------------------------------------------------------------------
  35. unsigned long _settingsSize() {
  36. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  37. while (size_t len = EEPROM.read(pos)) {
  38. pos = pos - len - 2;
  39. }
  40. return SPI_FLASH_SEC_SIZE - pos;
  41. }
  42. unsigned int _settingsKeyCount() {
  43. unsigned count = 0;
  44. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  45. while (size_t len = EEPROM.read(pos)) {
  46. pos = pos - len - 2;
  47. len = EEPROM.read(pos);
  48. pos = pos - len - 2;
  49. count ++;
  50. }
  51. return count;
  52. }
  53. String _settingsKeyName(unsigned int index) {
  54. String s;
  55. unsigned count = 0;
  56. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  57. while (size_t len = EEPROM.read(pos)) {
  58. pos = pos - len - 2;
  59. if (count == index) {
  60. s.reserve(len);
  61. for (unsigned char i = 0 ; i < len; i++) {
  62. s += (char) EEPROM.read(pos + i + 1);
  63. }
  64. break;
  65. }
  66. count++;
  67. len = EEPROM.read(pos);
  68. pos = pos - len - 2;
  69. }
  70. return s;
  71. }
  72. // -----------------------------------------------------------------------------
  73. // Commands
  74. // -----------------------------------------------------------------------------
  75. void _settingsHelp() {
  76. // Get sorted list of commands
  77. std::vector<String> commands;
  78. unsigned char size = embedis.getCommandCount();
  79. for (unsigned int i=0; i<size; i++) {
  80. String command = embedis.getCommandName(i);
  81. bool inserted = false;
  82. for (unsigned char j=0; j<commands.size(); j++) {
  83. // Check if we have to insert it before the current element
  84. if (commands[j].compareTo(command) > 0) {
  85. commands.insert(commands.begin() + j, command);
  86. inserted = true;
  87. break;
  88. }
  89. }
  90. // If we could not insert it, just push it at the end
  91. if (!inserted) commands.push_back(command);
  92. }
  93. // Output the list
  94. DEBUG_MSG_P(PSTR("Available commands:\n"));
  95. for (unsigned char i=0; i<commands.size(); i++) {
  96. DEBUG_MSG_P(PSTR("> %s\n"), (commands[i]).c_str());
  97. }
  98. }
  99. void _settingsKeys() {
  100. // Get sorted list of keys
  101. std::vector<String> keys;
  102. //unsigned int size = settingsKeyCount();
  103. unsigned int size = _settingsKeyCount();
  104. for (unsigned int i=0; i<size; i++) {
  105. //String key = settingsKeyName(i);
  106. String key = _settingsKeyName(i);
  107. bool inserted = false;
  108. for (unsigned char j=0; j<keys.size(); j++) {
  109. // Check if we have to insert it before the current element
  110. if (keys[j].compareTo(key) > 0) {
  111. keys.insert(keys.begin() + j, key);
  112. inserted = true;
  113. break;
  114. }
  115. }
  116. // If we could not insert it, just push it at the end
  117. if (!inserted) keys.push_back(key);
  118. }
  119. // Write key-values
  120. DEBUG_MSG_P(PSTR("Current settings:\n"));
  121. for (unsigned int i=0; i<keys.size(); i++) {
  122. String value = getSetting(keys[i]);
  123. DEBUG_MSG_P(PSTR("> %s => %s\n"), (keys[i]).c_str(), value.c_str());
  124. }
  125. unsigned long freeEEPROM = SPI_FLASH_SEC_SIZE - _settingsSize();
  126. DEBUG_MSG_P(PSTR("Number of keys: %d\n"), keys.size());
  127. DEBUG_MSG_P(PSTR("Free EEPROM: %d bytes (%d%%)\n"), freeEEPROM, 100 * freeEEPROM / SPI_FLASH_SEC_SIZE);
  128. }
  129. void _settingsFactoryReset() {
  130. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  131. EEPROM.write(i, 0xFF);
  132. }
  133. EEPROM.commit();
  134. }
  135. void _settingsDump(bool ascii) {
  136. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  137. if (i % 16 == 0) DEBUG_MSG_P(PSTR("\n[%04X] "), i);
  138. byte c = EEPROM.read(i);
  139. if (ascii && 32 <= c && c <= 126) {
  140. DEBUG_MSG_P(PSTR(" %c "), c);
  141. } else {
  142. DEBUG_MSG_P(PSTR("%02X "), c);
  143. }
  144. }
  145. }
  146. void _settingsInitCommands() {
  147. #if DEBUG_SUPPORT
  148. settingsRegisterCommand(F("CRASH"), [](Embedis* e) {
  149. debugDumpCrashInfo();
  150. DEBUG_MSG_P(PSTR("+OK\n"));
  151. });
  152. #endif
  153. settingsRegisterCommand(F("COMMANDS"), [](Embedis* e) {
  154. _settingsHelp();
  155. DEBUG_MSG_P(PSTR("+OK\n"));
  156. });
  157. settingsRegisterCommand(F("EEPROM.DUMP"), [](Embedis* e) {
  158. bool ascii = false;
  159. if (e->argc == 2) ascii = String(e->argv[1]).toInt() == 1;
  160. _settingsDump(ascii);
  161. DEBUG_MSG_P(PSTR("\n+OK\n"));
  162. });
  163. settingsRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  164. DEBUG_MSG_P(PSTR("+OK\n"));
  165. resetReason(CUSTOM_RESET_TERMINAL);
  166. ESP.eraseConfig();
  167. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  168. });
  169. settingsRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  170. _settingsFactoryReset();
  171. DEBUG_MSG_P(PSTR("+OK\n"));
  172. });
  173. settingsRegisterCommand(F("GPIO"), [](Embedis* e) {
  174. if (e->argc < 2) {
  175. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  176. return;
  177. }
  178. int pin = String(e->argv[1]).toInt();
  179. //if (!gpioValid(pin)) {
  180. // DEBUG_MSG_P(PSTR("-ERROR: Invalid GPIO\n"));
  181. // return;
  182. //}
  183. if (e->argc > 2) {
  184. bool state = String(e->argv[2]).toInt() == 1;
  185. digitalWrite(pin, state);
  186. }
  187. DEBUG_MSG_P(PSTR("GPIO %d is %s\n"), pin, digitalRead(pin) == HIGH ? "HIGH" : "LOW");
  188. DEBUG_MSG_P(PSTR("+OK\n"));
  189. });
  190. settingsRegisterCommand(F("HEAP"), [](Embedis* e) {
  191. DEBUG_MSG_P(PSTR("Free HEAP: %d bytes\n"), getFreeHeap());
  192. DEBUG_MSG_P(PSTR("+OK\n"));
  193. });
  194. settingsRegisterCommand(F("HELP"), [](Embedis* e) {
  195. _settingsHelp();
  196. DEBUG_MSG_P(PSTR("+OK\n"));
  197. });
  198. settingsRegisterCommand(F("INFO"), [](Embedis* e) {
  199. welcome();
  200. wifiStatus();
  201. //StreamString s;
  202. //WiFi.printDiag(s);
  203. //DEBUG_MSG(s.c_str());
  204. DEBUG_MSG_P(PSTR("+OK\n"));
  205. });
  206. settingsRegisterCommand(F("KEYS"), [](Embedis* e) {
  207. _settingsKeys();
  208. DEBUG_MSG_P(PSTR("+OK\n"));
  209. });
  210. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  211. DEBUG_MSG_P(PSTR("+OK\n"));
  212. deferredReset(100, CUSTOM_RESET_TERMINAL);
  213. });
  214. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  215. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  216. DEBUG_MSG_P(PSTR("+OK\n"));
  217. });
  218. }
  219. // -----------------------------------------------------------------------------
  220. // Key-value API
  221. // -----------------------------------------------------------------------------
  222. void moveSetting(const char * from, const char * to) {
  223. String value = getSetting(from);
  224. if (value.length() > 0) setSetting(to, value);
  225. delSetting(from);
  226. }
  227. template<typename T> String getSetting(const String& key, T defaultValue) {
  228. String value;
  229. if (!Embedis::get(key, value)) value = String(defaultValue);
  230. return value;
  231. }
  232. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  233. return getSetting(key + String(index), defaultValue);
  234. }
  235. String getSetting(const String& key) {
  236. return getSetting(key, "");
  237. }
  238. template<typename T> bool setSetting(const String& key, T value) {
  239. return Embedis::set(key, String(value));
  240. }
  241. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  242. return setSetting(key + String(index), value);
  243. }
  244. bool delSetting(const String& key) {
  245. return Embedis::del(key);
  246. }
  247. bool delSetting(const String& key, unsigned int index) {
  248. return delSetting(key + String(index));
  249. }
  250. bool hasSetting(const String& key) {
  251. return getSetting(key).length() != 0;
  252. }
  253. bool hasSetting(const String& key, unsigned int index) {
  254. return getSetting(key, index, "").length() != 0;
  255. }
  256. void saveSettings() {
  257. #if not SETTINGS_AUTOSAVE
  258. _settings_save = true;
  259. #endif
  260. }
  261. void resetSettings() {
  262. _settingsFactoryReset();
  263. }
  264. // -----------------------------------------------------------------------------
  265. // Settings
  266. // -----------------------------------------------------------------------------
  267. #if TELNET_SUPPORT
  268. void settingsInject(void *data, size_t len) {
  269. _serial.inject((char *) data, len);
  270. }
  271. #endif
  272. size_t settingsMaxSize() {
  273. size_t size = EEPROM_SIZE;
  274. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  275. size = (size + 3) & (~3);
  276. return size;
  277. }
  278. bool settingsRestoreJson(JsonObject& data) {
  279. const char* app = data["app"];
  280. if (strcmp(app, APP_NAME) != 0) return false;
  281. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  282. EEPROM.write(i, 0xFF);
  283. }
  284. for (auto element : data) {
  285. if (strcmp(element.key, "app") == 0) continue;
  286. if (strcmp(element.key, "version") == 0) continue;
  287. setSetting(element.key, element.value.as<char*>());
  288. }
  289. saveSettings();
  290. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  291. return true;
  292. }
  293. bool settingsGetJson(JsonObject& root) {
  294. unsigned int size = _settingsKeyCount();
  295. for (unsigned int i=0; i<size; i++) {
  296. String key = _settingsKeyName(i);
  297. String value = getSetting(key);
  298. root[key] = value;
  299. }
  300. }
  301. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  302. Embedis::command(name, call);
  303. };
  304. // -----------------------------------------------------------------------------
  305. // Initialization
  306. // -----------------------------------------------------------------------------
  307. void settingsSetup() {
  308. EEPROM.begin(SPI_FLASH_SEC_SIZE);
  309. #if TELNET_SUPPORT
  310. _serial.callback([](uint8_t ch) {
  311. telnetWrite(ch);
  312. });
  313. #endif
  314. Embedis::dictionary( F("EEPROM"),
  315. SPI_FLASH_SEC_SIZE,
  316. [](size_t pos) -> char { return EEPROM.read(pos); },
  317. [](size_t pos, char value) { EEPROM.write(pos, value); },
  318. #if SETTINGS_AUTOSAVE
  319. []() { _settings_save = true; }
  320. #else
  321. []() {}
  322. #endif
  323. );
  324. _settingsInitCommands();
  325. DEBUG_MSG_P(PSTR("[SETTINGS] EEPROM size: %d bytes\n"), SPI_FLASH_SEC_SIZE);
  326. DEBUG_MSG_P(PSTR("[SETTINGS] Settings size: %d bytes\n"), _settingsSize());
  327. #if TERMINAL_SUPPORT
  328. #ifdef SERIAL_RX_PORT
  329. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  330. #endif
  331. #endif
  332. }
  333. void settingsLoop() {
  334. if (_settings_save) {
  335. EEPROM.commit();
  336. _settings_save = false;
  337. }
  338. #if TERMINAL_SUPPORT
  339. embedis.process();
  340. #ifdef SERIAL_RX_PORT
  341. while (SERIAL_RX_PORT.available() > 0) {
  342. char rc = Serial.read();
  343. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  344. if ((_serial_rx_pointer == SERIAL_RX_BUFFER_SIZE) || (rc == 10)) {
  345. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  346. _serial_rx_pointer = 0;
  347. }
  348. }
  349. #endif // SERIAL_RX_PORT
  350. #endif // TERMINAL_SUPPORT
  351. }