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.

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