diff --git a/ports/esp32s2/common-hal/wifi/Radio.c b/ports/esp32s2/common-hal/wifi/Radio.c index 696af28f84..24ec210091 100644 --- a/ports/esp32s2/common-hal/wifi/Radio.c +++ b/ports/esp32s2/common-hal/wifi/Radio.c @@ -126,15 +126,25 @@ void common_hal_wifi_radio_set_hostname(wifi_radio_obj_t *self, const char *host } wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t* ssid, size_t ssid_len, uint8_t* password, size_t password_len, uint8_t channel, mp_float_t timeout, uint8_t* bssid, size_t bssid_len) { + if (!common_hal_wifi_radio_get_enabled(self)) { + mp_raise_RuntimeError(translate("Can't connect when wifi is not enabled")); + } + EventBits_t bits; + // can't block since both bits are false after wifi_init + // both bits are true after an existing connection stops bits = xEventGroupWaitBits(self->event_group_handle, WIFI_CONNECTED_BIT | WIFI_DISCONNECTED_BIT, pdTRUE, pdTRUE, 0); - if ((bits & WIFI_CONNECTED_BIT) != 0) { - return WIFI_RADIO_ERROR_NONE; - } + if (((bits & WIFI_CONNECTED_BIT) != 0) && + !((bits & WIFI_DISCONNECTED_BIT) != 0)) { + return WIFI_RADIO_ERROR_NONE; + } + // explicitly clear bits since xEventGroupWaitBits may have timed out + xEventGroupClearBits(self->event_group_handle, WIFI_CONNECTED_BIT); + xEventGroupClearBits(self->event_group_handle, WIFI_DISCONNECTED_BIT); start_station(self); wifi_config_t* config = &self->sta_config;