1+ #include < stdio.h>
2+ #include " freertos/FreeRTOS.h"
3+ #include " freertos/task.h"
4+ #include " esp_log.h"
5+ #include " nvs_flash.h"
6+ #include < esp_mac.h>
7+ #include < esp_system.h>
8+ #include < esp_ota_ops.h>
9+ #include < esp_partition.h>
10+ #include < nvs_flash.h>
11+ #include " blufi_wifi.h"
12+ #include " ssid_manager.h"
13+ static const char *TAG = " BulfiApp" ;
14+
15+ extern " C" void app_main (void )
16+ {
17+ ESP_LOGI (TAG, " Starting BLUFI WiFi configuration..." );
18+ /* 1. 初始化 NVS */
19+ esp_err_t ret = nvs_flash_init ();
20+ if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
21+ ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
22+ ESP_ERROR_CHECK (nvs_flash_erase ());
23+ ESP_ERROR_CHECK (nvs_flash_init ());
24+ }
25+
26+ std::string broad_name;
27+ // read nvs setting broad name
28+ nvs_handle_t nvs_handle = 0 ;
29+ nvs_open (" board" , NVS_READONLY, &nvs_handle);
30+ if (nvs_handle != 0 ) {
31+ size_t length = 0 ;
32+ if (nvs_get_str (nvs_handle, " name" , nullptr , &length) == ESP_OK) {
33+ broad_name.resize (length);
34+ if (nvs_get_str (nvs_handle, " name" , broad_name.data (), &length) == ESP_OK) {
35+ while (!broad_name.empty () && broad_name.back () == ' \0 ' ) {
36+ broad_name.pop_back ();
37+ }
38+ ESP_LOGI (TAG, " Read board name from nvs: %s" , broad_name.c_str ());
39+ } else {
40+ broad_name.clear ();
41+ }
42+ }
43+ }
44+
45+ if (broad_name.empty ()) {
46+ uint8_t mac[6 ];
47+ #if CONFIG_IDF_TARGET_ESP32P4
48+ esp_wifi_get_mac (WIFI_IF_AP, mac);
49+ #else
50+ ESP_ERROR_CHECK (esp_read_mac (mac, ESP_MAC_WIFI_SOFTAP));
51+ #endif
52+ char ssid[32 ];
53+ snprintf (ssid, sizeof (ssid), " %s-%02X%02X" , " yunxin" , mac[4 ], mac[5 ]);
54+ broad_name = std::string (ssid);
55+ }
56+ ESP_LOGI (TAG, " Broad name: %s" , broad_name.c_str ());
57+
58+ /* 2. 启动 Wi-Fi + Blufi */
59+ wifi_credential_t wifi_cred = initialise_wifi_and_blufi (broad_name.c_str ());
60+
61+ if (wifi_cred.succ == 1 ) {
62+ ESP_LOGI (TAG, " BLUFI WiFi connected! SSID: %s" , wifi_cred.ssid );
63+ SsidManager::GetInstance ().AddSsid (wifi_cred.ssid , wifi_cred.password ); // 存储账号密码
64+
65+ /* 设置下一次启动分区为 ota_0(主工程的应用在ota_0) */
66+ const esp_partition_t *ota0 = esp_partition_find_first (
67+ ESP_PARTITION_TYPE_APP,
68+ ESP_PARTITION_SUBTYPE_APP_OTA_0,
69+ NULL );
70+ ESP_ERROR_CHECK ( esp_ota_set_boot_partition (ota0) );
71+ } else {
72+ ESP_LOGE (TAG, " BLUFI WiFi connection failed" );
73+ }
74+
75+ ESP_LOGI (TAG, " BLUFI WiFi configuration completed, restarting..." );
76+ vTaskDelay (pdMS_TO_TICKS (500 ));
77+ // 执行重启
78+ esp_restart ();
79+ }
0 commit comments