Thanks for your interest but if it is working fine on a cold boot but not after my code why do you need the connect code. It is basically the same as the SNTP wifi example with only the wifi stuff in it.
Code: Select all
//! WiFi functions
/**
* @brief Checks the netif description if it contains specified prefix.
* All netifs created withing common connect component are prefixed with the module TAG,
* so it returns true if the specified netif is owned by this module
*/
bool is_our_netif(const char *prefix, esp_netif_t *netif)
{
return strncmp(prefix, esp_netif_get_desc(netif), strlen(prefix) - 1) == 0;
}
static bool netif_desc_matches_with(esp_netif_t *netif, void *ctx)
{
return strcmp(ctx, esp_netif_get_desc(netif)) == 0;
}
esp_netif_t *netif_from_desc(const char *desc)
{
return esp_netif_find_if(netif_desc_matches_with, (void*)desc);
}
static void handler_on_wifi_disconnect(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
s_retry_num++;
if (s_retry_num > WIFI_CONNECT_MAX_RETRY) {
ESP_LOGI(TAG, "WiFi Connect failed %d times, stop reconnect.", s_retry_num);
/* let wifi_sta_do_connect() return */
if (Semaphore_get_ip_addrs) {
xSemaphoreGive(Semaphore_get_ip_addrs);
}
wifi_sta_do_disconnect();
return;
}
wifi_event_sta_disconnected_t *disconn = event_data;
if (disconn->reason == WIFI_REASON_ROAMING) {
ESP_LOGD(TAG, "station roaming, do nothing");
return;
}
ESP_LOGI(TAG, "Wi-Fi disconnected %d, trying to reconnect...", disconn->reason);
esp_err_t err = esp_wifi_connect();
if (err == ESP_ERR_WIFI_NOT_STARTED) {
return;
}
REPORT(err);
}
static void handler_on_sta_got_ip(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
s_retry_num = 0;
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
if (!is_our_netif(NETIF_DESCRIPTION_STA, event->esp_netif)) {
return;
}
ESP_LOGI(TAG, "Got IPv4 event: Interface \"%s\" address: " IPSTR, esp_netif_get_desc(event->esp_netif), IP2STR(&event->ip_info.ip));
if (Semaphore_get_ip_addrs) {
xSemaphoreGive(Semaphore_get_ip_addrs);
} else {
ESP_LOGI(TAG, "- IPv4 address: " IPSTR ",", IP2STR(&event->ip_info.ip));
}
}
esp_err_t wifi_start(void)
{
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
CHECK(esp_wifi_init(&cfg));
esp_netif_inherent_config_t esp_netif_config = ESP_NETIF_INHERENT_DEFAULT_WIFI_STA();
// Warning: the interface desc is used in tests to capture actual connection details (IP, gw, mask)
esp_netif_config.if_desc = NETIF_DESCRIPTION_STA;
esp_netif_config.route_prio = 128;
STA_netif = esp_netif_create_wifi(WIFI_IF_STA, &esp_netif_config);
esp_wifi_set_default_wifi_sta_handlers();
CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
CHECK(esp_wifi_start());
return ESP_OK;
}
esp_err_t wifi_stop(void)
{
//~ esp_err_t err = esp_wifi_stop();
//~ if (err == ESP_ERR_WIFI_NOT_INIT) {
//~ return;
//~ }
CHECK(esp_wifi_stop());
CHECK(esp_wifi_deinit());
CHECK(esp_wifi_clear_default_wifi_driver_and_handlers(STA_netif));
esp_netif_destroy(STA_netif);
CHECK( esp_event_loop_delete_default());
STA_netif = NULL;
return ESP_OK;
}
esp_err_t wifi_sta_do_connect(wifi_config_t wifi_config, bool wait)
{
if (wait) {
Semaphore_get_ip_addrs = xSemaphoreCreateBinary();
if (Semaphore_get_ip_addrs == NULL) {
return ESP_ERR_NO_MEM;
}
}
s_retry_num = 0;
CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &handler_on_wifi_disconnect, NULL));
CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &handler_on_sta_got_ip, NULL));
//~ CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_CONNECTED, &handler_on_wifi_connect, STA_netif));
ESP_LOGI(TAG, "Connecting to %s...", wifi_config.sta.ssid);
CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
esp_err_t ret = esp_wifi_connect();
if (ret != ESP_OK) {
ESP_LOGE(TAG, "WiFi connect failed! ret:%x", ret);
return ret;
}
if (wait) {
ESP_LOGI(TAG, "Waiting for IP(s)");
xSemaphoreTake(Semaphore_get_ip_addrs, portMAX_DELAY);
if (s_retry_num > WIFI_CONNECT_MAX_RETRY) {
return ESP_FAIL;
}
}
return ESP_OK;
}
esp_err_t wifi_sta_do_disconnect(void)
{
CHECK(esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &handler_on_wifi_disconnect));
CHECK(esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &handler_on_sta_got_ip));
if (Semaphore_get_ip_addrs) {
vSemaphoreDelete(Semaphore_get_ip_addrs);
}
return esp_wifi_disconnect();
}
void wifi_shutdown(void)
{
REPORT(wifi_sta_do_disconnect());
REPORT(wifi_stop());
ESP_LOGI(TAG, "Disconnected from WiFi.");
}
esp_err_t wifi_connect(void)
{
esp_log_level_set("wifi",ESP_LOG_ERROR);
esp_log_level_set("wifi_init",ESP_LOG_ERROR);
ESP_LOGI(TAG, "Start wifi connect.");
wifi_start();
wifi_config_t wifi_config = {
.sta = {
//.ssid = Wifi_SSID,
//.password = Wifi_password,
/* Authmode threshold resets to WPA2 as default if password matches WPA2 standards (pasword len => 8).
* If you want to connect the device to deprecated WEP/WPA networks, Please set the threshold value
* to WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK and set the password with length and format matching to
* WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK standards.
*/
.scan_method = WIFI_ALL_CHANNEL_SCAN,
.sort_method = WIFI_CONNECT_AP_BY_SIGNAL,
//~ .threshold.rssi = CONFIG_WIFI_SCAN_RSSI_THRESHOLD,
.threshold.authmode = ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD,
.sae_pwe_h2e = ESP_WIFI_SAE_MODE,
.sae_h2e_identifier = SAE_H2E_IDENTIFIER,
},
};
//~ memcpy(wifi_config.sta.ssid, Wifi_SSID, sizeof(Wifi_SSIDwifi_config.sta.ssid));
memcpy(wifi_config.sta.ssid, Wifi_SSID, sizeof(wifi_config.sta.ssid));
memcpy(wifi_config.sta.password, Wifi_password, sizeof(wifi_config.sta.password));
return wifi_sta_do_connect(wifi_config, true);
}
static void print_servers(void)
{
ESP_LOGI(TAG, "List of configured NTP servers:");
for (uint8_t i = 0; i < SNTP_MAX_SERVERS; ++i){
if (esp_sntp_getservername(i)){
ESP_LOGI(TAG, "server %d: %s", i, esp_sntp_getservername(i));
} else {
// we have either IPv4 or IPv6 address, let's print it
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 48
#endif
char buff[INET6_ADDRSTRLEN];
ip_addr_t const *ip = esp_sntp_getserver(i);
if (ipaddr_ntoa_r(ip, buff, INET6_ADDRSTRLEN) != NULL)
ESP_LOGI(TAG, "server %d: %s", i, buff);
}
}
}
esp_err_t sync_time_to_sntp(void)
{
#ifdef CONFIG_NVS_PAGE_NAME
truc_nvs_init(true);
#else
CHECK( nvs_flash_init() );
#endif
CHECK( esp_netif_init() );
esp_event_loop_create_default(); // this is throwing iESP_ERR_INVALID_STATE when run after proir update
setenv("TZ", "UTC0", 0); // set enviroment to UTC and overwrite
tzset();
#if LWIP_DHCP_GET_NTP_SRV
/**
* NTP server address could be acquired via DHCP,
* see following menuconfig options:
* 'LWIP_DHCP_GET_NTP_SRV' - enable STNP over DHCP
* 'LWIP_SNTP_DEBUG' - enable debugging messages
*
* NOTE: This call should be made BEFORE esp acquires IP address from DHCP,
* otherwise NTP option would be rejected by default.
*/
ESP_LOGI(TAG, "Initializing SNTP");
esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(CONFIG_SNTP_TIME_SERVER);
config.start = false; // start SNTP service explicitly (after connecting)
config.server_from_dhcp = true; // accept NTP offers from DHCP server, if any (need to enable *before* connecting)
config.renew_servers_after_new_IP = true; // let esp-netif update configured SNTP server(s) after receiving DHCP lease
config.index_of_first_server = 1; // updates from server num 1, leaving server 0 (from DHCP) intact
// configure the event on which we renew servers
config.ip_event_to_renew = IP_EVENT_STA_GOT_IP;
//~ config.sync_cb = time_sync_notification_cb; // only if we need the notification function
esp_netif_sntp_init(&config);
#endif /* LWIP_DHCP_GET_NTP_SRV */
CHECK(wifi_connect());
#if LWIP_DHCP_GET_NTP_SRV
ESP_LOGI(TAG, "Starting SNTP");
esp_netif_sntp_start();
#if LWIP_IPV6 && SNTP_MAX_SERVERS > 2
/* This demonstrates using IPv6 address as an additional SNTP server
* (statically assigned IPv6 address is also possible)
*/
ip_addr_t ip6;
if (ipaddr_aton("2a01:3f7::1", &ip6)) { // ipv6 ntp source "ntp.netnod.se"
esp_sntp_setserver(2, &ip6);
}
#endif /* LWIP_IPV6 */
/* end LWIP_DHCP_GET_NTP_SRV */
#else
ESP_LOGI(TAG, "Initializing and starting SNTP");
#if CONFIG_LWIP_SNTP_MAX_SERVERS > 1
/* This demonstrates configuring more than one server
*/
esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(2,
ESP_SNTP_SERVER_LIST(CONFIG_SNTP_TIME_SERVER, "pool.ntp.org" ) );
#else
/*
* This is the basic default config with one server and starting the service
*/
esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
#endif
//~ config.sync_cb = time_sync_notification_cb; // Note: This is only needed if we want
//~ #ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
//~ config.smooth_sync = true;
//~ #endif
config.smooth_sync = false;
esp_netif_sntp_init(&config);
#endif
//~ print_servers();
// wait for time to be set
int retry = 0;
const int retry_count = 15;
while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count) {
ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
}
time(&SNTP_check_timestamp);
wifi_shutdown();
esp_netif_sntp_deinit();
#ifdef CONFIG_DS3231_I2C
time_t now = 0;
struct tm timeinfo = { 0 };
ESP_LOGW(__FUNCTION__,"Setting RTC");
if(rtc_available())
{
time(&now);
ds3231_time_get(&timeinfo);
time_t rtc_time_diff = mktime(&timeinfo) - now; // seconds is in UTC
// report the time difference
if(rtc_time_diff != 0)
{
ESP_LOGW(__FUNCTION__,"RTC was %s it will be adjusted by %d seconds",rtc_time_diff<0?"slower":"faster",abs((int)rtc_time_diff));
time(&now);
localtime_r(&now, &timeinfo);
if(ds3231_time_set(&timeinfo)==ESP_OK)
{
ds3231_time_get(&timeinfo);
char strftime_buf[64];
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
time(&now);
struct tm localtimeinfo;
//time(&now);
localtime_r(&now, &localtimeinfo);
char local[100];
strftime(local, sizeof(local), "%c", &localtimeinfo);
ESP_LOGI(__FUNCTION__, "System time synced to SNTP Server as UTC\nRTC : date/time is: %s \nLocal: date/time is: %s ", strftime_buf, local);
return true;
}
else
{
ESP_LOGW(__FUNCTION__, "Failed to set RTC");
}
}
}
#endif
return ESP_OK;
}