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.

466 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
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 _settingsDumpCommand() {
  129. EEPROMr.dump(_serial);
  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("EEPROM.DUMP"), [](Embedis* e) {
  144. _settingsDumpCommand();
  145. DEBUG_MSG_P(PSTR("\n+OK\n"));
  146. });
  147. settingsRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  148. DEBUG_MSG_P(PSTR("+OK\n"));
  149. resetReason(CUSTOM_RESET_TERMINAL);
  150. ESP.eraseConfig();
  151. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  152. });
  153. #if I2C_SUPPORT
  154. settingsRegisterCommand(F("I2C.SCAN"), [](Embedis* e) {
  155. i2cScan();
  156. DEBUG_MSG_P(PSTR("+OK\n"));
  157. });
  158. settingsRegisterCommand(F("I2C.CLEAR"), [](Embedis* e) {
  159. i2cClearBus();
  160. DEBUG_MSG_P(PSTR("+OK\n"));
  161. });
  162. #endif
  163. settingsRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  164. _settingsFactoryResetCommand();
  165. DEBUG_MSG_P(PSTR("+OK\n"));
  166. });
  167. settingsRegisterCommand(F("GPIO"), [](Embedis* e) {
  168. if (e->argc < 2) {
  169. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  170. return;
  171. }
  172. int pin = String(e->argv[1]).toInt();
  173. //if (!gpioValid(pin)) {
  174. // DEBUG_MSG_P(PSTR("-ERROR: Invalid GPIO\n"));
  175. // return;
  176. //}
  177. if (e->argc > 2) {
  178. bool state = String(e->argv[2]).toInt() == 1;
  179. digitalWrite(pin, state);
  180. }
  181. DEBUG_MSG_P(PSTR("GPIO %d is %s\n"), pin, digitalRead(pin) == HIGH ? "HIGH" : "LOW");
  182. DEBUG_MSG_P(PSTR("+OK\n"));
  183. });
  184. settingsRegisterCommand(F("HEAP"), [](Embedis* e) {
  185. DEBUG_MSG_P(PSTR("Free HEAP: %d bytes\n"), getFreeHeap());
  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. wifiStatus();
  195. //StreamString s;
  196. //WiFi.printDiag(s);
  197. //DEBUG_MSG(s.c_str());
  198. DEBUG_MSG_P(PSTR("+OK\n"));
  199. });
  200. settingsRegisterCommand(F("KEYS"), [](Embedis* e) {
  201. _settingsKeysCommand();
  202. DEBUG_MSG_P(PSTR("+OK\n"));
  203. });
  204. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  205. DEBUG_MSG_P(PSTR("+OK\n"));
  206. deferredReset(100, CUSTOM_RESET_TERMINAL);
  207. });
  208. settingsRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  209. EEPROMr.write(EEPROM_CRASH_COUNTER, SYSTEM_CHECK_MAX);
  210. DEBUG_MSG_P(PSTR("+OK\n"));
  211. deferredReset(100, CUSTOM_RESET_TERMINAL);
  212. });
  213. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  214. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  215. DEBUG_MSG_P(PSTR("+OK\n"));
  216. });
  217. }
  218. // -----------------------------------------------------------------------------
  219. // Key-value API
  220. // -----------------------------------------------------------------------------
  221. void moveSetting(const char * from, const char * to) {
  222. String value = getSetting(from);
  223. if (value.length() > 0) setSetting(to, value);
  224. delSetting(from);
  225. }
  226. template<typename T> String getSetting(const String& key, T defaultValue) {
  227. String value;
  228. if (!Embedis::get(key, value)) value = String(defaultValue);
  229. return value;
  230. }
  231. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  232. return getSetting(key + String(index), defaultValue);
  233. }
  234. String getSetting(const String& key) {
  235. return getSetting(key, "");
  236. }
  237. template<typename T> bool setSetting(const String& key, T value) {
  238. return Embedis::set(key, String(value));
  239. }
  240. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  241. return setSetting(key + String(index), value);
  242. }
  243. bool delSetting(const String& key) {
  244. return Embedis::del(key);
  245. }
  246. bool delSetting(const String& key, unsigned int index) {
  247. return delSetting(key + String(index));
  248. }
  249. bool hasSetting(const String& key) {
  250. return getSetting(key).length() != 0;
  251. }
  252. bool hasSetting(const String& key, unsigned int index) {
  253. return getSetting(key, index, "").length() != 0;
  254. }
  255. void saveSettings() {
  256. #if not SETTINGS_AUTOSAVE
  257. _settings_save = true;
  258. #endif
  259. }
  260. void resetSettings() {
  261. _settingsFactoryResetCommand();
  262. }
  263. // -----------------------------------------------------------------------------
  264. // Settings
  265. // -----------------------------------------------------------------------------
  266. void settingsInject(void *data, size_t len) {
  267. _serial.inject((char *) data, len);
  268. }
  269. size_t settingsMaxSize() {
  270. size_t size = EEPROM_SIZE;
  271. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  272. size = (size + 3) & (~3);
  273. return size;
  274. }
  275. bool settingsRestoreJson(JsonObject& data) {
  276. const char* app = data["app"];
  277. if (strcmp(app, APP_NAME) != 0) return false;
  278. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  279. EEPROMr.write(i, 0xFF);
  280. }
  281. for (auto element : data) {
  282. if (strcmp(element.key, "app") == 0) continue;
  283. if (strcmp(element.key, "version") == 0) continue;
  284. setSetting(element.key, element.value.as<char*>());
  285. }
  286. saveSettings();
  287. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  288. return true;
  289. }
  290. void settingsGetJson(JsonObject& root) {
  291. // Get sorted list of keys
  292. std::vector<String> keys = _settingsKeys();
  293. // Add the key-values to the json object
  294. for (unsigned int i=0; i<keys.size(); i++) {
  295. String value = getSetting(keys[i]);
  296. root[keys[i]] = value;
  297. }
  298. }
  299. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  300. Embedis::command(name, call);
  301. };
  302. // -----------------------------------------------------------------------------
  303. // Initialization
  304. // -----------------------------------------------------------------------------
  305. void settingsSetup() {
  306. EEPROMr.begin(SPI_FLASH_SEC_SIZE);
  307. _serial.callback([](uint8_t ch) {
  308. #if TELNET_SUPPORT
  309. telnetWrite(ch);
  310. #endif
  311. #if DEBUG_SERIAL_SUPPORT
  312. DEBUG_PORT.write(ch);
  313. #endif
  314. });
  315. Embedis::dictionary( F("EEPROM"),
  316. SPI_FLASH_SEC_SIZE,
  317. [](size_t pos) -> char { return EEPROMr.read(pos); },
  318. [](size_t pos, char value) { EEPROMr.write(pos, value); },
  319. #if SETTINGS_AUTOSAVE
  320. []() { _settings_save = true; }
  321. #else
  322. []() {}
  323. #endif
  324. );
  325. _settingsInitCommands();
  326. #if TERMINAL_SUPPORT
  327. #if SERIAL_RX_ENABLED
  328. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  329. #endif // SERIAL_RX_ENABLED
  330. #endif // TERMINAL_SUPPORT
  331. // Register loop
  332. espurnaRegisterLoop(settingsLoop);
  333. }
  334. void settingsLoop() {
  335. if (_settings_save) {
  336. EEPROMr.commit();
  337. _settings_save = false;
  338. }
  339. #if TERMINAL_SUPPORT
  340. #if DEBUG_SERIAL_SUPPORT
  341. while (DEBUG_PORT.available()) {
  342. _serial.inject(DEBUG_PORT.read());
  343. }
  344. #endif
  345. embedis.process();
  346. #if SERIAL_RX_ENABLED
  347. while (SERIAL_RX_PORT.available() > 0) {
  348. char rc = Serial.read();
  349. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  350. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  351. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  352. _serial_rx_pointer = 0;
  353. }
  354. }
  355. #endif // SERIAL_RX_ENABLED
  356. #endif // TERMINAL_SUPPORT
  357. }