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.

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