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.

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