console_cmd.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. */
  6. #include <string.h>
  7. #include "protocol_examples_common.h"
  8. #include "example_common_private.h"
  9. #include "esp_wifi.h"
  10. #include "esp_log.h"
  11. #include "esp_console.h"
  12. #include "argtable3/argtable3.h"
  13. static const char *TAG = "example_console";
  14. typedef struct {
  15. struct arg_str *ssid;
  16. struct arg_str *password;
  17. struct arg_int *channel;
  18. struct arg_end *end;
  19. } wifi_connect_args_t;
  20. static wifi_connect_args_t connect_args;
  21. static int cmd_do_wifi_connect(int argc, char **argv)
  22. {
  23. int nerrors = arg_parse(argc, argv, (void **) &connect_args);
  24. if (nerrors != 0) {
  25. arg_print_errors(stderr, connect_args.end, argv[0]);
  26. return 1;
  27. }
  28. wifi_config_t wifi_config = {
  29. .sta = {
  30. .scan_method = WIFI_ALL_CHANNEL_SCAN,
  31. .sort_method = WIFI_CONNECT_AP_BY_SIGNAL,
  32. },
  33. };
  34. if (connect_args.channel->count > 0) {
  35. wifi_config.sta.channel = (uint8_t)(connect_args.channel->ival[0]);
  36. }
  37. const char *ssid = connect_args.ssid->sval[0];
  38. const char *pass = connect_args.password->sval[0];
  39. strlcpy((char *) wifi_config.sta.ssid, ssid, sizeof(wifi_config.sta.ssid));
  40. if (pass) {
  41. strlcpy((char *) wifi_config.sta.password, pass, sizeof(wifi_config.sta.password));
  42. }
  43. example_wifi_sta_do_connect(wifi_config, false);
  44. return 0;
  45. }
  46. static int cmd_do_wifi_disconnect(int argc, char **argv)
  47. {
  48. example_wifi_sta_do_disconnect();
  49. return 0;
  50. }
  51. void example_register_wifi_connect_commands(void)
  52. {
  53. ESP_LOGI(TAG, "Registering WiFi connect commands.");
  54. example_wifi_start();
  55. connect_args.ssid = arg_str1(NULL, NULL, "<ssid>", "SSID of AP");
  56. connect_args.password = arg_str0(NULL, NULL, "<pass>", "password of AP");
  57. connect_args.channel = arg_int0("n", "channel", "<channel>", "channel of AP");
  58. connect_args.end = arg_end(2);
  59. const esp_console_cmd_t wifi_connect_cmd = {
  60. .command = "wifi_connect",
  61. .help = "WiFi is station mode, join specified soft-AP",
  62. .hint = NULL,
  63. .func = &cmd_do_wifi_connect,
  64. .argtable = &connect_args
  65. };
  66. ESP_ERROR_CHECK( esp_console_cmd_register(&wifi_connect_cmd) );
  67. const esp_console_cmd_t wifi_disconnect_cmd = {
  68. .command = "wifi_disconnect",
  69. .help = "Do wifi disconnect",
  70. .hint = NULL,
  71. .func = &cmd_do_wifi_disconnect,
  72. };
  73. ESP_ERROR_CHECK( esp_console_cmd_register(&wifi_disconnect_cmd) );
  74. }