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.

479 lines
13 KiB

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