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.

442 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. const auto maybeDefault = settingsQueryDefaults(key);
  203. if (maybeDefault.length()) {
  204. DEBUG_MSG_P(PSTR("> %s => %s (default)\n"), key.c_str(), maybeDefault.c_str());
  205. } else {
  206. DEBUG_MSG_P(PSTR("> %s =>\n"), key.c_str());
  207. }
  208. continue;
  209. }
  210. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), key.c_str(), value.c_str());
  211. }
  212. terminalOK();
  213. });
  214. terminalRegisterCommand(F("RELOAD"), [](Embedis* e) {
  215. espurnaReload();
  216. terminalOK();
  217. });
  218. terminalRegisterCommand(F("RESET"), [](Embedis* e) {
  219. terminalOK();
  220. deferredReset(100, CUSTOM_RESET_TERMINAL);
  221. });
  222. terminalRegisterCommand(F("RESET.SAFE"), [](Embedis* e) {
  223. systemStabilityCounter(SYSTEM_CHECK_MAX);
  224. terminalOK();
  225. deferredReset(100, CUSTOM_RESET_TERMINAL);
  226. });
  227. terminalRegisterCommand(F("UPTIME"), [](Embedis* e) {
  228. infoUptime();
  229. terminalOK();
  230. });
  231. terminalRegisterCommand(F("CONFIG"), [](Embedis* e) {
  232. DynamicJsonBuffer jsonBuffer(1024);
  233. JsonObject& root = jsonBuffer.createObject();
  234. settingsGetJson(root);
  235. // XXX: replace with streaming
  236. String output;
  237. root.printTo(output);
  238. DEBUG_MSG(output.c_str());
  239. });
  240. #if not SETTINGS_AUTOSAVE
  241. terminalRegisterCommand(F("SAVE"), [](Embedis* e) {
  242. eepromCommit();
  243. terminalOK();
  244. });
  245. #endif
  246. #if SECURE_CLIENT == SECURE_CLIENT_BEARSSL
  247. terminalRegisterCommand(F("MFLN.PROBE"), [](Embedis* e) {
  248. if (e->argc != 3) {
  249. terminalError(F("[url] [value]"));
  250. return;
  251. }
  252. URL _url(e->argv[1]);
  253. uint16_t requested_mfln = atol(e->argv[2]);
  254. auto client = std::make_unique<BearSSL::WiFiClientSecure>();
  255. client->setInsecure();
  256. if (client->probeMaxFragmentLength(_url.host.c_str(), _url.port, requested_mfln)) {
  257. terminalOK();
  258. } else {
  259. terminalError(F("Buffer size not supported"));
  260. }
  261. });
  262. #endif
  263. #if LWIP_VERSION_MAJOR != 1
  264. terminalRegisterCommand(F("HOST"), [](Embedis* e) {
  265. if (e->argc != 2) {
  266. terminalError(F("HOST [hostname]"));
  267. return;
  268. }
  269. ip_addr_t result;
  270. auto error = dns_gethostbyname(e->argv[1], &result, _terminalDnsFound, nullptr);
  271. if (error == ERR_OK) {
  272. _terminalPrintDnsResult(e->argv[1], &result);
  273. terminalOK();
  274. return;
  275. } else if (error != ERR_INPROGRESS) {
  276. DEBUG_MSG_P(PSTR("[DNS] dns_gethostbyname error: %s\n"), lwip_strerr(error));
  277. return;
  278. }
  279. });
  280. terminalRegisterCommand(F("NETSTAT"), [](Embedis*) {
  281. _terminalPrintTcpPcbs();
  282. });
  283. #endif // LWIP_VERSION_MAJOR != 1
  284. }
  285. void _terminalLoop() {
  286. #if DEBUG_SERIAL_SUPPORT
  287. while (DEBUG_PORT.available()) {
  288. _serial.inject(DEBUG_PORT.read());
  289. }
  290. #endif
  291. embedis.process();
  292. #if SERIAL_RX_ENABLED
  293. while (SERIAL_RX_PORT.available() > 0) {
  294. char rc = SERIAL_RX_PORT.read();
  295. _serial_rx_buffer[_serial_rx_pointer++] = rc;
  296. if ((_serial_rx_pointer == TERMINAL_BUFFER_SIZE) || (rc == 10)) {
  297. terminalInject(_serial_rx_buffer, (size_t) _serial_rx_pointer);
  298. _serial_rx_pointer = 0;
  299. }
  300. }
  301. #endif // SERIAL_RX_ENABLED
  302. }
  303. // -----------------------------------------------------------------------------
  304. // Pubic API
  305. // -----------------------------------------------------------------------------
  306. void terminalInject(void *data, size_t len) {
  307. _serial.inject((char *) data, len);
  308. }
  309. void terminalInject(char ch) {
  310. _serial.inject(ch);
  311. }
  312. Stream & terminalSerial() {
  313. return (Stream &) _serial;
  314. }
  315. void terminalRegisterCommand(const String& name, embedis_command_f command) {
  316. Embedis::command(name, command);
  317. };
  318. void terminalOK() {
  319. DEBUG_MSG_P(PSTR("+OK\n"));
  320. }
  321. void terminalError(const String& error) {
  322. DEBUG_MSG_P(PSTR("-ERROR: %s\n"), error.c_str());
  323. }
  324. void terminalSetup() {
  325. _serial.callback([](uint8_t ch) {
  326. #if TELNET_SUPPORT
  327. telnetWrite(ch);
  328. #endif
  329. #if DEBUG_SERIAL_SUPPORT
  330. DEBUG_PORT.write(ch);
  331. #endif
  332. });
  333. #if WEB_SUPPORT
  334. wsRegister()
  335. .onVisible([](JsonObject& root) { root["cmdVisible"] = 1; });
  336. #endif
  337. _terminalInitCommand();
  338. #if SERIAL_RX_ENABLED
  339. SERIAL_RX_PORT.begin(SERIAL_RX_BAUDRATE);
  340. #endif // SERIAL_RX_ENABLED
  341. // Register loop
  342. espurnaRegisterLoop(_terminalLoop);
  343. }
  344. #endif // TERMINAL_SUPPORT