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.

510 lines
14 KiB

7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 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_Rotate.h>
  6. #include <vector>
  7. #include "libs/EmbedisWrap.h"
  8. #include <Stream.h>
  9. #include "libs/StreamInjector.h"
  10. StreamInjector _serial = StreamInjector(TERMINAL_BUFFER_SIZE);
  11. EmbedisWrap embedis(_serial, TERMINAL_BUFFER_SIZE);
  12. #if TERMINAL_SUPPORT
  13. #if SERIAL_RX_ENABLED
  14. char _serial_rx_buffer[TERMINAL_BUFFER_SIZE];
  15. static unsigned char _serial_rx_pointer = 0;
  16. #endif // SERIAL_RX_ENABLED
  17. #endif // TERMINAL_SUPPORT
  18. // -----------------------------------------------------------------------------
  19. // Reverse engineering EEPROM storage format
  20. // -----------------------------------------------------------------------------
  21. unsigned long settingsSize() {
  22. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  23. while (size_t len = EEPROMr.read(pos)) {
  24. if (0xFF == len) break;
  25. pos = pos - len - 2;
  26. }
  27. return SPI_FLASH_SEC_SIZE - pos + EEPROM_DATA_END;
  28. }
  29. // -----------------------------------------------------------------------------
  30. unsigned int settingsKeyCount() {
  31. unsigned count = 0;
  32. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  33. while (size_t len = EEPROMr.read(pos)) {
  34. if (0xFF == len) break;
  35. pos = pos - len - 2;
  36. len = EEPROMr.read(pos);
  37. pos = pos - len - 2;
  38. count ++;
  39. }
  40. return count;
  41. }
  42. String settingsKeyName(unsigned int index) {
  43. String s;
  44. unsigned count = 0;
  45. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  46. while (size_t len = EEPROMr.read(pos)) {
  47. if (0xFF == len) break;
  48. pos = pos - len - 2;
  49. if (count == index) {
  50. s.reserve(len);
  51. for (unsigned char i = 0 ; i < len; i++) {
  52. s += (char) EEPROMr.read(pos + i + 1);
  53. }
  54. break;
  55. }
  56. count++;
  57. len = EEPROMr.read(pos);
  58. pos = pos - len - 2;
  59. }
  60. return s;
  61. }
  62. std::vector<String> _settingsKeys() {
  63. // Get sorted list of keys
  64. std::vector<String> keys;
  65. //unsigned int size = settingsKeyCount();
  66. unsigned int size = settingsKeyCount();
  67. for (unsigned int i=0; i<size; i++) {
  68. //String key = settingsKeyName(i);
  69. String key = settingsKeyName(i);
  70. bool inserted = false;
  71. for (unsigned char j=0; j<keys.size(); j++) {
  72. // Check if we have to insert it before the current element
  73. if (keys[j].compareTo(key) > 0) {
  74. keys.insert(keys.begin() + j, key);
  75. inserted = true;
  76. break;
  77. }
  78. }
  79. // If we could not insert it, just push it at the end
  80. if (!inserted) keys.push_back(key);
  81. }
  82. return keys;
  83. }
  84. // -----------------------------------------------------------------------------
  85. // Commands
  86. // -----------------------------------------------------------------------------
  87. void _settingsHelpCommand() {
  88. // Get sorted list of commands
  89. std::vector<String> commands;
  90. unsigned char size = embedis.getCommandCount();
  91. for (unsigned int i=0; i<size; i++) {
  92. String command = embedis.getCommandName(i);
  93. bool inserted = false;
  94. for (unsigned char j=0; j<commands.size(); j++) {
  95. // Check if we have to insert it before the current element
  96. if (commands[j].compareTo(command) > 0) {
  97. commands.insert(commands.begin() + j, command);
  98. inserted = true;
  99. break;
  100. }
  101. }
  102. // If we could not insert it, just push it at the end
  103. if (!inserted) commands.push_back(command);
  104. }
  105. // Output the list
  106. DEBUG_MSG_P(PSTR("Available commands:\n"));
  107. for (unsigned char i=0; i<commands.size(); i++) {
  108. DEBUG_MSG_P(PSTR("> %s\n"), (commands[i]).c_str());
  109. }
  110. }
  111. void _settingsKeysCommand() {
  112. // Get sorted list of keys
  113. std::vector<String> keys = _settingsKeys();
  114. // Write key-values
  115. DEBUG_MSG_P(PSTR("Current settings:\n"));
  116. for (unsigned int i=0; i<keys.size(); i++) {
  117. String value = getSetting(keys[i]);
  118. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), (keys[i]).c_str(), value.c_str());
  119. }
  120. unsigned long freeEEPROM = SPI_FLASH_SEC_SIZE - settingsSize();
  121. DEBUG_MSG_P(PSTR("Number of keys: %d\n"), keys.size());
  122. DEBUG_MSG_P(PSTR("Current EEPROM sector: %u\n"), EEPROMr.current());
  123. DEBUG_MSG_P(PSTR("Free EEPROM: %d bytes (%d%%)\n"), freeEEPROM, 100 * freeEEPROM / SPI_FLASH_SEC_SIZE);
  124. }
  125. void _settingsFactoryResetCommand() {
  126. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  127. EEPROMr.write(i, 0xFF);
  128. }
  129. EEPROMr.commit();
  130. }
  131. void _settingsInitCommands() {
  132. #if DEBUG_SUPPORT
  133. settingsRegisterCommand(F("CRASH"), [](Embedis* e) {
  134. debugDumpCrashInfo();
  135. debugClearCrashInfo();
  136. DEBUG_MSG_P(PSTR("+OK\n"));
  137. });
  138. #endif
  139. settingsRegisterCommand(F("COMMANDS"), [](Embedis* e) {
  140. _settingsHelpCommand();
  141. DEBUG_MSG_P(PSTR("+OK\n"));
  142. });
  143. settingsRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  144. DEBUG_MSG_P(PSTR("+OK\n"));
  145. resetReason(CUSTOM_RESET_TERMINAL);
  146. _eepromCommit();
  147. ESP.eraseConfig();
  148. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  149. });
  150. #if I2C_SUPPORT
  151. settingsRegisterCommand(F("I2C.SCAN"), [](Embedis* e) {
  152. i2cScan();
  153. DEBUG_MSG_P(PSTR("+OK\n"));
  154. });
  155. settingsRegisterCommand(F("I2C.CLEAR"), [](Embedis* e) {
  156. i2cClearBus();
  157. DEBUG_MSG_P(PSTR("+OK\n"));
  158. });
  159. #endif
  160. settingsRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  161. _settingsFactoryResetCommand();
  162. DEBUG_MSG_P(PSTR("+OK\n"));
  163. });
  164. settingsRegisterCommand(F("GPIO"), [](Embedis* e) {
  165. if (e->argc < 2) {
  166. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  167. return;
  168. }
  169. int pin = String(e->argv[1]).toInt();
  170. //if (!gpioValid(pin)) {
  171. // DEBUG_MSG_P(PSTR("-ERROR: Invalid GPIO\n"));
  172. // return;
  173. //}
  174. if (e->argc > 2) {
  175. bool state = String(e->argv[2]).toInt() == 1;
  176. digitalWrite(pin, state);
  177. }
  178. DEBUG_MSG_P(PSTR("GPIO %d is %s\n"), pin, digitalRead(pin) == HIGH ? "HIGH" : "LOW");
  179. DEBUG_MSG_P(PSTR("+OK\n"));
  180. });
  181. settingsRegisterCommand(F("HEAP"), [](Embedis* e) {
  182. infoMemory("Heap", getInitialFreeHeap(), getFreeHeap());
  183. DEBUG_MSG_P(PSTR("+OK\n"));
  184. });
  185. settingsRegisterCommand(F("STACK"), [](Embedis* e) {
  186. infoMemory("Stack", 4096, getFreeStack());
  187. DEBUG_MSG_P(PSTR("+OK\n"));
  188. });
  189. settingsRegisterCommand(F("HELP"), [](Embedis* e) {
  190. _settingsHelpCommand();
  191. DEBUG_MSG_P(PSTR("+OK\n"));
  192. });
  193. settingsRegisterCommand(F("INFO"), [](Embedis* e) {
  194. info();
  195. DEBUG_MSG_P(PSTR("+OK\n"));
  196. });
  197. settingsRegisterCommand(F("KEYS"), [](Embedis* e) {
  198. _settingsKeysCommand();
  199. DEBUG_MSG_P(PSTR("+OK\n"));
  200. });
  201. settingsRegisterCommand(F("GET"), [](Embedis* e) {
  202. if (e->argc < 2) {
  203. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  204. return;
  205. }
  206. for (unsigned char i = 1; i < e->argc; i++) {
  207. String key = String(e->argv[i]);
  208. String value;
  209. if (!Embedis::get(key, value)) {
  210. DEBUG_MSG_P(PSTR("> %s =>\n"), key.c_str());
  211. continue;
  212. }
  213. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), key.c_str(), value.c_str());
  214. }
  215. DEBUG_MSG_P(PSTR("+OK\n"));
  216. });
  217. settingsRegisterCommand(F("RELOAD"), [](Embedis* e) {
  218. espurnaReload();
  219. DEBUG_MSG_P(PSTR("+OK\n"));
  220. });
  221. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  222. DEBUG_MSG_P(PSTR("+OK\n"));
  223. deferredReset(100, CUSTOM_RESET_TERMINAL);
  224. });
  225. settingsRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  226. EEPROMr.write(EEPROM_CRASH_COUNTER, SYSTEM_CHECK_MAX);
  227. DEBUG_MSG_P(PSTR("+OK\n"));
  228. deferredReset(100, CUSTOM_RESET_TERMINAL);
  229. });
  230. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  231. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  232. DEBUG_MSG_P(PSTR("+OK\n"));
  233. });
  234. settingsRegisterCommand(F("CONFIG"), [](Embedis* e) {
  235. DynamicJsonBuffer jsonBuffer;
  236. JsonObject& root = jsonBuffer.createObject();
  237. settingsGetJson(root);
  238. String output;
  239. root.printTo(output);
  240. DEBUG_MSG(output.c_str());
  241. DEBUG_MSG_P(PSTR("\n+OK\n"));
  242. });
  243. #if not SETTINGS_AUTOSAVE
  244. settingsRegisterCommand(F("SAVE"), [](Embedis* e) {
  245. eepromCommit();
  246. DEBUG_MSG_P(PSTR("\n+OK\n"));
  247. });
  248. #endif
  249. }
  250. // -----------------------------------------------------------------------------
  251. // Key-value API
  252. // -----------------------------------------------------------------------------
  253. void moveSetting(const char * from, const char * to) {
  254. String value = getSetting(from);
  255. if (value.length() > 0) setSetting(to, value);
  256. delSetting(from);
  257. }
  258. template<typename T> String getSetting(const String& key, T defaultValue) {
  259. String value;
  260. if (!Embedis::get(key, value)) value = String(defaultValue);
  261. return value;
  262. }
  263. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  264. return getSetting(key + String(index), defaultValue);
  265. }
  266. String getSetting(const String& key) {
  267. return getSetting(key, "");
  268. }
  269. template<typename T> bool setSetting(const String& key, T value) {
  270. return Embedis::set(key, String(value));
  271. }
  272. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  273. return setSetting(key + String(index), value);
  274. }
  275. bool delSetting(const String& key) {
  276. return Embedis::del(key);
  277. }
  278. bool delSetting(const String& key, unsigned int index) {
  279. return delSetting(key + String(index));
  280. }
  281. bool hasSetting(const String& key) {
  282. return getSetting(key).length() != 0;
  283. }
  284. bool hasSetting(const String& key, unsigned int index) {
  285. return getSetting(key, index, "").length() != 0;
  286. }
  287. void saveSettings() {
  288. #if not SETTINGS_AUTOSAVE
  289. eepromCommit();
  290. #endif
  291. }
  292. void resetSettings() {
  293. _settingsFactoryResetCommand();
  294. }
  295. // -----------------------------------------------------------------------------
  296. // Settings
  297. // -----------------------------------------------------------------------------
  298. void settingsInject(void *data, size_t len) {
  299. _serial.inject((char *) data, len);
  300. }
  301. Stream & settingsSerial() {
  302. return (Stream &) _serial;
  303. }
  304. size_t settingsMaxSize() {
  305. size_t size = EEPROM_SIZE;
  306. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  307. size = (size + 3) & (~3);
  308. return size;
  309. }
  310. bool settingsRestoreJson(JsonObject& data) {
  311. // Check this is an ESPurna configuration file (must have "app":"ESPURNA")
  312. const char* app = data["app"];
  313. if (!app || strcmp(app, APP_NAME) != 0) {
  314. DEBUG_MSG_P(PSTR("[SETTING] Wrong or missing 'app' key\n"));
  315. return false;
  316. }
  317. // Clear settings
  318. bool is_backup = data["backup"];
  319. if (is_backup) {
  320. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  321. EEPROMr.write(i, 0xFF);
  322. }
  323. }
  324. // Dump settings to memory buffer
  325. for (auto element : data) {
  326. if (strcmp(element.key, "app") == 0) continue;
  327. if (strcmp(element.key, "version") == 0) continue;
  328. if (strcmp(element.key, "backup") == 0) continue;
  329. setSetting(element.key, element.value.as<char*>());
  330. }
  331. // Persist to EEPROM
  332. saveSettings();
  333. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  334. return true;
  335. }
  336. void settingsGetJson(JsonObject& root) {
  337. // Get sorted list of keys
  338. std::vector<String> keys = _settingsKeys();
  339. // Add the key-values to the json object
  340. for (unsigned int i=0; i<keys.size(); i++) {
  341. String value = getSetting(keys[i]);
  342. root[keys[i]] = value;
  343. }
  344. }
  345. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  346. Embedis::command(name, call);
  347. };
  348. // -----------------------------------------------------------------------------
  349. // Initialization
  350. // -----------------------------------------------------------------------------
  351. void settingsSetup() {
  352. _serial.callback([](uint8_t ch) {
  353. #if TELNET_SUPPORT
  354. telnetWrite(ch);
  355. #endif
  356. #if DEBUG_SERIAL_SUPPORT
  357. DEBUG_PORT.write(ch);
  358. #endif
  359. });
  360. Embedis::dictionary( F("EEPROM"),
  361. SPI_FLASH_SEC_SIZE,
  362. [](size_t pos) -> char { return EEPROMr.read(pos); },
  363. [](size_t pos, char value) { EEPROMr.write(pos, value); },
  364. #if SETTINGS_AUTOSAVE
  365. []() { eepromCommit(); }
  366. #else
  367. []() {}
  368. #endif
  369. );
  370. _settingsInitCommands();
  371. #if TERMINAL_SUPPORT
  372. #if SERIAL_RX_ENABLED
  373. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  374. #endif // SERIAL_RX_ENABLED
  375. #endif // TERMINAL_SUPPORT
  376. // Register loop
  377. espurnaRegisterLoop(settingsLoop);
  378. }
  379. void settingsLoop() {
  380. #if TERMINAL_SUPPORT
  381. #if DEBUG_SERIAL_SUPPORT
  382. while (DEBUG_PORT.available()) {
  383. _serial.inject(DEBUG_PORT.read());
  384. }
  385. #endif
  386. embedis.process();
  387. #if SERIAL_RX_ENABLED
  388. while (SERIAL_RX_PORT.available() > 0) {
  389. char rc = Serial.read();
  390. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  391. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  392. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  393. _serial_rx_pointer = 0;
  394. }
  395. }
  396. #endif // SERIAL_RX_ENABLED
  397. #endif // TERMINAL_SUPPORT
  398. }