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.

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