From e96d69d563bd9f378592f2d79ac54782867b9a54 Mon Sep 17 00:00:00 2001
From: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Date: Thu, 9 Nov 2023 16:18:39 +0200
Subject: [PATCH] esp32/network_wlan: Fix network.WLAN.status().

It can return STAT_NO_AP_FOUND and STAT_WRONG_PASSWORD.
This allows users to set the correct credentials.

Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
---
 ports/esp32/network_wlan.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/ports/esp32/network_wlan.c b/ports/esp32/network_wlan.c
index e1d16b4191d69..1f4c74f9158e8 100644
--- a/ports/esp32/network_wlan.c
+++ b/ports/esp32/network_wlan.c
@@ -106,21 +106,21 @@ static void network_wlan_wifi_event_handler(void *event_handler_arg, esp_event_b
             switch (disconn->reason) {
                 case WIFI_REASON_BEACON_TIMEOUT:
                     // AP has dropped out; try to reconnect.
-                    message = "\nbeacon timeout";
+                    message = "beacon timeout";
                     break;
                 case WIFI_REASON_NO_AP_FOUND:
                     // AP may not exist, or it may have momentarily dropped out; try to reconnect.
-                    message = "\nno AP found";
+                    message = "no AP found";
                     break;
                 case WIFI_REASON_AUTH_FAIL:
                     // Password may be wrong, or it just failed to connect; try to reconnect.
-                    message = "\nauthentication failed";
+                    message = "authentication failed";
                     break;
                 default:
                     // Let other errors through and try to reconnect.
                     break;
             }
-            ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d%s", disconn->reason, message);
+            ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d:%s", disconn->reason, message);
 
             wifi_sta_connected = false;
             if (wifi_sta_connect_requested) {
@@ -333,6 +333,10 @@ STATIC mp_obj_t network_wlan_status(size_t n_args, const mp_obj_t *args) {
             if (wifi_sta_connected) {
                 // Happy path, connected with IP
                 return MP_OBJ_NEW_SMALL_INT(STAT_GOT_IP);
+            } else if ((wifi_sta_disconn_reason == WIFI_REASON_NO_AP_FOUND) || (wifi_sta_disconn_reason == WIFI_REASON_AUTH_FAIL)) {
+                return MP_OBJ_NEW_SMALL_INT(wifi_sta_disconn_reason);
+            } else if (wifi_sta_disconn_reason == WIFI_REASON_CONNECTION_FAIL) {
+                return MP_OBJ_NEW_SMALL_INT(WIFI_REASON_AUTH_FAIL);
             } else if (wifi_sta_connect_requested
                        && (conf_wifi_sta_reconnects == 0
                            || wifi_sta_reconnects < conf_wifi_sta_reconnects)) {