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.

431 lines
12 KiB

  1. /*
  2. TERMINAL MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if TERMINAL_SUPPORT
  6. #include "settings.h"
  7. #include "system.h"
  8. #include "terminal.h"
  9. #include "utils.h"
  10. #include "libs/StreamInjector.h"
  11. #include "libs/HeapStats.h"
  12. #include <vector>
  13. #include <Stream.h>
  14. StreamInjector _serial = StreamInjector(TERMINAL_BUFFER_SIZE);
  15. EmbedisWrap embedis(_serial, TERMINAL_BUFFER_SIZE);
  16. #if SERIAL_RX_ENABLED
  17. char _serial_rx_buffer[TERMINAL_BUFFER_SIZE];
  18. static unsigned char _serial_rx_pointer = 0;
  19. #endif // SERIAL_RX_ENABLED
  20. // -----------------------------------------------------------------------------
  21. // Commands
  22. // -----------------------------------------------------------------------------
  23. void _terminalHelpCommand() {
  24. // Get sorted list of commands
  25. std::vector<String> commands;
  26. unsigned char size = embedis.getCommandCount();
  27. for (unsigned int i=0; i<size; i++) {
  28. String command = embedis.getCommandName(i);
  29. bool inserted = false;
  30. for (unsigned char j=0; j<commands.size(); j++) {
  31. // Check if we have to insert it before the current element
  32. if (commands[j].compareTo(command) > 0) {
  33. commands.insert(commands.begin() + j, command);
  34. inserted = true;
  35. break;
  36. }
  37. }
  38. // If we could not insert it, just push it at the end
  39. if (!inserted) commands.push_back(command);
  40. }
  41. // Output the list
  42. DEBUG_MSG_P(PSTR("Available commands:\n"));
  43. for (unsigned char i=0; i<commands.size(); i++) {
  44. DEBUG_MSG_P(PSTR("> %s\n"), (commands[i]).c_str());
  45. }
  46. }
  47. void _terminalKeysCommand() {
  48. // Get sorted list of keys
  49. std::vector<String> keys = _settingsKeys();
  50. // Write key-values
  51. DEBUG_MSG_P(PSTR("Current settings:\n"));
  52. for (unsigned int i=0; i<keys.size(); i++) {
  53. const auto value = getSetting(keys[i]);
  54. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), (keys[i]).c_str(), value.c_str());
  55. }
  56. unsigned long freeEEPROM [[gnu::unused]] = SPI_FLASH_SEC_SIZE - settingsSize();
  57. DEBUG_MSG_P(PSTR("Number of keys: %d\n"), keys.size());
  58. DEBUG_MSG_P(PSTR("Current EEPROM sector: %u\n"), EEPROMr.current());
  59. DEBUG_MSG_P(PSTR("Free EEPROM: %d bytes (%d%%)\n"), freeEEPROM, 100 * freeEEPROM / SPI_FLASH_SEC_SIZE);
  60. }
  61. #if LWIP_VERSION_MAJOR != 1
  62. // not yet CONNECTING or LISTENING
  63. extern struct tcp_pcb *tcp_bound_pcbs;
  64. // accepting or sending data
  65. extern struct tcp_pcb *tcp_active_pcbs;
  66. // // TIME-WAIT status
  67. extern struct tcp_pcb *tcp_tw_pcbs;
  68. String _terminalPcbStateToString(const unsigned char state) {
  69. switch (state) {
  70. case 0: return F("CLOSED");
  71. case 1: return F("LISTEN");
  72. case 2: return F("SYN_SENT");
  73. case 3: return F("SYN_RCVD");
  74. case 4: return F("ESTABLISHED");
  75. case 5: return F("FIN_WAIT_1");
  76. case 6: return F("FIN_WAIT_2");
  77. case 7: return F("CLOSE_WAIT");
  78. case 8: return F("CLOSING");
  79. case 9: return F("LAST_ACK");
  80. case 10: return F("TIME_WAIT");
  81. default: return String(int(state));
  82. };
  83. }
  84. void _terminalPrintTcpPcb(tcp_pcb* pcb) {
  85. char remote_ip[32] = {0};
  86. char local_ip[32] = {0};
  87. inet_ntoa_r((pcb->local_ip), local_ip, sizeof(local_ip));
  88. inet_ntoa_r((pcb->remote_ip), remote_ip, sizeof(remote_ip));
  89. DEBUG_MSG_P(PSTR("state=%s local=%s:%u remote=%s:%u snd_queuelen=%u lastack=%u send_wnd=%u rto=%u\n"),
  90. _terminalPcbStateToString(pcb->state).c_str(),
  91. local_ip, pcb->local_port,
  92. remote_ip, pcb->remote_port,
  93. pcb->snd_queuelen, pcb->lastack,
  94. pcb->snd_wnd, pcb->rto
  95. );
  96. }
  97. void _terminalPrintTcpPcbs() {
  98. tcp_pcb *pcb;
  99. //DEBUG_MSG_P(PSTR("Active PCB states:\n"));
  100. for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
  101. _terminalPrintTcpPcb(pcb);
  102. }
  103. //DEBUG_MSG_P(PSTR("TIME-WAIT PCB states:\n"));
  104. for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
  105. _terminalPrintTcpPcb(pcb);
  106. }
  107. //DEBUG_MSG_P(PSTR("BOUND PCB states:\n"));
  108. for (pcb = tcp_bound_pcbs; pcb != NULL; pcb = pcb->next) {
  109. _terminalPrintTcpPcb(pcb);
  110. }
  111. }
  112. void _terminalPrintDnsResult(const char* name, const ip_addr_t* address) {
  113. // TODO fix asynctcp building with lwip-ipv6
  114. /*
  115. #if LWIP_IPV6
  116. if (IP_IS_V6(address)) {
  117. DEBUG_MSG_P(PSTR("[DNS] %s has IPV6 address %s\n"), name, ip6addr_ntoa(ip_2_ip6(address)));
  118. }
  119. #endif
  120. */
  121. DEBUG_MSG_P(PSTR("[DNS] %s has address %s\n"), name, ipaddr_ntoa(address));
  122. }
  123. void _terminalDnsFound(const char* name, const ip_addr_t* result, void*) {
  124. if (!result) {
  125. DEBUG_MSG_P(PSTR("[DNS] %s not found\n"), name);
  126. return;
  127. }
  128. _terminalPrintDnsResult(name, result);
  129. }
  130. #endif // LWIP_VERSION_MAJOR != 1
  131. void _terminalInitCommand() {
  132. terminalRegisterCommand(F("COMMANDS"), [](Embedis* e) {
  133. _terminalHelpCommand();
  134. terminalOK();
  135. });
  136. terminalRegisterCommand(F("ERASE.CONFIG"), [](Embedis* e) {
  137. terminalOK();
  138. customResetReason(CUSTOM_RESET_TERMINAL);
  139. eraseSDKConfig();
  140. *((int*) 0) = 0; // see https://github.com/esp8266/Arduino/issues/1494
  141. });
  142. terminalRegisterCommand(F("FACTORY.RESET"), [](Embedis* e) {
  143. resetSettings();
  144. terminalOK();
  145. });
  146. terminalRegisterCommand(F("GPIO"), [](Embedis* e) {
  147. int pin = -1;
  148. if (e->argc < 2) {
  149. DEBUG_MSG("Printing all GPIO pins:\n");
  150. } else {
  151. pin = String(e->argv[1]).toInt();
  152. if (!gpioValid(pin)) {
  153. terminalError(F("Invalid GPIO pin"));
  154. return;
  155. }
  156. if (e->argc > 2) {
  157. bool state = String(e->argv[2]).toInt() == 1;
  158. digitalWrite(pin, state);
  159. }
  160. }
  161. for (int i = 0; i <= 15; i++) {
  162. if (gpioValid(i) && (pin == -1 || pin == i)) {
  163. DEBUG_MSG_P(PSTR("GPIO %s pin %d is %s\n"), GPEP(i) ? "output" : "input", i, digitalRead(i) == HIGH ? "HIGH" : "LOW");
  164. }
  165. }
  166. terminalOK();
  167. });
  168. terminalRegisterCommand(F("HEAP"), [](Embedis* e) {
  169. infoHeapStats();
  170. terminalOK();
  171. });
  172. terminalRegisterCommand(F("STACK"), [](Embedis* e) {
  173. infoMemory("Stack", CONT_STACKSIZE, getFreeStack());
  174. terminalOK();
  175. });
  176. terminalRegisterCommand(F("HELP"), [](Embedis* e) {
  177. _terminalHelpCommand();
  178. terminalOK();
  179. });
  180. terminalRegisterCommand(F("INFO"), [](Embedis* e) {
  181. info();
  182. terminalOK();
  183. });
  184. terminalRegisterCommand(F("KEYS"), [](Embedis* e) {
  185. _terminalKeysCommand();
  186. terminalOK();
  187. });
  188. terminalRegisterCommand(F("GET"), [](Embedis* e) {
  189. if (e->argc < 2) {
  190. terminalError(F("Wrong arguments"));
  191. return;
  192. }
  193. for (unsigned char i = 1; i < e->argc; i++) {
  194. String key = String(e->argv[i]);
  195. String value;
  196. if (!Embedis::get(key, value)) {
  197. DEBUG_MSG_P(PSTR("> %s =>\n"), key.c_str());
  198. continue;
  199. }
  200. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), key.c_str(), value.c_str());
  201. }
  202. terminalOK();
  203. });
  204. terminalRegisterCommand(F("RELOAD"), [](Embedis* e) {
  205. espurnaReload();
  206. terminalOK();
  207. });
  208. terminalRegisterCommand(F("RESET"), [](Embedis* e) {
  209. terminalOK();
  210. deferredReset(100, CUSTOM_RESET_TERMINAL);
  211. });
  212. terminalRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  213. systemStabilityCounter(SYSTEM_CHECK_MAX);
  214. terminalOK();
  215. deferredReset(100, CUSTOM_RESET_TERMINAL);
  216. });
  217. terminalRegisterCommand(F("UPTIME"), [](Embedis* e) {
  218. infoUptime();
  219. terminalOK();
  220. });
  221. terminalRegisterCommand(F("CONFIG"), [](Embedis* e) {
  222. DynamicJsonBuffer jsonBuffer(1024);
  223. JsonObject& root = jsonBuffer.createObject();
  224. settingsGetJson(root);
  225. // XXX: replace with streaming
  226. String output;
  227. root.printTo(output);
  228. DEBUG_MSG(output.c_str());
  229. });
  230. #if not SETTINGS_AUTOSAVE
  231. terminalRegisterCommand(F("SAVE"), [](Embedis* e) {
  232. eepromCommit();
  233. terminalOK();
  234. });
  235. #endif
  236. #if SECURE_CLIENT == SECURE_CLIENT_BEARSSL
  237. terminalRegisterCommand(F("MFLN.PROBE"), [](Embedis* e) {
  238. if (e->argc != 3) {
  239. terminalError(F("[url] [value]"));
  240. return;
  241. }
  242. URL _url(e->argv[1]);
  243. uint16_t requested_mfln = atol(e->argv[2]);
  244. auto client = std::make_unique<BearSSL::WiFiClientSecure>();
  245. client->setInsecure();
  246. if (client->probeMaxFragmentLength(_url.host.c_str(), _url.port, requested_mfln)) {
  247. terminalOK();
  248. } else {
  249. terminalError(F("Buffer size not supported"));
  250. }
  251. });
  252. #endif
  253. #if LWIP_VERSION_MAJOR != 1
  254. terminalRegisterCommand(F("HOST"), [](Embedis* e) {
  255. if (e->argc != 2) {
  256. terminalError(F("HOST [hostname]"));
  257. return;
  258. }
  259. ip_addr_t result;
  260. auto error = dns_gethostbyname(e->argv[1], &result, _terminalDnsFound, nullptr);
  261. if (error == ERR_OK) {
  262. _terminalPrintDnsResult(e->argv[1], &result);
  263. terminalOK();
  264. return;
  265. } else if (error != ERR_INPROGRESS) {
  266. DEBUG_MSG_P(PSTR("[DNS] dns_gethostbyname error: %s\n"), lwip_strerr(error));
  267. return;
  268. }
  269. });
  270. terminalRegisterCommand(F("NETSTAT"), [](Embedis*) {
  271. _terminalPrintTcpPcbs();
  272. });
  273. #endif // LWIP_VERSION_MAJOR != 1
  274. }
  275. void _terminalLoop() {
  276. #if DEBUG_SERIAL_SUPPORT
  277. while (DEBUG_PORT.available()) {
  278. _serial.inject(DEBUG_PORT.read());
  279. }
  280. #endif
  281. embedis.process();
  282. #if SERIAL_RX_ENABLED
  283. while (SERIAL_RX_PORT.available() > 0) {
  284. char rc = SERIAL_RX_PORT.read();
  285. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  286. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  287. terminalInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  288. _serial_rx_pointer = 0;
  289. }
  290. }
  291. #endif // SERIAL_RX_ENABLED
  292. }
  293. // -----------------------------------------------------------------------------
  294. // Pubic API
  295. // -----------------------------------------------------------------------------
  296. void terminalInject(void *data, size_t len) {
  297. _serial.inject((char *) data, len);
  298. }
  299. void terminalInject(char ch) {
  300. _serial.inject(ch);
  301. }
  302. Stream & terminalSerial() {
  303. return (Stream &) _serial;
  304. }
  305. void terminalRegisterCommand(const String& name, embedis_command_f command) {
  306. Embedis::command(name, command);
  307. };
  308. void terminalOK() {
  309. DEBUG_MSG_P(PSTR("+OK\n"));
  310. }
  311. void terminalError(const String& error) {
  312. DEBUG_MSG_P(PSTR("-ERROR: %s\n"), error.c_str());
  313. }
  314. void terminalSetup() {
  315. _serial.callback([](uint8_t ch) {
  316. #if TELNET_SUPPORT
  317. telnetWrite(ch);
  318. #endif
  319. #if DEBUG_SERIAL_SUPPORT
  320. DEBUG_PORT.write(ch);
  321. #endif
  322. });
  323. #if WEB_SUPPORT
  324. wsRegister()
  325. .onVisible([](JsonObject& root) { root["cmdVisible"] = 1; });
  326. #endif
  327. _terminalInitCommand();
  328. #if SERIAL_RX_ENABLED
  329. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  330. #endif // SERIAL_RX_ENABLED
  331. // Register loop
  332. espurnaRegisterLoop(_terminalLoop);
  333. }
  334. #endif // TERMINAL_SUPPORT