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.

461 lines
12 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
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. 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. pos = pos - len - 2;
  26. }
  27. return SPI_FLASH_SEC_SIZE - pos;
  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. pos = pos - len - 2;
  35. len = EEPROMr.read(pos);
  36. pos = pos - len - 2;
  37. count ++;
  38. }
  39. return count;
  40. }
  41. String _settingsKeyName(unsigned int index) {
  42. String s;
  43. unsigned count = 0;
  44. unsigned pos = SPI_FLASH_SEC_SIZE - 1;
  45. while (size_t len = EEPROMr.read(pos)) {
  46. pos = pos - len - 2;
  47. if (count == index) {
  48. s.reserve(len);
  49. for (unsigned char i = 0 ; i < len; i++) {
  50. s += (char) EEPROMr.read(pos + i + 1);
  51. }
  52. break;
  53. }
  54. count++;
  55. len = EEPROMr.read(pos);
  56. pos = pos - len - 2;
  57. }
  58. return s;
  59. }
  60. std::vector<String> _settingsKeys() {
  61. // Get sorted list of keys
  62. std::vector<String> keys;
  63. //unsigned int size = settingsKeyCount();
  64. unsigned int size = _settingsKeyCount();
  65. for (unsigned int i=0; i<size; i++) {
  66. //String key = settingsKeyName(i);
  67. String key = _settingsKeyName(i);
  68. bool inserted = false;
  69. for (unsigned char j=0; j<keys.size(); j++) {
  70. // Check if we have to insert it before the current element
  71. if (keys[j].compareTo(key) > 0) {
  72. keys.insert(keys.begin() + j, key);
  73. inserted = true;
  74. break;
  75. }
  76. }
  77. // If we could not insert it, just push it at the end
  78. if (!inserted) keys.push_back(key);
  79. }
  80. return keys;
  81. }
  82. // -----------------------------------------------------------------------------
  83. // Commands
  84. // -----------------------------------------------------------------------------
  85. void _settingsHelpCommand() {
  86. // Get sorted list of commands
  87. std::vector<String> commands;
  88. unsigned char size = embedis.getCommandCount();
  89. for (unsigned int i=0; i<size; i++) {
  90. String command = embedis.getCommandName(i);
  91. bool inserted = false;
  92. for (unsigned char j=0; j<commands.size(); j++) {
  93. // Check if we have to insert it before the current element
  94. if (commands[j].compareTo(command) > 0) {
  95. commands.insert(commands.begin() + j, command);
  96. inserted = true;
  97. break;
  98. }
  99. }
  100. // If we could not insert it, just push it at the end
  101. if (!inserted) commands.push_back(command);
  102. }
  103. // Output the list
  104. DEBUG_MSG_P(PSTR("Available commands:\n"));
  105. for (unsigned char i=0; i<commands.size(); i++) {
  106. DEBUG_MSG_P(PSTR("> %s\n"), (commands[i]).c_str());
  107. }
  108. }
  109. void _settingsKeysCommand() {
  110. // Get sorted list of keys
  111. std::vector<String> keys = _settingsKeys();
  112. // Write key-values
  113. DEBUG_MSG_P(PSTR("Current settings:\n"));
  114. for (unsigned int i=0; i<keys.size(); i++) {
  115. String value = getSetting(keys[i]);
  116. DEBUG_MSG_P(PSTR("> %s => %s\n"), (keys[i]).c_str(), value.c_str());
  117. }
  118. unsigned long freeEEPROM = SPI_FLASH_SEC_SIZE - settingsSize();
  119. DEBUG_MSG_P(PSTR("Number of keys: %d\n"), keys.size());
  120. DEBUG_MSG_P(PSTR("Free EEPROM: %d bytes (%d%%)\n"), freeEEPROM, 100 * freeEEPROM / SPI_FLASH_SEC_SIZE);
  121. }
  122. void _settingsFactoryResetCommand() {
  123. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  124. EEPROMr.write(i, 0xFF);
  125. }
  126. EEPROMr.commit();
  127. }
  128. void _settingsInitCommands() {
  129. #if DEBUG_SUPPORT
  130. settingsRegisterCommand(F("CRASH"), [](Embedis* e) {
  131. debugDumpCrashInfo();
  132. debugClearCrashInfo();
  133. DEBUG_MSG_P(PSTR("+OK\n"));
  134. });
  135. #endif
  136. settingsRegisterCommand(F("COMMANDS"), [](Embedis* e) {
  137. _settingsHelpCommand();
  138. DEBUG_MSG_P(PSTR("+OK\n"));
  139. });
  140. settingsRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  141. DEBUG_MSG_P(PSTR("+OK\n"));
  142. resetReason(CUSTOM_RESET_TERMINAL);
  143. ESP.eraseConfig();
  144. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  145. });
  146. #if I2C_SUPPORT
  147. settingsRegisterCommand(F("I2C.SCAN"), [](Embedis* e) {
  148. i2cScan();
  149. DEBUG_MSG_P(PSTR("+OK\n"));
  150. });
  151. settingsRegisterCommand(F("I2C.CLEAR"), [](Embedis* e) {
  152. i2cClearBus();
  153. DEBUG_MSG_P(PSTR("+OK\n"));
  154. });
  155. #endif
  156. settingsRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  157. _settingsFactoryResetCommand();
  158. DEBUG_MSG_P(PSTR("+OK\n"));
  159. });
  160. settingsRegisterCommand(F("GPIO"), [](Embedis* e) {
  161. if (e->argc < 2) {
  162. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  163. return;
  164. }
  165. int pin = String(e->argv[1]).toInt();
  166. //if (!gpioValid(pin)) {
  167. // DEBUG_MSG_P(PSTR("-ERROR: Invalid GPIO\n"));
  168. // return;
  169. //}
  170. if (e->argc > 2) {
  171. bool state = String(e->argv[2]).toInt() == 1;
  172. digitalWrite(pin, state);
  173. }
  174. DEBUG_MSG_P(PSTR("GPIO %d is %s\n"), pin, digitalRead(pin) == HIGH ? "HIGH" : "LOW");
  175. DEBUG_MSG_P(PSTR("+OK\n"));
  176. });
  177. settingsRegisterCommand(F("HEAP"), [](Embedis* e) {
  178. DEBUG_MSG_P(PSTR("Free HEAP: %d bytes\n"), getFreeHeap());
  179. DEBUG_MSG_P(PSTR("+OK\n"));
  180. });
  181. settingsRegisterCommand(F("HELP"), [](Embedis* e) {
  182. _settingsHelpCommand();
  183. DEBUG_MSG_P(PSTR("+OK\n"));
  184. });
  185. settingsRegisterCommand(F("INFO"), [](Embedis* e) {
  186. info();
  187. wifiStatus();
  188. //StreamString s;
  189. //WiFi.printDiag(s);
  190. //DEBUG_MSG(s.c_str());
  191. DEBUG_MSG_P(PSTR("+OK\n"));
  192. });
  193. settingsRegisterCommand(F("KEYS"), [](Embedis* e) {
  194. _settingsKeysCommand();
  195. DEBUG_MSG_P(PSTR("+OK\n"));
  196. });
  197. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  198. DEBUG_MSG_P(PSTR("+OK\n"));
  199. deferredReset(100, CUSTOM_RESET_TERMINAL);
  200. });
  201. settingsRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  202. EEPROMr.write(EEPROM_CRASH_COUNTER, SYSTEM_CHECK_MAX);
  203. DEBUG_MSG_P(PSTR("+OK\n"));
  204. deferredReset(100, CUSTOM_RESET_TERMINAL);
  205. });
  206. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  207. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  208. DEBUG_MSG_P(PSTR("+OK\n"));
  209. });
  210. }
  211. // -----------------------------------------------------------------------------
  212. // Key-value API
  213. // -----------------------------------------------------------------------------
  214. void moveSetting(const char * from, const char * to) {
  215. String value = getSetting(from);
  216. if (value.length() > 0) setSetting(to, value);
  217. delSetting(from);
  218. }
  219. template<typename T> String getSetting(const String& key, T defaultValue) {
  220. String value;
  221. if (!Embedis::get(key, value)) value = String(defaultValue);
  222. return value;
  223. }
  224. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  225. return getSetting(key + String(index), defaultValue);
  226. }
  227. String getSetting(const String& key) {
  228. return getSetting(key, "");
  229. }
  230. template<typename T> bool setSetting(const String& key, T value) {
  231. return Embedis::set(key, String(value));
  232. }
  233. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  234. return setSetting(key + String(index), value);
  235. }
  236. bool delSetting(const String& key) {
  237. return Embedis::del(key);
  238. }
  239. bool delSetting(const String& key, unsigned int index) {
  240. return delSetting(key + String(index));
  241. }
  242. bool hasSetting(const String& key) {
  243. return getSetting(key).length() != 0;
  244. }
  245. bool hasSetting(const String& key, unsigned int index) {
  246. return getSetting(key, index, "").length() != 0;
  247. }
  248. void saveSettings() {
  249. #if not SETTINGS_AUTOSAVE
  250. _settings_save = true;
  251. #endif
  252. }
  253. void resetSettings() {
  254. _settingsFactoryResetCommand();
  255. }
  256. // -----------------------------------------------------------------------------
  257. // Settings
  258. // -----------------------------------------------------------------------------
  259. void settingsInject(void *data, size_t len) {
  260. _serial.inject((char *) data, len);
  261. }
  262. Stream & settingsSerial() {
  263. return (Stream &) _serial;
  264. }
  265. size_t settingsMaxSize() {
  266. size_t size = EEPROM_SIZE;
  267. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  268. size = (size + 3) & (~3);
  269. return size;
  270. }
  271. bool settingsRestoreJson(JsonObject& data) {
  272. const char* app = data["app"];
  273. if (strcmp(app, APP_NAME) != 0) return false;
  274. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  275. EEPROMr.write(i, 0xFF);
  276. }
  277. for (auto element : data) {
  278. if (strcmp(element.key, "app") == 0) continue;
  279. if (strcmp(element.key, "version") == 0) continue;
  280. setSetting(element.key, element.value.as<char*>());
  281. }
  282. saveSettings();
  283. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  284. return true;
  285. }
  286. void settingsGetJson(JsonObject& root) {
  287. // Get sorted list of keys
  288. std::vector<String> keys = _settingsKeys();
  289. // Add the key-values to the json object
  290. for (unsigned int i=0; i<keys.size(); i++) {
  291. String value = getSetting(keys[i]);
  292. root[keys[i]] = value;
  293. }
  294. }
  295. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  296. Embedis::command(name, call);
  297. };
  298. // -----------------------------------------------------------------------------
  299. // Initialization
  300. // -----------------------------------------------------------------------------
  301. void settingsSetup() {
  302. EEPROMr.begin(SPI_FLASH_SEC_SIZE);
  303. _serial.callback([](uint8_t ch) {
  304. #if TELNET_SUPPORT
  305. telnetWrite(ch);
  306. #endif
  307. #if DEBUG_SERIAL_SUPPORT
  308. DEBUG_PORT.write(ch);
  309. #endif
  310. });
  311. Embedis::dictionary( F("EEPROM"),
  312. SPI_FLASH_SEC_SIZE,
  313. [](size_t pos) -> char { return EEPROMr.read(pos); },
  314. [](size_t pos, char value) { EEPROMr.write(pos, value); },
  315. #if SETTINGS_AUTOSAVE
  316. []() { _settings_save = true; }
  317. #else
  318. []() {}
  319. #endif
  320. );
  321. _settingsInitCommands();
  322. #if TERMINAL_SUPPORT
  323. #if SERIAL_RX_ENABLED
  324. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  325. #endif // SERIAL_RX_ENABLED
  326. #endif // TERMINAL_SUPPORT
  327. // Register loop
  328. espurnaRegisterLoop(settingsLoop);
  329. }
  330. void settingsLoop() {
  331. if (_settings_save) {
  332. EEPROMr.commit();
  333. _settings_save = false;
  334. }
  335. #if TERMINAL_SUPPORT
  336. #if DEBUG_SERIAL_SUPPORT
  337. while (DEBUG_PORT.available()) {
  338. _serial.inject(DEBUG_PORT.read());
  339. }
  340. #endif
  341. embedis.process();
  342. #if SERIAL_RX_ENABLED
  343. while (SERIAL_RX_PORT.available() > 0) {
  344. char rc = Serial.read();
  345. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  346. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  347. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  348. _serial_rx_pointer = 0;
  349. }
  350. }
  351. #endif // SERIAL_RX_ENABLED
  352. #endif // TERMINAL_SUPPORT
  353. }