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 "system.h"
  7. #include "utils.h"
  8. #include "libs/EmbedisWrap.h"
  9. #include "libs/StreamInjector.h"
  10. #include "libs/HeapStats.h"
  11. #include <vector>
  12. #include <Stream.h>
  13. StreamInjector _serial = StreamInjector(TERMINAL_BUFFER_SIZE);
  14. EmbedisWrap embedis(_serial, TERMINAL_BUFFER_SIZE);
  15. #if SERIAL_RX_ENABLED
  16. char _serial_rx_buffer[TERMINAL_BUFFER_SIZE];
  17. static unsigned char _serial_rx_pointer = 0;
  18. #endif // SERIAL_RX_ENABLED
  19. // -----------------------------------------------------------------------------
  20. // Commands
  21. // -----------------------------------------------------------------------------
  22. void _terminalHelpCommand() {
  23. // Get sorted list of commands
  24. std::vector<String> commands;
  25. unsigned char size = embedis.getCommandCount();
  26. for (unsigned int i=0; i<size; i++) {
  27. String command = embedis.getCommandName(i);
  28. bool inserted = false;
  29. for (unsigned char j=0; j<commands.size(); j++) {
  30. // Check if we have to insert it before the current element
  31. if (commands[j].compareTo(command) > 0) {
  32. commands.insert(commands.begin() + j, command);
  33. inserted = true;
  34. break;
  35. }
  36. }
  37. // If we could not insert it, just push it at the end
  38. if (!inserted) commands.push_back(command);
  39. }
  40. // Output the list
  41. DEBUG_MSG_P(PSTR("Available commands:\n"));
  42. for (unsigned char i=0; i<commands.size(); i++) {
  43. DEBUG_MSG_P(PSTR("> %s\n"), (commands[i]).c_str());
  44. }
  45. }
  46. void _terminalKeysCommand() {
  47. // Get sorted list of keys
  48. std::vector<String> keys = _settingsKeys();
  49. // Write key-values
  50. DEBUG_MSG_P(PSTR("Current settings:\n"));
  51. for (unsigned int i=0; i<keys.size(); i++) {
  52. String value = getSetting(keys[i]);
  53. DEBUG_MSG_P(PSTR("> %s => \"%s\"\n"), (keys[i]).c_str(), value.c_str());
  54. }
  55. unsigned long freeEEPROM = SPI_FLASH_SEC_SIZE - settingsSize();
  56. UNUSED(freeEEPROM);
  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, void (*call)(Embedis*)) {
  306. Embedis::command(name, call);
  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