/* * v2 controller: W5500 Ethernet, INMP441 beat detection, ESP-NOW master. */ #include #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log.h" #include "esp_check.h" #include "esp_event.h" #include "esp_netif.h" #include "esp_eth.h" #include "esp_mac.h" #include "nvs_flash.h" #include "driver/gpio.h" #include "driver/spi_master.h" #include "esp_http_server.h" #include "esp_timer.h" #include "esp_heap_caps.h" #include "esp_system.h" #include "mdns.h" #include "lwip/ip4_addr.h" #include "lwip/etharp.h" #include "lwip/netif.h" #include "lwip/sockets.h" #include "esp_netif_net_stack.h" #include "cJSON.h" #include "mic.h" #include "beat.h" #include "espnow_tx.h" #include "store.h" #include "ws.h" #include "api.h" #include "engine.h" #include "seqplay.h" #include "rel.h" #include "web.h" #include "audio.h" #include "ota.h" #include "drv_ota.h" static const char *TAG = "eth"; static httpd_handle_t s_server = NULL; static esp_netif_t *s_eth_netif = NULL; static esp_err_t status_get_handler(httpd_req_t *req) { beat_info_t bi; mic_level_t level; espnow_stats_t es; rel_stats_t rs; esp_netif_ip_info_t ip_info = { 0 }; uint8_t mac[6] = { 0 }; char ip[16], macs[18], buf[1024]; beat_get_info(&bi); mic_get_level(&level); espnow_tx_stats(&es); rel_stats(&rs); esp_netif_get_ip_info(s_eth_netif, &ip_info); esp_netif_get_mac(s_eth_netif, mac); snprintf(ip, sizeof(ip), IPSTR, IP2STR(&ip_info.ip)); snprintf(macs, sizeof(macs), MACSTR, MAC2STR(mac)); snprintf(buf, sizeof(buf), "{\"ip\":\"%s\",\"mac\":\"%s\",\"uptime_s\":%lld,\"free_heap\":%lu,\"free_internal\":%lu," "\"mic_rms_dbfs\":%.1f,\"mic_peak_dbfs\":%.1f,\"mic_spl_db\":%.1f," "\"bpm\":%.1f,\"beat_confidence\":%.2f,\"beat_locked\":%s,\"beats\":%lu,\"onsets\":%lu," "\"meter\":%d,\"bar_beat\":%d,\"bar_sure\":%s,\"downbeats\":%lu," "\"espnow\":{\"beats_sent\":%lu,\"beat_send_fail\":%lu,\"bulk_sent\":%lu," "\"bulk_retries\":%lu,\"bulk_failed\":%lu,\"sim_dropped\":%lu}," "\"link\":{\"ver\":%u,\"acked\":%lu,\"ack_timeouts\":%lu,\"retransmits\":%lu,\"resyncs\":%lu,\"digests\":%lu}}", ip, macs, (long long)(esp_timer_get_time() / 1000000), (unsigned long)esp_get_free_heap_size(), (unsigned long)heap_caps_get_free_size(MALLOC_CAP_INTERNAL), level.rms_dbfs, level.peak_dbfs, level.spl_db, bi.bpm, bi.confidence, bi.locked ? "true" : "false", (unsigned long)bi.beat_count, (unsigned long)bi.onset_count, bi.meter, bi.bar_beat, bi.bar_sure ? "true" : "false", (unsigned long)bi.downbeat_count, (unsigned long)es.beats_sent, (unsigned long)es.beat_send_fail, (unsigned long)es.bulk_sent, (unsigned long)es.bulk_retries, (unsigned long)es.bulk_failed, (unsigned long)es.sim_dropped, rel_ver(), (unsigned long)rs.acked, (unsigned long)rs.ack_timeouts, (unsigned long)rs.retransmits, (unsigned long)rs.resyncs, (unsigned long)rs.digests); httpd_resp_set_type(req, "application/json"); return httpd_resp_sendstr(req, buf); } #define DEFAULT_HOSTNAME "led-controller" static const char *settings_str(const char *key) { cJSON *v = cJSON_GetObjectItem(store_settings(), key); return cJSON_IsString(v) && v->valuestring[0] ? v->valuestring : NULL; } // "static_ips" setting: a list of {ip, netmask, gw, dns} tried in order on every link-up. The first whose // gateway answers ARP is kept; if none does, the controller falls back to DHCP. static bool parse_static(cJSON *e, esp_netif_ip_info_t *info, esp_netif_dns_info_t *dns) { const char *ip = NULL, *mask = "255.255.255.0", *gw = NULL, *d = NULL; cJSON *v; if (!cJSON_IsObject(e)) return false; if (cJSON_IsString(v = cJSON_GetObjectItem(e, "ip"))) ip = v->valuestring; if (cJSON_IsString(v = cJSON_GetObjectItem(e, "netmask"))) mask = v->valuestring; if (cJSON_IsString(v = cJSON_GetObjectItem(e, "gw"))) gw = v->valuestring; if (cJSON_IsString(v = cJSON_GetObjectItem(e, "dns"))) d = v->valuestring; memset(info, 0, sizeof(*info)); memset(dns, 0, sizeof(*dns)); if (!ip || esp_netif_str_to_ip4(ip, &info->ip) != ESP_OK || esp_netif_str_to_ip4(mask, &info->netmask) != ESP_OK || (gw && esp_netif_str_to_ip4(gw, &info->gw) != ESP_OK)) { return false; } if (d && esp_netif_str_to_ip4(d, &dns->ip.u_addr.ip4) == ESP_OK) { dns->ip.type = ESP_IPADDR_TYPE_V4; } else if (gw) { dns->ip.u_addr.ip4 = info->gw; dns->ip.type = ESP_IPADDR_TYPE_V4; } return true; } // Poke the gateway so lwIP ARPs for it, then wait for the entry to show up static bool gateway_answers(esp_netif_t *netif, const esp_ip4_addr_t *gw) { struct netif *nif = esp_netif_get_netif_impl(netif); ip4_addr_t g = { .addr = gw->addr }; int sock = socket(AF_INET, SOCK_DGRAM, 0); if (!nif || sock < 0) { if (sock >= 0) close(sock); return false; } struct sockaddr_in to = { .sin_family = AF_INET, .sin_port = htons(9), .sin_addr.s_addr = gw->addr }; bool ok = false; for (int i = 0; i < 15 && !ok; i++) { sendto(sock, "", 0, 0, (struct sockaddr *)&to, sizeof(to)); vTaskDelay(pdMS_TO_TICKS(100)); struct eth_addr *eth = NULL; const ip4_addr_t *ipr = NULL; ok = etharp_find_addr(nif, &g, ð, &ipr) >= 0; } close(sock); return ok; } static void static_ip_task(void *arg) { static bool running; if (running) { vTaskDelete(NULL); } running = true; cJSON *list = cJSON_GetObjectItem(store_settings(), "static_ips"); esp_netif_dhcpc_stop(s_eth_netif); bool done = false; cJSON *e; cJSON_ArrayForEach(e, list) { esp_netif_ip_info_t info; esp_netif_dns_info_t dns; if (!parse_static(e, &info, &dns)) { ESP_LOGW(TAG, "static_ips: skipping an invalid entry"); continue; } if (esp_netif_set_ip_info(s_eth_netif, &info) != ESP_OK) { continue; } if (dns.ip.type == ESP_IPADDR_TYPE_V4) { esp_netif_set_dns_info(s_eth_netif, ESP_NETIF_DNS_MAIN, &dns); } if (info.gw.addr == 0 || gateway_answers(s_eth_netif, &info.gw)) { ESP_LOGI(TAG, "Static IP " IPSTR " (gw " IPSTR ")", IP2STR(&info.ip), IP2STR(&info.gw)); done = true; break; } ESP_LOGI(TAG, "Static IP " IPSTR ": gateway " IPSTR " did not answer", IP2STR(&info.ip), IP2STR(&info.gw)); } if (!done) { ESP_LOGW(TAG, "No static IP matched this network, using DHCP"); esp_netif_ip_info_t none = { 0 }; esp_netif_set_ip_info(s_eth_netif, &none); esp_netif_dhcpc_start(s_eth_netif); } running = false; vTaskDelete(NULL); } static bool have_static_ips(void) { cJSON *l = cJSON_GetObjectItem(store_settings(), "static_ips"); return cJSON_IsArray(l) && cJSON_GetArraySize(l) > 0; } static void start_mdns(void) { const char *host = settings_str("hostname"); if (!host) { host = DEFAULT_HOSTNAME; } if (mdns_init() != ESP_OK) { ESP_LOGE(TAG, "mDNS init failed"); return; } mdns_hostname_set(host); mdns_instance_name_set("LED controller"); mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0); ESP_LOGI(TAG, "mDNS: %s.local", host); } static void start_webserver(void) { if (s_server) { return; } httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.uri_match_fn = httpd_uri_match_wildcard; config.max_uri_handlers = 72; config.stack_size = 8192; config.lru_purge_enable = true; if (httpd_start(&s_server, &config) != ESP_OK) { ESP_LOGE(TAG, "HTTP server start failed"); return; } const httpd_uri_t status_uri = { .uri = "/status", .method = HTTP_GET, .handler = status_get_handler }; httpd_register_uri_handler(s_server, &status_uri); web_register(s_server); audio_register(s_server); ota_register(s_server); drv_ota_register(s_server); api_register(s_server); ws_register(s_server); ESP_LOGI(TAG, "HTTP server started on port %d", config.server_port); } static void eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { esp_eth_handle_t eth_handle = *(esp_eth_handle_t *)event_data; uint8_t mac[6] = {0}; switch (event_id) { case ETHERNET_EVENT_CONNECTED: { eth_speed_t speed; eth_duplex_t duplex; esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac); esp_eth_ioctl(eth_handle, ETH_CMD_G_SPEED, &speed); esp_eth_ioctl(eth_handle, ETH_CMD_G_DUPLEX_MODE, &duplex); ESP_LOGI(TAG, "Ethernet Link Up, MAC " MACSTR, MAC2STR(mac)); if (have_static_ips()) { xTaskCreate(static_ip_task, "static_ip", 4096, NULL, 5, NULL); } ESP_LOGI(TAG, "%s Mbps %s Duplex", speed == ETH_SPEED_100M ? "100" : "10", duplex == ETH_DUPLEX_FULL ? "Full" : "Half"); break; } case ETHERNET_EVENT_DISCONNECTED: ESP_LOGI(TAG, "Ethernet Link Down"); break; case ETHERNET_EVENT_START: ESP_LOGI(TAG, "Ethernet Started"); break; case ETHERNET_EVENT_STOP: ESP_LOGI(TAG, "Ethernet Stopped"); break; default: break; } } static void got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; const esp_netif_ip_info_t *ip = &event->ip_info; ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&ip->ip)); ESP_LOGI(TAG, "Mask: " IPSTR, IP2STR(&ip->netmask)); ESP_LOGI(TAG, "GW: " IPSTR, IP2STR(&ip->gw)); // Server binds to all interfaces, so it keeps working across lease changes start_webserver(); static bool mdns_started; if (!mdns_started) { mdns_started = true; start_mdns(); } } static esp_err_t w5500_init(esp_eth_handle_t *eth_handle_out) { esp_err_t ret = ESP_OK; esp_eth_mac_t *mac = NULL; esp_eth_phy_t *phy = NULL; esp_eth_handle_t eth_handle = NULL; // INT pin uses a GPIO ISR ESP_RETURN_ON_ERROR(gpio_install_isr_service(0), TAG, "GPIO ISR service install failed"); spi_bus_config_t buscfg = { .miso_io_num = CONFIG_W5500_MISO_GPIO, .mosi_io_num = CONFIG_W5500_MOSI_GPIO, .sclk_io_num = CONFIG_W5500_SCLK_GPIO, .quadwp_io_num = -1, .quadhd_io_num = -1, }; ESP_RETURN_ON_ERROR(spi_bus_initialize(CONFIG_W5500_SPI_HOST, &buscfg, SPI_DMA_CH_AUTO), TAG, "SPI bus init failed"); spi_device_interface_config_t spi_devcfg = { .mode = 0, .clock_speed_hz = CONFIG_W5500_SPI_CLOCK_MHZ * 1000 * 1000, .queue_size = 20, .spics_io_num = CONFIG_W5500_CS_GPIO, }; eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(CONFIG_W5500_SPI_HOST, &spi_devcfg); w5500_config.int_gpio_num = CONFIG_W5500_INT_GPIO; if (CONFIG_W5500_INT_GPIO < 0) { w5500_config.poll_period_ms = CONFIG_W5500_POLL_PERIOD_MS; } eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); phy_config.reset_gpio_num = CONFIG_W5500_RST_GPIO; mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config); phy = esp_eth_phy_new_w5500(&phy_config); ESP_GOTO_ON_FALSE(mac && phy, ESP_FAIL, err, TAG, "W5500 MAC/PHY create failed"); esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, phy); ESP_GOTO_ON_ERROR(esp_eth_driver_install(ð_config, ð_handle), err, TAG, "Driver install failed (check W5500 wiring/power)"); // The W5500 has no factory MAC; use the ESP32's Ethernet MAC from eFuse uint8_t eth_mac[6]; ESP_GOTO_ON_ERROR(esp_read_mac(eth_mac, ESP_MAC_ETH), err, TAG, "Read MAC failed"); ESP_GOTO_ON_ERROR(esp_eth_ioctl(eth_handle, ETH_CMD_S_MAC_ADDR, eth_mac), err, TAG, "Set MAC failed"); *eth_handle_out = eth_handle; return ESP_OK; err: if (eth_handle) { esp_eth_driver_uninstall(eth_handle); } if (mac) { mac->del(mac); } if (phy) { phy->del(phy); } spi_bus_free(CONFIG_W5500_SPI_HOST); return ret; } void app_main(void) { esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); ota_confirm_later(); ESP_ERROR_CHECK(store_init()); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); esp_eth_handle_t eth_handle = NULL; ESP_ERROR_CHECK(w5500_init(ð_handle)); esp_netif_config_t netif_cfg = ESP_NETIF_DEFAULT_ETH(); s_eth_netif = esp_netif_new(&netif_cfg); ESP_ERROR_CHECK(esp_netif_attach(s_eth_netif, esp_eth_new_netif_glue(eth_handle))); const char *host = settings_str("hostname"); esp_netif_set_hostname(s_eth_netif, host ? host : DEFAULT_HOSTNAME); ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, ð_event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL)); ESP_ERROR_CHECK(esp_eth_start(eth_handle)); ESP_ERROR_CHECK(espnow_tx_init()); ESP_ERROR_CHECK(rel_init()); ESP_ERROR_CHECK(engine_init()); ESP_ERROR_CHECK(mic_start()); ESP_ERROR_CHECK(seqplay_init()); }