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