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.

601 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. settingsRegisterCommand(F("SET"), [](Embedis* e) {
  257. if (e->argc != 3) {
  258. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  259. return;
  260. }
  261. String key = String(e->argv[1]);
  262. String value = String(e->argv[2]);
  263. // Hacks for backwards compatibility
  264. if (key.startsWith("ssid")) key.replace("ssid", "wifiName");
  265. if (key.startsWith("pass")) key.replace("pass", "wifiPass");
  266. if (Embedis::set(key, value)) {
  267. DEBUG_MSG_P(PSTR("+OK\n"));
  268. } else {
  269. DEBUG_MSG_P(PSTR("-ERROR: Error storing key-value\n"));
  270. }
  271. });
  272. #if WEB_SUPPORT
  273. settingsRegisterCommand(F("RELOAD"), [](Embedis* e) {
  274. wsReload();
  275. DEBUG_MSG_P(PSTR("+OK\n"));
  276. });
  277. #endif
  278. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  279. DEBUG_MSG_P(PSTR("+OK\n"));
  280. deferredReset(100, CUSTOM_RESET_TERMINAL);
  281. });
  282. settingsRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  283. EEPROMr.write(EEPROM_CRASH_COUNTER, SYSTEM_CHECK_MAX);
  284. DEBUG_MSG_P(PSTR("+OK\n"));
  285. deferredReset(100, CUSTOM_RESET_TERMINAL);
  286. });
  287. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  288. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  289. DEBUG_MSG_P(PSTR("+OK\n"));
  290. });
  291. }
  292. // -----------------------------------------------------------------------------
  293. // Key-value API
  294. // -----------------------------------------------------------------------------
  295. void moveSetting(const char * from, const char * to) {
  296. String value = getSetting(from);
  297. if (value.length() > 0) setSetting(to, value);
  298. delSetting(from);
  299. }
  300. void moveSetting(const char * from, const char * to, unsigned int index) {
  301. String value = getSetting(from, index, "");
  302. if (value.length() > 0) setSetting(to, index, value);
  303. delSetting(from, index);
  304. }
  305. void moveSettings(const char * from, const char * to) {
  306. unsigned int index = 0;
  307. while (index < 100) {
  308. String value = getSetting(from, index, "");
  309. if (value.length() == 0) break;
  310. setSetting(to, index, value);
  311. delSetting(from, index);
  312. index++;
  313. }
  314. }
  315. template<typename T> String getSetting(const String& key, T defaultValue) {
  316. String value;
  317. if (!Embedis::get(key, value)) value = String(defaultValue);
  318. return value;
  319. }
  320. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  321. return getSetting(key + String(index), defaultValue);
  322. }
  323. String getSetting(const String& key) {
  324. return getSetting(key, "");
  325. }
  326. template<typename T> bool setSetting(const String& key, T value) {
  327. return Embedis::set(key, String(value));
  328. }
  329. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  330. return setSetting(key + String(index), value);
  331. }
  332. bool delSetting(const String& key) {
  333. return Embedis::del(key);
  334. }
  335. bool delSetting(const String& key, unsigned int index) {
  336. return delSetting(key + String(index));
  337. }
  338. bool hasSetting(const String& key) {
  339. return getSetting(key).length() != 0;
  340. }
  341. bool hasSetting(const String& key, unsigned int index) {
  342. return getSetting(key, index, "").length() != 0;
  343. }
  344. void saveSettings() {
  345. #if not SETTINGS_AUTOSAVE
  346. _settings_save = true;
  347. #endif
  348. }
  349. void resetSettings() {
  350. _settingsFactoryResetCommand();
  351. }
  352. // -----------------------------------------------------------------------------
  353. // Settings
  354. // -----------------------------------------------------------------------------
  355. void settingsInject(void *data, size_t len) {
  356. _serial.inject((char *) data, len);
  357. }
  358. Stream & settingsSerial() {
  359. return (Stream &) _serial;
  360. }
  361. size_t settingsMaxSize() {
  362. size_t size = EEPROM_SIZE;
  363. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  364. size = (size + 3) & (~3);
  365. return size;
  366. }
  367. bool settingsRestoreJson(JsonObject& data) {
  368. // Check this is an ESPurna configuration file (must have "app":"ESPURNA")
  369. const char* app = data["app"];
  370. if (!app || strcmp(app, APP_NAME) != 0) {
  371. DEBUG_MSG_P(PSTR("[SETTING] Wrong or missing 'app' key\n"));
  372. return false;
  373. }
  374. // Clear settings
  375. bool is_backup = data["backup"];
  376. if (is_backup) {
  377. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  378. EEPROMr.write(i, 0xFF);
  379. }
  380. }
  381. // Dump settings to memory buffer
  382. for (auto element : data) {
  383. if (strcmp(element.key, "app") == 0) continue;
  384. if (strcmp(element.key, "version") == 0) continue;
  385. if (strcmp(element.key, "backup") == 0) continue;
  386. if (strcmp(element.key, "timestamp") == 0) continue;
  387. setSetting(element.key, element.value.as<char*>());
  388. }
  389. // Persist to EEPROM
  390. saveSettings();
  391. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  392. return true;
  393. }
  394. void settingsGetJson(JsonObject& root) {
  395. // Get sorted list of keys
  396. std::vector<String> keys = _settingsKeys();
  397. // Add the key-values to the json object
  398. for (unsigned int i=0; i<keys.size(); i++) {
  399. String value = getSetting(keys[i]);
  400. root[keys[i]] = value;
  401. }
  402. }
  403. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  404. Embedis::command(name, call);
  405. };
  406. void settingsRegisterKeyCheck(setting_key_check_callback_f callback) {
  407. _setting_key_check_callbacks.push_back(callback);
  408. }
  409. // -----------------------------------------------------------------------------
  410. // Initialization
  411. // -----------------------------------------------------------------------------
  412. void settingsSetup() {
  413. EEPROMr.begin(SPI_FLASH_SEC_SIZE);
  414. _serial.callback([](uint8_t ch) {
  415. #if TELNET_SUPPORT
  416. telnetWrite(ch);
  417. #endif
  418. #if DEBUG_SERIAL_SUPPORT
  419. DEBUG_PORT.write(ch);
  420. #endif
  421. });
  422. Embedis::dictionary( F("EEPROM"),
  423. SPI_FLASH_SEC_SIZE,
  424. [](size_t pos) -> char { return EEPROMr.read(pos); },
  425. [](size_t pos, char value) { EEPROMr.write(pos, value); },
  426. #if SETTINGS_AUTOSAVE
  427. []() { _settings_save = true; }
  428. #else
  429. []() {}
  430. #endif
  431. );
  432. _settingsInitCommands();
  433. #if TERMINAL_SUPPORT
  434. #if SERIAL_RX_ENABLED
  435. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  436. #endif // SERIAL_RX_ENABLED
  437. #endif // TERMINAL_SUPPORT
  438. // Register key check
  439. settingsRegisterKeyCheck(_settingsKeyCheck);
  440. // Register loop
  441. espurnaRegisterLoop(settingsLoop);
  442. }
  443. void settingsLoop() {
  444. if (_settings_save) {
  445. EEPROMr.commit();
  446. _settings_save = false;
  447. }
  448. #if TERMINAL_SUPPORT
  449. #if DEBUG_SERIAL_SUPPORT
  450. while (DEBUG_PORT.available()) {
  451. _serial.inject(DEBUG_PORT.read());
  452. }
  453. #endif
  454. embedis.process();
  455. #if SERIAL_RX_ENABLED
  456. while (SERIAL_RX_PORT.available() > 0) {
  457. char rc = Serial.read();
  458. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  459. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  460. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  461. _serial_rx_pointer = 0;
  462. }
  463. }
  464. #endif // SERIAL_RX_ENABLED
  465. #endif // TERMINAL_SUPPORT
  466. }