diff --git a/ports/zephyr-cp/common-hal/wifi/Network.c b/ports/zephyr-cp/common-hal/wifi/Network.c index 44c049f88c1..510f8b9f5c2 100644 --- a/ports/zephyr-cp/common-hal/wifi/Network.c +++ b/ports/zephyr-cp/common-hal/wifi/Network.c @@ -34,35 +34,44 @@ mp_obj_t common_hal_wifi_network_get_country(wifi_network_obj_t *self) { } mp_obj_t common_hal_wifi_network_get_authmode(wifi_network_obj_t *self) { + // Translate Zephyr's wifi_security_type. An empty list would read as an + // open network to any caller checking for AUTHMODE_OPEN. uint32_t authmode_mask = 0; - // switch (self->record.authmode) { - // case WIFI_AUTH_OPEN: - // authmode_mask = AUTHMODE_OPEN; - // break; - // case WIFI_AUTH_WEP: - // authmode_mask = AUTHMODE_WEP; - // break; - // case WIFI_AUTH_WPA_PSK: - // authmode_mask = AUTHMODE_WPA | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA2_PSK: - // authmode_mask = AUTHMODE_WPA2 | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA_WPA2_PSK: - // authmode_mask = AUTHMODE_WPA | AUTHMODE_WPA2 | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA2_ENTERPRISE: - // authmode_mask = AUTHMODE_WPA2 | AUTHMODE_ENTERPRISE; - // break; - // case WIFI_AUTH_WPA3_PSK: - // authmode_mask = AUTHMODE_WPA3 | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA2_WPA3_PSK: - // authmode_mask = AUTHMODE_WPA2 | AUTHMODE_WPA3 | AUTHMODE_PSK; - // break; - // default: - // break; - // } + switch (self->scan_result.security) { + case WIFI_SECURITY_TYPE_NONE: + authmode_mask = AUTHMODE_OPEN; + break; + case WIFI_SECURITY_TYPE_WEP: + authmode_mask = AUTHMODE_WEP; + break; + case WIFI_SECURITY_TYPE_WPA_PSK: + authmode_mask = AUTHMODE_WPA | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_PSK: + case WIFI_SECURITY_TYPE_PSK_SHA256: + authmode_mask = AUTHMODE_WPA2 | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_SAE: // == WIFI_SECURITY_TYPE_SAE_HNP (alias) + case WIFI_SECURITY_TYPE_SAE_H2E: + case WIFI_SECURITY_TYPE_SAE_AUTO: + case WIFI_SECURITY_TYPE_SAE_EXT_KEY: + case WIFI_SECURITY_TYPE_FT_SAE: + authmode_mask = AUTHMODE_WPA3 | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_WPA_AUTO_PERSONAL: + authmode_mask = AUTHMODE_WPA | AUTHMODE_WPA2 | AUTHMODE_WPA3 | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_EAP: // == WIFI_SECURITY_TYPE_EAP_TLS (alias) + case WIFI_SECURITY_TYPE_EAP_PEAP_MSCHAPV2: + case WIFI_SECURITY_TYPE_EAP_PEAP_GTC: + case WIFI_SECURITY_TYPE_EAP_TTLS_MSCHAPV2: + case WIFI_SECURITY_TYPE_EAP_PEAP_TLS: + case WIFI_SECURITY_TYPE_FT_EAP: + authmode_mask = AUTHMODE_WPA2 | AUTHMODE_ENTERPRISE; + break; + default: + break; + } mp_obj_t authmode_list = mp_obj_new_list(0, NULL); if (authmode_mask != 0) { for (uint8_t i = 0; i < 32; i++) { diff --git a/ports/zephyr-cp/common-hal/wifi/Radio.c b/ports/zephyr-cp/common-hal/wifi/Radio.c index 35a0b76a362..a615c424259 100644 --- a/ports/zephyr-cp/common-hal/wifi/Radio.c +++ b/ports/zephyr-cp/common-hal/wifi/Radio.c @@ -25,6 +25,10 @@ #include "bindings/zephyr_kernel/__init__.h" #include +#include +#include +// dns_resolve_get_default() for radio.ipv4_dns. +#include #include #include #include @@ -33,6 +37,8 @@ #include "common-hal/mdns/Server.h" #endif +LOG_MODULE_DECLARE(cp_wifi); + #define MAC_ADDRESS_LENGTH 6 // static void set_mode_station(wifi_radio_obj_t *self, bool state) { @@ -85,7 +91,7 @@ void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { // #if CIRCUITPY_MDNS // mdns_server_deinit_singleton(); // #endif - printk("net_if_down\n"); + LOG_DBG("net_if_down"); int res = net_if_down(self->sta_netif); if (res < 0 && res != -EALREADY) { raise_zephyr_error(res); @@ -94,7 +100,7 @@ void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { return; } if (!self->started && enabled) { - printk("net_if_up\n"); + LOG_DBG("net_if_up"); int res = net_if_up(self->sta_netif); if (res < 0 && res != -EALREADY) { raise_zephyr_error(res); @@ -117,9 +123,19 @@ void common_hal_wifi_radio_set_hostname(wifi_radio_obj_t *self, const char *host } } +void wifi_radio_get_mac_address(wifi_radio_obj_t *self, uint8_t *mac) { + memset(mac, 0, MAC_ADDRESS_LENGTH); + if (self->sta_netif != NULL) { + struct net_linkaddr *addr = net_if_get_link_addr(self->sta_netif); + if (addr != NULL && addr->len >= MAC_ADDRESS_LENGTH) { + memcpy(mac, addr->addr, MAC_ADDRESS_LENGTH); + } + } +} + mp_obj_t common_hal_wifi_radio_get_mac_address(wifi_radio_obj_t *self) { uint8_t mac[MAC_ADDRESS_LENGTH]; - // esp_wifi_get_mac(ESP_IF_WIFI_STA, mac); + wifi_radio_get_mac_address(self, mac); return mp_obj_new_bytes(mac, MAC_ADDRESS_LENGTH); } @@ -214,13 +230,11 @@ void common_hal_wifi_radio_set_mac_address_ap(wifi_radio_obj_t *self, const uint } mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, uint8_t start_channel, uint8_t stop_channel) { - printk("common_hal_wifi_radio_start_scanning_networks\n"); + LOG_DBG("common_hal_wifi_radio_start_scanning_networks"); if (self->current_scan != NULL) { - printk("Already scanning for wifi networks\n"); mp_raise_RuntimeError(MP_ERROR_TEXT("Already scanning for wifi networks")); } if (!common_hal_wifi_radio_get_enabled(self)) { - printk("WiFi is not enabled\n"); mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } @@ -246,12 +260,12 @@ mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, u K_POLL_MODE_NOTIFY_ONLY, &scan->msgq); wifi_scannednetworks_scan_next_channel(scan); - printk("common_hal_wifi_radio_start_scanning_networks done %p\n", scan); + LOG_DBG("common_hal_wifi_radio_start_scanning_networks done %p", scan); return scan; } void common_hal_wifi_radio_stop_scanning_networks(wifi_radio_obj_t *self) { - printk("common_hal_wifi_radio_stop_scanning_networks\n"); + LOG_DBG("common_hal_wifi_radio_stop_scanning_networks"); // Return early if self->current_scan is NULL to avoid hang if (self->current_scan == NULL) { return; @@ -456,12 +470,146 @@ wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t // // We're connected, allow us to retry if we get disconnected. // self->retries_left = self->starting_retries; // } + + struct wifi_connect_req_params params = { 0 }; + + params.ssid = ssid; + params.ssid_length = ssid_len; + params.band = WIFI_FREQ_BAND_2_4_GHZ; + params.channel = channel == 0 ? WIFI_CHANNEL_ANY : channel; + params.mfp = WIFI_MFP_OPTIONAL; + params.timeout = SYS_FOREVER_MS; + + if (password_len > 0) { + params.psk = password; + params.psk_length = password_len; + // The security type must match what the AP advertises: this driver maps + // PSK to WPA2 and WPA_AUTO_PERSONAL to WPA3-transition, and rejects the + // wrong one with a generic "Authentication failure". So take it from the + // last scan, falling back to WPA2-PSK when the SSID was not seen. That + // fallback is wrong for a WPA3-only hidden AP. + params.security = WIFI_SECURITY_TYPE_PSK; + struct wifi_scan_result *cached = wifi_cached_scan_lookup(ssid, ssid_len); + if (cached != NULL) { + switch (cached->security) { + case WIFI_SECURITY_TYPE_SAE: + case WIFI_SECURITY_TYPE_SAE_H2E: + case WIFI_SECURITY_TYPE_SAE_AUTO: + params.security = WIFI_SECURITY_TYPE_WPA_AUTO_PERSONAL; + break; + case WIFI_SECURITY_TYPE_WPA_PSK: + params.security = WIFI_SECURITY_TYPE_WPA_PSK; + break; + default: + params.security = WIFI_SECURITY_TYPE_PSK; + break; + } + } + } else { + params.security = WIFI_SECURITY_TYPE_NONE; + } + + if (bssid_len == WIFI_MAC_ADDR_LEN) { + memcpy(params.bssid, bssid, WIFI_MAC_ADDR_LEN); + } + + // Already associated to the network being asked for: leave the link alone. + // supervisor_start_web_workflow() calls connect() on every invocation, so + // tearing the association down here would churn the link continuously. + if (self->connected && + ssid_len == self->current_ssid_len && + memcmp(ssid, self->current_ssid, ssid_len) == 0) { + return WIFI_RADIO_ERROR_NONE; + } + + // Switching networks. Connecting while associated returns -EALREADY and the + // failure path takes the interface down, so disconnect first. + if (self->connected) { + // A failure here is tolerated on purpose: if the interface really is + // unusable, the connect below returns a proper error to the caller. + (void)net_mgmt(NET_REQUEST_WIFI_DISCONNECT, self->sta_netif, NULL, 0); + // Give the controller a moment to tear the association down. + for (int i = 0; i < 40 && self->connected; i++) { + k_msleep(50); + } + self->connected = false; + } + + self->connected = false; + self->last_connect_status = -1; + self->last_disconnect_reason = 0; + k_sem_reset(&self->connect_sem); + + int res = net_mgmt(NET_REQUEST_WIFI_CONNECT, self->sta_netif, ¶ms, sizeof(params)); + if (res == -EALREADY) { + // Record the SSID as the success path does, so the early return above + // matches on a later connect() to the same network. + self->connected = true; + self->current_ssid_len = MIN(ssid_len, sizeof(self->current_ssid)); + memcpy(self->current_ssid, ssid, self->current_ssid_len); + return WIFI_RADIO_ERROR_NONE; + } + if (res < 0) { + return WIFI_RADIO_ERROR_UNSPECIFIED; + } + + // Wait for NET_EVENT_WIFI_CONNECT_RESULT (or a DISCONNECT_RESULT standing + // in for a failed attempt), staying responsive to ctrl-C. + mp_float_t timeout_s = timeout <= 0 ? (mp_float_t)10 : timeout; + int64_t deadline = k_uptime_get() + (int64_t)(timeout_s * 1000); + bool signalled = false; + while (k_uptime_get() < deadline) { + if (k_sem_take(&self->connect_sem, K_MSEC(50)) == 0) { + signalled = true; + break; + } + if (mp_hal_is_interrupted()) { + return WIFI_RADIO_ERROR_UNSPECIFIED; + } + } + + if (!signalled) { + return WIFI_RADIO_ERROR_HANDSHAKE_TIMEOUT; + } + if (!self->connected) { + switch (self->last_connect_status) { + case WIFI_STATUS_CONN_WRONG_PASSWORD: + return WIFI_RADIO_ERROR_AUTH_FAIL; + case WIFI_STATUS_CONN_AP_NOT_FOUND: + return WIFI_RADIO_ERROR_NO_AP_FOUND; + case WIFI_STATUS_CONN_TIMEOUT: + return WIFI_RADIO_ERROR_HANDSHAKE_TIMEOUT; + default: + return WIFI_RADIO_ERROR_CONNECTION_FAIL; + } + } + + // Remember which network this association is for, so a later connect() for + // the same SSID can return without disturbing it. + self->current_ssid_len = MIN(ssid_len, sizeof(self->current_ssid)); + memcpy(self->current_ssid, ssid, self->current_ssid_len); + + // Associated. Ask for an address; the AP side of DHCP can take a moment. + #if defined(CONFIG_NET_DHCPV4) + net_dhcpv4_start(self->sta_netif); + int64_t ip_deadline = k_uptime_get() + 15000; + while (k_uptime_get() < ip_deadline) { + if (net_if_ipv4_get_global_addr(self->sta_netif, NET_ADDR_PREFERRED) != NULL) { + break; + } + if (mp_hal_is_interrupted()) { + break; + } + k_msleep(50); + } + #endif + return WIFI_RADIO_ERROR_NONE; } bool common_hal_wifi_radio_get_connected(wifi_radio_obj_t *self) { - // return self->sta_mode && esp_netif_is_netif_up(self->netif); - return false; + return self->connected && self->sta_netif != NULL && + net_if_is_up(self->sta_netif); } mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self) { @@ -499,11 +647,23 @@ mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self) { } mp_obj_t common_hal_wifi_radio_get_ipv4_gateway(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + // net_if_ip.ipv4 only exists with CONFIG_NET_IPV4, and this file builds for + // every Wi-Fi board in the port, not just ones that enable it. + #if defined(CONFIG_NET_IPV4) + const struct net_if_config *cfg = net_if_get_config(self->sta_netif); + if (cfg == NULL || cfg->ip.ipv4 == NULL) { + return mp_const_none; + } + if (cfg->ip.ipv4->gw.s_addr == 0) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(cfg->ip.ipv4->gw.s_addr); + #else return mp_const_none; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return common_hal_ipaddress_new_ipv4address(self->ip_info.gw.addr); + #endif } mp_obj_t common_hal_wifi_radio_get_ipv4_gateway_ap(wifi_radio_obj_t *self) { @@ -515,11 +675,24 @@ mp_obj_t common_hal_wifi_radio_get_ipv4_gateway_ap(wifi_radio_obj_t *self) { } mp_obj_t common_hal_wifi_radio_get_ipv4_subnet(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + // See get_ipv4_gateway: net_if_ip.ipv4 needs CONFIG_NET_IPV4. + #if defined(CONFIG_NET_IPV4) + struct net_if_ipv4 *ipv4 = self->sta_netif->config.ip.ipv4; + if (ipv4 == NULL) { + return mp_const_none; + } + for (int i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { + if (ipv4->unicast[i].ipv4.is_used && + ipv4->unicast[i].ipv4.addr_state == NET_ADDR_PREFERRED) { + return common_hal_ipaddress_new_ipv4address( + ipv4->unicast[i].netmask.s_addr); + } + } + #endif return mp_const_none; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return common_hal_ipaddress_new_ipv4address(self->ip_info.netmask.addr); } mp_obj_t common_hal_wifi_radio_get_ipv4_subnet_ap(wifi_radio_obj_t *self) { @@ -562,31 +735,48 @@ mp_obj_t common_hal_wifi_radio_get_ipv4_subnet_ap(wifi_radio_obj_t *self) { // } mp_obj_t common_hal_wifi_radio_get_addresses(wifi_radio_obj_t *self) { - // return common_hal_wifi_radio_get_addresses_netif(self, self->netif); - return mp_const_none; + // shared-bindings documents this as Sequence[str], empty when not + // connected, so format as a dotted-quad string rather than returning an + // IPv4Address object. Same address as wifi_radio_get_ipv4_address(). + uint32_t ipv4_address = wifi_radio_get_ipv4_address(self); + if (ipv4_address == 0) { + return mp_const_empty_tuple; + } + uint8_t *octets = (uint8_t *)&ipv4_address; + char buf[16]; + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]); + mp_obj_t args[] = { mp_obj_new_str(buf, strlen(buf)) }; + return mp_obj_new_tuple(MP_ARRAY_SIZE(args), args); } mp_obj_t common_hal_wifi_radio_get_addresses_ap(wifi_radio_obj_t *self) { - // return common_hal_wifi_radio_get_addresses_netif(self, self->ap_netif); - return mp_const_none; + // AP mode is unimplemented here, but mp_const_none is still the wrong type + // for the Sequence[str] contract. + return mp_const_empty_tuple; } uint32_t wifi_radio_get_ipv4_address(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { - // return 0; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return self->ip_info.ip.addr; - return 0; + // Raw uint32_t sibling of common_hal_wifi_radio_get_ipv4_address(), + // used internally by supervisor/shared/web_workflow/web_workflow.c. + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return 0; + } + struct in_addr *addr = net_if_ipv4_get_global_addr(self->sta_netif, NET_ADDR_PREFERRED); + if (addr == NULL) { + return 0; + } + return addr->s_addr; } mp_obj_t common_hal_wifi_radio_get_ipv4_address(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { - // return mp_const_none; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return common_hal_ipaddress_new_ipv4address(self->ip_info.ip.addr); - return mp_const_none; + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + struct in_addr *addr = net_if_ipv4_get_global_addr(self->sta_netif, NET_ADDR_PREFERRED); + if (addr == NULL) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(addr->s_addr); } mp_obj_t common_hal_wifi_radio_get_ipv4_address_ap(wifi_radio_obj_t *self) { @@ -599,20 +789,26 @@ mp_obj_t common_hal_wifi_radio_get_ipv4_address_ap(wifi_radio_obj_t *self) { } mp_obj_t common_hal_wifi_radio_get_ipv4_dns(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { - // return mp_const_none; - // } - - // esp_netif_get_dns_info(self->netif, ESP_NETIF_DNS_MAIN, &self->dns_info); - - // if (self->dns_info.ip.type != ESP_IPADDR_TYPE_V4) { - // return mp_const_none; - // } - // // dns_info is of type esp_netif_dns_info_t, which is just ever so slightly - // // different than esp_netif_ip_info_t used for - // // common_hal_wifi_radio_get_ipv4_address (includes both ipv4 and 6), - // // so some extra jumping is required to get to the actual address - // return common_hal_ipaddress_new_ipv4address(self->dns_info.ip.u_addr.ip4.addr); + // Zephyr keeps resolver state in the DNS resolve context rather than on + // the interface, so read it there. + #if defined(CONFIG_DNS_RESOLVER) + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + struct dns_resolve_context *ctx = dns_resolve_get_default(); + if (ctx == NULL) { + return mp_const_none; + } + for (int i = 0; i < CONFIG_DNS_RESOLVER_MAX_SERVERS; i++) { + if (ctx->servers[i].dns_server.sa_family == AF_INET) { + struct sockaddr_in *addr = + (struct sockaddr_in *)&ctx->servers[i].dns_server; + if (addr->sin_addr.s_addr != 0) { + return common_hal_ipaddress_new_ipv4address(addr->sin_addr.s_addr); + } + } + } + #endif return mp_const_none; } diff --git a/ports/zephyr-cp/common-hal/wifi/Radio.h b/ports/zephyr-cp/common-hal/wifi/Radio.h index f177f493685..2500079df09 100644 --- a/ports/zephyr-cp/common-hal/wifi/Radio.h +++ b/ports/zephyr-cp/common-hal/wifi/Radio.h @@ -11,7 +11,9 @@ #include "shared-bindings/wifi/ScannedNetworks.h" #include "shared-bindings/wifi/Network.h" +#include #include +#include // Event bits for the Radio event group. #define WIFI_SCAN_DONE_BIT BIT0 @@ -38,6 +40,16 @@ typedef struct { uint8_t retries_left; uint8_t starting_retries; uint8_t last_disconnect_reason; + // Signalled from the net_mgmt event handler when a connect attempt + // finishes, so common_hal_wifi_radio_connect() can wait on the result. + struct k_sem connect_sem; + // Latest wifi_conn_status from NET_EVENT_WIFI_CONNECT_RESULT. + int last_connect_status; + bool connected; + // SSID of the association that `connected` refers to, so that a connect() + // for the network we are already on can return without touching the link. + uint8_t current_ssid[WIFI_SSID_MAX_LEN]; + size_t current_ssid_len; } wifi_radio_obj_t; extern void common_hal_wifi_radio_gc_collect(wifi_radio_obj_t *self); diff --git a/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c b/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c index 725bf1fa7cb..d7df14ffa5c 100644 --- a/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c +++ b/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c @@ -19,12 +19,15 @@ #include "bindings/zephyr_kernel/__init__.h" #include +#include #include +LOG_MODULE_DECLARE(cp_wifi); + void wifi_scannednetworks_scan_result(wifi_scannednetworks_obj_t *self, struct wifi_scan_result *result) { if (k_msgq_put(&self->msgq, result, K_NO_WAIT) != 0) { - printk("Dropping scan result!\n"); + LOG_WRN("Dropping scan result"); } } @@ -104,7 +107,7 @@ void wifi_scannednetworks_scan_next_channel(wifi_scannednetworks_obj_t *self) { } else { int res = net_mgmt(NET_REQUEST_WIFI_SCAN, self->netif, ¶ms, sizeof(params)); if (res != 0) { - printk("Failed to start wifi scan %d\n", res); + LOG_ERR("Failed to start wifi scan %d", res); raise_zephyr_error(res); wifi_scannednetworks_done(self); } else { diff --git a/ports/zephyr-cp/common-hal/wifi/__init__.c b/ports/zephyr-cp/common-hal/wifi/__init__.c index 4b967bc2780..33f1ad13ed8 100644 --- a/ports/zephyr-cp/common-hal/wifi/__init__.c +++ b/ports/zephyr-cp/common-hal/wifi/__init__.c @@ -4,6 +4,8 @@ // // SPDX-License-Identifier: MIT +#include + #include "common-hal/wifi/__init__.h" #include "shared-bindings/wifi/__init__.h" @@ -31,12 +33,15 @@ wifi_radio_obj_t common_hal_wifi_radio_obj; #endif #include +#include #include #include #define MAC_ADDRESS_LENGTH 6 +LOG_MODULE_REGISTER(cp_wifi, CONFIG_LOG_DEFAULT_LEVEL); + static void schedule_background_on_cp_core(void *arg) { #if CIRCUITPY_STATUS_BAR supervisor_status_bar_request_update(false); @@ -50,68 +55,124 @@ static void schedule_background_on_cp_core(void *arg) { static struct net_mgmt_event_callback wifi_cb; static struct net_mgmt_event_callback ipv4_cb; +// Small cache of the most recent scan, used by common_hal_wifi_radio_connect() +// to pick the right security type per AP. +#define WIFI_SCAN_CACHE_LEN 24 +static struct wifi_scan_result scan_cache[WIFI_SCAN_CACHE_LEN]; +static size_t scan_cache_count; + +struct wifi_scan_result *wifi_cached_scan_lookup(const uint8_t *ssid, size_t ssid_len) { + for (size_t i = 0; i < scan_cache_count; i++) { + if (scan_cache[i].ssid_length == ssid_len && + memcmp(scan_cache[i].ssid, ssid, ssid_len) == 0) { + return &scan_cache[i]; + } + } + return NULL; +} + +static void wifi_scan_cache_add(const struct wifi_scan_result *result) { + // Replace an existing entry for the same SSID so the cache tracks the + // latest reading rather than filling up with duplicate BSSIDs. + struct wifi_scan_result *existing = + wifi_cached_scan_lookup(result->ssid, result->ssid_length); + if (existing != NULL) { + *existing = *result; + return; + } + if (scan_cache_count < WIFI_SCAN_CACHE_LEN) { + scan_cache[scan_cache_count++] = *result; + } +} + static void _event_handler(struct net_mgmt_event_callback *cb, uint64_t mgmt_event, struct net_if *iface) { wifi_radio_obj_t *self = &common_hal_wifi_radio_obj; (void)iface; switch (mgmt_event) { case NET_EVENT_WIFI_SCAN_RESULT: { - printk("NET_EVENT_WIFI_SCAN_RESULT\n"); + LOG_DBG("NET_EVENT_WIFI_SCAN_RESULT"); const struct wifi_scan_result *result = cb->info; - if (result != NULL && self->current_scan != NULL) { - wifi_scannednetworks_scan_result(self->current_scan, result); + if (result != NULL) { + // Remember the authmode so connect() can request the matching + // security type later. + wifi_scan_cache_add(result); + if (self->current_scan != NULL) { + wifi_scannednetworks_scan_result(self->current_scan, result); + } } break; } case NET_EVENT_WIFI_SCAN_DONE: - printk("NET_EVENT_WIFI_SCAN_DONE (thread: %s prio=%d)\n", + LOG_DBG("NET_EVENT_WIFI_SCAN_DONE (thread: %s prio=%d)", k_thread_name_get(k_current_get()), k_thread_priority_get(k_current_get())); if (self->current_scan != NULL) { k_poll_signal_raise(&self->current_scan->channel_done, 0); } break; - case NET_EVENT_WIFI_CONNECT_RESULT: - printk("NET_EVENT_WIFI_CONNECT_RESULT\n"); + case NET_EVENT_WIFI_CONNECT_RESULT: { + const struct wifi_status *status = cb->info; + self->last_connect_status = status != NULL ? status->status : -1; + self->connected = self->last_connect_status == WIFI_STATUS_CONN_SUCCESS; + LOG_DBG("NET_EVENT_WIFI_CONNECT_RESULT status %d", self->last_connect_status); + k_sem_give(&self->connect_sem); break; - case NET_EVENT_WIFI_DISCONNECT_RESULT: - printk("NET_EVENT_WIFI_DISCONNECT_RESULT\n"); + } + case NET_EVENT_WIFI_DISCONNECT_RESULT: { + const struct wifi_status *status = cb->info; + self->last_disconnect_reason = status != NULL ? (uint8_t)status->status : 0; + self->connected = false; + LOG_DBG("NET_EVENT_WIFI_DISCONNECT_RESULT reason %d", self->last_disconnect_reason); + // A disconnect can also be the failure result of a connect attempt, + // so release any waiter rather than letting it sit until timeout. + k_sem_give(&self->connect_sem); break; + } case NET_EVENT_WIFI_IFACE_STATUS: - printk("NET_EVENT_WIFI_IFACE_STATUS\n"); + LOG_DBG("NET_EVENT_WIFI_IFACE_STATUS"); break; case NET_EVENT_WIFI_TWT: - printk("NET_EVENT_WIFI_TWT\n"); + LOG_DBG("NET_EVENT_WIFI_TWT"); break; case NET_EVENT_WIFI_TWT_SLEEP_STATE: - printk("NET_EVENT_WIFI_TWT_SLEEP_STATE\n"); + LOG_DBG("NET_EVENT_WIFI_TWT_SLEEP_STATE"); break; case NET_EVENT_WIFI_RAW_SCAN_RESULT: - printk("NET_EVENT_WIFI_RAW_SCAN_RESULT\n"); + LOG_DBG("NET_EVENT_WIFI_RAW_SCAN_RESULT"); break; case NET_EVENT_WIFI_DISCONNECT_COMPLETE: - printk("NET_EVENT_WIFI_DISCONNECT_COMPLETE\n"); + LOG_DBG("NET_EVENT_WIFI_DISCONNECT_COMPLETE"); break; case NET_EVENT_WIFI_SIGNAL_CHANGE: - printk("NET_EVENT_WIFI_SIGNAL_CHANGE\n"); + LOG_DBG("NET_EVENT_WIFI_SIGNAL_CHANGE"); break; case NET_EVENT_WIFI_NEIGHBOR_REP_COMP: - printk("NET_EVENT_WIFI_NEIGHBOR_REP_COMP\n"); + LOG_DBG("NET_EVENT_WIFI_NEIGHBOR_REP_COMP"); break; case NET_EVENT_WIFI_AP_ENABLE_RESULT: - printk("NET_EVENT_WIFI_AP_ENABLE_RESULT\n"); + LOG_DBG("NET_EVENT_WIFI_AP_ENABLE_RESULT"); break; case NET_EVENT_WIFI_AP_DISABLE_RESULT: - printk("NET_EVENT_WIFI_AP_DISABLE_RESULT\n"); + LOG_DBG("NET_EVENT_WIFI_AP_DISABLE_RESULT"); break; case NET_EVENT_WIFI_AP_STA_CONNECTED: - printk("NET_EVENT_WIFI_AP_STA_CONNECTED\n"); + LOG_DBG("NET_EVENT_WIFI_AP_STA_CONNECTED"); break; case NET_EVENT_WIFI_AP_STA_DISCONNECTED: - printk("NET_EVENT_WIFI_AP_STA_DISCONNECTED\n"); + LOG_DBG("NET_EVENT_WIFI_AP_STA_DISCONNECTED"); + break; + case NET_EVENT_IPV4_ADDR_ADD: + // DHCP bound, or a static address was configured. The address is read + // live by the ipv4_address getter, so nothing is stored here; the + // status bar just needs a refresh or it keeps showing "No IP". + LOG_DBG("NET_EVENT_IPV4_ADDR_ADD"); + schedule_background_on_cp_core(NULL); break; default: - printk("unhandled net event %x\n", mgmt_event); + // Print all 64 bits. The layer lives in the high bits, so a 32-bit + // print collapses every unhandled event in a layer to one value. + LOG_DBG("unhandled net event %llx", (unsigned long long)mgmt_event); break; } } @@ -196,7 +257,7 @@ static bool wifi_user_initiated; void common_hal_wifi_init(bool user_initiated) { wifi_radio_obj_t *self = &common_hal_wifi_radio_obj; - printk("common_hal_wifi_init\n"); + LOG_DBG("common_hal_wifi_init"); if (wifi_inited) { if (user_initiated && !wifi_user_initiated) { @@ -207,6 +268,9 @@ void common_hal_wifi_init(bool user_initiated) { wifi_inited = true; wifi_user_initiated = user_initiated; self->base.type = &wifi_radio_type; + k_sem_init(&self->connect_sem, 0, 1); + self->connected = false; + self->last_connect_status = -1; // struct net_if *default_iface = net_if_get_default(); // printk("default interface %p\n", default_iface); @@ -223,8 +287,8 @@ void common_hal_wifi_init(bool user_initiated) { // } self->sta_netif = net_if_get_wifi_sta(); self->ap_netif = net_if_get_wifi_sap(); - printk("sta_netif %p\n", self->sta_netif); - printk("ap_netif %p\n", self->ap_netif); + LOG_DBG("sta_netif %p", self->sta_netif); + LOG_DBG("ap_netif %p", self->ap_netif); struct wifi_iface_status status = { 0 }; @@ -232,39 +296,39 @@ void common_hal_wifi_init(bool user_initiated) { CHECK_ZEPHYR_RESULT(net_mgmt(NET_REQUEST_WIFI_IFACE_STATUS, self->sta_netif, &status, sizeof(struct wifi_iface_status))); if (net_if_is_up(self->sta_netif)) { - printk("STA is up\n"); + LOG_DBG("STA is up"); } else { - printk("STA is down\n"); + LOG_DBG("STA is down"); } if (net_if_is_carrier_ok(self->sta_netif)) { - printk("STA carrier is ok\n"); + LOG_DBG("STA carrier is ok"); } else { - printk("STA carrier is not ok\n"); + LOG_DBG("STA carrier is not ok"); } if (net_if_is_dormant(self->sta_netif)) { - printk("STA is dormant\n"); + LOG_DBG("STA is dormant"); } else { - printk("STA is not dormant\n"); + LOG_DBG("STA is not dormant"); } } if (self->ap_netif != NULL) { int res = net_mgmt(NET_REQUEST_WIFI_IFACE_STATUS, self->ap_netif, &status, sizeof(struct wifi_iface_status)); - printk("AP status request response %d\n", res); + LOG_DBG("AP status request response %d", res); if (net_if_is_up(self->ap_netif)) { - printk("AP is up\n"); + LOG_DBG("AP is up"); } else { - printk("AP is down\n"); + LOG_DBG("AP is down"); } if (net_if_is_carrier_ok(self->ap_netif)) { - printk("AP carrier is ok\n"); + LOG_DBG("AP carrier is ok"); } else { - printk("AP carrier is not ok\n"); + LOG_DBG("AP carrier is not ok"); } if (net_if_is_dormant(self->ap_netif)) { - printk("AP is dormant\n"); + LOG_DBG("AP is dormant"); } else { - printk("AP is not dormant\n"); + LOG_DBG("AP is not dormant"); } } @@ -278,6 +342,7 @@ void common_hal_wifi_init(bool user_initiated) { // self->ap_mode = 0; net_mgmt_init_event_callback(&wifi_cb, _event_handler, + NET_EVENT_WIFI_SCAN_RESULT | NET_EVENT_WIFI_SCAN_DONE | NET_EVENT_WIFI_CONNECT_RESULT | NET_EVENT_WIFI_DISCONNECT_RESULT | @@ -317,21 +382,21 @@ void common_hal_wifi_init(bool user_initiated) { char cpy_default_hostname[board_len + (MAC_ADDRESS_LENGTH * 2) + 6]; struct net_linkaddr *mac = net_if_get_link_addr(self->sta_netif); if (mac->len < MAC_ADDRESS_LENGTH) { - printk("MAC address too short"); + LOG_ERR("MAC address too short"); } snprintf(cpy_default_hostname, sizeof(cpy_default_hostname), "cpy-%s-%02x%02x%02x%02x%02x%02x", CIRCUITPY_BOARD_ID + board_trim, mac->addr[0], mac->addr[1], mac->addr[2], mac->addr[3], mac->addr[4], mac->addr[5]); CHECK_ZEPHYR_RESULT(net_hostname_set(cpy_default_hostname, strlen(cpy_default_hostname))); } #else - printk("Hostname support disabled in Zephyr config\n"); + LOG_WRN("Hostname support disabled in Zephyr config"); #endif // set station mode to avoid the default SoftAP common_hal_wifi_radio_start_station(self); // start wifi common_hal_wifi_radio_set_enabled(self, true); - printk("common_hal_wifi_init done\n"); + LOG_DBG("common_hal_wifi_init done"); } void wifi_user_reset(void) { @@ -342,7 +407,7 @@ void wifi_user_reset(void) { } void wifi_reset(void) { - printk("wifi_reset\n"); + LOG_DBG("wifi_reset"); if (!wifi_inited) { return; } diff --git a/ports/zephyr-cp/common-hal/wifi/__init__.h b/ports/zephyr-cp/common-hal/wifi/__init__.h index dab519b1a5f..9f730003878 100644 --- a/ports/zephyr-cp/common-hal/wifi/__init__.h +++ b/ports/zephyr-cp/common-hal/wifi/__init__.h @@ -8,10 +8,16 @@ #include "py/obj.h" +#include + struct sockaddr_storage; void wifi_reset(void); +// Look up an SSID in the cache of the most recent scan. Returns NULL if the +// network was not seen. +struct wifi_scan_result *wifi_cached_scan_lookup(const uint8_t *ssid, size_t ssid_len); + // void ipaddress_ipaddress_to_esp_idf(mp_obj_t ip_address, ip_addr_t *esp_ip_address); // void ipaddress_ipaddress_to_esp_idf_ip4(mp_obj_t ip_address, esp_ip4_addr_t *esp_ip_address);