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.

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