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.

473 lines
12 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
7 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. _settingsI2CScanCommand();
  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("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. #if TELNET_SUPPORT
  281. void settingsInject(void *data, size_t len) {
  282. _serial.inject((char *) data, len);
  283. }
  284. #endif
  285. size_t settingsMaxSize() {
  286. size_t size = EEPROM_SIZE;
  287. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  288. size = (size + 3) & (~3);
  289. return size;
  290. }
  291. bool settingsRestoreJson(JsonObject& data) {
  292. const char* app = data["app"];
  293. if (strcmp(app, APP_NAME) != 0) return false;
  294. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  295. EEPROM.write(i, 0xFF);
  296. }
  297. for (auto element : data) {
  298. if (strcmp(element.key, "app") == 0) continue;
  299. if (strcmp(element.key, "version") == 0) continue;
  300. setSetting(element.key, element.value.as<char*>());
  301. }
  302. saveSettings();
  303. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  304. return true;
  305. }
  306. bool settingsGetJson(JsonObject& root) {
  307. // Get sorted list of keys
  308. std::vector<String> keys = _settingsKeys();
  309. // Add the key-values to the json object
  310. for (unsigned int i=0; i<keys.size(); i++) {
  311. String value = getSetting(keys[i]);
  312. root[keys[i]] = value;
  313. }
  314. }
  315. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  316. Embedis::command(name, call);
  317. };
  318. // -----------------------------------------------------------------------------
  319. // Initialization
  320. // -----------------------------------------------------------------------------
  321. void settingsSetup() {
  322. EEPROM.begin(SPI_FLASH_SEC_SIZE);
  323. #if TELNET_SUPPORT
  324. _serial.callback([](uint8_t ch) {
  325. telnetWrite(ch);
  326. });
  327. #endif
  328. Embedis::dictionary( F("EEPROM"),
  329. SPI_FLASH_SEC_SIZE,
  330. [](size_t pos) -> char { return EEPROM.read(pos); },
  331. [](size_t pos, char value) { EEPROM.write(pos, value); },
  332. #if SETTINGS_AUTOSAVE
  333. []() { _settings_save = true; }
  334. #else
  335. []() {}
  336. #endif
  337. );
  338. _settingsInitCommands();
  339. #if TERMINAL_SUPPORT
  340. #if SERIAL_RX_ENABLED
  341. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  342. #endif // SERIAL_RX_ENABLED
  343. #endif // TERMINAL_SUPPORT
  344. // Register loop
  345. espurnaRegisterLoop(settingsLoop);
  346. }
  347. void settingsLoop() {
  348. if (_settings_save) {
  349. EEPROM.commit();
  350. _settings_save = false;
  351. }
  352. #if TERMINAL_SUPPORT
  353. embedis.process();
  354. #if SERIAL_RX_ENABLED
  355. while (SERIAL_RX_PORT.available() > 0) {
  356. char rc = Serial.read();
  357. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  358. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  359. settingsInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  360. _serial_rx_pointer = 0;
  361. }
  362. }
  363. #endif // SERIAL_RX_ENABLED
  364. #endif // TERMINAL_SUPPORT
  365. }