/********************************************************************************* * Copyright: (C) 2023 LingYun IoT System Studio. * All rights reserved. * * Filename: esp32.c * Description: This file is ESP32 high level logic API functions * * Version: 1.0.0(11/08/23) * Author: Guo Wenxue * ChangeLog: 1, Release initial version on "11/08/23 16:18:43" * ********************************************************************************/ #include "logger.h" #include "esp32.h" int esp32_init_module(comport_t *comport) { int rv; char version[256] = {0}; if( !comport ) return -1; rv = esp32_reset(comport); if( rv < 0) { log_error("Reset ESP32 WiFi module failed: %d\n", rv); return rv; } esp32_set_echo(comport, DISABLE); esp32_set_sysstore(comport, ENABLE); rv = esp32_get_firmware(comport, version, sizeof(version)); if( rv < 0) { log_error("Query ESP32 firmware version failed: %d\n", rv); return rv; } log_info("ESP32 firmware version:\n%s\n", version); return 0; } int esp32_setup_softap(comport_t *comport, char *ssid, char *pwd) { esp32_set_wmode(comport, MODE_SOFTAP, ENABLE); esp32_set_ipaddr(comport, MODE_SOFTAP, DEF_SOFTAP_IPADDR, DEF_SOFTAP_IPADDR); esp32_set_dhcp(comport, MODE_SOFTAP, ENABLE); esp32_set_softap(comport, ssid, pwd, 11, MODE_WPA2PSK); return 0; } int esp32_join_network(comport_t *comport, char *ssid, char *pwd) { int rv, status = 0; int times=10; char buf[128] = {0}; if( !comport ) return -1; esp32_join_status(comport, &status, buf); if( 2==status && !strcmp(buf, ssid) ) { log_info("ESP32 connected to \"%s\" already\n", ssid); return 0; } esp32_set_wmode(comport, MODE_STATION, ENABLE); esp32_set_dhcp(comport, MODE_STATION, ENABLE); rv = esp32_connect_ap(comport, ssid, pwd); if( rv < 0 ) { log_error("connect to AP \"%s\" failed, rv=%d", ssid, rv); return rv; } while(times--) { rv = esp32_join_status(comport, &status, buf); if( 2 == status ) { log_info("ESP32 connected to \"%s\" already\n", ssid); return 0; } rv = -3; } return rv; } int esp32_check_network(comport_t *comport) { int rv, times=5; char ip[IP_LEN] = {0}; char gateway[IP_LEN] = {0}; memset(ip, 0, sizeof(ip)); memset(gateway, 0, sizeof(gateway)); rv = esp32_get_ipaddr(comport, MODE_STATION, ip, gateway); if( rv<0 ) return rv; if( !strlen(ip) || !strlen(gateway) ) return -3; log_info("IP address: %s, netmask: %s\n", ip, gateway); while( times-- ) { if( !(rv=esp32_ping(comport, gateway, 5000)) ) { rv = 0; break; } } return 0; } int esp32_setup_tcp_server(comport_t *comport, int port) { int rv; rv = esp32_set_socket_mux(comport, ENABLE); if(rv<0) return rv; rv = esp32_set_socket_clients(comport, 2); if(rv<0) return rv; rv = esp32_set_tcp_server(comport, port); if(rv<0) return rv; rv = esp32_set_socket_timeout(comport, 600); if(rv<0) return rv; return 0; } int esp32_setup_tcp_client(comport_t *comport, char *host, int port) { int rv; rv = esp32_set_tcp_client(comport, DISABLE, host, port); if(rv<0) return rv; return 0; }