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.

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