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.

514 lines
14 KiB

6 years ago
6 years ago
6 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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. bool _settings_save = false;
  19. // -----------------------------------------------------------------------------
  20. // Reverse engineering EEPROM storage format
  21. // -----------------------------------------------------------------------------
  22. unsigned long settingsSize() {
  23. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  24. while (size_t len = EEPROMr.read(pos)) {
  25. if (0xFF == len) break;
  26. pos = pos - len - 2;
  27. }
  28. return SPI_FLASH_SEC_SIZE - pos + EEPROM_DATA_END;
  29. }
  30. // -----------------------------------------------------------------------------
  31. unsigned int settingsKeyCount() {
  32. unsigned count = 0;
  33. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  34. while (size_t len = EEPROMr.read(pos)) {
  35. if (0xFF == len) break;
  36. pos = pos - len - 2;
  37. len = EEPROMr.read(pos);
  38. pos = pos - len - 2;
  39. count ++;
  40. }
  41. return count;
  42. }
  43. String settingsKeyName(unsigned int index) {
  44. String s;
  45. unsigned count = 0;
  46. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  47. while (size_t len = EEPROMr.read(pos)) {
  48. if (0xFF == len) break;
  49. pos = pos - len - 2;
  50. if (count == index) {
  51. s.reserve(len);
  52. for (unsigned char i = 0 ; i < len; i++) {
  53. s += (char) EEPROMr.read(pos + i + 1);
  54. }
  55. break;
  56. }
  57. count++;
  58. len = EEPROMr.read(pos);
  59. pos = pos - len - 2;
  60. }
  61. return s;
  62. }
  63. std::vector<String> _settingsKeys() {
  64. // Get sorted list of keys
  65. std::vector<String> keys;
  66. //unsigned int size = settingsKeyCount();
  67. unsigned int size = settingsKeyCount();
  68. for (unsigned int i=0; i<size; i++) {
  69. //String key = settingsKeyName(i);
  70. String key = settingsKeyName(i);
  71. bool inserted = false;
  72. for (unsigned char j=0; j<keys.size(); j++) {
  73. // Check if we have to insert it before the current element
  74. if (keys[j].compareTo(key) > 0) {
  75. keys.insert(keys.begin() + j, key);
  76. inserted = true;
  77. break;
  78. }
  79. }
  80. // If we could not insert it, just push it at the end
  81. if (!inserted) keys.push_back(key);
  82. }
  83. return keys;
  84. }
  85. // -----------------------------------------------------------------------------
  86. // Commands
  87. // -----------------------------------------------------------------------------
  88. void _settingsHelpCommand() {
  89. // Get sorted list of commands
  90. std::vector<String> commands;
  91. unsigned char size = embedis.getCommandCount();
  92. for (unsigned int i=0; i<size; i++) {
  93. String command = embedis.getCommandName(i);
  94. bool inserted = false;
  95. for (unsigned char j=0; j<commands.size(); j++) {
  96. // Check if we have to insert it before the current element
  97. if (commands[j].compareTo(command) > 0) {
  98. commands.insert(commands.begin() + j, command);
  99. inserted = true;
  100. break;
  101. }
  102. }
  103. // If we could not insert it, just push it at the end
  104. if (!inserted) commands.push_back(command);
  105. }
  106. // Output the list
  107. DEBUG_MSG_P(PSTR("Available commands:\n"));
  108. for (unsigned char i=0; i<commands.size(); i++) {
  109. DEBUG_MSG_P(PSTR("> %s\n"), (commands[i]).c_str());
  110. }
  111. }
  112. void _settingsKeysCommand() {
  113. // Get sorted list of keys
  114. std::vector<String> keys = _settingsKeys();
  115. // Write key-values
  116. DEBUG_MSG_P(PSTR("Current settings:\n"));
  117. for (unsigned int i=0; i<keys.size(); i++) {
  118. String value = getSetting(keys[i]);
  119. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), (keys[i]).c_str(), value.c_str());
  120. }
  121. unsigned long freeEEPROM = SPI_FLASH_SEC_SIZE - settingsSize();
  122. DEBUG_MSG_P(PSTR("Number of keys: %d\n"), keys.size());
  123. DEBUG_MSG_P(PSTR("Current EEPROM sector: %u\n"), EEPROMr.current());
  124. DEBUG_MSG_P(PSTR("Free EEPROM: %d bytes (%d%%)\n"), freeEEPROM, 100 * freeEEPROM / SPI_FLASH_SEC_SIZE);
  125. }
  126. void _settingsFactoryResetCommand() {
  127. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  128. EEPROMr.write(i, 0xFF);
  129. }
  130. EEPROMr.commit();
  131. }
  132. void _settingsInitCommands() {
  133. #if DEBUG_SUPPORT
  134. settingsRegisterCommand(F("CRASH"), [](Embedis* e) {
  135. debugDumpCrashInfo();
  136. debugClearCrashInfo();
  137. DEBUG_MSG_P(PSTR("+OK\n"));
  138. });
  139. #endif
  140. settingsRegisterCommand(F("COMMANDS"), [](Embedis* e) {
  141. _settingsHelpCommand();
  142. DEBUG_MSG_P(PSTR("+OK\n"));
  143. });
  144. settingsRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  145. DEBUG_MSG_P(PSTR("+OK\n"));
  146. resetReason(CUSTOM_RESET_TERMINAL);
  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. #if WEB_SUPPORT
  218. settingsRegisterCommand(F("RELOAD"), [](Embedis* e) {
  219. espurnaReload();
  220. DEBUG_MSG_P(PSTR("+OK\n"));
  221. });
  222. #endif
  223. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  224. DEBUG_MSG_P(PSTR("+OK\n"));
  225. deferredReset(100, CUSTOM_RESET_TERMINAL);
  226. });
  227. settingsRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  228. EEPROMr.write(EEPROM_CRASH_COUNTER, SYSTEM_CHECK_MAX);
  229. DEBUG_MSG_P(PSTR("+OK\n"));
  230. deferredReset(100, CUSTOM_RESET_TERMINAL);
  231. });
  232. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  233. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  234. DEBUG_MSG_P(PSTR("+OK\n"));
  235. });
  236. settingsRegisterCommand(F("CONFIG"), [](Embedis* e) {
  237. DynamicJsonBuffer jsonBuffer;
  238. JsonObject& root = jsonBuffer.createObject();
  239. settingsGetJson(root);
  240. String output;
  241. root.printTo(output);
  242. DEBUG_MSG(output.c_str());
  243. DEBUG_MSG_P(PSTR("\n+OK\n"));
  244. });
  245. }
  246. // -----------------------------------------------------------------------------
  247. // Key-value API
  248. // -----------------------------------------------------------------------------
  249. void moveSetting(const char * from, const char * to) {
  250. String value = getSetting(from);
  251. if (value.length() > 0) setSetting(to, value);
  252. delSetting(from);
  253. }
  254. template<typename T> String getSetting(const String& key, T defaultValue) {
  255. String value;
  256. if (!Embedis::get(key, value)) value = String(defaultValue);
  257. return value;
  258. }
  259. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  260. return getSetting(key + String(index), defaultValue);
  261. }
  262. String getSetting(const String& key) {
  263. return getSetting(key, "");
  264. }
  265. template<typename T> bool setSetting(const String& key, T value) {
  266. return Embedis::set(key, String(value));
  267. }
  268. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  269. return setSetting(key + String(index), value);
  270. }
  271. bool delSetting(const String& key) {
  272. return Embedis::del(key);
  273. }
  274. bool delSetting(const String& key, unsigned int index) {
  275. return delSetting(key + String(index));
  276. }
  277. bool hasSetting(const String& key) {
  278. return getSetting(key).length() != 0;
  279. }
  280. bool hasSetting(const String& key, unsigned int index) {
  281. return getSetting(key, index, "").length() != 0;
  282. }
  283. void saveSettings() {
  284. #if not SETTINGS_AUTOSAVE
  285. _settings_save = true;
  286. #endif
  287. }
  288. void resetSettings() {
  289. _settingsFactoryResetCommand();
  290. }
  291. // -----------------------------------------------------------------------------
  292. // Settings
  293. // -----------------------------------------------------------------------------
  294. void settingsInject(void *data, size_t len) {
  295. _serial.inject((char *) data, len);
  296. }
  297. Stream & settingsSerial() {
  298. return (Stream &) _serial;
  299. }
  300. size_t settingsMaxSize() {
  301. size_t size = EEPROM_SIZE;
  302. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  303. size = (size + 3) & (~3);
  304. return size;
  305. }
  306. bool settingsRestoreJson(JsonObject& data) {
  307. // Check this is an ESPurna configuration file (must have "app":"ESPURNA")
  308. const char* app = data["app"];
  309. if (!app || strcmp(app, APP_NAME) != 0) {
  310. DEBUG_MSG_P(PSTR("[SETTING] Wrong or missing 'app' key\n"));
  311. return false;
  312. }
  313. // Clear settings
  314. bool is_backup = data["backup"];
  315. if (is_backup) {
  316. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  317. EEPROMr.write(i, 0xFF);
  318. }
  319. }
  320. // Dump settings to memory buffer
  321. for (auto element : data) {
  322. if (strcmp(element.key, "app") == 0) continue;
  323. if (strcmp(element.key, "version") == 0) continue;
  324. if (strcmp(element.key, "backup") == 0) continue;
  325. setSetting(element.key, element.value.as<char*>());
  326. }
  327. // Persist to EEPROM
  328. saveSettings();
  329. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  330. return true;
  331. }
  332. void settingsGetJson(JsonObject& root) {
  333. // Get sorted list of keys
  334. std::vector<String> keys = _settingsKeys();
  335. // Add the key-values to the json object
  336. for (unsigned int i=0; i<keys.size(); i++) {
  337. String value = getSetting(keys[i]);
  338. root[keys[i]] = value;
  339. }
  340. }
  341. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  342. Embedis::command(name, call);
  343. };
  344. // -----------------------------------------------------------------------------
  345. // Initialization
  346. // -----------------------------------------------------------------------------
  347. void settingsSetup() {
  348. EEPROMr.begin(SPI_FLASH_SEC_SIZE);
  349. _serial.callback([](uint8_t ch) {
  350. #if TELNET_SUPPORT
  351. telnetWrite(ch);
  352. #endif
  353. #if DEBUG_SERIAL_SUPPORT
  354. DEBUG_PORT.write(ch);
  355. #endif
  356. });
  357. Embedis::dictionary( F("EEPROM"),
  358. SPI_FLASH_SEC_SIZE,
  359. [](size_t pos) -> char { return EEPROMr.read(pos); },
  360. [](size_t pos, char value) { EEPROMr.write(pos, value); },
  361. #if SETTINGS_AUTOSAVE
  362. []() { _settings_save = true; }
  363. #else
  364. []() {}
  365. #endif
  366. );
  367. _settingsInitCommands();
  368. #if TERMINAL_SUPPORT
  369. #if SERIAL_RX_ENABLED
  370. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  371. #endif // SERIAL_RX_ENABLED
  372. #endif // TERMINAL_SUPPORT
  373. // Register loop
  374. espurnaRegisterLoop(settingsLoop);
  375. }
  376. void settingsLoop() {
  377. if (_settings_save) {
  378. EEPROMr.commit();
  379. _settings_save = false;
  380. }
  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. }