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.

511 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
6 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. ESP.eraseConfig();
  147. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  148. });
  149. #if I2C_SUPPORT
  150. settingsRegisterCommand(F("I2C.SCAN"), [](Embedis* e) {
  151. i2cScan();
  152. DEBUG_MSG_P(PSTR("+OK\n"));
  153. });
  154. settingsRegisterCommand(F("I2C.CLEAR"), [](Embedis* e) {
  155. i2cClearBus();
  156. DEBUG_MSG_P(PSTR("+OK\n"));
  157. });
  158. #endif
  159. settingsRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  160. _settingsFactoryResetCommand();
  161. DEBUG_MSG_P(PSTR("+OK\n"));
  162. });
  163. settingsRegisterCommand(F("GPIO"), [](Embedis* e) {
  164. if (e->argc < 2) {
  165. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  166. return;
  167. }
  168. int pin = String(e->argv[1]).toInt();
  169. //if (!gpioValid(pin)) {
  170. // DEBUG_MSG_P(PSTR("-ERROR: Invalid GPIO\n"));
  171. // return;
  172. //}
  173. if (e->argc > 2) {
  174. bool state = String(e->argv[2]).toInt() == 1;
  175. digitalWrite(pin, state);
  176. }
  177. DEBUG_MSG_P(PSTR("GPIO %d is %s\n"), pin, digitalRead(pin) == HIGH ? "HIGH" : "LOW");
  178. DEBUG_MSG_P(PSTR("+OK\n"));
  179. });
  180. settingsRegisterCommand(F("HEAP"), [](Embedis* e) {
  181. infoMemory("Heap", getInitialFreeHeap(), getFreeHeap());
  182. DEBUG_MSG_P(PSTR("+OK\n"));
  183. });
  184. settingsRegisterCommand(F("STACK"), [](Embedis* e) {
  185. infoMemory("Stack", 4096, getFreeStack());
  186. DEBUG_MSG_P(PSTR("+OK\n"));
  187. });
  188. settingsRegisterCommand(F("HELP"), [](Embedis* e) {
  189. _settingsHelpCommand();
  190. DEBUG_MSG_P(PSTR("+OK\n"));
  191. });
  192. settingsRegisterCommand(F("INFO"), [](Embedis* e) {
  193. info();
  194. DEBUG_MSG_P(PSTR("+OK\n"));
  195. });
  196. settingsRegisterCommand(F("KEYS"), [](Embedis* e) {
  197. _settingsKeysCommand();
  198. DEBUG_MSG_P(PSTR("+OK\n"));
  199. });
  200. settingsRegisterCommand(F("GET"), [](Embedis* e) {
  201. if (e->argc < 2) {
  202. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  203. return;
  204. }
  205. for (unsigned char i = 1; i < e->argc; i++) {
  206. String key = String(e->argv[i]);
  207. String value;
  208. if (!Embedis::get(key, value)) {
  209. DEBUG_MSG_P(PSTR("> %s =>\n"), key.c_str());
  210. continue;
  211. }
  212. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), key.c_str(), value.c_str());
  213. }
  214. DEBUG_MSG_P(PSTR("+OK\n"));
  215. });
  216. #if WEB_SUPPORT
  217. settingsRegisterCommand(F("RELOAD"), [](Embedis* e) {
  218. espurnaReload();
  219. DEBUG_MSG_P(PSTR("+OK\n"));
  220. });
  221. #endif
  222. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  223. DEBUG_MSG_P(PSTR("+OK\n"));
  224. deferredReset(100, CUSTOM_RESET_TERMINAL);
  225. });
  226. settingsRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  227. EEPROMr.write(EEPROM_CRASH_COUNTER, SYSTEM_CHECK_MAX);
  228. DEBUG_MSG_P(PSTR("+OK\n"));
  229. deferredReset(100, CUSTOM_RESET_TERMINAL);
  230. });
  231. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  232. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  233. DEBUG_MSG_P(PSTR("+OK\n"));
  234. });
  235. settingsRegisterCommand(F("CONFIG"), [](Embedis* e) {
  236. DynamicJsonBuffer jsonBuffer;
  237. JsonObject& root = jsonBuffer.createObject();
  238. settingsGetJson(root);
  239. String output;
  240. root.printTo(output);
  241. DEBUG_MSG(output.c_str());
  242. DEBUG_MSG_P(PSTR("\n+OK\n"));
  243. });
  244. #if not SETTINGS_AUTOSAVE
  245. settingsRegisterCommand(F("SAVE"), [](Embedis* e) {
  246. eepromCommit();
  247. DEBUG_MSG_P(PSTR("\n+OK\n"));
  248. });
  249. #endif
  250. }
  251. // -----------------------------------------------------------------------------
  252. // Key-value API
  253. // -----------------------------------------------------------------------------
  254. void moveSetting(const char * from, const char * to) {
  255. String value = getSetting(from);
  256. if (value.length() > 0) setSetting(to, value);
  257. delSetting(from);
  258. }
  259. template<typename T> String getSetting(const String& key, T defaultValue) {
  260. String value;
  261. if (!Embedis::get(key, value)) value = String(defaultValue);
  262. return value;
  263. }
  264. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  265. return getSetting(key + String(index), defaultValue);
  266. }
  267. String getSetting(const String& key) {
  268. return getSetting(key, "");
  269. }
  270. template<typename T> bool setSetting(const String& key, T value) {
  271. return Embedis::set(key, String(value));
  272. }
  273. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  274. return setSetting(key + String(index), value);
  275. }
  276. bool delSetting(const String& key) {
  277. return Embedis::del(key);
  278. }
  279. bool delSetting(const String& key, unsigned int index) {
  280. return delSetting(key + String(index));
  281. }
  282. bool hasSetting(const String& key) {
  283. return getSetting(key).length() != 0;
  284. }
  285. bool hasSetting(const String& key, unsigned int index) {
  286. return getSetting(key, index, "").length() != 0;
  287. }
  288. void saveSettings() {
  289. #if not SETTINGS_AUTOSAVE
  290. eepromCommit();
  291. #endif
  292. }
  293. void resetSettings() {
  294. _settingsFactoryResetCommand();
  295. }
  296. // -----------------------------------------------------------------------------
  297. // Settings
  298. // -----------------------------------------------------------------------------
  299. void settingsInject(void *data, size_t len) {
  300. _serial.inject((char *) data, len);
  301. }
  302. Stream & settingsSerial() {
  303. return (Stream &) _serial;
  304. }
  305. size_t settingsMaxSize() {
  306. size_t size = EEPROM_SIZE;
  307. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  308. size = (size + 3) & (~3);
  309. return size;
  310. }
  311. bool settingsRestoreJson(JsonObject& data) {
  312. // Check this is an ESPurna configuration file (must have "app":"ESPURNA")
  313. const char* app = data["app"];
  314. if (!app || strcmp(app, APP_NAME) != 0) {
  315. DEBUG_MSG_P(PSTR("[SETTING] Wrong or missing 'app' key\n"));
  316. return false;
  317. }
  318. // Clear settings
  319. bool is_backup = data["backup"];
  320. if (is_backup) {
  321. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  322. EEPROMr.write(i, 0xFF);
  323. }
  324. }
  325. // Dump settings to memory buffer
  326. for (auto element : data) {
  327. if (strcmp(element.key, "app") == 0) continue;
  328. if (strcmp(element.key, "version") == 0) continue;
  329. if (strcmp(element.key, "backup") == 0) continue;
  330. setSetting(element.key, element.value.as<char*>());
  331. }
  332. // Persist to EEPROM
  333. saveSettings();
  334. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  335. return true;
  336. }
  337. void settingsGetJson(JsonObject& root) {
  338. // Get sorted list of keys
  339. std::vector<String> keys = _settingsKeys();
  340. // Add the key-values to the json object
  341. for (unsigned int i=0; i<keys.size(); i++) {
  342. String value = getSetting(keys[i]);
  343. root[keys[i]] = value;
  344. }
  345. }
  346. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  347. Embedis::command(name, call);
  348. };
  349. // -----------------------------------------------------------------------------
  350. // Initialization
  351. // -----------------------------------------------------------------------------
  352. void settingsSetup() {
  353. _serial.callback([](uint8_t ch) {
  354. #if TELNET_SUPPORT
  355. telnetWrite(ch);
  356. #endif
  357. #if DEBUG_SERIAL_SUPPORT
  358. DEBUG_PORT.write(ch);
  359. #endif
  360. });
  361. Embedis::dictionary( F("EEPROM"),
  362. SPI_FLASH_SEC_SIZE,
  363. [](size_t pos) -> char { return EEPROMr.read(pos); },
  364. [](size_t pos, char value) { EEPROMr.write(pos, value); },
  365. #if SETTINGS_AUTOSAVE
  366. []() { eepromCommit(); }
  367. #else
  368. []() {}
  369. #endif
  370. );
  371. _settingsInitCommands();
  372. #if TERMINAL_SUPPORT
  373. #if SERIAL_RX_ENABLED
  374. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  375. #endif // SERIAL_RX_ENABLED
  376. #endif // TERMINAL_SUPPORT
  377. // Register loop
  378. espurnaRegisterLoop(settingsLoop);
  379. }
  380. void settingsLoop() {
  381. #if TERMINAL_SUPPORT
  382. #if DEBUG_SERIAL_SUPPORT
  383. while (DEBUG_PORT.available()) {
  384. _serial.inject(DEBUG_PORT.read());
  385. }
  386. #endif
  387. embedis.process();
  388. #if SERIAL_RX_ENABLED
  389. while (SERIAL_RX_PORT.available() > 0) {
  390. char rc = Serial.read();
  391. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  392. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  393. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  394. _serial_rx_pointer = 0;
  395. }
  396. }
  397. #endif // SERIAL_RX_ENABLED
  398. #endif // TERMINAL_SUPPORT
  399. }