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.

449 lines
12 KiB

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