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.

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