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.

417 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
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("\nAvailable commands:\n\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("\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. DEBUG_MSG_P(PSTR("\n"));
  120. unsigned long freeEEPROM = SPI_FLASH_SEC_SIZE - _settingsSize();
  121. DEBUG_MSG_P(PSTR("Number of keys: %d\n"), keys.size());
  122. DEBUG_MSG_P(PSTR("Free EEPROM: %d bytes (%d%%)\n"), freeEEPROM, 100 * freeEEPROM / SPI_FLASH_SEC_SIZE);
  123. }
  124. void _settingsFactoryReset() {
  125. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  126. EEPROM.write(i, 0xFF);
  127. }
  128. EEPROM.commit();
  129. }
  130. void _settingsDump(bool ascii) {
  131. for (unsigned int i = 0; i < SPI_FLASH_SEC_SIZE; i++) {
  132. if (i % 16 == 0) DEBUG_MSG_P(PSTR("\n[%04X] "), i);
  133. byte c = EEPROM.read(i);
  134. if (ascii && 32 <= c && c <= 126) {
  135. DEBUG_MSG_P(PSTR(" %c "), c);
  136. } else {
  137. DEBUG_MSG_P(PSTR("%02X "), c);
  138. }
  139. }
  140. }
  141. void _settingsInitCommands() {
  142. #if DEBUG_SUPPORT
  143. settingsRegisterCommand(F("CRASH"), [](Embedis* e) {
  144. debugDumpCrashInfo();
  145. DEBUG_MSG_P(PSTR("+OK\n"));
  146. });
  147. #endif
  148. settingsRegisterCommand(F("COMMANDS"), [](Embedis* e) {
  149. _settingsHelp();
  150. DEBUG_MSG_P(PSTR("+OK\n"));
  151. });
  152. settingsRegisterCommand(F("EEPROM.DUMP"), [](Embedis* e) {
  153. bool ascii = false;
  154. if (e->argc == 2) ascii = String(e->argv[1]).toInt() == 1;
  155. _settingsDump(ascii);
  156. DEBUG_MSG_P(PSTR("\n+OK\n"));
  157. });
  158. settingsRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  159. DEBUG_MSG_P(PSTR("+OK\n"));
  160. resetReason(CUSTOM_RESET_TERMINAL);
  161. ESP.eraseConfig();
  162. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  163. });
  164. settingsRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  165. _settingsFactoryReset();
  166. DEBUG_MSG_P(PSTR("+OK\n"));
  167. });
  168. settingsRegisterCommand(F("GPIO"), [](Embedis* e) {
  169. if (e->argc < 2) {
  170. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  171. return;
  172. }
  173. int pin = String(e->argv[1]).toInt();
  174. //if (!gpioValid(pin)) {
  175. // DEBUG_MSG_P(PSTR("-ERROR: Invalid GPIO\n"));
  176. // return;
  177. //}
  178. if (e->argc > 2) {
  179. bool state = String(e->argv[2]).toInt() == 1;
  180. digitalWrite(pin, state);
  181. }
  182. DEBUG_MSG_P(PSTR("GPIO %d is %s\n"), pin, digitalRead(pin) == HIGH ? "HIGH" : "LOW");
  183. DEBUG_MSG_P(PSTR("+OK\n"));
  184. });
  185. settingsRegisterCommand(F("HEAP"), [](Embedis* e) {
  186. DEBUG_MSG_P(PSTR("Free HEAP: %d bytes\n"), getFreeHeap());
  187. DEBUG_MSG_P(PSTR("+OK\n"));
  188. });
  189. settingsRegisterCommand(F("HELP"), [](Embedis* e) {
  190. _settingsHelp();
  191. DEBUG_MSG_P(PSTR("+OK\n"));
  192. });
  193. settingsRegisterCommand(F("INFO"), [](Embedis* e) {
  194. welcome();
  195. wifiStatus();
  196. //StreamString s;
  197. //WiFi.printDiag(s);
  198. //DEBUG_MSG(s.c_str());
  199. DEBUG_MSG_P(PSTR("+OK\n"));
  200. });
  201. settingsRegisterCommand(F("KEYS"), [](Embedis* e) {
  202. _settingsKeys();
  203. DEBUG_MSG_P(PSTR("+OK\n"));
  204. });
  205. settingsRegisterCommand(F("RESET"), [](Embedis* e) {
  206. DEBUG_MSG_P(PSTR("+OK\n"));
  207. deferredReset(100, CUSTOM_RESET_TERMINAL);
  208. });
  209. settingsRegisterCommand(F("UPTIME"), [](Embedis* e) {
  210. DEBUG_MSG_P(PSTR("Uptime: %d seconds\n"), getUptime());
  211. DEBUG_MSG_P(PSTR("+OK\n"));
  212. });
  213. }
  214. // -----------------------------------------------------------------------------
  215. // Key-value API
  216. // -----------------------------------------------------------------------------
  217. void moveSetting(const char * from, const char * to) {
  218. String value = getSetting(from);
  219. if (value.length() > 0) setSetting(to, value);
  220. delSetting(from);
  221. }
  222. template<typename T> String getSetting(const String& key, T defaultValue) {
  223. String value;
  224. if (!Embedis::get(key, value)) value = String(defaultValue);
  225. return value;
  226. }
  227. template<typename T> String getSetting(const String& key, unsigned int index, T defaultValue) {
  228. return getSetting(key + String(index), defaultValue);
  229. }
  230. String getSetting(const String& key) {
  231. return getSetting(key, "");
  232. }
  233. template<typename T> bool setSetting(const String& key, T value) {
  234. return Embedis::set(key, String(value));
  235. }
  236. template<typename T> bool setSetting(const String& key, unsigned int index, T value) {
  237. return setSetting(key + String(index), value);
  238. }
  239. bool delSetting(const String& key) {
  240. return Embedis::del(key);
  241. }
  242. bool delSetting(const String& key, unsigned int index) {
  243. return delSetting(key + String(index));
  244. }
  245. bool hasSetting(const String& key) {
  246. return getSetting(key).length() != 0;
  247. }
  248. bool hasSetting(const String& key, unsigned int index) {
  249. return getSetting(key, index, "").length() != 0;
  250. }
  251. void saveSettings() {
  252. #if not SETTINGS_AUTOSAVE
  253. _settings_save = true;
  254. #endif
  255. }
  256. void resetSettings() {
  257. _settingsFactoryReset();
  258. }
  259. // -----------------------------------------------------------------------------
  260. // Settings
  261. // -----------------------------------------------------------------------------
  262. #if TELNET_SUPPORT
  263. void settingsInject(void *data, size_t len) {
  264. _serial.inject((char *) data, len);
  265. }
  266. #endif
  267. size_t settingsMaxSize() {
  268. size_t size = EEPROM_SIZE;
  269. if (size > SPI_FLASH_SEC_SIZE) size = SPI_FLASH_SEC_SIZE;
  270. size = (size + 3) & (~3);
  271. return size;
  272. }
  273. bool settingsRestoreJson(JsonObject& data) {
  274. const char* app = data["app"];
  275. if (strcmp(app, APP_NAME) != 0) return false;
  276. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  277. EEPROM.write(i, 0xFF);
  278. }
  279. for (auto element : data) {
  280. if (strcmp(element.key, "app") == 0) continue;
  281. if (strcmp(element.key, "version") == 0) continue;
  282. setSetting(element.key, element.value.as<char*>());
  283. }
  284. saveSettings();
  285. DEBUG_MSG_P(PSTR("[SETTINGS] Settings restored successfully\n"));
  286. return true;
  287. }
  288. bool settingsGetJson(JsonObject& root) {
  289. unsigned int size = _settingsKeyCount();
  290. for (unsigned int i=0; i<size; i++) {
  291. String key = _settingsKeyName(i);
  292. String value = getSetting(key);
  293. root[key] = value;
  294. }
  295. }
  296. void settingsRegisterCommand(const String& name, void (*call)(Embedis*)) {
  297. Embedis::command(name, call);
  298. };
  299. // -----------------------------------------------------------------------------
  300. // Initialization
  301. // -----------------------------------------------------------------------------
  302. void settingsSetup() {
  303. EEPROM.begin(SPI_FLASH_SEC_SIZE);
  304. #if TELNET_SUPPORT
  305. _serial.callback([](uint8_t ch) {
  306. telnetWrite(ch);
  307. });
  308. #endif
  309. Embedis::dictionary( F("EEPROM"),
  310. SPI_FLASH_SEC_SIZE,
  311. [](size_t pos) -> char { return EEPROM.read(pos); },
  312. [](size_t pos, char value) { EEPROM.write(pos, value); },
  313. #if SETTINGS_AUTOSAVE
  314. []() { _settings_save = true; }
  315. #else
  316. []() {}
  317. #endif
  318. );
  319. _settingsInitCommands();
  320. DEBUG_MSG_P(PSTR("[SETTINGS] EEPROM size: %d bytes\n"), SPI_FLASH_SEC_SIZE);
  321. DEBUG_MSG_P(PSTR("[SETTINGS] Settings size: %d bytes\n"), _settingsSize());
  322. }
  323. void settingsLoop() {
  324. if (_settings_save) {
  325. EEPROM.commit();
  326. _settings_save = false;
  327. }
  328. #if TERMINAL_SUPPORT
  329. embedis.process();
  330. #endif
  331. }