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.

520 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. 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. // -----------------------------------------------------------------------------
  21. // Reverse engineering EEPROM storage format
  22. // -----------------------------------------------------------------------------
  23. unsigned long settingsSize() {
  24. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  25. while (size_t len = EEPROMr.read(pos)) {
  26. pos = pos - len - 2;
  27. }
  28. return SPI_FLASH_SEC_SIZE - pos;
  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. 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. pos = pos - len - 2;
  48. if (count == index) {
  49. s.reserve(len);
  50. for (unsigned char i = 0 ; i < len; i++) {
  51. s += (char) EEPROMr.read(pos + i + 1);
  52. }
  53. break;
  54. }
  55. count++;
  56. len = EEPROMr.read(pos);
  57. pos = pos - len - 2;
  58. }
  59. return s;
  60. }
  61. std::vector<String> _settingsKeys() {
  62. // Get sorted list of keys
  63. std::vector<String> keys;
  64. //unsigned int size = settingsKeyCount();
  65. unsigned int size = settingsKeyCount();
  66. for (unsigned int i=0; i<size; i++) {
  67. //String key = settingsKeyName(i);
  68. String key = settingsKeyName(i);
  69. bool inserted = false;
  70. for (unsigned char j=0; j<keys.size(); j++) {
  71. // Check if we have to insert it before the current element
  72. if (keys[j].compareTo(key) > 0) {
  73. keys.insert(keys.begin() + j, key);
  74. inserted = true;
  75. break;
  76. }
  77. }
  78. // If we could not insert it, just push it at the end
  79. if (!inserted) keys.push_back(key);
  80. }
  81. return keys;
  82. }
  83. // -----------------------------------------------------------------------------
  84. // Commands
  85. // -----------------------------------------------------------------------------
  86. void _settingsHelpCommand() {
  87. // Get sorted list of commands
  88. std::vector<String> commands;
  89. unsigned char size = embedis.getCommandCount();
  90. for (unsigned int i=0; i<size; i++) {
  91. String command = embedis.getCommandName(i);
  92. bool inserted = false;
  93. for (unsigned char j=0; j<commands.size(); j++) {
  94. // Check if we have to insert it before the current element
  95. if (commands[j].compareTo(command) > 0) {
  96. commands.insert(commands.begin() + j, command);
  97. inserted = true;
  98. break;
  99. }
  100. }
  101. // If we could not insert it, just push it at the end
  102. if (!inserted) commands.push_back(command);
  103. }
  104. // Output the list
  105. DEBUG_MSG_P(PSTR("Available commands:\n"));
  106. for (unsigned char i=0; i<commands.size(); i++) {
  107. DEBUG_MSG_P(PSTR("> %s\n"), (commands[i]).c_str());
  108. }
  109. }
  110. void _settingsKeysCommand() {
  111. // Get sorted list of keys
  112. std::vector<String> keys = _settingsKeys();
  113. // Write key-values
  114. DEBUG_MSG_P(PSTR("Current settings:\n"));
  115. for (unsigned int i=0; i<keys.size(); i++) {
  116. String value = getSetting(keys[i]);
  117. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), (keys[i]).c_str(), value.c_str());
  118. }
  119. unsigned long freeEEPROM = SPI_FLASH_SEC_SIZE - settingsSize();
  120. DEBUG_MSG_P(PSTR("Number of keys: %d\n"), keys.size());
  121. DEBUG_MSG_P(PSTR("Current EEPROM sector: %u\n"), EEPROMr.current());
  122. DEBUG_MSG_P(PSTR("Free EEPROM: %d bytes (%d%%)\n"), freeEEPROM, 100 * freeEEPROM / SPI_FLASH_SEC_SIZE);
  123. }
  124. void _settingsFactoryResetCommand() {
  125. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  126. EEPROMr.write(i, 0xFF);
  127. }
  128. EEPROMr.commit();
  129. }
  130. void _settingsInitCommands() {
  131. #if DEBUG_SUPPORT
  132. settingsRegisterCommand(F("CRASH"), [](Embedis* e) {
  133. debugDumpCrashInfo();
  134. debugClearCrashInfo();
  135. DEBUG_MSG_P(PSTR("+OK\n"));
  136. });
  137. #endif
  138. settingsRegisterCommand(F("COMMANDS"), [](Embedis* e) {
  139. _settingsHelpCommand();
  140. DEBUG_MSG_P(PSTR("+OK\n"));
  141. });
  142. settingsRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  143. DEBUG_MSG_P(PSTR("+OK\n"));
  144. resetReason(CUSTOM_RESET_TERMINAL);
  145. ESP.eraseConfig();
  146. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  147. });
  148. #if I2C_SUPPORT
  149. settingsRegisterCommand(F("I2C.SCAN"), [](Embedis* e) {
  150. i2cScan();
  151. DEBUG_MSG_P(PSTR("+OK\n"));
  152. });
  153. settingsRegisterCommand(F("I2C.CLEAR"), [](Embedis* e) {
  154. i2cClearBus();
  155. DEBUG_MSG_P(PSTR("+OK\n"));
  156. });
  157. #endif
  158. settingsRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  159. _settingsFactoryResetCommand();
  160. DEBUG_MSG_P(PSTR("+OK\n"));
  161. });
  162. settingsRegisterCommand(F("GPIO"), [](Embedis* e) {
  163. if (e->argc < 2) {
  164. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  165. return;
  166. }
  167. int pin = String(e->argv[1]).toInt();
  168. //if (!gpioValid(pin)) {
  169. // DEBUG_MSG_P(PSTR("-ERROR: Invalid GPIO\n"));
  170. // return;
  171. //}
  172. if (e->argc > 2) {
  173. bool state = String(e->argv[2]).toInt() == 1;
  174. digitalWrite(pin, state);
  175. }
  176. DEBUG_MSG_P(PSTR("GPIO %d is %s\n"), pin, digitalRead(pin) == HIGH ? "HIGH" : "LOW");
  177. DEBUG_MSG_P(PSTR("+OK\n"));
  178. });
  179. settingsRegisterCommand(F("HEAP"), [](Embedis* e) {
  180. DEBUG_MSG_P(PSTR("Free HEAP: %d bytes\n"), getFreeHeap());
  181. DEBUG_MSG_P(PSTR("+OK\n"));
  182. });
  183. settingsRegisterCommand(F("HELP"), [](Embedis* e) {
  184. _settingsHelpCommand();
  185. DEBUG_MSG_P(PSTR("+OK\n"));
  186. });
  187. settingsRegisterCommand(F("INFO"), [](Embedis* e) {
  188. info();
  189. wifiDebug();
  190. //StreamString s;
  191. //WiFi.printDiag(s);
  192. //DEBUG_MSG(s.c_str());
  193. DEBUG_MSG_P(PSTR("+OK\n"));
  194. });
  195. settingsRegisterCommand(F("KEYS"), [](Embedis* e) {
  196. _settingsKeysCommand();
  197. DEBUG_MSG_P(PSTR("+OK\n"));
  198. });
  199. settingsRegisterCommand(F("GET"), [](Embedis* e) {
  200. if (e->argc < 2) {
  201. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  202. return;
  203. }
  204. for (unsigned char i = 1; i < e->argc; i++) {
  205. String key = String(e->argv[i]);
  206. String value;
  207. if (!Embedis::get(key, value)) {
  208. DEBUG_MSG_P(PSTR("> %s =>\n"), key.c_str());
  209. continue;
  210. }
  211. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), key.c_str(), value.c_str());
  212. }
  213. DEBUG_MSG_P(PSTR("+OK\n"));
  214. });
  215. #if WEB_SUPPORT
  216. settingsRegisterCommand(F("RELOAD"), [](Embedis* e) {
  217. wsReload();
  218. DEBUG_MSG_P(PSTR("+OK\n"));
  219. });
  220. #endif
  221. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  222. DEBUG_MSG_P(PSTR("+OK\n"));
  223. deferredReset(100, CUSTOM_RESET_TERMINAL);
  224. });
  225. settingsRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  226. EEPROMr.write(EEPROM_CRASH_COUNTER, SYSTEM_CHECK_MAX);
  227. DEBUG_MSG_P(PSTR("+OK\n"));
  228. deferredReset(100, CUSTOM_RESET_TERMINAL);
  229. });
  230. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  231. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  232. DEBUG_MSG_P(PSTR("+OK\n"));
  233. });
  234. }
  235. // -----------------------------------------------------------------------------
  236. // Key-value API
  237. // -----------------------------------------------------------------------------
  238. void moveSetting(const char * from, const char * to) {
  239. String value = getSetting(from);
  240. if (value.length() > 0) setSetting(to, value);
  241. delSetting(from);
  242. }
  243. void moveSetting(const char * from, const char * to, unsigned int index) {
  244. String value = getSetting(from, index, "");
  245. if (value.length() > 0) setSetting(to, index, value);
  246. delSetting(from, index);
  247. }
  248. void moveSettings(const char * from, const char * to) {
  249. unsigned int index = 0;
  250. while (index < 100) {
  251. String value = getSetting(from, index, "");
  252. if (value.length() == 0) break;
  253. setSetting(to, index, value);
  254. delSetting(from, index);
  255. index++;
  256. }
  257. }
  258. template<typename T> String getSetting(const String& key, T defaultValue) {
  259. String value;
  260. if (!Embedis::get(key, value)) value = String(defaultValue);
  261. return value;
  262. }
  263. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  264. return getSetting(key + String(index), defaultValue);
  265. }
  266. String getSetting(const String& key) {
  267. return getSetting(key, "");
  268. }
  269. template<typename T> bool setSetting(const String& key, T value) {
  270. return Embedis::set(key, String(value));
  271. }
  272. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  273. return setSetting(key + String(index), value);
  274. }
  275. bool delSetting(const String& key) {
  276. return Embedis::del(key);
  277. }
  278. bool delSetting(const String& key, unsigned int index) {
  279. return delSetting(key + String(index));
  280. }
  281. bool hasSetting(const String& key) {
  282. return getSetting(key).length() != 0;
  283. }
  284. bool hasSetting(const String& key, unsigned int index) {
  285. return getSetting(key, index, "").length() != 0;
  286. }
  287. void saveSettings() {
  288. #if not SETTINGS_AUTOSAVE
  289. _settings_save = true;
  290. #endif
  291. }
  292. void resetSettings() {
  293. _settingsFactoryResetCommand();
  294. }
  295. // -----------------------------------------------------------------------------
  296. // Settings
  297. // -----------------------------------------------------------------------------
  298. void settingsInject(void *data, size_t len) {
  299. _serial.inject((char *) data, len);
  300. }
  301. Stream & settingsSerial() {
  302. return (Stream &) _serial;
  303. }
  304. size_t settingsMaxSize() {
  305. size_t size = EEPROM_SIZE;
  306. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  307. size = (size + 3) & (~3);
  308. return size;
  309. }
  310. bool settingsRestoreJson(JsonObject& data) {
  311. // Check this is an ESPurna configuration file (must have "app":"ESPURNA")
  312. const char* app = data["app"];
  313. if (!app || strcmp(app, APP_NAME) != 0) {
  314. DEBUG_MSG_P(PSTR("[SETTING] Wrong or missing 'app' key\n"));
  315. return false;
  316. }
  317. // Clear settings
  318. bool is_backup = data["backup"];
  319. if (is_backup) {
  320. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  321. EEPROMr.write(i, 0xFF);
  322. }
  323. }
  324. // Dump settings to memory buffer
  325. for (auto element : data) {
  326. if (strcmp(element.key, "app") == 0) continue;
  327. if (strcmp(element.key, "version") == 0) continue;
  328. if (strcmp(element.key, "backup") == 0) continue;
  329. if (strcmp(element.key, "timestamp") == 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. EEPROMr.begin(SPI_FLASH_SEC_SIZE);
  354. _serial.callback([](uint8_t ch) {
  355. #if TELNET_SUPPORT
  356. telnetWrite(ch);
  357. #endif
  358. #if DEBUG_SERIAL_SUPPORT
  359. DEBUG_PORT.write(ch);
  360. #endif
  361. });
  362. Embedis::dictionary( F("EEPROM"),
  363. SPI_FLASH_SEC_SIZE,
  364. [](size_t pos) -> char { return EEPROMr.read(pos); },
  365. [](size_t pos, char value) { EEPROMr.write(pos, value); },
  366. #if SETTINGS_AUTOSAVE
  367. []() { _settings_save = true; }
  368. #else
  369. []() {}
  370. #endif
  371. );
  372. _settingsInitCommands();
  373. #if TERMINAL_SUPPORT
  374. #if SERIAL_RX_ENABLED
  375. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  376. #endif // SERIAL_RX_ENABLED
  377. #endif // TERMINAL_SUPPORT
  378. // Register loop
  379. espurnaRegisterLoop(settingsLoop);
  380. }
  381. void settingsLoop() {
  382. if (_settings_save) {
  383. EEPROMr.commit();
  384. _settings_save = false;
  385. }
  386. #if TERMINAL_SUPPORT
  387. #if DEBUG_SERIAL_SUPPORT
  388. while (DEBUG_PORT.available()) {
  389. _serial.inject(DEBUG_PORT.read());
  390. }
  391. #endif
  392. embedis.process();
  393. #if SERIAL_RX_ENABLED
  394. while (SERIAL_RX_PORT.available() > 0) {
  395. char rc = Serial.read();
  396. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  397. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  398. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  399. _serial_rx_pointer = 0;
  400. }
  401. }
  402. #endif // SERIAL_RX_ENABLED
  403. #endif // TERMINAL_SUPPORT
  404. }