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.

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