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.

448 lines
12 KiB

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