/* * 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 #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 "audio_api.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 bool s_ap_on = false; // Wi-Fi access point running static const char *reset_reason(void) { switch (esp_reset_reason()) { case ESP_RST_POWERON: return "power_on"; case ESP_RST_EXT: return "external"; case ESP_RST_SW: return "software"; case ESP_RST_PANIC: return "panic"; case ESP_RST_INT_WDT: return "interrupt_watchdog"; case ESP_RST_TASK_WDT: return "task_watchdog"; case ESP_RST_WDT: return "watchdog"; case ESP_RST_BROWNOUT: return "brownout"; case ESP_RST_USB: return "usb"; case ESP_RST_PWR_GLITCH: return "power_glitch"; default: return "unknown"; } } 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], mask[16], gw[16], clients[400]; char *buf = malloc(2048); if (!buf) { return httpd_resp_send_500(req); } beat_get_info(&bi); mic_get_level(&level); espnow_tx_stats(&es); rel_stats(&rs); if (s_eth_netif) { // NULL when the W5500 did not start 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(mask, sizeof(mask), IPSTR, IP2STR(&ip_info.netmask)); snprintf(gw, sizeof(gw), IPSTR, IP2STR(&ip_info.gw)); espnow_tx_ap_clients(clients, sizeof(clients)); snprintf(buf, 2048, "{\"ap\":%s,\"eth\":{\"ip\":\"%s\",\"mask\":\"%s\",\"gw\":\"%s\",\"up\":%s},\"ap_ip\":\"192.168.5.1\",\"ap_clients\":%s,\"ip\":\"%s\",\"mac\":\"%s\",\"uptime_s\":%lld,\"reset_reason\":\"%s\",\"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}}", s_ap_on ? "true" : "false", ip, mask, gw, ip_info.ip.addr ? "true" : "false", clients, ip, macs, (long long)(esp_timer_get_time() / 1000000), reset_reason(), (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"); esp_err_t err = httpd_resp_sendstr(req, buf); free(buf); return err; } #define DEFAULT_HOSTNAME "led-controller" // Address when no DHCP server answers, as on a cable straight to a PC. The PC needs a static IP on this subnet. #define DEFAULT_IP ESP_IP4TOADDR(192, 168, 4, 1) #define DEFAULT_NETMASK ESP_IP4TOADDR(255, 255, 255, 0) #define DHCP_WAIT_S 15 // Boolean setting; def when missing or not a boolean static bool settings_bool(const char *key, bool def) { cJSON *v = cJSON_GetObjectItem(store_settings(), key); return cJSON_IsBool(v) ? cJSON_IsTrue(v) : def; } // AP button held (to ground) for AP_HOLD_MS from boot static bool ap_button_held(void) { #if CONFIG_AP_BUTTON_GPIO >= 0 gpio_config_t io = { .pin_bit_mask = 1ULL << CONFIG_AP_BUTTON_GPIO, .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_ENABLE }; if (gpio_config(&io) != ESP_OK) { return false; } for (int t = 0; t < CONFIG_AP_HOLD_MS; t += 10) { if (gpio_get_level(CONFIG_AP_BUTTON_GPIO)) { return false; } vTaskDelay(pdMS_TO_TICKS(10)); } return true; #else return false; #endif } 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, then to DEFAULT_IP. 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 bool have_static_ips(void) { cJSON *l = cJSON_GetObjectItem(store_settings(), "static_ips"); return cJSON_IsArray(l) && cJSON_GetArraySize(l) > 0; } static bool try_static_ips(void) { if (!have_static_ips()) { return false; } cJSON *list = cJSON_GetObjectItem(store_settings(), "static_ips"); esp_netif_dhcpc_stop(s_eth_netif); 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)); return true; } ESP_LOGI(TAG, "Static IP " IPSTR ": gateway " IPSTR " did not answer", IP2STR(&info.ip), IP2STR(&info.gw)); } ESP_LOGW(TAG, "No static IP matched this network, using DHCP"); return false; } // Start DHCP and wait for a lease. A lost link also ends the wait: the next link-up starts over. static bool dhcp_settled(void) { esp_netif_dhcpc_start(s_eth_netif); for (int i = 0; i < DHCP_WAIT_S * 10; i++) { esp_netif_ip_info_t ip; vTaskDelay(pdMS_TO_TICKS(100)); esp_netif_get_ip_info(s_eth_netif, &ip); if (ip.ip.addr != 0 || !esp_netif_is_netif_up(s_eth_netif)) { return true; } } return false; } static void link_up_task(void *arg) { static bool running; if (running) { vTaskDelete(NULL); } running = true; if (!try_static_ips() && !dhcp_settled()) { ESP_LOGW(TAG, "No DHCP server, using the default IP"); esp_netif_ip_info_t info = { .ip.addr = DEFAULT_IP, .netmask.addr = DEFAULT_NETMASK }; esp_netif_dhcpc_stop(s_eth_netif); esp_netif_set_ip_info(s_eth_netif, &info); } running = false; vTaskDelete(NULL); } 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 = 80; config.stack_size = 8192; config.lru_purge_enable = true; config.max_open_sockets = 12; // browsers open 6 connections at once config.backlog_conn = 10; // the default 5 drops the 6th SYN, a 1 s retry 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); audio_api_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)); esp_netif_create_ip6_linklocal(s_eth_netif); // lets mDNS answer AAAA queries (see espnow_tx.c) xTaskCreate(link_up_task, "link_up", 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()); // Wi-Fi (AP + ESP-NOW) comes up first so the AP is there even if Ethernet fails const char *host = settings_str("hostname"); bool held = ap_button_held(); s_ap_on = settings_bool("ap_enabled", true) || held; ESP_LOGI(TAG, "AP %s%s", s_ap_on ? "on" : "off", held ? " (button held)" : ""); espnow_tx_set_bridge(settings_str("bridge")); // led-simulator stands in for the radio ESP_ERROR_CHECK(espnow_tx_init(s_ap_on ? (host ? host : DEFAULT_HOSTNAME) : NULL, settings_str("ap_password"))); // Ethernet is optional: without it the web UI is still served over the AP esp_eth_handle_t eth_handle = NULL; if (w5500_init(ð_handle) == ESP_OK) { 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))); 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)); } else { ESP_LOGE(TAG, "Ethernet unavailable, continuing without it%s", s_ap_on ? " (web UI on the AP)" : ""); start_webserver(); start_mdns(); } ESP_ERROR_CHECK(rel_init()); ESP_ERROR_CHECK(engine_init()); ESP_ERROR_CHECK(mic_start()); ESP_ERROR_CHECK(seqplay_init()); }